homepage-connect-functions.php 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  1. <?php
  2. function homepageConnect($array)
  3. {
  4. switch ($array['data']['action']) {
  5. case 'getPlexStreams':
  6. return plexConnect('streams');
  7. break;
  8. case 'getPlexRecent':
  9. return plexConnect('recent');
  10. break;
  11. case 'getPlexMetadata':
  12. return plexConnect('metadata', $array['data']['key']);
  13. break;
  14. case 'getPlexSearch':
  15. return plexConnect('search', $array['data']['query']);
  16. break;
  17. case 'getPlexPlaylists':
  18. return getPlexPlaylists();
  19. break;
  20. case 'getEmbyStreams':
  21. return embyConnect('streams');
  22. break;
  23. case 'getEmbyRecent':
  24. return embyConnect('recent');
  25. break;
  26. case 'getEmbyMetadata':
  27. return embyConnect('metadata', $array['data']['key'], true);
  28. break;
  29. case 'getSabnzbd':
  30. return sabnzbdConnect();
  31. break;
  32. case 'getNzbget':
  33. return nzbgetConnect();
  34. break;
  35. case 'getTransmission':
  36. return transmissionConnect();
  37. break;
  38. case 'getqBittorrent':
  39. return qBittorrentConnect();
  40. break;
  41. case 'getDeluge':
  42. return delugeConnect();
  43. break;
  44. case 'getCalendar':
  45. return getCalendar();
  46. break;
  47. case 'getRequests':
  48. return getOmbiRequests();
  49. break;
  50. default:
  51. # code...
  52. break;
  53. }
  54. return false;
  55. }
  56. function streamType($value)
  57. {
  58. if ($value == "transcode" || $value == "Transcode") {
  59. return "Transcode";
  60. } elseif ($value == "copy" || $value == "DirectStream") {
  61. return "Direct Stream";
  62. } elseif ($value == "directplay" || $value == "DirectPlay") {
  63. return "Direct Play";
  64. } else {
  65. return "Direct Play";
  66. }
  67. }
  68. function resolveEmbyItem($itemDetails)
  69. {
  70. // Grab Each item info from Emby (extra call)
  71. $id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
  72. $url = qualifyURL($GLOBALS['embyURL']);
  73. $url = $url.'/Items?Ids='.$id.'&api_key='.$GLOBALS['embyToken'].'&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  74. try {
  75. $options = (localURL($url)) ? array('verify' => false ) : array();
  76. $response = Requests::get($url, array(), $options);
  77. if ($response->success) {
  78. $item = json_decode($response->body, true)['Items'][0];
  79. }
  80. } catch (Requests_Exception $e) {
  81. return false;
  82. };
  83. // Static Height & Width
  84. $height = 300;
  85. $width = 200;
  86. $nowPlayingHeight = 675;
  87. $nowPlayingWidth = 1200;
  88. $actorHeight = 450;
  89. $actorWidth = 300;
  90. // Cache Directories
  91. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  92. $cacheDirectoryWeb = 'plugins/images/cache/';
  93. // Types
  94. $embyItem['array-item'] = $item;
  95. $embyItem['array-itemdetails'] = $itemDetails;
  96. switch (@$item['Type']) {
  97. case 'Series':
  98. $embyItem['type'] = 'tv';
  99. $embyItem['title'] = $item['Name'];
  100. $embyItem['summary'] = '';
  101. $embyItem['ratingKey'] = $item['Id'];
  102. $embyItem['thumb'] = $item['Id'];
  103. $embyItem['key'] = $item['Id'] . "-list";
  104. $embyItem['nowPlayingThumb'] = $item['Id'];
  105. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  106. $embyItem['metadataKey'] = $item['Id'];
  107. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
  108. break;
  109. case 'Episode':
  110. $embyItem['type'] = 'tv';
  111. $embyItem['title'] = $item['SeriesName'];
  112. $embyItem['summary'] = '';
  113. $embyItem['ratingKey'] = $item['Id'];
  114. $embyItem['thumb'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']);
  115. $embyItem['key'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']) . "-list";
  116. $embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
  117. $embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'].'-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'].'-np' : false);
  118. $embyItem['metadataKey'] = $item['Id'];
  119. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
  120. $embyItem['nowPlayingTitle'] = @$item['SeriesName'].' - '.@$item['Name'];
  121. $embyItem['nowPlayingBottom'] = 'S'.@$item['ParentIndexNumber'].' · E'.@$item['IndexNumber'];
  122. break;
  123. case 'MusicAlbum':
  124. case 'Audio':
  125. $embyItem['type'] = 'music';
  126. $embyItem['title'] = $item['Name'];
  127. $embyItem['summary'] = '';
  128. $embyItem['ratingKey'] = $item['Id'];
  129. $embyItem['thumb'] = $item['Id'];
  130. $embyItem['key'] = $item['Id'] . "-list";
  131. $embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
  132. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  133. $embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
  134. $embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
  135. $embyItem['nowPlayingTitle'] = @$item['AlbumArtist'].' - '.@$item['Name'];
  136. $embyItem['nowPlayingBottom'] = @$item['Album'];
  137. break;
  138. case 'Movie':
  139. $embyItem['type'] = 'movie';
  140. $embyItem['title'] = $item['Name'];
  141. $embyItem['summary'] = '';
  142. $embyItem['ratingKey'] = $item['Id'];
  143. $embyItem['thumb'] = $item['Id'];
  144. $embyItem['key'] = $item['Id'] . "-list";
  145. $embyItem['nowPlayingThumb'] = $item['Id'];
  146. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  147. $embyItem['metadataKey'] = $item['Id'];
  148. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  149. $embyItem['nowPlayingTitle'] = @$item['Name'];
  150. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  151. break;
  152. case 'Video':
  153. $embyItem['type'] = 'video';
  154. $embyItem['title'] = $item['Name'];
  155. $embyItem['summary'] = '';
  156. $embyItem['ratingKey'] = $item['Id'];
  157. $embyItem['thumb'] = $item['Id'];
  158. $embyItem['key'] = $item['Id'] . "-list";
  159. $embyItem['nowPlayingThumb'] = $item['Id'];
  160. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  161. $embyItem['metadataKey'] = $item['Id'];
  162. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  163. $embyItem['nowPlayingTitle'] = @$item['Name'];
  164. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  165. break;
  166. default:
  167. return false;
  168. }
  169. $embyItem['uid'] = $item['Id'];
  170. $embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
  171. $embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
  172. $embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)$item['RunTimeTicks'];
  173. $embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
  174. $embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
  175. $embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
  176. $embyItem['id'] = $item['ServerId'];
  177. $embyItem['session'] = @$itemDetails['DeviceId'];
  178. $embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
  179. $embyItem['bandwidthType'] = 'wan';
  180. $embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
  181. $embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
  182. $embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? @(string)$itemDetails['UserName'] : "";
  183. $embyItem['userThumb'] = '';
  184. $embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
  185. $embyItem['address'] = $GLOBALS['embyTabURL'] ? '' : '';
  186. $embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'$'.randString();
  187. $embyItem['originalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'$'.randString();
  188. $embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
  189. $embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
  190. // Stream info
  191. $embyItem['userStream'] = array(
  192. 'platform' => @(string)$itemDetails['Client'],
  193. 'product' => @(string)$itemDetails['Client'],
  194. 'device' => @(string)$itemDetails['DeviceName'],
  195. 'stream' => @$itemDetails['PlayState']['PlayMethod'],
  196. 'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
  197. 'throttled' => false,
  198. 'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
  199. 'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
  200. 'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
  201. 'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
  202. 'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  203. 'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  204. 'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
  205. 'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
  206. );
  207. // Genre catch all
  208. if ($item['Genres']) {
  209. $genres = array();
  210. foreach ($item['Genres'] as $genre) {
  211. $genres[] = $genre;
  212. }
  213. }
  214. // Actor catch all
  215. if ($item['People']) {
  216. $actors = array();
  217. foreach ($item['People'] as $key => $value) {
  218. if (@$value['PrimaryImageTag'] && @$value['Role']) {
  219. if (file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg')) {
  220. $actorImage = $cacheDirectoryWeb.(string)$value['Id'].'-cast.jpg';
  221. }
  222. 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')) {
  223. $actorImage = 'api/?v1/image&source=emby&type=Primary&img='.(string)$value['Id'].'&height='.$actorHeight.'&width='.$actorWidth.'&key='.(string)$value['Id'].'-cast';
  224. }
  225. $actors[] = array(
  226. 'name' => (string)$value['Name'],
  227. 'role' => (string)$value['Role'],
  228. 'thumb' => $actorImage
  229. );
  230. }
  231. }
  232. }
  233. // Metadata information
  234. $embyItem['metadata'] = array(
  235. 'guid' => $item['Id'],
  236. 'summary' => @(string)$item['Overview'],
  237. 'rating' => @(string)$item['CommunityRating'],
  238. 'duration' => @(string)$item['RunTimeTicks'],
  239. 'originallyAvailableAt' => @(string)$item['PremiereDate'],
  240. 'year' => (string)$item['ProductionYear'],
  241. //'studio' => (string)$item['studio'],
  242. 'tagline' => @(string)$item['Taglines'][0],
  243. 'genres' => ($item['Genres']) ? $genres : '',
  244. 'actors' => ($item['People']) ? $actors : ''
  245. );
  246. if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')) {
  247. $embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$embyItem['nowPlayingKey'].'.jpg';
  248. }
  249. if (file_exists($cacheDirectory.$embyItem['key'].'.jpg')) {
  250. $embyItem['imageURL'] = $cacheDirectoryWeb.$embyItem['key'].'.jpg';
  251. }
  252. if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')) {
  253. $embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'';
  254. }
  255. if (file_exists($cacheDirectory.$embyItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['key'].'.jpg') || !file_exists($cacheDirectory.$embyItem['key'].'.jpg')) {
  256. $embyItem['imageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'';
  257. }
  258. if (!$embyItem['nowPlayingThumb']) {
  259. $embyItem['nowPlayingOriginalImage'] = $embyItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  260. $embyItem['nowPlayingKey'] = "no-np";
  261. }
  262. if (!$embyItem['thumb']) {
  263. $embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png";
  264. $embyItem['key'] = "no-list";
  265. }
  266. if (isset($useImage)) {
  267. $embyItem['useImage'] = $useImage;
  268. }
  269. return $embyItem;
  270. }
  271. function resolvePlexItem($item)
  272. {
  273. // Static Height & Width
  274. $height = 300;
  275. $width = 200;
  276. $nowPlayingHeight = 675;
  277. $nowPlayingWidth = 1200;
  278. // Cache Directories
  279. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  280. $cacheDirectoryWeb = 'plugins/images/cache/';
  281. // Types
  282. switch ($item['type']) {
  283. case 'season':
  284. $plexItem['type'] = 'tv';
  285. $plexItem['title'] = (string)$item['parentTitle'];
  286. $plexItem['summary'] = (string)$item['parentSummary'];
  287. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  288. $plexItem['thumb'] = (string)$item['thumb'];
  289. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  290. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  291. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  292. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  293. break;
  294. case 'episode':
  295. $plexItem['type'] = 'tv';
  296. $plexItem['title'] = (string)$item['grandparentTitle'];
  297. $plexItem['summary'] = (string)$item['title'];
  298. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  299. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  300. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  301. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  302. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  303. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
  304. $plexItem['nowPlayingBottom'] = 'S'.(string)$item['parentIndex'].' · E'.(string)$item['index'];
  305. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  306. break;
  307. case 'clip':
  308. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  309. $plexItem['type'] = 'clip';
  310. $plexItem['title'] = (string)$item['title'];
  311. $plexItem['summary'] = (string)$item['summary'];
  312. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  313. $plexItem['thumb'] = (string)$item['thumb'];
  314. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  315. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  316. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  317. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  318. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  319. break;
  320. case 'album':
  321. case 'track':
  322. $plexItem['type'] = 'music';
  323. $plexItem['title'] = (string)$item['parentTitle'].' - '.(string)$item['title'];
  324. $plexItem['summary'] = (string)$item['title'];
  325. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  326. $plexItem['thumb'] = (string)$item['thumb'];
  327. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  328. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  329. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  330. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
  331. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  332. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  333. break;
  334. default:
  335. $plexItem['type'] = 'movie';
  336. $plexItem['title'] = (string)$item['title'];
  337. $plexItem['summary'] = (string)$item['summary'];
  338. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  339. $plexItem['thumb'] = (string)$item['thumb'];
  340. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  341. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  342. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  343. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  344. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  345. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  346. }
  347. $plexItem['uid'] = (string)$item['ratingKey'];
  348. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  349. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  350. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  351. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress']- $plexItem['watched']) : '';
  352. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision']: '';
  353. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  354. $plexItem['session'] = (string)$item->Session['id'];
  355. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  356. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  357. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  358. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  359. $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
  360. $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
  361. $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
  362. $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'];
  363. $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'$'.randString();
  364. $plexItem['originalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'$'.randString();
  365. $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
  366. $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
  367. // Stream info
  368. $plexItem['userStream'] = array(
  369. 'platform' => (string)$item->Player['platform'],
  370. 'product' => (string)$item->Player['product'],
  371. 'device' => (string)$item->Player['device'],
  372. 'stream' => (string)$item->Media->Part['decision'].($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)': ''),
  373. 'videoResolution' => (string)$item->Media['videoResolution'],
  374. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  375. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  376. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  377. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  378. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  379. 'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
  380. 'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
  381. 'container' => (string)$item->TranscodeSession['container'],
  382. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  383. );
  384. // Genre catch all
  385. if ($item->Genre) {
  386. $genres = array();
  387. foreach ($item->Genre as $key => $value) {
  388. $genres[] = (string)$value['tag'];
  389. }
  390. }
  391. // Actor catch all
  392. if ($item->Role) {
  393. $actors = array();
  394. foreach ($item->Role as $key => $value) {
  395. if ($value['thumb']) {
  396. $actors[] = array(
  397. 'name' => (string)$value['tag'],
  398. 'role' => (string)$value['role'],
  399. 'thumb' => (string)$value['thumb']
  400. );
  401. }
  402. }
  403. }
  404. // Metadata information
  405. $plexItem['metadata'] = array(
  406. 'guid' => (string)$item['guid'],
  407. 'summary' => (string)$item['summary'],
  408. 'rating' => (string)$item['rating'],
  409. 'duration' => (string)$item['duration'],
  410. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  411. 'year' => (string)$item['year'],
  412. 'studio' => (string)$item['studio'],
  413. 'tagline' => (string)$item['tagline'],
  414. 'genres' => ($item->Genre) ? $genres : '',
  415. 'actors' => ($item->Role) ? $actors : ''
  416. );
  417. if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')) {
  418. $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$plexItem['nowPlayingKey'].'.jpg';
  419. }
  420. if (file_exists($cacheDirectory.$plexItem['key'].'.jpg')) {
  421. $plexItem['imageURL'] = $cacheDirectoryWeb.$plexItem['key'].'.jpg';
  422. }
  423. if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')) {
  424. $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'';
  425. }
  426. if (file_exists($cacheDirectory.$plexItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['key'].'.jpg') || !file_exists($cacheDirectory.$plexItem['key'].'.jpg')) {
  427. $plexItem['imageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'';
  428. }
  429. if (!$plexItem['nowPlayingThumb']) {
  430. $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  431. $plexItem['nowPlayingKey'] = "no-np";
  432. }
  433. if (!$plexItem['thumb']) {
  434. $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
  435. $plexItem['key'] = "no-list";
  436. }
  437. if (isset($useImage)) {
  438. $plexItem['useImage'] = $useImage;
  439. }
  440. return $plexItem;
  441. }
  442. function plexConnect($action, $key=null)
  443. {
  444. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))) {
  445. $url = qualifyURL($GLOBALS['plexURL']);
  446. $ignore = array();
  447. switch ($action) {
  448. case 'streams':
  449. $url = $url."/status/sessions?X-Plex-Token=".$GLOBALS['plexToken'];
  450. break;
  451. case 'recent':
  452. $url = $url."/library/recentlyAdded?X-Plex-Token=".$GLOBALS['plexToken'];
  453. break;
  454. case 'metadata':
  455. $url = $url."/library/metadata/".$key."?X-Plex-Token=".$GLOBALS['plexToken'];
  456. break;
  457. case 'playlists':
  458. $url = $url."/playlists?X-Plex-Token=".$GLOBALS['plexToken'];
  459. break;
  460. case 'search':
  461. $url = $url."/search?query=".rawurlencode($key)."&X-Plex-Token=".$GLOBALS['plexToken'];
  462. $ignore = array('artist', 'episode');
  463. break;
  464. default:
  465. # code...
  466. break;
  467. }
  468. try {
  469. $options = (localURL($url)) ? array('verify' => false ) : array();
  470. $response = Requests::get($url, array(), $options);
  471. libxml_use_internal_errors(true);
  472. if ($response->success) {
  473. $items = array();
  474. $plex = simplexml_load_string($response->body);
  475. foreach ($plex as $child) {
  476. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  477. $items[] = resolvePlexItem($child);
  478. }
  479. }
  480. $api['content'] = $items;
  481. $api['plexID'] = $GLOBALS['plexID'];
  482. $api['showNames'] = true;
  483. $api['group'] = '1';
  484. return $api;
  485. }
  486. } catch (Requests_Exception $e) {
  487. writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  488. };
  489. }
  490. return false;
  491. }
  492. function getPlexPlaylists()
  493. {
  494. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])) {
  495. $url = qualifyURL($GLOBALS['plexURL']);
  496. $url = $url."/playlists?X-Plex-Token=".$GLOBALS['plexToken'];
  497. try {
  498. $options = (localURL($url)) ? array('verify' => false ) : array();
  499. $response = Requests::get($url, array(), $options);
  500. libxml_use_internal_errors(true);
  501. if ($response->success) {
  502. $items = array();
  503. $plex = simplexml_load_string($response->body);
  504. foreach ($plex as $child) {
  505. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
  506. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  507. $playlistURL = qualifyURL($GLOBALS['plexURL']);
  508. $playlistURL = $playlistURL.$child['key']."?X-Plex-Token=".$GLOBALS['plexToken'];
  509. $options = (localURL($url)) ? array('verify' => false ) : array();
  510. $playlistResponse = Requests::get($playlistURL, array(), $options);
  511. if ($playlistResponse->success) {
  512. $playlistResponse = simplexml_load_string($playlistResponse->body);
  513. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  514. foreach ($playlistResponse->Video as $playlistItem) {
  515. $items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
  516. }
  517. }
  518. }
  519. }
  520. $api['content'] = $items;
  521. $api['plexID'] = $GLOBALS['plexID'];
  522. $api['showNames'] = true;
  523. $api['group'] = '1';
  524. return $api;
  525. }
  526. } catch (Requests_Exception $e) {
  527. writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  528. };
  529. }
  530. return false;
  531. }
  532. function embyConnect($action, $key=null, $skip=false)
  533. {
  534. if ($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])) {
  535. $url = qualifyURL($GLOBALS['embyURL']);
  536. switch ($action) {
  537. case 'streams':
  538. $url = $url.'/Sessions?api_key='.$GLOBALS['embyToken'];
  539. break;
  540. case 'recent':
  541. $username = false;
  542. if (isset($GLOBALS['organizrUser']['username'])) {
  543. $username = strtolower($GLOBALS['organizrUser']['username']);
  544. }
  545. // Get A User
  546. $userIds = $url."/Users?api_key=".$GLOBALS['embyToken'];
  547. $showPlayed = true;
  548. try {
  549. $options = (localURL($userIds)) ? array('verify' => false ) : array();
  550. $response = Requests::get($userIds, array(), $options);
  551. if ($response->success) {
  552. $emby = json_decode($response->body, true);
  553. foreach ($emby as $value) { // Scan for admin user
  554. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  555. $userId = $value['Id'];
  556. }
  557. if ($username && strtolower($value['Name']) == $username) {
  558. $userId = $value['Id'];
  559. $showPlayed = false;
  560. break;
  561. }
  562. }
  563. }
  564. } catch (Requests_Exception $e) {
  565. writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  566. };
  567. $url = $url.'/Users/'.$userId.'/Items/Latest?EnableImages=false&Limit=100&api_key='.$GLOBALS['embyToken'].($showPlayed?'':'&IsPlayed=false');
  568. break;
  569. case 'metadata':
  570. $skip = true;
  571. break;
  572. default:
  573. # code...
  574. break;
  575. }
  576. if ($skip && $key) {
  577. $items[] = resolveEmbyItem(array('Id'=>$key));
  578. $api['content'] = $items;
  579. return $api;
  580. }
  581. try {
  582. $options = (localURL($url)) ? array('verify' => false ) : array();
  583. $response = Requests::get($url, array(), $options);
  584. if ($response->success) {
  585. $items = array();
  586. $emby = json_decode($response->body, true);
  587. foreach ($emby as $child) {
  588. if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
  589. $items[] = resolveEmbyItem($child);
  590. }
  591. }
  592. $api['content'] = array_filter($items);
  593. return $api;
  594. }
  595. } catch (Requests_Exception $e) {
  596. writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  597. };
  598. }
  599. return false;
  600. }
  601. function sabnzbdConnect()
  602. {
  603. if ($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])) {
  604. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  605. $url = $url.'/api?mode=queue&output=json&apikey='.$GLOBALS['sabnzbdToken'];
  606. try {
  607. $options = (localURL($url)) ? array('verify' => false ) : array();
  608. $response = Requests::get($url, array(), $options);
  609. if ($response->success) {
  610. $api['content']['queueItems'] = json_decode($response->body, true);
  611. }
  612. } catch (Requests_Exception $e) {
  613. writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  614. };
  615. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  616. $url = $url.'/api?mode=history&output=json&apikey='.$GLOBALS['sabnzbdToken'];
  617. try {
  618. $options = (localURL($url)) ? array('verify' => false ) : array();
  619. $response = Requests::get($url, array(), $options);
  620. if ($response->success) {
  621. $api['content']['historyItems']= json_decode($response->body, true);
  622. }
  623. } catch (Requests_Exception $e) {
  624. writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  625. };
  626. $api['content'] = isset($api['content']) ? $api['content'] : false;
  627. return $api;
  628. }
  629. return false;
  630. }
  631. function nzbgetConnect()
  632. {
  633. if ($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])) {
  634. $url = qualifyURL($GLOBALS['nzbgetURL']);
  635. $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/listgroups';
  636. try {
  637. $options = (localURL($url)) ? array('verify' => false ) : array();
  638. $response = Requests::get($url, array(), $options);
  639. if ($response->success) {
  640. $api['content']['queueItems'] = json_decode($response->body, true);
  641. }
  642. } catch (Requests_Exception $e) {
  643. writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  644. };
  645. $url = qualifyURL($GLOBALS['nzbgetURL']);
  646. $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/history';
  647. try {
  648. $options = (localURL($url)) ? array('verify' => false ) : array();
  649. $response = Requests::get($url, array(), $options);
  650. if ($response->success) {
  651. $api['content']['historyItems']= json_decode($response->body, true);
  652. }
  653. } catch (Requests_Exception $e) {
  654. writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  655. };
  656. $api['content'] = isset($api['content']) ? $api['content'] : false;
  657. return $api;
  658. }
  659. return false;
  660. }
  661. function transmissionConnect()
  662. {
  663. if ($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])) {
  664. $digest = qualifyURL($GLOBALS['transmissionURL'], true);
  665. $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'].':'.decrypt($GLOBALS['transmissionPassword'])."@" : '';
  666. $url = $digest['scheme'].'://'.$passwordInclude.$digest['host'].$digest['port'].$digest['path'].'/rpc';
  667. try {
  668. $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false ) : array();
  669. $response = Requests::get($url, array(), $options);
  670. if ($response->headers['x-transmission-session-id']) {
  671. $headers = array(
  672. 'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
  673. 'Content-Type' => 'application/json'
  674. );
  675. $data = array(
  676. 'method' => 'torrent-get',
  677. 'arguments' => array(
  678. 'fields' => array(
  679. "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir","errorString"
  680. ),
  681. ),
  682. 'tags' => ''
  683. );
  684. $response = Requests::post($url, $headers, json_encode($data), $options);
  685. if ($response->success) {
  686. $torrentList = json_decode($response->body, true)['arguments']['torrents'];
  687. if ($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']) {
  688. $filter = array();
  689. $torrents['arguments']['torrents'] = array();
  690. if ($GLOBALS['transmissionHideSeeding']) {
  691. array_push($filter, 6, 5);
  692. }
  693. if ($GLOBALS['transmissionHideCompleted']) {
  694. array_push($filter, 0);
  695. }
  696. foreach ($torrentList as $key => $value) {
  697. if (!in_array($value['status'], $filter)) {
  698. $torrents['arguments']['torrents'][] = $value;
  699. }
  700. }
  701. } else {
  702. $torrents = json_decode($response->body, true);
  703. }
  704. $api['content']['queueItems'] = $torrents;
  705. $api['content']['historyItems'] = false;
  706. }
  707. } else {
  708. writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
  709. }
  710. } catch (Requests_Exception $e) {
  711. writeLog('error', 'Transmission Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  712. };
  713. $api['content'] = isset($api['content']) ? $api['content'] : false;
  714. return $api;
  715. }
  716. return false;
  717. }
  718. function qBittorrentConnect()
  719. {
  720. if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
  721. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  722. $data = array('username'=>$GLOBALS['qBittorrentUsername'], 'password'=> decrypt($GLOBALS['qBittorrentPassword']));
  723. $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/login';
  724. try {
  725. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false ) : array();
  726. $response = Requests::post($url, array(), $data, $options);
  727. $reflection = new ReflectionClass($response->cookies);
  728. $cookie = $reflection->getProperty("cookies");
  729. $cookie->setAccessible(true);
  730. $cookie = $cookie->getValue($response->cookies);
  731. if ($cookie) {
  732. $headers = array(
  733. 'Cookie' => 'SID=' . $cookie['SID']->value
  734. );
  735. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  736. $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  737. $response = Requests::get($url, $headers, $options);
  738. if ($response) {
  739. $torrentList = json_decode($response->body, true);
  740. if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
  741. $filter = array();
  742. $torrents['arguments']['torrents'] = array();
  743. if ($GLOBALS['qBittorrentHideSeeding']) {
  744. array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
  745. }
  746. if ($GLOBALS['qBittorrentHideCompleted']) {
  747. array_push($filter, 'pausedUP');
  748. }
  749. foreach ($torrentList as $key => $value) {
  750. if (!in_array($value['state'], $filter)) {
  751. $torrents['arguments']['torrents'][] = $value;
  752. }
  753. }
  754. } else {
  755. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  756. }
  757. $api['content']['queueItems'] = $torrents;
  758. $api['content']['historyItems'] = false;
  759. }
  760. } else {
  761. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  762. }
  763. } catch (Requests_Exception $e) {
  764. writeLog('error', 'qBittorrent Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  765. };
  766. $api['content'] = isset($api['content']) ? $api['content'] : false;
  767. return $api;
  768. }
  769. return false;
  770. }
  771. function delugeConnect()
  772. {
  773. if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
  774. try {
  775. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  776. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  777. $api['content']['queueItems'] = $torrents;
  778. $api['content']['historyItems'] = false;
  779. } catch (Excecption $e) {
  780. writeLog('error', 'Deluge Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  781. }
  782. }
  783. $api['content'] = isset($api['content']) ? $api['content'] : false;
  784. return $api;
  785. }
  786. function getCalendar()
  787. {
  788. $startDate = date('Y-m-d', strtotime("-".$GLOBALS['calendarStart']." days"));
  789. $endDate = date('Y-m-d', strtotime("+".$GLOBALS['calendarEnd']." days"));
  790. $calendarItems = array();
  791. // SONARR CONNECT
  792. if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  793. $sonarrs = array();
  794. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  795. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  796. if (count($sonarrURLList) == count($sonarrTokenList)) {
  797. foreach ($sonarrURLList as $key => $value) {
  798. $sonarrs[$key] = array(
  799. 'url' => $value,
  800. 'token' => $sonarrTokenList[$key]
  801. );
  802. }
  803. foreach ($sonarrs as $key => $value) {
  804. try {
  805. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  806. $sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate), $key);
  807. } catch (Exception $e) {
  808. writeLog('error', 'Sonarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  809. }
  810. if (!empty($sonarrCalendar)) {
  811. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  812. }
  813. }
  814. }
  815. }
  816. // RADARR CONNECT
  817. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  818. $radarrs = array();
  819. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  820. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  821. if (count($radarrURLList) == count($radarrTokenList)) {
  822. foreach ($radarrURLList as $key => $value) {
  823. $radarrs[$key] = array(
  824. 'url' => $value,
  825. 'token' => $radarrTokenList[$key]
  826. );
  827. }
  828. foreach ($radarrs as $key => $value) {
  829. try {
  830. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  831. $radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate), $key, $value['url']);
  832. } catch (Exception $e) {
  833. writeLog('error', 'Radarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  834. }
  835. if (!empty($radarrCalendar)) {
  836. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  837. }
  838. }
  839. }
  840. }
  841. // SICKRAGE/BEARD/MEDUSA CONNECT
  842. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  843. $sicks = array();
  844. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  845. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  846. if (count($sickURLList) == count($sickTokenList)) {
  847. foreach ($sickURLList as $key => $value) {
  848. $sicks[$key] = array(
  849. 'url' => $value,
  850. 'token' => $sickTokenList[$key]
  851. );
  852. }
  853. foreach ($sicks as $key => $value) {
  854. try {
  855. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  856. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  857. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  858. if (!empty($sickrageFuture)) {
  859. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  860. }
  861. if (!empty($sickrageHistory)) {
  862. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  863. }
  864. } catch (Exception $e) {
  865. writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  866. }
  867. }
  868. }
  869. }
  870. // COUCHPOTATO CONNECT
  871. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  872. $couchs = array();
  873. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  874. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  875. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  876. foreach ($couchpotatoURLList as $key => $value) {
  877. $couchs[$key] = array(
  878. 'url' => $value,
  879. 'token' => $couchpotatoTokenList[$key]
  880. );
  881. }
  882. foreach ($couchs as $key => $value) {
  883. try {
  884. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  885. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  886. if (!empty($couchCalendar)) {
  887. $calendarItems = array_merge($calendarItems, $couchCalendar);
  888. }
  889. } catch (Exception $e) {
  890. writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  891. }
  892. }
  893. }
  894. }
  895. return ($calendarItems) ? $calendarItems : false;
  896. }
  897. function getSonarrCalendar($array, $number)
  898. {
  899. $array = json_decode($array, true);
  900. $gotCalendar = array();
  901. $i = 0;
  902. foreach ($array as $child) {
  903. $i++;
  904. $seriesName = $child['series']['title'];
  905. $seriesID = $child['series']['tvdbId'];
  906. $episodeID = $child['series']['tvdbId'];
  907. if (!isset($episodeID)) {
  908. $episodeID = "";
  909. }
  910. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  911. if ($child['episodeNumber'] == "1") {
  912. $episodePremier = "true";
  913. } else {
  914. $episodePremier = "false";
  915. }
  916. $episodeAirDate = $child['airDateUtc'];
  917. $episodeAirDate = strtotime($episodeAirDate);
  918. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  919. if (new DateTime() < new DateTime($episodeAirDate)) {
  920. $unaired = true;
  921. }
  922. $downloaded = $child['hasFile'];
  923. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  924. $downloaded = "text-primary animated flash";
  925. } elseif ($downloaded == "0" && isset($unaired)) {
  926. $downloaded = "text-info";
  927. } elseif ($downloaded == "1") {
  928. $downloaded = "text-success";
  929. } else {
  930. $downloaded = "text-danger";
  931. }
  932. $fanart = "/plugins/images/cache/no-np.png";
  933. foreach ($child['series']['images'] as $image) {
  934. if ($image['coverType'] == "fanart") {
  935. $fanart = $image['url'];
  936. }
  937. }
  938. if ($fanart !== "/plugins/images/cache/no-np.png") {
  939. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  940. $imageURL = $fanart;
  941. $cacheFile = $cacheDirectory.$seriesID.'.jpg';
  942. $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
  943. if (!file_exists($cacheFile)) {
  944. cacheImage($imageURL, $seriesID);
  945. unset($imageURL);
  946. unset($cacheFile);
  947. }
  948. }
  949. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  950. $details = array(
  951. "seasonCount" => $child['series']['seasonCount'],
  952. "status" => $child['series']['status'],
  953. "topTitle" => $seriesName,
  954. "bottomTitle" => $bottomTitle,
  955. "overview" => isset($child['overview']) ? $child['overview'] : '',
  956. "runtime" => $child['series']['runtime'],
  957. "image" => $fanart,
  958. "ratings" => $child['series']['ratings']['value'],
  959. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  960. "audioChannels" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  961. "audioCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  962. "videoCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  963. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  964. "genres" => $child['series']['genres'],
  965. );
  966. array_push($gotCalendar, array(
  967. "id" => "Sonarr-".$number."-".$i,
  968. "title" => $seriesName,
  969. "start" => $child['airDateUtc'],
  970. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  971. "imagetype" => "tv ".$downloaded,
  972. "details" => $details
  973. ));
  974. }
  975. if ($i != 0) {
  976. return $gotCalendar;
  977. }
  978. return false;
  979. }
  980. function getRadarrCalendar($array, $number, $url)
  981. {
  982. $array = json_decode($array, true);
  983. $gotCalendar = array();
  984. $i = 0;
  985. foreach ($array as $child) {
  986. if (isset($child['physicalRelease'])) {
  987. $i++;
  988. $movieName = $child['title'];
  989. $movieID = $child['tmdbId'];
  990. if (!isset($movieID)) {
  991. $movieID = "";
  992. }
  993. $physicalRelease = $child['physicalRelease'];
  994. $physicalRelease = strtotime($physicalRelease);
  995. $physicalRelease = date("Y-m-d", $physicalRelease);
  996. if (new DateTime() < new DateTime($physicalRelease)) {
  997. $notReleased = "true";
  998. } else {
  999. $notReleased = "false";
  1000. }
  1001. $downloaded = $child['hasFile'];
  1002. if ($downloaded == "0" && $notReleased == "true") {
  1003. $downloaded = "text-info";
  1004. } elseif ($downloaded == "1") {
  1005. $downloaded = "text-success";
  1006. } else {
  1007. $downloaded = "text-danger";
  1008. }
  1009. $banner = "/plugins/images/cache/no-np.png";
  1010. foreach ($child['images'] as $image) {
  1011. if ($image['coverType'] == "banner") {
  1012. $url = rtrim($url, '/'); //remove trailing slash
  1013. $imageUrl = $image['url'];
  1014. $urlParts = explode("/", $url);
  1015. $imageParts = explode("/", $image['url']);
  1016. if ($imageParts[1] == end($urlParts)) {
  1017. unset($imageParts[1]);
  1018. $imageUrl = implode("/", $imageParts);
  1019. }
  1020. $banner = $url . $imageUrl;
  1021. }
  1022. }
  1023. if ($banner !== "/plugins/images/cache/no-np.png") {
  1024. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1025. $imageURL = $banner;
  1026. $cacheFile = $cacheDirectory.$movieID.'.jpg';
  1027. $banner = 'plugins/images/cache/'.$movieID.'.jpg';
  1028. if (!file_exists($cacheFile)) {
  1029. cacheImage($imageURL, $movieID);
  1030. unset($imageURL);
  1031. unset($cacheFile);
  1032. }
  1033. }
  1034. $alternativeTitles = "";
  1035. foreach ($child['alternativeTitles'] as $alternative) {
  1036. $alternativeTitles .= $alternative['title'] . ', ';
  1037. }
  1038. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1039. $details = array(
  1040. "topTitle" => $movieName,
  1041. "bottomTitle" => $alternativeTitles,
  1042. "status" => $child['status'],
  1043. "overview" => $child['overview'],
  1044. "runtime" => $child['runtime'],
  1045. "image" => $banner,
  1046. "ratings" => $child['ratings']['value'],
  1047. "videoQuality" => $child["hasFile"] ? $child['movieFile']['quality']['quality']['name'] : "unknown",
  1048. "audioChannels" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1049. "audioCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1050. "videoCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1051. "size" => $child["hasFile"] ? $child['movieFile']['size'] : "unknown",
  1052. "genres" => $child['genres'],
  1053. );
  1054. array_push($gotCalendar, array(
  1055. "id" => "Radarr-".$number."-".$i,
  1056. "title" => $movieName,
  1057. "start" => $physicalRelease,
  1058. "className" => "bg-calendar movieID--".$movieID,
  1059. "imagetype" => "film ".$downloaded,
  1060. "details" => $details
  1061. ));
  1062. }
  1063. }
  1064. if ($i != 0) {
  1065. return $gotCalendar;
  1066. }
  1067. return false;
  1068. }
  1069. function getCouchCalendar($array, $number)
  1070. {
  1071. $api = json_decode($array, true);
  1072. $gotCalendar = array();
  1073. $i = 0;
  1074. foreach ($api['movies'] as $child) {
  1075. if ($child['status'] == "active" || $child['status'] == "done") {
  1076. $i++;
  1077. $movieName = $child['info']['original_title'];
  1078. $movieID = $child['info']['tmdb_id'];
  1079. if (!isset($movieID)) {
  1080. $movieID = "";
  1081. }
  1082. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1083. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1084. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1085. $physicalRelease = strtotime($physicalRelease);
  1086. $physicalRelease = date("Y-m-d", $physicalRelease);
  1087. if (new DateTime() < new DateTime($physicalRelease)) {
  1088. $notReleased = "true";
  1089. } else {
  1090. $notReleased = "false";
  1091. }
  1092. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1093. if ($downloaded == "0" && $notReleased == "true") {
  1094. $downloaded = "text-info";
  1095. } elseif ($downloaded == "1") {
  1096. $downloaded = "text-success";
  1097. } else {
  1098. $downloaded = "text-danger";
  1099. }
  1100. if (!empty($child['info']['images']['backdrop_original'])) {
  1101. $banner = $child['info']['images']['backdrop_original'][0];
  1102. } elseif (!empty($child['info']['images']['backdrop'])) {
  1103. $banner = $child['info']['images']['backdrop_original'][0];
  1104. } else {
  1105. $banner = "/plugins/images/cache/no-np.png";
  1106. }
  1107. if ($banner !== "/plugins/images/cache/no-np.png") {
  1108. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1109. $imageURL = $banner;
  1110. $cacheFile = $cacheDirectory.$movieID.'.jpg';
  1111. $banner = 'plugins/images/cache/'.$movieID.'.jpg';
  1112. if (!file_exists($cacheFile)) {
  1113. cacheImage($imageURL, $movieID);
  1114. unset($imageURL);
  1115. unset($cacheFile);
  1116. }
  1117. }
  1118. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1119. $details = array(
  1120. "topTitle" => $movieName,
  1121. "bottomTitle" => $child['info']['tagline'],
  1122. "status" => $child['status'],
  1123. "overview" => $child['info']['plot'],
  1124. "runtime" => $child['info']['runtime'],
  1125. "image" => $banner,
  1126. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1127. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1128. "audioChannels" => "",
  1129. "audioCodec" => "",
  1130. "videoCodec" => "",
  1131. "genres" => $child['info']['genres'],
  1132. );
  1133. array_push($gotCalendar, array(
  1134. "id" => "CouchPotato-".$number."-".$i,
  1135. "title" => $movieName,
  1136. "start" => $physicalRelease,
  1137. "className" => "bg-calendar calendar-item movieID--".$movieID,
  1138. "imagetype" => "film ".$downloaded,
  1139. "details" => $details
  1140. ));
  1141. }
  1142. }
  1143. if ($i != 0) {
  1144. return $gotCalendar;
  1145. }
  1146. return false;
  1147. }
  1148. function getSickrageCalendarWanted($array, $number)
  1149. {
  1150. $array = json_decode($array, true);
  1151. $gotCalendar = array();
  1152. $i = 0;
  1153. foreach ($array['data']['missed'] as $child) {
  1154. $i++;
  1155. $seriesName = $child['show_name'];
  1156. $seriesID = $child['tvdbid'];
  1157. $episodeID = $child['tvdbid'];
  1158. $episodeAirDate = $child['airdate'];
  1159. $episodeAirDateTime = explode(" ", $child['airs']);
  1160. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1161. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1162. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1163. if (new DateTime() < new DateTime($episodeAirDate)) {
  1164. $unaired = true;
  1165. }
  1166. $downloaded = "0";
  1167. if ($downloaded == "0" && isset($unaired)) {
  1168. $downloaded = "text-info";
  1169. } elseif ($downloaded == "1") {
  1170. $downloaded = "text-success";
  1171. } else {
  1172. $downloaded = "text-danger";
  1173. }
  1174. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1175. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1176. $cacheFile = $cacheDirectory.$seriesID.'.jpg';
  1177. $fanart = "/plugins/images/cache/no-np.png";
  1178. if (file_exists($cacheFile)) {
  1179. $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
  1180. unset($cacheFile);
  1181. }
  1182. $details = array(
  1183. "seasonCount" => "",
  1184. "status" => $child['show_status'],
  1185. "topTitle" => $seriesName,
  1186. "bottomTitle" => $bottomTitle,
  1187. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1188. "runtime" => "",
  1189. "image" => $fanart,
  1190. "ratings" => "",
  1191. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1192. "audioChannels" => "",
  1193. "audioCodec" => "",
  1194. "videoCodec" => "",
  1195. "size" => "",
  1196. "genres" => "",
  1197. );
  1198. array_push($gotCalendar, array(
  1199. "id" => "Sick-".$number."-Miss-".$i,
  1200. "title" => $seriesName,
  1201. "start" => $episodeAirDate,
  1202. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1203. "imagetype" => "tv ".$downloaded,
  1204. "details" => $details,
  1205. ));
  1206. }
  1207. foreach ($array['data']['today'] as $child) {
  1208. $i++;
  1209. $seriesName = $child['show_name'];
  1210. $seriesID = $child['tvdbid'];
  1211. $episodeID = $child['tvdbid'];
  1212. $episodeAirDate = $child['airdate'];
  1213. $episodeAirDateTime = explode(" ", $child['airs']);
  1214. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1215. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1216. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1217. if (new DateTime() < new DateTime($episodeAirDate)) {
  1218. $unaired = true;
  1219. }
  1220. $downloaded = "0";
  1221. if ($downloaded == "0" && isset($unaired)) {
  1222. $downloaded = "text-info";
  1223. } elseif ($downloaded == "1") {
  1224. $downloaded = "text-success";
  1225. } else {
  1226. $downloaded = "text-danger";
  1227. }
  1228. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1229. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1230. $cacheFile = $cacheDirectory.$seriesID.'.jpg';
  1231. $fanart = "/plugins/images/cache/no-np.png";
  1232. if (file_exists($cacheFile)) {
  1233. $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
  1234. unset($cacheFile);
  1235. }
  1236. $details = array(
  1237. "seasonCount" => "",
  1238. "status" => $child['show_status'],
  1239. "topTitle" => $seriesName,
  1240. "bottomTitle" => $bottomTitle,
  1241. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1242. "runtime" => "",
  1243. "image" => $fanart,
  1244. "ratings" => "",
  1245. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1246. "audioChannels" => "",
  1247. "audioCodec" => "",
  1248. "videoCodec" => "",
  1249. "size" => "",
  1250. "genres" => "",
  1251. );
  1252. array_push($gotCalendar, array(
  1253. "id" => "Sick-".$number."-Today-".$i,
  1254. "title" => $seriesName,
  1255. "start" => $episodeAirDate,
  1256. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1257. "imagetype" => "tv ".$downloaded,
  1258. "details" => $details,
  1259. ));
  1260. }
  1261. foreach ($array['data']['soon'] as $child) {
  1262. $i++;
  1263. $seriesName = $child['show_name'];
  1264. $seriesID = $child['tvdbid'];
  1265. $episodeID = $child['tvdbid'];
  1266. $episodeAirDate = $child['airdate'];
  1267. $episodeAirDateTime = explode(" ", $child['airs']);
  1268. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1269. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1270. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1271. if (new DateTime() < new DateTime($episodeAirDate)) {
  1272. $unaired = true;
  1273. }
  1274. $downloaded = "0";
  1275. if ($downloaded == "0" && isset($unaired)) {
  1276. $downloaded = "text-info";
  1277. } elseif ($downloaded == "1") {
  1278. $downloaded = "text-success";
  1279. } else {
  1280. $downloaded = "text-danger";
  1281. }
  1282. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1283. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1284. $cacheFile = $cacheDirectory.$seriesID.'.jpg';
  1285. $fanart = "/plugins/images/cache/no-np.png";
  1286. if (file_exists($cacheFile)) {
  1287. $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
  1288. unset($cacheFile);
  1289. }
  1290. $details = array(
  1291. "seasonCount" => "",
  1292. "status" => $child['show_status'],
  1293. "topTitle" => $seriesName,
  1294. "bottomTitle" => $bottomTitle,
  1295. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1296. "runtime" => "",
  1297. "image" => $fanart,
  1298. "ratings" => "",
  1299. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1300. "audioChannels" => "",
  1301. "audioCodec" => "",
  1302. "videoCodec" => "",
  1303. "size" => "",
  1304. "genres" => "",
  1305. );
  1306. array_push($gotCalendar, array(
  1307. "id" => "Sick-".$number."-Soon-".$i,
  1308. "title" => $seriesName,
  1309. "start" => $episodeAirDate,
  1310. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1311. "imagetype" => "tv ".$downloaded,
  1312. "details" => $details,
  1313. ));
  1314. }
  1315. foreach ($array['data']['later'] as $child) {
  1316. $i++;
  1317. $seriesName = $child['show_name'];
  1318. $seriesID = $child['tvdbid'];
  1319. $episodeID = $child['tvdbid'];
  1320. $episodeAirDate = $child['airdate'];
  1321. $episodeAirDateTime = explode(" ", $child['airs']);
  1322. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1323. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1324. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1325. if (new DateTime() < new DateTime($episodeAirDate)) {
  1326. $unaired = true;
  1327. }
  1328. $downloaded = "0";
  1329. if ($downloaded == "0" && isset($unaired)) {
  1330. $downloaded = "text-info";
  1331. } elseif ($downloaded == "1") {
  1332. $downloaded = "text-success";
  1333. } else {
  1334. $downloaded = "text-danger";
  1335. }
  1336. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1337. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1338. $cacheFile = $cacheDirectory.$seriesID.'.jpg';
  1339. $fanart = "/plugins/images/cache/no-np.png";
  1340. if (file_exists($cacheFile)) {
  1341. $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
  1342. unset($cacheFile);
  1343. }
  1344. $details = array(
  1345. "seasonCount" => "",
  1346. "status" => $child['show_status'],
  1347. "topTitle" => $seriesName,
  1348. "bottomTitle" => $bottomTitle,
  1349. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1350. "runtime" => "",
  1351. "image" => $fanart,
  1352. "ratings" => "",
  1353. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1354. "audioChannels" => "",
  1355. "audioCodec" => "",
  1356. "videoCodec" => "",
  1357. "size" => "",
  1358. "genres" => "",
  1359. );
  1360. array_push($gotCalendar, array(
  1361. "id" => "Sick-".$number."-Later-".$i,
  1362. "title" => $seriesName,
  1363. "start" => $episodeAirDate,
  1364. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1365. "imagetype" => "tv ".$downloaded,
  1366. "details" => $details,
  1367. ));
  1368. }
  1369. if ($i != 0) {
  1370. return $gotCalendar;
  1371. }
  1372. return false;
  1373. }
  1374. function getSickrageCalendarHistory($array, $number)
  1375. {
  1376. $array = json_decode($array, true);
  1377. $gotCalendar = array();
  1378. $i = 0;
  1379. foreach ($array['data'] as $child) {
  1380. $i++;
  1381. $seriesName = $child['show_name'];
  1382. $seriesID = $child['tvdbid'];
  1383. $episodeID = $child['tvdbid'];
  1384. $episodeAirDate = $child['date'];
  1385. $downloaded = "text-success";
  1386. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  1387. $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  1388. $cacheFile = $cacheDirectory.$seriesID.'.jpg';
  1389. $fanart = "/plugins/images/cache/no-np.png";
  1390. if (file_exists($cacheFile)) {
  1391. $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
  1392. unset($cacheFile);
  1393. }
  1394. $details = array(
  1395. "seasonCount" => "",
  1396. "status" => $child['status'],
  1397. "topTitle" => $seriesName,
  1398. "bottomTitle" => $bottomTitle,
  1399. "overview" => '',
  1400. "runtime" => $child['series']['runtime'],
  1401. "image" => $fanart,
  1402. "ratings" => $child['series']['ratings']['value'],
  1403. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  1404. "audioChannels" => "",
  1405. "audioCodec" => "",
  1406. "videoCodec" => "",
  1407. "size" => "",
  1408. "genres" => "",
  1409. );
  1410. array_push($gotCalendar, array(
  1411. "id" => "Sick-".$number."-History-".$i,
  1412. "title" => $seriesName,
  1413. "start" => $episodeAirDate,
  1414. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1415. "imagetype" => "tv ".$downloaded,
  1416. "details" => $details,
  1417. ));
  1418. }
  1419. if ($i != 0) {
  1420. return $gotCalendar;
  1421. }
  1422. return false;
  1423. }
  1424. function ombiAPI($array)
  1425. {
  1426. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type']);
  1427. }
  1428. function ombiAction($id, $action, $type)
  1429. {
  1430. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1431. $url = qualifyURL($GLOBALS['ombiURL']);
  1432. $headers = array(
  1433. "Accept" => "application/json",
  1434. "Content-Type" => "application/json",
  1435. "Apikey" => $GLOBALS['ombiToken']
  1436. );
  1437. $data = array(
  1438. 'id' => $id,
  1439. );
  1440. switch ($type) {
  1441. case 'season':
  1442. case 'tv':
  1443. $type = 'tv';
  1444. $add = array(
  1445. 'tvDbId' => $id,
  1446. 'requestAll' => true,
  1447. 'latestSeason' => true,
  1448. 'firstSeason' => true
  1449. );
  1450. break;
  1451. default:
  1452. $type = 'movie';
  1453. $add = array("theMovieDbId" => (int)$id);
  1454. break;
  1455. }
  1456. $success['head'] = $headers;
  1457. $success['act'] = $action;
  1458. $success['data'] = $data;
  1459. $success['add'] = $add;
  1460. $success['type'] = $type;
  1461. try {
  1462. $options = (localURL($url)) ? array('verify' => false ) : array();
  1463. switch ($action) {
  1464. case 'add':
  1465. if (isset($_COOKIE['Auth'])) {
  1466. $headers = array(
  1467. "Accept" => "application/json",
  1468. "Content-Type" => "application/json",
  1469. "Authorization" => "Bearer ".$_COOKIE['Auth']
  1470. );
  1471. $success['head'] = $headers;
  1472. } else {
  1473. return false;
  1474. }
  1475. $response = Requests::post($url."/api/v1/Request/".$type, $headers, json_encode($add), $options);
  1476. break;
  1477. default:
  1478. if (qualifyRequest(1)) {
  1479. switch ($action) {
  1480. case 'approve':
  1481. $response = Requests::post($url."/api/v1/Request/".$type."/approve", $headers, json_encode($data), $options);
  1482. break;
  1483. case 'available':
  1484. $response = Requests::post($url."/api/v1/Request/".$type."/available", $headers, json_encode($data), $options);
  1485. break;
  1486. case 'unavailable':
  1487. $response = Requests::post($url."/api/v1/Request/".$type."/unavailable", $headers, json_encode($data), $options);
  1488. break;
  1489. case 'deny':
  1490. $response = Requests::put($url."/api/v1/Request/".$type."/deny", $headers, json_encode($data), $options);
  1491. break;
  1492. case 'delete':
  1493. $response = Requests::delete($url."/api/v1/Request/".$type."/".$id, $headers, $options);
  1494. break;
  1495. default:
  1496. return false;
  1497. }
  1498. }
  1499. break;
  1500. }
  1501. $success['api'] = $response;
  1502. $success['bd'] = $response->body;
  1503. $success['hd'] = $response->headers;
  1504. if ($response->success) {
  1505. $success['ok'] = true;
  1506. }
  1507. } catch (Requests_Exception $e) {
  1508. writeLog('error', 'OMBI Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  1509. };
  1510. }
  1511. return isset($success['ok']) ? $success : false;
  1512. }
  1513. function getOmbiRequests($type = "both")
  1514. {
  1515. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1516. $url = qualifyURL($GLOBALS['ombiURL']);
  1517. $headers = array(
  1518. "Accept" => "application/json",
  1519. "Apikey" => $GLOBALS['ombiToken'],
  1520. );
  1521. $requests = array();
  1522. try {
  1523. $options = (localURL($url)) ? array('verify' => false ) : array();
  1524. switch ($type) {
  1525. case 'movie':
  1526. $movie = Requests::get($url."/api/v1/Request/movie", $headers, $options);
  1527. break;
  1528. case 'tv':
  1529. $tv = Requests::get($url."/api/v1/Request/tv", $headers, $options);
  1530. break;
  1531. default:
  1532. $movie = Requests::get($url."/api/v1/Request/movie", $headers, $options);
  1533. $tv = Requests::get($url."/api/v1/Request/tv", $headers, $options);
  1534. break;
  1535. }
  1536. if ($movie->success || $tv->success) {
  1537. if (isset($movie)) {
  1538. $movie = json_decode($movie->body, true);
  1539. //$movie = array_reverse($movie);
  1540. foreach ($movie as $key => $value) {
  1541. $requests[] = array(
  1542. 'test' => $value,
  1543. 'id' => $value['theMovieDbId'],
  1544. 'title' => $value['title'],
  1545. 'overview' => $value['overview'],
  1546. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/'.$value['posterPath'] : '',
  1547. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/'.$value['background'] : '',
  1548. 'approved' => $value['approved'],
  1549. 'available' => $value['available'],
  1550. 'denied' => $value['denied'],
  1551. 'deniedReason' => $value['deniedReason'],
  1552. 'user' => $value['requestedUser']['userName'],
  1553. 'request_id' => $value['id'],
  1554. 'request_date' => $value['requestedDate'],
  1555. 'release_date' => $value['releaseDate'],
  1556. 'type' => 'movie',
  1557. 'icon' => 'mdi mdi-filmstrip',
  1558. 'color' => 'palette-Deep-Purple-900 bg white',
  1559. );
  1560. }
  1561. }
  1562. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  1563. $tv = json_decode($tv->body, true);
  1564. foreach ($tv as $key => $value) {
  1565. if (is_array($value['childRequests'][0])) {
  1566. $requests[] = array(
  1567. 'test' => $value,
  1568. 'id' => $value['tvDbId'],
  1569. 'title' => $value['title'],
  1570. 'overview' => $value['overview'],
  1571. 'poster' => $value['posterPath'],
  1572. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/'.$value['background'] : '',
  1573. 'approved' => $value['childRequests'][0]['approved'],
  1574. 'available' => $value['childRequests'][0]['available'],
  1575. 'denied' => $value['childRequests'][0]['denied'],
  1576. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  1577. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  1578. 'request_id' => $value['id'],
  1579. 'request_date' => $value['childRequests'][0]['requestedDate'],
  1580. 'release_date' => $value['releaseDate'],
  1581. 'type' => 'tv',
  1582. 'icon' => 'mdi mdi-television',
  1583. 'color' => 'grayish-blue-bg',
  1584. );
  1585. }
  1586. }
  1587. }
  1588. //sort here
  1589. usort($requests, function ($item1, $item2) {
  1590. if ($item1['request_date'] == $item2['request_date']) {
  1591. return 0;
  1592. }
  1593. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  1594. });
  1595. }
  1596. } catch (Requests_Exception $e) {
  1597. writeLog('error', 'OMBI Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  1598. };
  1599. }
  1600. $api['content'] = isset($requests) ? $requests : false;
  1601. return $api;
  1602. }