123movies-seo/app/Services/TmdbClient.php

276 lines
9 KiB
PHP
Raw Normal View History

2024-08-24 23:08:42 +03:00
<?php
namespace App\Services;
use App\Http\Resources\MovieDetail;
use App\Services\TmdbClient as ServicesTmdbClient;
use App\Supports\Traits\CleanItems;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
use Tmdb\Client;
use Tmdb\Event\BeforeRequestEvent;
use Tmdb\Event\Listener\Request\AcceptJsonRequestListener;
use Tmdb\Event\Listener\Request\ApiTokenRequestListener;
use Tmdb\Event\Listener\Request\ContentTypeJsonRequestListener;
use Tmdb\Event\Listener\Request\UserAgentRequestListener;
use Tmdb\Event\RequestEvent;
use Tmdb\Token\Api\ApiToken;
use Tmdb\Token\Api\BearerToken;
use Tmdb\Event\Listener\Psr6CachedRequestListener;
use Tmdb\Event\Listener\Request\LanguageFilterRequestListener;
use Tmdb\Event\Listener\Request\RegionFilterRequestListener;
class TmdbClient
{
use CleanItems;
private static $instance;
private $ttl = 3600*24;
private $use_cache = true;
/** @var Client $client **/
public $client;
private static $api_keys = ['aba8176c9250ba755ca1783de87528a2', '5c6763d6500cc611d442a5414e951c05'];
public function __construct($tmdb_key = null, $use_cache = false, $cache_time = 3600)
{
// 5c6763d6500cc611d442a5414e951c05
$this->ttl = $cache_time;
$this->use_cache = $use_cache;
$api_key_key = array_rand(self::$api_keys);
if(!defined("TMDB_API_KEY")){
define('TMDB_API_KEY', self::$api_keys[$api_key_key]);
}
$token = defined('TMDB_BEARER_TOKEN') && TMDB_BEARER_TOKEN !== 'TMDB_BEARER_TOKEN' ?
new BearerToken(TMDB_BEARER_TOKEN) :
new ApiToken(TMDB_API_KEY);
$ed = new \Symfony\Component\EventDispatcher\EventDispatcher();
$client = new Client(
[
/** @var ApiToken|BearerToken */
'api_token' => $token,
'event_dispatcher' => [
'adapter' => $ed
],
// We make use of PSR-17 and PSR-18 auto discovery to automatically guess these, but preferably set these explicitly.
'http' => [
'client' => null,
'request_factory' => null,
'response_factory' => null,
'stream_factory' => null,
'uri_factory' => null,
]
]
);
/**
* Required event listeners and events to be registered with the PSR-14 Event Dispatcher.
*/
// $cache = new FilesystemAdapter('php-tmdb', 86400, '/home/cache');
$redisConnection = RedisAdapter::createConnection('redis:///var/lib/redis/redis.sock/15');
$cache = new RedisTagAwareAdapter($redisConnection, 43200);
// $requestListener = new RequestListener($client->getHttpClient(), $ed);
$requestListener = new Psr6CachedRequestListener(
$client->getHttpClient(),
$ed,
$cache,
$client->getHttpClient()->getPsr17StreamFactory(),
[]
);
$ed->addListener(RequestEvent::class, $requestListener);
$apiTokenListener = new ApiTokenRequestListener($client->getToken());
$ed->addListener(BeforeRequestEvent::class, $apiTokenListener);
$acceptJsonListener = new AcceptJsonRequestListener();
$ed->addListener(BeforeRequestEvent::class, $acceptJsonListener);
$jsonContentTypeListener = new ContentTypeJsonRequestListener();
$ed->addListener(BeforeRequestEvent::class, $jsonContentTypeListener);
$userAgentListener = new UserAgentRequestListener();
$ed->addListener(BeforeRequestEvent::class, $userAgentListener);
// $regionFilerListener = new RegionFilterRequestListener();
// $ed->addListener(BeforeRequestEvent::class, $regionFilerListener);
// $languageFilerListener = new LanguageFilterRequestListener();
// $ed->addListener(BeforeRequestEvent::class, $languageFilerListener);
$this->client = $client;
// self::$client = $client;
}
/**
* @return Client
*/
public static function getClient() {
// Check is $_instance has been set
if(!isset(self::$instance))
{
// Creates sets object to instance
self::$instance = new TmdbClient();
}
// Returns the instance
return self::$instance::$client;
}
public function getMovie(int $id)
{
try {
$call = fn() => $this->formatTmdbMovie($this->client->getMoviesApi()->getMovie($id, ['append_to_response'=>'credits,videos,similar,keywords']));
if ($this->use_cache)
2024-08-25 16:11:19 +03:00
return Cache::remember('movie:'.$id, $this->ttl, $call);
2024-08-24 23:08:42 +03:00
return $call();
} catch (\Throwable $th) {
return abort(404, 'Not Found');
}
}
public function getShow(int $id)
{
try {
2024-08-25 16:11:19 +03:00
$call = fn() => $this->formatTmdbShow($this->client->getTvApi()->getTvshow($id, ['append_to_response'=>'credits,videos,similar,recommendations,keywords']));
2024-08-24 23:08:42 +03:00
if ($this->use_cache)
2024-08-25 16:11:19 +03:00
return Cache::remember('show:'.$id, $this->ttl, $call);
2024-08-24 23:08:42 +03:00
return $call();
} catch (\Throwable $th) {
return abort(404, 'Not Found');
}
}
public function getSeason(int $id, int $season_number)
{
$call = fn() => $this->client->getTvSeasonApi()->getSeason($id, $season_number, ['append_to_response'=>'credits,videos,keywords']);
if ($this->use_cache)
return Cache::remember('show'.$id.'_'.$season_number, $this->ttl, $call);
return $call();
}
public function getEpisode(int $id, int $season_number, int $episode_number)
{
$call = fn() => $this->client->getTvEpisodeApi()->getEpisode($id, $season_number, $episode_number, ['append_to_response'=>'credits,videos']);
if ($this->use_cache)
return Cache::remember('episode'.$id.'_'.$season_number.'_'.$episode_number, $this->ttl, $call);
return $call();
}
public function getUpcomingMovies($page = 1)
{
$call = fn() => $this->client->getMoviesApi()->getUpcoming();
if ($this->use_cache)
return Cache::remember('upcomingtmdb'.$page, $this->ttl, $call);
return $call();
}
public function getPopularMovies($page = 1)
{
$call = fn() => $this->client->getMoviesApi()->getPopular();
if ($this->use_cache)
return Cache::remember('populartmdb'.$page, $this->ttl, $call);
return $call();
}
public function getPopularShows($page = 1)
{
$call = fn() => $this->client->getTvApi()->getPopular();
if ($this->use_cache)
return Cache::remember('populartvtmdb'.$page, $this->ttl, $call);
return $call();
}
public function getAiringShows($page = 1)
{
$call = fn() => $this->client->getTvApi()->getOnTheAir();
if ($this->use_cache)
return Cache::remember('airingtmdb'.$page, $this->ttl, $call);
return $call();
}
public function getComingSoonMovies($page = 1)
{
$from = Carbon::now()
->subDay()
->format('Y-m-d');
$to = Carbon::now()
->addMonth()
->format('Y-m-d');
$call = fn() => $this->client->getMoviesApi()->getUpcoming(['sort_by' => 'popularity.desc',
'with_release_type' => '2|3',
'primary_release_date.gte' => $from,
'primary_release_date.lte' => $to,
'region' => 'US',
'language' => 'en',
'include_adult' => 'false',
'page' => $page,]);
if ($this->use_cache)
return Cache::remember('comingsoontmdb'.$page, $this->ttl, $call);
return $call();
}
public function getNowPlayingMovies($page = 1)
{
$call = fn() => $this->client->getMoviesApi()->getNowPlaying();
if ($this->use_cache)
return Cache::remember('nowplayingtmdb'.$page, $this->ttl, $call);
return $call();
}
public function getCountryMovies($country = 'us', $page = 1)
{
// dd($country);
$call = fn() => $this->client->getDiscoverApi()->discoverMovies(['language' => 'en-US', 'page' => $page, 'region' => $country, 'watch_region' => $country]);
if ($this->use_cache)
// return Cache::remember('country'.$country.$page, $this->ttl, $call);
return $call();
}
public function getTopRatedMovies($page = 1)
{
// dd($country);
// dd($page);
$call = fn() => $this->client->getMoviesApi()->getTopRated(['language' => 'en-US', 'page' => $page]);
if ($this->use_cache)
return Cache::remember('toprated'.$page, $this->ttl, $call);
return $call();
}
public function getSearch(string $query)
{
$kw = str_replace('-', ' ',$query);
$kw = urlencode($kw);
$call = fn() => $this->client->getSearchApi()->searchMulti($kw);
if ($this->use_cache)
return Cache::remember('search'.$kw, $this->ttl, $call);
return $call();
}
}