diff --git a/config.json b/config.json index 71c93e0c0..77be1ad3c 100644 --- a/config.json +++ b/config.json @@ -48,6 +48,6 @@ "gifs": { "proxyUrl": "gifs.sable.moe", - "klipyApiKey": "SET_YOUR_TOKEN_HERE" + "klipyApiKey": "IfeIBlDMvq0av2BcKPDuxwRqbnYRbS90yNqFHEkK2Ja207tkR5nssh3NIlJRCr76" } } diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index d464209eb..510acc956 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -165,7 +165,11 @@ const useGroups = ( return [emojiGroupItems, stickerGroupItems, gifGroupItems]; }; -const useItemRenderer = (tab: EmojiBoardTab, saveStickerEmojiBandwidth: boolean) => { +const useItemRenderer = ( + tab: EmojiBoardTab, + saveStickerEmojiBandwidth: boolean, + onGifSelect?: (gif: GifData, spoiler?: boolean) => void +) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -448,7 +452,7 @@ type EmojiBoardProps = { onEmojiSelect?: (unicode: string, shortcode: string) => void; onCustomEmojiSelect?: (mxc: string, shortcode: string) => void; onStickerSelect?: (mxc: string, shortcode: string, label: string) => void; - onGifSelect?: (gif: GifData) => void; + onGifSelect?: (gif: GifData, spoiler?: boolean) => void; allowTextCustomEmoji?: boolean; addToRecentEmoji?: boolean; isFullWidth?: boolean; @@ -550,6 +554,7 @@ export function EmojiBoard({ preview_url: preview?.url || fullRes?.url || '', width, height, + size: fullRes?.size || preview?.size || 0, }; }, []); @@ -631,7 +636,7 @@ export function EmojiBoard({ : gifGroupItems, }; const groups = groupsByTab[tab]; - const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth); + const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth, onGifSelect); const handleOnChange: ChangeEventHandler = useDebounce( useCallback( @@ -707,7 +712,8 @@ export function EmojiBoard({ if (emojiInfo.type === EmojiType.Gif) { const gifDataStr = targetEl.getAttribute('data-gif-data'); const gifData = gifDataStr ? JSON.parse(gifDataStr) : null; - onGifSelect?.(gifData); + const isSpoiler = targetEl.getAttribute('data-gif-spoiler') === 'true'; + onGifSelect?.(gifData, isSpoiler); } if (!evt.altKey && !evt.shiftKey) requestClose(); }; @@ -777,6 +783,7 @@ export function EmojiBoard({ key={tab} query={emojiResult?.query} onChange={handleOnChange} + tab={tab} allowTextCustomEmoji={allowTextCustomEmoji} onTextCustomEmojiSelect={handleTextCustomEmojiSelect} /> diff --git a/src/app/components/emoji-board/components/Item.tsx b/src/app/components/emoji-board/components/Item.tsx index 1b3e180bb..9dc104348 100644 --- a/src/app/components/emoji-board/components/Item.tsx +++ b/src/app/components/emoji-board/components/Item.tsx @@ -9,9 +9,11 @@ import type { CSSProperties, ReactNode } from 'react'; import { useEffect, useState } from 'react'; import * as css from './styles.css'; import { useFavoriteGifs } from '$hooks/useFavoriteGifs'; -import { Star, menuIcon } from '$components/icons/phosphor'; +import { Star, Eye, EyeSlash, menuIcon } from '$components/icons/phosphor'; import { MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS } from '$unstable/prefixes'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useClientConfig } from '$hooks/useClientConfig'; +import { getKlipyMxcUrl } from '$utils/klipy'; const ANIMATED_MIME_TYPES = new Set(['image/gif', 'image/apng']); @@ -165,16 +167,28 @@ export function GifItem({ children: ReactNode; }) { const [isHovered, setIsHovered] = useState(false); - const initialFavorited = useFavoriteGifs(); - const [favoritedContent, setFavoritedContent] = useState(initialFavorited); + const favoritedContent = useFavoriteGifs(); + const clientConfig = useClientConfig(); + + const mxcUrl = gif?.url ? getKlipyMxcUrl(gif.url, clientConfig.gifs?.proxyUrl) : ''; + const [favorited, setFavorited] = useState( - favoritedContent.gifs.find((v) => v.url == gif?.url) != undefined + favoritedContent.gifs.some((v) => { + const vMxc = getKlipyMxcUrl(v.url, clientConfig.gifs?.proxyUrl); + return vMxc === mxcUrl && mxcUrl !== ''; + }) ); + const [isSpoiler, setIsSpoiler] = useState(false); const mx = useMatrixClient(); useEffect(() => { - setFavoritedContent(initialFavorited); - }, [initialFavorited]); + setFavorited( + favoritedContent.gifs.some((v) => { + const vMxc = getKlipyMxcUrl(v.url, clientConfig.gifs?.proxyUrl); + return vMxc === mxcUrl && mxcUrl !== ''; + }) + ); + }, [favoritedContent, mxcUrl, clientConfig.gifs?.proxyUrl]); return ( setIsHovered(true)} onPointerLeave={() => setIsHovered(false)} > @@ -206,18 +221,19 @@ export function GifItem({ title={favorited ? 'Unfavorite gif' : 'Favorite gif'} onClick={async (e) => { e.preventDefault(); + e.stopPropagation(); if (!favorited) { setFavorited(true); await mx .setAccountData(MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS, { - gifs: [...favoritedContent.gifs, gif], + gifs: [...favoritedContent.gifs, { ...gif, url: mxcUrl }], }) .catch(() => setFavorited(false)); } else { setFavorited(false); await mx .setAccountData(MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS, { - gifs: favoritedContent.gifs.filter((v) => v.url != gif.url), + gifs: favoritedContent.gifs.filter((v) => getKlipyMxcUrl(v.url, clientConfig.gifs?.proxyUrl) !== mxcUrl), }) .catch(() => setFavorited(true)); } @@ -228,6 +244,23 @@ export function GifItem({ color: favorited ? color.Warning.MainHover : color.Surface.OnContainer, })} + { + e.preventDefault(); + e.stopPropagation(); + setIsSpoiler(!isSpoiler); + }} + > + {menuIcon(isSpoiler ? EyeSlash : Eye, { + weight: isSpoiler ? 'fill' : 'regular', + color: color.Surface.OnContainer, + })} + diff --git a/src/app/components/emoji-board/components/SearchInput.tsx b/src/app/components/emoji-board/components/SearchInput.tsx index bf4250fc8..5d55b061b 100644 --- a/src/app/components/emoji-board/components/SearchInput.tsx +++ b/src/app/components/emoji-board/components/SearchInput.tsx @@ -10,12 +10,14 @@ type SearchInputProps = { onChange: ChangeEventHandler; allowTextCustomEmoji?: boolean; onTextCustomEmojiSelect?: (text: string) => void; + tab?: EmojiBoardTab; }; export function SearchInput({ query, onChange, allowTextCustomEmoji, onTextCustomEmojiSelect, + tab, }: SearchInputProps) { const inputRef = useRef(null); @@ -31,11 +33,15 @@ export function SearchInput({ variant="SurfaceVariant" size="400" placeholder={ - allowTextCustomEmoji && !EmojiBoardTab.Gif ? 'Search or Text Reaction ' : 'Search' + tab === EmojiBoardTab.Gif + ? 'Search KLIPY' + : allowTextCustomEmoji + ? 'Search or Text Reaction ' + : 'Search' } maxLength={50} after={ - allowTextCustomEmoji && query && !EmojiBoardTab.Gif ? ( + allowTextCustomEmoji && query && tab !== EmojiBoardTab.Gif ? ( void; } -function toBase64Url(value: string): string { - const bytes = new TextEncoder().encode(value); - let binary = ''; - for (const byte of bytes) { - binary += String.fromCodePoint(byte); - } - - return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll(/=+$/g, ''); -} - -function toMatrixID(fname: string, urlPrefix: string): string { - const base64 = toBase64Url(fname); - return urlPrefix + base64; -} export const RoomInput = forwardRef( ({ editor, fileDropContainerRef, roomId, room, threadRootId, onEditLastMessage }, ref) => { @@ -590,27 +578,9 @@ export const RoomInput = forwardRef( handleRemoveUpload(uploads.map((upload) => upload.file)); }; - const handleSendUpload = async (uploads: UploadSuccess[]) => { + const handleSendContents = async (contents: IContent[]) => { const plainText = toPlainText(editor.children).trim(); - const contentsPromises = uploads.map(async (upload) => { - const fileItem = selectedFiles.find((f) => f.file === upload.file); - if (!fileItem) throw new Error('Broken upload'); - - if (fileItem.file.type.startsWith('image')) { - return getImageMsgContent(mx, fileItem, upload.mxc); - } - if (fileItem.file.type.startsWith('video')) { - return getVideoMsgContent(mx, fileItem, upload.mxc); - } - if (fileItem.file.type.startsWith('audio')) { - return getAudioMsgContent(fileItem, upload.mxc); - } - return getFileMsgContent(fileItem, upload.mxc); - }); - handleCancelUpload(uploads); - const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises)); - /** * the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending. * This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message, @@ -662,11 +632,11 @@ export const RoomInput = forwardRef( setEditingScheduledDelayId(null); setScheduledTime(null); } catch (error) { - debugLog.error('message', 'Failed to schedule uploaded file message', { + debugLog.error('message', 'Failed to schedule message', { roomId, error: error instanceof Error ? error.message : String(error), }); - log.error('failed to schedule uploaded message', { roomId }, error); + log.error('failed to schedule message', { roomId }, error); throw error; } } else { @@ -678,7 +648,7 @@ export const RoomInput = forwardRef( } catch { debugLog.error( 'message', - 'Failed to cancel scheduled event before immediate file send', + 'Failed to cancel scheduled event before immediate send', { roomId } ); } @@ -689,7 +659,7 @@ export const RoomInput = forwardRef( mx .sendMessage(roomId, threadRootId ?? null, content as RoomMessageEventContent) .then((res: { event_id: string }) => { - debugLog.info('message', 'Uploaded file message sent', { + debugLog.info('message', 'Message sent', { roomId, eventId: res.event_id, msgtype: content.msgtype, @@ -697,11 +667,11 @@ export const RoomInput = forwardRef( return res; }) .catch((error: unknown) => { - debugLog.error('message', 'Failed to send uploaded file message', { + debugLog.error('message', 'Failed to send message', { roomId, error: error instanceof Error ? error.message : String(error), }); - log.error('failed to send uploaded message', { roomId }, error); + log.error('failed to send message', { roomId }, error); throw error; }) ) @@ -709,6 +679,28 @@ export const RoomInput = forwardRef( } }; + const handleSendUpload = async (uploads: UploadSuccess[]) => { + const contentsPromises = uploads.map(async (upload) => { + const fileItem = selectedFiles.find((f) => f.file === upload.file); + if (!fileItem) throw new Error('Broken upload'); + + if (fileItem.file.type.startsWith('image')) { + return getImageMsgContent(mx, fileItem, upload.mxc); + } + if (fileItem.file.type.startsWith('video')) { + return getVideoMsgContent(mx, fileItem, upload.mxc); + } + if (fileItem.file.type.startsWith('audio')) { + return getAudioMsgContent(fileItem, upload.mxc); + } + return getFileMsgContent(fileItem, upload.mxc); + }); + handleCancelUpload(uploads); + const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises)); + + await handleSendContents(contents); + }; + const handleCloseAutocomplete = useCallback(() => { setAutocompleteQuery(undefined); ReactEditor.focus(editor); @@ -1324,39 +1316,12 @@ export const RoomInput = forwardRef( mx.sendEvent(roomId, EventType.Sticker, content); }; - const handleGifSelect = async (gif: GifData) => { - let url = gif.url.startsWith('mxc://') - ? gif.url - : `mxc://${clientConfig.gifs?.proxyUrl ?? ''}/${toMatrixID(gif.url.slice('https://static.klipy.com/ii/'.length), 'klipy_')}`; + const handleGifSelect = async (gif: GifData, spoiler?: boolean) => { + const url = getKlipyMxcUrl(gif.url, clientConfig.gifs?.proxyUrl); - const content: RoomMessageEventContent & ReplyEventContent & IContent = { - body: gif.title, - url: url, - msgtype: MsgType.Image, - info: { - w: gif.width, - h: gif.height, - mimetype: 'image/gif', - }, - }; + const content = await getGifMsgContent(mx, gif, url, spoiler); - // Handle replies if there's a reply draft - if (replyDraft) { - content['m.relates_to'] = { - 'm.in_reply_to': { - event_id: replyDraft.eventId, - }, - }; - if (replyDraft.relation?.rel_type === RelationType.Thread) { - content['m.relates_to'].event_id = replyDraft.relation.event_id; - content['m.relates_to'].rel_type = RelationType.Thread; - content['m.relates_to'].is_falling_back = false; - } - } - - // Send the gif as sticker event. - await mx.sendEvent(roomId, EventType.RoomMessage, content); - setReplyDraft(undefined); + await handleSendContents([content]); }; return ( diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index 8d51eb213..d0d77cadf 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -10,8 +10,9 @@ import { loadImageElement, loadVideoElement, } from '$utils/dom'; -import { encryptFile, getImageInfo, getThumbnailContent, getVideoInfo } from '$utils/matrix'; +import { encryptFile, getImageInfo, getThumbnailContent, getVideoInfo, mxcUrlToHttp } from '$utils/matrix'; import type { TUploadItem } from '$state/room/roomInputDrafts'; +import type { GifData } from '$components/emoji-board/types'; import { encodeBlurHash } from '$utils/blurHash'; import { scaleYDimension } from '$utils/common'; import { createLogger } from '$utils/debug'; @@ -237,3 +238,44 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { } return content; }; + +export const getGifMsgContent = async ( + mx: MatrixClient, + gif: GifData, + mxcUrl: string, + spoiler?: boolean +): Promise => { + const proxyUrl = mxcUrlToHttp(mx, mxcUrl, true); + const [imgError, imgEl] = await to(loadImageElement(proxyUrl ?? gif.url, 'anonymous')); + if (imgError) { + log.warn('Failed to load image element anonymously for blurhash, falling back to basic metadata:', imgError); + } + + const content: IContent = { + msgtype: MsgType.Image, + body: gif.title, + url: mxcUrl, + info: { + w: gif.width, + h: gif.height, + mimetype: 'image/gif', + }, + }; + + if (gif.size) { + content.info.size = gif.size; + } + + if (spoiler) { + content[MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME] = true; + } + + if (imgEl) { + const blurHash = encodeBlurHash(imgEl, 512, scaleYDimension(imgEl.width, 512, imgEl.height)); + if (blurHash) { + content.info[MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME] = blurHash; + } + } + + return content; +}; diff --git a/src/app/hooks/useFavoriteGifs.ts b/src/app/hooks/useFavoriteGifs.ts index 7504f3ff8..935d5efe9 100644 --- a/src/app/hooks/useFavoriteGifs.ts +++ b/src/app/hooks/useFavoriteGifs.ts @@ -2,12 +2,14 @@ import type { AccountDataEvents } from 'matrix-js-sdk'; import { MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS } from '../../unstable/prefixes'; import { useAccountData } from './useAccountData'; +const DEFAULT_FAVORITE_GIFS: AccountDataEvents[typeof MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS] = { gifs: [] }; + export const useFavoriteGifs = (): AccountDataEvents[typeof MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS] => { const favoritedGifsData = useAccountData(MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS); const favoritedContent = favoritedGifsData?.getContent< AccountDataEvents[typeof MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS] - >() ?? { gifs: [] }; + >() ?? DEFAULT_FAVORITE_GIFS; return favoritedContent; }; diff --git a/src/app/utils/blurHash.ts b/src/app/utils/blurHash.ts index 566f6d189..3fce2662e 100644 --- a/src/app/utils/blurHash.ts +++ b/src/app/utils/blurHash.ts @@ -14,8 +14,13 @@ export const encodeBlurHash = ( if (!context) return undefined; context.drawImage(img, 0, 0, canvas.width, canvas.height); - const data = context.getImageData(0, 0, canvas.width, canvas.height); - return encode(data.data, data.width, data.height, 4, 4); + try { + const data = context.getImageData(0, 0, canvas.width, canvas.height); + return encode(data.data, data.width, data.height, 4, 4); + } catch (err) { + console.warn('Failed to encode blurhash, possibly due to cross-origin tainted canvas:', err); + return undefined; + } }; export const validBlurHash = (hash?: string): string | undefined => { diff --git a/src/app/utils/dom.ts b/src/app/utils/dom.ts index 45099c9ad..50cba5424 100644 --- a/src/app/utils/dom.ts +++ b/src/app/utils/dom.ts @@ -99,9 +99,10 @@ export const getImageFileUrl = (fileOrBlob: File | Blob) => URL.createObjectURL( export const getVideoFileUrl = (fileOrBlob: File | Blob) => URL.createObjectURL(fileOrBlob); -export const loadImageElement = (url: string): Promise => +export const loadImageElement = (url: string, crossOrigin?: string): Promise => new Promise((resolve, reject) => { const img = document.createElement('img'); + if (crossOrigin) img.crossOrigin = crossOrigin; img.addEventListener('load', () => resolve(img)); img.addEventListener('error', (err) => reject(err)); img.src = url; diff --git a/src/app/utils/klipy.ts b/src/app/utils/klipy.ts new file mode 100644 index 000000000..aa04c07f6 --- /dev/null +++ b/src/app/utils/klipy.ts @@ -0,0 +1,25 @@ +export function toBase64Url(value: string): string { + const bytes = new TextEncoder().encode(value); + let binary = ''; + + for (const byte of bytes) { + binary += String.fromCodePoint(byte); + } + + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll(/=+$/g, ''); +} + +export function toMatrixID(fname: string, urlPrefix: string): string { + const base64 = toBase64Url(fname); + return urlPrefix + base64; +} + +export function getKlipyMxcUrl(url: string, proxyUrl?: string): string { + if (url.startsWith('mxc://')) return url; + if (!proxyUrl) return url; + if (url.startsWith('https://static.klipy.com/ii/')) { + const id = url.slice('https://static.klipy.com/ii/'.length); + return `mxc://${proxyUrl}/${toMatrixID(id, 'klipy_')}`; + } + return url; +}