pezza_action_push_web 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/MIT-LICENSE +20 -0
- data/README.md +299 -0
- data/Rakefile +8 -0
- data/app/assets/javascripts/action_push_web.js +424 -0
- data/app/assets/javascripts/components/action_push_web.js +7 -0
- data/app/assets/javascripts/components/denied.js +24 -0
- data/app/assets/javascripts/components/granted.js +86 -0
- data/app/assets/javascripts/components/request.js +55 -0
- data/app/assets/stylesheets/action_push_web/application.css +15 -0
- data/app/controllers/action_push_web/subscriptions_controller.rb +19 -0
- data/app/helpers/action_push_web/application_helper.rb +22 -0
- data/app/jobs/action_push_web/notification_job.rb +48 -0
- data/app/models/action_push_web/subscription.rb +13 -0
- data/db/migrate/20250907213606_create_action_push_web_subscriptions.rb +13 -0
- data/lib/action_push_web/engine.rb +36 -0
- data/lib/action_push_web/errors.rb +8 -0
- data/lib/action_push_web/notification.rb +63 -0
- data/lib/action_push_web/payload_encryption.rb +86 -0
- data/lib/action_push_web/pool.rb +46 -0
- data/lib/action_push_web/pusher.rb +85 -0
- data/lib/action_push_web/subscription_notification.rb +13 -0
- data/lib/action_push_web/vapid_key.rb +38 -0
- data/lib/action_push_web/vapid_key_generator.rb +19 -0
- data/lib/action_push_web/version.rb +3 -0
- data/lib/action_push_web.rb +37 -0
- data/lib/generators/action_push_web/install/install_generator.rb +51 -0
- data/lib/generators/action_push_web/install/templates/app/jobs/application_push_web_notification_job.rb.tt +7 -0
- data/lib/generators/action_push_web/install/templates/app/models/application_push_subscription.rb.tt +4 -0
- data/lib/generators/action_push_web/install/templates/app/models/application_push_web_notification.rb.tt +12 -0
- data/lib/generators/action_push_web/install/templates/app/views/pwa/service-worker.js +30 -0
- data/lib/generators/action_push_web/install/templates/config/push.yml.tt +22 -0
- data/lib/pezza_action_push_web.rb +4 -0
- data/lib/tasks/action_push_web_tasks.rake +4 -0
- metadata +160 -0
@@ -0,0 +1,424 @@
|
|
1
|
+
// app/assets/javascripts/components/request.js
|
2
|
+
class Request extends HTMLElement {
|
3
|
+
static observedAttributes = ["href"];
|
4
|
+
constructor() {
|
5
|
+
super();
|
6
|
+
}
|
7
|
+
connectedCallback() {
|
8
|
+
this.setAttribute("role", "button");
|
9
|
+
this.#setState();
|
10
|
+
this.addEventListener("click", this.onClick);
|
11
|
+
}
|
12
|
+
#setState() {
|
13
|
+
if (this.isEnabled) {
|
14
|
+
this.removeAttribute("disabled");
|
15
|
+
} else {
|
16
|
+
this.setAttribute("disabled", true);
|
17
|
+
}
|
18
|
+
this.hidden = !this.isEnabled;
|
19
|
+
}
|
20
|
+
disconnectedCallback() {
|
21
|
+
this.removeEventListener("click", this.onClick);
|
22
|
+
}
|
23
|
+
attributeChangedCallback() {
|
24
|
+
this.#setState();
|
25
|
+
}
|
26
|
+
get isEnabled() {
|
27
|
+
return navigator.serviceWorker && window.Notification && Notification.permission == "default" && this.getAttribute("href");
|
28
|
+
}
|
29
|
+
get #isDisabled() {
|
30
|
+
return this.hasAttribute("disabled");
|
31
|
+
}
|
32
|
+
async onClick(event) {
|
33
|
+
event.preventDefault();
|
34
|
+
event.stopPropagation();
|
35
|
+
if (this.isEnabled && !this.isDisabled) {
|
36
|
+
const permission = await Notification.requestPermission();
|
37
|
+
if (permission === "granted") {
|
38
|
+
document.dispatchEvent(new CustomEvent("action-push-web:granted", {}));
|
39
|
+
} else if (permission === "denied") {
|
40
|
+
document.dispatchEvent(new CustomEvent("action-push-web:denied", {}));
|
41
|
+
}
|
42
|
+
this.#setState();
|
43
|
+
}
|
44
|
+
}
|
45
|
+
}
|
46
|
+
|
47
|
+
// app/assets/javascripts/components/denied.js
|
48
|
+
class Denied extends HTMLElement {
|
49
|
+
constructor() {
|
50
|
+
super();
|
51
|
+
}
|
52
|
+
connectedCallback() {
|
53
|
+
this.hidden = !this.isEnabled;
|
54
|
+
document.addEventListener("action-push-web:granted", this.attributeChangedCallback.bind(this));
|
55
|
+
document.addEventListener("action-push-web:denied", this.attributeChangedCallback.bind(this));
|
56
|
+
}
|
57
|
+
disconnectedCallback() {
|
58
|
+
document.removeEventListener("action-push-web:granted", this.attributeChangedCallback.bind(this));
|
59
|
+
document.removeEventListener("action-push-web:denied", this.attributeChangedCallback.bind(this));
|
60
|
+
}
|
61
|
+
attributeChangedCallback() {
|
62
|
+
this.hidden = !this.isEnabled;
|
63
|
+
}
|
64
|
+
get isEnabled() {
|
65
|
+
return !navigator.serviceWorker || !window.Notification || Notification.permission == "denied";
|
66
|
+
}
|
67
|
+
}
|
68
|
+
|
69
|
+
// node_modules/@rails/request.js/src/fetch_response.js
|
70
|
+
class FetchResponse {
|
71
|
+
constructor(response) {
|
72
|
+
this.response = response;
|
73
|
+
}
|
74
|
+
get statusCode() {
|
75
|
+
return this.response.status;
|
76
|
+
}
|
77
|
+
get redirected() {
|
78
|
+
return this.response.redirected;
|
79
|
+
}
|
80
|
+
get ok() {
|
81
|
+
return this.response.ok;
|
82
|
+
}
|
83
|
+
get unauthenticated() {
|
84
|
+
return this.statusCode === 401;
|
85
|
+
}
|
86
|
+
get unprocessableEntity() {
|
87
|
+
return this.statusCode === 422;
|
88
|
+
}
|
89
|
+
get authenticationURL() {
|
90
|
+
return this.response.headers.get("WWW-Authenticate");
|
91
|
+
}
|
92
|
+
get contentType() {
|
93
|
+
const contentType = this.response.headers.get("Content-Type") || "";
|
94
|
+
return contentType.replace(/;.*$/, "");
|
95
|
+
}
|
96
|
+
get headers() {
|
97
|
+
return this.response.headers;
|
98
|
+
}
|
99
|
+
get html() {
|
100
|
+
if (this.contentType.match(/^(application|text)\/(html|xhtml\+xml)$/)) {
|
101
|
+
return this.text;
|
102
|
+
}
|
103
|
+
return Promise.reject(new Error(`Expected an HTML response but got "${this.contentType}" instead`));
|
104
|
+
}
|
105
|
+
get json() {
|
106
|
+
if (this.contentType.match(/^application\/.*json$/)) {
|
107
|
+
return this.responseJson || (this.responseJson = this.response.json());
|
108
|
+
}
|
109
|
+
return Promise.reject(new Error(`Expected a JSON response but got "${this.contentType}" instead`));
|
110
|
+
}
|
111
|
+
get text() {
|
112
|
+
return this.responseText || (this.responseText = this.response.text());
|
113
|
+
}
|
114
|
+
get isTurboStream() {
|
115
|
+
return this.contentType.match(/^text\/vnd\.turbo-stream\.html/);
|
116
|
+
}
|
117
|
+
get isScript() {
|
118
|
+
return this.contentType.match(/\b(?:java|ecma)script\b/);
|
119
|
+
}
|
120
|
+
async renderTurboStream() {
|
121
|
+
if (this.isTurboStream) {
|
122
|
+
if (window.Turbo) {
|
123
|
+
await window.Turbo.renderStreamMessage(await this.text);
|
124
|
+
} else {
|
125
|
+
console.warn("You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js");
|
126
|
+
}
|
127
|
+
} else {
|
128
|
+
return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`));
|
129
|
+
}
|
130
|
+
}
|
131
|
+
async activeScript() {
|
132
|
+
if (this.isScript) {
|
133
|
+
const script = document.createElement("script");
|
134
|
+
const metaTag = document.querySelector("meta[name=csp-nonce]");
|
135
|
+
if (metaTag) {
|
136
|
+
const nonce = metaTag.nonce === "" ? metaTag.content : metaTag.nonce;
|
137
|
+
if (nonce) {
|
138
|
+
script.setAttribute("nonce", nonce);
|
139
|
+
}
|
140
|
+
}
|
141
|
+
script.innerHTML = await this.text;
|
142
|
+
document.body.appendChild(script);
|
143
|
+
} else {
|
144
|
+
return Promise.reject(new Error(`Expected a Script response but got "${this.contentType}" instead`));
|
145
|
+
}
|
146
|
+
}
|
147
|
+
}
|
148
|
+
|
149
|
+
// node_modules/@rails/request.js/src/request_interceptor.js
|
150
|
+
class RequestInterceptor {
|
151
|
+
static register(interceptor) {
|
152
|
+
this.interceptor = interceptor;
|
153
|
+
}
|
154
|
+
static get() {
|
155
|
+
return this.interceptor;
|
156
|
+
}
|
157
|
+
static reset() {
|
158
|
+
this.interceptor = undefined;
|
159
|
+
}
|
160
|
+
}
|
161
|
+
|
162
|
+
// node_modules/@rails/request.js/src/lib/utils.js
|
163
|
+
function getCookie(name) {
|
164
|
+
const cookies = document.cookie ? document.cookie.split("; ") : [];
|
165
|
+
const prefix = `${encodeURIComponent(name)}=`;
|
166
|
+
const cookie = cookies.find((cookie2) => cookie2.startsWith(prefix));
|
167
|
+
if (cookie) {
|
168
|
+
const value = cookie.split("=").slice(1).join("=");
|
169
|
+
if (value) {
|
170
|
+
return decodeURIComponent(value);
|
171
|
+
}
|
172
|
+
}
|
173
|
+
}
|
174
|
+
function compact(object) {
|
175
|
+
const result = {};
|
176
|
+
for (const key in object) {
|
177
|
+
const value = object[key];
|
178
|
+
if (value !== undefined) {
|
179
|
+
result[key] = value;
|
180
|
+
}
|
181
|
+
}
|
182
|
+
return result;
|
183
|
+
}
|
184
|
+
function metaContent(name) {
|
185
|
+
const element = document.head.querySelector(`meta[name="${name}"]`);
|
186
|
+
return element && element.content;
|
187
|
+
}
|
188
|
+
function stringEntriesFromFormData(formData) {
|
189
|
+
return [...formData].reduce((entries, [name, value]) => {
|
190
|
+
return entries.concat(typeof value === "string" ? [[name, value]] : []);
|
191
|
+
}, []);
|
192
|
+
}
|
193
|
+
function mergeEntries(searchParams, entries) {
|
194
|
+
for (const [name, value] of entries) {
|
195
|
+
if (value instanceof window.File)
|
196
|
+
continue;
|
197
|
+
if (searchParams.has(name) && !name.includes("[]")) {
|
198
|
+
searchParams.delete(name);
|
199
|
+
searchParams.set(name, value);
|
200
|
+
} else {
|
201
|
+
searchParams.append(name, value);
|
202
|
+
}
|
203
|
+
}
|
204
|
+
}
|
205
|
+
|
206
|
+
// node_modules/@rails/request.js/src/fetch_request.js
|
207
|
+
class FetchRequest {
|
208
|
+
constructor(method, url, options = {}) {
|
209
|
+
this.method = method;
|
210
|
+
this.options = options;
|
211
|
+
this.originalUrl = url.toString();
|
212
|
+
}
|
213
|
+
async perform() {
|
214
|
+
try {
|
215
|
+
const requestInterceptor = RequestInterceptor.get();
|
216
|
+
if (requestInterceptor) {
|
217
|
+
await requestInterceptor(this);
|
218
|
+
}
|
219
|
+
} catch (error) {
|
220
|
+
console.error(error);
|
221
|
+
}
|
222
|
+
const fetch = this.responseKind === "turbo-stream" && window.Turbo ? window.Turbo.fetch : window.fetch;
|
223
|
+
const response = new FetchResponse(await fetch(this.url, this.fetchOptions));
|
224
|
+
if (response.unauthenticated && response.authenticationURL) {
|
225
|
+
return Promise.reject(window.location.href = response.authenticationURL);
|
226
|
+
}
|
227
|
+
if (response.isScript) {
|
228
|
+
await response.activeScript();
|
229
|
+
}
|
230
|
+
const responseStatusIsTurboStreamable = response.ok || response.unprocessableEntity;
|
231
|
+
if (responseStatusIsTurboStreamable && response.isTurboStream) {
|
232
|
+
await response.renderTurboStream();
|
233
|
+
}
|
234
|
+
return response;
|
235
|
+
}
|
236
|
+
addHeader(key, value) {
|
237
|
+
const headers = this.additionalHeaders;
|
238
|
+
headers[key] = value;
|
239
|
+
this.options.headers = headers;
|
240
|
+
}
|
241
|
+
sameHostname() {
|
242
|
+
if (!this.originalUrl.startsWith("http:") && !this.originalUrl.startsWith("https:")) {
|
243
|
+
return true;
|
244
|
+
}
|
245
|
+
try {
|
246
|
+
return new URL(this.originalUrl).hostname === window.location.hostname;
|
247
|
+
} catch (_) {
|
248
|
+
return true;
|
249
|
+
}
|
250
|
+
}
|
251
|
+
get fetchOptions() {
|
252
|
+
return {
|
253
|
+
method: this.method.toUpperCase(),
|
254
|
+
headers: this.headers,
|
255
|
+
body: this.formattedBody,
|
256
|
+
signal: this.signal,
|
257
|
+
credentials: this.credentials,
|
258
|
+
redirect: this.redirect,
|
259
|
+
keepalive: this.keepalive
|
260
|
+
};
|
261
|
+
}
|
262
|
+
get headers() {
|
263
|
+
const baseHeaders = {
|
264
|
+
"X-Requested-With": "XMLHttpRequest",
|
265
|
+
"Content-Type": this.contentType,
|
266
|
+
Accept: this.accept
|
267
|
+
};
|
268
|
+
if (this.sameHostname()) {
|
269
|
+
baseHeaders["X-CSRF-Token"] = this.csrfToken;
|
270
|
+
}
|
271
|
+
return compact(Object.assign(baseHeaders, this.additionalHeaders));
|
272
|
+
}
|
273
|
+
get csrfToken() {
|
274
|
+
return getCookie(metaContent("csrf-param")) || metaContent("csrf-token");
|
275
|
+
}
|
276
|
+
get contentType() {
|
277
|
+
if (this.options.contentType) {
|
278
|
+
return this.options.contentType;
|
279
|
+
} else if (this.body == null || this.body instanceof window.FormData) {
|
280
|
+
return;
|
281
|
+
} else if (this.body instanceof window.File) {
|
282
|
+
return this.body.type;
|
283
|
+
}
|
284
|
+
return "application/json";
|
285
|
+
}
|
286
|
+
get accept() {
|
287
|
+
switch (this.responseKind) {
|
288
|
+
case "html":
|
289
|
+
return "text/html, application/xhtml+xml";
|
290
|
+
case "turbo-stream":
|
291
|
+
return "text/vnd.turbo-stream.html, text/html, application/xhtml+xml";
|
292
|
+
case "json":
|
293
|
+
return "application/json, application/vnd.api+json";
|
294
|
+
case "script":
|
295
|
+
return "text/javascript, application/javascript";
|
296
|
+
default:
|
297
|
+
return "*/*";
|
298
|
+
}
|
299
|
+
}
|
300
|
+
get body() {
|
301
|
+
return this.options.body;
|
302
|
+
}
|
303
|
+
get query() {
|
304
|
+
const originalQuery = (this.originalUrl.split("?")[1] || "").split("#")[0];
|
305
|
+
const params = new URLSearchParams(originalQuery);
|
306
|
+
let requestQuery = this.options.query;
|
307
|
+
if (requestQuery instanceof window.FormData) {
|
308
|
+
requestQuery = stringEntriesFromFormData(requestQuery);
|
309
|
+
} else if (requestQuery instanceof window.URLSearchParams) {
|
310
|
+
requestQuery = requestQuery.entries();
|
311
|
+
} else {
|
312
|
+
requestQuery = Object.entries(requestQuery || {});
|
313
|
+
}
|
314
|
+
mergeEntries(params, requestQuery);
|
315
|
+
const query = params.toString();
|
316
|
+
return query.length > 0 ? `?${query}` : "";
|
317
|
+
}
|
318
|
+
get url() {
|
319
|
+
return this.originalUrl.split("?")[0].split("#")[0] + this.query;
|
320
|
+
}
|
321
|
+
get responseKind() {
|
322
|
+
return this.options.responseKind || "html";
|
323
|
+
}
|
324
|
+
get signal() {
|
325
|
+
return this.options.signal;
|
326
|
+
}
|
327
|
+
get redirect() {
|
328
|
+
return this.options.redirect || "follow";
|
329
|
+
}
|
330
|
+
get credentials() {
|
331
|
+
return this.options.credentials || "same-origin";
|
332
|
+
}
|
333
|
+
get keepalive() {
|
334
|
+
return this.options.keepalive || false;
|
335
|
+
}
|
336
|
+
get additionalHeaders() {
|
337
|
+
return this.options.headers || {};
|
338
|
+
}
|
339
|
+
get formattedBody() {
|
340
|
+
const bodyIsAString = Object.prototype.toString.call(this.body) === "[object String]";
|
341
|
+
const contentTypeIsJson = this.headers["Content-Type"] === "application/json";
|
342
|
+
if (contentTypeIsJson && !bodyIsAString) {
|
343
|
+
return JSON.stringify(this.body);
|
344
|
+
}
|
345
|
+
return this.body;
|
346
|
+
}
|
347
|
+
}
|
348
|
+
|
349
|
+
// node_modules/@rails/request.js/src/verbs.js
|
350
|
+
async function post(url, options) {
|
351
|
+
const request = new FetchRequest("post", url, options);
|
352
|
+
return request.perform();
|
353
|
+
}
|
354
|
+
|
355
|
+
// app/assets/javascripts/components/granted.js
|
356
|
+
class Granted extends HTMLElement {
|
357
|
+
constructor() {
|
358
|
+
super();
|
359
|
+
}
|
360
|
+
connectedCallback() {
|
361
|
+
document.addEventListener("action-push-web:granted", this.attributeChangedCallback.bind(this));
|
362
|
+
document.addEventListener("action-push-web:denied", this.attributeChangedCallback.bind(this));
|
363
|
+
this.#setState();
|
364
|
+
}
|
365
|
+
disconnectedCallback() {
|
366
|
+
document.removeEventListener("action-push-web:granted", this.attributeChangedCallback.bind(this));
|
367
|
+
document.removeEventListener("action-push-web:denied", this.attributeChangedCallback.bind(this));
|
368
|
+
}
|
369
|
+
attributeChangedCallback() {
|
370
|
+
this.#setState();
|
371
|
+
}
|
372
|
+
async#subscribe() {
|
373
|
+
const registration = await this.#serviceWorkerRegistration || await this.#registerServiceWorker();
|
374
|
+
registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.#vapidPublicKey }).then((subscription) => {
|
375
|
+
this.#syncPushSubscription(subscription);
|
376
|
+
});
|
377
|
+
}
|
378
|
+
get #isEnabled() {
|
379
|
+
return !!navigator.serviceWorker && !!window.Notification && Notification.permission == "granted";
|
380
|
+
}
|
381
|
+
get #serviceWorkerRegistration() {
|
382
|
+
return navigator.serviceWorker.getRegistration();
|
383
|
+
}
|
384
|
+
get #vapidPublicKey() {
|
385
|
+
const encodedVapidPublicKey = document.querySelector('meta[name="action-push-web-public-key"]').content;
|
386
|
+
return this.#urlBase64ToUint8Array(encodedVapidPublicKey);
|
387
|
+
}
|
388
|
+
async#syncPushSubscription(subscription) {
|
389
|
+
const response = await post(this.getAttribute("href"), {
|
390
|
+
body: this.#extractJsonPayloadAsString(subscription)
|
391
|
+
});
|
392
|
+
if (!response.ok) {
|
393
|
+
subscription.unsubscribe();
|
394
|
+
}
|
395
|
+
}
|
396
|
+
#extractJsonPayloadAsString(subscription) {
|
397
|
+
const { endpoint, keys: { p256dh, auth } } = subscription.toJSON();
|
398
|
+
return JSON.stringify({ push_subscription: { endpoint, p256dh_key: p256dh, auth_key: auth } });
|
399
|
+
}
|
400
|
+
#setState() {
|
401
|
+
this.hidden = !this.#isEnabled;
|
402
|
+
if (this.#isEnabled) {
|
403
|
+
this.#subscribe();
|
404
|
+
}
|
405
|
+
}
|
406
|
+
#urlBase64ToUint8Array(base64String) {
|
407
|
+
const padding = "=".repeat((4 - base64String.length % 4) % 4);
|
408
|
+
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
|
409
|
+
const rawData = window.atob(base64);
|
410
|
+
const outputArray = new Uint8Array(rawData.length);
|
411
|
+
for (let i = 0;i < rawData.length; ++i) {
|
412
|
+
outputArray[i] = rawData.charCodeAt(i);
|
413
|
+
}
|
414
|
+
return outputArray;
|
415
|
+
}
|
416
|
+
#registerServiceWorker() {
|
417
|
+
return navigator.serviceWorker.register(this.getAttribute("service-worker-url"));
|
418
|
+
}
|
419
|
+
}
|
420
|
+
|
421
|
+
// app/assets/javascripts/components/action_push_web.js
|
422
|
+
customElements.define("action-push-web-request", Request);
|
423
|
+
customElements.define("action-push-web-denied", Denied);
|
424
|
+
customElements.define("action-push-web-granted", Granted);
|
@@ -0,0 +1,7 @@
|
|
1
|
+
import Request from "./request";
|
2
|
+
import Denied from "./denied";
|
3
|
+
import Granted from "./granted";
|
4
|
+
|
5
|
+
customElements.define("action-push-web-request", Request);
|
6
|
+
customElements.define("action-push-web-denied", Denied);
|
7
|
+
customElements.define("action-push-web-granted", Granted);
|
@@ -0,0 +1,24 @@
|
|
1
|
+
export default class Denied extends HTMLElement {
|
2
|
+
constructor() {
|
3
|
+
super();
|
4
|
+
}
|
5
|
+
|
6
|
+
connectedCallback() {
|
7
|
+
this.hidden = !this.isEnabled;
|
8
|
+
document.addEventListener('action-push-web:granted', this.attributeChangedCallback.bind(this));
|
9
|
+
document.addEventListener('action-push-web:denied', this.attributeChangedCallback.bind(this));
|
10
|
+
}
|
11
|
+
|
12
|
+
disconnectedCallback() {
|
13
|
+
document.removeEventListener('action-push-web:granted', this.attributeChangedCallback.bind(this));
|
14
|
+
document.removeEventListener('action-push-web:denied', this.attributeChangedCallback.bind(this));
|
15
|
+
}
|
16
|
+
|
17
|
+
attributeChangedCallback() {
|
18
|
+
this.hidden = !this.isEnabled;
|
19
|
+
}
|
20
|
+
|
21
|
+
get isEnabled() {
|
22
|
+
return !navigator.serviceWorker || !window.Notification || Notification.permission == "denied"
|
23
|
+
}
|
24
|
+
}
|
@@ -0,0 +1,86 @@
|
|
1
|
+
import { post } from "@rails/request.js"
|
2
|
+
|
3
|
+
export default class Granted extends HTMLElement {
|
4
|
+
constructor() {
|
5
|
+
super();
|
6
|
+
}
|
7
|
+
|
8
|
+
connectedCallback() {
|
9
|
+
document.addEventListener('action-push-web:granted', this.attributeChangedCallback.bind(this));
|
10
|
+
document.addEventListener('action-push-web:denied', this.attributeChangedCallback.bind(this));
|
11
|
+
this.#setState()
|
12
|
+
}
|
13
|
+
|
14
|
+
disconnectedCallback() {
|
15
|
+
document.removeEventListener('action-push-web:granted', this.attributeChangedCallback.bind(this));
|
16
|
+
document.removeEventListener('action-push-web:denied', this.attributeChangedCallback.bind(this));
|
17
|
+
}
|
18
|
+
|
19
|
+
attributeChangedCallback() {
|
20
|
+
this.#setState()
|
21
|
+
}
|
22
|
+
|
23
|
+
async #subscribe() {
|
24
|
+
const registration = await this.#serviceWorkerRegistration || await this.#registerServiceWorker()
|
25
|
+
registration.pushManager
|
26
|
+
.subscribe({ userVisibleOnly: true, applicationServerKey: this.#vapidPublicKey })
|
27
|
+
.then(subscription => {
|
28
|
+
this.#syncPushSubscription(subscription)
|
29
|
+
})
|
30
|
+
}
|
31
|
+
|
32
|
+
get #isEnabled() {
|
33
|
+
return !!navigator.serviceWorker && !!window.Notification && Notification.permission == "granted"
|
34
|
+
}
|
35
|
+
|
36
|
+
get #serviceWorkerRegistration() {
|
37
|
+
return navigator.serviceWorker.getRegistration()
|
38
|
+
}
|
39
|
+
|
40
|
+
get #vapidPublicKey() {
|
41
|
+
const encodedVapidPublicKey = document.querySelector('meta[name="action-push-web-public-key"]').content
|
42
|
+
return this.#urlBase64ToUint8Array(encodedVapidPublicKey)
|
43
|
+
}
|
44
|
+
|
45
|
+
async #syncPushSubscription(subscription) {
|
46
|
+
const response = await post(this.getAttribute('href'), {
|
47
|
+
body: this.#extractJsonPayloadAsString(subscription),
|
48
|
+
})
|
49
|
+
|
50
|
+
if (!response.ok) {
|
51
|
+
subscription.unsubscribe()
|
52
|
+
}
|
53
|
+
}
|
54
|
+
|
55
|
+
#extractJsonPayloadAsString(subscription) {
|
56
|
+
const { endpoint, keys: { p256dh, auth } } = subscription.toJSON()
|
57
|
+
|
58
|
+
return JSON.stringify({ push_subscription: { endpoint, p256dh_key: p256dh, auth_key: auth } })
|
59
|
+
}
|
60
|
+
|
61
|
+
#setState() {
|
62
|
+
this.hidden = !this.#isEnabled;
|
63
|
+
if (this.#isEnabled) {
|
64
|
+
this.#subscribe()
|
65
|
+
}
|
66
|
+
}
|
67
|
+
|
68
|
+
// VAPID public key comes encoded as base64 but service worker registration needs it as a Uint8Array
|
69
|
+
#urlBase64ToUint8Array(base64String) {
|
70
|
+
const padding = "=".repeat((4 - base64String.length % 4) % 4)
|
71
|
+
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/")
|
72
|
+
|
73
|
+
const rawData = window.atob(base64)
|
74
|
+
const outputArray = new Uint8Array(rawData.length)
|
75
|
+
|
76
|
+
for (let i = 0; i < rawData.length; ++i) {
|
77
|
+
outputArray[i] = rawData.charCodeAt(i)
|
78
|
+
}
|
79
|
+
|
80
|
+
return outputArray
|
81
|
+
}
|
82
|
+
|
83
|
+
#registerServiceWorker() {
|
84
|
+
return navigator.serviceWorker.register(this.getAttribute('service-worker-url'))
|
85
|
+
}
|
86
|
+
}
|
@@ -0,0 +1,55 @@
|
|
1
|
+
export default class Request extends HTMLElement {
|
2
|
+
static observedAttributes = ["href"];
|
3
|
+
|
4
|
+
constructor() {
|
5
|
+
super();
|
6
|
+
}
|
7
|
+
|
8
|
+
connectedCallback() {
|
9
|
+
this.setAttribute('role', 'button');
|
10
|
+
this.#setState()
|
11
|
+
|
12
|
+
this.addEventListener('click', this.onClick);
|
13
|
+
}
|
14
|
+
|
15
|
+
#setState() {
|
16
|
+
if (this.isEnabled) {
|
17
|
+
this.removeAttribute('disabled')
|
18
|
+
} else {
|
19
|
+
this.setAttribute('disabled', true)
|
20
|
+
}
|
21
|
+
|
22
|
+
this.hidden = !this.isEnabled;
|
23
|
+
}
|
24
|
+
|
25
|
+
disconnectedCallback() {
|
26
|
+
this.removeEventListener('click', this.onClick);
|
27
|
+
}
|
28
|
+
|
29
|
+
attributeChangedCallback() {
|
30
|
+
this.#setState()
|
31
|
+
}
|
32
|
+
|
33
|
+
get isEnabled() {
|
34
|
+
return navigator.serviceWorker && window.Notification && Notification.permission == "default" && this.getAttribute('href')
|
35
|
+
}
|
36
|
+
|
37
|
+
get #isDisabled() {
|
38
|
+
return this.hasAttribute('disabled')
|
39
|
+
}
|
40
|
+
|
41
|
+
async onClick(event) {
|
42
|
+
event.preventDefault();
|
43
|
+
event.stopPropagation();
|
44
|
+
|
45
|
+
if (this.isEnabled && !this.isDisabled) {
|
46
|
+
const permission = await Notification.requestPermission()
|
47
|
+
if (permission === "granted") {
|
48
|
+
document.dispatchEvent(new CustomEvent('action-push-web:granted', {}))
|
49
|
+
} else if (permission === "denied") {
|
50
|
+
document.dispatchEvent(new CustomEvent('action-push-web:denied', {}))
|
51
|
+
}
|
52
|
+
this.#setState()
|
53
|
+
}
|
54
|
+
}
|
55
|
+
}
|
@@ -0,0 +1,15 @@
|
|
1
|
+
/*
|
2
|
+
* This is a manifest file that'll be compiled into application.css, which will include all the files
|
3
|
+
* listed below.
|
4
|
+
*
|
5
|
+
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
|
6
|
+
* or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
|
7
|
+
*
|
8
|
+
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
|
9
|
+
* compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
|
10
|
+
* files in this directory. Styles in this file should be added after the last require_* statement.
|
11
|
+
* It is generally better to create a new file per style scope.
|
12
|
+
*
|
13
|
+
*= require_tree .
|
14
|
+
*= require_self
|
15
|
+
*/
|
@@ -0,0 +1,19 @@
|
|
1
|
+
module ActionPushWeb
|
2
|
+
class SubscriptionsController < ApplicationController
|
3
|
+
def create
|
4
|
+
if subscription = ApplicationPushSubscription.find_by(push_subscription_params)
|
5
|
+
subscription.touch
|
6
|
+
else
|
7
|
+
ApplicationPushSubscription.create! push_subscription_params.merge(user_agent: request.user_agent)
|
8
|
+
end
|
9
|
+
|
10
|
+
head :ok
|
11
|
+
end
|
12
|
+
|
13
|
+
private
|
14
|
+
|
15
|
+
def push_subscription_params
|
16
|
+
params.expect(push_subscription: %i[endpoint p256dh_key auth_key])
|
17
|
+
end
|
18
|
+
end
|
19
|
+
end
|
@@ -0,0 +1,22 @@
|
|
1
|
+
module ActionPushWeb
|
2
|
+
module ApplicationHelper
|
3
|
+
def action_push_web_key_tag(application: nil)
|
4
|
+
tag.meta name: "action-push-web-public-key",
|
5
|
+
content: ActionPushWeb.config_for(application)[:public_key]
|
6
|
+
end
|
7
|
+
|
8
|
+
def when_web_notifications_disabled(**attrs, &block)
|
9
|
+
content_tag("action-push-web-denied", capture(&block), **attrs)
|
10
|
+
end
|
11
|
+
|
12
|
+
def when_web_notifications_allowed(href: action_push_web.subscriptions_path,
|
13
|
+
service_worker_url: pwa_service_worker_path(format: :js), **attrs, &block)
|
14
|
+
content_tag("action-push-web-granted", capture(&block),
|
15
|
+
href:, service_worker_url:, **attrs)
|
16
|
+
end
|
17
|
+
|
18
|
+
def ask_for_web_notifications(**attrs, &block)
|
19
|
+
content_tag("action-push-web-request", capture(&block), **attrs)
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|