sonarr.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. trait SonarrHomepageItem
  3. {
  4. public function sonarrSettingsArray($infoOnly = false)
  5. {
  6. $homepageInformation = [
  7. 'name' => 'Sonarr',
  8. 'enabled' => strpos('personal', $this->config['license']) !== false,
  9. 'image' => 'plugins/images/tabs/sonarr.png',
  10. 'category' => 'PVR',
  11. 'settingsArray' => __FUNCTION__
  12. ];
  13. if ($infoOnly) {
  14. return $homepageInformation;
  15. }
  16. $homepageSettings = [
  17. 'docs' => $this->docs('features/homepage/sonarr-homepage-item'),
  18. 'debug' => true,
  19. 'settings' => [
  20. 'About' => [
  21. $this->settingsOption('about', 'Sonarr', ['about' => 'This item allows access to Sonarr\'s calendar data and aggregates it to Organizr\'s calendar. Along with that you also have the Downloader function that allow access to Sonarr\'s queue. The last item that is included is the API SOCKS function which acts as a middleman between API\'s which is useful if you are not port forwarding or reverse proxying Sonarr.']),
  22. ],
  23. 'Enable' => [
  24. $this->settingsOption('enable', 'homepageSonarrEnabled'),
  25. $this->settingsOption('auth', 'homepageSonarrAuth'),
  26. ],
  27. 'Connection' => [
  28. $this->settingsOption('multiple-url', 'sonarrURL'),
  29. $this->settingsOption('multiple-token', 'sonarrToken'),
  30. $this->settingsOption('disable-cert-check', 'sonarrDisableCertCheck'),
  31. $this->settingsOption('use-custom-certificate', 'sonarrUseCustomCertificate'),
  32. ],
  33. 'API SOCKS' => [
  34. $this->settingsOption('socks', 'sonarr'),
  35. $this->settingsOption('blank'),
  36. $this->settingsOption('enable', 'sonarrSocksEnabled'),
  37. $this->settingsOption('auth', 'sonarrSocksAuth'),
  38. ],
  39. 'Queue' => [
  40. $this->settingsOption('enable', 'homepageSonarrQueueEnabled'),
  41. $this->settingsOption('auth', 'homepageSonarrQueueAuth'),
  42. $this->settingsOption('combine', 'homepageSonarrQueueCombine'),
  43. $this->settingsOption('refresh', 'homepageSonarrQueueRefresh'),
  44. ],
  45. 'Calendar' => [
  46. $this->settingsOption('calendar-start', 'calendarStart'),
  47. $this->settingsOption('calendar-end', 'calendarEnd'),
  48. $this->settingsOption('calendar-starting-day', 'calendarFirstDay'),
  49. $this->settingsOption('calendar-default-view', 'calendarDefault'),
  50. $this->settingsOption('calendar-time-format', 'calendarTimeFormat'),
  51. $this->settingsOption('calendar-locale', 'calendarLocale'),
  52. $this->settingsOption('calendar-limit', 'calendarLimit'),
  53. $this->settingsOption('refresh', 'calendarRefresh'),
  54. $this->settingsOption('calendar-link-url', 'sonarrCalendarLink'),
  55. $this->settingsOption('calendar-frame-target', 'sonarrFrameTarget'),
  56. $this->settingsOption('blank'),
  57. $this->settingsOption('switch', 'sonarrUnmonitored', ['label' => 'Show Unmonitored']),
  58. ],
  59. 'Test Connection' => [
  60. $this->settingsOption('blank', null, ['label' => 'Please Save before Testing']),
  61. $this->settingsOption('test', 'sonarr'),
  62. ]
  63. ]
  64. ];
  65. return array_merge($homepageInformation, $homepageSettings);
  66. }
  67. public function testConnectionSonarr()
  68. {
  69. if (empty($this->config['sonarrURL'])) {
  70. $this->setAPIResponse('error', 'Sonarr URL is not defined', 422);
  71. return false;
  72. }
  73. if (empty($this->config['sonarrToken'])) {
  74. $this->setAPIResponse('error', 'Sonarr Token is not defined', 422);
  75. return false;
  76. }
  77. $failed = false;
  78. $errors = '';
  79. $list = $this->csvHomepageUrlToken($this->config['sonarrURL'], $this->config['sonarrToken']);
  80. foreach ($list as $key => $value) {
  81. try {
  82. $options = $this->requestOptions($value['url'], null, $this->config['sonarrDisableCertCheck'], $this->config['sonarrUseCustomCertificate']);
  83. $downloader = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], 'sonarr', null, null, $options);
  84. $results = $downloader->getRootFolder();
  85. $downloadList = json_decode($results, true);
  86. if (is_array($downloadList) || is_object($downloadList)) {
  87. $queue = (array_key_exists('error', $downloadList)) ? $downloadList['error']['msg'] : $downloadList;
  88. if (!is_array($queue)) {
  89. $ip = $value['url'];
  90. $errors .= $ip . ': ' . $queue;
  91. $failed = true;
  92. }
  93. } else {
  94. $ip = $value['url'];
  95. $errors .= $ip . ': Response was not JSON';
  96. $failed = true;
  97. }
  98. } catch (Exception $e) {
  99. $failed = true;
  100. $ip = $value['url'];
  101. $errors .= $ip . ': ' . $e->getMessage();
  102. $this->writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  103. }
  104. }
  105. if ($failed) {
  106. $this->setAPIResponse('error', $errors, 500);
  107. return false;
  108. } else {
  109. $this->setAPIResponse('success', null, 200);
  110. return true;
  111. }
  112. }
  113. public function sonarrHomepagePermissions($key = null)
  114. {
  115. $permissions = [
  116. 'calendar' => [
  117. 'enabled' => [
  118. 'homepageSonarrEnabled'
  119. ],
  120. 'auth' => [
  121. 'homepageSonarrAuth'
  122. ],
  123. 'not_empty' => [
  124. 'sonarrURL',
  125. 'sonarrToken'
  126. ]
  127. ],
  128. 'queue' => [
  129. 'enabled' => [
  130. 'homepageSonarrEnabled',
  131. 'homepageSonarrQueueEnabled'
  132. ],
  133. 'auth' => [
  134. 'homepageSonarrAuth',
  135. 'homepageSonarrQueueAuth'
  136. ],
  137. 'not_empty' => [
  138. 'sonarrURL',
  139. 'sonarrToken'
  140. ]
  141. ]
  142. ];
  143. return $this->homepageCheckKeyPermissions($key, $permissions);
  144. }
  145. public function homepageOrderSonarrQueue()
  146. {
  147. if ($this->homepageItemPermissions($this->sonarrHomepagePermissions('queue'))) {
  148. $loadingBox = ($this->config['homepageSonarrQueueCombine']) ? '' : '<div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Download Queue...</h2></div>';
  149. $builder = ($this->config['homepageSonarrQueueCombine']) ? 'buildDownloaderCombined(\'sonarr\');' : '$("#' . __FUNCTION__ . '").html(buildDownloader("sonarr"));';
  150. return '
  151. <div id="' . __FUNCTION__ . '">
  152. ' . $loadingBox . '
  153. <script>
  154. // homepageOrderSonarrQueue
  155. ' . $builder . '
  156. homepageDownloader("sonarr", "' . $this->config['homepageSonarrQueueRefresh'] . '");
  157. // End homepageOrderSonarrQueue
  158. </script>
  159. </div>
  160. ';
  161. }
  162. }
  163. public function getSonarrQueue()
  164. {
  165. if (!$this->homepageItemPermissions($this->sonarrHomepagePermissions('queue'), true)) {
  166. return false;
  167. }
  168. $queueItems = array();
  169. $list = $this->csvHomepageUrlToken($this->config['sonarrURL'], $this->config['sonarrToken']);
  170. foreach ($list as $key => $value) {
  171. try {
  172. $options = $this->requestOptions($value['url'], $this->config['homepageSonarrQueueRefresh'], $this->config['sonarrDisableCertCheck'], $this->config['sonarrUseCustomCertificate']);
  173. $downloader = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], 'sonarr', null, null, $options);
  174. $results = $downloader->getQueue();
  175. $downloadList = json_decode($results, true);
  176. if (is_array($downloadList) || is_object($downloadList)) {
  177. $queue = (array_key_exists('error', $downloadList)) ? [] : $downloadList;
  178. $queue = $queue['records'] ?? $queue;
  179. } else {
  180. $queue = [];
  181. }
  182. if (!empty($queue)) {
  183. $queueItems = array_merge($queueItems, $queue);
  184. }
  185. } catch (Exception $e) {
  186. $this->writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  187. }
  188. }
  189. $api['content']['queueItems'] = $queueItems;
  190. $api['content']['historyItems'] = false;
  191. $api['content'] = $api['content'] ?? false;
  192. $this->setAPIResponse('success', null, 200, $api);
  193. return $api;
  194. }
  195. public function getSonarrCalendar($startDate = null, $endDate = null)
  196. {
  197. $startDate = ($startDate) ?? $_GET['start'] ?? date('Y-m-d', strtotime('-' . $this->config['calendarStart'] . ' days'));
  198. $endDate = ($endDate) ?? $_GET['end'] ?? date('Y-m-d', strtotime('+' . $this->config['calendarEnd'] . ' days'));
  199. if (!$this->homepageItemPermissions($this->sonarrHomepagePermissions('calendar'), true)) {
  200. return false;
  201. }
  202. if ($this->demo) {
  203. return $this->demoData('sonarr/calendar.json');
  204. }
  205. $calendarItems = array();
  206. $list = $this->csvHomepageUrlToken($this->config['sonarrURL'], $this->config['sonarrToken']);
  207. foreach ($list as $key => $value) {
  208. try {
  209. $options = $this->requestOptions($value['url'], null, $this->config['sonarrDisableCertCheck'], $this->config['sonarrUseCustomCertificate']);
  210. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], 'sonarr', null, null, $options);
  211. $sonarr = $sonarr->getCalendar($startDate, $endDate, $this->config['sonarrUnmonitored']);
  212. $result = json_decode($sonarr, true);
  213. if (is_array($result) || is_object($result)) {
  214. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : $this->formatSonarrCalendar($sonarr, $key);
  215. } else {
  216. $sonarrCalendar = '';
  217. }
  218. } catch (Exception $e) {
  219. $this->writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  220. }
  221. if (!empty($sonarrCalendar)) {
  222. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  223. }
  224. }
  225. $this->setAPIResponse('success', null, 200, $calendarItems);
  226. return $calendarItems;
  227. }
  228. public function formatSonarrCalendar($array, $number)
  229. {
  230. $array = json_decode($array, true);
  231. $gotCalendar = array();
  232. $i = 0;
  233. foreach ($array as $child) {
  234. $i++;
  235. $seriesName = $child['series']['title'];
  236. $seriesID = $child['series']['tvdbId'];
  237. $episodeID = $child['series']['tvdbId'];
  238. $monitored = $child['monitored'];
  239. if (!isset($episodeID)) {
  240. $episodeID = "";
  241. }
  242. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  243. $episodeAirDate = $child['airDateUtc'];
  244. $episodeAirDate = strtotime($episodeAirDate);
  245. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  246. if (new DateTime() < new DateTime($episodeAirDate)) {
  247. $unaired = true;
  248. }
  249. if ($child['episodeNumber'] == "1") {
  250. $episodePremier = "true";
  251. } else {
  252. $episodePremier = "false";
  253. $date = new DateTime($episodeAirDate);
  254. $date->add(new DateInterval("PT1S"));
  255. $date->format(DateTime::ATOM);
  256. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  257. }
  258. $downloaded = $child['hasFile'];
  259. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  260. $downloaded = "text-primary animated flash";
  261. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  262. $downloaded = "text-dark";
  263. } elseif ($downloaded == "0" && isset($unaired)) {
  264. $downloaded = "text-info";
  265. } elseif ($downloaded == "1") {
  266. $downloaded = "text-success";
  267. } else {
  268. $downloaded = "text-danger";
  269. }
  270. $fanart = "/plugins/images/cache/no-np.png";
  271. foreach ($child['series']['images'] as $image) {
  272. if ($image['coverType'] == "fanart") {
  273. $fanart = $image['url'];
  274. }
  275. }
  276. if ($fanart !== "/plugins/images/cache/no-np.png" || (strpos($fanart, '://') === false)) {
  277. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  278. $imageURL = $fanart;
  279. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  280. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  281. if (!file_exists($cacheFile)) {
  282. $this->cacheImage($imageURL, $seriesID);
  283. unset($imageURL);
  284. unset($cacheFile);
  285. }
  286. }
  287. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  288. $href = $this->config['sonarrCalendarLink'] ?? '';
  289. if (empty($href) && !empty($this->config['sonarrURL'])){
  290. $href_arr = explode(',',$this->config['sonarrURL']);
  291. $href = reset($href_arr);
  292. }
  293. if (!empty($href)){
  294. $href = $href . '/series/' . preg_replace('/[^A-Za-z0-9. -]/', '', preg_replace('/[[:space:]]+/', '-', $seriesName));
  295. $href = str_replace("//series/","/series/",$href);
  296. }
  297. $details = array(
  298. "seasonCount" => $child['series']['seasonCount'] ?? isset($child['series']['seasons']) ? count($child['series']['seasons']) : 0,
  299. "status" => $child['series']['status'],
  300. "topTitle" => $seriesName,
  301. "bottomTitle" => $bottomTitle,
  302. "overview" => $child['overview'] ?? '',
  303. "runtime" => $child['series']['runtime'],
  304. "image" => $fanart,
  305. "ratings" => $child['series']['ratings']['value'],
  306. "videoQuality" => $child["hasFile"] && isset($child['episodeFile']['quality']['quality']['name']) ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  307. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  308. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  309. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  310. "size" => $child["hasFile"] && isset($child['episodeFile']['size']) ? $child['episodeFile']['size'] : "unknown",
  311. "genres" => $child['series']['genres'],
  312. "href" => strtolower($href),
  313. "icon" => "/plugins/images/tabs/sonarr.png",
  314. "frame" => $this->config['sonarrFrameTarget'] ?? '',
  315. );
  316. array_push($gotCalendar, array(
  317. "id" => "Sonarr-" . $number . "-" . $i,
  318. "title" => $seriesName,
  319. "start" => $child['airDateUtc'],
  320. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  321. "imagetype" => "tv " . $downloaded,
  322. "imagetypeFilter" => "tv",
  323. "downloadFilter" => $downloaded,
  324. "bgColor" => str_replace('text', 'bg', $downloaded),
  325. "details" => $details
  326. ));
  327. }
  328. if ($i != 0) {
  329. return $gotCalendar;
  330. }
  331. return false;
  332. }
  333. }