sonarr.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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('blank'),
  55. $this->settingsOption('switch', 'sonarrUnmonitored', ['label' => 'Show Unmonitored']),
  56. $this->settingsOption('blank', '', ['type' => 'html', 'html' => '<hr />']),
  57. $this->settingsOption('blank', '', ['type' => 'html', 'html' => '<hr />']),
  58. $this->settingsOption('enable', 'sonarrIcon', ['label' => 'Show Sonarr Icon']),
  59. $this->settingsOption('calendar-link-url', 'sonarrCalendarLink'),
  60. $this->settingsOption('blank'),
  61. $this->settingsOption('calendar-frame-target', 'sonarrFrameTarget')
  62. ],
  63. 'Test Connection' => [
  64. $this->settingsOption('blank', null, ['label' => 'Please Save before Testing']),
  65. $this->settingsOption('test', 'sonarr'),
  66. ]
  67. ]
  68. ];
  69. return array_merge($homepageInformation, $homepageSettings);
  70. }
  71. public function testConnectionSonarr()
  72. {
  73. if (empty($this->config['sonarrURL'])) {
  74. $this->setAPIResponse('error', 'Sonarr URL is not defined', 422);
  75. return false;
  76. }
  77. if (empty($this->config['sonarrToken'])) {
  78. $this->setAPIResponse('error', 'Sonarr Token is not defined', 422);
  79. return false;
  80. }
  81. $failed = false;
  82. $errors = '';
  83. $list = $this->csvHomepageUrlToken($this->config['sonarrURL'], $this->config['sonarrToken']);
  84. foreach ($list as $key => $value) {
  85. try {
  86. $options = $this->requestOptions($value['url'], null, $this->config['sonarrDisableCertCheck'], $this->config['sonarrUseCustomCertificate']);
  87. $downloader = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], 'sonarr', null, null, $options);
  88. $results = $downloader->getRootFolder();
  89. $downloadList = json_decode($results, true);
  90. if (is_array($downloadList) || is_object($downloadList)) {
  91. $queue = (array_key_exists('error', $downloadList)) ? $downloadList['error']['msg'] : $downloadList;
  92. if (!is_array($queue)) {
  93. $ip = $value['url'];
  94. $errors .= $ip . ': ' . $queue;
  95. $failed = true;
  96. }
  97. } else {
  98. $ip = $value['url'];
  99. $errors .= $ip . ': Response was not JSON';
  100. $failed = true;
  101. }
  102. } catch (Exception $e) {
  103. $failed = true;
  104. $ip = $value['url'];
  105. $errors .= $ip . ': ' . $e->getMessage();
  106. $this->setLoggerChannel('Sonarr')->error($e);
  107. }
  108. }
  109. if ($failed) {
  110. $this->setAPIResponse('error', $errors, 500);
  111. return false;
  112. } else {
  113. $this->setAPIResponse('success', null, 200);
  114. return true;
  115. }
  116. }
  117. public function sonarrHomepagePermissions($key = null)
  118. {
  119. $permissions = [
  120. 'calendar' => [
  121. 'enabled' => [
  122. 'homepageSonarrEnabled'
  123. ],
  124. 'auth' => [
  125. 'homepageSonarrAuth'
  126. ],
  127. 'not_empty' => [
  128. 'sonarrURL',
  129. 'sonarrToken'
  130. ]
  131. ],
  132. 'queue' => [
  133. 'enabled' => [
  134. 'homepageSonarrEnabled',
  135. 'homepageSonarrQueueEnabled'
  136. ],
  137. 'auth' => [
  138. 'homepageSonarrAuth',
  139. 'homepageSonarrQueueAuth'
  140. ],
  141. 'not_empty' => [
  142. 'sonarrURL',
  143. 'sonarrToken'
  144. ]
  145. ]
  146. ];
  147. return $this->homepageCheckKeyPermissions($key, $permissions);
  148. }
  149. public function homepageOrderSonarrQueue()
  150. {
  151. if ($this->homepageItemPermissions($this->sonarrHomepagePermissions('queue'))) {
  152. $loadingBox = ($this->config['homepageSonarrQueueCombine']) ? '' : '<div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Download Queue...</h2></div>';
  153. $builder = ($this->config['homepageSonarrQueueCombine']) ? 'buildDownloaderCombined(\'sonarr\');' : '$("#' . __FUNCTION__ . '").html(buildDownloader("sonarr"));';
  154. return '
  155. <div id="' . __FUNCTION__ . '">
  156. ' . $loadingBox . '
  157. <script>
  158. // homepageOrderSonarrQueue
  159. ' . $builder . '
  160. homepageDownloader("sonarr", "' . $this->config['homepageSonarrQueueRefresh'] . '");
  161. // End homepageOrderSonarrQueue
  162. </script>
  163. </div>
  164. ';
  165. }
  166. }
  167. public function getSonarrQueue()
  168. {
  169. if (!$this->homepageItemPermissions($this->sonarrHomepagePermissions('queue'), true)) {
  170. return false;
  171. }
  172. $queueItems = array();
  173. $list = $this->csvHomepageUrlToken($this->config['sonarrURL'], $this->config['sonarrToken']);
  174. foreach ($list as $key => $value) {
  175. try {
  176. $options = $this->requestOptions($value['url'], $this->config['homepageSonarrQueueRefresh'], $this->config['sonarrDisableCertCheck'], $this->config['sonarrUseCustomCertificate']);
  177. $downloader = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], 'sonarr', null, null, $options);
  178. $results = $downloader->getQueue();
  179. $downloadList = json_decode($results, true);
  180. if (is_array($downloadList) || is_object($downloadList)) {
  181. $queue = (array_key_exists('error', $downloadList)) ? [] : $downloadList;
  182. $queue = $queue['records'] ?? $queue;
  183. } else {
  184. $queue = [];
  185. }
  186. if (!empty($queue)) {
  187. $queueItems = array_merge($queueItems, $queue);
  188. }
  189. } catch (Exception $e) {
  190. $this->setLoggerChannel('Sonarr')->error($e);
  191. }
  192. }
  193. $api['content']['queueItems'] = $queueItems;
  194. $api['content']['historyItems'] = false;
  195. $api['content'] = $api['content'] ?? false;
  196. $this->setAPIResponse('success', null, 200, $api);
  197. return $api;
  198. }
  199. public function getSonarrCalendar($startDate = null, $endDate = null)
  200. {
  201. $startDate = ($startDate) ?? $_GET['start'] ?? date('Y-m-d', strtotime('-' . $this->config['calendarStart'] . ' days'));
  202. $endDate = ($endDate) ?? $_GET['end'] ?? date('Y-m-d', strtotime('+' . $this->config['calendarEnd'] . ' days'));
  203. if (!$this->homepageItemPermissions($this->sonarrHomepagePermissions('calendar'), true)) {
  204. return false;
  205. }
  206. if ($this->demo) {
  207. return $this->demoData('sonarr/calendar.json');
  208. }
  209. $calendarItems = array();
  210. $list = $this->csvHomepageUrlToken($this->config['sonarrURL'], $this->config['sonarrToken']);
  211. foreach ($list as $key => $value) {
  212. try {
  213. $options = $this->requestOptions($value['url'], null, $this->config['sonarrDisableCertCheck'], $this->config['sonarrUseCustomCertificate']);
  214. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], 'sonarr', null, null, $options);
  215. $sonarr = $sonarr->getCalendar($startDate, $endDate, $this->config['sonarrUnmonitored']);
  216. $result = json_decode($sonarr, true);
  217. if (is_array($result) || is_object($result)) {
  218. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : $this->formatSonarrCalendar($sonarr, $key);
  219. } else {
  220. $sonarrCalendar = '';
  221. }
  222. } catch (Exception $e) {
  223. $this->setLoggerChannel('Sonarr')->error($e);
  224. }
  225. if (!empty($sonarrCalendar)) {
  226. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  227. }
  228. }
  229. $this->setAPIResponse('success', null, 200, $calendarItems);
  230. return $calendarItems;
  231. }
  232. public function formatSonarrCalendar($array, $number)
  233. {
  234. $array = json_decode($array, true);
  235. $gotCalendar = [];
  236. $i = 0;
  237. foreach ($array as $child) {
  238. $i++;
  239. $seriesName = $child['series']['title'];
  240. $seriesID = $child['series']['tvdbId'];
  241. $episodeID = $child['series']['tvdbId'];
  242. $monitored = $child['monitored'];
  243. if (!isset($episodeID)) {
  244. $episodeID = "";
  245. }
  246. $episodeAirDate = $child['airDateUtc'];
  247. $episodeAirDate = strtotime($episodeAirDate);
  248. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  249. if (new DateTime() < new DateTime($episodeAirDate)) {
  250. $unAired = true;
  251. }
  252. if ($child['episodeNumber'] == "1") {
  253. $episodePremier = "true";
  254. } else {
  255. $episodePremier = "false";
  256. $date = new DateTime($episodeAirDate);
  257. $date->add(new DateInterval("PT1S"));
  258. $date->format(DateTime::ATOM);
  259. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  260. }
  261. $downloaded = $child['hasFile'];
  262. if ($downloaded == "0" && isset($unAired) && $episodePremier == "true") {
  263. $downloaded = "text-primary animated flash";
  264. } elseif ($downloaded == "0" && isset($unAired) && $monitored == "0") {
  265. $downloaded = "text-dark";
  266. } elseif ($downloaded == "0" && isset($unAired)) {
  267. $downloaded = "text-info";
  268. } elseif ($downloaded == "1") {
  269. $downloaded = "text-success";
  270. } else {
  271. $downloaded = "text-danger";
  272. }
  273. $fanArt = "/plugins/images/homepage/no-np.png";
  274. foreach ($child['series']['images'] as $image) {
  275. if ($image['coverType'] == "fanart" && (isset($image['url']) && $image['url'] !== '')) {
  276. $fanArt = $image['url'];
  277. }
  278. if ($image['coverType'] == 'fanart' && (isset($image['remoteUrl']) && $image['remoteUrl'] !== '')) {
  279. $fanArt = $image['remoteUrl'];
  280. }
  281. }
  282. if ($fanArt !== "/plugins/images/homepage/no-np.png" || (strpos($fanArt, '://') === false)) {
  283. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  284. $imageURL = $fanArt;
  285. $fanArt = 'data/cache/' . $seriesID . '.jpg';
  286. if (!file_exists($cacheDirectory . $seriesID . '.jpg')) {
  287. $this->cacheImage($imageURL, $seriesID);
  288. unset($imageURL);
  289. }
  290. }
  291. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  292. $href = $this->config['sonarrCalendarLink'] ?? '';
  293. if (empty($href) && !empty($this->config['sonarrURL'])) {
  294. $href_arr = explode(',', $this->config['sonarrURL']);
  295. $href = reset($href_arr);
  296. }
  297. if (!empty($href)) {
  298. $href = $href . '/series/' . preg_replace('/[^A-Za-z0-9 -]/', '', str_replace('&', 'and', preg_replace('/[[:space:]]+/', '-', $seriesName)));
  299. $href = str_replace("//series/", "/series/", $href);
  300. }
  301. $details = [
  302. "seasonCount" => $child['series']['seasonCount'] ?? isset($child['series']['seasons']) ? count($child['series']['seasons']) : 0,
  303. "status" => $child['series']['status'],
  304. "topTitle" => $seriesName,
  305. "bottomTitle" => $bottomTitle,
  306. "overview" => $child['overview'] ?? '',
  307. "runtime" => $child['series']['runtime'],
  308. "image" => $fanArt,
  309. "ratings" => $child['series']['ratings']['value'],
  310. "videoQuality" => $child["hasFile"] && isset($child['episodeFile']['quality']['quality']['name']) ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  311. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  312. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  313. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  314. "size" => $child["hasFile"] && isset($child['episodeFile']['size']) ? $child['episodeFile']['size'] : "unknown",
  315. "genres" => $child['series']['genres'],
  316. "href" => strtolower($href),
  317. "icon" => "/plugins/images/tabs/sonarr.png",
  318. "frame" => $this->config['sonarrFrameTarget'],
  319. "showLink" => $this->config['sonarrIcon']
  320. ];
  321. $gotCalendar[] = [
  322. "id" => "Sonarr-" . $number . "-" . $i,
  323. "title" => $seriesName,
  324. "start" => $child['airDateUtc'],
  325. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  326. "imagetype" => "tv " . $downloaded,
  327. "imagetypeFilter" => "tv",
  328. "downloadFilter" => $downloaded,
  329. "bgColor" => str_replace('text', 'bg', $downloaded),
  330. "details" => $details
  331. ];
  332. }
  333. if ($i != 0) {
  334. return $gotCalendar;
  335. }
  336. return false;
  337. }
  338. }