homepage-connect-functions.php 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  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']) && !empty($GLOBALS['healthChecksURL']) && 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 = qualifyURL($GLOBALS['healthChecksURL']) . '/' . $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. if (is_array($result) || is_object($result)) {
  1078. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : getSonarrCalendar($sonarr, $key);
  1079. } else {
  1080. $sonarrCalendar = '';
  1081. }
  1082. } catch (Exception $e) {
  1083. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1084. }
  1085. if (!empty($sonarrCalendar)) {
  1086. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  1087. }
  1088. }
  1089. }
  1090. }
  1091. // LIDARR CONNECT
  1092. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  1093. $lidarrs = array();
  1094. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  1095. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  1096. if (count($lidarrURLList) == count($lidarrTokenList)) {
  1097. foreach ($lidarrURLList as $key => $value) {
  1098. $lidarrs[$key] = array(
  1099. 'url' => $value,
  1100. 'token' => $lidarrTokenList[$key]
  1101. );
  1102. }
  1103. foreach ($lidarrs as $key => $value) {
  1104. try {
  1105. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1106. $lidarr = $lidarr->getCalendar($startDate, $endDate);
  1107. $result = json_decode($lidarr, true);
  1108. if (is_array($result) || is_object($result)) {
  1109. $lidarrCalendar = (array_key_exists('error', $result)) ? '' : getLidarrCalendar($lidarr, $key);
  1110. } else {
  1111. $lidarrCalendar = '';
  1112. }
  1113. } catch (Exception $e) {
  1114. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1115. }
  1116. if (!empty($lidarrCalendar)) {
  1117. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. // RADARR CONNECT
  1123. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1124. $radarrs = array();
  1125. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1126. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1127. if (count($radarrURLList) == count($radarrTokenList)) {
  1128. foreach ($radarrURLList as $key => $value) {
  1129. $radarrs[$key] = array(
  1130. 'url' => $value,
  1131. 'token' => $radarrTokenList[$key]
  1132. );
  1133. }
  1134. foreach ($radarrs as $key => $value) {
  1135. try {
  1136. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1137. $radarr = $radarr->getCalendar($startDate, $endDate);
  1138. $result = json_decode($radarr, true);
  1139. if (is_array($result) || is_object($result)) {
  1140. $radarrCalendar = (array_key_exists('error', $result)) ? '' : getRadarrCalendar($radarr, $key, $value['url']);
  1141. } else {
  1142. $radarrCalendar = '';
  1143. }
  1144. } catch (Exception $e) {
  1145. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1146. }
  1147. if (!empty($radarrCalendar)) {
  1148. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. // SICKRAGE/BEARD/MEDUSA CONNECT
  1154. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1155. $sicks = array();
  1156. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1157. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1158. if (count($sickURLList) == count($sickTokenList)) {
  1159. foreach ($sickURLList as $key => $value) {
  1160. $sicks[$key] = array(
  1161. 'url' => $value,
  1162. 'token' => $sickTokenList[$key]
  1163. );
  1164. }
  1165. foreach ($sicks as $key => $value) {
  1166. try {
  1167. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1168. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1169. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1170. if (!empty($sickrageFuture)) {
  1171. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1172. }
  1173. if (!empty($sickrageHistory)) {
  1174. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1175. }
  1176. } catch (Exception $e) {
  1177. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // COUCHPOTATO CONNECT
  1183. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1184. $couchs = array();
  1185. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1186. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1187. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1188. foreach ($couchpotatoURLList as $key => $value) {
  1189. $couchs[$key] = array(
  1190. 'url' => $value,
  1191. 'token' => $couchpotatoTokenList[$key]
  1192. );
  1193. }
  1194. foreach ($couchs as $key => $value) {
  1195. try {
  1196. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1197. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1198. if (!empty($couchCalendar)) {
  1199. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1200. }
  1201. } catch (Exception $e) {
  1202. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1203. }
  1204. }
  1205. }
  1206. }
  1207. // iCal URL
  1208. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1209. $calendars = array();
  1210. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1211. $icalEvents = array();
  1212. foreach ($calendarURLList as $key => $value) {
  1213. $icsEvents = getIcsEventsAsArray($value);
  1214. if (isset($icsEvents) && !empty($icsEvents)) {
  1215. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1216. unset($icsEvents [1]);
  1217. foreach ($icsEvents as $icsEvent) {
  1218. $startKeys = array_filter_key($icsEvent, function ($key) {
  1219. return strpos($key, 'DTSTART') === 0;
  1220. });
  1221. $endKeys = array_filter_key($icsEvent, function ($key) {
  1222. return strpos($key, 'DTEND') === 0;
  1223. });
  1224. if (!empty($startKeys) && !empty($endKeys) && isset($icsEvent['SUMMARY'])) {
  1225. /* Getting start date and time */
  1226. $repeat = isset($icsEvent ['RRULE']) ? $icsEvent ['RRULE'] : false;
  1227. $start = reset($startKeys);
  1228. $end = reset($endKeys);
  1229. $totalDays = $GLOBALS['calendarStart'] + $GLOBALS['calendarEnd'];
  1230. if ($repeat) {
  1231. $repeatOverride = getCalenderRepeatCount(trim($icsEvent["RRULE"]));
  1232. switch (trim(strtolower(getCalenderRepeat($repeat)))) {
  1233. case 'daily':
  1234. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1235. $term = 'days';
  1236. break;
  1237. case 'weekly':
  1238. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 7);
  1239. $term = 'weeks';
  1240. break;
  1241. case 'monthly':
  1242. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 30);
  1243. $term = 'months';
  1244. break;
  1245. case 'yearly':
  1246. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 365);
  1247. $term = 'years';
  1248. break;
  1249. default:
  1250. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1251. $term = 'days';
  1252. break;
  1253. }
  1254. } else {
  1255. $repeat = 1;
  1256. $term = 'day';
  1257. }
  1258. $calendarTimes = 0;
  1259. while ($calendarTimes < $repeat) {
  1260. $currentDate = new DateTime ($GLOBALS['currentTime']);
  1261. $oldestDay = new DateTime ($GLOBALS['currentTime']);
  1262. $oldestDay->modify('-' . $GLOBALS['calendarStart'] . ' days');
  1263. $newestDay = new DateTime ($GLOBALS['currentTime']);
  1264. $newestDay->modify('+' . $GLOBALS['calendarEnd'] . ' days');
  1265. /* Converting to datetime and apply the timezone to get proper date time */
  1266. $startDt = new DateTime ($start);
  1267. /* Getting end date with time */
  1268. $endDt = new DateTime ($end);
  1269. if ($calendarTimes !== 0) {
  1270. $dateDiff = date_diff($startDt, $currentDate);
  1271. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1272. $startDt->modify('+' . $calendarTimes . ' ' . $term);
  1273. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1274. $endDt->modify('+' . $calendarTimes . ' ' . $term);
  1275. } elseif ($calendarTimes == 0 && $repeat !== 1) {
  1276. $dateDiff = date_diff($startDt, $currentDate);
  1277. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1278. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1279. }
  1280. $calendarStartDiff = date_diff($startDt, $newestDay);
  1281. $calendarEndDiff = date_diff($startDt, $oldestDay);
  1282. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1283. $endDt->setTimeZone(new DateTimezone ($timeZone));
  1284. $startDate = $startDt->format(DateTime::ATOM);
  1285. $endDate = $endDt->format(DateTime::ATOM);
  1286. if (new DateTime() < $endDt) {
  1287. $extraClass = 'text-info';
  1288. } else {
  1289. $extraClass = 'text-success';
  1290. }
  1291. /* Getting the name of event */
  1292. $eventName = $icsEvent['SUMMARY'];
  1293. if (!calendarDaysCheck($calendarStartDiff->format('%R') . $calendarStartDiff->days, $calendarEndDiff->format('%R') . $calendarEndDiff->days)) {
  1294. break;
  1295. }
  1296. if (isset($icsEvent["RRULE"]) && getCalenderRepeatUntil(trim($icsEvent["RRULE"]))) {
  1297. $untilDate = new DateTime (getCalenderRepeatUntil(trim($icsEvent["RRULE"])));
  1298. $untilDiff = date_diff($currentDate, $untilDate);
  1299. if ($untilDiff->days > 0) {
  1300. break;
  1301. }
  1302. }
  1303. $icalEvents[] = array(
  1304. 'title' => $eventName,
  1305. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1306. 'imagetypeFilter' => 'ical',
  1307. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1308. 'start' => $startDate,
  1309. 'end' => $endDate,
  1310. 'bgColor' => str_replace('text', 'bg', $extraClass),
  1311. );
  1312. $calendarTimes = $calendarTimes + 1;
  1313. }
  1314. }
  1315. }
  1316. }
  1317. }
  1318. $calendarSources['ical'] = $icalEvents;
  1319. }
  1320. $calendarSources['events'] = $calendarItems;
  1321. return ($calendarSources) ? $calendarSources : false;
  1322. }
  1323. function calendarDaysCheck($entryStart, $entryEnd)
  1324. {
  1325. $success = false;
  1326. $entryStart = intval($entryStart);
  1327. $entryEnd = intval($entryEnd);
  1328. if ($entryStart >= 0 && $entryEnd <= 0) {
  1329. $success = true;
  1330. }
  1331. return $success;
  1332. }
  1333. function getCalenderRepeat($value)
  1334. {
  1335. //FREQ=DAILY
  1336. //RRULE:FREQ=WEEKLY;BYDAY=TH
  1337. $first = explode('=', $value);
  1338. if (count($first) > 1) {
  1339. $second = explode(';', $first[1]);
  1340. } else {
  1341. return $value;
  1342. }
  1343. if ($second) {
  1344. return $second[0];
  1345. } else {
  1346. return $first[1];
  1347. }
  1348. }
  1349. function getCalenderRepeatUntil($value)
  1350. {
  1351. $first = explode('UNTIL=', $value);
  1352. if (count($first) > 1) {
  1353. return $first[1];
  1354. } else {
  1355. return false;
  1356. }
  1357. }
  1358. function getCalenderRepeatCount($value)
  1359. {
  1360. $first = explode('COUNT=', $value);
  1361. if (count($first) > 1) {
  1362. return $first[1];
  1363. } else {
  1364. return false;
  1365. }
  1366. }
  1367. function getSonarrCalendar($array, $number)
  1368. {
  1369. $array = json_decode($array, true);
  1370. $gotCalendar = array();
  1371. $i = 0;
  1372. foreach ($array as $child) {
  1373. $i++;
  1374. $seriesName = $child['series']['title'];
  1375. $seriesID = $child['series']['tvdbId'];
  1376. $episodeID = $child['series']['tvdbId'];
  1377. $monitored = $child['monitored'];
  1378. if (!isset($episodeID)) {
  1379. $episodeID = "";
  1380. }
  1381. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1382. $episodeAirDate = $child['airDateUtc'];
  1383. $episodeAirDate = strtotime($episodeAirDate);
  1384. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1385. if (new DateTime() < new DateTime($episodeAirDate)) {
  1386. $unaired = true;
  1387. }
  1388. if ($child['episodeNumber'] == "1") {
  1389. $episodePremier = "true";
  1390. } else {
  1391. $episodePremier = "false";
  1392. $date = new DateTime($episodeAirDate);
  1393. $date->add(new DateInterval("PT1S"));
  1394. $date->format(DateTime::ATOM);
  1395. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1396. }
  1397. $downloaded = $child['hasFile'];
  1398. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1399. $downloaded = "text-primary animated flash";
  1400. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1401. $downloaded = "text-dark";
  1402. } elseif ($downloaded == "0" && isset($unaired)) {
  1403. $downloaded = "text-info";
  1404. } elseif ($downloaded == "1") {
  1405. $downloaded = "text-success";
  1406. } else {
  1407. $downloaded = "text-danger";
  1408. }
  1409. $fanart = "/plugins/images/cache/no-np.png";
  1410. foreach ($child['series']['images'] as $image) {
  1411. if ($image['coverType'] == "fanart") {
  1412. $fanart = $image['url'];
  1413. }
  1414. }
  1415. if ($fanart !== "/plugins/images/cache/no-np.png") {
  1416. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1417. $imageURL = $fanart;
  1418. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1419. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1420. if (!file_exists($cacheFile)) {
  1421. cacheImage($imageURL, $seriesID);
  1422. unset($imageURL);
  1423. unset($cacheFile);
  1424. }
  1425. }
  1426. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1427. $details = array(
  1428. "seasonCount" => $child['series']['seasonCount'],
  1429. "status" => $child['series']['status'],
  1430. "topTitle" => $seriesName,
  1431. "bottomTitle" => $bottomTitle,
  1432. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1433. "runtime" => $child['series']['runtime'],
  1434. "image" => $fanart,
  1435. "ratings" => $child['series']['ratings']['value'],
  1436. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1437. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1438. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1439. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1440. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  1441. "genres" => $child['series']['genres'],
  1442. );
  1443. array_push($gotCalendar, array(
  1444. "id" => "Sonarr-" . $number . "-" . $i,
  1445. "title" => $seriesName,
  1446. "start" => $child['airDateUtc'],
  1447. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1448. "imagetype" => "tv " . $downloaded,
  1449. "imagetypeFilter" => "tv",
  1450. "downloadFilter" => $downloaded,
  1451. "bgColor" => str_replace('text', 'bg', $downloaded),
  1452. "details" => $details
  1453. ));
  1454. }
  1455. if ($i != 0) {
  1456. return $gotCalendar;
  1457. }
  1458. return false;
  1459. }
  1460. function getLidarrCalendar($array, $number)
  1461. {
  1462. $array = json_decode($array, true);
  1463. $gotCalendar = array();
  1464. $i = 0;
  1465. foreach ($array as $child) {
  1466. $i++;
  1467. $albumName = $child['title'];
  1468. $artistName = $child['artist']['artistName'];
  1469. $albumID = '';
  1470. $releaseDate = $child['releaseDate'];
  1471. $releaseDate = strtotime($releaseDate);
  1472. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1473. if (new DateTime() < new DateTime($releaseDate)) {
  1474. $unaired = true;
  1475. }
  1476. if (isset($child['statistics']['percentOfTracks'])) {
  1477. if ($child['statistics']['percentOfTracks'] == '100.0') {
  1478. $downloaded = '1';
  1479. } else {
  1480. $downloaded = '0';
  1481. }
  1482. } else {
  1483. $downloaded = '0';
  1484. }
  1485. if ($downloaded == "0" && isset($unaired)) {
  1486. $downloaded = "text-info";
  1487. } elseif ($downloaded == "1") {
  1488. $downloaded = "text-success";
  1489. } else {
  1490. $downloaded = "text-danger";
  1491. }
  1492. $fanart = "/plugins/images/cache/no-np.png";
  1493. foreach ($child['artist']['images'] as $image) {
  1494. if ($image['coverType'] == "fanart") {
  1495. $fanart = str_replace('http://', 'https://', $image['url']);
  1496. }
  1497. }
  1498. $details = array(
  1499. "seasonCount" => '',
  1500. "status" => '',
  1501. "topTitle" => $albumName,
  1502. "bottomTitle" => $artistName,
  1503. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1504. "runtime" => '',
  1505. "image" => $fanart,
  1506. "ratings" => $child['artist']['ratings']['value'],
  1507. "videoQuality" => "unknown",
  1508. "audioChannels" => "unknown",
  1509. "audioCodec" => "unknown",
  1510. "videoCodec" => "unknown",
  1511. "size" => "unknown",
  1512. "genres" => $child['genres'],
  1513. );
  1514. array_push($gotCalendar, array(
  1515. "id" => "Lidarr-" . $number . "-" . $i,
  1516. "title" => $artistName,
  1517. "start" => $child['releaseDate'],
  1518. "className" => "inline-popups bg-calendar calendar-item musicID--",
  1519. "imagetype" => "music " . $downloaded,
  1520. "imagetypeFilter" => "music",
  1521. "downloadFilter" => $downloaded,
  1522. "bgColor" => str_replace('text', 'bg', $downloaded),
  1523. "details" => $details,
  1524. "data" => $child
  1525. ));
  1526. }
  1527. if ($i != 0) {
  1528. return $gotCalendar;
  1529. }
  1530. return false;
  1531. }
  1532. function getRadarrCalendar($array, $number, $url)
  1533. {
  1534. $array = json_decode($array, true);
  1535. $gotCalendar = array();
  1536. $i = 0;
  1537. foreach ($array as $child) {
  1538. if (isset($child['physicalRelease'])) {
  1539. $i++;
  1540. $movieName = $child['title'];
  1541. $movieID = $child['tmdbId'];
  1542. if (!isset($movieID)) {
  1543. $movieID = "";
  1544. }
  1545. $physicalRelease = $child['physicalRelease'];
  1546. $physicalRelease = strtotime($physicalRelease);
  1547. $physicalRelease = date("Y-m-d", $physicalRelease);
  1548. if (new DateTime() < new DateTime($physicalRelease)) {
  1549. $notReleased = "true";
  1550. } else {
  1551. $notReleased = "false";
  1552. }
  1553. $downloaded = $child['hasFile'];
  1554. if ($downloaded == "0" && $notReleased == "true") {
  1555. $downloaded = "text-info";
  1556. } elseif ($downloaded == "1") {
  1557. $downloaded = "text-success";
  1558. } else {
  1559. $downloaded = "text-danger";
  1560. }
  1561. $banner = "/plugins/images/cache/no-np.png";
  1562. foreach ($child['images'] as $image) {
  1563. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1564. $url = rtrim($url, '/'); //remove trailing slash
  1565. $imageUrl = $image['url'];
  1566. $urlParts = explode("/", $url);
  1567. $imageParts = explode("/", $image['url']);
  1568. if ($imageParts[1] == end($urlParts)) {
  1569. unset($imageParts[1]);
  1570. $imageUrl = implode("/", $imageParts);
  1571. }
  1572. $banner = $url . $imageUrl;
  1573. }
  1574. }
  1575. if ($banner !== "/plugins/images/cache/no-np.png") {
  1576. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1577. $imageURL = $banner;
  1578. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1579. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1580. if (!file_exists($cacheFile)) {
  1581. cacheImage($imageURL, $movieID);
  1582. unset($imageURL);
  1583. unset($cacheFile);
  1584. }
  1585. }
  1586. $alternativeTitles = "";
  1587. foreach ($child['alternativeTitles'] as $alternative) {
  1588. $alternativeTitles .= $alternative['title'] . ', ';
  1589. }
  1590. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1591. $details = array(
  1592. "topTitle" => $movieName,
  1593. "bottomTitle" => $alternativeTitles,
  1594. "status" => $child['status'],
  1595. "overview" => $child['overview'],
  1596. "runtime" => $child['runtime'],
  1597. "image" => $banner,
  1598. "ratings" => $child['ratings']['value'],
  1599. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1600. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1601. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1602. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1603. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1604. "genres" => $child['genres'],
  1605. "year" => isset($child['year']) ? $child['year'] : '',
  1606. "studio" => isset($child['studio']) ? $child['studio'] : '',
  1607. );
  1608. array_push($gotCalendar, array(
  1609. "id" => "Radarr-" . $number . "-" . $i,
  1610. "title" => $movieName,
  1611. "start" => $physicalRelease,
  1612. "className" => "inline-popups bg-calendar movieID--" . $movieID,
  1613. "imagetype" => "film " . $downloaded,
  1614. "imagetypeFilter" => "film",
  1615. "downloadFilter" => $downloaded,
  1616. "bgColor" => str_replace('text', 'bg', $downloaded),
  1617. "details" => $details
  1618. ));
  1619. }
  1620. }
  1621. if ($i != 0) {
  1622. return $gotCalendar;
  1623. }
  1624. return false;
  1625. }
  1626. function getCouchCalendar($array, $number)
  1627. {
  1628. $api = json_decode($array, true);
  1629. $gotCalendar = array();
  1630. $i = 0;
  1631. foreach ($api['movies'] as $child) {
  1632. if ($child['status'] == "active" || $child['status'] == "done") {
  1633. $i++;
  1634. $movieName = $child['info']['original_title'];
  1635. $movieID = $child['info']['tmdb_id'];
  1636. if (!isset($movieID)) {
  1637. $movieID = "";
  1638. }
  1639. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1640. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1641. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1642. $physicalRelease = strtotime($physicalRelease);
  1643. $physicalRelease = date("Y-m-d", $physicalRelease);
  1644. if (new DateTime() < new DateTime($physicalRelease)) {
  1645. $notReleased = "true";
  1646. } else {
  1647. $notReleased = "false";
  1648. }
  1649. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1650. if ($downloaded == "0" && $notReleased == "true") {
  1651. $downloaded = "text-info";
  1652. } elseif ($downloaded == "1") {
  1653. $downloaded = "text-success";
  1654. } else {
  1655. $downloaded = "text-danger";
  1656. }
  1657. if (!empty($child['info']['images']['backdrop_original'])) {
  1658. $banner = $child['info']['images']['backdrop_original'][0];
  1659. } elseif (!empty($child['info']['images']['backdrop'])) {
  1660. $banner = $child['info']['images']['backdrop_original'][0];
  1661. } else {
  1662. $banner = "/plugins/images/cache/no-np.png";
  1663. }
  1664. if ($banner !== "/plugins/images/cache/no-np.png") {
  1665. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1666. $imageURL = $banner;
  1667. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1668. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1669. if (!file_exists($cacheFile)) {
  1670. cacheImage($imageURL, $movieID);
  1671. unset($imageURL);
  1672. unset($cacheFile);
  1673. }
  1674. }
  1675. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1676. $details = array(
  1677. "topTitle" => $movieName,
  1678. "bottomTitle" => $child['info']['tagline'],
  1679. "status" => $child['status'],
  1680. "overview" => $child['info']['plot'],
  1681. "runtime" => $child['info']['runtime'],
  1682. "image" => $banner,
  1683. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1684. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1685. "audioChannels" => "",
  1686. "audioCodec" => "",
  1687. "videoCodec" => "",
  1688. "genres" => $child['info']['genres'],
  1689. "year" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1690. "studio" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1691. );
  1692. array_push($gotCalendar, array(
  1693. "id" => "CouchPotato-" . $number . "-" . $i,
  1694. "title" => $movieName,
  1695. "start" => $physicalRelease,
  1696. "className" => "inline-popups bg-calendar calendar-item movieID--" . $movieID,
  1697. "imagetype" => "film " . $downloaded,
  1698. "imagetypeFilter" => "film",
  1699. "downloadFilter" => $downloaded,
  1700. "bgColor" => str_replace('text', 'bg', $downloaded),
  1701. "details" => $details
  1702. ));
  1703. }
  1704. }
  1705. if ($i != 0) {
  1706. return $gotCalendar;
  1707. }
  1708. return false;
  1709. }
  1710. function getSickrageCalendarWanted($array, $number)
  1711. {
  1712. $array = json_decode($array, true);
  1713. $gotCalendar = array();
  1714. $i = 0;
  1715. foreach ($array['data']['missed'] as $child) {
  1716. $i++;
  1717. $seriesName = $child['show_name'];
  1718. $seriesID = $child['tvdbid'];
  1719. $episodeID = $child['tvdbid'];
  1720. $episodeAirDate = $child['airdate'];
  1721. $episodeAirDateTime = explode(" ", $child['airs']);
  1722. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1723. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1724. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1725. if (new DateTime() < new DateTime($episodeAirDate)) {
  1726. $unaired = true;
  1727. }
  1728. $downloaded = "0";
  1729. if ($downloaded == "0" && isset($unaired)) {
  1730. $downloaded = "text-info";
  1731. } elseif ($downloaded == "1") {
  1732. $downloaded = "text-success";
  1733. } else {
  1734. $downloaded = "text-danger";
  1735. }
  1736. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1737. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1738. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1739. $fanart = "/plugins/images/cache/no-np.png";
  1740. if (file_exists($cacheFile)) {
  1741. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1742. unset($cacheFile);
  1743. }
  1744. $details = array(
  1745. "seasonCount" => "",
  1746. "status" => $child['show_status'],
  1747. "topTitle" => $seriesName,
  1748. "bottomTitle" => $bottomTitle,
  1749. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1750. "runtime" => "",
  1751. "image" => $fanart,
  1752. "ratings" => "",
  1753. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1754. "audioChannels" => "",
  1755. "audioCodec" => "",
  1756. "videoCodec" => "",
  1757. "size" => "",
  1758. "genres" => "",
  1759. );
  1760. array_push($gotCalendar, array(
  1761. "id" => "Sick-" . $number . "-Miss-" . $i,
  1762. "title" => $seriesName,
  1763. "start" => $episodeAirDate,
  1764. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1765. "imagetype" => "tv " . $downloaded,
  1766. "imagetypeFilter" => "tv",
  1767. "downloadFilter" => $downloaded,
  1768. "bgColor" => str_replace('text', 'bg', $downloaded),
  1769. "details" => $details,
  1770. ));
  1771. }
  1772. foreach ($array['data']['today'] as $child) {
  1773. $i++;
  1774. $seriesName = $child['show_name'];
  1775. $seriesID = $child['tvdbid'];
  1776. $episodeID = $child['tvdbid'];
  1777. $episodeAirDate = $child['airdate'];
  1778. $episodeAirDateTime = explode(" ", $child['airs']);
  1779. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1780. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1781. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1782. if (new DateTime() < new DateTime($episodeAirDate)) {
  1783. $unaired = true;
  1784. }
  1785. $downloaded = "0";
  1786. if ($downloaded == "0" && isset($unaired)) {
  1787. $downloaded = "text-info";
  1788. } elseif ($downloaded == "1") {
  1789. $downloaded = "text-success";
  1790. } else {
  1791. $downloaded = "text-danger";
  1792. }
  1793. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1794. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1795. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1796. $fanart = "/plugins/images/cache/no-np.png";
  1797. if (file_exists($cacheFile)) {
  1798. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1799. unset($cacheFile);
  1800. }
  1801. $details = array(
  1802. "seasonCount" => "",
  1803. "status" => $child['show_status'],
  1804. "topTitle" => $seriesName,
  1805. "bottomTitle" => $bottomTitle,
  1806. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1807. "runtime" => "",
  1808. "image" => $fanart,
  1809. "ratings" => "",
  1810. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1811. "audioChannels" => "",
  1812. "audioCodec" => "",
  1813. "videoCodec" => "",
  1814. "size" => "",
  1815. "genres" => "",
  1816. );
  1817. array_push($gotCalendar, array(
  1818. "id" => "Sick-" . $number . "-Today-" . $i,
  1819. "title" => $seriesName,
  1820. "start" => $episodeAirDate,
  1821. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1822. "imagetype" => "tv " . $downloaded,
  1823. "imagetypeFilter" => "tv",
  1824. "downloadFilter" => $downloaded,
  1825. "bgColor" => str_replace('text', 'bg', $downloaded),
  1826. "details" => $details,
  1827. ));
  1828. }
  1829. foreach ($array['data']['soon'] as $child) {
  1830. $i++;
  1831. $seriesName = $child['show_name'];
  1832. $seriesID = $child['tvdbid'];
  1833. $episodeID = $child['tvdbid'];
  1834. $episodeAirDate = $child['airdate'];
  1835. $episodeAirDateTime = explode(" ", $child['airs']);
  1836. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1837. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1838. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1839. if (new DateTime() < new DateTime($episodeAirDate)) {
  1840. $unaired = true;
  1841. }
  1842. $downloaded = "0";
  1843. if ($downloaded == "0" && isset($unaired)) {
  1844. $downloaded = "text-info";
  1845. } elseif ($downloaded == "1") {
  1846. $downloaded = "text-success";
  1847. } else {
  1848. $downloaded = "text-danger";
  1849. }
  1850. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1851. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1852. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1853. $fanart = "/plugins/images/cache/no-np.png";
  1854. if (file_exists($cacheFile)) {
  1855. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1856. unset($cacheFile);
  1857. }
  1858. $details = array(
  1859. "seasonCount" => "",
  1860. "status" => $child['show_status'],
  1861. "topTitle" => $seriesName,
  1862. "bottomTitle" => $bottomTitle,
  1863. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1864. "runtime" => "",
  1865. "image" => $fanart,
  1866. "ratings" => "",
  1867. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1868. "audioChannels" => "",
  1869. "audioCodec" => "",
  1870. "videoCodec" => "",
  1871. "size" => "",
  1872. "genres" => "",
  1873. );
  1874. array_push($gotCalendar, array(
  1875. "id" => "Sick-" . $number . "-Soon-" . $i,
  1876. "title" => $seriesName,
  1877. "start" => $episodeAirDate,
  1878. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1879. "imagetype" => "tv " . $downloaded,
  1880. "imagetypeFilter" => "tv",
  1881. "downloadFilter" => $downloaded,
  1882. "bgColor" => str_replace('text', 'bg', $downloaded),
  1883. "details" => $details,
  1884. ));
  1885. }
  1886. foreach ($array['data']['later'] as $child) {
  1887. $i++;
  1888. $seriesName = $child['show_name'];
  1889. $seriesID = $child['tvdbid'];
  1890. $episodeID = $child['tvdbid'];
  1891. $episodeAirDate = $child['airdate'];
  1892. $episodeAirDateTime = explode(" ", $child['airs']);
  1893. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1894. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1895. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1896. if (new DateTime() < new DateTime($episodeAirDate)) {
  1897. $unaired = true;
  1898. }
  1899. $downloaded = "0";
  1900. if ($downloaded == "0" && isset($unaired)) {
  1901. $downloaded = "text-info";
  1902. } elseif ($downloaded == "1") {
  1903. $downloaded = "text-success";
  1904. } else {
  1905. $downloaded = "text-danger";
  1906. }
  1907. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1908. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1909. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1910. $fanart = "/plugins/images/cache/no-np.png";
  1911. if (file_exists($cacheFile)) {
  1912. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1913. unset($cacheFile);
  1914. }
  1915. $details = array(
  1916. "seasonCount" => "",
  1917. "status" => $child['show_status'],
  1918. "topTitle" => $seriesName,
  1919. "bottomTitle" => $bottomTitle,
  1920. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1921. "runtime" => "",
  1922. "image" => $fanart,
  1923. "ratings" => "",
  1924. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1925. "audioChannels" => "",
  1926. "audioCodec" => "",
  1927. "videoCodec" => "",
  1928. "size" => "",
  1929. "genres" => "",
  1930. );
  1931. array_push($gotCalendar, array(
  1932. "id" => "Sick-" . $number . "-Later-" . $i,
  1933. "title" => $seriesName,
  1934. "start" => $episodeAirDate,
  1935. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1936. "imagetype" => "tv " . $downloaded,
  1937. "imagetypeFilter" => "tv",
  1938. "downloadFilter" => $downloaded,
  1939. "bgColor" => str_replace('text', 'bg', $downloaded),
  1940. "details" => $details,
  1941. ));
  1942. }
  1943. if ($i != 0) {
  1944. return $gotCalendar;
  1945. }
  1946. return false;
  1947. }
  1948. function getSickrageCalendarHistory($array, $number)
  1949. {
  1950. $array = json_decode($array, true);
  1951. $gotCalendar = array();
  1952. $i = 0;
  1953. foreach ($array['data'] as $child) {
  1954. $i++;
  1955. $seriesName = $child['show_name'];
  1956. $seriesID = $child['tvdbid'];
  1957. $episodeID = $child['tvdbid'];
  1958. $episodeAirDate = $child['date'];
  1959. $downloaded = "text-success";
  1960. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  1961. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1962. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1963. $fanart = "/plugins/images/cache/no-np.png";
  1964. if (file_exists($cacheFile)) {
  1965. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1966. unset($cacheFile);
  1967. }
  1968. $details = array(
  1969. "seasonCount" => "",
  1970. "status" => $child['status'],
  1971. "topTitle" => $seriesName,
  1972. "bottomTitle" => $bottomTitle,
  1973. "overview" => '',
  1974. "runtime" => isset($child['series']['runtime']) ? $child['series']['runtime'] : 30,
  1975. "image" => $fanart,
  1976. "ratings" => isset($child['series']['ratings']['value']) ? $child['series']['ratings']['value'] : "unknown",
  1977. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  1978. "audioChannels" => "",
  1979. "audioCodec" => "",
  1980. "videoCodec" => "",
  1981. "size" => "",
  1982. "genres" => "",
  1983. );
  1984. array_push($gotCalendar, array(
  1985. "id" => "Sick-" . $number . "-History-" . $i,
  1986. "title" => $seriesName,
  1987. "start" => $episodeAirDate,
  1988. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1989. "imagetype" => "tv " . $downloaded,
  1990. "imagetypeFilter" => "tv",
  1991. "downloadFilter" => $downloaded,
  1992. "bgColor" => str_replace('text', 'bg', $downloaded),
  1993. "details" => $details,
  1994. ));
  1995. }
  1996. if ($i != 0) {
  1997. return $gotCalendar;
  1998. }
  1999. return false;
  2000. }
  2001. function ombiAPI($array)
  2002. {
  2003. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  2004. }
  2005. function ombiImport($type = null)
  2006. {
  2007. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  2008. try {
  2009. $url = qualifyURL($GLOBALS['ombiURL']);
  2010. $headers = array(
  2011. "Accept" => "application/json",
  2012. "Content-Type" => "application/json",
  2013. "Apikey" => $GLOBALS['ombiToken']
  2014. );
  2015. $options = (localURL($url)) ? array('verify' => false) : array();
  2016. switch ($type) {
  2017. case 'emby':
  2018. case 'emby_local':
  2019. case 'emby_connect':
  2020. case 'emby_all':
  2021. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  2022. break;
  2023. case 'plex':
  2024. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  2025. break;
  2026. default:
  2027. return false;
  2028. break;
  2029. }
  2030. if ($response->success) {
  2031. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  2032. return true;
  2033. } else {
  2034. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  2035. return false;
  2036. }
  2037. } catch (Requests_Exception $e) {
  2038. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2039. return false;
  2040. };
  2041. }
  2042. return false;
  2043. }
  2044. function ombiAction($id, $action, $type, $fullArray = null)
  2045. {
  2046. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2047. $url = qualifyURL($GLOBALS['ombiURL']);
  2048. $headers = array(
  2049. "Accept" => "application/json",
  2050. "Content-Type" => "application/json",
  2051. "Apikey" => $GLOBALS['ombiToken']
  2052. );
  2053. $data = array(
  2054. 'id' => $id,
  2055. );
  2056. switch ($type) {
  2057. case 'season':
  2058. case 'tv':
  2059. $type = 'tv';
  2060. $add = array(
  2061. 'tvDbId' => $id,
  2062. 'requestAll' => ombiTVDefault('all'),
  2063. 'latestSeason' => ombiTVDefault('last'),
  2064. 'firstSeason' => ombiTVDefault('first')
  2065. );
  2066. break;
  2067. default:
  2068. $type = 'movie';
  2069. $add = array("theMovieDbId" => (int)$id);
  2070. break;
  2071. }
  2072. $success['head'] = $headers;
  2073. $success['act'] = $action;
  2074. $success['data'] = $data;
  2075. $success['add'] = $add;
  2076. $success['type'] = $type;
  2077. try {
  2078. $options = (localURL($url)) ? array('verify' => false) : array();
  2079. switch ($action) {
  2080. case 'add':
  2081. if (isset($_COOKIE['Auth'])) {
  2082. $headers = array(
  2083. "Accept" => "application/json",
  2084. "Content-Type" => "application/json",
  2085. "Authorization" => "Bearer " . $_COOKIE['Auth']
  2086. );
  2087. $success['head'] = $headers;
  2088. } else {
  2089. return false;
  2090. }
  2091. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  2092. break;
  2093. default:
  2094. if (qualifyRequest(1)) {
  2095. switch ($action) {
  2096. case 'approve':
  2097. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  2098. break;
  2099. case 'available':
  2100. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  2101. break;
  2102. case 'unavailable':
  2103. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  2104. break;
  2105. case 'deny':
  2106. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  2107. break;
  2108. case 'delete':
  2109. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  2110. break;
  2111. default:
  2112. return false;
  2113. }
  2114. }
  2115. break;
  2116. }
  2117. $success['api'] = $response;
  2118. $success['bd'] = $response->body;
  2119. $success['hd'] = $response->headers;
  2120. if ($response->success) {
  2121. $success['ok'] = true;
  2122. }
  2123. } catch (Requests_Exception $e) {
  2124. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2125. };
  2126. }
  2127. return isset($success['ok']) ? $success : false;
  2128. }
  2129. function getOmbiRequests($type = "both", $limit = 50)
  2130. {
  2131. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2132. $url = qualifyURL($GLOBALS['ombiURL']);
  2133. $headers = array(
  2134. "Accept" => "application/json",
  2135. "Apikey" => $GLOBALS['ombiToken'],
  2136. );
  2137. $requests = array();
  2138. try {
  2139. $options = (localURL($url)) ? array('verify' => false) : array();
  2140. switch ($type) {
  2141. case 'movie':
  2142. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2143. break;
  2144. case 'tv':
  2145. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2146. break;
  2147. default:
  2148. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2149. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2150. break;
  2151. }
  2152. if ($movie->success || $tv->success) {
  2153. if (isset($movie)) {
  2154. $movie = json_decode($movie->body, true);
  2155. //$movie = array_reverse($movie);
  2156. foreach ($movie as $key => $value) {
  2157. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2158. if ($proceed) {
  2159. $requests[] = array(
  2160. 'test' => $value,
  2161. 'id' => $value['theMovieDbId'],
  2162. 'title' => $value['title'],
  2163. 'overview' => $value['overview'],
  2164. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
  2165. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2166. 'approved' => $value['approved'],
  2167. 'available' => $value['available'],
  2168. 'denied' => $value['denied'],
  2169. 'deniedReason' => $value['deniedReason'],
  2170. 'user' => $value['requestedUser']['userName'],
  2171. 'userAlias' => $value['requestedUser']['userAlias'],
  2172. 'request_id' => $value['id'],
  2173. 'request_date' => $value['requestedDate'],
  2174. 'release_date' => $value['releaseDate'],
  2175. 'type' => 'movie',
  2176. 'icon' => 'mdi mdi-filmstrip',
  2177. 'color' => 'palette-Deep-Purple-900 bg white',
  2178. );
  2179. }
  2180. }
  2181. }
  2182. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2183. $tv = json_decode($tv->body, true);
  2184. foreach ($tv as $key => $value) {
  2185. if (count($value['childRequests']) > 0) {
  2186. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2187. if ($proceed) {
  2188. $requests[] = array(
  2189. 'test' => $value,
  2190. 'id' => $value['tvDbId'],
  2191. 'title' => $value['title'],
  2192. 'overview' => $value['overview'],
  2193. 'poster' => $value['posterPath'],
  2194. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2195. 'approved' => $value['childRequests'][0]['approved'],
  2196. 'available' => $value['childRequests'][0]['available'],
  2197. 'denied' => $value['childRequests'][0]['denied'],
  2198. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2199. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2200. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2201. 'request_id' => $value['id'],
  2202. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2203. 'release_date' => $value['releaseDate'],
  2204. 'type' => 'tv',
  2205. 'icon' => 'mdi mdi-television',
  2206. 'color' => 'grayish-blue-bg',
  2207. );
  2208. }
  2209. }
  2210. }
  2211. }
  2212. //sort here
  2213. usort($requests, function ($item1, $item2) {
  2214. if ($item1['request_date'] == $item2['request_date']) {
  2215. return 0;
  2216. }
  2217. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2218. });
  2219. }
  2220. } catch (Requests_Exception $e) {
  2221. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2222. };
  2223. }
  2224. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2225. return $api;
  2226. }
  2227. function testAPIConnection($array)
  2228. {
  2229. switch ($array['data']['action']) {
  2230. case 'ombi':
  2231. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2232. $url = qualifyURL($GLOBALS['ombiURL']);
  2233. $url = $url . "/api/v1/Status/info";
  2234. $headers = array(
  2235. "Accept" => "application/json",
  2236. "Content-Type" => "application/json",
  2237. "Apikey" => $GLOBALS['ombiToken']
  2238. );
  2239. try {
  2240. $options = (localURL($url)) ? array('verify' => false) : array();
  2241. $response = Requests::get($url, $headers, $options);
  2242. if ($response->success) {
  2243. return true;
  2244. } else {
  2245. return $response->body;
  2246. }
  2247. } catch (Requests_Exception $e) {
  2248. return $e->getMessage();
  2249. };
  2250. } else {
  2251. return 'URL and/or Token not setup';
  2252. }
  2253. break;
  2254. case 'plex':
  2255. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2256. $url = qualifyURL($GLOBALS['plexURL']);
  2257. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2258. try {
  2259. $options = (localURL($url)) ? array('verify' => false) : array();
  2260. $response = Requests::get($url, array(), $options);
  2261. libxml_use_internal_errors(true);
  2262. if ($response->success) {
  2263. return true;
  2264. }
  2265. } catch (Requests_Exception $e) {
  2266. return $e->getMessage();
  2267. };
  2268. } else {
  2269. return 'URL and/or Token not setup';
  2270. }
  2271. break;
  2272. case 'emby':
  2273. break;
  2274. case 'sonarr':
  2275. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2276. $sonarrs = array();
  2277. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2278. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2279. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2280. foreach ($sonarrURLList as $key => $value) {
  2281. $sonarrs[$key] = array(
  2282. 'url' => $value,
  2283. 'token' => $sonarrTokenList[$key]
  2284. );
  2285. }
  2286. foreach ($sonarrs as $key => $value) {
  2287. try {
  2288. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2289. $result = json_decode($sonarr->getSystemStatus(), true);
  2290. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2291. } catch (Exception $e) {
  2292. return strip($e->getMessage());
  2293. }
  2294. }
  2295. }
  2296. } else {
  2297. return 'URL/s and/or Token/s not setup';
  2298. }
  2299. break;
  2300. case 'lidarr':
  2301. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2302. $sonarrs = array();
  2303. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2304. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2305. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2306. foreach ($sonarrURLList as $key => $value) {
  2307. $sonarrs[$key] = array(
  2308. 'url' => $value,
  2309. 'token' => $sonarrTokenList[$key]
  2310. );
  2311. }
  2312. foreach ($sonarrs as $key => $value) {
  2313. try {
  2314. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2315. $result = json_decode($sonarr->getSystemStatus(), true);
  2316. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2317. } catch (Exception $e) {
  2318. return $e->getMessage();
  2319. }
  2320. }
  2321. }
  2322. } else {
  2323. return 'URL/s and/or Token/s not setup';
  2324. }
  2325. break;
  2326. case 'radarr':
  2327. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2328. $sonarrs = array();
  2329. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2330. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2331. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2332. foreach ($sonarrURLList as $key => $value) {
  2333. $sonarrs[$key] = array(
  2334. 'url' => $value,
  2335. 'token' => $sonarrTokenList[$key]
  2336. );
  2337. }
  2338. foreach ($sonarrs as $key => $value) {
  2339. try {
  2340. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2341. $result = json_decode($sonarr->getSystemStatus(), true);
  2342. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2343. } catch (Exception $e) {
  2344. return $e->getMessage();
  2345. }
  2346. }
  2347. }
  2348. } else {
  2349. return 'URL/s and/or Token/s not setup';
  2350. }
  2351. break;
  2352. case 'sabnzbd':
  2353. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2354. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2355. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2356. try {
  2357. $options = (localURL($url)) ? array('verify' => false) : array();
  2358. $response = Requests::get($url, array(), $options);
  2359. if ($response->success) {
  2360. return true;
  2361. }
  2362. } catch (Requests_Exception $e) {
  2363. return $e->getMessage();
  2364. };
  2365. } else {
  2366. return 'URL and/or Token not setup';
  2367. }
  2368. break;
  2369. case 'nzbget':
  2370. if (!empty($GLOBALS['nzbgetURL'])) {
  2371. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2372. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  2373. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  2374. } else {
  2375. $url = $url . '/jsonrpc/listgroups';
  2376. }
  2377. try {
  2378. $options = (localURL($url)) ? array('verify' => false) : array();
  2379. $response = Requests::get($url, array(), $options);
  2380. if ($response->success) {
  2381. return true;
  2382. }
  2383. } catch (Requests_Exception $e) {
  2384. return $e->getMessage();
  2385. };
  2386. } else {
  2387. return 'URL and/or Username/Password not setup';
  2388. }
  2389. break;
  2390. case 'deluge':
  2391. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2392. try {
  2393. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2394. $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');
  2395. return true;
  2396. } catch (Exception $e) {
  2397. return $e->getMessage();
  2398. }
  2399. } else {
  2400. return 'URL and/or Password not setup';
  2401. }
  2402. break;
  2403. case 'rtorrent':
  2404. if (!empty($GLOBALS['rTorrentURL'])) {
  2405. try {
  2406. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  2407. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2408. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2409. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  2410. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2411. $options = (localURL($url)) ? array('verify' => false) : array();
  2412. $data = xmlrpc_encode_request("system.listMethods", null);
  2413. $response = Requests::post($url, array(), $data, $options);
  2414. if ($response->success) {
  2415. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2416. if (count($methods) !== 0) {
  2417. return true;
  2418. }
  2419. }
  2420. return false;
  2421. } catch
  2422. (Requests_Exception $e) {
  2423. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2424. return $e->getMessage();
  2425. };
  2426. }
  2427. break;
  2428. case 'ldap_login':
  2429. $username = $array['data']['data']['username'];
  2430. $password = $array['data']['data']['password'];
  2431. if (empty($username) || empty($password)) {
  2432. return 'Missing Username or Password';
  2433. }
  2434. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2435. $ad = new \Adldap\Adldap();
  2436. // Create a configuration array.
  2437. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2438. $i = 0;
  2439. foreach ($ldapServers as $key => $value) {
  2440. // Calculate parts
  2441. $digest = parse_url(trim($value));
  2442. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2443. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2444. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2445. // Reassign
  2446. $ldapHosts[] = $host;
  2447. $ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
  2448. if ($i == 0) {
  2449. $ldapPort = $port;
  2450. }
  2451. $i++;
  2452. }
  2453. $config = [
  2454. // Mandatory Configuration Options
  2455. 'hosts' => $ldapHosts,
  2456. 'base_dn' => $GLOBALS['authBaseDN'],
  2457. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  2458. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  2459. // Optional Configuration Options
  2460. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  2461. 'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
  2462. 'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
  2463. 'port' => $ldapPort,
  2464. 'follow_referrals' => false,
  2465. 'use_ssl' => false,
  2466. 'use_tls' => false,
  2467. 'version' => 3,
  2468. 'timeout' => 5,
  2469. // Custom LDAP Options
  2470. 'custom_options' => [
  2471. // See: http://php.net/ldap_set_option
  2472. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  2473. ]
  2474. ];
  2475. // Add a connection provider to Adldap.
  2476. $ad->addProvider($config);
  2477. try {
  2478. // If a successful connection is made to your server, the provider will be returned.
  2479. $provider = $ad->connect();
  2480. //prettyPrint($provider);
  2481. if ($provider->auth()->attempt($username, $password, true)) {
  2482. // Passed.
  2483. $user = $provider->search()->find($username);
  2484. //return $user->getFirstAttribute('cn');
  2485. //return $user->getGroups(['cn']);
  2486. //return $user;
  2487. //return $user->getUserPrincipalName();
  2488. //return $user->getGroups(['cn']);
  2489. return true;
  2490. } else {
  2491. // Failed.
  2492. return 'Username/Password Failed to authenticate';
  2493. }
  2494. } catch (\Adldap\Auth\BindException $e) {
  2495. $detailedError = $e->getDetailedError();
  2496. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  2497. return $detailedError->getErrorMessage();
  2498. // There was an issue binding / connecting to the server.
  2499. } catch (Adldap\Auth\UsernameRequiredException $e) {
  2500. $detailedError = $e->getDetailedError();
  2501. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  2502. return $detailedError->getErrorMessage();
  2503. // The user didn't supply a username.
  2504. } catch (Adldap\Auth\PasswordRequiredException $e) {
  2505. $detailedError = $e->getDetailedError();
  2506. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  2507. return $detailedError->getErrorMessage();
  2508. // The user didn't supply a password.
  2509. }
  2510. }
  2511. break;
  2512. case 'ldap':
  2513. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2514. $ad = new \Adldap\Adldap();
  2515. // Create a configuration array.
  2516. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2517. $i = 0;
  2518. foreach ($ldapServers as $key => $value) {
  2519. // Calculate parts
  2520. $digest = parse_url(trim($value));
  2521. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2522. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2523. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2524. // Reassign
  2525. $ldapHosts[] = $host;
  2526. if ($i == 0) {
  2527. $ldapPort = $port;
  2528. }
  2529. $i++;
  2530. }
  2531. $config = [
  2532. // Mandatory Configuration Options
  2533. 'hosts' => $ldapHosts,
  2534. 'base_dn' => $GLOBALS['authBaseDN'],
  2535. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  2536. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  2537. // Optional Configuration Options
  2538. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  2539. 'account_prefix' => '',
  2540. 'account_suffix' => '',
  2541. 'port' => $ldapPort,
  2542. 'follow_referrals' => false,
  2543. 'use_ssl' => false,
  2544. 'use_tls' => false,
  2545. 'version' => 3,
  2546. 'timeout' => 5,
  2547. // Custom LDAP Options
  2548. 'custom_options' => [
  2549. // See: http://php.net/ldap_set_option
  2550. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  2551. ]
  2552. ];
  2553. // Add a connection provider to Adldap.
  2554. $ad->addProvider($config);
  2555. try {
  2556. // If a successful connection is made to your server, the provider will be returned.
  2557. $provider = $ad->connect();
  2558. } catch (\Adldap\Auth\BindException $e) {
  2559. $detailedError = $e->getDetailedError();
  2560. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
  2561. return $detailedError->getErrorMessage();
  2562. // There was an issue binding / connecting to the server.
  2563. }
  2564. return ($provider) ? true : false;
  2565. }
  2566. return false;
  2567. break;
  2568. default :
  2569. return false;
  2570. }
  2571. return false;
  2572. }