homepage-connect-functions.php 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  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. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  782. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  783. $options = (localURL($url)) ? array('verify' => false) : array();
  784. $data = xmlrpc_encode_request("d.multicall2", array(
  785. "",
  786. "main",
  787. "d.name=",
  788. "d.base_path=",
  789. "d.up.total=",
  790. "d.size_bytes=",
  791. "d.down.total=",
  792. "d.completed_bytes=",
  793. "d.connection_current=",
  794. "d.down.rate=",
  795. "d.up.rate=",
  796. "d.timestamp.started=",
  797. "d.state=",
  798. "d.group.name=",
  799. "d.hash=",
  800. "d.complete=",
  801. "d.ratio=",
  802. "d.chunk_size=",
  803. "f.size_bytes=",
  804. "f.size_chunks=",
  805. "f.completed_chunks=",
  806. "d.custom=",
  807. "d.custom1=",
  808. "d.custom2=",
  809. "d.custom3=",
  810. "d.custom4=",
  811. "d.custom5=",
  812. ), array());
  813. $response = Requests::post($url, array(), $data, $options);
  814. if ($response->success) {
  815. $torrentList = xmlrpc_decode(str_replace('i8>', 'string>', $response->body));
  816. foreach ($torrentList as $key => $value) {
  817. $tempStatus = rTorrentStatus($value[13], $value[10], $value[6]);
  818. if ($tempStatus == 'Seeding' && $GLOBALS['rTorrentHideSeeding']) {
  819. //do nothing
  820. } elseif ($tempStatus == 'Finished' && $GLOBALS['rTorrentHideCompleted']) {
  821. //do nothing
  822. } else {
  823. $torrents[$key] = array(
  824. 'name' => $value[0],
  825. 'base' => $value[1],
  826. 'upTotal' => $value[2],
  827. 'size' => $value[3],
  828. 'downTotal' => $value[4],
  829. 'downloaded' => $value[5],
  830. 'connectionState' => $value[6],
  831. 'leech' => $value[7],
  832. 'seed' => $value[8],
  833. 'date' => $value[9],
  834. 'state' => ($value[10]) ? 'on' : 'off',
  835. 'group' => $value[11],
  836. 'hash' => $value[12],
  837. 'complete' => ($value[13]) ? 'yes' : 'no',
  838. 'ratio' => $value[14],
  839. 'label' => $value[20],
  840. 'status' => $tempStatus,
  841. 'temp' => $value[16] . ' - ' . $value[17] . ' - ' . $value[18],
  842. 'custom' => $value[19] . ' - ' . $value[20] . ' - ' . $value[21],
  843. 'custom2' => $value[22] . ' - ' . $value[23] . ' - ' . $value[24],
  844. );
  845. }
  846. }
  847. if (count($torrents) !== 0) {
  848. usort($torrents, function ($a, $b) {
  849. $direction = substr($GLOBALS['rTorrentSortOrder'], -1);
  850. $sort = substr($GLOBALS['rTorrentSortOrder'], 0, strlen($GLOBALS['rTorrentSortOrder']) - 1);
  851. switch ($direction) {
  852. case 'a':
  853. return $a[$sort] <=> $b[$sort];
  854. break;
  855. case 'd':
  856. return $b[$sort] <=> $a[$sort];
  857. break;
  858. default:
  859. return $b['date'] <=> $a['date'];
  860. }
  861. });
  862. }
  863. $api['content']['queueItems'] = $torrents;
  864. $api['content']['historyItems'] = false;
  865. }
  866. } catch
  867. (Requests_Exception $e) {
  868. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  869. };
  870. $api['content'] = isset($api['content']) ? $api['content'] : false;
  871. return $api;
  872. }
  873. return false;
  874. }
  875. function qBittorrentConnect()
  876. {
  877. if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
  878. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  879. $data = array('username' => $GLOBALS['qBittorrentUsername'], 'password' => decrypt($GLOBALS['qBittorrentPassword']));
  880. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/login';
  881. try {
  882. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false) : array();
  883. $response = Requests::post($url, array(), $data, $options);
  884. $reflection = new ReflectionClass($response->cookies);
  885. $cookie = $reflection->getProperty("cookies");
  886. $cookie->setAccessible(true);
  887. $cookie = $cookie->getValue($response->cookies);
  888. if ($cookie) {
  889. $headers = array(
  890. 'Cookie' => 'SID=' . $cookie['SID']->value
  891. );
  892. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  893. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  894. $response = Requests::get($url, $headers, $options);
  895. if ($response) {
  896. $torrentList = json_decode($response->body, true);
  897. if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
  898. $filter = array();
  899. $torrents['arguments']['torrents'] = array();
  900. if ($GLOBALS['qBittorrentHideSeeding']) {
  901. array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
  902. }
  903. if ($GLOBALS['qBittorrentHideCompleted']) {
  904. array_push($filter, 'pausedUP');
  905. }
  906. foreach ($torrentList as $key => $value) {
  907. if (!in_array($value['state'], $filter)) {
  908. $torrents['arguments']['torrents'][] = $value;
  909. }
  910. }
  911. } else {
  912. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  913. }
  914. $api['content']['queueItems'] = $torrents;
  915. $api['content']['historyItems'] = false;
  916. }
  917. } else {
  918. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  919. }
  920. } catch (Requests_Exception $e) {
  921. writeLog('error', 'qBittorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  922. };
  923. $api['content'] = isset($api['content']) ? $api['content'] : false;
  924. return $api;
  925. }
  926. return false;
  927. }
  928. function delugeConnect()
  929. {
  930. if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
  931. try {
  932. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  933. $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');
  934. if ($GLOBALS['delugeHideSeeding'] || $GLOBALS['delugeHideCompleted']) {
  935. $filter = array();
  936. if ($GLOBALS['delugeHideSeeding']) {
  937. array_push($filter, 'Seeding', 'Uploading', 'queuedUP');
  938. }
  939. if ($GLOBALS['delugeHideCompleted']) {
  940. array_push($filter, 'Seeding', 'Completed');
  941. }
  942. //prettyPrint($torrents);
  943. foreach ($torrents as $key => $value) {
  944. if (!in_array($value->state, $filter)) {
  945. $api['content']['queueItems'][] = $value;
  946. }
  947. }
  948. } else {
  949. $api['content']['queueItems'] = $torrents;
  950. }
  951. $api['content']['queueItems'] = (empty($api['content']['queueItems'])) ? [] : $api['content']['queueItems'];
  952. $api['content']['historyItems'] = false;
  953. } catch (Excecption $e) {
  954. writeLog('error', 'Deluge Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  955. }
  956. }
  957. $api['content'] = isset($api['content']) ? $api['content'] : false;
  958. return $api;
  959. }
  960. function getCalendar()
  961. {
  962. $startDate = date('Y-m-d', strtotime("-" . $GLOBALS['calendarStart'] . " days"));
  963. $endDate = date('Y-m-d', strtotime("+" . $GLOBALS['calendarEnd'] . " days"));
  964. $icalCalendarSources = array();
  965. $calendarItems = array();
  966. // SONARR CONNECT
  967. if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  968. $sonarrs = array();
  969. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  970. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  971. if (count($sonarrURLList) == count($sonarrTokenList)) {
  972. foreach ($sonarrURLList as $key => $value) {
  973. $sonarrs[$key] = array(
  974. 'url' => $value,
  975. 'token' => $sonarrTokenList[$key]
  976. );
  977. }
  978. foreach ($sonarrs as $key => $value) {
  979. try {
  980. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  981. $sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate, $GLOBALS['sonarrUnmonitored']), $key);
  982. } catch (Exception $e) {
  983. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  984. }
  985. if (!empty($sonarrCalendar)) {
  986. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  987. }
  988. }
  989. }
  990. }
  991. // LIDARR CONNECT
  992. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  993. $lidarrs = array();
  994. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  995. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  996. if (count($lidarrURLList) == count($lidarrTokenList)) {
  997. foreach ($lidarrURLList as $key => $value) {
  998. $lidarrs[$key] = array(
  999. 'url' => $value,
  1000. 'token' => $lidarrTokenList[$key]
  1001. );
  1002. }
  1003. foreach ($lidarrs as $key => $value) {
  1004. try {
  1005. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1006. $lidarrCalendar = getLidarrCalendar($lidarr->getCalendar($startDate, $endDate), $key);
  1007. } catch (Exception $e) {
  1008. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1009. }
  1010. if (!empty($lidarrCalendar)) {
  1011. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1012. }
  1013. }
  1014. }
  1015. }
  1016. // RADARR CONNECT
  1017. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1018. $radarrs = array();
  1019. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1020. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1021. if (count($radarrURLList) == count($radarrTokenList)) {
  1022. foreach ($radarrURLList as $key => $value) {
  1023. $radarrs[$key] = array(
  1024. 'url' => $value,
  1025. 'token' => $radarrTokenList[$key]
  1026. );
  1027. }
  1028. foreach ($radarrs as $key => $value) {
  1029. try {
  1030. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1031. $radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate), $key, $value['url']);
  1032. } catch (Exception $e) {
  1033. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1034. }
  1035. if (!empty($radarrCalendar)) {
  1036. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. // SICKRAGE/BEARD/MEDUSA CONNECT
  1042. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1043. $sicks = array();
  1044. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1045. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1046. if (count($sickURLList) == count($sickTokenList)) {
  1047. foreach ($sickURLList as $key => $value) {
  1048. $sicks[$key] = array(
  1049. 'url' => $value,
  1050. 'token' => $sickTokenList[$key]
  1051. );
  1052. }
  1053. foreach ($sicks as $key => $value) {
  1054. try {
  1055. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1056. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1057. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1058. if (!empty($sickrageFuture)) {
  1059. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1060. }
  1061. if (!empty($sickrageHistory)) {
  1062. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1063. }
  1064. } catch (Exception $e) {
  1065. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1066. }
  1067. }
  1068. }
  1069. }
  1070. // COUCHPOTATO CONNECT
  1071. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1072. $couchs = array();
  1073. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1074. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1075. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1076. foreach ($couchpotatoURLList as $key => $value) {
  1077. $couchs[$key] = array(
  1078. 'url' => $value,
  1079. 'token' => $couchpotatoTokenList[$key]
  1080. );
  1081. }
  1082. foreach ($couchs as $key => $value) {
  1083. try {
  1084. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1085. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1086. if (!empty($couchCalendar)) {
  1087. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1088. }
  1089. } catch (Exception $e) {
  1090. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1091. }
  1092. }
  1093. }
  1094. }
  1095. // iCal URL
  1096. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1097. $calendars = array();
  1098. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1099. $icalEvents = array();
  1100. foreach ($calendarURLList as $key => $value) {
  1101. $icsEvents = getIcsEventsAsArray($value);
  1102. if (isset($icsEvents) && !empty($icsEvents)) {
  1103. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1104. unset($icsEvents [1]);
  1105. foreach ($icsEvents as $icsEvent) {
  1106. if ((isset($icsEvent['DTSTART']) || isset($icsEvent['DTSTART;VALUE=DATE'])) && (isset($icsEvent['DTEND']) || isset($icsEvent['DTEND;VALUE=DATE'])) && isset($icsEvent['SUMMARY'])) {
  1107. /* Getting start date and time */
  1108. $start = isset($icsEvent ['DTSTART;VALUE=DATE']) ? $icsEvent ['DTSTART;VALUE=DATE'] : $icsEvent ['DTSTART'];
  1109. /* Converting to datetime and apply the timezone to get proper date time */
  1110. $startDt = new DateTime ($start);
  1111. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1112. $startDate = $startDt->format(DateTime::ATOM);
  1113. /* Getting end date with time */
  1114. $end = isset($icsEvent ['DTEND;VALUE=DATE']) ? $icsEvent ['DTEND;VALUE=DATE'] : $icsEvent ['DTEND'];
  1115. $endDt = new DateTime ($end);
  1116. $endDate = $endDt->format(DateTime::ATOM);
  1117. if (new DateTime() < $endDt) {
  1118. $extraClass = 'text-info';
  1119. } else {
  1120. $extraClass = 'text-success';
  1121. }
  1122. /* Getting the name of event */
  1123. $eventName = $icsEvent['SUMMARY'];
  1124. $icalEvents[] = array(
  1125. 'title' => $eventName,
  1126. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1127. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1128. 'start' => $startDate,
  1129. 'end' => $endDate
  1130. );
  1131. }
  1132. }
  1133. }
  1134. }
  1135. $calendarSources['ical'] = $icalEvents;
  1136. }
  1137. $calendarSources['events'] = $calendarItems;
  1138. return ($calendarSources) ? $calendarSources : false;
  1139. }
  1140. function getSonarrCalendar($array, $number)
  1141. {
  1142. $array = json_decode($array, true);
  1143. $gotCalendar = array();
  1144. $i = 0;
  1145. foreach ($array as $child) {
  1146. $i++;
  1147. $seriesName = $child['series']['title'];
  1148. $seriesID = $child['series']['tvdbId'];
  1149. $episodeID = $child['series']['tvdbId'];
  1150. $monitored = $child['monitored'];
  1151. if (!isset($episodeID)) {
  1152. $episodeID = "";
  1153. }
  1154. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1155. $episodeAirDate = $child['airDateUtc'];
  1156. $episodeAirDate = strtotime($episodeAirDate);
  1157. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1158. if (new DateTime() < new DateTime($episodeAirDate)) {
  1159. $unaired = true;
  1160. }
  1161. if ($child['episodeNumber'] == "1") {
  1162. $episodePremier = "true";
  1163. } else {
  1164. $episodePremier = "false";
  1165. $date = new DateTime($episodeAirDate);
  1166. $date->add(new DateInterval("PT1S"));
  1167. $date->format(DateTime::ATOM);
  1168. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1169. }
  1170. $downloaded = $child['hasFile'];
  1171. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1172. $downloaded = "text-primary animated flash";
  1173. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1174. $downloaded = "text-dark";
  1175. } elseif ($downloaded == "0" && isset($unaired)) {
  1176. $downloaded = "text-info";
  1177. } elseif ($downloaded == "1") {
  1178. $downloaded = "text-success";
  1179. } else {
  1180. $downloaded = "text-danger";
  1181. }
  1182. $fanart = "/plugins/images/cache/no-np.png";
  1183. foreach ($child['series']['images'] as $image) {
  1184. if ($image['coverType'] == "fanart") {
  1185. $fanart = $image['url'];
  1186. }
  1187. }
  1188. if ($fanart !== "/plugins/images/cache/no-np.png") {
  1189. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1190. $imageURL = $fanart;
  1191. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1192. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1193. if (!file_exists($cacheFile)) {
  1194. cacheImage($imageURL, $seriesID);
  1195. unset($imageURL);
  1196. unset($cacheFile);
  1197. }
  1198. }
  1199. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1200. $details = array(
  1201. "seasonCount" => $child['series']['seasonCount'],
  1202. "status" => $child['series']['status'],
  1203. "topTitle" => $seriesName,
  1204. "bottomTitle" => $bottomTitle,
  1205. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1206. "runtime" => $child['series']['runtime'],
  1207. "image" => $fanart,
  1208. "ratings" => $child['series']['ratings']['value'],
  1209. "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1210. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1211. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1212. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1213. "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
  1214. "genres" => $child['series']['genres'],
  1215. );
  1216. array_push($gotCalendar, array(
  1217. "id" => "Sonarr-" . $number . "-" . $i,
  1218. "title" => $seriesName,
  1219. "start" => $child['airDateUtc'],
  1220. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1221. "imagetype" => "tv " . $downloaded,
  1222. "imagetypeFilter" => "tv",
  1223. "downloadFilter" => $downloaded,
  1224. "bgColor" => str_replace('text', 'bg', $downloaded),
  1225. "details" => $details
  1226. ));
  1227. }
  1228. if ($i != 0) {
  1229. return $gotCalendar;
  1230. }
  1231. return false;
  1232. }
  1233. function getLidarrCalendar($array, $number)
  1234. {
  1235. $array = json_decode($array, true);
  1236. $gotCalendar = array();
  1237. $i = 0;
  1238. foreach ($array as $child) {
  1239. $i++;
  1240. $albumName = $child['title'];
  1241. $artistName = $child['artist']['artistName'];
  1242. $albumID = '';
  1243. $releaseDate = $child['releaseDate'];
  1244. $releaseDate = strtotime($releaseDate);
  1245. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1246. if (new DateTime() < new DateTime($releaseDate)) {
  1247. $unaired = true;
  1248. }
  1249. $downloaded = (isset($child['statistics']['percentOfEpisodes']) && $child['statistics']['percentOfEpisodes'] !== '100.0') ? '0' : '1';
  1250. if ($downloaded == "0" && isset($unaired)) {
  1251. $downloaded = "text-info";
  1252. } elseif ($downloaded == "1") {
  1253. $downloaded = "text-success";
  1254. } else {
  1255. $downloaded = "text-danger";
  1256. }
  1257. $fanart = "/plugins/images/cache/no-np.png";
  1258. foreach ($child['artist']['images'] as $image) {
  1259. if ($image['coverType'] == "fanart") {
  1260. $fanart = str_replace('http://', 'https://', $image['url']);
  1261. }
  1262. }
  1263. $details = array(
  1264. "seasonCount" => '',
  1265. "status" => '',
  1266. "topTitle" => $albumName,
  1267. "bottomTitle" => $artistName,
  1268. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1269. "runtime" => '',
  1270. "image" => $fanart,
  1271. "ratings" => $child['artist']['ratings']['value'],
  1272. "videoQuality" => "unknown",
  1273. "audioChannels" => "unknown",
  1274. "audioCodec" => "unknown",
  1275. "videoCodec" => "unknown",
  1276. "size" => "unknown",
  1277. "genres" => $child['genres'],
  1278. );
  1279. array_push($gotCalendar, array(
  1280. "id" => "Lidarr-" . $number . "-" . $i,
  1281. "title" => $artistName,
  1282. "start" => $child['releaseDate'],
  1283. "className" => "bg-calendar calendar-item musicID--",
  1284. "imagetype" => "music " . $downloaded,
  1285. "imagetypeFilter" => "music",
  1286. "downloadFilter" => $downloaded,
  1287. "bgColor" => str_replace('text', 'bg', $downloaded),
  1288. "details" => $details
  1289. ));
  1290. }
  1291. if ($i != 0) {
  1292. return $gotCalendar;
  1293. }
  1294. return false;
  1295. }
  1296. function getRadarrCalendar($array, $number, $url)
  1297. {
  1298. $array = json_decode($array, true);
  1299. $gotCalendar = array();
  1300. $i = 0;
  1301. foreach ($array as $child) {
  1302. if (isset($child['physicalRelease'])) {
  1303. $i++;
  1304. $movieName = $child['title'];
  1305. $movieID = $child['tmdbId'];
  1306. if (!isset($movieID)) {
  1307. $movieID = "";
  1308. }
  1309. $physicalRelease = $child['physicalRelease'];
  1310. $physicalRelease = strtotime($physicalRelease);
  1311. $physicalRelease = date("Y-m-d", $physicalRelease);
  1312. if (new DateTime() < new DateTime($physicalRelease)) {
  1313. $notReleased = "true";
  1314. } else {
  1315. $notReleased = "false";
  1316. }
  1317. $downloaded = $child['hasFile'];
  1318. if ($downloaded == "0" && $notReleased == "true") {
  1319. $downloaded = "text-info";
  1320. } elseif ($downloaded == "1") {
  1321. $downloaded = "text-success";
  1322. } else {
  1323. $downloaded = "text-danger";
  1324. }
  1325. $banner = "/plugins/images/cache/no-np.png";
  1326. foreach ($child['images'] as $image) {
  1327. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1328. $url = rtrim($url, '/'); //remove trailing slash
  1329. $imageUrl = $image['url'];
  1330. $urlParts = explode("/", $url);
  1331. $imageParts = explode("/", $image['url']);
  1332. if ($imageParts[1] == end($urlParts)) {
  1333. unset($imageParts[1]);
  1334. $imageUrl = implode("/", $imageParts);
  1335. }
  1336. $banner = $url . $imageUrl;
  1337. }
  1338. }
  1339. if ($banner !== "/plugins/images/cache/no-np.png") {
  1340. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1341. $imageURL = $banner;
  1342. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1343. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1344. if (!file_exists($cacheFile)) {
  1345. cacheImage($imageURL, $movieID);
  1346. unset($imageURL);
  1347. unset($cacheFile);
  1348. }
  1349. }
  1350. $alternativeTitles = "";
  1351. foreach ($child['alternativeTitles'] as $alternative) {
  1352. $alternativeTitles .= $alternative['title'] . ', ';
  1353. }
  1354. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1355. $details = array(
  1356. "topTitle" => $movieName,
  1357. "bottomTitle" => $alternativeTitles,
  1358. "status" => $child['status'],
  1359. "overview" => $child['overview'],
  1360. "runtime" => $child['runtime'],
  1361. "image" => $banner,
  1362. "ratings" => $child['ratings']['value'],
  1363. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1364. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1365. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1366. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1367. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1368. "genres" => $child['genres'],
  1369. );
  1370. array_push($gotCalendar, array(
  1371. "id" => "Radarr-" . $number . "-" . $i,
  1372. "title" => $movieName,
  1373. "start" => $physicalRelease,
  1374. "className" => "bg-calendar movieID--" . $movieID,
  1375. "imagetype" => "film " . $downloaded,
  1376. "imagetypeFilter" => "film",
  1377. "downloadFilter" => $downloaded,
  1378. "bgColor" => str_replace('text', 'bg', $downloaded),
  1379. "details" => $details
  1380. ));
  1381. }
  1382. }
  1383. if ($i != 0) {
  1384. return $gotCalendar;
  1385. }
  1386. return false;
  1387. }
  1388. function getCouchCalendar($array, $number)
  1389. {
  1390. $api = json_decode($array, true);
  1391. $gotCalendar = array();
  1392. $i = 0;
  1393. foreach ($api['movies'] as $child) {
  1394. if ($child['status'] == "active" || $child['status'] == "done") {
  1395. $i++;
  1396. $movieName = $child['info']['original_title'];
  1397. $movieID = $child['info']['tmdb_id'];
  1398. if (!isset($movieID)) {
  1399. $movieID = "";
  1400. }
  1401. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1402. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1403. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1404. $physicalRelease = strtotime($physicalRelease);
  1405. $physicalRelease = date("Y-m-d", $physicalRelease);
  1406. if (new DateTime() < new DateTime($physicalRelease)) {
  1407. $notReleased = "true";
  1408. } else {
  1409. $notReleased = "false";
  1410. }
  1411. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1412. if ($downloaded == "0" && $notReleased == "true") {
  1413. $downloaded = "text-info";
  1414. } elseif ($downloaded == "1") {
  1415. $downloaded = "text-success";
  1416. } else {
  1417. $downloaded = "text-danger";
  1418. }
  1419. if (!empty($child['info']['images']['backdrop_original'])) {
  1420. $banner = $child['info']['images']['backdrop_original'][0];
  1421. } elseif (!empty($child['info']['images']['backdrop'])) {
  1422. $banner = $child['info']['images']['backdrop_original'][0];
  1423. } else {
  1424. $banner = "/plugins/images/cache/no-np.png";
  1425. }
  1426. if ($banner !== "/plugins/images/cache/no-np.png") {
  1427. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1428. $imageURL = $banner;
  1429. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1430. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1431. if (!file_exists($cacheFile)) {
  1432. cacheImage($imageURL, $movieID);
  1433. unset($imageURL);
  1434. unset($cacheFile);
  1435. }
  1436. }
  1437. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1438. $details = array(
  1439. "topTitle" => $movieName,
  1440. "bottomTitle" => $child['info']['tagline'],
  1441. "status" => $child['status'],
  1442. "overview" => $child['info']['plot'],
  1443. "runtime" => $child['info']['runtime'],
  1444. "image" => $banner,
  1445. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1446. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1447. "audioChannels" => "",
  1448. "audioCodec" => "",
  1449. "videoCodec" => "",
  1450. "genres" => $child['info']['genres'],
  1451. );
  1452. array_push($gotCalendar, array(
  1453. "id" => "CouchPotato-" . $number . "-" . $i,
  1454. "title" => $movieName,
  1455. "start" => $physicalRelease,
  1456. "className" => "bg-calendar calendar-item movieID--" . $movieID,
  1457. "imagetype" => "film " . $downloaded,
  1458. "imagetypeFilter" => "film",
  1459. "downloadFilter" => $downloaded,
  1460. "bgColor" => str_replace('text', 'bg', $downloaded),
  1461. "details" => $details
  1462. ));
  1463. }
  1464. }
  1465. if ($i != 0) {
  1466. return $gotCalendar;
  1467. }
  1468. return false;
  1469. }
  1470. function getSickrageCalendarWanted($array, $number)
  1471. {
  1472. $array = json_decode($array, true);
  1473. $gotCalendar = array();
  1474. $i = 0;
  1475. foreach ($array['data']['missed'] as $child) {
  1476. $i++;
  1477. $seriesName = $child['show_name'];
  1478. $seriesID = $child['tvdbid'];
  1479. $episodeID = $child['tvdbid'];
  1480. $episodeAirDate = $child['airdate'];
  1481. $episodeAirDateTime = explode(" ", $child['airs']);
  1482. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1483. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1484. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1485. if (new DateTime() < new DateTime($episodeAirDate)) {
  1486. $unaired = true;
  1487. }
  1488. $downloaded = "0";
  1489. if ($downloaded == "0" && isset($unaired)) {
  1490. $downloaded = "text-info";
  1491. } elseif ($downloaded == "1") {
  1492. $downloaded = "text-success";
  1493. } else {
  1494. $downloaded = "text-danger";
  1495. }
  1496. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1497. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1498. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1499. $fanart = "/plugins/images/cache/no-np.png";
  1500. if (file_exists($cacheFile)) {
  1501. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1502. unset($cacheFile);
  1503. }
  1504. $details = array(
  1505. "seasonCount" => "",
  1506. "status" => $child['show_status'],
  1507. "topTitle" => $seriesName,
  1508. "bottomTitle" => $bottomTitle,
  1509. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1510. "runtime" => "",
  1511. "image" => $fanart,
  1512. "ratings" => "",
  1513. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1514. "audioChannels" => "",
  1515. "audioCodec" => "",
  1516. "videoCodec" => "",
  1517. "size" => "",
  1518. "genres" => "",
  1519. );
  1520. array_push($gotCalendar, array(
  1521. "id" => "Sick-" . $number . "-Miss-" . $i,
  1522. "title" => $seriesName,
  1523. "start" => $episodeAirDate,
  1524. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1525. "imagetype" => "tv " . $downloaded,
  1526. "imagetypeFilter" => "tv",
  1527. "downloadFilter" => $downloaded,
  1528. "bgColor" => str_replace('text', 'bg', $downloaded),
  1529. "details" => $details,
  1530. ));
  1531. }
  1532. foreach ($array['data']['today'] as $child) {
  1533. $i++;
  1534. $seriesName = $child['show_name'];
  1535. $seriesID = $child['tvdbid'];
  1536. $episodeID = $child['tvdbid'];
  1537. $episodeAirDate = $child['airdate'];
  1538. $episodeAirDateTime = explode(" ", $child['airs']);
  1539. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1540. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1541. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1542. if (new DateTime() < new DateTime($episodeAirDate)) {
  1543. $unaired = true;
  1544. }
  1545. $downloaded = "0";
  1546. if ($downloaded == "0" && isset($unaired)) {
  1547. $downloaded = "text-info";
  1548. } elseif ($downloaded == "1") {
  1549. $downloaded = "text-success";
  1550. } else {
  1551. $downloaded = "text-danger";
  1552. }
  1553. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1554. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1555. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1556. $fanart = "/plugins/images/cache/no-np.png";
  1557. if (file_exists($cacheFile)) {
  1558. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1559. unset($cacheFile);
  1560. }
  1561. $details = array(
  1562. "seasonCount" => "",
  1563. "status" => $child['show_status'],
  1564. "topTitle" => $seriesName,
  1565. "bottomTitle" => $bottomTitle,
  1566. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1567. "runtime" => "",
  1568. "image" => $fanart,
  1569. "ratings" => "",
  1570. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1571. "audioChannels" => "",
  1572. "audioCodec" => "",
  1573. "videoCodec" => "",
  1574. "size" => "",
  1575. "genres" => "",
  1576. );
  1577. array_push($gotCalendar, array(
  1578. "id" => "Sick-" . $number . "-Today-" . $i,
  1579. "title" => $seriesName,
  1580. "start" => $episodeAirDate,
  1581. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1582. "imagetype" => "tv " . $downloaded,
  1583. "imagetypeFilter" => "tv",
  1584. "downloadFilter" => $downloaded,
  1585. "bgColor" => str_replace('text', 'bg', $downloaded),
  1586. "details" => $details,
  1587. ));
  1588. }
  1589. foreach ($array['data']['soon'] as $child) {
  1590. $i++;
  1591. $seriesName = $child['show_name'];
  1592. $seriesID = $child['tvdbid'];
  1593. $episodeID = $child['tvdbid'];
  1594. $episodeAirDate = $child['airdate'];
  1595. $episodeAirDateTime = explode(" ", $child['airs']);
  1596. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1597. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1598. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1599. if (new DateTime() < new DateTime($episodeAirDate)) {
  1600. $unaired = true;
  1601. }
  1602. $downloaded = "0";
  1603. if ($downloaded == "0" && isset($unaired)) {
  1604. $downloaded = "text-info";
  1605. } elseif ($downloaded == "1") {
  1606. $downloaded = "text-success";
  1607. } else {
  1608. $downloaded = "text-danger";
  1609. }
  1610. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1611. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1612. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1613. $fanart = "/plugins/images/cache/no-np.png";
  1614. if (file_exists($cacheFile)) {
  1615. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1616. unset($cacheFile);
  1617. }
  1618. $details = array(
  1619. "seasonCount" => "",
  1620. "status" => $child['show_status'],
  1621. "topTitle" => $seriesName,
  1622. "bottomTitle" => $bottomTitle,
  1623. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1624. "runtime" => "",
  1625. "image" => $fanart,
  1626. "ratings" => "",
  1627. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1628. "audioChannels" => "",
  1629. "audioCodec" => "",
  1630. "videoCodec" => "",
  1631. "size" => "",
  1632. "genres" => "",
  1633. );
  1634. array_push($gotCalendar, array(
  1635. "id" => "Sick-" . $number . "-Soon-" . $i,
  1636. "title" => $seriesName,
  1637. "start" => $episodeAirDate,
  1638. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1639. "imagetype" => "tv " . $downloaded,
  1640. "imagetypeFilter" => "tv",
  1641. "downloadFilter" => $downloaded,
  1642. "bgColor" => str_replace('text', 'bg', $downloaded),
  1643. "details" => $details,
  1644. ));
  1645. }
  1646. foreach ($array['data']['later'] as $child) {
  1647. $i++;
  1648. $seriesName = $child['show_name'];
  1649. $seriesID = $child['tvdbid'];
  1650. $episodeID = $child['tvdbid'];
  1651. $episodeAirDate = $child['airdate'];
  1652. $episodeAirDateTime = explode(" ", $child['airs']);
  1653. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1654. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1655. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1656. if (new DateTime() < new DateTime($episodeAirDate)) {
  1657. $unaired = true;
  1658. }
  1659. $downloaded = "0";
  1660. if ($downloaded == "0" && isset($unaired)) {
  1661. $downloaded = "text-info";
  1662. } elseif ($downloaded == "1") {
  1663. $downloaded = "text-success";
  1664. } else {
  1665. $downloaded = "text-danger";
  1666. }
  1667. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1668. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1669. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1670. $fanart = "/plugins/images/cache/no-np.png";
  1671. if (file_exists($cacheFile)) {
  1672. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1673. unset($cacheFile);
  1674. }
  1675. $details = array(
  1676. "seasonCount" => "",
  1677. "status" => $child['show_status'],
  1678. "topTitle" => $seriesName,
  1679. "bottomTitle" => $bottomTitle,
  1680. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1681. "runtime" => "",
  1682. "image" => $fanart,
  1683. "ratings" => "",
  1684. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1685. "audioChannels" => "",
  1686. "audioCodec" => "",
  1687. "videoCodec" => "",
  1688. "size" => "",
  1689. "genres" => "",
  1690. );
  1691. array_push($gotCalendar, array(
  1692. "id" => "Sick-" . $number . "-Later-" . $i,
  1693. "title" => $seriesName,
  1694. "start" => $episodeAirDate,
  1695. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1696. "imagetype" => "tv " . $downloaded,
  1697. "imagetypeFilter" => "tv",
  1698. "downloadFilter" => $downloaded,
  1699. "bgColor" => str_replace('text', 'bg', $downloaded),
  1700. "details" => $details,
  1701. ));
  1702. }
  1703. if ($i != 0) {
  1704. return $gotCalendar;
  1705. }
  1706. return false;
  1707. }
  1708. function getSickrageCalendarHistory($array, $number)
  1709. {
  1710. $array = json_decode($array, true);
  1711. $gotCalendar = array();
  1712. $i = 0;
  1713. foreach ($array['data'] as $child) {
  1714. $i++;
  1715. $seriesName = $child['show_name'];
  1716. $seriesID = $child['tvdbid'];
  1717. $episodeID = $child['tvdbid'];
  1718. $episodeAirDate = $child['date'];
  1719. $downloaded = "text-success";
  1720. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  1721. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1722. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1723. $fanart = "/plugins/images/cache/no-np.png";
  1724. if (file_exists($cacheFile)) {
  1725. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1726. unset($cacheFile);
  1727. }
  1728. $details = array(
  1729. "seasonCount" => "",
  1730. "status" => $child['status'],
  1731. "topTitle" => $seriesName,
  1732. "bottomTitle" => $bottomTitle,
  1733. "overview" => '',
  1734. "runtime" => $child['series']['runtime'],
  1735. "image" => $fanart,
  1736. "ratings" => $child['series']['ratings']['value'],
  1737. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  1738. "audioChannels" => "",
  1739. "audioCodec" => "",
  1740. "videoCodec" => "",
  1741. "size" => "",
  1742. "genres" => "",
  1743. );
  1744. array_push($gotCalendar, array(
  1745. "id" => "Sick-" . $number . "-History-" . $i,
  1746. "title" => $seriesName,
  1747. "start" => $episodeAirDate,
  1748. "className" => "bg-calendar calendar-item tvID--" . $episodeID,
  1749. "imagetype" => "tv " . $downloaded,
  1750. "imagetypeFilter" => "tv",
  1751. "downloadFilter" => $downloaded,
  1752. "bgColor" => str_replace('text', 'bg', $downloaded),
  1753. "details" => $details,
  1754. ));
  1755. }
  1756. if ($i != 0) {
  1757. return $gotCalendar;
  1758. }
  1759. return false;
  1760. }
  1761. function ombiAPI($array)
  1762. {
  1763. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type']);
  1764. }
  1765. function ombiImport($type = null)
  1766. {
  1767. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  1768. try {
  1769. $url = qualifyURL($GLOBALS['ombiURL']);
  1770. $headers = array(
  1771. "Accept" => "application/json",
  1772. "Content-Type" => "application/json",
  1773. "Apikey" => $GLOBALS['ombiToken']
  1774. );
  1775. $options = (localURL($url)) ? array('verify' => false) : array();
  1776. switch ($type) {
  1777. case 'emby':
  1778. case 'emby_local':
  1779. case 'emby_connect':
  1780. case 'emby_all':
  1781. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  1782. break;
  1783. case 'plex':
  1784. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  1785. break;
  1786. default:
  1787. break;
  1788. }
  1789. if ($response->success) {
  1790. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  1791. return true;
  1792. } else {
  1793. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  1794. return false;
  1795. }
  1796. } catch (Requests_Exception $e) {
  1797. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1798. return false;
  1799. };
  1800. }
  1801. return false;
  1802. }
  1803. function ombiAction($id, $action, $type)
  1804. {
  1805. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1806. $url = qualifyURL($GLOBALS['ombiURL']);
  1807. $headers = array(
  1808. "Accept" => "application/json",
  1809. "Content-Type" => "application/json",
  1810. "Apikey" => $GLOBALS['ombiToken']
  1811. );
  1812. $data = array(
  1813. 'id' => $id,
  1814. );
  1815. switch ($type) {
  1816. case 'season':
  1817. case 'tv':
  1818. $type = 'tv';
  1819. $add = array(
  1820. 'tvDbId' => $id,
  1821. 'requestAll' => true,
  1822. 'latestSeason' => true,
  1823. 'firstSeason' => true
  1824. );
  1825. break;
  1826. default:
  1827. $type = 'movie';
  1828. $add = array("theMovieDbId" => (int)$id);
  1829. break;
  1830. }
  1831. $success['head'] = $headers;
  1832. $success['act'] = $action;
  1833. $success['data'] = $data;
  1834. $success['add'] = $add;
  1835. $success['type'] = $type;
  1836. try {
  1837. $options = (localURL($url)) ? array('verify' => false) : array();
  1838. switch ($action) {
  1839. case 'add':
  1840. if (isset($_COOKIE['Auth'])) {
  1841. $headers = array(
  1842. "Accept" => "application/json",
  1843. "Content-Type" => "application/json",
  1844. "Authorization" => "Bearer " . $_COOKIE['Auth']
  1845. );
  1846. $success['head'] = $headers;
  1847. } else {
  1848. return false;
  1849. }
  1850. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  1851. break;
  1852. default:
  1853. if (qualifyRequest(1)) {
  1854. switch ($action) {
  1855. case 'approve':
  1856. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  1857. break;
  1858. case 'available':
  1859. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  1860. break;
  1861. case 'unavailable':
  1862. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  1863. break;
  1864. case 'deny':
  1865. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  1866. break;
  1867. case 'delete':
  1868. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  1869. break;
  1870. default:
  1871. return false;
  1872. }
  1873. }
  1874. break;
  1875. }
  1876. $success['api'] = $response;
  1877. $success['bd'] = $response->body;
  1878. $success['hd'] = $response->headers;
  1879. if ($response->success) {
  1880. $success['ok'] = true;
  1881. }
  1882. } catch (Requests_Exception $e) {
  1883. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1884. };
  1885. }
  1886. return isset($success['ok']) ? $success : false;
  1887. }
  1888. function getOmbiRequests($type = "both")
  1889. {
  1890. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  1891. $url = qualifyURL($GLOBALS['ombiURL']);
  1892. $headers = array(
  1893. "Accept" => "application/json",
  1894. "Apikey" => $GLOBALS['ombiToken'],
  1895. );
  1896. $requests = array();
  1897. try {
  1898. $options = (localURL($url)) ? array('verify' => false) : array();
  1899. switch ($type) {
  1900. case 'movie':
  1901. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  1902. break;
  1903. case 'tv':
  1904. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  1905. break;
  1906. default:
  1907. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  1908. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  1909. break;
  1910. }
  1911. if ($movie->success || $tv->success) {
  1912. if (isset($movie)) {
  1913. $movie = json_decode($movie->body, true);
  1914. //$movie = array_reverse($movie);
  1915. foreach ($movie as $key => $value) {
  1916. $requests[] = array(
  1917. 'test' => $value,
  1918. 'id' => $value['theMovieDbId'],
  1919. 'title' => $value['title'],
  1920. 'overview' => $value['overview'],
  1921. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
  1922. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  1923. 'approved' => $value['approved'],
  1924. 'available' => $value['available'],
  1925. 'denied' => $value['denied'],
  1926. 'deniedReason' => $value['deniedReason'],
  1927. 'user' => $value['requestedUser']['userName'],
  1928. 'request_id' => $value['id'],
  1929. 'request_date' => $value['requestedDate'],
  1930. 'release_date' => $value['releaseDate'],
  1931. 'type' => 'movie',
  1932. 'icon' => 'mdi mdi-filmstrip',
  1933. 'color' => 'palette-Deep-Purple-900 bg white',
  1934. );
  1935. }
  1936. }
  1937. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  1938. $tv = json_decode($tv->body, true);
  1939. foreach ($tv as $key => $value) {
  1940. if (is_array($value['childRequests'][0])) {
  1941. $requests[] = array(
  1942. 'test' => $value,
  1943. 'id' => $value['tvDbId'],
  1944. 'title' => $value['title'],
  1945. 'overview' => $value['overview'],
  1946. 'poster' => $value['posterPath'],
  1947. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  1948. 'approved' => $value['childRequests'][0]['approved'],
  1949. 'available' => $value['childRequests'][0]['available'],
  1950. 'denied' => $value['childRequests'][0]['denied'],
  1951. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  1952. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  1953. 'request_id' => $value['id'],
  1954. 'request_date' => $value['childRequests'][0]['requestedDate'],
  1955. 'release_date' => $value['releaseDate'],
  1956. 'type' => 'tv',
  1957. 'icon' => 'mdi mdi-television',
  1958. 'color' => 'grayish-blue-bg',
  1959. );
  1960. }
  1961. }
  1962. }
  1963. //sort here
  1964. usort($requests, function ($item1, $item2) {
  1965. if ($item1['request_date'] == $item2['request_date']) {
  1966. return 0;
  1967. }
  1968. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  1969. });
  1970. }
  1971. } catch (Requests_Exception $e) {
  1972. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1973. };
  1974. }
  1975. $api['content'] = isset($requests) ? $requests : false;
  1976. return $api;
  1977. }
  1978. function testAPIConnection($array)
  1979. {
  1980. switch ($array['data']['action']) {
  1981. case 'plex':
  1982. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  1983. $url = qualifyURL($GLOBALS['plexURL']);
  1984. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  1985. try {
  1986. $options = (localURL($url)) ? array('verify' => false) : array();
  1987. $response = Requests::get($url, array(), $options);
  1988. libxml_use_internal_errors(true);
  1989. if ($response->success) {
  1990. return true;
  1991. }
  1992. } catch (Requests_Exception $e) {
  1993. return $e->getMessage();
  1994. };
  1995. } else {
  1996. return 'URL and/or Token not setup';
  1997. }
  1998. break;
  1999. case 'emby':
  2000. break;
  2001. case 'sonarr':
  2002. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2003. $sonarrs = array();
  2004. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2005. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2006. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2007. foreach ($sonarrURLList as $key => $value) {
  2008. $sonarrs[$key] = array(
  2009. 'url' => $value,
  2010. 'token' => $sonarrTokenList[$key]
  2011. );
  2012. }
  2013. foreach ($sonarrs as $key => $value) {
  2014. try {
  2015. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2016. $sonarr->getSystemStatus();
  2017. return true;
  2018. } catch (Exception $e) {
  2019. return $e->getMessage();
  2020. }
  2021. }
  2022. }
  2023. } else {
  2024. return 'URL/s and/or Token/s not setup';
  2025. }
  2026. break;
  2027. case 'lidarr':
  2028. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2029. $sonarrs = array();
  2030. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2031. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2032. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2033. foreach ($sonarrURLList as $key => $value) {
  2034. $sonarrs[$key] = array(
  2035. 'url' => $value,
  2036. 'token' => $sonarrTokenList[$key]
  2037. );
  2038. }
  2039. foreach ($sonarrs as $key => $value) {
  2040. try {
  2041. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2042. $sonarr->getSystemStatus();
  2043. return true;
  2044. } catch (Exception $e) {
  2045. return $e->getMessage();
  2046. }
  2047. }
  2048. }
  2049. } else {
  2050. return 'URL/s and/or Token/s not setup';
  2051. }
  2052. break;
  2053. case 'radarr':
  2054. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2055. $sonarrs = array();
  2056. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2057. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2058. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2059. foreach ($sonarrURLList as $key => $value) {
  2060. $sonarrs[$key] = array(
  2061. 'url' => $value,
  2062. 'token' => $sonarrTokenList[$key]
  2063. );
  2064. }
  2065. foreach ($sonarrs as $key => $value) {
  2066. try {
  2067. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2068. $sonarr->getSystemStatus();
  2069. return true;
  2070. } catch (Exception $e) {
  2071. return $e->getMessage();
  2072. }
  2073. }
  2074. }
  2075. } else {
  2076. return 'URL/s and/or Token/s not setup';
  2077. }
  2078. break;
  2079. case 'sabnzbd':
  2080. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2081. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2082. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2083. try {
  2084. $options = (localURL($url)) ? array('verify' => false) : array();
  2085. $response = Requests::get($url, array(), $options);
  2086. if ($response->success) {
  2087. return true;
  2088. }
  2089. } catch (Requests_Exception $e) {
  2090. return $e->getMessage();
  2091. };
  2092. } else {
  2093. return 'URL and/or Token not setup';
  2094. }
  2095. break;
  2096. case 'nzbget':
  2097. if (!empty($GLOBALS['nzbgetURL'])) {
  2098. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2099. if (!empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
  2100. $url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
  2101. } else {
  2102. $url = $url . '/jsonrpc/listgroups';
  2103. }
  2104. try {
  2105. $options = (localURL($url)) ? array('verify' => false) : array();
  2106. $response = Requests::get($url, array(), $options);
  2107. if ($response->success) {
  2108. return true;
  2109. }
  2110. } catch (Requests_Exception $e) {
  2111. return $e->getMessage();
  2112. };
  2113. } else {
  2114. return 'URL and/or Username/Password not setup';
  2115. }
  2116. break;
  2117. case 'deluge':
  2118. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2119. try {
  2120. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2121. $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');
  2122. return true;
  2123. } catch (Exception $e) {
  2124. return $e->getMessage();
  2125. }
  2126. } else {
  2127. return 'URL and/or Password not setup';
  2128. }
  2129. break;
  2130. case 'rtorrent':
  2131. if (!empty($GLOBALS['rTorrentURL'])) {
  2132. try {
  2133. $digest = qualifyURL($GLOBALS['rTorrentURL'], true);
  2134. $passwordInclude = ($GLOBALS['rTorrentUsername'] != '' && $GLOBALS['rTorrentPassword'] != '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2135. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2136. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2137. $options = (localURL($url)) ? array('verify' => false) : array();
  2138. $data = xmlrpc_encode_request("system.listMethods", null);
  2139. $response = Requests::post($url, array(), $data, $options);
  2140. if ($response->success) {
  2141. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2142. if (count($methods) !== 0) {
  2143. return true;
  2144. }
  2145. }
  2146. return false;
  2147. } catch
  2148. (Requests_Exception $e) {
  2149. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2150. return $e->getMessage();
  2151. };
  2152. }
  2153. break;
  2154. default :
  2155. return false;
  2156. }
  2157. return false;
  2158. }