homepage-connect-functions.php 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333
  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($GLOBALS['ombiLimit']);
  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['addedAt'] = isset($item['addedAt']) ? (int)$item['addedAt'] : null;
  386. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  387. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress'] - $plexItem['watched']) : '';
  388. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision'] : '';
  389. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  390. $plexItem['session'] = (string)$item->Session['id'];
  391. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  392. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  393. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  394. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  395. $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
  396. $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
  397. $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
  398. $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'];
  399. $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '$' . randString();
  400. $plexItem['originalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '$' . randString();
  401. $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
  402. $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
  403. // Stream info
  404. $plexItem['userStream'] = array(
  405. 'platform' => (string)$item->Player['platform'],
  406. 'product' => (string)$item->Player['product'],
  407. 'device' => (string)$item->Player['device'],
  408. 'stream' => (string)$item->Media->Part['decision'] . ($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)' : ''),
  409. 'videoResolution' => (string)$item->Media['videoResolution'],
  410. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  411. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  412. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  413. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  414. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  415. 'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
  416. 'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
  417. 'container' => (string)$item->TranscodeSession['container'],
  418. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  419. );
  420. // Genre catch all
  421. if ($item->Genre) {
  422. $genres = array();
  423. foreach ($item->Genre as $key => $value) {
  424. $genres[] = (string)$value['tag'];
  425. }
  426. }
  427. // Actor catch all
  428. if ($item->Role) {
  429. $actors = array();
  430. foreach ($item->Role as $key => $value) {
  431. if ($value['thumb']) {
  432. $actors[] = array(
  433. 'name' => (string)$value['tag'],
  434. 'role' => (string)$value['role'],
  435. 'thumb' => (string)$value['thumb']
  436. );
  437. }
  438. }
  439. }
  440. // Metadata information
  441. $plexItem['metadata'] = array(
  442. 'guid' => (string)$item['guid'],
  443. 'summary' => (string)$item['summary'],
  444. 'rating' => (string)$item['rating'],
  445. 'duration' => (string)$item['duration'],
  446. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  447. 'year' => (string)$item['year'],
  448. 'studio' => (string)$item['studio'],
  449. 'tagline' => (string)$item['tagline'],
  450. 'genres' => ($item->Genre) ? $genres : '',
  451. 'actors' => ($item->Role) ? $actors : ''
  452. );
  453. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  454. $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $plexItem['nowPlayingKey'] . '.jpg';
  455. }
  456. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  457. $plexItem['imageURL'] = $cacheDirectoryWeb . $plexItem['key'] . '.jpg';
  458. }
  459. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  460. $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '';
  461. }
  462. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['key'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  463. $plexItem['imageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '';
  464. }
  465. if (!$plexItem['nowPlayingThumb']) {
  466. $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  467. $plexItem['nowPlayingKey'] = "no-np";
  468. }
  469. if (!$plexItem['thumb']) {
  470. $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
  471. $plexItem['key'] = "no-list";
  472. }
  473. if (isset($useImage)) {
  474. $plexItem['useImage'] = $useImage;
  475. }
  476. return $plexItem;
  477. }
  478. function plexConnect($action, $key = null)
  479. {
  480. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))) {
  481. $url = qualifyURL($GLOBALS['plexURL']);
  482. $multipleURL = false;
  483. $ignore = array();
  484. $resolve = true;
  485. switch ($action) {
  486. case 'streams':
  487. $url = $url . "/status/sessions?X-Plex-Token=" . $GLOBALS['plexToken'];
  488. break;
  489. case 'libraries':
  490. $url = $url . "/library/sections?X-Plex-Token=" . $GLOBALS['plexToken'];
  491. $resolve = false;
  492. break;
  493. case 'recent':
  494. //$url = $url . "/library/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&limit=" . $GLOBALS['homepageRecentLimit'];
  495. $urls['movie'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $GLOBALS['homepageRecentLimit'] . "&type=1";
  496. $urls['tv'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $GLOBALS['homepageRecentLimit'] . "&type=2";
  497. $urls['music'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $GLOBALS['homepageRecentLimit'] . "&type=8";
  498. $multipleURL = true;
  499. break;
  500. case 'metadata':
  501. $url = $url . "/library/metadata/" . $key . "?X-Plex-Token=" . $GLOBALS['plexToken'];
  502. break;
  503. case 'playlists':
  504. $url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
  505. break;
  506. case 'search':
  507. $url = $url . "/search?query=" . rawurlencode($key) . "&X-Plex-Token=" . $GLOBALS['plexToken'];
  508. $ignore = array('artist', 'episode');
  509. break;
  510. default:
  511. # code...
  512. break;
  513. }
  514. try {
  515. if (!$multipleURL) {
  516. $options = (localURL($url)) ? array('verify' => false) : array();
  517. $response = Requests::get($url, array(), $options);
  518. libxml_use_internal_errors(true);
  519. if ($response->success) {
  520. $items = array();
  521. $plex = simplexml_load_string($response->body);
  522. foreach ($plex as $child) {
  523. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  524. $items[] = resolvePlexItem($child);
  525. }
  526. }
  527. $api['content'] = ($resolve) ? $items : $plex;
  528. $api['plexID'] = $GLOBALS['plexID'];
  529. $api['showNames'] = true;
  530. $api['group'] = '1';
  531. return $api;
  532. }
  533. } else {
  534. foreach ($urls as $k => $v) {
  535. $options = (localURL($v)) ? array('verify' => false) : array();
  536. $response = Requests::get($v, array(), $options);
  537. libxml_use_internal_errors(true);
  538. if ($response->success) {
  539. $items = array();
  540. $plex = simplexml_load_string($response->body);
  541. foreach ($plex as $child) {
  542. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  543. $items[] = resolvePlexItem($child);
  544. }
  545. }
  546. if (isset($api)) {
  547. $api['content'] = array_merge($api['content'], ($resolve) ? $items : $plex);
  548. } else {
  549. $api['content'] = ($resolve) ? $items : $plex;
  550. }
  551. }
  552. }
  553. if (isset($api['content'])) {
  554. usort($api['content'], function ($a, $b) {
  555. return $b['addedAt'] <=> $a['addedAt'];
  556. });
  557. }
  558. $api['plexID'] = $GLOBALS['plexID'];
  559. $api['showNames'] = true;
  560. $api['group'] = '1';
  561. return $api;
  562. }
  563. } catch (Requests_Exception $e) {
  564. writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  565. };
  566. }
  567. return false;
  568. }
  569. function getPlexPlaylists()
  570. {
  571. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])) {
  572. $url = qualifyURL($GLOBALS['plexURL']);
  573. $url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
  574. try {
  575. $options = (localURL($url)) ? array('verify' => false) : array();
  576. $response = Requests::get($url, array(), $options);
  577. libxml_use_internal_errors(true);
  578. if ($response->success) {
  579. $items = array();
  580. $plex = simplexml_load_string($response->body);
  581. foreach ($plex as $child) {
  582. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
  583. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  584. $playlistURL = qualifyURL($GLOBALS['plexURL']);
  585. $playlistURL = $playlistURL . $child['key'] . "?X-Plex-Token=" . $GLOBALS['plexToken'];
  586. $options = (localURL($url)) ? array('verify' => false) : array();
  587. $playlistResponse = Requests::get($playlistURL, array(), $options);
  588. if ($playlistResponse->success) {
  589. $playlistResponse = simplexml_load_string($playlistResponse->body);
  590. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  591. foreach ($playlistResponse->Video as $playlistItem) {
  592. $items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
  593. }
  594. }
  595. }
  596. }
  597. $api['content'] = $items;
  598. $api['plexID'] = $GLOBALS['plexID'];
  599. $api['showNames'] = true;
  600. $api['group'] = '1';
  601. return $api;
  602. }
  603. } catch (Requests_Exception $e) {
  604. writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  605. };
  606. }
  607. return false;
  608. }
  609. function embyConnect($action, $key = null, $skip = false)
  610. {
  611. if ($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])) {
  612. $url = qualifyURL($GLOBALS['embyURL']);
  613. switch ($action) {
  614. case 'streams':
  615. $url = $url . '/Sessions?api_key=' . $GLOBALS['embyToken'];
  616. break;
  617. case 'recent':
  618. $username = false;
  619. if (isset($GLOBALS['organizrUser']['username'])) {
  620. $username = strtolower($GLOBALS['organizrUser']['username']);
  621. }
  622. // Get A User
  623. $userIds = $url . "/Users?api_key=" . $GLOBALS['embyToken'];
  624. $showPlayed = true;
  625. try {
  626. $options = (localURL($userIds)) ? array('verify' => false) : array();
  627. $response = Requests::get($userIds, array(), $options);
  628. if ($response->success) {
  629. $emby = json_decode($response->body, true);
  630. foreach ($emby as $value) { // Scan for admin user
  631. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  632. $userId = $value['Id'];
  633. }
  634. if ($username && strtolower($value['Name']) == $username) {
  635. $userId = $value['Id'];
  636. $showPlayed = false;
  637. break;
  638. }
  639. }
  640. $url = $url . '/Users/' . $userId . '/Items/Latest?EnableImages=false&Limit=' . $GLOBALS['homepageRecentLimit'] . '&api_key=' . $GLOBALS['embyToken'] . ($showPlayed ? '' : '&IsPlayed=false');
  641. }
  642. } catch (Requests_Exception $e) {
  643. writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  644. };
  645. break;
  646. case 'metadata':
  647. $skip = true;
  648. break;
  649. default:
  650. # code...
  651. break;
  652. }
  653. if ($skip && $key) {
  654. $items[] = resolveEmbyItem(array('Id' => $key));
  655. $api['content'] = $items;
  656. return $api;
  657. }
  658. try {
  659. $options = (localURL($url)) ? array('verify' => false) : array();
  660. $response = Requests::get($url, array(), $options);
  661. if ($response->success) {
  662. $items = array();
  663. $emby = json_decode($response->body, true);
  664. foreach ($emby as $child) {
  665. if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
  666. $items[] = resolveEmbyItem($child);
  667. }
  668. }
  669. $api['content'] = array_filter($items);
  670. return $api;
  671. }
  672. } catch (Requests_Exception $e) {
  673. writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  674. };
  675. }
  676. return false;
  677. }
  678. function sabnzbdConnect()
  679. {
  680. if ($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])) {
  681. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  682. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  683. try {
  684. $options = (localURL($url)) ? array('verify' => false) : array();
  685. $response = Requests::get($url, array(), $options);
  686. if ($response->success) {
  687. $api['content']['queueItems'] = json_decode($response->body, true);
  688. }
  689. } catch (Requests_Exception $e) {
  690. writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  691. };
  692. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  693. $url = $url . '/api?mode=history&output=json&limit=100&apikey=' . $GLOBALS['sabnzbdToken'];
  694. try {
  695. $options = (localURL($url)) ? array('verify' => false) : array();
  696. $response = Requests::get($url, array(), $options);
  697. if ($response->success) {
  698. $api['content']['historyItems'] = json_decode($response->body, true);
  699. }
  700. } catch (Requests_Exception $e) {
  701. writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  702. };
  703. $api['content'] = isset($api['content']) ? $api['content'] : false;
  704. return $api;
  705. }
  706. return false;
  707. }
  708. function nzbgetConnect()
  709. {
  710. if ($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])) {
  711. $url = qualifyURL($GLOBALS['nzbgetURL']);
  712. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  713. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  714. } else {
  715. $url = $url . '/jsonrpc/listgroups';
  716. }
  717. try {
  718. $options = (localURL($url)) ? array('verify' => false) : array();
  719. $response = Requests::get($url, array(), $options);
  720. if ($response->success) {
  721. $api['content']['queueItems'] = json_decode($response->body, true);
  722. }
  723. } catch (Requests_Exception $e) {
  724. writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  725. };
  726. $url = qualifyURL($GLOBALS['nzbgetURL']);
  727. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  728. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/history';
  729. } else {
  730. $url = $url . '/jsonrpc/history';
  731. }
  732. try {
  733. $options = (localURL($url)) ? array('verify' => false) : array();
  734. $response = Requests::get($url, array(), $options);
  735. if ($response->success) {
  736. $api['content']['historyItems'] = json_decode($response->body, true);
  737. }
  738. } catch (Requests_Exception $e) {
  739. writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  740. };
  741. $api['content'] = isset($api['content']) ? $api['content'] : false;
  742. return $api;
  743. }
  744. return false;
  745. }
  746. function transmissionConnect()
  747. {
  748. if ($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])) {
  749. $digest = qualifyURL($GLOBALS['transmissionURL'], true);
  750. $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'] . ':' . decrypt($GLOBALS['transmissionPassword']) . "@" : '';
  751. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . '/rpc';
  752. try {
  753. $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false) : array();
  754. $response = Requests::get($url, array(), $options);
  755. if ($response->headers['x-transmission-session-id']) {
  756. $headers = array(
  757. 'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
  758. 'Content-Type' => 'application/json'
  759. );
  760. $data = array(
  761. 'method' => 'torrent-get',
  762. 'arguments' => array(
  763. 'fields' => array(
  764. "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir", "errorString"
  765. ),
  766. ),
  767. 'tags' => ''
  768. );
  769. $response = Requests::post($url, $headers, json_encode($data), $options);
  770. if ($response->success) {
  771. $torrentList = json_decode($response->body, true)['arguments']['torrents'];
  772. if ($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']) {
  773. $filter = array();
  774. $torrents['arguments']['torrents'] = array();
  775. if ($GLOBALS['transmissionHideSeeding']) {
  776. array_push($filter, 6, 5);
  777. }
  778. if ($GLOBALS['transmissionHideCompleted']) {
  779. array_push($filter, 0);
  780. }
  781. foreach ($torrentList as $key => $value) {
  782. if (!in_array($value['status'], $filter)) {
  783. $torrents['arguments']['torrents'][] = $value;
  784. }
  785. }
  786. } else {
  787. $torrents = json_decode($response->body, true);
  788. }
  789. $api['content']['queueItems'] = $torrents;
  790. $api['content']['historyItems'] = false;
  791. }
  792. } else {
  793. writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
  794. }
  795. } catch (Requests_Exception $e) {
  796. writeLog('error', 'Transmission Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  797. };
  798. $api['content'] = isset($api['content']) ? $api['content'] : false;
  799. return $api;
  800. }
  801. return false;
  802. }
  803. function rTorrentStatus($completed, $state, $status)
  804. {
  805. if ($completed && $state && $status == 'seed') {
  806. $state = 'Seeding';
  807. } elseif (!$completed && !$state && $status == 'leech') {
  808. $state = 'Stopped';
  809. } elseif (!$completed && $state && $status == 'leech') {
  810. $state = 'Downloading';
  811. } elseif ($completed && !$state && $status == 'seed') {
  812. $state = 'Finished';
  813. }
  814. return ($state) ? $state : $status;
  815. }
  816. function rTorrentConnect()
  817. {
  818. if ($GLOBALS['homepagerTorrentEnabled'] && !empty($GLOBALS['rTorrentURL']) && qualifyRequest($GLOBALS['homepagerTorrentAuth'])) {
  819. try {
  820. $torrents = array();
  821. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  822. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  823. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  824. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  825. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  826. $options = (localURL($url)) ? array('verify' => false) : array();
  827. $data = xmlrpc_encode_request("d.multicall2", array(
  828. "",
  829. "main",
  830. "d.name=",
  831. "d.base_path=",
  832. "d.up.total=",
  833. "d.size_bytes=",
  834. "d.down.total=",
  835. "d.completed_bytes=",
  836. "d.connection_current=",
  837. "d.down.rate=",
  838. "d.up.rate=",
  839. "d.timestamp.started=",
  840. "d.state=",
  841. "d.group.name=",
  842. "d.hash=",
  843. "d.complete=",
  844. "d.ratio=",
  845. "d.chunk_size=",
  846. "f.size_bytes=",
  847. "f.size_chunks=",
  848. "f.completed_chunks=",
  849. "d.custom=",
  850. "d.custom1=",
  851. "d.custom2=",
  852. "d.custom3=",
  853. "d.custom4=",
  854. "d.custom5=",
  855. ), array());
  856. $response = Requests::post($url, array(), $data, $options);
  857. if ($response->success) {
  858. $torrentList = xmlrpc_decode(str_replace('i8>', 'string>', $response->body));
  859. foreach ($torrentList as $key => $value) {
  860. $tempStatus = rTorrentStatus($value[13], $value[10], $value[6]);
  861. if ($tempStatus == 'Seeding' && $GLOBALS['rTorrentHideSeeding']) {
  862. //do nothing
  863. } elseif ($tempStatus == 'Finished' && $GLOBALS['rTorrentHideCompleted']) {
  864. //do nothing
  865. } else {
  866. $torrents[$key] = array(
  867. 'name' => $value[0],
  868. 'base' => $value[1],
  869. 'upTotal' => $value[2],
  870. 'size' => $value[3],
  871. 'downTotal' => $value[4],
  872. 'downloaded' => $value[5],
  873. 'connectionState' => $value[6],
  874. 'leech' => $value[7],
  875. 'seed' => $value[8],
  876. 'date' => $value[9],
  877. 'state' => ($value[10]) ? 'on' : 'off',
  878. 'group' => $value[11],
  879. 'hash' => $value[12],
  880. 'complete' => ($value[13]) ? 'yes' : 'no',
  881. 'ratio' => $value[14],
  882. 'label' => $value[20],
  883. 'status' => $tempStatus,
  884. 'temp' => $value[16] . ' - ' . $value[17] . ' - ' . $value[18],
  885. 'custom' => $value[19] . ' - ' . $value[20] . ' - ' . $value[21],
  886. 'custom2' => $value[22] . ' - ' . $value[23] . ' - ' . $value[24],
  887. );
  888. }
  889. }
  890. if (count($torrents) !== 0) {
  891. usort($torrents, function ($a, $b) {
  892. $direction = substr($GLOBALS['rTorrentSortOrder'], -1);
  893. $sort = substr($GLOBALS['rTorrentSortOrder'], 0, strlen($GLOBALS['rTorrentSortOrder']) - 1);
  894. switch ($direction) {
  895. case 'a':
  896. return $a[$sort] <=> $b[$sort];
  897. break;
  898. case 'd':
  899. return $b[$sort] <=> $a[$sort];
  900. break;
  901. default:
  902. return $b['date'] <=> $a['date'];
  903. }
  904. });
  905. }
  906. $api['content']['queueItems'] = $torrents;
  907. $api['content']['historyItems'] = false;
  908. }
  909. } catch
  910. (Requests_Exception $e) {
  911. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  912. };
  913. $api['content'] = isset($api['content']) ? $api['content'] : false;
  914. return $api;
  915. }
  916. return false;
  917. }
  918. function qBittorrentConnect()
  919. {
  920. if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
  921. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  922. $data = array('username' => $GLOBALS['qBittorrentUsername'], 'password' => decrypt($GLOBALS['qBittorrentPassword']));
  923. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/login';
  924. try {
  925. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false) : array();
  926. $response = Requests::post($url, array(), $data, $options);
  927. $reflection = new ReflectionClass($response->cookies);
  928. $cookie = $reflection->getProperty("cookies");
  929. $cookie->setAccessible(true);
  930. $cookie = $cookie->getValue($response->cookies);
  931. if ($cookie) {
  932. $headers = array(
  933. 'Cookie' => 'SID=' . $cookie['SID']->value
  934. );
  935. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  936. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  937. $response = Requests::get($url, $headers, $options);
  938. if ($response) {
  939. $torrentList = json_decode($response->body, true);
  940. if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
  941. $filter = array();
  942. $torrents['arguments']['torrents'] = array();
  943. if ($GLOBALS['qBittorrentHideSeeding']) {
  944. array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
  945. }
  946. if ($GLOBALS['qBittorrentHideCompleted']) {
  947. array_push($filter, 'pausedUP');
  948. }
  949. foreach ($torrentList as $key => $value) {
  950. if (!in_array($value['state'], $filter)) {
  951. $torrents['arguments']['torrents'][] = $value;
  952. }
  953. }
  954. } else {
  955. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  956. }
  957. $api['content']['queueItems'] = $torrents;
  958. $api['content']['historyItems'] = false;
  959. }
  960. } else {
  961. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  962. }
  963. } catch (Requests_Exception $e) {
  964. writeLog('error', 'qBittorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  965. };
  966. $api['content'] = isset($api['content']) ? $api['content'] : false;
  967. return $api;
  968. }
  969. return false;
  970. }
  971. function delugeStatus($queued, $status, $state)
  972. {
  973. if ($queued == '-1' && $state == '100' && ($status == 'Seeding' || $status == 'Queued' || $status == 'Paused')) {
  974. $state = 'Seeding';
  975. } elseif ($state !== '100') {
  976. $state = 'Downloading';
  977. } else {
  978. $state = 'Finished';
  979. }
  980. return ($state) ? $state : $status;
  981. }
  982. function delugeConnect()
  983. {
  984. if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
  985. try {
  986. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  987. $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');
  988. foreach ($torrents as $key => $value) {
  989. $tempStatus = delugeStatus($value->queue, $value->state, $value->progress);
  990. if ($tempStatus == 'Seeding' && $GLOBALS['delugeHideSeeding']) {
  991. //do nothing
  992. } elseif ($tempStatus == 'Finished' && $GLOBALS['delugeHideCompleted']) {
  993. //do nothing
  994. } else {
  995. $api['content']['queueItems'][] = $value;
  996. }
  997. }
  998. $api['content']['queueItems'] = (empty($api['content']['queueItems'])) ? [] : $api['content']['queueItems'];
  999. $api['content']['historyItems'] = false;
  1000. } catch (Excecption $e) {
  1001. writeLog('error', 'Deluge Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1002. }
  1003. }
  1004. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1005. return $api;
  1006. }
  1007. function getCalendar()
  1008. {
  1009. $startDate = date('Y-m-d', strtotime("-" . $GLOBALS['calendarStart'] . " days"));
  1010. $endDate = date('Y-m-d', strtotime("+" . $GLOBALS['calendarEnd'] . " days"));
  1011. $icalCalendarSources = array();
  1012. $calendarItems = array();
  1013. // SONARR CONNECT
  1014. if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  1015. $sonarrs = array();
  1016. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  1017. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  1018. if (count($sonarrURLList) == count($sonarrTokenList)) {
  1019. foreach ($sonarrURLList as $key => $value) {
  1020. $sonarrs[$key] = array(
  1021. 'url' => $value,
  1022. 'token' => $sonarrTokenList[$key]
  1023. );
  1024. }
  1025. foreach ($sonarrs as $key => $value) {
  1026. try {
  1027. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1028. $sonarr = $sonarr->getCalendar($startDate, $endDate, $GLOBALS['sonarrUnmonitored']);
  1029. $result = json_decode($sonarr, true);
  1030. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : getSonarrCalendar($sonarr, $key);;
  1031. } catch (Exception $e) {
  1032. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1033. }
  1034. if (!empty($sonarrCalendar)) {
  1035. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. // LIDARR CONNECT
  1041. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  1042. $lidarrs = array();
  1043. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  1044. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  1045. if (count($lidarrURLList) == count($lidarrTokenList)) {
  1046. foreach ($lidarrURLList as $key => $value) {
  1047. $lidarrs[$key] = array(
  1048. 'url' => $value,
  1049. 'token' => $lidarrTokenList[$key]
  1050. );
  1051. }
  1052. foreach ($lidarrs as $key => $value) {
  1053. try {
  1054. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1055. $lidarr = $lidarr->getCalendar($startDate, $endDate);
  1056. $result = json_decode($lidarr, true);
  1057. $lidarrCalendar = (array_key_exists('error', $result)) ? '' : getLidarrCalendar($lidarr, $key);;
  1058. } catch (Exception $e) {
  1059. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1060. }
  1061. if (!empty($lidarrCalendar)) {
  1062. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1063. }
  1064. }
  1065. }
  1066. }
  1067. // RADARR CONNECT
  1068. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1069. $radarrs = array();
  1070. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1071. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1072. if (count($radarrURLList) == count($radarrTokenList)) {
  1073. foreach ($radarrURLList as $key => $value) {
  1074. $radarrs[$key] = array(
  1075. 'url' => $value,
  1076. 'token' => $radarrTokenList[$key]
  1077. );
  1078. }
  1079. foreach ($radarrs as $key => $value) {
  1080. try {
  1081. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1082. $radarr = $radarr->getCalendar($startDate, $endDate);
  1083. $result = json_decode($radarr, true);
  1084. $radarrCalendar = (array_key_exists('error', $result)) ? '' : getRadarrCalendar($radarr, $key, $value['url']);
  1085. } catch (Exception $e) {
  1086. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1087. }
  1088. if (!empty($radarrCalendar)) {
  1089. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. // SICKRAGE/BEARD/MEDUSA CONNECT
  1095. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1096. $sicks = array();
  1097. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1098. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1099. if (count($sickURLList) == count($sickTokenList)) {
  1100. foreach ($sickURLList as $key => $value) {
  1101. $sicks[$key] = array(
  1102. 'url' => $value,
  1103. 'token' => $sickTokenList[$key]
  1104. );
  1105. }
  1106. foreach ($sicks as $key => $value) {
  1107. try {
  1108. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1109. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1110. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1111. if (!empty($sickrageFuture)) {
  1112. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1113. }
  1114. if (!empty($sickrageHistory)) {
  1115. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1116. }
  1117. } catch (Exception $e) {
  1118. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1119. }
  1120. }
  1121. }
  1122. }
  1123. // COUCHPOTATO CONNECT
  1124. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1125. $couchs = array();
  1126. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1127. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1128. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1129. foreach ($couchpotatoURLList as $key => $value) {
  1130. $couchs[$key] = array(
  1131. 'url' => $value,
  1132. 'token' => $couchpotatoTokenList[$key]
  1133. );
  1134. }
  1135. foreach ($couchs as $key => $value) {
  1136. try {
  1137. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1138. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1139. if (!empty($couchCalendar)) {
  1140. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1141. }
  1142. } catch (Exception $e) {
  1143. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1144. }
  1145. }
  1146. }
  1147. }
  1148. // iCal URL
  1149. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1150. $calendars = array();
  1151. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1152. $icalEvents = array();
  1153. foreach ($calendarURLList as $key => $value) {
  1154. $icsEvents = getIcsEventsAsArray($value);
  1155. if (isset($icsEvents) && !empty($icsEvents)) {
  1156. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1157. unset($icsEvents [1]);
  1158. foreach ($icsEvents as $icsEvent) {
  1159. if ((isset($icsEvent['DTSTART']) || isset($icsEvent['DTSTART;VALUE=DATE'])) && (isset($icsEvent['DTEND']) || isset($icsEvent['DTEND;VALUE=DATE'])) && isset($icsEvent['SUMMARY'])) {
  1160. /* Getting start date and time */
  1161. $start = isset($icsEvent ['DTSTART;VALUE=DATE']) ? $icsEvent ['DTSTART;VALUE=DATE'] : $icsEvent ['DTSTART'];
  1162. /* Converting to datetime and apply the timezone to get proper date time */
  1163. $startDt = new DateTime ($start);
  1164. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1165. $startDate = $startDt->format(DateTime::ATOM);
  1166. /* Getting end date with time */
  1167. $end = isset($icsEvent ['DTEND;VALUE=DATE']) ? $icsEvent ['DTEND;VALUE=DATE'] : $icsEvent ['DTEND'];
  1168. $endDt = new DateTime ($end);
  1169. $endDate = $endDt->format(DateTime::ATOM);
  1170. if (new DateTime() < $endDt) {
  1171. $extraClass = 'text-info';
  1172. } else {
  1173. $extraClass = 'text-success';
  1174. }
  1175. /* Getting the name of event */
  1176. $eventName = $icsEvent['SUMMARY'];
  1177. $icalEvents[] = array(
  1178. 'title' => $eventName,
  1179. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1180. 'imagetypeFilter' => 'ical',
  1181. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1182. 'start' => $startDate,
  1183. 'end' => $endDate,
  1184. 'bgColor' => str_replace('text', 'bg', $extraClass),
  1185. );
  1186. }
  1187. }
  1188. }
  1189. }
  1190. $calendarSources['ical'] = $icalEvents;
  1191. }
  1192. $calendarSources['events'] = $calendarItems;
  1193. return ($calendarSources) ? $calendarSources : false;
  1194. }
  1195. function getSonarrCalendar($array, $number)
  1196. {
  1197. $array = json_decode($array, true);
  1198. $gotCalendar = array();
  1199. $i = 0;
  1200. foreach ($array as $child) {
  1201. $i++;
  1202. $seriesName = $child['series']['title'];
  1203. $seriesID = $child['series']['tvdbId'];
  1204. $episodeID = $child['series']['tvdbId'];
  1205. $monitored = $child['monitored'];
  1206. if (!isset($episodeID)) {
  1207. $episodeID = "";
  1208. }
  1209. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1210. $episodeAirDate = $child['airDateUtc'];
  1211. $episodeAirDate = strtotime($episodeAirDate);
  1212. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1213. if (new DateTime() < new DateTime($episodeAirDate)) {
  1214. $unaired = true;
  1215. }
  1216. if ($child['episodeNumber'] == "1") {
  1217. $episodePremier = "true";
  1218. } else {
  1219. $episodePremier = "false";
  1220. $date = new DateTime($episodeAirDate);
  1221. $date->add(new DateInterval("PT1S"));
  1222. $date->format(DateTime::ATOM);
  1223. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1224. }
  1225. $downloaded = $child['hasFile'];
  1226. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1227. $downloaded = "text-primary animated flash";
  1228. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1229. $downloaded = "text-dark";
  1230. } elseif ($downloaded == "0" && isset($unaired)) {
  1231. $downloaded = "text-info";
  1232. } elseif ($downloaded == "1") {
  1233. $downloaded = "text-success";
  1234. } else {
  1235. $downloaded = "text-danger";
  1236. }
  1237. $fanart = "/plugins/images/cache/no-np.png";
  1238. foreach ($child['series']['images'] as $image) {
  1239. if ($image['coverType'] == "fanart") {
  1240. $fanart = $image['url'];
  1241. }
  1242. }
  1243. if ($fanart !== "/plugins/images/cache/no-np.png") {
  1244. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1245. $imageURL = $fanart;
  1246. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1247. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1248. if (!file_exists($cacheFile)) {
  1249. cacheImage($imageURL, $seriesID);
  1250. unset($imageURL);
  1251. unset($cacheFile);
  1252. }
  1253. }
  1254. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1255. $details = array(
  1256. "seasonCount" => $child['series']['seasonCount'],
  1257. "status" => $child['series']['status'],
  1258. "topTitle" => $seriesName,
  1259. "bottomTitle" => $bottomTitle,
  1260. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1261. "runtime" => $child['series']['runtime'],
  1262. "image" => $fanart,
  1263. "ratings" => $child['series']['ratings']['value'],
  1264. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1265. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1266. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1267. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1268. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  1269. "genres" => $child['series']['genres'],
  1270. );
  1271. array_push($gotCalendar, array(
  1272. "id" => "Sonarr-" . $number . "-" . $i,
  1273. "title" => $seriesName,
  1274. "start" => $child['airDateUtc'],
  1275. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1276. "imagetype" => "tv " . $downloaded,
  1277. "imagetypeFilter" => "tv",
  1278. "downloadFilter" => $downloaded,
  1279. "bgColor" => str_replace('text', 'bg', $downloaded),
  1280. "details" => $details
  1281. ));
  1282. }
  1283. if ($i != 0) {
  1284. return $gotCalendar;
  1285. }
  1286. return false;
  1287. }
  1288. function getLidarrCalendar($array, $number)
  1289. {
  1290. $array = json_decode($array, true);
  1291. $gotCalendar = array();
  1292. $i = 0;
  1293. foreach ($array as $child) {
  1294. $i++;
  1295. $albumName = $child['title'];
  1296. $artistName = $child['artist']['artistName'];
  1297. $albumID = '';
  1298. $releaseDate = $child['releaseDate'];
  1299. $releaseDate = strtotime($releaseDate);
  1300. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1301. if (new DateTime() < new DateTime($releaseDate)) {
  1302. $unaired = true;
  1303. }
  1304. $downloaded = (isset($child['statistics']['percentOfEpisodes']) && $child['statistics']['percentOfEpisodes'] !== '100.0') ? '0' : '1';
  1305. if ($downloaded == "0" && isset($unaired)) {
  1306. $downloaded = "text-info";
  1307. } elseif ($downloaded == "1") {
  1308. $downloaded = "text-success";
  1309. } else {
  1310. $downloaded = "text-danger";
  1311. }
  1312. $fanart = "/plugins/images/cache/no-np.png";
  1313. foreach ($child['artist']['images'] as $image) {
  1314. if ($image['coverType'] == "fanart") {
  1315. $fanart = str_replace('http://', 'https://', $image['url']);
  1316. }
  1317. }
  1318. $details = array(
  1319. "seasonCount" => '',
  1320. "status" => '',
  1321. "topTitle" => $albumName,
  1322. "bottomTitle" => $artistName,
  1323. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1324. "runtime" => '',
  1325. "image" => $fanart,
  1326. "ratings" => $child['artist']['ratings']['value'],
  1327. "videoQuality" => "unknown",
  1328. "audioChannels" => "unknown",
  1329. "audioCodec" => "unknown",
  1330. "videoCodec" => "unknown",
  1331. "size" => "unknown",
  1332. "genres" => $child['genres'],
  1333. );
  1334. array_push($gotCalendar, array(
  1335. "id" => "Lidarr-" . $number . "-" . $i,
  1336. "title" => $artistName,
  1337. "start" => $child['releaseDate'],
  1338. "className" => "inline-popups bg-calendar calendar-item musicID--",
  1339. "imagetype" => "music " . $downloaded,
  1340. "imagetypeFilter" => "music",
  1341. "downloadFilter" => $downloaded,
  1342. "bgColor" => str_replace('text', 'bg', $downloaded),
  1343. "details" => $details
  1344. ));
  1345. }
  1346. if ($i != 0) {
  1347. return $gotCalendar;
  1348. }
  1349. return false;
  1350. }
  1351. function getRadarrCalendar($array, $number, $url)
  1352. {
  1353. $array = json_decode($array, true);
  1354. $gotCalendar = array();
  1355. $i = 0;
  1356. foreach ($array as $child) {
  1357. if (isset($child['physicalRelease'])) {
  1358. $i++;
  1359. $movieName = $child['title'];
  1360. $movieID = $child['tmdbId'];
  1361. if (!isset($movieID)) {
  1362. $movieID = "";
  1363. }
  1364. $physicalRelease = $child['physicalRelease'];
  1365. $physicalRelease = strtotime($physicalRelease);
  1366. $physicalRelease = date("Y-m-d", $physicalRelease);
  1367. if (new DateTime() < new DateTime($physicalRelease)) {
  1368. $notReleased = "true";
  1369. } else {
  1370. $notReleased = "false";
  1371. }
  1372. $downloaded = $child['hasFile'];
  1373. if ($downloaded == "0" && $notReleased == "true") {
  1374. $downloaded = "text-info";
  1375. } elseif ($downloaded == "1") {
  1376. $downloaded = "text-success";
  1377. } else {
  1378. $downloaded = "text-danger";
  1379. }
  1380. $banner = "/plugins/images/cache/no-np.png";
  1381. foreach ($child['images'] as $image) {
  1382. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1383. $url = rtrim($url, '/'); //remove trailing slash
  1384. $imageUrl = $image['url'];
  1385. $urlParts = explode("/", $url);
  1386. $imageParts = explode("/", $image['url']);
  1387. if ($imageParts[1] == end($urlParts)) {
  1388. unset($imageParts[1]);
  1389. $imageUrl = implode("/", $imageParts);
  1390. }
  1391. $banner = $url . $imageUrl;
  1392. }
  1393. }
  1394. if ($banner !== "/plugins/images/cache/no-np.png") {
  1395. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1396. $imageURL = $banner;
  1397. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1398. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1399. if (!file_exists($cacheFile)) {
  1400. cacheImage($imageURL, $movieID);
  1401. unset($imageURL);
  1402. unset($cacheFile);
  1403. }
  1404. }
  1405. $alternativeTitles = "";
  1406. foreach ($child['alternativeTitles'] as $alternative) {
  1407. $alternativeTitles .= $alternative['title'] . ', ';
  1408. }
  1409. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1410. $details = array(
  1411. "topTitle" => $movieName,
  1412. "bottomTitle" => $alternativeTitles,
  1413. "status" => $child['status'],
  1414. "overview" => $child['overview'],
  1415. "runtime" => $child['runtime'],
  1416. "image" => $banner,
  1417. "ratings" => $child['ratings']['value'],
  1418. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1419. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1420. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1421. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1422. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1423. "genres" => $child['genres'],
  1424. "year" => isset($child['year']) ? $child['year'] : '',
  1425. "studio" => isset($child['studio']) ? $child['studio'] : '',
  1426. );
  1427. array_push($gotCalendar, array(
  1428. "id" => "Radarr-" . $number . "-" . $i,
  1429. "title" => $movieName,
  1430. "start" => $physicalRelease,
  1431. "className" => "inline-popups bg-calendar movieID--" . $movieID,
  1432. "imagetype" => "film " . $downloaded,
  1433. "imagetypeFilter" => "film",
  1434. "downloadFilter" => $downloaded,
  1435. "bgColor" => str_replace('text', 'bg', $downloaded),
  1436. "details" => $details
  1437. ));
  1438. }
  1439. }
  1440. if ($i != 0) {
  1441. return $gotCalendar;
  1442. }
  1443. return false;
  1444. }
  1445. function getCouchCalendar($array, $number)
  1446. {
  1447. $api = json_decode($array, true);
  1448. $gotCalendar = array();
  1449. $i = 0;
  1450. foreach ($api['movies'] as $child) {
  1451. if ($child['status'] == "active" || $child['status'] == "done") {
  1452. $i++;
  1453. $movieName = $child['info']['original_title'];
  1454. $movieID = $child['info']['tmdb_id'];
  1455. if (!isset($movieID)) {
  1456. $movieID = "";
  1457. }
  1458. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1459. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1460. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1461. $physicalRelease = strtotime($physicalRelease);
  1462. $physicalRelease = date("Y-m-d", $physicalRelease);
  1463. if (new DateTime() < new DateTime($physicalRelease)) {
  1464. $notReleased = "true";
  1465. } else {
  1466. $notReleased = "false";
  1467. }
  1468. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1469. if ($downloaded == "0" && $notReleased == "true") {
  1470. $downloaded = "text-info";
  1471. } elseif ($downloaded == "1") {
  1472. $downloaded = "text-success";
  1473. } else {
  1474. $downloaded = "text-danger";
  1475. }
  1476. if (!empty($child['info']['images']['backdrop_original'])) {
  1477. $banner = $child['info']['images']['backdrop_original'][0];
  1478. } elseif (!empty($child['info']['images']['backdrop'])) {
  1479. $banner = $child['info']['images']['backdrop_original'][0];
  1480. } else {
  1481. $banner = "/plugins/images/cache/no-np.png";
  1482. }
  1483. if ($banner !== "/plugins/images/cache/no-np.png") {
  1484. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1485. $imageURL = $banner;
  1486. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1487. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1488. if (!file_exists($cacheFile)) {
  1489. cacheImage($imageURL, $movieID);
  1490. unset($imageURL);
  1491. unset($cacheFile);
  1492. }
  1493. }
  1494. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1495. $details = array(
  1496. "topTitle" => $movieName,
  1497. "bottomTitle" => $child['info']['tagline'],
  1498. "status" => $child['status'],
  1499. "overview" => $child['info']['plot'],
  1500. "runtime" => $child['info']['runtime'],
  1501. "image" => $banner,
  1502. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1503. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1504. "audioChannels" => "",
  1505. "audioCodec" => "",
  1506. "videoCodec" => "",
  1507. "genres" => $child['info']['genres'],
  1508. "year" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1509. "studio" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1510. );
  1511. array_push($gotCalendar, array(
  1512. "id" => "CouchPotato-" . $number . "-" . $i,
  1513. "title" => $movieName,
  1514. "start" => $physicalRelease,
  1515. "className" => "inline-popups bg-calendar calendar-item movieID--" . $movieID,
  1516. "imagetype" => "film " . $downloaded,
  1517. "imagetypeFilter" => "film",
  1518. "downloadFilter" => $downloaded,
  1519. "bgColor" => str_replace('text', 'bg', $downloaded),
  1520. "details" => $details
  1521. ));
  1522. }
  1523. }
  1524. if ($i != 0) {
  1525. return $gotCalendar;
  1526. }
  1527. return false;
  1528. }
  1529. function getSickrageCalendarWanted($array, $number)
  1530. {
  1531. $array = json_decode($array, true);
  1532. $gotCalendar = array();
  1533. $i = 0;
  1534. foreach ($array['data']['missed'] as $child) {
  1535. $i++;
  1536. $seriesName = $child['show_name'];
  1537. $seriesID = $child['tvdbid'];
  1538. $episodeID = $child['tvdbid'];
  1539. $episodeAirDate = $child['airdate'];
  1540. $episodeAirDateTime = explode(" ", $child['airs']);
  1541. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1542. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1543. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1544. if (new DateTime() < new DateTime($episodeAirDate)) {
  1545. $unaired = true;
  1546. }
  1547. $downloaded = "0";
  1548. if ($downloaded == "0" && isset($unaired)) {
  1549. $downloaded = "text-info";
  1550. } elseif ($downloaded == "1") {
  1551. $downloaded = "text-success";
  1552. } else {
  1553. $downloaded = "text-danger";
  1554. }
  1555. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1556. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1557. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1558. $fanart = "/plugins/images/cache/no-np.png";
  1559. if (file_exists($cacheFile)) {
  1560. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1561. unset($cacheFile);
  1562. }
  1563. $details = array(
  1564. "seasonCount" => "",
  1565. "status" => $child['show_status'],
  1566. "topTitle" => $seriesName,
  1567. "bottomTitle" => $bottomTitle,
  1568. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1569. "runtime" => "",
  1570. "image" => $fanart,
  1571. "ratings" => "",
  1572. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1573. "audioChannels" => "",
  1574. "audioCodec" => "",
  1575. "videoCodec" => "",
  1576. "size" => "",
  1577. "genres" => "",
  1578. );
  1579. array_push($gotCalendar, array(
  1580. "id" => "Sick-" . $number . "-Miss-" . $i,
  1581. "title" => $seriesName,
  1582. "start" => $episodeAirDate,
  1583. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1584. "imagetype" => "tv " . $downloaded,
  1585. "imagetypeFilter" => "tv",
  1586. "downloadFilter" => $downloaded,
  1587. "bgColor" => str_replace('text', 'bg', $downloaded),
  1588. "details" => $details,
  1589. ));
  1590. }
  1591. foreach ($array['data']['today'] as $child) {
  1592. $i++;
  1593. $seriesName = $child['show_name'];
  1594. $seriesID = $child['tvdbid'];
  1595. $episodeID = $child['tvdbid'];
  1596. $episodeAirDate = $child['airdate'];
  1597. $episodeAirDateTime = explode(" ", $child['airs']);
  1598. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1599. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1600. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1601. if (new DateTime() < new DateTime($episodeAirDate)) {
  1602. $unaired = true;
  1603. }
  1604. $downloaded = "0";
  1605. if ($downloaded == "0" && isset($unaired)) {
  1606. $downloaded = "text-info";
  1607. } elseif ($downloaded == "1") {
  1608. $downloaded = "text-success";
  1609. } else {
  1610. $downloaded = "text-danger";
  1611. }
  1612. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1613. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1614. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1615. $fanart = "/plugins/images/cache/no-np.png";
  1616. if (file_exists($cacheFile)) {
  1617. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1618. unset($cacheFile);
  1619. }
  1620. $details = array(
  1621. "seasonCount" => "",
  1622. "status" => $child['show_status'],
  1623. "topTitle" => $seriesName,
  1624. "bottomTitle" => $bottomTitle,
  1625. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1626. "runtime" => "",
  1627. "image" => $fanart,
  1628. "ratings" => "",
  1629. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1630. "audioChannels" => "",
  1631. "audioCodec" => "",
  1632. "videoCodec" => "",
  1633. "size" => "",
  1634. "genres" => "",
  1635. );
  1636. array_push($gotCalendar, array(
  1637. "id" => "Sick-" . $number . "-Today-" . $i,
  1638. "title" => $seriesName,
  1639. "start" => $episodeAirDate,
  1640. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1641. "imagetype" => "tv " . $downloaded,
  1642. "imagetypeFilter" => "tv",
  1643. "downloadFilter" => $downloaded,
  1644. "bgColor" => str_replace('text', 'bg', $downloaded),
  1645. "details" => $details,
  1646. ));
  1647. }
  1648. foreach ($array['data']['soon'] as $child) {
  1649. $i++;
  1650. $seriesName = $child['show_name'];
  1651. $seriesID = $child['tvdbid'];
  1652. $episodeID = $child['tvdbid'];
  1653. $episodeAirDate = $child['airdate'];
  1654. $episodeAirDateTime = explode(" ", $child['airs']);
  1655. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1656. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1657. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1658. if (new DateTime() < new DateTime($episodeAirDate)) {
  1659. $unaired = true;
  1660. }
  1661. $downloaded = "0";
  1662. if ($downloaded == "0" && isset($unaired)) {
  1663. $downloaded = "text-info";
  1664. } elseif ($downloaded == "1") {
  1665. $downloaded = "text-success";
  1666. } else {
  1667. $downloaded = "text-danger";
  1668. }
  1669. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1670. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1671. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1672. $fanart = "/plugins/images/cache/no-np.png";
  1673. if (file_exists($cacheFile)) {
  1674. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1675. unset($cacheFile);
  1676. }
  1677. $details = array(
  1678. "seasonCount" => "",
  1679. "status" => $child['show_status'],
  1680. "topTitle" => $seriesName,
  1681. "bottomTitle" => $bottomTitle,
  1682. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1683. "runtime" => "",
  1684. "image" => $fanart,
  1685. "ratings" => "",
  1686. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1687. "audioChannels" => "",
  1688. "audioCodec" => "",
  1689. "videoCodec" => "",
  1690. "size" => "",
  1691. "genres" => "",
  1692. );
  1693. array_push($gotCalendar, array(
  1694. "id" => "Sick-" . $number . "-Soon-" . $i,
  1695. "title" => $seriesName,
  1696. "start" => $episodeAirDate,
  1697. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1698. "imagetype" => "tv " . $downloaded,
  1699. "imagetypeFilter" => "tv",
  1700. "downloadFilter" => $downloaded,
  1701. "bgColor" => str_replace('text', 'bg', $downloaded),
  1702. "details" => $details,
  1703. ));
  1704. }
  1705. foreach ($array['data']['later'] as $child) {
  1706. $i++;
  1707. $seriesName = $child['show_name'];
  1708. $seriesID = $child['tvdbid'];
  1709. $episodeID = $child['tvdbid'];
  1710. $episodeAirDate = $child['airdate'];
  1711. $episodeAirDateTime = explode(" ", $child['airs']);
  1712. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1713. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1714. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1715. if (new DateTime() < new DateTime($episodeAirDate)) {
  1716. $unaired = true;
  1717. }
  1718. $downloaded = "0";
  1719. if ($downloaded == "0" && isset($unaired)) {
  1720. $downloaded = "text-info";
  1721. } elseif ($downloaded == "1") {
  1722. $downloaded = "text-success";
  1723. } else {
  1724. $downloaded = "text-danger";
  1725. }
  1726. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1727. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1728. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1729. $fanart = "/plugins/images/cache/no-np.png";
  1730. if (file_exists($cacheFile)) {
  1731. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1732. unset($cacheFile);
  1733. }
  1734. $details = array(
  1735. "seasonCount" => "",
  1736. "status" => $child['show_status'],
  1737. "topTitle" => $seriesName,
  1738. "bottomTitle" => $bottomTitle,
  1739. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1740. "runtime" => "",
  1741. "image" => $fanart,
  1742. "ratings" => "",
  1743. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1744. "audioChannels" => "",
  1745. "audioCodec" => "",
  1746. "videoCodec" => "",
  1747. "size" => "",
  1748. "genres" => "",
  1749. );
  1750. array_push($gotCalendar, array(
  1751. "id" => "Sick-" . $number . "-Later-" . $i,
  1752. "title" => $seriesName,
  1753. "start" => $episodeAirDate,
  1754. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1755. "imagetype" => "tv " . $downloaded,
  1756. "imagetypeFilter" => "tv",
  1757. "downloadFilter" => $downloaded,
  1758. "bgColor" => str_replace('text', 'bg', $downloaded),
  1759. "details" => $details,
  1760. ));
  1761. }
  1762. if ($i != 0) {
  1763. return $gotCalendar;
  1764. }
  1765. return false;
  1766. }
  1767. function getSickrageCalendarHistory($array, $number)
  1768. {
  1769. $array = json_decode($array, true);
  1770. $gotCalendar = array();
  1771. $i = 0;
  1772. foreach ($array['data'] as $child) {
  1773. $i++;
  1774. $seriesName = $child['show_name'];
  1775. $seriesID = $child['tvdbid'];
  1776. $episodeID = $child['tvdbid'];
  1777. $episodeAirDate = $child['date'];
  1778. $downloaded = "text-success";
  1779. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  1780. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1781. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1782. $fanart = "/plugins/images/cache/no-np.png";
  1783. if (file_exists($cacheFile)) {
  1784. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1785. unset($cacheFile);
  1786. }
  1787. $details = array(
  1788. "seasonCount" => "",
  1789. "status" => $child['status'],
  1790. "topTitle" => $seriesName,
  1791. "bottomTitle" => $bottomTitle,
  1792. "overview" => '',
  1793. "runtime" => isset($child['series']['runtime']) ? $child['series']['runtime'] : 30,
  1794. "image" => $fanart,
  1795. "ratings" => isset($child['series']['ratings']['value']) ? $child['series']['ratings']['value'] : "unknown",
  1796. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  1797. "audioChannels" => "",
  1798. "audioCodec" => "",
  1799. "videoCodec" => "",
  1800. "size" => "",
  1801. "genres" => "",
  1802. );
  1803. array_push($gotCalendar, array(
  1804. "id" => "Sick-" . $number . "-History-" . $i,
  1805. "title" => $seriesName,
  1806. "start" => $episodeAirDate,
  1807. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1808. "imagetype" => "tv " . $downloaded,
  1809. "imagetypeFilter" => "tv",
  1810. "downloadFilter" => $downloaded,
  1811. "bgColor" => str_replace('text', 'bg', $downloaded),
  1812. "details" => $details,
  1813. ));
  1814. }
  1815. if ($i != 0) {
  1816. return $gotCalendar;
  1817. }
  1818. return false;
  1819. }
  1820. function ombiAPI($array)
  1821. {
  1822. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  1823. }
  1824. function ombiImport($type = null)
  1825. {
  1826. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  1827. try {
  1828. $url = qualifyURL($GLOBALS['ombiURL']);
  1829. $headers = array(
  1830. "Accept" => "application/json",
  1831. "Content-Type" => "application/json",
  1832. "Apikey" => $GLOBALS['ombiToken']
  1833. );
  1834. $options = (localURL($url)) ? array('verify' => false) : array();
  1835. switch ($type) {
  1836. case 'emby':
  1837. case 'emby_local':
  1838. case 'emby_connect':
  1839. case 'emby_all':
  1840. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  1841. break;
  1842. case 'plex':
  1843. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  1844. break;
  1845. default:
  1846. return false;
  1847. break;
  1848. }
  1849. if ($response->success) {
  1850. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  1851. return true;
  1852. } else {
  1853. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  1854. return false;
  1855. }
  1856. } catch (Requests_Exception $e) {
  1857. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1858. return false;
  1859. };
  1860. }
  1861. return false;
  1862. }
  1863. function ombiAction($id, $action, $type, $fullArray = null)
  1864. {
  1865. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1866. $url = qualifyURL($GLOBALS['ombiURL']);
  1867. $headers = array(
  1868. "Accept" => "application/json",
  1869. "Content-Type" => "application/json",
  1870. "Apikey" => $GLOBALS['ombiToken']
  1871. );
  1872. $data = array(
  1873. 'id' => $id,
  1874. );
  1875. switch ($type) {
  1876. case 'season':
  1877. case 'tv':
  1878. $type = 'tv';
  1879. $add = array(
  1880. 'tvDbId' => $id,
  1881. 'requestAll' => ombiTVDefault('all'),
  1882. 'latestSeason' => ombiTVDefault('last'),
  1883. 'firstSeason' => ombiTVDefault('first')
  1884. );
  1885. break;
  1886. default:
  1887. $type = 'movie';
  1888. $add = array("theMovieDbId" => (int)$id);
  1889. break;
  1890. }
  1891. $success['head'] = $headers;
  1892. $success['act'] = $action;
  1893. $success['data'] = $data;
  1894. $success['add'] = $add;
  1895. $success['type'] = $type;
  1896. try {
  1897. $options = (localURL($url)) ? array('verify' => false) : array();
  1898. switch ($action) {
  1899. case 'add':
  1900. if (isset($_COOKIE['Auth'])) {
  1901. $headers = array(
  1902. "Accept" => "application/json",
  1903. "Content-Type" => "application/json",
  1904. "Authorization" => "Bearer " . $_COOKIE['Auth']
  1905. );
  1906. $success['head'] = $headers;
  1907. } else {
  1908. return false;
  1909. }
  1910. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  1911. break;
  1912. default:
  1913. if (qualifyRequest(1)) {
  1914. switch ($action) {
  1915. case 'approve':
  1916. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  1917. break;
  1918. case 'available':
  1919. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  1920. break;
  1921. case 'unavailable':
  1922. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  1923. break;
  1924. case 'deny':
  1925. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  1926. break;
  1927. case 'delete':
  1928. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  1929. break;
  1930. default:
  1931. return false;
  1932. }
  1933. }
  1934. break;
  1935. }
  1936. $success['api'] = $response;
  1937. $success['bd'] = $response->body;
  1938. $success['hd'] = $response->headers;
  1939. if ($response->success) {
  1940. $success['ok'] = true;
  1941. }
  1942. } catch (Requests_Exception $e) {
  1943. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1944. };
  1945. }
  1946. return isset($success['ok']) ? $success : false;
  1947. }
  1948. function getOmbiRequests($type = "both", $limit = 50)
  1949. {
  1950. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1951. $url = qualifyURL($GLOBALS['ombiURL']);
  1952. $headers = array(
  1953. "Accept" => "application/json",
  1954. "Apikey" => $GLOBALS['ombiToken'],
  1955. );
  1956. $requests = array();
  1957. try {
  1958. $options = (localURL($url)) ? array('verify' => false) : array();
  1959. switch ($type) {
  1960. case 'movie':
  1961. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  1962. break;
  1963. case 'tv':
  1964. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  1965. break;
  1966. default:
  1967. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  1968. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  1969. break;
  1970. }
  1971. if ($movie->success || $tv->success) {
  1972. if (isset($movie)) {
  1973. $movie = json_decode($movie->body, true);
  1974. //$movie = array_reverse($movie);
  1975. foreach ($movie as $key => $value) {
  1976. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  1977. if ($proceed) {
  1978. $requests[] = array(
  1979. 'test' => $value,
  1980. 'id' => $value['theMovieDbId'],
  1981. 'title' => $value['title'],
  1982. 'overview' => $value['overview'],
  1983. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
  1984. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  1985. 'approved' => $value['approved'],
  1986. 'available' => $value['available'],
  1987. 'denied' => $value['denied'],
  1988. 'deniedReason' => $value['deniedReason'],
  1989. 'user' => $value['requestedUser']['userName'],
  1990. 'userAlias' => $value['requestedUser']['userAlias'],
  1991. 'request_id' => $value['id'],
  1992. 'request_date' => $value['requestedDate'],
  1993. 'release_date' => $value['releaseDate'],
  1994. 'type' => 'movie',
  1995. 'icon' => 'mdi mdi-filmstrip',
  1996. 'color' => 'palette-Deep-Purple-900 bg white',
  1997. );
  1998. }
  1999. }
  2000. }
  2001. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2002. $tv = json_decode($tv->body, true);
  2003. foreach ($tv as $key => $value) {
  2004. if (count($value['childRequests']) > 0) {
  2005. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2006. if ($proceed) {
  2007. $requests[] = array(
  2008. 'test' => $value,
  2009. 'id' => $value['tvDbId'],
  2010. 'title' => $value['title'],
  2011. 'overview' => $value['overview'],
  2012. 'poster' => $value['posterPath'],
  2013. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2014. 'approved' => $value['childRequests'][0]['approved'],
  2015. 'available' => $value['childRequests'][0]['available'],
  2016. 'denied' => $value['childRequests'][0]['denied'],
  2017. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2018. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2019. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2020. 'request_id' => $value['id'],
  2021. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2022. 'release_date' => $value['releaseDate'],
  2023. 'type' => 'tv',
  2024. 'icon' => 'mdi mdi-television',
  2025. 'color' => 'grayish-blue-bg',
  2026. );
  2027. }
  2028. }
  2029. }
  2030. }
  2031. //sort here
  2032. usort($requests, function ($item1, $item2) {
  2033. if ($item1['request_date'] == $item2['request_date']) {
  2034. return 0;
  2035. }
  2036. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2037. });
  2038. }
  2039. } catch (Requests_Exception $e) {
  2040. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2041. };
  2042. }
  2043. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2044. return $api;
  2045. }
  2046. function testAPIConnection($array)
  2047. {
  2048. switch ($array['data']['action']) {
  2049. case 'ombi':
  2050. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2051. $url = qualifyURL($GLOBALS['ombiURL']);
  2052. $url = $url . "/api/v1/Status/info";
  2053. $headers = array(
  2054. "Accept" => "application/json",
  2055. "Content-Type" => "application/json",
  2056. "Apikey" => $GLOBALS['ombiToken']
  2057. );
  2058. try {
  2059. $options = (localURL($url)) ? array('verify' => false) : array();
  2060. $response = Requests::get($url, $headers, $options);
  2061. if ($response->success) {
  2062. return true;
  2063. } else {
  2064. return $response->body;
  2065. }
  2066. } catch (Requests_Exception $e) {
  2067. return $e->getMessage();
  2068. };
  2069. } else {
  2070. return 'URL and/or Token not setup';
  2071. }
  2072. break;
  2073. case 'plex':
  2074. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2075. $url = qualifyURL($GLOBALS['plexURL']);
  2076. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2077. try {
  2078. $options = (localURL($url)) ? array('verify' => false) : array();
  2079. $response = Requests::get($url, array(), $options);
  2080. libxml_use_internal_errors(true);
  2081. if ($response->success) {
  2082. return true;
  2083. }
  2084. } catch (Requests_Exception $e) {
  2085. return $e->getMessage();
  2086. };
  2087. } else {
  2088. return 'URL and/or Token not setup';
  2089. }
  2090. break;
  2091. case 'emby':
  2092. break;
  2093. case 'sonarr':
  2094. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2095. $sonarrs = array();
  2096. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2097. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2098. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2099. foreach ($sonarrURLList as $key => $value) {
  2100. $sonarrs[$key] = array(
  2101. 'url' => $value,
  2102. 'token' => $sonarrTokenList[$key]
  2103. );
  2104. }
  2105. foreach ($sonarrs as $key => $value) {
  2106. try {
  2107. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2108. $result = json_decode($sonarr->getSystemStatus(), true);
  2109. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2110. } catch (Exception $e) {
  2111. return strip($e->getMessage());
  2112. }
  2113. }
  2114. }
  2115. } else {
  2116. return 'URL/s and/or Token/s not setup';
  2117. }
  2118. break;
  2119. case 'lidarr':
  2120. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2121. $sonarrs = array();
  2122. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2123. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2124. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2125. foreach ($sonarrURLList as $key => $value) {
  2126. $sonarrs[$key] = array(
  2127. 'url' => $value,
  2128. 'token' => $sonarrTokenList[$key]
  2129. );
  2130. }
  2131. foreach ($sonarrs as $key => $value) {
  2132. try {
  2133. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2134. $result = json_decode($sonarr->getSystemStatus(), true);
  2135. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2136. } catch (Exception $e) {
  2137. return $e->getMessage();
  2138. }
  2139. }
  2140. }
  2141. } else {
  2142. return 'URL/s and/or Token/s not setup';
  2143. }
  2144. break;
  2145. case 'radarr':
  2146. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2147. $sonarrs = array();
  2148. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2149. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2150. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2151. foreach ($sonarrURLList as $key => $value) {
  2152. $sonarrs[$key] = array(
  2153. 'url' => $value,
  2154. 'token' => $sonarrTokenList[$key]
  2155. );
  2156. }
  2157. foreach ($sonarrs as $key => $value) {
  2158. try {
  2159. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2160. $result = json_decode($sonarr->getSystemStatus(), true);
  2161. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2162. } catch (Exception $e) {
  2163. return $e->getMessage();
  2164. }
  2165. }
  2166. }
  2167. } else {
  2168. return 'URL/s and/or Token/s not setup';
  2169. }
  2170. break;
  2171. case 'sabnzbd':
  2172. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2173. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2174. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2175. try {
  2176. $options = (localURL($url)) ? array('verify' => false) : array();
  2177. $response = Requests::get($url, array(), $options);
  2178. if ($response->success) {
  2179. return true;
  2180. }
  2181. } catch (Requests_Exception $e) {
  2182. return $e->getMessage();
  2183. };
  2184. } else {
  2185. return 'URL and/or Token not setup';
  2186. }
  2187. break;
  2188. case 'nzbget':
  2189. if (!empty($GLOBALS['nzbgetURL'])) {
  2190. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2191. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  2192. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  2193. } else {
  2194. $url = $url . '/jsonrpc/listgroups';
  2195. }
  2196. try {
  2197. $options = (localURL($url)) ? array('verify' => false) : array();
  2198. $response = Requests::get($url, array(), $options);
  2199. if ($response->success) {
  2200. return true;
  2201. }
  2202. } catch (Requests_Exception $e) {
  2203. return $e->getMessage();
  2204. };
  2205. } else {
  2206. return 'URL and/or Username/Password not setup';
  2207. }
  2208. break;
  2209. case 'deluge':
  2210. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2211. try {
  2212. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2213. $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');
  2214. return true;
  2215. } catch (Exception $e) {
  2216. return $e->getMessage();
  2217. }
  2218. } else {
  2219. return 'URL and/or Password not setup';
  2220. }
  2221. break;
  2222. case 'rtorrent':
  2223. if (!empty($GLOBALS['rTorrentURL'])) {
  2224. try {
  2225. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  2226. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2227. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2228. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  2229. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2230. $options = (localURL($url)) ? array('verify' => false) : array();
  2231. $data = xmlrpc_encode_request("system.listMethods", null);
  2232. $response = Requests::post($url, array(), $data, $options);
  2233. if ($response->success) {
  2234. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2235. if (count($methods) !== 0) {
  2236. return true;
  2237. }
  2238. }
  2239. return false;
  2240. } catch
  2241. (Requests_Exception $e) {
  2242. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2243. return $e->getMessage();
  2244. };
  2245. }
  2246. break;
  2247. case 'ldap':
  2248. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2249. $ad = new \Adldap\Adldap();
  2250. // Create a configuration array.
  2251. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2252. $i = 0;
  2253. foreach ($ldapServers as $key => $value) {
  2254. // Calculate parts
  2255. $digest = parse_url(trim($value));
  2256. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2257. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2258. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2259. // Reassign
  2260. $ldapHosts[] = $host;
  2261. if ($i == 0) {
  2262. $ldapPort = $port;
  2263. }
  2264. $i++;
  2265. }
  2266. $config = [
  2267. // Mandatory Configuration Options
  2268. 'hosts' => $ldapHosts,
  2269. 'base_dn' => $GLOBALS['authBaseDN'],
  2270. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  2271. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  2272. // Optional Configuration Options
  2273. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  2274. 'account_prefix' => '',
  2275. 'account_suffix' => '',
  2276. 'port' => $ldapPort,
  2277. 'follow_referrals' => false,
  2278. 'use_ssl' => false,
  2279. 'use_tls' => false,
  2280. 'version' => 3,
  2281. 'timeout' => 5,
  2282. // Custom LDAP Options
  2283. 'custom_options' => [
  2284. // See: http://php.net/ldap_set_option
  2285. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  2286. ]
  2287. ];
  2288. // Add a connection provider to Adldap.
  2289. $ad->addProvider($config);
  2290. try {
  2291. // If a successful connection is made to your server, the provider will be returned.
  2292. $provider = $ad->connect();
  2293. } catch (\Adldap\Auth\BindException $e) {
  2294. writeLog('error', 'LDAP Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2295. return $e->getMessage();
  2296. // There was an issue binding / connecting to the server.
  2297. }
  2298. return ($provider) ? true : false;
  2299. }
  2300. return false;
  2301. break;
  2302. default :
  2303. return false;
  2304. }
  2305. return false;
  2306. }