Test-Knopf fuer App-Erinnerungen in den Einstellungen ergaenzen
This commit is contained in:
parent
6e30fea4e6
commit
7737b6a46b
5 changed files with 146 additions and 17 deletions
|
|
@ -293,6 +293,10 @@ von `users.gets_reminders`.
|
|||
- Der Versand läuft in `Roundmail::sendReminder` über
|
||||
`PushSubscription::sendReminder`. Abgelaufene Abos (HTTP 404/410) werden
|
||||
dabei automatisch entfernt.
|
||||
- **Test-Knopf:** „Test-Erinnerung senden“ schickt eine Nachricht an genau das
|
||||
Gerät, auf dem der Knopf gedrückt wurde (`POST ?page=push_test`, höchstens
|
||||
alle 5 Sekunden). Der Text stammt aus derselben Funktion wie der echte
|
||||
Erinnerungslauf (`Roundmail::pushPayload`), nur der Tag ist `reminder-test`.
|
||||
|
||||
**Verschlüsselung und Schlüssel**
|
||||
|
||||
|
|
|
|||
|
|
@ -403,8 +403,8 @@ if ($page === 'reminder') {
|
|||
$entries = FetcherLog::getRange($from, $to);
|
||||
|
||||
require __DIR__ . '/../src/Views/admin/fetcher_activity.php';
|
||||
} elseif ($page === 'push_subscribe' || $page === 'push_unsubscribe') {
|
||||
// Speichert bzw. löscht das Push-Abo für App-Erinnerungen (JSON, nur eingeloggt).
|
||||
} elseif (in_array($page, ['push_subscribe', 'push_unsubscribe', 'push_test'], true)) {
|
||||
// Push-Abo speichern/löschen und Test-Erinnerung (JSON, nur eingeloggt).
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
|
||||
if (!Auth::check()) {
|
||||
|
|
@ -425,15 +425,68 @@ if ($page === 'reminder') {
|
|||
exit;
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
if (!is_array($input)) {
|
||||
$input = [];
|
||||
}
|
||||
|
||||
if ($page === 'push_unsubscribe') {
|
||||
PushSubscription::deleteForUser((int)Auth::id());
|
||||
echo json_encode(['ok' => true]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$endpoint = is_array($input) ? (string)($input['endpoint'] ?? '') : '';
|
||||
$keys = is_array($input) && is_array($input['keys'] ?? null) ? $input['keys'] : [];
|
||||
if ($page === 'push_test') {
|
||||
// Nur das Gerät testen, auf dem der Knopf gedrückt wurde. Kurze Sperre
|
||||
// gegen versehentliches Mehrfachklicken.
|
||||
$now = time();
|
||||
if (isset($_SESSION['push_test_at']) && $now - (int)$_SESSION['push_test_at'] < 5) {
|
||||
http_response_code(429);
|
||||
echo json_encode(['error' => 'Bitte kurz warten, dann erneut testen.']);
|
||||
exit;
|
||||
}
|
||||
$_SESSION['push_test_at'] = $now;
|
||||
|
||||
$endpoint = (string)($input['endpoint'] ?? '');
|
||||
$subscription = PushSubscription::findForUserAndEndpoint((int)Auth::id(), $endpoint);
|
||||
if (!$subscription) {
|
||||
http_response_code(409);
|
||||
echo json_encode(['error' => 'Dieses Gerät ist nicht als Abo hinterlegt. Bitte den Haken aus- und wieder einschalten.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Gleicher Text wie im echten Erinnerungslauf, damit die Vorschau stimmt.
|
||||
$appUrl = getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
|
||||
$season = Season::getCurrent();
|
||||
$round = $season ? Round::getFirstTippable($season['id']) : null;
|
||||
if ($round) {
|
||||
$payload = Roundmail::pushPayload($round, Round::getLockTime($round['games']), $appUrl);
|
||||
} else {
|
||||
$payload = [
|
||||
'title' => 'Hoschis Tippspiel',
|
||||
'body' => 'Test-Erinnerung: Es fehlen noch Tipps/Joker.',
|
||||
'url' => rtrim($appUrl, '/') . '/index.php?page=tipps',
|
||||
];
|
||||
}
|
||||
// Eigener Tag: Der Test soll eine echte Erinnerung nicht ersetzen.
|
||||
$payload['tag'] = 'reminder-test';
|
||||
|
||||
$send = WebPush::send($subscription, $payload);
|
||||
if ($send['ok']) {
|
||||
echo json_encode(['ok' => true, 'sent' => 1]);
|
||||
} elseif ($send['gone']) {
|
||||
PushSubscription::deleteByEndpoint($endpoint);
|
||||
http_response_code(410);
|
||||
echo json_encode(['error' => 'Das Abo ist abgelaufen und wurde entfernt. Bitte den Haken aus- und wieder einschalten.']);
|
||||
} else {
|
||||
http_response_code(502);
|
||||
echo json_encode(['error' => 'Push-Dienst nicht erreichbar: ' . $send['error']]);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
$endpoint = (string)($input['endpoint'] ?? '');
|
||||
$keys = is_array($input['keys'] ?? null) ? $input['keys'] : [];
|
||||
$p256dh = (string)($keys['p256dh'] ?? '');
|
||||
$authKey = (string)($keys['auth'] ?? '');
|
||||
|
||||
|
|
|
|||
|
|
@ -91,6 +91,24 @@ class PushSubscription {
|
|||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein bestimmtes Gerät eines Spielers (für den Test-Knopf).
|
||||
*
|
||||
* @param int $userId
|
||||
* @param string $endpoint
|
||||
* @return array|false
|
||||
*/
|
||||
public static function findForUserAndEndpoint($userId, $endpoint) {
|
||||
if (!self::isAvailable() || $endpoint === '') {
|
||||
return false;
|
||||
}
|
||||
$stmt = Database::getConnection()->prepare(
|
||||
"SELECT * FROM push_subscriptions WHERE user_id = ? AND endpoint_hash = ?"
|
||||
);
|
||||
$stmt->execute([(int)$userId, hash('sha256', $endpoint)]);
|
||||
return $stmt->fetch(\PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht alle Abos eines Spielers.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -232,13 +232,7 @@ class Roundmail {
|
|||
|
||||
// App-Erinnerung ist ein eigener Kanal: Sie hängt an der zweiten
|
||||
// Checkbox (gespeichertes Push-Abo), nicht an gets_reminders.
|
||||
$push = PushSubscription::sendReminder($userIds, [
|
||||
'title' => 'Hoschis Tippspiel',
|
||||
'body' => 'Es fehlen noch Tipps/Joker für ' . $round['name']
|
||||
. '. Die Runde sperrt sich am ' . $lockTime->format('d.m.Y H:i') . '.',
|
||||
'url' => rtrim($appUrl, '/') . '/index.php?page=tipps',
|
||||
'tag' => 'reminder-' . (int)$round['id'],
|
||||
]);
|
||||
$push = PushSubscription::sendReminder($userIds, self::pushPayload($round, $lockTime, $appUrl));
|
||||
|
||||
if (empty($recipients) && $push['sent'] === 0 && $push['failed'] === 0 && $push['removed'] === 0) {
|
||||
return $round['name'] . ': Erinnerung nötig, aber kein Empfänger aktiviert.';
|
||||
|
|
@ -277,6 +271,26 @@ class Roundmail {
|
|||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut die Push-Nutzlast für eine Runde. Wird sowohl vom echten Erinnerungslauf
|
||||
* als auch vom Test-Knopf in den Einstellungen verwendet, damit die Vorschau
|
||||
* exakt wie die spätere Erinnerung aussieht.
|
||||
*
|
||||
* @param array $round
|
||||
* @param \DateTime $lockTime
|
||||
* @param string $appUrl
|
||||
* @return array
|
||||
*/
|
||||
public static function pushPayload($round, $lockTime, $appUrl) {
|
||||
return [
|
||||
'title' => 'Hoschis Tippspiel',
|
||||
'body' => 'Es fehlen noch Tipps/Joker für ' . $round['name']
|
||||
. '. Die Runde sperrt sich am ' . $lockTime->format('d.m.Y H:i') . '.',
|
||||
'url' => rtrim($appUrl, '/') . '/index.php?page=tipps',
|
||||
'tag' => 'reminder-' . (int)$round['id'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht automatische Erinnerungsmails (Automailer, Betreff REMINDER_TOPIC), die älter als
|
||||
* REMINDER_RETENTION_MONTHS Monate sind. Rundmails von Admins bleiben unberührt.
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ require __DIR__ . '/partials/header.php';
|
|||
<input type="checkbox" id="push_reminders" <?php if (!empty($pushEnabled)) echo 'checked'; ?>>
|
||||
<label for="push_reminders" class="inline">Ich möchte Smartphone-Erinnerungen erhalten (App)</label>
|
||||
<p class="settings-hint" id="push-reminder-hint"></p>
|
||||
<button type="button" id="push-test-button" class="push-test-button" hidden>Test-Erinnerung senden</button>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
|
|
@ -73,10 +74,12 @@ require __DIR__ . '/partials/header.php';
|
|||
.settings-form button { margin-left: 164px; }
|
||||
.settings-hint { margin: 0.3em 0 0 164px; font-size: 0.9em; color: #555; }
|
||||
.settings-hint.is-error { color: #b00020; }
|
||||
.settings-form .push-test-button { margin: 0.5em 0 0 164px; }
|
||||
@media (max-width: 600px) {
|
||||
.settings-form .form-group > label:first-child { width: auto; display: block; }
|
||||
.settings-form button { margin-left: 0; }
|
||||
.settings-hint { margin-left: 0; }
|
||||
.settings-form .push-test-button { margin-left: 0; }
|
||||
}
|
||||
</style>
|
||||
|
||||
|
|
@ -85,7 +88,8 @@ require __DIR__ . '/partials/header.php';
|
|||
var group = document.getElementById('push-reminder-group');
|
||||
var box = document.getElementById('push_reminders');
|
||||
var hint = document.getElementById('push-reminder-hint');
|
||||
if (!group || !box || !hint) {
|
||||
var testButton = document.getElementById('push-test-button');
|
||||
if (!group || !box || !hint || !testButton) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -105,6 +109,10 @@ require __DIR__ . '/partials/header.php';
|
|||
hint.className = 'settings-hint' + (isError ? ' is-error' : '');
|
||||
}
|
||||
|
||||
function syncTestButton() {
|
||||
testButton.hidden = !box.checked;
|
||||
}
|
||||
|
||||
function keyToBytes(base64url) {
|
||||
var padding = new Array((4 - (base64url.length % 4)) % 4 + 1).join('=');
|
||||
var base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
|
|
@ -123,10 +131,14 @@ require __DIR__ . '/partials/header.php';
|
|||
credentials: 'same-origin',
|
||||
body: JSON.stringify(payload || {})
|
||||
}).then(function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('Server meldet HTTP ' + response.status + '.');
|
||||
}
|
||||
return response.json();
|
||||
return response.json().catch(function () {
|
||||
return {};
|
||||
}).then(function (data) {
|
||||
if (!response.ok) {
|
||||
throw new Error((data && data.error) ? data.error : 'Server meldet HTTP ' + response.status + '.');
|
||||
}
|
||||
return data;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -199,9 +211,37 @@ require __DIR__ . '/partials/header.php';
|
|||
setHint(error && error.message ? error.message : 'Aktion fehlgeschlagen.', true);
|
||||
}).then(function () {
|
||||
box.disabled = false;
|
||||
syncTestButton();
|
||||
});
|
||||
});
|
||||
|
||||
// Test-Erinnerung an genau dieses Gerät. Der Server nimmt denselben Text wie
|
||||
// der echte Erinnerungslauf, nur mit eigenem Tag.
|
||||
testButton.addEventListener('click', function () {
|
||||
if (testButton.disabled) {
|
||||
return;
|
||||
}
|
||||
testButton.disabled = true;
|
||||
setHint('Test-Erinnerung wird gesendet …');
|
||||
|
||||
navigator.serviceWorker.ready.then(function (registration) {
|
||||
return registration.pushManager.getSubscription();
|
||||
}).then(function (subscription) {
|
||||
if (!subscription) {
|
||||
throw new Error('Dieses Gerät hat noch kein Abo. Bitte den Haken aus- und wieder einschalten.');
|
||||
}
|
||||
return post('push_test', { endpoint: subscription.endpoint });
|
||||
}).then(function () {
|
||||
setHint('Test-Erinnerung gesendet. Sie sollte jetzt auf diesem Gerät erscheinen.');
|
||||
}).catch(function (error) {
|
||||
setHint(error && error.message ? error.message : 'Test fehlgeschlagen.', true);
|
||||
}).then(function () {
|
||||
testButton.disabled = false;
|
||||
});
|
||||
});
|
||||
|
||||
syncTestButton();
|
||||
|
||||
// Beim Öffnen das Gerät still nachtragen, wenn Erinnerungen gewünscht sind
|
||||
// und die Erlaubnis schon erteilt ist (z. B. zweites Gerät). Bewusst kein
|
||||
// automatisches Abmelden: Auf einem geteilten Gerät kann das Abo zu einem
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue