homepage-connect-functions.php 114 KB

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