homepage-connect-functions.php 85 KB

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