forked from d8ahazard/Phlex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.php
4646 lines (4301 loc) · 164 KB
/
api.php
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
<?php
require_once dirname(__FILE__) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/cast/Chromecast.php';
require_once dirname(__FILE__) . '/util.php';
require_once dirname(__FILE__) . '/body.php';
//require_once dirname(__FILE__) . '/new_body.php';
use digitalhigh\Radarr\Radarr;
use Kryptonit3\SickRage\SickRage;
use Kryptonit3\Sonarr\Sonarr;
$config = new Config_Lite('config.ini.php');
setDefaults();
if (isset($_GET['revision'])) {
$rev = $config->get('general','revision',false);
echo $rev ? substr($rev,0,8) : "unknown";
die;
}
checkSignIn();
$user = validateCredentials();
if ($user['valid']) {
if ( session_started() === FALSE ) {
session_id($user['apiToken']);
session_start();
}
$_SESSION['plexUserName'] = $user['plexUserName'];
$_SESSION['apiToken'] = $user['apiToken'];
$_SESSION['plexToken'] = $user['plexToken'];
setSessionVariables();
initialize();
} else {
write_log("Sorry, couldn't validate user.");
if (isset($_GET['testclient'])) {
write_log("API Link Test FAILED! Invalid API Token.");
echo json_encode(['error'=>'Invalid API Token Specified, please re-link your account through the Phlex Web UI.']);
write_log("ERROR: Unauthenticated access detected. Originating IP - ".$_SERVER['REMOTE_ADDR'],"ERROR");
$entityBody = file_get_contents('php://input');
if ($_SERVER['REQUEST_METHOD'] === 'POST') write_log("Post BODY: ".$entityBody);
die();
} else {
write_log("Invalid API Token, forcing logout.");
header("Location: ".serverProtocol().$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?logout');
die();
}
}
function initialize() {
sessionData();
if (isset($_POST['username']) && isset($_POST['password'])) {
define('LOGGED_IN', true);
if (isset($_POST['new'])) {
echo makeNewBody();
} else {
if ($_SESSION['newToken']) write_log("New token found.","WARN");
echo makeBody($_SESSION['newToken']);
}
die();
}
write_log('Session Started',"DEBUG");
$_SESSION['lang'] = checkSetLanguage();
if (!(isset($_SESSION['counter']))) {
$_SESSION['counter'] = 0;
}
if (isset($_GET['pollPlayer'])) {
if (substr_count($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")) ob_start("ob_gzhandler"); else ob_start();
$result['playerStatus'] = playerStatus();
$file = 'commands.php';
$handle = fopen($file, "r");
//Read first line, but do nothing with it
fgets($handle);
$contents = '';
//now read the rest of the file line by line, and explode data
while (!feof($handle)) {
$contents .= fgets($handle);
}
$devs = [];
foreach($_SESSION as $var=>$value) {
if (preg_match("/device_[0-9]/",$var)) {
write_log("Got a device variable: $var = $value");
$vars = explode("_",$var);
write_log("Vars: ".json_encode($vars));
$devs[$vars[1]][$vars[2]] = $value;
}
}
write_log("Devs: ".json_encode($devs));
$result['devs'] = $devs;
$result['commands'] = urlencode(($contents));
$devices = scanDevices();
$result['players'] = $devices['clients'];
$result['servers'] = fetchServerList($devices);
$result['dvrs'] = fetchDVRList($devices);
$result['updates'] = checkUpdates();
$lines = $_GET['logLimit'] ?? 50;
$result['logs'] = formatLog(tail(file_build_path(dirname(__FILE__),"logs","Phlex.log"),$lines));
if ($_SESSION['updateAvailable']) $result['updateAvailable'] = $_SESSION['updateAvailable'];
header('Content-Type: application/json');
echo JSON_ENCODE($result);
die();
}
if (isset($_GET['testclient'])) {
write_log("API Link Test successful!!","INFO");
echo 'success';
die();
}
if (isset($_GET['test'])) {
$result = array();
$result['status'] = testConnection($_GET['test']);
header('Content-Type: application/json');
echo json_encode($result);
die();
}
if (isset($_GET['registerServer'])) {
write_log("Registering server with phlexchat.com","INFO");
registerServer();
echo "OK";
die();
}
if (isset($_GET['card'])) {
echo json_encode(popCommand($_GET['card']));
die();
}
if (isset($_GET['checkUpdates'])) {
echo checkUpdates();
die();
}
if (isset($_GET['installUpdates'])) {
echo checkUpdates(true);
die();
}
if (isset($_GET['newDevice'])) {
$devJSON = json_decode($_GET['newDevice'],true);
write_log("Device JSON? ".json_encode($devJSON));
$device = 'device_'.$devJSON['id'].'_';
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'],$device.'Name',$devJSON['name']);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'],$device.'IP',$devJSON['ip']);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'],$device.'Port',$devJSON['port']);
saveConfig($GLOBALS['config']);
}
if (isset($_GET['device'])) {
$type = $_GET['device'];
$id = $_GET['id'];
$uri = $_GET['uri'];
$publicUri = $_GET['publicUri'];
$name = $_GET['name'];
$product = $_GET['product'];
write_log('New device selected. Type is ' . $type . ". ID is " . $id . ". Name is " . $name,"INFO");
if ($id != 'rescan') {
if ($type == 'plexServerId') {
$token = $_GET['token'];
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'Token', $token);
}
if ($type == 'plexDvr') $GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'Key', $_GET['key']);
if ($type=='plexClient') {
$_SESSION['plexClientId'] = $id;
}
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type, $id);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'Id', $id);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'Uri', $uri);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'PublicUri', $publicUri);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'Name', $name);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], $type . 'Product', $product);
saveConfig($GLOBALS['config']);
setSessionVariables();
sessionData();
scanDevices();
} else {
scanDevices(true);
}
die();
}
// If we are changing a setting variable via the web UI.
if (isset($_GET['id'])) {
$id = $_GET['id'];
$value = $_GET['value'];
write_log('Setting parameter changed:"' . $id . ' : ' . $value.'"',"INFO");
if (preg_match("/IP/", $id) && !preg_match("/device/", $id)) $value = addScheme($value);
if (preg_match("/Path/",$id)) if ((substr($value,0,1) != "/") && (trim($value) !== "")) $value = "/".$value;
$section = ($id === 'forceSSL') ? 'general' : 'user-_-' . $_SESSION['plexUserName'];
if (is_bool($value) === true) {
$GLOBALS['config']->setBool( $section, $id, $value);
} else {
$GLOBALS['config']->set($section, $id, $value);
}
saveConfig($GLOBALS['config']);
if ((trim($id) === 'useCast') || (trim($id) === 'noLoop')) scanDevices(true);
setSessionVariables(false);
if ($id == "appLanguage")checkSetLanguage($value);
die();
}
if (isset($_GET['TEST'])) {
if (isset($_GET['apiToken'])) {
foreach ($GLOBALS['config'] as $section => $setting) {
if ($section != "general") {
$testToken = $setting['apiToken'];
if ($testToken == $_GET['apiToken']) {
echo 'success';
die();
}
}
}
}
write_log("Unrecognized token used for testing.","ERROR");
echo 'token_not_recognized';
die();
}
// Fetches a list of clients
if (isset($_GET['clientList'])) {
$devices = fetchClientList(scanDevices());
echo $devices;
die();
}
if (isset($_GET['serverList'])) {
$devices = fetchServerList(scanDevices());
echo $devices;
die();
}
if (isset($_GET['fetchList'])) {
$fetch = $_GET['fetchList'];
$list = fetchList($fetch);
write_log("API: Returning profile list for " . $fetch.": ".json_encode($list),"INFO");
echo $list;
die();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['amazonRequest'] = false;
write_log("Incoming API.ai request detected.","INFO");
$json = file_get_contents('php://input');
write_log("JSON: ".$json);
$request = json_decode($json, true);
write_log("Request array: ".json_encode($request));
if ($request['type'] === 'Amazon') {
if ($request['reason'] == 'ERROR') {
write_log("Alexa Error message: ".$request['error']['type'].'::'.$request['error']['message'],"ERROR");
die();
}
$_SESSION['amazonRequest'] = true;
}
parseApiCommand($request);
die();
}
if ((isset($_GET['say'])) && (isset($_GET['command']))) {
write_log("Incoming API request detected.","INFO");
try {
$request = queryApiAi($_GET['command']);
parseApiCommand($request);
die();
} catch (\Exception $error) {
write_log(json_encode($error->getMessage()),"ERROR");
}
}
// This tells the api to parse our command with the plex "play" parser
if (isset($_GET['play'])) {
if (isset($_GET['command'])) {
$command = cleanCommandString($_GET['command']);
write_log('Got a request to play ' . $command,"INFO");
$resultArray = parsePlayCommand($command);
$queryOut = array();
$queryOut['initialCommand'] = $command;
$queryOut['parsedCommand'] = $command;
if ($resultArray) {
$result = $resultArray[0];
$queryOut['mediaResult'] = $result;
$playResult = playMedia($result);
$searchType = $result['searchType'];
$type = (($searchType == '') ? $result['type'] : $searchType);
$queryOut['parsedCommand'] = 'Play the ' . $type . ' named ' . $command . '.';
$queryOut['playResult'] = $playResult;
if ($queryOut['mediaResult']['exact'] == 1) {
$queryOut['mediaStatus'] = "SUCCESS: Exact match found.";
} else {
$queryOut['mediaStatus'] = "SUCCESS: Approximate match found.";
}
} else {
$queryOut['mediaStatus'] = 'ERROR: No results found';
}
$queryOut['timestamp'] = timeStamp();
$queryOut['serverURI'] = $_SESSION['plexServerUri'];
$queryOut['serverToken'] = $_SESSION['plexServerToken'];
$queryOut['clientURI'] = $_SESSION['plexClientUri'];
$queryOut['clientName'] = $_SESSION['plexClientName'];
$queryOut['commandType'] = 'play';
$result = json_encode($queryOut);
header('Content-Type: application/json');
logCommand($result);
echo $result;
die();
}
}
// This tells the api to parse our command with the plex "control" parser
if (isset($_GET['control'])) {
if (isset($_GET['command'])) {
$command = cleanCommandString($_GET['command']);
write_log('Got a control request: ' . $command,"INFO");
$result = parseControlCommand($command);
$newCommand = json_decode($result, true);
$newCommand['timestamp'] = timeStamp();
$result = json_encode($newCommand);
header('Content-Type: application/json');
if (! isset($_GET['noLog'])) {
logCommand($result);
echo $result;
}
die();
}
}
// This tells the api to parse our command with the "fetch" parser
if (isset($_GET['fetch'])) {
if (isset($_GET['command'])) {
$command = cleanCommandString($_GET['command']);
write_log('Got a fetch request: ' . $command,"INFO");
$result = parseFetchCommand($command);
$result['commandType'] = 'fetch';
$result['timestamp'] = timeStamp();
logCommand(json_encode($result));
header('Content-Type: application/json');
echo json_encode($result);
die();
}
}
}
/*
DO NOT SET ANY SESSION VARIABLES UNTIL THIS IS CALLED HERE
*/
function setSessionVariables($rescan=true) {
$_SESSION['mc'] = initMCurl();
$_SESSION['deviceID'] = checkSetDeviceID();
$ip = $GLOBALS['config']->get('user-_-'.$_SESSION['plexUserName'],'publicAddress', fetchUrl());
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'publicAddress', $ip);
saveConfig($GLOBALS['config']);
setStartUrl();
$devices = $GLOBALS['config']->get('user-_-'.$_SESSION['plexUserName'], 'dlist', false);
if ($devices) $_SESSION['list_plexdevices'] = json_decode(base64_decode($devices),true);
if($rescan) $devices = scanDevices();
// See if we have a server saved in settings
$_SESSION['plexServerId'] = $GLOBALS['config']->get('user-_-'.$_SESSION['plexUserName'], 'plexServerId', false);
if (!($_SESSION['plexServerId'])) {
// If no server, fetch a list of them and select the first one.
write_log('No server selected, fetching first avaialable device.',"INFO");
$servers = $devices['servers'];
if ($servers) {
$server = $servers[0];
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerId',$server['id']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerProduct',$server['product']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerName',$server['name']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerUri',$server['uri']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerPublicUri',$server['publicUri']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerPublicAddress',$server['publicAddress']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexServerToken',$server['token']);
fetchSections();
saveConfig($GLOBALS['config']);
}
}
// Now check and set up our client, just like we did with the server
$_SESSION['plexClientId'] = $GLOBALS['config']->get('user-_-'.$_SESSION['plexUserName'], 'plexClientId', false);
if (!($_SESSION['plexClientId'])) {
write_log("No client selected, fetching first available device.","INFO");
$clients = $devices['clients'];
if ($clients) {
$client = $clients[0];
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexClientId',$client['id']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexClientProduct',$client['product']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexClientName',$client['name']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexClientUri',$client['uri']);
saveConfig($GLOBALS['config']);
}
}
$_SESSION['plexDvrId'] = $GLOBALS['config']->get('user-_-'.$_SESSION['plexUserName'], 'plexDvrId', false);
if (!($_SESSION['plexDvrId'])) {
write_log("No DVR found, checking for available devices.","INFO");
$dvrs = $devices['dvrs'] ?? [];
if (count($dvrs) >= 1) {
$dvr = $dvrs[0];
write_log("DVR found: ".json_encode($dvr),"INFO");
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'], 'plexDvrId',$dvr['id']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexDvrProduct',$dvr['product']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexDvrName',$dvr['name']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexDvrUri',$dvr['uri']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexDvrPublicUri',$dvr['publicAddress']);
$GLOBALS['config']->set('user-_-'.$_SESSION['plexUserName'],'plexDvrToken',$dvr['token']);
saveConfig($GLOBALS['config']);
}
}
checkSetApiToken($_SESSION['plexUserName']);
$userSections = $GLOBALS['config']->getSection('user-_-'.$_SESSION['plexUserName'],false);
foreach ($userSections as $key=>$value) {
$value = toBool($value);
$_SESSION[$key] = $value;
}
foreach ($_SESSION as $key=>$value) {
if (preg_match("/ip_/",$key)) {
if (!isset(parse_url($value)['scheme'])) {
$_SESSION[$key] = 'http://' . parse_url($value)['path'] ?? 'http://localhost';
write_log("URL Does not have a specified protocol, setting " . $key . ": " . $_SESSION[$key],"INFO");
}
}
}
$defaults = ['returnItems'=>'6', 'rescanTime'=>'6', 'couchIP'=>'http://localhost', 'ombiIP'=>'http://localhost', 'sonarrIP'=>'http://localhost', 'sickIP'=>'http://localhost', 'radarrIP'=>'http://localhost', 'couchPort'=>'5050', 'ombiPort'=>'3579', 'sonarrPort'=>'8989', 'sickPort'=>'8083', 'radarrPort'=>'7878', 'apiClientToken'=>'', 'apiDevToken'=>'', 'dvr_resolution'=>'0', 'plexDvrNewAirings'=>'true','plexDvrStartOffset'=>'2','plexDvrEndOffset'=>'2','plexDvrResolution'=>'0','appLanguage'=>'en'];
foreach ($defaults as $key=>$value) {
if (! isset($_SESSION[$key])) $_SESSION[$key] = $value;
}
// Reload section UUID's
if ($_SESSION['plexServerUri']) fetchSections();
$_SESSION['plexHeader'] = '&X-Plex-Product=Phlex'.
'&X-Plex-Version=1.0.0'.
'&X-Plex-Client-Identifier='.$_SESSION['deviceID'].
'&X-Plex-Platform=Web'.
'&X-Plex-Platform-Version=1.0.0'.
'&X-Plex-Device=PhlexWeb'.
'&X-Plex-Device-Name=Phlex'.
'&X-Plex-Device-Screen-Resolution=1520x707,1680x1050,1920x1080'.
'&X-Plex-Token='.$_SESSION['plexToken'];
// Q&D Variable with the plex target client header
$_SESSION['plexClientHeader']='&X-Plex-Target-Client-Identifier='.$_SESSION['plexClientId'];
}
// Log our current session variables
function sessionData() {
$data = [
"UserName"=>$_SESSION['plexUserName'],
"DeviceID"=>$_SESSION['deviceID'],
"Server Name"=>$_SESSION['plexServerName'],
"Server URI"=>$_SESSION['plexServerUri'],
"Server Public URI"=>$_SESSION['plexServerPublicUri'],
"Server Token"=>(isset($_SESSION['plexServerToken']) ? "Valid": "ERROR"),
"Client Name"=>$_SESSION['plexClientName'],
"Client ID"=>$_SESSION['plexClientId'],
"Client URI"=>$_SESSION['plexClientUri'],
"Client Product"=>$_SESSION['plexClientProduct'],
"Plex DVR Enabled"=>($_SESSION['plexDvrUri'] ? "true" : "false"),
"CouchPotato Enabled"=>$_SESSION['couchEnabled'],
"Ombi Enabled"=>$_SESSION['ombiEnabled'],
"Radarr Enabled"=>$_SESSION['radarrEnabled'],
"Sonarr Enabled"=>$_SESSION['sonarrEnabled'],
"Sick Enabled"=>$_SESSION['sickEnabled'],
"Clean Logs"=>$_SESSION['cleanLogs'],
"Cast Enabled"=>$_SESSION['useCast'],
"Git Enabled"=>checkGit(),
"Auto-Update Enabled"=>$_SESSION['autoUpdate']
];
write_log("Session Variables: ".json_encode($data));
}
/* This is our handler for fetch commands
You can either say just the name of the show or series you want to fetch,
or explicitely state "the movie" or "the show" or "the series" to specify which one.
If no media type is specified, a search will first be executed for a movie, and then a
show, with the first found result being added.
If a searcher is not enabled in settings, nothing will happen and an appropriate status
message should be returned as the 'status' value of our object.
*/
function parseFetchCommand($command,$type=false) {
fireHook($command,"Fetch");
$resultOut = array();
$episode = $remove = $season = $tmdbResult = $useNext = false;
//Sanitize our string and try to rule out synonyms for commands
$result['initialCommand'] = $command;
$command = translateControl(strtolower($command),$_SESSION['lang']['fetchSynonymsArray']);
$commandArray = explode(' ',strtolower($command));
if (arrayContains('movie',$commandArray)) {
$commandArray = array_diff($commandArray,array('movie'));
$command = implode(" ",$commandArray);
$type = 'movie';
}
if (arrayContains('show',$commandArray)) {
$commandArray = array_diff($commandArray,array('show'));
$command = implode(" ",$commandArray);
$type = 'show';
}
if (arrayContains('season',$commandArray)) {
foreach($commandArray as $word) {
if ($useNext) {
$season = intVal($word);
break;
}
if ($word == 'season') {
$useNext = true;
}
}
if ($season) {
$type = 'show';
$commandArray = array_diff($commandArray,array('season',$season));
$command = implode(" ",$commandArray);
}
}
$useNext = false;
if (arrayContains('episode',$commandArray)) {
foreach($commandArray as $word) {
if ($useNext) {
$episode = intVal($word);
break;
}
if ($word == 'episode') {
$useNext = true;
}
if (($word == 'latest')) {
$remove = $word;
$episode = -1;
break;
}
}
if ($episode) {
$type = 'show';
$commandArray = array_diff($commandArray,array('episode',$episode));
if (($episode == -1) && ($remove)) $commandArray = array_diff($commandArray,array('episode',$remove));
$command = implode(" ",$commandArray);
}
}
write_log("No type specified, let's ask the internet.","INFO");
$tmdbResult = fetchTMDBInfo($command);
if ($tmdbResult) $type = $tmdbResult['type'] ?? false;
if (! $type) $resultOut['parsedCommand'] = 'Fetch the first movie or show named '.implode(" ",$commandArray);
write_log("Type: $type");
switch ($type) {
case 'show':
write_log("Searching explicitely for a show.","INFO");
if ($_SESSION['sonarrEnabled'] || $_SESSION['sickEnabled']) {
$result = downloadSeries(implode(" ",$commandArray),$season,$episode,$tmdbResult);
$resultTitle = $result['mediaResult']['title'];
$resultOut['parsedCommand'] = 'Fetch '.($season ? 'Season '.$season.' of ' : '').($episode ? 'Episode '.$episode.' of ' : '').'the show named '.$resultTitle;
write_log("Result ".json_encode($result));
} else {
$result['status'] = 'ERROR: No fetcher configured for ' .$type.'.';
write_log($result['status'],"WARN");
}
break;
case 'movie':
write_log("Searching explicitely for a movie.","INFO");
if (($_SESSION['couchEnabled']) || ($_SESSION['ombiEnabled']) || ($_SESSION['radarrEnabled'])) {
$result = downloadMovie(implode(" ",$commandArray),$tmdbResult);
} else {
$result['status'] = 'ERROR: No fetcher configured for ' .$type.'.';
write_log($result['status'],"WARN");
}
break;
default:
if (($_SESSION['couchEnabled']) || ($_SESSION['radarrEnabled'])) {
write_log("Searching for first media matching title, starting with movies.");
$result = downloadMovie(implode(" ", $commandArray),$tmdbResult);
}
if ((preg_match("/ERROR/",$result['status'])) && (($_SESSION['sonarrEnabled']) || ($_SESSION['sickEnabled']))) {
$result = downloadSeries(implode(" ", $commandArray),$tmdbResult);
break;
}
if (preg_match("/ERROR/",$result['status'])) {
$result['status'] = 'ERROR: No results found or no fetcher configured.';
write_log($result['status'],"WARN");
}
break;
}
$result['mediaStatus'] = $result['status'];
$result['parsedCommand'] = $resultOut['parsedCommand'];
$result['initialCommand'] = $command;
return $result;
}
function translateControl($string,$searchArray) {
foreach($searchArray as $replace =>$search) {
$string = str_replace($search,$replace,$string);
}
return $string;
}
function parseControlCommand($command) {
//Sanitize our string and try to rule out synonyms for commands
$synonyms = $_SESSION['lang']['commandSynonymsArray'];
$queryOut['initialCommand'] = $command;
$command = translateControl(strtolower($command),$synonyms);
$adjust = $cmd = false;
$queryOut['parsedCommand'] = "";
$commandArray = array("play","pause","stop","skipNext","stepForward","stepBack","skipPrevious","volume");
if (strpos($command,"volume")) {
$int = filter_var($command, FILTER_SANITIZE_NUMBER_INT);
if (! $int) {
if (preg_match("/up/",$command)) {
$adjust = true;
$int = 10;
}
if (preg_match("/down/",$command)) {
$adjust = true;
$int = -10;
}
if ($adjust) {
$status = playerStatus();
$status = json_decode($status,true);
$type = $status['type'] ?? false;
$volume = $status['volume'];
if ($volume) {
if ($type) $volume = $volume * 100;
$int = $volume + $int;
if ($type) $int = $int/100;
}
}
}
$queryOut['parsedCommand'] .= "Set the volume to " . $int . " percent.";
$cmd = 'setParameters?volume='.$int;
}
if (preg_match("/subtitles/",$command)) {
$streamID = 0;
if (preg_match("/on/",$command)) {
$status = playerStatus();
$statusArray = json_decode($status,true);
$streams = $statusArray['mediaResult']['Media']['Part']['Stream'];
foreach ($streams as $stream) {
$type = $stream['@attributes']['streamType'];
if ($type == 3) {
$code = $stream['@attributes']['languageCode'];
if (preg_match("/eng/",$code)) {
$streamID = $stream['@attributes']['id'];
}
}
}
}
$cmd = 'setStreams?subtitleStreamID='.$streamID;
}
if (! $cmd ) {
write_log("No command set so far, making one.","INFO");
$cmds = explode(" ",$command);
$newString = array_intersect($commandArray,$cmds);
$result = implode(" ",$newString);
if ($result) {
$cmd = $queryOut['parsedCommand'] .= $cmd = $result;
}
}
if ($cmd) {
$result = sendCommand($cmd);
$results['url'] = $result['url'];
$results['status'] = $result['status'];
$queryOut['playResult'] = $results;
$queryOut['mediaStatus'] = 'SUCCESS: Not a media command';
$queryOut['commandType'] = 'control';
$queryOut['clientURI'] = $_SESSION['plexClientUri'];
$queryOut['clientName'] = $_SESSION['plexClientName'];
return json_encode($queryOut);
}
return false;
}
function parseRecordCommand($command) {
write_log("Function fired.");
$request = [
'uri'=> $_SESSION['plexDvrUri'],
'path'=>'/'.urldecode($_SESSION['plexDvrKey']).'/hubs/search',
'query'=>[
'sectionId'=>'',
'query'=>urlencode($command),
'X-Plex-Token'=>$_SESSION['plexDvrToken']
]
];
$result = doRequest($request,5);
if ($result) {
$newContainer = new SimpleXMLElement($result);
$result = false;
$newScore = .69;
foreach ($newContainer->Hub as $hub) {
if ($hub['type'] == 'show' || $hub['type'] == 'movie') {
foreach($hub->Directory as $show) {
$show = flattenXML($show);
$score = similarity(cleanCommandString($show['title']), cleanCommandString($command));
if ($score >= $newScore) {
write_log("We have a match: " . json_encode($show),"INFO");
$result = $show;
$newScore = $score;
}
}
}
}
}
if ($result) {
$query = '?guid=' . urlencode($result['guid']) . '&X-Plex-Token=' . $_SESSION['plexDvrToken'];
$template = doRequest(['uri' => $_SESSION['plexDvrUri'], 'path' => '/media/subscriptions/template' . $query]);
if (!$template) {
write_log("Error fetching download template, aborting.", "ERROR");
return false;
}
$container = flattenXML(new SimpleXMLElement($template));
$sectionId = $result['librarySectionID'];
$title = $result['title'];
parse_str($container['SubscriptionTemplate']['MediaSubscription']['parameters'], $hints);
$params = [
'prefs' => [
'onlyNewAirings' => $_SESSION['plexDvrNewAirings'] ? 1 : 0,
'minVideoQuality' => $_SESSION['plexDvrResolution'],
'replaceLowerQuality' => $_SESSION['plexDvrRelaceLower'] ? 'true' : 'false',
'recordPartials' => $_SESSION['plexDvrRecordPartials'] ? 'true' : 'false',
'startOffsetMinutes' => $_SESSION['plexDvrStartOffset'],
'endOffsetMinutes' => $_SESSION['plexDvrEndOffset'],
'lineupChannel' => '',
'startTimeslot' => -1,
'oneShot' => "true",
'autoDeletionItemPolicyUnwatchedLibrary' => 0,
'autoDeletionItemPolicyWatchedLibrary' => 0
],
'targetLibrarySectionID' => $sectionId,
'targetSectionLocationID' => '',
'includeGrabs' => 1,
'type' => $sectionId,
'X-Plex-Token' => $_SESSION['plexDvrToken']];
$queryString = http_build_query(array_merge($params, $hints));
$query = ['uri' => $_SESSION['plexDvrUri'], 'path' => '/media/subscriptions', 'query' => "?" . $queryString,'type'=>'post'];
$result = doRequest($query, 0);
if ($result) {
$container = new SimpleXMLElement($result);
if (isset($container->MediaSubscription)) {
foreach ($container->MediaSubscription as $subscription) {
$show = flattenXML($subscription);
write_log("Show: ".json_encode($show));
$foundTitle = $show['Directory']['title'];
if (cleanCommandString($title) == cleanCommandString($foundTitle)) {
$extra = fetchTMDBInfo($title, false, false, 'tv');
$art = $extra['art'] ?? $show['Directory']['thumb'];
$return = ["title" => $foundTitle, "year" => $show['Directory']['year'], "type" => $show['Directory']['type'], "thumb" => $art, "art" => $art, "url" => $_SESSION['plexServerUri'] . '/subscriptions/' . $show['key'] . '?X-Plex-Token=' . $_SESSION['plexServerToken']];
write_log("Show added to record successfully: " . json_encode($return), "INFO");
return $return;
}
}
}
}
}
return false;
}
// This is now our one and only handler for searches.
function parsePlayCommand($command,$year=false,$artist=false,$type=false) {
$playerIn = false;
$commandArray = explode(" " ,$command);
// An array of words which don't do us any good
// Adding the apostrophe and 's' are necessary for the movie "Daddy's Home", which Google Inexplicably returns as "Daddy ' s Home"
$stripIn = $_SESSION['lang']['parseStripArray'];
// An array of words that indicate what kind of media we'd like
$mediaIn = $_SESSION['lang']['parseMediaArray'];
// An array of words that would modify or filter our search
$filterIn = $_SESSION['lang']['parseFilterArray'];
// An array of words that would indicate which specific episode or media we want
$numberWordIn = $_SESSION['lang']['parseNumberArray'];
foreach($_SESSION['list_plexdevices']['clients'] as $client) {
if ($client['name'] != "") {
$clientName = '/' . cleanCommandString($client['name']) . '/';
if (preg_match($clientName, $command)) {
write_log("I was just asked me to play something on a specific device: " . $client['name'],"INFO");
$playerIn = explode(" ", cleanCommandString($client['name']));
array_push($playerIn, "on", "in");
$_SESSION['plexClientId'] = $client['id'];
$_SESSION['plexClientName'] = $client['name'];
$_SESSION['plexClientUri'] = $client['uri'];
$_SESSION['plexClientProduct'] = $client['product'];
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], 'plexClientId', $client['id']);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], 'plexClientProduct', $client['product']);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], 'plexClientName', $client['name']);
$GLOBALS['config']->set('user-_-' . $_SESSION['plexUserName'], 'plexClientUri', $client['uri']);
saveConfig($GLOBALS['config']);
}
}
}
if (isset($_SESSION['cleaned_search'])) unset($_SESSION['cleaned_search']);
if ($playerIn) {
$commandArray = array_diff($commandArray,$playerIn);
$_SESSION['cleaned_search'] = ucwords(implode(" ",$commandArray));
}
// An array of words from our command that are numeric
$numberIn=array();
foreach($commandArray as $number) {
if ((is_numeric($number)) || in_array($number,$numberWordIn)) {
array_push($numberIn,$number);
}
}
// Create arrays of values we need to evaluate
$stripOut = array_intersect($commandArray,$stripIn);
$mediaOut = array_intersect($commandArray,$mediaIn);
$filterOut = array_intersect($commandArray,$filterIn);
$numberOut = array_intersect($commandArray,$numberIn);
if ($year) {
array_push($mediaOut,'year');
array_push($numberOut,$year);
}
$mods = array();
$mods['num'] = array();
$mods['filter'] = array();
$mods['media'] = array();
if ($stripOut) {
$commandArray = array_diff($commandArray, $stripOut);
}
if ($filterOut) {
$commandArray = array_diff($commandArray, $filterOut);
// "genre","year","actor","director","directed","starring","featuring","with","made","created","released","filmed"
$replaceArray = array("","","actor","director","director","actor","actor","actor","year","year","year","year");
$filterOut = str_replace($filterIn,$replaceArray,$filterOut);
$mods['filter']=$filterOut;
}
$mods['preFilter'] = implode(" ",$commandArray);
if ($mediaOut) {
$commandArray = array_diff($commandArray, $mediaOut);
// "season","series","show","episode","movie","film","beginning","rest","end","minute","minutes","hour","hours"
$replaceArray = array("season","season","show","episode","movie","movie","0","-1","-1","mm","mm","hh","hh","ss","ss");
$mediaOut=str_replace($mediaIn,$replaceArray,$mediaOut);
foreach($mediaOut as $media) {
if (is_numeric($media)) {
$mediaOut = array_diff($mediaOut,array($media));
array_push($mediaOut,"offset");
array_push($numberOut,$media);
}
}
$mods['media'] = $mediaOut;
}
if ($numberOut) {
$commandArray = array_diff($commandArray, $numberOut);
// "first","pilot","second","third","last","final","latest","random"
$replaceArray = array(1,1,2,3,-1,-1,-1,-2);
$mods['num']=str_replace($numberWordIn,$replaceArray,$numberOut);
}
if((empty($commandArray)) && (count($mods['num']) > count($mods['media']))) {
array_push($commandArray,$mods['num'][count($mods['num'])-1]);
unset($mods['num'][count($mods['num'])-1]);
}
$mods['target']=implode(" ",$commandArray);
if ($artist) $mods['artist']=$artist;
if ($type) $mods['type']=$type;
$result = fetchInfo($mods); // Returns false if nothing found
return $result;
}
// Parse and handle API.ai commands
function parseApiCommand($request) {
$lang = $request['lang'];
if ($lang) $_SESSION['lang'] = checkSetLanguage($lang);
$_SESSION['lastRequest'] = json_encode($request);
$greeting = $mediaResult = $rechecked = $screen = $year = false;
$card = $suggestions = false;
write_log("Full API.AI request: ".json_encode($request),"INFO");
$result = $request["result"];
$action = $result['parameters']["action"] ?? false;
$command = $result["parameters"]["command"] ?? false;
$control = $result["parameters"]["Controls"] ?? false;
$year = $request["result"]["parameters"]["age"]["amount"] ?? false;
$type = $result['parameters']['type'] ?? false;
$days = $result['parameters']['days'] ?? false;
$artist = $result['parameters']['artist'] ?? false;
$_SESSION['apiVersion'] = $request['originalRequest']['version'] ?? "1";
if ($command) $command = cleanCommandString($command);
$rawspeech = $result['resolvedQuery'];
if (cleanCommandString($rawspeech) == cleanCommandString($_SESSION['hookCustomPhrase'])) {
fireHook(false,"Custom");
write_log("Custom phrase triggered: ".$_SESSION['hookCustomPhrase'],"INFO");
$queryOut['initialCommand'] = $rawspeech;
$speech = ($_SESSION['hookCustomReply']!="" ? $_SESSION['hookCustomReply'] : $_SESSION['lang']['speechHookCustomDefault']);
$queryOut['speech'] = $speech;
returnSpeech($speech,"yes",false,false);
logCommand(json_encode($queryOut));
die();
}
if ($control) $control = strtolower($control);
$capabilities = $request['originalRequest']['data']['surface']['capabilities'];
$GLOBALS['screen'] = false;
foreach ($capabilities as $capability) {
if ($capability['name'] == "actions.capability.SCREEN_OUTPUT") $GLOBALS['screen'] = true;
}
if ($rawspeech == "GOOGLE_ASSISTANT_WELCOME") $rawspeech = "Talk to Flex TV.";
write_log("Raw speech is ".$rawspeech);
$queryOut=array();
$queryOut['serverURI'] = $_SESSION['plexServerUri'];
$queryOut['serverToken'] = $_SESSION['plexServerToken'];
$queryOut['clientURI'] = $_SESSION['plexClientUri'];
$queryOut['clientName'] = $_SESSION['plexClientName'];
$queryOut['initialCommand'] = $rawspeech;
$queryOut['timestamp'] = timeStamp();
write_log("Action is currently ".$action);
$contexts=$result["contexts"];
$inputs = ['originalRequest']['data']['inputs'];
foreach ($inputs as $input) {
if ($input['intent'] == 'actions.intent.OPTION') {
$action = 'playfromlist';
$command = $rawspeech;
}
}
foreach($contexts as $context) {
if ($context['name'] == 'actions_intent_option') {
if (preg_match("/play/",$context['parameters']['OPTION'])) {
$option = $context['parameters']['OPTION'];
$action = 'playfromlist';
$command = str_replace('play','',$option);
write_log("Hey, we got it. Command is now: ".$command);
$rawspeech = $command;
$command = cleanCommandString($command);
}
}
if (($context['name'] == 'promptfortitle') && ($action=='') && ($control=='') && ($command=='')) {
$action = 'play';
write_log("This is a response to a title query.");
if (!($command)) $command = cleanCommandString($result['resolvedQuery']);
if ($command == 'googleassistantwelcome') {
$action = $command = false;
$greeting = true;
}
}
if ((cleanCommandString($rawspeech) == 'talk to flex tv') && (! $greeting)) {
write_log("Fixing duplicate talk to request","INFO");
$action = $command = false;
$greeting = true;
}
if (($artist) && (! $command)) {
$command = $artist;
$artist = false;
}
if (($control == 'play') && ($action == '') && (! $command == '')) {
$action = 'play';
$control = false;
}
if (($command == '') && ($control == '') && ($action == 'play') && ($type == '')) {
$action = 'control';
$command = 'play';
}
if (($context['name'] == 'yes') && ($action=='fetchAPI')) {
$command = (string)$context['parameters']['command'];
$type = (isset($context['parameters']['type']) ? (string) $context['parameters']['type'] : false);