plex.php 30 KB

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