plex.php 33 KB

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