diff --git a/legacy/Dockerfile b/legacy/Dockerfile
deleted file mode 100644
index d981c25..0000000
--- a/legacy/Dockerfile
+++ /dev/null
@@ -1,70 +0,0 @@
-# Build stage
-FROM golang:1-alpine as builder
-
-WORKDIR /app
-
-COPY ./share/we-lang/we-lang.go /app
-
-RUN apk add --no-cache git
-
-
-RUN go get -u github.com/mattn/go-colorable && \
- go get -u github.com/klauspost/lctime && \
- go get -u github.com/mattn/go-runewidth && \
- CGO_ENABLED=0 go build /app/we-lang.go
-# Results in /app/we-lang
-
-
-FROM alpine:3
-
-WORKDIR /app
-
-COPY ./requirements.txt /app
-
-ENV LLVM_CONFIG=/usr/bin/llvm9-config
-
-RUN apk add --no-cache --virtual .build \
- autoconf \
- automake \
- g++ \
- gcc \
- jpeg-dev \
- llvm9-dev\
- make \
- zlib-dev \
- && apk add --no-cache \
- python3 \
- py3-pip \
- py3-scipy \
- py3-wheel \
- py3-gevent \
- zlib \
- jpeg \
- llvm9 \
- libtool \
- supervisor \
- py3-numpy-dev \
- python3-dev && \
- mkdir -p /app/cache && \
- mkdir -p /var/log/supervisor && \
- mkdir -p /etc/supervisor/conf.d && \
- chmod -R o+rw /var/log/supervisor && \
- chmod -R o+rw /var/run && \
- pip install -r requirements.txt && \
- apk del --no-cache -r .build
-
-COPY --from=builder /app/we-lang /app/bin/we-lang
-COPY ./bin /app/bin
-COPY ./lib /app/lib
-COPY ./share /app/share
-COPY share/docker/supervisord.conf /etc/supervisor/supervisord.conf
-
-ENV WTTR_MYDIR="/app"
-ENV WTTR_GEOLITE="/app/GeoLite2-City.mmdb"
-ENV WTTR_WEGO="/app/bin/we-lang"
-ENV WTTR_LISTEN_HOST="0.0.0.0"
-ENV WTTR_LISTEN_PORT="8002"
-
-EXPOSE 8002
-
-CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
diff --git a/legacy/LICENSE b/legacy/LICENSE
deleted file mode 100644
index 8f71f43..0000000
--- a/legacy/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
diff --git a/legacy/README.md b/legacy/README.md
deleted file mode 100644
index 5990f04..0000000
--- a/legacy/README.md
+++ /dev/null
@@ -1,612 +0,0 @@
-*wttr.in — the right way to check the weather!*
-
-wttr.in is a console-oriented weather forecast service that supports various information
-representation methods like terminal-oriented ANSI-sequences for console HTTP clients
-(curl, httpie, or wget), HTML for web browsers, or PNG for graphical viewers.
-
-wttr.in uses [wego](http://github.com/schachmat/wego) for visualization
-and various data sources for weather forecast information.
-
-You can see it running here: [wttr.in](http://wttr.in).
-
-## Usage
-
-You can access the service from a shell or from a Web browser like this:
-
- $ curl wttr.in
- Weather for City: Paris, France
-
- \ / Clear
- .-. 10 – 11 °C
- ― ( ) ― ↑ 11 km/h
- `-’ 10 km
- / \ 0.0 mm
-
-
-Here is an actual weather report for your location (it's live!):
-
-
-
-(It's not your actual location - GitHub's CDN hides your real IP address with its own IP address,
-but it's still a live weather report in your language.)
-
-Or in PowerShell:
-
-```PowerShell
-Invoke-RestMethod http://wttr.in
-```
-
-Want to get the weather information for a specific location? You can add the desired location to the URL in your
-request like this:
-
- $ curl wttr.in/London
- $ curl wttr.in/Moscow
- $ curl wttr.in/Salt+Lake+City
-
-If you omit the location name, you will get the report for your current location based on your IP address.
-
-Use 3-letter airport codes in order to get the weather information at a certain airport:
-
- $ curl wttr.in/muc # Weather for IATA: muc, Munich International Airport, Germany
- $ curl wttr.in/ham # Weather for IATA: ham, Hamburg Airport, Germany
-
-Let's say you'd like to get the weather for a geographical location other than a town or city - maybe an attraction
-in a city, a mountain name, or some special location. Add the character `~` before the name to look up that special
-location name before the weather is then retrieved:
-
- $ curl wttr.in/~Vostok+Station
- $ curl wttr.in/~Eiffel+Tower
- $ curl wttr.in/~Kilimanjaro
-
-For these examples, you'll see a line below the weather forecast output that shows the geolocation
-results of looking up the location:
-
- Location: Vostok Station, станция Восток, AAT, Antarctica [-78.4642714,106.8364678]
- Location: Tour Eiffel, 5, Avenue Anatole France, Gros-Caillou, 7e, Paris, Île-de-France, 75007, France [48.8582602,2.29449905432]
- Location: Kilimanjaro, Northern, Tanzania [-3.4762789,37.3872648]
-
-You can also use IP-addresses (direct) or domain names (prefixed with `@`) to specify a location:
-
- $ curl wttr.in/@github.com
- $ curl wttr.in/@msu.ru
-
-To get detailed information online, you can access the [/:help](http://wttr.in/:help) page:
-
- $ curl wttr.in/:help
-
-
-### Weather Units
-
-By default the USCS units are used for the queries from the USA and the metric system for the rest of the world.
-You can override this behavior by adding `?u` or `?m` to a URL like this:
-
- $ curl wttr.in/Amsterdam?u
- $ curl wttr.in/Amsterdam?m
-
-## Supported output formats and views
-
-wttr.in currently supports five output formats:
-
-* ANSI for the terminal;
-* Plain-text for the terminal and scripts;
-* HTML for the browser;
-* PNG for the graphical viewers;
-* JSON for scripts and APIs;
-* Prometheus metrics for scripts and APIs.
-
-The ANSI and HTML formats are selected basing on the User-Agent string.
-The PNG format can be forced by adding `.png` to the end of the query:
-
- $ wget wttr.in/Paris.png
-
-You can use all of the options with the PNG-format like in an URL, but you have
-to separate them with `_` instead of `?` and `&`:
-
- $ wget wttr.in/Paris_0tqp_lang=fr.png
-
-Useful options for the PNG format:
-
-* `t` for transparency (`transparency=150`);
-* transparency=0..255 for a custom transparency level.
-
-Transparency is a useful feature when weather PNGs are used to add weather data to pictures:
-
- $ convert source.jpg <( curl wttr.in/Oymyakon_tqp0.png ) -geometry +50+50 -composite target.jpg
-
-In this example:
-
-* `source.jpg` - source file;
-* `target.jpg` - target file;
-* `Oymyakon` - name of the location;
-* `tqp0` - options (recommended).
-
-
-
-You can embed a special wttr.in widget, that displays the weather condition for the current or a selected location, into a HTML page using the [wttr-switcher](https://github.com/midzer/wttr-switcher). That is how it looks like: [wttr-switcher-example](https://midzer.github.io/wttr-switcher/) or on a real world web site: https://feuerwehr-eisolzried.de/.
-
-
-
-## One-line output
-
-For one-line output format, specify additional URL parameter `format`:
-
-```
-$ curl wttr.in/Nuremberg?format=3
-Nuremberg: 🌦 +11⁰C
-```
-
-Available preconfigured formats: 1, 2, 3, 4 and the custom format using the percent notation (see below).
-
-You can specify multiple locations separated with `:` (for repeating queries):
-
-```
-$ curl wttr.in/Nuremberg:Hamburg:Berlin?format=3
-Nuremberg: 🌦 +11⁰C
-```
-Or to process all this queries at once:
-
-```
-$ curl -s 'wttr.in/{Nuremberg,Hamburg,Berlin}?format=3'
-Nuremberg: 🌦 +11⁰C
-Hamburg: 🌦 +8⁰C
-Berlin: 🌦 +8⁰C
-```
-
-To specify your own custom output format, use the special `%`-notation:
-
-```
- c Weather condition,
- C Weather condition textual name,
- h Humidity,
- t Temperature (Actual),
- f Temperature (Feels Like),
- w Wind,
- l Location,
- m Moonphase 🌑🌒🌓🌔🌕🌖🌗🌘,
- M Moonday,
- p precipitation (mm),
- o Probability of Precipitation,
- P pressure (hPa),
-
- D Dawn*,
- S Sunrise*,
- z Zenith*,
- s Sunset*,
- d Dusk*.
-
-(*times are shown in the local timezone)
-```
-
-So, these two calls are the same:
-
-```
- $ curl wttr.in/London?format=3
- London: ⛅️ +7⁰C
- $ curl wttr.in/London?format="%l:+%c+%t\n"
- London: ⛅️ +7⁰C
-```
-Keep in mind, that when using in `tmux.conf`, you have to escape `%` with `%`, i.e. write there `%%` instead of `%`.
-
-In programs, that are querying the service automatically (such as tmux), it is better to use some reasonable update interval. In tmux, you can configure it with `status-interval`.
-
-If several, `:` separated locations, are specified in the query, specify update period
-as an additional query parameter `period=`:
-```
-set -g status-interval 60
-WEATHER='#(curl -s wttr.in/London:Stockholm:Moscow\?format\="%%l:+%%c%%20%%t%%60%%w&period=60")'
-set -g status-right "$WEATHER ..."
-```
-
-
-To see emojis in terminal, you need:
-
-1. Terminal support for emojis (was added to Cairo 1.15.8);
-2. Font with emojis support.
-
-For the Emoji font, we recommend *Noto Color Emoji*, and a good alternative option would be the *Emoji One* font;
-both of them support all necessary emoji glyphs.
-
-Font configuration:
-
-```xml
-$ cat ~/.config/fontconfig/fonts.conf
-
-
-
-
- serif
-
- Noto Color Emoji
-
-
-
- sans-serif
-
- Noto Color Emoji
-
-
-
- monospace
-
- Noto Color Emoji
-
-
-
-```
-
-(to apply the configuration, run `fc-cache -f -v`)
-
-## Data-rich output format
-
-In the experimental data-rich output format, that is available under the view code `v2`,
-a lot of additional weather and astronomical information is available:
-
-* Temperature, and precepetation changes forecast throughout the days;
-* Moonphase for today and the next three days;
-* The current weather condition, temperature, humidity, windspeed and direction, pressure;
-* Timezone;
-* Dawn, sunrise, noon, sunset, dusk time for he selected location;
-* Precise geographical coordinates for the selected location.
-
-```
- $ curl v2.wttr.in/München
-```
-
-or
-
-```
- $ curl wttr.in/München?format=v2
-```
-
-or, if you prefer Nerd Fonts instead of Emoji, `v2d` (day) or `v2n` (night):
-
-```
- $ curl v2d.wttr.in/München
-```
-
-
-
-
-(The mode is experimental, and it has several limitations currently:
-
-* It works only in terminal;
-* Only English is supported).
-
-Currently, you need some tweaks for some terminals, to get the best possible visualization.
-
-### URXVT
-
-Depending on your configuration you might be taking all steps, or only a few. URXVT currently doesn't support emoji related fonts, but we can get almost the same effect using *Font-Symbola*. So add to your `.Xresources` file the following line:
-```
- xft:symbola:size=10:minspace=False
-```
-You can add it _after_ your preferred font and it will only show up when required.
-Then, if you see or feel like you're having spacing issues, add this: `URxvt.letterSpace: 0`
-For some reason URXVT sometimes stops deciding right the word spacing and we need to force it this way.
-
-The result, should look like:
-
-
-
-## Different output formats
-
-### JSON output
-
-The JSON format is a feature providing access to *wttr.in* data through an easy-to-parse format, without requiring the user to create a complex script to reinterpret wttr.in's graphical output.
-
-To fetch information in JSON format, use the following syntax:
-
- $ curl wttr.in/Detroit?format=j1
-
-This will fetch information on the Detroit region in JSON format. The j1 format code is used to allow for the use of other layouts for the JSON output.
-
-The result will look something like the following:
-```json
-{
- "current_condition": [
- {
- "FeelsLikeC": "25",
- "FeelsLikeF": "76",
- "cloudcover": "100",
- "humidity": "76",
- "observation_time": "04:08 PM",
- "precipMM": "0.2",
- "pressure": "1019",
- "temp_C": "22",
- "temp_F": "72",
- "uvIndex": 5,
- "visibility": "16",
- "weatherCode": "122",
- "weatherDesc": [
- {
- "value": "Overcast"
- }
- ],
- "weatherIconUrl": [
- {
- "value": ""
- }
- ],
- "winddir16Point": "NNE",
- "winddirDegree": "20",
- "windspeedKmph": "7",
- "windspeedMiles": "4"
- }
- ],
-...
-```
-
-Most of these values are self-explanatory, aside from `weatherCode`. The `weatherCode` is an enumeration which you can find at either [the WorldWeatherOnline website](https://www.worldweatheronline.com/developer/api/docs/weather-icons.aspx) or [in the wttr.in source code](https://github.com/chubin/wttr.in/blob/master/lib/constants.py).
-
-### Prometheus Metrics Output
-
-The [Prometheus](https://github.com/prometheus/prometheus) Metrics format is a feature providing access to *wttr.in* data through an easy-to-parse format for monitoring systems, without requiring the user to create a complex script to reinterpret wttr.in's graphical output.
-
-To fetch information in Prometheus format, use the following syntax:
-
- $ curl wttr.in/Detroit?format=p1
-
-This will fetch information on the Detroit region in Prometheus Metrics format. The `p1` format code is used to allow for the use of other layouts for the Prometheus Metrics output.
-
-A possible configuration for Prometheus could look like this:
-
-```yaml
- - job_name: 'wttr_in_detroit'
- static_configs:
- - targets: ['wttr.in']
- metrics_path: '/Detroit'
- params:
- format: ['p1']
-```
-
-The result will look something like the following:
-
-
- # HELP temperature_feels_like_celsius Feels Like Temperature in Celsius
- temperature_feels_like_celsius{forecast="current"} 7
- # HELP temperature_feels_like_fahrenheit Feels Like Temperature in Fahrenheit
- temperature_feels_like_fahrenheit{forecast="current"} 45
- [truncated]
-...
-
-
-## Moon phases
-
-wttr.in can also be used to check the phase of the Moon. This example shows how to see the current Moon phase
-in the full-output mode:
-
- $ curl wttr.in/Moon
-
-Get the Moon phase for a particular date by adding `@YYYY-MM-DD`:
-
- $ curl wttr.in/Moon@2016-12-25
-
-The Moon phase information uses [pyphoon](https://github.com/chubin/pyphoon) as its backend.
-
-To get the moon phase information in the online mode, use `%m`:
-
- $ curl wttr.in/London?format=%m
- 🌖
-
-Keep in mind that the Unicode representation of moonphases suffers 2 caveats:
-
-- With some fonts, the representation `🌘` is ambiguous, for it either seem
- almost-shadowed or almost-lit, depending on whether your terminal is in
- light mode or dark mode. Relying on colored fonts like `noto-fonts` works
- around this problem.
-
-- The representation `🌘` is also ambiguous, for it means "last quarter" in
- northern hemisphere, but "first quarter" in souther hemisphere. It also means
- nothing in tropical zones. This is a limitation that
- [Unicode](https://www.unicode.org/L2/L2017/17304-moon-var.pdf) is aware about.
- But it has not been worked around at `wttr.in` yet.
-
-See #247, #364 for the corresponding tracking issues,
-and [pyphoon#1](https://github.com/chubin/pyphoon/issues/1) for pyphoon. Any help is welcome.
-
-## Internationalization and localization
-
-wttr.in supports multilingual locations names that can be specified in any language in the world
-(it may be surprising, but many locations in the world don't have an English name).
-
-The query string should be specified in Unicode (hex-encoded or not). Spaces in the query string
-must be replaced with `+`:
-
- $ curl wttr.in/станция+Восток
- Weather report: станция Восток
-
- Overcast
- .--. -65 – -47 °C
- .-( ). ↑ 23 km/h
- (___.__)__) 15 km
- 0.0 mm
-
-The language used for the output (except the location name) does not depend on the input language
-and it is either English (by default) or the preferred language of the browser (if the query
-was issued from a browser) that is specified in the query headers (`Accept-Language`).
-
-The language can be set explicitly when using console clients by using command-line options like this:
-
- curl -H "Accept-Language: fr" wttr.in
- http GET wttr.in Accept-Language:ru
-
-The preferred language can be forced using the `lang` option:
-
- $ curl wttr.in/Berlin?lang=de
-
-The third option is to choose the language using the DNS name used in the query:
-
- $ curl de.wttr.in/Berlin
-
-wttr.in is currently translated into 54 languages, and the number of supported languages is constantly growing.
-
-See [/:translation](http://wttr.in/:translation) to learn more about the translation process,
-to see the list of supported languages and contributors, or to know how you can help to translate wttr.in
-in your language.
-
-
-
-## Windows Users
-
-There are currently two Windows related issues that prevent the examples found on this page from working exactly as expected out of the box. Until Microsoft fixes the issues, there are a few workarounds. To circumvent both issues you may use a shell such as `bash` on the [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/install-win10) or read on for alternative solutions.
-
-### Garbage characters in the output
-There is a limitation of the current Win32 version of `curl`. Until the [Win32 curl issue](https://github.com/chubin/wttr.in/issues/18#issuecomment-474145551) is resolved and rolled out in a future Windows release, it is recommended that you use Powershell’s `Invoke-Web-Request` command instead:
-- `(Invoke-WebRequest http://wttr.in).Content`
-
-### Missing or double wide diagonal wind direction characters
-The second issue is regarding the width of the diagonal arrow glyphs that some Windows Terminal Applications such as the default `conhost.exe` use. At the time of writing this, `ConEmu.exe`, `ConEmu64.exe` and Terminal Applications built on top of ConEmu such as Cmder (`cmder.exe`) use these double-wide glyphs by default. The result is the same with all of these programs, either a missing character for certain wind directions or a broken table in the output or both. Some third-party Terminal Applications have addressed the wind direction glyph issue but that fix depends on the font and the Terminal Application you are using.
-One way to display the diagonal wind direction glyphs in your Terminal Application is to use [Windows Terminal](https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701?activetab=pivot:overviewtab) which is currently available in the [Microsoft Store](https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701?activetab=pivot:overviewtab). Windows Terminal is currently a preview release and will be rolled out as the default Terminal Application in an upcoming release. If your output is still skewed after using Windows Terminal then try maximizing the terminal window.
-Another way you can display the diagonal wind direction is to swap out the problematic characters with forward and backward slashes as shown [here](https://github.com/chubin/wttr.in/issues/18#issuecomment-405640892).
-
-## Installation
-
-To install the application:
-
-1. Install external dependencies
-2. Install Python dependencies used by the service
-3. Configure IP2Location (optional)
-4. Get a WorldWeatherOnline API and configure wego
-5. Configure wttr.in
-6. Configure the HTTP-frontend service
-
-### Install external dependencies
-
-wttr.in has the following external dependencies:
-
-* [golang](https://golang.org/doc/install), wego dependency
-* [wego](https://github.com/schachmat/wego), weather client for terminal
-
-After you install [golang](https://golang.org/doc/install), install `wego`:
-
- $ go get -u github.com/schachmat/wego
- $ go install github.com/schachmat/wego
-
-### Install Python dependencies
-
-Python requirements:
-
-* Flask
-* geoip2
-* geopy
-* requests
-* gevent
-
-If you want to get weather reports as PNG files, you'll also need to install:
-
-* PIL
-* pyte (>=0.6)
-* necessary fonts
-
-You can install most of them using `pip`.
-
-Some python package use LLVM, so install it first:
-
- $ apt-get install llvm-7 llvm-7-dev
-
-If `virtualenv` is used:
-
- $ virtualenv -p python3 ve
- $ ve/bin/pip3 install -r requirements.txt
- $ ve/bin/python3 bin/srv.py
-
-Also, you need to install the geoip2 database.
-You can use a free database GeoLite2 that can be downloaded from (http://dev.maxmind.com/geoip/geoip2/geolite2/).
-
-### Configure IP2Location (optional)
-
-If you want to use the IP2location service for IP-addresses that are not covered by GeoLite2,
-you have to obtain a API key of that service, and after that save into the `~/.ip2location.key` file:
-
-```
-$ echo 'YOUR_IP2LOCATION_KEY' > ~/.ip2location.key
-```
-
-If you don't have this file, the service will be silently skipped (it is not a big problem,
-because the MaxMind database is pretty good).
-
-### Installation with Docker
-
-* Install Docker
-* Build Docker Image
-* These files should be mounted by the user at runtime:
-
-```
-/root/.wegorc
-/root/.ip2location.key (optional)
-/app/airports.dat
-/app/GeoLite2-City.mmdb
-```
-
-### Get a WorldWeatherOnline key and configure wego
-
-To get a WorldWeatherOnline API key, you must register here:
-
- https://developer.worldweatheronline.com/auth/register
-
-After you have a WorldWeatherOnline key, you can save it into the
-WWO key file: `~/.wwo.key`
-
-Also, you have to specify the key in the `wego` configuration:
-
-```json
-$ cat ~/.wegorc
-{
- "APIKey": "00XXXXXXXXXXXXXXXXXXXXXXXXXXX",
- "City": "London",
- "Numdays": 3,
- "Imperial": false,
- "Lang": "en"
-}
-```
-
-The `City` parameter in `~/.wegorc` is ignored.
-
-### Configure wttr.in
-
-Configure the following environment variables that define the path to the local `wttr.in`
-installation, to the GeoLite database, and to the `wego` installation. For example:
-
-```bash
-export WTTR_MYDIR="/home/igor/wttr.in"
-export WTTR_GEOLITE="/home/igor/wttr.in/GeoLite2-City.mmdb"
-export WTTR_WEGO="/home/igor/go/bin/wego"
-export WTTR_LISTEN_HOST="0.0.0.0"
-export WTTR_LISTEN_PORT="8002"
-```
-
-
-### Configure the HTTP-frontend service
-
-It's recommended that you also configure the web server that will be used to access the service:
-
-```nginx
-server {
- listen [::]:80;
- server_name wttr.in *.wttr.in;
- access_log /var/log/nginx/wttr.in-access.log main;
- error_log /var/log/nginx/wttr.in-error.log;
-
- location / {
- proxy_pass http://127.0.0.1:8002;
-
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $remote_addr;
-
- client_max_body_size 10m;
- client_body_buffer_size 128k;
-
- proxy_connect_timeout 90;
- proxy_send_timeout 90;
- proxy_read_timeout 90;
-
- proxy_buffer_size 4k;
- proxy_buffers 4 32k;
- proxy_busy_buffers_size 64k;
- proxy_temp_file_write_size 64k;
-
- expires off;
- }
-}
-```
diff --git a/legacy/bin/geo-proxy.py b/legacy/bin/geo-proxy.py
deleted file mode 100644
index cfe2e9f..0000000
--- a/legacy/bin/geo-proxy.py
+++ /dev/null
@@ -1,114 +0,0 @@
-
-import gevent
-from gevent.pywsgi import WSGIServer
-from gevent.queue import Queue
-from gevent.monkey import patch_all
-from gevent.subprocess import Popen, PIPE, STDOUT
-patch_all()
-
-import sys
-import os
-import json
-
-from flask import Flask, request, render_template, send_from_directory, send_file, make_response, jsonify, Response
-app = Flask(__name__)
-
-MYDIR = os.path.abspath(os.path.dirname('__file__'))
-sys.path.append(os.path.join(MYDIR, 'lib'))
-
-CACHEDIR = os.path.join(MYDIR, 'cache')
-
-from geopy.geocoders import Nominatim #, Mapzen
-#geomapzen = Mapzen("mapzen-RBNbmcZ") # Nominatim()
-geoosm = Nominatim(timeout=7, user_agent="wttrin-geo/0.0.2")
-
-import airports
-
-# from tzwhere import tzwhere
-import timezonefinder
-tf = timezonefinder.TimezoneFinder()
-
-def load_cache(location_string):
- try:
- location_string = location_string.replace('/', '_')
- cachefile = os.path.join(CACHEDIR, location_string)
-
- return json.loads(open(cachefile, 'r').read())
- except:
- return None
-
-def shorten_full_address(address):
- parts = address.split(',')
- if len(parts) > 6:
- parts = parts[:2] + [x for x in parts[-4:] if len(x) < 20]
- return ','.join(parts)
- return address
-
-
-def save_cache(location_string, answer):
- location_string = location_string.replace('/', '_')
- cachefile = os.path.join(CACHEDIR, location_string)
- open(cachefile, 'w').write(json.dumps(answer))
-
-def query_osm(location_string):
- try:
- location = geoosm.geocode(location_string)
- return {
- 'address': location.address,
- 'latitude': location.latitude,
- 'longitude':location.longitude,
- }
-
- except Exception as e:
- print(e)
- return None
-
-def add_timezone_information(geo_data):
- # tzwhere_ = tzwhere.tzwhere()
- # timezone_str = tzwhere_.tzNameAt(geo_data["latitude"], geo_data["longitude"])
- timezone_str = tf.certain_timezone_at(lat=geo_data["latitude"], lng=geo_data["longitude"])
-
- answer = geo_data.copy()
- answer["timezone"] = timezone_str
-
- return answer
-
-@app.route("/")
-def find_location(location):
-
- airport_gps_location = airports.get_airport_gps_location(location.upper().lstrip('~'))
- is_airport = False
- if airport_gps_location is not None:
- location = airport_gps_location
- is_airport = True
-
- location = location.replace('+', ' ')
- answer = load_cache(location)
- loaded_answer = None
-
- if answer is not None:
- loaded_answer = answer.copy()
- print("cache found: %s" % location)
-
- if answer is None:
- answer = query_osm(location)
-
- if is_airport:
- answer['address'] = shorten_full_address(answer['address'])
-
- if "timezone" not in answer:
- answer = add_timezone_information(answer)
-
- if answer is not None and loaded_answer != answer:
- save_cache(location, answer)
-
- if answer is None:
- return ""
- else:
- r = Response(json.dumps(answer))
- r.headers["Content-Type"] = "text/json; charset=utf-8"
- return r
-
-app.config['JSON_AS_ASCII'] = False
-server = WSGIServer(("127.0.0.1", 8004), app)
-server.serve_forever()
diff --git a/legacy/bin/proxy.py b/legacy/bin/proxy.py
deleted file mode 100755
index 09c24c2..0000000
--- a/legacy/bin/proxy.py
+++ /dev/null
@@ -1,291 +0,0 @@
-#vim: fileencoding=utf-8
-
-"""
-
-The proxy server acts as a backend for the wttr.in service.
-
-It caches the answers and handles various data sources transforming their
-answers into format supported by the wttr.in service.
-
-If WTTRIN_TEST is specified, it works in a special test mode:
-it does not fetch and does not store the data in the cache,
-but is using the fake data from "test/proxy-data".
-
-"""
-from __future__ import print_function
-
-from gevent.pywsgi import WSGIServer
-from gevent.monkey import patch_all
-patch_all()
-
-# pylint: disable=wrong-import-position,wrong-import-order
-import sys
-import os
-import time
-import json
-import hashlib
-
-import requests
-import cyrtranslit
-
-from flask import Flask, request
-APP = Flask(__name__)
-
-
-MYDIR = os.path.abspath(
- os.path.dirname(os.path.dirname('__file__')))
-sys.path.append("%s/lib/" % MYDIR)
-
-from globals import PROXY_CACHEDIR, PROXY_HOST, PROXY_PORT, USE_METNO, USER_AGENT
-from metno import create_standard_json_from_metno, metno_request
-from translations import PROXY_LANGS
-# pylint: enable=wrong-import-position
-
-def is_testmode():
- """Server is running in the wttr.in test mode"""
-
- return "WTTRIN_TEST" in os.environ
-
-def load_translations():
- """
- load all translations
- """
- translations = {}
-
- for f_name in PROXY_LANGS:
- f_name = 'share/translations/%s.txt' % f_name
- translation = {}
- lang = f_name.split('/')[-1].split('.', 1)[0]
- with open(f_name, "r") as f_file:
- for line in f_file:
- if ':' not in line:
- continue
- if line.count(':') == 3:
- _, trans, orig, _ = line.strip().split(':', 4)
- else:
- _, trans, orig = line.strip().split(':', 3)
- trans = trans.strip()
- orig = orig.strip()
-
- translation[orig] = trans
- translations[lang] = translation
- return translations
-TRANSLATIONS = load_translations()
-
-def _is_metno():
- return USE_METNO
-
-def _find_srv_for_query(path, query): # pylint: disable=unused-argument
- if _is_metno():
- return 'https://api.met.no'
- return 'http://api.worldweatheronline.com'
-
-def _cache_file(path, query):
- """Return cache file name for specified `path` and `query`
- and for the current time.
-
- Do smooth load on the server, expiration time
- is slightly varied basing on the path+query sha1 hash digest.
- """
-
- digest = hashlib.sha1(("%s %s" % (path, query)).encode("utf-8")).hexdigest()
- digest_number = ord(digest[0].upper())
- expiry_interval = 60*(digest_number+40)
-
- timestamp = "%010d" % (int(time.time())//expiry_interval*expiry_interval)
- filename = os.path.join(PROXY_CACHEDIR, timestamp, path, query)
-
- return filename
-
-
-def _load_content_and_headers(path, query):
- if is_testmode():
- cache_file = "test/proxy-data/data1"
- else:
- cache_file = _cache_file(path, query)
- try:
- return (open(cache_file, 'r').read(),
- json.loads(open(cache_file+".headers", 'r').read()))
- except IOError:
- return None, None
-
-def _touch_empty_file(path, query):
- cache_file = _cache_file(path, query)
- cache_dir = os.path.dirname(cache_file)
- if not os.path.exists(cache_dir):
- os.makedirs(cache_dir)
- open(cache_file, 'w').write("")
-
-def _save_content_and_headers(path, query, content, headers):
- cache_file = _cache_file(path, query)
- cache_dir = os.path.dirname(cache_file)
- if not os.path.exists(cache_dir):
- os.makedirs(cache_dir)
- open(cache_file + ".headers", 'w').write(json.dumps(headers))
- open(cache_file, 'wb').write(content)
-
-def translate(text, lang):
- """
- Translate `text` into `lang`
- """
- translated = TRANSLATIONS.get(lang, {}).get(text, text)
- if text == translated:
- print("%s: %s" % (lang, text))
- return translated
-
-def cyr(to_translate):
- """
- Transliterate `to_translate` from latin into cyrillic
- """
- return cyrtranslit.to_cyrillic(to_translate)
-
-def _patch_greek(original):
- return original.replace(u"Ηλιόλουστη/ο", u"Ηλιόλουστη")
-
-def add_translations(content, lang):
- """
- Add `lang` translation to `content` (JSON)
- returned by the data source
- """
-
- if content == "{}":
- return {}
-
- languages_to_translate = TRANSLATIONS.keys()
- try:
- d = json.loads(content) # pylint: disable=invalid-name
- except (ValueError, TypeError) as exception:
- print("---")
- print(exception)
- print("---")
- return {}
-
- try:
- weather_condition = d['data']['current_condition'
- ][0]['weatherDesc'][0]['value'].capitalize()
- d['data']['current_condition'][0]['weatherDesc'][0]['value'] = \
- weather_condition
- if lang in languages_to_translate:
- d['data']['current_condition'][0]['lang_%s' % lang] = \
- [{'value': translate(weather_condition, lang)}]
- elif lang == 'sr':
- d['data']['current_condition'][0]['lang_%s' % lang] = \
- [{'value': cyr(
- d['data']['current_condition'][0]['lang_%s' % lang][0]['value']\
- )}]
- elif lang == 'el':
- d['data']['current_condition'][0]['lang_%s' % lang] = \
- [{'value': _patch_greek(
- d['data']['current_condition'][0]['lang_%s' % lang][0]['value']\
- )}]
- elif lang == 'sr-lat':
- d['data']['current_condition'][0]['lang_%s' % lang] = \
- [{'value':d['data']['current_condition'][0]['lang_sr'][0]['value']\
- }]
-
- fixed_weather = []
- for w in d['data']['weather']: # pylint: disable=invalid-name
- fixed_hourly = []
- for h in w['hourly']: # pylint: disable=invalid-name
- weather_condition = h['weatherDesc'][0]['value']
- if lang in languages_to_translate:
- h['lang_%s' % lang] = \
- [{'value': translate(weather_condition, lang)}]
- elif lang == 'sr':
- h['lang_%s' % lang] = \
- [{'value': cyr(h['lang_%s' % lang][0]['value'])}]
- elif lang == 'el':
- h['lang_%s' % lang] = \
- [{'value': _patch_greek(h['lang_%s' % lang][0]['value'])}]
- elif lang == 'sr-lat':
- h['lang_%s' % lang] = \
- [{'value': h['lang_sr'][0]['value']}]
- fixed_hourly.append(h)
- w['hourly'] = fixed_hourly
- fixed_weather.append(w)
- d['data']['weather'] = fixed_weather
-
- content = json.dumps(d)
- except (IndexError, ValueError) as exception:
- print(exception)
- return content
-
-def _fetch_content_and_headers(path, query_string, **kwargs):
- content, headers = _load_content_and_headers(path, query_string)
-
- if content is None:
- srv = _find_srv_for_query(path, query_string)
- url = '%s/%s?%s' % (srv, path, query_string)
-
- attempts = 10
- response = None
- while attempts:
- try:
- response = requests.get(url, timeout=2, **kwargs)
- except requests.ReadTimeout:
- attempts -= 1
- continue
- try:
- json.loads(response.content)
- break
- except ValueError:
- attempts -= 1
-
- _touch_empty_file(path, query_string)
- if response:
- headers = {}
- headers['Content-Type'] = response.headers['content-type']
- _save_content_and_headers(path, query_string, response.content, headers)
- content = response.content
- else:
- content = "{}"
- else:
- print("cache found")
- return content, headers
-
-
-@APP.route("/")
-def proxy(path):
- """
- Main proxy function. Handles incoming HTTP queries.
- """
-
- lang = request.args.get('lang', 'en')
- query_string = request.query_string.decode("utf-8")
- query_string = query_string.replace('sr-lat', 'sr')
- query_string = query_string.replace('lang=None', 'lang=en')
- content = ""
- headers = ""
- if _is_metno():
- path, query, days = metno_request(path, query_string)
- if USER_AGENT == '':
- raise ValueError('User agent must be set to adhere to metno ToS: https://api.met.no/doc/TermsOfService')
- content, headers = _fetch_content_and_headers(path, query, headers={
- 'User-Agent': USER_AGENT
- })
- content = create_standard_json_from_metno(content, days)
- else:
- # WWO tweaks
- query_string += "&extra=localObsTime"
- query_string += "&includelocation=yes"
- content, headers = _fetch_content_and_headers(path, query)
-
- content = add_translations(content, lang)
-
- return content, 200, headers
-
-if __name__ == "__main__":
- #app.run(host='0.0.0.0', port=5001, debug=False)
- #app.debug = True
- if len(sys.argv) == 1:
- bind_addr = "0.0.0.0"
- SERVER = WSGIServer((bind_addr, PROXY_PORT), APP)
- SERVER.serve_forever()
- else:
- print('running single request from command line arg')
- APP.testing = True
- with APP.test_client() as c:
- resp = c.get(sys.argv[1])
- print('Status: ' + resp.status)
- # print('Headers: ' + dumps(resp.headers))
- print(resp.data.decode('utf-8'))
diff --git a/legacy/bin/srv.py b/legacy/bin/srv.py
deleted file mode 100644
index 8d4f447..0000000
--- a/legacy/bin/srv.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python
-# vim: set encoding=utf-8
-
-from gevent.pywsgi import WSGIServer
-from gevent.monkey import patch_all
-patch_all()
-
-# pylint: disable=wrong-import-position,wrong-import-order
-import sys
-import os
-import jinja2
-
-from flask import Flask, request, send_from_directory
-APP = Flask(__name__)
-
-MYDIR = os.path.abspath(
- os.path.dirname(os.path.dirname('__file__')))
-sys.path.append("%s/lib/" % MYDIR)
-
-import wttr_srv
-from globals import TEMPLATES, STATIC, LISTEN_HOST, LISTEN_PORT
-# pylint: enable=wrong-import-position,wrong-import-order
-
-
-MY_LOADER = jinja2.ChoiceLoader([
- APP.jinja_loader,
- jinja2.FileSystemLoader(TEMPLATES),
-])
-
-APP.jinja_loader = MY_LOADER
-
-@APP.route('/files/')
-def send_static(path):
- "Send any static file located in /files/"
- return send_from_directory(STATIC, path)
-
-@APP.route('/favicon.ico')
-def send_favicon():
- "Send static file favicon.ico"
- return send_from_directory(STATIC, 'favicon.ico')
-
-@APP.route('/malformed-response.html')
-def send_malformed():
- "Send static file malformed-response.html"
- return send_from_directory(STATIC, 'malformed-response.html')
-
-@APP.route("/")
-@APP.route("/")
-def wttr(location=None):
- "Main function wrapper"
- return wttr_srv.wttr(location, request)
-
-SERVER = WSGIServer(
- (LISTEN_HOST, int(os.environ.get('WTTRIN_SRV_PORT', LISTEN_PORT))),
- APP)
-SERVER.serve_forever()
diff --git a/legacy/cmd/peakHandling.go b/legacy/cmd/peakHandling.go
deleted file mode 100644
index eb98191..0000000
--- a/legacy/cmd/peakHandling.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package main
-
-import (
- "log"
- "net/http"
- "sync"
- "time"
-
- "github.com/robfig/cron"
-)
-
-var peakRequest30 sync.Map
-var peakRequest60 sync.Map
-
-func initPeakHandling() {
- c := cron.New()
- // cronTime := fmt.Sprintf("%d,%d * * * *", 30-prefetchInterval/60, 60-prefetchInterval/60)
- c.AddFunc("24 * * * *", prefetchPeakRequests30)
- c.AddFunc("54 * * * *", prefetchPeakRequests60)
- c.Start()
-}
-
-func savePeakRequest(cacheDigest string, r *http.Request) {
- _, min, _ := time.Now().Clock()
- if min == 30 {
- peakRequest30.Store(cacheDigest, *r)
- } else if min == 0 {
- peakRequest60.Store(cacheDigest, *r)
- }
-}
-
-func prefetchRequest(r *http.Request) {
- processRequest(r)
-}
-
-func syncMapLen(sm *sync.Map) int {
- count := 0
-
- f := func(key, value interface{}) bool {
-
- // Not really certain about this part, don't know for sure
- // if this is a good check for an entry's existence
- if key == "" {
- return false
- }
- count++
-
- return true
- }
-
- sm.Range(f)
-
- return count
-}
-
-func prefetchPeakRequests(peakRequestMap *sync.Map) {
- peakRequestLen := syncMapLen(peakRequestMap)
- log.Printf("PREFETCH: Prefetching %d requests\n", peakRequestLen)
- if peakRequestLen == 0 {
- return
- }
- sleepBetweenRequests := time.Duration(prefetchInterval*1000/peakRequestLen) * time.Millisecond
- peakRequestMap.Range(func(key interface{}, value interface{}) bool {
- go func(r http.Request) {
- prefetchRequest(&r)
- }(value.(http.Request))
- peakRequestMap.Delete(key)
- time.Sleep(sleepBetweenRequests)
- return true
- })
-}
-
-func prefetchPeakRequests30() {
- prefetchPeakRequests(&peakRequest30)
-}
-
-func prefetchPeakRequests60() {
- prefetchPeakRequests(&peakRequest60)
-}
diff --git a/legacy/cmd/processRequest.go b/legacy/cmd/processRequest.go
deleted file mode 100644
index 7c44a9f..0000000
--- a/legacy/cmd/processRequest.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package main
-
-import (
- "fmt"
- "io/ioutil"
- "log"
- "math/rand"
- "net"
- "net/http"
- "strings"
- "time"
-)
-
-func processRequest(r *http.Request) responseWithHeader {
- var response responseWithHeader
-
- if dontCache(r) {
- return get(r)
- }
-
- cacheDigest := getCacheDigest(r)
-
- foundInCache := false
-
- savePeakRequest(cacheDigest, r)
-
- cacheBody, ok := lruCache.Get(cacheDigest)
- if ok {
- cacheEntry := cacheBody.(responseWithHeader)
-
- // if after all attempts we still have no answer,
- // we try to make the query on our own
- for attempts := 0; attempts < 300; attempts++ {
- if !ok || !cacheEntry.InProgress {
- break
- }
- time.Sleep(30 * time.Millisecond)
- cacheBody, ok = lruCache.Get(cacheDigest)
- cacheEntry = cacheBody.(responseWithHeader)
- }
- if cacheEntry.InProgress {
- log.Printf("TIMEOUT: %s\n", cacheDigest)
- }
- if ok && !cacheEntry.InProgress && cacheEntry.Expires.After(time.Now()) {
- response = cacheEntry
- foundInCache = true
- }
- }
-
- if !foundInCache {
- lruCache.Add(cacheDigest, responseWithHeader{InProgress: true})
- response = get(r)
- if response.StatusCode == 200 || response.StatusCode == 304 {
- lruCache.Add(cacheDigest, response)
- } else {
- log.Printf("REMOVE: %d response for %s from cache\n", response.StatusCode, cacheDigest)
- lruCache.Remove(cacheDigest)
- }
- }
- return response
-}
-
-func get(req *http.Request) responseWithHeader {
-
- client := &http.Client{}
-
- queryURL := fmt.Sprintf("http://%s%s", req.Host, req.RequestURI)
-
- proxyReq, err := http.NewRequest(req.Method, queryURL, req.Body)
- if err != nil {
- log.Printf("Request: %s\n", err)
- }
-
- // proxyReq.Header.Set("Host", req.Host)
- // proxyReq.Header.Set("X-Forwarded-For", req.RemoteAddr)
-
- for header, values := range req.Header {
- for _, value := range values {
- proxyReq.Header.Add(header, value)
- }
- }
-
- res, err := client.Do(proxyReq)
-
- if err != nil {
- panic(err)
- }
-
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- log.Println(err)
- }
-
- return responseWithHeader{
- InProgress: false,
- Expires: time.Now().Add(time.Duration(randInt(1000, 1500)) * time.Second),
- Body: body,
- Header: res.Header,
- StatusCode: res.StatusCode,
- }
-}
-
-// implementation of the cache.get_signature of original wttr.in
-func getCacheDigest(req *http.Request) string {
-
- userAgent := req.Header.Get("User-Agent")
-
- queryHost := req.Host
- queryString := req.RequestURI
-
- clientIPAddress := readUserIP(req)
-
- lang := req.Header.Get("Accept-Language")
-
- return fmt.Sprintf("%s:%s%s:%s:%s", userAgent, queryHost, queryString, clientIPAddress, lang)
-}
-
-// return true if request should not be cached
-func dontCache(req *http.Request) bool {
-
- // dont cache cyclic requests
- loc := strings.Split(req.RequestURI, "?")[0]
- if strings.Contains(loc, ":") {
- return true
- }
- return false
-}
-
-func readUserIP(r *http.Request) string {
- IPAddress := r.Header.Get("X-Real-Ip")
- if IPAddress == "" {
- IPAddress = r.Header.Get("X-Forwarded-For")
- }
- if IPAddress == "" {
- IPAddress = r.RemoteAddr
- var err error
- IPAddress, _, err = net.SplitHostPort(IPAddress)
- if err != nil {
- log.Printf("ERROR: userip: %q is not IP:port\n", IPAddress)
- }
- }
- return IPAddress
-}
-
-func randInt(min int, max int) int {
- return min + rand.Intn(max-min)
-}
diff --git a/legacy/cmd/srv.go b/legacy/cmd/srv.go
deleted file mode 100644
index aae32d5..0000000
--- a/legacy/cmd/srv.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package main
-
-import (
- "context"
- "log"
- "net"
- "net/http"
- "time"
-
- lru "github.com/hashicorp/golang-lru"
-)
-
-const uplinkSrvAddr = "127.0.0.1:9002"
-const uplinkTimeout = 30
-const prefetchInterval = 300
-const lruCacheSize = 12800
-
-var lruCache *lru.Cache
-
-type responseWithHeader struct {
- InProgress bool // true if the request is being processed
- Expires time.Time // expiration time of the cache entry
-
- Body []byte
- Header http.Header
- StatusCode int // e.g. 200
-}
-
-func init() {
- var err error
- lruCache, err = lru.New(lruCacheSize)
- if err != nil {
- panic(err)
- }
-
- dialer := &net.Dialer{
- Timeout: uplinkTimeout * time.Second,
- KeepAlive: uplinkTimeout * time.Second,
- DualStack: true,
- }
-
- http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
- return dialer.DialContext(ctx, network, uplinkSrvAddr)
- }
-
- initPeakHandling()
-}
-
-func copyHeader(dst, src http.Header) {
- for k, vv := range src {
- for _, v := range vv {
- dst.Add(k, v)
- }
- }
-}
-
-func main() {
- http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- // printStat()
- response := processRequest(r)
-
- copyHeader(w.Header(), response.Header)
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.WriteHeader(response.StatusCode)
- w.Write(response.Body)
- })
-
- log.Fatal(http.ListenAndServe(":8082", nil))
-}
diff --git a/legacy/cmd/stat.go b/legacy/cmd/stat.go
deleted file mode 100644
index 1fc135e..0000000
--- a/legacy/cmd/stat.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package main
-
-import (
- "log"
- "sync"
- "time"
-)
-
-type safeCounter struct {
- v map[int]int
- mux sync.Mutex
-}
-
-func (c *safeCounter) inc(key int) {
- c.mux.Lock()
- c.v[key]++
- c.mux.Unlock()
-}
-
-// func (c *safeCounter) val(key int) int {
-// c.mux.Lock()
-// defer c.mux.Unlock()
-// return c.v[key]
-// }
-//
-// func (c *safeCounter) reset(key int) int {
-// c.mux.Lock()
-// defer c.mux.Unlock()
-// result := c.v[key]
-// c.v[key] = 0
-// return result
-// }
-
-var queriesPerMinute safeCounter
-
-func printStat() {
- _, min, _ := time.Now().Clock()
- queriesPerMinute.inc(min)
- log.Printf("Processed %d requests\n", min)
-}
diff --git a/legacy/lib/airports.py b/legacy/lib/airports.py
deleted file mode 100644
index e950ceb..0000000
--- a/legacy/lib/airports.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import csv
-
-AIRPORTS_DAT_FILE = '/home/igor/wttrin-geo/share/airports.dat'
-
-def load_aiports_index():
- file_ = open(AIRPORTS_DAT_FILE, "r")
- reader = csv.reader(file_)
- airport_index = {}
-
- for line in reader:
- airport_index[line[4]] = line
-
- return airport_index
-
-AIRPORTS_INDEX = load_aiports_index()
-
-def get_airport_gps_location(iata_code):
- if iata_code in AIRPORTS_INDEX:
- airport = AIRPORTS_INDEX[iata_code]
- return '%s,%s airport' % (airport[6], airport[7]) #, airport[1])
- return None
-
diff --git a/legacy/lib/buttons.py b/legacy/lib/buttons.py
deleted file mode 100644
index bd79b4f..0000000
--- a/legacy/lib/buttons.py
+++ /dev/null
@@ -1,34 +0,0 @@
-TWITTER_BUTTON = """
-
-"""
-
-GITHUB_BUTTON = """
-wttr.in
-"""
-
-GITHUB_BUTTON_2 = """
-
-wego
-"""
-
-GITHUB_BUTTON_3 = """
-
-pyphoon
-"""
-
-GITHUB_BUTTON_FOOTER = """
-
-
-"""
-
-def add_buttons(output):
- """
- Add buttons to html output
- """
-
- return output.replace('