homepage-connect-functions.php 95 KB

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