diff --git a/src/app/paarrot-api.ts b/src/app/paarrot-api.ts index d342bf3d..d22ea8de 100644 --- a/src/app/paarrot-api.ts +++ b/src/app/paarrot-api.ts @@ -7,7 +7,7 @@ * To use this, import and call initPaarrotAPI() early in your app initialization. */ -import { MatrixClient } from 'matrix-js-sdk'; +import { MatrixClient, Room } from 'matrix-js-sdk'; import { getHomeRoomPath, getDirectRoomPath, getSpaceRoomPath } from './pages/pathUtils'; import { getCanonicalAliasOrRoomId } from './utils/matrix'; import { getCallService } from './features/call/useCall'; @@ -31,11 +31,7 @@ let navigateFunction: ((path: string) => void) | null = null; */ let isInitialized = false; -/** - * @param {any} room - * @returns {boolean} - */ -function isSpaceLikeRoom(room: any): boolean { +function isSpaceLikeRoom(room: Room): boolean { if (!room) return false; if (typeof room.isSpaceRoom === 'function' && room.isSpaceRoom()) return true; const roomKindEvent = room.currentState?.getStateEvents?.(StateEvent.PaarrotRoomKind, ''); @@ -237,7 +233,7 @@ async function setDeafen(matrixClient: MatrixClient, deafened: boolean) { /** * Change to a different room/channel */ -async function changeChannel(matrixClient: any, roomId: string) { +async function changeChannel(matrixClient: MatrixClient, roomId: string) { const room = matrixClient?.getRoom(roomId); if (!room) { throw new Error(`Room not found: ${roomId}`); @@ -280,12 +276,12 @@ async function changeChannel(matrixClient: any, roomId: string) { /** * Get list of rooms/channels */ -async function getChannels(matrixClient: any) { +async function getChannels(matrixClient: MatrixClient) { const rooms = matrixClient?.getRooms() || []; return rooms - .filter((room: any) => !isSpaceLikeRoom(room)) - .map((room: any) => { + .filter((room) => !isSpaceLikeRoom(room)) + .map((room) => { // Extract server domain from roomId (!localpart:domain.tld) const serverMatch = room.roomId.match(/:(.+)$/); const server = serverMatch ? serverMatch[1] : null; @@ -298,7 +294,7 @@ async function getChannels(matrixClient: any) { avatar: room.getMxcAvatarUrl() || null, }; }) - .sort((a: any, b: any) => a.name.localeCompare(b.name)); + .sort((a, b) => a.name.localeCompare(b.name)); } /** @@ -326,7 +322,7 @@ async function sendMessage(matrixClient: any, roomId: string, message: string) { /** * Send a message to the current room */ -async function sendMessageCurrent(matrixClient: any, message: string) { +async function sendMessageCurrent(matrixClient: MatrixClient, message: string) { const currentRoomId = getCurrentRoomId(); if (!currentRoomId) { throw new Error('No room currently active'); @@ -338,7 +334,7 @@ async function sendMessageCurrent(matrixClient: any, message: string) { /** * Get information about the current room */ -async function getCurrentRoom(matrixClient: any) { +async function getCurrentRoom(matrixClient: MatrixClient) { const currentRoomId = getCurrentRoomId(); if (!currentRoomId) { throw new Error('No room currently active'); @@ -379,7 +375,7 @@ type ApiMessage = { body: string; }; -function isDirectRoom(room: any): boolean { +function isDirectRoom(room: Room): boolean { return room?.guessDMUserId?.() !== null; } @@ -395,7 +391,7 @@ function parseMessageLimit(limit?: number | string): number { * Collect recent room messages from the local live timeline (newest last). * Skips reactions, edits, and redacted events. */ -function collectRecentMessages(room: any, limit: number): ApiMessage[] { +function collectRecentMessages(room: Room, limit: number): ApiMessage[] { const liveEvents = room.getLiveTimeline?.()?.getEvents?.() ?? []; const isDirect = isDirectRoom(room); const { roomId } = room; @@ -451,16 +447,16 @@ function collectRecentMessages(room: any, limit: number): ApiMessage[] { return messages.reverse(); } -function getRoomsForScope(matrixClient: any, scope: MessageScope) { +function getRoomsForScope(matrixClient: MatrixClient, scope: MessageScope) { const rooms = (matrixClient?.getRooms?.() || []).filter( - (room: any) => !isSpaceLikeRoom(room) && room.getMyMembership?.() === 'join', + (room) => !isSpaceLikeRoom(room) && room.getMyMembership?.() === 'join', ); if (scope === 'groups') { - return rooms.filter((room: any) => !isDirectRoom(room)); + return rooms.filter((room) => !isDirectRoom(room)); } if (scope === 'dms') { - return rooms.filter((room: any) => isDirectRoom(room)); + return rooms.filter((room) => isDirectRoom(room)); } return rooms; } @@ -468,7 +464,11 @@ function getRoomsForScope(matrixClient: any, scope: MessageScope) { /** * Get recent messages across groups, DMs, or both (combined). */ -async function getMessagesByScope(matrixClient: any, scope: MessageScope, limit?: number | string) { +async function getMessagesByScope( + matrixClient: MatrixClient, + scope: MessageScope, + limit?: number | string, +) { const limitNum = parseMessageLimit(limit); const rooms = getRoomsForScope(matrixClient, scope); @@ -493,7 +493,7 @@ async function getMessagesByScope(matrixClient: any, scope: MessageScope, limit? * List unread conversations across groups, DMs, or both (combined). * Uses the same unread rules as the app UI (notification counts + read receipts, muted excluded). */ -async function getUnreadsByScope(matrixClient: any, scope: MessageScope) { +async function getUnreadsByScope(matrixClient: MatrixClient, scope: MessageScope) { const rooms = getRoomsForScope(matrixClient, scope); const unreads: Array<{ roomId: string; @@ -662,13 +662,13 @@ export function initPaarrotAPI(matrixClient: MatrixClient) { }); console.log('Paarrot API: Action completed successfully:', action.action); - } catch (error: any) { + } catch (error) { console.error('Paarrot API: Action failed:', action.action, error); // Send error response back (window as any).electron.api.sendResponse(action.responseChannel, { success: false, - error: error.message || 'Unknown error', + error: error instanceof Error ? error.message : 'Unknown error', }); } }, diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index ca73f49c..46f99fe7 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -1,3 +1,4 @@ +import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { useAtomValue } from 'jotai'; import React, { ReactNode, useCallback, useEffect, useRef, useState, Fragment } from 'react'; import { useNavigate } from 'react-router-dom'; @@ -137,10 +138,11 @@ function InviteNotifications() { (count: number) => { const body = `You have ${count} new invitation request.`; const invitesPath = getInboxInvitesPath(); + const { electron } = window; // Flash taskbar icon for desktop notifications (only visible when window is not focused) - if (isElectron() && (window as any).electron?.window?.flashFrame) { - (window as any).electron.window + if (isElectron() && electron?.window?.flashFrame) { + electron.window .flashFrame(true) .then((result: { success: boolean }) => { console.log('[InviteNotifications] flashFrame result:', result); @@ -172,8 +174,8 @@ function InviteNotifications() { if (!window.closed) navigate(invitesPath); noti.close(); // Stop flashing when user clicks notification - if ((window as any).electron?.window?.flashFrame) { - (window as any).electron.window.flashFrame(false); + if (electron?.window?.flashFrame) { + electron.window.flashFrame(false); } }; } @@ -183,12 +185,13 @@ function InviteNotifications() { const playSound = useCallback(() => { console.log('[InviteNotifications] playSound called, isElectron:', isElectron()); - if (isElectron() && (window as any).electron?.audio?.playNotificationSound) { + const { electron } = window; + if (isElectron() && electron?.audio?.playNotificationSound) { console.log('[InviteNotifications] Using Electron audio API'); - (window as any).electron.audio + electron.audio .playNotificationSound('invite') - .then((result: any) => console.log('[InviteNotifications] Sound result:', result)) - .catch((err: any) => console.error('[InviteNotifications] Sound error:', err)); + .then((result) => console.log('[InviteNotifications] Sound result:', result)) + .catch((err) => console.error('[InviteNotifications] Sound error:', err)); } else { console.log('[InviteNotifications] Using HTML5 Audio fallback'); new Audio('./sound/invite.ogg').play().catch((err) => { @@ -252,6 +255,7 @@ function MessageNotifications() { }) => { const notificationTitle = username; const notificationBody = messageBody || 'New message'; + const { electron } = window; /** Replicates TitleBar click navigation logic */ const navigateToRoom = () => { @@ -277,8 +281,8 @@ function MessageNotifications() { // Flash taskbar icon for desktop notifications (only visible when window is not focused) console.log('[Notifications] Attempting flashFrame'); - if (isElectron() && (window as any).electron?.window?.flashFrame) { - (window as any).electron.window + if (isElectron() && electron?.window?.flashFrame) { + electron.window .flashFrame(true) .then((result: { success: boolean }) => { console.log('[Notifications] flashFrame result:', result); @@ -316,13 +320,13 @@ function MessageNotifications() { noti.onclick = () => { // Tell main process to bring window to front - (window as any).electron?.window?.focus(); + electron?.window?.focus(); if (!window.closed) navigateToRoom(); noti.close(); notifRef.current = undefined; // Stop flashing when user clicks notification - if ((window as any).electron?.window?.flashFrame) { - (window as any).electron.window.flashFrame(false); + if (electron?.window?.flashFrame) { + electron.window.flashFrame(false); } }; @@ -335,12 +339,13 @@ function MessageNotifications() { const playSound = useCallback(() => { console.log('[MessageNotifications] playSound called, isElectron:', isElectron()); - if (isElectron() && (window as any).electron?.audio?.playNotificationSound) { + const { electron } = window; + if (isElectron() && electron?.audio?.playNotificationSound) { console.log('[MessageNotifications] Using Electron audio API'); - (window as any).electron.audio + electron.audio .playNotificationSound('message') - .then((result: any) => console.log('[MessageNotifications] Sound result:', result)) - .catch((err: any) => console.error('[MessageNotifications] Sound error:', err)); + .then((result) => console.log('[MessageNotifications] Sound result:', result)) + .catch((err) => console.error('[MessageNotifications] Sound error:', err)); } else { console.log('[MessageNotifications] Using HTML5 Audio fallback'); new Audio('./sound/notification.ogg').play().catch((err) => { @@ -503,18 +508,19 @@ function PaarrotAPIInitializer() { */ function TaskbarFlashStopper() { useEffect(() => { + const { electron } = window; // Log what's available on mount - console.log('[TaskbarFlashStopper] window.electron:', (window as any).electron); + console.log('[TaskbarFlashStopper] window.electron:', electron); console.log('[TaskbarFlashStopper] Available APIs:', { - hasWindow: !!(window as any).electron?.window, - hasFlashFrame: !!(window as any).electron?.window?.flashFrame, - hasAudio: !!(window as any).electron?.audio, - hasPlaySound: !!(window as any).electron?.audio?.playNotificationSound, + hasWindow: !!electron?.window, + hasFlashFrame: !!electron?.window?.flashFrame, + hasAudio: !!electron?.audio, + hasPlaySound: !!electron?.audio?.playNotificationSound, }); const handleFocus = () => { - if ((window as any).electron?.window?.flashFrame) { - (window as any).electron.window.flashFrame(false); + if (electron?.window?.flashFrame) { + electron.window.flashFrame(false); } }; @@ -558,7 +564,7 @@ function AndroidShareIntentHandler() { const originalFile = await materializeSharedFile(sharedFile, share.receivedAt); let fileToUpload = originalFile; - let encInfo: any; + let encInfo: EncryptedAttachmentInfo | undefined; if (room.hasEncryptionStateEvent()) { const encrypted = await encryptFile(originalFile); diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index bce8d941..dd3f4e25 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -181,7 +181,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { // Since we can't directly intercept, we'll use a MutationObserver-style approach // by checking for repeated key upload failures - const checkKeyConflict = (args: any[]): boolean => { + const checkKeyConflict = (args: unknown[]): boolean => { const message = args.map((a) => String(a)).join(' '); return keyConflictPattern.test(message); }; @@ -190,7 +190,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { const originalError = console.error; const originalWarn = console.warn; - const errorHandler = (...args: any[]) => { + const errorHandler = (...args: unknown[]) => { if (checkKeyConflict(args)) { keyConflictCount += 1; console.log( @@ -236,7 +236,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { }; console.error = errorHandler; - console.warn = (...args: any[]) => { + console.warn = (...args: unknown[]) => { if (checkKeyConflict(args)) { keyConflictCount += 1; } @@ -332,9 +332,9 @@ export const initClient = async (session: Session): Promise => { console.log('[initMatrix] Registered global MatrixClient for auth utils'); return mx; - } catch (error: any) { + } catch (error) { // Handle crypto store account mismatch error - if (error && error.message && error.message.includes("account in the store doesn't match")) { + if (error instanceof Error && error.message.includes("account in the store doesn't match")) { console.error('[initMatrix] ❌ Crypto store account mismatch detected!'); console.error('[initMatrix] Error details:', error.message); console.error('[initMatrix] Expected account:', session.userId, session.deviceId); @@ -433,7 +433,7 @@ export const logoutClient = async (mx: MatrixClient) => { const currentUserId = getLocalStorageItem('currentSessionUserId', undefined); // Remove the current session - const remainingSessions = allSessions.filter((s: any) => s.userId !== userId); + const remainingSessions = allSessions.filter((s: Session) => s.userId !== userId); setLocalStorageItem('matrixSessions', remainingSessions); // If we're logging out the current session and there are other sessions, switch to the first one diff --git a/src/ext.d.ts b/src/ext.d.ts index a558aea3..01ba4c4d 100644 --- a/src/ext.d.ts +++ b/src/ext.d.ts @@ -28,6 +28,13 @@ interface PluginAPI { interface ElectronAPI { platform?: string; arch?: string; + window?: { + focus: () => Promise; + flashFrame: (flash?: boolean) => Promise<{ success: boolean; error?: string }>; + }; + audio?: { + playNotificationSound: (soundType?: string) => Promise<{ success: boolean; error?: string }>; + }; clipboard?: { writeText: (text: string) => void; };