homepage-connect-functions.php 133 KB

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