homepage-connect-functions.php 85 KB

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