diff options
Diffstat (limited to 'src/detection/weather')
| -rw-r--r-- | src/detection/weather/weather.c | 62 | ||||
| -rw-r--r-- | src/detection/weather/weather.h | 7 |
2 files changed, 69 insertions, 0 deletions
diff --git a/src/detection/weather/weather.c b/src/detection/weather/weather.c new file mode 100644 index 0000000..69df642 --- /dev/null +++ b/src/detection/weather/weather.c @@ -0,0 +1,62 @@ +#include "weather.h" +#include "common/networking.h" + +#define FF_UNITIALIZED ((const char*) (uintptr_t) -1) +static FFNetworkingState state; +static const char* status = FF_UNITIALIZED; + +void ffPrepareWeather(FFWeatherOptions* options) { + if (status != FF_UNITIALIZED) { + fputs("Error: Weather module can only be used once due to internal limitations\n", stderr); + exit(1); + } + + state.timeout = options->timeout; + + FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/"); + if (options->location.length) { + ffStrbufAppend(&path, &options->location); + } + ffStrbufAppendS(&path, "?format="); + ffStrbufAppend(&path, &options->outputFormat); + switch (instance.config.display.tempUnit) { + case FF_TEMPERATURE_UNIT_CELSIUS: + ffStrbufAppendS(&path, "&m"); + break; + case FF_TEMPERATURE_UNIT_FAHRENHEIT: + ffStrbufAppendS(&path, "&u"); + break; + default: + break; + } + status = ffNetworkingSendHttpRequest(&state, "wttr.in", path.chars, "User-Agent: curl/0.0.0\r\n"); +} + +const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result) { + if (status == FF_UNITIALIZED) { + ffPrepareWeather(options); + } + + if (status != NULL) { + return status; + } + + ffStrbufEnsureFree(result, 4095); + const char* error = ffNetworkingRecvHttpResponse(&state, result); + + state = (FFNetworkingState) {}; + status = FF_UNITIALIZED; + + if (error == NULL) { + ffStrbufSubstrAfterFirstS(result, "\r\n\r\n"); + ffStrbufTrimRightSpace(result); + } else { + return error; + } + + if (result->length == 0) { + return "Empty server response received"; + } + + return NULL; +} diff --git a/src/detection/weather/weather.h b/src/detection/weather/weather.h new file mode 100644 index 0000000..bd3d1bc --- /dev/null +++ b/src/detection/weather/weather.h @@ -0,0 +1,7 @@ +#pragma once + +#include "fastfetch.h" +#include "modules/weather/option.h" + +void ffPrepareWeather(FFWeatherOptions* options); +const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result); |