plex.php 32 KB

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