homepage-connect-functions.php 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624
  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']) && !empty($GLOBALS['healthChecksURL']) && 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 = qualifyURL($GLOBALS['healthChecksURL']) . '/' . $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. if (is_array($result) || is_object($result)) {
  1078. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : getSonarrCalendar($sonarr, $key);
  1079. } else {
  1080. $sonarrCalendar = '';
  1081. }
  1082. } catch (Exception $e) {
  1083. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1084. }
  1085. if (!empty($sonarrCalendar)) {
  1086. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  1087. }
  1088. }
  1089. }
  1090. }
  1091. // LIDARR CONNECT
  1092. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  1093. $lidarrs = array();
  1094. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  1095. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  1096. if (count($lidarrURLList) == count($lidarrTokenList)) {
  1097. foreach ($lidarrURLList as $key => $value) {
  1098. $lidarrs[$key] = array(
  1099. 'url' => $value,
  1100. 'token' => $lidarrTokenList[$key]
  1101. );
  1102. }
  1103. foreach ($lidarrs as $key => $value) {
  1104. try {
  1105. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1106. $lidarr = $lidarr->getCalendar($startDate, $endDate);
  1107. $result = json_decode($lidarr, true);
  1108. if (is_array($result) || is_object($result)) {
  1109. $lidarrCalendar = (array_key_exists('error', $result)) ? '' : getLidarrCalendar($lidarr, $key);
  1110. } else {
  1111. $lidarrCalendar = '';
  1112. }
  1113. } catch (Exception $e) {
  1114. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1115. }
  1116. if (!empty($lidarrCalendar)) {
  1117. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. // RADARR CONNECT
  1123. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1124. $radarrs = array();
  1125. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1126. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1127. if (count($radarrURLList) == count($radarrTokenList)) {
  1128. foreach ($radarrURLList as $key => $value) {
  1129. $radarrs[$key] = array(
  1130. 'url' => $value,
  1131. 'token' => $radarrTokenList[$key]
  1132. );
  1133. }
  1134. foreach ($radarrs as $key => $value) {
  1135. try {
  1136. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1137. $radarr = $radarr->getCalendar($startDate, $endDate);
  1138. $result = json_decode($radarr, true);
  1139. if (is_array($result) || is_object($result)) {
  1140. $radarrCalendar = (array_key_exists('error', $result)) ? '' : getRadarrCalendar($radarr, $key, $value['url']);
  1141. } else {
  1142. $radarrCalendar = '';
  1143. }
  1144. } catch (Exception $e) {
  1145. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1146. }
  1147. if (!empty($radarrCalendar)) {
  1148. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. // SICKRAGE/BEARD/MEDUSA CONNECT
  1154. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1155. $sicks = array();
  1156. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1157. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1158. if (count($sickURLList) == count($sickTokenList)) {
  1159. foreach ($sickURLList as $key => $value) {
  1160. $sicks[$key] = array(
  1161. 'url' => $value,
  1162. 'token' => $sickTokenList[$key]
  1163. );
  1164. }
  1165. foreach ($sicks as $key => $value) {
  1166. try {
  1167. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1168. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1169. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1170. if (!empty($sickrageFuture)) {
  1171. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1172. }
  1173. if (!empty($sickrageHistory)) {
  1174. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1175. }
  1176. } catch (Exception $e) {
  1177. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // COUCHPOTATO CONNECT
  1183. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1184. $couchs = array();
  1185. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1186. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1187. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1188. foreach ($couchpotatoURLList as $key => $value) {
  1189. $couchs[$key] = array(
  1190. 'url' => $value,
  1191. 'token' => $couchpotatoTokenList[$key]
  1192. );
  1193. }
  1194. foreach ($couchs as $key => $value) {
  1195. try {
  1196. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1197. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1198. if (!empty($couchCalendar)) {
  1199. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1200. }
  1201. } catch (Exception $e) {
  1202. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1203. }
  1204. }
  1205. }
  1206. }
  1207. // iCal URL
  1208. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1209. $calendars = array();
  1210. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1211. $icalEvents = array();
  1212. foreach ($calendarURLList as $key => $value) {
  1213. $icsEvents = getIcsEventsAsArray($value);
  1214. if (isset($icsEvents) && !empty($icsEvents)) {
  1215. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1216. $originalTimeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : false;
  1217. unset($icsEvents [1]);
  1218. foreach ($icsEvents as $icsEvent) {
  1219. $startKeys = array_filter_key($icsEvent, function ($key) {
  1220. return strpos($key, 'DTSTART') === 0;
  1221. });
  1222. $endKeys = array_filter_key($icsEvent, function ($key) {
  1223. return strpos($key, 'DTEND') === 0;
  1224. });
  1225. if (!empty($startKeys) && !empty($endKeys) && isset($icsEvent['SUMMARY'])) {
  1226. /* Getting start date and time */
  1227. $repeat = isset($icsEvent ['RRULE']) ? $icsEvent ['RRULE'] : false;
  1228. if (!$originalTimeZone) {
  1229. $tzKey = array_keys($startKeys);
  1230. if (strpos($tzKey[0], 'TZID=') !== false) {
  1231. $originalTimeZone = explode('TZID=', (string)$tzKey[0]);
  1232. $originalTimeZone = (count($originalTimeZone) >= 2) ? $originalTimeZone[1] : false;
  1233. }
  1234. }
  1235. $start = reset($startKeys);
  1236. $end = reset($endKeys);
  1237. $totalDays = $GLOBALS['calendarStart'] + $GLOBALS['calendarEnd'];
  1238. if ($repeat) {
  1239. $repeatOverride = getCalenderRepeatCount(trim($icsEvent["RRULE"]));
  1240. switch (trim(strtolower(getCalenderRepeat($repeat)))) {
  1241. case 'daily':
  1242. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1243. $term = 'days';
  1244. break;
  1245. case 'weekly':
  1246. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 7);
  1247. $term = 'weeks';
  1248. break;
  1249. case 'monthly':
  1250. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 30);
  1251. $term = 'months';
  1252. break;
  1253. case 'yearly':
  1254. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 365);
  1255. $term = 'years';
  1256. break;
  1257. default:
  1258. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1259. $term = 'days';
  1260. break;
  1261. }
  1262. } else {
  1263. $repeat = 1;
  1264. $term = 'day';
  1265. }
  1266. $calendarTimes = 0;
  1267. while ($calendarTimes < $repeat) {
  1268. $currentDate = new DateTime ($GLOBALS['currentTime']);
  1269. $oldestDay = new DateTime ($GLOBALS['currentTime']);
  1270. $oldestDay->modify('-' . $GLOBALS['calendarStart'] . ' days');
  1271. $newestDay = new DateTime ($GLOBALS['currentTime']);
  1272. $newestDay->modify('+' . $GLOBALS['calendarEnd'] . ' days');
  1273. /* Converting to datetime and apply the timezone to get proper date time */
  1274. $startDt = new DateTime ($start);
  1275. /* Getting end date with time */
  1276. $endDt = new DateTime ($end);
  1277. if ($calendarTimes !== 0) {
  1278. $dateDiff = date_diff($startDt, $currentDate);
  1279. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1280. $startDt->modify('+' . $calendarTimes . ' ' . $term);
  1281. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1282. $endDt->modify('+' . $calendarTimes . ' ' . $term);
  1283. } elseif ($calendarTimes == 0 && $repeat !== 1) {
  1284. $dateDiff = date_diff($startDt, $currentDate);
  1285. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1286. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1287. }
  1288. $calendarStartDiff = date_diff($startDt, $newestDay);
  1289. $calendarEndDiff = date_diff($startDt, $oldestDay);
  1290. if ($originalTimeZone && $originalTimeZone !== 'UTC' && (strpos($start, 'Z') == false)) {
  1291. $dateTimeOriginalTZ = new DateTimeZone($originalTimeZone);
  1292. $dateTimeOriginal = new DateTime('now', $dateTimeOriginalTZ);
  1293. $dateTimeUTCTZ = new DateTimeZone(date_default_timezone_get());
  1294. $dateTimeUTC = new DateTime('now', $dateTimeUTCTZ);
  1295. $dateTimeOriginalOffset = $dateTimeOriginal->getOffset() / 3600;
  1296. $dateTimeUTCOffset = $dateTimeUTC->getOffset() / 3600;
  1297. $diff = $dateTimeUTCOffset - $dateTimeOriginalOffset;
  1298. $startDt->modify('+ ' . $diff . ' hour');
  1299. $endDt->modify('+ ' . $diff . ' hour');
  1300. }
  1301. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1302. $endDt->setTimeZone(new DateTimezone ($timeZone));
  1303. $startDate = $startDt->format(DateTime::ATOM);
  1304. $endDate = $endDt->format(DateTime::ATOM);
  1305. if (new DateTime() < $endDt) {
  1306. $extraClass = 'text-info';
  1307. } else {
  1308. $extraClass = 'text-success';
  1309. }
  1310. /* Getting the name of event */
  1311. $eventName = $icsEvent['SUMMARY'];
  1312. if (!calendarDaysCheck($calendarStartDiff->format('%R') . $calendarStartDiff->days, $calendarEndDiff->format('%R') . $calendarEndDiff->days)) {
  1313. break;
  1314. }
  1315. if (isset($icsEvent["RRULE"]) && getCalenderRepeatUntil(trim($icsEvent["RRULE"]))) {
  1316. $untilDate = new DateTime (getCalenderRepeatUntil(trim($icsEvent["RRULE"])));
  1317. $untilDiff = date_diff($currentDate, $untilDate);
  1318. if ($untilDiff->days > 0) {
  1319. break;
  1320. }
  1321. }
  1322. $icalEvents[] = array(
  1323. 'title' => $eventName,
  1324. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1325. 'imagetypeFilter' => 'ical',
  1326. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1327. 'start' => $startDate,
  1328. 'end' => $endDate,
  1329. 'bgColor' => str_replace('text', 'bg', $extraClass),
  1330. );
  1331. $calendarTimes = $calendarTimes + 1;
  1332. }
  1333. }
  1334. }
  1335. }
  1336. }
  1337. $calendarSources['ical'] = $icalEvents;
  1338. }
  1339. $calendarSources['events'] = $calendarItems;
  1340. return ($calendarSources) ? $calendarSources : false;
  1341. }
  1342. function calendarDaysCheck($entryStart, $entryEnd)
  1343. {
  1344. $success = false;
  1345. $entryStart = intval($entryStart);
  1346. $entryEnd = intval($entryEnd);
  1347. if ($entryStart >= 0 && $entryEnd <= 0) {
  1348. $success = true;
  1349. }
  1350. return $success;
  1351. }
  1352. function getCalenderRepeat($value)
  1353. {
  1354. //FREQ=DAILY
  1355. //RRULE:FREQ=WEEKLY;BYDAY=TH
  1356. $first = explode('=', $value);
  1357. if (count($first) > 1) {
  1358. $second = explode(';', $first[1]);
  1359. } else {
  1360. return $value;
  1361. }
  1362. if ($second) {
  1363. return $second[0];
  1364. } else {
  1365. return $first[1];
  1366. }
  1367. }
  1368. function getCalenderRepeatUntil($value)
  1369. {
  1370. $first = explode('UNTIL=', $value);
  1371. if (count($first) > 1) {
  1372. return $first[1];
  1373. } else {
  1374. return false;
  1375. }
  1376. }
  1377. function getCalenderRepeatCount($value)
  1378. {
  1379. $first = explode('COUNT=', $value);
  1380. if (count($first) > 1) {
  1381. return $first[1];
  1382. } else {
  1383. return false;
  1384. }
  1385. }
  1386. function getSonarrCalendar($array, $number)
  1387. {
  1388. $array = json_decode($array, true);
  1389. $gotCalendar = array();
  1390. $i = 0;
  1391. foreach ($array as $child) {
  1392. $i++;
  1393. $seriesName = $child['series']['title'];
  1394. $seriesID = $child['series']['tvdbId'];
  1395. $episodeID = $child['series']['tvdbId'];
  1396. $monitored = $child['monitored'];
  1397. if (!isset($episodeID)) {
  1398. $episodeID = "";
  1399. }
  1400. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1401. $episodeAirDate = $child['airDateUtc'];
  1402. $episodeAirDate = strtotime($episodeAirDate);
  1403. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1404. if (new DateTime() < new DateTime($episodeAirDate)) {
  1405. $unaired = true;
  1406. }
  1407. if ($child['episodeNumber'] == "1") {
  1408. $episodePremier = "true";
  1409. } else {
  1410. $episodePremier = "false";
  1411. $date = new DateTime($episodeAirDate);
  1412. $date->add(new DateInterval("PT1S"));
  1413. $date->format(DateTime::ATOM);
  1414. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1415. }
  1416. $downloaded = $child['hasFile'];
  1417. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1418. $downloaded = "text-primary animated flash";
  1419. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1420. $downloaded = "text-dark";
  1421. } elseif ($downloaded == "0" && isset($unaired)) {
  1422. $downloaded = "text-info";
  1423. } elseif ($downloaded == "1") {
  1424. $downloaded = "text-success";
  1425. } else {
  1426. $downloaded = "text-danger";
  1427. }
  1428. $fanart = "/plugins/images/cache/no-np.png";
  1429. foreach ($child['series']['images'] as $image) {
  1430. if ($image['coverType'] == "fanart") {
  1431. $fanart = $image['url'];
  1432. }
  1433. }
  1434. if ($fanart !== "/plugins/images/cache/no-np.png") {
  1435. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1436. $imageURL = $fanart;
  1437. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1438. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1439. if (!file_exists($cacheFile)) {
  1440. cacheImage($imageURL, $seriesID);
  1441. unset($imageURL);
  1442. unset($cacheFile);
  1443. }
  1444. }
  1445. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1446. $details = array(
  1447. "seasonCount" => $child['series']['seasonCount'],
  1448. "status" => $child['series']['status'],
  1449. "topTitle" => $seriesName,
  1450. "bottomTitle" => $bottomTitle,
  1451. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1452. "runtime" => $child['series']['runtime'],
  1453. "image" => $fanart,
  1454. "ratings" => $child['series']['ratings']['value'],
  1455. "videoQuality" => $child["hasFile"] && isset($child['episodeFile']['quality']['quality']['name']) ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1456. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1457. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1458. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1459. "size" => $child["hasFile"] && isset($child['episodeFile']['size']) ? $child['episodeFile']['size'] : "unknown",
  1460. "genres" => $child['series']['genres'],
  1461. );
  1462. array_push($gotCalendar, array(
  1463. "id" => "Sonarr-" . $number . "-" . $i,
  1464. "title" => $seriesName,
  1465. "start" => $child['airDateUtc'],
  1466. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1467. "imagetype" => "tv " . $downloaded,
  1468. "imagetypeFilter" => "tv",
  1469. "downloadFilter" => $downloaded,
  1470. "bgColor" => str_replace('text', 'bg', $downloaded),
  1471. "details" => $details
  1472. ));
  1473. }
  1474. if ($i != 0) {
  1475. return $gotCalendar;
  1476. }
  1477. return false;
  1478. }
  1479. function getLidarrCalendar($array, $number)
  1480. {
  1481. $array = json_decode($array, true);
  1482. $gotCalendar = array();
  1483. $i = 0;
  1484. foreach ($array as $child) {
  1485. $i++;
  1486. $albumName = $child['title'];
  1487. $artistName = $child['artist']['artistName'];
  1488. $albumID = '';
  1489. $releaseDate = $child['releaseDate'];
  1490. $releaseDate = strtotime($releaseDate);
  1491. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1492. if (new DateTime() < new DateTime($releaseDate)) {
  1493. $unaired = true;
  1494. }
  1495. if (isset($child['statistics']['percentOfTracks'])) {
  1496. if ($child['statistics']['percentOfTracks'] == '100.0') {
  1497. $downloaded = '1';
  1498. } else {
  1499. $downloaded = '0';
  1500. }
  1501. } else {
  1502. $downloaded = '0';
  1503. }
  1504. if ($downloaded == "0" && isset($unaired)) {
  1505. $downloaded = "text-info";
  1506. } elseif ($downloaded == "1") {
  1507. $downloaded = "text-success";
  1508. } else {
  1509. $downloaded = "text-danger";
  1510. }
  1511. $fanart = "/plugins/images/cache/no-np.png";
  1512. foreach ($child['artist']['images'] as $image) {
  1513. if ($image['coverType'] == "fanart") {
  1514. $fanart = str_replace('http://', 'https://', $image['url']);
  1515. }
  1516. }
  1517. $details = array(
  1518. "seasonCount" => '',
  1519. "status" => '',
  1520. "topTitle" => $albumName,
  1521. "bottomTitle" => $artistName,
  1522. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1523. "runtime" => '',
  1524. "image" => $fanart,
  1525. "ratings" => $child['artist']['ratings']['value'],
  1526. "videoQuality" => "unknown",
  1527. "audioChannels" => "unknown",
  1528. "audioCodec" => "unknown",
  1529. "videoCodec" => "unknown",
  1530. "size" => "unknown",
  1531. "genres" => $child['genres'],
  1532. );
  1533. array_push($gotCalendar, array(
  1534. "id" => "Lidarr-" . $number . "-" . $i,
  1535. "title" => $artistName,
  1536. "start" => $child['releaseDate'],
  1537. "className" => "inline-popups bg-calendar calendar-item musicID--",
  1538. "imagetype" => "music " . $downloaded,
  1539. "imagetypeFilter" => "music",
  1540. "downloadFilter" => $downloaded,
  1541. "bgColor" => str_replace('text', 'bg', $downloaded),
  1542. "details" => $details,
  1543. "data" => $child
  1544. ));
  1545. }
  1546. if ($i != 0) {
  1547. return $gotCalendar;
  1548. }
  1549. return false;
  1550. }
  1551. function getRadarrCalendar($array, $number, $url)
  1552. {
  1553. $array = json_decode($array, true);
  1554. $gotCalendar = array();
  1555. $i = 0;
  1556. foreach ($array as $child) {
  1557. if (isset($child['physicalRelease'])) {
  1558. $i++;
  1559. $movieName = $child['title'];
  1560. $movieID = $child['tmdbId'];
  1561. if (!isset($movieID)) {
  1562. $movieID = "";
  1563. }
  1564. $physicalRelease = $child['physicalRelease'];
  1565. $physicalRelease = strtotime($physicalRelease);
  1566. $physicalRelease = date("Y-m-d", $physicalRelease);
  1567. if (new DateTime() < new DateTime($physicalRelease)) {
  1568. $notReleased = "true";
  1569. } else {
  1570. $notReleased = "false";
  1571. }
  1572. $downloaded = $child['hasFile'];
  1573. if ($downloaded == "0" && $notReleased == "true") {
  1574. $downloaded = "text-info";
  1575. } elseif ($downloaded == "1") {
  1576. $downloaded = "text-success";
  1577. } else {
  1578. $downloaded = "text-danger";
  1579. }
  1580. $banner = "/plugins/images/cache/no-np.png";
  1581. foreach ($child['images'] as $image) {
  1582. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1583. $url = rtrim($url, '/'); //remove trailing slash
  1584. $imageUrl = $image['url'];
  1585. $urlParts = explode("/", $url);
  1586. $imageParts = explode("/", $image['url']);
  1587. if ($imageParts[1] == end($urlParts)) {
  1588. unset($imageParts[1]);
  1589. $imageUrl = implode("/", $imageParts);
  1590. }
  1591. $banner = $url . $imageUrl;
  1592. }
  1593. }
  1594. if ($banner !== "/plugins/images/cache/no-np.png") {
  1595. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1596. $imageURL = $banner;
  1597. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1598. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1599. if (!file_exists($cacheFile)) {
  1600. cacheImage($imageURL, $movieID);
  1601. unset($imageURL);
  1602. unset($cacheFile);
  1603. }
  1604. }
  1605. $alternativeTitles = "";
  1606. foreach ($child['alternativeTitles'] as $alternative) {
  1607. $alternativeTitles .= $alternative['title'] . ', ';
  1608. }
  1609. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1610. $details = array(
  1611. "topTitle" => $movieName,
  1612. "bottomTitle" => $alternativeTitles,
  1613. "status" => $child['status'],
  1614. "overview" => $child['overview'],
  1615. "runtime" => $child['runtime'],
  1616. "image" => $banner,
  1617. "ratings" => $child['ratings']['value'],
  1618. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1619. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1620. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1621. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1622. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1623. "genres" => $child['genres'],
  1624. "year" => isset($child['year']) ? $child['year'] : '',
  1625. "studio" => isset($child['studio']) ? $child['studio'] : '',
  1626. );
  1627. array_push($gotCalendar, array(
  1628. "id" => "Radarr-" . $number . "-" . $i,
  1629. "title" => $movieName,
  1630. "start" => $physicalRelease,
  1631. "className" => "inline-popups bg-calendar movieID--" . $movieID,
  1632. "imagetype" => "film " . $downloaded,
  1633. "imagetypeFilter" => "film",
  1634. "downloadFilter" => $downloaded,
  1635. "bgColor" => str_replace('text', 'bg', $downloaded),
  1636. "details" => $details
  1637. ));
  1638. }
  1639. }
  1640. if ($i != 0) {
  1641. return $gotCalendar;
  1642. }
  1643. return false;
  1644. }
  1645. function getCouchCalendar($array, $number)
  1646. {
  1647. $api = json_decode($array, true);
  1648. $gotCalendar = array();
  1649. $i = 0;
  1650. foreach ($api['movies'] as $child) {
  1651. if ($child['status'] == "active" || $child['status'] == "done") {
  1652. $i++;
  1653. $movieName = $child['info']['original_title'];
  1654. $movieID = $child['info']['tmdb_id'];
  1655. if (!isset($movieID)) {
  1656. $movieID = "";
  1657. }
  1658. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1659. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1660. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1661. $physicalRelease = strtotime($physicalRelease);
  1662. $physicalRelease = date("Y-m-d", $physicalRelease);
  1663. if (new DateTime() < new DateTime($physicalRelease)) {
  1664. $notReleased = "true";
  1665. } else {
  1666. $notReleased = "false";
  1667. }
  1668. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1669. if ($downloaded == "0" && $notReleased == "true") {
  1670. $downloaded = "text-info";
  1671. } elseif ($downloaded == "1") {
  1672. $downloaded = "text-success";
  1673. } else {
  1674. $downloaded = "text-danger";
  1675. }
  1676. if (!empty($child['info']['images']['backdrop_original'])) {
  1677. $banner = $child['info']['images']['backdrop_original'][0];
  1678. } elseif (!empty($child['info']['images']['backdrop'])) {
  1679. $banner = $child['info']['images']['backdrop_original'][0];
  1680. } else {
  1681. $banner = "/plugins/images/cache/no-np.png";
  1682. }
  1683. if ($banner !== "/plugins/images/cache/no-np.png") {
  1684. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1685. $imageURL = $banner;
  1686. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1687. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1688. if (!file_exists($cacheFile)) {
  1689. cacheImage($imageURL, $movieID);
  1690. unset($imageURL);
  1691. unset($cacheFile);
  1692. }
  1693. }
  1694. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1695. $details = array(
  1696. "topTitle" => $movieName,
  1697. "bottomTitle" => $child['info']['tagline'],
  1698. "status" => $child['status'],
  1699. "overview" => $child['info']['plot'],
  1700. "runtime" => $child['info']['runtime'],
  1701. "image" => $banner,
  1702. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1703. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1704. "audioChannels" => "",
  1705. "audioCodec" => "",
  1706. "videoCodec" => "",
  1707. "genres" => $child['info']['genres'],
  1708. "year" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1709. "studio" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1710. );
  1711. array_push($gotCalendar, array(
  1712. "id" => "CouchPotato-" . $number . "-" . $i,
  1713. "title" => $movieName,
  1714. "start" => $physicalRelease,
  1715. "className" => "inline-popups bg-calendar calendar-item movieID--" . $movieID,
  1716. "imagetype" => "film " . $downloaded,
  1717. "imagetypeFilter" => "film",
  1718. "downloadFilter" => $downloaded,
  1719. "bgColor" => str_replace('text', 'bg', $downloaded),
  1720. "details" => $details
  1721. ));
  1722. }
  1723. }
  1724. if ($i != 0) {
  1725. return $gotCalendar;
  1726. }
  1727. return false;
  1728. }
  1729. function getSickrageCalendarWanted($array, $number)
  1730. {
  1731. $array = json_decode($array, true);
  1732. $gotCalendar = array();
  1733. $i = 0;
  1734. foreach ($array['data']['missed'] as $child) {
  1735. $i++;
  1736. $seriesName = $child['show_name'];
  1737. $seriesID = $child['tvdbid'];
  1738. $episodeID = $child['tvdbid'];
  1739. $episodeAirDate = $child['airdate'];
  1740. $episodeAirDateTime = explode(" ", $child['airs']);
  1741. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1742. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1743. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1744. if (new DateTime() < new DateTime($episodeAirDate)) {
  1745. $unaired = true;
  1746. }
  1747. $downloaded = "0";
  1748. if ($downloaded == "0" && isset($unaired)) {
  1749. $downloaded = "text-info";
  1750. } elseif ($downloaded == "1") {
  1751. $downloaded = "text-success";
  1752. } else {
  1753. $downloaded = "text-danger";
  1754. }
  1755. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1756. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1757. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1758. $fanart = "/plugins/images/cache/no-np.png";
  1759. if (file_exists($cacheFile)) {
  1760. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1761. unset($cacheFile);
  1762. }
  1763. $details = array(
  1764. "seasonCount" => "",
  1765. "status" => $child['show_status'],
  1766. "topTitle" => $seriesName,
  1767. "bottomTitle" => $bottomTitle,
  1768. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1769. "runtime" => "",
  1770. "image" => $fanart,
  1771. "ratings" => "",
  1772. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1773. "audioChannels" => "",
  1774. "audioCodec" => "",
  1775. "videoCodec" => "",
  1776. "size" => "",
  1777. "genres" => "",
  1778. );
  1779. array_push($gotCalendar, array(
  1780. "id" => "Sick-" . $number . "-Miss-" . $i,
  1781. "title" => $seriesName,
  1782. "start" => $episodeAirDate,
  1783. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1784. "imagetype" => "tv " . $downloaded,
  1785. "imagetypeFilter" => "tv",
  1786. "downloadFilter" => $downloaded,
  1787. "bgColor" => str_replace('text', 'bg', $downloaded),
  1788. "details" => $details,
  1789. ));
  1790. }
  1791. foreach ($array['data']['today'] as $child) {
  1792. $i++;
  1793. $seriesName = $child['show_name'];
  1794. $seriesID = $child['tvdbid'];
  1795. $episodeID = $child['tvdbid'];
  1796. $episodeAirDate = $child['airdate'];
  1797. $episodeAirDateTime = explode(" ", $child['airs']);
  1798. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1799. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1800. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1801. if (new DateTime() < new DateTime($episodeAirDate)) {
  1802. $unaired = true;
  1803. }
  1804. $downloaded = "0";
  1805. if ($downloaded == "0" && isset($unaired)) {
  1806. $downloaded = "text-info";
  1807. } elseif ($downloaded == "1") {
  1808. $downloaded = "text-success";
  1809. } else {
  1810. $downloaded = "text-danger";
  1811. }
  1812. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1813. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1814. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1815. $fanart = "/plugins/images/cache/no-np.png";
  1816. if (file_exists($cacheFile)) {
  1817. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1818. unset($cacheFile);
  1819. }
  1820. $details = array(
  1821. "seasonCount" => "",
  1822. "status" => $child['show_status'],
  1823. "topTitle" => $seriesName,
  1824. "bottomTitle" => $bottomTitle,
  1825. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1826. "runtime" => "",
  1827. "image" => $fanart,
  1828. "ratings" => "",
  1829. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1830. "audioChannels" => "",
  1831. "audioCodec" => "",
  1832. "videoCodec" => "",
  1833. "size" => "",
  1834. "genres" => "",
  1835. );
  1836. array_push($gotCalendar, array(
  1837. "id" => "Sick-" . $number . "-Today-" . $i,
  1838. "title" => $seriesName,
  1839. "start" => $episodeAirDate,
  1840. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1841. "imagetype" => "tv " . $downloaded,
  1842. "imagetypeFilter" => "tv",
  1843. "downloadFilter" => $downloaded,
  1844. "bgColor" => str_replace('text', 'bg', $downloaded),
  1845. "details" => $details,
  1846. ));
  1847. }
  1848. foreach ($array['data']['soon'] as $child) {
  1849. $i++;
  1850. $seriesName = $child['show_name'];
  1851. $seriesID = $child['tvdbid'];
  1852. $episodeID = $child['tvdbid'];
  1853. $episodeAirDate = $child['airdate'];
  1854. $episodeAirDateTime = explode(" ", $child['airs']);
  1855. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1856. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1857. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1858. if (new DateTime() < new DateTime($episodeAirDate)) {
  1859. $unaired = true;
  1860. }
  1861. $downloaded = "0";
  1862. if ($downloaded == "0" && isset($unaired)) {
  1863. $downloaded = "text-info";
  1864. } elseif ($downloaded == "1") {
  1865. $downloaded = "text-success";
  1866. } else {
  1867. $downloaded = "text-danger";
  1868. }
  1869. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1870. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1871. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1872. $fanart = "/plugins/images/cache/no-np.png";
  1873. if (file_exists($cacheFile)) {
  1874. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1875. unset($cacheFile);
  1876. }
  1877. $details = array(
  1878. "seasonCount" => "",
  1879. "status" => $child['show_status'],
  1880. "topTitle" => $seriesName,
  1881. "bottomTitle" => $bottomTitle,
  1882. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1883. "runtime" => "",
  1884. "image" => $fanart,
  1885. "ratings" => "",
  1886. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1887. "audioChannels" => "",
  1888. "audioCodec" => "",
  1889. "videoCodec" => "",
  1890. "size" => "",
  1891. "genres" => "",
  1892. );
  1893. array_push($gotCalendar, array(
  1894. "id" => "Sick-" . $number . "-Soon-" . $i,
  1895. "title" => $seriesName,
  1896. "start" => $episodeAirDate,
  1897. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1898. "imagetype" => "tv " . $downloaded,
  1899. "imagetypeFilter" => "tv",
  1900. "downloadFilter" => $downloaded,
  1901. "bgColor" => str_replace('text', 'bg', $downloaded),
  1902. "details" => $details,
  1903. ));
  1904. }
  1905. foreach ($array['data']['later'] as $child) {
  1906. $i++;
  1907. $seriesName = $child['show_name'];
  1908. $seriesID = $child['tvdbid'];
  1909. $episodeID = $child['tvdbid'];
  1910. $episodeAirDate = $child['airdate'];
  1911. $episodeAirDateTime = explode(" ", $child['airs']);
  1912. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1913. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1914. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1915. if (new DateTime() < new DateTime($episodeAirDate)) {
  1916. $unaired = true;
  1917. }
  1918. $downloaded = "0";
  1919. if ($downloaded == "0" && isset($unaired)) {
  1920. $downloaded = "text-info";
  1921. } elseif ($downloaded == "1") {
  1922. $downloaded = "text-success";
  1923. } else {
  1924. $downloaded = "text-danger";
  1925. }
  1926. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1927. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1928. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1929. $fanart = "/plugins/images/cache/no-np.png";
  1930. if (file_exists($cacheFile)) {
  1931. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1932. unset($cacheFile);
  1933. }
  1934. $details = array(
  1935. "seasonCount" => "",
  1936. "status" => $child['show_status'],
  1937. "topTitle" => $seriesName,
  1938. "bottomTitle" => $bottomTitle,
  1939. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1940. "runtime" => "",
  1941. "image" => $fanart,
  1942. "ratings" => "",
  1943. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1944. "audioChannels" => "",
  1945. "audioCodec" => "",
  1946. "videoCodec" => "",
  1947. "size" => "",
  1948. "genres" => "",
  1949. );
  1950. array_push($gotCalendar, array(
  1951. "id" => "Sick-" . $number . "-Later-" . $i,
  1952. "title" => $seriesName,
  1953. "start" => $episodeAirDate,
  1954. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1955. "imagetype" => "tv " . $downloaded,
  1956. "imagetypeFilter" => "tv",
  1957. "downloadFilter" => $downloaded,
  1958. "bgColor" => str_replace('text', 'bg', $downloaded),
  1959. "details" => $details,
  1960. ));
  1961. }
  1962. if ($i != 0) {
  1963. return $gotCalendar;
  1964. }
  1965. return false;
  1966. }
  1967. function getSickrageCalendarHistory($array, $number)
  1968. {
  1969. $array = json_decode($array, true);
  1970. $gotCalendar = array();
  1971. $i = 0;
  1972. foreach ($array['data'] as $child) {
  1973. $i++;
  1974. $seriesName = $child['show_name'];
  1975. $seriesID = $child['tvdbid'];
  1976. $episodeID = $child['tvdbid'];
  1977. $episodeAirDate = $child['date'];
  1978. $downloaded = "text-success";
  1979. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  1980. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1981. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1982. $fanart = "/plugins/images/cache/no-np.png";
  1983. if (file_exists($cacheFile)) {
  1984. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1985. unset($cacheFile);
  1986. }
  1987. $details = array(
  1988. "seasonCount" => "",
  1989. "status" => $child['status'],
  1990. "topTitle" => $seriesName,
  1991. "bottomTitle" => $bottomTitle,
  1992. "overview" => '',
  1993. "runtime" => isset($child['series']['runtime']) ? $child['series']['runtime'] : 30,
  1994. "image" => $fanart,
  1995. "ratings" => isset($child['series']['ratings']['value']) ? $child['series']['ratings']['value'] : "unknown",
  1996. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  1997. "audioChannels" => "",
  1998. "audioCodec" => "",
  1999. "videoCodec" => "",
  2000. "size" => "",
  2001. "genres" => "",
  2002. );
  2003. array_push($gotCalendar, array(
  2004. "id" => "Sick-" . $number . "-History-" . $i,
  2005. "title" => $seriesName,
  2006. "start" => $episodeAirDate,
  2007. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2008. "imagetype" => "tv " . $downloaded,
  2009. "imagetypeFilter" => "tv",
  2010. "downloadFilter" => $downloaded,
  2011. "bgColor" => str_replace('text', 'bg', $downloaded),
  2012. "details" => $details,
  2013. ));
  2014. }
  2015. if ($i != 0) {
  2016. return $gotCalendar;
  2017. }
  2018. return false;
  2019. }
  2020. function ombiAPI($array)
  2021. {
  2022. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  2023. }
  2024. function ombiImport($type = null)
  2025. {
  2026. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  2027. try {
  2028. $url = qualifyURL($GLOBALS['ombiURL']);
  2029. $headers = array(
  2030. "Accept" => "application/json",
  2031. "Content-Type" => "application/json",
  2032. "Apikey" => $GLOBALS['ombiToken']
  2033. );
  2034. $options = (localURL($url)) ? array('verify' => false) : array();
  2035. switch ($type) {
  2036. case 'emby':
  2037. case 'emby_local':
  2038. case 'emby_connect':
  2039. case 'emby_all':
  2040. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  2041. break;
  2042. case 'plex':
  2043. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  2044. break;
  2045. default:
  2046. return false;
  2047. break;
  2048. }
  2049. if ($response->success) {
  2050. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  2051. return true;
  2052. } else {
  2053. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  2054. return false;
  2055. }
  2056. } catch (Requests_Exception $e) {
  2057. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2058. return false;
  2059. };
  2060. }
  2061. return false;
  2062. }
  2063. function ombiAction($id, $action, $type, $fullArray = null)
  2064. {
  2065. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2066. $url = qualifyURL($GLOBALS['ombiURL']);
  2067. $headers = array(
  2068. "Accept" => "application/json",
  2069. "Content-Type" => "application/json",
  2070. "Apikey" => $GLOBALS['ombiToken']
  2071. );
  2072. $data = array(
  2073. 'id' => $id,
  2074. );
  2075. switch ($type) {
  2076. case 'season':
  2077. case 'tv':
  2078. $type = 'tv';
  2079. $add = array(
  2080. 'tvDbId' => $id,
  2081. 'requestAll' => ombiTVDefault('all'),
  2082. 'latestSeason' => ombiTVDefault('last'),
  2083. 'firstSeason' => ombiTVDefault('first')
  2084. );
  2085. break;
  2086. default:
  2087. $type = 'movie';
  2088. $add = array("theMovieDbId" => (int)$id);
  2089. break;
  2090. }
  2091. $success['head'] = $headers;
  2092. $success['act'] = $action;
  2093. $success['data'] = $data;
  2094. $success['add'] = $add;
  2095. $success['type'] = $type;
  2096. try {
  2097. $options = (localURL($url)) ? array('verify' => false) : array();
  2098. switch ($action) {
  2099. case 'add':
  2100. if (isset($_COOKIE['Auth'])) {
  2101. $headers = array(
  2102. "Accept" => "application/json",
  2103. "Content-Type" => "application/json",
  2104. "Authorization" => "Bearer " . $_COOKIE['Auth']
  2105. );
  2106. $success['head'] = $headers;
  2107. } else {
  2108. return false;
  2109. }
  2110. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  2111. break;
  2112. default:
  2113. if (qualifyRequest(1)) {
  2114. switch ($action) {
  2115. case 'approve':
  2116. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  2117. break;
  2118. case 'available':
  2119. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  2120. break;
  2121. case 'unavailable':
  2122. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  2123. break;
  2124. case 'deny':
  2125. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  2126. break;
  2127. case 'delete':
  2128. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  2129. break;
  2130. default:
  2131. return false;
  2132. }
  2133. }
  2134. break;
  2135. }
  2136. $success['api'] = $response;
  2137. $success['bd'] = $response->body;
  2138. $success['hd'] = $response->headers;
  2139. if ($response->success) {
  2140. $success['ok'] = true;
  2141. }
  2142. } catch (Requests_Exception $e) {
  2143. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2144. };
  2145. }
  2146. return isset($success['ok']) ? $success : false;
  2147. }
  2148. function getOmbiRequests($type = "both", $limit = 50)
  2149. {
  2150. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2151. $url = qualifyURL($GLOBALS['ombiURL']);
  2152. $headers = array(
  2153. "Accept" => "application/json",
  2154. "Apikey" => $GLOBALS['ombiToken'],
  2155. );
  2156. $requests = array();
  2157. try {
  2158. $options = (localURL($url)) ? array('verify' => false) : array();
  2159. switch ($type) {
  2160. case 'movie':
  2161. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2162. break;
  2163. case 'tv':
  2164. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2165. break;
  2166. default:
  2167. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2168. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2169. break;
  2170. }
  2171. if ($movie->success || $tv->success) {
  2172. if (isset($movie)) {
  2173. $movie = json_decode($movie->body, true);
  2174. //$movie = array_reverse($movie);
  2175. foreach ($movie as $key => $value) {
  2176. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2177. if ($proceed) {
  2178. $requests[] = array(
  2179. 'test' => $value,
  2180. 'id' => $value['theMovieDbId'],
  2181. 'title' => $value['title'],
  2182. 'overview' => $value['overview'],
  2183. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
  2184. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2185. 'approved' => $value['approved'],
  2186. 'available' => $value['available'],
  2187. 'denied' => $value['denied'],
  2188. 'deniedReason' => $value['deniedReason'],
  2189. 'user' => $value['requestedUser']['userName'],
  2190. 'userAlias' => $value['requestedUser']['userAlias'],
  2191. 'request_id' => $value['id'],
  2192. 'request_date' => $value['requestedDate'],
  2193. 'release_date' => $value['releaseDate'],
  2194. 'type' => 'movie',
  2195. 'icon' => 'mdi mdi-filmstrip',
  2196. 'color' => 'palette-Deep-Purple-900 bg white',
  2197. );
  2198. }
  2199. }
  2200. }
  2201. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2202. $tv = json_decode($tv->body, true);
  2203. foreach ($tv as $key => $value) {
  2204. if (count($value['childRequests']) > 0) {
  2205. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2206. if ($proceed) {
  2207. $requests[] = array(
  2208. 'test' => $value,
  2209. 'id' => $value['tvDbId'],
  2210. 'title' => $value['title'],
  2211. 'overview' => $value['overview'],
  2212. 'poster' => $value['posterPath'],
  2213. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2214. 'approved' => $value['childRequests'][0]['approved'],
  2215. 'available' => $value['childRequests'][0]['available'],
  2216. 'denied' => $value['childRequests'][0]['denied'],
  2217. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2218. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2219. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2220. 'request_id' => $value['id'],
  2221. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2222. 'release_date' => $value['releaseDate'],
  2223. 'type' => 'tv',
  2224. 'icon' => 'mdi mdi-television',
  2225. 'color' => 'grayish-blue-bg',
  2226. );
  2227. }
  2228. }
  2229. }
  2230. }
  2231. //sort here
  2232. usort($requests, function ($item1, $item2) {
  2233. if ($item1['request_date'] == $item2['request_date']) {
  2234. return 0;
  2235. }
  2236. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2237. });
  2238. }
  2239. } catch (Requests_Exception $e) {
  2240. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2241. };
  2242. }
  2243. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2244. return $api;
  2245. }
  2246. function testAPIConnection($array)
  2247. {
  2248. switch ($array['data']['action']) {
  2249. case 'ombi':
  2250. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2251. $url = qualifyURL($GLOBALS['ombiURL']);
  2252. $url = $url . "/api/v1/Status/info";
  2253. $headers = array(
  2254. "Accept" => "application/json",
  2255. "Content-Type" => "application/json",
  2256. "Apikey" => $GLOBALS['ombiToken']
  2257. );
  2258. try {
  2259. $options = (localURL($url)) ? array('verify' => false) : array();
  2260. $response = Requests::get($url, $headers, $options);
  2261. if ($response->success) {
  2262. return true;
  2263. } else {
  2264. return $response->body;
  2265. }
  2266. } catch (Requests_Exception $e) {
  2267. return $e->getMessage();
  2268. };
  2269. } else {
  2270. return 'URL and/or Token not setup';
  2271. }
  2272. break;
  2273. case 'plex':
  2274. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2275. $url = qualifyURL($GLOBALS['plexURL']);
  2276. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2277. try {
  2278. $options = (localURL($url)) ? array('verify' => false) : array();
  2279. $response = Requests::get($url, array(), $options);
  2280. libxml_use_internal_errors(true);
  2281. if ($response->success) {
  2282. return true;
  2283. }
  2284. } catch (Requests_Exception $e) {
  2285. return $e->getMessage();
  2286. };
  2287. } else {
  2288. return 'URL and/or Token not setup';
  2289. }
  2290. break;
  2291. case 'emby':
  2292. break;
  2293. case 'sonarr':
  2294. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2295. $sonarrs = array();
  2296. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2297. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2298. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2299. foreach ($sonarrURLList as $key => $value) {
  2300. $sonarrs[$key] = array(
  2301. 'url' => $value,
  2302. 'token' => $sonarrTokenList[$key]
  2303. );
  2304. }
  2305. foreach ($sonarrs as $key => $value) {
  2306. try {
  2307. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2308. $result = json_decode($sonarr->getSystemStatus(), true);
  2309. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2310. } catch (Exception $e) {
  2311. return strip($e->getMessage());
  2312. }
  2313. }
  2314. }
  2315. } else {
  2316. return 'URL/s and/or Token/s not setup';
  2317. }
  2318. break;
  2319. case 'lidarr':
  2320. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2321. $sonarrs = array();
  2322. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2323. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2324. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2325. foreach ($sonarrURLList as $key => $value) {
  2326. $sonarrs[$key] = array(
  2327. 'url' => $value,
  2328. 'token' => $sonarrTokenList[$key]
  2329. );
  2330. }
  2331. foreach ($sonarrs as $key => $value) {
  2332. try {
  2333. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2334. $result = json_decode($sonarr->getSystemStatus(), true);
  2335. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2336. } catch (Exception $e) {
  2337. return $e->getMessage();
  2338. }
  2339. }
  2340. }
  2341. } else {
  2342. return 'URL/s and/or Token/s not setup';
  2343. }
  2344. break;
  2345. case 'radarr':
  2346. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2347. $sonarrs = array();
  2348. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2349. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2350. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2351. foreach ($sonarrURLList as $key => $value) {
  2352. $sonarrs[$key] = array(
  2353. 'url' => $value,
  2354. 'token' => $sonarrTokenList[$key]
  2355. );
  2356. }
  2357. foreach ($sonarrs as $key => $value) {
  2358. try {
  2359. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2360. $result = json_decode($sonarr->getSystemStatus(), true);
  2361. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2362. } catch (Exception $e) {
  2363. return $e->getMessage();
  2364. }
  2365. }
  2366. }
  2367. } else {
  2368. return 'URL/s and/or Token/s not setup';
  2369. }
  2370. break;
  2371. case 'sabnzbd':
  2372. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2373. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2374. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2375. try {
  2376. $options = (localURL($url)) ? array('verify' => false) : array();
  2377. $response = Requests::get($url, array(), $options);
  2378. if ($response->success) {
  2379. return true;
  2380. }
  2381. } catch (Requests_Exception $e) {
  2382. return $e->getMessage();
  2383. };
  2384. } else {
  2385. return 'URL and/or Token not setup';
  2386. }
  2387. break;
  2388. case 'nzbget':
  2389. if (!empty($GLOBALS['nzbgetURL'])) {
  2390. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2391. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  2392. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  2393. } else {
  2394. $url = $url . '/jsonrpc/listgroups';
  2395. }
  2396. try {
  2397. $options = (localURL($url)) ? array('verify' => false) : array();
  2398. $response = Requests::get($url, array(), $options);
  2399. if ($response->success) {
  2400. return true;
  2401. }
  2402. } catch (Requests_Exception $e) {
  2403. return $e->getMessage();
  2404. };
  2405. } else {
  2406. return 'URL and/or Username/Password not setup';
  2407. }
  2408. break;
  2409. case 'deluge':
  2410. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2411. try {
  2412. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2413. $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');
  2414. return true;
  2415. } catch (Exception $e) {
  2416. return $e->getMessage();
  2417. }
  2418. } else {
  2419. return 'URL and/or Password not setup';
  2420. }
  2421. break;
  2422. case 'rtorrent':
  2423. if (!empty($GLOBALS['rTorrentURL'])) {
  2424. try {
  2425. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  2426. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2427. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2428. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  2429. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2430. $options = (localURL($url)) ? array('verify' => false) : array();
  2431. $data = xmlrpc_encode_request("system.listMethods", null);
  2432. $response = Requests::post($url, array(), $data, $options);
  2433. if ($response->success) {
  2434. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2435. if (count($methods) !== 0) {
  2436. return true;
  2437. }
  2438. }
  2439. return false;
  2440. } catch
  2441. (Requests_Exception $e) {
  2442. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2443. return $e->getMessage();
  2444. };
  2445. }
  2446. break;
  2447. case 'ldap_login':
  2448. $username = $array['data']['data']['username'];
  2449. $password = $array['data']['data']['password'];
  2450. if (empty($username) || empty($password)) {
  2451. return 'Missing Username or Password';
  2452. }
  2453. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2454. $ad = new \Adldap\Adldap();
  2455. // Create a configuration array.
  2456. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2457. $i = 0;
  2458. foreach ($ldapServers as $key => $value) {
  2459. // Calculate parts
  2460. $digest = parse_url(trim($value));
  2461. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2462. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2463. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2464. // Reassign
  2465. $ldapHosts[] = $host;
  2466. $ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
  2467. if ($i == 0) {
  2468. $ldapPort = $port;
  2469. }
  2470. $i++;
  2471. }
  2472. $config = [
  2473. // Mandatory Configuration Options
  2474. 'hosts' => $ldapHosts,
  2475. 'base_dn' => $GLOBALS['authBaseDN'],
  2476. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  2477. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  2478. // Optional Configuration Options
  2479. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  2480. 'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
  2481. 'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
  2482. 'port' => $ldapPort,
  2483. 'follow_referrals' => false,
  2484. 'use_ssl' => false,
  2485. 'use_tls' => false,
  2486. 'version' => 3,
  2487. 'timeout' => 5,
  2488. // Custom LDAP Options
  2489. 'custom_options' => [
  2490. // See: http://php.net/ldap_set_option
  2491. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  2492. ]
  2493. ];
  2494. // Add a connection provider to Adldap.
  2495. $ad->addProvider($config);
  2496. try {
  2497. // If a successful connection is made to your server, the provider will be returned.
  2498. $provider = $ad->connect();
  2499. //prettyPrint($provider);
  2500. if ($provider->auth()->attempt($username, $password, true)) {
  2501. // Passed.
  2502. $user = $provider->search()->find($username);
  2503. //return $user->getFirstAttribute('cn');
  2504. //return $user->getGroups(['cn']);
  2505. //return $user;
  2506. //return $user->getUserPrincipalName();
  2507. //return $user->getGroups(['cn']);
  2508. return true;
  2509. } else {
  2510. // Failed.
  2511. return 'Username/Password Failed to authenticate';
  2512. }
  2513. } catch (\Adldap\Auth\BindException $e) {
  2514. $detailedError = $e->getDetailedError();
  2515. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  2516. return $detailedError->getErrorMessage();
  2517. // There was an issue binding / connecting to the server.
  2518. } catch (Adldap\Auth\UsernameRequiredException $e) {
  2519. $detailedError = $e->getDetailedError();
  2520. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  2521. return $detailedError->getErrorMessage();
  2522. // The user didn't supply a username.
  2523. } catch (Adldap\Auth\PasswordRequiredException $e) {
  2524. $detailedError = $e->getDetailedError();
  2525. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  2526. return $detailedError->getErrorMessage();
  2527. // The user didn't supply a password.
  2528. }
  2529. }
  2530. break;
  2531. case 'ldap':
  2532. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2533. $ad = new \Adldap\Adldap();
  2534. // Create a configuration array.
  2535. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2536. $i = 0;
  2537. foreach ($ldapServers as $key => $value) {
  2538. // Calculate parts
  2539. $digest = parse_url(trim($value));
  2540. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2541. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2542. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2543. // Reassign
  2544. $ldapHosts[] = $host;
  2545. if ($i == 0) {
  2546. $ldapPort = $port;
  2547. }
  2548. $i++;
  2549. }
  2550. $config = [
  2551. // Mandatory Configuration Options
  2552. 'hosts' => $ldapHosts,
  2553. 'base_dn' => $GLOBALS['authBaseDN'],
  2554. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  2555. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  2556. // Optional Configuration Options
  2557. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  2558. 'account_prefix' => '',
  2559. 'account_suffix' => '',
  2560. 'port' => $ldapPort,
  2561. 'follow_referrals' => false,
  2562. 'use_ssl' => false,
  2563. 'use_tls' => false,
  2564. 'version' => 3,
  2565. 'timeout' => 5,
  2566. // Custom LDAP Options
  2567. 'custom_options' => [
  2568. // See: http://php.net/ldap_set_option
  2569. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  2570. ]
  2571. ];
  2572. // Add a connection provider to Adldap.
  2573. $ad->addProvider($config);
  2574. try {
  2575. // If a successful connection is made to your server, the provider will be returned.
  2576. $provider = $ad->connect();
  2577. } catch (\Adldap\Auth\BindException $e) {
  2578. $detailedError = $e->getDetailedError();
  2579. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
  2580. return $detailedError->getErrorMessage();
  2581. // There was an issue binding / connecting to the server.
  2582. }
  2583. return ($provider) ? true : false;
  2584. }
  2585. return false;
  2586. break;
  2587. default :
  2588. return false;
  2589. }
  2590. return false;
  2591. }