homepage-connect-functions.php 101 KB

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