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 = str_replace('%', '', trim($node->div[2]))/100;
263 $rainrisk = trim(str_replace('%', '', $node->div
[1]))/100;
266 $data[$zipcode][$dsm]['daily'] = [
267 'temperature' => $temperature,
268 'rainrisk' => $rainrisk
273 //Iterate on each div containing data
274 #(string)$sx->xpath('//div[@class="hourly-card-nfl"]')[0]->attributes()->value
275 #/html/body/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/div[1]/div/h2/span[1]
276 foreach($sx->xpath('//div[@data-shared="false"]') as $node) {
278 $hour = trim(str_replace(' h', '', $node->div
[0]->div
[0]->div
[0]->div
[0]->div
[0]->h2
[0]));
280 //Compute dsm from day (1=d,2=d+1,3=d+2)
281 $dsm = (new \
DateTime('+'.($day - 1).' day'))->format('d/m');
284 $temperature = str_replace('Ā°', '', $node->div
[0]->div
[0]->div
[0]->div
[0]->div
[1]);
287 $realfeel = trim(str_replace(['RealFeelĀ®', 'Ā°'], '', $node->div
[0]->div
[0]->div
[0]->div
[1]->div
[0]->div
[0]->div
[0]));
290 $rainrisk = floatval(str_replace('%', '', trim($node->div
[0]->div
[0]->div
[0]->div
[2]->div
[0]))/100);
292 //Set rainfall to 0 (mm)
295 //Iterate on each entry
296 //TODO: wind and other infos are present in $node->div[1]->div[0]->div[1]->div[0]->p
297 #foreach($node->div[1]->div[0]->div[1]->div[1]->p as $p) {
298 foreach($node->div
[1]->div
[0]->div
[1]->div
[0]->p
as $p) {
299 //Lookup for rain entry if present
300 if (in_array(trim($p), ['Rain', 'Pluie'])) {
302 $rainfall = floatval(str_replace(' mm', '', $p->span
[0]));
307 $data[$zipcode][$dsm][$hour] = [
308 'temperature' => $temperature,
309 'realfeel' => $realfeel,
310 'rainrisk' => $rainrisk,
311 'rainfall' => $rainfall
322 foreach($types as $type => $sessions) {
323 //Iterate on each type
324 foreach($sessions as $sessionId => $session) {
326 $zipcode = $session->getLocation()->getZipcode();
329 $start = $session->getStart();
332 if ($type == 'daily') {
334 $period = [ $start ];
338 $stop = $session->getStop();
341 $period = new \
DatePeriod(
344 //Iterate on each hour
345 new \
DateInterval('PT1H'),
346 //End with begin + length
356 'realfeelmin' => null,
357 'realfeelmax' => null,
359 'temperaturemin' => null,
360 'temperaturemax' => null
363 //Iterate on the period
364 foreach($period as $time) {
366 $dsm = $time->format('d/m');
369 $hour = $type=='daily'?$type:$time->format('H');
371 //Check data availability
372 //XXX: sometimes startup delay causes weather data to be unavailable for session first hour
373 if (!isset($data[$zipcode][$dsm][$hour])) {
374 //Skip unavailable data
379 $info = $data[$zipcode][$dsm][$hour];
381 //Check if rainrisk is higher
382 if ($meteo['rainrisk'] === null || $info['rainrisk'] > $meteo['rainrisk']) {
383 //Set highest rain risk
384 $meteo['rainrisk'] = floatval($info['rainrisk']);
387 //Check if rainfall is set
388 if (isset($info['rainfall'])) {
390 $meteo['rainfall'] +
= floatval($info['rainfall']);
394 $meteo['temperature'][$hour] = $info['temperature'];
397 if ($type != 'daily') {
398 //Check min temperature
399 if ($meteo['temperaturemin'] === null || $info['temperature'] < $meteo['temperaturemin']) {
400 $meteo['temperaturemin'] = floatval($info['temperature']);
403 //Check max temperature
404 if ($meteo['temperaturemax'] === null || $info['temperature'] > $meteo['temperaturemax']) {
405 $meteo['temperaturemax'] = floatval($info['temperature']);
409 //Check if realfeel is set
410 if (isset($info['realfeel'])) {
412 $meteo['realfeel'][$hour] = $info['realfeel'];
415 if ($meteo['realfeelmin'] === null || $info['realfeel'] < $meteo['realfeelmin']) {
416 $meteo['realfeelmin'] = floatval($info['realfeel']);
420 if ($meteo['realfeelmax'] === null || $info['realfeel'] > $meteo['realfeelmax']) {
421 $meteo['realfeelmax'] = floatval($info['realfeel']);
426 //Check if rainfall is set and differ
427 if ($session->getRainfall() !== $meteo['rainfall']) {
429 $session->setRainfall($meteo['rainfall']);
432 //Check if rainrisk differ
433 if ($session->getRainrisk() !== $meteo['rainrisk']) {
435 $session->setRainrisk($meteo['rainrisk']);
438 //Check realfeel array
439 if ($meteo['realfeel'] !== []) {
441 $realfeel = floatval(round(array_sum($meteo['realfeel'])/count($meteo['realfeel']),1));
443 //Check if realfeel differ
444 if ($session->getRealfeel() !== $realfeel) {
445 //Set average realfeel
446 #$meteo['realfeel'] = array_sum($meteo['realfeel'])/count($meteo['realfeel']);
447 $session->setRealfeel($realfeel);
450 //Check if realfeelmin differ
451 if ($session->getRealfeelmin() !== $meteo['realfeelmin']) {
453 $session->setRealfeelmin($meteo['realfeelmin']);
456 //Check if realfeelmax differ
457 if ($session->getRealfeelmax() !== $meteo['realfeelmax']) {
459 $session->setRealfeelmax($meteo['realfeelmax']);
463 //Check temperature array
464 if ($meteo['temperature'] !== []) {
465 //Compute temperature
466 $temperature = floatval(round(array_sum($meteo['temperature'])/count($meteo['temperature']),1));
468 //Check if temperature differ
469 if ($session->getTemperature() !== $temperature) {
470 //Set average temperature
471 #$meteo['temperature'] = array_sum($meteo['temperature'])/count($meteo['temperature']);
472 $session->setTemperature($temperature);
475 //Check if temperaturemin differ
476 if ($session->getTemperaturemin() !== $meteo['temperaturemin']) {
478 $session->setTemperaturemin($meteo['temperaturemin']);
481 //Check if temperaturemax differ
482 if ($session->getTemperaturemax() !== $meteo['temperaturemax']) {
484 $session->setTemperaturemax($meteo['temperaturemax']);
490 //Flush to get the ids
491 $this->doctrine
->getManager()->flush();
497 return self
::SUCCESS
;
503 * @return bool|void Return success or exit
505 function curl_init() {
507 if (($this->ch
= curl_init()) === false) {
509 echo 'Curl init failed: '.curl_error($this->ch
)."\n";
520 CURLOPT_HTTP_VERSION
=> CURL_HTTP_VERSION_2_0
,
522 CURLOPT_HTTPHEADER
=> [
523 //XXX: it seems that you can disable akamai fucking protection with Pragma: akamai-x-cache-off
524 //XXX: see https://support.globaldots.com/hc/en-us/articles/115003996705-Akamai-Pragma-Headers-overview
525 #'Pragma: akamai-x-cache-off',
526 //XXX: working curl command
527 #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/'
529 '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',
530 //Set accept language
531 'Accept-Language: en-GB,en;q=0.9',
533 'Cache-Control: no-cache',
534 //Keep connection alive
535 'Connection: keep-alive',
538 //Force secure requests
539 'Upgrade-Insecure-Requests: 1',
541 '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',
542 //Force akamai cookie
543 //XXX: seems to come from http request
547 CURLOPT_COOKIEFILE
=> '',
548 //Disable location following
549 CURLOPT_FOLLOWLOCATION
=> false,
551 #CURLOPT_URL => $url = 'https://www.accuweather.com/',
553 CURLOPT_HEADER
=> true,
555 CURLOPT_RETURNTRANSFER
=> true,
558 CURLINFO_HEADER_OUT
=> true
563 echo 'Curl setopt array failed: '.curl_error($this->ch
)."\n";
575 * @return string|void Return url content or exit
577 function curl_get($url) {
579 if (curl_setopt($this->ch
, CURLOPT_URL
, $url) === false) {
581 echo 'Setopt for '.$url.' failed: '.curl_error($this->ch
)."\n";
584 curl_close($this->ch
);
590 //Check return status
591 if (($response = curl_exec($this->ch
)) === false) {
593 echo 'Get for '.$url.' failed: '.curl_error($this->ch
)."\n";
595 //Display sent headers
596 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
602 curl_close($this->ch
);
609 if (empty($hs = curl_getinfo($this->ch
, CURLINFO_HEADER_SIZE
))) {
611 echo 'Getinfo for '.$url.' failed: '.curl_error($this->ch
)."\n";
613 //Display sent headers
614 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
620 curl_close($this->ch
);
627 if (empty($header = substr($response, 0, $hs))) {
629 echo 'Header for '.$url.' empty: '.curl_error($this->ch
)."\n";
631 //Display sent headers
632 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
638 curl_close($this->ch
);
644 //Check request success
645 if (strlen($header) <= 10 || substr($header, 0, 10) !== 'HTTP/2 200') {
647 echo 'Status for '.$url.' failed: '.curl_error($this->ch
)."\n";
649 //Display sent headers
650 var_dump(curl_getinfo($this->ch
, CURLINFO_HEADER_OUT
));
656 curl_close($this->ch
);
663 return substr($response, $hs);
669 * @return bool Return success or failure
671 function curl_close() {
672 return curl_close($this->ch
);