plex.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. <?php
  2. trait PlexHomepageItem
  3. {
  4. public function plexSettingsArray($infoOnly = false)
  5. {
  6. $homepageInformation = [
  7. 'name' => 'Plex',
  8. 'enabled' => strpos('personal', $this->config['license']) !== false,
  9. 'image' => 'plugins/images/tabs/plex.png',
  10. 'category' => 'Media Server',
  11. 'settingsArray' => __FUNCTION__
  12. ];
  13. if ($infoOnly) {
  14. return $homepageInformation;
  15. }
  16. if ($this->config['plexID'] !== '' && $this->config['plexToken'] !== '') {
  17. $loop = $this->plexLibraryList('key')['libraries'];
  18. foreach ($loop as $key => $value) {
  19. $libraryList[] = array(
  20. 'name' => $key,
  21. 'value' => $value
  22. );
  23. }
  24. } else {
  25. $libraryList = array(
  26. array(
  27. 'name' => 'Refresh page to update List',
  28. 'value' => '',
  29. 'disabled' => true,
  30. ),
  31. );
  32. }
  33. $homepageSettings = array(
  34. 'name' => 'Plex',
  35. 'enabled' => strpos('personal', $this->config['license']) !== false,
  36. 'image' => 'plugins/images/tabs/plex.png',
  37. 'category' => 'Media Server',
  38. 'settings' => array(
  39. 'Enable' => array(
  40. array(
  41. 'type' => 'switch',
  42. 'name' => 'homepagePlexEnabled',
  43. 'label' => 'Enable',
  44. 'value' => $this->config['homepagePlexEnabled']
  45. ),
  46. array(
  47. 'type' => 'select',
  48. 'name' => 'homepagePlexAuth',
  49. 'label' => 'Minimum Authentication',
  50. 'value' => $this->config['homepagePlexAuth'],
  51. 'options' => $this->groupOptions
  52. )
  53. ),
  54. 'Connection' => array(
  55. array(
  56. 'type' => 'input',
  57. 'name' => 'plexURL',
  58. 'label' => 'URL',
  59. 'value' => $this->config['plexURL'],
  60. 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.',
  61. 'placeholder' => 'http(s)://hostname:port'
  62. ),
  63. array(
  64. 'type' => 'blank',
  65. 'name' => '',
  66. 'label' => '',
  67. ),
  68. array(
  69. 'type' => 'password-alt',
  70. 'name' => 'plexToken',
  71. 'label' => 'Token',
  72. 'value' => $this->config['plexToken']
  73. ),
  74. array(
  75. 'type' => 'button',
  76. 'label' => 'Get Plex Token',
  77. 'icon' => 'fa fa-ticket',
  78. 'text' => 'Retrieve',
  79. 'attr' => 'onclick="showPlexTokenForm(\'#homepage-Plex-form [name=plexToken]\')"'
  80. ),
  81. array(
  82. 'type' => 'password-alt',
  83. 'name' => 'plexID',
  84. 'label' => 'Plex Machine',
  85. 'value' => $this->config['plexID']
  86. ),
  87. array(
  88. 'type' => 'button',
  89. 'label' => 'Get Plex Machine',
  90. 'icon' => 'fa fa-id-badge',
  91. 'text' => 'Retrieve',
  92. 'attr' => 'onclick="showPlexMachineForm(\'#homepage-Plex-form [name=plexID]\')"'
  93. ),
  94. ),
  95. 'Active Streams' => array(
  96. array(
  97. 'type' => 'switch',
  98. 'name' => 'homepagePlexStreams',
  99. 'label' => 'Enable',
  100. 'value' => $this->config['homepagePlexStreams']
  101. ),
  102. array(
  103. 'type' => 'select',
  104. 'name' => 'homepagePlexStreamsAuth',
  105. 'label' => 'Minimum Authorization',
  106. 'value' => $this->config['homepagePlexStreamsAuth'],
  107. 'options' => $this->groupOptions
  108. ),
  109. array(
  110. 'type' => 'switch',
  111. 'name' => 'homepageShowStreamNames',
  112. 'label' => 'User Information',
  113. 'value' => $this->config['homepageShowStreamNames']
  114. ),
  115. array(
  116. 'type' => 'select2',
  117. 'class' => 'select2-multiple',
  118. 'id' => 'plex-stream-exclude-select',
  119. 'name' => 'homepagePlexStreamsExclude',
  120. 'label' => 'Libraries to Exclude',
  121. 'value' => $this->config['homepagePlexStreamsExclude'],
  122. 'options' => $libraryList
  123. ),
  124. array(
  125. 'type' => 'select',
  126. 'name' => 'homepageShowStreamNamesAuth',
  127. 'label' => 'Minimum Authorization',
  128. 'value' => $this->config['homepageShowStreamNamesAuth'],
  129. 'options' => $this->groupOptions
  130. ),
  131. array(
  132. 'type' => 'select',
  133. 'name' => 'homepageStreamRefresh',
  134. 'label' => 'Refresh Seconds',
  135. 'value' => $this->config['homepageStreamRefresh'],
  136. 'options' => $this->timeOptions()
  137. ),
  138. ),
  139. 'Recent Items' => array(
  140. array(
  141. 'type' => 'switch',
  142. 'name' => 'homepagePlexRecent',
  143. 'label' => 'Enable',
  144. 'value' => $this->config['homepagePlexRecent']
  145. ),
  146. array(
  147. 'type' => 'select',
  148. 'name' => 'homepagePlexRecentAuth',
  149. 'label' => 'Minimum Authorization',
  150. 'value' => $this->config['homepagePlexRecentAuth'],
  151. 'options' => $this->groupOptions
  152. ),
  153. array(
  154. 'type' => 'number',
  155. 'name' => 'homepageRecentLimit',
  156. 'label' => 'Item Limit',
  157. 'value' => $this->config['homepageRecentLimit'],
  158. ),
  159. array(
  160. 'type' => 'select',
  161. 'name' => 'homepageRecentRefresh',
  162. 'label' => 'Refresh Seconds',
  163. 'value' => $this->config['homepageRecentRefresh'],
  164. 'options' => $this->timeOptions()
  165. ),
  166. ),
  167. 'Media Search' => array(
  168. array(
  169. 'type' => 'switch',
  170. 'name' => 'mediaSearch',
  171. 'label' => 'Enable',
  172. 'value' => $this->config['mediaSearch']
  173. ),
  174. array(
  175. 'type' => 'select',
  176. 'name' => 'mediaSearchAuth',
  177. 'label' => 'Minimum Authorization',
  178. 'value' => $this->config['mediaSearchAuth'],
  179. 'options' => $this->groupOptions
  180. ),
  181. array(
  182. 'type' => 'select',
  183. 'name' => 'mediaSearchType',
  184. 'label' => 'Media Server',
  185. 'value' => $this->config['mediaSearchType'],
  186. 'options' => $this->mediaServerOptions()
  187. ),
  188. ),
  189. 'Playlists' => array(
  190. array(
  191. 'type' => 'switch',
  192. 'name' => 'homepagePlexPlaylist',
  193. 'label' => 'Enable',
  194. 'value' => $this->config['homepagePlexPlaylist']
  195. ),
  196. array(
  197. 'type' => 'select',
  198. 'name' => 'homepagePlexPlaylistAuth',
  199. 'label' => 'Minimum Authorization',
  200. 'value' => $this->config['homepagePlexPlaylistAuth'],
  201. 'options' => $this->groupOptions
  202. ),
  203. ),
  204. 'Misc Options' => array(
  205. array(
  206. 'type' => 'input',
  207. 'name' => 'plexTabName',
  208. 'label' => 'Plex Tab Name',
  209. 'value' => $this->config['plexTabName'],
  210. 'placeholder' => 'Only use if you have Plex in a reverse proxy'
  211. ),
  212. array(
  213. 'type' => 'input',
  214. 'name' => 'plexTabURL',
  215. 'label' => 'Plex Tab WAN URL',
  216. 'value' => $this->config['plexTabURL'],
  217. 'placeholder' => 'http(s)://hostname:port'
  218. ),
  219. array(
  220. 'type' => 'select',
  221. 'name' => 'cacheImageSize',
  222. 'label' => 'Image Cache Size',
  223. 'value' => $this->config['cacheImageSize'],
  224. 'options' => array(
  225. array(
  226. 'name' => 'Low',
  227. 'value' => '.5'
  228. ),
  229. array(
  230. 'name' => '1x',
  231. 'value' => '1'
  232. ),
  233. array(
  234. 'name' => '2x',
  235. 'value' => '2'
  236. ),
  237. array(
  238. 'name' => '3x',
  239. 'value' => '3'
  240. )
  241. )
  242. ),
  243. array(
  244. 'type' => 'blank',
  245. 'label' => ''
  246. ),
  247. array(
  248. 'type' => 'switch',
  249. 'name' => 'homepageUseCustomStreamNames',
  250. 'label' => 'Use custom names for users',
  251. 'value' => $this->config['homepageUseCustomStreamNames']
  252. ),
  253. array(
  254. 'type' => 'html',
  255. 'name' => 'grabFromTautulli',
  256. 'label' => 'Grab from Tautulli. (Note, you must have set the Tautulli API key already)',
  257. 'override' => 6,
  258. 'html' => '<button type="button" onclick="getTautulliFriendlyNames()" class="btn btn-sm btn-success btn-rounded waves-effect waves-light b-none">Grab Names</button>',
  259. ),
  260. array(
  261. 'type' => 'html',
  262. 'name' => 'homepageCustomStreamNamesAce',
  263. 'class' => 'jsonTextarea hidden',
  264. 'label' => 'Custom definitions for user names (JSON Object, with the key being the plex name, and the value what you want to override with)',
  265. 'override' => 12,
  266. 'html' => '<div id="homepageCustomStreamNamesAce" style="height: 300px;">' . htmlentities($this->config['homepageCustomStreamNames']) . '</div>',
  267. ),
  268. array(
  269. 'type' => 'textbox',
  270. 'name' => 'homepageCustomStreamNames',
  271. 'class' => 'jsonTextarea hidden',
  272. 'id' => 'homepageCustomStreamNamesText',
  273. 'label' => '',
  274. 'value' => $this->config['homepageCustomStreamNames'],
  275. )
  276. ),
  277. 'Test Connection' => array(
  278. array(
  279. 'type' => 'blank',
  280. 'label' => 'Please Save before Testing'
  281. ),
  282. array(
  283. 'type' => 'button',
  284. 'label' => '',
  285. 'icon' => 'fa fa-flask',
  286. 'class' => 'pull-right',
  287. 'text' => 'Test Connection',
  288. 'attr' => 'onclick="testAPIConnection(\'plex\')"'
  289. ),
  290. )
  291. )
  292. );
  293. return array_merge($homepageInformation, $homepageSettings);
  294. }
  295. public function testConnectionPlex()
  296. {
  297. if (!empty($this->config['plexURL']) && !empty($this->config['plexToken'])) {
  298. $url = $this->qualifyURL($this->config['plexURL']) . "/servers?X-Plex-Token=" . $this->config['plexToken'];
  299. try {
  300. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  301. $response = Requests::get($url, array(), $options);
  302. libxml_use_internal_errors(true);
  303. if ($response->success) {
  304. $this->setAPIResponse('success', 'API Connection succeeded', 200);
  305. return true;
  306. } else {
  307. $this->setAPIResponse('error', 'URL and/or Token not setup correctly', 422);
  308. return false;
  309. }
  310. } catch (Requests_Exception $e) {
  311. $this->setAPIResponse('error', $e->getMessage(), 500);
  312. return false;
  313. }
  314. } else {
  315. $this->setAPIResponse('error', 'URL and/or Token not setup', 422);
  316. return 'URL and/or Token not setup';
  317. }
  318. }
  319. public function plexHomepagePermissions($key = null)
  320. {
  321. $permissions = [
  322. 'streams' => [
  323. 'enabled' => [
  324. 'homepagePlexEnabled',
  325. 'homepagePlexStreams'
  326. ],
  327. 'auth' => [
  328. 'homepagePlexAuth',
  329. 'homepagePlexStreamsAuth'
  330. ],
  331. 'not_empty' => [
  332. 'plexURL',
  333. 'plexToken',
  334. 'plexID'
  335. ]
  336. ],
  337. 'recent' => [
  338. 'enabled' => [
  339. 'homepagePlexEnabled',
  340. 'homepagePlexRecent'
  341. ],
  342. 'auth' => [
  343. 'homepagePlexAuth',
  344. 'homepagePlexRecentAuth'
  345. ],
  346. 'not_empty' => [
  347. 'plexURL',
  348. 'plexToken',
  349. 'plexID'
  350. ]
  351. ],
  352. 'playlists' => [
  353. 'enabled' => [
  354. 'homepagePlexEnabled',
  355. 'homepagePlexPlaylist'
  356. ],
  357. 'auth' => [
  358. 'homepagePlexAuth',
  359. 'homepagePlexPlaylistAuth'
  360. ],
  361. 'not_empty' => [
  362. 'plexURL',
  363. 'plexToken',
  364. 'plexID'
  365. ]
  366. ],
  367. 'metadata' => [
  368. 'enabled' => [
  369. 'homepagePlexEnabled'
  370. ],
  371. 'auth' => [
  372. 'homepagePlexAuth'
  373. ],
  374. 'not_empty' => [
  375. 'plexURL',
  376. 'plexToken',
  377. 'plexID'
  378. ]
  379. ],
  380. 'search' => [
  381. 'enabled' => [
  382. 'homepagePlexEnabled',
  383. 'mediaSearch'
  384. ],
  385. 'auth' => [
  386. 'homepagePlexAuth',
  387. 'mediaSearchAuth'
  388. ],
  389. 'not_empty' => [
  390. 'plexURL',
  391. 'plexToken',
  392. 'plexID'
  393. ]
  394. ]
  395. ];
  396. if (array_key_exists($key, $permissions)) {
  397. return $permissions[$key];
  398. } elseif ($key == 'all') {
  399. return $permissions;
  400. } else {
  401. return [];
  402. }
  403. }
  404. public function homepageOrderplexnowplaying()
  405. {
  406. if ($this->homepageItemPermissions($this->plexHomepagePermissions('streams'))) {
  407. return '
  408. <div id="' . __FUNCTION__ . '">
  409. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Now Playing...</h2></div>
  410. <script>
  411. // Plex Stream
  412. homepageStream("plex", "' . $this->config['homepageStreamRefresh'] . '");
  413. // End Plex Stream
  414. </script>
  415. </div>
  416. ';
  417. }
  418. }
  419. public function homepageOrderplexrecent()
  420. {
  421. if ($this->homepageItemPermissions($this->plexHomepagePermissions('recent'))) {
  422. return '
  423. <div id="' . __FUNCTION__ . '">
  424. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Recent...</h2></div>
  425. <script>
  426. // Plex Recent
  427. homepageRecent("plex", "' . $this->config['homepageRecentRefresh'] . '");
  428. // End Plex Recent
  429. </script>
  430. </div>
  431. ';
  432. }
  433. }
  434. public function homepageOrderplexplaylist()
  435. {
  436. if ($this->homepageItemPermissions($this->plexHomepagePermissions('playlists'))) {
  437. return '
  438. <div id="' . __FUNCTION__ . '">
  439. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Playlists...</h2></div>
  440. <script>
  441. // Plex Playlist
  442. homepagePlaylist("plex");
  443. // End Plex Playlist
  444. </script>
  445. </div>
  446. ';
  447. }
  448. }
  449. public function getPlexHomepageStreams()
  450. {
  451. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('streams'), true)) {
  452. return false;
  453. }
  454. $ignore = array();
  455. $exclude = explode(',', $this->config['homepagePlexStreamsExclude']);
  456. $resolve = true;
  457. $url = $this->qualifyURL($this->config['plexURL']);
  458. $url = $url . "/status/sessions?X-Plex-Token=" . $this->config['plexToken'];
  459. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  460. $response = Requests::get($url, array(), $options);
  461. libxml_use_internal_errors(true);
  462. if ($response->success) {
  463. $items = array();
  464. $plex = simplexml_load_string($response->body);
  465. foreach ($plex as $child) {
  466. if (!in_array($child['type'], $ignore) && !in_array($child['librarySectionID'], $exclude) && isset($child['librarySectionID'])) {
  467. $items[] = $this->resolvePlexItem($child);
  468. }
  469. }
  470. $api['content'] = ($resolve) ? $items : $plex;
  471. $api['plexID'] = $this->config['plexID'];
  472. $api['showNames'] = true;
  473. $api['group'] = '1';
  474. $this->setAPIResponse('success', null, 200, $api);
  475. return $api;
  476. }
  477. }
  478. public function getPlexHomepageRecent()
  479. {
  480. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('recent'), true)) {
  481. return false;
  482. }
  483. $ignore = array();
  484. $resolve = true;
  485. $url = $this->qualifyURL($this->config['plexURL']);
  486. $urls['movie'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $this->config['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $this->config['homepageRecentLimit'] . "&type=1";
  487. $urls['tv'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $this->config['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $this->config['homepageRecentLimit'] . "&type=2";
  488. $urls['music'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $this->config['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $this->config['homepageRecentLimit'] . "&type=8";
  489. foreach ($urls as $k => $v) {
  490. $options = ($this->localURL($v)) ? array('verify' => false) : array();
  491. $response = Requests::get($v, array(), $options);
  492. libxml_use_internal_errors(true);
  493. if ($response->success) {
  494. $items = array();
  495. $plex = simplexml_load_string($response->body);
  496. foreach ($plex as $child) {
  497. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  498. $items[] = $this->resolvePlexItem($child);
  499. }
  500. }
  501. if (isset($api)) {
  502. $api['content'] = array_merge($api['content'], ($resolve) ? $items : $plex);
  503. } else {
  504. $api['content'] = ($resolve) ? $items : $plex;
  505. }
  506. }
  507. }
  508. if (isset($api['content'])) {
  509. usort($api['content'], function ($a, $b) {
  510. return $b['addedAt'] <=> $a['addedAt'];
  511. });
  512. }
  513. $api['plexID'] = $this->config['plexID'];
  514. $api['showNames'] = true;
  515. $api['group'] = '1';
  516. $this->setAPIResponse('success', null, 200, $api);
  517. return $api;
  518. }
  519. public function getPlexHomepagePlaylists()
  520. {
  521. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('playlists'), true)) {
  522. return false;
  523. }
  524. $url = $this->qualifyURL($this->config['plexURL']);
  525. $url = $url . "/playlists?X-Plex-Token=" . $this->config['plexToken'];
  526. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  527. $response = Requests::get($url, array(), $options);
  528. libxml_use_internal_errors(true);
  529. if ($response->success) {
  530. $items = array();
  531. $plex = simplexml_load_string($response->body);
  532. foreach ($plex as $child) {
  533. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
  534. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  535. $playlistURL = $this->qualifyURL($this->config['plexURL']);
  536. $playlistURL = $playlistURL . $child['key'] . "?X-Plex-Token=" . $this->config['plexToken'];
  537. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  538. $playlistResponse = Requests::get($playlistURL, array(), $options);
  539. if ($playlistResponse->success) {
  540. $playlistResponse = simplexml_load_string($playlistResponse->body);
  541. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  542. foreach ($playlistResponse->Video as $playlistItem) {
  543. $items[$playlistTitleClean][] = $this->resolvePlexItem($playlistItem);
  544. }
  545. }
  546. }
  547. }
  548. $api['content'] = $items;
  549. $api['plexID'] = $this->config['plexID'];
  550. $api['showNames'] = true;
  551. $api['group'] = '1';
  552. $this->setAPIResponse('success', null, 200, $api);
  553. return $api;
  554. } else {
  555. $this->setAPIResponse('error', 'Plex API error', 500);
  556. return false;
  557. }
  558. }
  559. public function getPlexHomepageMetadata($array)
  560. {
  561. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('metadata'), true)) {
  562. return false;
  563. }
  564. $key = $array['key'] ?? null;
  565. if (!$key) {
  566. $this->setAPIResponse('error', 'Plex Metadata key is not defined', 422);
  567. return false;
  568. }
  569. $ignore = array();
  570. $resolve = true;
  571. $url = $this->qualifyURL($this->config['plexURL']);
  572. $url = $url . "/library/metadata/" . $key . "?X-Plex-Token=" . $this->config['plexToken'];
  573. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  574. $response = Requests::get($url, array(), $options);
  575. libxml_use_internal_errors(true);
  576. if ($response->success) {
  577. $items = array();
  578. $plex = simplexml_load_string($response->body);
  579. foreach ($plex as $child) {
  580. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  581. $items[] = $this->resolvePlexItem($child);
  582. }
  583. }
  584. $api['content'] = ($resolve) ? $items : $plex;
  585. $api['plexID'] = $this->config['plexID'];
  586. $api['showNames'] = true;
  587. $api['group'] = '1';
  588. $this->setAPIResponse('success', null, 200, $api);
  589. return $api;
  590. }
  591. }
  592. public function getPlexHomepageSearch($query)
  593. {
  594. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('search'), true)) {
  595. return false;
  596. }
  597. $query = $query ?? null;
  598. if (!$query) {
  599. $this->setAPIResponse('error', 'Plex Metadata key is not defined', 422);
  600. return false;
  601. }
  602. $ignore = array('artist', 'episode');
  603. $resolve = true;
  604. $url = $this->qualifyURL($this->config['plexURL']);
  605. $url = $url . "/search?query=" . rawurlencode($query) . "&X-Plex-Token=" . $this->config['plexToken'];
  606. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  607. $response = Requests::get($url, array(), $options);
  608. libxml_use_internal_errors(true);
  609. if ($response->success) {
  610. $items = array();
  611. $plex = simplexml_load_string($response->body);
  612. foreach ($plex as $child) {
  613. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  614. $items[] = $this->resolvePlexItem($child);
  615. }
  616. }
  617. $api['content'] = ($resolve) ? $items : $plex;
  618. $api['plexID'] = $this->config['plexID'];
  619. $api['showNames'] = true;
  620. $api['group'] = '1';
  621. $this->setAPIResponse('success', null, 200, $api);
  622. return $api;
  623. }
  624. }
  625. public function resolvePlexItem($item)
  626. {
  627. // Static Height & Width
  628. $height = $this->getCacheImageSize('h');
  629. $width = $this->getCacheImageSize('w');
  630. $nowPlayingHeight = $this->getCacheImageSize('nph');
  631. $nowPlayingWidth = $this->getCacheImageSize('npw');
  632. // Cache Directories
  633. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  634. $cacheDirectoryWeb = 'plugins/images/cache/';
  635. // Types
  636. switch ($item['type']) {
  637. case 'show':
  638. $plexItem['type'] = 'tv';
  639. $plexItem['title'] = (string)$item['title'];
  640. $plexItem['secondaryTitle'] = (string)$item['year'];
  641. $plexItem['summary'] = (string)$item['summary'];
  642. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  643. $plexItem['thumb'] = (string)$item['thumb'];
  644. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  645. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  646. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  647. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  648. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  649. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  650. break;
  651. case 'season':
  652. $plexItem['type'] = 'tv';
  653. $plexItem['title'] = (string)$item['parentTitle'];
  654. $plexItem['secondaryTitle'] = (string)$item['title'];
  655. $plexItem['summary'] = (string)$item['parentSummary'];
  656. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  657. $plexItem['thumb'] = (string)$item['thumb'];
  658. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  659. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  660. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  661. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  662. break;
  663. case 'episode':
  664. $plexItem['type'] = 'tv';
  665. $plexItem['title'] = (string)$item['grandparentTitle'];
  666. $plexItem['secondaryTitle'] = (string)$item['parentTitle'];
  667. $plexItem['summary'] = (string)$item['title'];
  668. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  669. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  670. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  671. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  672. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  673. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  674. $plexItem['nowPlayingBottom'] = 'S' . (string)$item['parentIndex'] . ' · E' . (string)$item['index'];
  675. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  676. break;
  677. case 'clip':
  678. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  679. $plexItem['type'] = 'clip';
  680. $plexItem['title'] = (isset($item['live']) ? 'Live TV' : (string)$item['title']);
  681. $plexItem['secondaryTitle'] = '';
  682. $plexItem['summary'] = (string)$item['summary'];
  683. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  684. $plexItem['thumb'] = (string)$item['thumb'];
  685. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  686. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  687. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  688. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  689. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  690. break;
  691. case 'album':
  692. case 'track':
  693. $plexItem['type'] = 'music';
  694. $plexItem['title'] = (string)$item['parentTitle'];
  695. $plexItem['secondaryTitle'] = (string)$item['title'];
  696. $plexItem['summary'] = (string)$item['title'];
  697. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  698. $plexItem['thumb'] = (string)$item['thumb'];
  699. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  700. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  701. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  702. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  703. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  704. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  705. break;
  706. default:
  707. $plexItem['type'] = 'movie';
  708. $plexItem['title'] = (string)$item['title'];
  709. $plexItem['secondaryTitle'] = (string)$item['year'];
  710. $plexItem['summary'] = (string)$item['summary'];
  711. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  712. $plexItem['thumb'] = (string)$item['thumb'];
  713. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  714. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  715. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  716. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  717. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  718. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  719. }
  720. $plexItem['originalType'] = $item['type'];
  721. $plexItem['uid'] = (string)$item['ratingKey'];
  722. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  723. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  724. $plexItem['addedAt'] = isset($item['addedAt']) ? (int)$item['addedAt'] : null;
  725. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  726. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress'] - $plexItem['watched']) : '';
  727. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision'] : '';
  728. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  729. $plexItem['session'] = (string)$item->Session['id'];
  730. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  731. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  732. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  733. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  734. $plexItem['user'] = $this->formatPlexUserName($item);
  735. $plexItem['userThumb'] = ($this->config['homepageShowStreamNames'] && $this->qualifyRequest($this->config['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
  736. $plexItem['userAddress'] = ($this->config['homepageShowStreamNames'] && $this->qualifyRequest($this->config['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
  737. $plexItem['address'] = $this->config['plexTabURL'] ? $this->config['plexTabURL'] . "/web/index.html#!/server/" . $this->config['plexID'] . "/details?key=/library/metadata/" . $item['ratingKey'] : "https://app.plex.tv/web/app#!/server/" . $this->config['plexID'] . "/details?key=/library/metadata/" . $item['ratingKey'];
  738. $plexItem['nowPlayingOriginalImage'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '$' . $this->randString();
  739. $plexItem['originalImage'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '$' . $this->randString();
  740. $plexItem['openTab'] = $this->config['plexTabURL'] && $this->config['plexTabName'] ? true : false;
  741. $plexItem['tabName'] = $this->config['plexTabName'] ? $this->config['plexTabName'] : '';
  742. // Stream info
  743. $plexItem['userStream'] = array(
  744. 'platform' => (string)$item->Player['platform'],
  745. 'product' => (string)$item->Player['product'],
  746. 'device' => (string)$item->Player['device'],
  747. 'stream' => isset($item->Media) ? (string)$item->Media->Part['decision'] . ($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)' : '') : '',
  748. 'videoResolution' => (string)$item->Media['videoResolution'],
  749. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  750. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  751. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  752. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  753. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  754. 'videoDecision' => $this->streamType((string)$item->TranscodeSession['videoDecision']),
  755. 'audioDecision' => $this->streamType((string)$item->TranscodeSession['audioDecision']),
  756. 'container' => (string)$item->TranscodeSession['container'],
  757. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  758. );
  759. // Genre catch all
  760. if ($item->Genre) {
  761. $genres = array();
  762. foreach ($item->Genre as $key => $value) {
  763. $genres[] = (string)$value['tag'];
  764. }
  765. }
  766. // Actor catch all
  767. if ($item->Role) {
  768. $actors = array();
  769. foreach ($item->Role as $key => $value) {
  770. if ($value['thumb']) {
  771. $actors[] = array(
  772. 'name' => (string)$value['tag'],
  773. 'role' => (string)$value['role'],
  774. 'thumb' => (string)$value['thumb']
  775. );
  776. }
  777. }
  778. }
  779. // Metadata information
  780. $plexItem['metadata'] = array(
  781. 'guid' => (string)$item['guid'],
  782. 'summary' => (string)$item['summary'],
  783. 'rating' => (string)$item['rating'],
  784. 'duration' => (string)$item['duration'],
  785. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  786. 'year' => (string)$item['year'],
  787. 'studio' => (string)$item['studio'],
  788. 'tagline' => (string)$item['tagline'],
  789. 'genres' => ($item->Genre) ? $genres : '',
  790. 'actors' => ($item->Role) ? $actors : ''
  791. );
  792. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  793. $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $plexItem['nowPlayingKey'] . '.jpg';
  794. }
  795. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  796. $plexItem['imageURL'] = $cacheDirectoryWeb . $plexItem['key'] . '.jpg';
  797. }
  798. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  799. $plexItem['nowPlayingImageURL'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '';
  800. }
  801. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['key'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  802. $plexItem['imageURL'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '';
  803. }
  804. if (!$plexItem['nowPlayingThumb']) {
  805. $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  806. $plexItem['nowPlayingKey'] = "no-np";
  807. }
  808. if (!$plexItem['thumb'] || $plexItem['addedAt'] >= (time() - 300)) {
  809. $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
  810. $plexItem['key'] = "no-list";
  811. }
  812. if (isset($useImage)) {
  813. $plexItem['useImage'] = $useImage;
  814. }
  815. return $plexItem;
  816. }
  817. public function getTautulliFriendlyNames()
  818. {
  819. if (!$this->qualifyRequest(1)) {
  820. return false;
  821. }
  822. $url = $this->qualifyURL($this->config['tautulliURL']);
  823. $url .= '/api/v2?apikey=' . $this->config['tautulliApikey'];
  824. $url .= '&cmd=get_users';
  825. $response = Requests::get($url, [], []);
  826. $names = [];
  827. try {
  828. $response = json_decode($response->body, true);
  829. foreach ($response['response']['data'] as $user) {
  830. if ($user['user_id'] != 0) {
  831. $names[$user['username']] = $user['friendly_name'];
  832. }
  833. }
  834. } catch (Exception $e) {
  835. $this->setAPIResponse('failure', null, 422, [$e->getMessage()]);
  836. }
  837. $this->setAPIResponse('success', null, 200, $names);
  838. }
  839. private function formatPlexUserName($item)
  840. {
  841. $name = ($this->config['homepageShowStreamNames'] && $this->qualifyRequest($this->config['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
  842. try {
  843. if ($this->config['homepageUseCustomStreamNames']) {
  844. $customNames = json_decode($this->config['homepageCustomStreamNames'], true);
  845. if (array_key_exists($name, $customNames)) {
  846. $name = $customNames[$name];
  847. }
  848. }
  849. } catch (Exception $e) {
  850. // don't do anythig if it goes wrong, like if the JSON is badly formatted
  851. }
  852. return $name;
  853. }
  854. public function plexLibraryList($value = 'id')
  855. {
  856. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  857. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'];
  858. try {
  859. $headers = array(
  860. "Accept" => "application/json",
  861. "X-Plex-Token" => $this->config['plexToken']
  862. );
  863. $response = Requests::get($url, $headers, array());
  864. libxml_use_internal_errors(true);
  865. if ($response->success) {
  866. $libraryList = array();
  867. $plex = simplexml_load_string($response->body);
  868. foreach ($plex->Server->Section as $child) {
  869. $libraryList['libraries'][(string)$child['title']] = (string)$child[$value];
  870. }
  871. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  872. return $libraryList;
  873. }
  874. } catch (Requests_Exception $e) {
  875. $this->writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  876. return false;
  877. };
  878. }
  879. return false;
  880. }
  881. }