summaryrefslogtreecommitdiff
path: root/app/Libraries/Background.php
blob: 6c84e9764da956e830d932ab4037d6734db7294b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace App\Libraries;

use Carbon\Carbon;

use App\Libraries\AnimeSchedule;
use App\Libraries\AnimeSeason;
use App\Anime;
use App\AnimeStats;
use App\MALUser;
use App\Calendar;
use App\Airing;

use Eluceo\iCal\Component\Calendar as iCalendar; 
use Eluceo\iCal\Component\Event;

class Background {

	public function setAiring(Anime $anime) {
		$stats = $anime->getStats()->get()->first();
		if ( is_null($stats->score) ) {
			return;
		}

		$airing = Airing::where('mal_id', $stats->mal_id)->get()->first();
		if ( is_null($airing) ) {
			$airing = new Airing();
		}

		/**
		 * Try to get Data from Anilist.
		 * On error return early.
		 */
		try {
			$airing_data = $anime->getDataFromAnilist();
		} catch( Exception $e ) {
			echo "Getting Data from Anilist failed for anime: " . $anime->title_pref . " (" . $anime->mal_id . ")\n";
			return;
		}
		if ( "" == $airing_data ) {
			echo "Got empty data from Anilist for anime: " . $anime->title_pref . " (" . $anime->mal_id . ")\n";
			return;
		}

		/**
		 * Check if we need to save the airing data or if we already have it in database.
		 */
		if ( ! is_null( $airing->episode ) ) {
			if ( ! is_null( $airing_data->nextAiringEpisode ) && 
			   ( $airing->episode == $airing_data->nextAiringEpisode->episode) ) {
				if ( $airing->aired_at == $airing_data->nextAiringEpisode->airingAt ) {
					/**
					 * Double entry.
					 */
					return;
				}
				/**
				 * We need to update because the airing data was postponed.
				 */
			}
		} 

		$airing->mal_id = $anime->mal_id;
		if ( ! is_null($airing_data->nextAiringEpisode) ) {
			$airing->episode = $airing_data->nextAiringEpisode->episode;
		}
		if ( ! is_null($airing_data->nextAiringEpisode) ) {
			$airing->aired_at = Carbon::createFromTimestamp($airing_data->nextAiringEpisode->airingAt);
		}
		if ( ! is_null($airing_data) ) {
			$airing->duration = $airing_data->duration;
		}

		if ( is_null($airing_data->duration) ) {
			echo "No duration found for anime: " . $anime->title_pref . " (" . $anime->mal_id . "). (Autoset to 20.)\n";
			$airing->duration = 20;
		}

		if ( is_null($airing->aired_at) ) {
			echo "No airing date found for anime: " . $anime->title_pref . " (" . $anime->mal_id . ")\n";
			return;
		}
		
		$airing->save();
	}

	public function setAiringForAll() {
		$anime_all = Anime::get();
		foreach( $anime_all as $anime ) {
			$this->setAiring($anime);
			sleep(1);
		}
	}
}