chore: improve readability

This commit is contained in:
Su-Yong
2025-10-12 14:28:29 +09:00
parent 4f716d8e0b
commit ffa61687bf
137 changed files with 2625 additions and 2626 deletions

View File

@ -7,12 +7,12 @@ import * as config from '@/config';
export const restart = () => restartInternal();
export const setupAppControls = () => {
ipcMain.on('ytmd:restart', restart);
ipcMain.handle('ytmd:get-downloads-folder', () => app.getPath('downloads'));
ipcMain.on('ytmd:reload', () =>
ipcMain.on('peard:restart', restart);
ipcMain.handle('peard:get-downloads-folder', () => app.getPath('downloads'));
ipcMain.on('peard:reload', () =>
BrowserWindow.getFocusedWindow()?.webContents.loadURL(config.get('url')),
);
ipcMain.handle('ytmd:get-path', (_, ...args: string[]) => path.join(...args));
ipcMain.handle('peard:get-path', (_, ...args: string[]) => path.join(...args));
};
function restartInternal() {

View File

@ -1,8 +1,8 @@
import youtubeMusicTrayIcon from '@assets/youtube-music-tray.png?asset&asarUnpack';
import trayIcon from '@assets/tray.png?asset&asarUnpack';
const promptOptions = {
customStylesheet: 'dark',
icon: youtubeMusicTrayIcon,
icon: trayIcon,
};
export default () => promptOptions;

View File

@ -4,7 +4,7 @@ import { app, type BrowserWindow } from 'electron';
import { getSongControls } from './song-controls';
export const APP_PROTOCOL = 'youtubemusic';
export const APP_PROTOCOL = 'peardesktop';
let protocolHandler: ((cmd: string, ...args: string[]) => void) | undefined;

View File

@ -39,62 +39,62 @@ const parseStringFromArgsType = (args: ArgsType<string>) => {
export const getSongControls = (win: BrowserWindow) => {
return {
// Playback
previous: () => win.webContents.send('ytmd:previous-video'),
next: () => win.webContents.send('ytmd:next-video'),
play: () => win.webContents.send('ytmd:play'),
pause: () => win.webContents.send('ytmd:pause'),
playPause: () => win.webContents.send('ytmd:toggle-play'),
like: () => win.webContents.send('ytmd:update-like', LikeType.Like),
dislike: () => win.webContents.send('ytmd:update-like', LikeType.Dislike),
previous: () => win.webContents.send('peard:previous-video'),
next: () => win.webContents.send('peard:next-video'),
play: () => win.webContents.send('peard:play'),
pause: () => win.webContents.send('peard:pause'),
playPause: () => win.webContents.send('peard:toggle-play'),
like: () => win.webContents.send('peard:update-like', LikeType.Like),
dislike: () => win.webContents.send('peard:update-like', LikeType.Dislike),
seekTo: (seconds: ArgsType<number>) => {
const secondsNumber = parseNumberFromArgsType(seconds);
if (secondsNumber !== null) {
win.webContents.send('ytmd:seek-to', seconds);
win.webContents.send('peard:seek-to', seconds);
}
},
goBack: (seconds: ArgsType<number>) => {
const secondsNumber = parseNumberFromArgsType(seconds);
if (secondsNumber !== null) {
win.webContents.send('ytmd:seek-by', -secondsNumber);
win.webContents.send('peard:seek-by', -secondsNumber);
}
},
goForward: (seconds: ArgsType<number>) => {
const secondsNumber = parseNumberFromArgsType(seconds);
if (secondsNumber !== null) {
win.webContents.send('ytmd:seek-by', seconds);
win.webContents.send('peard:seek-by', seconds);
}
},
requestShuffleInformation: () => {
win.webContents.send('ytmd:get-shuffle');
win.webContents.send('peard:get-shuffle');
},
shuffle: () => win.webContents.send('ytmd:shuffle'),
shuffle: () => win.webContents.send('peard:shuffle'),
switchRepeat: (n: ArgsType<number> = 1) => {
const repeat = parseNumberFromArgsType(n);
if (repeat !== null) {
win.webContents.send('ytmd:switch-repeat', n);
win.webContents.send('peard:switch-repeat', n);
}
},
// General
setVolume: (volume: ArgsType<number>) => {
const volumeNumber = parseNumberFromArgsType(volume);
if (volumeNumber !== null) {
win.webContents.send('ytmd:update-volume', volume);
win.webContents.send('peard:update-volume', volume);
}
},
setFullscreen: (isFullscreen: ArgsType<boolean>) => {
const isFullscreenValue = parseBooleanFromArgsType(isFullscreen);
if (isFullscreenValue !== null) {
win.setFullScreen(isFullscreenValue);
win.webContents.send('ytmd:click-fullscreen-button', isFullscreenValue);
win.webContents.send('peard:click-fullscreen-button', isFullscreenValue);
}
},
requestFullscreenInformation: () => {
win.webContents.send('ytmd:get-fullscreen');
win.webContents.send('peard:get-fullscreen');
},
requestQueueInformation: () => {
win.webContents.send('ytmd:get-queue');
win.webContents.send('peard:get-queue');
},
muteUnmute: () => win.webContents.send('ytmd:toggle-mute'),
muteUnmute: () => win.webContents.send('peard:toggle-mute'),
openSearchBox: () => {
win.webContents.sendInputEvent({
type: 'keyDown',
@ -107,7 +107,7 @@ export const getSongControls = (win: BrowserWindow) => {
if (videoIdValue === null) return;
win.webContents.send(
'ytmd:add-to-queue',
'peard:add-to-queue',
videoIdValue,
queueInsertPosition,
);
@ -120,28 +120,28 @@ export const getSongControls = (win: BrowserWindow) => {
const toIndexValue = parseNumberFromArgsType(toIndex);
if (fromIndexValue === null || toIndexValue === null) return;
win.webContents.send('ytmd:move-in-queue', fromIndexValue, toIndexValue);
win.webContents.send('peard:move-in-queue', fromIndexValue, toIndexValue);
},
removeSongFromQueue: (index: ArgsType<number>) => {
const indexValue = parseNumberFromArgsType(index);
if (indexValue === null) return;
win.webContents.send('ytmd:remove-from-queue', indexValue);
win.webContents.send('peard:remove-from-queue', indexValue);
},
setQueueIndex: (index: ArgsType<number>) => {
const indexValue = parseNumberFromArgsType(index);
if (indexValue === null) return;
win.webContents.send('ytmd:set-queue-index', indexValue);
win.webContents.send('peard:set-queue-index', indexValue);
},
clearQueue: () => win.webContents.send('ytmd:clear-queue'),
clearQueue: () => win.webContents.send('peard:clear-queue'),
search: (query: string, params?: string, continuation?: string) =>
new Promise((resolve) => {
ipcMain.once('ytmd:search-results', (_, result) => {
ipcMain.once('peard:search-results', (_, result) => {
resolve(result as string);
});
win.webContents.send('ytmd:search', query, params, continuation);
win.webContents.send('peard:search', query, params, continuation);
}),
};
};

View File

@ -2,11 +2,11 @@ import { singleton } from './decorators';
import { LikeType, type GetState } from '@/types/datahost-get-state';
import type { YoutubePlayer } from '@/types/youtube-player';
import type { MusicPlayer } from '@/types/music-player';
import type {
AlbumDetails,
PlayerOverlays,
VideoDataChangeValue,
VideoDataChangeValue
} from '@/types/player-api-events';
import type { SongInfo } from './song-info';
@ -18,19 +18,19 @@ let songInfo: SongInfo = {} as SongInfo;
export const getSongInfo = () => songInfo;
window.ipcRenderer.on(
'ytmd:update-song-info',
'peard:update-song-info',
(_, extractedSongInfo: SongInfo) => {
songInfo = extractedSongInfo;
},
}
);
// Used because 'loadeddata' or 'loadedmetadata' weren't firing on song start for some users (https://github.com/th-ch/youtube-music/issues/473)
const srcChangedEvent = new CustomEvent('ytmd:src-changed');
// Used because 'loadeddata' or 'loadedmetadata' weren't firing on song start for some users (https://github.com/pear-devs/pear-music/issues/473)
const srcChangedEvent = new CustomEvent('peard:src-changed');
export const setupSeekedListener = singleton(() => {
document.querySelector('video')?.addEventListener('seeked', (v) => {
if (v.target instanceof HTMLVideoElement) {
window.ipcRenderer.send('ytmd:seeked', v.target.currentTime);
window.ipcRenderer.send('peard:seeked', v.target.currentTime);
}
});
});
@ -40,7 +40,7 @@ export const setupTimeChangedListener = singleton(() => {
for (const mutation of mutations) {
const target = mutation.target as Node & { value: string };
const numberValue = Number(target.value);
window.ipcRenderer.send('ytmd:time-changed', numberValue);
window.ipcRenderer.send('peard:time-changed', numberValue);
songInfo.elapsedSeconds = numberValue;
}
});
@ -52,33 +52,33 @@ export const setupTimeChangedListener = singleton(() => {
export const setupRepeatChangedListener = singleton(() => {
const repeatObserver = new MutationObserver((mutations) => {
// provided by YouTube Music
// provided by Pear Desktop
window.ipcRenderer.send(
'ytmd:repeat-changed',
'peard:repeat-changed',
(
mutations[0].target as Node & {
__dataHost: {
getState: () => GetState;
};
}
).__dataHost.getState().queue.repeatMode,
).__dataHost.getState().queue.repeatMode
);
});
repeatObserver.observe(document.querySelector('#right-controls .repeat')!, {
attributeFilter: ['title'],
attributeFilter: ['title']
});
// Emit the initial value as well; as it's persistent between launches.
// provided by YouTube Music
// provided by Pear Desktop
window.ipcRenderer.send(
'ytmd:repeat-changed',
'peard:repeat-changed',
document
.querySelector<
HTMLElement & {
getState: () => GetState;
}
getState: () => GetState;
}
>('ytmusic-player-bar')
?.getState().queue.repeatMode,
?.getState().queue.repeatMode
);
});
@ -92,41 +92,41 @@ const LIKE_STATUS_ATTRIBUTE = 'like-status';
export const setupLikeChangedListener = singleton(() => {
const likeDislikeObserver = new MutationObserver((mutations) => {
window.ipcRenderer.send(
'ytmd:like-changed',
'peard:like-changed',
mapLikeStatus(
(mutations[0].target as HTMLElement)?.getAttribute?.(
LIKE_STATUS_ATTRIBUTE,
),
),
LIKE_STATUS_ATTRIBUTE
)
)
);
});
const likeButtonRenderer = document.querySelector('#like-button-renderer');
if (likeButtonRenderer) {
likeDislikeObserver.observe(likeButtonRenderer, {
attributes: true,
attributeFilter: [LIKE_STATUS_ATTRIBUTE],
attributeFilter: [LIKE_STATUS_ATTRIBUTE]
});
// Emit the initial value as well; as it's persistent between launches.
window.ipcRenderer.send(
'ytmd:like-changed',
mapLikeStatus(likeButtonRenderer.getAttribute?.(LIKE_STATUS_ATTRIBUTE)),
'peard:like-changed',
mapLikeStatus(likeButtonRenderer.getAttribute?.(LIKE_STATUS_ATTRIBUTE))
);
}
});
export const setupVolumeChangedListener = singleton((api: YoutubePlayer) => {
export const setupVolumeChangedListener = singleton((api: MusicPlayer) => {
document.querySelector('video')?.addEventListener('volumechange', () => {
window.ipcRenderer.send('ytmd:volume-changed', {
window.ipcRenderer.send('peard:volume-changed', {
state: api.getVolume(),
isMuted: api.isMuted(),
isMuted: api.isMuted()
});
});
// Emit the initial value as well; as it's persistent between launches.
window.ipcRenderer.send('ytmd:volume-changed', {
window.ipcRenderer.send('peard:volume-changed', {
state: api.getVolume(),
isMuted: api.isMuted(),
isMuted: api.isMuted()
});
});
@ -134,14 +134,14 @@ export const setupShuffleChangedListener = singleton(() => {
const playerBar = document.querySelector('ytmusic-player-bar');
if (!playerBar) {
window.ipcRenderer.send('ytmd:shuffle-changed-supported', false);
window.ipcRenderer.send('peard:shuffle-changed-supported', false);
return;
}
const observer = new MutationObserver(() => {
window.ipcRenderer.send(
'ytmd:shuffle-changed',
(playerBar?.attributes.getNamedItem('shuffle-on') ?? null) !== null,
'peard:shuffle-changed',
(playerBar?.attributes.getNamedItem('shuffle-on') ?? null) !== null
);
});
@ -149,7 +149,7 @@ export const setupShuffleChangedListener = singleton(() => {
attributes: true,
attributeFilter: ['shuffle-on'],
childList: false,
subtree: false,
subtree: false
});
});
@ -157,15 +157,15 @@ export const setupFullScreenChangedListener = singleton(() => {
const playerBar = document.querySelector('ytmusic-player-bar');
if (!playerBar) {
window.ipcRenderer.send('ytmd:fullscreen-changed-supported', false);
window.ipcRenderer.send('peard:fullscreen-changed-supported', false);
return;
}
const observer = new MutationObserver(() => {
window.ipcRenderer.send(
'ytmd:fullscreen-changed',
'peard:fullscreen-changed',
(playerBar?.attributes.getNamedItem('player-fullscreened') ?? null) !==
null,
null
);
});
@ -173,56 +173,56 @@ export const setupFullScreenChangedListener = singleton(() => {
attributes: true,
attributeFilter: ['player-fullscreened'],
childList: false,
subtree: false,
subtree: false
});
});
export const setupAutoPlayChangedListener = singleton(() => {
const autoplaySlider = document.querySelector<HTMLInputElement>(
'.autoplay > tp-yt-paper-toggle-button',
'.autoplay > tp-yt-paper-toggle-button'
);
const observer = new MutationObserver(() => {
window.ipcRenderer.send('ytmd:autoplay-changed');
window.ipcRenderer.send('peard:autoplay-changed');
});
observer.observe(autoplaySlider!, {
attributes: true,
childList: false,
subtree: false,
subtree: false
});
});
export const setupSongInfo = (api: YoutubePlayer) => {
window.ipcRenderer.on('ytmd:setup-time-changed-listener', () => {
export const setupSongInfo = (api: MusicPlayer) => {
window.ipcRenderer.on('peard:setup-time-changed-listener', () => {
setupTimeChangedListener();
});
window.ipcRenderer.on('ytmd:setup-like-changed-listener', () => {
window.ipcRenderer.on('peard:setup-like-changed-listener', () => {
setupLikeChangedListener();
});
window.ipcRenderer.on('ytmd:setup-repeat-changed-listener', () => {
window.ipcRenderer.on('peard:setup-repeat-changed-listener', () => {
setupRepeatChangedListener();
});
window.ipcRenderer.on('ytmd:setup-volume-changed-listener', () => {
window.ipcRenderer.on('peard:setup-volume-changed-listener', () => {
setupVolumeChangedListener(api);
});
window.ipcRenderer.on('ytmd:setup-shuffle-changed-listener', () => {
window.ipcRenderer.on('peard:setup-shuffle-changed-listener', () => {
setupShuffleChangedListener();
});
window.ipcRenderer.on('ytmd:setup-fullscreen-changed-listener', () => {
window.ipcRenderer.on('peard:setup-fullscreen-changed-listener', () => {
setupFullScreenChangedListener();
});
window.ipcRenderer.on('ytmd:setup-autoplay-changed-listener', () => {
window.ipcRenderer.on('peard:setup-autoplay-changed-listener', () => {
setupAutoPlayChangedListener();
});
window.ipcRenderer.on('ytmd:setup-seeked-listener', () => {
window.ipcRenderer.on('peard:setup-seeked-listener', () => {
setupSeekedListener();
});
@ -231,27 +231,27 @@ export const setupSongInfo = (api: YoutubePlayer) => {
e.target instanceof HTMLVideoElement &&
Math.round(e.target.currentTime) > 0
) {
window.ipcRenderer.send('ytmd:play-or-paused', {
window.ipcRenderer.send('peard:play-or-paused', {
isPaused: status === 'pause',
elapsedSeconds: Math.floor(e.target.currentTime),
elapsedSeconds: Math.floor(e.target.currentTime)
});
}
};
const playPausedHandlers = {
playing: (e: Event) => playPausedHandler(e, 'playing'),
pause: (e: Event) => playPausedHandler(e, 'pause'),
pause: (e: Event) => playPausedHandler(e, 'pause')
};
const videoEventDispatcher = async (
name: string,
videoData: VideoDataChangeValue,
videoData: VideoDataChangeValue
// eslint-disable-next-line @typescript-eslint/require-await
) =>
document.dispatchEvent(
new CustomEvent<VideoDataChanged>('videodatachange', {
detail: { name, videoData },
}),
detail: { name, videoData }
})
);
const waitingEvent = new Set<string>();
@ -311,7 +311,7 @@ export const setupSongInfo = (api: YoutubePlayer) => {
title,
author,
video_id: videoId,
list: playlistId,
list: playlistId
} = api.getVideoData();
const watchNextResponse = api.getWatchNextResponse();
@ -326,7 +326,7 @@ export const setupSongInfo = (api: YoutubePlayer) => {
lengthSeconds: video.duration,
loading: true,
ytmdWatchNextResponse: watchNextResponse,
ytmdWatchNextResponse: watchNextResponse
} satisfies VideoDataChangeValue);
}
}
@ -339,7 +339,7 @@ export const setupSongInfo = (api: YoutubePlayer) => {
if (!videoData.ytmdWatchNextResponse) {
playerOverlay = (
Object.entries(videoData).find(
([, value]) => value && Object.hasOwn(value, 'playerOverlays'),
([, value]) => value && Object.hasOwn(value, 'playerOverlays')
) as [string, AlbumDetails | undefined]
)?.[1]?.playerOverlays;
} else {
@ -347,11 +347,11 @@ export const setupSongInfo = (api: YoutubePlayer) => {
}
data.videoDetails.album =
playerOverlay?.playerOverlayRenderer?.browserMediaSession?.browserMediaSessionRenderer?.album?.runs?.at(
0,
0
)?.text;
data.videoDetails.elapsedSeconds = 0;
data.videoDetails.isPaused = false;
window.ipcRenderer.send('ytmd:video-src-changed', data);
window.ipcRenderer.send('peard:video-src-changed', data);
}
};

View File

@ -16,7 +16,7 @@ export enum MediaType {
*/
OriginalMusicVideo = 'ORIGINAL_MUSIC_VIDEO',
/**
* Normal YouTube video uploaded by a user
* Normal video uploaded by a user
*/
UserGeneratedContent = 'USER_GENERATED_CONTENT',
/**
@ -53,7 +53,7 @@ export const getImage = async (src: string): Promise<Electron.NativeImage> => {
Buffer.from(await result.arrayBuffer()),
);
if (output.isEmpty() && !src.endsWith('.jpg') && src.includes('.jpg')) {
// Fix hidden webp files (https://github.com/th-ch/youtube-music/issues/315)
// Fix hidden webp files (https://github.com/pear-devs/pear-desktop/issues/315)
return getImage(src.slice(0, src.lastIndexOf('.jpg') + 4));
}
@ -96,7 +96,7 @@ const handleData = async (
songInfo.playlistId =
new URL(microformat.urlCanonical).searchParams.get('list') ?? '';
if (microformat.pageOwnerDetails?.externalChannelId) {
songInfo.artistUrl = `https://music.youtube.com/channel/${microformat.pageOwnerDetails.externalChannelId}`;
songInfo.artistUrl = `https://music.\u0079\u006f\u0075\u0074\u0075\u0062\u0065.com/channel/${microformat.pageOwnerDetails.externalChannelId}`;
}
// Used for options.resumeOnStart
config.set('url', microformat.urlCanonical);
@ -164,16 +164,16 @@ const handleData = async (
if (songInfo.imageSrc) songInfo.image = await getImage(songInfo.imageSrc);
win.webContents.send('ytmd:update-song-info', songInfo);
win.webContents.send('peard:update-song-info', songInfo);
}
return songInfo;
};
export enum SongInfoEvent {
VideoSrcChanged = 'ytmd:video-src-changed',
PlayOrPaused = 'ytmd:play-or-paused',
TimeChanged = 'ytmd:time-changed',
VideoSrcChanged = 'peard:video-src-changed',
PlayOrPaused = 'peard:play-or-paused',
TimeChanged = 'peard:time-changed',
}
// This variable will be filled with the callbacks once they register
@ -193,7 +193,7 @@ const registerProvider = (win: BrowserWindow) => {
let songInfo: SongInfo | null = null;
// This will be called when the song-info-front finds a new request with song data
ipcMain.on('ytmd:video-src-changed', async (_, data: GetPlayerResponse) => {
ipcMain.on('peard:video-src-changed', async (_, data: GetPlayerResponse) => {
const tempSongInfo = await dataMutex.runExclusive<SongInfo | null>(
async () => {
songInfo = await handleData(data, win);
@ -208,7 +208,7 @@ const registerProvider = (win: BrowserWindow) => {
}
});
ipcMain.on(
'ytmd:play-or-paused',
'peard:play-or-paused',
async (
_,
{
@ -235,7 +235,7 @@ const registerProvider = (win: BrowserWindow) => {
},
);
ipcMain.on('ytmd:time-changed', async (_, seconds: number) => {
ipcMain.on('peard:time-changed', async (_, seconds: number) => {
const tempSongInfo = await dataMutex.runExclusive<SongInfo | null>(() => {
if (!songInfo) {
return null;