plex.php 33 KB

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