homepage-connect-functions.php 79 KB

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