homepage-connect-functions.php 101 KB

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