4
0

homepage-connect-functions.php 114 KB

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