homepage-connect-functions.php 136 KB

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