homepage-connect-functions.php 117 KB

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