homepage-connect-functions.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. <?php
  2. function homepageConnect($array){
  3. switch ($array['data']['action']) {
  4. case 'getPlexStreams':
  5. return plexConnect('streams');
  6. break;
  7. case 'getPlexRecent':
  8. return plexConnect('recent');
  9. break;
  10. case 'getPlexMetadata':
  11. return plexConnect('metadata',$array['data']['key']);
  12. break;
  13. case 'getPlexSearch':
  14. return plexConnect('search',$array['data']['query']);
  15. break;
  16. case 'getPlexPlaylists':
  17. return getPlexPlaylists();
  18. break;
  19. case 'getEmbyStreams':
  20. return embyConnect('streams');
  21. break;
  22. case 'getEmbyRecent':
  23. return embyConnect('recent');
  24. break;
  25. case 'getEmbyMetadata':
  26. return embyConnect('metadata',$array['data']['key'],true);
  27. break;
  28. case 'getSabnzbd':
  29. return sabnzbdConnect();
  30. break;
  31. case 'getNzbget':
  32. return nzbgetConnect();
  33. break;
  34. case 'getTransmission':
  35. return transmissionConnect();
  36. break;
  37. case 'getqBittorrent':
  38. return qBittorrentConnect();
  39. break;
  40. case 'getDeluge':
  41. return delugeConnect();
  42. break;
  43. case 'getCalendar':
  44. return getCalendar();
  45. break;
  46. case 'getRequests':
  47. return getOmbiRequests();
  48. break;
  49. default:
  50. # code...
  51. break;
  52. }
  53. }
  54. function streamType($value){
  55. if($value == "transcode" || $value == "Transcode"){
  56. return "Transcode";
  57. }elseif($value == "copy" || $value == "DirectStream"){
  58. return "Direct Stream";
  59. }elseif($value == "directplay" || $value == "DirectPlay"){
  60. return "Direct Play";
  61. }else{
  62. return "Direct Play";
  63. }
  64. }
  65. function resolveEmbyItem($itemDetails) {
  66. // Grab Each item info from Emby (extra call)
  67. $id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
  68. $url = qualifyURL($GLOBALS['embyURL']);
  69. $url = $url.'/Items?Ids='.$id.'&api_key='.$GLOBALS['embyToken'].'&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  70. try{
  71. $options = (localURL($url)) ? array('verify' => false ) : array();
  72. $response = Requests::get($url, array(), $options);
  73. if($response->success){
  74. $item = json_decode($response->body,true)['Items'][0];
  75. }
  76. }catch( Requests_Exception $e ) {
  77. return false;
  78. };
  79. // Static Height & Width
  80. $height = 300;
  81. $width = 200;
  82. $nowPlayingHeight = 675;
  83. $nowPlayingWidth = 1200;
  84. $actorHeight = 450;
  85. $actorWidth = 300;
  86. $widthOverride = 100;
  87. // Cache Directories
  88. $cacheDirectory = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  89. $cacheDirectoryWeb = 'plugins/images/cache/';
  90. // Types
  91. $embyItem['array-item'] = $item;
  92. $embyItem['array-itemdetails'] = $itemDetails;
  93. switch (@$item['Type']) {
  94. case 'Series':
  95. $embyItem['type'] = 'tv';
  96. $embyItem['title'] = $item['Name'];
  97. $embyItem['summary'] = '';
  98. $embyItem['ratingKey'] = $item['Id'];
  99. $embyItem['thumb'] = $item['Id'];
  100. $embyItem['key'] = $item['Id'] . "-list";
  101. $embyItem['nowPlayingThumb'] = $item['Id'];
  102. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  103. $embyItem['metadataKey'] = $item['Id'];
  104. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
  105. break;
  106. case 'Episode':
  107. $embyItem['type'] = 'tv';
  108. $embyItem['title'] = $item['SeriesName'];
  109. $embyItem['summary'] = '';
  110. $embyItem['ratingKey'] = $item['Id'];
  111. $embyItem['thumb'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']);
  112. $embyItem['key'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']) . "-list";
  113. $embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
  114. $embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'].'-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'].'-np' : false);
  115. $embyItem['metadataKey'] = $item['Id'];
  116. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
  117. $embyItem['nowPlayingTitle'] = @$item['SeriesName'].' - '.@$item['Name'];
  118. $embyItem['nowPlayingBottom'] = 'S'.@$item['ParentIndexNumber'].' · E'.@$item['IndexNumber'];
  119. break;
  120. case 'MusicAlbum':
  121. case 'Audio':
  122. $embyItem['type'] = 'music';
  123. $embyItem['title'] = $item['Name'];
  124. $embyItem['summary'] = '';
  125. $embyItem['ratingKey'] = $item['Id'];
  126. $embyItem['thumb'] = $item['Id'];
  127. $embyItem['key'] = $item['Id'] . "-list";
  128. $embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
  129. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  130. $embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
  131. $embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
  132. $embyItem['nowPlayingTitle'] = @$item['AlbumArtist'].' - '.@$item['Name'];
  133. $embyItem['nowPlayingBottom'] = @$item['Album'];
  134. break;
  135. case 'Movie':
  136. $embyItem['type'] = 'movie';
  137. $embyItem['title'] = $item['Name'];
  138. $embyItem['summary'] = '';
  139. $embyItem['ratingKey'] = $item['Id'];
  140. $embyItem['thumb'] = $item['Id'];
  141. $embyItem['key'] = $item['Id'] . "-list";
  142. $embyItem['nowPlayingThumb'] = $item['Id'];
  143. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  144. $embyItem['metadataKey'] = $item['Id'];
  145. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  146. $embyItem['nowPlayingTitle'] = @$item['Name'];
  147. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  148. break;
  149. case 'Video':
  150. $embyItem['type'] = 'video';
  151. $embyItem['title'] = $item['Name'];
  152. $embyItem['summary'] = '';
  153. $embyItem['ratingKey'] = $item['Id'];
  154. $embyItem['thumb'] = $item['Id'];
  155. $embyItem['key'] = $item['Id'] . "-list";
  156. $embyItem['nowPlayingThumb'] = $item['Id'];
  157. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  158. $embyItem['metadataKey'] = $item['Id'];
  159. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  160. $embyItem['nowPlayingTitle'] = @$item['Name'];
  161. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  162. break;
  163. default:
  164. return false;
  165. }
  166. $embyItem['uid'] = $item['Id'];
  167. $embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
  168. $embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
  169. $embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)$item['RunTimeTicks'];
  170. $embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
  171. $embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
  172. $embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
  173. $embyItem['id'] = $item['ServerId'];
  174. $embyItem['session'] = @$itemDetails['DeviceId'];
  175. $embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
  176. $embyItem['bandwidthType'] = 'wan';
  177. $embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
  178. $embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
  179. $embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? @(string)$itemDetails['UserName'] : "";
  180. $embyItem['userThumb'] = '';
  181. $embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
  182. $embyItem['address'] = $GLOBALS['embyTabURL'] ? '' : '';
  183. $embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'$'.randString();
  184. $embyItem['originalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'$'.randString();
  185. $embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
  186. $embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
  187. // Stream info
  188. $embyItem['userStream'] = array(
  189. 'platform' => @(string)$itemDetails['Client'],
  190. 'product' => @(string)$itemDetails['Client'],
  191. 'device' => @(string)$itemDetails['DeviceName'],
  192. 'stream' => @$itemDetails['PlayState']['PlayMethod'],
  193. 'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
  194. 'throttled' => false,
  195. 'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
  196. 'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
  197. 'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
  198. 'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
  199. 'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  200. 'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  201. 'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
  202. 'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
  203. );
  204. // Genre catch all
  205. if($item['Genres']){
  206. $genres = array();
  207. foreach ($item['Genres'] as $genre) {
  208. $genres[] = $genre;
  209. }
  210. }
  211. // Actor catch all
  212. if($item['People'] ){
  213. $actors = array();
  214. foreach ($item['People'] as $key => $value) {
  215. if(@$value['PrimaryImageTag'] && @$value['Role']){
  216. if (file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg')){ $actorImage = $cacheDirectoryWeb.(string)$value['Id'].'-cast.jpg'; }
  217. 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')) {
  218. $actorImage = 'api/?v1/image&source=emby&type=Primary&img='.(string)$value['Id'].'&height='.$actorHeight.'&width='.$actorWidth.'&key='.(string)$value['Id'].'-cast';
  219. }
  220. $actors[] = array(
  221. 'name' => (string)$value['Name'],
  222. 'role' => (string)$value['Role'],
  223. 'thumb' => $actorImage
  224. );
  225. }
  226. }
  227. }
  228. // Metadata information
  229. $embyItem['metadata'] = array(
  230. 'guid' => $item['Id'],
  231. 'summary' => @(string)$item['Overview'],
  232. 'rating' => @(string)$item['CommunityRating'],
  233. 'duration' => @(string)$item['RunTimeTicks'],
  234. 'originallyAvailableAt' => @(string)$item['PremiereDate'],
  235. 'year' => (string)$item['ProductionYear'],
  236. //'studio' => (string)$item['studio'],
  237. 'tagline' => @(string)$item['Taglines'][0],
  238. 'genres' => ($item['Genres']) ? $genres : '',
  239. 'actors' => ($item['People']) ? $actors : ''
  240. );
  241. if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')){ $embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$embyItem['nowPlayingKey'].'.jpg'; }
  242. if (file_exists($cacheDirectory.$embyItem['key'].'.jpg')){ $embyItem['imageURL'] = $cacheDirectoryWeb.$embyItem['key'].'.jpg'; }
  243. if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')) {
  244. $embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'';
  245. }
  246. if (file_exists($cacheDirectory.$embyItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['key'].'.jpg') || !file_exists($cacheDirectory.$embyItem['key'].'.jpg')) {
  247. $embyItem['imageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'';
  248. }
  249. if(!$embyItem['nowPlayingThumb'] ){ $embyItem['nowPlayingOriginalImage'] = $embyItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png"; $embyItem['nowPlayingKey'] = "no-np"; }
  250. if(!$embyItem['thumb'] ){ $embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png"; $embyItem['key'] = "no-list"; }
  251. if(isset($useImage)){ $embyItem['useImage'] = $useImage; }
  252. return $embyItem;
  253. }
  254. function resolvePlexItem($item) {
  255. // Static Height & Width
  256. $height = 300;
  257. $width = 200;
  258. $nowPlayingHeight = 675;
  259. $nowPlayingWidth = 1200;
  260. $widthOverride = 100;
  261. // Cache Directories
  262. $cacheDirectory = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  263. $cacheDirectoryWeb = 'plugins/images/cache/';
  264. // Types
  265. switch ($item['type']) {
  266. case 'season':
  267. $plexItem['type'] = 'tv';
  268. $plexItem['title'] = (string)$item['parentTitle'];
  269. $plexItem['summary'] = (string)$item['parentSummary'];
  270. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  271. $plexItem['thumb'] = (string)$item['thumb'];
  272. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  273. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  274. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  275. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  276. break;
  277. case 'episode':
  278. $plexItem['type'] = 'tv';
  279. $plexItem['title'] = (string)$item['grandparentTitle'];
  280. $plexItem['summary'] = (string)$item['title'];
  281. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  282. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  283. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  284. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  285. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  286. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
  287. $plexItem['nowPlayingBottom'] = 'S'.(string)$item['parentIndex'].' · E'.(string)$item['index'];
  288. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  289. break;
  290. case 'clip':
  291. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  292. $plexItem['type'] = 'clip';
  293. $plexItem['title'] = (string)$item['title'];
  294. $plexItem['summary'] = (string)$item['summary'];
  295. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  296. $plexItem['thumb'] = (string)$item['thumb'];
  297. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  298. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  299. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  300. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  301. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  302. break;
  303. case 'album':
  304. case 'track':
  305. $plexItem['type'] = 'music';
  306. $plexItem['title'] = (string)$item['parentTitle'].' - '.(string)$item['title'];
  307. $plexItem['summary'] = (string)$item['title'];
  308. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  309. $plexItem['thumb'] = (string)$item['thumb'];
  310. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  311. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  312. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  313. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
  314. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  315. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  316. break;
  317. default:
  318. $plexItem['type'] = 'movie';
  319. $plexItem['title'] = (string)$item['title'];
  320. $plexItem['summary'] = (string)$item['summary'];
  321. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  322. $plexItem['thumb'] = (string)$item['thumb'];
  323. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  324. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  325. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  326. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  327. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  328. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  329. }
  330. $plexItem['uid'] = (string)$item['ratingKey'];
  331. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  332. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  333. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  334. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress']- $plexItem['watched']) : '';
  335. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision']: '';
  336. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  337. $plexItem['session'] = (string)$item->Session['id'];
  338. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  339. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  340. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  341. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  342. $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? (string)$item->User['title'] : "";
  343. $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? (string)$item->User['thumb'] : "";
  344. $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth']) ) ? (string)$item->Player['address'] : "x.x.x.x";
  345. $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'];
  346. $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'$'.randString();
  347. $plexItem['originalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'$'.randString();
  348. $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
  349. $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
  350. // Stream info
  351. $plexItem['userStream'] = array(
  352. 'platform' => (string)$item->Player['platform'],
  353. 'product' => (string)$item->Player['product'],
  354. 'device' => (string)$item->Player['device'],
  355. 'stream' => (string)$item->Media->Part['decision'].($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)': ''),
  356. 'videoResolution' => (string)$item->Media['videoResolution'],
  357. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  358. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  359. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  360. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  361. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  362. 'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
  363. 'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
  364. 'container' => (string)$item->TranscodeSession['container'],
  365. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  366. );
  367. // Genre catch all
  368. if($item->Genre){
  369. $genres = array();
  370. foreach ($item->Genre as $key => $value) {
  371. $genres[] = (string)$value['tag'];
  372. }
  373. }
  374. // Actor catch all
  375. if($item->Role ){
  376. $actors = array();
  377. foreach ($item->Role as $key => $value) {
  378. if($value['thumb']){
  379. $actors[] = array(
  380. 'name' => (string)$value['tag'],
  381. 'role' => (string)$value['role'],
  382. 'thumb' => (string)$value['thumb']
  383. );
  384. }
  385. }
  386. }
  387. // Metadata information
  388. $plexItem['metadata'] = array(
  389. 'guid' => (string)$item['guid'],
  390. 'summary' => (string)$item['summary'],
  391. 'rating' => (string)$item['rating'],
  392. 'duration' => (string)$item['duration'],
  393. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  394. 'year' => (string)$item['year'],
  395. 'studio' => (string)$item['studio'],
  396. 'tagline' => (string)$item['tagline'],
  397. 'genres' => ($item->Genre) ? $genres : '',
  398. 'actors' => ($item->Role) ? $actors : ''
  399. );
  400. if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')){ $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$plexItem['nowPlayingKey'].'.jpg'; }
  401. if (file_exists($cacheDirectory.$plexItem['key'].'.jpg')){ $plexItem['imageURL'] = $cacheDirectoryWeb.$plexItem['key'].'.jpg'; }
  402. if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')) {
  403. $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'';
  404. }
  405. if (file_exists($cacheDirectory.$plexItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['key'].'.jpg') || !file_exists($cacheDirectory.$plexItem['key'].'.jpg')) {
  406. $plexItem['imageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'';
  407. }
  408. if(!$plexItem['nowPlayingThumb'] ){ $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png"; $plexItem['nowPlayingKey'] = "no-np"; }
  409. if(!$plexItem['thumb'] ){ $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png"; $plexItem['key'] = "no-list"; }
  410. if(isset($useImage)){ $plexItem['useImage'] = $useImage; }
  411. return $plexItem;
  412. }
  413. function plexConnect($action,$key=null){
  414. if($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))){
  415. $url = qualifyURL($GLOBALS['plexURL']);
  416. $ignore = array();
  417. switch ($action) {
  418. case 'streams':
  419. $url = $url."/status/sessions?X-Plex-Token=".$GLOBALS['plexToken'];
  420. break;
  421. case 'recent':
  422. $url = $url."/library/recentlyAdded?X-Plex-Token=".$GLOBALS['plexToken'];
  423. break;
  424. case 'metadata':
  425. $url = $url."/library/metadata/".$key."?X-Plex-Token=".$GLOBALS['plexToken'];
  426. break;
  427. case 'playlists':
  428. $url = $url."/playlists?X-Plex-Token=".$GLOBALS['plexToken'];
  429. break;
  430. case 'search':
  431. $url = $url."/search?query=".rawurlencode($key)."&X-Plex-Token=".$GLOBALS['plexToken'];
  432. $ignore = array('artist', 'episode');
  433. break;
  434. default:
  435. # code...
  436. break;
  437. }
  438. try{
  439. $options = (localURL($url)) ? array('verify' => false ) : array();
  440. $response = Requests::get($url, array(), $options);
  441. libxml_use_internal_errors(true);
  442. if($response->success){
  443. $items = array();
  444. $plex = simplexml_load_string($response->body);
  445. foreach($plex AS $child) {
  446. if( !in_array($child['type'], $ignore) && isset($child['librarySectionID'])){
  447. $items[] = resolvePlexItem($child);
  448. }
  449. }
  450. $api['content'] = $items;
  451. $api['plexID'] = $GLOBALS['plexID'];
  452. $api['showNames'] = true;
  453. $api['group'] = '1';
  454. return $api;
  455. }
  456. }catch( Requests_Exception $e ) {
  457. writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  458. };
  459. }
  460. return false;
  461. }
  462. function getPlexPlaylists(){
  463. if($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])){
  464. $url = qualifyURL($GLOBALS['plexURL']);
  465. $url = $url."/playlists?X-Plex-Token=".$GLOBALS['plexToken'];
  466. try{
  467. $options = (localURL($url)) ? array('verify' => false ) : array();
  468. $response = Requests::get($url, array(), $options);
  469. libxml_use_internal_errors(true);
  470. if($response->success){
  471. $items = array();
  472. $plex = simplexml_load_string($response->body);
  473. foreach($plex AS $child) {
  474. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']) , 'private') === false){
  475. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  476. $playlistURL = qualifyURL($GLOBALS['plexURL']);
  477. $playlistURL = $playlistURL.$child['key']."?X-Plex-Token=".$GLOBALS['plexToken'];
  478. $options = (localURL($url)) ? array('verify' => false ) : array();
  479. $playlistResponse = Requests::get($playlistURL, array(), $options);
  480. if($playlistResponse->success){
  481. $playlistResponse = simplexml_load_string($playlistResponse->body);
  482. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  483. foreach($playlistResponse->Video AS $playlistItem){
  484. $items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
  485. }
  486. }
  487. }
  488. }
  489. $api['content'] = $items;
  490. $api['plexID'] = $GLOBALS['plexID'];
  491. $api['showNames'] = true;
  492. $api['group'] = '1';
  493. return $api;
  494. }
  495. }catch( Requests_Exception $e ) {
  496. writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  497. };
  498. }
  499. return false;
  500. }
  501. function embyConnect($action,$key=null,$skip=false){
  502. if($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])){
  503. $url = qualifyURL($GLOBALS['embyURL']);
  504. switch ($action) {
  505. case 'streams':
  506. $url = $url.'/Sessions?api_key='.$GLOBALS['embyToken'];
  507. break;
  508. case 'recent':
  509. $username = false;
  510. if (isset($GLOBALS['organizrUser']['username'])) {
  511. $username = strtolower($GLOBALS['organizrUser']['username']);
  512. }
  513. // Get A User
  514. $userIds = $url."/Users?api_key=".$GLOBALS['embyToken'];
  515. $showPlayed = true;
  516. try{
  517. $options = (localURL($userIds)) ? array('verify' => false ) : array();
  518. $response = Requests::get($userIds, array(), $options);
  519. if($response->success){
  520. $emby = json_decode($response->body, true);
  521. foreach ($emby as $value) { // Scan for admin user
  522. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  523. $userId = $value['Id'];
  524. }
  525. if ($username && strtolower($value['Name']) == $username) {
  526. $userId = $value['Id'];
  527. $showPlayed = false;
  528. break;
  529. }
  530. }
  531. }
  532. }catch( Requests_Exception $e ) {
  533. writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  534. };
  535. $url = $url.'/Users/'.$userId.'/Items/Latest?EnableImages=false&Limit=100&api_key='.$GLOBALS['embyToken'].($showPlayed?'':'&IsPlayed=false');
  536. break;
  537. case 'metadata':
  538. $skip = true;
  539. break;
  540. default:
  541. # code...
  542. break;
  543. }
  544. if($skip && $key){
  545. $items[] = resolveEmbyItem(array('Id'=>$key));
  546. $api['content'] = $items;
  547. return $api;
  548. }
  549. try{
  550. $options = (localURL($url)) ? array('verify' => false ) : array();
  551. $response = Requests::get($url, array(), $options);
  552. if($response->success){
  553. $items = array();
  554. $emby = json_decode($response->body, true);
  555. foreach($emby AS $child) {
  556. if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
  557. $items[] = resolveEmbyItem($child);
  558. }
  559. }
  560. $api['content'] = array_filter($items);
  561. return $api;
  562. }
  563. }catch( Requests_Exception $e ) {
  564. writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  565. };
  566. }
  567. return false;
  568. }
  569. function sabnzbdConnect() {
  570. if($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])){
  571. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  572. $url = $url.'/api?mode=queue&output=json&apikey='.$GLOBALS['sabnzbdToken'];
  573. try{
  574. $options = (localURL($url)) ? array('verify' => false ) : array();
  575. $response = Requests::get($url, array(), $options);
  576. if($response->success){
  577. $api['content']['queueItems'] = json_decode($response->body, true);
  578. }
  579. }catch( Requests_Exception $e ) {
  580. writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  581. };
  582. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  583. $url = $url.'/api?mode=history&output=json&apikey='.$GLOBALS['sabnzbdToken'];
  584. try{
  585. $options = (localURL($url)) ? array('verify' => false ) : array();
  586. $response = Requests::get($url, array(), $options);
  587. if($response->success){
  588. $api['content']['historyItems']= json_decode($response->body, true);
  589. }
  590. }catch( Requests_Exception $e ) {
  591. writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  592. };
  593. $api['content'] = isset($api['content']) ? $api['content'] : false;
  594. return $api;
  595. }
  596. }
  597. function nzbgetConnect() {
  598. if($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])){
  599. $url = qualifyURL($GLOBALS['nzbgetURL']);
  600. $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/listgroups';
  601. try{
  602. $options = (localURL($url)) ? array('verify' => false ) : array();
  603. $response = Requests::get($url, array(), $options);
  604. if($response->success){
  605. $api['content']['queueItems'] = json_decode($response->body, true);
  606. }
  607. }catch( Requests_Exception $e ) {
  608. writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  609. };
  610. $url = qualifyURL($GLOBALS['nzbgetURL']);
  611. $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/history';
  612. try{
  613. $options = (localURL($url)) ? array('verify' => false ) : array();
  614. $response = Requests::get($url, array(), $options);
  615. if($response->success){
  616. $api['content']['historyItems']= json_decode($response->body, true);
  617. }
  618. }catch( Requests_Exception $e ) {
  619. writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  620. };
  621. $api['content'] = isset($api['content']) ? $api['content'] : false;
  622. return $api;
  623. }
  624. }
  625. function transmissionConnect() {
  626. if($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])){
  627. $digest = qualifyURL($GLOBALS['transmissionURL'], true);
  628. $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'].':'.decrypt($GLOBALS['transmissionPassword'])."@" : '';
  629. $url = $digest['scheme'].'://'.$passwordInclude.$digest['host'].$digest['port'].$digest['path'].'/rpc';
  630. try{
  631. $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false ) : array();
  632. $response = Requests::get($url, array(), $options);
  633. if($response->headers['x-transmission-session-id']){
  634. $headers = array(
  635. 'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
  636. 'Content-Type' => 'application/json'
  637. );
  638. $data = array(
  639. 'method' => 'torrent-get',
  640. 'arguments' => array(
  641. 'fields' => array(
  642. "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir","errorString"
  643. ),
  644. ),
  645. 'tags' => ''
  646. );
  647. $response = Requests::post($url, $headers, json_encode($data), $options);
  648. if($response->success){
  649. $torrentList = json_decode($response->body, true)['arguments']['torrents'];
  650. if($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']){
  651. $filter = array();
  652. $torrents['arguments']['torrents'] = array();
  653. if($GLOBALS['transmissionHideSeeding']){ array_push($filter, 6, 5); }
  654. if($GLOBALS['transmissionHideCompleted']){ array_push($filter, 0); }
  655. foreach ($torrentList as $key => $value) {
  656. if(!in_array($value['status'], $filter)){
  657. $torrents['arguments']['torrents'][] = $value;
  658. }
  659. }
  660. }else{
  661. $torrents = json_decode($response->body, true);
  662. }
  663. $api['content']['queueItems'] = $torrents;
  664. $api['content']['historyItems'] = false;
  665. }
  666. }else{
  667. writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
  668. }
  669. }catch( Requests_Exception $e ) {
  670. writeLog('error', 'Transmission Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  671. };
  672. $api['content'] = isset($api['content']) ? $api['content'] : false;
  673. return $api;
  674. }
  675. }
  676. function qBittorrentConnect() {
  677. if($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])){
  678. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  679. $passwordInclude = ($GLOBALS['qBittorrentUsername'] != '' && $GLOBALS['qBittorrentPassword'] != '') ? 'username='.$GLOBALS['qBittorrentUsername'].'&password='.decrypt($GLOBALS['qBittorrentPassword'])."@" : '';
  680. $data = array('username'=>$GLOBALS['qBittorrentUsername'], 'password'=> decrypt($GLOBALS['qBittorrentPassword']));
  681. $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/login';
  682. try{
  683. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false ) : array();
  684. $response = Requests::post($url, array(), $data, $options);
  685. $reflection = new ReflectionClass($response->cookies);
  686. $cookie = $reflection->getProperty("cookies");
  687. $cookie->setAccessible(true);
  688. $cookie = $cookie->getValue($response->cookies);
  689. if($cookie){
  690. $headers = array(
  691. 'Cookie' => 'SID=' . $cookie['SID']->value
  692. );
  693. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  694. $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  695. $response = Requests::get($url, $headers, $options);
  696. if($response){
  697. $torrentList = json_decode($response->body, true);
  698. if($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']){
  699. $filter = array();
  700. $torrents['arguments']['torrents'] = array();
  701. if($GLOBALS['qBittorrentHideSeeding']){ array_push($filter, 'uploading', 'stalledUP', 'queuedUP'); }
  702. if($GLOBALS['qBittorrentHideCompleted']){ array_push($filter, 'pausedUP'); }
  703. foreach ($torrentList as $key => $value) {
  704. if(!in_array($value['state'], $filter)){
  705. $torrents['arguments']['torrents'][] = $value;
  706. }
  707. }
  708. }else{
  709. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  710. }
  711. $api['content']['queueItems'] = $torrents;
  712. $api['content']['historyItems'] = false;
  713. }
  714. }else{
  715. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  716. }
  717. }catch( Requests_Exception $e ) {
  718. writeLog('error', 'qBittorrent Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  719. };
  720. $api['content'] = isset($api['content']) ? $api['content'] : false;
  721. return $api;
  722. }
  723. }
  724. function delugeConnect(){
  725. if($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])){
  726. try{
  727. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  728. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  729. $api['content']['queueItems'] = $torrents;
  730. $api['content']['historyItems'] = false;
  731. }catch( Excecption $e){
  732. writeLog('error', 'Deluge Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  733. }
  734. }
  735. $api['content'] = isset($api['content']) ? $api['content'] : false;
  736. return $api;
  737. }
  738. function getCalendar(){
  739. $startDate = date('Y-m-d',strtotime("-".$GLOBALS['calendarStart']." days"));
  740. $endDate = date('Y-m-d',strtotime("+".$GLOBALS['calendarEnd']." days"));
  741. $calendarItems = array();
  742. // SONARR CONNECT
  743. if($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])){
  744. $sonarrs = array();
  745. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  746. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  747. if(count($sonarrURLList) == count($sonarrTokenList)){
  748. foreach ($sonarrURLList as $key => $value) {
  749. $sonarrs[$key] = array(
  750. 'url' => $value,
  751. 'token' => $sonarrTokenList[$key]
  752. );
  753. }
  754. foreach ($sonarrs as $key => $value) {
  755. try {
  756. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  757. $sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate),$key);
  758. } catch (Exception $e) {
  759. writeLog('error', 'Sonarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  760. }
  761. if(!empty($sonarrCalendar)) { $calendarItems = array_merge($calendarItems, $sonarrCalendar); }
  762. }
  763. }
  764. }
  765. // RADARR CONNECT
  766. if($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])){
  767. $radarrs = array();
  768. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  769. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  770. if(count($radarrURLList) == count($radarrTokenList)){
  771. foreach ($radarrURLList as $key => $value) {
  772. $radarrs[$key] = array(
  773. 'url' => $value,
  774. 'token' => $radarrTokenList[$key]
  775. );
  776. }
  777. foreach ($radarrs as $key => $value) {
  778. try {
  779. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  780. $radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate),$key,$value['url']);
  781. } catch (Exception $e) {
  782. writeLog('error', 'Radarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  783. }
  784. if(!empty($radarrCalendar)) { $calendarItems = array_merge($calendarItems, $radarrCalendar); }
  785. }
  786. }
  787. }
  788. // SICKRAGE/BEARD/MEDUSA CONNECT
  789. if($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])){
  790. $sicks = array();
  791. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  792. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  793. if(count($sickURLList) == count($sickTokenList)){
  794. foreach ($sickURLList as $key => $value) {
  795. $sicks[$key] = array(
  796. 'url' => $value,
  797. 'token' => $sickTokenList[$key]
  798. );
  799. }
  800. foreach ($sicks as $key => $value) {
  801. try {
  802. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  803. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(),$key);
  804. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100","downloaded"),$key);
  805. if(!empty($sickrageFuture)) { $calendarItems = array_merge($calendarItems, $sickrageFuture); }
  806. if(!empty($sickrageHistory)) { $calendarItems = array_merge($calendarItems, $sickrageHistory); }
  807. } catch (Exception $e) {
  808. writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  809. }
  810. }
  811. }
  812. }
  813. // COUCHPOTATO CONNECT
  814. if($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])){
  815. $couchs = array();
  816. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  817. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  818. if(count($couchpotatoURLList) == count($couchpotatoTokenList)){
  819. foreach ($couchpotatoURLList as $key => $value) {
  820. $couchs[$key] = array(
  821. 'url' => $value,
  822. 'token' => $couchpotatoTokenList[$key]
  823. );
  824. }
  825. foreach ($couchs as $key => $value) {
  826. try {
  827. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  828. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(),$key);
  829. if(!empty($couchCalendar)) { $calendarItems = array_merge($calendarItems, $couchCalendar); }
  830. } catch (Exception $e) {
  831. writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  832. }
  833. }
  834. }
  835. }
  836. return ($calendarItems) ? $calendarItems : false;
  837. }
  838. function getSonarrCalendar($array,$number){
  839. $array = json_decode($array, true);
  840. $gotCalendar = array();
  841. $i = 0;
  842. foreach($array AS $child) {
  843. $i++;
  844. $seriesName = $child['series']['title'];
  845. $episodeID = $child['series']['tvdbId'];
  846. if(!isset($episodeID)){ $episodeID = ""; }
  847. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  848. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  849. $episodeAirDate = $child['airDateUtc'];
  850. $episodeAirDate = strtotime($episodeAirDate);
  851. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  852. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  853. $downloaded = $child['hasFile'];
  854. if($downloaded == "0" && isset($unaired) && $episodePremier == "true"){ $downloaded = "text-primary"; }elseif($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success"; }else{ $downloaded = "text-danger"; }
  855. $fanart = "/plugins/images/cache/no-np.png";
  856. foreach ($child['series']['images'] as $image) {
  857. if($image['coverType'] == "fanart") {
  858. $fanart = $image['url'];
  859. }
  860. }
  861. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  862. $details = array(
  863. "seasonCount" => $child['series']['seasonCount'],
  864. "status" => $child['series']['status'],
  865. "topTitle" => $seriesName,
  866. "bottomTitle" => $bottomTitle,
  867. "overview" => isset($child['overview']) ? $child['overview'] : '',
  868. "runtime" => $child['series']['runtime'],
  869. "image" => $fanart,
  870. "ratings" => $child['series']['ratings']['value'],
  871. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  872. "audioChannels" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  873. "audioCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  874. "videoCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  875. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  876. "genres" => $child['series']['genres'],
  877. );
  878. array_push($gotCalendar, array(
  879. "id" => "Sonarr-".$number."-".$i,
  880. "title" => $seriesName,
  881. "start" => $child['airDateUtc'],
  882. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  883. "imagetype" => "tv ".$downloaded,
  884. "details" => $details
  885. ));
  886. }
  887. if ($i != 0){ return $gotCalendar; }
  888. }
  889. function getRadarrCalendar($array,$number, $url){
  890. $array = json_decode($array, true);
  891. $gotCalendar = array();
  892. $i = 0;
  893. foreach($array AS $child) {
  894. if(isset($child['physicalRelease'])){
  895. $i++;
  896. $movieName = $child['title'];
  897. $movieID = $child['tmdbId'];
  898. if(!isset($movieID)){ $movieID = ""; }
  899. $physicalRelease = $child['physicalRelease'];
  900. $physicalRelease = strtotime($physicalRelease);
  901. $physicalRelease = date("Y-m-d", $physicalRelease);
  902. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  903. $downloaded = $child['hasFile'];
  904. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success"; }else{ $downloaded = "text-danger"; }
  905. $banner = "/plugins/images/cache/no-np.png";
  906. foreach ($child['images'] as $image) {
  907. if($image['coverType'] == "banner") {
  908. $url = rtrim($url, '/'); //remove trailing slash
  909. $imageUrl = $image['url'];
  910. $urlParts = explode("/", $url);
  911. $imageParts = explode("/", $image['url']);
  912. if ($imageParts[1] == end($urlParts)) {
  913. unset($imageParts[1]);
  914. $imageUrl = implode("/", $imageParts);
  915. }
  916. $banner = $url . $imageUrl;
  917. }
  918. }
  919. if($banner !== "/plugins/images/cache/no-np.png"){
  920. $cacheDirectory = dirname(__DIR__,2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
  921. $imageURL = $banner;
  922. $cacheFile = $cacheDirectory.$movieID.'.jpg';
  923. $banner = 'plugins/images/cache/'.$movieID.'.jpg';
  924. if(!file_exists($cacheFile)){
  925. cacheImage($imageURL,$movieID);
  926. unset($imageURL);
  927. unset($cacheFile);
  928. }
  929. }
  930. $alternativeTitles = "";
  931. foreach ($child['alternativeTitles'] as $alternative) {
  932. $alternativeTitles .= $alternative['title'] . ', ';
  933. }
  934. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  935. $details = array(
  936. "topTitle" => $movieName,
  937. "bottomTitle" => $alternativeTitles,
  938. "status" => $child['status'],
  939. "overview" => $child['overview'],
  940. "runtime" => $child['runtime'],
  941. "image" => $banner,
  942. "ratings" => $child['ratings']['value'],
  943. "videoQuality" => $child["hasFile"] ? $child['movieFile']['quality']['quality']['name'] : "unknown",
  944. "audioChannels" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  945. "audioCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  946. "videoCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  947. "size" => $child["hasFile"] ? $child['movieFile']['size'] : "unknown",
  948. "genres" => $child['genres'],
  949. );
  950. array_push($gotCalendar, array(
  951. "id" => "Radarr-".$number."-".$i,
  952. "title" => $movieName,
  953. "start" => $physicalRelease,
  954. "className" => "bg-calendar movieID--".$movieID,
  955. "imagetype" => "film ".$downloaded,
  956. "details" => $details
  957. ));
  958. }
  959. }
  960. if ($i != 0){ return $gotCalendar; }
  961. }
  962. function getCouchCalendar($array,$number){
  963. $api = json_decode($array, true);
  964. $gotCalendar = array();
  965. $i = 0;
  966. foreach($api['movies'] AS $child) {
  967. if($child['status'] == "active" || $child['status'] == "done" ){
  968. $i++;
  969. $movieName = $child['info']['original_title'];
  970. $movieID = $child['info']['tmdb_id'];
  971. if(!isset($movieID)){ $movieID = ""; }
  972. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  973. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  974. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  975. $physicalRelease = strtotime($physicalRelease);
  976. $physicalRelease = date("Y-m-d", $physicalRelease);
  977. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  978. $downloaded = ($child['status'] == "active") ? "0" : "1";
  979. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success"; }else{ $downloaded = "text-danger"; }
  980. array_push($gotCalendar, array(
  981. "id" => "CouchPotato-".$number."-".$i,
  982. "title" => $movieName,
  983. "start" => $physicalRelease,
  984. "className" => "bg-calendar calendar-item movieID--".$movieID,
  985. "imagetype" => "film ".$downloaded,
  986. ));
  987. }
  988. }
  989. if ($i != 0){ return $gotCalendar; }
  990. }
  991. function getSickrageCalendarWanted($array,$number){
  992. $array = json_decode($array, true);
  993. $gotCalendar = array();
  994. $i = 0;
  995. foreach($array['data']['missed'] AS $child) {
  996. $i++;
  997. $seriesName = $child['show_name'];
  998. $episodeID = $child['tvdbid'];
  999. $episodeAirDate = $child['airdate'];
  1000. $episodeAirDateTime = explode(" ",$child['airs']);
  1001. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1002. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1003. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1004. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1005. $downloaded = "0";
  1006. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  1007. array_push($gotCalendar, array(
  1008. "id" => "Sick-".$number."-Miss-".$i,
  1009. "title" => $seriesName,
  1010. "start" => $episodeAirDate,
  1011. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1012. "imagetype" => "tv ".$downloaded,
  1013. ));
  1014. }
  1015. foreach($array['data']['today'] AS $child) {
  1016. $i++;
  1017. $seriesName = $child['show_name'];
  1018. $episodeID = $child['tvdbid'];
  1019. $episodeAirDate = $child['airdate'];
  1020. $episodeAirDateTime = explode(" ",$child['airs']);
  1021. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1022. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1023. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1024. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1025. $downloaded = "0";
  1026. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  1027. array_push($gotCalendar, array(
  1028. "id" => "Sick-".$number."-Today-".$i,
  1029. "title" => $seriesName,
  1030. "start" => $episodeAirDate,
  1031. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1032. "imagetype" => "tv ".$downloaded,
  1033. ));
  1034. }
  1035. foreach($array['data']['soon'] AS $child) {
  1036. $i++;
  1037. $seriesName = $child['show_name'];
  1038. $episodeID = $child['tvdbid'];
  1039. $episodeAirDate = $child['airdate'];
  1040. $episodeAirDateTime = explode(" ",$child['airs']);
  1041. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1042. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1043. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1044. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1045. $downloaded = "0";
  1046. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  1047. array_push($gotCalendar, array(
  1048. "id" => "Sick-".$number."-Soon-".$i,
  1049. "title" => $seriesName,
  1050. "start" => $episodeAirDate,
  1051. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1052. "imagetype" => "tv ".$downloaded,
  1053. ));
  1054. }
  1055. foreach($array['data']['later'] AS $child) {
  1056. $i++;
  1057. $seriesName = $child['show_name'];
  1058. $episodeID = $child['tvdbid'];
  1059. $episodeAirDate = $child['airdate'];
  1060. $episodeAirDateTime = explode(" ",$child['airs']);
  1061. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1062. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1063. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1064. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1065. $downloaded = "0";
  1066. if($downloaded == "0" && isset($unaired)){ $downloaded = "text-info"; }elseif($downloaded == "1"){ $downloaded = "text-success";}else{ $downloaded = "text-danger"; }
  1067. array_push($gotCalendar, array(
  1068. "id" => "Sick-".$number."-Later-".$i,
  1069. "title" => $seriesName,
  1070. "start" => $episodeAirDate,
  1071. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1072. "imagetype" => "tv ".$downloaded,
  1073. ));
  1074. }
  1075. if ($i != 0){ return $gotCalendar; }
  1076. }
  1077. function getSickrageCalendarHistory($array,$number){
  1078. $array = json_decode($array, true);
  1079. $gotCalendar = array();
  1080. $i = 0;
  1081. foreach($array['data'] AS $child) {
  1082. $i++;
  1083. $seriesName = $child['show_name'];
  1084. $episodeID = $child['tvdbid'];
  1085. $episodeAirDate = $child['date'];
  1086. $downloaded = "text-success";
  1087. array_push($gotCalendar, array(
  1088. "id" => "Sick-".$number."-History-".$i,
  1089. "title" => $seriesName,
  1090. "start" => $episodeAirDate,
  1091. "className" => "bg-calendar calendar-item tvID--".$episodeID,
  1092. "imagetype" => "tv ".$downloaded,
  1093. ));
  1094. }
  1095. if ($i != 0){ return $gotCalendar; }
  1096. }
  1097. function ombiAPI($array){
  1098. return ombiAction($array['data']['id'],$array['data']['action'],$array['data']['type']);
  1099. }
  1100. function ombiAction($id, $action, $type) {
  1101. if($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])){
  1102. $url = qualifyURL($GLOBALS['ombiURL']);
  1103. $headers = array(
  1104. "Accept" => "application/json",
  1105. "Content-Type" => "application/json",
  1106. "Apikey" => $GLOBALS['ombiToken']
  1107. );
  1108. $data = array(
  1109. 'id' => $id,
  1110. );
  1111. switch ($type) {
  1112. case 'season':
  1113. case 'tv':
  1114. $type = 'tv';
  1115. $add = array(
  1116. 'tvDbId' => $id,
  1117. 'requestAll' => true,
  1118. 'latestSeason' => true,
  1119. 'firstSeason' => true
  1120. );
  1121. break;
  1122. default:
  1123. $type = 'movie';
  1124. $add = array("theMovieDbId" => (int)$id);
  1125. break;
  1126. }
  1127. $success['head'] = $headers;
  1128. $success['act'] = $action;
  1129. $success['data'] = $data;
  1130. $success['add'] = $add;
  1131. $success['type'] = $type;
  1132. try{
  1133. $options = (localURL($url)) ? array('verify' => false ) : array();
  1134. switch ($action) {
  1135. case 'add':
  1136. if(isset($_COOKIE['Auth'])){
  1137. $headers = array(
  1138. "Accept" => "application/json",
  1139. "Content-Type" => "application/json",
  1140. "Authorization" => "Bearer ".$_COOKIE['Auth']
  1141. );
  1142. $success['head'] = $headers;
  1143. }else{
  1144. return false;
  1145. }
  1146. $response = Requests::post($url."/api/v1/Request/".$type, $headers, json_encode($add), $options);
  1147. break;
  1148. default:
  1149. if(qualifyRequest(1)){
  1150. switch ($action) {
  1151. case 'approve':
  1152. $response = Requests::post($url."/api/v1/Request/".$type."/approve", $headers, json_encode($data), $options);
  1153. break;
  1154. case 'available':
  1155. $response = Requests::post($url."/api/v1/Request/".$type."/available", $headers, json_encode($data), $options);
  1156. break;
  1157. case 'unavailable':
  1158. $response = Requests::post($url."/api/v1/Request/".$type."/unavailable", $headers, json_encode($data), $options);
  1159. break;
  1160. case 'deny':
  1161. $response = Requests::put($url."/api/v1/Request/".$type."/deny", $headers, json_encode($data), $options);
  1162. break;
  1163. case 'delete':
  1164. $response = Requests::delete($url."/api/v1/Request/".$type."/".$id, $headers, $options);
  1165. break;
  1166. default:
  1167. return false;
  1168. }
  1169. }
  1170. break;
  1171. }
  1172. $success['api'] = $response;
  1173. $success['bd'] = $response->body;
  1174. $success['hd'] = $response->headers;
  1175. if($response->success){
  1176. $success['ok'] = true;
  1177. }
  1178. }catch( Requests_Exception $e ) {
  1179. writeLog('error', 'OMBI Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  1180. };
  1181. }
  1182. return isset($success['ok']) ? $success : false;
  1183. }
  1184. function getOmbiRequests($type = "both"){
  1185. if($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])){
  1186. $url = qualifyURL($GLOBALS['ombiURL']);
  1187. $headers = array(
  1188. "Accept" => "application/json",
  1189. "Apikey" => $GLOBALS['ombiToken'],
  1190. );
  1191. $requests = array();
  1192. try{
  1193. $options = (localURL($url)) ? array('verify' => false ) : array();
  1194. switch ($type) {
  1195. case 'movie':
  1196. $movie = Requests::get($url."/api/v1/Request/movie", $headers, $options);
  1197. break;
  1198. case 'tv':
  1199. $tv = Requests::get($url."/api/v1/Request/tv", $headers, $options);
  1200. break;
  1201. default:
  1202. $movie = Requests::get($url."/api/v1/Request/movie", $headers, $options);
  1203. $tv = Requests::get($url."/api/v1/Request/tv", $headers, $options);
  1204. break;
  1205. }
  1206. if($movie->success || $tv->success){
  1207. if(isset($movie)){
  1208. $movie = json_decode($movie->body, true);
  1209. //$movie = array_reverse($movie);
  1210. foreach ($movie as $key => $value) {
  1211. $requests[] = array(
  1212. 'test' => $value,
  1213. 'id' => $value['theMovieDbId'],
  1214. 'title' => $value['title'],
  1215. 'overview' => $value['overview'],
  1216. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/'.$value['posterPath'] : '',
  1217. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/'.$value['background'] : '',
  1218. 'approved' => $value['approved'],
  1219. 'available' => $value['available'],
  1220. 'denied' => $value['denied'],
  1221. 'deniedReason' => $value['deniedReason'],
  1222. 'user' => $value['requestedUser']['userName'],
  1223. 'request_id' => $value['id'],
  1224. 'request_date' => $value['requestedDate'],
  1225. 'release_date' => $value['releaseDate'],
  1226. 'type' => 'movie',
  1227. 'icon' => 'mdi mdi-filmstrip',
  1228. 'color' => 'palette-Deep-Purple-900 bg white',
  1229. );
  1230. }
  1231. }
  1232. if(isset($tv) && (is_array($tv) || is_object($tv))){
  1233. $tv = json_decode($tv->body, true);
  1234. foreach ($tv as $key => $value) {
  1235. if(is_array($value['childRequests'][0])){
  1236. $requests[] = array(
  1237. 'test' => $value,
  1238. 'id' => $value['tvDbId'],
  1239. 'title' => $value['title'],
  1240. 'overview' => $value['overview'],
  1241. 'poster' => $value['posterPath'],
  1242. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/'.$value['background'] : '',
  1243. 'approved' => $value['childRequests'][0]['approved'],
  1244. 'available' => $value['childRequests'][0]['available'],
  1245. 'denied' => $value['childRequests'][0]['denied'],
  1246. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  1247. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  1248. 'request_id' => $value['id'],
  1249. 'request_date' => $value['childRequests'][0]['requestedDate'],
  1250. 'release_date' => $value['releaseDate'],
  1251. 'type' => 'tv',
  1252. 'icon' => 'mdi mdi-television',
  1253. 'color' => 'grayish-blue-bg',
  1254. );
  1255. }
  1256. }
  1257. }
  1258. //sort here
  1259. usort($requests, function ($item1, $item2) {
  1260. if ($item1['request_date'] == $item2['request_date']) return 0;
  1261. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  1262. });
  1263. }
  1264. }catch( Requests_Exception $e ) {
  1265. writeLog('error', 'OMBI Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
  1266. };
  1267. }
  1268. $api['content'] = isset($requests) ? $requests : false;
  1269. return $api;
  1270. }