Move the Capacitor code to the mobile overlay. [skip build]
This commit is contained in:
@@ -1,309 +0,0 @@
|
|||||||
import { useAtomValue } from 'jotai';
|
|
||||||
import React, { ChangeEventHandler, useCallback, useMemo, useRef, useState } from 'react';
|
|
||||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
|
||||||
import FocusTrap from 'focus-trap-react';
|
|
||||||
import {
|
|
||||||
Avatar,
|
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
Header,
|
|
||||||
IconButton,
|
|
||||||
Input,
|
|
||||||
MenuItem,
|
|
||||||
Modal,
|
|
||||||
Overlay,
|
|
||||||
OverlayBackdrop,
|
|
||||||
OverlayCenter,
|
|
||||||
Scroll,
|
|
||||||
Text,
|
|
||||||
config,
|
|
||||||
} from 'folds';
|
|
||||||
import { Icon, Icons } from '../components/icons';
|
|
||||||
import { useMatrixClient } from '../hooks/useMatrixClient';
|
|
||||||
import { useAllJoinedRoomsSet, useGetRoom } from '../hooks/useGetRoom';
|
|
||||||
import { allRoomsAtom } from '../state/room-list/roomList';
|
|
||||||
import { mDirectAtom } from '../state/mDirectList';
|
|
||||||
import { useDirects, useRooms } from '../state/hooks/roomList';
|
|
||||||
import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '../utils/room';
|
|
||||||
import { RoomAvatar, RoomIcon } from '../components/room-avatar';
|
|
||||||
import { nameInitials } from '../utils/common';
|
|
||||||
import { useMediaAuthentication } from '../hooks/useMediaAuthentication';
|
|
||||||
import { factoryRoomIdByActivity } from '../utils/sort';
|
|
||||||
import {
|
|
||||||
SearchItemStrGetter,
|
|
||||||
useAsyncSearch,
|
|
||||||
UseAsyncSearchOptions,
|
|
||||||
} from '../hooks/useAsyncSearch';
|
|
||||||
import { VirtualTile } from '../components/virtualizer';
|
|
||||||
import { AndroidSharePayload } from '../utils/androidShare';
|
|
||||||
import { stopPropagation } from '../utils/keyboard';
|
|
||||||
|
|
||||||
const SEARCH_OPTS: UseAsyncSearchOptions = {
|
|
||||||
limit: 200,
|
|
||||||
matchOptions: {
|
|
||||||
contain: true,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
type ShareRoomPickerProps = {
|
|
||||||
/** The pending share payload to display a preview of. */
|
|
||||||
share: AndroidSharePayload;
|
|
||||||
/** Called when the user picks a room. */
|
|
||||||
onPick: (roomId: string) => void;
|
|
||||||
/** Called when the user dismisses without picking. */
|
|
||||||
onDismiss: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Full-screen modal that lets the user pick a room to send
|
|
||||||
* an incoming Android share intent into.
|
|
||||||
*/
|
|
||||||
export function ShareRoomPicker({ share, onPick, onDismiss }: ShareRoomPickerProps) {
|
|
||||||
const mx = useMatrixClient();
|
|
||||||
const useAuthentication = useMediaAuthentication();
|
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
|
||||||
const [confirmRoomId, setConfirmRoomId] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const mDirects = useAtomValue(mDirectAtom);
|
|
||||||
const allRoomsSet = useAllJoinedRoomsSet();
|
|
||||||
const getRoom = useGetRoom(allRoomsSet);
|
|
||||||
const rooms = useRooms(mx, allRoomsAtom, mDirects);
|
|
||||||
const directs = useDirects(mx, allRoomsAtom, mDirects);
|
|
||||||
|
|
||||||
const allItems = useMemo(
|
|
||||||
() => [...rooms, ...directs].sort(factoryRoomIdByActivity(mx)),
|
|
||||||
[mx, rooms, directs],
|
|
||||||
);
|
|
||||||
|
|
||||||
const getRoomNameStr: SearchItemStrGetter<string> = useCallback(
|
|
||||||
(rId) => getRoom(rId)?.name ?? rId,
|
|
||||||
[getRoom],
|
|
||||||
);
|
|
||||||
|
|
||||||
const [searchResult, searchRoom, resetSearch] = useAsyncSearch(
|
|
||||||
allItems,
|
|
||||||
getRoomNameStr,
|
|
||||||
SEARCH_OPTS,
|
|
||||||
);
|
|
||||||
|
|
||||||
const items = searchResult ? searchResult.items : allItems;
|
|
||||||
|
|
||||||
const virtualizer = useVirtualizer({
|
|
||||||
count: items.length,
|
|
||||||
getScrollElement: () => scrollRef.current,
|
|
||||||
estimateSize: () => 48,
|
|
||||||
overscan: 8,
|
|
||||||
});
|
|
||||||
const vItems = virtualizer.getVirtualItems();
|
|
||||||
|
|
||||||
const handleSearchChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
|
|
||||||
const value = evt.currentTarget.value.trim();
|
|
||||||
if (!value) {
|
|
||||||
resetSearch();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
searchRoom(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRoomClick: React.MouseEventHandler<HTMLButtonElement> = (evt) => {
|
|
||||||
const roomId = evt.currentTarget.getAttribute('data-room-id');
|
|
||||||
if (roomId) {
|
|
||||||
setConfirmRoomId(roomId);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleConfirm = useCallback(() => {
|
|
||||||
if (confirmRoomId) {
|
|
||||||
onPick(confirmRoomId);
|
|
||||||
}
|
|
||||||
}, [confirmRoomId, onPick]);
|
|
||||||
|
|
||||||
const handleCancelConfirm = useCallback(() => {
|
|
||||||
setConfirmRoomId(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const previewText = share.text?.slice(0, 80) ?? share.subject?.slice(0, 80);
|
|
||||||
const fileCount = share.files.length;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Overlay open>
|
|
||||||
<FocusTrap
|
|
||||||
focusTrapOptions={{
|
|
||||||
initialFocus: false,
|
|
||||||
clickOutsideDeactivates: true,
|
|
||||||
onDeactivate: onDismiss,
|
|
||||||
escapeDeactivates: stopPropagation,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
grow="Yes"
|
|
||||||
direction="Column"
|
|
||||||
style={{
|
|
||||||
position: 'fixed',
|
|
||||||
inset: 0,
|
|
||||||
zIndex: 999,
|
|
||||||
backgroundColor: '#1a1d23',
|
|
||||||
paddingTop: '60px',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Header size="500" style={{ padding: config.space.S400 }}>
|
|
||||||
<Box grow="Yes" direction="Column" gap="100" style={{ minWidth: 0, maxWidth: '80%' }}>
|
|
||||||
<Text size="H4">Share to Room</Text>
|
|
||||||
{(previewText || fileCount > 0) && (
|
|
||||||
<Text
|
|
||||||
size="T200"
|
|
||||||
priority="300"
|
|
||||||
style={{ opacity: 0.7, wordBreak: 'break-word', whiteSpace: 'normal' }}
|
|
||||||
>
|
|
||||||
{previewText
|
|
||||||
? `"${previewText}${(share.text?.length ?? 0) > 80 ? '…' : ''}"`
|
|
||||||
: `${fileCount} file${fileCount !== 1 ? 's' : ''}`}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
<Box shrink="No">
|
|
||||||
<IconButton size="300" radii="300" onClick={onDismiss}>
|
|
||||||
<Icon src={Icons.Cross} />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
</Header>
|
|
||||||
|
|
||||||
<Box
|
|
||||||
style={{
|
|
||||||
padding: config.space.S200,
|
|
||||||
paddingTop: config.space.S300,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
onChange={handleSearchChange}
|
|
||||||
before={<Icon size="200" src={Icons.Search} />}
|
|
||||||
placeholder="Search rooms…"
|
|
||||||
size="400"
|
|
||||||
variant="Background"
|
|
||||||
outlined
|
|
||||||
autoFocus
|
|
||||||
style={{ width: '100%' }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Scroll ref={scrollRef} size="300" hideTrack style={{ flex: 1, minHeight: 0 }}>
|
|
||||||
<Box style={{ padding: config.space.S300 }} direction="Column">
|
|
||||||
{vItems.length === 0 && (
|
|
||||||
<Box
|
|
||||||
style={{ padding: `${config.space.S700} 0` }}
|
|
||||||
alignItems="Center"
|
|
||||||
justifyContent="Center"
|
|
||||||
direction="Column"
|
|
||||||
gap="100"
|
|
||||||
>
|
|
||||||
<Text size="H6" align="Center">
|
|
||||||
{searchResult ? 'No Match Found' : 'No Rooms'}
|
|
||||||
</Text>
|
|
||||||
<Text size="T200" align="Center" priority="300">
|
|
||||||
{searchResult
|
|
||||||
? `No rooms found for "${searchResult.query}".`
|
|
||||||
: 'You have no rooms to share into.'}
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
<Box style={{ position: 'relative', height: virtualizer.getTotalSize() }}>
|
|
||||||
{vItems.map((vItem) => {
|
|
||||||
const roomId = items[vItem.index];
|
|
||||||
const room = getRoom(roomId);
|
|
||||||
if (!room) return null;
|
|
||||||
const isDm = mDirects.has(roomId);
|
|
||||||
|
|
||||||
const avatarSrc = isDm
|
|
||||||
? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication)
|
|
||||||
: getRoomAvatarUrl(mx, room, 96, useAuthentication);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<VirtualTile
|
|
||||||
virtualItem={vItem}
|
|
||||||
style={{ paddingBottom: config.space.S100 }}
|
|
||||||
ref={virtualizer.measureElement}
|
|
||||||
key={roomId}
|
|
||||||
>
|
|
||||||
<MenuItem
|
|
||||||
data-room-id={roomId}
|
|
||||||
onClick={handleRoomClick}
|
|
||||||
variant="Surface"
|
|
||||||
size="400"
|
|
||||||
radii="400"
|
|
||||||
before={
|
|
||||||
<Avatar size="300" radii={isDm ? '400' : '300'}>
|
|
||||||
{avatarSrc ? (
|
|
||||||
<RoomAvatar
|
|
||||||
roomId={roomId}
|
|
||||||
src={avatarSrc}
|
|
||||||
alt={room.name}
|
|
||||||
renderFallback={() => (
|
|
||||||
<Text as="span" size="H6">
|
|
||||||
{nameInitials(room.name)}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<RoomIcon room={room} size="200" filled />
|
|
||||||
)}
|
|
||||||
</Avatar>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Box grow="Yes" direction="Column">
|
|
||||||
<Text size="B400" truncate>
|
|
||||||
{room.name}
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
</MenuItem>
|
|
||||||
</VirtualTile>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Scroll>
|
|
||||||
</Box>
|
|
||||||
</FocusTrap>
|
|
||||||
</Overlay>
|
|
||||||
|
|
||||||
{confirmRoomId &&
|
|
||||||
(() => {
|
|
||||||
const room = getRoom(confirmRoomId);
|
|
||||||
const roomName = room?.name ?? confirmRoomId;
|
|
||||||
const isDm = mDirects.has(confirmRoomId);
|
|
||||||
return (
|
|
||||||
<Overlay open backdrop={<OverlayBackdrop />}>
|
|
||||||
<OverlayCenter>
|
|
||||||
<FocusTrap
|
|
||||||
focusTrapOptions={{
|
|
||||||
initialFocus: false,
|
|
||||||
onDeactivate: handleCancelConfirm,
|
|
||||||
escapeDeactivates: stopPropagation,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Modal style={{ maxWidth: '280px' }}>
|
|
||||||
<Box direction="Column" gap="100" style={{ padding: config.space.S300 }}>
|
|
||||||
<Box direction="Column" gap="100">
|
|
||||||
<Text size="H4">Share to {isDm ? 'Person' : 'Room'}?</Text>
|
|
||||||
<Text size="T300" priority="300">
|
|
||||||
Send to <strong>{roomName}</strong>?
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
<Box gap="200" justifyContent="End">
|
|
||||||
<Button onClick={handleCancelConfirm} variant="Secondary" size="400">
|
|
||||||
<Text size="B400">Cancel</Text>
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleConfirm} variant="Primary" size="400">
|
|
||||||
<Text size="B400">Share</Text>
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Modal>
|
|
||||||
</FocusTrap>
|
|
||||||
</OverlayCenter>
|
|
||||||
</Overlay>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useCallback, useEffect, useState } from 'react';
|
import React, { useCallback } from 'react';
|
||||||
import { Box, Text, Switch, Button, color, Spinner } from 'folds';
|
import { Box, Text, Switch, Button, color, Spinner } from 'folds';
|
||||||
import { IPusherRequest } from 'matrix-js-sdk';
|
import { IPusherRequest } from 'matrix-js-sdk';
|
||||||
import { SequenceCard } from '../../../components/sequence-card';
|
import { SequenceCard } from '../../../components/sequence-card';
|
||||||
@@ -11,12 +11,6 @@ import { useEmailNotifications } from '../../../hooks/useEmailNotifications';
|
|||||||
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
|
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
|
||||||
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
import { isCapacitorNative, requestSystemNotificationPermission } from '../../../utils/tauri';
|
import { isCapacitorNative, requestSystemNotificationPermission } from '../../../utils/tauri';
|
||||||
import {
|
|
||||||
isBackgroundSyncSupported,
|
|
||||||
getBackgroundSyncStatus,
|
|
||||||
requestResetPushRegistration,
|
|
||||||
triggerBackgroundSyncPing,
|
|
||||||
} from '../../../utils/backgroundSync';
|
|
||||||
|
|
||||||
function EmailNotification() {
|
function EmailNotification() {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
@@ -91,193 +85,6 @@ function EmailNotification() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type PushStatus = {
|
|
||||||
registered: boolean;
|
|
||||||
distributor: string;
|
|
||||||
endpoint: string;
|
|
||||||
distributors: string[];
|
|
||||||
lastFailure: string;
|
|
||||||
autoStartBlocked: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Android-only section showing UnifiedPush registration status and controls. */
|
|
||||||
function AndroidPushNotifications() {
|
|
||||||
const [status, setStatus] = useState<PushStatus | undefined>(undefined);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [lastError, setLastError] = useState<string | undefined>(undefined);
|
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
|
||||||
setLoading(true);
|
|
||||||
const s = await getBackgroundSyncStatus();
|
|
||||||
let distributors: string[] = [];
|
|
||||||
if (Array.isArray(s?.distributors)) {
|
|
||||||
distributors = s.distributors;
|
|
||||||
} else if (typeof s?.distributors === 'string' && s.distributors && s.distributors !== '[]') {
|
|
||||||
distributors = [s.distributors];
|
|
||||||
}
|
|
||||||
setStatus(
|
|
||||||
s
|
|
||||||
? {
|
|
||||||
registered: s.registered,
|
|
||||||
distributor: s.distributor || '',
|
|
||||||
endpoint: s.endpoint || '',
|
|
||||||
distributors,
|
|
||||||
lastFailure: s.lastFailure || '',
|
|
||||||
autoStartBlocked: Boolean(s.autoStartBlocked),
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
);
|
|
||||||
setLoading(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
refresh();
|
|
||||||
}, [refresh]);
|
|
||||||
|
|
||||||
const [resetState, reset] = useAsyncCallback(
|
|
||||||
useCallback(async () => {
|
|
||||||
setLastError(undefined);
|
|
||||||
const result = await requestResetPushRegistration();
|
|
||||||
await refresh();
|
|
||||||
if (!result.success) {
|
|
||||||
setLastError(
|
|
||||||
'Selected distributor but did not get a push endpoint. In ntfy: enable UnifiedPush, allow unrestricted battery, then try Reset again.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, [refresh]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const [pingState, ping] = useAsyncCallback(
|
|
||||||
useCallback(async () => {
|
|
||||||
await triggerBackgroundSyncPing('manual-test');
|
|
||||||
}, []),
|
|
||||||
);
|
|
||||||
|
|
||||||
const isBusy =
|
|
||||||
loading ||
|
|
||||||
resetState.status === AsyncStatus.Loading ||
|
|
||||||
pingState.status === AsyncStatus.Loading;
|
|
||||||
|
|
||||||
const statusDescription = (() => {
|
|
||||||
if (loading) return 'Loading status…';
|
|
||||||
if (status === undefined) {
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
|
||||||
Failed to read push status.
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status.registered) {
|
|
||||||
return (
|
|
||||||
<Text as="span" size="T200">
|
|
||||||
{`Distributor: ${status.distributor || 'unknown'}`}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status.lastFailure === 'AUTO_START_BLOCKED' || status.autoStartBlocked) {
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
|
||||||
Phone is blocking auto-start for Paarrot. Open App Boot / Auto-start settings, allow
|
|
||||||
Paarrot (and ntfy), then tap Reset.
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status.lastFailure) {
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
|
||||||
{`Registration failed (${status.lastFailure}). Tap Reset and pick ntfy again.`}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (status.distributors.length === 0) {
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
|
||||||
No UnifiedPush distributor found. Install ntfy from Play Store/F-Droid and enable
|
|
||||||
UnifiedPush in ntfy settings.
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<Text as="span" style={{ color: color.Warning?.Main ?? color.Critical.Main }} size="T200">
|
|
||||||
{`Found ${status.distributors.join(', ')} but not registered yet. Tap Reset and pick ntfy.`}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
})();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box direction="Column" gap="100">
|
|
||||||
<Text size="L400">Android Push (UnifiedPush)</Text>
|
|
||||||
<SequenceCard
|
|
||||||
className={SequenceCardStyle}
|
|
||||||
variant="SurfaceVariant"
|
|
||||||
direction="Column"
|
|
||||||
gap="400"
|
|
||||||
>
|
|
||||||
<SettingTile
|
|
||||||
title="Background Notifications"
|
|
||||||
description={
|
|
||||||
<>
|
|
||||||
{statusDescription}
|
|
||||||
{lastError ? (
|
|
||||||
<Text
|
|
||||||
as="span"
|
|
||||||
style={{ color: color.Critical.Main, display: 'block' }}
|
|
||||||
size="T200"
|
|
||||||
>
|
|
||||||
{lastError}
|
|
||||||
</Text>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
after={loading ? <Spinner variant="Secondary" /> : undefined}
|
|
||||||
/>
|
|
||||||
<SettingTile
|
|
||||||
title="Change Distributor"
|
|
||||||
description="Shows a list of installed UnifiedPush apps (ntfy, etc.) and registers the one you pick."
|
|
||||||
after={
|
|
||||||
<Button
|
|
||||||
size="300"
|
|
||||||
radii="300"
|
|
||||||
variant="Secondary"
|
|
||||||
disabled={isBusy}
|
|
||||||
onClick={() => {
|
|
||||||
reset();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{resetState.status === AsyncStatus.Loading ? (
|
|
||||||
<Spinner variant="Secondary" size="200" />
|
|
||||||
) : (
|
|
||||||
<Text size="B300">Reset</Text>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<SettingTile
|
|
||||||
title="Test Notification"
|
|
||||||
description="Trigger a test push ping to verify the pipeline works."
|
|
||||||
after={
|
|
||||||
<Button
|
|
||||||
size="300"
|
|
||||||
radii="300"
|
|
||||||
variant="Secondary"
|
|
||||||
disabled={isBusy}
|
|
||||||
onClick={() => {
|
|
||||||
ping();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{pingState.status === AsyncStatus.Loading ? (
|
|
||||||
<Spinner variant="Secondary" size="200" />
|
|
||||||
) : (
|
|
||||||
<Text size="B300">Send Test</Text>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</SequenceCard>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SystemNotification() {
|
export function SystemNotification() {
|
||||||
const notifPermission = usePermissionState('notifications', getNotificationState());
|
const notifPermission = usePermissionState('notifications', getNotificationState());
|
||||||
const capacitorNative = isCapacitorNative();
|
const capacitorNative = isCapacitorNative();
|
||||||
@@ -340,7 +147,6 @@ export function SystemNotification() {
|
|||||||
after={<Switch value={isNotificationSounds} onChange={setIsNotificationSounds} />}
|
after={<Switch value={isNotificationSounds} onChange={setIsNotificationSounds} />}
|
||||||
/>
|
/>
|
||||||
</SequenceCard>
|
</SequenceCard>
|
||||||
{isBackgroundSyncSupported() && <AndroidPushNotifications />}
|
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
|
||||||
import { useAtomValue } from 'jotai';
|
import { useAtomValue } from 'jotai';
|
||||||
import React, { ReactNode, useCallback, useEffect, useRef, useState, Fragment } from 'react';
|
import React, { ReactNode, useCallback, useEffect, useRef, Fragment } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
|
import { RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
|
||||||
import { roomToUnreadAtom, unreadEqual, unreadInfoToUnread } from '../../state/room/roomToUnread';
|
import { roomToUnreadAtom, unreadEqual, unreadInfoToUnread } from '../../state/room/roomToUnread';
|
||||||
@@ -28,18 +27,12 @@ import {
|
|||||||
guessPerfectParent,
|
guessPerfectParent,
|
||||||
} from '../../utils/room';
|
} from '../../utils/room';
|
||||||
import { NotificationType, UnreadInfo } from '../../../types/matrix/room';
|
import { NotificationType, UnreadInfo } from '../../../types/matrix/room';
|
||||||
import {
|
import { getMxIdLocalPart, mxcUrlToHttp, getCanonicalAliasOrRoomId } from '../../utils/matrix';
|
||||||
getMxIdLocalPart,
|
|
||||||
mxcUrlToHttp,
|
|
||||||
getCanonicalAliasOrRoomId,
|
|
||||||
encryptFile,
|
|
||||||
} from '../../utils/matrix';
|
|
||||||
import { mDirectAtom } from '../../state/mDirectList';
|
import { mDirectAtom } from '../../state/mDirectList';
|
||||||
import { roomToParentsAtom } from '../../state/room/roomToParents';
|
import { roomToParentsAtom } from '../../state/room/roomToParents';
|
||||||
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
|
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
|
||||||
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
|
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
|
||||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
import { ShareRoomPicker } from '../../features/ShareRoomPicker';
|
|
||||||
import {
|
import {
|
||||||
isTauri,
|
isTauri,
|
||||||
isElectron,
|
isElectron,
|
||||||
@@ -48,19 +41,6 @@ import {
|
|||||||
setupNotificationTapListener,
|
setupNotificationTapListener,
|
||||||
} from '../../utils/tauri';
|
} from '../../utils/tauri';
|
||||||
import { setPaarrotNavigate, initPaarrotAPI } from '../../paarrot-api';
|
import { setPaarrotNavigate, initPaarrotAPI } from '../../paarrot-api';
|
||||||
import {
|
|
||||||
startBackgroundSync,
|
|
||||||
stopBackgroundSync,
|
|
||||||
setAppForegroundState,
|
|
||||||
} from '../../utils/backgroundSync';
|
|
||||||
import {
|
|
||||||
AndroidSharePayload,
|
|
||||||
clearPendingAndroidShare,
|
|
||||||
getPendingAndroidShare,
|
|
||||||
isAndroidShareSupported,
|
|
||||||
listenForAndroidShares,
|
|
||||||
materializeSharedFile,
|
|
||||||
} from '../../utils/androidShare';
|
|
||||||
import { UpdatesDialogHost } from '../../components/updates-dialog';
|
import { UpdatesDialogHost } from '../../components/updates-dialog';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -454,34 +434,6 @@ function MessageNotifications() {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Configures native Android push-ping background sync on login, keeps it
|
|
||||||
* informed of foreground state so it doesn't double-fire notifications,
|
|
||||||
* and clears it cleanly on unmount (logout).
|
|
||||||
* Only active on Android Capacitor builds.
|
|
||||||
*/
|
|
||||||
function BackgroundSyncSetup() {
|
|
||||||
const mx = useMatrixClient();
|
|
||||||
// Try to make a simple fetch to verify component is rendering
|
|
||||||
fetch('/_matrix/client/v3/sync', { method: 'HEAD' }).catch(() => {});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
console.log('BackgroundSyncSetup: Starting background sync for', mx.getUserId());
|
|
||||||
startBackgroundSync(mx);
|
|
||||||
|
|
||||||
const onVisibility = () => setAppForegroundState(!document.hidden);
|
|
||||||
document.addEventListener('visibilitychange', onVisibility);
|
|
||||||
setAppForegroundState(!document.hidden);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
document.removeEventListener('visibilitychange', onVisibility);
|
|
||||||
stopBackgroundSync();
|
|
||||||
};
|
|
||||||
}, [mx]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes the Paarrot API for Electron integration
|
* Initializes the Paarrot API for Electron integration
|
||||||
* Registers the navigate function and sets up IPC handlers
|
* Registers the navigate function and sets up IPC handlers
|
||||||
@@ -533,162 +485,6 @@ function TaskbarFlashStopper() {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function AndroidShareIntentHandler() {
|
|
||||||
const mx = useMatrixClient();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const [pendingShare, setPendingShare] = useState<AndroidSharePayload | null>(null);
|
|
||||||
const mDirects = useAtomValue(mDirectAtom);
|
|
||||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
|
||||||
|
|
||||||
const applyPendingShare = useCallback(
|
|
||||||
async (share: AndroidSharePayload, roomId: string) => {
|
|
||||||
const room = mx.getRoom(roomId);
|
|
||||||
if (!room) return false;
|
|
||||||
|
|
||||||
// Send text message if present
|
|
||||||
const nextParts = [share.subject?.trim(), share.text?.trim()].filter(
|
|
||||||
(value): value is string => !!value,
|
|
||||||
);
|
|
||||||
if (nextParts.length > 0) {
|
|
||||||
const textContent = {
|
|
||||||
msgtype: 'm.text' as const,
|
|
||||||
body: nextParts.join('\n'),
|
|
||||||
};
|
|
||||||
await mx.sendMessage(roomId, textContent);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload and send files if present
|
|
||||||
if (share.files.length > 0) {
|
|
||||||
for (let i = 0; i < share.files.length; i += 1) {
|
|
||||||
const sharedFile = share.files[i];
|
|
||||||
const originalFile = await materializeSharedFile(sharedFile, share.receivedAt);
|
|
||||||
|
|
||||||
let fileToUpload = originalFile;
|
|
||||||
let encInfo: EncryptedAttachmentInfo | undefined;
|
|
||||||
|
|
||||||
if (room.hasEncryptionStateEvent()) {
|
|
||||||
const encrypted = await encryptFile(originalFile);
|
|
||||||
fileToUpload = encrypted.file;
|
|
||||||
encInfo = encrypted.encInfo;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upload file
|
|
||||||
const uploadResult = await mx.uploadContent(fileToUpload);
|
|
||||||
const mxc = uploadResult?.content_uri;
|
|
||||||
if (mxc) {
|
|
||||||
// Determine message type and send
|
|
||||||
const fileType = originalFile.type;
|
|
||||||
let msgtype = 'm.file' as const;
|
|
||||||
if (fileType.startsWith('image/')) msgtype = 'm.image' as const;
|
|
||||||
else if (fileType.startsWith('video/')) msgtype = 'm.video' as const;
|
|
||||||
else if (fileType.startsWith('audio/')) msgtype = 'm.audio' as const;
|
|
||||||
|
|
||||||
const fileContent: any = {
|
|
||||||
msgtype,
|
|
||||||
body: originalFile.name,
|
|
||||||
filename: originalFile.name,
|
|
||||||
info: {
|
|
||||||
mimetype: originalFile.type,
|
|
||||||
size: originalFile.size,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
if (encInfo) {
|
|
||||||
fileContent.file = {
|
|
||||||
...encInfo,
|
|
||||||
url: mxc,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
fileContent.url = mxc;
|
|
||||||
}
|
|
||||||
|
|
||||||
await mx.sendMessage(roomId, fileContent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await clearPendingAndroidShare();
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
[mx],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handlePickRoom = useCallback(
|
|
||||||
(roomId: string) => {
|
|
||||||
if (!pendingShare) return;
|
|
||||||
|
|
||||||
applyPendingShare(pendingShare, roomId)
|
|
||||||
.then((applied) => {
|
|
||||||
if (applied) {
|
|
||||||
setPendingShare(null);
|
|
||||||
|
|
||||||
// Navigate to the selected room
|
|
||||||
const isDirect = mDirects.has(roomId);
|
|
||||||
if (isDirect) {
|
|
||||||
navigate(getDirectRoomPath(roomId));
|
|
||||||
} else {
|
|
||||||
const parents = roomToParents.get(roomId);
|
|
||||||
const parent = parents && parents.length > 0 ? parents[0] : undefined;
|
|
||||||
if (parent) {
|
|
||||||
navigate(getSpaceRoomPath(parent, roomId));
|
|
||||||
} else {
|
|
||||||
navigate(getHomeRoomPath(roomId));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error('[AndroidShare] Failed to apply share after pick:', err);
|
|
||||||
setPendingShare(null);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
[applyPendingShare, pendingShare, navigate, mDirects, roomToParents],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleDismiss = useCallback(() => {
|
|
||||||
clearPendingAndroidShare().catch(() => {});
|
|
||||||
setPendingShare(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isAndroidShareSupported()) return undefined;
|
|
||||||
|
|
||||||
let mounted = true;
|
|
||||||
let listenerHandle: { remove: () => Promise<void> } | undefined;
|
|
||||||
|
|
||||||
getPendingAndroidShare()
|
|
||||||
.then((share) => {
|
|
||||||
if (mounted && share) {
|
|
||||||
setPendingShare(share);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error('[AndroidShare] Failed to get pending share:', err);
|
|
||||||
});
|
|
||||||
|
|
||||||
listenForAndroidShares((share) => {
|
|
||||||
if (mounted) {
|
|
||||||
setPendingShare(share);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.then((handle) => {
|
|
||||||
listenerHandle = handle;
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error('[AndroidShare] Failed to listen for shares:', err);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
mounted = false;
|
|
||||||
listenerHandle?.remove();
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (!pendingShare) return null;
|
|
||||||
|
|
||||||
return <ShareRoomPicker share={pendingShare} onPick={handlePickRoom} onDismiss={handleDismiss} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
type ClientNonUIFeaturesProps = {
|
type ClientNonUIFeaturesProps = {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
};
|
};
|
||||||
@@ -701,10 +497,8 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
|
|||||||
<FaviconUpdater />
|
<FaviconUpdater />
|
||||||
<InviteNotifications />
|
<InviteNotifications />
|
||||||
<MessageNotifications />
|
<MessageNotifications />
|
||||||
<BackgroundSyncSetup />
|
|
||||||
<PaarrotAPIInitializer />
|
<PaarrotAPIInitializer />
|
||||||
<TaskbarFlashStopper />
|
<TaskbarFlashStopper />
|
||||||
<AndroidShareIntentHandler />
|
|
||||||
{children}
|
{children}
|
||||||
<UpdatesDialogHost />
|
<UpdatesDialogHost />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
import type { PluginListenerHandle } from '@capacitor/core';
|
|
||||||
|
|
||||||
const CAPACITOR_CORE_MODULE_ID = '@capacitor/core';
|
|
||||||
|
|
||||||
type CapacitorCoreModule = typeof import('@capacitor/core');
|
|
||||||
|
|
||||||
const loadCapacitorCore = async (): Promise<CapacitorCoreModule> =>
|
|
||||||
import(/* @vite-ignore */ CAPACITOR_CORE_MODULE_ID);
|
|
||||||
|
|
||||||
/** Metadata for a file received from an Android share intent. */
|
|
||||||
export type AndroidSharedFile = {
|
|
||||||
path: string;
|
|
||||||
name: string;
|
|
||||||
mimeType: string;
|
|
||||||
size: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Payload persisted by the native Android share handler. */
|
|
||||||
export type AndroidSharePayload = {
|
|
||||||
text?: string;
|
|
||||||
subject?: string;
|
|
||||||
files: AndroidSharedFile[];
|
|
||||||
receivedAt: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
interface AndroidShareHandlerPlugin {
|
|
||||||
/** Returns the last pending share payload, if one exists. */
|
|
||||||
getPendingShare(): Promise<{ share: AndroidSharePayload | null }>;
|
|
||||||
/** Clears the last pending share payload after it has been consumed. */
|
|
||||||
clearPendingShare(): Promise<void>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'shareReceived',
|
|
||||||
listenerFunc: (payload: AndroidSharePayload) => void,
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const getAndroidShareHandler = async (): Promise<AndroidShareHandlerPlugin> => {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
return registerPlugin<AndroidShareHandlerPlugin>('AndroidShareHandler');
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Returns true when the Android share bridge is available. */
|
|
||||||
export const isAndroidShareSupported = (): boolean => {
|
|
||||||
const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] })
|
|
||||||
.Capacitor;
|
|
||||||
return Boolean(capacitor?.isNativePlatform?.() && capacitor.getPlatform() === 'android');
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Fetches the current pending native share payload. */
|
|
||||||
export const getPendingAndroidShare = async (): Promise<AndroidSharePayload | null> => {
|
|
||||||
if (!isAndroidShareSupported()) return null;
|
|
||||||
const AndroidShareHandler = await getAndroidShareHandler();
|
|
||||||
const result = await AndroidShareHandler.getPendingShare();
|
|
||||||
return result.share;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Clears the native pending share payload. */
|
|
||||||
export const clearPendingAndroidShare = async (): Promise<void> => {
|
|
||||||
if (!isAndroidShareSupported()) return;
|
|
||||||
const AndroidShareHandler = await getAndroidShareHandler();
|
|
||||||
await AndroidShareHandler.clearPendingShare();
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Subscribes to new incoming native share payloads. */
|
|
||||||
export const listenForAndroidShares = async (
|
|
||||||
listener: (payload: AndroidSharePayload) => void,
|
|
||||||
): Promise<PluginListenerHandle | undefined> => {
|
|
||||||
if (!isAndroidShareSupported()) return undefined;
|
|
||||||
const AndroidShareHandler = await getAndroidShareHandler();
|
|
||||||
return AndroidShareHandler.addListener('shareReceived', listener);
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Converts a cached native shared file into a browser File for upload. */
|
|
||||||
export const materializeSharedFile = async (
|
|
||||||
sharedFile: AndroidSharedFile,
|
|
||||||
receivedAt: number,
|
|
||||||
): Promise<File> => {
|
|
||||||
const { Capacitor } = await loadCapacitorCore();
|
|
||||||
const fileUrl = Capacitor.convertFileSrc(sharedFile.path);
|
|
||||||
const response = await fetch(fileUrl);
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to read shared file: ${sharedFile.name}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const blob = await response.blob();
|
|
||||||
return new File([blob], sharedFile.name, {
|
|
||||||
type: sharedFile.mimeType || blob.type,
|
|
||||||
lastModified: receivedAt,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -1,605 +0,0 @@
|
|||||||
import type { PluginListenerHandle } from '@capacitor/core';
|
|
||||||
import type { IPusherRequest, MatrixClient } from 'matrix-js-sdk';
|
|
||||||
import { promptDialog } from '../state/dialog';
|
|
||||||
|
|
||||||
const CAPACITOR_CORE_MODULE_ID = '@capacitor/core';
|
|
||||||
|
|
||||||
type CapacitorCoreModule = typeof import('@capacitor/core');
|
|
||||||
|
|
||||||
const loadCapacitorCore = async (): Promise<CapacitorCoreModule> =>
|
|
||||||
import(/* @vite-ignore */ CAPACITOR_CORE_MODULE_ID);
|
|
||||||
|
|
||||||
type UnifiedPushStatus = {
|
|
||||||
running: boolean;
|
|
||||||
endpoint: string;
|
|
||||||
instance: string;
|
|
||||||
registered: boolean;
|
|
||||||
distributor: string;
|
|
||||||
distributors: string[] | string;
|
|
||||||
lastFailure?: string;
|
|
||||||
/** OEM App Boot / AUTO_START is blocking distributor broadcasts (e.g. TCL). */
|
|
||||||
autoStartBlocked?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UnifiedPushEndpointEvent = {
|
|
||||||
endpoint: string;
|
|
||||||
previousEndpoint: string;
|
|
||||||
instance: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UnifiedPushUnregisteredEvent = {
|
|
||||||
previousEndpoint: string;
|
|
||||||
instance: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UnifiedPushRegistrationFailedEvent = {
|
|
||||||
reason: string;
|
|
||||||
instance: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
interface MatrixBackgroundSyncPlugin {
|
|
||||||
/** Persist credentials and request UnifiedPush registration. */
|
|
||||||
start(options: {
|
|
||||||
homeserverUrl: string;
|
|
||||||
accessToken: string;
|
|
||||||
userId: string;
|
|
||||||
deviceId: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
/** Trigger a one-shot fetch as if a push ping arrived. */
|
|
||||||
triggerPing(options: { reason?: string }): Promise<void>;
|
|
||||||
/** Re-open distributor setup flow and retry registration. */
|
|
||||||
requestDistributorSetup(): Promise<{ success: boolean }>;
|
|
||||||
/** Stop any in-flight fetch, clear credentials, and unregister UnifiedPush. */
|
|
||||||
stop(): Promise<void>;
|
|
||||||
/**
|
|
||||||
* Notify the service whether the app UI is visible.
|
|
||||||
* When foreground is true, the service suppresses native notifications
|
|
||||||
* because the JS layer handles them via LocalNotifications.
|
|
||||||
*/
|
|
||||||
setAppForeground(options: { foreground: boolean }): Promise<void>;
|
|
||||||
/** Returns fetch state and current UnifiedPush registration details. */
|
|
||||||
getStatus(): Promise<UnifiedPushStatus>;
|
|
||||||
/** Native Matrix gateway discovery for a UnifiedPush endpoint (avoids WebView CORS). */
|
|
||||||
resolveUnifiedPushGateway(options: { endpoint: string }): Promise<{ gatewayUrl: string }>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'unifiedPushNewEndpoint',
|
|
||||||
listenerFunc: (event: UnifiedPushEndpointEvent) => void,
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'unifiedPushUnregistered',
|
|
||||||
listenerFunc: (event: UnifiedPushUnregisteredEvent) => void,
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
addListener(
|
|
||||||
eventName: 'unifiedPushRegistrationFailed',
|
|
||||||
listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void,
|
|
||||||
): Promise<PluginListenerHandle>;
|
|
||||||
}
|
|
||||||
|
|
||||||
type StoredPusherState = {
|
|
||||||
endpoint: string;
|
|
||||||
appId: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULT_UNIFIED_PUSH_GATEWAY =
|
|
||||||
'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
|
|
||||||
const PUSHER_APP_ID_BASE = 'com.paarrot.app.android';
|
|
||||||
const PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush';
|
|
||||||
|
|
||||||
/** Returns true when the current platform is Android Capacitor. */
|
|
||||||
export const isBackgroundSyncSupported = (): boolean => {
|
|
||||||
const capacitor = (window as typeof window & { Capacitor?: CapacitorCoreModule['Capacitor'] })
|
|
||||||
.Capacitor;
|
|
||||||
return Boolean(capacitor?.isNativePlatform?.() && capacitor.getPlatform() === 'android');
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStoredPusherKey = (userId: string | null, deviceId: string | null): string =>
|
|
||||||
`${PUSHER_STORAGE_PREFIX}:${userId ?? 'unknown'}:${deviceId ?? 'unknown'}`;
|
|
||||||
|
|
||||||
const buildPusherAppId = (deviceId: string | null): string => {
|
|
||||||
const raw = deviceId ? `${PUSHER_APP_ID_BASE}.${deviceId}` : PUSHER_APP_ID_BASE;
|
|
||||||
return raw.length > 64 ? raw.slice(0, 64) : raw;
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadStoredPusherState = (
|
|
||||||
userId: string | null,
|
|
||||||
deviceId: string | null,
|
|
||||||
): StoredPusherState | undefined => {
|
|
||||||
if (typeof window === 'undefined' || !window.localStorage) return undefined;
|
|
||||||
|
|
||||||
const raw = window.localStorage.getItem(getStoredPusherKey(userId, deviceId));
|
|
||||||
if (!raw) return undefined;
|
|
||||||
|
|
||||||
try {
|
|
||||||
return JSON.parse(raw) as StoredPusherState;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const saveStoredPusherState = (
|
|
||||||
userId: string | null,
|
|
||||||
deviceId: string | null,
|
|
||||||
state: StoredPusherState,
|
|
||||||
): void => {
|
|
||||||
if (typeof window === 'undefined' || !window.localStorage) return;
|
|
||||||
window.localStorage.setItem(getStoredPusherKey(userId, deviceId), JSON.stringify(state));
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearStoredPusherState = (userId: string | null, deviceId: string | null): void => {
|
|
||||||
if (typeof window === 'undefined' || !window.localStorage) return;
|
|
||||||
window.localStorage.removeItem(getStoredPusherKey(userId, deviceId));
|
|
||||||
};
|
|
||||||
|
|
||||||
const normalizeDistributors = (raw: UnifiedPushStatus['distributors']): string[] => {
|
|
||||||
if (Array.isArray(raw)) return raw;
|
|
||||||
if (typeof raw !== 'string') return [];
|
|
||||||
|
|
||||||
const trimmed = raw.trim();
|
|
||||||
if (!trimmed || trimmed === '[]') return [];
|
|
||||||
|
|
||||||
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
|
|
||||||
return trimmed
|
|
||||||
.slice(1, -1)
|
|
||||||
.split(',')
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
|
||||||
|
|
||||||
return [trimmed];
|
|
||||||
};
|
|
||||||
|
|
||||||
const resolveUnifiedPushGateway = async (endpoint: string): Promise<string> => {
|
|
||||||
// Prefer native HTTP — ntfy/Matrix gateway responses omit CORS headers, so
|
|
||||||
// WebView fetch fails with TypeError: Failed to fetch and wrongly falls back.
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
const result = await MatrixBackgroundSync.resolveUnifiedPushGateway({ endpoint });
|
|
||||||
if (result?.gatewayUrl) return result.gatewayUrl;
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] Native UnifiedPush gateway discovery failed:', err);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const discoveryUrl = new URL(endpoint);
|
|
||||||
discoveryUrl.pathname = '/_matrix/push/v1/notify';
|
|
||||||
discoveryUrl.search = '';
|
|
||||||
|
|
||||||
const response = await fetch(discoveryUrl.toString(), { method: 'GET' });
|
|
||||||
if (!response.ok) return DEFAULT_UNIFIED_PUSH_GATEWAY;
|
|
||||||
|
|
||||||
const body = (await response.json()) as {
|
|
||||||
gateway?: string;
|
|
||||||
unifiedpush?: { gateway?: string };
|
|
||||||
};
|
|
||||||
|
|
||||||
if (body.gateway === 'matrix' || body.unifiedpush?.gateway === 'matrix') {
|
|
||||||
return discoveryUrl.toString();
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] UnifiedPush gateway discovery failed:', err);
|
|
||||||
}
|
|
||||||
|
|
||||||
return DEFAULT_UNIFIED_PUSH_GATEWAY;
|
|
||||||
};
|
|
||||||
|
|
||||||
class AndroidUnifiedPushManager {
|
|
||||||
private client: MatrixClient | undefined;
|
|
||||||
|
|
||||||
private listenerHandles: PluginListenerHandle[] = [];
|
|
||||||
|
|
||||||
private listenersReady = false;
|
|
||||||
|
|
||||||
private distributorSetupAttempted = false;
|
|
||||||
|
|
||||||
private distributorPromptShown = false;
|
|
||||||
|
|
||||||
/** Start native UnifiedPush registration and synchronize the Matrix pusher. */
|
|
||||||
async start(mx: MatrixClient): Promise<void> {
|
|
||||||
const { Capacitor, registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
'[BackgroundSync] start() called, platform:',
|
|
||||||
Capacitor.getPlatform(),
|
|
||||||
'isNative:',
|
|
||||||
Capacitor.isNativePlatform(),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!isBackgroundSyncSupported()) {
|
|
||||||
console.log('[BackgroundSync] Background sync not supported on this platform');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const homeserverUrl = mx.getHomeserverUrl();
|
|
||||||
const accessToken = mx.getAccessToken();
|
|
||||||
const userId = mx.getUserId();
|
|
||||||
const deviceId = mx.getDeviceId();
|
|
||||||
|
|
||||||
console.log('[BackgroundSync] Credentials check:', {
|
|
||||||
userId,
|
|
||||||
deviceId,
|
|
||||||
hasToken: !!accessToken,
|
|
||||||
hasUrl: !!homeserverUrl,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!homeserverUrl || !accessToken || !userId) {
|
|
||||||
console.warn('[BackgroundSync] Missing credentials, not starting');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.client = mx;
|
|
||||||
this.distributorSetupAttempted = false;
|
|
||||||
this.distributorPromptShown = false;
|
|
||||||
await this.ensureListeners();
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log('[BackgroundSync] Calling plugin.start()...');
|
|
||||||
await MatrixBackgroundSync.start({
|
|
||||||
homeserverUrl,
|
|
||||||
accessToken,
|
|
||||||
userId,
|
|
||||||
deviceId: deviceId ?? '',
|
|
||||||
});
|
|
||||||
console.log('[BackgroundSync] plugin.start() completed');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BackgroundSync] plugin.start() failed:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.syncExistingEndpoint();
|
|
||||||
await this.ensureDistributorPromptFromStatus();
|
|
||||||
console.log('[BackgroundSync] UnifiedPush registration requested');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stop native UnifiedPush integration and remove the Matrix pusher for this device. */
|
|
||||||
async stop(): Promise<void> {
|
|
||||||
if (!isBackgroundSyncSupported()) return;
|
|
||||||
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
|
|
||||||
const { client } = this;
|
|
||||||
if (client) {
|
|
||||||
const deviceId = client.getDeviceId();
|
|
||||||
const userId = client.getUserId();
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
const stored = loadStoredPusherState(userId, deviceId);
|
|
||||||
const endpoint = status?.endpoint || stored?.endpoint;
|
|
||||||
const appId = stored?.appId ?? buildPusherAppId(deviceId);
|
|
||||||
|
|
||||||
if (endpoint) {
|
|
||||||
await this.removePusher(client, endpoint, appId);
|
|
||||||
}
|
|
||||||
clearStoredPusherState(userId, deviceId);
|
|
||||||
}
|
|
||||||
|
|
||||||
await MatrixBackgroundSync.stop();
|
|
||||||
await this.disposeListeners();
|
|
||||||
this.client = undefined;
|
|
||||||
console.log('[BackgroundSync] UnifiedPush stopped');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Update the Matrix pusher when a new native endpoint is published. */
|
|
||||||
private async handleNewEndpoint(event: UnifiedPushEndpointEvent): Promise<void> {
|
|
||||||
const { client } = this;
|
|
||||||
if (!client) return;
|
|
||||||
|
|
||||||
if (event.previousEndpoint) {
|
|
||||||
await this.removePusher(client, event.previousEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.upsertPusher(client, event.endpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove the Matrix pusher when UnifiedPush unregisters this instance. */
|
|
||||||
private async handleUnregistered(event: UnifiedPushUnregisteredEvent): Promise<void> {
|
|
||||||
const { client } = this;
|
|
||||||
if (!client) return;
|
|
||||||
|
|
||||||
const stored = loadStoredPusherState(client.getUserId(), client.getDeviceId());
|
|
||||||
const endpoint = event.previousEndpoint || stored?.endpoint;
|
|
||||||
const appId = stored?.appId ?? buildPusherAppId(client.getDeviceId());
|
|
||||||
|
|
||||||
if (endpoint) {
|
|
||||||
await this.removePusher(client, endpoint, appId);
|
|
||||||
}
|
|
||||||
|
|
||||||
clearStoredPusherState(client.getUserId(), client.getDeviceId());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Log native registration failures so the missing distributor path is visible. */
|
|
||||||
private handleRegistrationFailed(event: UnifiedPushRegistrationFailedEvent): void {
|
|
||||||
console.warn('[BackgroundSync] UnifiedPush registration failed:', event.reason);
|
|
||||||
|
|
||||||
if (event.reason !== 'ACTION_REQUIRED' || this.distributorSetupAttempted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.distributorSetupAttempted = true;
|
|
||||||
this.tryRequestDistributorSetup();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Re-opens distributor selection once after ACTION_REQUIRED and logs actionable status. */
|
|
||||||
private async tryRequestDistributorSetup(): Promise<void> {
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync =
|
|
||||||
registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
const setupResult = await MatrixBackgroundSync.requestDistributorSetup();
|
|
||||||
console.warn('[BackgroundSync] requestDistributorSetup result:', setupResult);
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
console.warn('[BackgroundSync] UnifiedPush status after setup attempt:', status);
|
|
||||||
const distributors = normalizeDistributors(status?.distributors ?? []);
|
|
||||||
if (distributors.length === 0) {
|
|
||||||
console.error(
|
|
||||||
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.',
|
|
||||||
);
|
|
||||||
this.showNoDistributorPrompt();
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] requestDistributorSetup failed:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Fallback check so users still get prompted even when ACTION_REQUIRED event is missed. */
|
|
||||||
private async ensureDistributorPromptFromStatus(): Promise<void> {
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
if (!status) return;
|
|
||||||
|
|
||||||
const distributors = normalizeDistributors(status.distributors);
|
|
||||||
if (!status.registered && distributors.length === 0) {
|
|
||||||
console.error(
|
|
||||||
'[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.',
|
|
||||||
);
|
|
||||||
this.showNoDistributorPrompt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Show a one-time actionable prompt when no distributor app is installed. */
|
|
||||||
private showNoDistributorPrompt(): void {
|
|
||||||
if (this.distributorPromptShown) return;
|
|
||||||
this.distributorPromptShown = true;
|
|
||||||
|
|
||||||
const message =
|
|
||||||
'Android background notifications need a UnifiedPush distributor app. Install one (for example ntfy), then reopen Paarrot.';
|
|
||||||
const docsUrl = 'https://unifiedpush.org/users/distributors/';
|
|
||||||
|
|
||||||
if (typeof window === 'undefined') return;
|
|
||||||
|
|
||||||
promptDialog(`${message}\n\nOpen distributor list now?`, true).then((openDocs) => {
|
|
||||||
if (openDocs) {
|
|
||||||
window.open(docsUrl, '_blank', 'noopener,noreferrer');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Install plugin listeners once for the active Matrix client. */
|
|
||||||
private async ensureListeners(): Promise<void> {
|
|
||||||
if (this.listenersReady) return;
|
|
||||||
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
|
|
||||||
this.listenerHandles = [
|
|
||||||
await MatrixBackgroundSync.addListener(
|
|
||||||
'unifiedPushNewEndpoint',
|
|
||||||
(event: UnifiedPushEndpointEvent) => {
|
|
||||||
this.handleNewEndpoint(event).catch((err) => {
|
|
||||||
console.error('[BackgroundSync] handleNewEndpoint failed:', err);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
),
|
|
||||||
await MatrixBackgroundSync.addListener(
|
|
||||||
'unifiedPushUnregistered',
|
|
||||||
(event: UnifiedPushUnregisteredEvent) => {
|
|
||||||
this.handleUnregistered(event);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
await MatrixBackgroundSync.addListener(
|
|
||||||
'unifiedPushRegistrationFailed',
|
|
||||||
(event: UnifiedPushRegistrationFailedEvent) => {
|
|
||||||
this.handleRegistrationFailed(event);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
];
|
|
||||||
this.listenersReady = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove all plugin listeners when the manager stops. */
|
|
||||||
private async disposeListeners(): Promise<void> {
|
|
||||||
await Promise.all(this.listenerHandles.map((handle) => handle.remove()));
|
|
||||||
this.listenerHandles = [];
|
|
||||||
this.listenersReady = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reconcile an already-persisted native endpoint after app startup. */
|
|
||||||
private async syncExistingEndpoint(): Promise<void> {
|
|
||||||
const { client } = this;
|
|
||||||
if (!client) return;
|
|
||||||
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
|
|
||||||
const status = await this.safeGetStatus();
|
|
||||||
console.log('[BackgroundSync] Native status before pusher sync:', status);
|
|
||||||
if (status?.registered && status.endpoint) {
|
|
||||||
await this.upsertPusher(client, status.endpoint);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Create or refresh the Matrix HTTP pusher for the current device. */
|
|
||||||
private async upsertPusher(mx: MatrixClient, endpoint: string): Promise<void> {
|
|
||||||
const deviceId = mx.getDeviceId();
|
|
||||||
const userId = mx.getUserId();
|
|
||||||
const appId = buildPusherAppId(deviceId);
|
|
||||||
const gatewayUrl = await resolveUnifiedPushGateway(endpoint);
|
|
||||||
|
|
||||||
console.log('[BackgroundSync] Upserting Matrix pusher', {
|
|
||||||
appId,
|
|
||||||
endpoint,
|
|
||||||
gatewayUrl,
|
|
||||||
deviceId,
|
|
||||||
userId,
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await mx.setPusher({
|
|
||||||
kind: 'http',
|
|
||||||
app_id: appId,
|
|
||||||
pushkey: endpoint,
|
|
||||||
app_display_name: 'Paarrot',
|
|
||||||
device_display_name: deviceId ?? 'Android',
|
|
||||||
lang: 'en',
|
|
||||||
data: {
|
|
||||||
url: gatewayUrl,
|
|
||||||
format: 'event_id_only',
|
|
||||||
},
|
|
||||||
append: false,
|
|
||||||
device_id: deviceId ?? undefined,
|
|
||||||
} as unknown as IPusherRequest);
|
|
||||||
|
|
||||||
const pushers = (await mx.getPushers())?.pushers ?? [];
|
|
||||||
const thisPusher = pushers.find((p) => p.pushkey === endpoint && p.app_id === appId);
|
|
||||||
console.log('[BackgroundSync] Matrix pusher upserted successfully', {
|
|
||||||
totalPushers: pushers.length,
|
|
||||||
foundThisPusher: Boolean(thisPusher),
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BackgroundSync] Matrix pusher upsert failed:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
saveStoredPusherState(userId, deviceId, { endpoint, appId });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove a previously-registered Matrix HTTP pusher for this device. */
|
|
||||||
private async removePusher(
|
|
||||||
mx: MatrixClient,
|
|
||||||
endpoint: string,
|
|
||||||
appId = buildPusherAppId(mx.getDeviceId()),
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
await mx.setPusher({
|
|
||||||
pushkey: endpoint,
|
|
||||||
app_id: appId,
|
|
||||||
kind: null,
|
|
||||||
} as unknown as IPusherRequest);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] Failed to remove UnifiedPush pusher:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Read native registration state without failing the caller. */
|
|
||||||
private async safeGetStatus(): Promise<UnifiedPushStatus | undefined> {
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync =
|
|
||||||
registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
return await MatrixBackgroundSync.getStatus();
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] Failed to read UnifiedPush status:', err);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const unifiedPushManager = new AndroidUnifiedPushManager();
|
|
||||||
|
|
||||||
/** Start native UnifiedPush registration and sync the Matrix pusher. */
|
|
||||||
export const startBackgroundSync = async (mx: MatrixClient): Promise<void> => {
|
|
||||||
await unifiedPushManager.start(mx);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manually triggers a one-shot native fetch.
|
|
||||||
* Useful for diagnostics and bridge testing.
|
|
||||||
*/
|
|
||||||
export const triggerBackgroundSyncPing = async (reason?: string): Promise<void> => {
|
|
||||||
if (!isBackgroundSyncSupported()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
await MatrixBackgroundSync.triggerPing({ reason });
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] triggerPing failed:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Stop UnifiedPush integration and remove the Matrix pusher for this session. */
|
|
||||||
export const stopBackgroundSync = async (): Promise<void> => {
|
|
||||||
await unifiedPushManager.stop();
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tells the native service whether the app UI is in the foreground.
|
|
||||||
* Call when document visibility changes so the service can suppress
|
|
||||||
* duplicate notifications while the JS layer is active.
|
|
||||||
* @param foreground true if the WebView UI is currently visible
|
|
||||||
*/
|
|
||||||
export const setAppForegroundState = async (foreground: boolean): Promise<void> => {
|
|
||||||
if (!isBackgroundSyncSupported()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
await MatrixBackgroundSync.setAppForeground({ foreground });
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] setAppForeground failed:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Returns the current native UnifiedPush status, or undefined if unavailable. */
|
|
||||||
export const getBackgroundSyncStatus = async (): Promise<UnifiedPushStatus | undefined> => {
|
|
||||||
if (!isBackgroundSyncSupported()) return undefined;
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
return await MatrixBackgroundSync.getStatus();
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('[BackgroundSync] getStatus failed:', err);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-opens the UnifiedPush distributor selection dialog.
|
|
||||||
* Allows users to re-select or change their push notification distributor without terminal access.
|
|
||||||
* Useful when the current endpoint becomes unavailable.
|
|
||||||
*/
|
|
||||||
export const requestResetPushRegistration = async (): Promise<{ success: boolean }> => {
|
|
||||||
if (!isBackgroundSyncSupported()) {
|
|
||||||
console.warn('[BackgroundSync] Background sync not supported on this platform');
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { registerPlugin } = await loadCapacitorCore();
|
|
||||||
const MatrixBackgroundSync = registerPlugin<MatrixBackgroundSyncPlugin>('MatrixBackgroundSync');
|
|
||||||
const result = await MatrixBackgroundSync.requestDistributorSetup();
|
|
||||||
console.log('[BackgroundSync] requestDistributorSetup completed:', result);
|
|
||||||
if (!result?.success) return { success: false };
|
|
||||||
|
|
||||||
// Endpoint arrives asynchronously from the distributor after register().
|
|
||||||
for (let i = 0; i < 40; i += 1) {
|
|
||||||
await new Promise((resolve) => {
|
|
||||||
setTimeout(resolve, 250);
|
|
||||||
});
|
|
||||||
const status = await getBackgroundSyncStatus();
|
|
||||||
if (status?.registered && status.endpoint) {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
if (status?.lastFailure) {
|
|
||||||
console.warn('[BackgroundSync] Registration failed while waiting:', status.lastFailure);
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.warn('[BackgroundSync] Distributor selected but no endpoint received in time');
|
|
||||||
return { success: false };
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BackgroundSync] requestDistributorSetup failed:', err);
|
|
||||||
return { success: false };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
+2
-115
@@ -109,20 +109,6 @@ export const isYouTubeStreamingAvailable = (): boolean => {
|
|||||||
/** Callback for notification tap actions */
|
/** Callback for notification tap actions */
|
||||||
let notificationTapCallback: ((path: string) => void) | null = null;
|
let notificationTapCallback: ((path: string) => void) | null = null;
|
||||||
|
|
||||||
const ANDROID_NOTIFICATION_SMALL_ICON = 'ic_stat_paarrot';
|
|
||||||
const ANDROID_NOTIFICATION_ICON_COLOR = '#FF8A00';
|
|
||||||
|
|
||||||
const CAPACITOR_LOCAL_NOTIFICATIONS_MODULE_ID = '@capacitor/local-notifications';
|
|
||||||
|
|
||||||
type CapacitorLocalNotificationsModule = typeof import('@capacitor/local-notifications');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lazy-load Capacitor local notifications at runtime only.
|
|
||||||
* Vite must not pre-resolve this module because some desktop builds do not include it.
|
|
||||||
*/
|
|
||||||
const importCapacitorLocalNotifications = async (): Promise<CapacitorLocalNotificationsModule> =>
|
|
||||||
import(/* @vite-ignore */ CAPACITOR_LOCAL_NOTIFICATIONS_MODULE_ID);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bring the app window to the front and focus it
|
* Bring the app window to the front and focus it
|
||||||
*/
|
*/
|
||||||
@@ -166,24 +152,6 @@ export const setupNotificationTapListener = async (
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isCapacitorNative()) {
|
|
||||||
try {
|
|
||||||
const { LocalNotifications } = await importCapacitorLocalNotifications();
|
|
||||||
await LocalNotifications.addListener(
|
|
||||||
'localNotificationActionPerformed',
|
|
||||||
async (event: any) => {
|
|
||||||
await focusWindow();
|
|
||||||
const path = event?.notification?.extra?.path;
|
|
||||||
if (path && typeof path === 'string' && notificationTapCallback) {
|
|
||||||
notificationTapCallback(path);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Failed to set up Capacitor notification tap listener:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -264,32 +232,8 @@ const sendBrowserNotification = (options: {
|
|||||||
return notification;
|
return notification;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Flag to track if notification channel has been created on Android */
|
|
||||||
let notificationChannelCreated = false;
|
|
||||||
|
|
||||||
const ensureCapacitorNotificationChannel = async (): Promise<void> => {
|
|
||||||
if (notificationChannelCreated || !isAndroid()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { LocalNotifications } = await importCapacitorLocalNotifications();
|
|
||||||
await LocalNotifications.createChannel({
|
|
||||||
id: 'messages',
|
|
||||||
name: 'Messages',
|
|
||||||
description: 'Message notifications from Matrix',
|
|
||||||
importance: 5,
|
|
||||||
sound: 'default',
|
|
||||||
visibility: 1,
|
|
||||||
vibration: true,
|
|
||||||
lights: true,
|
|
||||||
});
|
|
||||||
notificationChannelCreated = true;
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Failed to create Capacitor notification channel:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request notification permission across Electron, Tauri, Capacitor, and browser
|
* Request notification permission across Electron, Tauri, and browser
|
||||||
*/
|
*/
|
||||||
export const requestSystemNotificationPermission = async (): Promise<boolean> => {
|
export const requestSystemNotificationPermission = async (): Promise<boolean> => {
|
||||||
if (isElectron()) {
|
if (isElectron()) {
|
||||||
@@ -298,37 +242,12 @@ export const requestSystemNotificationPermission = async (): Promise<boolean> =>
|
|||||||
return permission === 'granted';
|
return permission === 'granted';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isCapacitorNative()) {
|
|
||||||
try {
|
|
||||||
const { LocalNotifications } = await importCapacitorLocalNotifications();
|
|
||||||
let perm = await LocalNotifications.checkPermissions();
|
|
||||||
if (perm.display !== 'granted') {
|
|
||||||
perm = await LocalNotifications.requestPermissions();
|
|
||||||
}
|
|
||||||
return perm.display === 'granted';
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Capacitor notification permission request failed:', err);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!('Notification' in window)) return false;
|
if (!('Notification' in window)) return false;
|
||||||
const permission = await Notification.requestPermission();
|
const permission = await Notification.requestPermission();
|
||||||
return permission === 'granted';
|
return permission === 'granted';
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getSystemNotificationPermissionState = async (): Promise<PermissionState> => {
|
export const getSystemNotificationPermissionState = async (): Promise<PermissionState> => {
|
||||||
if (isCapacitorNative()) {
|
|
||||||
try {
|
|
||||||
const { LocalNotifications } = await importCapacitorLocalNotifications();
|
|
||||||
const perm = await LocalNotifications.checkPermissions();
|
|
||||||
return perm.display === 'granted' ? 'granted' : 'prompt';
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Failed to check Capacitor notification permission:', err);
|
|
||||||
return 'denied';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ('Notification' in window) {
|
if ('Notification' in window) {
|
||||||
if (window.Notification.permission === 'default') {
|
if (window.Notification.permission === 'default') {
|
||||||
return 'prompt';
|
return 'prompt';
|
||||||
@@ -340,7 +259,7 @@ export const getSystemNotificationPermissionState = async (): Promise<Permission
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a notification on Electron or Capacitor, falling back to the browser Notification API
|
* Send a notification on Electron, falling back to the browser Notification API
|
||||||
*/
|
*/
|
||||||
export const sendNotification = async (options: {
|
export const sendNotification = async (options: {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -369,38 +288,6 @@ export const sendNotification = async (options: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isCapacitorNative()) {
|
|
||||||
try {
|
|
||||||
const { LocalNotifications } = await importCapacitorLocalNotifications();
|
|
||||||
let perm = await LocalNotifications.checkPermissions();
|
|
||||||
if (perm.display !== 'granted') {
|
|
||||||
perm = await LocalNotifications.requestPermissions();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (perm.display === 'granted') {
|
|
||||||
await ensureCapacitorNotificationChannel();
|
|
||||||
|
|
||||||
const id = Math.floor(Date.now() % 2147483647);
|
|
||||||
await LocalNotifications.schedule({
|
|
||||||
notifications: [
|
|
||||||
{
|
|
||||||
id,
|
|
||||||
title,
|
|
||||||
body,
|
|
||||||
channelId: isAndroid() ? 'messages' : undefined,
|
|
||||||
smallIcon: isAndroid() ? ANDROID_NOTIFICATION_SMALL_ICON : undefined,
|
|
||||||
iconColor: isAndroid() ? ANDROID_NOTIFICATION_ICON_COLOR : undefined,
|
|
||||||
extra: path ? { path } : undefined,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Capacitor notification failed:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback to browser notification
|
// Fallback to browser notification
|
||||||
sendBrowserNotification({ title, body, icon, onClick });
|
sendBrowserNotification({ title, body, icon, onClick });
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user