Skip to content

Commit

Permalink
Merge pull request #9 from vannut/feature-extract-fetch-to-action
Browse files Browse the repository at this point in the history
Fetch data in Action and CP updates
  • Loading branch information
vannut committed Dec 11, 2021
2 parents 89a96b0 + c58a26b commit 722a0ef
Show file tree
Hide file tree
Showing 9 changed files with 201 additions and 71 deletions.
49 changes: 29 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,38 +33,47 @@ Next to the data provided by the API, the addon adds a couple of nice additional
{{ wind_bft }} Wind speed in Beaufort
{{ uvi_color }} Color representation of the UV Index
{{ uvi_percentage }} Percentage where UVI 10 = 100%;
{{ fetched_at }} Unix Epoch timestamp of the datetime when fetched from API
```

You'll have two tags to your disposal: `{{ forecast }}` and `{{ current_weather }}`

## Simple 7 day forecast
The `{{ forecast }}` tag is an array of days which you can traverse to display weather-cards.
With the `{{ forecast }}` tag you will be able to display a card per day with the forecast.
This data is located in the `days` array which you can traverse and add your styling magic.

This is a very simple example:
```html
<div class="flex bg-neutral-100">
{{ forecast :locale="site" }}
<div class="rounded-xl bg-white">
<div class="lining-nums p-4 text-center">
{{ dt format_localized="%A" }}<br>
{{ dt format_localized="%e %b %Y" }}
</div>
<div class="pb-4 text-5xl flex justify-center">
<i class="fal {{ icon }}"></i>
</div>
<div class="pb-2 flex items-center justify-center">
<div>
{{ temp.max | round }}<span class="text-neutral-700">&deg;C</span>
{{ days }}
<div class="rounded-xl bg-white">
<div class="lining-nums p-4 text-center">
{{ dt format_localized="%A" }}<br>
{{ dt format_localized="%e %b %Y" }}
</div>
<div class="text-sm">
<span class="text-neutral-700">&nbsp;&nbsp; / </span>
{{ temp.min | round }}<span class="text-neutral-700">&deg;C</span>
<div class="pb-4 text-5xl flex justify-center">
<i class="fal {{ icon }}"></i>
</div>
</div>
<div class="flex items-center justify-center pb-4">
<div>
<i class="fal fa-wind"></i>
{{ wind_compass }} {{ wind_bft }}<span class="text-neutral-700">Bft</span>
<div class="pb-2 flex items-center justify-center">
<div>
{{ temp.max | round }}<span class="text-neutral-700">&deg;C</span>
</div>
<div class="text-sm">
<span class="text-neutral-700">&nbsp;&nbsp; / </span>
{{ temp.min | round }}<span class="text-neutral-700">&deg;C</span>
</div>
</div>
<div class="flex items-center justify-center pb-4">
<div>
<i class="fal fa-wind"></i>
{{ wind_compass }} {{ wind_bft }}<span class="text-neutral-700">Bft</span>
</div>
</div>
</div>
{{ /days }}
<div>
Forecast feched at: {{ fetched_at format_localized="%e %b %Y %H:%M" }} server time
</div>
{{/forecast }}
</div>
Expand Down
31 changes: 31 additions & 0 deletions resources/views/current_data.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
@extends('statamic::layout')
@section('title', 'Weather settings')
@section('wrapper_class', 'max-w-md ml-0')

@section('content')

<form
title="Fetch current Weather"
method="post"
action="{{ cp_route('weather.data.fetchWeather') }}"
>
<button class="btn-primary" type="submit">Fetch/update Weather data</button>
@csrf
</form>

<h1 class="mt-4">Current Data</h1>
@if( ! $json )
<p><em>No data stored yet</em></p>
@else
<div name="textarea">
<textarea
id="field_textarea"
class="input-text"
style="width:100%; overflow-wrap: break-word; height: 450px;"
>{{ $json }}</textarea>
</div>
@endif



@endsection
16 changes: 15 additions & 1 deletion routes/cp.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@

