homepage-connect-functions.php 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189
  1. <?php
  2. /** @noinspection PhpUndefinedFieldInspection */
  3. function homepageConnect($array)
  4. {
  5. switch ($array['data']['action']) {
  6. case 'getPlexStreams':
  7. return (qualifyRequest($GLOBALS['homepagePlexStreamsAuth'])) ? plexConnect('streams') : false;
  8. break;
  9. case 'getPlexRecent':
  10. return (qualifyRequest($GLOBALS['homepagePlexRecentAuth'])) ? plexConnect('recent') : false;
  11. break;
  12. case 'getPlexMetadata':
  13. return (qualifyRequest($GLOBALS['homepagePlexAuth'])) ? plexConnect('metadata', $array['data']['key']) : false;
  14. break;
  15. case 'getPlexSearch':
  16. return (qualifyRequest($GLOBALS['mediaSearchAuth'])) ? plexConnect('search', $array['data']['query']) : false;
  17. break;
  18. case 'getPlexPlaylists':
  19. return (qualifyRequest($GLOBALS['homepagePlexPlaylistAuth'])) ? getPlexPlaylists() : false;
  20. break;
  21. case 'getEmbyStreams':
  22. return (qualifyRequest($GLOBALS['homepageEmbyStreamsAuth'])) ? embyConnect('streams') : false;
  23. break;
  24. case 'getEmbyRecent':
  25. return (qualifyRequest($GLOBALS['homepageEmbyRecentAuth'])) ? embyConnect('recent') : false;
  26. break;
  27. case 'getEmbyMetadata':
  28. return (qualifyRequest($GLOBALS['homepageEmbyAuth'])) ? embyConnect('metadata', $array['data']['key'], true) : false;
  29. break;
  30. case 'getSabnzbd':
  31. return sabnzbdConnect();
  32. break;
  33. case 'getNzbget':
  34. return nzbgetConnect();
  35. break;
  36. case 'getTransmission':
  37. return transmissionConnect();
  38. break;
  39. case 'getqBittorrent':
  40. return qBittorrentConnect();
  41. break;
  42. case 'getrTorrent':
  43. return rTorrentConnect();
  44. break;
  45. case 'getDeluge':
  46. return delugeConnect();
  47. break;
  48. case 'getCalendar':
  49. return getCalendar();
  50. break;
  51. case 'getRequests':
  52. return getOmbiRequests();
  53. break;
  54. default:
  55. # code...
  56. break;
  57. }
  58. return false;
  59. }
  60. function streamType($value)
  61. {
  62. if ($value == "transcode" || $value == "Transcode") {
  63. return "Transcode";
  64. } elseif ($value == "copy" || $value == "DirectStream") {
  65. return "Direct Stream";
  66. } elseif ($value == "directplay" || $value == "DirectPlay") {
  67. return "Direct Play";
  68. } else {
  69. return "Direct Play";
  70. }
  71. }
  72. function resolveEmbyItem($itemDetails)
  73. {
  74. // Grab Each item info from Emby (extra call)
  75. $id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
  76. $url = qualifyURL($GLOBALS['embyURL']);
  77. $url = $url . '/Items?Ids=' . $id . '&api_key=' . $GLOBALS['embyToken'] . '&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  78. try {
  79. $options = (localURL($url)) ? array('verify' => false) : array();
  80. $response = Requests::get($url, array(), $options);
  81. if ($response->success) {
  82. $item = json_decode($response->body, true)['Items'][0];
  83. }
  84. } catch (Requests_Exception $e) {
  85. return false;
  86. };
  87. // Static Height & Width
  88. $height = getCacheImageSize('h');
  89. $width = getCacheImageSize('w');
  90. $nowPlayingHeight = getCacheImageSize('nph');
  91. $nowPlayingWidth = getCacheImageSize('npw');
  92. $actorHeight = 450;
  93. $actorWidth = 300;
  94. // Cache Directories
  95. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  96. $cacheDirectoryWeb = 'plugins/images/cache/';
  97. // Types
  98. $embyItem['array-item'] = $item;
  99. $embyItem['array-itemdetails'] = $itemDetails;
  100. switch (@$item['Type']) {
  101. case 'Series':
  102. $embyItem['type'] = 'tv';
  103. $embyItem['title'] = $item['Name'];
  104. $embyItem['secondaryTitle'] = '';
  105. $embyItem['summary'] = '';
  106. $embyItem['ratingKey'] = $item['Id'];
  107. $embyItem['thumb'] = $item['Id'];
  108. $embyItem['key'] = $item['Id'] . "-list";
  109. $embyItem['nowPlayingThumb'] = $item['Id'];
  110. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  111. $embyItem['metadataKey'] = $item['Id'];
  112. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
  113. break;
  114. case 'Episode':
  115. $embyItem['type'] = 'tv';
  116. $embyItem['title'] = $item['SeriesName'];
  117. $embyItem['secondaryTitle'] = '';
  118. $embyItem['summary'] = '';
  119. $embyItem['ratingKey'] = $item['Id'];
  120. $embyItem['thumb'] = (isset($item['SeriesId']) ? $item['SeriesId'] : $item['Id']);
  121. $embyItem['key'] = (isset($item['SeriesId']) ? $item['SeriesId'] : $item['Id']) . "-list";
  122. $embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
  123. $embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] . '-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] . '-np' : false);
  124. $embyItem['metadataKey'] = $item['Id'];
  125. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
  126. $embyItem['nowPlayingTitle'] = @$item['SeriesName'] . ' - ' . @$item['Name'];
  127. $embyItem['nowPlayingBottom'] = 'S' . @$item['ParentIndexNumber'] . ' · E' . @$item['IndexNumber'];
  128. break;
  129. case 'MusicAlbum':
  130. case 'Audio':
  131. $embyItem['type'] = 'music';
  132. $embyItem['title'] = $item['Name'];
  133. $embyItem['secondaryTitle'] = '';
  134. $embyItem['summary'] = '';
  135. $embyItem['ratingKey'] = $item['Id'];
  136. $embyItem['thumb'] = $item['Id'];
  137. $embyItem['key'] = $item['Id'] . "-list";
  138. $embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
  139. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  140. $embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
  141. $embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
  142. $embyItem['nowPlayingTitle'] = @$item['AlbumArtist'] . ' - ' . @$item['Name'];
  143. $embyItem['nowPlayingBottom'] = @$item['Album'];
  144. break;
  145. case 'Movie':
  146. $embyItem['type'] = 'movie';
  147. $embyItem['title'] = $item['Name'];
  148. $embyItem['secondaryTitle'] = '';
  149. $embyItem['summary'] = '';
  150. $embyItem['ratingKey'] = $item['Id'];
  151. $embyItem['thumb'] = $item['Id'];
  152. $embyItem['key'] = $item['Id'] . "-list";
  153. $embyItem['nowPlayingThumb'] = $item['Id'];
  154. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  155. $embyItem['metadataKey'] = $item['Id'];
  156. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  157. $embyItem['nowPlayingTitle'] = @$item['Name'];
  158. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  159. break;
  160. case 'Video':
  161. $embyItem['type'] = 'video';
  162. $embyItem['title'] = $item['Name'];
  163. $embyItem['secondaryTitle'] = '';
  164. $embyItem['summary'] = '';
  165. $embyItem['ratingKey'] = $item['Id'];
  166. $embyItem['thumb'] = $item['Id'];
  167. $embyItem['key'] = $item['Id'] . "-list";
  168. $embyItem['nowPlayingThumb'] = $item['Id'];
  169. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  170. $embyItem['metadataKey'] = $item['Id'];
  171. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  172. $embyItem['nowPlayingTitle'] = @$item['Name'];
  173. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  174. break;
  175. default:
  176. return false;
  177. }
  178. $embyItem['uid'] = $item['Id'];
  179. $embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
  180. $embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
  181. $embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)(isset($item['RunTimeTicks']) ? $item['RunTimeTicks'] : '');
  182. $embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
  183. $embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
  184. $embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
  185. $embyItem['id'] = $item['ServerId'];
  186. $embyItem['session'] = @$itemDetails['DeviceId'];
  187. $embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
  188. $embyItem['bandwidthType'] = 'wan';
  189. $embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
  190. $embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
  191. $embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? @(string)$itemDetails['UserName'] : "";
  192. $embyItem['userThumb'] = '';
  193. $embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
  194. $embyItem['address'] = $GLOBALS['embyTabURL'] ? rtrim($GLOBALS['embyTabURL'], '/') . "/web/#!/itemdetails.html?id=" . $embyItem['uid'] : "https://app.emby.media/#!/itemdetails.html?id=" . $embyItem['uid'] . "&serverId=" . $embyItem['id'];
  195. $embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type=' . $embyItem['nowPlayingImageType'] . '&img=' . $embyItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $embyItem['nowPlayingKey'] . '$' . randString();
  196. $embyItem['originalImage'] = 'api/?v1/image&source=emby&type=' . $embyItem['imageType'] . '&img=' . $embyItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $embyItem['key'] . '$' . randString();
  197. $embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
  198. $embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
  199. // Stream info
  200. $embyItem['userStream'] = array(
  201. 'platform' => @(string)$itemDetails['Client'],
  202. 'product' => @(string)$itemDetails['Client'],
  203. 'device' => @(string)$itemDetails['DeviceName'],
  204. 'stream' => @$itemDetails['PlayState']['PlayMethod'],
  205. 'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
  206. 'throttled' => false,
  207. 'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
  208. 'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
  209. 'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
  210. 'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
  211. 'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  212. 'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  213. 'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
  214. 'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
  215. );
  216. // Genre catch all
  217. if ($item['Genres']) {
  218. $genres = array();
  219. foreach ($item['Genres'] as $genre) {
  220. $genres[] = $genre;
  221. }
  222. }
  223. // Actor catch all
  224. if ($item['People']) {
  225. $actors = array();
  226. foreach ($item['People'] as $key => $value) {
  227. if (@$value['PrimaryImageTag'] && @$value['Role']) {
  228. if (file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg')) {
  229. $actorImage = $cacheDirectoryWeb . (string)$value['Id'] . '-cast.jpg';
  230. }
  231. 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')) {
  232. $actorImage = 'api/?v1/image&source=emby&type=Primary&img=' . (string)$value['Id'] . '&height=' . $actorHeight . '&width=' . $actorWidth . '&key=' . (string)$value['Id'] . '-cast';
  233. }
  234. $actors[] = array(
  235. 'name' => (string)$value['Name'],
  236. 'role' => (string)$value['Role'],
  237. 'thumb' => $actorImage
  238. );
  239. }
  240. }
  241. }
  242. // Metadata information
  243. $embyItem['metadata'] = array(
  244. 'guid' => $item['Id'],
  245. 'summary' => @(string)$item['Overview'],
  246. 'rating' => @(string)$item['CommunityRating'],
  247. 'duration' => @(string)$item['RunTimeTicks'],
  248. 'originallyAvailableAt' => @(string)$item['PremiereDate'],
  249. 'year' => (string)isset($item['ProductionYear']) ? $item['ProductionYear'] : '',
  250. //'studio' => (string)$item['studio'],
  251. 'tagline' => @(string)$item['Taglines'][0],
  252. 'genres' => ($item['Genres']) ? $genres : '',
  253. 'actors' => ($item['People']) ? $actors : ''
  254. );
  255. if (file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg')) {
  256. $embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $embyItem['nowPlayingKey'] . '.jpg';
  257. }
  258. if (file_exists($cacheDirectory . $embyItem['key'] . '.jpg')) {
  259. $embyItem['imageURL'] = $cacheDirectoryWeb . $embyItem['key'] . '.jpg';
  260. }
  261. if (file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg')) {
  262. $embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type=' . $embyItem['nowPlayingImageType'] . '&img=' . $embyItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $embyItem['nowPlayingKey'] . '';
  263. }
  264. if (file_exists($cacheDirectory . $embyItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $embyItem['key'] . '.jpg') || !file_exists($cacheDirectory . $embyItem['key'] . '.jpg')) {
  265. $embyItem['imageURL'] = 'api/?v1/image&source=emby&type=' . $embyItem['imageType'] . '&img=' . $embyItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $embyItem['key'] . '';
  266. }
  267. if (!$embyItem['nowPlayingThumb']) {
  268. $embyItem['nowPlayingOriginalImage'] = $embyItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  269. $embyItem['nowPlayingKey'] = "no-np";
  270. }
  271. if (!$embyItem['thumb']) {
  272. $embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png";
  273. $embyItem['key'] = "no-list";
  274. }
  275. if (isset($useImage)) {
  276. $embyItem['useImage'] = $useImage;
  277. }
  278. return $embyItem;
  279. }
  280. function getCacheImageSize($type)
  281. {
  282. switch ($type) {
  283. case 'height':
  284. case 'h':
  285. return 300 * $GLOBALS['cacheImageSize'];
  286. break;
  287. case 'width':
  288. case 'w':
  289. return 200 * $GLOBALS['cacheImageSize'];
  290. break;
  291. case 'nowPlayingHeight':
  292. case 'nph':
  293. return 675 * $GLOBALS['cacheImageSize'];
  294. break;
  295. case 'nowPlayingWidth':
  296. case 'npw':
  297. return 1200 * $GLOBALS['cacheImageSize'];
  298. break;
  299. }
  300. }
  301. function resolvePlexItem($item)
  302. {
  303. // Static Height & Width
  304. $height = getCacheImageSize('h');
  305. $width = getCacheImageSize('w');
  306. $nowPlayingHeight = getCacheImageSize('nph');
  307. $nowPlayingWidth = getCacheImageSize('npw');
  308. // Cache Directories
  309. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  310. $cacheDirectoryWeb = 'plugins/images/cache/';
  311. // Types
  312. switch ($item['type']) {
  313. case 'season':
  314. $plexItem['type'] = 'tv';
  315. $plexItem['title'] = (string)$item['parentTitle'];
  316. $plexItem['secondaryTitle'] = (string)$item['title'];
  317. $plexItem['summary'] = (string)$item['parentSummary'];
  318. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  319. $plexItem['thumb'] = (string)$item['thumb'];
  320. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  321. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  322. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  323. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  324. break;
  325. case 'episode':
  326. $plexItem['type'] = 'tv';
  327. $plexItem['title'] = (string)$item['grandparentTitle'];
  328. $plexItem['secondaryTitle'] = (string)$item['parentTitle'];
  329. $plexItem['summary'] = (string)$item['title'];
  330. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  331. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  332. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  333. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  334. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  335. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  336. $plexItem['nowPlayingBottom'] = 'S' . (string)$item['parentIndex'] . ' · E' . (string)$item['index'];
  337. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  338. break;
  339. case 'clip':
  340. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  341. $plexItem['type'] = 'clip';
  342. $plexItem['title'] = (isset($item['live']) ? 'Live TV' : (string)$item['title']);
  343. $plexItem['secondaryTitle'] = '';
  344. $plexItem['summary'] = (string)$item['summary'];
  345. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  346. $plexItem['thumb'] = (string)$item['thumb'];
  347. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  348. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  349. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  350. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  351. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  352. break;
  353. case 'album':
  354. case 'track':
  355. $plexItem['type'] = 'music';
  356. $plexItem['title'] = (string)$item['parentTitle'];
  357. $plexItem['secondaryTitle'] = (string)$item['title'];
  358. $plexItem['summary'] = (string)$item['title'];
  359. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  360. $plexItem['thumb'] = (string)$item['thumb'];
  361. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  362. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  363. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  364. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  365. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  366. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  367. break;
  368. default:
  369. $plexItem['type'] = 'movie';
  370. $plexItem['title'] = (string)$item['title'];
  371. $plexItem['secondaryTitle'] = (string)$item['year'];
  372. $plexItem['summary'] = (string)$item['summary'];
  373. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  374. $plexItem['thumb'] = (string)$item['thumb'];
  375. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  376. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  377. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  378. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  379. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  380. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  381. }
  382. $plexItem['uid'] = (string)$item['ratingKey'];
  383. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  384. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  385. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  386. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress'] - $plexItem['watched']) : '';
  387. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision'] : '';
  388. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  389. $plexItem['session'] = (string)$item->Session['id'];
  390. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  391. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  392. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  393. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  394. $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
  395. $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
  396. $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
  397. $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'];
  398. $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '$' . randString();
  399. $plexItem['originalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '$' . randString();
  400. $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
  401. $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
  402. // Stream info
  403. $plexItem['userStream'] = array(
  404. 'platform' => (string)$item->Player['platform'],
  405. 'product' => (string)$item->Player['product'],
  406. 'device' => (string)$item->Player['device'],
  407. 'stream' => (string)$item->Media->Part['decision'] . ($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)' : ''),
  408. 'videoResolution' => (string)$item->Media['videoResolution'],
  409. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  410. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  411. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  412. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  413. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  414. 'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
  415. 'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
  416. 'container' => (string)$item->TranscodeSession['container'],
  417. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  418. );
  419. // Genre catch all
  420. if ($item->Genre) {
  421. $genres = array();
  422. foreach ($item->Genre as $key => $value) {
  423. $genres[] = (string)$value['tag'];
  424. }
  425. }
  426. // Actor catch all
  427. if ($item->Role) {
  428. $actors = array();
  429. foreach ($item->Role as $key => $value) {
  430. if ($value['thumb']) {
  431. $actors[] = array(
  432. 'name' => (string)$value['tag'],
  433. 'role' => (string)$value['role'],
  434. 'thumb' => (string)$value['thumb']
  435. );
  436. }
  437. }
  438. }
  439. // Metadata information
  440. $plexItem['metadata'] = array(
  441. 'guid' => (string)$item['guid'],
  442. 'summary' => (string)$item['summary'],
  443. 'rating' => (string)$item['rating'],
  444. 'duration' => (string)$item['duration'],
  445. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  446. 'year' => (string)$item['year'],
  447. 'studio' => (string)$item['studio'],
  448. 'tagline' => (string)$item['tagline'],
  449. 'genres' => ($item->Genre) ? $genres : '',
  450. 'actors' => ($item->Role) ? $actors : ''
  451. );
  452. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  453. $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $plexItem['nowPlayingKey'] . '.jpg';
  454. }
  455. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  456. $plexItem['imageURL'] = $cacheDirectoryWeb . $plexItem['key'] . '.jpg';
  457. }
  458. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  459. $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '';
  460. }
  461. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['key'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  462. $plexItem['imageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '';
  463. }
  464. if (!$plexItem['nowPlayingThumb']) {
  465. $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  466. $plexItem['nowPlayingKey'] = "no-np";
  467. }
  468. if (!$plexItem['thumb']) {
  469. $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
  470. $plexItem['key'] = "no-list";
  471. }
  472. if (isset($useImage)) {
  473. $plexItem['useImage'] = $useImage;
  474. }
  475. return $plexItem;
  476. }
  477. function plexConnect($action, $key = null)
  478. {
  479. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))) {
  480. $url = qualifyURL($GLOBALS['plexURL']);
  481. $ignore = array();
  482. $resolve = true;
  483. switch ($action) {
  484. case 'streams':
  485. $url = $url . "/status/sessions?X-Plex-Token=" . $GLOBALS['plexToken'];
  486. break;
  487. case 'libraries':
  488. $url = $url . "/library/sections?X-Plex-Token=" . $GLOBALS['plexToken'];
  489. $resolve = false;
  490. break;
  491. case 'recent':
  492. $url = $url . "/library/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&limit=" . $GLOBALS['homepageRecentLimit'];
  493. break;
  494. case 'metadata':
  495. $url = $url . "/library/metadata/" . $key . "?X-Plex-Token=" . $GLOBALS['plexToken'];
  496. break;
  497. case 'playlists':
  498. $url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
  499. break;
  500. case 'search':
  501. $url = $url . "/search?query=" . rawurlencode($key) . "&X-Plex-Token=" . $GLOBALS['plexToken'];
  502. $ignore = array('artist', 'episode');
  503. break;
  504. default:
  505. # code...
  506. break;
  507. }
  508. try {
  509. $options = (localURL($url)) ? array('verify' => false) : array();
  510. $response = Requests::get($url, array(), $options);
  511. libxml_use_internal_errors(true);
  512. if ($response->success) {
  513. $items = array();
  514. $plex = simplexml_load_string($response->body);
  515. foreach ($plex as $child) {
  516. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  517. $items[] = resolvePlexItem($child);
  518. }
  519. }
  520. $api['content'] = ($resolve) ? $items : $plex;
  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 getPlexPlaylists()
  533. {
  534. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])) {
  535. $url = qualifyURL($GLOBALS['plexURL']);
  536. $url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
  537. try {
  538. $options = (localURL($url)) ? array('verify' => false) : array();
  539. $response = Requests::get($url, array(), $options);
  540. libxml_use_internal_errors(true);
  541. if ($response->success) {
  542. $items = array();
  543. $plex = simplexml_load_string($response->body);
  544. foreach ($plex as $child) {
  545. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
  546. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  547. $playlistURL = qualifyURL($GLOBALS['plexURL']);
  548. $playlistURL = $playlistURL . $child['key'] . "?X-Plex-Token=" . $GLOBALS['plexToken'];
  549. $options = (localURL($url)) ? array('verify' => false) : array();
  550. $playlistResponse = Requests::get($playlistURL, array(), $options);
  551. if ($playlistResponse->success) {
  552. $playlistResponse = simplexml_load_string($playlistResponse->body);
  553. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  554. foreach ($playlistResponse->Video as $playlistItem) {
  555. $items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
  556. }
  557. }
  558. }
  559. }
  560. $api['content'] = $items;
  561. $api['plexID'] = $GLOBALS['plexID'];
  562. $api['showNames'] = true;
  563. $api['group'] = '1';
  564. return $api;
  565. }
  566. } catch (Requests_Exception $e) {
  567. writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  568. };
  569. }
  570. return false;
  571. }
  572. function embyConnect($action, $key = null, $skip = false)
  573. {
  574. if ($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])) {
  575. $url = qualifyURL($GLOBALS['embyURL']);
  576. switch ($action) {
  577. case 'streams':
  578. $url = $url . '/Sessions?api_key=' . $GLOBALS['embyToken'];
  579. break;
  580. case 'recent':
  581. $username = false;
  582. if (isset($GLOBALS['organizrUser']['username'])) {
  583. $username = strtolower($GLOBALS['organizrUser']['username']);
  584. }
  585. // Get A User
  586. $userIds = $url . "/Users?api_key=" . $GLOBALS['embyToken'];
  587. $showPlayed = true;
  588. try {
  589. $options = (localURL($userIds)) ? array('verify' => false) : array();
  590. $response = Requests::get($userIds, array(), $options);
  591. if ($response->success) {
  592. $emby = json_decode($response->body, true);
  593. foreach ($emby as $value) { // Scan for admin user
  594. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  595. $userId = $value['Id'];
  596. }
  597. if ($username && strtolower($value['Name']) == $username) {
  598. $userId = $value['Id'];
  599. $showPlayed = false;
  600. break;
  601. }
  602. }
  603. $url = $url . '/Users/' . $userId . '/Items/Latest?EnableImages=false&Limit=' . $GLOBALS['homepageRecentLimit'] . '&api_key=' . $GLOBALS['embyToken'] . ($showPlayed ? '' : '&IsPlayed=false');
  604. }
  605. } catch (Requests_Exception $e) {
  606. writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  607. };
  608. break;
  609. case 'metadata':
  610. $skip = true;
  611. break;
  612. default:
  613. # code...
  614. break;
  615. }
  616. if ($skip && $key) {
  617. $items[] = resolveEmbyItem(array('Id' => $key));
  618. $api['content'] = $items;
  619. return $api;
  620. }
  621. try {
  622. $options = (localURL($url)) ? array('verify' => false) : array();
  623. $response = Requests::get($url, array(), $options);
  624. if ($response->success) {
  625. $items = array();
  626. $emby = json_decode($response->body, true);
  627. foreach ($emby as $child) {
  628. if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
  629. $items[] = resolveEmbyItem($child);
  630. }
  631. }
  632. $api['content'] = array_filter($items);
  633. return $api;
  634. }
  635. } catch (Requests_Exception $e) {
  636. writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  637. };
  638. }
  639. return false;
  640. }
  641. function sabnzbdConnect()
  642. {
  643. if ($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])) {
  644. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  645. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  646. try {
  647. $options = (localURL($url)) ? array('verify' => false) : array();
  648. $response = Requests::get($url, array(), $options);
  649. if ($response->success) {
  650. $api['content']['queueItems'] = json_decode($response->body, true);
  651. }
  652. } catch (Requests_Exception $e) {
  653. writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  654. };
  655. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  656. $url = $url . '/api?mode=history&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  657. try {
  658. $options = (localURL($url)) ? array('verify' => false) : array();
  659. $response = Requests::get($url, array(), $options);
  660. if ($response->success) {
  661. $api['content']['historyItems'] = json_decode($response->body, true);
  662. }
  663. } catch (Requests_Exception $e) {
  664. writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  665. };
  666. $api['content'] = isset($api['content']) ? $api['content'] : false;
  667. return $api;
  668. }
  669. return false;
  670. }
  671. function nzbgetConnect()
  672. {
  673. if ($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])) {
  674. $url = qualifyURL($GLOBALS['nzbgetURL']);
  675. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  676. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  677. } else {
  678. $url = $url . '/jsonrpc/listgroups';
  679. }
  680. try {
  681. $options = (localURL($url)) ? array('verify' => false) : array();
  682. $response = Requests::get($url, array(), $options);
  683. if ($response->success) {
  684. $api['content']['queueItems'] = json_decode($response->body, true);
  685. }
  686. } catch (Requests_Exception $e) {
  687. writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  688. };
  689. $url = qualifyURL($GLOBALS['nzbgetURL']);
  690. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  691. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/history';
  692. } else {
  693. $url = $url . '/jsonrpc/history';
  694. }
  695. try {
  696. $options = (localURL($url)) ? array('verify' => false) : array();
  697. $response = Requests::get($url, array(), $options);
  698. if ($response->success) {
  699. $api['content']['historyItems'] = json_decode($response->body, true);
  700. }
  701. } catch (Requests_Exception $e) {
  702. writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  703. };
  704. $api['content'] = isset($api['content']) ? $api['content'] : false;
  705. return $api;
  706. }
  707. return false;
  708. }
  709. function transmissionConnect()
  710. {
  711. if ($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])) {
  712. $digest = qualifyURL($GLOBALS['transmissionURL'], true);
  713. $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'] . ':' . decrypt($GLOBALS['transmissionPassword']) . "@" : '';
  714. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . '/rpc';
  715. try {
  716. $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false) : array();
  717. $response = Requests::get($url, array(), $options);
  718. if ($response->headers['x-transmission-session-id']) {
  719. $headers = array(
  720. 'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
  721. 'Content-Type' => 'application/json'
  722. );
  723. $data = array(
  724. 'method' => 'torrent-get',
  725. 'arguments' => array(
  726. 'fields' => array(
  727. "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir", "errorString"
  728. ),
  729. ),
  730. 'tags' => ''
  731. );
  732. $response = Requests::post($url, $headers, json_encode($data), $options);
  733. if ($response->success) {
  734. $torrentList = json_decode($response->body, true)['arguments']['torrents'];
  735. if ($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']) {
  736. $filter = array();
  737. $torrents['arguments']['torrents'] = array();
  738. if ($GLOBALS['transmissionHideSeeding']) {
  739. array_push($filter, 6, 5);
  740. }
  741. if ($GLOBALS['transmissionHideCompleted']) {
  742. array_push($filter, 0);
  743. }
  744. foreach ($torrentList as $key => $value) {
  745. if (!in_array($value['status'], $filter)) {
  746. $torrents['arguments']['torrents'][] = $value;
  747. }
  748. }
  749. } else {
  750. $torrents = json_decode($response->body, true);
  751. }
  752. $api['content']['queueItems'] = $torrents;
  753. $api['content']['historyItems'] = false;
  754. }
  755. } else {
  756. writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
  757. }
  758. } catch (Requests_Exception $e) {
  759. writeLog('error', 'Transmission Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  760. };
  761. $api['content'] = isset($api['content']) ? $api['content'] : false;
  762. return $api;
  763. }
  764. return false;
  765. }
  766. function rTorrentStatus($completed, $state, $status)
  767. {
  768. if ($completed && $state && $status == 'seed') {
  769. $state = 'Seeding';
  770. } elseif (!$completed && !$state && $status == 'leech') {
  771. $state = 'Stopped';
  772. } elseif (!$completed && $state && $status == 'leech') {
  773. $state = 'Downloading';
  774. } elseif ($completed && !$state && $status == 'seed') {
  775. $state = 'Finished';
  776. }
  777. return $state;
  778. }
  779. function rTorrentConnect()
  780. {
  781. if ($GLOBALS['homepagerTorrentEnabled'] && !empty($GLOBALS['rTorrentURL']) && qualifyRequest($GLOBALS['homepagerTorrentAuth'])) {
  782. try {
  783. $torrents = array();
  784. $digest = qualifyURL($GLOBALS['rTorrentURL'], true);
  785. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  786. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  787. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  788. $options = (localURL($url)) ? array('verify' => false) : array();
  789. $data = xmlrpc_encode_request("d.multicall2", array(
  790. "",
  791. "main",
  792. "d.name=",
  793. "d.base_path=",
  794. "d.up.total=",
  795. "d.size_bytes=",
  796. "d.down.total=",
  797. "d.completed_bytes=",
  798. "d.connection_current=",
  799. "d.down.rate=",
  800. "d.up.rate=",
  801. "d.timestamp.started=",
  802. "d.state=",
  803. "d.group.name=",
  804. "d.hash=",
  805. "d.complete=",
  806. "d.ratio=",
  807. "d.chunk_size=",
  808. "f.size_bytes=",
  809. "f.size_chunks=",
  810. "f.completed_chunks=",
  811. "d.custom=",
  812. "d.custom1=",
  813. "d.custom2=",
  814. "d.custom3=",
  815. "d.custom4=",
  816. "d.custom5=",
  817. ), array());
  818. $response = Requests::post($url, array(), $data, $options);
  819. if ($response->success) {
  820. $torrentList = xmlrpc_decode(str_replace('i8>', 'string>', $response->body));
  821. foreach ($torrentList as $key => $value) {
  822. $tempStatus = rTorrentStatus($value[13], $value[10], $value[6]);
  823. if ($tempStatus == 'Seeding' && $GLOBALS['rTorrentHideSeeding']) {
  824. //do nothing
  825. } elseif ($tempStatus == 'Finished' && $GLOBALS['rTorrentHideCompleted']) {
  826. //do nothing
  827. } else {
  828. $torrents[$key] = array(
  829. 'name' => $value[0],
  830. 'base' => $value[1],
  831. 'upTotal' => $value[2],
  832. 'size' => $value[3],
  833. 'downTotal' => $value[4],
  834. 'downloaded' => $value[5],
  835. 'connectionState' => $value[6],
  836. 'leech' => $value[7],
  837. 'seed' => $value[8],
  838. 'date' => $value[9],
  839. 'state' => ($value[10]) ? 'on' : 'off',
  840. 'group' => $value[11],
  841. 'hash' => $value[12],
  842. 'complete' => ($value[13]) ? 'yes' : 'no',
  843. 'ratio' => $value[14],
  844. 'label' => $value[20],
  845. 'status' => $tempStatus,
  846. 'temp' => $value[16] . ' - ' . $value[17] . ' - ' . $value[18],
  847. 'custom' => $value[19] . ' - ' . $value[20] . ' - ' . $value[21],
  848. 'custom2' => $value[22] . ' - ' . $value[23] . ' - ' . $value[24],
  849. );
  850. }
  851. }
  852. if (count($torrents) !== 0) {
  853. usort($torrents, function ($a, $b) {
  854. $direction = substr($GLOBALS['rTorrentSortOrder'], -1);
  855. $sort = substr($GLOBALS['rTorrentSortOrder'], 0, strlen($GLOBALS['rTorrentSortOrder']) - 1);
  856. switch ($direction) {
  857. case 'a':
  858. return $a[$sort] <=> $b[$sort];
  859. break;
  860. case 'd':
  861. return $b[$sort] <=> $a[$sort];
  862. break;
  863. default:
  864. return $b['date'] <=> $a['date'];
  865. }
  866. });
  867. }
  868. $api['content']['queueItems'] = $torrents;
  869. $api['content']['historyItems'] = false;
  870. }
  871. } catch
  872. (Requests_Exception $e) {
  873. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  874. };
  875. $api['content'] = isset($api['content']) ? $api['content'] : false;
  876. return $api;
  877. }
  878. return false;
  879. }
  880. function qBittorrentConnect()
  881. {
  882. if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
  883. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  884. $data = array('username' => $GLOBALS['qBittorrentUsername'], 'password' => decrypt($GLOBALS['qBittorrentPassword']));
  885. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/login';
  886. try {
  887. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false) : array();
  888. $response = Requests::post($url, array(), $data, $options);
  889. $reflection = new ReflectionClass($response->cookies);
  890. $cookie = $reflection->getProperty("cookies");
  891. $cookie->setAccessible(true);
  892. $cookie = $cookie->getValue($response->cookies);
  893. if ($cookie) {
  894. $headers = array(
  895. 'Cookie' => 'SID=' . $cookie['SID']->value
  896. );
  897. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  898. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  899. $response = Requests::get($url, $headers, $options);
  900. if ($response) {
  901. $torrentList = json_decode($response->body, true);
  902. if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
  903. $filter = array();
  904. $torrents['arguments']['torrents'] = array();
  905. if ($GLOBALS['qBittorrentHideSeeding']) {
  906. array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
  907. }
  908. if ($GLOBALS['qBittorrentHideCompleted']) {
  909. array_push($filter, 'pausedUP');
  910. }
  911. foreach ($torrentList as $key => $value) {
  912. if (!in_array($value['state'], $filter)) {
  913. $torrents['arguments']['torrents'][] = $value;
  914. }
  915. }
  916. } else {
  917. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  918. }
  919. $api['content']['queueItems'] = $torrents;
  920. $api['content']['historyItems'] = false;
  921. }
  922. } else {
  923. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  924. }
  925. } catch (Requests_Exception $e) {
  926. writeLog('error', 'qBittorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  927. };
  928. $api['content'] = isset($api['content']) ? $api['content'] : false;
  929. return $api;
  930. }
  931. return false;
  932. }
  933. function delugeConnect()
  934. {
  935. if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
  936. try {
  937. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  938. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  939. if ($GLOBALS['delugeHideSeeding'] || $GLOBALS['delugeHideCompleted']) {
  940. $filter = array();
  941. if ($GLOBALS['delugeHideSeeding']) {
  942. array_push($filter, 'Seeding', 'Uploading', 'queuedUP');
  943. }
  944. if ($GLOBALS['delugeHideCompleted']) {
  945. array_push($filter, 'Seeding', 'Completed');
  946. }
  947. //prettyPrint($torrents);
  948. foreach ($torrents as $key => $value) {
  949. if (!in_array($value->state, $filter)) {
  950. $api['content']['queueItems'][] = $value;
  951. }
  952. }
  953. } else {
  954. $api['content']['queueItems'] = $torrents;
  955. }
  956. $api['content']['queueItems'] = (empty($api['content']['queueItems'])) ? [] : $api['content']['queueItems'];
  957. $api['content']['historyItems'] = false;
  958. } catch (Excecption $e) {
  959. writeLog('error', 'Deluge Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  960. }
  961. }
  962. $api['content'] = isset($api['content']) ? $api['content'] : false;
  963. return $api;
  964. }
  965. function getCalendar()
  966. {
  967. $startDate = date('Y-m-d', strtotime("-" . $GLOBALS['calendarStart'] . " days"));
  968. $endDate = date('Y-m-d', strtotime("+" . $GLOBALS['calendarEnd'] . " days"));
  969. $icalCalendarSources = array();
  970. $calendarItems = array();
  971. // SONARR CONNECT
  972. if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  973. $sonarrs = array();
  974. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  975. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  976. if (count($sonarrURLList) == count($sonarrTokenList)) {
  977. foreach ($sonarrURLList as $key => $value) {
  978. $sonarrs[$key] = array(
  979. 'url' => $value,
  980. 'token' => $sonarrTokenList[$key]
  981. );
  982. }
  983. foreach ($sonarrs as $key => $value) {
  984. try {
  985. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  986. $sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate, $GLOBALS['sonarrUnmonitored']), $key);
  987. } catch (Exception $e) {
  988. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  989. }
  990. if (!empty($sonarrCalendar)) {
  991. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  992. }
  993. }
  994. }
  995. }
  996. // LIDARR CONNECT
  997. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  998. $lidarrs = array();
  999. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  1000. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  1001. if (count($lidarrURLList) == count($lidarrTokenList)) {
  1002. foreach ($lidarrURLList as $key => $value) {
  1003. $lidarrs[$key] = array(
  1004. 'url' => $value,
  1005. 'token' => $lidarrTokenList[$key]
  1006. );
  1007. }
  1008. foreach ($lidarrs as $key => $value) {
  1009. try {
  1010. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1011. $lidarrCalendar = getLidarrCalendar($lidarr->getCalendar($startDate, $endDate), $key);
  1012. } catch (Exception $e) {
  1013. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1014. }
  1015. if (!empty($lidarrCalendar)) {
  1016. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1017. }
  1018. }
  1019. }
  1020. }
  1021. // RADARR CONNECT
  1022. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1023. $radarrs = array();
  1024. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1025. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1026. if (count($radarrURLList) == count($radarrTokenList)) {
  1027. foreach ($radarrURLList as $key => $value) {
  1028. $radarrs[$key] = array(
  1029. 'url' => $value,
  1030. 'token' => $radarrTokenList[$key]
  1031. );
  1032. }
  1033. foreach ($radarrs as $key => $value) {
  1034. try {
  1035. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1036. $radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate), $key, $value['url']);
  1037. } catch (Exception $e) {
  1038. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1039. }
  1040. if (!empty($radarrCalendar)) {
  1041. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1042. }
  1043. }
  1044. }
  1045. }
  1046. // SICKRAGE/BEARD/MEDUSA CONNECT
  1047. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1048. $sicks = array();
  1049. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1050. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1051. if (count($sickURLList) == count($sickTokenList)) {
  1052. foreach ($sickURLList as $key => $value) {
  1053. $sicks[$key] = array(
  1054. 'url' => $value,
  1055. 'token' => $sickTokenList[$key]
  1056. );
  1057. }
  1058. foreach ($sicks as $key => $value) {
  1059. try {
  1060. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1061. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1062. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1063. if (!empty($sickrageFuture)) {
  1064. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1065. }
  1066. if (!empty($sickrageHistory)) {
  1067. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1068. }
  1069. } catch (Exception $e) {
  1070. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1071. }
  1072. }
  1073. }
  1074. }
  1075. // COUCHPOTATO CONNECT
  1076. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1077. $couchs = array();
  1078. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1079. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1080. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1081. foreach ($couchpotatoURLList as $key => $value) {
  1082. $couchs[$key] = array(
  1083. 'url' => $value,
  1084. 'token' => $couchpotatoTokenList[$key]
  1085. );
  1086. }
  1087. foreach ($couchs as $key => $value) {
  1088. try {
  1089. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1090. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1091. if (!empty($couchCalendar)) {
  1092. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1093. }
  1094. } catch (Exception $e) {
  1095. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1096. }
  1097. }
  1098. }
  1099. }
  1100. // iCal URL
  1101. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1102. $calendars = array();
  1103. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1104. $icalEvents = array();
  1105. foreach ($calendarURLList as $key => $value) {
  1106. $icsEvents = getIcsEventsAsArray($value);
  1107. if (isset($icsEvents) && !empty($icsEvents)) {
  1108. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1109. unset($icsEvents [1]);
  1110. foreach ($icsEvents as $icsEvent) {
  1111. if ((isset($icsEvent['DTSTART']) || isset($icsEvent['DTSTART;VALUE=DATE'])) && (isset($icsEvent['DTEND']) || isset($icsEvent['DTEND;VALUE=DATE'])) && isset($icsEvent['SUMMARY'])) {
  1112. /* Getting start date and time */
  1113. $start = isset($icsEvent ['DTSTART;VALUE=DATE']) ? $icsEvent ['DTSTART;VALUE=DATE'] : $icsEvent ['DTSTART'];
  1114. /* Converting to datetime and apply the timezone to get proper date time */
  1115. $startDt = new DateTime ($start);
  1116. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1117. $startDate = $startDt->format(DateTime::ATOM);
  1118. /* Getting end date with time */
  1119. $end = isset($icsEvent ['DTEND;VALUE=DATE']) ? $icsEvent ['DTEND;VALUE=DATE'] : $icsEvent ['DTEND'];
  1120. $endDt = new DateTime ($end);
  1121. $endDate = $endDt->format(DateTime::ATOM);
  1122. if (new DateTime() < $endDt) {
  1123. $extraClass = 'text-info';
  1124. } else {
  1125. $extraClass = 'text-success';
  1126. }
  1127. /* Getting the name of event */
  1128. $eventName = $icsEvent['SUMMARY'];
  1129. $icalEvents[] = array(
  1130. 'title' => $eventName,
  1131. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1132. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1133. 'start' => $startDate,
  1134. 'end' => $endDate
  1135. );
  1136. }
  1137. }
  1138. }
  1139. }
  1140. $calendarSources['ical'] = $icalEvents;
  1141. }
  1142. $calendarSources['events'] = $calendarItems;
  1143. return ($calendarSources) ? $calendarSources : false;
  1144. }
  1145. function getSonarrCalendar($array, $number)
  1146. {
  1147. $array = json_decode($array, true);
  1148. $gotCalendar = array();
  1149. $i = 0;
  1150. foreach ($array as $child) {
  1151. $i++;
  1152. $seriesName = $child['series']['title'];
  1153. $seriesID = $child['series']['tvdbId'];
  1154. $episodeID = $child['series']['tvdbId'];
  1155. $monitored = $child['monitored'];
  1156. if (!isset($episodeID)) {
  1157. $episodeID = "";
  1158. }
  1159. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1160. $episodeAirDate = $child['airDateUtc'];
  1161. $episodeAirDate = strtotime($episodeAirDate);
  1162. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1163. if (new DateTime() < new DateTime($episodeAirDate)) {
  1164. $unaired = true;
  1165. }
  1166. if ($child['episodeNumber'] == "1") {
  1167. $episodePremier = "true";
  1168. } else {
  1169. $episodePremier = "false";
  1170. $date = new DateTime($episodeAirDate);
  1171. $date->add(new DateInterval("PT1S"));
  1172. $date->format(DateTime::ATOM);
  1173. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1174. }
  1175. $downloaded = $child['hasFile'];
  1176. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1177. $downloaded = "text-primary animated flash";
  1178. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1179. $downloaded = "text-dark";
  1180. } elseif ($downloaded == "0" && isset($unaired)) {
  1181. $downloaded = "text-info";
  1182. } elseif ($downloaded == "1") {
  1183. $downloaded = "text-success";
  1184. } else {
  1185. $downloaded = "text-danger";
  1186. }
  1187. $fanart = "/plugins/images/cache/no-np.png";
  1188. foreach ($child['series']['images'] as $image) {
  1189. if ($image['coverType'] == "fanart") {
  1190. $fanart = $image['url'];
  1191. }
  1192. }
  1193. if ($fanart !== "/plugins/images/cache/no-np.png") {
  1194. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1195. $imageURL = $fanart;
  1196. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1197. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1198. if (!file_exists($cacheFile)) {
  1199. cacheImage($imageURL, $seriesID);
  1200. unset($imageURL);
  1201. unset($cacheFile);
  1202. }
  1203. }
  1204. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1205. $details = array(
  1206. "seasonCount" => $child['series']['seasonCount'],
  1207. "status" => $child['series']['status'],
  1208. "topTitle" => $seriesName,
  1209. "bottomTitle" => $bottomTitle,
  1210. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1211. "runtime" => $child['series']['runtime'],
  1212. "image" => $fanart,
  1213. "ratings" => $child['series']['ratings']['value'],
  1214. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1215. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1216. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1217. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1218. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  1219. "genres" => $child['series']['genres'],
  1220. );
  1221. array_push($gotCalendar, array(
  1222. "id" => "Sonarr-" . $number . "-" . $i,
  1223. "title" => $seriesName,
  1224. "start" => $child['airDateUtc'],
  1225. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1226. "imagetype" => "tv " . $downloaded,
  1227. "imagetypeFilter" => "tv",
  1228. "downloadFilter" => $downloaded,
  1229. "bgColor" => str_replace('text', 'bg', $downloaded),
  1230. "details" => $details
  1231. ));
  1232. }
  1233. if ($i != 0) {
  1234. return $gotCalendar;
  1235. }
  1236. return false;
  1237. }
  1238. function getLidarrCalendar($array, $number)
  1239. {
  1240. $array = json_decode($array, true);
  1241. $gotCalendar = array();
  1242. $i = 0;
  1243. foreach ($array as $child) {
  1244. $i++;
  1245. $albumName = $child['title'];
  1246. $artistName = $child['artist']['artistName'];
  1247. $albumID = '';
  1248. $releaseDate = $child['releaseDate'];
  1249. $releaseDate = strtotime($releaseDate);
  1250. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1251. if (new DateTime() < new DateTime($releaseDate)) {
  1252. $unaired = true;
  1253. }
  1254. $downloaded = (isset($child['statistics']['percentOfEpisodes']) && $child['statistics']['percentOfEpisodes'] !== '100.0') ? '0' : '1';
  1255. if ($downloaded == "0" && isset($unaired)) {
  1256. $downloaded = "text-info";
  1257. } elseif ($downloaded == "1") {
  1258. $downloaded = "text-success";
  1259. } else {
  1260. $downloaded = "text-danger";
  1261. }
  1262. $fanart = "/plugins/images/cache/no-np.png";
  1263. foreach ($child['artist']['images'] as $image) {
  1264. if ($image['coverType'] == "fanart") {
  1265. $fanart = str_replace('http://', 'https://', $image['url']);
  1266. }
  1267. }
  1268. $details = array(
  1269. "seasonCount" => '',
  1270. "status" => '',
  1271. "topTitle" => $albumName,
  1272. "bottomTitle" => $artistName,
  1273. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1274. "runtime" => '',
  1275. "image" => $fanart,
  1276. "ratings" => $child['artist']['ratings']['value'],
  1277. "videoQuality" => "unknown",
  1278. "audioChannels" => "unknown",
  1279. "audioCodec" => "unknown",
  1280. "videoCodec" => "unknown",
  1281. "size" => "unknown",
  1282. "genres" => $child['genres'],
  1283. );
  1284. array_push($gotCalendar, array(
  1285. "id" => "Lidarr-" . $number . "-" . $i,
  1286. "title" => $artistName,
  1287. "start" => $child['releaseDate'],
  1288. "className" => "bg-calendar calendar-item musicID--",
  1289. "imagetype" => "music " . $downloaded,
  1290. "imagetypeFilter" => "music",
  1291. "downloadFilter" => $downloaded,
  1292. "bgColor" => str_replace('text', 'bg', $downloaded),
  1293. "details" => $details
  1294. ));
  1295. }
  1296. if ($i != 0) {
  1297. return $gotCalendar;
  1298. }
  1299. return false;
  1300. }
  1301. function getRadarrCalendar($array, $number, $url)
  1302. {
  1303. $array = json_decode($array, true);
  1304. $gotCalendar = array();
  1305. $i = 0;
  1306. foreach ($array as $child) {
  1307. if (isset($child['physicalRelease'])) {
  1308. $i++;
  1309. $movieName = $child['title'];
  1310. $movieID = $child['tmdbId'];
  1311. if (!isset($movieID)) {
  1312. $movieID = "";
  1313. }
  1314. $physicalRelease = $child['physicalRelease'];
  1315. $physicalRelease = strtotime($physicalRelease);
  1316. $physicalRelease = date("Y-m-d", $physicalRelease);
  1317. if (new DateTime() < new DateTime($physicalRelease)) {
  1318. $notReleased = "true";
  1319. } else {
  1320. $notReleased = "false";
  1321. }
  1322. $downloaded = $child['hasFile'];
  1323. if ($downloaded == "0" && $notReleased == "true") {
  1324. $downloaded = "text-info";
  1325. } elseif ($downloaded == "1") {
  1326. $downloaded = "text-success";
  1327. } else {
  1328. $downloaded = "text-danger";
  1329. }
  1330. $banner = "/plugins/images/cache/no-np.png";
  1331. foreach ($child['images'] as $image) {
  1332. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1333. $url = rtrim($url, '/'); //remove trailing slash
  1334. $imageUrl = $image['url'];
  1335. $urlParts = explode("/", $url);
  1336. $imageParts = explode("/", $image['url']);
  1337. if ($imageParts[1] == end($urlParts)) {
  1338. unset($imageParts[1]);
  1339. $imageUrl = implode("/", $imageParts);
  1340. }
  1341. $banner = $url . $imageUrl;
  1342. }
  1343. }
  1344. if ($banner !== "/plugins/images/cache/no-np.png") {
  1345. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1346. $imageURL = $banner;
  1347. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1348. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1349. if (!file_exists($cacheFile)) {
  1350. cacheImage($imageURL, $movieID);
  1351. unset($imageURL);
  1352. unset($cacheFile);
  1353. }
  1354. }
  1355. $alternativeTitles = "";
  1356. foreach ($child['alternativeTitles'] as $alternative) {
  1357. $alternativeTitles .= $alternative['title'] . ', ';
  1358. }
  1359. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1360. $details = array(
  1361. "topTitle" => $movieName,
  1362. "bottomTitle" => $alternativeTitles,
  1363. "status" => $child['status'],
  1364. "overview" => $child['overview'],
  1365. "runtime" => $child['runtime'],
  1366. "image" => $banner,
  1367. "ratings" => $child['ratings']['value'],
  1368. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1369. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1370. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1371. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1372. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1373. "genres" => $child['genres'],
  1374. );
  1375. array_push($gotCalendar, array(
  1376. "id" => "Radarr-" . $number . "-" . $i,
  1377. "title" => $movieName,
  1378. "start" => $physicalRelease,
  1379. "className" => "bg-calendar movieID--" . $movieID,
  1380. "imagetype" => "film " . $downloaded,
  1381. "imagetypeFilter" => "film",
  1382. "downloadFilter" => $downloaded,
  1383. "bgColor" => str_replace('text', 'bg', $downloaded),
  1384. "details" => $details
  1385. ));
  1386. }
  1387. }
  1388. if ($i != 0) {
  1389. return $gotCalendar;
  1390. }
  1391. return false;
  1392. }
  1393. function getCouchCalendar($array, $number)
  1394. {
  1395. $api = json_decode($array, true);
  1396. $gotCalendar = array();
  1397. $i = 0;
  1398. foreach ($api['movies'] as $child) {
  1399. if ($child['status'] == "active" || $child['status'] == "done") {
  1400. $i++;
  1401. $movieName = $child['info']['original_title'];
  1402. $movieID = $child['info']['tmdb_id'];
  1403. if (!isset($movieID)) {
  1404. $movieID = "";
  1405. }
  1406. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1407. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1408. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1409. $physicalRelease = strtotime($physicalRelease);
  1410. $physicalRelease = date("Y-m-d", $physicalRelease);
  1411. if (new DateTime() < new DateTime($physicalRelease)) {
  1412. $notReleased = "true";
  1413. } else {
  1414. $notReleased = "false";
  1415. }
  1416. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1417. if ($downloaded == "0" && $notReleased == "true") {
  1418. $downloaded = "text-info";
  1419. } elseif ($downloaded == "1") {
  1420. $downloaded = "text-success";
  1421. } else {
  1422. $downloaded = "text-danger";
  1423. }
  1424. if (!empty($child['info']['images']['backdrop_original'])) {
  1425. $banner = $child['info']['images']['backdrop_original'][0];
  1426. } elseif (!empty($child['info']['images']['backdrop'])) {
  1427. $banner = $child['info']['images']['backdrop_original'][0];
  1428. } else {
  1429. $banner = "/plugins/images/cache/no-np.png";
  1430. }
  1431. if ($banner !== "/plugins/images/cache/no-np.png") {
  1432. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1433. $imageURL = $banner;
  1434. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1435. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1436. if (!file_exists($cacheFile)) {
  1437. cacheImage($imageURL, $movieID);
  1438. unset($imageURL);
  1439. unset($cacheFile);
  1440. }
  1441. }
  1442. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1443. $details = array(
  1444. "topTitle" => $movieName,
  1445. "bottomTitle" => $child['info']['tagline'],
  1446. "status" => $child['status'],
  1447. "overview" => $child['info']['plot'],
  1448. "runtime" => $child['info']['runtime'],
  1449. "image" => $banner,
  1450. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1451. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1452. "audioChannels" => "",
  1453. "audioCodec" => "",
  1454. "videoCodec" => "",
  1455. "genres" => $child['info']['genres'],
  1456. );
  1457. array_push($gotCalendar, array(
  1458. "id" => "CouchPotato-" . $number . "-" . $i,
  1459. "title" => $movieName,
  1460. "start" => $physicalRelease,
  1461. "className" => "bg-calendar calendar-item movieID--" . $movieID,
  1462. "imagetype" => "film " . $downloaded,
  1463. "imagetypeFilter" => "film",
  1464. "downloadFilter" => $downloaded,
  1465. "bgColor" => str_replace('text', 'bg', $downloaded),
  1466. "details" => $details
  1467. ));
  1468. }
  1469. }
  1470. if ($i != 0) {
  1471. return $gotCalendar;
  1472. }
  1473. return false;
  1474. }
  1475. function getSickrageCalendarWanted($array, $number)
  1476. {
  1477. $array = json_decode($array, true);
  1478. $gotCalendar = array();
  1479. $i = 0;
  1480. foreach ($array['data']['missed'] as $child) {
  1481. $i++;
  1482. $seriesName = $child['show_name'];
  1483. $seriesID = $child['tvdbid'];
  1484. $episodeID = $child['tvdbid'];
  1485. $episodeAirDate = $child['airdate'];
  1486. $episodeAirDateTime = explode(" ", $child['airs']);
  1487. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1488. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1489. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1490. if (new DateTime() < new DateTime($episodeAirDate)) {
  1491. $unaired = true;
  1492. }
  1493. $downloaded = "0";
  1494. if ($downloaded == "0" && isset($unaired)) {
  1495. $downloaded = "text-info";
  1496. } elseif ($downloaded == "1") {
  1497. $downloaded = "text-success";
  1498. } else {
  1499. $downloaded = "text-danger";
  1500. }
  1501. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1502. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1503. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1504. $fanart = "/plugins/images/cache/no-np.png";
  1505. if (file_exists($cacheFile)) {
  1506. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1507. unset($cacheFile);
  1508. }
  1509. $details = array(
  1510. "seasonCount" => "",
  1511. "status" => $child['show_status'],
  1512. "topTitle" => $seriesName,
  1513. "bottomTitle" => $bottomTitle,
  1514. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1515. "runtime" => "",
  1516. "image" => $fanart,
  1517. "ratings" => "",
  1518. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1519. "audioChannels" => "",
  1520. "audioCodec" => "",
  1521. "videoCodec" => "",
  1522. "size" => "",
  1523. "genres" => "",
  1524. );
  1525. array_push($gotCalendar, array(
  1526. "id" => "Sick-" . $number . "-Miss-" . $i,
  1527. "title" => $seriesName,
  1528. "start" => $episodeAirDate,
  1529. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1530. "imagetype" => "tv " . $downloaded,
  1531. "imagetypeFilter" => "tv",
  1532. "downloadFilter" => $downloaded,
  1533. "bgColor" => str_replace('text', 'bg', $downloaded),
  1534. "details" => $details,
  1535. ));
  1536. }
  1537. foreach ($array['data']['today'] as $child) {
  1538. $i++;
  1539. $seriesName = $child['show_name'];
  1540. $seriesID = $child['tvdbid'];
  1541. $episodeID = $child['tvdbid'];
  1542. $episodeAirDate = $child['airdate'];
  1543. $episodeAirDateTime = explode(" ", $child['airs']);
  1544. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1545. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1546. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1547. if (new DateTime() < new DateTime($episodeAirDate)) {
  1548. $unaired = true;
  1549. }
  1550. $downloaded = "0";
  1551. if ($downloaded == "0" && isset($unaired)) {
  1552. $downloaded = "text-info";
  1553. } elseif ($downloaded == "1") {
  1554. $downloaded = "text-success";
  1555. } else {
  1556. $downloaded = "text-danger";
  1557. }
  1558. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1559. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1560. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1561. $fanart = "/plugins/images/cache/no-np.png";
  1562. if (file_exists($cacheFile)) {
  1563. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1564. unset($cacheFile);
  1565. }
  1566. $details = array(
  1567. "seasonCount" => "",
  1568. "status" => $child['show_status'],
  1569. "topTitle" => $seriesName,
  1570. "bottomTitle" => $bottomTitle,
  1571. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1572. "runtime" => "",
  1573. "image" => $fanart,
  1574. "ratings" => "",
  1575. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1576. "audioChannels" => "",
  1577. "audioCodec" => "",
  1578. "videoCodec" => "",
  1579. "size" => "",
  1580. "genres" => "",
  1581. );
  1582. array_push($gotCalendar, array(
  1583. "id" => "Sick-" . $number . "-Today-" . $i,
  1584. "title" => $seriesName,
  1585. "start" => $episodeAirDate,
  1586. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1587. "imagetype" => "tv " . $downloaded,
  1588. "imagetypeFilter" => "tv",
  1589. "downloadFilter" => $downloaded,
  1590. "bgColor" => str_replace('text', 'bg', $downloaded),
  1591. "details" => $details,
  1592. ));
  1593. }
  1594. foreach ($array['data']['soon'] as $child) {
  1595. $i++;
  1596. $seriesName = $child['show_name'];
  1597. $seriesID = $child['tvdbid'];
  1598. $episodeID = $child['tvdbid'];
  1599. $episodeAirDate = $child['airdate'];
  1600. $episodeAirDateTime = explode(" ", $child['airs']);
  1601. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1602. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1603. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1604. if (new DateTime() < new DateTime($episodeAirDate)) {
  1605. $unaired = true;
  1606. }
  1607. $downloaded = "0";
  1608. if ($downloaded == "0" && isset($unaired)) {
  1609. $downloaded = "text-info";
  1610. } elseif ($downloaded == "1") {
  1611. $downloaded = "text-success";
  1612. } else {
  1613. $downloaded = "text-danger";
  1614. }
  1615. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1616. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1617. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1618. $fanart = "/plugins/images/cache/no-np.png";
  1619. if (file_exists($cacheFile)) {
  1620. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1621. unset($cacheFile);
  1622. }
  1623. $details = array(
  1624. "seasonCount" => "",
  1625. "status" => $child['show_status'],
  1626. "topTitle" => $seriesName,
  1627. "bottomTitle" => $bottomTitle,
  1628. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1629. "runtime" => "",
  1630. "image" => $fanart,
  1631. "ratings" => "",
  1632. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1633. "audioChannels" => "",
  1634. "audioCodec" => "",
  1635. "videoCodec" => "",
  1636. "size" => "",
  1637. "genres" => "",
  1638. );
  1639. array_push($gotCalendar, array(
  1640. "id" => "Sick-" . $number . "-Soon-" . $i,
  1641. "title" => $seriesName,
  1642. "start" => $episodeAirDate,
  1643. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1644. "imagetype" => "tv " . $downloaded,
  1645. "imagetypeFilter" => "tv",
  1646. "downloadFilter" => $downloaded,
  1647. "bgColor" => str_replace('text', 'bg', $downloaded),
  1648. "details" => $details,
  1649. ));
  1650. }
  1651. foreach ($array['data']['later'] as $child) {
  1652. $i++;
  1653. $seriesName = $child['show_name'];
  1654. $seriesID = $child['tvdbid'];
  1655. $episodeID = $child['tvdbid'];
  1656. $episodeAirDate = $child['airdate'];
  1657. $episodeAirDateTime = explode(" ", $child['airs']);
  1658. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1659. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1660. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1661. if (new DateTime() < new DateTime($episodeAirDate)) {
  1662. $unaired = true;
  1663. }
  1664. $downloaded = "0";
  1665. if ($downloaded == "0" && isset($unaired)) {
  1666. $downloaded = "text-info";
  1667. } elseif ($downloaded == "1") {
  1668. $downloaded = "text-success";
  1669. } else {
  1670. $downloaded = "text-danger";
  1671. }
  1672. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1673. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1674. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1675. $fanart = "/plugins/images/cache/no-np.png";
  1676. if (file_exists($cacheFile)) {
  1677. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1678. unset($cacheFile);
  1679. }
  1680. $details = array(
  1681. "seasonCount" => "",
  1682. "status" => $child['show_status'],
  1683. "topTitle" => $seriesName,
  1684. "bottomTitle" => $bottomTitle,
  1685. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1686. "runtime" => "",
  1687. "image" => $fanart,
  1688. "ratings" => "",
  1689. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1690. "audioChannels" => "",
  1691. "audioCodec" => "",
  1692. "videoCodec" => "",
  1693. "size" => "",
  1694. "genres" => "",
  1695. );
  1696. array_push($gotCalendar, array(
  1697. "id" => "Sick-" . $number . "-Later-" . $i,
  1698. "title" => $seriesName,
  1699. "start" => $episodeAirDate,
  1700. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1701. "imagetype" => "tv " . $downloaded,
  1702. "imagetypeFilter" => "tv",
  1703. "downloadFilter" => $downloaded,
  1704. "bgColor" => str_replace('text', 'bg', $downloaded),
  1705. "details" => $details,
  1706. ));
  1707. }
  1708. if ($i != 0) {
  1709. return $gotCalendar;
  1710. }
  1711. return false;
  1712. }
  1713. function getSickrageCalendarHistory($array, $number)
  1714. {
  1715. $array = json_decode($array, true);
  1716. $gotCalendar = array();
  1717. $i = 0;
  1718. foreach ($array['data'] as $child) {
  1719. $i++;
  1720. $seriesName = $child['show_name'];
  1721. $seriesID = $child['tvdbid'];
  1722. $episodeID = $child['tvdbid'];
  1723. $episodeAirDate = $child['date'];
  1724. $downloaded = "text-success";
  1725. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  1726. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1727. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1728. $fanart = "/plugins/images/cache/no-np.png";
  1729. if (file_exists($cacheFile)) {
  1730. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1731. unset($cacheFile);
  1732. }
  1733. $details = array(
  1734. "seasonCount" => "",
  1735. "status" => $child['status'],
  1736. "topTitle" => $seriesName,
  1737. "bottomTitle" => $bottomTitle,
  1738. "overview" => '',
  1739. "runtime" => $child['series']['runtime'],
  1740. "image" => $fanart,
  1741. "ratings" => $child['series']['ratings']['value'],
  1742. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  1743. "audioChannels" => "",
  1744. "audioCodec" => "",
  1745. "videoCodec" => "",
  1746. "size" => "",
  1747. "genres" => "",
  1748. );
  1749. array_push($gotCalendar, array(
  1750. "id" => "Sick-" . $number . "-History-" . $i,
  1751. "title" => $seriesName,
  1752. "start" => $episodeAirDate,
  1753. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1754. "imagetype" => "tv " . $downloaded,
  1755. "imagetypeFilter" => "tv",
  1756. "downloadFilter" => $downloaded,
  1757. "bgColor" => str_replace('text', 'bg', $downloaded),
  1758. "details" => $details,
  1759. ));
  1760. }
  1761. if ($i != 0) {
  1762. return $gotCalendar;
  1763. }
  1764. return false;
  1765. }
  1766. function ombiAPI($array)
  1767. {
  1768. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  1769. }
  1770. function ombiImport($type = null)
  1771. {
  1772. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  1773. try {
  1774. $url = qualifyURL($GLOBALS['ombiURL']);
  1775. $headers = array(
  1776. "Accept" => "application/json",
  1777. "Content-Type" => "application/json",
  1778. "Apikey" => $GLOBALS['ombiToken']
  1779. );
  1780. $options = (localURL($url)) ? array('verify' => false) : array();
  1781. switch ($type) {
  1782. case 'emby':
  1783. case 'emby_local':
  1784. case 'emby_connect':
  1785. case 'emby_all':
  1786. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  1787. break;
  1788. case 'plex':
  1789. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  1790. break;
  1791. default:
  1792. break;
  1793. }
  1794. if ($response->success) {
  1795. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  1796. return true;
  1797. } else {
  1798. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  1799. return false;
  1800. }
  1801. } catch (Requests_Exception $e) {
  1802. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1803. return false;
  1804. };
  1805. }
  1806. return false;
  1807. }
  1808. function ombiAction($id, $action, $type, $fullArray = null)
  1809. {
  1810. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1811. $url = qualifyURL($GLOBALS['ombiURL']);
  1812. $headers = array(
  1813. "Accept" => "application/json",
  1814. "Content-Type" => "application/json",
  1815. "Apikey" => $GLOBALS['ombiToken']
  1816. );
  1817. $data = array(
  1818. 'id' => $id,
  1819. );
  1820. switch ($type) {
  1821. case 'season':
  1822. case 'tv':
  1823. $type = 'tv';
  1824. $add = array(
  1825. 'tvDbId' => $id,
  1826. 'requestAll' => ombiTVDefault('all'),
  1827. 'latestSeason' => ombiTVDefault('last'),
  1828. 'firstSeason' => ombiTVDefault('first')
  1829. );
  1830. break;
  1831. default:
  1832. $type = 'movie';
  1833. $add = array("theMovieDbId" => (int)$id);
  1834. break;
  1835. }
  1836. $success['head'] = $headers;
  1837. $success['act'] = $action;
  1838. $success['data'] = $data;
  1839. $success['add'] = $add;
  1840. $success['type'] = $type;
  1841. try {
  1842. $options = (localURL($url)) ? array('verify' => false) : array();
  1843. switch ($action) {
  1844. case 'add':
  1845. if (isset($_COOKIE['Auth'])) {
  1846. $headers = array(
  1847. "Accept" => "application/json",
  1848. "Content-Type" => "application/json",
  1849. "Authorization" => "Bearer " . $_COOKIE['Auth']
  1850. );
  1851. $success['head'] = $headers;
  1852. } else {
  1853. return false;
  1854. }
  1855. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  1856. break;
  1857. default:
  1858. if (qualifyRequest(1)) {
  1859. switch ($action) {
  1860. case 'approve':
  1861. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  1862. break;
  1863. case 'available':
  1864. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  1865. break;
  1866. case 'unavailable':
  1867. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  1868. break;
  1869. case 'deny':
  1870. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  1871. break;
  1872. case 'delete':
  1873. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  1874. break;
  1875. default:
  1876. return false;
  1877. }
  1878. }
  1879. break;
  1880. }
  1881. $success['api'] = $response;
  1882. $success['bd'] = $response->body;
  1883. $success['hd'] = $response->headers;
  1884. if ($response->success) {
  1885. $success['ok'] = true;
  1886. }
  1887. } catch (Requests_Exception $e) {
  1888. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1889. };
  1890. }
  1891. return isset($success['ok']) ? $success : false;
  1892. }
  1893. function getOmbiRequests($type = "both")
  1894. {
  1895. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1896. $url = qualifyURL($GLOBALS['ombiURL']);
  1897. $headers = array(
  1898. "Accept" => "application/json",
  1899. "Apikey" => $GLOBALS['ombiToken'],
  1900. );
  1901. $requests = array();
  1902. try {
  1903. $options = (localURL($url)) ? array('verify' => false) : array();
  1904. switch ($type) {
  1905. case 'movie':
  1906. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  1907. break;
  1908. case 'tv':
  1909. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  1910. break;
  1911. default:
  1912. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  1913. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  1914. break;
  1915. }
  1916. if ($movie->success || $tv->success) {
  1917. if (isset($movie)) {
  1918. $movie = json_decode($movie->body, true);
  1919. //$movie = array_reverse($movie);
  1920. foreach ($movie as $key => $value) {
  1921. $requests[] = array(
  1922. 'test' => $value,
  1923. 'id' => $value['theMovieDbId'],
  1924. 'title' => $value['title'],
  1925. 'overview' => $value['overview'],
  1926. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
  1927. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  1928. 'approved' => $value['approved'],
  1929. 'available' => $value['available'],
  1930. 'denied' => $value['denied'],
  1931. 'deniedReason' => $value['deniedReason'],
  1932. 'user' => $value['requestedUser']['userName'],
  1933. 'request_id' => $value['id'],
  1934. 'request_date' => $value['requestedDate'],
  1935. 'release_date' => $value['releaseDate'],
  1936. 'type' => 'movie',
  1937. 'icon' => 'mdi mdi-filmstrip',
  1938. 'color' => 'palette-Deep-Purple-900 bg white',
  1939. );
  1940. }
  1941. }
  1942. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  1943. $tv = json_decode($tv->body, true);
  1944. foreach ($tv as $key => $value) {
  1945. if (is_array($value['childRequests'][0])) {
  1946. $requests[] = array(
  1947. 'test' => $value,
  1948. 'id' => $value['tvDbId'],
  1949. 'title' => $value['title'],
  1950. 'overview' => $value['overview'],
  1951. 'poster' => $value['posterPath'],
  1952. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  1953. 'approved' => $value['childRequests'][0]['approved'],
  1954. 'available' => $value['childRequests'][0]['available'],
  1955. 'denied' => $value['childRequests'][0]['denied'],
  1956. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  1957. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  1958. 'request_id' => $value['id'],
  1959. 'request_date' => $value['childRequests'][0]['requestedDate'],
  1960. 'release_date' => $value['releaseDate'],
  1961. 'type' => 'tv',
  1962. 'icon' => 'mdi mdi-television',
  1963. 'color' => 'grayish-blue-bg',
  1964. );
  1965. }
  1966. }
  1967. }
  1968. //sort here
  1969. usort($requests, function ($item1, $item2) {
  1970. if ($item1['request_date'] == $item2['request_date']) {
  1971. return 0;
  1972. }
  1973. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  1974. });
  1975. }
  1976. } catch (Requests_Exception $e) {
  1977. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1978. };
  1979. }
  1980. $api['content'] = isset($requests) ? $requests : false;
  1981. return $api;
  1982. }
  1983. function testAPIConnection($array)
  1984. {
  1985. switch ($array['data']['action']) {
  1986. case 'plex':
  1987. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  1988. $url = qualifyURL($GLOBALS['plexURL']);
  1989. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  1990. try {
  1991. $options = (localURL($url)) ? array('verify' => false) : array();
  1992. $response = Requests::get($url, array(), $options);
  1993. libxml_use_internal_errors(true);
  1994. if ($response->success) {
  1995. return true;
  1996. }
  1997. } catch (Requests_Exception $e) {
  1998. return $e->getMessage();
  1999. };
  2000. } else {
  2001. return 'URL and/or Token not setup';
  2002. }
  2003. break;
  2004. case 'emby':
  2005. break;
  2006. case 'sonarr':
  2007. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2008. $sonarrs = array();
  2009. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2010. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2011. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2012. foreach ($sonarrURLList as $key => $value) {
  2013. $sonarrs[$key] = array(
  2014. 'url' => $value,
  2015. 'token' => $sonarrTokenList[$key]
  2016. );
  2017. }
  2018. foreach ($sonarrs as $key => $value) {
  2019. try {
  2020. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2021. $sonarr->getSystemStatus();
  2022. return true;
  2023. } catch (Exception $e) {
  2024. return $e->getMessage();
  2025. }
  2026. }
  2027. }
  2028. } else {
  2029. return 'URL/s and/or Token/s not setup';
  2030. }
  2031. break;
  2032. case 'lidarr':
  2033. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2034. $sonarrs = array();
  2035. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2036. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2037. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2038. foreach ($sonarrURLList as $key => $value) {
  2039. $sonarrs[$key] = array(
  2040. 'url' => $value,
  2041. 'token' => $sonarrTokenList[$key]
  2042. );
  2043. }
  2044. foreach ($sonarrs as $key => $value) {
  2045. try {
  2046. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2047. $sonarr->getSystemStatus();
  2048. return true;
  2049. } catch (Exception $e) {
  2050. return $e->getMessage();
  2051. }
  2052. }
  2053. }
  2054. } else {
  2055. return 'URL/s and/or Token/s not setup';
  2056. }
  2057. break;
  2058. case 'radarr':
  2059. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2060. $sonarrs = array();
  2061. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2062. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2063. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2064. foreach ($sonarrURLList as $key => $value) {
  2065. $sonarrs[$key] = array(
  2066. 'url' => $value,
  2067. 'token' => $sonarrTokenList[$key]
  2068. );
  2069. }
  2070. foreach ($sonarrs as $key => $value) {
  2071. try {
  2072. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2073. $sonarr->getSystemStatus();
  2074. return true;
  2075. } catch (Exception $e) {
  2076. return $e->getMessage();
  2077. }
  2078. }
  2079. }
  2080. } else {
  2081. return 'URL/s and/or Token/s not setup';
  2082. }
  2083. break;
  2084. case 'sabnzbd':
  2085. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2086. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2087. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2088. try {
  2089. $options = (localURL($url)) ? array('verify' => false) : array();
  2090. $response = Requests::get($url, array(), $options);
  2091. if ($response->success) {
  2092. return true;
  2093. }
  2094. } catch (Requests_Exception $e) {
  2095. return $e->getMessage();
  2096. };
  2097. } else {
  2098. return 'URL and/or Token not setup';
  2099. }
  2100. break;
  2101. case 'nzbget':
  2102. if (!empty($GLOBALS['nzbgetURL'])) {
  2103. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2104. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  2105. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  2106. } else {
  2107. $url = $url . '/jsonrpc/listgroups';
  2108. }
  2109. try {
  2110. $options = (localURL($url)) ? array('verify' => false) : array();
  2111. $response = Requests::get($url, array(), $options);
  2112. if ($response->success) {
  2113. return true;
  2114. }
  2115. } catch (Requests_Exception $e) {
  2116. return $e->getMessage();
  2117. };
  2118. } else {
  2119. return 'URL and/or Username/Password not setup';
  2120. }
  2121. break;
  2122. case 'deluge':
  2123. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2124. try {
  2125. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2126. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  2127. return true;
  2128. } catch (Exception $e) {
  2129. return $e->getMessage();
  2130. }
  2131. } else {
  2132. return 'URL and/or Password not setup';
  2133. }
  2134. break;
  2135. case 'rtorrent':
  2136. if (!empty($GLOBALS['rTorrentURL'])) {
  2137. try {
  2138. $digest = qualifyURL($GLOBALS['rTorrentURL'], true);
  2139. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2140. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2141. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2142. $options = (localURL($url)) ? array('verify' => false) : array();
  2143. $data = xmlrpc_encode_request("system.listMethods", null);
  2144. $response = Requests::post($url, array(), $data, $options);
  2145. if ($response->success) {
  2146. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2147. if (count($methods) !== 0) {
  2148. return true;
  2149. }
  2150. }
  2151. return false;
  2152. } catch
  2153. (Requests_Exception $e) {
  2154. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2155. return $e->getMessage();
  2156. };
  2157. }
  2158. break;
  2159. default :
  2160. return false;
  2161. }
  2162. return false;
  2163. }