plex.php 31 KB

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