Skip to content

Commit

Permalink
fix: fix callback events
Browse files Browse the repository at this point in the history
  • Loading branch information
JellyBrick committed Nov 3, 2024
1 parent 72eef68 commit b258d97
Show file tree
Hide file tree
Showing 8 changed files with 101 additions and 84 deletions.
38 changes: 22 additions & 16 deletions src/plugins/discord/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { app, dialog, ipcMain } from 'electron';
import { app, dialog } from 'electron';
import { Client as DiscordClient } from '@xhayper/discord-rpc';
import { dev } from 'electron-is';

import { ActivityType, GatewayActivityButton } from 'discord-api-types/v10';

import registerCallback, { type SongInfo } from '@/providers/song-info';
import registerCallback, {
type SongInfo,
SongInfoEvent,
} from '@/providers/song-info';
import { createBackend, LoggerPrefix } from '@/utils';
import { t } from '@/i18n';

Expand Down Expand Up @@ -243,25 +246,28 @@ export const backend = createBackend<

// If the page is ready, register the callback
ctx.window.once('ready-to-show', () => {
let lastSongInfo: SongInfo;
registerCallback((songInfo) => {
lastSongInfo = songInfo;
if (this.config) this.updateActivity(songInfo, this.config);
});
connect();
let lastSent = Date.now();
ipcMain.on('ytmd:time-changed', (_, t: number) => {
const currentTime = Date.now();
// if lastSent is more than 5 seconds ago, send the new time
if (currentTime - lastSent > 5000) {
lastSent = currentTime;
if (lastSongInfo) {
lastSongInfo.elapsedSeconds = t;
if (this.config) this.updateActivity(lastSongInfo, this.config);
registerCallback((songInfo, event) => {
if (event !== SongInfoEvent.TimeChanged) {
info.lastSongInfo = songInfo;
if (this.config) this.updateActivity(songInfo, this.config);
} else {
const currentTime = Date.now();
// if lastSent is more than 5 seconds ago, send the new time
if (currentTime - lastSent > 5000) {
lastSent = currentTime;
if (songInfo) {
info.lastSongInfo = songInfo;
if (this.config) this.updateActivity(songInfo, this.config);
}
}
}
});
connect();
});
ctx.ipc.on('ytmd:player-api-loaded', () =>
ctx.ipc.send('ytmd:setup-time-changed-listener'),
);
app.on('window-all-closed', clear);
},
stop() {
Expand Down
21 changes: 14 additions & 7 deletions src/plugins/downloader/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@ import registerCallback, {
getImage,
MediaType,
type SongInfo,
SongInfoEvent,
} from '@/providers/song-info';
import { getNetFetchAsFetch } from '@/plugins/utils/main';

import { t } from '@/i18n';

import { YoutubeFormatList, type Preset, DefaultPresetList } from '../types';
import { DefaultPresetList, type Preset, YoutubeFormatList } from '../types';

import type { DownloaderPluginConfig } from '../index';

Expand Down Expand Up @@ -68,7 +69,12 @@ const sendError = (error: Error, source?: string) => {
sendFeedback_(win); // Reset feedback

const songNameMessage = source ? `\nin ${source}` : '';
const cause = error.cause ? `\n\n${String(error.cause)}` : '';
const cause = error.cause
? `\n\n${
// eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions
error.cause instanceof Error ? error.cause.toString() : error.cause
}`
: '';
const message = `${error.toString()}${songNameMessage}${cause}`;

console.error(message);
Expand Down Expand Up @@ -174,7 +180,12 @@ function downloadSongOnFinishSetup({

const defaultDownloadFolder = app.getPath('downloads');

registerCallback((songInfo: SongInfo) => {
registerCallback((songInfo: SongInfo, event) => {
if (event === SongInfoEvent.TimeChanged) {
const elapsedSeconds = songInfo.elapsedSeconds ?? 0;
if (elapsedSeconds > time) time = elapsedSeconds;
return;
}
if (
!songInfo.isPaused &&
songInfo.url !== currentUrl &&
Expand Down Expand Up @@ -213,10 +224,6 @@ function downloadSongOnFinishSetup({
ipcMain.on('ytmd:player-api-loaded', () => {
ipc.send('ytmd:setup-time-changed-listener');
});

ipcMain.on('ytmd:time-changed', (_, t: number) => {
if (t > time) time = t;
});
}

async function downloadSongUnsafe(
Expand Down
6 changes: 5 additions & 1 deletion src/plugins/lumiastream/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default createPlugin({
config: {
enabled: false,
},
backend() {
backend({ ipc }) {
const secToMilisec = (t?: number) =>
t ? Math.round(Number(t) * 1e3) : undefined;
const previousStatePaused = null;
Expand Down Expand Up @@ -65,6 +65,10 @@ export default createPlugin({
});
};

ipc.on('ytmd:player-api-loaded', () =>
ipc.send('ytmd:setup-time-changed-listener'),
);

registerCallback((songInfo) => {
if (!songInfo.title && !songInfo.artist) {
return;
Expand Down
14 changes: 8 additions & 6 deletions src/plugins/notifications/interactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import previousIcon from '@assets/media-icons-black/previous.png?asset&asarUnpac
import { notificationImage, secondsToMinutes, ToastStyles } from './utils';

import getSongControls from '@/providers/song-controls';
import registerCallback, { SongInfo } from '@/providers/song-info';
import registerCallback, {
type SongInfo,
SongInfoEvent,
} from '@/providers/song-info';
import { changeProtocolHandler } from '@/providers/protocol-handler';
import { setTrayOnClick, setTrayOnDoubleClick } from '@/tray';
import { mediaIcons } from '@/types/media-icons';
Expand Down Expand Up @@ -258,15 +261,14 @@ export default (
let currentSeconds = 0;
on('ytmd:player-api-loaded', () => send('ytmd:setup-time-changed-listener'));

on('ytmd:time-changed', (t: number) => {
currentSeconds = t;
});

let savedSongInfo: SongInfo;
let lastUrl: string | undefined;

// Register songInfoCallback
registerCallback((songInfo) => {
registerCallback((songInfo, event) => {
if (event === SongInfoEvent.TimeChanged) {
currentSeconds = songInfo.elapsedSeconds ?? 0;
}
if (!songInfo.artist && !songInfo.title) {
return;
}
Expand Down
29 changes: 16 additions & 13 deletions src/plugins/shortcuts/mpris.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { BrowserWindow, ipcMain } from 'electron';

import MprisPlayer, {
Track,
LoopStatus,
type PlayBackStatus,
type PlayerOptions,
PLAYBACK_STATUS_STOPPED,
PLAYBACK_STATUS_PAUSED,
PLAYBACK_STATUS_PLAYING,
LOOP_STATUS_NONE,
LOOP_STATUS_PLAYLIST,
LOOP_STATUS_TRACK,
LoopStatus,
PLAYBACK_STATUS_PAUSED,
PLAYBACK_STATUS_PLAYING,
PLAYBACK_STATUS_STOPPED,
type PlayBackStatus,
type PlayerOptions,
type Position,
Track,
} from '@jellybrick/mpris-service';

import registerCallback, { type SongInfo } from '@/providers/song-info';
import registerCallback, {
type SongInfo,
SongInfoEvent,
} from '@/providers/song-info';
import getSongControls from '@/providers/song-controls';
import config from '@/config';
import { LoggerPrefix } from '@/utils';
Expand Down Expand Up @@ -134,10 +137,6 @@ function registerMPRIS(win: BrowserWindow) {
player.seeked(secToMicro(t));
});

ipcMain.on('ytmd:time-changed', (_, t: number) => {
player.setPosition(secToMicro(t));
});

ipcMain.on('ytmd:repeat-changed', (_, mode: RepeatMode) => {
switch (mode) {
case 'NONE': {
Expand Down Expand Up @@ -319,7 +318,11 @@ function registerMPRIS(win: BrowserWindow) {
}
});

registerCallback((songInfo: SongInfo) => {
registerCallback((songInfo: SongInfo, event) => {
if (event === SongInfoEvent.TimeChanged) {
player.setPosition(secToMicro(songInfo.elapsedSeconds ?? 0));
return;
}
if (player) {
const data: Track = {
'mpris:length': secToMicro(songInfo.songDuration),
Expand Down
17 changes: 11 additions & 6 deletions src/plugins/taskbar-mediacontrol/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import previousIcon from '@assets/media-icons-black/previous.png?asset&asarUnpac

import { createPlugin } from '@/utils';
import getSongControls from '@/providers/song-controls';
import registerCallback, { type SongInfo } from '@/providers/song-info';
import registerCallback, {
type SongInfo,
SongInfoEvent,
} from '@/providers/song-info';
import { mediaIcons } from '@/types/media-icons';
import { t } from '@/i18n';

Expand Down Expand Up @@ -102,11 +105,13 @@ export default createPlugin({
]);
};

registerCallback((songInfo) => {
// Update currentsonginfo for win.on('show')
currentSongInfo = songInfo;
// Update thumbar
setThumbar(songInfo);
registerCallback((songInfo, event) => {
if (event !== SongInfoEvent.TimeChanged) {
// Update currentsonginfo for win.on('show')
currentSongInfo = songInfo;
// Update thumbar
setThumbar(songInfo);
}
});

// Need to set thumbar again after win.show
Expand Down
43 changes: 12 additions & 31 deletions src/plugins/tuna-obs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,6 @@ export default createPlugin({
},
backend: {
liteMode: false,
data: {
cover: '',
cover_url: '',
title: '',
artists: [] as string[],
status: '',
progress: 0,
duration: 0,
album_url: '',
album: undefined,
url: '',
} as Data,
start({ ipc }) {
const secToMilisec = (t: number) => Math.round(Number(t) * 1e3);

Expand Down Expand Up @@ -85,31 +73,24 @@ export default createPlugin({
ipc.on('ytmd:player-api-loaded', () =>
ipc.send('ytmd:setup-time-changed-listener'),
);
ipc.on('ytmd:time-changed', (t: number) => {
if (!this.data.title) {
return;
}

this.data.progress = secToMilisec(t);
post(this.data);
});

registerCallback((songInfo) => {
if (!songInfo.title && !songInfo.artist) {
return;
}

this.data.duration = secToMilisec(songInfo.songDuration);
this.data.progress = secToMilisec(songInfo.elapsedSeconds ?? 0);
this.data.cover = songInfo.imageSrc ?? '';
this.data.cover_url = songInfo.imageSrc ?? '';
this.data.album_url = songInfo.imageSrc ?? '';
this.data.title = songInfo.title;
this.data.artists = [songInfo.artist];
this.data.status = songInfo.isPaused ? 'stopped' : 'playing';
this.data.album = songInfo.album;
this.data.url = songInfo.url ?? '';
post(this.data);
post({
duration: secToMilisec(songInfo.songDuration),
progress: secToMilisec(songInfo.elapsedSeconds ?? 0),
cover: songInfo.imageSrc ?? '',
cover_url: songInfo.imageSrc ?? '',
album_url: songInfo.imageSrc ?? '',
title: songInfo.title,
artists: [songInfo.artist],
status: songInfo.isPaused ? 'stopped' : 'playing',
album: songInfo.album,
url: songInfo.url ?? '',
});
});
},
},
Expand Down
17 changes: 13 additions & 4 deletions src/providers/song-info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,17 @@ const handleData = async (
return songInfo;
};

export enum SongInfoEvent {
VideoSrcChanged = 'ytmd:video-src-changed',
PlayOrPaused = 'ytmd:play-or-paused',
TimeChanged = 'ytmd:time-changed',
}

// This variable will be filled with the callbacks once they register
export type SongInfoCallback = (songInfo: SongInfo, event?: string) => void;
export type SongInfoCallback = (
songInfo: SongInfo,
event: SongInfoEvent,
) => void;
const callbacks: Set<SongInfoCallback> = new Set();

// This function will allow plugins to register callback that will be triggered when data changes
Expand All @@ -173,7 +182,7 @@ const registerProvider = (win: BrowserWindow) => {

if (tempSongInfo) {
for (const c of callbacks) {
c(tempSongInfo, 'ytmd:video-src-changed');
c(tempSongInfo, SongInfoEvent.VideoSrcChanged);
}
}
});
Expand All @@ -199,7 +208,7 @@ const registerProvider = (win: BrowserWindow) => {

if (tempSongInfo) {
for (const c of callbacks) {
c(tempSongInfo, 'ytmd:play-or-paused');
c(tempSongInfo, SongInfoEvent.PlayOrPaused);
}
}
},
Expand All @@ -218,7 +227,7 @@ const registerProvider = (win: BrowserWindow) => {

if (tempSongInfo) {
for (const c of callbacks) {
c(tempSongInfo, 'ytmd:time-changed');
c(tempSongInfo, SongInfoEvent.TimeChanged);
}
}
});
Expand Down

0 comments on commit b258d97

Please sign in to comment.