⑤ ベータ機能:管理者向け Web Push 通知
Browse files依存: pywebpush>=2.0.0 を requirements.txt に追加
DB:
- db/database.py: push_subscriptions テーブルを追加
- db/repositories.py: get/save/delete_push_subscription 関数を追加
新規 Blueprint:
- routes/push.py: VAPID 鍵管理・購読登録・解除・テスト送信エンドポイント
GET /push/vapid-public-key — ブラウザが Push 購読に使う公開鍵を返す
POST /push/subscribe — 購読情報を DB に保存
POST /push/unsubscribe — 購読を解除
POST /push/send-test — テスト通知を全購読者に送信
内部: _send_push_notification() — 他ルートから呼び出せる共通関数
Push トリガー:
- routes/schedule.py: confirm() でシフト確定時に Push 通知を送信
- routes/shifts.py: save() で個人保存時に希望提出通知を送信
フロントエンド:
- templates/pwa/sw.js: push / notificationclick イベントハンドラを追加
- templates/settings/index.html: 「管理者向け Web Push 通知(β)」セクションを追加
VAPID 鍵取得 → 通知許可リクエスト → 購読 → 解除 / テスト送信の UI
- web_app.py: push Blueprint を登録、push.* エンドポイントを認証免除リストに追加
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- db/database.py +7 -0
- requirements.txt +1 -0
- routes/push.py +133 -0
- routes/shifts.py +12 -0
- templates/pwa/sw.js +24 -0
- templates/settings/index.html +131 -0
- web_app.py +4 -1
|
@@ -353,6 +353,13 @@ _CREATE_TABLES = [
|
|
| 353 |
key TEXT PRIMARY KEY,
|
| 354 |
credentials_json TEXT NOT NULL
|
| 355 |
)""",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
]
|
| 357 |
|
| 358 |
_MIGRATIONS = [
|
|
|
|
| 353 |
key TEXT PRIMARY KEY,
|
| 354 |
credentials_json TEXT NOT NULL
|
| 355 |
)""",
|
| 356 |
+
"""CREATE TABLE IF NOT EXISTS push_subscriptions (
|
| 357 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 358 |
+
endpoint TEXT NOT NULL UNIQUE,
|
| 359 |
+
p256dh TEXT NOT NULL,
|
| 360 |
+
auth TEXT NOT NULL,
|
| 361 |
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
| 362 |
+
)""",
|
| 363 |
]
|
| 364 |
|
| 365 |
_MIGRATIONS = [
|
|
@@ -14,3 +14,4 @@ google-auth>=2.20.0
|
|
| 14 |
google-auth-oauthlib>=1.0.0
|
| 15 |
google-auth-httplib2>=0.1.0
|
| 16 |
google-api-python-client>=2.90.0
|
|
|
|
|
|
| 14 |
google-auth-oauthlib>=1.0.0
|
| 15 |
google-auth-httplib2>=0.1.0
|
| 16 |
google-api-python-client>=2.90.0
|
| 17 |
+
pywebpush>=2.0.0
|
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""管理者向け Web Push 通知ルート(β機能)"""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
from flask import Blueprint, jsonify, request
|
| 9 |
+
|
| 10 |
+
from db import repositories as repo
|
| 11 |
+
|
| 12 |
+
bp = Blueprint("push", __name__, url_prefix="/push")
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# ── VAPID 鍵管理 ──────────────────────────────────────────────────────────
|
| 17 |
+
|
| 18 |
+
def _get_or_create_vapid_keys() -> tuple[str, str]:
|
| 19 |
+
"""VAPID 公開鍵(base64url, ブラウザ用)と秘密鍵(PEM文字列, pywebpush用)を返す。
|
| 20 |
+
未生成の場合は生成して app_settings に保存する。"""
|
| 21 |
+
pub = repo.get_app_setting("vapid_public_key", "")
|
| 22 |
+
priv = repo.get_app_setting("vapid_private_key", "")
|
| 23 |
+
if pub and priv:
|
| 24 |
+
return pub, priv
|
| 25 |
+
try:
|
| 26 |
+
import base64
|
| 27 |
+
from py_vapid import Vapid
|
| 28 |
+
from cryptography.hazmat.primitives.serialization import (
|
| 29 |
+
Encoding, PublicFormat,
|
| 30 |
+
)
|
| 31 |
+
v = Vapid()
|
| 32 |
+
v.generate_keys()
|
| 33 |
+
# 公開鍵: DER → 末尾65バイト(非圧縮 EC 点)を base64url でブラウザに渡す
|
| 34 |
+
pub_der = v.public_key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
|
| 35 |
+
pub = base64.urlsafe_b64encode(pub_der[-65:]).decode().rstrip("=")
|
| 36 |
+
# 秘密鍵: PEM 文字列を pywebpush へ直接渡す
|
| 37 |
+
priv = v.private_pem().decode()
|
| 38 |
+
repo.save_all_app_settings({"vapid_public_key": pub, "vapid_private_key": priv})
|
| 39 |
+
return pub, priv
|
| 40 |
+
except Exception as e:
|
| 41 |
+
logger.error(f"[push] VAPID 鍵生成失敗: {e}")
|
| 42 |
+
return "", ""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ── エンドポイント ────────────────────────────────────────────────────────
|
| 46 |
+
|
| 47 |
+
@bp.get("/vapid-public-key")
|
| 48 |
+
def vapid_public_key():
|
| 49 |
+
"""フロントエンドが Push 購読時に使う VAPID 公開鍵を返す"""
|
| 50 |
+
pub, _ = _get_or_create_vapid_keys()
|
| 51 |
+
if not pub:
|
| 52 |
+
return jsonify({"error": "VAPID 鍵の生成に失敗しました"}), 500
|
| 53 |
+
return jsonify({"publicKey": pub})
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@bp.post("/subscribe")
|
| 57 |
+
def subscribe():
|
| 58 |
+
"""ブラウザから Push サブスクリプションを受け取り DB に保存する"""
|
| 59 |
+
data = request.get_json(silent=True)
|
| 60 |
+
if not data:
|
| 61 |
+
return jsonify({"ok": False, "error": "Invalid JSON"}), 400
|
| 62 |
+
endpoint = data.get("endpoint")
|
| 63 |
+
keys = data.get("keys", {})
|
| 64 |
+
p256dh = keys.get("p256dh")
|
| 65 |
+
auth = keys.get("auth")
|
| 66 |
+
if not (endpoint and p256dh and auth):
|
| 67 |
+
return jsonify({"ok": False, "error": "必須フィールドが不足しています"}), 400
|
| 68 |
+
repo.save_push_subscription(endpoint, p256dh, auth)
|
| 69 |
+
return jsonify({"ok": True})
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@bp.post("/unsubscribe")
|
| 73 |
+
def unsubscribe():
|
| 74 |
+
"""Push サブスクリプションを削除する"""
|
| 75 |
+
data = request.get_json(silent=True)
|
| 76 |
+
if not data or not data.get("endpoint"):
|
| 77 |
+
return jsonify({"ok": False, "error": "endpoint が不足しています"}), 400
|
| 78 |
+
repo.delete_push_subscription(data["endpoint"])
|
| 79 |
+
return jsonify({"ok": True})
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@bp.post("/send-test")
|
| 83 |
+
def send_test():
|
| 84 |
+
"""テスト Push 通知を全購読者に送信する(設定画面から実行)"""
|
| 85 |
+
_send_push_notification("SDU-Shift テスト通知", "プッシュ通知の設定が完了しました")
|
| 86 |
+
return jsonify({"ok": True})
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ── 内部ユーティリティ ────────────────────────────────────────────────────
|
| 90 |
+
|
| 91 |
+
def _send_push_notification(title: str, body: str) -> None:
|
| 92 |
+
"""全購読者に Push 通知を送る。失敗しても例外を伝播させない。"""
|
| 93 |
+
try:
|
| 94 |
+
from py_vapid import Vapid
|
| 95 |
+
from pywebpush import webpush, WebPushException
|
| 96 |
+
except ImportError:
|
| 97 |
+
logger.warning("[push] pywebpush がインストールされていません")
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
pub, priv = _get_or_create_vapid_keys()
|
| 101 |
+
if not pub or not priv:
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
subscriptions = repo.get_push_subscriptions()
|
| 105 |
+
if not subscriptions:
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
payload = json.dumps({"title": title, "body": body}, ensure_ascii=False)
|
| 109 |
+
dead_endpoints: list[str] = []
|
| 110 |
+
|
| 111 |
+
for sub in subscriptions:
|
| 112 |
+
try:
|
| 113 |
+
webpush(
|
| 114 |
+
subscription_info={
|
| 115 |
+
"endpoint": sub["endpoint"],
|
| 116 |
+
"keys": {"p256dh": sub["p256dh"], "auth": sub["auth"]},
|
| 117 |
+
},
|
| 118 |
+
data=payload,
|
| 119 |
+
vapid_private_key=priv, # PEM 文字列
|
| 120 |
+
vapid_claims={"sub": "mailto:admin@sdu-shift.local"},
|
| 121 |
+
ttl=86400,
|
| 122 |
+
)
|
| 123 |
+
except WebPushException as e:
|
| 124 |
+
# 410 Gone → 購読が失効(ブラウザ側で解除済み)
|
| 125 |
+
if e.response and e.response.status_code in (404, 410):
|
| 126 |
+
dead_endpoints.append(sub["endpoint"])
|
| 127 |
+
else:
|
| 128 |
+
logger.warning(f"[push] 送信失敗 {sub['endpoint'][:40]}…: {e}")
|
| 129 |
+
except Exception as e:
|
| 130 |
+
logger.warning(f"[push] 送信エラー: {e}")
|
| 131 |
+
|
| 132 |
+
for ep in dead_endpoints:
|
| 133 |
+
repo.delete_push_subscription(ep)
|
|
@@ -272,6 +272,18 @@ def save(period_id):
|
|
| 272 |
repo.save_shift_requests(period_id, new_requests)
|
| 273 |
flash("希望シフトを保存しました", "success")
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
# 1人モードなら次の従業員へ
|
| 276 |
next_idx = request.form.get("next_emp_idx", type=int)
|
| 277 |
if next_idx is not None:
|
|
|
|
| 272 |
repo.save_shift_requests(period_id, new_requests)
|
| 273 |
flash("希望シフトを保存しました", "success")
|
| 274 |
|
| 275 |
+
# 管理者に Push 通知を送る(1名分保存時のみ)
|
| 276 |
+
if emp_id_filter is not None:
|
| 277 |
+
emp_name = next((e.name for e in employees if e.id == emp_id_filter), "スタッフ")
|
| 278 |
+
try:
|
| 279 |
+
from routes.push import _send_push_notification
|
| 280 |
+
_send_push_notification(
|
| 281 |
+
"希望シフト提出",
|
| 282 |
+
f"{emp_name} さんが {period.start_date}〜{period.end_date} の希望シフトを提出しました",
|
| 283 |
+
)
|
| 284 |
+
except Exception:
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
# 1人モードなら次の従業員へ
|
| 288 |
next_idx = request.form.get("next_emp_idx", type=int)
|
| 289 |
if next_idx is not None:
|
|
@@ -75,3 +75,27 @@ self.addEventListener("fetch", e => {
|
|
| 75 |
e.respondWith(handleOther(e.request));
|
| 76 |
}
|
| 77 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
e.respondWith(handleOther(e.request));
|
| 76 |
}
|
| 77 |
});
|
| 78 |
+
|
| 79 |
+
// ── Web Push 通知(管理者向けβ) ──────────────────────────────────────
|
| 80 |
+
self.addEventListener("push", e => {
|
| 81 |
+
let title = "SDU-Shift";
|
| 82 |
+
let body = "";
|
| 83 |
+
try {
|
| 84 |
+
const data = e.data?.json() ?? {};
|
| 85 |
+
title = data.title ?? title;
|
| 86 |
+
body = data.body ?? body;
|
| 87 |
+
} catch {}
|
| 88 |
+
e.waitUntil(
|
| 89 |
+
self.registration.showNotification(title, {
|
| 90 |
+
body,
|
| 91 |
+
icon: "/static/icons/icon-192.png",
|
| 92 |
+
badge: "/static/icons/icon-192.png",
|
| 93 |
+
tag: "sdu-shift-admin",
|
| 94 |
+
})
|
| 95 |
+
);
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
self.addEventListener("notificationclick", e => {
|
| 99 |
+
e.notification.close();
|
| 100 |
+
e.waitUntil(clients.openWindow("/"));
|
| 101 |
+
});
|
|
@@ -462,6 +462,35 @@
|
|
| 462 |
</div>
|
| 463 |
</div>
|
| 464 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
</div>
|
| 466 |
</div>
|
| 467 |
</form>
|
|
@@ -558,5 +587,107 @@
|
|
| 558 |
input.type = show ? 'text' : 'password';
|
| 559 |
icon.className = show ? 'bi bi-eye-slash' : 'bi bi-eye';
|
| 560 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
</script>
|
| 562 |
{% endblock %}
|
|
|
|
| 462 |
</div>
|
| 463 |
</div>
|
| 464 |
|
| 465 |
+
<!-- 機能:Web Push 通知(管理者向けβ) -->
|
| 466 |
+
<div class="border-top pt-3 mt-3" style="border-color: var(--border) !important">
|
| 467 |
+
<div class="d-flex align-items-center mb-2">
|
| 468 |
+
<div class="fw-semibold small">管理者向け Web Push 通知(β)</div>
|
| 469 |
+
<span class="help-btn" data-bs-toggle="popover" data-bs-trigger="click" data-bs-placement="bottom"
|
| 470 |
+
data-bs-title="Web Push 通知(β)"
|
| 471 |
+
data-bs-content="シフト確定時・スタッフが希望シフトを提出したときに、このデバイスへリアルタイム通知を送る機能です。HTTPS 環境・対応ブラウザのみで動作します。購読するとブラウザを閉じていても通知が届きます。">?</span>
|
| 472 |
+
</div>
|
| 473 |
+
<div id="push-status" class="d-flex align-items-center gap-2 p-2 rounded-2 border mb-2"
|
| 474 |
+
style="background-color: var(--card-bg-hover); border-color: var(--border) !important; font-size:.85rem">
|
| 475 |
+
<span id="push-badge" class="badge bg-secondary"><i class="bi bi-bell-slash-fill me-1"></i>未登録</span>
|
| 476 |
+
<span id="push-status-text" class="text-muted small">読み込み中…</span>
|
| 477 |
+
</div>
|
| 478 |
+
<div class="d-flex gap-2 flex-wrap">
|
| 479 |
+
<button type="button" class="btn btn-primary btn-sm" id="push-subscribe-btn" onclick="subscribePush()" disabled>
|
| 480 |
+
<i class="bi bi-bell-fill me-1"></i>このデバイスで通知を受け取る
|
| 481 |
+
</button>
|
| 482 |
+
<button type="button" class="btn btn-outline-secondary btn-sm" id="push-unsubscribe-btn" onclick="unsubscribePush()" style="display:none">
|
| 483 |
+
<i class="bi bi-bell-slash me-1"></i>通知を解除する
|
| 484 |
+
</button>
|
| 485 |
+
<button type="button" class="btn btn-outline-info btn-sm" id="push-test-btn" onclick="sendTestPush()" style="display:none">
|
| 486 |
+
<i class="bi bi-send me-1"></i>テスト通知を送る
|
| 487 |
+
</button>
|
| 488 |
+
</div>
|
| 489 |
+
<div class="text-muted small mt-2">
|
| 490 |
+
※ HTTPS 環境・Chrome / Edge / Firefox などの対応ブラウザが必要です。iOS Safari は現時点では非対応です。
|
| 491 |
+
</div>
|
| 492 |
+
</div>
|
| 493 |
+
|
| 494 |
</div>
|
| 495 |
</div>
|
| 496 |
</form>
|
|
|
|
| 587 |
input.type = show ? 'text' : 'password';
|
| 588 |
icon.className = show ? 'bi bi-eye-slash' : 'bi bi-eye';
|
| 589 |
}
|
| 590 |
+
|
| 591 |
+
// ── Web Push 通知(β) ────────────────────────────────────────────
|
| 592 |
+
let _swReg = null;
|
| 593 |
+
|
| 594 |
+
async function initPushUI() {
|
| 595 |
+
const badge = document.getElementById('push-badge');
|
| 596 |
+
const text = document.getElementById('push-status-text');
|
| 597 |
+
const subBtn = document.getElementById('push-subscribe-btn');
|
| 598 |
+
const unBtn = document.getElementById('push-unsubscribe-btn');
|
| 599 |
+
const testBtn = document.getElementById('push-test-btn');
|
| 600 |
+
|
| 601 |
+
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
| 602 |
+
badge.className = 'badge bg-warning text-dark';
|
| 603 |
+
badge.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i>非対応';
|
| 604 |
+
text.textContent = 'このブラウザは Web Push に対応していません';
|
| 605 |
+
return;
|
| 606 |
+
}
|
| 607 |
+
|
| 608 |
+
try {
|
| 609 |
+
_swReg = await navigator.serviceWorker.ready;
|
| 610 |
+
const sub = await _swReg.pushManager.getSubscription();
|
| 611 |
+
if (sub) {
|
| 612 |
+
badge.className = 'badge bg-success';
|
| 613 |
+
badge.innerHTML = '<i class="bi bi-bell-fill me-1"></i>通知ON';
|
| 614 |
+
text.textContent = 'このデバイスで通知を受け取る設定になっています';
|
| 615 |
+
subBtn.style.display = 'none';
|
| 616 |
+
unBtn.style.display = '';
|
| 617 |
+
testBtn.style.display = '';
|
| 618 |
+
} else {
|
| 619 |
+
badge.className = 'badge bg-secondary';
|
| 620 |
+
badge.innerHTML = '<i class="bi bi-bell-slash-fill me-1"></i>未登録';
|
| 621 |
+
text.textContent = '通知の購読が未設定です';
|
| 622 |
+
subBtn.disabled = false;
|
| 623 |
+
}
|
| 624 |
+
} catch (e) {
|
| 625 |
+
text.textContent = '状態確認エラー: ' + e.message;
|
| 626 |
+
}
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
async function subscribePush() {
|
| 630 |
+
const subBtn = document.getElementById('push-subscribe-btn');
|
| 631 |
+
subBtn.disabled = true;
|
| 632 |
+
subBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>購読中…';
|
| 633 |
+
try {
|
| 634 |
+
const keyResp = await fetch('/push/vapid-public-key');
|
| 635 |
+
const { publicKey } = await keyResp.json();
|
| 636 |
+
const perm = await Notification.requestPermission();
|
| 637 |
+
if (perm !== 'granted') {
|
| 638 |
+
alert('通知の許可が得られませんでした。ブラウザの設定を確認してください。');
|
| 639 |
+
subBtn.disabled = false;
|
| 640 |
+
subBtn.innerHTML = '<i class="bi bi-bell-fill me-1"></i>このデバイスで通知を受け取る';
|
| 641 |
+
return;
|
| 642 |
+
}
|
| 643 |
+
const sub = await _swReg.pushManager.subscribe({
|
| 644 |
+
userVisibleOnly: true,
|
| 645 |
+
applicationServerKey: urlBase64ToUint8Array(publicKey),
|
| 646 |
+
});
|
| 647 |
+
await fetch('/push/subscribe', {
|
| 648 |
+
method: 'POST',
|
| 649 |
+
headers: { 'Content-Type': 'application/json' },
|
| 650 |
+
body: JSON.stringify(sub.toJSON()),
|
| 651 |
+
});
|
| 652 |
+
initPushUI();
|
| 653 |
+
} catch (e) {
|
| 654 |
+
alert('購読に失敗しました: ' + e.message);
|
| 655 |
+
subBtn.disabled = false;
|
| 656 |
+
subBtn.innerHTML = '<i class="bi bi-bell-fill me-1"></i>このデバイスで通知を受け取る';
|
| 657 |
+
}
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
async function unsubscribePush() {
|
| 661 |
+
const sub = await _swReg.pushManager.getSubscription();
|
| 662 |
+
if (!sub) { initPushUI(); return; }
|
| 663 |
+
await fetch('/push/unsubscribe', {
|
| 664 |
+
method: 'POST',
|
| 665 |
+
headers: { 'Content-Type': 'application/json' },
|
| 666 |
+
body: JSON.stringify({ endpoint: sub.endpoint }),
|
| 667 |
+
});
|
| 668 |
+
await sub.unsubscribe();
|
| 669 |
+
initPushUI();
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
async function sendTestPush() {
|
| 673 |
+
const btn = document.getElementById('push-test-btn');
|
| 674 |
+
btn.disabled = true;
|
| 675 |
+
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>';
|
| 676 |
+
try {
|
| 677 |
+
await fetch('/push/send-test', { method: 'POST' });
|
| 678 |
+
} finally {
|
| 679 |
+
btn.disabled = false;
|
| 680 |
+
btn.innerHTML = '<i class="bi bi-send me-1"></i>テスト通知を送る';
|
| 681 |
+
}
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
function urlBase64ToUint8Array(base64String) {
|
| 685 |
+
const padding = '='.repeat((4 - base64String.length % 4) % 4);
|
| 686 |
+
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
|
| 687 |
+
const raw = window.atob(base64);
|
| 688 |
+
return Uint8Array.from([...raw].map(c => c.charCodeAt(0)));
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
document.addEventListener('DOMContentLoaded', initPushUI);
|
| 692 |
</script>
|
| 693 |
{% endblock %}
|
|
@@ -94,7 +94,8 @@ def create_app():
|
|
| 94 |
def require_login():
|
| 95 |
if not APP_PASSWORD:
|
| 96 |
return # パスワード未設定なら全開放
|
| 97 |
-
exempt = {"auth.login", "auth.login_post", "static", "pwa.service_worker", "pwa.offline"
|
|
|
|
| 98 |
if request.endpoint in exempt:
|
| 99 |
return
|
| 100 |
if not session.get("authenticated") or session.get("sv") != SESSION_VERSION:
|
|
@@ -124,6 +125,7 @@ def create_app():
|
|
| 124 |
from routes.export_routes import bp as export_bp
|
| 125 |
from routes.help_routes import bp as help_bp
|
| 126 |
from routes.pwa_routes import bp as pwa_bp
|
|
|
|
| 127 |
|
| 128 |
app.register_blueprint(emp_bp)
|
| 129 |
app.register_blueprint(shifts_bp)
|
|
@@ -134,6 +136,7 @@ def create_app():
|
|
| 134 |
app.register_blueprint(export_bp)
|
| 135 |
app.register_blueprint(help_bp)
|
| 136 |
app.register_blueprint(pwa_bp)
|
|
|
|
| 137 |
|
| 138 |
@app.teardown_appcontext
|
| 139 |
def close_db(error):
|
|
|
|
| 94 |
def require_login():
|
| 95 |
if not APP_PASSWORD:
|
| 96 |
return # パスワード未設定なら全開放
|
| 97 |
+
exempt = {"auth.login", "auth.login_post", "static", "pwa.service_worker", "pwa.offline",
|
| 98 |
+
"push.vapid_public_key", "push.subscribe", "push.unsubscribe", "push.send_test"}
|
| 99 |
if request.endpoint in exempt:
|
| 100 |
return
|
| 101 |
if not session.get("authenticated") or session.get("sv") != SESSION_VERSION:
|
|
|
|
| 125 |
from routes.export_routes import bp as export_bp
|
| 126 |
from routes.help_routes import bp as help_bp
|
| 127 |
from routes.pwa_routes import bp as pwa_bp
|
| 128 |
+
from routes.push import bp as push_bp
|
| 129 |
|
| 130 |
app.register_blueprint(emp_bp)
|
| 131 |
app.register_blueprint(shifts_bp)
|
|
|
|
| 136 |
app.register_blueprint(export_bp)
|
| 137 |
app.register_blueprint(help_bp)
|
| 138 |
app.register_blueprint(pwa_bp)
|
| 139 |
+
app.register_blueprint(push_bp)
|
| 140 |
|
| 141 |
@app.teardown_appcontext
|
| 142 |
def close_db(error):
|