Route::namespace('\Vannut\StatamicWeather\Controllers')->group(function () {
Route::prefix('weather')->as('weather')->group(function () {
Route::get('/', 'ControlPanelController@index')->name('.settings');

// Data routes
Route::get(
'/',
'ControlPanelController@currentData'
)->name('.data');
Route::post(
'/fetch-weather',
'ControlPanelController@fetchWeather'
)->name('.data.fetchWeather');


// Settings
Route::get('/settings', 'ControlPanelController@index')->name('.settings');
Route::post('/update-settings', 'ControlPanelController@update')->name('.settings.update');

});
});
69 changes: 69 additions & 0 deletions src/Actions/FetchAndStoreAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace Vannut\StatamicWeather\Actions;

use Storage;
use Illuminate\Support\Collection;

class FetchAndStoreAction {

public function __construct(
Collection $config
) {
$this->config = $config;
}

public function execute(): bool
{

$content = $this->talkToOpenweathermap();

// Do nothing when we don't get anything back
if ($content === false) {
return false;
}

// Decode the json object, drop out when not a valid object
$jsonObj = json_decode($content);
if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
return false;
}

// add the fetch time
$jsonObj = array_merge(["fetched_at" => now()->format('U')], (array) $jsonObj);

// Store the JSON to be used by the tags and endpoints
Storage::put('weather-forecast.json', json_encode($jsonObj));

return true;

}


private function talkToOpenweathermap(): string
{
$endpoint = $this->config->get('api_url')
.'onecall?lat='.$this->config->get('lat')
.'&lon='.$this->config->get('lon')
.'&exclude=minutely,hourly,alerts'
.'&units='.$this->config->get('units', 'metric')
.'&appid='.$this->config->get('api_secret_key')
.'&lang='.$this->config->get('lang','en');


$headers = [
'Content-Type:application/json',
];
$ch = curl_init($endpoint);


curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

$result = curl_exec($ch);
curl_close($ch);

return $result;
}

}
45 changes: 4 additions & 41 deletions src/Commands/FetchForecast.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Storage;
use Illuminate\Console\Command;
use Vannut\StatamicWeather\Settings;
use Vannut\StatamicWeather\Actions\FetchAndStoreAction;

class FetchForecast extends Command
{
Expand All @@ -21,49 +22,11 @@ public function __construct()

public function handle()
{
$this->config = (new Settings)->get();
$content = $this->fetch();
$settings = (new Settings)->get();

// Do nothing when we don't get anything back
if ($content === false) {
return;
}

// Decode the json object, drop out when not a valid object
$jsonObj = json_decode($content);
if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
return;
}

// Store the JSON to be used by the tags and endpoints
Storage::put('weather-forecast.json', json_encode($jsonObj));
$success = (new FetchAndStoreAction($settings))->execute();

}

public function fetch()
{
$endpoint = $this->config->get('api_url')
.'onecall?lat='.$this->config->get('lat')
.'&lon='.$this->config->get('lon')
.'&exclude=minutely,hourly,alerts'
.'&units='.$this->config->get('units', 'metric')
.'&appid='.$this->config->get('api_secret_key')
.'&lang='.$this->config->get('lang','en');


$headers = [
'Content-Type:application/json',
];
$ch = curl_init($endpoint);


curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

$result = curl_exec($ch);
curl_close($ch);

return $result;

}

}
41 changes: 38 additions & 3 deletions src/Controllers/ControlPanelController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@

namespace Vannut\StatamicWeather\Controllers;

use Statamic\Http\Controllers\CP\CpController;
use Statamic\Facades\Blueprint;
use Storage;
use Illuminate\Http\Request;
use Statamic\Facades\CP\Toast;
use Statamic\Facades\Blueprint;
use Vannut\StatamicWeather\Settings;
use Illuminate\Support\Facades\Artisan;
use Statamic\Http\Controllers\CP\CpController;
use Vannut\StatamicWeather\Actions\FetchAndStoreAction;

