-
Notifications
You must be signed in to change notification settings - Fork 20
/
LastfmApiClient.ts
278 lines (257 loc) · 10 KB
/
LastfmApiClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import LastFm, {
AuthGetSessionResponse,
NowPlayingResponse,
TrackObject,
TrackScrobblePayload,
UserGetInfoResponse
} from "lastfm-node-client";
import AbstractApiClient from "./AbstractApiClient.js";
import dayjs from "dayjs";
import {readJson, removeUndefinedKeys, sleep, writeFile} from "../../utils.js";
import { DEFAULT_RETRY_MULTIPLIER, FormatPlayObjectOptions } from "../infrastructure/Atomic.js";
import { LastfmData } from "../infrastructure/config/client/lastfm.js";
import { PlayObject } from "../../../core/Atomic.js";
import {getNodeNetworkException, isNodeNetworkException} from "../errors/NodeErrors.js";
import {nonEmptyStringOrDefault, splitByFirstFound} from "../../../core/StringUtils.js";
import {ErrorWithCause} from "pony-cause";
import {getScrobbleTsSOCDate} from "../../utils/TimeUtils.js";
import {UpstreamError} from "../errors/UpstreamError.js";
const badErrors = [
'api key suspended',
'invalid session key',
'invalid api key',
'authentication failed'
];
const retryErrors = [
'operation failed',
'service offline',
'temporarily unavailable',
'rate limit'
]
export default class LastfmApiClient extends AbstractApiClient {
user?: string;
declare config: LastfmData;
constructor(name: any, config: Partial<LastfmData> & {configDir: string, localUrl: string}, options = {}) {
super('lastfm', name, config, options);
const {redirectUri, apiKey, secret, session, configDir} = config;
this.redirectUri = `${redirectUri ?? `${config.localUrl}/lastfm/callback`}?state=${name}`;
if (apiKey === undefined) {
this.logger.warn("'apiKey' not found in config!");
}
this.workingCredsPath = `${configDir}/currentCreds-lastfm-${name}.json`;
this.client = new LastFm(apiKey as string, secret, session);
}
static formatPlayObj = (obj: TrackObject, options: FormatPlayObjectOptions = {}): PlayObject => {
const {
artist: {
'#text': artists,
name: artistName,
mbid: artistMbid,
},
name: title,
album: {
'#text': album,
mbid: albumMbid,
},
duration,
date: {
// @ts-ignore
uts: time,
} = {},
'@attr': {
nowplaying = 'false',
} = {},
url,
mbid,
} = obj;
// arbitrary decision yikes
let artistStrings = splitByFirstFound(artists, [','], [artistName]);
return {
data: {
artists: [...new Set(artistStrings)] as string[],
track: title,
album,
duration,
playDate: time !== undefined ? dayjs.unix(time) : undefined,
meta: {
brainz: {
album: nonEmptyStringOrDefault<undefined>(albumMbid),
artist: splitByFirstFound<undefined>(artistMbid, [',',';'], undefined),
track: nonEmptyStringOrDefault<undefined>(mbid)
}
}
},
meta: {
nowPlaying: nowplaying === 'true',
mbid,
source: 'Lastfm',
url: {
web: url,
}
}
}
}
callApi = async <T>(func: any, retries = 0): Promise<T> => {
const {
maxRequestRetries = 2,
retryMultiplier = DEFAULT_RETRY_MULTIPLIER
} = this.config;
try {
return await func(this.client) as T;
} catch (e) {
const {
message,
} = e;
// for now check for exceptional errors by matching error code text
const retryError = retryErrors.find(x => message.toLocaleLowerCase().includes(x));
let networkError = null;
if(retryError === undefined) {
const nError = getNodeNetworkException(e);
if(nError !== undefined) {
networkError = nError.message;
} else if(message.includes('ETIMEDOUT')) {
networkError = 'request timed out after 3 seconds'
}
}
if (undefined !== retryError || networkError !== undefined) {
if (retries < maxRequestRetries) {
const delay = (retries + 1) * retryMultiplier;
if(networkError !== undefined) {
this.logger.warn(`API call failed due to network issue (${networkError}), retrying in ${delay} seconds...`);
} else {
this.logger.warn(`API call was not good but recoverable (${retryError}), retrying in ${delay} seconds...`);
}
await sleep(delay * 1000);
return this.callApi(func, retries + 1);
} else {
throw new UpstreamError(`API call failed due -> ${retryError ?? 'API call timed out'} <- after max retries hit ${maxRequestRetries}`, {cause: e})
}
}
throw e;
}
}
getAuthUrl = () => {
return `http://www.last.fm/api/auth/?api_key=${this.config.apiKey}&cb=${encodeURIComponent(this.redirectUri)}`
}
authenticate = async (token: any) => {
const sessionRes: AuthGetSessionResponse = await this.client.authGetSession({token});
const {
session: {
key: sessionKey,
name, // username
} = {}
} = sessionRes;
this.client.sessionKey = sessionKey;
await writeFile(this.workingCredsPath, JSON.stringify({
sessionKey,
}));
}
initialize = async (): Promise<true> => {
try {
const creds = await readJson(this.workingCredsPath, {throwOnNotFound: false});
const {sessionKey} = creds || {};
if (this.client.sessionKey === undefined && sessionKey !== undefined) {
this.client.sessionKey = sessionKey;
}
return true;
} catch (e) {
throw new ErrorWithCause('Current lastfm credentials file exists but could not be parsed', {cause: e});
}
}
testAuth = async () => {
if (this.client.sessionKey === undefined) {
this.logger.warn('No session key found. User interaction for authentication required.');
this.logger.info(`Redirect URL that will be used on auth callback: '${this.redirectUri}'`);
return false;
}
try {
const infoResp = await this.callApi<UserGetInfoResponse>((client: any) => client.userGetInfo());
const {
user: {
name,
} = {}
} = infoResp;
this.user = name;
this.initialized = true;
this.logger.info(`Client authorized for user ${name}`)
return true;
} catch (e) {
this.logger.error('Testing auth failed');
if(isNodeNetworkException(e)) {
this.logger.error('Could not communicate with Last.fm API');
}
throw e;
}
}
public playToClientPayload(playObj: PlayObject): TrackScrobblePayload {
const {
data: {
artists = [],
album,
albumArtists = [],
track,
duration,
playDate,
meta: {
brainz: {
track: mbid
} = {},
} = {}
} = {}
} = playObj;
// LFM does not support multiple artists in scrobble payload
// https://www.last.fm/api/show/track.scrobble
let artist: string;
if (artists.length === 0) {
artist = "";
} else {
artist = artists[0];
}
const rawPayload: TrackScrobblePayload = {
artist: artist,
duration,
track,
album,
timestamp: getScrobbleTsSOCDate(playObj).unix(),
mbid,
};
// LFM does not support multiple artists in scrobble payload
// https://www.last.fm/api/show/track.scrobble
if (albumArtists.length > 0) {
rawPayload.albumArtist = albumArtists[0];
}
// I don't know if its lastfm-node-client building the request params incorrectly
// or the last.fm api not handling the params correctly...
//
// ...but in either case if any of the below properties is undefined (possibly also null??)
// then last.fm responds with an IGNORED scrobble and error code 1 (totally unhelpful)
// so remove all undefined keys from the object before passing to the api client
return removeUndefinedKeys(rawPayload);
}
updateNowPlaying = async (play: PlayObject) => {
try {
const {timestamp, mbid, ...rest} = this.playToClientPayload(play);
const response = await this.callApi<NowPlayingResponse>((client: LastFm) => {
return client.trackUpdateNowPlaying(rest)
});
const {
nowplaying: {
ignoredMessage: {
code: ignoreCode,
'#text': ignoreMsg,
} = {},
} = {}
} = response;
if (ignoreCode > 0) {
this.logger.warn(`Service ignored this scrobble 😬 => (Code ${ignoreCode}) ${(ignoreMsg === '' ? '(No error message returned)' : ignoreMsg)} -- See https://www.last.fm/api/show/track.updateNowPlaying for more information`, {payload: rest});
}
return response;
} catch (e) {
if (!(e instanceof UpstreamError)) {
throw new UpstreamError('Error received from LastFM API', {cause: e, showStopper: true});
} else {
throw e;
}
}
}
}