homepage-connect-functions.php 112 KB

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