plex.php 29 KB

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