plex.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. if (array_key_exists($key, $permissions)) {
  183. return $permissions[$key];
  184. } elseif ($key == 'all') {
  185. return $permissions;
  186. } else {
  187. return [];
  188. }
  189. }
  190. public function homepageOrderplexnowplaying()
  191. {
  192. if ($this->homepageItemPermissions($this->plexHomepagePermissions('streams'))) {
  193. return '
  194. <div id="' . __FUNCTION__ . '">
  195. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Now Playing...</h2></div>
  196. <script>
  197. // Plex Stream
  198. homepageStream("plex", "' . $this->config['homepageStreamRefresh'] . '");
  199. // End Plex Stream
  200. </script>
  201. </div>
  202. ';
  203. }
  204. }
  205. public function homepageOrderplexrecent()
  206. {
  207. if ($this->homepageItemPermissions($this->plexHomepagePermissions('recent'))) {
  208. return '
  209. <div id="' . __FUNCTION__ . '">
  210. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Recent...</h2></div>
  211. <script>
  212. // Plex Recent
  213. homepageRecent("plex", "' . $this->config['homepageRecentRefresh'] . '");
  214. // End Plex Recent
  215. </script>
  216. </div>
  217. ';
  218. }
  219. }
  220. public function homepageOrderplexplaylist()
  221. {
  222. if ($this->homepageItemPermissions($this->plexHomepagePermissions('playlists'))) {
  223. return '
  224. <div id="' . __FUNCTION__ . '">
  225. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Playlists...</h2></div>
  226. <script>
  227. // Plex Playlist
  228. homepagePlaylist("plex");
  229. // End Plex Playlist
  230. </script>
  231. </div>
  232. ';
  233. }
  234. }
  235. public function getPlexHomepageStreams()
  236. {
  237. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('streams'), true)) {
  238. return false;
  239. }
  240. $this->setTautulliFriendlyNames();
  241. $ignore = array();
  242. $exclude = explode(',', $this->config['homepagePlexStreamsExclude']);
  243. $resolve = true;
  244. $url = $this->qualifyURL($this->config['plexURL']);
  245. $url = $url . "/status/sessions?X-Plex-Token=" . $this->config['plexToken'];
  246. $options = $this->requestOptions($url, $this->config['homepageStreamRefresh'], $this->config['plexDisableCertCheck'], $this->config['plexUseCustomCertificate']);
  247. $response = Requests::get($url, [], $options);
  248. libxml_use_internal_errors(true);
  249. if ($response->success) {
  250. $items = array();
  251. $plex = simplexml_load_string($response->body);
  252. foreach ($plex as $child) {
  253. if (!in_array($child['type'], $ignore) && !in_array($child['librarySectionID'], $exclude) && isset($child['librarySectionID'])) {
  254. $items[] = $this->resolvePlexItem($child);
  255. }
  256. }
  257. $api['content'] = ($resolve) ? $items : $plex;
  258. $api['plexID'] = $this->config['plexID'];
  259. $api['showNames'] = true;
  260. $api['group'] = '1';
  261. $this->setAPIResponse('success', null, 200, $api);
  262. return $api;
  263. }
  264. }
  265. public function getPlexHomepageRecent()
  266. {
  267. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('recent'), true)) {
  268. return false;
  269. }
  270. $ignore = array();
  271. $exclude = explode(',', $this->config['homepagePlexRecentExclude']);
  272. $resolve = true;
  273. $url = $this->qualifyURL($this->config['plexURL']);
  274. $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";
  275. $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";
  276. $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";
  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. }
  307. public function getPlexHomepagePlaylists()
  308. {
  309. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('playlists'), true)) {
  310. return false;
  311. }
  312. $url = $this->qualifyURL($this->config['plexURL']);
  313. $url = $url . "/playlists?X-Plex-Token=" . $this->config['plexToken'];
  314. $options = $this->requestOptions($url, null, $this->config['plexDisableCertCheck'], $this->config['plexUseCustomCertificate']);
  315. $response = Requests::get($url, [], $options);
  316. libxml_use_internal_errors(true);
  317. if ($response->success) {
  318. $items = array();
  319. $plex = simplexml_load_string($response->body);
  320. foreach ($plex as $child) {
  321. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
  322. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  323. $playlistURL = $this->qualifyURL($this->config['plexURL']);
  324. $playlistURL = $playlistURL . $child['key'] . "?X-Plex-Token=" . $this->config['plexToken'];
  325. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  326. $playlistResponse = Requests::get($playlistURL, array(), $options);
  327. if ($playlistResponse->success) {
  328. $playlistResponse = simplexml_load_string($playlistResponse->body);
  329. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  330. foreach ($playlistResponse->Video as $playlistItem) {
  331. $items[$playlistTitleClean][] = $this->resolvePlexItem($playlistItem);
  332. }
  333. }
  334. }
  335. }
  336. $api['content'] = $items;
  337. $api['plexID'] = $this->config['plexID'];
  338. $api['showNames'] = true;
  339. $api['group'] = '1';
  340. $this->setAPIResponse('success', null, 200, $api);
  341. return $api;
  342. } else {
  343. $this->setAPIResponse('error', 'Plex API error', 500);
  344. return false;
  345. }
  346. }
  347. public function getPlexHomepageMetadata($array)
  348. {
  349. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('metadata'), true)) {
  350. return false;
  351. }
  352. $key = $array['key'] ?? null;
  353. if (!$key) {
  354. $this->setAPIResponse('error', 'Plex Metadata key is not defined', 422);
  355. return false;
  356. }
  357. $ignore = array();
  358. $resolve = true;
  359. $url = $this->qualifyURL($this->config['plexURL']);
  360. $url = $url . "/library/metadata/" . $key . "?X-Plex-Token=" . $this->config['plexToken'];
  361. $options = $this->requestOptions($url, null, $this->config['plexDisableCertCheck'], $this->config['plexUseCustomCertificate']);
  362. $response = Requests::get($url, [], $options);
  363. libxml_use_internal_errors(true);
  364. if ($response->success) {
  365. $items = array();
  366. $plex = simplexml_load_string($response->body);
  367. foreach ($plex as $child) {
  368. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  369. $items[] = $this->resolvePlexItem($child);
  370. }
  371. }
  372. $api['content'] = ($resolve) ? $items : $plex;
  373. $api['plexID'] = $this->config['plexID'];
  374. $api['showNames'] = true;
  375. $api['group'] = '1';
  376. $this->setAPIResponse('success', null, 200, $api);
  377. return $api;
  378. }
  379. }
  380. public function getPlexHomepageSearch($query)
  381. {
  382. if (!$this->homepageItemPermissions($this->plexHomepagePermissions('search'), true)) {
  383. return false;
  384. }
  385. $query = $query ?? null;
  386. if (!$query) {
  387. $this->setAPIResponse('error', 'Plex Metadata key is not defined', 422);
  388. return false;
  389. }
  390. $ignore = array('artist', 'episode');
  391. $exclude = explode(',', $this->config['homepagePlexSearchExclude']);
  392. $resolve = true;
  393. $url = $this->qualifyURL($this->config['plexURL']);
  394. $url = $url . "/search?query=" . rawurlencode($query) . "&X-Plex-Token=" . $this->config['plexToken'];
  395. $options = $this->requestOptions($url, null, $this->config['plexDisableCertCheck'], $this->config['plexUseCustomCertificate']);
  396. $response = Requests::get($url, [], $options);
  397. libxml_use_internal_errors(true);
  398. if ($response->success) {
  399. $items = array();
  400. $plex = simplexml_load_string($response->body);
  401. foreach ($plex as $child) {
  402. if (!in_array($child['type'], $ignore) && !in_array($child['librarySectionID'], $exclude) && isset($child['librarySectionID'])) {
  403. $items[] = $this->resolvePlexItem($child);
  404. }
  405. }
  406. $api['content'] = ($resolve) ? $items : $plex;
  407. $api['plexID'] = $this->config['plexID'];
  408. $api['showNames'] = true;
  409. $api['group'] = '1';
  410. $this->setAPIResponse('success', null, 200, $api);
  411. return $api;
  412. }
  413. }
  414. public function resolvePlexItem($item)
  415. {
  416. // Static Height & Width
  417. $height = $this->getCacheImageSize('h');
  418. $width = $this->getCacheImageSize('w');
  419. $nowPlayingHeight = $this->getCacheImageSize('nph');
  420. $nowPlayingWidth = $this->getCacheImageSize('npw');
  421. // Cache Directories
  422. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  423. $cacheDirectoryWeb = 'plugins/images/cache/';
  424. // Types
  425. switch ($item['type']) {
  426. case 'show':
  427. $plexItem['type'] = 'tv';
  428. $plexItem['title'] = (string)$item['title'];
  429. $plexItem['secondaryTitle'] = (string)$item['year'];
  430. $plexItem['summary'] = (string)$item['summary'];
  431. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  432. $plexItem['thumb'] = (string)$item['thumb'];
  433. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  434. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  435. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  436. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  437. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  438. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  439. break;
  440. case 'season':
  441. $plexItem['type'] = 'tv';
  442. $plexItem['title'] = (string)$item['parentTitle'];
  443. $plexItem['secondaryTitle'] = (string)$item['title'];
  444. $plexItem['summary'] = (string)$item['parentSummary'];
  445. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  446. $plexItem['thumb'] = (string)$item['thumb'];
  447. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  448. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  449. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  450. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  451. break;
  452. case 'episode':
  453. $plexItem['type'] = 'tv';
  454. $plexItem['title'] = (string)$item['grandparentTitle'];
  455. $plexItem['secondaryTitle'] = (string)$item['parentTitle'];
  456. $plexItem['summary'] = (string)$item['title'];
  457. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  458. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  459. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  460. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  461. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  462. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  463. $plexItem['nowPlayingBottom'] = 'S' . (string)$item['parentIndex'] . ' · E' . (string)$item['index'];
  464. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  465. break;
  466. case 'clip':
  467. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  468. $plexItem['type'] = 'clip';
  469. $plexItem['title'] = (isset($item['live']) ? 'Live TV' : (string)$item['title']);
  470. $plexItem['secondaryTitle'] = '';
  471. $plexItem['summary'] = (string)$item['summary'];
  472. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  473. $plexItem['thumb'] = (string)$item['thumb'];
  474. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  475. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  476. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  477. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  478. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  479. break;
  480. case 'album':
  481. case 'track':
  482. $plexItem['type'] = 'music';
  483. $plexItem['title'] = (string)$item['parentTitle'];
  484. $plexItem['secondaryTitle'] = (string)$item['title'];
  485. $plexItem['summary'] = (string)$item['title'];
  486. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  487. $plexItem['thumb'] = (string)$item['thumb'];
  488. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  489. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  490. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  491. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  492. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  493. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  494. break;
  495. default:
  496. $plexItem['type'] = 'movie';
  497. $plexItem['title'] = (string)$item['title'];
  498. $plexItem['secondaryTitle'] = (string)$item['year'];
  499. $plexItem['summary'] = (string)$item['summary'];
  500. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  501. $plexItem['thumb'] = (string)$item['thumb'];
  502. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  503. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  504. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  505. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  506. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  507. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  508. }
  509. $plexItem['originalType'] = $item['type'];
  510. $plexItem['uid'] = (string)$item['ratingKey'];
  511. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  512. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  513. $plexItem['addedAt'] = isset($item['addedAt']) ? (int)$item['addedAt'] : null;
  514. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  515. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress'] - $plexItem['watched']) : '';
  516. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision'] : '';
  517. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  518. $plexItem['session'] = (string)$item->Session['id'];
  519. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  520. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  521. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  522. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  523. $plexItem['user'] = $this->formatPlexUserName($item);
  524. $plexItem['userThumb'] = ($this->config['homepageShowStreamNames'] && $this->qualifyRequest($this->config['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
  525. $plexItem['userAddress'] = ($this->config['homepageShowStreamNames'] && $this->qualifyRequest($this->config['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
  526. $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'];
  527. $plexItem['nowPlayingOriginalImage'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '$' . $this->randString();
  528. $plexItem['originalImage'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '$' . $this->randString();
  529. $plexItem['openTab'] = $this->config['plexTabURL'] && $this->config['plexTabName'] ? true : false;
  530. $plexItem['tabName'] = $this->config['plexTabName'] ? $this->config['plexTabName'] : '';
  531. // Stream info
  532. $plexItem['userStream'] = array(
  533. 'platform' => (string)$item->Player['platform'],
  534. 'product' => (string)$item->Player['product'],
  535. 'device' => (string)$item->Player['device'],
  536. 'stream' => isset($item->Media) ? (string)$item->Media->Part['decision'] . ($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)' : '') : '',
  537. 'videoResolution' => (string)$item->Media['videoResolution'],
  538. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  539. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  540. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  541. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  542. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  543. 'videoDecision' => $this->streamType((string)$item->TranscodeSession['videoDecision']),
  544. 'audioDecision' => $this->streamType((string)$item->TranscodeSession['audioDecision']),
  545. 'container' => (string)$item->TranscodeSession['container'],
  546. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  547. );
  548. // Genre catch all
  549. if ($item->Genre) {
  550. $genres = array();
  551. foreach ($item->Genre as $key => $value) {
  552. $genres[] = (string)$value['tag'];
  553. }
  554. }
  555. // Actor catch all
  556. if ($item->Role) {
  557. $actors = array();
  558. foreach ($item->Role as $key => $value) {
  559. if ($value['thumb']) {
  560. $actors[] = array(
  561. 'name' => (string)$value['tag'],
  562. 'role' => (string)$value['role'],
  563. 'thumb' => (string)$value['thumb']
  564. );
  565. }
  566. }
  567. }
  568. // Metadata information
  569. $plexItem['metadata'] = array(
  570. 'guid' => (string)$item['guid'],
  571. 'summary' => (string)$item['summary'],
  572. 'rating' => (string)$item['rating'],
  573. 'duration' => (string)$item['duration'],
  574. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  575. 'year' => (string)$item['year'],
  576. 'studio' => (string)$item['studio'],
  577. 'tagline' => (string)$item['tagline'],
  578. 'genres' => ($item->Genre) ? $genres : '',
  579. 'actors' => ($item->Role) ? $actors : ''
  580. );
  581. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  582. $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $plexItem['nowPlayingKey'] . '.jpg';
  583. }
  584. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  585. $plexItem['imageURL'] = $cacheDirectoryWeb . $plexItem['key'] . '.jpg';
  586. }
  587. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  588. $plexItem['nowPlayingImageURL'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '';
  589. }
  590. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['key'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  591. $plexItem['imageURL'] = 'api/v2/homepage/image?source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '';
  592. }
  593. if (!$plexItem['nowPlayingThumb']) {
  594. $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  595. $plexItem['nowPlayingKey'] = "no-np";
  596. }
  597. if (!$plexItem['thumb'] || $plexItem['addedAt'] >= (time() - 300)) {
  598. $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
  599. $plexItem['key'] = "no-list";
  600. }
  601. if (isset($useImage)) {
  602. $plexItem['useImage'] = $useImage;
  603. }
  604. return $plexItem;
  605. }
  606. public function getTautulliFriendlyNames($bypass = null)
  607. {
  608. $names = [];
  609. if (!$this->qualifyRequest(1) && !$bypass) {
  610. return false;
  611. }
  612. $url = $this->qualifyURL($this->config['tautulliURL']);
  613. $url .= '/api/v2?apikey=' . $this->config['tautulliApikey'];
  614. $url .= '&cmd=get_users';
  615. $options = $this->requestOptions($url, null, $this->config['tautulliDisableCertCheck'], $this->config['tautulliUseCustomCertificate']);
  616. $response = Requests::get($url, [], $options);
  617. try {
  618. $response = json_decode($response->body, true);
  619. foreach ($response['response']['data'] as $user) {
  620. if ($user['user_id'] != 0) {
  621. $names[$user['username']] = $user['friendly_name'];
  622. }
  623. }
  624. } catch (Exception $e) {
  625. $this->setAPIResponse('error', null, 422, [$e->getMessage()]);
  626. }
  627. $this->setAPIResponse('success', null, 200, $names);
  628. return $names;
  629. }
  630. public function setTautulliFriendlyNames()
  631. {
  632. if ($this->config['tautulliURL'] && $this->config['tautulliApikey'] && $this->config['homepageUseCustomStreamNames']) {
  633. $names = $this->getTautulliFriendlyNames(true);
  634. if (json_encode($names) !== $this->config['homepageCustomStreamNames']) {
  635. $this->updateConfig(array('homepageCustomStreamNames' => json_encode($names)));
  636. $this->config['homepageCustomStreamNames'] = json_encode($names);
  637. $this->debug('Updating Tautulli custom names config item', 'SYSTEM');
  638. }
  639. }
  640. }
  641. private function formatPlexUserName($item)
  642. {
  643. $name = ($this->config['homepageShowStreamNames'] && $this->qualifyRequest($this->config['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
  644. try {
  645. if ($this->config['homepageUseCustomStreamNames']) {
  646. $customNames = json_decode($this->config['homepageCustomStreamNames'], true);
  647. if (array_key_exists($name, $customNames)) {
  648. $name = $customNames[$name];
  649. }
  650. }
  651. } catch (Exception $e) {
  652. // don't do anythig if it goes wrong, like if the JSON is badly formatted
  653. }
  654. return $name;
  655. }
  656. public function plexLibraryList($value = 'id')
  657. {
  658. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  659. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'];
  660. try {
  661. $headers = array(
  662. "Accept" => "application/json",
  663. "X-Plex-Token" => $this->config['plexToken']
  664. );
  665. $response = Requests::get($url, $headers, array());
  666. libxml_use_internal_errors(true);
  667. if ($response->success) {
  668. $libraryList = array();
  669. $plex = simplexml_load_string($response->body);
  670. foreach ($plex->Server->Section as $child) {
  671. $libraryList['libraries'][(string)$child['title']] = (string)$child[$value];
  672. }
  673. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  674. return $libraryList;
  675. }
  676. } catch (Requests_Exception $e) {
  677. $this->writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  678. return false;
  679. };
  680. }
  681. return false;
  682. }
  683. }