homepage-connect-functions.php 121 KB

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