diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/calls.js | 25 | ||||
| -rw-r--r-- | src/dm-inbox.js | 24 | ||||
| -rw-r--r-- | src/features/messages.js | 36 | ||||
| -rw-r--r-- | src/i18n.js | 1 | ||||
| -rw-r--r-- | src/sw-nwc.js | 35 |
5 files changed, 110 insertions, 11 deletions
diff --git a/src/calls.js b/src/calls.js index 2447a2f..98d0a46 100644 --- a/src/calls.js +++ b/src/calls.js @@ -23,7 +23,8 @@ const ALT = { [CALL.HANGUP]: 'WebRTC call hangup', [CALL.REJECT]: 'WebRTC call rejection', [CALL.RENEGOTIATE]: 'WebRTC call renegotiation', }; export const STALE_S = 20; // older setup messages are a relay replaying the past -const RING_MS = 60_000; +export const RING_S = 60; +const RING_MS = RING_S * 1000; const ENDED_MS = 2500; // how long "Call ended" stays up const now = () => Math.floor(Date.now() / 1000); @@ -102,7 +103,12 @@ export function createCalls(env) { c.remote = new MediaStream(); pc.ontrack = (e) => { for (const t of (e.streams[0] || { getTracks: () => [e.track] }).getTracks()) if (!c.remote.getTracks().includes(t)) c.remote.addTrack(t); changed(); }; c.trickle = env.trickle ? env.trickle() !== false : true; - pc.onicecandidate = (e) => { if (c.trickle && e.candidate && call === c && c.state !== 'ended') sendFor(c, CALL.ICE, c.peer, candidateJson(e.candidate)).catch(() => {}); }; + c.sent = []; + pc.onicecandidate = (e) => { + if (!c.trickle || !e.candidate || call !== c || c.state === 'ended') return; + c.sent.push(e.candidate); + sendFor(c, CALL.ICE, c.peer, candidateJson(e.candidate)).catch(() => {}); + }; pc.onconnectionstatechange = () => { if (call !== c) return; const s = pc.connectionState; @@ -218,11 +224,14 @@ export function createCalls(env) { } // ---- what arrives - async function handle(ev) { + // `maxAge`: an offer the service worker kept from a push may be older than + // a relay's live one (the person had to tap the notification): it still + // rings, for what's left of its minute + async function handle(ev, { maxAge = STALE_S } = {}) { if (!ev || seen.has(ev.id)) return; + if (now() - ev.created_at > maxAge) return; seen.add(ev.id); if (seen.size > 5000) seen.clear(); - if (now() - ev.created_at > STALE_S) return; const me = env.me(); const id = callIdOf(ev), from = ev.pubkey, self = from === me; const c = call; @@ -237,7 +246,7 @@ export function createCalls(env) { clearTimeout(endTimer); const type = tagOf(ev, 'call-type') === 'video' ? 'video' : 'voice'; const n = call = { id, peer: from, type, dir: 'in', state: 'incoming', offer: ev.content, ice: [], at: Date.now(), muted: false, camOff: false, facing: 'user' }; - ringTimer = setTimeout(() => { if (call === n && n.state === 'incoming') end('missed', n); }, RING_MS); + ringTimer = setTimeout(() => { if (call === n && n.state === 'incoming') end('missed', n); }, Math.max(5000, RING_MS - (Date.now() - ev.created_at * 1000))); changed(); return; } @@ -248,7 +257,11 @@ export function createCalls(env) { if (c.state === 'offering') { c.state = 'connecting'; changed(); try { await c.pc.setRemoteDescription({ type: 'answer', sdp: ev.content }); c.remoteSet = true; await addCandidates(c); } - catch { end('error', c); } + catch { end('error', c); return; } + // Our candidates went out while they rang — to an app that may have + // been closed then (woken by a push, it heard none of them). Once + // more, now that they're listening; a repeat is harmless. + if (c.trickle) for (const cand of c.sent || []) sendFor(c, CALL.ICE, c.peer, candidateJson(cand)).catch(() => {}); } else if (c.renegotiating) { // their answer to our renegotiation c.renegotiating = false; try { await c.pc.setRemoteDescription({ type: 'answer', sdp: ev.content }); } catch {} diff --git a/src/dm-inbox.js b/src/dm-inbox.js index b9eec3a..1a026c1 100644 --- a/src/dm-inbox.js +++ b/src/dm-inbox.js @@ -15,6 +15,8 @@ // notification instead of a filtered one. import { unwrapDM } from './dm.js'; +import { openCall, CALL, RING_S } from './calls.js'; +import * as nip44 from 'nostr-tools/nip44'; const DB = 'coinos-dm-inbox'; const STORE = 'inbox'; @@ -115,3 +117,25 @@ export function shouldNotifyDm(verdict) { if (verdict.followed || verdict.known) return true; return !verdict.hasList; } + +// A call ringing in (NIP-AC), the wrap a push pointed at: opened with the key +// it's for, and worth ringing only as a fresh offer from someone this +// account follows or talks to, and hasn't muted. Returns { offer, name, +// type } to ring with, or null for anything else (a candidate, a stranger, +// a stale one, a wrap we hold no key for). +export async function classifyCall(wrap, inboxes, nowS = Math.floor(Date.now() / 1000)) { + for (const rec of inboxes) { + if (!rec || !rec.sk) continue; + let sk; + try { sk = unhex(rec.sk); } catch { continue; } + const ev = await openCall(wrap, async (pk, ct) => nip44.decrypt(ct, nip44.getConversationKey(sk, pk))); + if (!ev) continue; + const from = ev.pubkey; + if (ev.kind !== CALL.OFFER || from === rec.pubkey || nowS - ev.created_at > RING_S) return null; + if ((rec.muted || []).includes(from)) return null; + if (!(rec.follows || []).includes(from) && !(rec.known || []).includes(from)) return null; + const type = (ev.tags.find((x) => x[0] === 'call-type') || [])[1] === 'video' ? 'video' : 'voice'; + return { offer: ev, name: (rec.names || {})[from] || null, type }; + } + return null; +} diff --git a/src/features/messages.js b/src/features/messages.js index ec564e8..9d03a86 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -53,7 +53,7 @@ import { animateZap, warmZapSound } from '../zap-animation.js'; import { SIGNER_SILENT } from '../dm.js'; import { cacheStorage, onCacheReady, cacheIsReady } from '../cache-store.js'; import { dlog } from '../debug.js'; -import { createCalls, openCall, wrapCall, CALL_WRAP } from '../calls.js'; +import { createCalls, openCall, wrapCall, CALL_WRAP, RING_S } from '../calls.js'; import { LIVE_KIND, LIVE_CHAT_KIND, LIVE_RELAYS, liveAddr, liveHost, liveTitle, liveSummary, liveImage, liveViewers, liveStarts, liveStream, liveRecording, liveStatus, isLiveNow, liveRelays, newestByAddr, zapLine, setZapAddr } from '../live.js'; import { qrSvg } from '../qr.js'; @@ -2416,7 +2416,7 @@ export function messagesFeature(ctx) { // never sends what the user turned off (a suppressed-but-delivered push // would earn Chrome's generic "updated in background" nag instead) const want = (k) => s.reasons?.[k] !== false; - const reasons = { payment: want('payment'), zap: want('zap'), dm: want('dm'), mention: want('mention'), reaction: want('reaction') }; + const reasons = { payment: want('payment'), zap: want('zap'), dm: want('dm'), mention: want('mention'), reaction: want('reaction'), call: want('call') }; // Stamp the network: the same seed makes the same nostr pubkey on mainnet // AND staging, so without this the notifier fans a mainnet payment push // out to the staging PWA's subscription too — and tapping it opened @@ -2480,6 +2480,7 @@ export function messagesFeature(ctx) { rowT(t('notifDm'), 'dm'), rowT(t('notifMention'), 'mention'), rowT(t('notifReaction'), 'reaction'), + rowT(t('notifCall'), 'call'), h('div', { class: 'small faint' }, t('notifChatHint'))); } @@ -2487,13 +2488,17 @@ export function messagesFeature(ctx) { // stranger's: our key (only if we actually hold one), who we follow, and the // names we already know. See dm-inbox.js for the threat model — a remote // signer stores no key here and simply gets unfiltered notifications. - let inboxAt = 0; + let inboxAt = 0, inboxTries = 0; async function syncInbox({ force = false } = {}) { if (!force && Date.now() - inboxAt < 5 * 60_000) return; inboxAt = Date.now(); try { const id = await identity(); - if (!id) return; + // the keys not there yet (a wallet still opening): try again shortly — + // this used to count as done for five minutes, and a phone woken by a + // push in that time had no key to open a DM or a call with + if (!id) { if (++inboxTries <= 10) { inboxAt = 0; setTimeout(() => { syncInbox().catch(() => {}); }, 3000); } return; } + inboxTries = 0; const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [3], authors: [id.pubkey] }, 4000); const newest = evs.sort((a, b) => b.created_at - a.created_at)[0]; @@ -9106,6 +9111,18 @@ export function messagesFeature(ctx) { if (inner) { profileOf(inner.pubkey); await callsNow().handle(inner); return; } } } + // the call offer a push brought (sw-nwc.js keeps it): rung now, once + async function pendingCall() { + try { + if (typeof caches === 'undefined') return; + const cache = await caches.open('coinos-call'); + const r = await cache.match('/__pending-call'); + if (!r) return; + await cache.delete('/__pending-call'); + const { offer, at } = await r.json(); + if (offer && Date.now() - at < RING_S * 1000) await callsNow().handle(offer, { maxAge: RING_S }); + } catch {} + } function startCall(peer, type) { if (typeof RTCPeerConnection === 'undefined' || !navigator.mediaDevices?.getUserMedia) { toast(t('callUnsupported')); return; } const cur = callsNow().call; @@ -9133,6 +9150,10 @@ export function messagesFeature(ctx) { ringFor = want; clearInterval(ringTimer); ringTimer = null; try { navigator.vibrate && navigator.vibrate(0); } catch {} + // answered, declined or over: its "is calling" notification goes too + if (!want || want.endsWith(':offering')) { + try { navigator.serviceWorker?.ready.then((r) => r.getNotifications({ tag: 'call' })).then((ns) => { for (const n of ns || []) n.close(); }).catch(() => {}); } catch {} + } if (!want) return; const incoming = c.state === 'incoming'; const beat = () => { @@ -17111,8 +17132,15 @@ export function messagesFeature(ctx) { try { navigator.serviceWorker?.addEventListener('message', (ev) => { if (ev.data && ev.data.type === 'open' && ev.data.view === 'notifs') openNotifs(); + // a call the worker was woken for: rung here too (an app in the + // background may have missed it live), or picked up from the tap + if (ev.data && ev.data.type === 'call-offer' && ev.data.offer) callsNow().handle(ev.data.offer, { maxAge: RING_S }).catch(() => {}); + if (ev.data && ev.data.type === 'open' && ev.data.view === 'call') pendingCall(); }); } catch {} + // a tapped "is calling" opened the app, or brought it back: the offer the worker kept + setTimeout(pendingCall, 0); + document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') pendingCall(); }); if (urlInvite && !pendingLink) { loadLinkInvite(urlInvite); setTimeout(() => { ui.chatOpen = true; ui.msgView = 'home'; render(); }, 0); diff --git a/src/i18n.js b/src/i18n.js index 586a7e6..80e8146 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -518,6 +518,7 @@ const STR = { callAnsweredElsewhere: 'Answered on another device', callDeclinedElsewhere: 'Declined on another device', callUnsupported: 'This browser can’t make calls.', + notifCall: 'Calls', feedAttach: 'Attach a picture or video', postLike: 'Like', postBoost: 'Boost', diff --git a/src/sw-nwc.js b/src/sw-nwc.js index 3dac246..b6af6b8 100644 --- a/src/sw-nwc.js +++ b/src/sw-nwc.js @@ -7,15 +7,48 @@ import { respondFromBg, tendRenewals } from './nwc-respond.js'; import { withRequestLock } from './nwc-lock.js'; import { bgAutoWithdraw } from './bg-autowithdraw.js'; -import { allInboxes, classifyDm, shouldNotifyDm } from './dm-inbox.js'; +import { allInboxes, classifyDm, shouldNotifyDm, classifyCall } from './dm-inbox.js'; const NOTIFIER = 'https://nwcpush.coinos.io'; +const CALL_CACHE = 'coinos-call'; // a call offer a push brought, for the app the tap opens +// where a call's offer wrap is fetched from: the notifier, or (the app served +// on this machine, as the tests do) this origin +const WRAPS = /^(localhost|127\.0\.0\.1)$/.test(self.location.hostname) ? self.location.origin + '/nwcpush' : NOTIFIER; self.addEventListener('push', (e) => { let data = {}; try { data = e.data ? e.data.json() : {}; } catch (_) {} // User-facing notifications (payments, DMs, community chat). An open // window already shows everything live — stay quiet then. + // A call ringing in: the push names the offer's wrap, kept at the notifier + // (too big to ride in a push). Opened here with our key; a fresh offer + // from someone we follow or talk to rings, as a notification that stays + // until it's answered or missed. The offer is kept for the app to pick up + // when the tap opens it (CALL_CACHE). An open window rings by itself. + if (data.type === 'notify' && data.reason === 'call') { + e.waitUntil((async () => { + const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); + if (clients.some((c) => c.visibilityState === 'visible')) return; + let ring = null; + try { + const r = await fetch(WRAPS + '/wrap/' + encodeURIComponent(data.wrapId || '')); + if (r.ok) ring = await classifyCall(await r.json(), await allInboxes()); + } catch (err) { console.warn('[sw-call] could not open:', err && err.message); } + if (!ring) return; + try { + const cache = await caches.open(CALL_CACHE); + await cache.put('/__pending-call', new Response(JSON.stringify({ offer: ring.offer, at: Date.now() }), { headers: { 'content-type': 'application/json' } })); + } catch (_) {} + for (const c of clients) { try { c.postMessage({ type: 'call-offer', offer: ring.offer }); } catch (_) {} } + await self.registration.showNotification((ring.name || 'Someone') + ' is calling', { + body: ring.type === 'video' ? 'Video call. Tap to answer.' : 'Voice call. Tap to answer.', + icon: 'icon-192.png', badge: 'badge-96.png', + tag: 'call', renotify: true, requireInteraction: true, vibrate: [400, 200, 400, 200, 400], + data: { url: './?open=call', view: 'call' }, + }); + })()); + return; + } if (data.type === 'notify') { e.waitUntil((async () => { const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); |
