plex.php 33 KB

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