plexsonic 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,424 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ const XML_HEADER = '<?xml version="1.0" encoding="UTF-8"?>';
22
+ const XMLNS = 'http://subsonic.org/restapi';
23
+ const API_VERSION = '1.16.1';
24
+ const SERVER_TYPE = 'Plexsonic';
25
+ const SERVER_VERSION = '0.1.0';
26
+ const OPEN_SUBSONIC = true;
27
+
28
+ const TOKEN_START = '\u0001';
29
+ const TOKEN_END = '\u0002';
30
+ const TOKEN_PATTERN = /\u0001(\d+)\u0002/g;
31
+
32
+ let nodeSeq = 0;
33
+ const nodeRegistry = new Map();
34
+
35
+ export function xmlEscape(value) {
36
+ const sanitized = sanitizeXmlText(String(value));
37
+ return sanitized
38
+ .replaceAll('&', '&amp;')
39
+ .replaceAll('<', '&lt;')
40
+ .replaceAll('>', '&gt;')
41
+ .replaceAll('"', '&quot;')
42
+ .replaceAll("'", '&apos;');
43
+ }
44
+
45
+ function sanitizeXmlText(value) {
46
+ let output = '';
47
+ for (const char of value) {
48
+ const codePoint = char.codePointAt(0);
49
+ if (
50
+ codePoint === 0x9 ||
51
+ codePoint === 0xa ||
52
+ codePoint === 0xd ||
53
+ (codePoint >= 0x20 && codePoint <= 0xd7ff) ||
54
+ (codePoint >= 0xe000 && codePoint <= 0xfffd) ||
55
+ (codePoint >= 0x10000 && codePoint <= 0x10ffff)
56
+ ) {
57
+ output += char;
58
+ }
59
+ }
60
+ return output;
61
+ }
62
+
63
+ function storeNode(node) {
64
+ const id = ++nodeSeq;
65
+ nodeRegistry.set(id, node);
66
+ return `${TOKEN_START}${id}${TOKEN_END}`;
67
+ }
68
+
69
+ function parseTokenText(text) {
70
+ const out = [];
71
+ let index = 0;
72
+ let match;
73
+
74
+ TOKEN_PATTERN.lastIndex = 0;
75
+ while ((match = TOKEN_PATTERN.exec(text)) !== null) {
76
+ const before = text.slice(index, match.index);
77
+ if (before) {
78
+ out.push(before);
79
+ }
80
+
81
+ const nodeId = Number(match[1]);
82
+ const tokenNode = nodeRegistry.get(nodeId);
83
+ if (tokenNode) {
84
+ out.push(tokenNode);
85
+ }
86
+
87
+ index = match.index + match[0].length;
88
+ }
89
+
90
+ const tail = text.slice(index);
91
+ if (tail) {
92
+ out.push(tail);
93
+ }
94
+
95
+ return out;
96
+ }
97
+
98
+ function normalizeChildren(input) {
99
+ if (input == null) {
100
+ return [];
101
+ }
102
+ if (Array.isArray(input)) {
103
+ return input.flatMap((item) => normalizeChildren(item));
104
+ }
105
+ if (typeof input === 'string') {
106
+ return parseTokenText(input);
107
+ }
108
+ if (typeof input === 'object' && input.kind === 'node') {
109
+ return [input];
110
+ }
111
+ return [String(input)];
112
+ }
113
+
114
+ function xmlAttrs(attrs = {}) {
115
+ return Object.entries(attrs)
116
+ .filter(([, value]) => value !== undefined && value !== null)
117
+ .map(([key, value]) => ` ${key}="${xmlEscape(value)}"`)
118
+ .join('');
119
+ }
120
+
121
+ function renderXmlPart(part) {
122
+ if (typeof part === 'string') {
123
+ return xmlEscape(part);
124
+ }
125
+ if (!part || part.kind !== 'node') {
126
+ return '';
127
+ }
128
+
129
+ const attrs = xmlAttrs(part.attrs);
130
+ if (part.selfClosing && part.children.length === 0) {
131
+ return `<${part.name}${attrs}/>`;
132
+ }
133
+
134
+ const inner = part.children.map(renderXmlPart).join('');
135
+ return `<${part.name}${attrs}>${inner}</${part.name}>`;
136
+ }
137
+
138
+ function renderXmlChildren(inner) {
139
+ return normalizeChildren(inner).map(renderXmlPart).join('');
140
+ }
141
+
142
+ const NUMERIC_ATTRS = new Set([
143
+ 'code',
144
+ 'count',
145
+ 'offset',
146
+ 'duration',
147
+ 'songCount',
148
+ 'albumCount',
149
+ 'track',
150
+ 'discNumber',
151
+ 'bitRate',
152
+ 'size',
153
+ 'year',
154
+ 'userRating',
155
+ 'playCount',
156
+ 'leafCount',
157
+ 'leafCountAdded',
158
+ 'leafCountRequested',
159
+ 'position',
160
+ 'lastModified',
161
+ 'start',
162
+ ]);
163
+
164
+ const BOOLEAN_ATTRS = new Set([
165
+ 'openSubsonic',
166
+ 'valid',
167
+ 'scanning',
168
+ 'isDir',
169
+ 'public',
170
+ 'scrobblingEnabled',
171
+ 'adminRole',
172
+ 'settingsRole',
173
+ 'downloadRole',
174
+ 'uploadRole',
175
+ 'playlistRole',
176
+ 'coverArtRole',
177
+ 'commentRole',
178
+ 'podcastRole',
179
+ 'streamRole',
180
+ 'jukeboxRole',
181
+ 'shareRole',
182
+ 'videoConversionRole',
183
+ 'smart',
184
+ 'synced',
185
+ 'readonly',
186
+ ]);
187
+
188
+ const ARRAY_CHILDREN_BY_PARENT = {
189
+ openSubsonicExtensions: new Set(['openSubsonicExtension']),
190
+ albumList: new Set(['album']),
191
+ albumList2: new Set(['album']),
192
+ artists: new Set(['index']),
193
+ indexes: new Set(['index']),
194
+ index: new Set(['artist']),
195
+ artist: new Set(['album']),
196
+ album: new Set(['song']),
197
+ songsByGenre: new Set(['song']),
198
+ randomSongs: new Set(['song']),
199
+ topSongs: new Set(['song']),
200
+ searchResult: new Set(['artist', 'album', 'match']),
201
+ searchResult2: new Set(['artist', 'album', 'song']),
202
+ searchResult3: new Set(['artist', 'album', 'song']),
203
+ musicFolders: new Set(['musicFolder']),
204
+ genres: new Set(['genre']),
205
+ playlists: new Set(['playlist']),
206
+ directory: new Set(['child']),
207
+ playlist: new Set(['entry']),
208
+ lyricsList: new Set(['structuredLyrics']),
209
+ structuredLyrics: new Set(['line']),
210
+ starred: new Set(['artist', 'album', 'song']),
211
+ starred2: new Set(['artist', 'album', 'song']),
212
+ };
213
+
214
+ function shouldUseArray(parentName, childName) {
215
+ return ARRAY_CHILDREN_BY_PARENT[parentName]?.has(childName) || false;
216
+ }
217
+
218
+ function coerceAttrValue(key, value) {
219
+ if (key === 'genres') {
220
+ const genreNames = (() => {
221
+ if (Array.isArray(value)) {
222
+ return value
223
+ .flatMap((entry) => {
224
+ if (entry == null) {
225
+ return [];
226
+ }
227
+ if (typeof entry === 'string') {
228
+ return [entry];
229
+ }
230
+ if (typeof entry === 'object') {
231
+ return [String(entry.name || entry.tag || entry.value || entry.title || '').trim()];
232
+ }
233
+ return [String(entry).trim()];
234
+ })
235
+ .filter(Boolean);
236
+ }
237
+
238
+ const raw = String(value || '').trim();
239
+ if (!raw) {
240
+ return [];
241
+ }
242
+ const parts = raw.includes(';') ? raw.split(';') : raw.split(',');
243
+ return parts.map((part) => part.trim()).filter(Boolean);
244
+ })();
245
+
246
+ return genreNames.map((name) => ({ name }));
247
+ }
248
+
249
+ if (key === 'moods') {
250
+ if (Array.isArray(value)) {
251
+ return value.map((entry) => String(entry || '').trim()).filter(Boolean);
252
+ }
253
+ const raw = String(value || '').trim();
254
+ if (!raw) {
255
+ return [];
256
+ }
257
+ const parts = raw.includes(';') ? raw.split(';') : raw.split(',');
258
+ return parts.map((part) => part.trim()).filter(Boolean);
259
+ }
260
+
261
+ if (BOOLEAN_ATTRS.has(key)) {
262
+ if (value === 'true') {
263
+ return true;
264
+ }
265
+ if (value === 'false') {
266
+ return false;
267
+ }
268
+ }
269
+
270
+ if (NUMERIC_ATTRS.has(key) && /^-?\d+$/.test(String(value))) {
271
+ return Number(value);
272
+ }
273
+
274
+ return value;
275
+ }
276
+
277
+ function nodeToJson(node) {
278
+ const out = {};
279
+ for (const [key, value] of Object.entries(node.attrs || {})) {
280
+ out[key] = coerceAttrValue(key, value);
281
+ }
282
+
283
+ for (const child of node.children || []) {
284
+ if (typeof child === 'string') {
285
+ if (child.trim()) {
286
+ out.value = (out.value || '') + child;
287
+ }
288
+ continue;
289
+ }
290
+
291
+ const value = nodeToJson(child);
292
+ if (shouldUseArray(node.name, child.name)) {
293
+ if (!Array.isArray(out[child.name])) {
294
+ out[child.name] = [];
295
+ }
296
+ out[child.name].push(value);
297
+ continue;
298
+ }
299
+
300
+ if (Object.prototype.hasOwnProperty.call(out, child.name)) {
301
+ if (!Array.isArray(out[child.name])) {
302
+ out[child.name] = [out[child.name]];
303
+ }
304
+ out[child.name].push(value);
305
+ continue;
306
+ }
307
+
308
+ out[child.name] = value;
309
+ }
310
+
311
+ const arrayChildren = ARRAY_CHILDREN_BY_PARENT[node.name];
312
+ if (arrayChildren) {
313
+ for (const childName of arrayChildren) {
314
+ if (!Object.prototype.hasOwnProperty.call(out, childName)) {
315
+ out[childName] = [];
316
+ }
317
+ }
318
+ }
319
+
320
+ if (node.name === 'openSubsonicExtensions') {
321
+ const extensions = out.openSubsonicExtension;
322
+ if (Array.isArray(extensions)) {
323
+ return extensions;
324
+ }
325
+ return extensions == null ? [] : [extensions];
326
+ }
327
+
328
+ return out;
329
+ }
330
+
331
+ function subsonicRoot(status, children = []) {
332
+ return {
333
+ kind: 'node',
334
+ name: 'subsonic-response',
335
+ selfClosing: false,
336
+ attrs: {
337
+ status,
338
+ version: API_VERSION,
339
+ type: SERVER_TYPE,
340
+ serverVersion: SERVER_VERSION,
341
+ openSubsonic: OPEN_SUBSONIC,
342
+ xmlns: XMLNS,
343
+ },
344
+ children,
345
+ };
346
+ }
347
+
348
+ export function emptyNode(name, attrs = {}) {
349
+ return storeNode({
350
+ kind: 'node',
351
+ name,
352
+ attrs,
353
+ children: [],
354
+ selfClosing: true,
355
+ });
356
+ }
357
+
358
+ export function node(name, attrs = {}, inner = '') {
359
+ return storeNode({
360
+ kind: 'node',
361
+ name,
362
+ attrs,
363
+ children: normalizeChildren(inner),
364
+ selfClosing: false,
365
+ });
366
+ }
367
+
368
+ export function okResponse(inner = '') {
369
+ const root = subsonicRoot('ok', normalizeChildren(inner));
370
+ return `${XML_HEADER}${renderXmlPart(root)}`;
371
+ }
372
+
373
+ export function failedResponse(code, message) {
374
+ const errorNode = {
375
+ kind: 'node',
376
+ name: 'error',
377
+ attrs: {
378
+ code,
379
+ message: String(message),
380
+ },
381
+ children: [],
382
+ selfClosing: true,
383
+ };
384
+ const root = subsonicRoot('failed', [errorNode]);
385
+ return `${XML_HEADER}${renderXmlPart(root)}`;
386
+ }
387
+
388
+ export function okResponseJson(inner = '') {
389
+ const root = subsonicRoot('ok', normalizeChildren(inner));
390
+ const json = nodeToJson(root);
391
+ delete json.xmlns;
392
+ return { 'subsonic-response': json };
393
+ }
394
+
395
+ export function failedResponseJson(code, message) {
396
+ const errorNode = {
397
+ kind: 'node',
398
+ name: 'error',
399
+ attrs: {
400
+ code,
401
+ message: String(message),
402
+ },
403
+ children: [],
404
+ selfClosing: true,
405
+ };
406
+ const root = subsonicRoot('failed', [errorNode]);
407
+ const json = nodeToJson(root);
408
+ delete json.xmlns;
409
+ return { 'subsonic-response': json };
410
+ }
411
+
412
+ // Backward-compatible export for older callsites.
413
+ export function responseJson(xml) {
414
+ // Kept only for compatibility during migration; no XML parsing path is used by server responses.
415
+ return {
416
+ 'subsonic-response': {
417
+ status: 'failed',
418
+ error: {
419
+ code: 10,
420
+ message: 'responseJson(xml) is deprecated',
421
+ },
422
+ },
423
+ };
424
+ }
@@ -0,0 +1,84 @@
1
+ /* Copyright Yukino Song, SudoMaker Ltd.
2
+ *
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements. See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership. The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License. You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied. See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+ import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
22
+
23
+ const VERSION = 1;
24
+ const IV_LENGTH = 12;
25
+ const TAG_LENGTH = 16;
26
+
27
+ function decodeKey(raw) {
28
+ if (!raw) {
29
+ return null;
30
+ }
31
+
32
+ if (/^[0-9a-fA-F]{64}$/.test(raw)) {
33
+ return Buffer.from(raw, 'hex');
34
+ }
35
+
36
+ try {
37
+ const decoded = Buffer.from(raw, 'base64');
38
+ if (decoded.length === 32) {
39
+ return decoded;
40
+ }
41
+ } catch {
42
+ // ignored
43
+ }
44
+
45
+ return null;
46
+ }
47
+
48
+ function keyFromSeed(seed) {
49
+ return createHash('sha256').update(seed).digest();
50
+ }
51
+
52
+ export function createTokenCipher({ rawKey, fallbackSeed }) {
53
+ const key = decodeKey(rawKey) || keyFromSeed(fallbackSeed);
54
+
55
+ return {
56
+ hasExplicitKey: Boolean(decodeKey(rawKey)),
57
+
58
+ encrypt(plainText) {
59
+ const iv = randomBytes(IV_LENGTH);
60
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
61
+ const ciphertext = Buffer.concat([cipher.update(String(plainText), 'utf8'), cipher.final()]);
62
+ const tag = cipher.getAuthTag();
63
+
64
+ return Buffer.concat([Buffer.from([VERSION]), iv, tag, ciphertext]);
65
+ },
66
+
67
+ decrypt(blob) {
68
+ const input = Buffer.isBuffer(blob) ? blob : Buffer.from(blob);
69
+ const version = input.readUInt8(0);
70
+ if (version !== VERSION) {
71
+ throw new Error('Unsupported token blob version');
72
+ }
73
+
74
+ const iv = input.subarray(1, 1 + IV_LENGTH);
75
+ const tag = input.subarray(1 + IV_LENGTH, 1 + IV_LENGTH + TAG_LENGTH);
76
+ const ciphertext = input.subarray(1 + IV_LENGTH + TAG_LENGTH);
77
+
78
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
79
+ decipher.setAuthTag(tag);
80
+
81
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
82
+ },
83
+ };
84
+ }