homepage-connect-functions.php 102 KB

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