homepage-connect-functions.php 100 KB

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