homepage-connect-functions.php 115 KB

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