homepage-connect-functions.php 104 KB

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