homepage-connect-functions.php 118 KB

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