homepage-connect-functions.php 112 KB

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