homepage-connect-functions.php 133 KB

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