Files
movies/app/Service/MediaProcessing/ShowProcessingService.php
T
2025-02-10 01:58:12 +02:00

968 lines
34 KiB
PHP

<?php
namespace App\Service\MediaProcessing;
use App\Models\Comment;
use App\Models\ContentRating;
use App\Models\Episode;
use App\Models\ExternalId;
use App\Models\Genre;
use App\Models\Image;
use App\Models\ItemToFetch;
use App\Models\ItemToFetchJobs;
use App\Models\Keyword;
use App\Models\Network;
use App\Models\Person;
use App\Models\ProductionCompany;
use App\Models\ProductionCountry;
use App\Models\Season;
use App\Models\Show;
use App\Models\ShowAlternativeTitle;
use App\Models\ShowRecommendation;
use App\Models\ShowSimilar;
use App\Models\ShowTranslation;
use App\Models\Translation;
use App\Models\Video;
use App\Models\WatchProvider;
use App\Service\TMDBApi\PersonApi;
use App\Service\TMDBApi\ShowsApi;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use function PHPUnit\Framework\containsIdentical;
class ShowProcessingService implements ProcessingInterface
{
private ShowsApi $showsApi;
private PersonApi $personApi;
public function __construct(
ShowsApi $showsApi,
PersonApi $personApi
) {
$this->showsApi = $showsApi;
$this->personApi = $personApi;
}
public static function getBatch(int $batch, string $job, int $tmdbId = null)
{
$query = ItemToFetchJobs::leftJoin('shows', function ($join) {
$join->on('shows.tmdb_id', '=', 'item_to_fetch_jobs.tmdb_id');
})
->select('item_to_fetch_jobs.*');
if ($tmdbId) {
$query = $query->where('item_to_fetch_jobs.tmdb_id', $tmdbId);
}
if ($job === ItemToFetchJobs::JOB_DETAILS) {
return $query
->whereRaw("FIND_IN_SET('".ItemToFetchJobs::JOB_DETAILS."', item_to_fetch_jobs.jobs)")
->where('item_to_fetch_jobs.type', 'tv_series')
->whereNull('shows.id')
->take($batch)
->get();
}
return $query
->whereRaw("FIND_IN_SET('".$job."', item_to_fetch_jobs.jobs)")
->where('item_to_fetch_jobs.type', 'tv_series')
->whereNotNull('shows.id')
->take($batch)
->get();
}
public function process($item, $job)
{
$methodName = "get".ucfirst($job);
if (!method_exists($this, $methodName)) {
throw new \Exception("No method named $methodName\n");
}
$this->$methodName($item);
}
private function getDetails($item)
{
$tmdbShow = $this->showsApi->getTvshow($item->tmdb_id);
$tmdbShow['tmdb_id'] = $tmdbShow['id'];
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
if ($show) {
// echo "+";
return;
}
// echo ".";
$tmdbShow['slug'] = Str::slug($tmdbShow['name'].'-'.$tmdbShow['tmdb_id']);
$tmdbShow['first_air_date'] = $tmdbShow['first_air_date'] ? new \DateTime($tmdbShow['first_air_date']) : null;
$tmdbShow['last_air_date'] = $tmdbShow['last_air_date'] ? new \DateTime($tmdbShow['last_air_date']) : null;
$tmdbShow['episode_run_time'] = is_array($tmdbShow['episode_run_time']) ? reset($tmdbShow['episode_run_time']) : $tmdbShow['episode_run_time'];
$tmdbShow['languages'] = json_encode($tmdbShow['languages']);
$tmdbShow['number_of_episodes'] = $tmdbShow['number_of_episodes'] ?? 0;
$tmdbShow['origin_country'] = is_array($tmdbShow['origin_country']) ? reset($tmdbShow['origin_country']) : $tmdbShow['origin_country'];
try {
$show = Show::create($tmdbShow);
} catch (\Throwable $e) {
dd($e, $tmdbShow);
}
if (!empty($tmdbShow['seasons'])) {
$this->processSeasons($show, $tmdbShow['seasons']);
}
if (!empty($tmdbShow['genres'])) {
$this->processGenres($item, $tmdbShow['genres']);
}
if (!empty($tmdbShow['networks'])) {
$this->processNetworks($item, $tmdbShow['networks']);
}
// @todo process created_by
if (!empty($tmdbShow['production_countries'])) {
//dd('123');
$this->processProductionCountries($item, $tmdbShow['production_countries']);
}
if (!empty($tmdbShow['production_companies'])) {
//dd('456');
$this->processProductionCompanies($item, $tmdbShow['production_companies']);
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_DETAILS);
}
private function getAlternativeTitles($item)
{
$tmdbAlternativeTitles = $this->showsApi->getAlternativeTitles($item->tmdb_id);
if (empty($tmdbAlternativeTitles) ||empty($tmdbAlternativeTitles['results'])) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbAlternativeTitles['results'] as $tmdbAlternativeTitle) {
$alternativeTitle = ShowAlternativeTitle::where('show_id', $show->id)
->where('iso', $tmdbAlternativeTitle['iso_3166_1'])
->first();
if (!$alternativeTitle) {
ShowAlternativeTitle::create([
'iso' => $tmdbAlternativeTitle['iso_3166_1'],
'title' => $tmdbAlternativeTitle['title'],
'show_id' => $show->id,
'type' => $tmdbAlternativeTitle['type'],
]);
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_ALTERNVATIVE_TITLES);
}
private function getCredits($item)
{
$tmdbCredits = $this->showsApi->getCredits($item->tmdb_id);
if (empty($tmdbCredits)) {
echo "no credits\n";
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
echo $item->tmdb_id."\n";
$this->processCast($show, $tmdbCredits['cast'] ?? []);
$this->processCrew($show, $tmdbCredits['crew'] ?? []);
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_CREDITS);
}
private function getExternalIds($item)
{
$tmdbExternalIds = $this->showsApi->getExternalIds($item->tmdb_id);
if (empty($tmdbExternalIds)) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
if (!$show) {
return;
}
$externalId = ExternalId::where('entity_id', $show->id)
->where('entity_type', ExternalId::TYPE_SHOW)
->first();
if (!$externalId) {
$externalIds['tmdb_id'] = $tmdbExternalIds['id'];
//$externalIds['show_id'] = $show->id;
unset($externalIds['id']);
$externalIds['entity_id'] = $show->id;
$externalIds['entity_type'] = ExternalId::TYPE_SHOW;
$externalId['imdb_id'] = $tmdbExternalIds['imdb_id'] ?? null;
$externalId['wikidata_id'] = $tmdbExternalIds['wikidata_id'] ?? null;
$externalId['facebook_id'] = $tmdbExternalIds['facebook_id'] ?? null;
$externalId['instagram_id'] = $tmdbExternalIds['instagram_id'] ?? null;
$externalId['twitter_id'] = $tmdbExternalIds['twitter_id'] ?? null;
$externalId['tvdb_id'] = $tmdbExternalIds['tvdb_id'] ?? null;
$externalId['freebase_id'] = $tmdbExternalIds['freebase_id'] ?? null;
$externalId['tvrage_id'] = $tmdbExternalIds['tvrage_id'] ?? null;
ExternalId::create($externalIds);
} else {
$externalId->imdb_id = $tmdbExternalIds['imdb_id'] ?? null;
$externalId->wikidata_id = $tmdbExternalIds['wikidata_id'] ?? null;
$externalId->facebook_id = $tmdbExternalIds['facebook_id'] ?? null;
$externalId->instagram_id = $tmdbExternalIds['instagram_id'] ?? null;
$externalId->twitter_id = $tmdbExternalIds['twitter_id'] ?? null;
$externalId->tvdb_id = $tmdbExternalIds['tvdb_id'] ?? null;
$externalId->freebase_id = $tmdbExternalIds['freebase_id'] ?? null;
$externalId->tvrage_id = $tmdbExternalIds['tvrage_id'] ?? null;
$externalId->save();
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_EXTERNAL_IDS);
}
private function getImages($item)
{
$tmdbImages = $this->showsApi->getImages($item->tmdb_id);
if (empty($tmdbImages)) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbImages as $type => $images) {
if (!is_array($images)) {
continue;
}
foreach ($images as $image) {
$imageExists = Image::where('type', $type)
->where('file_path', $image['file_path'])
->first();
if (!$imageExists) {
$image['iso'] = $image['iso_639_1'];
$image['type'] = $type;
$imageExists = Image::create($image);
}
if ($show->whereHas('images', function ($query) use ($imageExists) {
$query->where('type', $imageExists->type)
->where('file_path', $imageExists->file_path);
})->exists()) {
return;
} else {
$show->images()->attach($imageExists);
}
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_IMAGES);
}
private function getVideos($item)
{
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
$tmdbVideos = $this->showsApi->getVideos($item->tmdb_id);
if (empty($tmdbVideos) || empty($tmdbVideos['results'])) {
return;
}
foreach ($tmdbVideos['results'] as $tmdbVideo) {
$videoExists = Video::where('tmdb_id', $tmdbVideo['id'])->first();
if (!$videoExists) {
$videoExists = Video::create([
'iso_639' => $tmdbVideo['iso_639_1'],
'iso_3166' => $tmdbVideo['iso_3166_1'],
'name' => $tmdbVideo['name'],
'key' => $tmdbVideo['key'],
'site' => $tmdbVideo['site'],
'size' => $tmdbVideo['size'],
'type' => $tmdbVideo['type'],
'official' => $tmdbVideo['official'],
'published_at' => $tmdbVideo['published_at'] ? new \DateTime($tmdbVideo['published_at']) : null,
'tmdb_id' => $tmdbVideo['id'],
]);
}
$videoIsAttached = DB::table('show_videos')
->where('show_id', $show->id)
->where('video_id', $videoExists->id)
->first();
if (!$videoIsAttached) {
DB::table('show_videos')
->insert([
'show_id' => $show->id,
'video_id' => $videoExists->id
]);
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_VIDEOS);
}
private function getKeywords($item)
{
$tmdbKeywords = $this->showsApi->getKeywords($item->tmdb_id);
if (empty($tmdbKeywords) || !isset($tmdbKeywords['results'])) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbKeywords['results'] as $tmdbKeyword) {
$existingKeyword = Keyword::where('tmdb_id', $tmdbKeyword['id'])->first();
if (!$existingKeyword) {
$existingKeyword = Keyword::create([
'name' => $tmdbKeyword['name'],
'tmdb_id' => $tmdbKeyword['id'],
]);
}
$keywordIsAttached = DB::table('show_keywords')
->where('show_id', $show->id)
->where('keyword_id', $existingKeyword->id)
->first();
if (!$keywordIsAttached) {
DB::table('show_keywords')
->insert([
'show_id' => $show->id,
'keyword_id' => $existingKeyword->id,
]);
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_KEYWORDS);
}
private function getTranslations($item)
{
$tmdbMovieTranslations = $this->showsApi->getTranslations($item->tmdb_id);
if (!$tmdbMovieTranslations || !isset($tmdbMovieTranslations['translations'])) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbMovieTranslations['translations'] as $tmdbTranslation) {
$existingTranslation = ShowTranslation::where('show_id', $show->id)
->where('name', $tmdbTranslation['name'])
->first();
if (!$existingTranslation) {
ShowTranslation::create([
'show_id' => $show->id,
'iso_3166' => $tmdbTranslation['iso_3166_1'],
'iso_639' => $tmdbTranslation['iso_639_1'],
'name' => $tmdbTranslation['name'],
'english_name' => $tmdbTranslation['english_name'],
'homepage' => $tmdbTranslation['data']['homepage'],
'overview' => $tmdbTranslation['data']['overview'],
'runtime' => $tmdbTranslation['data']['runtime'] ?? 0,
'tagline' => $tmdbTranslation['data']['tagline'],
'title' => $tmdbTranslation['data']['title'] ?? '',
]);
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_TRANSLATIONS);
}
private function getWatchProviders($item)
{
$tmdbWatchProviders = $this->showsApi->getWatchProviders($item->tmdb_id);
if (empty($tmdbWatchProviders) || empty($tmdbWatchProviders['results'])) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
if (!$show) {
$itemToFetch = $this->createJob($item->tmdb_id);
$this->getDetails($itemToFetch);
return;
}
$types = [
'flatrate',
'rent',
'buy',
];
foreach ($tmdbWatchProviders['results'] as $locale => $tmdbWatchProvider) {
foreach ($types as $type) {
if (!isset($tmdbWatchProvider[$type])) {
continue;
}
$providerInfo = $tmdbWatchProvider[$type];
$providerInfo = reset($providerInfo);
if (!isset($providerInfo['provider_id'])) {
continue;
}
$existingWatchProvider = WatchProvider::where('tmdb_provider_id', $providerInfo['provider_id'])->first();
if(!$existingWatchProvider) {
$existingWatchProvider = WatchProvider::create([
'type' => $type,
'logo_path' => $providerInfo['logo_path'],
'tmdb_provider_id' => $providerInfo['provider_id'],
'provider_name' => $providerInfo['provider_name'],
'display_priority' => $providerInfo['display_priority'],
]);
}
if (!$show->whereHas('watchProviders', function ($query) use ($show) {
$query->where('show_id', $show->id);
})->exists()) {
$show->watchProviders()->attach($existingWatchProvider, [
'locale' => $locale,
'tmdb_url' => $tmdbWatchProvider['link'],
]);
}
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_WATCH_PROVIDERS);
}
private function getRecommendations($item)
{
$tmdbRecommendations = $this->showsApi->getRecommendations($item->tmdb_id);
if (empty($tmdbRecommendations) || empty($tmdbRecommendations['results'])) {
return;
}
$initialShow = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbRecommendations['results'] as $tmdbRecommendation) {
$itemToFetch = ItemToFetch::where('tmdb_id', $tmdbRecommendation['id'])->where('type', ItemToFetch::TYPE_TV_SERIES)->first();
if ($itemToFetch) {
$this->getDetails($itemToFetch);
continue;
}
$show = Show::where('tmdb_id', $tmdbRecommendation['id'])->first();
if ($show) {
$recommendationLink = ShowRecommendation::where('show_id', $initialShow->id)
->where('recommended_show_id', $show->id)
->first();
if (!$recommendationLink) {
ShowRecommendation::create([
'show_id' => $initialShow->id,
'recommended_show_id' => $show->id,
]);
}
continue;
} else {
$itemToFetch = ItemToFetch::create([
'tmdb_id' => $tmdbRecommendation['id'],
'type' => ItemToFetch::TYPE_TV_SERIES,
]);
$jobs = ItemToFetchJobs::JOBS;
$jobs[] = "Details";
ItemToFetchJobs::create([
'tmdb_id' => $tmdbRecommendation['id'],
'type' => ItemToFetch::TYPE_TV_SERIES,
'remaining_jobs' => json_encode($jobs),
]);
$this->getDetails($itemToFetch);
}
$recommendedShow = Show::where('tmdb_id', $tmdbRecommendation['id'])->first();
ShowRecommendation::create([
'show_id' => $initialShow->id,
'recommended_show_id' => $recommendedShow->id,
]);
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_RECOMMNDATION);
}
private function getSimilar($item)
{
$tmdbSimilarMovies = $this->showsApi->getSimilar($item->tmdb_id);
if (empty($tmdbSimilarMovies) || empty($tmdbSimilarMovies['results'])) {
return;
}
$initialShow = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbSimilarMovies['results'] as $tmdbSimilarMovie) {
$itemToFetch = ItemToFetch::where('tmdb_id', $tmdbSimilarMovie['id'])->where('type', ItemToFetch::TYPE_TV_SERIES)->first();
if ($itemToFetch) {
$this->getDetails($itemToFetch);
continue;
}
$similarShow = Show::where('tmdb_id', $tmdbSimilarMovie['id'])->first();
if ($similarShow) {
$similarLink = ShowSimilar::where('show_id', $initialShow->id)
->where('similar_show_id', $similarShow->id)
->first();
if (!$similarLink) {
ShowSimilar::create([
'show_id' => $initialShow->id,
'similar_show_id' => $similarShow->id,
]);
}
continue;
}
$itemToFetch = ItemToFetch::create([
'tmdb_id' => $tmdbSimilarMovie['id'],
'type' => ItemToFetch::TYPE_TV_SERIES,
]);
$jobs = ItemToFetchJobs::JOBS;
$jobs[] = "Details";
ItemToFetchJobs::create([
'tmdb_id' => $tmdbSimilarMovie['id'],
'type' => ItemToFetch::TYPE_TV_SERIES,
'remaining_jobs' => json_encode($jobs),
]);
$this->getDetails($itemToFetch);
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
$similarShow = Show::where('tmdb_id', $tmdbSimilarMovie['id'])->first();
ShowSimilar::create([
'show_id' => $show->id,
'similar_show_id' => $similarShow->id,
]);
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_SIMILAR);
}
private function getContentRatings($item)
{
$tmdbContentRatings = $this->showsApi->getContentRatings($item->tmdb_id);
if (empty($tmdbContentRatings) || empty($tmdbContentRatings['results'])) {
return;
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($tmdbContentRatings['results'] as $contentRating) {
$existingContentRating = ContentRating::where('iso_3166', $contentRating['iso_3166_1'])
->where('rating', $contentRating['rating'])
->first();
if (!$existingContentRating) {
$existingContentRating = ContentRating::create([
'descriptors' => $contentRating['descriptors'],
'iso_3166' => $contentRating['iso_3166_1'],
'rating' => $contentRating['rating'],
]);
}
// attach if not attached
if (!$show->whereHas('contentRatings', function ($query) use ($show) {
$query->where('show_id', $show->id);
})->exists()) {
$show->contentRatings()->attach($existingContentRating);
}
}
$this->removeElementFromRemainingJobs($item->tmdb_id, ItemToFetchJobs::JOB_CONTENT_RATINGS);
}
private function processSeasons(Show $show, array $seasons)
{
foreach ($seasons as $season) {
$showSeason = Season::where('tmdb_id', $season['id'])
->where('show_id', $show->id)
->first();
if (!$showSeason) {
$season['show_id'] = $show->id;
$showSeason = Season::create($season);
$tmdbSeasonDetails = $this->showsApi->getSeasonDetails($show->tmdb_id, $season['season_number']);
$this->processEpisodes($show, $showSeason, $tmdbSeasonDetails['episodes'] ?? []);
}
}
}
private function processEpisodes($show, $season, array $tmdbEpisodes)
{
if (empty($tmdbEpisodes)) {
return;
}
foreach ($tmdbEpisodes as $tmdbEpisode) {
$episode = Episode::where('show_id', $show->id)
->where('season_id', $season->id)
->where('tmdb_id', $tmdbEpisode['id'])
->first();
if (!$episode) {
$tmdbEpisode['tmdb_id'] = $tmdbEpisode['id'];
$tmdbEpisode['slug'] = Str::slug($tmdbEpisode['name']);
$tmdbEpisode['tmdb_show_id'] = $tmdbEpisode['show_id'];
$tmdbEpisode['season_id'] = $season->id;
// $tmdbEpisode['crew'] = $tmdbEpisode['crew'];
// $tmdbEpisode['guest_stars'] = $tmdbEpisode['guest_stars'];
$tmdbEpisode['show_id'] = $show->id;
$tmdbEpisode['tmdb_id'] = $season->id;
Episode::create($tmdbEpisode);
}
}
}
private function removeElementFromRemainingJobs(int $tmdbId, string $job)
{
$itemToFetchJobs = ItemToFetchJobs::where('tmdb_id', $tmdbId)
->where('type', 'tv_series')
->first();
if (!$itemToFetchJobs) {
echo "no job for ".$tmdbId."\n";
return;
}
$remainingJobs = $itemToFetchJobs->jobs;
if (is_string($remainingJobs)) {
$remainingJobs = explode(',', $remainingJobs);
} else if ($itemToFetchJobs->jobs == null) {
$this->removeItemToFetch($tmdbId);
return;
} else {
dd("Not string", $remainingJobs, $itemToFetchJobs);
return;
}
$remainingJobKey = array_search($job, $remainingJobs);
unset($remainingJobs[$remainingJobKey]);
if (empty($remainingJobs)) {
$this->removeItemToFetch($tmdbId);
return;
}
$itemToFetchJobs->jobs = implode(',', $remainingJobs);
$itemToFetchJobs->save();
}
private function removeItemToFetch($tmdbId)
{
$itemToFetchJobs = ItemToFetchJobs::where('tmdb_id', $tmdbId)
->where('type', 'tv_series')
->first();
$itemToFetch = ItemToFetch::where('tmdb_id', $tmdbId)
->where('type', 'tv_series')
->first();
if ($itemToFetch) {
$itemToFetch->delete();
}
if ($itemToFetchJobs) {
$itemToFetchJobs->delete();
}
}
private function processCast($show, array $credits)
{
if (empty($credits) || $show === null) {
echo "+";
return;
}
foreach ($credits as $castPerson) {
echo "Searching for person ".$castPerson['id']."\n";
$person = Person::where('tmdb_id', $castPerson['id'])->first();
if (!$person) {
$personData = [
'adult' => $castPerson['adult'],
'tmdb_id' => $castPerson['id'],
'gender' => $castPerson['gender'],
'name' => $castPerson['name'],
'slug' => Str::slug($castPerson['name']),
'popularity' => $castPerson['popularity'],
'profile_path' => $castPerson['profile_path'],
];
$tmdbPerson = $this->personApi->getPerson($castPerson['id']);
if (!empty($tmdbPerson)) {
$personData = array_merge($personData, [
'biography' => $tmdbPerson['biography'],
'birtday' => $tmdbPerson['birthday'],
'deathday' => $tmdbPerson['deathday'],
'homepage' => $tmdbPerson['homepage'],
'imdb_id' => $tmdbPerson['imdb_id'],
'known_for_department' => $tmdbPerson['known_for_department'] ? json_encode($tmdbPerson['known_for_department']) : null,
'also_known_as' => $tmdbPerson['also_known_as'] ? json_encode($tmdbPerson['also_known_as']) : null,
'place_of_birth' => $tmdbPerson['place_of_birth'],
]);
}
echo "Creating person ".$castPerson['id']."\n";
$person = Person::create($personData);
}
$castExists = DB::table('show_cast')
->where('show_id', $show->id)
->where('person_id', $person->id)
->first();
if (!$castExists) {
DB::table('show_cast')
->insert([
'show_id' => $show->id,
'person_id' => $person->id,
'known_for_department' => trim($castPerson['known_for_department'], '"'),
'character' => $castPerson['character'],
'tmdb_cast_id' => $castPerson['credit_id'],
'order' => $castPerson['order'],
]);
}
}
}
private function processCrew($show, array $credits)
{
if (empty($credits) || $show === null) {
echo "+";
return;
}
foreach ($credits as $crewPerson) {
$person = Person::where('tmdb_id', $crewPerson['id'])->first();
if (!$person) {
$personData = [
'adult' => $crewPerson['adult'],
'tmdb_id' => $crewPerson['id'],
'gender' => $crewPerson['gender'],
'name' => $crewPerson['name'],
'slug' => Str::slug($crewPerson['name']),
'popularity' => $crewPerson['popularity'],
'profile_path' => $crewPerson['profile_path'],
];
$tmdbPerson = $this->personApi->getPerson($crewPerson['id']);
if (!empty($tmdbPerson)) {
$personData = array_merge($personData, [
'biography' => $tmdbPerson['biography'],
'birtday' => $tmdbPerson['birthday'],
'deathday' => $tmdbPerson['deathday'],
'homepage' => $tmdbPerson['homepage'],
'imdb_id' => $tmdbPerson['imdb_id'],
'known_for_department' => $tmdbPerson['known_for_department'] ? json_encode($tmdbPerson['known_for_department']) : null,
'also_known_as' => $tmdbPerson['also_known_as'] ? json_encode($tmdbPerson['also_known_as']) : null,
'place_of_birth' => $tmdbPerson['place_of_birth'],
]);
}
$person = Person::create($personData);
}
$crewExists = DB::table('show_crew')
->where('show_id', $show->id)
->where('person_id', $person->id)
->first();
if (!$crewExists) {
DB::table('show_crew')
->insert([
'show_id' => $show->id,
'person_id' => $person->id,
'known_for_department' => trim($crewPerson['known_for_department'], '"'),
'job' => $crewPerson['job'],
'department' => $crewPerson['department'],
'tmdb_cast_id' => $crewPerson['credit_id'],
]);
}
}
}
private function createJob($tmdbId)
{
$itemToFetch = ItemToFetch::where('tmdb_id', $tmdbId)->where('type', ItemToFetch::TYPE_TV_SERIES)->first();
if ($itemToFetch) {
return $itemToFetch;
}
$show = Show::where('tmdb_id', $tmdbId)->first();
if ($show) {
return;
}
$itemToFetch = ItemToFetch::create([
'tmdb_id' => $tmdbId,
'type' => ItemToFetch::TYPE_TV_SERIES,
]);
$jobs = ItemToFetchJobs::JOBS;
$jobs[] = "Details";
ItemToFetchJobs::create([
'tmdb_id' => $tmdbId,
'type' => ItemToFetch::TYPE_TV_SERIES,
'remaining_jobs' => json_encode($jobs),
]);
return $itemToFetch;
}
private function processGenres($item, array $genres)
{
foreach ($genres as $tmdbGenre) {
$genre = Genre::where('name', $tmdbGenre['name'])
->where('tmdb_id', $tmdbGenre['id'])
->first();
if (!$genre) {
$genre = Genre::create([
'name' => $tmdbGenre['name'],
'slug' => Str::slug($tmdbGenre['name']),
'tmdb_id' => $tmdbGenre['id'],
'type' => Genre::TYPE_SHOW,
]);
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
if ($show->whereHas('genres', function ($query) use ($genre) {
$query->where('tmdb_id', '=', $genre->tmdb_id);
})->exists()) {
return;
} else {
$show->genres()->attach($genre);
}
}
}
private function processNetworks($item, array $networks)
{
foreach ($networks as $tmdbNetwork) {
$network = Network::where('name', $tmdbNetwork['name'])
->where('tmdb_id', $tmdbNetwork['id'])
->first();
if (!$network) {
$network = Network::create([
'name' => $tmdbNetwork['name'],
'slug' => Str::slug($tmdbNetwork['name']),
'tmdb_id' => $tmdbNetwork['id'],
'logo_path' => $tmdbNetwork['logo_path'],
'origin_country' => $tmdbNetwork['origin_country'],
]);
}
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
if ($show->whereHas('networks', function ($query) use ($network) {
$query->where('tmdb_id', '=', $network->tmdb_id);
})->exists()) {
return;
} else {
$show->networks()->attach($network);
}
}
}
private function processProductionCompanies($item, array $productionCompanies)
{
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($productionCompanies as $productionCompany) {
$existingProductionCompany = ProductionCompany::where('tmdb_id', $productionCompany['id'])->first();
if (!$existingProductionCompany) {
$existingProductionCompany = ProductionCompany::create([
'tmdb_id' => $productionCompany['id'],
'logo_path' => $productionCompany['logo_path'],
'name' => $productionCompany['name'],
'origin_country' => $productionCompany['origin_country'],
]);
}
if ($show->whereHas('productionCompanies', function ($query) use ($existingProductionCompany) {
$query->where('production_company_id', '=', $existingProductionCompany->id);
})->exists()) {
return;
} else {
$show->productionCompanies()->attach($existingProductionCompany);
}
}
}
private function processProductionCountries($item, array $productionCountries)
{
$show = Show::where('tmdb_id', $item->tmdb_id)->first();
foreach ($productionCountries as $productionCountry) {
$existingProductionCountry = ProductionCountry::where('iso_3166', $productionCountry['iso_3166_1'])->first();
if (!$existingProductionCountry) {
$existingProductionCountry = ProductionCountry::create([
'iso_3166' => $productionCountry['iso_3166_1'],
'name' => $productionCountry['name'],
]);
}
if ($show->whereHas('productionCountries', function ($query) use ($existingProductionCountry) {
$query->where('production_country_id', '=', $existingProductionCountry->id);
})->exists()) {
return;
} else {
$show->productionCountries()->attach($existingProductionCountry);
}
}
}
}