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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
import { type App, type Plugin, inject } from 'vue'
import { orderBy, sumBy, uniqBy, startCase } from 'lodash-es'
import { Md5 } from 'ts-md5';
import { randomString } from './utils'
import fallbackImage from './assets/fallback.svg';
import type {
Auth, ServerInfo, StreamFormat,
Playlist, PlayQueue,
Album, AlbumGenre, AlbumSort,
Artist, Track,
SearchMode, SearchResult,
} from './types'
export class UnsupportedOperationError extends Error { }
export class SubsonicError extends Error {
readonly code: string | null
constructor(message: string, code: string | null) {
super(message)
this.name = 'SubsonicError'
this.code = code
}
}
export class OfflineError extends Error {
constructor() {
super('Offline')
this.name = 'OfflineError'
}
}
export const useSubsonicApi = (): SubsonicApi => (inject('subsonicApi') as SubsonicApi)
export const createSubsonicApi = (): SubsonicApi & Plugin => {
const instance = new SubsonicApi()
return Object.assign(instance, {
install: (app: App) => {
app.provide('subsonicApi', instance)
}
})
}
export class SubsonicApi {
public static clientName = import.meta.env.VITE_APP_NAME ?? 'Domsonic'
public static staticParams = {
f: 'json',
v: "1.16.1",
c: SubsonicApi.clientName,
}
public serverUrl: string = ''
public auth: { u: string, s: string, t: string } | null = null
public streamFormat: StreamFormat | null = null
public streamBitrate: number | null = null
public coverSize: number | null = null
private initialized: boolean = false
private readonly fetch = async (endpoint: string, params?: any): Promise<any> => {
const
url = new URL(endpoint, this.serverUrl),
searchParams = new URLSearchParams({
...SubsonicApi.staticParams,
...this.auth,
...params,
}),
reqParams = {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', },
body: searchParams,
},
request = new Request(url, reqParams)
try {
const response = await fetch(request)
if (!response.ok) {
if (response.status === 501)
throw new UnsupportedOperationError(
`Request failed with status ${response.status}`
)
throw new Error(`Request failed with status ${response.status}`)
}
const
json = await response.json(),
subsonicResponse = json['subsonic-response']
if (subsonicResponse.status !== 'ok')
throw new SubsonicError(
subsonicResponse.error?.message || subsonicResponse.status,
subsonicResponse.error?.code ?? null
);
return subsonicResponse
} catch (err: any) {
if (err instanceof TypeError && !navigator.onLine) {
console.info('[Offline mode] Api request skipped:', endpoint)
throw new OfflineError()
}
throw err
}
}
public static createAuth(username: string, password: string): Auth {
const salt = randomString()
return {
username,
salt,
hash: Md5.hashStr(password + salt),
}
}
constructor() {}
setServerUrl = (url: string) => {
if (!URL.parse(url))
throw new Error(
'Invalid server url supplied.'
)
this.initialized = false
this.auth = null
this.serverUrl = url
}
setAuth = (auth: Auth) => {
if (!auth)
throw new Error(
'Invalid Auth object supplied.'
)
this.initialized = false
this.auth = {
u: auth.username,
s: auth.salt,
t: auth.hash,
}
}
setStreamFormat = (format: StreamFormat, bitrate: number) => {
if (!format)
throw new Error(
'Invalid format specified'
)
if (typeof bitrate !== 'number')
throw new Error(
'Invalid bitrate specified'
)
this.streamFormat = format
this.streamBitrate = bitrate
}
setCoverSize = (size: number) => {
if (!size)
throw new Error(
'Invalid size specified'
)
this.coverSize = size
}
isInitialized = (): boolean => this.initialized
checkInitialized = (): boolean => {
if (!this.initialized)
throw Error(
'Not initialized.'
)
return true
}
initialize = (): boolean => {
if (this.serverUrl === '')
throw new Error(
'No server-url set.'
)
if (!this.auth)
throw new Error(
'No credentials set.'
)
this.initialized = true
return true
}
async fetchServerInfo(): Promise<ServerInfo> {
this.checkInitialized()
const response = await this.fetch('/rest/getOpenSubsonicExtensions')
if (!response || response.status !== 'ok' )
throw new Error(
response?.error?.message ||
response?.status ||
'Unknown error'
)
if (!response?.openSubsonic)
throw new Error(
'This server is not OpenSubsonic compatible.'
)
return {
name: response.type,
version: response.version,
openSubsonic: true,
extensions: (response.openSubsonicExtensions ?? []).map(
(ext: any) => ext.name
),
}
}
async isOnline(): Promise<boolean> {
this.checkInitialized()
try {
const response = await this.fetch('/rest/ping', {})
return response?.status === 'ok'
} catch (err) {
if (err instanceof OfflineError) return false
return false
}
}
async getGenres() {
this.checkInitialized()
const response = await this.fetch('/rest/getGenres', {})
return (response.genres.genre || [])
.map((item: any) => ({
id: item.value,
name: item.value,
albumCount: item.albumCount ?? 0,
trackCount: item.songCount ?? 0,
}))
.sort((a: any, b:any) => b.albumCount - a.albumCount)
}
async getAlbumsByGenre(
id: string,
size: number,
offset = 0,
random = false,
) {
this.checkInitialized()
const
response = await this.fetch('/rest/getAlbumList2', {
type: 'byGenre',
genre: id,
size,
offset,
}),
albums = (response.albumList2?.album || []).map(
this.normalizeAlbum,
this,
)
if (!random) {
// Fisher–Yates shuffle (in-place)
for (let i = albums.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[albums[i], albums[j]] = [albums[j], albums[i]]
}
}
return albums
}
async getTracksByGenre(id: string, size: number, offset = 0) {
this.checkInitialized()
const response = await this.fetch('/rest/getSongsByGenre', {
genre: id,
count: size,
offset,
})
return (response.songsByGenre?.song || []).map(this.normalizeTrack, this)
}
async getSimilarTracksByArtist(id: string, size = 50): Promise<Track[]> {
this.checkInitialized()
const
artist = await this.getArtistDetails(id),
albums = artist.albums || []
if (!albums.length) return []
const genreWeightMap: Record<string, number> = {}
for (const alb of albums) {
for (const g of alb.genres || []) {
genreWeightMap[g.name] = (genreWeightMap[g.name] || 0) + 1
}
}
const
weightedGenres = Object.entries(genreWeightMap).flatMap(
([genre, count]) => Array(count).fill(genre)
)
if (!weightedGenres.length) return []
const chosenGenre = weightedGenres[Math.floor(Math.random() * weightedGenres.length)]
return this.getRandomTracks({ genre: chosenGenre, size })
}
async getArtists(): Promise<Artist[]> {
this.checkInitialized()
const response = await this.fetch('/rest/getArtists')
return (
(response.artists?.index || [])
.flatMap((index: any) => index.artist)
.map(this.normalizeArtist, this)
)
}
async getAlbums(sort: AlbumSort, size: number, offset = 0): Promise<Album[]> {
this.checkInitialized()
const response = await this.fetch('/rest/getAlbumList2', {
type: {
'a-z': 'alphabeticalByName',
'recently-added': 'newest',
'recently-played': 'recent',
'most-played': 'frequent',
random: 'random',
}[sort],
offset,
size
})
return (response.albumList2?.album || []).map(this.normalizeAlbum, this)
}
async getArtistDetails(id: string): Promise<Artist> {
this.checkInitialized()
const artist = await this.fetch('/rest/getArtist', { id }).then(r => r.artist)
return this.normalizeArtist({
topSongs: await this.fetch('/rest/getTopSongs', { artist: artist.name }).then(r => r.topSongs?.song),
album: artist.album,
...(await this.fetch('/rest/getArtistInfo2', { id }).then(r => r.artistInfo2)),
...artist,
})
}
async * getTracksByArtist(id: string): AsyncGenerator<Track[]> {
this.checkInitialized()
const
artist = await this.fetch('/rest/getArtist', { id }).then(r => r.artist),
albumIds = orderBy(artist.album || [], x => x.year || 0, 'desc').map(x => x.id),
pending = albumIds.map(albumId => this.getAlbumDetails(albumId))
for (const promise of pending) {
const { tracks } = await promise
if (tracks?.length) yield tracks
}
}
async getAlbumDetails(id: string): Promise<Album> {
this.checkInitialized()
const
params = { id },
[info, info2] = await Promise.all([
this.fetch('/rest/getAlbum', params),
this.fetch('/rest/getAlbumInfo2', params),
])
return this.normalizeAlbum({
...info.album,
...info2.albumInfo
})
}
async getPlaylists() {
this.checkInitialized()
const response = await this.fetch('/rest/getPlaylists')
return (response.playlists?.playlist || []).map(this.normalizePlaylist, this)
}
async getPlaylist(id: string): Promise<Playlist> {
this.checkInitialized()
if (id === 'random') {
const tracks = await this.getRandomTracks()
return {
id,
name: 'Random',
comment: '',
createdAt: '',
updatedAt: '',
duration: sumBy(tracks, 'duration'),
isPublic: false,
isReadOnly: true,
trackCount: tracks.length,
tracks,
}
}
const response = await this.fetch('/rest/getPlaylist', {
id
})
return {
...this.normalizePlaylist(response.playlist),
tracks: (response.playlist.entry || []).map(this.normalizeTrack, this),
}
}
async createPlaylist(name: string, tracks?: string[]) {
this.checkInitialized()
await this.fetch('/rest/createPlaylist', {
songId: tracks,
name,
})
return this.getPlaylists()
}
async editPlaylist(playlistId: string, name: string, comment: string, isPublic: boolean) {
this.checkInitialized()
await this.fetch('/rest/updatePlaylist', {
playlistId,
name,
comment,
public: isPublic,
})
}
async deletePlaylist(id: string) {
this.checkInitialized()
await this.fetch('/rest/deletePlaylist', {
id
})
}
async addToPlaylist(playlistId: string, tracks: string[]) {
this.checkInitialized()
await this.fetch('/rest/updatePlaylist', {
songIdToAdd: tracks,
playlistId,
})
}
async removeFromPlaylist(playlistId: string, index: number) {
this.checkInitialized()
await this.fetch('/rest/updatePlaylist', {
songIndexToRemove: index,
playlistId,
})
}
async getPlayQueue(): Promise<PlayQueue> {
this.checkInitialized()
const
response = await this.fetch('/rest/getPlayQueue'),
tracks = (response.playQueue?.entry || []).map(this.normalizeTrack, this) as Track[],
currentTrackId = response.playQueue?.current?.toString(),
index = tracks.findIndex(track => track.id === currentTrackId),
currentTrack =
(index >= 0)
? index
: 0
return {
currentTrackPosition: (response.playQueue?.position || 0) / 1000,
currentTrack,
tracks,
}
}
async savePlayQueue(
tracks: Track[],
currentTrack: Track | null,
currentTime: number | null
) {
this.checkInitialized()
try {
const tracksIds = tracks.filter(t => !t.isStream).map(t => t.id)
await this.fetch('/rest/savePlayQueue', {
id: tracksIds,
current:
(!currentTrack?.isStream)
? currentTrack?.id
: undefined,
position:
(currentTime !== null)
? Math.round(currentTime * 1000)
: undefined,
})
} catch (err: any) {
if (
err instanceof OfflineError ||
err.code === 0 || err.code === 10
) return
throw err
}
}
async getRandomTracks(
{
size = 200,
genre,
fromYear,
toYear,
}: {
size?: number
genre?: string
fromYear?: number
toYear?: number
} = {}
): Promise<Track[]> {
this.checkInitialized()
const response = await this.fetch('/rest/getRandomSongs', {
size,
...genre && { genre },
...fromYear && { fromYear },
...toYear && { toYear },
})
return (response.randomSongs?.song || []).map(this.normalizeTrack, this)
}
async getFavourites() {
this.checkInitialized()
const response = await this.fetch('/rest/getStarred2')
return {
albums: (response.starred2?.album || []).map(this.normalizeAlbum, this),
artists: (response.starred2?.artist || []).map(this.normalizeArtist, this),
tracks: (response.starred2?.song || []).map(this.normalizeTrack, this)
}
}
async getRecentlyPlayedTracks(size = 200) {
this.checkInitialized()
const albums = await this.getAlbums('recently-played', size)
return albums.flatMap(a => a.tracks || [])
}
async addFavourite(id: string, type: 'track' | 'album' | 'artist') {
this.checkInitialized()
await this.fetch('/rest/star', {
id: type === 'track' ? id : undefined,
albumId: type === 'album' ? id : undefined,
artistId: type === 'artist' ? id : undefined,
})
}
async removeFavourite(id: string, type: 'track' | 'album' | 'artist') {
this.checkInitialized()
await this.fetch('/rest/unstar', {
id: type === 'track' ? id : undefined,
albumId: type === 'album' ? id : undefined,
artistId: type === 'artist' ? id : undefined,
})
}
async search (query: string, mode: SearchMode, size: number, offset?: number): Promise<SearchResult> {
this.checkInitialized()
const data = await this.fetch('/rest/search3', {
query,
albumCount: !mode || mode === 'album' ? size : 0,
artistCount: !mode || mode === 'artist' ? size : 0,
songCount: !mode || mode === 'track' ? size : 0,
albumOffset: offset ?? 0,
artistOffset: offset ?? 0,
songOffset: offset ?? 0,
})
return {
albums: (data.searchResult3.album || []).map(this.normalizeAlbum, this),
artists: (data.searchResult3.artist || []).map(this.normalizeArtist, this),
tracks: (data.searchResult3.song || []).map(this.normalizeTrack, this),
}
}
scan = async (): Promise<void> => {
this.checkInitialized()
return this.fetch('/rest/startScan')
}
async getScanStatus(): Promise<boolean> {
this.checkInitialized()
const response = await this.fetch('/rest/getScanStatus')
return response.scanStatus.scanning
}
async scrobble(id: string): Promise<void> {
this.checkInitialized()
try {
await this.fetch('/rest/scrobble', { id, submission: true })
} catch (err) {
if (err instanceof OfflineError) return
throw err
}
}
getDownloadUrl = (id: any): string => {
this.checkInitialized()
const url = new URL('/rest/download', this.serverUrl)
url.search = new URLSearchParams({
v: SubsonicApi.staticParams.v,
c: SubsonicApi.clientName,
...this.auth,
id,
}).toString()
return url.toString()
}
getCoverArtUrl = (item: any): string | undefined => {
this.checkInitialized()
if (!item.coverArt)
return fallbackImage
const url = new URL('/rest/getCoverArt', this.serverUrl)
url.search = new URLSearchParams({
v: SubsonicApi.staticParams.v,
c: SubsonicApi.clientName,
...this.auth,
size: (this.coverSize ?? 512).toString(),
id: item.coverArt,
}).toString()
return url.toString()
}
getStreamUrl = (id: any): string => {
this.checkInitialized()
const url = new URL('/rest/stream', this.serverUrl)
url.search = new URLSearchParams({
v: SubsonicApi.staticParams.v,
c: SubsonicApi.clientName,
...this.auth,
format: this.streamFormat ?? 'raw',
maxBitRate: (this.streamBitrate ?? 0).toString(),
id,
}).toString()
return url.toString()
}
private normalizeTrack = (item: any): Track => ({
id: item.id,
title: item.title,
duration: item.duration,
size: item.size,
favourite: !!item.starred,
track: item.track,
album: item.album,
albumId: item.albumId,
artists: item.artists?.length
? item.artists
: [{ id: item.artistId, name: item.artist }],
url: this.getStreamUrl(item.id),
image: this.getCoverArtUrl(item),
replayGain:
(Number.isFinite(item.replayGain?.trackGain) &&
Number.isFinite(item.replayGain?.albumGain) &&
item.replayGain?.trackPeak > 0 &&
item.replayGain?.albumPeak > 0)
? item.replayGain
: null,
});
private normalizeGenres = (item: any): AlbumGenre[] => (
item.genres?.length ? item.genres : (
item.genre ? [{ name: item.genre }] : []
)
);
private normalizeAlbum = (item: any): Album => ({
id: item.id,
name: item.name,
description: (item.notes || '').replace(/<a[^>]*>.*?<\/a>/gm, ''),
artists:
item.artists?.length
? item.artists
: [{ id: item.artistId, name: item.artist }],
image: this.getCoverArtUrl(item),
year: item.year || 0,
favourite: !!item.starred,
genres: this.normalizeGenres(item),
lastFmUrl: item.lastFmUrl,
musicBrainzUrl:
item.musicBrainzId
? `https://musicbrainz.org/release/${item.musicBrainzId}`
: undefined,
tracks: (item.song || []).map(this.normalizeTrack, this),
releaseType: this.normalizeReleaseType(item),
});
private normalizeReleaseType = (item: any): string => {
if (item.isCompilation) return 'COMPILATION'
if (!item.releaseTypes?.length || item.releaseTypes[0] === '') return 'ALBUM'
const value = item.releaseTypes[0].toUpperCase()
return (['ALBUM', 'EP', 'SINGLE', 'COMPILATION'].includes(value)) ? value : startCase(item.releaseTypes[0].toLowerCase())
}
private normalizeArtist = (item: any): Artist => {
const
rawAlbums = item.album ? (Array.isArray(item.album) ? item.album : [item.album]) : [],
getAlbumTime = (a: any) => {
const released =
(a?.released)
? Date.parse(a.released)
: NaN
if (!isNaN(released)) return released
const year = Number(a?.year)
if (!isNaN(year)) return new Date(year, 0, 1).getTime()
return Number.MIN_SAFE_INTEGER
},
sortedAlbums = [...rawAlbums].sort(
(a, b) => getAlbumTime(b) - getAlbumTime(a)
);
return {
id: item.id,
name: item.name,
description: (item.biography || '').replace(/<a[^>]*>.*?<\/a>/gm, ''),
genres: uniqBy(sortedAlbums.flatMap(this.normalizeGenres, this), 'name'),
albumCount: item.albumCount,
trackCount: rawAlbums.reduce((acc, a) => acc + (a.songCount || 0), 0),
favourite: !!item.starred,
lastFmUrl: item.lastFmUrl,
musicBrainzUrl:
item.musicBrainzId
? `https://musicbrainz.org/artist/${item.musicBrainzId}`
: undefined,
albums: sortedAlbums.map(a => this.normalizeAlbum(a)),
similarArtist: (item.similarArtist || []).map(this.normalizeArtist, this),
topTracks: (item.topSongs || []).slice(0, 5).map(this.normalizeTrack, this),
image:
item.coverArt
? this.getCoverArtUrl(item)
: item.artistImageUrl
}
}
private normalizePlaylist = (response: any): Playlist => ({
id: response.id,
name: response.name || '(Unnamed)',
comment: response.comment || '',
owner: response.owner || '',
createdAt: response.created || '',
updatedAt: response.changed || '',
trackCount: response.songCount,
duration: response.duration,
isPublic: response.public,
isReadOnly: false,
image:
(response.songCount > 0)
? this.getCoverArtUrl(response)
: undefined,
})
}