plex.php 30 KB

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