Spaces:
Running
Running
File size: 8,294 Bytes
3750964 96f68cd 3750964 b5229dd 3750964 96f68cd 3750964 9313ac7 3750964 9313ac7 3750964 9313ac7 3750964 09f04ee 3750964 96f68cd 3750964 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | <?php
namespace App\Controllers;
use App\Models\PushData;
use App\Services\WebPushService;
require_once __DIR__ . '/../Helpers/view.php';
class PushController
{
private function model()
{
return new PushData();
}
private function push()
{
return new WebPushService();
}
private function json($data, $code = 200)
{
if (ob_get_level()) ob_clean();
http_response_code($code);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
public function index()
{
$model = $this->model();
$notifications = array_reverse($model->notifications());
$config = [
'vapidPublicKey' => $this->push()->isConfigured() ? (getenv('VAPID_PUBLIC_KEY') ?: ($_ENV['VAPID_PUBLIC_KEY'] ?? '')) : '',
'configured' => $this->push()->isConfigured(),
'bucketConfigured' => $this->bucketConfigured(),
];
return view('pages.push.index', [
'notifications' => $notifications,
'config' => $config,
'seo' => [
'title' => 'ຈັດການແຈ້ງເຕືອນ - ຄຳສອນພຸດທະ',
'description' => 'ຈັດການຂໍ້ຄວາມແຈ້ງເຕືອນ Push Notification ສຳລັບໂທລະສັບ',
'robots' => 'noindex, nofollow',
]
]);
}
public function pubkey()
{
$service = $this->push();
$this->json([
'success' => true,
'publicKey' => $service->isConfigured() ? (getenv('VAPID_PUBLIC_KEY') ?: ($_ENV['VAPID_PUBLIC_KEY'] ?? '')) : '',
'configured' => $service->isConfigured(),
]);
}
public function apiList()
{
$model = $this->model();
$notifications = array_reverse($model->notifications());
$this->json([
'success' => true,
'notifications' => $notifications,
'subscriberCount' => count($model->subscriptions()),
'config' => [
'configured' => $this->push()->isConfigured(),
'bucketConfigured' => $this->bucketConfigured(),
],
]);
}
public function store()
{
$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
$input = $_POST;
}
$id = $input['id'] ?? null;
$fields = $id ? $this->model()->findNotification($id) : null;
$data = [
'id' => $id,
'title' => $input['title'] ?? ($fields['title'] ?? ''),
'body' => $input['body'] ?? ($fields['body'] ?? ''),
'url' => $input['url'] ?? ($fields['url'] ?? ''),
'enabled' => isset($input['enabled']) ? filter_var($input['enabled'], FILTER_VALIDATE_BOOLEAN) : ($fields['enabled'] ?? true),
'created_at' => $fields['created_at'] ?? null,
];
if ($data['title'] === '') {
$this->json(['success' => false, 'error' => 'ກະລຸນາປ້ອນຫົວຂໍ້'], 400);
}
$result = $this->model()->storeNotification($data);
if (!$result['success']) {
$this->json(['success' => false, 'error' => $result['error'] ?? 'Save failed'], 500);
}
$this->autoSyncBucket();
$this->json(['success' => true, 'notification' => $result['notification']]);
}
public function destroy()
{
$input = json_decode(file_get_contents('php://input'), true);
$id = $input['id'] ?? ($_POST['id'] ?? '');
if ($id) {
$result = $this->model()->destroyNotification($id);
} else {
// Fallback: match by title when ID is empty (stale bucket data)
$title = $input['title'] ?? '';
$result = $this->model()->destroyNotificationByTitle($title);
}
if (!$result['success']) {
$this->json(['success' => false, 'error' => $result['error'] ?? 'Delete failed'], 404);
}
$this->autoSyncBucket();
$this->json(['success' => true]);
}
/**
* Save a subscription coming from the PWA client.
*/
public function subscribe()
{
$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input) || empty($input['endpoint'])) {
$this->json(['success' => false, 'error' => 'Invalid subscription'], 400);
}
$this->model()->addSubscription([
'endpoint' => $input['endpoint'],
'keys' => [
'p256dh' => $input['keys']['p256dh'] ?? '',
'auth' => $input['keys']['auth'] ?? '',
],
]);
$this->json(['success' => true]);
}
public function unsubscribe()
{
$input = json_decode(file_get_contents('php://input'), true);
$endpoint = $input['endpoint'] ?? ($_POST['endpoint'] ?? '');
if (!$endpoint) {
$this->json(['success' => false, 'error' => 'Missing endpoint'], 400);
}
$this->model()->removeSubscription($endpoint);
$this->json(['success' => true]);
}
/**
* Broadcast a notification to every subscribed device.
*/
public function send()
{
$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
$input = $_POST;
}
$notificationId = $input['id'] ?? '';
$model = $this->model();
$title = '';
$body = '';
$url = '';
if ($notificationId) {
$n = $model->findNotification($notificationId);
if ($n) {
$title = $n['title'] ?? '';
$body = $n['body'] ?? '';
$url = $n['url'] ?? '';
}
}
// Fallback to input fields (sendNow sends title/body/url too)
if ($title === '') $title = $input['title'] ?? '';
if ($body === '') $body = $input['body'] ?? '';
if ($url === '') $url = $input['url'] ?? '';
if ($title === '') {
$this->json(['success' => false, 'error' => 'Missing title'], 400);
}
$subs = $model->subscriptions();
if (empty($subs)) {
$this->json(['success' => true, 'sent' => 0, 'total' => 0, 'message' => 'No subscribers yet']);
}
$payload = [
'title' => $title,
'body' => $body,
'url' => $url ? $url : url('/'),
];
$service = $this->push();
if (!$service->isConfigured()) {
$this->json(['success' => false, 'error' => 'VAPID keys not configured'], 500);
}
$sent = 0;
$failures = 0;
$gone = [];
foreach ($subs as $sub) {
$result = $service->send($sub, $payload);
if ($result['success']) {
$sent++;
} else {
$failures++;
if (!empty($result['gone'])) {
$gone[] = $sub['endpoint'] ?? '';
}
}
}
// Remove dead subscriptions
foreach ($gone as $endpoint) {
$model->removeSubscription($endpoint);
}
$this->json([
'success' => true,
'sent' => $sent,
'failed' => $failures,
'total' => count($subs),
]);
}
/**
* Push local notification/subscription data to the HF bucket (durable storage).
*/
public function syncBucket()
{
$result = $this->model()->syncToBucket();
$this->json($result);
}
/**
* Pull notification data from the HF bucket into local storage.
*/
public function pullBucket()
{
$result = $this->model()->pullFromBucket();
$this->json($result);
}
private function bucketConfigured()
{
$bucket = getenv('HF_BUCKET') ?: ($_ENV['HF_BUCKET'] ?? '');
return $bucket !== '';
}
private function autoSyncBucket()
{
if (!$this->bucketConfigured()) return;
try {
$this->model()->syncToBucket();
} catch (\Throwable $e) {}
}
}
|