3 namespace Rapsys\AirBundle\Command
;
5 use Doctrine\Bundle\DoctrineBundle\Command\DoctrineCommand
;
6 use Doctrine\Persistence\ManagerRegistry
;
7 use Symfony\Component\Console\Input\InputInterface
;
8 use Symfony\Component\Console\Output\OutputInterface
;
9 use Symfony\Component\Filesystem\Exception\IOException
;
10 use Symfony\Component\Filesystem\Filesystem
;
12 use Rapsys\AirBundle\Entity\Session
;
14 class WeatherCommand
extends DoctrineCommand
{
15 //Set failure constant
18 ///Set success constant
23 //Mostly useless in fact
25 //Required to simplify simplexml transition
27 //Required to avoid xml errors
28 'quote-nbsp' => false,
29 //Required to fix code
33 ///Set accuweather uris
34 private $accuweather = [
37 75001 => 'https://www.accuweather.com/en/fr/paris-01-louvre/75001/hourly-weather-forecast/179142_pc?day=',
38 75004 => 'https://www.accuweather.com/en/fr/paris-04-hotel-de-ville/75004/hourly-weather-forecast/179145_pc?day=',
39 75005 => 'https://www.accuweather.com/en/fr/paris-05-pantheon/75005/hourly-weather-forecast/179146_pc?day=',
40 75006 => 'https://www.accuweather.com/fr/fr/paris-06-luxembourg/75006/hourly-weather-forecast/179147_pc?day=',
41 75007 => 'https://www.accuweather.com/en/fr/paris-07-palais-bourbon/75007/hourly-weather-forecast/179148_pc?day=',
42 75009 => 'https://www.accuweather.com/en/fr/paris-09-opera/75009/hourly-weather-forecast/179150_pc?day=',
43 75012 => 'https://www.accuweather.com/en/fr/paris-12-reuilly/75012/hourly-weather-forecast/179153_pc?day=',
44 75013 => 'https://www.accuweather.com/en/fr/paris-13-gobelins/75013/hourly-weather-forecast/179154_pc?day=',
45 75015 => 'https://www.accuweather.com/en/fr/paris-15-vaugirard/75015/hourly-weather-forecast/179156_pc?day=',
46 75019 => 'https://www.accuweather.com/en/fr/paris-19-buttes-chaumont/75019/hourly-weather-forecast/179160_pc?day=',
47 75116 => 'https://www.accuweather.com/en/fr/paris-16-passy/75116/hourly-weather-forecast/179246_pc?day='
51 75001 => 'https://www.accuweather.com/en/fr/paris-01-louvre/75001/daily-weather-forecast/179142_pc',
52 75004 => 'https://www.accuweather.com/en/fr/paris-04-hotel-de-ville/75004/daily-weather-forecast/179145_pc',
53 75005 => 'https://www.accuweather.com/en/fr/paris-05-pantheon/75005/daily-weather-forecast/179146_pc',
54 75006 => 'https://www.accuweather.com/fr/fr/paris-06-luxembourg/75006/daily-weather-forecast/179147_pc',
55 75007 => 'https://www.accuweather.com/en/fr/paris-07-palais-bourbon/75007/daily-weather-forecast/179148_pc',
56 75009 => 'https://www.accuweather.com/en/fr/paris-09-opera/75009/daily-weather-forecast/179150_pc',
57 75012 => 'https://www.accuweather.com/en/fr/paris-12-reuilly/75012/daily-weather-forecast/179153_pc',
58 75013 => 'https://www.accuweather.com/en/fr/paris-13-gobelins/75013/daily-weather-forecast/179154_pc',
59 75015 => 'https://www.accuweather.com/en/fr/paris-15-vaugirard/75015/daily-weather-forecast/179156_pc',
60 75019 => 'https://www.accuweather.com/en/fr/paris-19-buttes-chaumont/75019/daily-weather-forecast/179160_pc',
61 75116 => 'https://www.accuweather.com/en/fr/paris-16-passy/75116/daily-weather-forecast/179246_pc'
68 ///Set manager registry
74 ///Weather command constructor
75 public function __construct(ManagerRegistry
$doctrine, Filesystem
$filesystem) {
76 parent
::__construct($doctrine);
79 $this->doctrine
= $doctrine;
82 $this->filesystem
= $filesystem;
85 ///Configure attribute command
86 protected function configure() {
90 ->setName('rapsysair:weather')
91 //Set description shown with bin/console list
92 ->setDescription('Updates session rain and temperature fields')
93 //Set description shown with bin/console --help airlibre:attribute
94 ->setHelp('This command updates session rain and temperature fields in next three days')
95 //Add daily and hourly aliases
96 ->setAliases(['rapsysair:weather:daily', 'rapsysair:weather:hourly']);
99 ///Process the attribution
100 protected function execute(InputInterface
$input, OutputInterface
$output) {
102 $kernel = $this->getApplication()->getKernel();
105 $tmpdir = $kernel->getContainer()->getParameter('kernel.project_dir').'/var/cache/weather';
108 //XXX: worst case scenario we have 3 files per zipcode plus daily
109 if (!is_dir($tmpdir)) {
112 $this->filesystem
->mkdir($tmpdir, 0775);
113 } catch (IOException
$exception) {
115 echo 'Create dir '.$exception->getPath().' failed'."\n";
128 //Init zipcodes array
134 //Process hourly accuweather
135 if (($command = $input->getFirstArgument()) == 'rapsysair:weather:hourly' || $command == 'rapsysair:weather') {
136 //Fetch hourly sessions to attribute
137 $types['hourly'] = $this->doctrine
->getRepository(Session
::class)->findAllPendingHourlyWeather();
139 //Iterate on each session
140 foreach($types['hourly'] as $sessionId => $session) {
142 $zipcode = $session->getLocation()->getZipcode();
145 $start = $session->getStart();
148 $day = $start->diff((new \
DateTime('now'))->setTime(0, 0, 0))->d +
1;
150 //Check if zipcode is set
151 if (!isset($zipcodes[$zipcode])) {
152 $zipcodes[$zipcode] = [];
155 //Check if zipcode date is set
156 if (!isset($zipcodes[$zipcode][$day])) {
157 $zipcodes[$zipcode][$day] = [ $sessionId => $sessionId ];
159 $zipcodes[$zipcode][$day][$sessionId] = $sessionId;
163 $stop = $session->getStop();
166 $day = $stop->diff((new \
DateTime('now'))->setTime(0, 0, 0))->d +
1;
168 //Check if zipcode date is set
169 if (!isset($zipcodes[$zipcode][$day])) {
170 $zipcodes[$zipcode][$day] = [ $sessionId => $sessionId ];
172 $zipcodes[$zipcode][$day][$sessionId] = $sessionId;
177 //Process daily accuweather
178 if ($command == 'rapsysair:weather:daily' || $command == 'rapsysair:weather') {
179 //Fetch daily sessions to attribute
180 $types['daily'] = $this->doctrine
->getRepository(Session
::class)->findAllPendingDailyWeather();
182 //Iterate on each session
183 foreach($types['daily'] as $sessionId => $session) {
185 $zipcode = $session->getLocation()->getZipcode();
188 $start = $session->getStart();
193 //Check if zipcode is set
194 if (!isset($zipcodes[$zipcode])) {
195 $zipcodes[$zipcode] = [];
198 //Check if zipcode date is set
199 if (!isset($zipcodes[$zipcode][$day])) {
200 $zipcodes[$zipcode][$day] = [ $sessionId => $sessionId ];
202 $zipcodes[$zipcode][$day][$sessionId] = $sessionId;
213 //Iterate on zipcodes
214 foreach($zipcodes as $zipcode => $days) {
216 foreach($days as $day => $null) {
217 //Try to load content from cache
218 if (!is_file($file = $tmpdir.'/'.$zipcode.'.'.$day.'.html') || stat($file)['ctime'] <= (time() - ($day == 'daily' ? 4 : 2)*3600) || ($content = file_get_contents($file)) === false) {
219 //Prevent timing detection
220 //XXX: from 0.1 to 5 seconds
221 usleep(rand(1,50) * 100000);
224 //TODO: for daily we may load data for requested quarter of the day
225 $content = $this->curl_get($day == 'daily' ? $this->accuweather
['daily'][$zipcode] : $this->accuweather
['hourly'][$zipcode].$day);
228 if (file_put_contents($tmpdir.'/'.$zipcode.'.'.$day.'.html', $content) === false) {
230 echo 'Write to '.$tmpdir.'/'.$zipcode.'.'.$day.'.html failed'."\n";
238 $tidy->parseString($content, $this->config
, 'utf8');
241 //XXX: don't care about theses errors, tidy is here to fix...
242 #if (!empty($tidy->errorBuffer)) {
243 # var_dump($tidy->errorBuffer);
244 # die('Tidy errors');
248 //XXX: trash all xmlns= broken tags
249 $sx = new \
SimpleXMLElement(str_replace(['xmlns=', 'xlink:href='], ['xns=', 'href='], $tidy));
252 if ($day == 'daily') {
253 //Iterate on each link containing data
254 foreach($sx->xpath('//a[contains(@class,"daily-forecast-card")]') as $node) {
256 $dsm = trim($node->div
[0]->h2
[0]->span
[1]);
259 $temperature = str_replace('Ā°', '', $node->div
[0]->div
[0]->span
[0]);
262 $rainrisk = trim(str_replace('%', '', $node->div
[1]))/100;
265 $data[$zipcode][$dsm]['daily'] = [
266 'temperature' => $temperature,
267 'rainrisk' => $rainrisk
272 //Iterate on each div containing data
273 #(string)$sx->xpath('//div[@class="hourly-card-nfl"]')[0]->attributes()->value
274 #/html/body/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/div[1]/div/h2/span[1]
275 foreach($sx->xpath('//div[@data-shared="false"]') as $node) {
277 $hour = trim(str_replace(' h', '', $node->div
[0]->div
[0]->div
[0]->div
[0]->div
[0]->h2
[0]));
279 //Compute dsm from day (1=d,2=d+1,3=d+2)
280 $dsm = (new \
DateTime('+'.($day - 1).' day'))->format('d/m');
283 $temperature = str_replace('Ā°', '', $node->div
[0]->div
[0]->div
[0]->div
[0]->div
[1]);
286 $realfeel = trim(str_replace(['RealFeelĀ®', 'Ā°'], '', $node->div
[0]->div
[0]->div
[0]->div
[1]->div
[0]->div
[0]->div
[0]));
289 $rainrisk = floatval(str_replace('%', '', trim($node->div
[0]->div
[0]->div
[0]->div
[2]->div
[0]))/100);
291 //Set rainfall to 0 (mm)
294 //Iterate on each entry
295 //TODO: wind and other infos are present in $node->div[1]->div[0]->div[1]->div[0]->p
296 foreach($node->div
[1]->div
[0]->div
[1]->div
[0]->p
as $p) {
297 //Lookup for rain entry if present
298 if (in_array(trim($p), ['Rain', 'Pluie'])) {
300 $rainfall = floatval(str_replace(' mm', '', $p->span
[0]));
305 $data[$zipcode][$dsm][$hour] = [
306 'temperature' => $temperature,
307 'realfeel' => $realfeel,
308 'rainrisk' => $rainrisk,
309 'rainfall' => $rainfall
320 foreach($types as $type => $sessions) {
321 //Iterate on each type
322 foreach($sessions as $sessionId => $session) {
324 $zipcode = $session->getLocation()->getZipcode();
327 $start = $session->getStart();
330 if ($type == 'daily') {
332 $period = [ $start ];
336 $stop = $session->getStop();
339 $period = new \
DatePeriod(
342 //Iterate on each hour
343 new \
DateInterval('PT1H'),
344 //End with begin + length
354 'realfeelmin' => null,
355 'realfeelmax' => null,
357 'temperaturemin' => null,
358 'temperaturemax' => null
361 //Iterate on the period
362 foreach($period as $time) {
364 $dsm = $time->format('d/m');
367 $hour = $type=='daily'?$type:$time->format('H');
369 //Check data availability
370 //XXX: sometimes startup delay causes weather data to be unavailable for session first hour
371 if (!isset($data[$zipcode][$dsm][$hour])) {
372 //Skip unavailable data
377 $info = $data[$zipcode][$dsm][$hour];
379 //Check if rainrisk is higher
380 if ($meteo['rainrisk'] === null || $info['rainrisk'] > $meteo['rainrisk']) {
381 //Set highest rain risk
382 $meteo['rainrisk'] = floatval($info['rainrisk']);
385 //Check if rainfall is set
386 if (isset($info['rainfall'])) {
388 $meteo['rainfall'] +
= floatval($info['rainfall']);
392 $meteo['temperature'][$hour] = $info['temperature'];
395 if ($type != 'daily') {
396 //Check min temperature
397 if ($meteo['temperaturemin'] === null || $info['temperature'] < $meteo['temperaturemin']) {
398 $meteo['temperaturemin'] = floatval($info['temperature']);
401 //Check max temperature
402 if ($meteo['temperaturemax'] === null || $info['temperature'] > $meteo['temperaturemax']) {
403 $meteo['temperaturemax'] = floatval($info['temperature']);
407 //Check if realfeel is set
408 if (isset($info['realfeel'])) {
410 $meteo['realfeel'][$hour] = $info['realfeel'];
413 if ($meteo['realfeelmin'] === null || $info['realfeel'] < $meteo['realfeelmin']) {
414 $meteo['realfeelmin'] = floatval($info['realfeel']);
418 if ($meteo['realfeelmax'] === null || $info['realfeel'] > $meteo['realfeelmax']) {
419 $meteo['realfeelmax'] = floatval($info['realfeel']);
424 //Check if rainfall is set and differ
425 if ($session->getRainfall() !== $meteo['rainfall']) {
427 $session->setRainfall($meteo['rainfall']);
430 //Check if rainrisk differ
431 if ($session->getRainrisk() !== $meteo['rainrisk']) {
433 $session->setRainrisk($meteo['rainrisk']);
436 //Check realfeel array
437 if ($meteo['realfeel'] !== []) {
439 $realfeel = floatval(round(array_sum($meteo['realfeel'])/count($meteo['realfeel']),1));
441 //Check if realfeel differ
442 if ($session->getRealfeel() !== $realfeel) {
443 //Set average realfeel
444 $session->setRealfeel($realfeel);
447 //Check if realfeelmin differ
448 if ($session->getRealfeelmin() !== $meteo['realfeelmin']) {
450 $session->setRealfeelmin($meteo['realfeelmin']);
453 //Check if realfeelmax differ
454 if ($session->getRealfeelmax() !== $meteo['realfeelmax']) {
456 $session->setRealfeelmax($meteo['realfeelmax']);
460 //Check temperature array
461 if ($meteo['temperature'] !== []) {
462 //Compute temperature
463 $temperature = floatval(round(array_sum($meteo['temperature'])/count($meteo['temperature']),1));
465 //Check if temperature differ
466 if ($session->getTemperature() !== $temperature) {
467 //Set average temperature
468 $session->setTemperature($temperature);
471 //Check if temperaturemin differ
472 if ($session->getTemperaturemin() !== $meteo['temperaturemin']) {
474 $session->setTemperaturemin($meteo['temperaturemin']);
477 //Check if temperaturemax differ
478 if ($session->getTemperaturemax() !== $meteo['temperaturemax']) {
480 $session->setTemperaturemax($meteo['temperaturemax']);
486 //Flush to get the ids
487 $this->doctrine
->getManager()->flush();
493 return self
::SUCCESS
;
499 * @return bool|void Return success or exit
501 function curl_init() {
503 if (($this->ch
= curl_init()) === false) {
505 echo 'Curl init failed: '.curl_error($this->ch
)."\n";
516 CURLOPT_HTTP_VERSION
=> CURL_HTTP_VERSION_2_0
,
518 CURLOPT_HTTPHEADER
=> [
519 //XXX: it seems that you can disable akamai fucking protection with Pragma: akamai-x-cache-off
520 //XXX: see https://support.globaldots.com/hc/en-us/articles/115003996705-Akamai-Pragma-Headers-overview
521 #'Pragma: akamai-x-cache-off',
522 //XXX: working curl command
523 #curl --http2 --cookie file.jar --cookie-jar file.jar -v -i -k -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' -H 'Accept-Language: en-GB,en;q=0.9' -H 'Cache-Control: no-cache' -H 'Connection: keep-alive' -H 'Host: www.accuweather.com' -H 'Pragma: no-cache' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36' 'https://www.accuweather.com/'
525 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
526 //Set accept language
527 'Accept-Language: en-GB,en;q=0.9',
529 'Cache-Control: no-cache',
530 //Keep connection alive
531 'Connection: keep-alive',
534 //Force secure requests
535 'Upgrade-Insecure-Requests: 1',
537 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
538 //Force akamai cookie
539 //XXX: seems to come from http request
543 CURLOPT_COOKIEFILE
=> '',
544 //Disable location following
545 CURLOPT_FOLLOWLOCATION
=> false,
547 #CURLOPT_URL => $url = 'https://www.accuweather.com/',
549 CURLOPT_HEADER
=> true,
551 CURLOPT_RETURNTRANSFER
=> true,
554 CURLINFO_HEADER_OUT
=> true
559 echo 'Curl setopt array failed: '.curl_error($this->ch
)."\n";
571 * @return string|void Return url content or exit
573 function curl_get($url) {
575 if (curl_setopt($this->ch
, CURLOPT_URL
, $url) === false) {
577 echo 'Setopt for '.$url.' failed: '.curl_error($this->ch
)."\n";
580 curl_close($this->ch
);
586 //Check return status
587 if (($response = curl_exec($this->ch
)) === false) {
589 echo 'Get for '.$url.' failed: '.curl_error($this->ch
)."\n";
591 //Display sent headers
592 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
598 curl_close($this->ch
);
605 if (empty($hs = curl_getinfo($this->ch
, CURLINFO_HEADER_SIZE
))) {
607 echo 'Getinfo for '.$url.' failed: '.curl_error($this->ch
)."\n";
609 //Display sent headers
610 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
616 curl_close($this->ch
);
623 if (empty($header = substr($response, 0, $hs))) {
625 echo 'Header for '.$url.' empty: '.curl_error($this->ch
)."\n";
627 //Display sent headers
628 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
634 curl_close($this->ch
);
640 //Check request success
641 if (strlen($header) <= 10 || substr($header, 0, 10) !== 'HTTP/2 200') {
643 echo 'Status for '.$url.' failed: '.curl_error($this->ch
)."\n";
645 //Display sent headers
646 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
652 curl_close($this->ch
);
659 return substr($response, $hs);
665 * @return bool Return success or failure
667 function curl_close() {
668 return curl_close($this->ch
);