Sonarr.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. <?php
  2. namespace Kryptonit3\Sonarr;
  3. use GuzzleHttp\Client;
  4. use Composer\Semver\Comparator;
  5. class Sonarr
  6. {
  7. protected $url;
  8. protected $apiKey;
  9. protected $httpAuthUsername;
  10. protected $httpAuthPassword;
  11. public $options;
  12. public function __construct($url, $apiKey, $type = 'sonarr', $httpAuthUsername = null, $httpAuthPassword = null, $options = [])
  13. {
  14. $this->url = rtrim($url, '/\\'); // Example: http://127.0.0.1:8989 (no trailing forward-backward slashes)
  15. $this->apiKey = $apiKey;
  16. $this->type = strtolower($type);
  17. $this->httpAuthUsername = $httpAuthUsername;
  18. $this->httpAuthPassword = $httpAuthPassword;
  19. $this->options = $options;
  20. }
  21. /**
  22. * Gets upcoming episodes, if start/end are not supplied episodes airing today and tomorrow will be returned
  23. * When supplying start and/or end date you must supply date in format yyyy-mm-dd
  24. * Example: $sonarr->getCalendar('2015-01-25', '2016-01-15');
  25. * 'start' and 'end' not required. You may supply, one or both.
  26. *
  27. * @param string|null $start
  28. * @param string|null $end
  29. * @return array|object|string
  30. */
  31. public function getCalendar($start = null, $end = null, $sonarrUnmonitored = 'false')
  32. {
  33. $uriData = [];
  34. if ( $start ) {
  35. if ( $this->validateDate($start) ) {
  36. $uriData['start'] = $start;
  37. } else {
  38. return json_encode(array(
  39. 'error' => array(
  40. 'msg' => 'Start date string was not recognized as a valid DateTime. Format must be yyyy-mm-dd.',
  41. 'code' => 400,
  42. ),
  43. ));
  44. exit();
  45. }
  46. }
  47. if ( $end ) {
  48. if ( $this->validateDate($end) ) {
  49. $uriData['end'] = $end;
  50. } else {
  51. return json_encode(array(
  52. 'error' => array(
  53. 'msg' => 'End date string was not recognized as a valid DateTime. Format must be yyyy-mm-dd.',
  54. 'code' => 400,
  55. ),
  56. ));
  57. exit();
  58. }
  59. }
  60. if ( $sonarrUnmonitored == 'true' ) {
  61. $uriData['unmonitored'] = 'true';
  62. }
  63. if ( $this->type == 'lidarr' ) {
  64. $uriData['includeArtist'] = 'true';
  65. }
  66. if ( $this->type == 'sonarr' ) {
  67. $uriData['includeSeries'] = 'true';
  68. }
  69. $response = [
  70. 'uri' => 'calendar',
  71. 'type' => 'get',
  72. 'data' => $uriData
  73. ];
  74. return $this->processRequest($response);
  75. }
  76. /**
  77. * Queries the status of a previously started command, or all currently started commands.
  78. *
  79. * @param null $id Unique ID of the command
  80. * @return array|object|string
  81. */
  82. public function getCommand($id = null)
  83. {
  84. $uri = ($id) ? 'command/' . $id : 'command';
  85. $response = [
  86. 'uri' => $uri,
  87. 'type' => 'get',
  88. 'data' => []
  89. ];
  90. return $this->processRequest($response);
  91. }
  92. /**
  93. * Publish a new command for Sonarr to run.
  94. * These commands are executed asynchronously; use GET to retrieve the current status.
  95. *
  96. * Commands and their parameters can be found here:
  97. * https://github.com/Sonarr/Sonarr/wiki/Command#commands
  98. *
  99. * @param $name
  100. * @param array|null $params
  101. * @return string
  102. */
  103. public function postCommand($name, array $params = null)
  104. {
  105. $uri = 'command';
  106. $uriData = [
  107. 'name' => $name
  108. ];
  109. if (is_array($params)) {
  110. foreach($params as $key=>$value) {
  111. $uriData[$key] = $value;
  112. }
  113. }
  114. $response = [
  115. 'uri' => $uri,
  116. 'type' => 'post',
  117. 'data' => $uriData
  118. ];
  119. return $this->processRequest($response);
  120. }
  121. /**
  122. * Gets Diskspace
  123. *
  124. * @return array|object|string
  125. */
  126. public function getDiskspace()
  127. {
  128. $uri = 'diskspace';
  129. $response = [
  130. 'uri' => $uri,
  131. 'type' => 'get',
  132. 'data' => []
  133. ];
  134. return $this->processRequest($response);
  135. }
  136. /**
  137. * Returns all episodes for the given series
  138. *
  139. * @param $seriesId
  140. * @return array|object|string
  141. */
  142. public function getEpisodes($seriesId)
  143. {
  144. $uri = 'episode';
  145. $response = [
  146. 'uri' => $uri,
  147. 'type' => 'get',
  148. 'data' => [
  149. 'SeriesId' => $seriesId
  150. ]
  151. ];
  152. return $this->processRequest($response);
  153. }
  154. /**
  155. * Returns the episode with the matching id
  156. *
  157. * @param $id
  158. * @return string
  159. */
  160. public function getEpisode($id)
  161. {
  162. $uri = 'episode';
  163. $response = [
  164. 'uri' => $uri . '/' . $id,
  165. 'type' => 'get',
  166. 'data' => []
  167. ];
  168. return $this->processRequest($response);
  169. }
  170. /**
  171. * Update the given episodes, currently only monitored is changed, all other modifications are ignored.
  172. *
  173. * Required: All parameters; You should perform a getEpisode(id)
  174. * and submit the full body with the changes, as other values may be editable in the future.
  175. *
  176. * @param array $data
  177. * @return string
  178. */
  179. public function updateEpisode(array $data)
  180. {
  181. $uri = 'episode';
  182. $response = [
  183. 'uri' => $uri,
  184. 'type' => 'put',
  185. 'data' => $data
  186. ];
  187. return $this->processRequest($response);
  188. }
  189. /**
  190. * Returns all episode files for the given series
  191. *
  192. * @param $seriesId
  193. * @return array|object|string
  194. */
  195. public function getEpisodeFiles($seriesId)
  196. {
  197. $uri = 'episodefile';
  198. $response = [
  199. 'uri' => $uri,
  200. 'type' => 'get',
  201. 'data' => [
  202. 'SeriesId' => $seriesId
  203. ]
  204. ];
  205. return $this->processRequest($response);
  206. }
  207. /**
  208. * Returns the episode file with the matching id
  209. *
  210. * @param $id
  211. * @return string
  212. */
  213. public function getEpisodeFile($id)
  214. {
  215. $uri = 'episodefile';
  216. $response = [
  217. 'uri' => $uri . '/' . $id,
  218. 'type' => 'get',
  219. 'data' => []
  220. ];
  221. return $this->processRequest($response);
  222. }
  223. /**
  224. * Delete the given episode file
  225. *
  226. * @param $id
  227. * @return string
  228. */
  229. public function deleteEpisodeFile($id)
  230. {
  231. $uri = 'episodefile';
  232. $response = [
  233. 'uri' => $uri . '/' . $id,
  234. 'type' => 'delete',
  235. 'data' => []
  236. ];
  237. return $this->processRequest($response);
  238. }
  239. /**
  240. * Gets history (grabs/failures/completed).
  241. *
  242. * @param int $page Page Number
  243. * @param int $pageSize Results per Page
  244. * @param string $sortKey 'series.title' or 'date'
  245. * @param string $sortDir 'asc' or 'desc'
  246. * @return array|object|string
  247. */
  248. public function getHistory($page = 1, $pageSize = 10, $sortKey = 'series.title', $sortDir = 'asc')
  249. {
  250. $uri = 'history';
  251. $response = [
  252. 'uri' => $uri,
  253. 'type' => 'get',
  254. 'data' => [
  255. 'page' => $page,
  256. 'pageSize' => $pageSize,
  257. 'sortKey' => $sortKey,
  258. 'sortDir' => $sortDir
  259. ]
  260. ];
  261. return $this->processRequest($response);
  262. }
  263. /**
  264. * Gets missing episode (episodes without files).
  265. *
  266. * @param int $page Page Number
  267. * @param int $pageSize Results per Page
  268. * @param string $sortKey 'series.title' or 'airDateUtc'
  269. * @param string $sortDir 'asc' or 'desc'
  270. * @return array|object|string
  271. */
  272. public function getWantedMissing($page = 1, $pageSize = 10, $sortKey = 'series.title', $sortDir = 'asc')
  273. {
  274. $uri = 'wanted/missing';
  275. $response = [
  276. 'uri' => $uri,
  277. 'type' => 'get',
  278. 'data' => [
  279. 'page' => $page,
  280. 'pageSize' => $pageSize,
  281. 'sortKey' => $sortKey,
  282. 'sortDir' => $sortDir
  283. ]
  284. ];
  285. return $this->processRequest($response);
  286. }
  287. /**
  288. * Displays currently downloading info
  289. *
  290. * @return array|object|string
  291. */
  292. public function getQueue()
  293. {
  294. $uri = 'queue';
  295. $response = [
  296. 'uri' => $uri,
  297. 'type' => 'get',
  298. 'data' => [
  299. 'includeUnknownSeriesItems' => 'false',
  300. 'pageSize' => 1000
  301. ]
  302. ];
  303. if ( $this->type == 'sonarr' ) {
  304. $response['data']['includeSeries'] = 'true';
  305. $response['data']['includeEpisode'] = 'true';
  306. }
  307. return $this->processRequest($response);
  308. }
  309. /**
  310. * Gets all quality profiles
  311. *
  312. * @return array|object|string
  313. */
  314. public function getProfiles()
  315. {
  316. $uri = 'profile';
  317. $response = [
  318. 'uri' => $uri,
  319. 'type' => 'get',
  320. 'data' => []
  321. ];
  322. return $this->processRequest($response);
  323. }
  324. /**
  325. * Get release by episode id
  326. *
  327. * @param $episodeId
  328. * @return string
  329. */
  330. public function getRelease($episodeId)
  331. {
  332. $uri = 'release';
  333. $uriData = [
  334. 'episodeId' => $episodeId
  335. ];
  336. $response = [
  337. 'uri' => $uri,
  338. 'type' => 'get',
  339. 'data' => $uriData
  340. ];
  341. return $this->processRequest($response);
  342. }
  343. /**
  344. * Adds a previously searched release to the download client,
  345. * if the release is still in Sonarr's search cache (30 minute cache).
  346. * If the release is not found in the cache Sonarr will return a 404.
  347. *
  348. * @param $guid
  349. * @return string
  350. */
  351. public function postRelease($guid)
  352. {
  353. $uri = 'release';
  354. $uriData = [
  355. 'guid' => $guid
  356. ];
  357. $response = [
  358. 'uri' => $uri,
  359. 'type' => 'post',
  360. 'data' => $uriData
  361. ];
  362. return $this->processRequest($response);
  363. }
  364. /**
  365. * Push a release to download client
  366. *
  367. * @param $title
  368. * @param $downloadUrl
  369. * @param $downloadProtocol (Usenet or Torrent)
  370. * @param $publishDate (ISO8601 Date)
  371. * @return string
  372. */
  373. public function postReleasePush($title, $downloadUrl, $downloadProtocol, $publishDate)
  374. {
  375. $uri = 'release';
  376. $uriData = [
  377. 'title' => $title,
  378. 'downloadUrl' => $downloadUrl,
  379. 'downloadProtocol' => $downloadProtocol,
  380. 'publishDate' => $publishDate
  381. ];
  382. $response = [
  383. 'uri' => $uri,
  384. 'type' => 'post',
  385. 'data' => $uriData
  386. ];
  387. return $this->processRequest($response);
  388. }
  389. /**
  390. * Gets root folder
  391. *
  392. * @return array|object|string
  393. */
  394. public function getRootFolder()
  395. {
  396. $uri = 'rootfolder';
  397. $response = [
  398. 'uri' => $uri,
  399. 'type' => 'get',
  400. 'data' => []
  401. ];
  402. return $this->processRequest($response);
  403. }
  404. /**
  405. * Returns all series in your collection
  406. *
  407. * @return array|object|string
  408. */
  409. public function getSeries()
  410. {
  411. $uri = 'series';
  412. $response = [
  413. 'uri' => $uri,
  414. 'type' => 'get',
  415. 'data' => []
  416. ];
  417. return $this->processRequest($response);
  418. }
  419. /**
  420. * Adds a new series to your collection
  421. *
  422. * NOTE: if you do not add the required params, then the series wont function.
  423. * Some of these without the others can indeed make a "series". But it wont function properly in Sonarr.
  424. *
  425. * Required: tvdbId (int) title (string) qualityProfileId (int) titleSlug (string) seasons (array)
  426. * See GET output for format
  427. *
  428. * path (string) - full path to the series on disk or rootFolderPath (string)
  429. * Full path will be created by combining the rootFolderPath with the series title
  430. *
  431. * Optional: tvRageId (int) seasonFolder (bool) monitored (bool)
  432. *
  433. * @param array $data
  434. * @param bool|true $onlyFutureEpisodes It can be used to control which episodes Sonarr monitors
  435. * after adding the series, setting to true (default) will only monitor future episodes.
  436. *
  437. * @return array|object|string
  438. */
  439. public function postSeries(array $data, $onlyFutureEpisodes = true)
  440. {
  441. $uri = 'series';
  442. $uriData = [];
  443. // Required
  444. $uriData['tvdbId'] = $data['tvdbId'];
  445. $uriData['title'] = $data['title'];
  446. $uriData['qualityProfileId'] = $data['qualityProfileId'];
  447. if ( array_key_exists('titleSlug', $data) ) { $uriData['titleSlug'] = $data['titleSlug']; }
  448. if ( array_key_exists('seasons', $data) ) { $uriData['seasons'] = $data['seasons']; }
  449. if ( array_key_exists('path', $data) ) { $uriData['path'] = $data['path']; }
  450. if ( array_key_exists('rootFolderPath', $data) ) { $uriData['rootFolderPath'] = $data['rootFolderPath']; }
  451. if ( array_key_exists('tvRageId', $data) ) { $uriData['tvRageId'] = $data['tvRageId']; }
  452. $uriData['seasonFolder'] = ( array_key_exists('seasonFolder', $data) ) ? $data['seasonFolder'] : true;
  453. if ( array_key_exists('monitored', $data) ) { $uriData['monitored'] = $data['monitored']; }
  454. if ( $onlyFutureEpisodes ) {
  455. $uriData['addOptions'] = [
  456. 'ignoreEpisodesWithFiles' => true,
  457. 'ignoreEpisodesWithoutFiles' => true
  458. ];
  459. }
  460. $response = [
  461. 'uri' => $uri,
  462. 'type' => 'post',
  463. 'data' => $uriData
  464. ];
  465. return $this->processRequest($response);
  466. }
  467. /**
  468. * Delete the series with the given ID
  469. *
  470. * @param int $id
  471. * @param bool|true $deleteFiles
  472. * @return string
  473. */
  474. public function deleteSeries($id, $deleteFiles = true)
  475. {
  476. $uri = 'series';
  477. $uriData = [];
  478. $uriData['deleteFiles'] = ($deleteFiles) ? 'true' : 'false';
  479. $response = [
  480. 'uri' => $uri . '/' . $id,
  481. 'type' => 'delete',
  482. 'data' => $uriData
  483. ];
  484. return $this->processRequest($response);
  485. }
  486. /**
  487. * Searches for new shows on trakt
  488. * Search by name or tvdbid
  489. * Example: 'The Blacklist' or 'tvdb:266189'
  490. *
  491. * @param string $searchTerm query string for the search (Use tvdb:12345 to lookup TVDB ID 12345)
  492. * @return string
  493. */
  494. public function getSeriesLookup($searchTerm)
  495. {
  496. $uri = 'series/lookup';
  497. $uriData = [
  498. 'term' => $searchTerm
  499. ];
  500. $response = [
  501. 'uri' => $uri,
  502. 'type' => 'get',
  503. 'data' => $uriData
  504. ];
  505. return $this->processRequest($response);
  506. }
  507. /**
  508. * Get System Status
  509. *
  510. * @return string
  511. */
  512. public function getSystemStatus()
  513. {
  514. $uri = 'system/status';
  515. $response = [
  516. 'uri' => $uri,
  517. 'type' => 'get',
  518. 'data' => []
  519. ];
  520. return $this->preProcessRequest($response);
  521. }
  522. /**
  523. * Process requests with Guzzle
  524. *
  525. * @param array $params
  526. * @return \Psr\Http\Message\ResponseInterface
  527. */
  528. protected function _request(array $params)
  529. {
  530. $client = new Client($this->options);
  531. $options = [
  532. 'headers' => [
  533. 'X-Api-Key' => $this->apiKey
  534. ]
  535. ];
  536. if ( $this->httpAuthUsername && $this->httpAuthPassword ) {
  537. $options['auth'] = [
  538. $this->httpAuthUsername,
  539. $this->httpAuthPassword
  540. ];
  541. }
  542. if($this->type == 'lidarr'){
  543. $params['version'] = 'v1/';
  544. }
  545. $version = $params['version'] ?? '';
  546. if ( $params['type'] == 'get' ) {
  547. $url = $this->url . '/api/' . $version . $params['uri'] . '?' . http_build_query($params['data']);
  548. return $client->get($url, $options);
  549. }
  550. if ( $params['type'] == 'put' ) {
  551. $url = $this->url . '/api/' . $version . $params['uri'];
  552. $options['json'] = $params['data'];
  553. return $client->put($url, $options);
  554. }
  555. if ( $params['type'] == 'post' ) {
  556. $url = $this->url . '/api/' . $version . $params['uri'];
  557. $options['json'] = $params['data'];
  558. return $client->post($url, $options);
  559. }
  560. if ( $params['type'] == 'delete' ) {
  561. $url = $this->url . '/api/' . $version . $params['uri'] . '?' . http_build_query($params['data']);
  562. return $client->delete($url, $options);
  563. }
  564. }
  565. /**
  566. * Process requests, catch exceptions, return json response
  567. *
  568. * @param array $request uri, type, data from method
  569. * @return string json encoded response
  570. */
  571. protected function processRequest(array $request)
  572. {
  573. try {
  574. $versionCheck = $this->getSystemStatus();
  575. $versionCheck = json_decode($versionCheck, true);
  576. $versionCheck = (is_array($versionCheck) && array_key_exists('version', $versionCheck)) ? $versionCheck['version'] : '1.0';
  577. $compare = new Comparator;
  578. switch ($this->type){
  579. case 'sonarr':
  580. $versionCheck = 'v3/';
  581. break;
  582. case 'radarr':
  583. $versionCheck = 'v3/';
  584. break;
  585. case 'lidarr':
  586. $versionCheck = 'v1/';
  587. break;
  588. default:
  589. $versionCheck = '';
  590. }
  591. } catch ( \Exception $e ) {
  592. return json_encode(array(
  593. 'error' => array(
  594. 'msg' => $e->getMessage(),
  595. 'code' => $e->getCode(),
  596. ),
  597. ));
  598. exit();
  599. }
  600. try {
  601. $response = $this->_request(
  602. [
  603. 'uri' => $request['uri'],
  604. 'type' => $request['type'],
  605. 'data' => $request['data'],
  606. 'version' => $versionCheck
  607. ]
  608. );
  609. } catch ( \Exception $e ) {
  610. return json_encode(array(
  611. 'error' => array(
  612. 'msg' => $e->getMessage(),
  613. 'code' => $e->getCode(),
  614. ),
  615. ));
  616. exit();
  617. }
  618. return $response->getBody()->getContents();
  619. }
  620. protected function preProcessRequest(array $request)
  621. {
  622. try {
  623. $response = $this->_request(
  624. [
  625. 'uri' => $request['uri'],
  626. 'type' => $request['type'],
  627. 'data' => $request['data']
  628. ]
  629. );
  630. } catch ( \Exception $e ) {
  631. return json_encode(array(
  632. 'error' => array(
  633. 'msg' => $e->getMessage(),
  634. 'code' => $e->getCode(),
  635. ),
  636. ));
  637. exit();
  638. }
  639. return $response->getBody()->getContents();
  640. }
  641. /**
  642. * Verify date is in proper format
  643. *
  644. * @param $date
  645. * @param string $format
  646. * @return bool
  647. */
  648. private function validateDate($date, $format = 'Y-m-d')
  649. {
  650. $d = \DateTime::createFromFormat($format, $date);
  651. return $d && $d->format($format) == $date;
  652. }
  653. }