-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcore.js
818 lines (736 loc) · 26.6 KB
/
core.js
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
809
810
811
812
813
814
815
816
817
818
/**
* API request variables
* @typedef {Object} ApiRequest
* @property {string} siteId - (sonarr / radarr / lidarr)
* @property {string} endpoint - (Version / Status / Lookup / GetEntity / SetEntity / QualityProfiles)
*/
/**
* An API response
* @typedef {Object} ApiResponse
* @property {Object} data - the API response
* @property {ApiRequest} request - the API method request variables
* @property {bool} success - success flag
* @property {string} error - error details
*/
/**
* All settings
* @typedef {Object} Setting
* @property {SiteSetting[]} sites - all site settings
* @property {Integration[]} integrations - all integrations
* @property {InjectedIconConfig} injectedIconConfig - injected icon type and position configuration
* @property {bool} enabled - is enabled
* @property {bool} contextMenu - whether to show context menu
* @property {bool} debug - log to console
* @property {int} searchInputWaitForMs - jQuery selector for the search input on the search page
* @property {int} searchInputMaxAttempts - text that is shown for this site's entry in the context menu
* @property {bool} customIconPosition - The type of injected icon. 'false' injects in the element defined in the config. 'true' injects a custom icon.
*/
/**
* A Servarr site setting
* @typedef {Object} SiteSetting
* @property {string} id - site identifier (sonarr / radarr / lidarr)
* @property {string} domain - site domain
* @property {bool} enabled - is enabled
* @property {string} searchPath - URL path to the site search / add new page
* @property {string} searchInputSelector - jQuery selector for the search input on the search page
* @property {string} menuText - text that is shown for this site's entry in the context menu
* @property {string} apiKey - API key
* @property {bool} autoPopAdvancedFromApi - whether the search path / selector settings should be updated from the API
*/
/**
* A site integration
* @typedef {Object} Integration
* @property {string} id - integration identifier
* @property {string} name - integration name
* @property {string} image - logo
* @property {bool} enabled - is enabled
*/
/**
* All instance API specific configurations
* @typedef {ApiConfig[]} ApiConfigs
*/
/**
* API configuration endpoints for a Servarr instance
* @typedef {Object} ApiConfig
* @property {string} id - site identifier (sonarr / radarr / lidarr)
* @property {ApiConfigEndpoint[]} endpoints - API endpoints for the Servarr instance
*/
/**
* API configuration endpoint details
* @typedef {Object} ApiConfigEndpoint
* @property {string} key - identifier
* @property {string} value - API URL part
*/
/**
* All site version specific configurations
* @typedef {VersionConfig[]} VersionConfigs
*/
/**
* Version configurations for a site
* @typedef {Object} VersionConfig
* @property {string} id - site identifier (sonarr / radarr / lidarr)
* @property {VersionConfigItem[]} configs - configs for all versions to be matched against current version
*/
/**
* Version configuration for a site version
* @typedef {Object} VersionConfigItem
* @property {string} versionMatch - regex pattern to match against the site version
* @property {string} searchPath - URL path to the site search / add new page
* @property {string} searchInputSelector - jQuery selector for the search input on the search page
*/
/**
* Version configuration for a site version
* @typedef {Object} InjectedIconConfig
* @property {string} type - 'anchored' for left or right side anchoring, 'floating' for floating.
* @property {string} side - 'left' or 'right'. for anchored this sets which side is anchored to, for floating this combined with the sideOffset sets the absolute horizontal position.
* @property {string} sideOffset - for floating only. this combined with the side sets the absolute horizontal position.
* @property {string} position - 'top' or 'bottom'. for anchored and floating this combined with the positionOffset sets the absolute vertical position.
* @property {string} positionOffset - this combined with the position sets the absolute vertical position.
* @property {string} backgroundColor - The background colour of the icon container.
* @property {string} fontColor - The font colour of the icon container.
*/
/**
* Global variables
*/
let sessionId,
defaultSettings = {
sites: [
{
id: 'sonarr',
domain: 'http://my.sonarr-url.domain:8989',
enabled: true,
searchPath: '/add/new/',
searchInputSelector: 'input[name="seriesLookup"]',
menuText: 'Search Sonarr for tv',
apiKey: '',
autoPopAdvancedFromApi: true
}, {
id: 'radarr',
domain: 'http://my.radarr-url.domain:7878',
enabled: true,
searchPath: '/add/new/',
searchInputSelector: 'input[name="movieLookup"]',
menuText: 'Search Radarr for movie',
apiKey: '',
autoPopAdvancedFromApi: true
}, {
id: 'lidarr',
domain: 'http://my.lidarr-url.domain:8686',
enabled: true,
searchPath: '/add/search/',
searchInputSelector: 'input[name="searchBox"]',
menuText: 'Search Lidarr',
apiKey: '',
autoPopAdvancedFromApi: true
}, {
id: 'readarr_ebook',
domain: 'http://my.readarr-ebook-url.domain:8787',
enabled: false,
searchPath: '/add/search/',
searchInputSelector: 'input[name="searchBox"]',
menuText: 'Search Readarr (ebook)',
apiKey: '',
autoPopAdvancedFromApi: true
}, {
id: 'readarr_audiobook',
domain: 'http://my.readarr-audiobook-url.domain:8788',
enabled: false,
searchPath: '/add/search/',
searchInputSelector: 'input[name="searchBox"]',
menuText: 'Search Readarr (audiobook)',
apiKey: '',
autoPopAdvancedFromApi: true
}
],
integrations: [
{
id: 'imdb',
name: 'IMDb',
image: 'imdb.png',
enabled: true
},
{
id: 'tmdb',
name: 'TMDb',
image: 'tmdb.svg',
enabled: true
},
{
id: 'tvdb',
name: 'tvdb',
image: 'tvdb.png',
enabled: true
},
{
id: 'trakt',
name: 'Trakt',
image: 'trakt.png',
enabled: true
},
{
id: 'tvmaze',
name: 'TVmaze',
image: 'tvmaze.png',
enabled: true
},
{
id: 'musicbrainz',
name: 'MusicBrainz',
image: 'musicbrainz.svg',
enabled: true
},
{
id: 'letterboxd',
name: 'Letterboxd',
image: 'letterboxd.svg',
enabled: true
},
{
id: 'tvcalendar',
name: 'TV Calendar',
image: 'tvcalendar.png',
enabled: true
},
{
id: 'rottentomatoes',
name: 'Rotten Tomatoes',
image: 'rotten-tomatoes.svg',
enabled: true
},
{
id: 'metacritic',
name: 'metacritic',
image: 'metacritic.svg',
enabled: true
},
{
id: 'simkl',
name: 'simkl',
image: 'simkl.png',
enabled: true
},
{
id: 'iptorrents',
name: 'IPTorrents',
image: 'iptorrents.png',
enabled: true,
warning: 'IPTorrents requires an account to be actively used or it is removed. The developer does not maintain an active account. This integration is entirely community supported.'
},
{
id: 'lastfm',
name: 'last.fm',
image: 'lastfm.png',
enabled: true
},
{
id: 'allocine',
name: 'Allociné',
image: 'allocine.png',
enabled: true
},
{
id: 'senscritique',
name: 'SensCritique',
image: 'senscritique.png',
enabled: true
},
{
id: 'betaseries',
name: 'BetaSeries',
image: 'betaseries.png',
enabled: true
},
{
id: 'primevideo',
name: 'Prime Video',
image: 'primevideo.png',
enabled: true,
warning: 'This integration was created by a community member for the French version of the website and is not maintained by the developer.'
},
{
id: 'myanimelist',
name: 'MyAnimeList',
image: 'myanimelist.png',
enabled: true
}
// {
// id: 'nextepisode',
// name: 'Next Episode',
// image: 'nextepisode.png',
// enabled: true
// }
],
injectedIconConfig: {
type: 'anchored', // anchored, floating
side: 'left', // left, right
sideOffset: '5%',
position: 'bottom', // top, bottom
positionOffset: '5%',
backgroundColor: '#222',
fontColor: '#fff',
},
config: {
enabled: true,
contextMenu: true,
debug: false,
searchInputWaitForMs: 300,
searchInputMaxAttempts: 20,
customIconPosition: false
}
},
/* may need to expand this out differently for use with v3, as adding a v3 to the URL for a v3 of radarr or sonarr gives some more or different info.
* the issue is the version can only be detected from the API, and you can't call a different API version without first knowing the version!
* may need to do v3 try and fallback, or call the base, save the version setting and use going forward?
* Will need to do periodic checks for updates, but this will be done anyway for checking search path / selector configs.
* For now we're only interested in the version so leaving as is.
*/
apiConfig = [
{
id: 'sonarr',
endpoints: [
{
key: 'Version',
value: 'system/status'
},
{
key: 'Status',
value: 'system/status'
},
{
key: 'QualityProfiles',
value: 'profile'
}
]
},
{
id: 'radarr',
endpoints: [
{
key: 'Version',
value: 'system/status'
},
{
key: 'Status',
value: 'system/status'
},
{
key: 'QualityProfiles',
value: 'qualityProfile'
}
]
},
{
id: 'lidarr',
endpoints: [
{
key: 'Version',
value: 'v1/system/status'
},
{
key: 'Status',
value: 'v1/system/status'
},
{
key: 'QualityProfiles',
value: 'v1/qualityprofile'
}
]
},
{
id: 'readarr_ebook',
endpoints: [
{
key: 'Version',
value: 'v1/system/status'
},
{
key: 'Status',
value: 'v1/system/status'
},
{
key: 'QualityProfiles',
value: 'v1/qualityprofile'
}
]
},
{
id: 'readarr_audiobook',
endpoints: [
{
key: 'Version',
value: 'v1/system/status'
},
{
key: 'Status',
value: 'v1/system/status'
},
{
key: 'QualityProfiles',
value: 'v1/qualityprofile'
}
]
}
],
versionConfig = [
{
id: 'sonarr',
configs: [
{
versionMatch: /^2/,
searchPath: '/addseries/',
searchInputSelector: '.add-series-search .x-series-search'
},
{
versionMatch: /^[3|4|5|6]/,
searchPath: '/add/new/?term=',
searchInputSelector: 'input[name="seriesLookup"]'
}
]
},
{
id: 'radarr',
configs: [
{
versionMatch: /^[0|2]/,
searchPath: '/addmovies/',
searchInputSelector: '.add-movies-search .x-movies-search'
},
{
versionMatch: /^[3|4|5|6]/,
searchPath: '/add/new/?term=',
searchInputSelector: 'input[name="movieLookup"]'
}
]
},
{
id: 'lidarr',
configs: [
{
versionMatch: /^[0|1|2]/,
searchPath: '/add/search/',
searchInputSelector: 'input[name="searchBox"]'
}
]
},
{
id: 'readarr_ebook',
configs: [
{
versionMatch: /^[0|1]/,
searchPath: '/add/search/',
searchInputSelector: 'input[name="searchBox"]'
}
]
},
{
id: 'readarr_audiobook',
configs: [
{
versionMatch: /^[0|1]/,
searchPath: '/add/search/',
searchInputSelector: 'input[name="searchBox"]'
}
]
}
];
/**
* Logs to console if the debug flag is set.
* Always warns or errors regardless of if the debug flag is set.
* Should be a string or array of objects.
* Adds an identifier to the start of the content if it's a string, otherwise as a string object at the beginning of the array.
* @param {any[]} content
* @param {string} logLevel
*/
async function log(content, logLevel = 'info') {
const settings = await getSettings();
if (!settings.config.debug && logLevel === 'info') {
return;
}
const identifier = `[ServarrExt ${new Date().toISOString()}]`;
// concat identifier if it's a string
if (typeof content === "string" || content instanceof String) {
content = `${identifier} ${content}`;
}
// otherwise it's an array
else {
try {
content.unshift(identifier);
} catch (e) {
content = new Array(identifier, content);
}
}
switch (logLevel) {
case 'info':
console.log(content);
return;
case 'warn':
console.warn(content);
return;
case 'error':
console.error(content);
return;
}
}
/*
* Log old and new values when an item in a storage area is changed
*/
let logStorageChange = function(changes, area) {
let changedItems = Object.keys(changes);
for (let item of changedItems) {
log(`Change in storage area: ${area} to item ${item}`);
log(['Old value: ', changes[item].oldValue]);
log(['New value: ', changes[item].newValue]);
}
};
browser.storage.onChanged.addListener(logStorageChange);
/**
* Retrieves settings from local storage
* Checks for potentially missing properties in the settings object (caused by new properties being added on new versions of the code)
* and create those properties as defaults or from the defaultSettings object.
*/
async function getSettings() {
let data = await browser.storage.sync.get({ 'sonarrRadarrLidarrAutosearchSettings': defaultSettings });
// if (!data.sonarrRadarrLidarrAutosearchSettings.hasOwnProperty('enabled')) {
// data.sonarrRadarrLidarrAutosearchSettings.enabled = true;
// }
// if (!data.sonarrRadarrLidarrAutosearchSettings.hasOwnProperty('debug')) {
// data.sonarrRadarrLidarrAutosearchSettings.debug = false;
// }
if (!data.sonarrRadarrLidarrAutosearchSettings.hasOwnProperty('integrations')) {
data.sonarrRadarrLidarrAutosearchSettings.integrations = defaultSettings.integrations;
}
if (!data.sonarrRadarrLidarrAutosearchSettings.hasOwnProperty('config')) {
data.sonarrRadarrLidarrAutosearchSettings.config = defaultSettings.config;
}
if (!data.sonarrRadarrLidarrAutosearchSettings.hasOwnProperty('injectedIconConfig')) {
data.sonarrRadarrLidarrAutosearchSettings.injectedIconConfig = defaultSettings.injectedIconConfig;
}
// check integrations array
for (let i = 0; i < defaultSettings.integrations.length; i++) {
/* jshint ignore:start */
// try to find the integration
if (data.sonarrRadarrLidarrAutosearchSettings.integrations.some(integration => integration.id === defaultSettings.integrations[i].id)) {
if (defaultSettings.integrations[i].hasOwnProperty('warning')) {
data.sonarrRadarrLidarrAutosearchSettings.integrations[i].warning = defaultSettings.integrations[i].warning;
}
continue;
}
/* jshint ignore:end */
// integration not found
data.sonarrRadarrLidarrAutosearchSettings.integrations.push(defaultSettings.integrations[i]);
}
// check sites array
for (let i = 0; i < defaultSettings.sites.length; i++) {
/* jshint ignore:start */
// try to find the site
if (data.sonarrRadarrLidarrAutosearchSettings.sites.some(integration => integration.id === defaultSettings.sites[i].id)) {
continue;
}
/* jshint ignore:end */
// site not found
data.sonarrRadarrLidarrAutosearchSettings.sites.push(defaultSettings.sites[i]);
}
for (let i = 0; i < data.sonarrRadarrLidarrAutosearchSettings.sites.length; i++) {
if (!data.sonarrRadarrLidarrAutosearchSettings.sites[i].hasOwnProperty('apiKey')) {
data.sonarrRadarrLidarrAutosearchSettings.sites[i].apiKey = '';
}
if (!data.sonarrRadarrLidarrAutosearchSettings.sites[i].hasOwnProperty('autoPopAdvancedFromApi')) {
data.sonarrRadarrLidarrAutosearchSettings.sites[i].autoPopAdvancedFromApi = true;
}
}
// check config customIconPosition property
if (!data.sonarrRadarrLidarrAutosearchSettings.config.hasOwnProperty('customIconPosition')) {
data.sonarrRadarrLidarrAutosearchSettings.config.customIconPosition = defaultSettings.config.customIconPosition;
}
// check config contextMenu property
if (!data.sonarrRadarrLidarrAutosearchSettings.config.hasOwnProperty('contextMenu')) {
data.sonarrRadarrLidarrAutosearchSettings.config.contextMenu = defaultSettings.config.contextMenu;
}
return data.sonarrRadarrLidarrAutosearchSettings;
}
/**
* Saves settings to local storage
* Checks for potentially missing properties in the settings object (caused by new properties being added on new versions of the code)
* and create those properties as defaults or from the defaultSettings object.
* @param {Settings} data - settings to save
*/
async function setSettings(data) {
if (!data.hasOwnProperty('enabled')) {
data.enabled = true;
}
if (!data.hasOwnProperty('contextMenu')) {
data.contextMenu = true;
}
if (!data.hasOwnProperty('debug')) {
data.enabled = false;
}
if (!data.hasOwnProperty('integrations')) {
data.integrations = defaultSettings.integrations;
}
if (!data.hasOwnProperty('config')) {
data.config = defaultSettings.config;
}
if (!data.config.hasOwnProperty('customIconPosition')) {
data.config.customIconPosition = defaultSettings.config.customIconPosition;
}
if (!data.hasOwnProperty('injectedIconConfig')) {
data.injectedIconConfig = defaultSettings.injectedIconConfig;
}
let obj = {
'sonarrRadarrLidarrAutosearchSettings': data
};
//obj['sonarrRadarrLidarrAutosearchSettings'] = data;
await browser.storage.sync.set(obj);
return data;
}
/**
* Get search path / selector configuration for a given site and version
* @param {string} siteId
* @param {string} version
* @returns {VersionConfigItem}
*/
let getVersionConfig = (siteId, version) =>
versionConfig
.find(v => v.id === siteId)
.configs
.find(c => c.versionMatch.test(version));
/**
* Build a URL to call an API
* @param {string} siteId
* @param {string} endpoint
* @returns {URL} - the url
*/
let getApiUrl = (site, endpoint, useV3 = true) => {
let _endpoint = apiConfig
.find(a => a.id == site.id)
.endpoints
.find(e => e.key == endpoint);
let url = new URL(`${site.domain.replace(/(.+)\/$/, '$1')}/api/${(useV3 ? 'v3/' : '')}${_endpoint.value}`);
// lidarr & readarr uses a different URL structure, so overwrite
if (site.id === 'lidarr' || site.id === 'readarr_ebook' || site.id === 'readarr_audiobook') {
url = new URL(`${site.domain.replace(/(.+)\/$/, '$1')}/api/${_endpoint.value}`);
}
url.searchParams.append('apikey', site.apiKey);
return url;
};
/**
* Call an instance API
* @param {ApiRequest} request
* @returns {Promise<ApiResponse>}
*/
async function callApi(request) {
const settings = await getSettings();
let site = settings.sites
.filter(s => s.enabled)
.find(s => s.id == request.siteId);
if (site == null) {
return {
data: null,
request: request,
success: false,
error: 'site config not found (likely it\'s not enabled)'
};
}
if (site.apiKey == null || site.apiKey === '') {
return {
data: null,
request: request,
success: false,
error: 'no api key set for site'
};
}
// /**
// * Wrap the actual API call in a function so it can be called for multiple url options
// * @param {string} url
// * @returns {ApiResponse}
// */
// async function performCall(url) {
// try {
// const data = await $.getJSON(url);
// const response = {
// data: data,
// request: request,
// success: true,
// error: null
// };
// switch (request.endpoint) {
// // if this is a 'Version' call try to update settings with version specific data
// case 'Version':
// // if auto population is turned off the just return response
// if (!site.autoPopAdvancedFromApi && request.source != 'ApiAutoPopEnabled') {
// return response;
// }
// // auto population is enabled, so get the config for this version and update settings
// let config = getVersionConfig(site.id, data.version);
// for (let i = 0; i < settings.sites.length; i++) {
// if (settings.sites[i].id === site.id) {
// settings.sites[i].searchPath = config.searchPath;
// settings.sites[i].searchInputSelector = config.searchInputSelector;
// }
// }
// await setSettings(settings);
// return response;
// default:
// return response;
// }
// } catch (error) {
// return {
// data: null,
// request: request,
// success: false,
// error: error
// };
// }
// }
/**
* Wrap the actual API call in a function so it can be called for multiple url options
* @param {string} url
* @returns {ApiResponse}
*/
async function performCall(url) {
try {
const response = await fetch(url);
const data = await response.json();
const apiResponse = {
data: data,
request: request,
success: true,
error: null
};
switch (request.endpoint) {
case 'Version':
if (!site.autoPopAdvancedFromApi && request.source != 'ApiAutoPopEnabled') {
return apiResponse;
}
let config = getVersionConfig(site.id, data.version);
for (let i = 0; i < settings.sites.length; i++) {
if (settings.sites[i].id === site.id) {
settings.sites[i].searchPath = config.searchPath;
settings.sites[i].searchInputSelector = config.searchInputSelector;
}
}
await setSettings(settings);
return apiResponse;
default:
return apiResponse;
}
} catch (error) {
return {
data: null,
request: request,
success: false,
error: error
};
}
}
// try the explicit v3 api first
let url = getApiUrl(site, request.endpoint);
let response = await performCall(url);
if (response.success) {
return response;
}
// try the api without v3
url = getApiUrl(site, request.endpoint, false);
response = await performCall(url);
return response;
}