homepage-connect-functions.php 114 KB

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