// Quple for iPhone: sign in with Quine, keep contacts, call people by // username, and take calls on iOS's own call screen. Calls happen in the // Jitsi Meet SDK, on whichever Jitsi server the caller picked. // // Screens: settings → sign-in → home (contacts, calling) → call. import React, { useCallback, useEffect, useRef, useState } from 'react'; import { ActivityIndicator, AppState, Linking, ScrollView, FlatList, KeyboardAvoidingView, Platform, Pressable, StatusBar, StyleSheet, Text, TextInput, View, useColorScheme, } from 'react-native'; import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'; import { getBuildNumber, getVersion } from 'react-native-device-info'; import Clipboard from '@react-native-clipboard/clipboard'; import { dump } from './src/logs'; import { JitsiMeeting, JitsiRefProps } from '@jitsi/react-native-sdk'; import { ActiveCall, Api, CallStatus, Contact, Invite, Me } from './src/api'; import { SignedOut, restore, signIn, signOut } from './src/auth'; import { connected, finish, onHangUp, ring, setupCallKit, startOutgoing, stopRinging } from './src/callkit'; import { POLL_MS } from './src/config'; import { lastMedia, rememberMedia } from './src/media'; import { Settings, cleanUrl, loadSettings, saveSettings } from './src/settings'; import { NOTIFIED_NO_ANSWER_MS, NO_ANSWER_MS, decide, peerEnded } from './src/watchdog'; import { NTFY_APP_STORE_URL, dismissForThisLaunch, dismissedThisLaunch, isSetUp, markSetUp } from './src/notifications'; /** * A call to join: where, the name to show in it, and its CallKit call * (callkit.ts), which lasts as long as the meeting. */ type Meeting = { jitsiUrl: string; meetingId: string; displayName: string; callUUID: string; outgoing: boolean; /** Who's on the other end. */ peer: string; /** * An outgoing call rings (RingingScreen) until the other side answers; * only then does the app join the Jitsi room. Incoming calls start answered. */ answered: boolean; /** The callee's app was closed: they got a notification, and it rings longer. */ notified?: boolean; }; export default function App() { const dark = useColorScheme() === 'dark'; const c = dark ? darkColors : lightColors; const [settings, setSettings] = useState(null); const [signedIn, setSignedIn] = useState(null); const [showSettings, setShowSettings] = useState(false); const [error, setError] = useState(''); const [meeting, setMeeting] = useState(null); // Why the last call ended, when it wasn't you: shown on the home screen. const [notice, setNotice] = useState(''); // Settings, then the saved sign-in. useEffect(() => { (async () => { const s = await loadSettings(); setSettings(s); try { setSignedIn(await restore(s.identityUrl)); } catch (e: any) { setError(String(e?.message ?? e)); setSignedIn(false); } })(); setupCallKit().catch(() => {}); }, []); const onSignedOut = useCallback(() => setSignedIn(false), []); if (!settings || signedIn === null) { return ( ); } if (meeting && !meeting.answered) { return ( setMeeting({ ...meeting, answered: true })} onEnd={why => { setMeeting(null); setNotice(why ?? ''); }} /> ); } if (meeting) { return ( { setMeeting(null); setNotice(why ?? ''); }} /> ); } if (showSettings) { return ( setShowSettings(false)} onSave={async next => { const identityChanged = next.identityUrl !== settings.identityUrl; await saveSettings(next); setSettings(next); setShowSettings(false); // A different identity server is a different account. if (identityChanged && signedIn) { await signOut(); setSignedIn(false); } }} onSignOut={ signedIn ? async () => { await signOut(); setSignedIn(false); setShowSettings(false); } : undefined } /> ); } if (!signedIn) { return ( { setError(''); try { await signIn(settings.identityUrl); setSignedIn(true); } catch (e: any) { // Closing the sheet isn't an error worth showing. if (!/cancel/i.test(String(e?.message))) setError(String(e?.message ?? e)); } }} onSettings={() => setShowSettings(true)} /> ); } return ( setShowSettings(true)} onSignedOut={onSignedOut} onJoin={setMeeting} onRemember={async jitsiUrl => { const next = { ...settings, jitsiUrl }; setSettings(next); await saveSettings(next); }} /> ); } // ---- Home: who you are, calling, contacts, incoming calls ----------------- function HomeScreen(props: { c: Colors; settings: Settings; /** Why the last call ended, if it wasn't you. */ notice: string; onSettings: () => void; onSignedOut: () => void; onJoin: (m: Meeting) => void; onRemember: (jitsiUrl: string) => Promise; }) { const { c, settings, onSignedOut, onJoin } = props; const api = useRef(new Api(settings.serverUrl)).current; const [me, setMe] = useState(null); const [contacts, setContacts] = useState(null); const [target, setTarget] = useState(''); const [jitsi, setJitsi] = useState(settings.jitsiUrl); const [status, setStatus] = useState(props.notice); // Your calls on your other devices (the Mac), to move here. const [elsewhere, setElsewhere] = useState([]); // Setting up call notifications (ntfy): asked at launch until done. const [showNotifications, setShowNotifications] = useState(false); useEffect(() => { const topic = me?.ntfyTopic; if (!topic || dismissedThisLaunch()) return; isSetUp(topic).then(done => { if (!done) setShowNotifications(true); }); }, [me?.ntfyTopic]); // Takes a call over from another device: this one joins the room, and // the other leaves once it has (README "Moving a call"). const moveHere = async (ac: ActiveCall) => { const callUUID = startOutgoing(ac.peer); try { const moved = await api.move(ac.meetingId); setElsewhere([]); onJoin({ jitsiUrl: moved.jitsiUrl, meetingId: moved.meetingId, displayName: me?.username ?? '', callUUID, outgoing: true, peer: moved.peer, answered: true, }); } catch (e) { finish(callUUID); fail(e); } }; // Invites already rung, so a poll doesn't ring the same one twice. const seen = useRef(new Set()); const meRef = useRef(null); meRef.current = me; const fail = useCallback( (e: any) => { if (e instanceof SignedOut) onSignedOut(); else setStatus(String(e?.message ?? e)); }, [onSignedOut], ); const refreshContacts = useCallback(() => { api.contacts().then(setContacts).catch(fail); }, [api, fail]); useEffect(() => { api.me().then(setMe).catch(fail); refreshContacts(); }, [api, fail, refreshContacts]); // Calls ringing here: how to stop one, by meeting, when we call its // caller back and the server answers it for us (a crossed call). const ringingHere = useRef(new Map void>()); const incoming = useCallback( (inv: Invite) => { if (seen.current.has(inv.meetingId)) return; seen.current.add(inv.meetingId); // While it rings, check whether the caller gave up (GET, which // doesn't count as answering), whatever the app's state: iOS's // incoming-call screen takes the app out of the foreground. let watch: ReturnType | null = null; const stopWatching = () => { if (watch) clearInterval(watch); watch = null; ringingHere.current.delete(inv.meetingId); }; const id = ring( inv.from, callUUID => { stopWatching(); onJoin({ jitsiUrl: inv.jitsiUrl, meetingId: inv.meetingId, displayName: meRef.current?.username ?? '', callUUID, outgoing: false, peer: inv.from, answered: true, }); }, () => { stopWatching(); setStatus(`Missed a call from ${inv.from}`); // Declined, or rang out: the caller's app stops ringing. api.hangUp(inv.meetingId).catch(() => {}); }, ); ringingHere.current.set(inv.meetingId, () => { stopWatching(); stopRinging(id, true); }); watch = setInterval(() => { api .callStatus(inv.meetingId) .then(st => { if (st.answeredOn) { // Answered on another of your devices: not a missed call. stopWatching(); stopRinging(id, true); setStatus(`Answered on your ${st.answeredOn}`); } else if (st.endedBy) { stopRinging(id); } }) .catch(() => {}); }, POLL_MS); }, [api, onJoin], ); // Poll while the app is in the foreground: that's both "I'm online" and // "did anyone call me?". iOS suspends a backgrounded app, so it stops there. useEffect(() => { let timer: ReturnType | null = null; const tick = () => { api .poll() .then(r => { r.invites.forEach(incoming); setElsewhere(r.calls); }) .catch(fail); }; const start = () => { if (timer) return; tick(); timer = setInterval(tick, POLL_MS); }; const stop = () => { if (timer) clearInterval(timer); timer = null; }; if (AppState.currentState === 'active') start(); const sub = AppState.addEventListener('change', s => { if (s === 'active') { start(); refreshContacts(); } else { stop(); } }); return () => { stop(); sub.remove(); }; }, [api, incoming, fail, refreshContacts]); const call = async (to: string) => { to = to.trim().toLowerCase(); if (!to) return; setStatus(`Calling ${to}…`); const callUUID = startOutgoing(to); try { const server = jitsi.trim() ? cleanUrl(jitsi) : undefined; const res = await api.call(to, server); // Remember the server for next time, or forget it when the field was // emptied: blank means the signaling server's default (ours). await props.onRemember(server ?? ''); setStatus(''); if (res.joined) { // They were calling us at the same time: the server answered their // call for us (README "Crossed calls"). Stop it ringing here, as // answered, so it never counts as a decline. seen.current.add(res.meetingId); ringingHere.current.get(res.meetingId)?.(); } onJoin({ jitsiUrl: res.jitsiUrl, meetingId: res.meetingId, displayName: me?.username ?? '', callUUID, outgoing: true, peer: to, answered: !!res.joined, notified: res.notified, }); } catch (e) { finish(callUUID); fail(e); } }; const isContact = (name: string) => (contacts ?? []).some(x => x.username === name); if (showNotifications && me?.ntfyServer && me.ntfyTopic) { return ( { await markSetUp(me.ntfyTopic!); setShowNotifications(false); }} onLater={() => { dismissForThisLaunch(); setShowNotifications(false); }} /> ); } return ( Signed in as {me?.username ?? '…'} {me?.ntfyTopic ? ( setShowNotifications(true)} hitSlop={12}> Notifications ) : null} Settings call(target)} returnKeyType="go" />