class ControlPanelController extends CpController
{
Expand All @@ -15,6 +19,25 @@ public function __construct()
{
$this->settings = new Settings;
}

public function currentData()
{

if (Storage::exists('weather-forecast.json')) {

$json = json_encode(
json_decode(Storage::get('weather-forecast.json')),
JSON_PRETTY_PRINT
);
} else {
$json = false;
}

return view('weather::current_data', [
'json' => $json
]);
}

public function index()
{

Expand Down Expand Up @@ -59,7 +82,19 @@ public function update(Request $request)
}



public function fetchWeather()
{

$success = (new FetchAndStoreAction($this->settings->get()))->execute();

if ($success) {
Toast::success('Data updated');
} else {
Toast::error('Something went wrong');
}
return redirect()->back();

}



Expand Down
12 changes: 8 additions & 4 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,15 @@ protected function navigation()
{
Nav::extend(function ($nav) {
$nav->content('Weather')
->route('weather.settings')
// ->route('')
->icon('<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-cloud-sun" viewBox="0 0 16 16">
<path d="M7 8a3.5 3.5 0 0 1 3.5 3.555.5.5 0 0 0 .624.492A1.503 1.503 0 0 1 13 13.5a1.5 1.5 0 0 1-1.5 1.5H3a2 2 0 1 1 .1-3.998.5.5 0 0 0 .51-.375A3.502 3.502 0 0 1 7 8zm4.473 3a4.5 4.5 0 0 0-8.72-.99A3 3 0 0 0 3 16h8.5a2.5 2.5 0 0 0 0-5h-.027z"/>
<path d="M10.5 1.5a.5.5 0 0 0-1 0v1a.5.5 0 0 0 1 0v-1zm3.743 1.964a.5.5 0 1 0-.707-.707l-.708.707a.5.5 0 0 0 .708.708l.707-.708zm-7.779-.707a.5.5 0 0 0-.707.707l.707.708a.5.5 0 1 0 .708-.708l-.708-.707zm1.734 3.374a2 2 0 1 1 3.296 2.198c.199.281.372.582.516.898a3 3 0 1 0-4.84-3.225c.352.011.696.055 1.028.129zm4.484 4.074c.6.215 1.125.59 1.522 1.072a.5.5 0 0 0 .039-.742l-.707-.707a.5.5 0 0 0-.854.377zM14.5 6.5a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1h-1z"/>
</svg>');
<path d="M7 8a3.5 3.5 0 0 1 3.5 3.555.5.5 0 0 0 .624.492A1.503 1.503 0 0 1 13 13.5a1.5 1.5 0 0 1-1.5 1.5H3a2 2 0 1 1 .1-3.998.5.5 0 0 0 .51-.375A3.502 3.502 0 0 1 7 8zm4.473 3a4.5 4.5 0 0 0-8.72-.99A3 3 0 0 0 3 16h8.5a2.5 2.5 0 0 0 0-5h-.027z"/>
<path d="M10.5 1.5a.5.5 0 0 0-1 0v1a.5.5 0 0 0 1 0v-1zm3.743 1.964a.5.5 0 1 0-.707-.707l-.708.707a.5.5 0 0 0 .708.708l.707-.708zm-7.779-.707a.5.5 0 0 0-.707.707l.707.708a.5.5 0 1 0 .708-.708l-.708-.707zm1.734 3.374a2 2 0 1 1 3.296 2.198c.199.281.372.582.516.898a3 3 0 1 0-4.84-3.225c.352.011.696.055 1.028.129zm4.484 4.074c.6.215 1.125.59 1.522 1.072a.5.5 0 0 0 .039-.742l-.707-.707a.5.5 0 0 0-.854.377zM14.5 6.5a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1h-1z"/>
</svg>')
->children([
'Settings' => cp_route('weather.settings'),
'Current Data' => cp_route('weather.data'),
]);
});
}
}
2 changes: 2 additions & 0 deletions src/Tags/CurrentWeather.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public function index(): Collection
$current['uvi_color'] = $this->UVIndexToColor($current['uvi']);
$current['uvi_percentage'] = $this->UVIndexToPercentage($current['uvi']);

$current['fetched_at'] = $json['fetched_at'];

return $current;
}
}
7 changes: 5 additions & 2 deletions src/Tags/Forecast.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Forecast extends \Statamic\Tags\Tags
use \Vannut\StatamicWeather\ConversionTrait;

// {{ forecast locale="nl" }} {{ /forecast }}
public function index(): Collection
public function index(): array
{
$locale = strtolower($this->params->get('locale'));
$config = (new Settings)->get();
Expand All @@ -34,7 +34,10 @@ public function index(): Collection
return $item;
});

return $daily;
return [
'fetched_at' => $json['fetched_at'],
'days' => $daily
];
}


Expand Down

0 comments on commit 722a0ef

Please sign in to comment.