homepage-connect-functions.php 60 KB

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