Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52a9da18f2 | ||
|
|
9b3956d85f | ||
|
|
f81461c044 | ||
|
|
96d0d27549 | ||
|
|
33ae13e514 |
@@ -117,6 +117,9 @@ export default [
|
||||
|
||||
// Matrix video events carry no caption field, so there is no caption source to read.
|
||||
'jsx-a11y/media-has-caption': 'off',
|
||||
|
||||
// Prism tokens are not unique within a line, so the array index is the only key available.
|
||||
'react/no-array-index-key': 'off',
|
||||
},
|
||||
},
|
||||
].flatMap((config) =>
|
||||
|
||||
@@ -136,7 +136,6 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) {
|
||||
>
|
||||
{sasData.sas.emoji?.map(([emoji, name], index) => (
|
||||
<Box
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={`${emoji}${name}${index}`}
|
||||
direction="Column"
|
||||
gap="100"
|
||||
|
||||
@@ -30,8 +30,6 @@ import {
|
||||
UrlPreviewHolder,
|
||||
YouTubeEmbed,
|
||||
isYouTubeUrl,
|
||||
TikTokEmbed,
|
||||
isTikTokUrl,
|
||||
GiphyEmbed,
|
||||
isGiphyUrl,
|
||||
} from './url-preview';
|
||||
@@ -88,11 +86,8 @@ export function RenderMessageContent({
|
||||
|
||||
// Separate special URLs from generic ones
|
||||
const youtubeUrls = filteredUrls.filter(isYouTubeUrl);
|
||||
const tiktokUrls = filteredUrls.filter(isTikTokUrl);
|
||||
const giphyUrls = filteredUrls.filter(isGiphyUrl);
|
||||
const otherUrls = filteredUrls.filter(
|
||||
(url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url),
|
||||
);
|
||||
const otherUrls = filteredUrls.filter((url) => !isYouTubeUrl(url) && !isGiphyUrl(url));
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -100,10 +95,6 @@ export function RenderMessageContent({
|
||||
{youtubeUrls.map((url) => (
|
||||
<YouTubeEmbed key={url} url={url} />
|
||||
))}
|
||||
{/* Render TikTok embeds */}
|
||||
{tiktokUrls.map((url) => (
|
||||
<TikTokEmbed key={url} url={url} />
|
||||
))}
|
||||
{/* Render Giphy embeds */}
|
||||
{giphyUrls.map((url) => (
|
||||
<GiphyEmbed key={url} url={url} />
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { DefaultReset, color, config, toRem } from 'folds';
|
||||
|
||||
export const TikTokEmbed = style([
|
||||
DefaultReset,
|
||||
{
|
||||
width: toRem(360),
|
||||
maxWidth: '100%',
|
||||
backgroundColor: color.SurfaceVariant.Container,
|
||||
border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`,
|
||||
borderRadius: config.radii.R300,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
]);
|
||||
|
||||
export const TikTokEmbedHeader = style([
|
||||
DefaultReset,
|
||||
{
|
||||
padding: `${config.space.S200} ${config.space.S300}`,
|
||||
backgroundColor: color.SurfaceVariant.ContainerActive,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: config.space.S200,
|
||||
},
|
||||
]);
|
||||
|
||||
export const TikTokEmbedInfo = style([
|
||||
DefaultReset,
|
||||
{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: config.space.S100,
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
export const TikTokEmbedTitle = style({
|
||||
color: color.Primary.Main,
|
||||
textDecoration: 'none',
|
||||
fontWeight: config.fontWeight.W500,
|
||||
':hover': {
|
||||
textDecoration: 'underline',
|
||||
},
|
||||
});
|
||||
|
||||
export const TikTokEmbedAuthor = style({
|
||||
color: color.SurfaceVariant.OnContainer,
|
||||
textDecoration: 'none',
|
||||
opacity: 0.8,
|
||||
':hover': {
|
||||
textDecoration: 'underline',
|
||||
opacity: 1,
|
||||
},
|
||||
});
|
||||
|
||||
export const TikTokEmbedLink = style({
|
||||
color: color.Success.Main,
|
||||
textDecoration: 'none',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
':hover': {
|
||||
textDecoration: 'underline',
|
||||
},
|
||||
});
|
||||
|
||||
export const TikTokThumbnailContainer = style([
|
||||
DefaultReset,
|
||||
{
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
height: toRem(550),
|
||||
backgroundColor: '#000',
|
||||
display: 'block',
|
||||
},
|
||||
]);
|
||||
|
||||
export const TikTokThumbnailButton = style([
|
||||
DefaultReset,
|
||||
{
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
height: toRem(550),
|
||||
border: 'none',
|
||||
padding: 0,
|
||||
cursor: 'pointer',
|
||||
backgroundColor: '#000',
|
||||
display: 'block',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
]);
|
||||
|
||||
export const TikTokThumbnail = style([
|
||||
DefaultReset,
|
||||
{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
objectFit: 'cover',
|
||||
objectPosition: 'center',
|
||||
},
|
||||
]);
|
||||
|
||||
export const TikTokEmbedContainer = style([
|
||||
DefaultReset,
|
||||
{
|
||||
width: '100%',
|
||||
height: toRem(550),
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
backgroundColor: '#000',
|
||||
border: 'none',
|
||||
display: 'block',
|
||||
},
|
||||
]);
|
||||
@@ -1,277 +0,0 @@
|
||||
import React, { MouseEvent, useEffect, useState } from 'react';
|
||||
import { Box, Spinner, Text, as } from 'folds';
|
||||
import * as css from './TikTokEmbed.css';
|
||||
import { openExternalUrl } from '../../utils/tauri';
|
||||
|
||||
/**
|
||||
* Regex patterns to match TikTok URLs
|
||||
*/
|
||||
const TIKTOK_URL_PATTERNS = [
|
||||
// Standard tiktok.com/@username/video/VIDEO_ID
|
||||
/(?:https?:\/\/)?(?:www\.)?tiktok\.com\/@[\w.-]+\/video\/(\d+)/i,
|
||||
// Short vm.tiktok.com/VIDEO_CODE
|
||||
/(?:https?:\/\/)?(?:www\.)?vm\.tiktok\.com\/([\w]+)/i,
|
||||
// Short vt.tiktok.com/VIDEO_CODE
|
||||
/(?:https?:\/\/)?(?:www\.)?vt\.tiktok\.com\/([\w]+)/i,
|
||||
// Mobile m.tiktok.com
|
||||
/(?:https?:\/\/)?(?:www\.)?m\.tiktok\.com\/v\/(\d+)/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* TikTok oEmbed API base
|
||||
*/
|
||||
const TIKTOK_OEMBED_API = 'https://www.tiktok.com/oembed';
|
||||
|
||||
/**
|
||||
* Click handler for external links - uses Tauri shell on desktop/mobile
|
||||
*/
|
||||
const handleExternalLinkClick = (e: MouseEvent<HTMLAnchorElement>) => {
|
||||
const { href } = e.currentTarget;
|
||||
if (href && (href.startsWith('http://') || href.startsWith('https://'))) {
|
||||
e.preventDefault();
|
||||
openExternalUrl(href);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if a URL is a TikTok URL
|
||||
* @param url The URL to check
|
||||
* @returns True if the URL is a TikTok URL
|
||||
*/
|
||||
export function isTikTokUrl(url: string): boolean {
|
||||
return TIKTOK_URL_PATTERNS.some((pattern) => pattern.test(url));
|
||||
}
|
||||
|
||||
function extractTikTokVideoId(url: string, embedHtml = ''): string | null {
|
||||
const urlMatch = url.match(/\/video\/(\d+)/i) ?? url.match(/\/v\/(\d+)/i);
|
||||
const embedMatch = embedHtml.match(/data-video-id=["'](\d+)["']/i);
|
||||
return urlMatch?.[1] ?? embedMatch?.[1] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches TikTok video metadata using oEmbed API
|
||||
* @param url The TikTok video URL
|
||||
* @returns Video metadata including title, author, and thumbnail
|
||||
*/
|
||||
async function fetchTikTokOEmbed(url: string): Promise<{
|
||||
title: string;
|
||||
authorName: string;
|
||||
authorUrl: string;
|
||||
thumbnailUrl: string;
|
||||
embedHtml: string;
|
||||
videoId: string | null;
|
||||
} | null> {
|
||||
try {
|
||||
const { electron } = window as any;
|
||||
let data;
|
||||
if (electron?.tiktok?.getOEmbed) {
|
||||
data = await electron.tiktok.getOEmbed(url);
|
||||
} else {
|
||||
const oembedUrl = `${TIKTOK_OEMBED_API}?url=${encodeURIComponent(url)}`;
|
||||
const response = await fetch(oembedUrl);
|
||||
if (!response.ok) return null;
|
||||
data = await response.json();
|
||||
}
|
||||
if (!data) return null;
|
||||
|
||||
return {
|
||||
title: data.title || 'TikTok Video',
|
||||
authorName: data.author_name || 'Unknown',
|
||||
authorUrl: data.author_url || url,
|
||||
thumbnailUrl: data.thumbnail_url || '',
|
||||
embedHtml: data.html || '',
|
||||
videoId: extractTikTokVideoId(url, data.html || ''),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type TikTokEmbedState =
|
||||
| { status: 'loading' }
|
||||
| {
|
||||
status: 'loaded';
|
||||
title: string;
|
||||
authorName: string;
|
||||
authorUrl: string;
|
||||
thumbnailUrl: string;
|
||||
embedHtml: string;
|
||||
videoId: string | null;
|
||||
}
|
||||
| { status: 'error' };
|
||||
|
||||
type TikTokEmbedProps = {
|
||||
/** The original TikTok URL */
|
||||
url: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* TikTok embed component that shows video preview with metadata
|
||||
*/
|
||||
export const TikTokEmbed = as<'div', TikTokEmbedProps>(({ url, ...props }, ref) => {
|
||||
const [state, setState] = useState<TikTokEmbedState>({ status: 'loading' });
|
||||
const [showPlayer, setShowPlayer] = useState(false);
|
||||
|
||||
// Fetch video info on mount
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
fetchTikTokOEmbed(url).then((info) => {
|
||||
if (cancelled) return;
|
||||
|
||||
if (info) {
|
||||
setState({
|
||||
status: 'loaded',
|
||||
title: info.title,
|
||||
authorName: info.authorName,
|
||||
authorUrl: info.authorUrl,
|
||||
thumbnailUrl: info.thumbnailUrl,
|
||||
embedHtml: info.embedHtml,
|
||||
videoId: info.videoId,
|
||||
});
|
||||
} else {
|
||||
setState({ status: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [url]);
|
||||
|
||||
// Loading state
|
||||
if (state.status === 'loading') {
|
||||
return (
|
||||
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
|
||||
<div className={css.TikTokEmbedHeader}>
|
||||
<Text
|
||||
as="a"
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
size="T200"
|
||||
className={css.TikTokEmbedLink}
|
||||
onClick={handleExternalLinkClick}
|
||||
truncate
|
||||
>
|
||||
TikTok - Loading...
|
||||
</Text>
|
||||
</div>
|
||||
<Box
|
||||
className={css.TikTokThumbnailContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
style={{ background: '#000', display: 'flex' }}
|
||||
>
|
||||
<Spinner variant="Secondary" size="600" />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state - show basic link
|
||||
if (state.status === 'error') {
|
||||
return (
|
||||
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
|
||||
<div className={css.TikTokEmbedHeader}>
|
||||
<Text
|
||||
as="a"
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
size="T200"
|
||||
className={css.TikTokEmbedLink}
|
||||
onClick={handleExternalLinkClick}
|
||||
truncate
|
||||
>
|
||||
TikTok Video
|
||||
</Text>
|
||||
</div>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Loaded state - show thumbnail or embed
|
||||
if (!showPlayer) {
|
||||
return (
|
||||
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
|
||||
<div className={css.TikTokEmbedHeader}>
|
||||
<div className={css.TikTokEmbedInfo}>
|
||||
<Text
|
||||
as="a"
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
size="T300"
|
||||
className={css.TikTokEmbedTitle}
|
||||
onClick={handleExternalLinkClick}
|
||||
truncate
|
||||
>
|
||||
{state.title}
|
||||
</Text>
|
||||
<Text
|
||||
as="a"
|
||||
href={state.authorUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
size="T200"
|
||||
className={css.TikTokEmbedAuthor}
|
||||
onClick={handleExternalLinkClick}
|
||||
truncate
|
||||
>
|
||||
{state.authorName}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={css.TikTokThumbnailButton}
|
||||
onClick={() => setShowPlayer(true)}
|
||||
aria-label="Play TikTok video"
|
||||
>
|
||||
{state.thumbnailUrl ? (
|
||||
<img src={state.thumbnailUrl} alt={state.title} className={css.TikTokThumbnail} />
|
||||
) : null}
|
||||
</button>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const playerUrl = state.videoId
|
||||
? `https://www.tiktok.com/player/v1/${state.videoId}?autoplay=1`
|
||||
: null;
|
||||
|
||||
// Use TikTok's documented player instead of injecting the oEmbed script.
|
||||
return (
|
||||
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
|
||||
<div className={css.TikTokEmbedHeader}>
|
||||
<Text
|
||||
as="a"
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
size="T200"
|
||||
className={css.TikTokEmbedLink}
|
||||
onClick={handleExternalLinkClick}
|
||||
truncate
|
||||
>
|
||||
{state.title}
|
||||
</Text>
|
||||
</div>
|
||||
{playerUrl ? (
|
||||
<iframe
|
||||
className={css.TikTokEmbedContainer}
|
||||
src={playerUrl}
|
||||
title="TikTok video player"
|
||||
allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
|
||||
allowFullScreen
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className={css.TikTokEmbedContainer}
|
||||
dangerouslySetInnerHTML={{ __html: state.embedHtml }}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
export * from './UrlPreview';
|
||||
export * from './UrlPreviewCard';
|
||||
export * from './YouTubeEmbed';
|
||||
export * from './TikTokEmbed';
|
||||
export * from './GiphyEmbed';
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/* eslint-disable react/no-array-index-key */
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Badge, Box, Button, Chip, config, Menu, Spinner, Text } from 'folds';
|
||||
import { EventType } from 'matrix-js-sdk';
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/* eslint-disable react/no-array-index-key */
|
||||
import React, { useState, MouseEventHandler, ReactNode } from 'react';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import {
|
||||
|
||||
@@ -180,7 +180,6 @@ export function ForumPostUploadField({
|
||||
.reverse()
|
||||
.map((fileItem, index) => (
|
||||
<UploadCardRenderer
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={index}
|
||||
isEncrypted={!!fileItem.encInfo}
|
||||
fileItem={fileItem}
|
||||
|
||||
@@ -35,32 +35,7 @@ export function scopeRoomAppCss(css: string, scopeSelector: string): string {
|
||||
return `${scoped}{${body}}`;
|
||||
};
|
||||
|
||||
const rewriteBlock = (block: string): string => {
|
||||
const trimmed = block.trim();
|
||||
if (!trimmed) return '';
|
||||
|
||||
if (trimmed.startsWith('@')) {
|
||||
const open = trimmed.indexOf('{');
|
||||
if (open === -1) return `${trimmed};`;
|
||||
const header = trimmed.slice(0, open).trim();
|
||||
const inner = trimmed.slice(open + 1);
|
||||
// @keyframes / @font-face: keep as-is (namespaced risk is low for MVP)
|
||||
if (/^@(keyframes|font-face)\b/i.test(header)) {
|
||||
return `${header}{${inner}}`;
|
||||
}
|
||||
// @media / @supports: re-scope nested rules
|
||||
const nested = rewriteCssChunk(inner);
|
||||
return `${header}{${nested}}`;
|
||||
}
|
||||
|
||||
const open = trimmed.indexOf('{');
|
||||
if (open === -1) return '';
|
||||
const selectors = trimmed.slice(0, open);
|
||||
const body = trimmed.slice(open + 1);
|
||||
return scopeRule(selectors, body);
|
||||
};
|
||||
|
||||
const rewriteCssChunk = (chunk: string): string => {
|
||||
function rewriteChunk(chunk: string): string {
|
||||
const parts: string[] = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
@@ -70,15 +45,32 @@ export function scopeRoomAppCss(css: string, scopeSelector: string): string {
|
||||
else if (ch === '}') {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
parts.push(rewriteBlock(chunk.slice(start, i)));
|
||||
const block = chunk.slice(start, i).trim();
|
||||
start = i + 1;
|
||||
if (block) {
|
||||
const open = block.indexOf('{');
|
||||
if (open === -1) {
|
||||
parts.push(`${block};`);
|
||||
} else {
|
||||
const header = block.slice(0, open).trim();
|
||||
const inner = block.slice(open + 1);
|
||||
if (!header.startsWith('@')) {
|
||||
parts.push(scopeRule(header, inner));
|
||||
} else if (/^@(keyframes|font-face)\b/i.test(header)) {
|
||||
parts.push(`${header}{${inner}}`);
|
||||
} else {
|
||||
// @media / @supports: re-scope nested rules
|
||||
parts.push(`${header}{${rewriteChunk(inner)}}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts.filter(Boolean).join('\n');
|
||||
};
|
||||
}
|
||||
|
||||
return rewriteCssChunk(sanitized);
|
||||
return rewriteChunk(sanitized);
|
||||
}
|
||||
|
||||
export function isAllowedRoomAppImageSrc(src: string): boolean {
|
||||
|
||||
@@ -635,7 +635,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
.reverse()
|
||||
.map((fileItem, index) => (
|
||||
<UploadCardRenderer
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={index}
|
||||
isEncrypted={!!fileItem.encInfo}
|
||||
fileItem={fileItem}
|
||||
|
||||
@@ -167,14 +167,21 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
// first sync) can not leave the splash up forever.
|
||||
const splashDeadline = useRef<number | undefined>(undefined);
|
||||
|
||||
const scheduleHide = useCallback((reason?: string) => {
|
||||
if (splashHoldTimer.current !== undefined) return;
|
||||
// The splash particles animate for 450ms with up to 640ms of stagger. Hold only
|
||||
// for whatever is left of that, so a load that already took longer swaps at once.
|
||||
const splashShownAt = useRef(performance.now());
|
||||
const splashHidden = useRef(false);
|
||||
|
||||
if (reason) console.log(`[ClientRoot] Hiding splash: ${reason}`);
|
||||
const scheduleHide = useCallback((reason?: string) => {
|
||||
if (splashHidden.current) return;
|
||||
|
||||
const hold = Math.max(0, 1100 - (performance.now() - splashShownAt.current));
|
||||
if (reason) console.log(`[ClientRoot] Hiding splash: ${reason} (hold ${Math.round(hold)}ms)`);
|
||||
splashHidden.current = true;
|
||||
splashHoldTimer.current = window.setTimeout(() => {
|
||||
splashHoldTimer.current = undefined;
|
||||
setLoading(false);
|
||||
}, 1500);
|
||||
}, hold);
|
||||
}, []);
|
||||
|
||||
// The UI renders chats from the room-list atoms, which are filled by
|
||||
@@ -182,10 +189,9 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
// so the first paint after the splash already contains the chats.
|
||||
const roomsAtom = useAtomValue(allRoomsAtom);
|
||||
const directsAtom = useAtomValue(mDirectAtom);
|
||||
const chatsReady =
|
||||
roomsAtom.length > 0 &&
|
||||
directsAtom.size > 0 &&
|
||||
roomsAtom.some((roomId) => directsAtom.has(roomId));
|
||||
// An account with no direct chats can never satisfy a gate that requires one, so it
|
||||
// always waits for the deadline. Gate on the rooms only.
|
||||
const chatsReady = roomsAtom.length > 0;
|
||||
|
||||
const tryHide = useCallback(
|
||||
(reason: string): boolean => {
|
||||
@@ -285,12 +291,10 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
const poll = window.setInterval(check, 400);
|
||||
mx.on(ClientEvent.Room, check);
|
||||
mx.on(ClientEvent.AccountData, check);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(poll);
|
||||
mx.removeListener(ClientEvent.Room, check);
|
||||
mx.removeListener(ClientEvent.AccountData, check);
|
||||
};
|
||||
|
||||
+1
-232
@@ -5,7 +5,6 @@ import { clearNavToActivePathStore } from '../app/state/navToActivePath';
|
||||
import { Session, Sessions, getSessionStoreName } from '../app/state/sessions';
|
||||
import { getSettings } from '../app/state/settings';
|
||||
import { recordPacket } from '../app/state/debugPackets';
|
||||
import { promptDialog } from '../app/state/dialog';
|
||||
|
||||
const MAX_BODY = 8192;
|
||||
|
||||
@@ -86,183 +85,9 @@ const debugFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise
|
||||
return res;
|
||||
};
|
||||
|
||||
// Track if we're currently handling a key conflict to prevent loops
|
||||
let handlingKeyConflict = false;
|
||||
|
||||
const deleteIndexedDB = (dbName: string): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const request = globalThis.indexedDB.deleteDatabase(dbName);
|
||||
request.onsuccess = () => {
|
||||
console.log(`[initMatrix] Deleted IndexedDB database: ${dbName}`);
|
||||
resolve();
|
||||
};
|
||||
request.onerror = () => {
|
||||
console.error(`[initMatrix] Failed to delete IndexedDB database: ${dbName}`, request.error);
|
||||
reject(request.error);
|
||||
};
|
||||
request.onblocked = () => {
|
||||
console.warn(`[initMatrix] Delete blocked for IndexedDB database: ${dbName}`);
|
||||
// Resolve anyway as the delete might succeed later
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
|
||||
const getAllIndexedDBNames = async (): Promise<string[]> => {
|
||||
try {
|
||||
if ('databases' in globalThis.indexedDB) {
|
||||
// Add timeout to prevent hanging
|
||||
const timeoutPromise = new Promise<string[]>((resolve) => {
|
||||
setTimeout(() => {
|
||||
console.warn('[initMatrix] indexedDB.databases() timed out after 2s');
|
||||
resolve([]);
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
const databasesPromise = globalThis.indexedDB
|
||||
.databases()
|
||||
.then((dbs) => dbs.map((db) => db.name).filter((name) => typeof name === 'string'));
|
||||
|
||||
return await Promise.race([databasesPromise, timeoutPromise]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[initMatrix] Error getting IndexedDB names:', error);
|
||||
}
|
||||
// Fallback for browsers that don't support indexedDB.databases()
|
||||
return [];
|
||||
};
|
||||
|
||||
/**
|
||||
* Delete the Rust crypto database to fix one-time key conflicts.
|
||||
* This happens when the local crypto state has keys that conflict with server state.
|
||||
*/
|
||||
const deleteRustCryptoDatabase = async (session: Session): Promise<boolean> => {
|
||||
console.log('[initMatrix] 🔑 Attempting to delete Rust crypto database to fix key conflicts...');
|
||||
|
||||
const dbNames = await getAllIndexedDBNames();
|
||||
const storagePrefix = `${session.userId}@${session.deviceId}`;
|
||||
|
||||
// Find crypto databases for this session
|
||||
const cryptoDbNames = dbNames.filter(
|
||||
(name) => name.includes('matrix-sdk-crypto') || name.includes(storagePrefix),
|
||||
);
|
||||
|
||||
if (cryptoDbNames.length === 0) {
|
||||
console.log('[initMatrix] No crypto databases found to delete');
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames);
|
||||
|
||||
for (let i = 0; i < cryptoDbNames.length; i += 1) {
|
||||
const dbName = cryptoDbNames[i];
|
||||
try {
|
||||
await deleteIndexedDB(dbName);
|
||||
console.log(`[initMatrix] ✅ Deleted: ${dbName}`);
|
||||
} catch (error) {
|
||||
console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Setup error listener to detect one-time key conflicts and auto-fix them.
|
||||
*/
|
||||
const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
|
||||
// Listen for HTTP errors from the client
|
||||
let keyConflictCount = 0;
|
||||
const KEY_CONFLICT_THRESHOLD = 3;
|
||||
|
||||
// Patch console.log/error to detect the key conflict errors
|
||||
const keyConflictPattern = /One time key.*already exists/;
|
||||
|
||||
// We need to use a different approach - listen to the crypto module
|
||||
// Since we can't directly intercept, we'll use a MutationObserver-style approach
|
||||
// by checking for repeated key upload failures
|
||||
|
||||
const checkKeyConflict = (args: unknown[]): boolean => {
|
||||
const message = args.map((a) => String(a)).join(' ');
|
||||
return keyConflictPattern.test(message);
|
||||
};
|
||||
|
||||
// Override console methods temporarily to detect the errors
|
||||
const originalError = console.error;
|
||||
const originalWarn = console.warn;
|
||||
|
||||
const errorHandler = (...args: unknown[]) => {
|
||||
if (checkKeyConflict(args)) {
|
||||
keyConflictCount += 1;
|
||||
console.log(
|
||||
`[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`,
|
||||
);
|
||||
|
||||
if (keyConflictCount >= KEY_CONFLICT_THRESHOLD && !handlingKeyConflict) {
|
||||
handlingKeyConflict = true;
|
||||
console.log('[initMatrix] 🔄 Too many key conflicts detected, attempting auto-fix...');
|
||||
|
||||
// Schedule the fix for next page load to avoid issues during active session
|
||||
localStorage.setItem(
|
||||
'cinny_fix_key_conflict',
|
||||
JSON.stringify({
|
||||
userId: session.userId,
|
||||
deviceId: session.deviceId,
|
||||
timestamp: Date.now(),
|
||||
}),
|
||||
);
|
||||
|
||||
// Restore console methods
|
||||
console.error = originalError;
|
||||
console.warn = originalWarn;
|
||||
|
||||
// Notify user and reload
|
||||
setTimeout(() => {
|
||||
promptDialog(
|
||||
'Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?',
|
||||
true,
|
||||
).then((continueFix) => {
|
||||
if (continueFix) {
|
||||
deleteRustCryptoDatabase(session).then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
} else {
|
||||
handlingKeyConflict = false;
|
||||
}
|
||||
});
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
originalError.apply(console, args);
|
||||
};
|
||||
|
||||
console.error = errorHandler;
|
||||
console.warn = (...args: unknown[]) => {
|
||||
if (checkKeyConflict(args)) {
|
||||
keyConflictCount += 1;
|
||||
}
|
||||
originalWarn.apply(console, args);
|
||||
};
|
||||
};
|
||||
|
||||
export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
const storeName = getSessionStoreName(session);
|
||||
|
||||
// Check if we need to fix a key conflict from a previous session
|
||||
const pendingFix = localStorage.getItem('cinny_fix_key_conflict');
|
||||
if (pendingFix) {
|
||||
try {
|
||||
const fixData = JSON.parse(pendingFix);
|
||||
if (fixData.userId === session.userId && fixData.deviceId === session.deviceId) {
|
||||
console.log('[initMatrix] 🔧 Found pending key conflict fix, clearing crypto database...');
|
||||
await deleteRustCryptoDatabase(session);
|
||||
localStorage.removeItem('cinny_fix_key_conflict');
|
||||
console.log('[initMatrix] ✅ Crypto database cleared');
|
||||
}
|
||||
} catch {
|
||||
localStorage.removeItem('cinny_fix_key_conflict');
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[initMatrix] ========================================');
|
||||
console.log('[initMatrix] Initializing Matrix client for session:');
|
||||
console.log('[initMatrix] User ID:', session.userId);
|
||||
@@ -298,15 +123,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
|
||||
await indexedDBStore.startup();
|
||||
|
||||
// Initialize Rust crypto with a unique store prefix for this account
|
||||
// This ensures each account has its own isolated crypto database
|
||||
console.log(
|
||||
'[initMatrix] Initializing Rust crypto with prefix:',
|
||||
`${session.userId}@${session.deviceId}`,
|
||||
);
|
||||
await mx.initRustCrypto({
|
||||
cryptoDatabasePrefix: `${session.userId}@${session.deviceId}`,
|
||||
});
|
||||
await mx.initRustCrypto();
|
||||
|
||||
console.log('[initMatrix] ✅ Client initialized successfully!');
|
||||
|
||||
@@ -323,9 +140,6 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
return user;
|
||||
};
|
||||
|
||||
// Setup handler to detect and auto-fix one-time key conflicts
|
||||
setupKeyConflictHandler(mx, session);
|
||||
|
||||
// Register this as the global MatrixClient so auth utils can access the latest token
|
||||
const { setGlobalMatrixClient } = await import('../app/utils/auth');
|
||||
setGlobalMatrixClient(mx);
|
||||
@@ -367,51 +181,6 @@ export const clearCacheAndReload = async (mx: MatrixClient) => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
/**
|
||||
* Fix one-time key conflicts by clearing the Rust crypto database.
|
||||
* Call this when you see repeated "One time key already exists" errors.
|
||||
* The user will need to re-verify their devices after this.
|
||||
*/
|
||||
export const fixKeyConflict = async (mx: MatrixClient): Promise<void> => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const deviceId = mx.getDeviceId();
|
||||
|
||||
if (!userId || !deviceId) {
|
||||
console.error('[initMatrix] Cannot fix key conflict: missing userId or deviceId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[initMatrix] 🔧 Fixing key conflict for', userId, deviceId);
|
||||
|
||||
// Stop the client first
|
||||
mx.stopClient();
|
||||
|
||||
// Delete the crypto databases
|
||||
const dbNames = await getAllIndexedDBNames();
|
||||
const storagePrefix = `${userId}@${deviceId}`;
|
||||
|
||||
const cryptoDbNames = dbNames.filter(
|
||||
(name) =>
|
||||
name.includes('matrix-sdk-crypto') || name.includes(storagePrefix) || name.includes('crypto'),
|
||||
);
|
||||
|
||||
console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames);
|
||||
|
||||
for (let i = 0; i < cryptoDbNames.length; i += 1) {
|
||||
const dbName = cryptoDbNames[i];
|
||||
try {
|
||||
await deleteIndexedDB(dbName);
|
||||
console.log(`[initMatrix] ✅ Deleted: ${dbName}`);
|
||||
} catch (error) {
|
||||
console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Reload the page
|
||||
console.log('[initMatrix] 🔄 Reloading...');
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
export const logoutClient = async (mx: MatrixClient) => {
|
||||
mx.stopClient();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user