homepage-connect-functions.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. <?php
  2. function homepageConnect($array){
  3. switch ($array['data']['action']) {
  4. case 'getPlexStreams':
  5. return plexConnect('streams');
  6. break;
  7. case 'getPlexRecent':
  8. return plexConnect('recent');
  9. break;
  10. case 'getPlexMetadata':
  11. return plexConnect('metadata',$array['data']['key']);
  12. break;
  13. case 'getEmbyStreams':
  14. return embyConnect('streams');
  15. break;
  16. case 'getEmbyRecent':
  17. return embyConnect('recent');
  18. break;
  19. case 'getEmbyMetadata':
  20. return embyConnect('metadata',$array['data']['key'],true);
  21. break;
  22. case 'getSabnzbd':
  23. return sabnzbdConnect();
  24. break;
  25. case 'getNzbget':
  26. return nzbgetConnect();
  27. break;
  28. case 'getTransmission':
  29. return transmissionConnect();
  30. break;
  31. case 'getqBittorrent':
  32. return qBittorrentConnect();
  33. break;
  34. case 'getDeluge':
  35. return delugeConnect();
  36. break;
  37. case 'getCalendar':
  38. return getCalendar();
  39. break;
  40. default:
  41. # code...
  42. break;
  43. }
  44. }
  45. function streamType($value){
  46. if($value == "transcode" || $value == "Transcode"){
  47. return "Transcode";
  48. }elseif($value == "copy" || $value == "DirectStream"){
  49. return "Direct Stream";
  50. }elseif($value == "directplay" || $value == "DirectPlay"){
  51. return "Direct Play";
  52. }else{
  53. return "Direct Play";
  54. }
  55. }
  56. function resolveEmbyItem($itemDetails) {
  57. // Grab Each item info from Emby (extra call)
  58. $id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
  59. $url = qualifyURL($GLOBALS['embyURL']);
  60. $url = $url.'/Items?Ids='.$id.'&api_key='.$GLOBALS['embyToken'].'&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  61. try{
  62. $options = (localURL($url)) ? array('verify' => false ) : array();
  63. $response = Requests::get($url, array(), $options);
  64. if($response->success){
  65. $item = json_decode($response->body,true)['Items'][0];
  66. }
  67. }catch( Requests_Exception $e ) {
  68. return false;
  69. };
  70. // Static Height & Width
  71. $height = 300;
  72. $width = 200;
  73. $nowPlayingHeight = 675;
  74. $nowPlayingWidth = 1200;
  75. $actorHeight = 450;
  76. $actorWidth = 300;
  77. $widthOverride = 100;
  78. // Cache Directories
  79. $cacheDirectory = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  80. $cacheDirectoryWeb = 'plugins/images/cache/';
  81. // Types
  82. $embyItem['array-item'] = $item;
  83. $embyItem['array-itemdetails'] = $itemDetails;
  84. switch (@$item['Type']) {
  85. case 'Series':
  86. $embyItem['type'] = 'tv';
  87. $embyItem['title'] = $item['Name'];
  88. $embyItem['summary'] = '';
  89. $embyItem['ratingKey'] = $item['Id'];
  90. $embyItem['thumb'] = $item['Id'];
  91. $embyItem['key'] = $item['Id'] . "-list";
  92. $embyItem['nowPlayingThumb'] = $item['Id'];
  93. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  94. $embyItem['metadataKey'] = $item['Id'];
  95. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
  96. break;
  97. case 'Episode':
  98. $embyItem['type'] = 'tv';
  99. $embyItem['title'] = $item['SeriesName'];
  100. $embyItem['summary'] = '';
  101. $embyItem['ratingKey'] = $item['Id'];
  102. $embyItem['thumb'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']);
  103. $embyItem['key'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']) . "-list";
  104. $embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
  105. $embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'].'-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'].'-np' : false);
  106. $embyItem['metadataKey'] = $item['Id'];
  107. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
  108. $embyItem['nowPlayingTitle'] = @$item['SeriesName'].' - '.@$item['Name'];
  109. $embyItem['nowPlayingBottom'] = 'S'.@$item['ParentIndexNumber'].' · E'.@$item['IndexNumber'];
  110. break;
  111. case 'MusicAlbum':
  112. case 'Audio':
  113. $embyItem['type'] = 'music';
  114. $embyItem['title'] = $item['Name'];
  115. $embyItem['summary'] = '';
  116. $embyItem['ratingKey'] = $item['Id'];
  117. $embyItem['thumb'] = $item['Id'];
  118. $embyItem['key'] = $item['Id'] . "-list";
  119. $embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
  120. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  121. $embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
  122. $embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
  123. $embyItem['nowPlayingTitle'] = @$item['AlbumArtist'].' - '.@$item['Name'];
  124. $embyItem['nowPlayingBottom'] = @$item['Album'];
  125. break;
  126. case 'Movie':
  127. $embyItem['type'] = 'movie';
  128. $embyItem['title'] = $item['Name'];
  129. $embyItem['summary'] = '';
  130. $embyItem['ratingKey'] = $item['Id'];
  131. $embyItem['thumb'] = $item['Id'];
  132. $embyItem['key'] = $item['Id'] . "-list";
  133. $embyItem['nowPlayingThumb'] = $item['Id'];
  134. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  135. $embyItem['metadataKey'] = $item['Id'];
  136. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  137. $embyItem['nowPlayingTitle'] = @$item['Name'];
  138. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  139. break;
  140. case 'Video':
  141. $embyItem['type'] = 'video';
  142. $embyItem['title'] = $item['Name'];
  143. $embyItem['summary'] = '';
  144. $embyItem['ratingKey'] = $item['Id'];
  145. $embyItem['thumb'] = $item['Id'];
  146. $embyItem['key'] = $item['Id'] . "-list";
  147. $embyItem['nowPlayingThumb'] = $item['Id'];
  148. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  149. $embyItem['metadataKey'] = $item['Id'];
  150. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  151. $embyItem['nowPlayingTitle'] = @$item['Name'];
  152. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  153. break;
  154. default:
  155. return false;
  156. }
  157. $embyItem['uid'] = $item['Id'];
  158. $embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
  159. $embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
  160. $embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)$item['RunTimeTicks'];
  161. $embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
  162. $embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
  163. $embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
  164. $embyItem['id'] = $item['ServerId'];
  165. $embyItem['session'] = @$itemDetails['DeviceId'];
  166. $embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
  167. $embyItem['bandwidthType'] = 'wan';
  168. $embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
  169. $embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
  170. $embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? @(string)$itemDetails['UserName'] : "";
  171. $embyItem['userThumb'] = '';
  172. $embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
  173. $embyItem['address'] = $GLOBALS['embyTabURL'] ? '' : '';
  174. $embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'$'.randString();
  175. $embyItem['originalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'$'.randString();
  176. $embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
  177. $embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
  178. // Stream info
  179. $embyItem['userStream'] = array(
  180. 'platform' => @(string)$itemDetails['Client'],
  181. 'product' => @(string)$itemDetails['Client'],
  182. 'device' => @(string)$itemDetails['DeviceName'],
  183. 'stream' => @$itemDetails['PlayState']['PlayMethod'],
  184. 'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
  185. 'throttled' => false,
  186. 'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
  187. 'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
  188. 'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
  189. 'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
  190. 'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  191. 'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  192. 'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
  193. 'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
  194. );
  195. // Genre catch all
  196. if($item['Genres']){
  197. $genres = array();
  198. foreach ($item['Genres'] as $genre) {
  199. $genres[] = $genre;
  200. }
  201. }
  202. // Actor catch all
  203. if($item['People'] ){
  204. $actors = array();
  205. foreach ($item['People'] as $key => $value) {
  206. if(@$value['PrimaryImageTag'] && @$value['Role']){
  207. if (file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg')){ $actorImage = $cacheDirectoryWeb.(string)$value['Id'].'-cast.jpg'; }
  208. if (file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg') && (time() - 604800) > filemtime($cacheDirectory.(string)$value['Id'].'-cast.jpg') || !file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg')) {
  209. $actorImage = 'api/?v1/image&source=emby&type=Primary&img='.(string)$value['Id'].'&height='.$actorHeight.'&width='.$actorWidth.'&key='.(string)$value['Id'].'-cast';
  210. }
  211. $actors[] = array(
  212. 'name' => (string)$value['Name'],
  213. 'role' => (string)$value['Role'],
  214. 'thumb' => $actorImage
  215. );
  216. }
  217. }
  218. }
  219. // Metadata information
  220. $embyItem['metadata'] = array(
  221. 'guid' => $item['Id'],
  222. 'summary' => @(string)$item['Overview'],
  223. 'rating' => @(string)$item['CommunityRating'],
  224. 'duration' => @(string)$item['RunTimeTicks'],
  225. 'originallyAvailableAt' => @(string)$item['PremiereDate'],
  226. 'year' => (string)$item['ProductionYear'],
  227. //'studio' => (string)$item['studio'],
  228. 'tagline' => @(string)$item['Taglines'][0],
  229. 'genres' => ($item['Genres']) ? $genres : '',
  230. 'actors' => ($item['People']) ? $actors : ''
  231. );
  232. if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')){ $embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$embyItem['nowPlayingKey'].'.jpg'; }
  233. if (file_exists($cacheDirectory.$embyItem['key'].'.jpg')){ $embyItem['imageURL'] = $cacheDirectoryWeb.$embyItem['key'].'.jpg'; }
  234. if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')) {
  235. $embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'';
  236. }
  237. if (file_exists($cacheDirectory.$embyItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['key'].'.jpg') || !file_exists($cacheDirectory.$embyItem['key'].'.jpg')) {
  238. $embyItem['imageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'';
  239. }
  240. if(!$embyItem['nowPlayingThumb'] ){ $embyItem['nowPlayingOriginalImage'] = $embyItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png"; $embyItem['nowPlayingKey'] = "no-np"; }
  241. if(!$embyItem['thumb'] ){ $embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png"; $embyItem['key'] = "no-list"; }
  242. if(isset($useImage)){ $embyItem['useImage'] = $useImage; }
  243. return $embyItem;
  244. }
  245. function resolvePlexItem($item) {
  246. // Static Height & Width
  247. $height = 300;
  248. $width = 200;
  249. $nowPlayingHeight = 675;
  250. $nowPlayingWidth = 1200;
  251. $widthOverride = 100;
  252. // Cache Directories
  253. $cacheDirectory = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  254. $cacheDirectoryWeb = 'plugins/images/cache/';
  255. // Types
  256. switch ($item['type']) {
  257. case 'season':
  258. $plexItem['type'] = 'tv';
  259. $plexItem['title'] = (string)$item['parentTitle'];
  260. $plexItem['summary'] = (string)$item['parentSummary'];
  261. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  262. $plexItem['thumb'] = (string)$item['thumb'];
  263. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  264. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  265. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  266. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  267. break;
  268. case 'episode':
  269. $plexItem['type'] = 'tv';
  270. $plexItem['title'] = (string)$item['grandparentTitle'];
  271. $plexItem['summary'] = (string)$item['title'];
  272. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  273. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  274. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  275. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  276. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  277. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
  278. $plexItem['nowPlayingBottom'] = 'S'.(string)$item['parentIndex'].' · E'.(string)$item['index'];
  279. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  280. break;
  281. case 'clip':
  282. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  283. $plexItem['type'] = 'clip';
  284. $plexItem['title'] = (string)$item['title'];
  285. $plexItem['summary'] = (string)$item['summary'];
  286. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  287. $plexItem['thumb'] = (string)$item['thumb'];
  288. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  289. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  290. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  291. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  292. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  293. break;
  294. case 'album':
  295. case 'track':
  296. $plexItem['type'] = 'music';
  297. $plexItem['title'] = (string)$item['parentTitle'];
  298. $plexItem['summary'] = (string)$item['title'];
  299. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  300. $plexItem['thumb'] = (string)$item['thumb'];
  301. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  302. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  303. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  304. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
  305. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  306. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  307. break;
  308. default:
  309. $plexItem['type'] = 'movie';
  310. $plexItem['title'] = (string)$item['title'];
  311. $plexItem['summary'] = (string)$item['summary'];
  312. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  313. $plexItem['thumb'] = (string)$item['thumb'];
  314. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  315. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  316. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  317. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  318. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  319. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  320. }
  321. $plexItem['uid'] = (string)$item['ratingKey'];
  322. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  323. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  324. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  325. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress']- $plexItem['watched']) : '';
  326. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision']: '';
  327. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  328. $plexItem['session'] = (string)$item->Session['id'];
  329. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  330. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  331. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  332. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  333. $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? (string)$item->User['title'] : "";
  334. $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? (string)$item->User['thumb'] : "";
  335. $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? (string)$item->Player['address'] : "x.x.x.x";
  336. $plexItem['address'] = $GLOBALS['plexTabURL'] ? $GLOBALS['plexTabURL']."/web/index.html#!/server/".$GLOBALS['plexID']."/details?key=/library/metadata/".$item['ratingKey'] : "https://app.plex.tv/web/app#!/server/".$GLOBALS['plexID']."/details?key=/library/metadata/".$item['ratingKey'];
  337. $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'$'.randString();
  338. $plexItem['originalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'$'.randString();
  339. $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
  340. $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
  341. // Stream info
  342. $plexItem['userStream'] = array(
  343. 'platform' => (string)$item->Player['platform'],
  344. 'product' => (string)$item->Player['product'],
  345. 'device' => (string)$item->Player['device'],
  346. 'stream' => (string)$item->Media->Part['decision'].($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)': ''),
  347. 'videoResolution' => (string)$item->Media['videoResolution'],
  348. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  349. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  350. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  351. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  352. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  353. 'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
  354. 'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
  355. 'container' => (string)$item->TranscodeSession['container'],
  356. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  357. );
  358. // Genre catch all
  359. if($item->Genre){
  360. $genres = array();
  361. foreach ($item->Genre as $key => $value) {
  362. $genres[] = (string)$value['tag'];
  363. }
  364. }
  365. // Actor catch all
  366. if($item->Role ){
  367. $actors = array();
  368. foreach ($item->Role as $key => $value) {
  369. if($value['thumb']){
  370. $actors[] = array(
  371. 'name' => (string)$value['tag'],
  372. 'role' => (string)$value['role'],
  373. 'thumb' => (string)$value['thumb']
  374. );
  375. }
  376. }
  377. }
  378. // Metadata information
  379. $plexItem['metadata'] = array(
  380. 'guid' => (string)$item['guid'],
  381. 'summary' => (string)$item['summary'],
  382. 'rating' => (string)$item['rating'],
  383. 'duration' => (string)$item['duration'],
  384. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  385. 'year' => (string)$item['year'],
  386. 'studio' => (string)$item['studio'],
  387. 'tagline' => (string)$item['tagline'],
  388. 'genres' => ($item->Genre) ? $genres : '',
  389. 'actors' => ($item->Role) ? $actors : ''
  390. );
  391. if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')){ $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$plexItem['nowPlayingKey'].'.jpg'; }
  392. if (file_exists($cacheDirectory.$plexItem['key'].'.jpg')){ $plexItem['imageURL'] = $cacheDirectoryWeb.$plexItem['key'].'.jpg'; }
  393. if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')) {
  394. $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'';
  395. }
  396. if (file_exists($cacheDirectory.$plexItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['key'].'.jpg') || !file_exists($cacheDirectory.$plexItem['key'].'.jpg')) {
  397. $plexItem['imageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'';
  398. }
  399. if(!$plexItem['nowPlayingThumb'] ){ $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png"; $plexItem['nowPlayingKey'] = "no-np"; }
  400. if(!$plexItem['thumb'] ){ $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png"; $plexItem['key'] = "no-list"; }
  401. if(isset($useImage)){ $plexItem['useImage'] = $useImage; }
  402. return $plexItem;
  403. }
  404. function plexConnect($action,$key=null){
  405. if($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))){
  406. $url = qualifyURL($GLOBALS['plexURL']);
  407. switch ($action) {
  408. case 'streams':
  409. $url = $url."/status/sessions?X-Plex-Token=".$GLOBALS['plexToken'];
  410. break;
  411. case 'recent':
  412. $url = $url."/library/recentlyAdded?X-Plex-Token=".$GLOBALS['plexToken'];
  413. break;
  414. case 'metadata':
  415. $url = $url."/library/metadata/".$key."?X-Plex-Token=".$GLOBALS['plexToken'];
  416. break;
  417. default:
  418. # code...
  419. break;
  420. }
  421. try{
  422. $options = (localURL($url)) ? array('verify' => false ) : array();
  423. $response = Requests::get($url, array(), $options);
  424. libxml_use_internal_errors(true);
  425. if($response->success){
  426. $items = array();
  427. $plex = simplexml_load_string($response->body);
  428. foreach($plex AS $child) {
  429. $items[] = resolvePlexItem($child);
  430. }
  431. $api['content'] = $items;
  432. $api['plexID'] = $GLOBALS['plexID'];
  433. $api['showNames'] = true;
  434. $api['group'] = '1';
  435. return $api;
  436. }
  437. }catch( Requests_Exception $e ) {
  438. writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  439. };
  440. }
  441. return false;
  442. }
  443. function embyConnect($action,$key=null,$skip=false){
  444. if($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])){
  445. $url = qualifyURL($GLOBALS['embyURL']);
  446. switch ($action) {
  447. case 'streams':
  448. $url = $url.'/Sessions?api_key='.$GLOBALS['embyToken'];
  449. break;
  450. case 'recent':
  451. $username = false;
  452. if (isset($GLOBALS['organizrUser']['username'])) {
  453. $username = strtolower($GLOBALS['organizrUser']['username']);
  454. }
  455. // Get A User
  456. $userIds = $url."/Users?api_key=".$GLOBALS['embyToken'];
  457. $showPlayed = true;
  458. try{
  459. $options = (localURL($userIds)) ? array('verify' => false ) : array();
  460. $response = Requests::get($userIds, array(), $options);
  461. if($response->success){
  462. $emby = json_decode($response->body, true);
  463. foreach ($emby as $value) { // Scan for admin user
  464. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  465. $userId = $value['Id'];
  466. }
  467. if ($username && strtolower($value['Name']) == $username) {
  468. $userId = $value['Id'];
  469. $showPlayed = false;
  470. break;
  471. }
  472. }
  473. }
  474. }catch( Requests_Exception $e ) {
  475. writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  476. };
  477. $url = $url.'/Users/'.$userId.'/Items/Latest?EnableImages=false&Limit=100&api_key='.$GLOBALS['embyToken'].($showPlayed?'':'&IsPlayed=false');
  478. break;
  479. case 'metadata':
  480. $skip = true;
  481. break;
  482. default:
  483. # code...
  484. break;
  485. }
  486. if($skip && $key){
  487. $items[] = resolveEmbyItem(array('Id'=>$key));
  488. $api['content'] = $items;
  489. return $api;
  490. }
  491. try{
  492. $options = (localURL($url)) ? array('verify' => false ) : array();
  493. $response = Requests::get($url, array(), $options);
  494. if($response->success){
  495. $items = array();
  496. $emby = json_decode($response->body, true);
  497. foreach($emby AS $child) {
  498. if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
  499. $items[] = resolveEmbyItem($child);
  500. }
  501. }
  502. $api['content'] = array_filter($items);
  503. return $api;
  504. }
  505. }catch( Requests_Exception $e ) {
  506. writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  507. };
  508. }
  509. return false;
  510. }
  511. function sabnzbdConnect() {
  512. if($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])){
  513. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  514. $url = $url.'/api?mode=queue&output=json&apikey='.$GLOBALS['sabnzbdToken'];
  515. try{
  516. $options = (localURL($url)) ? array('verify' => false ) : array();
  517. $response = Requests::get($url, array(), $options);
  518. if($response->success){
  519. $api['content']['queueItems'] = json_decode($response->body, true);
  520. }
  521. }catch( Requests_Exception $e ) {
  522. writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  523. };
  524. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  525. $url = $url.'/api?mode=history&output=json&apikey='.$GLOBALS['sabnzbdToken'];
  526. try{
  527. $options = (localURL($url)) ? array('verify' => false ) : array();
  528. $response = Requests::get($url, array(), $options);
  529. if($response->success){
  530. $api['content']['historyItems']= json_decode($response->body, true);
  531. }
  532. }catch( Requests_Exception $e ) {
  533. writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  534. };
  535. $api['content'] = isset($api['content']) ? $api['content'] : false;
  536. return $api;
  537. }
  538. }
  539. function nzbgetConnect() {
  540. if($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])){
  541. $url = qualifyURL($GLOBALS['nzbgetURL']);
  542. $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/listgroups';
  543. try{
  544. $options = (localURL($url)) ? array('verify' => false ) : array();
  545. $response = Requests::get($url, array(), $options);
  546. if($response->success){
  547. $api['content']['queueItems'] = json_decode($response->body, true);
  548. }
  549. }catch( Requests_Exception $e ) {
  550. writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  551. };
  552. $url = qualifyURL($GLOBALS['nzbgetURL']);
  553. $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/history';
  554. try{
  555. $options = (localURL($url)) ? array('verify' => false ) : array();
  556. $response = Requests::get($url, array(), $options);
  557. if($response->success){
  558. $api['content']['historyItems']= json_decode($response->body, true);
  559. }
  560. }catch( Requests_Exception $e ) {
  561. writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  562. };
  563. $api['content'] = isset($api['content']) ? $api['content'] : false;
  564. return $api;
  565. }
  566. }
  567. function transmissionConnect() {
  568. if($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])){
  569. $digest = qualifyURL($GLOBALS['transmissionURL'], true);
  570. $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'].':'.decrypt($GLOBALS['transmissionPassword'])."@" : '';
  571. $url = $digest['scheme'].'://'.$passwordInclude.$digest['host'].$digest['port'].$digest['path'].'/rpc';
  572. try{
  573. $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false ) : array();
  574. $response = Requests::get($url, array(), $options);
  575. if($response->headers['x-transmission-session-id']){
  576. $headers = array(
  577. 'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
  578. 'Content-Type' => 'application/json'
  579. );
  580. $data = array(
  581. 'method' => 'torrent-get',
  582. 'arguments' => array(
  583. 'fields' => array(
  584. "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir","errorString"
  585. ),
  586. ),
  587. 'tags' => ''
  588. );
  589. $response = Requests::post($url, $headers, json_encode($data), $options);
  590. if($response->success){
  591. $torrentList = json_decode($response->body, true)['arguments']['torrents'];
  592. if($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']){
  593. $filter = array();
  594. $torrents['arguments']['torrents'] = array();
  595. if($GLOBALS['transmissionHideSeeding']){ array_push($filter, 6, 5); }
  596. if($GLOBALS['transmissionHideCompleted']){ array_push($filter, 0); }
  597. foreach ($torrentList as $key => $value) {
  598. if(!in_array($value['status'], $filter)){
  599. $torrents['arguments']['torrents'][] = $value;
  600. }
  601. }
  602. }else{
  603. $torrents = json_decode($response->body, true);
  604. }
  605. $api['content']['queueItems'] = $torrents;
  606. $api['content']['historyItems'] = false;
  607. }
  608. }else{
  609. writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
  610. }
  611. }catch( Requests_Exception $e ) {
  612. writeLog('error', 'Transmission Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  613. };
  614. $api['content'] = isset($api['content']) ? $api['content'] : false;
  615. return $api;
  616. }
  617. }
  618. function qBittorrentConnect() {
  619. if($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])){
  620. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  621. $passwordInclude = ($GLOBALS['qBittorrentUsername'] != '' && $GLOBALS['qBittorrentPassword'] != '') ? 'username='.$GLOBALS['qBittorrentUsername'].'&password='.decrypt($GLOBALS['qBittorrentPassword'])."@" : '';
  622. $data = array('username'=>$GLOBALS['qBittorrentUsername'], 'password'=> decrypt($GLOBALS['qBittorrentPassword']));
  623. $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/login';
  624. try{
  625. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false ) : array();
  626. $response = Requests::post($url, array(), $data, $options);
  627. $reflection = new ReflectionClass($response->cookies);
  628. $cookie = $reflection->getProperty("cookies");
  629. $cookie->setAccessible(true);
  630. $cookie = $cookie->getValue($response->cookies);
  631. if($cookie){
  632. $headers = array(
  633. 'Cookie' => 'SID=' . $cookie['SID']->value
  634. );
  635. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  636. $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  637. $response = Requests::get($url, $headers, $options);
  638. if($response){
  639. $torrentList = json_decode($response->body, true);
  640. if($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']){
  641. $filter = array();
  642. $torrents['arguments']['torrents'] = array();
  643. if($GLOBALS['qBittorrentHideSeeding']){ array_push($filter, 'uploading', 'stalledUP', 'queuedUP'); }
  644. if($GLOBALS['qBittorrentHideCompleted']){ array_push($filter, 'pausedUP'); }
  645. foreach ($torrentList as $key => $value) {
  646. if(!in_array($value['state'], $filter)){
  647. $torrents['arguments']['torrents'][] = $value;
  648. }
  649. }
  650. }else{
  651. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  652. }
  653. $api['content']['queueItems'] = $torrents;
  654. $api['content']['historyItems'] = false;
  655. }
  656. }else{
  657. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  658. }
  659. }catch( Requests_Exception $e ) {
  660. writeLog('error', 'qBittorrent Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  661. };
  662. $api['content'] = isset($api['content']) ? $api['content'] : false;
  663. return $api;
  664. }
  665. }
  666. function delugeConnect(){
  667. if($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])){
  668. try{
  669. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  670. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  671. $api['content']['queueItems'] = $torrents;
  672. $api['content']['historyItems'] = false;
  673. }catch( Excecption $e){
  674. writeLog('error', 'Deluge Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  675. }
  676. }
  677. $api['content'] = isset($api['content']) ? $api['content'] : false;
  678. return $api;
  679. }
  680. function getCalendar(){
  681. $startDate = date('Y-m-d',strtotime("-".$GLOBALS['calendarStart']." days"));
  682. $endDate = date('Y-m-d',strtotime("+".$GLOBALS['calendarEnd']." days"));
  683. $calendarItems = array();
  684. // SONARR CONNECT
  685. if($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])){
  686. $sonarrs = array();
  687. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  688. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  689. if(count($sonarrURLList) == count($sonarrTokenList)){
  690. foreach ($sonarrURLList as $key => $value) {
  691. $sonarrs[$key] = array(
  692. 'url' => $value,
  693. 'token' => $sonarrTokenList[$key]
  694. );
  695. }
  696. foreach ($sonarrs as $key => $value) {
  697. try {
  698. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  699. $sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate),$key);
  700. } catch (Exception $e) {
  701. writeLog('error', 'Sonarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  702. }
  703. if(!empty($sonarrCalendar)) { $calendarItems = array_merge($calendarItems, $sonarrCalendar); }
  704. }
  705. }
  706. }
  707. // RADARR CONNECT
  708. if($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])){
  709. $radarrs = array();
  710. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  711. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  712. if(count($radarrURLList) == count($radarrTokenList)){
  713. foreach ($radarrURLList as $key => $value) {
  714. $radarrs[$key] = array(
  715. 'url' => $value,
  716. 'token' => $radarrTokenList[$key]
  717. );
  718. }
  719. foreach ($radarrs as $key => $value) {
  720. try {
  721. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  722. $radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate),$key,$value['url']);
  723. } catch (Exception $e) {
  724. writeLog('error', 'Radarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  725. }
  726. if(!empty($radarrCalendar)) { $calendarItems = array_merge($calendarItems, $radarrCalendar); }
  727. }
  728. }
  729. }
  730. // SICKRAGE/BEARD/MEDUSA CONNECT
  731. if($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])){
  732. $sicks = array();
  733. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  734. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  735. if(count($sickURLList) == count($sickTokenList)){
  736. foreach ($sickURLList as $key => $value) {
  737. $sicks[$key] = array(
  738. 'url' => $value,
  739. 'token' => $sickTokenList[$key]
  740. );
  741. }
  742. foreach ($sicks as $key => $value) {
  743. try {
  744. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  745. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(),$key);
  746. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100","downloaded"),$key);
  747. if(!empty($sickrageFuture)) { $calendarItems = array_merge($calendarItems, $sickrageFuture); }
  748. if(!empty($sickrageHistory)) { $calendarItems = array_merge($calendarItems, $sickrageHistory); }
  749. } catch (Exception $e) {
  750. writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  751. }
  752. }
  753. }
  754. }
  755. // COUCHPOTATO CONNECT
  756. if($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])){
  757. $couchs = array();
  758. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  759. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  760. if(count($couchpotatoURLList) == count($couchpotatoTokenList)){
  761. foreach ($couchpotatoURLList as $key => $value) {
  762. $couchs[$key] = array(
  763. 'url' => $value,
  764. 'token' => $couchpotatoTokenList[$key]
  765. );
  766. }
  767. foreach ($couchs as $key => $value) {
  768. try {
  769. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  770. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(),$key);
  771. if(!empty($couchCalendar)) { $calendarItems = array_merge($calendarItems, $couchCalendar); }
  772. } catch (Exception $e) {
  773. writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  774. }
  775. }
  776. }
  777. }
  778. return ($calendarItems) ? $calendarItems : false;
  779. }
  780. function getSonarrCalendar($array,$number){
  781. $array = json_decode($array, true);
  782. $gotCalendar = array();
  783. $i = 0;
  784. foreach($array AS $child) {
  785. $i++;
  786. $seriesName = $child['series']['title'];
  787. $episodeID = $child['series']['tvdbId'];
  788. if(!isset($episodeID)){ $episodeID = ""; }
  789. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  790. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  791. $episodeAirDate = $child['airDateUtc'];
  792. $episodeAirDate = strtotime($episodeAirDate);
  793. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  794. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  795. $downloaded = $child['hasFile'];
  796. if($downloaded == "0" && isset($unaired) && $episodePremier == "true"){ $downloaded = "text-primary"; }elseif($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success"; }else{ $downloaded = "text-danger"; }
  797. $fanart = "/plugins/images/cache/no-np.png";
  798. foreach ($child['series']['images'] as $image) {
  799. if($image['coverType'] == "fanart") {
  800. $fanart = $image['url'];
  801. }
  802. }
  803. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  804. $details = array(
  805. "seasonCount" => $child['series']['seasonCount'],
  806. "status" => $child['series']['status'],
  807. "topTitle" => $seriesName,
  808. "bottomTitle" => $bottomTitle,
  809. "overview" => isset($child['overview']) ? $child['overview'] : '',
  810. "runtime" => $child['series']['runtime'],
  811. "image" => $fanart,
  812. "ratings" => $child['series']['ratings']['value'],
  813. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  814. "audioChannels" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  815. "audioCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  816. "videoCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  817. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  818. "genres" => $child['series']['genres'],
  819. );
  820. array_push($gotCalendar, array(
  821. "id" => "Sonarr-".$number."-".$i,
  822. "title" => $seriesName,
  823. "start" => $child['airDateUtc'],
  824. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  825. "imagetype" => "tv ".$downloaded,
  826. "details" => $details
  827. ));
  828. }
  829. if ($i != 0){ return $gotCalendar; }
  830. }
  831. function getRadarrCalendar($array,$number, $url){
  832. $array = json_decode($array, true);
  833. $gotCalendar = array();
  834. $i = 0;
  835. foreach($array AS $child) {
  836. if(isset($child['physicalRelease'])){
  837. $i++;
  838. $movieName = $child['title'];
  839. $movieID = $child['tmdbId'];
  840. if(!isset($movieID)){ $movieID = ""; }
  841. $physicalRelease = $child['physicalRelease'];
  842. $physicalRelease = strtotime($physicalRelease);
  843. $physicalRelease = date("Y-m-d", $physicalRelease);
  844. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  845. $downloaded = $child['hasFile'];
  846. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success"; }else{ $downloaded = "text-danger"; }
  847. $banner = "/plugins/images/cache/no-np.png";
  848. foreach ($child['images'] as $image) {
  849. if($image['coverType'] == "banner") {
  850. $url = rtrim($url, '/'); //remove trailing slash
  851. $imageUrl = $image['url'];
  852. $urlParts = explode("/", $url);
  853. $imageParts = explode("/", $image['url']);
  854. if ($imageParts[1] == end($urlParts)) {
  855. unset($imageParts[1]);
  856. $imageUrl = implode("/", $imageParts);
  857. }
  858. $banner = $url . $imageUrl;
  859. }
  860. }
  861. if($banner !== "/plugins/images/cache/no-np.png"){
  862. $cacheDirectory = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  863. $imageURL = $banner;
  864. $cacheFile = $cacheDirectory.$movieID.'.jpg';
  865. $banner = 'plugins/images/cache/'.$movieID.'.jpg';
  866. if(!file_exists($cacheFile)){
  867. cacheImage($imageURL,$movieID);
  868. unset($imageURL);
  869. unset($cacheFile);
  870. }
  871. }
  872. $alternativeTitles = "";
  873. foreach ($child['alternativeTitles'] as $alternative) {
  874. $alternativeTitles .= $alternative['title'] . ', ';
  875. }
  876. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  877. $details = array(
  878. "topTitle" => $movieName,
  879. "bottomTitle" => $alternativeTitles,
  880. "status" => $child['status'],
  881. "overview" => $child['overview'],
  882. "runtime" => $child['runtime'],
  883. "image" => $banner,
  884. "ratings" => $child['ratings']['value'],
  885. "videoQuality" => $child["hasFile"] ? $child['movieFile']['quality']['quality']['name'] : "unknown",
  886. "audioChannels" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  887. "audioCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  888. "videoCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  889. "size" => $child["hasFile"] ? $child['movieFile']['size'] : "unknown",
  890. "genres" => $child['genres'],
  891. );
  892. array_push($gotCalendar, array(
  893. "id" => "Radarr-".$number."-".$i,
  894. "title" => $movieName,
  895. "start" => $physicalRelease,
  896. "className" => "bg-calendar movieID--".$movieID,
  897. "imagetype" => "film ".$downloaded,
  898. "details" => $details
  899. ));
  900. }
  901. }
  902. if ($i != 0){ return $gotCalendar; }
  903. }
  904. function getCouchCalendar($array,$number){
  905. $api = json_decode($array, true);
  906. $gotCalendar = array();
  907. $i = 0;
  908. foreach($api['movies'] AS $child) {
  909. if($child['status'] == "active" || $child['status'] == "done" ){
  910. $i++;
  911. $movieName = $child['info']['original_title'];
  912. $movieID = $child['info']['tmdb_id'];
  913. if(!isset($movieID)){ $movieID = ""; }
  914. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  915. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  916. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  917. $physicalRelease = strtotime($physicalRelease);
  918. $physicalRelease = date("Y-m-d", $physicalRelease);
  919. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  920. $downloaded = ($child['status'] == "active") ? "0" : "1";
  921. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success"; }else{ $downloaded = "text-danger"; }
  922. array_push($gotCalendar, array(
  923. "id" => "CouchPotato-".$number."-".$i,
  924. "title" => $movieName,
  925. "start" => $physicalRelease,
  926. "className" => "bg-calendar calendar-item movieID--".$movieID,
  927. "imagetype" => "film ".$downloaded,
  928. ));
  929. }
  930. }
  931. if ($i != 0){ return $gotCalendar; }
  932. }
  933. function getSickrageCalendarWanted($array,$number){
  934. $array = json_decode($array, true);
  935. $gotCalendar = array();
  936. $i = 0;
  937. foreach($array['data']['missed'] AS $child) {
  938. $i++;
  939. $seriesName = $child['show_name'];
  940. $episodeID = $child['tvdbid'];
  941. $episodeAirDate = $child['airdate'];
  942. $episodeAirDateTime = explode(" ",$child['airs']);
  943. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  944. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  945. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  946. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  947. $downloaded = "0";
  948. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  949. array_push($gotCalendar, array(
  950. "id" => "Sick-".$number."-Miss-".$i,
  951. "title" => $seriesName,
  952. "start" => $episodeAirDate,
  953. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  954. "imagetype" => "tv ".$downloaded,
  955. ));
  956. }
  957. foreach($array['data']['today'] AS $child) {
  958. $i++;
  959. $seriesName = $child['show_name'];
  960. $episodeID = $child['tvdbid'];
  961. $episodeAirDate = $child['airdate'];
  962. $episodeAirDateTime = explode(" ",$child['airs']);
  963. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  964. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  965. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  966. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  967. $downloaded = "0";
  968. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  969. array_push($gotCalendar, array(
  970. "id" => "Sick-".$number."-Today-".$i,
  971. "title" => $seriesName,
  972. "start" => $episodeAirDate,
  973. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  974. "imagetype" => "tv ".$downloaded,
  975. ));
  976. }
  977. foreach($array['data']['soon'] AS $child) {
  978. $i++;
  979. $seriesName = $child['show_name'];
  980. $episodeID = $child['tvdbid'];
  981. $episodeAirDate = $child['airdate'];
  982. $episodeAirDateTime = explode(" ",$child['airs']);
  983. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  984. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  985. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  986. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  987. $downloaded = "0";
  988. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  989. array_push($gotCalendar, array(
  990. "id" => "Sick-".$number."-Soon-".$i,
  991. "title" => $seriesName,
  992. "start" => $episodeAirDate,
  993. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  994. "imagetype" => "tv ".$downloaded,
  995. ));
  996. }
  997. foreach($array['data']['later'] AS $child) {
  998. $i++;
  999. $seriesName = $child['show_name'];
  1000. $episodeID = $child['tvdbid'];
  1001. $episodeAirDate = $child['airdate'];
  1002. $episodeAirDateTime = explode(" ",$child['airs']);
  1003. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1004. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1005. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1006. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1007. $downloaded = "0";
  1008. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  1009. array_push($gotCalendar, array(
  1010. "id" => "Sick-".$number."-Later-".$i,
  1011. "title" => $seriesName,
  1012. "start" => $episodeAirDate,
  1013. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1014. "imagetype" => "tv ".$downloaded,
  1015. ));
  1016. }
  1017. if ($i != 0){ return $gotCalendar; }
  1018. }
  1019. function getSickrageCalendarHistory($array,$number){
  1020. $array = json_decode($array, true);
  1021. $gotCalendar = array();
  1022. $i = 0;
  1023. foreach($array['data'] AS $child) {
  1024. $i++;
  1025. $seriesName = $child['show_name'];
  1026. $episodeID = $child['tvdbid'];
  1027. $episodeAirDate = $child['date'];
  1028. $downloaded = "text-success";
  1029. array_push($gotCalendar, array(
  1030. "id" => "Sick-".$number."-History-".$i,
  1031. "title" => $seriesName,
  1032. "start" => $episodeAirDate,
  1033. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1034. "imagetype" => "tv ".$downloaded,
  1035. ));
  1036. }
  1037. if ($i != 0){ return $gotCalendar; }
  1038. }