homepage-connect-functions.php 99 KB

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