Merged main branch and updates win.ts with some dumb stuff that still hasn't fixed it
This commit is contained in:
parent
8e1d2dc96b
commit
57c7002b25
59 changed files with 16275 additions and 1626 deletions
|
@ -1,138 +0,0 @@
|
|||
const {app} = require('electron'),
|
||||
DiscordRPC = require('discord-rpc')
|
||||
|
||||
module.exports = {
|
||||
|
||||
/**
|
||||
* Connects to Discord RPC
|
||||
* @param {string} clientId
|
||||
*/
|
||||
connect: function (clientId) {
|
||||
app.discord = {isConnected: false};
|
||||
if (app.cfg.get('general.discord_rpc') == 0) return;
|
||||
|
||||
DiscordRPC.register(clientId) // Apparently needed for ask to join, join, spectate etc.
|
||||
const client = new DiscordRPC.Client({transport: "ipc"});
|
||||
app.discord = Object.assign(client, {error: false, activityCache: null, isConnected: false});
|
||||
|
||||
// Login to Discord
|
||||
app.discord.login({clientId})
|
||||
.then(() => {
|
||||
app.discord.isConnected = true;
|
||||
})
|
||||
.catch((e) => console.error(`[DiscordRPC][connect] ${e}`));
|
||||
|
||||
app.discord.on('ready', () => {
|
||||
console.log(`[DiscordRPC][connect] Successfully Connected to Discord. Authed for user: ${client.user.username} (${client.user.id})`);
|
||||
|
||||
if (app.discord.activityCache) {
|
||||
client.setActivity(app.discord.activityCache).catch((e) => console.error(e));
|
||||
app.discord.activityCache = null;
|
||||
}
|
||||
})
|
||||
|
||||
// Handles Errors
|
||||
app.discord.on('error', err => {
|
||||
console.error(`[DiscordRPC] ${err}`);
|
||||
this.disconnect()
|
||||
app.discord.isConnected = false;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Disconnects from Discord RPC
|
||||
*/
|
||||
disconnect: function () {
|
||||
if (app.cfg.get('general.discord_rpc') == 0 || !app.discord.isConnected) return;
|
||||
|
||||
try {
|
||||
app.discord.destroy().then(() => {
|
||||
app.discord.isConnected = false;
|
||||
console.log('[DiscordRPC][disconnect] Disconnected from discord.')
|
||||
}).catch((e) => console.error(`[DiscordRPC][disconnect] ${e}`));
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the activity of the client
|
||||
* @param {object} attributes
|
||||
*/
|
||||
updateActivity: function (attributes) {
|
||||
if (app.cfg.get('general.discord_rpc') == 0) return;
|
||||
|
||||
if (!app.discord.isConnected) {
|
||||
this.connect()
|
||||
}
|
||||
|
||||
if (!app.discord.isConnected) return;
|
||||
|
||||
// console.log('[DiscordRPC][updateActivity] Updating Discord Activity.')
|
||||
|
||||
const listenURL = `https://applemusicelectron.com/p?id=${attributes.playParams.id}`
|
||||
//console.log(attributes)
|
||||
let ActivityObject = {
|
||||
details: attributes.name,
|
||||
state: `by ${attributes.artistName}`,
|
||||
startTimestamp: attributes.startTime,
|
||||
endTimestamp: attributes.endTime,
|
||||
largeImageKey: (attributes.artwork.url.replace('{w}', '512').replace('{h}', '512')) ?? 'cider',
|
||||
largeImageText: attributes.albumName,
|
||||
smallImageKey: (attributes.status ? 'play' : 'pause'),
|
||||
smallImageText: (attributes.status ? 'Playing' : 'Paused'),
|
||||
instance: true,
|
||||
buttons: [
|
||||
{label: "Listen on Cider", url: listenURL},
|
||||
]
|
||||
};
|
||||
if (ActivityObject.largeImageKey == "" || ActivityObject.largeImageKey == null) {
|
||||
ActivityObject.largeImageKey = (app.cfg.get("general.discord_rpc") == 1) ? "cider" : "logo"
|
||||
}
|
||||
// console.log(`[LinkHandler] Listening URL has been set to: ${listenURL}`);
|
||||
|
||||
if (app.cfg.get('general.discordClearActivityOnPause') == 1) {
|
||||
delete ActivityObject.smallImageKey
|
||||
delete ActivityObject.smallImageText
|
||||
}
|
||||
|
||||
// Check all the values work
|
||||
if (!((new Date(attributes.endTime)).getTime() > 0)) {
|
||||
delete ActivityObject.startTimestamp
|
||||
delete ActivityObject.endTimestamp
|
||||
}
|
||||
if (!attributes.artistName) {
|
||||
delete ActivityObject.state
|
||||
}
|
||||
if (!ActivityObject.largeImageText || ActivityObject.largeImageText.length < 2) {
|
||||
delete ActivityObject.largeImageText
|
||||
}
|
||||
if (ActivityObject.details.length > 128) {
|
||||
AcitivityObject.details = ActivityObject.details.substring(0, 125) + '...'
|
||||
}
|
||||
|
||||
// Clear if if needed
|
||||
if (!attributes.status) {
|
||||
if (app.cfg.get('general.discordClearActivityOnPause') == 1) {
|
||||
app.discord.clearActivity().catch((e) => console.error(`[DiscordRPC][clearActivity] ${e}`));
|
||||
ActivityObject = null
|
||||
} else
|
||||
{
|
||||
delete ActivityObject.startTimestamp
|
||||
delete ActivityObject.endTimestamp
|
||||
ActivityObject.smallImageKey = 'pause'
|
||||
ActivityObject.smallImageText = 'Paused'
|
||||
}
|
||||
}
|
||||
|
||||
if (ActivityObject) {
|
||||
try {
|
||||
// console.log(`[DiscordRPC][setActivity] Setting activity to ${JSON.stringify(ActivityObject)}`);
|
||||
app.discord.setActivity(ActivityObject)
|
||||
} catch (err) {
|
||||
console.error(`[DiscordRPC][setActivity] ${err}`)
|
||||
}
|
||||
|
||||
}
|
||||
},
|
||||
}
|
|
@ -1,153 +0,0 @@
|
|||
const {app, Notification} = require('electron'),
|
||||
fs = require('fs'),
|
||||
{resolve} = require('path'),
|
||||
sessionPath = resolve(app.getPath('userData'), 'session.json'),
|
||||
apiCredentials = require('../../../resources/lfmApiCredentials.json'),
|
||||
LastfmAPI = require('lastfmapi');
|
||||
|
||||
const lfm = {
|
||||
authenticateFromFile: function () {
|
||||
let sessionData = require(sessionPath)
|
||||
console.log("[LastFM][authenticateFromFile] Logging in with Session Info.")
|
||||
app.lastfm.setSessionCredentials(sessionData.name, sessionData.key)
|
||||
console.log("[LastFM][authenticateFromFile] Logged in.")
|
||||
},
|
||||
|
||||
authenticate: function () {
|
||||
if (app.cfg.get('lastfm.auth_token')) {
|
||||
app.cfg.set('lastfm.enabled', true);
|
||||
}
|
||||
|
||||
if (!app.cfg.get('lastfm.enabled') || !app.cfg.get('lastfm.auth_token')) {
|
||||
app.cfg.set('lastfm.enabled', false);
|
||||
return
|
||||
}
|
||||
|
||||
const lfmAPI = new LastfmAPI({
|
||||
'api_key': apiCredentials.key,
|
||||
'secret': apiCredentials.secret
|
||||
});
|
||||
|
||||
app.lastfm = Object.assign(lfmAPI, {cachedAttributes: false, cachedNowPlayingAttributes: false});
|
||||
|
||||
fs.stat(sessionPath, function (err) {
|
||||
if (err) {
|
||||
console.error("[LastFM][Session] Session file couldn't be opened or doesn't exist,", err)
|
||||
console.log("[LastFM][Auth] Beginning authentication from configuration")
|
||||
app.lastfm.authenticate(app.cfg.get('lastfm.auth_token'), function (err, session) {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log("[LastFM] Successfully obtained LastFM session info,", session); // {"name": "LASTFM_USERNAME", "key": "THE_USER_SESSION_KEY"}
|
||||
console.log("[LastFM] Saving session info to disk.")
|
||||
let tempData = JSON.stringify(session)
|
||||
fs.writeFile(sessionPath, tempData, (err) => {
|
||||
if (err)
|
||||
console.log("[LastFM][fs]", err)
|
||||
else {
|
||||
console.log("[LastFM][fs] File was written successfully.")
|
||||
lfm.authenticateFromFile()
|
||||
new Notification({
|
||||
title: app.getName(),
|
||||
body: "Successfully logged into LastFM using Authentication Key."
|
||||
}).show()
|
||||
}
|
||||
})
|
||||
});
|
||||
} else {
|
||||
lfm.authenticateFromFile()
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
scrobbleSong: async function (attributes) {
|
||||
await new Promise(resolve => setTimeout(resolve, app.cfg.get('lastfm.scrobble_after') * 1000));
|
||||
const currentAttributes = app.media;
|
||||
|
||||
if (!app.lastfm || app.lastfm.cachedAttributes === attributes ) {
|
||||
return
|
||||
}
|
||||
|
||||
if (app.lastfm.cachedAttributes) {
|
||||
if (app.lastfm.cachedAttributes.playParams.id === attributes.playParams.id) return;
|
||||
}
|
||||
|
||||
if (currentAttributes.status && currentAttributes === attributes) {
|
||||
if (fs.existsSync(sessionPath)) {
|
||||
// Scrobble playing song.
|
||||
if (attributes.status === true) {
|
||||
app.lastfm.track.scrobble({
|
||||
'artist': lfm.filterArtistName(attributes.artistName),
|
||||
'track': attributes.name,
|
||||
'album': attributes.albumName,
|
||||
'albumArtist': this.filterArtistName(attributes.artistName),
|
||||
'timestamp': new Date().getTime() / 1000
|
||||
}, function (err, scrobbled) {
|
||||
if (err) {
|
||||
return console.error('[LastFM] An error occurred while scrobbling', err);
|
||||
}
|
||||
|
||||
console.log('[LastFM] Successfully scrobbled: ', scrobbled);
|
||||
});
|
||||
app.lastfm.cachedAttributes = attributes
|
||||
}
|
||||
} else {
|
||||
this.authenticate();
|
||||
}
|
||||
} else {
|
||||
return console.log('[LastFM] Did not add ', attributes.name , '-' , lfm.filterArtistName(attributes.artistName), 'because now playing a other song.');
|
||||
}
|
||||
},
|
||||
|
||||
filterArtistName: function (artist) {
|
||||
if (!app.cfg.get('lastfm.enabledRemoveFeaturingArtists')) return artist;
|
||||
|
||||
artist = artist.split(' ');
|
||||
if (artist.includes('&')) {
|
||||
artist.length = artist.indexOf('&');
|
||||
}
|
||||
if (artist.includes('and')) {
|
||||
artist.length = artist.indexOf('and');
|
||||
}
|
||||
artist = artist.join(' ');
|
||||
if (artist.includes(',')) {
|
||||
artist = artist.split(',')
|
||||
artist = artist[0]
|
||||
}
|
||||
return artist.charAt(0).toUpperCase() + artist.slice(1);
|
||||
},
|
||||
|
||||
updateNowPlayingSong: function (attributes) {
|
||||
if (!app.lastfm ||app.lastfm.cachedNowPlayingAttributes === attributes | !app.cfg.get('lastfm.NowPlaying')) {
|
||||
return
|
||||
}
|
||||
|
||||
if (app.lastfm.cachedNowPlayingAttributes) {
|
||||
if (app.lastfm.cachedNowPlayingAttributes.playParams.id === attributes.playParams.id) return;
|
||||
}
|
||||
|
||||
if (fs.existsSync(sessionPath)) {
|
||||
// update Now Playing
|
||||
if (attributes.status === true) {
|
||||
app.lastfm.track.updateNowPlaying({
|
||||
'artist': lfm.filterArtistName(attributes.artistName),
|
||||
'track': attributes.name,
|
||||
'album': attributes.albumName,
|
||||
'albumArtist': this.filterArtistName(attributes.artistName)
|
||||
}, function (err, nowPlaying) {
|
||||
if (err) {
|
||||
return console.error('[LastFM] An error occurred while updating nowPlayingSong', err);
|
||||
}
|
||||
|
||||
console.log('[LastFM] Successfully updated nowPlayingSong', nowPlaying);
|
||||
});
|
||||
app.lastfm.cachedNowPlayingAttributes = attributes
|
||||
}
|
||||
|
||||
} else {
|
||||
this.authenticate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = lfm;
|
|
@ -1,113 +0,0 @@
|
|||
let mediaPlayer = null;
|
||||
|
||||
module.exports = {
|
||||
|
||||
/**
|
||||
* Connects to the MPRIS interface.
|
||||
* @param {Object} win - The BrowserWindow.
|
||||
*/
|
||||
connect: (win) => {
|
||||
if (process.platform !== "linux") return;
|
||||
|
||||
const Player = require('mpris-service');
|
||||
|
||||
mediaPlayer = Player({
|
||||
name: 'Cider',
|
||||
identity: 'Cider',
|
||||
supportedUriSchemes: [],
|
||||
supportedMimeTypes: [],
|
||||
supportedInterfaces: ['player']
|
||||
});
|
||||
mediaPlayer = Object.assign(mediaPlayer, { canQuit: true, canControl: true, canPause: true, canPlay: true, canGoNext: true })
|
||||
|
||||
|
||||
let pos_atr = {durationInMillis: 0};
|
||||
mediaPlayer.getPosition = function () {
|
||||
const durationInMicro = pos_atr.durationInMillis * 1000;
|
||||
const percentage = parseFloat("0") || 0;
|
||||
return durationInMicro * percentage;
|
||||
}
|
||||
|
||||
mediaPlayer.active = true
|
||||
|
||||
mediaPlayer.on('playpause', async () => {
|
||||
win.webContents.executeJavaScript('MusicKitInterop.pausePlay()').catch(err => console.error(err))
|
||||
});
|
||||
|
||||
mediaPlayer.on('play', async () => {
|
||||
win.webContents.executeJavaScript('MusicKitInterop.pausePlay()').catch(err => console.error(err))
|
||||
});
|
||||
|
||||
mediaPlayer.on('pause', async () => {
|
||||
win.webContents.executeJavaScript('MusicKitInterop.pausePlay()').catch(err => console.error(err))
|
||||
});
|
||||
|
||||
mediaPlayer.on('next', async () => {
|
||||
win.webContents.executeJavaScript('MusicKitInterop.nextTrack()').catch(err => console.error(err))
|
||||
});
|
||||
|
||||
mediaPlayer.on('previous', async () => {
|
||||
win.webContents.executeJavaScript('MusicKitInterop.previousTrack()').catch(err => console.error(err))
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates the MPRIS interface.
|
||||
* @param {Object} attributes - The attributes of the track.
|
||||
*/
|
||||
updateAttributes: (attributes) => {
|
||||
if (process.platform !== "linux") return;
|
||||
|
||||
const MetaData = {
|
||||
'mpris:trackid': mediaPlayer.objectPath(`track/${attributes.playParams.id.replace(/[.]+/g, "")}`),
|
||||
'mpris:length': attributes.durationInMillis * 1000, // In microseconds
|
||||
'mpris:artUrl': (attributes.artwork.url.replace('/{w}x{h}bb', '/512x512bb')).replace('/2000x2000bb', '/35x35bb'),
|
||||
'xesam:title': `${attributes.name}`,
|
||||
'xesam:album': `${attributes.albumName}`,
|
||||
'xesam:artist': [`${attributes.artistName}`,],
|
||||
'xesam:genre': attributes.genreNames
|
||||
}
|
||||
|
||||
if (mediaPlayer.metadata["mpris:trackid"] === MetaData["mpris:trackid"]) {
|
||||
return
|
||||
}
|
||||
|
||||
mediaPlayer.metadata = MetaData
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates the playback state of the MPRIS interface.
|
||||
* @param {Object} attributes - The attributes of the track.
|
||||
*/
|
||||
updateState: (attributes) => {
|
||||
if (process.platform !== "linux") return;
|
||||
|
||||
function setPlaybackIfNeeded(status) {
|
||||
if (mediaPlayer.playbackStatus === status) {
|
||||
return
|
||||
}
|
||||
mediaPlayer.playbackStatus = status;
|
||||
}
|
||||
|
||||
switch (attributes.status) {
|
||||
case true: // Playing
|
||||
setPlaybackIfNeeded('Playing');
|
||||
break;
|
||||
case false: // Paused
|
||||
setPlaybackIfNeeded('Paused');
|
||||
break;
|
||||
default: // Stopped
|
||||
setPlaybackIfNeeded('Stopped');
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Closes the MPRIS interface.
|
||||
*/
|
||||
clearActivity: () => {
|
||||
if (process.platform !== "linux") return;
|
||||
mediaPlayer.metadata = {'mpris:trackid': '/org/mpris/MediaPlayer2/TrackList/NoTrack'}
|
||||
mediaPlayer.playbackStatus = 'Stopped';
|
||||
},
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue