-
Notifications
You must be signed in to change notification settings - Fork 5
/
plex.js
1459 lines (1328 loc) · 55 KB
/
plex.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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const ioPackage = require('./io-package.json');
const adapterName = ioPackage.common.name;
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const _fs = require('fs');
const _http = require('express')();
const _parser = require('body-parser');
const _multer = require('multer');
const _axios = require('axios');
const { v1: _uuid } = require('uuid');
const Plex = require('plex-api');
const Tautulli = require('tautulli-api');
/*
* internal libraries
*/
const Library = require(`${__dirname}/lib/library.js`);
const PlexPinAuth = require(`${__dirname}/lib/plexPinAuth.js`);
const _NODES = JSON.parse(_fs.readFileSync('./_NODES.json').toString());
const _ACTIONS = JSON.parse(_fs.readFileSync('./_ACTIONS.json').toString());
const _PLAYERDETAILS = JSON.parse(_fs.readFileSync('./_PLAYERDETAILS.json').toString());
const { Controller } = require(`${__dirname}/lib/players.js`);
/*
* constants & variables initiation
*/
let adapter;
let library;
let controller;
let unloaded;
let retryCycle, refreshCycle;
// Temp Json only for new Data
let encryptionKey;
let plex, tautulli, data;
let detailsCounter = 0;
/**
* players: maschine-id of players
* playing: friendly name of running players
* streams: number of active streams
* playingDevice: object
* playingDevice.prefix: state prefix of runnning players
* playingDevice.start: start date since last update
*/
let playing = [],
streams = 0,
playingDevice = [];
const players = [];
let history = [];
const notifications = {};
const upload = _multer({ dest: '/tmp/' });
let refreshInterval = null;
const watched = ['01-last_24h', '02-last_7d', '03-last_30d', '00-all_time'];
const plexOptions = {
identifier: '5cc42810-6dc0-44b1-8c70-747152d4f7f9',
product: 'Plex for ioBroker',
version: '1.0',
deviceName: 'ioBroker',
platform: 'ioBroker',
};
/*
* ADAPTER
*
*/
function startAdapter(options) {
options = options || {};
adapter = new utils.Adapter({ ...options, name: adapterName });
/*
* ADAPTER READY
*
*/
adapter.on('ready', function ready() {
library = new Library(adapter, {
nodes: _NODES,
actions: _ACTIONS,
updatesInLog: adapter.config.debug || false,
});
unloaded = false;
refreshInterval = adapter.setInterval(refreshViewOffset, 1000);
// set encryption key
if (adapter.config.encryptionKey === undefined || adapter.config.encryptionKey === '') {
//let key = encryptor.getEncryptionKey();
encryptionKey = library.getKey(20);
adapter.getForeignObject(`system.adapter.plex.${adapter.instance}`, (err, obj) => {
if (err || obj === undefined) {
return;
}
obj.native.encryptionKey = encryptionKey;
adapter.setForeignObject(obj._id, obj);
});
adapter.log.debug('Generated new encryption key for password encryption.');
} else {
encryptionKey = adapter.config.encryptionKey;
}
// Secure connection
library.AXIOS_OPTIONS.secureConnection = false;
library.AXIOS_OPTIONS._protocol = 'http:';
library.AXIOS_OPTIONS.timeout = 3000;
if (adapter.config.secureConnection && adapter.config.certPublicVal && adapter.config.certPrivateVal) {
adapter.log.info('Establishing secure connection to Plex Media Server...');
try {
library.AXIOS_OPTIONS = {
...library.AXIOS_OPTIONS,
cert:
adapter.config.certPublicVal.indexOf('.') === -1
? adapter.config.certPublicVal
: _fs.readFileSync(adapter.config.certPublicVal),
key:
adapter.config.certPrivateVal.indexOf('.') === -1
? adapter.config.certPrivateVal
: _fs.readFileSync(adapter.config.certPrivateVal),
rejectUnauthorized: false,
secureConnection: true,
_protocol: 'https:',
};
if (adapter.config.certChainedVal) {
library.AXIOS_OPTIONS.ca =
adapter.config.certChainedVal.indexOf('.') === -1
? adapter.config.certChainedVal
: _fs.readFileSync(adapter.config.certChainedVal);
}
if (library.AXIOS_OPTIONS.key.indexOf('ENCRYPTED') > -1) {
library.AXIOS_OPTIONS.passphrase = adapter.config.passphrase;
}
} catch (err) {
adapter.log.warn(
'Failed loading certificates! Falling back to insecure connection to Plex Media Server...',
);
adapter.log.debug(err.message);
library.AXIOS_OPTIONS.secureConnection = false;
library.AXIOS_OPTIONS._protocol = 'http:';
}
} else {
adapter.log.info('Establishing insecure connection to Plex Media Server...');
}
// get notifications
if (adapter.config.notifications) {
adapter.config.notifications.forEach(notification => {
if (!notifications[notification.media]) {
notifications[notification.media] = {};
}
notifications[notification.media][notification.event] = {
message: notification.message,
caption: notification.caption,
thumb: notification.thumb,
};
});
} else {
adapter.config.notifications = ioPackage.native.notifications;
}
// verify Plex settings
if (!adapter.config.plexIp || !adapter.config.plexToken) {
return library.terminate(
'Plex IP and Plex Token not configured! Please go to settings, fill in Plex IP and retrieve a Plex Token.',
);
}
// initialize Plex API
adapter.config.plexPort = adapter.config.plexPort || 32400;
plex = new Plex({
hostname: adapter.config.plexIp,
port: adapter.config.plexPort,
https: library.AXIOS_OPTIONS.secureConnection,
token: adapter.config.plexToken,
requestOptions: library.AXIOS_OPTIONS,
options: plexOptions,
});
library._plex = plex;
controller = new Controller(
adapter,
{
controllerIdentifier: plexOptions.identifier,
plexToken: plexOptions.plexToken,
actions: _ACTIONS,
nodes: _NODES,
playerdetails: _PLAYERDETAILS,
},
library,
);
// retrieve all values from states to avoid message "Unsubscribe from all states, except system's, because over 3 seconds the number of events is over 200 (in last second 0)"
adapter.getStates(`${adapter.name}.${adapter.instance}.*`, (err, states) => {
library.set(Library.CONNECTION, true);
// set current states from objects
for (const state in states) {
//Reset own states common.type and common.role
library.extendState(state);
if (states[state] !== null && states[state] !== undefined) {
library.setDeviceState(
state.replace(`${adapter.name}.${adapter.instance}.`, ''),
states[state].val,
);
// set history
if (state.indexOf('events.history') > -1) {
history = JSON.parse(states[state].val);
}
}
}
// empty _playing on start
if (adapter.config.resetMedia) {
library.del('_playing', true, () => adapter.log.debug('Plex Media flushed!'));
}
// subscribe to remote player
adapter.subscribeForeignStates('iot.0.services.custom_plex');
adapter.subscribeForeignStates('cloud.0.services.custom_plex');
// test connection
init();
});
library.subscribeNode('metadata.viewoffset', (state, prefix) => {
library.confirmNode({ node: `${prefix}_Control.seekTo` });
});
});
/*
* STATE CHANGE
*
*/
adapter.on('stateChange', function (id, state) {
if (!state || state.ack === true) {
return;
}
adapter.log.debug(`State of ${id} has changed ${JSON.stringify(state)}.`);
let action = id.slice(id.lastIndexOf('.') + 1);
let val = state.val;
// Cloud / iot Adapter
if (action == 'custom_plex') {
try {
let playerNamespace;
if (!state.val || typeof state.val !== 'string') {
return;
}
[playerNamespace, action, val] = state.val.split('_');
id = `_playing.${playerNamespace}._Controls.playback.${action}`;
} catch (err) {
adapter.log.warn(err.message);
return;
}
}
// Refresh Library
if (action == '_refresh') {
const libId = id.substring(id.indexOf('libraries.') + 10, id.indexOf('-'));
const options = {
...library.AXIOS_OPTIONS,
url: `${library.AXIOS_OPTIONS._protocol}//${adapter.config.plexIp}:${adapter.config.plexPort}/library/sections/${libId}/refresh?force=1`,
method: 'POST',
headers: {
'X-Plex-Token': adapter.config.plexToken,
},
};
_axios(options)
.then(res => {
adapter.log.info(`Successfully triggered refresh on library with ID ${libId}.`);
adapter.log.debug(JSON.stringify(res));
})
.catch(err => {
adapter.log.warn(
`Error triggering refresh on library with ID ${libId}! See debug log for details.`,
);
adapter.log.debug(err);
});
// Player Controls
} else {
const path = id.replace(`${adapter.name}.${adapter.instance}.`, '').split('.');
action = path.pop() || '';
const mode = path.pop();
path.splice(-1);
const p = controller.existPlayer(path.join('.'));
if (p) {
p.action({ mode: mode, action: action, val: val, id: `${path.join('.')}._Controls` });
}
}
});
/*
* HANDLE MESSAGES
*
*/
adapter.on('message', function (msg) {
adapter.log.debug(`Message: ${JSON.stringify(msg)}`);
const plexPin = new PlexPinAuth(plexOptions);
switch (msg.command) {
// get PIN
case 'getPin':
plexPin
.getPin()
.then(pin => {
adapter.log.debug(`Successfully retrieved PIN: ${pin.code}`);
library.msg(msg.from, msg.command, { result: true, pin: pin }, msg.callback);
})
.catch(err => {
adapter.log.warn(err.message);
library.msg(msg.from, msg.command, { result: false, error: err.message }, msg.callback);
});
break;
// get token
case 'getToken':
plexPin
.getToken(msg.message.pinId)
.then(res => {
// success getting token
if (res.token === true) {
adapter.log.debug('Successfully retrieved token.');
library.msg(msg.from, msg.command, { result: true, token: res.auth_token }, msg.callback);
} else {
// failed getting token
library.msg(
msg.from,
msg.command,
{ result: false, error: 'No token retrieved!' },
msg.callback,
);
}
})
.catch(err => {
adapter.log.warn(err.message);
library.msg(msg.from, msg.command, { result: false, error: err.message }, msg.callback);
});
break;
}
});
/*
* ADAPTER UNLOAD
*
*/
adapter.on('unload', function (callback) {
try {
adapter.log.info(`Plex Adapter stopped und unloaded.`);
unloaded = true;
controller.delete();
_http.close(() => adapter.log.debug('Server for listener closed.'));
adapter.clearTimeout(retryCycle);
adapter.clearTimeout(refreshCycle);
adapter.clearInterval(refreshInterval);
callback();
} catch {
callback();
}
});
return adapter;
}
/************* ✨ Codeium Command ⭐ *************/
/**
* Initializes the Plex adapter and sets up connections and configurations.
*
* - Queries the Plex server for session status and retrieves currently playing media.
/****** b350a5c6-373d-49d9-b629-c3b8405c4f02 ******
* - Sets device states based on retrieved data to avoid excessive event subscriptions.
* - Configures and creates controllable players based on available player data.
* - Verifies and initializes Tautulli settings for additional media information.
* - Sets up a refresh cycle to periodically retrieve data from the Plex server.
* - Starts a listener for events from the Plex server.
* - Retrieves and sets the server ID if available.
* - Handles errors related to server connectivity and retries initialization if necessary.
*/
function init() {
plex.query('/status/sessions')
.then(res => {
adapter.log.debug(
`Retrieved playing now from plex server: ${(res && res.MediaContainer && JSON.stringify(res.MediaContainer)) || 'empty'}`,
);
library.set(Library.CONNECTION, true);
// retrieve values from states to avoid message "Unsubscribe from all states, except system's, because over 3 seconds the number of events is over 200 (in last second 0)"
adapter.getStates(`${adapter.name}.${adapter.instance}.*`, (err, states) => {
if (err || !states) {
return;
}
for (const state in states) {
library.setDeviceState(
state.replace(`${adapter.name}.${adapter.instance}.`, ''),
states[state] && states[state].val,
);
}
playing =
(library.getDeviceState('_playing.players') &&
library.getDeviceState('_playing.players').split(',')) ||
[];
streams = library.getDeviceState('_playing.streams') || 0;
//create all controllable players
const playerConfig = {};
for (const state in states) {
for (const end of [
{ text: '.Player.localAddress', key: 'address' },
{ text: '.Player.port', key: 'port' },
{ text: '.Player.protocolCapabilities', key: 'protocolCapabilities' },
{ text: '.Player.uuid', key: 'uuid' },
{ text: '.Player.title', key: 'title' },
]) {
if (state.endsWith(end.text) && state.indexOf(`Metadata${end.text}`) == -1) {
const prefix = state
.replace(`${adapter.name}.${adapter.instance}.`, '')
.replace(end.text, '');
playerConfig[prefix] = playerConfig[prefix] || {};
playerConfig[prefix][end.key] = (states[state] && states[state].val) || '';
}
}
}
for (const prefix in playerConfig) {
const c = playerConfig[prefix];
if (
c !== undefined &&
c.protocolCapabilities !== undefined &&
c.protocolCapabilities.split(',').indexOf('timeline') &&
c.port !== undefined &&
c.address !== undefined &&
c.uuid !== undefined &&
c.title !== undefined
) {
if (`_playing.${library.clean(c.title, true)}-${c.uuid}` !== prefix) {
continue;
}
controller.createPlayerIfNotExist({
address: c.address,
port: c.port,
config: {
title: c.title,
uuid: c.uuid,
},
});
}
}
});
// verify Tautulli settings
if (!adapter.config.tautulliIp || !adapter.config.tautulliToken) {
adapter.log.info(
`Tautulli ${!adapter.config.tautulliIp ? ' IP/ ' : ''}${!adapter.config.tautulliToken ? 'API token ' : ''}missing!`,
);
tautulli = { get: () => Promise.reject('Not connected!') };
} else {
// initialize Tautulli API
try {
tautulli = new Tautulli(
adapter.config.tautulliIp,
adapter.config.tautulliPort || 8181,
library.decode(encryptionKey, adapter.config.tautulliToken),
);
} catch {
adapter.log.error(
`Tautulli configuration is incorrect. IP:${adapter.config.tautulliIp} Port:${adapter.config.tautulliPort} Api-Key:${library.decode(encryptionKey, adapter.config.tautulliToken)}`,
);
}
}
// retrieve data
if (!adapter.config.refresh) {
adapter.config.refresh = 0;
} else if (adapter.config.refresh > 0 && adapter.config.refresh < 10) {
adapter.log.warn(
'Due to performance reasons, the refresh rate can not be set to less than 10 seconds. Using 10 seconds now.',
);
adapter.config.refresh = 10;
}
refreshCycle = adapter.setTimeout(function updater() {
retrieveData();
if (adapter.config.refresh > 0 && !unloaded) {
refreshCycle = adapter.setTimeout(updater, Math.floor(parseInt(adapter.config.refresh) * 1000));
}
}, 1000);
// listen to events from Plex
startListener();
// connection is ok get server id
plex.query('/')
.then(res => {
if (res && res.MediaContainer && res.MediaContainer.machineIdentifier) {
controller.setServerId(res.MediaContainer.machineIdentifier);
}
})
.catch(err => {
adapter.log.debug(err);
});
})
.catch(err => {
adapter.log.debug(`Configuration: ${JSON.stringify(adapter.config)}`);
adapter.log.debug(`Request-Options: ${JSON.stringify(library.AXIOS_OPTIONS)}`);
adapter.log.debug(`Stack-Trace: ${JSON.stringify(err.stack)}`);
if (err.message.indexOf('EHOSTUNREACH') > -1) {
adapter.config.retry = 60;
adapter.log.info(
`Plex Media Server(${adapter.config.plexIp}:${adapter.config.plexPort}) not reachable! Will try again in ${adapter.config.retry} minutes...`,
);
library.set(Library.CONNECTION, false);
retryCycle = adapter.setTimeout(init, adapter.config.retry * 60 * 1000);
} else {
library.terminate(err.message);
}
});
}
/**
* Receive event from webhook
*
* @param data - The event data received from the webhook
* @param source - The source of the event
* @param prefix - The prefix of the event
*/
function setEvent(data, source, prefix) {
adapter.log.debug(
`Received ${prefix} playload - ${data['event'] || 'unknown'} - from ${source}: ${JSON.stringify(data)}`,
);
// empty payload
if (Object.keys(data).length === 0 || !data['event']) {
adapter.log.warn(`Empty payload received from ${source}! Please go to ${source} and configure payload!`);
return false;
}
// add meta data
data.media = data.Metadata && data.Metadata.type;
data.player = data.Player && data.Player.title;
data.account = data.Account && data.Account.title;
data.source = source;
data.timestamp = Math.floor(Date.now() / 1000);
data.datetime = library.getDateTime(Date.now());
data.playing = data.event.indexOf('play') > -1 || data.event.indexOf('resume') > -1;
if (!adapter.config.getMetadataTrees && data.Metadata) {
delete data.Metadata.Media;
}
// PLAYING
if (prefix == '_playing') {
// update latest player
if (data.Player && data.Player.title != '_recent') {
setEvent({ ...data, Player: { title: '_recent', uuid: 'player' } }, source, prefix);
}
// group by player
data.Player = data.Player !== undefined ? data.Player : {};
const groupBy =
data.Player.title && data.Player.uuid !== undefined
? `${library.clean(data.Player.title, true)}-${data.Player.uuid}`
: 'unknown';
// channel by player
library.set({
node: prefix,
role: library.getNode('plexplayers', true).role,
description: library.getNode('plexplayers', true).description,
});
library.set({
node: `${prefix}.${groupBy}`,
role: 'channel',
description: library.appendToDescription(
library.getNode('plex.player', true).description,
` ${data.Player.title || library.getNode('plex.player.unknown', true).description}`,
),
});
// adapt prefix
prefix = `${prefix}.${groupBy}`;
let playerTemp;
// index current playing players
if (data.event && data.Player && data.Player.title != '_recent') {
const playerIp = library.getDeviceState(`${prefix}.Player.localAddress`);
const playerPort = library.getDeviceState(`${prefix}.Player.port`);
playerTemp = controller.createPlayerIfNotExist({
address: playerIp,
port: playerPort,
config: {
title: data.Player.title,
uuid: data.Player.uuid,
},
});
if (['media.play', 'media.resume'].indexOf(data.event) > -1) {
if (playing.indexOf(data.Player.title) == -1) {
playing.push(data.Player.title);
}
if (playingDevice.findIndex(player => player.prefix == prefix) == -1) {
playingDevice.push({
prefix: prefix,
title: data.Player.title,
local: data.Player.local,
playerIp: playerIp,
playerPort: playerPort,
playerIdentifier: data.Player.uuid,
});
}
streams++;
} else if (['media.stop', 'media.pause'].indexOf(data.event) > -1) {
playing = playing.filter(player => player !== data.Player.title);
playingDevice = playingDevice.filter(player => player.prefix !== prefix);
streams > 0 && streams--;
}
library.set(
{
node: '_playing.players',
role: library.getNode('playing.players', true).role,
type: library.getNode('playing.players', true).type,
description: library.getNode('playing.players', true).description,
},
playing.join(','),
);
library.set(
{
node: '_playing.streams',
role: library.getNode('playing.streams', true).role,
type: library.getNode('playing.streams', true).type,
description: library.getNode('plex.player', true).description,
},
streams,
);
}
// add player controls
if (
data.Player &&
data.Player.uuid &&
players.indexOf(data.Player.uuid) == -1 &&
data.Player.title != '_recent'
) {
getPlayers();
// update play_switch control
} else if (
data.Player &&
data.Player.title != '_recent' &&
['media.play', 'media.resume', 'media.stop', 'media.pause'].indexOf(data.event) > -1
) {
library.confirmNode(
{ node: `${prefix}._Controls.playback.play_switch` },
['media.play', 'media.resume'].indexOf(data.event) > -1,
);
}
// get library details plex.0._playing.ipad-10A88133-3762-4948-AF10-9503A37517AC.Metadata.key
//if (adapter.config.getAllItem && data.Player.title != '_recent') getItemDetails(data.Metadata && data.Metadata.key, prefix)
if (data.event && data.Player && data.Player.title != '_recent' && playerTemp) {
playerTemp.setNotificationData(JSON.parse(JSON.stringify(data))), 100;
data = {};
}
} else if (prefix == 'events') {
// EVENTS
// channel
library.set(
{
node: prefix,
role: library.getNode('plex.events', true).role,
description: library.getNode('plex.events', true).description,
},
undefined,
);
// replace placeholders in notification message
const event = data.event && data.event.replace('media.', '');
const message = (notifications[data.media] && notifications[data.media][event]) ||
(notifications['any'] && notifications['any'][event]) ||
(notifications[data.media] && notifications[data.media]['any']) ||
(notifications['any'] && notifications['any']['any']) || {
message: '',
caption: '',
thumb: '',
notExist: true,
};
if (!message.notExist) {
// structure event
const eventData = JSON.parse(JSON.stringify(data));
const notification = {
id: _uuid(),
timestamp: data.timestamp,
datetime: data.datetime,
account: data.account,
player: data.player,
media: data.media,
event: event,
thumb: message.thumb
? `${library.AXIOS_OPTIONS._protocol}//${adapter.config.plexIp}:${adapter.config.plexPort}${replacePlaceholders(message.thumb, eventData)}?X-Plex-Token=${adapter.config.plexToken}`
: '',
message: replacePlaceholders(message.message, eventData),
caption: replacePlaceholders(message.caption, eventData),
source: data.source,
};
// dont add events with same media, account, and event (within 1 sec)
let addNotification = true;
for (let i = history.length - 1; i >= 0; i--) {
const lastItem = history[i];
if (
lastItem.source != notification.source &&
lastItem.media == notification.media &&
lastItem.account == notification.account
) {
addNotification =
lastItem.media != notification.media || lastItem.timestamp + 1000 <= notification.timestamp;
break;
}
}
if (addNotification) {
// add event to history
history.push(notification);
data = Object.assign({}, notification); // copy object
data.history = JSON.stringify(history.slice(-1000));
}
} else {
adapter.log.debug(`No message defined for ${data.media} ${event}`);
}
}
// write states
for (const key in data) {
library.readData(`${prefix}.${key}`, data[key], prefix);
}
// cleanup old states when playing something new
if (prefix.indexOf('_playing') > -1 && data.event == 'media.play') {
library.runGarbageCollector(prefix, false, 30000, [...Controller.garbageExcluded, '_Controls']);
}
}
/**
* Ersetzt Platzhalter im übergebenen Nachrichtentext durch die entsprechenden Werte aus den Daten.
*
* @param message - Die Nachricht mit Platzhaltern.
* @param data - Die Daten, die zum Ersetzen der Platzhalter verwendet werden.
* @returns - Die Nachricht mit ersetzten Platzhaltern.
*/
function replacePlaceholders(message, data) {
let pos, variable, tmp, path, index;
while (message.indexOf('%') > -1) {
pos = message.indexOf('%');
variable = message.substring(pos, message.indexOf('%', pos + 1) + 1).replace(/%/g, '');
// get value for placeholders
tmp = JSON.parse(JSON.stringify(data));
path = variable;
while (path.indexOf('.') > -1) {
try {
index = path.slice(0, path.indexOf('.'));
path = path.slice(path.indexOf('.') + 1);
tmp = tmp[index];
} catch (err) {
adapter.log.debug(`catch: 30 ${err.message}`);
}
}
// check value
if (tmp === undefined || tmp[path] === undefined || tmp === null || tmp[path] === null) {
message = message.replace(RegExp(`%${variable}%`, 'gi'), `(${variable} not found!)`);
} else {
message = message.replace(RegExp(`%${variable}%`, 'gi'), tmp[path]);
}
}
return message; // .replace(/ /g, '');
}
/**
* Checks if the API response is valid.
*
* @param res - The API response to be checked.
* @returns - Returns true if the response is valid, otherwise false.
*/
function is(res) {
if (
res === undefined ||
res.response === undefined ||
res.response.result === undefined ||
res.response.result !== 'success'
) {
adapter.log.warn('API response invalid!');
adapter.log.debug(`debug 23 ${JSON.stringify(res)}`);
return false;
} else if (res.response.message === 'Invalid apikey') {
adapter.log.warn('Invalid API key. No results retrieved!');
return false;
}
return true;
}
/**
* Retrieves items from the specified path and updates the library with the item count.
*
* @param path - The path to query items from.
* @param key - The key used to identify the items.
* @param node - The node to update with the item count.
*/
function getItems(path, key, node) {
if (!adapter.config.getAllItems) {
return;
}
plex.query(path)
.then(res => {
//library.set({node: node + '.items', type: library.getNode(key.toLowerCase() + '.items').type, role: library.getNode(key.toLowerCase() + '.items').role, description: library.getNode(key.toLowerCase() + '.items').description}, JSON.stringify(res.MediaContainer.Metadata));
library.set(
{
node: `${node}.itemsCount`,
type: library.getNode(`${key.toLowerCase()}.itemscount`).type,
role: library.getNode(`${key.toLowerCase()}.itemscount`).role,
description: library.getNode(`${key.toLowerCase()}.itemscount`).description,
},
res.MediaContainer.size,
);
})
.catch(err => {
adapter.log.debug(`Could not retrieve items for ${key} from Plex!`);
adapter.log.debug(err);
});
}
/**
* Retrieve data from Plex
*
*/
function retrieveData() {
// GET SERVERS
if (adapter.config.getServers) {
getServers();
}
// GET LIBRARIES
if (adapter.config.getLibraries) {
getLibraries();
}
// GET USERS (https://github.com/Tautulli/Tautulli/blob/master/API.md#get_users)
if (adapter.config.getUsers) {
getUsers();
}
// GET SETTINGS
if (adapter.config.getSettings) {
getSettings();
}
// GET PLAYLISTS
if (adapter.config.getPlaylists) {
getPlaylists();
}
// GET CLIENTS / PLAYERS
getPlayers();
}
/**
* Retrieve Server from Plex
*
*/
function getServers() {
plex.query('/servers')
.then(res => {
adapter.log.debug('Retrieved Servers from Plex.');
library.set(
{
node: 'servers',
role: library.getNode('servers').role,
description: library.getNode('servers').description,
},
undefined,
);
const data = res.MediaContainer.Server || [];
data.forEach(entry => {
const serverId = entry['name'].toLowerCase();
library.set(
{
node: `servers.${serverId}`,
role: library.getNode('server').role,
description: library.replaceDescription(
library.getNode('server').description,
'%server%',
entry['name'],
),
},
undefined,
);
// index all keys as states
for (const key in entry) {
library.set(
{
node: `servers.${serverId}.${key}`,
role: library.getNode(`servers.${key.toLowerCase()}`).role,
type: library.getNode(`servers.${key.toLowerCase()}`).type,
description: library.getNode(`servers.${key.toLowerCase()}`).description,
},
entry[key],
);
}
});
})
.catch(err => {
adapter.log.debug('Could not retrieve Servers from Plex!');
adapter.log.debug(err);
});
}
/**
* Retrieve Libraries from Plex
*
*/
function getLibraries() {
plex.query('/library/sections')
.then(res => {
adapter.log.debug('Retrieved Libraries from Plex.');
library.set({
node: 'libraries',
role: library.getNode('libraries').role,
description: library.getNode('libraries').description,
});
let data = res.MediaContainer.Directory || [];
data.forEach(entry => {
const libId = `${entry['key']}-${entry['title'].toLowerCase()}`;
library.set(
{
node: `libraries.${libId}`,
role: library.getNode('library').role,
description: library.replaceDescription(
library.getNode('library').description,
'%library%',
entry['title'],
),
},
undefined,
);
// refresh button
library.set(
{
node: `libraries.${libId}._refresh`,
type: library.getNode('plex.events', true).type,
role: library.getNode('plex.events', true).role,
description: library.getNode('plex.events', true).description,
},
false,
);
adapter.subscribeStates(`libraries.${libId}._refresh`);
// index all keys as states
for (const key in entry) {
library.set(
{
node: `libraries.${libId}.${key.toLowerCase()}`,
type: library.getNode(`libraries.${key.toLowerCase()}`).type,
role: library.getNode(`libraries.${key.toLowerCase()}`).role,
description: library.getNode(`libraries.${key.toLowerCase()}`).description,
},
typeof entry[key] == 'object' ? JSON.stringify(entry[key]) : entry[key],
);
}
// get library content
getItems(`/library/sections/${entry['key']}/all`, 'libraries', `libraries.${libId}`);
// get statistics / watch time
// https://github.com/Tautulli/Tautulli/blob/master/API.md#get_library_watch_time_stats
if (adapter.config.getStatistics) {
tautulli