homepage-connect-functions.php 118 KB

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