nextcloud-app-radio/lib/Search/SearchProvider.php

90 lines
2.0 KiB
PHP
Raw Normal View History

2020-11-04 09:32:06 +00:00
<?php
declare(strict_types=1);
namespace OCA\Radio\Search;
use OCA\Radio\AppInfo\Application;
use OCP\IUser;
use OCP\IURLGenerator;
use OCP\Search\IProvider;
use OCP\Search\ISearchQuery;
use OCP\Search\SearchResult;
use OCP\Search\SearchResultEntry;
2020-11-09 12:17:18 +00:00
use OCP\Http\Client\IClientService;
2020-11-04 09:32:06 +00:00
use function urlencode;
class SearchProvider implements IProvider {
2020-11-09 12:17:18 +00:00
/** @var IClientService */
private $clientService;
2020-11-04 09:32:06 +00:00
/** @var IURLGenerator */
private $url;
public function __construct(
2020-11-09 12:17:18 +00:00
IClientService $clientService,
2020-11-04 09:32:06 +00:00
IURLGenerator $url
) {
2020-11-09 12:17:18 +00:00
$this->clientService = $clientService;
2020-11-04 09:32:06 +00:00
$this->url = $url;
}
public function getId(): string {
return Application::APP_ID;
}
public function getName(): string {
return 'Radio';
}
public function getOrder(string $route, array $routeParameters): int {
if (strpos($route, 'files' . '.') === 0) {
return 25;
} elseif (strpos($route, Application::APP_ID . '.') === 0) {
return -1;
}
return 4;
}
public function search(IUser $user, ISearchQuery $query): SearchResult {
2020-11-09 12:17:18 +00:00
$term = $query->getTerm();
2020-11-10 13:27:01 +00:00
$url = "https://de1.api.radio-browser.info/json/stations/byname/" . $term . "?limit=20";
2020-11-09 12:17:18 +00:00
$client = $this->clientService->newClient();
try {
$response = $client->get($url);
} catch (Exception $e) {
$this->logger->error("Could not search for radio stations: " . $e->getMessage());
throw $e;
}
$body = $response->getBody();
$parsed = json_decode($body, true);
$result = array_map(function (array $result) {
return new SearchResultEntry(
$result['favicon'],
$result['name'],
2020-11-10 12:53:45 +00:00
str_replace(",",", ",$result['tags']),
2020-11-09 12:17:18 +00:00
'#/search/virus',
2020-11-10 13:27:01 +00:00
'icon-radio'
2020-11-09 12:17:18 +00:00
);
}, $parsed);
// $result = [new SearchResultEntry(
// '',
// 'SRF Virus',
// 'alternative, youth',
// $this->url->linkToRouteAbsolute('radio.page.index') . 'search/' . urlencode($query->getTerm()), // FIXME: urlencode working?
// 'icon-notes-trans'
// )];
2020-11-04 09:32:06 +00:00
return SearchResult::complete(
$this->getName(),
$result
);
}
}