4
0

homepage-connect-functions.php 81 KB

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