repod/lib/Controller/TopController.php
Michel Roux 48fef0d993
All checks were successful
repod / nextcloud-25 (push) Successful in 1m1s
repod / nextcloud-27 (push) Successful in 44s
repod / nodejs (push) Successful in 1m38s
Begin to work on no gpodder enabled
2023-07-04 17:43:58 +02:00

53 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
namespace OCA\RePod\Controller;
use Exception;
use OCA\RePod\AppInfo\Application;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\Http\Client\IClientService;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\L10N\IFactory;
class TopController extends Controller
{
public function __construct(
IRequest $request,
private IClientService $clientService,
private IFactory $l10n,
private IUserSession $userSession
) {
parent::__construct(Application::APP_ID, $request);
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*/
public function index(int $limit = 10): JSONResponse {
if (!in_array($limit, [10, 25, 50])) {
return new JSONResponse(['Invalid limit, can be 10, 25 or 50.'], Http::STATUS_BAD_REQUEST);
}
try {
$lang = $this->l10n->getUserLanguage($this->userSession->getUser());
$lang = explode('_', $lang);
$lang = count($lang) > 1 ? $lang[1] : $lang[0];
$lang = $lang === 'en' ? 'us' : $lang;
$client = $this->clientService->newClient();
$response = $client->get("https://rss.applemarketingtools.com/api/v2/{$lang}/podcasts/top/{$limit}/podcasts.json");
/** @var array $json */
$json = json_decode((string) $response->getBody(), true, flags: JSON_THROW_ON_ERROR);
return new JSONResponse($json, $response->getStatusCode());
} catch (Exception $e) {
return new JSONResponse([$e->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
}