Compare commits

..
93 Commits
Author SHA1 Message Date
shmyga 41914d7f74 ci(version): 0.8.2 2026-09-12 15:27:15 +03:00
shmyga de466de805 fix(view): fix build_url function 2026-09-12 15:26:35 +03:00
shmyga 1bffafd6a3 ci(version): 0.8.1 2026-09-10 18:48:42 +03:00
shmyga 46e72feb82 fix(rp5): fix rp5 parser 2026-09-10 18:48:23 +03:00
shmyga fdf6e0eac3 ci(version): 0.8.0 2026-09-10 16:16:03 +03:00
shmyga 60651de186 fix(rp5): fix rp5 parser 2026-09-10 10:28:24 +03:00
shmyga bed8d7af7b refactor(static): add base component types 2026-09-10 10:28:12 +03:00
shmyga 6683b7b5b0 style: add lint excludes 2026-09-08 23:35:55 +03:00
shmyga fa0edca522 refactor(easel): remove TagUtil 2026-09-08 23:22:05 +03:00
shmyga f76f33b501 feat(schedule): improve predefined schedule groups 2026-09-08 21:12:08 +03:00
shmyga a6f6586969 docs: update README 2026-09-08 21:07:57 +03:00
shmyga 1835935eaf feat(shcedule): add predefined schedule sport group 2026-09-07 23:39:34 +03:00
shmyga 5db61da32b refactor(static): split schedule and weather to modules 2026-09-07 18:09:49 +03:00
shmyga d44c8076b4 feat(schedule): add tv schedule group page 2026-09-05 16:30:37 +03:00
shmyga 24214ebc3a refactor: add headers module 2026-09-04 10:23:00 +03:00
shmyga b5a8a1536c ci(version): 0.7.0 2026-09-03 20:09:23 +03:00
shmyga 4aafe720dd feat(static): update WeatherLocationElement 2026-09-03 20:01:34 +03:00
shmyga 7c2436fb57 feat(rp5): add rp5 api 2026-09-03 19:47:42 +03:00
shmyga d6487facf4 test(yandexweather): add yandexweather tests 2026-09-01 22:36:54 +03:00
shmyga 86879a3219 ci(version): 0.6.1 2026-08-30 16:04:58 +03:00
shmyga aa0d5a7a41 feat(gismeteo): change gismeteo values merging mode 2026-08-30 16:04:43 +03:00
shmyga bec48e3289 ci(version): 0.6.0 2026-08-28 10:14:35 +03:00
shmyga d8ee66480c build(docker): optimize docker build 2026-08-28 10:13:58 +03:00
shmyga 9f5c43ce92 fix(yandexweather): fix yandexweather parser 2026-08-28 10:13:05 +03:00
shmyga 60c0a7a6fc fix(gismeteo): fix gismeteo parser 2026-08-28 10:02:36 +03:00
shmyga 50c4221b8d feat(yandexweather): add yandexweather api 2026-08-28 10:01:49 +03:00
shmyga a92b63b855 build: update pylint config 2026-08-21 20:10:58 +03:00
shmyga 712c7615a6 test: add default OPENWEATHER_KEY env value for tests 2026-08-21 20:10:27 +03:00
shmyga 1b5d009cdf feat(gismeteo): add gismeteo auth cookie support 2026-08-21 11:05:49 +03:00
shmyga ca08bc282d fix(openweather): fix pressure convertation 2026-08-21 10:28:08 +03:00
shmyga a19de3e01d ci(version): 0.5.4 2026-08-21 10:20:30 +03:00
shmyga f79f754f1b fix(weather): optional pressure and humidity in weather value 2026-08-21 10:19:52 +03:00
shmyga 555b7f4392 ci(version): 0.5.3 2026-08-14 20:59:10 +03:00
shmyga b412a9cee3 fix(static): add autoprefixer 2026-08-14 20:58:33 +03:00
shmyga b0245a1714 build(python): update pyproject.toml format 2026-07-30 15:18:28 +03:00
shmyga 91b530f84c build(docker): add DOCKER_TAG env variable 2026-07-29 11:31:27 +03:00
shmyga 2b1dfad929 build(npm): add babel and postcss webpack rules 2026-07-24 14:00:24 +03:00
shmyga 1df83ec34d ci(version): 0.5.2 2026-07-22 22:16:16 +03:00
shmyga 1c4dac74ca feat(weather): inline weather svg icons 2026-07-22 22:16:16 +03:00
shmyga 75343a21b9 ci(version): 0.5.1 2026-07-22 22:16:16 +03:00
shmyga 83fabdd538 fix(static): fix bootstrap usage 2026-07-22 22:16:16 +03:00
shmyga 29364bb7d4 ci(version): 0.5.0 2026-07-22 22:16:15 +03:00
shmyga 195bd76608 build(scripts): add save docker action 2026-07-22 22:15:08 +03:00
shmyga 436c6c7364 fix(gismeteo): add heavy_rain variant 2026-07-22 22:15:08 +03:00
shmyga 0a734f9c43 feat(static): colorize weather icons 2026-07-22 22:15:08 +03:00
shmyga 6171ec8a26 refactor(static): refactor static module 2026-07-22 22:15:08 +03:00
shmyga 72fd148a54 build(static): fix webpack build warngins 2026-07-22 22:15:06 +03:00
shmyga 12774db70f refactor(static): refactor weather-icons lib 2026-07-22 22:14:41 +03:00
shmyga 0008e99c66 feat(static): use webpack instead of vite 2026-07-22 22:14:41 +03:00
shmyga bad5dff2b2 ci(version): 0.4.2 2026-07-22 21:52:30 +03:00
shmyga e2af31b812 fix(gismeteo): fix empty wind direction value in parser 2026-07-22 21:52:15 +03:00
shmyga 6c76dae760 ci(version): 0.4.1 2026-07-02 14:17:55 +03:00
shmyga 28951df9b5 fix(openweather): optional visability field in forecast model 2026-07-02 14:17:48 +03:00
shmyga 5aa290c772 ci(version): 0.4.0 2026-07-02 14:06:15 +03:00
shmyga 13a70990e5 feat(weather): add hail precipitation variant 2026-07-02 02:59:49 +03:00
shmyga a3fab92e3d feat(view): fix index page 2026-07-02 02:43:43 +03:00
shmyga 4fdb7e9717 fix(view): fix index pages api resolving 2026-07-02 01:30:38 +03:00
shmyga 1d13f6e05d refactor(doc): update docs static 2026-07-01 22:48:24 +03:00
shmyga fcb000afb0 test: fix tests 2026-07-01 21:05:49 +03:00
shmyga 0730b9f567 build(poetry): update python dependencies 2026-07-01 20:53:01 +03:00
shmyga 081aa8d17f feat(openweather): add location name to forecast response 2026-07-01 16:40:16 +03:00
shmyga 29fe06462e feat(schedule): implement multiple schedule providers 2026-06-27 16:03:28 +03:00
shmyga 8b20eb1220 test(openweather): add openweather location seacrh test 2026-06-26 16:27:36 +03:00
shmyga 5333690c47 feat(weather): implement provider in weather api endpoints 2026-06-25 19:19:21 +03:00
shmyga d82fc4ea46 feat(weather): improve weather locations list 2026-06-24 21:02:06 +03:00
shmyga df2f1d0d81 refactor(easel): add view root module 2026-06-24 16:00:39 +03:00
shmyga 9192ca3e4a feat(easel): implement multiple weather providers 2026-06-24 16:00:39 +03:00
shmyga e37ca6eeac feat(easel): add api provider 2026-06-24 16:00:39 +03:00
shmyga 657a62eab5 ci(version): 0.3.4 2026-06-24 15:54:43 +03:00
shmyga d8e2be013a fix(gismeteo): fix precipitation parser 2026-06-24 15:54:35 +03:00
shmyga a91ec12d22 ci(version): 0.3.3 2026-06-22 15:33:36 +03:00
shmyga 9c862863e5 fix(gismeteo): fix precipitation parser 2026-06-22 15:33:19 +03:00
shmyga fc59e52337 ci(version): 0.3.2 2026-06-20 18:59:43 +03:00
shmyga 3e93a41400 fix(gismeteo): fix date-time row parsing 2026-06-20 18:59:27 +03:00
shmyga c2cd18386b refactor(easel): update api router 2026-06-16 21:18:16 +03:00
shmyga 2bca3dd75a ci(version): 0.3.1 2026-06-16 20:17:37 +03:00
shmyga 469bd9bc1f feat(easel): add version to header 2026-06-16 20:17:12 +03:00
shmyga 027d1e2d55 build(docker): add docker build caches mount 2026-06-16 20:01:29 +03:00
shmyga 7cf0012229 feat(schedule): update navigate icons 2026-06-16 20:00:46 +03:00
shmyga edc014d98c docs: update screenshot 2026-06-15 23:37:31 +03:00
shmyga 1813ec213b ci(version): 0.3.0 2026-06-15 23:19:57 +03:00
shmyga 1b700086f2 feat(weather): update navigate icons 2026-06-15 23:18:48 +03:00
shmyga 02a6ffc931 feat(weather): new weather icons 2026-06-15 11:22:41 +03:00
shmyga 2dfedfea57 fix(easel): fix header icons 2026-06-15 11:22:28 +03:00
shmyga 8012d9b8ed fix(gismeteo): add max_date validation 2026-06-14 10:23:38 +03:00
shmyga 3a6faa85be fix(gismeteo): add new variants to sky parser 2026-06-14 10:23:13 +03:00
shmyga 1af61aa3c7 feat(easel): add sky details tooltip 2026-06-14 10:22:43 +03:00
shmyga 315838604e feat(easel): add widget mode support 2026-06-14 09:48:27 +03:00
shmyga f368e6717c style: format code 2026-06-12 00:16:15 +03:00
shmyga 91e2c9d123 ci(version): 0.2.3 2026-06-10 11:49:56 +03:00
shmyga 91d9c37612 build(vscode): add settings 2026-06-10 11:49:48 +03:00
shmyga b5f2c272bb feat(easel): update navbar 2026-06-10 11:37:49 +03:00
shmyga eec72c77ab docs: add screenshot 2026-05-07 01:11:42 +03:00
182 changed files with 17964 additions and 8565 deletions
+1 -1
View File
@@ -10,4 +10,4 @@ max_line_length = 120
[*.md] [*.md]
max_line_length = off max_line_length = off
trim_trailing_whitespace = false trim_trailing_whitespace = true
-5
View File
@@ -1,5 +0,0 @@
DOCKER_REPO=git.shmyga.ru
DOCKER_GROUP=infernalgames
DOCKER_ROOT="$DOCKER_REPO/$DOCKER_GROUP"
VERSION=$(grep -m 1 'version' ./pyproject.toml | grep -oP 'version\s*=\s*"\K[^"]+')
DOCKER_PROJECTS=("gallery")
+10
View File
@@ -0,0 +1,10 @@
DOCKER_REPO=git.shmyga.ru
DOCKER_GROUP=infernalgames
DOCKER_ROOT="$DOCKER_REPO/$DOCKER_GROUP"
VERSION=$(grep -m 1 'version' ./pyproject.toml | grep -oP 'version\s*=\s*"\K[^"]+')
PYTHON_VERSION=$(grep -m 1 'python' ./pyproject.toml | grep -oP 'python\s*=\s*"\^?\K[^"]+')
DOCKER_PROJECTS=("gallery")
DOCKER_TAG="${DOCKER_TAG:-latest}"
OPENWEATHER_KEY=""
GISMETEO_AUTH=""
+2
View File
@@ -5,3 +5,5 @@
#.vscode #.vscode
static/node_modules static/node_modules
static/dist static/dist
.env
dist
+9
View File
@@ -0,0 +1,9 @@
[presets.python.tasks.setup.playwright]
conditions = ["{{ '.venv/bin/playwright' | file }}"]
commands = [".venv/bin/playwright install chromium --with-deps --only-shell"]
[presets.locales.tasks.build.locales]
priority = 1
conditions = ["{{ 'locales/ru/LC_MESSAGES' | file }}"]
cwd = "locales/ru/LC_MESSAGES"
commands = ["msgfmt messages.po"]
+4 -15
View File
@@ -4,23 +4,12 @@ ignore=.venv
[MESSAGES CONTROL] [MESSAGES CONTROL]
disable= disable=
missing-docstring, missing-docstring,
too-few-public-methods,
too-many-instance-attributes,
too-many-arguments,
too-many-locals,
too-many-boolean-expressions,
too-many-public-methods,
no-else-return,
singleton-comparison,
unused-argument,
unspecified-encoding,
fixme, fixme,
invalid-name,
duplicate-code, duplicate-code,
too-few-public-methods,
extension-pkg-allow-list= too-many-locals,
lxml, no-else-return,
GeoIP,
pydantic
[MISCELLANEOUS] [MISCELLANEOUS]
notes=FIXME,TODO notes=FIXME,TODO
+9
View File
@@ -0,0 +1,9 @@
{
"python-envs.pythonProjects": [
{
"path": ".",
"envManager": "ms-python.python:poetry",
"packageManager": "ms-python.python:poetry"
}
]
}
+11 -5
View File
@@ -1,4 +1,4 @@
FROM python:3.12 AS builder FROM python:3.14 AS builder
ENV POETRY_HOME="/opt/poetry" ENV POETRY_HOME="/opt/poetry"
ENV PATH="$POETRY_HOME/bin:$PATH" ENV PATH="$POETRY_HOME/bin:$PATH"
RUN apt update && \ RUN apt update && \
@@ -7,7 +7,9 @@ WORKDIR /app
RUN curl -sSL https://install.python-poetry.org | python3 - RUN curl -sSL https://install.python-poetry.org | python3 -
COPY pyproject.toml poetry.lock README.md ./ COPY pyproject.toml poetry.lock README.md ./
RUN poetry config virtualenvs.in-project true RUN poetry config virtualenvs.in-project true
RUN poetry install --with app --no-root RUN --mount=type=cache,target=/root/.cache/pypoetry/cache \
--mount=type=cache,target=/root/.cache/pypoetry/artifacts \
poetry install --extras app --no-root
COPY locales ./locales COPY locales ./locales
RUN cd locales/ru/LC_MESSAGES && msgfmt messages.po RUN cd locales/ru/LC_MESSAGES && msgfmt messages.po
@@ -15,19 +17,23 @@ FROM node:24 AS node-builder
ENV PATH=/app/node_modules/.bin:$PATH ENV PATH=/app/node_modules/.bin:$PATH
WORKDIR /app WORKDIR /app
COPY static/package.json static/package-lock.json ./ COPY static/package.json static/package-lock.json ./
RUN npm ci RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY static ./ COPY static ./
RUN npm run build RUN npm run build
FROM python:3.12-slim FROM python:3.14-slim
ENV PATH="/app/.venv/bin:$PATH" ENV PATH="/app/.venv/bin:$PATH"
WORKDIR /app WORKDIR /app
ENV TZ="Europe/Moscow" ENV TZ="Europe/Moscow"
COPY --from=builder /app ./ COPY --from=builder /app ./
RUN .venv/bin/playwright install chromium --with-deps --only-shell
COPY --from=node-builder /app/dist ./static/dist COPY --from=node-builder /app/dist ./static/dist
COPY gallery gallery/ COPY gallery gallery/
#COPY --from=builder /app/gallery/easel/route/view/locales /app/gallery/easel/route/view/locales
COPY --from=builder --parents locales/**/*.mo ./ COPY --from=builder --parents locales/**/*.mo ./
CMD ["uvicorn", "gallery.main:app", "--host", "0.0.0.0", "--port", "80", "--log-config", "gallery/logging.yaml"] CMD ["uvicorn", "gallery.main:app", "--host", "0.0.0.0", "--port", "80", "--log-config", "gallery/logging.yaml"]
+70 -4
View File
@@ -1,9 +1,75 @@
# API Gallery # API Gallery
## View Currently implemented APIs:
- Weather forecast
- TV program
## API
Swagger: https://api.shmyga.ru/docs
### Weather
#### Providers list
```
https://api.shmyga.ru/api/weather/providers
```
#### Locations search
```
https://api.shmyga.ru/api/weather/{provider}/locations?query={query}
```
#### Weather forecast
```
https://api.shmyga.ru/api/weather/{provider}/{location_id}/day/{date}
https://api.shmyga.ru/api/weather/{provider}/{location_id}/days/{days_count}
```
### TV program
#### Providers list
```
https://api.shmyga.ru/api/schedule/providers
```
#### Channels search
```
https://api.shmyga.ru/api/schedule/{provider}/channels?query={query}
```
#### TV program
```
https://api.shmyga.ru/api/schedule/{provider}/{channel_id}/{date}
```
## Providers
### Weather
| Provider | Site | API sample |
| :- | :- | :- |
| gismeteo | https://www.gismeteo.ru | https://api.shmyga.ru/api/weather/gismeteo/orel-4432/day/today |
| openweather | https://openweathermap.org | https://api.shmyga.ru/api/weather/openweather/52.9685433%3A36.0692477/day/today |
| yandex | https://yandex.ru/pogoda | https://api.shmyga.ru/api/weather/yandex/10/day/today |
| rp5 | https://rp5.ru | https://api.shmyga.ru/api/weather/rp5/Погода_в_Орле%2C_Орловская_область/day/today |
### TV program
| Provider | Site | API sample |
| :- | :- | :- |
| matchtv | https://matchtv.ru/tvguide | https://api.shmyga.ru/api/schedule/matchtv/igra/today |
| yandextv | https://tv.yandex.ru | https://api.shmyga.ru/api/schedule/yandextv/146/today |
## Demo
https://api.shmyga.ru https://api.shmyga.ru
## Swagger ![API Gallery](docs/screenshot.png "API Gallery")
https://api.shmyga.ru/docs
+2
View File
@@ -12,6 +12,8 @@ services:
build: . build: .
environment: environment:
- REDIS_HOST=redis - REDIS_HOST=redis
- OPENWEATHER_KEY=$OPENWEATHER_KEY
- GISMETEO_AUTH=$GISMETEO_AUTH
- DEBUG=1 - DEBUG=1
ports: ports:
- 8000:80 - 8000:80
+6 -4
View File
@@ -1,17 +1,19 @@
name: gallery name: gallery-${DOCKER_TAG}
services: services:
redis: redis:
container_name: gallery-redis container_name: gallery-${DOCKER_TAG}-redis
image: redis:alpine image: redis:alpine
stop_grace_period: 3s stop_grace_period: 3s
volumes: volumes:
- redis_data:/data - redis_data:/data
app: app:
container_name: gallery-app container_name: gallery-${DOCKER_TAG}-app
image: ${DOCKER_ROOT}/gallery image: ${DOCKER_ROOT}/gallery:${DOCKER_TAG}
environment: environment:
- REDIS_HOST=redis - REDIS_HOST=redis
- OPENWEATHER_KEY=$OPENWEATHER_KEY
- GISMETEO_AUTH=$GISMETEO_AUTH
depends_on: depends_on:
- redis - redis
ports: ports:
Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

+5
View File
@@ -8,6 +8,8 @@
"python.testing.pytestArgs": ["tests", "-s"], "python.testing.pytestArgs": ["tests", "-s"],
"python.testing.unittestEnabled": false, "python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true, "python.testing.pytestEnabled": true,
"python.terminal.useEnvFile": true,
"python.analysis.importFormat": "relative",
"python-envs.pythonProjects": [ "python-envs.pythonProjects": [
{ {
"path": ".", "path": ".",
@@ -34,6 +36,8 @@
"request": "launch", "request": "launch",
"module": "uvicorn", "module": "uvicorn",
"args": ["gallery.main:app", "--reload", "--log-config", "gallery/logging.yaml"], "args": ["gallery.main:app", "--reload", "--log-config", "gallery/logging.yaml"],
"justMyCode": true,
"consoleTitle": "gallery:app",
}, },
{ {
"name": "gallery:static", "name": "gallery:static",
@@ -41,6 +45,7 @@
"request": "launch", "request": "launch",
"type": "node-terminal", "type": "node-terminal",
"command": "npm run dev", "command": "npm run dev",
"consoleTitle": "gallery:static",
}, },
], ],
}, },
+1 -1
View File
@@ -10,7 +10,7 @@ caches.set_config(
{ {
"default": { "default": {
"cache": "aiocache.SimpleMemoryCache", "cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"}, "serializer": {"class": "aiocache.serializers.PickleSerializer"},
}, },
"redis": { "redis": {
"cache": "aiocache.RedisCache", "cache": "aiocache.RedisCache",
+3 -4
View File
@@ -4,8 +4,7 @@ from fastapi.staticfiles import StaticFiles
from gallery.sketch.bundle import ApiBundle from gallery.sketch.bundle import ApiBundle
from gallery.util import root_path from gallery.util import root_path
from .route import api, doc from .route import api, doc, view
from .route.view import router as view_router
def build_app(api_bundle: ApiBundle) -> FastAPI: def build_app(api_bundle: ApiBundle) -> FastAPI:
@@ -17,6 +16,6 @@ def build_app(api_bundle: ApiBundle) -> FastAPI:
app.state.api = api_bundle app.state.api = api_bundle
app.mount("/static", StaticFiles(directory=root_path / "static/dist")) app.mount("/static", StaticFiles(directory=root_path / "static/dist"))
doc.mount(app) doc.mount(app)
api.mount(app) app.include_router(api.router)
app.include_router(view_router) app.include_router(view.router)
return app return app
View File
+17
View File
@@ -0,0 +1,17 @@
from fastapi import HTTPException, status
from gallery.easel.core import AppRequest
from gallery.sketch.api import API
def api_resolver(api_type: type[API]):
def get_api(request: AppRequest, provider: str) -> API:
providers = request.app.state.api.get_api_providers(api_type)
if provider not in providers:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={"provider": f"'{provider}' not in {providers}"},
)
return request.app.state.api.get_api(api_type, provider)
return get_api
+25
View File
@@ -0,0 +1,25 @@
import datetime
from typing import Annotated
from fastapi import Depends, HTTPException, status
def date_parser(date: str) -> datetime.date:
if date == "today":
return datetime.date.today()
elif date == "tomorrow":
return datetime.date.today() + datetime.timedelta(days=1)
elif date.startswith("day-"):
days = int(date.split("-")[-1])
return datetime.date.today() + datetime.timedelta(days=days)
else:
try:
return datetime.date.strptime(date, "%Y-%m-%d")
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={"date": f"{exc}"},
) from exc
DateDepends = Annotated[datetime.date, Depends(date_parser)]
+9
View File
@@ -0,0 +1,9 @@
from typing import Annotated
from fastapi import Depends
from gallery.sketch.schedule.api import ScheduleApi
from .api import api_resolver
ScheduleApiDepends = Annotated[ScheduleApi, Depends(api_resolver(ScheduleApi))]
+9
View File
@@ -0,0 +1,9 @@
from typing import Annotated
from fastapi import Depends
from gallery.sketch.weather.api import WeatherApi
from .api import api_resolver
WeatherApiDepends = Annotated[WeatherApi, Depends(api_resolver(WeatherApi))]
+4 -5
View File
@@ -1,8 +1,7 @@
from fastapi import FastAPI from fastapi import APIRouter
from . import schedule, weather from . import schedule, weather
router = APIRouter(prefix="/api")
def mount(app: FastAPI): router.include_router(weather.router)
weather.mount(app) router.include_router(schedule.router)
schedule.mount(app)
+22 -15
View File
@@ -1,20 +1,27 @@
import datetime from fastapi import APIRouter
from fastapi import FastAPI
from gallery.easel.core import AppRequest from gallery.easel.core import AppRequest
from gallery.sketch.schedule.model import ChannelId, Schedule from gallery.easel.depends.schedule import ScheduleApiDepends
from gallery.sketch.schedule.api import ScheduleApi
from gallery.sketch.schedule.model import Channel, Schedule
from ...depends.date import DateDepends
router = APIRouter(prefix="/schedule", tags=["Schedule"])
def mount(app: FastAPI): @router.get("/providers")
@app.get("/api/schedule/channels", tags=["API"]) async def get_api_weather_providers(request: AppRequest) -> list[str]:
async def get_api_schedule_channels(request: AppRequest) -> list[ChannelId]: return request.app.state.api.get_api_providers(ScheduleApi)
schedule_api = request.app.state.api.schedule
return await schedule_api.get_channels()
@app.get("/api/schedule/{channel}/{date}", tags=["API"])
async def get_api_schedule_channel_schedule( @router.get("/{provider}/channels")
request: AppRequest, channel: str, date: datetime.date async def find_api_schedule_channels(schedule_api: ScheduleApiDepends, query: str) -> list[Channel]:
) -> Schedule: return await schedule_api.find_channels(query)
schedule_api = request.app.state.api.schedule
return await schedule_api.get_channel_schedule(ChannelId(channel), date)
@router.get("/{provider}/{channel}/{date}")
async def get_api_schedule_channel_schedule(
schedule_api: ScheduleApiDepends, channel: str, date: DateDepends
) -> Schedule:
return await schedule_api.get_schedule(channel, date)
+20 -19
View File
@@ -1,29 +1,30 @@
import datetime from fastapi import APIRouter
from fastapi import FastAPI
from gallery.easel.core import AppRequest from gallery.easel.core import AppRequest
from gallery.easel.depends.weather import WeatherApiDepends
from gallery.sketch.weather.api import WeatherApi
from gallery.sketch.weather.model import Location, WeatherResponse from gallery.sketch.weather.model import Location, WeatherResponse
from ...depends.date import DateDepends
def mount(app: FastAPI): router = APIRouter(prefix="/weather", tags=["Weather"])
@app.get("/api/weather/locations", tags=["API"])
async def get_api_weather_locations(
request: AppRequest, query: str @router.get("/providers")
) -> list[Location]: async def get_api_weather_providers(request: AppRequest) -> list[str]:
weather_api = request.app.state.api.weather return request.app.state.api.get_api_providers(WeatherApi)
@router.get("/{provider}/locations")
async def find_api_weather_locations(weather_api: WeatherApiDepends, query: str) -> list[Location]:
return await weather_api.find_locations(query) return await weather_api.find_locations(query)
@app.get("/api/weather/{location}/day/{date}", tags=["API"])
async def get_api_weather_day( @router.get("/{provider}/{location}/day/{date}")
request: AppRequest, location: str, date: datetime.date async def get_api_weather_day(weather_api: WeatherApiDepends, location: str, date: DateDepends) -> WeatherResponse:
) -> WeatherResponse:
weather_api = request.app.state.api.weather
return await weather_api.get_day(location, date) return await weather_api.get_day(location, date)
@app.get("/api/weather/{location}/days/{days}", tags=["API"])
async def get_api_weather_days( @router.get("/{provider}/{location}/days/{days}")
request: AppRequest, location: str, days: int async def get_api_weather_days(weather_api: WeatherApiDepends, location: str, days: int) -> WeatherResponse:
) -> WeatherResponse:
weather_api = request.app.state.api.weather
return await weather_api.get_days(location, days) return await weather_api.get_days(location, days)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -1,11 +1,11 @@
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends
from .common import router as common_router from .root import router as root_router
from .schedule import router as schedule_router from .schedule import router as schedule_router
from .translation import set_language from .translation import set_language
from .weather import router as weather_router from .weather import router as weather_router
router = APIRouter(dependencies=[Depends(set_language)]) router = APIRouter(tags=["view"], dependencies=[Depends(set_language)], include_in_schema=False)
router.include_router(common_router) router.include_router(root_router)
router.include_router(weather_router) router.include_router(weather_router)
router.include_router(schedule_router) router.include_router(schedule_router)
@@ -1,41 +0,0 @@
from pathlib import Path
from typing import NamedTuple
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from gallery.version import __version__
from ..translation import _
class Section(NamedTuple):
link: str
title: str
icon: str
SECTIONS = [
Section("weather", "Weather", "brightness-high"),
Section("schedule", "TV program", "tv"),
]
base_dir = Path(__file__).parent
router = APIRouter()
templates = Jinja2Templates(directory=base_dir / "templates")
templates.env.globals.update({"_": _})
@router.get("/", response_class=HTMLResponse)
async def get_section_list(request: Request):
return templates.TemplateResponse(
request=request,
name="root_index.html",
context={
"version": __version__,
"sections": SECTIONS,
},
)
@@ -12,19 +12,22 @@
<link rel="stylesheet" <link rel="stylesheet"
href="/static/gallery.css?v={{version}}"> href="/static/gallery.css?v={{version}}">
<script type="module" <script type="module"
src="/static/gallery.es.js?v={{version}}"></script> src="/static/gallery.js?v={{version}}"></script>
<link rel="icon" <link rel="icon"
href="/favicon.ico?v={{version}}" href="/favicon.ico?v={{version}}"
type="image/x-icon"> type="image/x-icon">
{% endblock %} {% endblock %}
</head> </head>
<body> <body class="{{ is_widget and 'widget' or ''}}">
<div class="app col-lg-8 mx-auto p-3 py-md-5"> <div class="app col-lg-8 mx-auto p-3 py-md-5">
<header class="d-flex align-items-center pb-3 mb-5 border-bottom"> {% if not is_widget %}
<header class="app-header pb-3 mb-5 border-bottom">
<div class="link-list">
<app-link href="/" <app-link href="/"
icon="gear">API Gallery</app-link> icon="gear">API Gallery</app-link>
{% block header %}{% endblock %} {% block header %}{% endblock %}
</div>
<ul class="navbar-nav flex-row flex-wrap ms-md-auto"> <ul class="navbar-nav flex-row flex-wrap ms-md-auto">
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<button class="btn btn-link nav-link py-2 px-0 px-lg-2 dropdown-toggle d-flex align-items-center" <button class="btn btn-link nav-link py-2 px-0 px-lg-2 dropdown-toggle d-flex align-items-center"
@@ -33,7 +36,7 @@
aria-expanded="false" aria-expanded="false"
data-bs-toggle="dropdown" data-bs-toggle="dropdown"
aria-label="{{_('Select language')}} (default)"> aria-label="{{_('Select language')}} (default)">
<span class="fi fi-gb me-2 language-icon-active"></span> <span class="fi fir fi-gb me-2 language-icon-active icon-header"></span>
<span class="d-lg-none ms-2" <span class="d-lg-none ms-2"
id="bd-language-text">{{_("Select language")}}</span> id="bd-language-text">{{_("Select language")}}</span>
</button> </button>
@@ -44,7 +47,7 @@
class="dropdown-item d-flex align-items-center" class="dropdown-item d-flex align-items-center"
data-bs-language-value="en" data-bs-language-value="en"
aria-pressed="false"> aria-pressed="false">
<span class="fi fi-gb me-2 language-icon-active"></span> <span class="fi fir fi-gb me-2 language-icon-active"></span>
{{_("English")}} {{_("English")}}
</button> </button>
</li> </li>
@@ -53,7 +56,7 @@
class="dropdown-item d-flex align-items-center" class="dropdown-item d-flex align-items-center"
data-bs-language-value="ru" data-bs-language-value="ru"
aria-pressed="false"> aria-pressed="false">
<span class="fi fi-ru me-2 language-icon-active"></span> <span class="fi fir fi-ru me-2 language-icon-active"></span>
{{_("Russian")}} {{_("Russian")}}
</button> </button>
</li> </li>
@@ -66,7 +69,7 @@
aria-expanded="false" aria-expanded="false"
data-bs-toggle="dropdown" data-bs-toggle="dropdown"
aria-label="Toggle theme (auto)"> aria-label="Toggle theme (auto)">
<span class="bi bi-circle-half me-2 opacity-50 theme-icon-active"></span> <span class="bi bi-circle-half me-2 opacity-50 theme-icon-active icon-header"></span>
<span class="d-lg-none ms-2" <span class="d-lg-none ms-2"
id="bd-theme-text">{{_("Toggle theme")}}</span> id="bd-theme-text">{{_("Toggle theme")}}</span>
</button> </button>
@@ -103,22 +106,19 @@
</li> </li>
</ul> </ul>
</header> </header>
{% endif %}
<main> <main>
{% block content %}{% endblock %} {% block content %}{% endblock %}
</main> </main>
<footer class="pt-5 my-5 text-muted border-top"> {% if not is_widget %}
Created by shmyga &middot; &copy; 2026 <footer class="app-footer pt-5 my-5 text-muted border-top">
<div class="d-flex justify-content-between">
<span>Created by shmyga &middot; &copy; 2026</span>
<span>v{{ version }}</span>
</div>
</footer> </footer>
{% endif %}
</div> </div>
<script>
(function () {
const params = new URLSearchParams(window.location.search);
const widget = params.get('widget') || window.location.hostname.startsWith('weather');
if (widget) {
document.body.classList.add('widget');
}
}());
</script>
</body> </body>
</html> </html>
@@ -1,26 +0,0 @@
{% extends "base.html" %}
{% block title %}{{_("Index")}}{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<h1>{{_("View")}}</h1>
<div class="list-group mb-5">
{% for section in sections %}
<a href="{{section.link}}"
class="list-group-item list-group-item-action px-4">
<app-link href="{{section.link}}"
icon="{{section.icon}}">
{{_(section.title)}}
</app-link>
</a>
{% endfor %}
</div>
<hr class="col-3 col-md-2 mb-5">
<h1>{{_("Docs")}}</h1>
<a href="/docs"
target="_blank">
<h4>Swagger</h4>
</a>
{% endblock %}
-57
View File
@@ -1,57 +0,0 @@
import datetime
from enum import Enum
from typing import NamedTuple
class TagType(str, Enum):
DAY = "day"
DAYS = "days"
class Tag(NamedTuple):
type: TagType
date: datetime.date
days: int = 1
def __str__(self) -> str:
if self.type == TagType.DAY:
today = datetime.date.today()
day = (self.date - today).days
return f"day-{day}"
elif self.type == TagType.DAYS:
return f"days-{self.days}"
else:
raise ValueError(self.type)
class TagUtil:
@classmethod
def parse_tag(cls, tag: str) -> Tag:
if tag == "today":
return Tag(TagType.DAY, datetime.date.today())
elif tag == "tomorrow":
return Tag(TagType.DAY, datetime.date.today() + datetime.timedelta(days=1))
elif tag.startswith("day-"):
days = int(tag.split("-")[-1])
return Tag(
TagType.DAY,
datetime.date.today() + datetime.timedelta(days=days),
)
elif tag.startswith("days-"):
days = int(tag.split("-")[-1])
return Tag(TagType.DAYS, datetime.date.today(), days)
raise ValueError(tag)
@classmethod
def create_tag(
cls,
tag_type: TagType,
date: datetime.date,
day: int = 0,
days: int = 10,
) -> Tag:
if tag_type == TagType.DAY:
return Tag(tag_type, date + datetime.timedelta(days=day))
if tag_type == TagType.DAYS:
return Tag(tag_type, date, days)
raise ValueError(tag_type)
@@ -0,0 +1,73 @@
import datetime
import typing
from pathlib import Path
from urllib.parse import parse_qsl, urlencode, urlsplit
from babel.dates import format_date
from fastapi import Request
from fastapi.templating import Jinja2Templates
from gallery.easel.core import AppRequest
from gallery.version import __version__
from ...translation import _
ContextProcessor = typing.Callable[[AppRequest], dict[str, typing.Any]]
def is_widget(request: Request) -> bool:
return (request.url.hostname and request.url.hostname.startswith("weather")) or (
request.query_params.get("widget") is not None
)
def base_context_processor(request: Request) -> dict:
return {
"is_widget": is_widget(request),
"provider": request.query_params.get("provider") or request.path_params.get("provider"),
}
def build_url(
request: Request, *, path: list[str] | None = None, up: int | None = None, query: dict | None = None
) -> str:
parts = urlsplit(str(request.url))
if up:
path = [".."] * up
if path:
path_parts = parts.path.split("/")
for item in path:
if item == "..":
path_parts = path_parts[:-1]
else:
path_parts.append(str(item))
parts = parts._replace(path="/".join(path_parts))
if query:
query_dict = {**dict(parse_qsl(parts.query)), **query}
parts = parts._replace(query=urlencode(query_dict))
return "/".join([""] + parts.geturl().split("/")[3:])
def build_templates(
templates_dir: Path | None = None, filters: dict | None = None, context_processor: ContextProcessor | None = None
) -> Jinja2Templates:
directory = [Path(__file__).parent.parent / "templates"]
if templates_dir:
directory.append(templates_dir)
context_processors: list[ContextProcessor] = [base_context_processor]
if context_processor:
context_processors.append(context_processor)
templates = Jinja2Templates(directory=directory, context_processors=context_processors)
templates.env.globals.update(
{
"_": _,
"version": __version__,
"format_date": format_date,
"datetime": datetime,
"DATE_FORMAT": "E, d MMMM Y",
"build_url": build_url,
}
)
if filters:
templates.env.filters.update(filters)
return templates
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
from typing import NamedTuple
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from ..common.utils.template import build_templates
class Section(NamedTuple):
link: str
title: str
icon: str
SECTIONS = [
Section("weather", "Weather", "brightness-high"),
Section("schedule", "TV program", "tv"),
]
base_dir = Path(__file__).parent
router = APIRouter()
templates = build_templates(Path(__file__).parent / "templates")
@router.get("/", response_class=HTMLResponse)
async def get_section_list(request: Request):
return templates.TemplateResponse(
request=request,
name="root_index.html",
context={
"sections": SECTIONS,
},
)
@@ -0,0 +1,33 @@
{% extends "base.html" %}
{% block title %}{{_("Index")}}{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<h1>{{_("View")}}</h1>
<div class="list-group mb-3">
{% for section in sections %}
<app-link href="{{section.link}}"
icon="{{section.icon}}"
class="list-group-item list-group-item-action">
{{_(section.title)}}
</app-link>
{% endfor %}
</div>
<h1>{{_("Docs")}}</h1>
<div class="list-group mb-3">
<app-link href="/docs"
target="_blank"
icon="file-earmark-text"
class="list-group-item list-group-item-action">
Swagger UI
</app-link>
<app-link href="/redoc"
target="_blank"
icon="file-earmark-text"
class="list-group-item list-group-item-action">
ReDoc
</app-link>
</div>
{% endblock %}
+1 -92
View File
@@ -1,92 +1 @@
import datetime from .route import router
from pathlib import Path
from babel.dates import format_date
from fastapi import APIRouter
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from gallery.easel.core import AppRequest
from gallery.sketch.schedule.catalog import BUNDLE
from gallery.version import __version__
from ..common.util import TagType, TagUtil
from ..translation import _
from .filters import timedelta_format
base_dir = Path(__file__).parent
templates = Jinja2Templates(
directory=[
base_dir.parent / "common/templates",
base_dir / "templates",
]
)
templates.env.globals.update(
{
"_": _,
"version": __version__,
"format_date": format_date,
}
)
templates.env.filters["timedelta_format"] = timedelta_format
router = APIRouter()
@router.get("/schedule", response_class=HTMLResponse)
async def get_schedule_list(request: AppRequest):
schedule_api = request.app.state.api.schedule
channels = await schedule_api.get_channels()
channels_data = BUNDLE.select_items(channels)
return templates.TemplateResponse(
request=request,
name="index.html",
context={
"version": __version__,
"channels": channels_data,
},
)
@router.get("/schedule/tag/{tag}", response_class=HTMLResponse)
async def get_schedule_tag(request: AppRequest, tag: str, live: bool = False):
tag_value = TagUtil.parse_tag(tag)
schedule_api = request.app.state.api.schedule
results = await schedule_api.get_all_schedules(tag_value.date)
return templates.TemplateResponse(
request=request,
name="schedule.html",
context={
"version": __version__,
"tag_util": TagUtil,
"datetime": datetime,
"response": results[0],
"responses": results,
"live": live,
},
)
@router.get("/schedule/{channel}", response_class=RedirectResponse)
async def get_channel_default(channel: str):
return RedirectResponse(f"{channel}/tag/today")
@router.get("/schedule/{channel}/tag/{tag}", response_class=HTMLResponse)
async def get_channel_tag(request: AppRequest, channel: str, tag: str):
tag_value = TagUtil.parse_tag(tag)
schedule_api = request.app.state.api.schedule
if tag_value.type == TagType.DAY:
response = await schedule_api.get_channel_schedule(channel, tag_value.date)
else:
raise ValueError(tag)
return templates.TemplateResponse(
request=request,
name="channel.html",
context={
"version": __version__,
"tag_util": TagUtil,
"datetime": datetime,
"response": response,
},
)
@@ -0,0 +1,18 @@
GROUP_MAP = {
"central": [
("yandextv", "146"), # pervyy
("yandextv", "587"), # rossya-1
("yandextv", "162"), # ntv
("yandextv", "79"), # sts
],
"sport": [
("matchtv", "matchtv"),
("matchtv", "igra"),
("matchtv", "arena"),
("matchtv", "futbol-1"),
("matchtv", "futbol-2"),
("matchtv", "futbol-3"),
("matchtv", "strana"),
("yandextv", "1799"), # start
],
}
@@ -0,0 +1,86 @@
import datetime
from pathlib import Path
from urllib import parse
from fastapi import APIRouter
from fastapi.responses import HTMLResponse, RedirectResponse
from gallery.easel.core import AppRequest
from gallery.easel.depends.api import api_resolver
from gallery.easel.depends.date import DateDepends
from gallery.easel.depends.schedule import ScheduleApiDepends
from gallery.sketch.bundle import ApiBundle
from gallery.sketch.schedule.api import ScheduleApi
from gallery.sketch.schedule.model import Schedule
from ..common.utils.template import build_templates
from .bundle import GROUP_MAP
from .filters import timedelta_format
def context_procesor(request: AppRequest) -> dict:
return {
"providers": request.app.state.api.get_api_providers(ScheduleApi),
}
templates = build_templates(
Path(__file__).parent / "templates",
{
"timedelta_format": timedelta_format,
},
context_procesor,
)
router = APIRouter(prefix="/schedule")
@router.get("/", response_class=HTMLResponse)
async def get_schedule_index(request: AppRequest, provider: str | None = None, query: str | None = None):
if query and provider:
schedule_api = api_resolver(ScheduleApi)(request, provider)
channels = await schedule_api.find_channels(query)
else:
channels = []
return templates.TemplateResponse(
request=request,
name="index.html",
context={"channels": [item.model_dump() for item in channels], "groups": GROUP_MAP.keys()},
)
async def _get_group_schedule(api: ApiBundle, channels: list[tuple[str, str]], date: datetime.date) -> list[Schedule]:
return [
await api.get_api(ScheduleApi, provider).get_schedule(channel_id, date) for provider, channel_id in channels
]
@router.get("/group/{group_id}", response_class=RedirectResponse)
async def get_group_default(group_id: str):
return RedirectResponse(f"{parse.quote(group_id)}/today")
@router.get("/group/{group_id}/{date}", response_class=HTMLResponse)
async def get_group(request: AppRequest, group_id: str, date: DateDepends):
channels = GROUP_MAP.get(group_id, [tuple(item.split(":")) for item in group_id.split(",")])
responses = await _get_group_schedule(request.app.state.api, channels, date)
return templates.TemplateResponse(
request=request,
name="group.html",
context={"responses": responses},
)
@router.get("/{provider}/{channel}", response_class=RedirectResponse)
async def get_channel_default(channel: str):
return RedirectResponse(f"{channel}/today")
@router.get("/{provider}/{channel}/{date}", response_class=HTMLResponse)
async def get_channel(request: AppRequest, schedule_api: ScheduleApiDepends, channel: str, date: DateDepends):
response = await schedule_api.get_schedule(channel, date)
return templates.TemplateResponse(
request=request,
name="channel.html",
context={"response": response},
)
@@ -1,37 +1,51 @@
{% extends "base.html" %} {% extends "base.html" %}
{% set live = request.query_params.live == '1' %}
{% set date = response.date %}
{% block title %} {% block title %}
{{_("TV program")}} | {{response.channel.name}} | {{format_date(response.date, 'E, d MMMM Y', locale=request.state.language)}} {{_("TV program")}} | {{response.channel.name}} | {{format_date(response.date, DATE_FORMAT,
locale=request.state.language)}}
{% endblock %} {% endblock %}
{% block header %} {% block header %}
<span class="fs-4 text-body ms-2 me-2">/</span>
<app-link href="/schedule" <app-link href="/schedule"
icon="tv">{{_("TV program")}}</app-link> icon="tv">{{_("TV program")}}</app-link>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<h4> <h4 class="mb-4">
<a class="button {{'disabled' if response.date == datetime.date.today() else ''}}" <a class="icon-link {{'disabled' if date == datetime.date.today() else ''}}"
href="../tag/{{tag_util.create_tag('day', response.date, -1)}}">⬅️</a> href="{{build_url(request, path=['..', date - datetime.timedelta(days=1)])}}">
<a class="button" <i class="bi bi-arrow-left-square"></i>
href="../..">⬆️</a> </a>
<span>{{response.channel.name}} | {{format_date(response.date, 'E, d MMMM Y', locale=request.state.language)}}</span> <a class="icon-link"
<a class="button" href="{{build_url(request, up=3)}}">
href="../tag/{{tag_util.create_tag('day', response.date, 1)}}">➡️</a> <i class="bi bi-arrow-up-square"></i>
</a>
<a class="icon-link {{'text-secondary' if not live else ''}}"
href="{{build_url(request, query={'live': 0 if live else 1})}}">
<i class="bi bi-cast"></i>
</a>
<span class="badge rounded-pill text-bg-secondary fs-6">{{provider}}</span>
<span>{{response.channel.name}} | {{format_date(response.date, DATE_FORMAT, locale=request.state.language)}}</span>
<a class="icon-link"
href="{{build_url(request, path=['..', date + datetime.timedelta(days=1)])}}">
<i class="bi bi-arrow-right-square"></i>
</a>
</h4> </h4>
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<td></td> <td></td>
<td></td> <td style="width:100%"></td>
<td></td>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for value in response.values %} {% for value in response.values %}
<tr class="{{'table-success' if value.live else ''}}"> <tr class="{{'d-none' if (live and not value.live) else 'table-success' if (not live and value.live) else ''}}">
<td>{{value.start.strftime('%H:%M')}}</td> <td>
<td>{{(value.end - value.start) | timedelta_format}}</td> <span>{{value.start.strftime('%H:%M')}}</span>&nbsp;<span class="small ms-1">({{(value.end - value.start) | timedelta_format}})</span>
</td>
<td>{{value.label}}</td> <td>{{value.label}}</td>
</tr> </tr>
{% endfor %} {% endfor %}
@@ -0,0 +1,59 @@
{% extends "base.html" %}
{% set live = request.query_params.live == '1' %}
{% set date = responses[0].date %}
{% block title %}
{{_("TV program")}}
{% endblock %}
{% block header %}
<app-link href="/schedule"
icon="tv">{{_("TV program")}}</app-link>
{% endblock %}
{% block content %}
<h4 class="mb-4">
<a class="icon-link {{'disabled' if date == datetime.date.today() else ''}}"
href="{{build_url(request, path=['..', date - datetime.timedelta(days=1)])}}">
<i class="bi bi-arrow-left-square"></i>
</a>
<a class="icon-link"
href="{{build_url(request, up=3)}}">
<i class="bi bi-arrow-up-square"></i>
</a>
<a class="icon-link {{'text-secondary' if not live else ''}}"
href="{{build_url(request, query={'live': 0 if live else 1})}}">
<i class="bi bi-cast"></i>
</a>
<span>{{format_date(date, DATE_FORMAT, locale=request.state.language)}}</span>
<a class="icon-link"
href="{{build_url(request, path=['..', date + datetime.timedelta(days=1)])}}">
<i class="bi bi-arrow-right-square"></i>
</a>
</h4>
{% for response in responses %}
<h5>
<span class="badge rounded-pill text-bg-secondary fs-6">{{response.channel.provider}}</span>
<span>{{response.channel.name}}</span>
</h5>
<table class="table">
<thead>
<tr>
<td></td>
<td style="width:100%"></td>
</tr>
</thead>
<tbody>
{% for value in response.values %}
<tr class="{{'d-none' if (live and not value.live) else 'table-success' if (not live and value.live) else ''}}">
<td>
<span>{{value.start.strftime('%H:%M')}}</span>&nbsp;<span class="small ms-1">({{(value.end - value.start) |
timedelta_format}})</span>
</td>
<td>{{value.label}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
{% endblock %}
@@ -3,16 +3,68 @@
{% block content %} {% block content %}
<h1>{{_("TV program")}}</h1> <h1>{{_("TV program")}}</h1>
<div class="list-group mb-5"> <form action=""
<a href="schedule/tag/today" method="get"
class="list-group-item list-group-item-action px-4"> class="mb-4">
<span class="fw-bold">Все</span> <div class="input-group mb-3">
</a> <input type="text"
{% for channel in channels %} class="form-control"
<a href="schedule/{{channel.id}}" id="query"
class="list-group-item list-group-item-action px-4"> name="query"
<span class="text-primary">{{channel.name}}</span> placeholder="{{_('Enter the channel name')}}">
</a> <input type="hidden"
class="form-control"
id="provider"
name="provider"
value="{{provider or providers[0]}}">
<button id="providerBtn"
class="btn btn-secondary dropdown-toggle"
type="text"
data-bs-toggle="dropdown"
aria-expanded="false">{{provider or providers[0]}}</button>
<ul class="dropdown-menu dropdown-menu-end">
{% for provider in providers %}
<li>
<a class="dropdown-item"
onclick="provider.value='{{provider}}'; providerBtn.innerText='{{provider}}'">{{provider}}</a>
</li>
{% endfor %} {% endfor %}
</ul>
<button class="btn btn-primary"
type="submit">{{_("Search")}}</button>
</div>
</form>
{% if channels %}
<div class="mb-4">
<schedule-channel-list value="{{channels | tojson | forceescape}}"
onclick="scheduleChannelManager.store(element)"
onadd="scheduleChannelManager.add(element)"></schedule-channel-list>
<hr>
</div> </div>
{% endif %}
<div class="mb-4">
<h3>{{_("Stored channels")}}</h3>
<schedule-channel-list id="storedChannels"
onremove="scheduleChannelManager.remove(element)"></schedule-channel-list>
</div>
<div class="mb-4">
<h3>{{_("Channel groups")}}</h3>
<ul class="list-group">
{% for group in groups %}
<schedule-channel-group value="{{group | tojson | forceescape}}"></schedule-channel-group>
{% endfor %}
</ul>
</div>
<script>
(function () {
const params = new URLSearchParams(window.location.search);
const searchQuery = params.get('query');
if (searchQuery) {
document.querySelector('#query').value = searchQuery;
}
document.addEventListener("DOMContentLoaded", (event) => {
scheduleChannelManager.load();
});
})();
</script>
{% endblock %} {% endblock %}
@@ -1,52 +0,0 @@
{% extends "base.html" %}
{% block title %}
{{_("Live broadcasts") if live else _("TV program")}} | {{format_date(response.date, 'E, d MMMM Y', locale=request.state.language)}}
{% endblock %}
{% block header %}
<span class="fs-4 text-body ms-2 me-2">/</span>
<app-link href="/schedule"
icon="tv">{{_("TV program")}}</app-link>
{% endblock %}
{% block content %}
<h4>
<a class="button {{'disabled' if response.date == datetime.date.today() else ''}}"
href="../tag/{{tag_util.create_tag('day', response.date, -1)}}">⬅️</a>
<a class="button"
href="..">⬆️</a>
<span>{{_("Live broadcasts") if live else _("TV program")}} | {{format_date(response.date, 'E, d MMMM Y', locale=request.state.language)}}</span>
<a class="button"
href="../tag/{{tag_util.create_tag('day', response.date, 1)}}">➡️</a>
</h4>
<div>
<table class="table">
<thead>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
{% for response in responses %}
{% set values = (response.values|selectattr('live') if live else response.values)|list %}
{% if values|length > 0 %}
<tr class="table-primary fs-4">
<td colspan="3">
<div>{{response.channel.name}}</div>
</td>
</tr>
{% for value in values %}
<tr class="{{'table-success' if not live and value.live else ''}}">
<td>{{value.start.strftime('%H:%M')}}</td>
<td>{{(value.end - value.start) | timedelta_format}}</td>
<td>{{value.label}}</td>
</tr>
{% endfor %}
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
+2 -6
View File
@@ -5,9 +5,7 @@ from fastapi import Cookie, Header, Request
from gallery.util import root_path from gallery.util import root_path
_translation: ContextVar[gettext.GNUTranslations | gettext.NullTranslations] = ( _translation: ContextVar[gettext.GNUTranslations | gettext.NullTranslations] = ContextVar("translation")
ContextVar("translation")
)
async def set_language( async def set_language(
@@ -19,9 +17,7 @@ async def set_language(
lang = language or accept_language.split(",")[0].split("-")[0] lang = language or accept_language.split(",")[0].split("-")[0]
try: try:
t = gettext.translation( t = gettext.translation("messages", localedir=root_path / "locales", languages=[lang])
"messages", localedir=root_path / "locales", languages=[lang]
)
except FileNotFoundError: except FileNotFoundError:
t = gettext.NullTranslations() t = gettext.NullTranslations()
+1 -92
View File
@@ -1,92 +1 @@
import datetime from .route import router
from pathlib import Path
from fastapi import APIRouter
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from babel.dates import format_date
from gallery.easel.core import AppRequest
from gallery.sketch.weather.model import WeatherResponse
from gallery.version import __version__
from ..common.util import TagType, TagUtil
from ..translation import _
from .filters import cloudness_icon, wind_direction_icon
base_dir = Path(__file__).parent
templates = Jinja2Templates(
directory=[
base_dir.parent / "common/templates",
base_dir / "templates",
]
)
templates.env.globals.update(
{
"_": _,
"version": __version__,
"format_date": format_date,
}
)
templates.env.filters["wind_direction_icon"] = wind_direction_icon
templates.env.filters["cloudness_icon"] = cloudness_icon
def build_weather_response(request: AppRequest, response: WeatherResponse):
return templates.TemplateResponse(
request=request,
name="weather.html",
context={
"tag_util": TagUtil,
"datetime": datetime,
"response": response,
},
)
router = APIRouter()
@router.get("/weather", response_class=HTMLResponse)
async def get_weather_index(request: AppRequest, query: str | None = None):
weather_api = request.app.state.api.weather
locations = (await weather_api.find_locations(query)) if query else []
return templates.TemplateResponse(
request=request,
name="index.html",
context={
"locations": locations,
},
)
@router.get("/weather/{location}", response_class=RedirectResponse)
async def get_weather_default(location: str):
return RedirectResponse(f"{location}/tag/today")
@router.get("/weather/{location}/day/{date}", response_class=HTMLResponse)
async def get_weather_day(request: AppRequest, location: str, date: datetime.date):
weather_api = request.app.state.api.weather
response = await weather_api.get_day(location, date)
return build_weather_response(request, response)
@router.get("/weather/{location}/days/{days}", response_class=HTMLResponse)
async def get_weather_days(request: AppRequest, location: str, days: int):
weather_api = request.app.state.api.weather
response = await weather_api.get_days(location, days)
return build_weather_response(request, response)
@router.get("/weather/{location}/tag/{tag}", response_class=HTMLResponse)
async def get_weather_tag(request: AppRequest, location: str, tag: str):
tag_value = TagUtil.parse_tag(tag)
weather_api = request.app.state.api.weather
if tag_value.type == TagType.DAY:
response = await weather_api.get_day(location, tag_value.date)
elif tag_value.type == TagType.DAYS:
response = await weather_api.get_days(location, tag_value.days)
else:
raise ValueError(tag)
return build_weather_response(request, response)
+60 -27
View File
@@ -1,3 +1,7 @@
import datetime
from markupsafe import Markup
from gallery.sketch.weather.model import ( from gallery.sketch.weather.model import (
Cloudness, Cloudness,
Precipitation, Precipitation,
@@ -5,44 +9,73 @@ from gallery.sketch.weather.model import (
WindDirection, WindDirection,
WindDirectionDeg, WindDirectionDeg,
) )
from gallery.util import root_path
def wind_direction_icon(wind_direction_deg: float) -> str: def wind_direction_icon(wind_direction_deg: float) -> str:
wind_direction = WindDirectionDeg(wind_direction_deg).direction wind_direction = WindDirectionDeg(wind_direction_deg).direction
return { if wind_direction == WindDirection.CALM:
WindDirection.N: "⬇️", return "wind-calm"
WindDirection.NE: "↙️", else:
WindDirection.E: "⬅️", return f"wind-from-{wind_direction.name.lower()}"
WindDirection.SE: "↖️",
WindDirection.S: "⬆️",
WindDirection.SW: "↗️",
WindDirection.W: "➡️",
WindDirection.NW: "↘️",
WindDirection.CALM: "",
}.get(wind_direction, wind_direction)
def cloudness_icon(sky: Sky) -> list[str]: def cloudness_icon(sky: Sky, date: datetime.datetime, period: str) -> list[str]:
day = (3 < date.hour < 22) if period == "day" else True
day_prefix = "day" if day else "night-alt"
main_icon = "" main_icon = ""
if sky.thunder: if sky.thunder:
if sky.cloudness == Cloudness.CLEAR: main_icon = {
main_icon = "🌩️" Precipitation.NO: "lightning",
if sky.precipitation == Precipitation.NO: Precipitation.SMALL_RAIN: "storm-showers",
main_icon = "⚡" Precipitation.RAIN: "thunderstorm",
else: Precipitation.HEAVY_RAIN: "thunderstorm",
main_icon = "⛈️" Precipitation.SHOWER: "thunderstorm",
Precipitation.SNOW: "storm-showers",
Precipitation.HEAVY_SNOW: "storm-showers",
}[sky.precipitation]
if sky.cloudness == Cloudness.PARTLY_CLOUDY:
main_icon = f"{day_prefix}-{main_icon}"
elif sky.precipitation == Precipitation.NO: elif sky.precipitation == Precipitation.NO:
main_icon = { main_icon = {
Cloudness.CLEAR: "☀️", Cloudness.CLEAR: "day-sunny" if day else "night-clear",
Cloudness.PARTLY_CLOUDY: "🌤️", Cloudness.PARTLY_CLOUDY: f"{day_prefix}-cloudy",
Cloudness.CLOUDY: "⛅", Cloudness.CLOUDY: "cloud",
Cloudness.MAINLY_CLOUDY: "☁️", Cloudness.MAINLY_CLOUDY: "cloudy",
}[sky.cloudness] }[sky.cloudness]
elif sky.precipitation in [Precipitation.SNOW, Precipitation.HEAVY_SNOW]:
main_icon = "🌨️"
else: else:
main_icon = "🌧️" main_icon = {
Precipitation.SMALL_RAIN: "showers",
Precipitation.RAIN: "rain-mix",
Precipitation.HEAVY_RAIN: "rain",
Precipitation.SHOWER: "rain",
Precipitation.SNOW: "snow",
Precipitation.HEAVY_SNOW: "snow",
Precipitation.HAIL: "hail",
}[sky.precipitation]
if sky.cloudness == Cloudness.PARTLY_CLOUDY:
main_icon = f"{day_prefix}-{main_icon}"
icons = [main_icon] icons = [main_icon]
if sky.fog:
icons.append("🌫️")
return icons return icons
class WeatherIconBundle:
def __init__(self):
self._icon_path = root_path / "static/dist/weather-icons/icons"
self._cache = {}
def _load_icon(self, icon: str) -> Markup:
icon_file = self._icon_path / f"wi-{icon}.svg"
return Markup(icon_file.read_text())
def get(self, icon: str) -> Markup:
if icon not in self._cache:
self._cache[icon] = self._load_icon(icon)
return self._cache[icon]
WEATHER_ICON_BUNDLE = WeatherIconBundle()
def weather_icon_svg(icon: str) -> Markup:
return WEATHER_ICON_BUNDLE.get(icon)
+81
View File
@@ -0,0 +1,81 @@
from pathlib import Path
from typing import Literal
from fastapi import APIRouter
from fastapi.responses import HTMLResponse, RedirectResponse
from gallery.easel.core import AppRequest
from gallery.easel.depends.api import api_resolver
from gallery.easel.depends.date import DateDepends
from gallery.easel.depends.weather import WeatherApiDepends
from gallery.sketch.weather.api import WeatherApi
from gallery.sketch.weather.model import WeatherResponse
from ..common.utils.template import build_templates
from .filters import cloudness_icon, weather_icon_svg, wind_direction_icon
def context_procesor(request: AppRequest) -> dict:
return {
"providers": request.app.state.api.get_api_providers(WeatherApi),
}
templates = build_templates(
Path(__file__).parent / "templates",
{
"wind_direction_icon": wind_direction_icon,
"cloudness_icon": cloudness_icon,
"weather_icon_svg": weather_icon_svg,
},
context_procesor,
)
def build_weather_response(request: AppRequest, response: WeatherResponse):
return templates.TemplateResponse(
request=request,
name="weather.html",
context={"response": response},
)
router = APIRouter(prefix="/weather")
@router.get("/", response_class=HTMLResponse)
async def get_weather_index(request: AppRequest, provider: str | None = None, query: str | None = None):
if query and provider:
weather_api = api_resolver(WeatherApi)(request, provider)
locations = await weather_api.find_locations(query)
else:
locations = []
return templates.TemplateResponse(
request=request,
name="index.html",
context={"locations": [item.model_dump() for item in locations]},
)
@router.get("/{provider}/{location}", response_class=RedirectResponse)
async def get_weather(location: str):
return RedirectResponse(f"{location}/day/today")
@router.get("/{provider}/{location}/days/{days}", response_class=HTMLResponse)
async def get_weather_days(request: AppRequest, weather_api: WeatherApiDepends, location: str, days: int):
response = await weather_api.get_days(location, days)
return build_weather_response(request, response)
# TODO: tag mode route deprecated, used in tizen app
@router.get("/{provider}/{location}/{mode:str}/{date}", response_class=HTMLResponse)
async def get_weather_day(
request: AppRequest,
weather_api: WeatherApiDepends,
location: str,
date: DateDepends,
mode: Literal["day", "tag"], # pylint:disable=unused-argument
):
response = await weather_api.get_day(location, date)
return build_weather_response(request, response)
@@ -12,63 +12,52 @@
id="query" id="query"
name="query" name="query"
placeholder="{{_('Enter the city name')}}"> placeholder="{{_('Enter the city name')}}">
<input type="hidden"
class="form-control"
id="provider"
name="provider"
value="{{provider or providers[0]}}">
<button id="providerBtn"
class="btn btn-secondary dropdown-toggle"
type="text"
data-bs-toggle="dropdown"
aria-expanded="false">{{provider or providers[0]}}</button>
<ul class="dropdown-menu dropdown-menu-end">
{% for provider in providers %}
<li>
<a class="dropdown-item"
onclick="provider.value='{{provider}}'; providerBtn.innerText='{{provider}}'">{{provider}}</a>
</li>
{% endfor %}
</ul>
<button class="btn btn-primary" <button class="btn btn-primary"
type="submit">{{_("Search")}}</button> type="submit">{{_("Search")}}</button>
</div> </div>
</form> </form>
<ul id="locations" {% if locations %}
class="list-group mb-5"> <div class="mb-4">
{% for location in locations %} <weather-location-list value="{{locations | tojson | forceescape}}"
<a href="weather/{{location.id}}" onclick="weatherLocationManager.store(element)"
class="list-group-item list-group-item-action px-4" onadd="weatherLocationManager.add(element)"></weather-location-list>
onclick="saveLocation({id:'{{location.id}}', name:'{{location.name}}'});"> <hr>
<span class="fi fi-{{location.country_code}} me-1"></span> </div>
<span class="text-primary">{{location.name}}</span> {% endif %}
<span class="small ms-1 text-secondary"> <div class="mb-4">
{{location.country}}, {{location.district}}, {{location.subdistrict}} <h3>{{_("Stored locations")}}</h3>
</span> <weather-location-list id="storedLocations"
<span></span> onremove="weatherLocationManager.remove(element)"></weather-location-list>
</a> </div>
{% endfor %}
</ul>
<script> <script>
(function () { (function () {
document.loadLocations = () => {
const locations = JSON.parse(window.localStorage.getItem('locations') || '{}');
const container = document.querySelector('#locations');
container.innerHTML = '';
for (const [id, name] of Object.entries(locations)) {
const element = document.createElement('a');
element.href = `weather/${id}`;
element.className = 'list-group-item list-group-item-action px-4 d-flex justify-content-between align-items-start';
element.innerHTML = `
<span class="text-primary me-auto">${name}</span>
<span class="text-danger" onclick="removeLocation('${id}'); event.preventDefault();">&#x2715;</span>
`;
container.appendChild(element);
}
}
document.saveLocation = (location) => {
const locations = JSON.parse(window.localStorage.getItem('locations') || '{}');
locations[location.id] = location.name;
window.localStorage.setItem('locations', JSON.stringify(locations));
}
document.removeLocation = (id) => {
const locations = JSON.parse(window.localStorage.getItem('locations') || '{}');
delete locations[id];
window.localStorage.setItem('locations', JSON.stringify(locations));
document.loadLocations();
}
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
const searchQuery = params.get('query'); const searchQuery = params.get('query');
if (searchQuery) { if (searchQuery) {
document.querySelector('#query').value = searchQuery; document.querySelector('#query').value = searchQuery;
} else {
document.loadLocations();
} }
document.addEventListener("DOMContentLoaded", (event) => {
weatherLocationManager.load();
});
})(); })();
</script> </script>
{% endblock %} {% endblock %}
@@ -1,24 +1,37 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}{{_("Weather")}} | {{response.location}} | {{response.date.strftime('%a, %d %B %Y')}}{% endblock %} {% set date = response.date %}
{% block title %}{{_("Weather")}} | {{response.location}} | {{format_date(response.date, DATE_FORMAT,
locale=request.state.language)}}{% endblock %}
{% block header %} {% block header %}
<span class="fs-4 text-body ms-2 me-2">/</span> <app-link href="/weather"
<app-link href="/weather" icon="brightness-high">{{_("Weather")}}</app-link> icon="brightness-high">{{_("Weather")}}</app-link>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<h4> <h4>
{% if response.period == 'day' %} {% if response.period == 'day' %}
<a class="button {{'disabled' if response.date == datetime.date.today() else ''}}" <a class="icon-link {{'disabled' if date == datetime.date.today() else ''}}"
href="../tag/{{tag_util.create_tag('day', response.date, -1)}}">⬅️</a> href="{{build_url(request, path=['..', date - datetime.timedelta(days=1)])}}">
<a class="button" <i class="bi bi-arrow-left-square"></i>
href="../tag/days-10">⬆️</a> </a>
<span>{{response.location}} | {{format_date(response.date, 'E, d MMMM Y', locale=request.state.language)}}</span> <a class="icon-link"
<a class="button" href="{{build_url(request, path=['..', '..', 'days', '10'])}}">
href="../tag/{{tag_util.create_tag('day', response.date, 1)}}">➡️</a> <i class="bi bi-arrow-up-square"></i>
</a>
<span class="badge rounded-pill text-bg-secondary fs-6">{{provider}}</span>
<span>{{response.location}} | {{format_date(response.date, DATE_FORMAT, locale=request.state.language)}}</span>
<a class="icon-link"
href="{{build_url(request, path=['..', date + datetime.timedelta(days=1)])}}">
<i class="bi bi-arrow-right-square"></i>
</a>
{% endif %} {% endif %}
{% if response.period == 'days' %} {% if response.period == 'days' %}
<span>{{response.location}} | {{format_date(response.date, 'E, d MMMM Y', locale=request.state.language)}}</span> <span class="badge rounded-pill text-bg-secondary fs-6">{{provider}}</span>
<span>{{response.location}} | {{format_date(response.date, DATE_FORMAT, locale=request.state.language)}}</span>
<span>- {{format_date(response.date + datetime.timedelta(days=(response.values | length - 1)), DATE_FORMAT,
locale=request.state.language)}}</span>
{% endif %} {% endif %}
</h4> </h4>
<div class="table-responsive"> <div class="table-responsive">
@@ -37,7 +50,7 @@
{% if response.period == 'days' %} {% if response.period == 'days' %}
<td class="date {{'now' if value.date.date() == datetime.date.today() else ''}}"> <td class="date {{'now' if value.date.date() == datetime.date.today() else ''}}">
<span class="value {{'text-danger' if value.date.weekday() in [5,6] else ''}}"> <span class="value {{'text-danger' if value.date.weekday() in [5,6] else ''}}">
<a href="../tag/{{tag_util.create_tag('day', value.date.date())}}"> <a href="{{build_url(request, path=['..', '..', 'day', value.date.date()])}}">
{{format_date(value.date, 'E d', locale=request.state.language)}} {{format_date(value.date, 'E d', locale=request.state.language)}}
</a> </a>
</span> </span>
@@ -54,9 +67,12 @@
</tr> </tr>
<tr> <tr>
{% for value in response.values %} {% for value in response.values %}
<td class="cloudness"> <td class="cloudness"
{% for icon in value.sky | cloudness_icon %} data-bs-toggle="tooltip"
<div class="icon">{{icon}}</div> data-bs-title="{{ value.sky }}">
{% for icon in value.sky | cloudness_icon(value.date, response.period) %}
<div class="wi-svg wi-l wi-border"
style="margin: 0 auto;">{{ icon | weather_icon_svg }}</div>
{% endfor %} {% endfor %}
</td> </td>
{% endfor %} {% endfor %}
@@ -89,8 +105,11 @@
</tr> </tr>
<tr> <tr>
{% for value in response.values %} {% for value in response.values %}
<td class="wind"> <td class="wind"
<span class="icon">{{value.wind_direction | wind_direction_icon}}</span> data-bs-toggle="tooltip"
data-bs-title="{{ value.wind_direction }}">
<div class="wi-svg wi-s wi-{{value.wind_direction | wind_direction_icon}}"
style="margin: 0 auto;">{{ 'wind-deg' | weather_icon_svg }}</div>
</td> </td>
{% endfor %} {% endfor %}
</tr> </tr>
@@ -106,7 +125,7 @@
<td class="wind" <td class="wind"
style="background-color: rgba(128, 128, 128, {{value.wind_speed * 0.05}});"> style="background-color: rgba(128, 128, 128, {{value.wind_speed * 0.05}});">
<span class="speed">{{value.wind_speed}}</span> <span class="speed">{{value.wind_speed}}</span>
{% if value.wind_gust != value.wind_speed %} {% if value.wind_gust != value.wind_speed and value.wind_gust > 0 %}
<span class="gust"> <span class="gust">
({{value.wind_gust}}) ({{value.wind_gust}})
</span> </span>
@@ -125,7 +144,7 @@
{% for value in response.values %} {% for value in response.values %}
<td class="precipitation" <td class="precipitation"
style="background-color: rgba(0, 128, 255, {{value.precipitation * 0.1}});"> style="background-color: rgba(0, 128, 255, {{value.precipitation * 0.1}});">
<span class="value">{{value.precipitation or ' '}}</span> <span class="value">{{(value.precipitation | round(2)) if value.precipitation else ' '}}</span>
</td> </td>
{% endfor %} {% endfor %}
</tr> </tr>
@@ -158,7 +177,7 @@
{% for value in response.values %} {% for value in response.values %}
<td class="humidity" <td class="humidity"
style="background-color: rgba(128, 128, 255, {{value.humidity * 0.005}});"> style="background-color: rgba(128, 128, 255, {{value.humidity * 0.005}});">
<span class="value">{{value.humidity}}</span> {% if value.humidity > -1%}<span class="value">{{value.humidity}}</span>{% endif %}
</td> </td>
{% endfor %} {% endfor %}
</tr> </tr>
+4
View File
@@ -7,7 +7,9 @@ from gallery.easel import build_app
from gallery.painting.gismeteo.api import GismeteoApi from gallery.painting.gismeteo.api import GismeteoApi
from gallery.painting.matchtv.api import MatchTvApi from gallery.painting.matchtv.api import MatchTvApi
from gallery.painting.openweather.api import OpenWeatherApi from gallery.painting.openweather.api import OpenWeatherApi
from gallery.painting.rp5.api import RP5WeatherApi
from gallery.painting.yandextv.api import YandexTvApi from gallery.painting.yandextv.api import YandexTvApi
from gallery.painting.yandexweather.api import YandexWeatherApi
from gallery.sketch.bundle import ApiBundle from gallery.sketch.bundle import ApiBundle
from gallery.sketch.schedule.cached import CachedScheduleApi from gallery.sketch.schedule.cached import CachedScheduleApi
from gallery.sketch.weather.cached import CachedWeatherApi from gallery.sketch.weather.cached import CachedWeatherApi
@@ -18,6 +20,8 @@ api = ApiBundle(
CachedScheduleApi(MatchTvApi()), CachedScheduleApi(MatchTvApi()),
CachedWeatherApi(GismeteoApi()), CachedWeatherApi(GismeteoApi()),
CachedWeatherApi(OpenWeatherApi()), CachedWeatherApi(OpenWeatherApi()),
CachedWeatherApi(YandexWeatherApi()),
CachedWeatherApi(RP5WeatherApi()),
] ]
) )
app = build_app(api) app = build_app(api)
+36 -18
View File
@@ -1,36 +1,40 @@
import datetime import datetime
import json import json
import logging import logging
from os import environ
from typing import Any from typing import Any
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from fastapi import HTTPException, status
from gallery.sketch.source import ApiSource from gallery.sketch.source import ApiSource
from gallery.sketch.weather.api import WeatherApi from gallery.sketch.weather.api import WeatherApi
from gallery.sketch.weather.model import Location, WeatherResponse, WeatherValue from gallery.sketch.weather.model import Location, WeatherResponse, WeatherValue
from gallery.sketch.weather.util import merge_weather_values
from . import datehelp
from .parser import DAYS_PARSER, LOCATION_PARSER, ONE_DAY_PARSER, ROW_PARSERS from .parser import DAYS_PARSER, LOCATION_PARSER, ONE_DAY_PARSER, ROW_PARSERS
logger = logging.getLogger("gismeteo") logger = logging.getLogger("gismeteo")
def format_date(date: datetime.date) -> str:
today = datetime.date.today()
days = (date - today).days
if days == 0:
return "today"
elif days == 1:
return "tomorrow"
else:
return f"{days + 1}-day"
class GismeteoApi(WeatherApi): class GismeteoApi(WeatherApi):
PROVIDER = "gismeteo" PROVIDER = "gismeteo"
SOURCE = ApiSource(
def _build_source(self) -> ApiSource:
return ApiSource(
"https://www.gismeteo.ru", "https://www.gismeteo.ru",
cookies={ cookies={"xauth": auth} if (auth := environ.get("GISMETEO_AUTH")) else None,
"cf_clearance": (
"zPj8qeaYZWp5BUZsWIRD7kd32s59IDWWaVvD7GGf6b4-1724254262-1.2.1.1-"
"R1PaHoqlm4OEgHfrOg6oAJmVmFJ7053JI_QDjIFlCAmbNY0oyw1J4QtgmEkAkTWF4C99X5hpXmZB2en."
"9Ey3NL0kzaE10UGBHPli5OLxHNKC3wQ34xmxTxg6GcKouXOPRgqo92lVRpQP7ghvDmvvT_"
"S6YXDbRonkamptWhZiAsIhsnIQg2Mt7Lk1fxSEVbaey_RXVQBvaR2ofiFgIavcbQPRFSvJ."
"Ct_FujmymTAZWh1XHTptK32kur81NXyPuARThetOKQm8AklaMa855Oom6Bms1a4F9b0yEHSd2inA4j3FR7uauu8hhwO0Z2goa3."
"ktpXXAQLz6dm.fBEWIHD7wooda15X57tCcDOely4hxhO4LK2lIH6TbOr."
"rZQAiRRhltHiCizP1Ou2SiF_81lb1umoDh739tQD1cnw_USnL."
"JwTHvkB00ZnaHRMi4FCBrsKIE0NxJO6kiv1QANqumzf5.8_pSIGRo2cKeO8xCydduDNFbStdOmLR6FU7ZKqVu"
)
},
) )
def _parse_oneday(self, date: datetime.date, data: str) -> WeatherResponse: def _parse_oneday(self, date: datetime.date, data: str) -> WeatherResponse:
@@ -44,6 +48,12 @@ class GismeteoApi(WeatherApi):
result.append({}) result.append({})
result[index][parser.KEY] = value result[index][parser.KEY] = value
values = [WeatherValue(**item) for item in result] values = [WeatherValue(**item) for item in result]
# group values by 3 hours
if len(values) > 8:
n = 3
values = [
merge_weather_values(values[i].date, values[i : i + n], "average") for i in range(0, len(values), n)
]
return WeatherResponse( return WeatherResponse(
location=location or "n/a", location=location or "n/a",
date=date, date=date,
@@ -74,7 +84,7 @@ class GismeteoApi(WeatherApi):
latitude = 52.968498 latitude = 52.968498
longitude = 36.0695 longitude = 36.0695
data = json.loads( data = json.loads(
await self.SOURCE.request( await self.source.request(
f"mq/city/q/?q={query}&geo={geo}&latitude={latitude}&longitude={longitude}&limit=10" f"mq/city/q/?q={query}&geo={geo}&latitude={latitude}&longitude={longitude}&limit=10"
) )
) )
@@ -84,11 +94,14 @@ class GismeteoApi(WeatherApi):
Location( Location(
id=f"{item['slug']}-{item['id']}", id=f"{item['slug']}-{item['id']}",
name=item["translations"]["kk"]["city"]["name"], name=item["translations"]["kk"]["city"]["name"],
provider=self.provider,
lat=item["coordinates"]["latitude"], lat=item["coordinates"]["latitude"],
lon=item["coordinates"]["longitude"], lon=item["coordinates"]["longitude"],
country=item["translations"]["kk"]["country"]["name"], country=item["translations"]["kk"]["country"]["name"],
country_code=item["country"]["code"].lower(), country_code=item["country"]["code"].lower(),
district=item["translations"]["kk"]["district"]["name"], district=(
item["translations"]["kk"]["district"]["name"] if item["translations"]["kk"]["district"] else ""
),
subdistrict=( subdistrict=(
item["translations"]["kk"]["subdistrict"]["name"] item["translations"]["kk"]["subdistrict"]["name"]
if "subdistrict" in item["translations"]["kk"] if "subdistrict" in item["translations"]["kk"]
@@ -99,9 +112,14 @@ class GismeteoApi(WeatherApi):
return result return result
async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse: async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse:
data = await self.SOURCE.request(f"weather-{location_id}/{datehelp.dump(date)}") max_date = datetime.date.today() + datetime.timedelta(days=9)
if date > max_date:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail={"max_date": max_date.strftime("%Y-%m-%d")}
)
data = await self.source.request(f"weather-{location_id}/{format_date(date)}")
return self._parse_oneday(date, data) return self._parse_oneday(date, data)
async def get_days(self, location_id: str, days: int) -> WeatherResponse: async def get_days(self, location_id: str, days: int) -> WeatherResponse:
data = await self.SOURCE.request(f"weather-{location_id}/{days}-days") data = await self.source.request(f"weather-{location_id}/{days}-days")
return self._parse_manydays(data) return self._parse_manydays(data)
-30
View File
@@ -1,30 +0,0 @@
from typing import Generic, Iterable, Optional, TypeVar
from bs4 import Tag
T = TypeVar("T")
class WidgetParser:
def parse_widget(self, tag: Tag) -> Tag:
raise NotImplementedError
class BaseWidgetParser(WidgetParser):
SELECT: str
def __init__(self, select: Optional[str] = None):
super().__init__()
self._select = select or self.SELECT
def parse_widget(self, tag: Tag) -> Tag:
widget = tag.select_one(self._select)
if widget is None:
raise ValueError(self._select)
return widget
class RowParser(Generic[T]):
KEY: str
def parse_row(self, tag: Tag) -> Iterable[T]:
raise NotImplementedError
-39
View File
@@ -1,39 +0,0 @@
import datetime
from enum import Enum
import dateparser
import dateparser.date_parser
class Day(str, Enum):
TODAY = "today"
TOMORROW = "tomorrow"
DAY_3 = "3-day"
DAY_4 = "4-day"
DAY_5 = "5-day"
def parse(value: str) -> datetime.date:
if value in ["today", "mock"]:
return datetime.date.today()
elif value == "tomorrow":
return datetime.date.today() + datetime.timedelta(days=1)
elif value.endswith("-day"):
days = int(value.split("-")[0]) - 1
return datetime.date.today() + datetime.timedelta(days=days)
else:
date = dateparser.parse(value)
if date is None:
raise ValueError(value)
return date.date()
def dump(date: datetime.date) -> str:
today = datetime.date.today()
days = (date - today).days
if days == 0:
return "today"
elif days == 1:
return "tomorrow"
else:
return f"{days + 1}-day"
+75 -50
View File
@@ -1,6 +1,7 @@
import datetime import datetime
import logging
import re import re
from typing import Iterable from typing import Generic, Iterable, Optional, TypeVar
import dateparser import dateparser
from bs4 import Tag from bs4 import Tag
@@ -10,10 +11,39 @@ from gallery.sketch.weather.model import (
Precipitation, Precipitation,
Sky, Sky,
WindDirection, WindDirection,
WindDirectionDeg,
) )
from gallery.sketch.weather.parser import ParseError, parse_wind_direction
logger = logging.getLogger("gismeteo")
T = TypeVar("T")
class WidgetParser:
def parse_widget(self, tag: Tag) -> Tag:
raise NotImplementedError
class BaseWidgetParser(WidgetParser):
SELECT: str
def __init__(self, select: Optional[str] = None):
super().__init__()
self._select = select or self.SELECT
def parse_widget(self, tag: Tag) -> Tag:
widget = tag.select_one(self._select)
if widget is None:
raise ValueError(self._select)
return widget
class RowParser(Generic[T]):
KEY: str
def parse_row(self, tag: Tag) -> Iterable[T]:
raise NotImplementedError
from .core import BaseWidgetParser, RowParser
ONE_DAY_PARSER = BaseWidgetParser(".widget.widget-oneday .widget-items") ONE_DAY_PARSER = BaseWidgetParser(".widget.widget-oneday .widget-items")
DAYS_PARSER = BaseWidgetParser(".widget.widget-days .widget-items") DAYS_PARSER = BaseWidgetParser(".widget.widget-days .widget-items")
@@ -36,21 +66,22 @@ class DateParser(RowParser[datetime.datetime]):
KEY = "date" KEY = "date"
def parse_row(self, tag: Tag) -> Iterable[datetime.datetime]: def parse_row(self, tag: Tag) -> Iterable[datetime.datetime]:
datetime_date_tag = tag.select_one( datetime_time_row = tag.select_one(".widget-row.widget-row-datetime-time")
".widget-row.widget-row-datetime-date > .row-item" if datetime_time_row:
) for item in datetime_time_row.select(".row-item > time-value"):
if datetime_date_tag: timestamp = int(item.attrs["timestamp"])
date_str = datetime_date_tag.find(text=True, recursive=False).text time = datetime.datetime.fromtimestamp(timestamp)
date = dateparser.parse(date_str, languages=["ru"])
for item in tag.select(".widget-row.widget-row-datetime-time > .row-item"):
time_str = item.text
time = dateparser.parse(time_str, languages=["ru"])
time = time.replace(year=date.year, month=date.month, day=date.day)
yield time yield time
else: else:
month = None
for item in tag.select(".widget-row.widget-row-date > .row-item"): for item in tag.select(".widget-row.widget-row-date > .row-item"):
date_str = item.text date_str = item.text
date = dateparser.parse(date_str, languages=["ru"]) date = dateparser.parse(date_str, languages=["ru"])
if date is None:
raise ParseError.invalid_date(date_str)
if month and month > date.month:
date = date.replace(month=month)
month = date.month
yield date yield date
@@ -59,6 +90,7 @@ class SkyParser(RowParser[Sky]):
CLOUDNESS_MAP: dict[str, Cloudness] = { CLOUDNESS_MAP: dict[str, Cloudness] = {
"ясно": Cloudness.CLEAR, "ясно": Cloudness.CLEAR,
"безоблачно": Cloudness.CLEAR,
"малооблачно": Cloudness.PARTLY_CLOUDY, "малооблачно": Cloudness.PARTLY_CLOUDY,
"облачно": Cloudness.CLOUDY, "облачно": Cloudness.CLOUDY,
"пасмурно": Cloudness.MAINLY_CLOUDY, "пасмурно": Cloudness.MAINLY_CLOUDY,
@@ -66,8 +98,11 @@ class SkyParser(RowParser[Sky]):
PRECIPITATION_MAP: dict[str, Precipitation] = { PRECIPITATION_MAP: dict[str, Precipitation] = {
"без осадков": Precipitation.NO, "без осадков": Precipitation.NO,
"без существенных осадков": Precipitation.NO,
"небольшой дождь": Precipitation.SMALL_RAIN, "небольшой дождь": Precipitation.SMALL_RAIN,
"сильный дождь": Precipitation.HEAVY_RAIN, "сильный дождь": Precipitation.HEAVY_RAIN,
"очень сильный дождь": Precipitation.HEAVY_RAIN,
"ливневый дождь": Precipitation.SHOWER,
"дождь": Precipitation.RAIN, "дождь": Precipitation.RAIN,
"ливень": Precipitation.SHOWER, "ливень": Precipitation.SHOWER,
"снег": Precipitation.SNOW, "снег": Precipitation.SNOW,
@@ -78,24 +113,37 @@ class SkyParser(RowParser[Sky]):
"сильный снег с дождём": Precipitation.HEAVY_SNOW, "сильный снег с дождём": Precipitation.HEAVY_SNOW,
"небольшой снег с дождём": Precipitation.SNOW, "небольшой снег с дождём": Precipitation.SNOW,
"небольшой мокрый снег": Precipitation.SNOW, "небольшой мокрый снег": Precipitation.SNOW,
"град": Precipitation.HAIL,
} }
THUNDER = {"гроза"}
FOG = {"дымка", "туман"}
@classmethod
def _detect_flag(cls, values: set[str], flag_values: set[str]) -> tuple[set[str], bool]:
result_values = values - flag_values
return result_values, len(result_values) < len(values)
def parse_row(self, tag: Tag) -> Iterable[Sky]: def parse_row(self, tag: Tag) -> Iterable[Sky]:
for item in tag.select(".widget-row[data-row=icon-tooltip] > .row-item"): for item in tag.select(".widget-row[data-row=icon-tooltip] > .row-item"):
sky_str = item.attrs["data-tooltip"] sky_str = item.attrs["data-tooltip"]
values = {item.strip().lower() for item in sky_str.split(",")} values = {item.strip().lower() for item in sky_str.split(",")}
cloudness = Cloudness.CLEAR cloudness = Cloudness.CLEAR
precipitation = Precipitation.NO precipitation = Precipitation.NO
thunder = "гроза" in values values, thunder = self._detect_flag(values, self.THUNDER)
fog = "дымка" in values values, fog = self._detect_flag(values, self.FOG)
for k, v in self.CLOUDNESS_MAP.items(): for k, v in self.CLOUDNESS_MAP.items():
if k in values: if k in values:
cloudness = v cloudness = v
values.remove(k)
break break
for k, v in self.PRECIPITATION_MAP.items(): for k, v in self.PRECIPITATION_MAP.items():
if k in values: if k in values:
precipitation = v precipitation = v
values.remove(k)
break break
if values:
logger.warning("unknown sky values: %s:", values)
yield Sky( yield Sky(
cloudness=cloudness, cloudness=cloudness,
precipitation=precipitation, precipitation=precipitation,
@@ -108,21 +156,15 @@ class TemperatureParser(RowParser[list[int]]):
KEY = "temperature" KEY = "temperature"
def parse_row(self, tag: Tag) -> Iterable[list[int]]: def parse_row(self, tag: Tag) -> Iterable[list[int]]:
for item in tag.select( for item in tag.select(".widget-row-chart[data-row=temperature-air] > .chart > .values > .value"):
".widget-row-chart[data-row=temperature-air] > .chart > .values > .value" yield [int(value.attrs["value"]) for value in item.select("temperature-value")]
):
yield [
int(value.attrs["value"]) for value in item.select("temperature-value")
]
class WindSpeedParser(RowParser[int]): class WindSpeedParser(RowParser[int]):
KEY = "wind_speed" KEY = "wind_speed"
def parse_row(self, tag: Tag) -> Iterable[int]: def parse_row(self, tag: Tag) -> Iterable[int]:
for item in tag.select( for item in tag.select(".widget-row-wind > .row-item > .wind-speed > speed-value"):
".widget-row-wind > .row-item > .wind-speed > speed-value"
):
yield int(item.attrs["value"]) yield int(item.attrs["value"])
@@ -138,46 +180,29 @@ class WindGustParser(RowParser[int]):
class WindDirectionParser(RowParser[WindDirection]): class WindDirectionParser(RowParser[WindDirection]):
KEY = "wind_direction" KEY = "wind_direction"
WIND_DIRECTION_MAP: dict[str, WindDirection] = {
"—": WindDirection.CALM,
"штиль": WindDirection.CALM,
"с": WindDirection.N,
"св": WindDirection.NE,
"в": WindDirection.E,
"юв": WindDirection.SE,
"ю": WindDirection.S,
"юз": WindDirection.SW,
"з": WindDirection.W,
"сз": WindDirection.NW,
}
def parse_row(self, tag: Tag) -> Iterable[float]: def parse_row(self, tag: Tag) -> Iterable[float]:
for item in tag.select( for item in tag.select(".widget-row-wind > .row-item > .wind-speed > .wind-direction"):
".widget-row-wind > .row-item > .wind-speed > .wind-direction"
):
wind_direction_str = item.text.lower().strip() wind_direction_str = item.text.lower().strip()
yield WindDirectionDeg.from_direction( yield parse_wind_direction(wind_direction_str)
self.WIND_DIRECTION_MAP[wind_direction_str]
).value
class PrecipitationParser(RowParser[float]): class PrecipitationParser(RowParser[float]):
KEY = "precipitation" KEY = "precipitation"
def parse_row(self, tag: Tag) -> Iterable[float]: def parse_row(self, tag: Tag) -> Iterable[float]:
for item in tag.select( for item in tag.select(".widget-row[data-row=precipitation-bars] > .row-item"):
".widget-row[data-row=precipitation-bars] > .row-item > .item-unit" value = item.select_one("precipitation-value")
): if value:
yield float(item.text.replace(",", ".")) yield float(value.attrs["value"])
else:
yield 0
class PressureParser(RowParser[list[int]]): class PressureParser(RowParser[list[int]]):
KEY = "pressure" KEY = "pressure"
def parse_row(self, tag: Tag) -> Iterable[list[int]]: def parse_row(self, tag: Tag) -> Iterable[list[int]]:
for item in tag.select( for item in tag.select(".widget-row-chart[data-row=pressure] > .chart > .values > .value"):
".widget-row-chart[data-row=pressure] > .chart > .values > .value"
):
yield [int(value.attrs["value"]) for value in item.select("pressure-value")] yield [int(value.attrs["value"]) for value in item.select("pressure-value")]
+28 -38
View File
@@ -1,10 +1,9 @@
import datetime import datetime
import json
import logging import logging
from bs4 import BeautifulSoup
from gallery.sketch.schedule.api import ScheduleApi from gallery.sketch.schedule.api import ScheduleApi
from gallery.sketch.schedule.model import Channel, ChannelId, Schedule, ScheduleValue from gallery.sketch.schedule.model import Channel, Schedule, ScheduleValue
from gallery.sketch.source import ApiSource from gallery.sketch.source import ApiSource
logger = logging.getLogger("matchtv") logger = logging.getLogger("matchtv")
@@ -12,45 +11,34 @@ logger = logging.getLogger("matchtv")
class MatchTvApi(ScheduleApi): class MatchTvApi(ScheduleApi):
PROVIDER = "matchtv" PROVIDER = "matchtv"
SOURCE = ApiSource("https://matchtv.ru")
async def get_channels(self) -> list[ChannelId]: def _build_source(self) -> ApiSource:
return [ return ApiSource("https://matchtv.ru")
ChannelId.MATCH_TV,
ChannelId.MATCH_IGRA,
ChannelId.MATCH_ARENA,
ChannelId.MATCH_FUTBOL_1,
ChannelId.MATCH_FUTBOL_2,
ChannelId.MATCH_FUTBOL_3,
ChannelId.MATCH_STRANA,
]
async def get_channel_schedule( async def find_channels(self, query: str) -> list[Channel]:
self, channel_id: ChannelId, date: datetime.date endpoint = "api/v1/channels"
) -> Schedule: data = json.loads(await self.source.request(endpoint))
endpoint = f"tvguide/{channel_id}?date={date:%Y%m%d}" result = []
data = await self.SOURCE.request(endpoint) query = query.lower()
soup = BeautifulSoup(data, features="html.parser") for item in data["result"]:
if query in item["name"].lower() or query in item["alias"]:
channel_id = item["alias"]
name = item["name"].split("|")[0].strip()
result.append(Channel(id=channel_id, name=name, provider=self.provider))
return result
async def get_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
endpoint = f"api/v1/channels/{channel_id}/tv-schedule?date={date:%Y%m%d}"
data = json.loads(await self.source.request(endpoint))
channel_data = data["result"]["channels"][0]
channel = Channel(id=channel_data["alias"], name=channel_data["name"], provider=self.provider)
values = [] values = []
channel_name = ( current_day = datetime.datetime.combine(date.today(), datetime.datetime.min.time())
soup.select_one(".p-tv-guide-header__title")
.text.replace("Телепрограмма ", "")
.strip()
)
current_day = datetime.datetime.combine(
date.today(), datetime.datetime.min.time()
)
end = current_day + datetime.timedelta(days=1, hours=6) end = current_day + datetime.timedelta(days=1, hours=6)
prev_value: ScheduleValue | None = None prev_value: ScheduleValue | None = None
for item in soup.select( for item in channel_data["schedule"]:
".p-tv-guide-schedule-channel-carcass__transmissions .p-tv-guide-schedule-channel-transmission" title = item["title"]
): time_str = item["time"]
title = item.select_one(
".p-tv-guide-schedule-channel-transmission__title"
).text.strip()
time_str = item.select_one(
".p-tv-guide-schedule-channel-transmission__time-block"
).text.strip()
hours, minutes = map(int, time_str.split(":")) hours, minutes = map(int, time_str.split(":"))
item_date = current_day.replace(hour=hours, minute=minutes) item_date = current_day.replace(hour=hours, minute=minutes)
if prev_value is not None and item_date.hour < prev_value.start.hour: if prev_value is not None and item_date.hour < prev_value.start.hour:
@@ -63,5 +51,7 @@ class MatchTvApi(ScheduleApi):
prev_value.end = item_date prev_value.end = item_date
prev_value = value prev_value = value
return Schedule( return Schedule(
channel=Channel(id=channel_id, name=channel_name), date=date, values=values channel=channel,
date=date,
values=values,
) )
+38 -12
View File
@@ -1,6 +1,7 @@
import datetime import datetime
import logging import logging
from collections import defaultdict from collections import defaultdict
from os import environ
from aiocache import cached from aiocache import cached
@@ -9,32 +10,59 @@ from gallery.sketch.weather.model import Location, WeatherResponse, WeatherValue
from gallery.sketch.weather.util import merge_weather_values from gallery.sketch.weather.util import merge_weather_values
from gallery.util import TimeUnit from gallery.util import TimeUnit
from .openweather import Forecast, OpenWeather from .openweather import Forecast
from .openweather import Location as OpenWeatherLocation
from .openweather import OpenWeather
from .parser import FORECAST_ITEM_PARSER from .parser import FORECAST_ITEM_PARSER
logger = logging.getLogger("openweather") logger = logging.getLogger("openweather")
class OpenWeatherApi(WeatherApi): class OpenWeatherApi(WeatherApi[OpenWeather]):
PROVIDER = "openweather" PROVIDER = "openweather"
SOURCE = OpenWeather("517a6bccceaa1c48127f6199ec3fb7cf")
def _build_source(self) -> OpenWeather:
return OpenWeather(environ["OPENWEATHER_KEY"])
@classmethod @classmethod
def _parse_location(cls, location_id: str) -> tuple[float, float]: def _parse_location(cls, location_id: str) -> tuple[float, float]:
return tuple(map(float, location_id.split(":", maxsplit=2))) return tuple(map(float, location_id.split(":", maxsplit=2)))
@cached( @cached(
key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.forecast", key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.location",
alias="redis", alias="redis",
ttl=TimeUnit.DAY, ttl=TimeUnit.DAY,
) )
async def _get_location(self, location_id: str) -> OpenWeatherLocation:
return await self.source.get_location(*self._parse_location(location_id))
@cached(
key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.forecast",
alias="redis",
ttl=TimeUnit.HOUR,
)
async def _get_location_forecast(self, location_id: str) -> Forecast: async def _get_location_forecast(self, location_id: str) -> Forecast:
return await self.SOURCE.get_forecast(*self._parse_location(location_id)) return await self.source.get_forecast(*self._parse_location(location_id))
async def find_locations(self, query: str) -> list[Location]: async def find_locations(self, query: str) -> list[Location]:
raise NotImplementedError result = await self.source.find_locations(query)
return [
Location(
id=f"{item.lat}:{item.lon}",
name=item.name,
provider=self.provider,
lat=item.lat,
lon=item.lon,
country=item.country,
country_code=item.country.lower(),
district=item.state or "",
subdistrict="",
)
for item in result
]
async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse: async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse:
location: OpenWeatherLocation = await self._get_location(location_id)
data: Forecast = await self._get_location_forecast(location_id) data: Forecast = await self._get_location_forecast(location_id)
values = [] values = []
for item in data.list: for item in data.list:
@@ -42,25 +70,23 @@ class OpenWeatherApi(WeatherApi):
if value.date.date() == date: if value.date.date() == date:
values.append(value) values.append(value)
return WeatherResponse( return WeatherResponse(
location=location_id, location=location.name,
date=date, date=date,
period="day", period="day",
values=values, values=values,
) )
async def get_days(self, location_id: str, days: int) -> WeatherResponse: async def get_days(self, location_id: str, days: int) -> WeatherResponse:
location: OpenWeatherLocation = await self._get_location(location_id)
data: Forecast = await self._get_location_forecast(location_id) data: Forecast = await self._get_location_forecast(location_id)
values_by_date: dict[datetime.datetime, list[WeatherValue]] = defaultdict(list) values_by_date: dict[datetime.datetime, list[WeatherValue]] = defaultdict(list)
for item in data.list: for item in data.list:
value = FORECAST_ITEM_PARSER.parse(item) value = FORECAST_ITEM_PARSER.parse(item)
item_date = value.date.replace(hour=0, minute=0) item_date = value.date.replace(hour=0, minute=0)
values_by_date[item_date].append(value) values_by_date[item_date].append(value)
values = [ values = [merge_weather_values(date, values) for date, values in values_by_date.items()]
merge_weather_values(date, values)
for date, values in values_by_date.items()
]
return WeatherResponse( return WeatherResponse(
location=location_id, location=location.name,
date=datetime.date.today(), date=datetime.date.today(),
period="days", period="days",
values=list(sorted(values, key=lambda item: item.date)), values=list(sorted(values, key=lambda item: item.date)),
@@ -1,5 +0,0 @@
from pathlib import Path
from gallery.sketch.mock import MockData
OPENWEATHER_MOCK_DATA = MockData(Path(__file__).parent / "data")
+28 -8
View File
@@ -53,7 +53,7 @@ class ForecastItem(Model):
weather: list[Weather] weather: list[Weather]
clouds: Clouds clouds: Clouds
wind: Wind wind: Wind
visibility: int visibility: int | None = None
pop: float pop: float
rain: Rain | None = None rain: Rain | None = None
sys: Sys sys: Sys
@@ -67,17 +67,37 @@ class Forecast(Model):
list: list[ForecastItem] list: list[ForecastItem]
class OpenWeather: class Location(Model):
name: str
lat: float
lon: float
country: str
state: str | None = None
local_names: dict[str, str] | None = None
class OpenWeather(ApiSource):
BASE_URL = "https://api.openweathermap.org" BASE_URL = "https://api.openweathermap.org"
def __init__(self, api_key: str): def __init__(self, api_key: str):
self._api_key = api_key self._api_key = api_key
self._source = ApiSource(self.BASE_URL) super().__init__(self.BASE_URL)
async def get_forecast(self, lat: float, lon: float) -> Forecast: async def get_forecast(self, lat: float, lon: float) -> Forecast:
endpoint = ( endpoint = f"data/2.5/forecast?lat={lat}&lon={lon}&appid={self._api_key}&units=metric"
f"data/2.5/forecast?lat={lat}&lon={lon}&appid={self._api_key}&units=metric" response = await self.request(endpoint)
)
response = await self._source.request(endpoint)
response_data = json.loads(response) response_data = json.loads(response)
return Forecast(**response_data) return Forecast.model_validate(response_data)
async def find_locations(self, query: str, limit: int = 5) -> list[Location]:
endpoint = f"geo/1.0/direct?q={query}&limit={limit}&appid={self._api_key}"
response = await self.request(endpoint)
response_data = json.loads(response)
return [Location.model_validate(item) for item in response_data]
async def get_location(self, lat: float, lon: float) -> Location:
limit = 1
endpoint = f"geo/1.0/reverse?lat={lat}&lon={lon}&limit={limit}&appid={self._api_key}"
response = await self.request(endpoint)
response_data = json.loads(response)
return Location.model_validate(response_data[0])
+4 -12
View File
@@ -24,26 +24,18 @@ class ForecastItemParser:
def parse(self, item: ForecastItem) -> WeatherValue: def parse(self, item: ForecastItem) -> WeatherValue:
item_date = datetime.datetime.fromtimestamp(item.dt, datetime.UTC) item_date = datetime.datetime.fromtimestamp(item.dt, datetime.UTC)
item_date = ( item_date = item_date.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None).replace(tzinfo=None)
item_date.replace(tzinfo=datetime.timezone.utc)
.astimezone(tz=None)
.replace(tzinfo=None)
)
value = build_weather_value(item_date) value = build_weather_value(item_date)
# TODO parse temperature interval flag # TODO parse temperature interval flag
value.temperature = [round(item.main.temp)] value.temperature = [round(item.main.temp)]
# value.temperature = [round(item.main.temp_max), round(item.main.temp_min)] # value.temperature = [round(item.main.temp_max), round(item.main.temp_min)]
value.pressure = [round(item.main.pressure / 133.3 * 100)] value.pressure = [round(item.main.pressure * 0.75006)]
value.humidity = item.main.humidity value.humidity = item.main.humidity
value.wind_speed = round(item.wind.speed) value.wind_speed = round(item.wind.speed)
value.wind_gust = round(item.wind.gust) value.wind_gust = round(item.wind.gust)
value.wind_direction = item.wind.deg value.wind_direction = item.wind.deg
value.sky.cloudness = self.CLOUDNESS_MAP.get( value.sky.cloudness = self.CLOUDNESS_MAP.get(item.weather[0].description, Cloudness.CLEAR)
item.weather[0].description, Cloudness.CLEAR value.sky.precipitation = self.PRECIPITATION_MAP.get(item.weather[0].description, Precipitation.NO)
)
value.sky.precipitation = self.PRECIPITATION_MAP.get(
item.weather[0].description, Precipitation.NO
)
if item.rain: if item.rain:
value.precipitation = round(item.rain.interval_3h, 1) value.precipitation = round(item.rain.interval_3h, 1)
return value return value
View File
+86
View File
@@ -0,0 +1,86 @@
import datetime
import logging
import aiohttp
from aiocache import cached
from bs4 import BeautifulSoup
from gallery.sketch.source import ApiSource
from gallery.sketch.weather.api import WeatherApi
from gallery.sketch.weather.model import (
Location,
WeatherResponse,
)
from gallery.sketch.weather.util import merge_weather_values
from gallery.util import TimeUnit
from ...sketch.headers import build_headers
from .parser import parse_page
logger = logging.getLogger("rp5")
class RP5WeatherApi(WeatherApi):
PROVIDER = "rp5"
def _build_source(self) -> ApiSource:
return ApiSource("https://rp5.ru", headers=build_headers("rp5.ru"))
async def find_locations(self, query: str) -> list[Location]:
endpoint = "docs/search/ru"
data = aiohttp.FormData({"searchStr": query})
response = await self.source.request(endpoint, method="POST", data=data)
soup = BeautifulSoup(response, features="html.parser")
table = soup.select_one(".searchResults")
result = []
for row in table.select("tr")[1:]:
cells = row.select("td")
name = cells[0].text.strip()
location_id = cells[0].select_one("a").attrs["href"].lstrip("/")
country = cells[1].text.strip()
district = cells[2].text.strip()
subdistrict = cells[3].text.strip()
result.append(
Location(
id=location_id,
name=name,
provider=self.provider,
lat=0,
lon=0,
country=country,
country_code="ru", # TODO: contry_code from country
district=district,
subdistrict=subdistrict,
)
)
return result
@cached(
key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.forecast",
alias="redis",
ttl=TimeUnit.HOUR,
)
async def _get_location_forecast(self, location_id: str) -> list[WeatherResponse]:
endpoint = f"{location_id}"
content = await self.source.request(endpoint)
soup = BeautifulSoup(content, features="html.parser")
return parse_page(soup)
async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse:
forecast = await self._get_location_forecast(location_id)
for response in forecast:
if response.date == date:
return response
if date == datetime.date.today():
return WeatherResponse(location=location_id, date=date, period="day", values=[])
raise ValueError(f"Unsupported date: {date}")
async def get_days(self, location_id: str, days: int) -> WeatherResponse:
forecast = await self._get_location_forecast(location_id)
values = [merge_weather_values(item.date, item.values) for item in forecast]
return WeatherResponse(
location=forecast[0].location,
date=datetime.date.today(),
period="days",
values=values,
)
+146
View File
@@ -0,0 +1,146 @@
import re
from enum import Enum, auto
from typing import Iterable
import dateparser
from bs4 import BeautifulSoup, Tag
from gallery.sketch.weather.model import (
Cloudness,
Precipitation,
WeatherResponse,
WeatherValue,
)
from gallery.sketch.weather.parser import ParseError, parse_wind_direction
from gallery.sketch.weather.util import build_weather_value
CLOUDNESS_MAP = {
"Ясно": Cloudness.CLEAR,
"Малооблачно": Cloudness.PARTLY_CLOUDY,
"Облачно с прояснениями": Cloudness.PARTLY_CLOUDY,
"Переменная облачность": Cloudness.PARTLY_CLOUDY,
"Небольшая облачность": Cloudness.CLOUDY,
"Облачно": Cloudness.CLOUDY,
"Значительная облачность": Cloudness.MAINLY_CLOUDY,
"Пасмурная погода": Cloudness.MAINLY_CLOUDY,
}
PRECIPITATION_MAP = {
"Явления погоды отсутствуют": Precipitation.NO,
"Cлабый дождь": Precipitation.SMALL_RAIN,
}
def _parse_wind_speed(cell: Tag) -> int:
element = cell.select_one(".wv_0")
if element:
return int(element.text.strip() or "0")
return 0
class RowType(Enum):
DATE = auto()
TIME = auto()
CLOUDNESS = auto()
PRECIPITATION = auto()
TEMPERATURE = auto()
PRESSURE = auto()
WIND_SPEED = auto()
WIND_GUST = auto()
WIND_DIRECTION = auto()
HUMIDITY = auto()
def _iter_table_rows(table: Tag) -> Iterable[tuple[RowType, Tag]]:
for row in table.select("tr"):
title = row.select_one("td").text.strip().lower()
if "сегодня" in title:
yield RowType.DATE, row
elif "местное время" in title:
yield RowType.TIME, row
elif "облачность" in title:
yield RowType.CLOUDNESS, row
elif "осадки" in title:
yield RowType.PRECIPITATION, row
elif "температура" in title:
yield RowType.TEMPERATURE, row
elif "давление" in title:
yield RowType.PRESSURE, row
elif "скорость" in title:
yield RowType.WIND_SPEED, row
elif "порывы" in title:
yield RowType.WIND_GUST, row
elif "направление" in title:
yield RowType.WIND_DIRECTION, row
elif "влажность" in title:
yield RowType.HUMIDITY, row
# pylint:disable=too-many-branches
def parse_page(page: BeautifulSoup) -> list[WeatherResponse]:
location = page.select(".intoLeftNavi > .verticalBottom > a")[-1].text.strip()
table = page.select_one("#forecastTable")
if table is None:
raise ParseError("#forecastTable not found")
result: list[WeatherResponse] = []
values: list[WeatherValue] = []
for row_type, row in _iter_table_rows(table):
match row_type:
case RowType.DATE:
for index, cell in enumerate(row.select("td")):
colspan = int(cell.attrs["colspan"])
if index == 0:
colspan -= 1
date_str = ",".join(cell.text.strip().split(",")[-2:])
date = dateparser.parse(date_str, languages=["ru"])
if date is None:
raise ParseError.invalid_date(date_str)
item_values = [build_weather_value(date) for _ in range(colspan)]
result.append(
WeatherResponse(
location=location,
date=date.date(),
period="day",
values=item_values,
)
)
values += item_values
case RowType.TIME:
for index, cell in enumerate(row.select("td")[1:]):
hour = int(cell.text.strip())
values[index].date = values[index].date.replace(hour=hour)
case RowType.CLOUDNESS:
for index, cell in enumerate(row.select("td")[1:]):
onmouseover = cell.select_one(".cc_0").next_element.attrs["onmouseover"]
cloudness_str = re.compile("<b>(.*?)</b>").search(onmouseover).group(1).strip()
values[index].sky.cloudness = CLOUDNESS_MAP[cloudness_str]
case RowType.PRECIPITATION:
for index, cell in enumerate(row.select("td")[1:]):
onmouseover = cell.select_one(".pr_0").attrs["onmouseover"]
precipitation_str = onmouseover.split(",")[1].strip(" '")
precipitation_value_matched = re.compile("(\\d+\\.\\d+) мм").search(precipitation_str)
if precipitation_value_matched:
# one hour value
values[index].precipitation = float(precipitation_value_matched.group(1)) * 6
if "(" in precipitation_str:
precipitation_str = precipitation_str.split(" (")[0]
values[index].sky.precipitation = PRECIPITATION_MAP[precipitation_str]
case RowType.TEMPERATURE:
for index, cell in enumerate(row.select("td")[1:]):
values[index].temperature = [int(cell.select_one(".t_0").text.lstrip("+").strip())]
case RowType.PRESSURE:
for index, cell in enumerate(row.select("td")[1:]):
values[index].pressure = [int(cell.select_one(".p_0").text.strip())]
case RowType.WIND_SPEED:
for index, cell in enumerate(row.select("td")[1:]):
values[index].wind_speed = _parse_wind_speed(cell)
case RowType.WIND_GUST:
for index, cell in enumerate(row.select("td")[1:]):
values[index].wind_gust = _parse_wind_speed(cell)
case RowType.WIND_DIRECTION:
for index, cell in enumerate(row.select("td")[1:]):
values[index].wind_direction = parse_wind_direction(cell.text.strip())
case RowType.HUMIDITY:
for index, cell in enumerate(row.select("td")[1:]):
values[index].humidity = int(cell.text.strip())
return result
+26 -56
View File
@@ -1,78 +1,46 @@
import datetime import datetime
import json
import logging import logging
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from gallery.sketch.schedule.api import ScheduleApi from gallery.sketch.schedule.api import ScheduleApi
from gallery.sketch.schedule.model import Channel, ChannelId, Schedule, ScheduleValue from gallery.sketch.schedule.model import Channel, Schedule, ScheduleValue
from gallery.sketch.source import ApiSource from gallery.sketch.source import ApiSource
from ...sketch.headers import build_headers
logger = logging.getLogger("matchtv") logger = logging.getLogger("matchtv")
CHANNELS_MAP: dict[ChannelId, str] = {
ChannelId.MATCH_TV: "match-tv-49",
ChannelId.MATCH_IGRA: "match-igra-1174",
ChannelId.MATCH_ARENA: "match-arena-1173",
ChannelId.MATCH_FUTBOL_1: "match-futbol-1-646",
ChannelId.MATCH_FUTBOL_2: "match-futbol-2-593",
ChannelId.MATCH_FUTBOL_3: "match-futbol-3-797",
ChannelId.MATCH_STRANA: "match-strana-1356",
ChannelId.MATCH_PLANETA: "match-planeta-1177",
# ChannelId.EUROSPORT: "eurosport-677",
# ChannelId.EUROSPORT_2: "eurosport-2-720",
ChannelId.START: "start-103",
}
HEADERS: dict[str, str] = {
"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"
),
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Host": "tv.yandex.ru",
"sec-ch-ua": '"Chromium";v="100", " Not A;Brand";v="99"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Linux"',
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/100.0.4896.133 "
"Safari/537.36"
),
}
class YandexTvApi(ScheduleApi): class YandexTvApi(ScheduleApi):
PROVIDER = "yandextv" PROVIDER = "yandextv"
SOURCE = ApiSource("https://tv.yandex.ru", headers=HEADERS)
async def get_channels(self) -> list[ChannelId]: def _build_source(self) -> ApiSource:
return list(CHANNELS_MAP.keys()) return ApiSource("https://tv.yandex.ru", headers=build_headers("tv.yandex.ru"))
async def get_channel_schedule( async def find_channels(self, query: str) -> list[Channel]:
self, channel_id: ChannelId, date: datetime.date url = (
) -> Schedule: "https://suggest-multi.yandex.ru/suggest-tv2?"
endpoint = f"channel/{CHANNELS_MAP[channel_id]}?date={date:%Y-%m-%d}" f"v=4&uil=ru&lr=10&count_channels=4&count_programs=4&sn=50&part={query}"
data = await self.SOURCE.request(endpoint) )
_, values = json.loads(await self.source.request(url))
result = []
for _, name, content in values:
if content["label"] == "Каналы":
channel_id = content["url"].split("/")[-1]
result.append(Channel(id=channel_id, name=name, provider=self.provider))
return result
async def get_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
endpoint = f"channels/{channel_id}?date={date:%Y-%m-%d}"
data = await self.source.request(endpoint)
soup = BeautifulSoup(data, features="html.parser") soup = BeautifulSoup(data, features="html.parser")
if soup.select_one(".CheckboxCaptcha") is not None: if soup.select_one(".CheckboxCaptcha") is not None:
raise RuntimeError("Captcha") raise RuntimeError("Captcha")
values = [] values = []
channel_name = soup.select_one(".channel-header__text").text.strip() channel_name = soup.select_one(".channel-header__text").text.strip()
current_day = datetime.datetime.combine( current_day = datetime.datetime.combine(date.today(), datetime.datetime.min.time())
date.today(), datetime.datetime.min.time()
)
end = current_day + datetime.timedelta(days=1, hours=6) end = current_day + datetime.timedelta(days=1, hours=6)
prev_value: ScheduleValue | None = None prev_value: ScheduleValue | None = None
for item in soup.select(".channel-schedule .channel-schedule__event"): for item in soup.select(".channel-schedule .channel-schedule__event"):
@@ -90,5 +58,7 @@ class YandexTvApi(ScheduleApi):
prev_value.end = item_date prev_value.end = item_date
prev_value = value prev_value = value
return Schedule( return Schedule(
channel=Channel(id=channel_id, name=channel_name), date=date, values=values channel=Channel(id=channel_id, name=channel_name, provider=self.provider),
date=date,
values=values,
) )
+75
View File
@@ -0,0 +1,75 @@
import datetime
import json
import logging
from aiocache import cached
from bs4 import BeautifulSoup
from gallery.sketch.source import ApiSource
from gallery.sketch.weather.api import WeatherApi
from gallery.sketch.weather.model import (
Location,
WeatherResponse,
)
from gallery.sketch.weather.util import merge_weather_values
from gallery.util import TimeUnit
from .parser import parse_article
logger = logging.getLogger("yandexweather")
class YandexWeatherApi(WeatherApi):
PROVIDER = "yandex"
def _build_source(self) -> ApiSource:
return ApiSource("https://yandex.ru")
@cached(
key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.forecast",
alias="redis",
ttl=TimeUnit.HOUR,
)
async def _get_location_forecast(self, location_id: str) -> list[WeatherResponse]:
endpoint = f"pogoda/ru/{location_id}/details"
content = await self.source.request(endpoint, mode="browser")
soup = BeautifulSoup(content, features="html.parser")
location = soup.select_one("[class^=Suggest_placeholder]").text.strip()
articles = soup.select("article[class^=AppForecastDay]")
return [parse_article(article, location) for article in articles]
async def find_locations(self, query: str) -> list[Location]:
endpoint = f"weather/api/suggest?part={query}&lang=ru&type=weather"
response = await self.source.request(endpoint)
data = json.loads(response)
return [
Location(
id=str(item["geoId"]),
name=item["title"],
provider=self.provider,
lat=item["coords"]["lat"],
lon=item["coords"]["lon"],
country="ru",
country_code="ru",
district=item["description"],
subdistrict="",
)
for item in data
]
async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse:
forecast = await self._get_location_forecast(location_id)
for response in forecast:
if response.date == date:
return response
raise ValueError(f"Unsupported date: {date}")
async def get_days(self, location_id: str, days: int) -> WeatherResponse:
forecast = await self._get_location_forecast(location_id)
values = [merge_weather_values(item.date, item.values) for item in forecast]
return WeatherResponse(
location=forecast[0].location,
date=datetime.date.today(),
period="days",
values=values,
)
+91
View File
@@ -0,0 +1,91 @@
import logging
from enum import Enum
import dateparser
from bs4 import Tag
from gallery.sketch.weather.model import Cloudness, Precipitation, Sky, WeatherResponse
from gallery.sketch.weather.parser import ParseError, parse_wind_direction
from gallery.sketch.weather.util import build_weather_value
logger = logging.getLogger("yandexweather")
class DayPart(Enum):
MORNING = ("Утром", 6)
AFTERNOON = ("Днём", 12)
EVENING = ("Вечером", 18)
NIGHT = ("Ночью", 0)
def __init__(self, title: str, hour: int):
super().__init__()
self.title = title
self.hour = hour
def parse_sky(sky: str) -> Sky:
cloudness = Cloudness.CLEAR
precipitation = Precipitation.NO
thunder = False
fog = False
if sky == "ясно":
pass
elif sky == "облачно с прояснениями":
cloudness = Cloudness.PARTLY_CLOUDY
elif sky == "малооблачно":
cloudness = Cloudness.CLOUDY
elif sky == "пасмурно":
cloudness = Cloudness.MAINLY_CLOUDY
elif sky == "небольшой дождь":
precipitation = Precipitation.SMALL_RAIN
elif sky == "дождь":
precipitation = Precipitation.RAIN
elif sky == "ливень":
precipitation = Precipitation.SHOWER
else:
logger.warning("unknown sky value: %s", sky)
return Sky(
cloudness=cloudness,
precipitation=precipitation,
thunder=thunder,
fog=fog,
)
def parse_article(article: Tag, location: str) -> WeatherResponse:
date_str = article.select_one("[class^=AppForecastDayHeader_dayTitle]").text.split(",")[-1].strip()
date = dateparser.parse(date_str, languages=["ru"])
if date is None:
raise ParseError.invalid_date(date_str)
values = []
for day_part in DayPart:
value = build_weather_value(date.replace(hour=day_part.hour))
day_part_tag = article.find(string=day_part.title)
temperature_tag = day_part_tag.next_element
temperature = int(temperature_tag.text.strip().rstrip("°"))
value.temperature.append(temperature)
sky_tag = temperature_tag.next_element.next_element.next_element
sky_str = sky_tag.text.strip()
value.sky = parse_sky(sky_str)
temperature_tag = sky_tag.next_element.next_element
temperature = int(temperature_tag.text.strip().rstrip("°"))
value.temperature.append(temperature)
wind_speed_tag = temperature_tag.next_element.next_element
wind_speed = int(wind_speed_tag.text.strip())
value.wind_speed = wind_speed
wind_direction_tag = wind_speed_tag.next_element.next_element.next_element.next_element
wind_direction_str = wind_direction_tag.text.strip()
value.wind_direction = parse_wind_direction(wind_direction_str)
humidity_tag = wind_direction_tag.next_element.next_element.next_element.next_element
humidity = int(humidity_tag.text.strip().rstrip("%"))
value.humidity = humidity
pressure_tag = humidity_tag.next_element.next_element
pressure = int(pressure_tag.text.strip())
value.pressure.append(pressure)
values.append(value)
return WeatherResponse(
location=location,
date=date,
period="day",
values=values,
)
+21 -1
View File
@@ -1,12 +1,32 @@
from typing import TypeVar from typing import TypeVar
from .source import ApiSource
class Api: S = TypeVar("S", bound=ApiSource)
class Api[S = ApiSource]:
TYPE: str
PROVIDER: str PROVIDER: str
_source: S | None = None
def _build_source(self) -> S:
raise NotImplementedError
@property
def type(self) -> str:
return self.TYPE
@property @property
def provider(self) -> str: def provider(self) -> str:
return self.PROVIDER return self.PROVIDER
@property
def source(self) -> S:
if self._source is None:
self._source = self._build_source()
return self._source
API = TypeVar("API", bound=Api) API = TypeVar("API", bound=Api)
+14 -23
View File
@@ -1,28 +1,19 @@
from collections import defaultdict
from .api import API, Api from .api import API, Api
from .schedule.api import ScheduleApi
from .weather.api import WeatherApi
class ApiBundle(list[Api]): class ApiBundle:
def __init__(self, values: list[Api]) -> None: def __init__(self, values: list[Api]):
super().__init__(values) self._values = values
self._providers_by_api = defaultdict(list)
self._api_map = {}
for value in self._values:
self._providers_by_api[value.type].append(value.provider)
self._api_map[(value.type, value.provider)] = value
def get_api_by_provider(self, provider: str) -> Api: def get_api_providers(self, api_type: type[API]) -> list[str]:
for value in self: return self._providers_by_api[api_type.TYPE]
if value.PROVIDER == provider:
return value
raise ValueError(provider)
def get_api_by_type(self, api_type: type[API]) -> API: def get_api(self, api_type: type[API], provider: str) -> API:
for value in self: return self._api_map[(api_type.TYPE, provider)]
if isinstance(value, api_type):
return value
raise ValueError(api_type)
@property
def weather(self) -> WeatherApi:
return self.get_api_by_type(WeatherApi)
@property
def schedule(self) -> ScheduleApi:
return self.get_api_by_type(ScheduleApi)
+4
View File
@@ -1,5 +1,6 @@
from typing import Generic, NamedTuple from typing import Generic, NamedTuple
from gallery.sketch.source import ApiSource
from gallery.util import TimeUnit from gallery.util import TimeUnit
from .api import API, Api from .api import API, Api
@@ -19,6 +20,9 @@ class CachedApi(Api, Generic[API]):
def __init__(self, api: API): def __init__(self, api: API):
self._api = api self._api = api
def _build_source(self) -> ApiSource:
raise RuntimeError("Source not used in CachedApi")
@property @property
def provider(self) -> str: def provider(self) -> str:
return self._api.provider return self._api.provider
-14
View File
@@ -1,14 +0,0 @@
from typing import Generic, TypeVar
T = TypeVar("T")
class CatalogBundle(Generic[T]):
def __init__(self, items: list[T]) -> None:
self._items_by_id = {item.id: item for item in items}
def get_item(self, item_id: str) -> T:
return self._items_by_id[item_id]
def select_items(self, ids: list[str]) -> list[T]:
return [self._items_by_id[id_] for id_ in ids]
+42
View File
@@ -0,0 +1,42 @@
DEFAULT_USER_AGENT = (
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36"
)
DEFAULT_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.7"
)
DEFAULT_HEADERS = {
"Accept": DEFAULT_ACCEPT,
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9,ru-RU;q=0.8,ru;q=0.7,uk;q=0.6",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Host": None,
"Referer": None,
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": DEFAULT_USER_AGENT,
"sec-ch-ua": '"Not;A=Brand";v="8", "Chromium";v="150", "Google Chrome";v="150"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Linux"',
}
def build_headers(host: str, *, user_agent: str | None = None) -> dict[str, str]:
result = DEFAULT_HEADERS.copy()
result["Host"] = host
result["Referer"] = f"https://{host}/"
if user_agent is not None:
result["User-Agent"] = user_agent
return result
+6 -19
View File
@@ -1,28 +1,15 @@
import asyncio
import datetime import datetime
from ..api import Api from ..api import Api
from .model import ChannelId, Schedule from ..source import ApiSource
from .model import Channel, Schedule
class ScheduleApi(Api): class ScheduleApi[S = ApiSource](Api[S]):
INTERVAL: float = 0.5 TYPE = "schedule"
async def get_channels(self) -> list[ChannelId]: async def find_channels(self, query: str) -> list[Channel]:
raise NotImplementedError raise NotImplementedError
async def get_channel_schedule( async def get_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
self, channel_id: ChannelId, date: datetime.date
) -> Schedule:
raise NotImplementedError raise NotImplementedError
async def get_all_schedules(self, date: datetime.date) -> list[Schedule]:
channels = await self.get_channels()
results = []
for channel in channels:
results.append(
await self.get_channel_schedule(channel_id=channel, date=date)
)
if self.INTERVAL > 0:
await asyncio.sleep(self.INTERVAL)
return results
+7 -18
View File
@@ -6,20 +6,20 @@ from gallery.sketch.cached import CachedApi, CachePreset
from gallery.util import TimeUnit from gallery.util import TimeUnit
from .api import ScheduleApi from .api import ScheduleApi
from .model import ChannelId, Schedule from .model import Channel, Schedule
CACHE_PRESET = CachePreset(ttl=TimeUnit.HOUR * 6) CACHE_PRESET = CachePreset(ttl=TimeUnit.HOUR * 6)
class CachedScheduleApi(ScheduleApi, CachedApi[ScheduleApi]): class CachedScheduleApi(ScheduleApi, CachedApi[ScheduleApi]):
CACHE_KEY = "schedule" CACHE_KEY = ScheduleApi.TYPE
@cached( @cached(
key_builder=lambda fun, self: f"api.{self.CACHE_KEY}.{self.provider}.channels", key_builder=lambda fun, self, query: f"api.{self.CACHE_KEY}.{self.provider}.find.{query}",
**CACHE_PRESET._asdict(), **CACHE_PRESET._asdict(),
) )
async def get_channels(self) -> list[ChannelId]: async def find_channels(self, query: str) -> list[Channel]:
return await self._api.get_channels() return await self._api.find_channels(query)
@cached( @cached(
key_builder=lambda fun, self, channel_id, date: ( key_builder=lambda fun, self, channel_id, date: (
@@ -27,16 +27,5 @@ class CachedScheduleApi(ScheduleApi, CachedApi[ScheduleApi]):
), ),
**CACHE_PRESET._asdict(), **CACHE_PRESET._asdict(),
) )
async def get_channel_schedule( async def get_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
self, channel_id: ChannelId, date: datetime.date return await self._api.get_schedule(channel_id, date)
) -> Schedule:
return await self._api.get_channel_schedule(channel_id, date)
@cached(
key_builder=lambda fun, self, date: (
f"api.{self.CACHE_KEY}.{self.provider}.all.{date}"
),
**CACHE_PRESET._asdict(),
)
async def get_all_schedules(self, date: datetime.date) -> list[Schedule]:
return await self._api.get_all_schedules(date)
-21
View File
@@ -1,21 +0,0 @@
from gallery.sketch.catalog import CatalogBundle
from .model import Channel, ChannelId
BUNDLE = CatalogBundle(
[
Channel(id=ChannelId.MATCH_TV, name="Матч ТВ"),
Channel(id=ChannelId.MATCH_IGRA, name="Матч! Игра"),
Channel(id=ChannelId.MATCH_ARENA, name="Матч! Арена"),
Channel(id=ChannelId.MATCH_FUTBOL_1, name="Футбол 1"),
Channel(id=ChannelId.MATCH_FUTBOL_2, name="Футбол 2"),
Channel(id=ChannelId.MATCH_FUTBOL_3, name="Футбол 3"),
Channel(id=ChannelId.MATCH_STRANA, name="Матч! Страна"),
Channel(id=ChannelId.MATCH_PLANETA, name="Матч! Планета"),
Channel(id=ChannelId.MATCH_PLANETA, name="Матч! Планета"),
Channel(id=ChannelId.EUROSPORT, name="Europsort"),
Channel(id=ChannelId.EUROSPORT_2, name="Europsort 2"),
Channel(id=ChannelId.START, name="Старт!"),
Channel(id=ChannelId.TEST, name="Тест"),
]
)
+2 -20
View File
@@ -1,5 +1,4 @@
import datetime import datetime
from enum import StrEnum
from pydantic import BaseModel from pydantic import BaseModel
@@ -9,27 +8,10 @@ class Model(BaseModel):
use_enum_values = True use_enum_values = True
class ChannelId(StrEnum):
MATCH_TV = "matchtv"
MATCH_IGRA = "igra"
MATCH_ARENA = "arena"
MATCH_FUTBOL_1 = "futbol-1"
MATCH_FUTBOL_2 = "futbol-2"
MATCH_FUTBOL_3 = "futbol-3"
MATCH_STRANA = "strana"
MATCH_PLANETA = "planeta"
EUROSPORT = "eurosport"
EUROSPORT_2 = "eurosport-2"
START = "start"
TEST = "test"
def __str__(self) -> str:
return self.value
class Channel(Model): class Channel(Model):
id: ChannelId id: str
name: str name: str
provider: str
class ScheduleValue(Model): class ScheduleValue(Model):
+47 -13
View File
@@ -1,40 +1,74 @@
import datetime
import logging import logging
from typing import Any, Literal
import aiohttp import aiohttp
from playwright.async_api import async_playwright
logger = logging.getLogger("source") logger = logging.getLogger("source")
RequestMode = Literal["base", "browser"]
DEFAULT_REQUEST_MODE: RequestMode = "base"
DEFAULT_METHOD: str = "GET"
class ApiSource: class ApiSource:
DEFAULT_USER_AGENT = (
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/126.0.0.0 Safari/537.36"
)
DEFAULT_TIMEOUT = 30.0 DEFAULT_TIMEOUT = 30.0
def __init__( def __init__(
self, self,
base_url, base_url,
user_agent: str = DEFAULT_USER_AGENT,
timeout: float = DEFAULT_TIMEOUT, timeout: float = DEFAULT_TIMEOUT,
cookies: dict[str, str] | None = None, cookies: dict[str, str] | None = None,
headers: dict[str, str] | None = None, headers: dict[str, str] | None = None,
): ):
self._base_url = base_url self._base_url = base_url
self._user_agent = user_agent
self._timeout = timeout self._timeout = timeout
self._cookies = cookies self._cookies = cookies
self._headers = headers self._headers = headers
async def request(self, endpoint: str) -> str: async def _base_request(
url = f"{self._base_url}/{endpoint}" self,
logger.info(url) url: str,
headers = {"User-Agent": self._user_agent, **(self._headers or {})} method: str = DEFAULT_METHOD,
data: Any | None = None,
) -> str:
async with aiohttp.ClientSession( async with aiohttp.ClientSession(
headers=headers, headers=self._headers,
cookies=self._cookies, cookies=self._cookies,
raise_for_status=True, raise_for_status=True,
) as session: ) as session:
async with session.request("GET", url, timeout=self._timeout) as response: async with session.request(method, url, timeout=self._timeout, data=data) as response:
return await response.text() return await response.text()
# pylint:disable=unused-argument
async def _browser_request(
self,
url: str,
method: str = DEFAULT_METHOD,
data: Any | None = None,
) -> str:
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(url, timeout=datetime.timedelta(seconds=self._timeout), wait_until="networkidle")
content = await page.content()
await browser.close()
return content
async def request(
self,
endpoint: str,
/,
mode: RequestMode = DEFAULT_REQUEST_MODE,
method: str = DEFAULT_METHOD,
data: Any | None = None,
) -> str:
if endpoint.startswith("https:"):
url = endpoint
else:
url = f"{self._base_url}/{endpoint}"
logger.info(url)
fun = getattr(self, f"_{mode}_request")
return await fun(url, method, data)
+3 -1
View File
@@ -1,10 +1,12 @@
import datetime import datetime
from ..api import Api from ..api import Api
from ..source import ApiSource
from .model import Location, WeatherResponse from .model import Location, WeatherResponse
class WeatherApi(Api): class WeatherApi[S = ApiSource](Api[S]):
TYPE = "weather"
async def find_locations(self, query: str) -> list[Location]: async def find_locations(self, query: str) -> list[Location]:
raise NotImplementedError raise NotImplementedError
+1 -1
View File
@@ -11,7 +11,7 @@ CACHE_PRESET = DEFAULT_CACHE_PRESET
class CachedWeatherApi(WeatherApi, CachedApi[WeatherApi]): class CachedWeatherApi(WeatherApi, CachedApi[WeatherApi]):
CACHE_KEY = "weather" CACHE_KEY = WeatherApi.TYPE
@cached( @cached(
key_builder=lambda fun, self, query: f"api.{self.CACHE_KEY}.{self.provider}.locations.{query}", key_builder=lambda fun, self, query: f"api.{self.CACHE_KEY}.{self.provider}.locations.{query}",
+45 -30
View File
@@ -1,7 +1,8 @@
import datetime import datetime
from enum import Enum from enum import StrEnum, auto
from typing import Self
from pydantic import BaseModel from pydantic import BaseModel, Field
class Model(BaseModel): class Model(BaseModel):
@@ -12,6 +13,7 @@ class Model(BaseModel):
class Location(Model): class Location(Model):
id: str id: str
name: str name: str
provider: str
lat: float lat: float
lon: float lon: float
country: str country: str
@@ -20,21 +22,32 @@ class Location(Model):
subdistrict: str subdistrict: str
class Cloudness(str, Enum): class Cloudness(StrEnum):
CLEAR = "clear" CLEAR = auto()
PARTLY_CLOUDY = "party_cloudy" PARTLY_CLOUDY = auto()
CLOUDY = "cloudy" CLOUDY = auto()
MAINLY_CLOUDY = "mainly_cloudy" MAINLY_CLOUDY = auto()
values: list[Self]
class Precipitation(str, Enum): Cloudness.values = list(Cloudness)
NO = "no"
SMALL_RAIN = "small_rain"
RAIN = "rain" class Precipitation(StrEnum):
HEAVY_RAIN = "heavy_rain" NO = auto()
SHOWER = "shower" SMALL_RAIN = auto()
SNOW = "snow" RAIN = auto()
HEAVY_SNOW = "heavy_snow" HEAVY_RAIN = auto()
SHOWER = auto()
SNOW = auto()
HEAVY_SNOW = auto()
HAIL = auto()
values: list[Self]
Precipitation.values = list(Precipitation)
class Sky(Model): class Sky(Model):
@@ -44,16 +57,16 @@ class Sky(Model):
fog: bool fog: bool
class WindDirection(str, Enum): class WindDirection(StrEnum):
CALM = "calm" CALM = auto()
N = "N" N = auto()
NE = "NE" NE = auto()
E = "E" E = auto()
SE = "SE" SE = auto()
S = "S" S = auto()
SW = "SW" SW = auto()
W = "W" W = auto()
NW = "NW" NW = auto()
class WindDirectionDeg(float): class WindDirectionDeg(float):
@@ -67,7 +80,9 @@ class WindDirectionDeg(float):
# pylint:disable=too-many-return-statements # pylint:disable=too-many-return-statements
def to_direction(self) -> WindDirection: def to_direction(self) -> WindDirection:
if self > 337.5 or self <= 22.25: if self == -1:
return WindDirection.CALM
elif self > 337.5 or self <= 22.25:
return WindDirection.N return WindDirection.N
elif self <= 67.5: elif self <= 67.5:
return WindDirection.NE return WindDirection.NE
@@ -84,10 +99,10 @@ class WindDirectionDeg(float):
elif self <= 337.5: elif self <= 337.5:
return WindDirection.NW return WindDirection.NW
else: else:
return WindDirection.CALM raise ValueError(self)
@classmethod @classmethod
def from_direction(cls, direction: WindDirection) -> "WindDirectionDeg": def from_direction(cls, direction: WindDirection) -> Self:
return cls( return cls(
{ {
WindDirection.CALM: -1, WindDirection.CALM: -1,
@@ -111,8 +126,8 @@ class WeatherValue(Model):
wind_gust: int wind_gust: int
wind_direction: float wind_direction: float
precipitation: float precipitation: float
pressure: list[int] pressure: list[int] = Field(default=[])
humidity: int humidity: int = Field(default=-1)
class WeatherResponse(Model): class WeatherResponse(Model):
+29
View File
@@ -0,0 +1,29 @@
from typing import Self
from gallery.sketch.weather.model import WindDirection, WindDirectionDeg
class ParseError(Exception):
@classmethod
def invalid_date(cls, date_str: str) -> Self:
return cls("Invalid date string", date_str)
WIND_DIRECTION_MAP: dict[str, WindDirection] = {
"—": WindDirection.CALM,
"": WindDirection.CALM,
"штиль": WindDirection.CALM,
"штл": WindDirection.CALM,
"с": WindDirection.N,
"св": WindDirection.NE,
"в": WindDirection.E,
"юв": WindDirection.SE,
"ю": WindDirection.S,
"юз": WindDirection.SW,
"з": WindDirection.W,
"сз": WindDirection.NW,
}
def parse_wind_direction(value: str) -> WindDirectionDeg:
return WindDirectionDeg.from_direction(WIND_DIRECTION_MAP[value.replace("-", "").lower()])
+21 -8
View File
@@ -1,8 +1,11 @@
import datetime import datetime
import statistics import statistics
from typing import Literal
from .model import Cloudness, Precipitation, Sky, WeatherValue, WindDirectionDeg from .model import Cloudness, Precipitation, Sky, WeatherValue, WindDirectionDeg
MergeMode = Literal["interval", "average"]
def build_weather_value(date: datetime.datetime) -> WeatherValue: def build_weather_value(date: datetime.datetime) -> WeatherValue:
return WeatherValue( return WeatherValue(
@@ -19,12 +22,24 @@ def build_weather_value(date: datetime.datetime) -> WeatherValue:
wind_direction=WindDirectionDeg(-1), wind_direction=WindDirectionDeg(-1),
precipitation=0, precipitation=0,
pressure=[], pressure=[],
humidity=0, humidity=-1,
) )
def _merge_values(values: list[int], mode: MergeMode) -> list[int]:
if mode == "interval":
if (max_value := max(values)) == (min_value := min(values)):
return [max_value]
else:
return [max_value, min_value]
else:
return [round(sum(values) / len(values))]
def merge_weather_values( def merge_weather_values(
date: datetime.datetime, values: list[WeatherValue] date: datetime.datetime,
values: list[WeatherValue],
mode: MergeMode = "interval",
) -> WeatherValue: ) -> WeatherValue:
result = build_weather_value(date) result = build_weather_value(date)
temperatures = [] temperatures = []
@@ -46,19 +61,17 @@ def merge_weather_values(
cloudnesses.append(value.sky.cloudness) cloudnesses.append(value.sky.cloudness)
precipitations.append(value.sky.precipitation) precipitations.append(value.sky.precipitation)
precipitation += value.precipitation precipitation += value.precipitation
result.temperature = [max(temperatures), min(temperatures)] result.temperature = _merge_values(temperatures, mode)
result.pressure = [max(pressures), min(pressures)] result.pressure = _merge_values(pressures, mode)
result.humidity = round(statistics.mean(humidities)) result.humidity = round(statistics.mean(humidities))
result.wind_speed = round(statistics.mean(wind_speeds)) result.wind_speed = round(statistics.mean(wind_speeds))
result.wind_gust = round(statistics.mean(wind_gusts)) result.wind_gust = round(statistics.mean(wind_gusts))
result.wind_direction = statistics.mean(wind_directions) result.wind_direction = statistics.mean(wind_directions)
# TODO: merge cloudnesses
for item in cloudnesses: for item in cloudnesses:
if item != Cloudness.CLEAR: if Cloudness.values.index(item) > Cloudness.values.index(result.sky.cloudness):
result.sky.cloudness = item result.sky.cloudness = item
# TODO: merge precipitations
for item in precipitations: for item in precipitations:
if item != Precipitation.NO: if Precipitation.values.index(item) > Precipitation.values.index(result.sky.precipitation):
result.sky.precipitation = item result.sky.precipitation = item
result.precipitation = precipitation result.precipitation = precipitation
return result return result
+4 -1
View File
@@ -1 +1,4 @@
__version__ = "0.2.2" import tomllib
from pathlib import Path
__version__ = tomllib.loads((Path(__file__).parent.parent / "pyproject.toml").read_text())["project"]["version"]
+9
View File
@@ -69,9 +69,18 @@ msgstr "Давление, мм рт. ст."
msgid "Humidity, %" msgid "Humidity, %"
msgstr "Влажность, %" msgstr "Влажность, %"
msgid "Stored locations"
msgstr "Сохранённые локации"
# tv # tv
msgid "TV program" msgid "TV program"
msgstr "Телепрограмма" msgstr "Телепрограмма"
msgid "Live broadcasts" msgid "Live broadcasts"
msgstr "Прямые трансляции" msgstr "Прямые трансляции"
msgid "Stored channels"
msgstr "Сохранённые каналы"
msgid "Channel groups"
msgstr "Группы каналов"
Generated
+2466 -1231
View File
File diff suppressed because it is too large Load Diff
+36 -30
View File
@@ -1,43 +1,49 @@
[tool.poetry] [project]
name = "gallery" name = "gallery"
version = "0.2.2"
description = "" description = ""
authors = ["shmyga <shmyga.z@gmail.com>"] version = "0.8.2"
readme = "README.md" readme = "README.md"
authors = [{ name = "shmyga", email = "shmyga.z@gmail.com" }]
requires-python = '>=3.14,<4.0'
dependencies = [
'aiohttp (>=3.14,<4.0)',
'beautifulsoup4 (>=4.15,<5.0)',
'dateparser (>=1.4,<2.0)',
'pydantic (>=2.13,<3.0)',
'aiocache[redis] (>=0.12,<0.13)',
"playwright (>=1.62.0,<2.0.0)",
]
[project.optional-dependencies]
app = [
"fastapi[standard] (>=0.139,<0.140)",
"jinja2 (>=3.1,<4.0)",
"babel (>=2.18,<3.0)",
]
[dependency-groups]
test = ["pytest (>=9.1,<10.0)", "pytest-asyncio (>=1.4,<2.0)"]
dev = ["pylint (>=4.0.6,<5.0.0)", "black (>=26.5,<27.0)", "isort (>=8.0,<9.0)"]
[project.scripts]
gallery = "gallery.main:run"
[tool.poetry]
packages = [{ include = "gallery" }] packages = [{ include = "gallery" }]
requires-poetry = '>=2.0.0,<3.0.0'
[tool.poetry.dependencies]
python = "^3.12"
aiohttp = "^3.9.5"
beautifulsoup4 = "^4.12.3"
dateparser = "^1.2.0"
pydantic = "^2.8.2"
aiocache = {extras = ["redis"], version = "^0.12.2"}
[tool.poetry.group.app.dependencies]
fastapi = "^0.111.1"
jinja2 = "^3.1.4"
babel = "^2.18.0"
[tool.poetry.group.test.dependencies]
pytest = "^8.3.1"
pytest-asyncio = "^0.23.8"
[tool.poetry.group.dev.dependencies]
pylint = "^3.2.6"
black = "^24.4.2"
isort = "^5.13.2"
[build-system] [build-system]
requires = ["poetry-core"] requires = ['poetry-core (>=2.0.0,<3.0.0)']
build-backend = "poetry.core.masonry.api" build-backend = "poetry.core.masonry.api"
[tool.poetry.scripts] [tool.black]
gallery = "gallery.main:run" line-length = 120
target-version = ["py314"]
[tool.isort]
profile = "black"
[tool.pytest.ini_options] [tool.pytest.ini_options]
addopts = "-p no:warnings" addopts = "-p no:warnings"
asyncio_mode = "auto" asyncio_mode = "auto"
testpaths = ["tests"] testpaths = ["tests"]
[tool.poetry_bumpversion.file."gallery/version.py"]
+12 -2
View File
@@ -29,9 +29,19 @@ publish () {
for PROJECT in "${DOCKER_PROJECTS[@]}"; do for PROJECT in "${DOCKER_PROJECTS[@]}"; do
IFS=: read -r PROJECT_NAME PROJECT_TARGET <<< "$PROJECT" IFS=: read -r PROJECT_NAME PROJECT_TARGET <<< "$PROJECT"
docker tag $DOCKER_GROUP/$PROJECT_NAME $DOCKER_ROOT/$PROJECT_NAME:$VERSION docker tag $DOCKER_GROUP/$PROJECT_NAME $DOCKER_ROOT/$PROJECT_NAME:$VERSION
docker tag $DOCKER_GROUP/$PROJECT_NAME $DOCKER_ROOT/$PROJECT_NAME:latest docker tag $DOCKER_GROUP/$PROJECT_NAME $DOCKER_ROOT/$PROJECT_NAME:$DOCKER_TAG
docker push $DOCKER_ROOT/$PROJECT_NAME:$VERSION docker push $DOCKER_ROOT/$PROJECT_NAME:$VERSION
docker push $DOCKER_ROOT/$PROJECT_NAME:latest docker push $DOCKER_ROOT/$PROJECT_NAME:$DOCKER_TAG
done
}
save () {
echo "save: $1"
. "$1/.env"
mkdir -p "$1/dist"
for PROJECT in "${DOCKER_PROJECTS[@]}"; do
IFS=: read -r PROJECT_NAME PROJECT_TARGET <<< "$PROJECT"
docker save --output "$1/dist/$PROJECT_NAME-$VERSION.tar" "$DOCKER_GROUP/$PROJECT_NAME"
done done
} }
Executable
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -e
cd "$(dirname $(dirname "$0"))" || exit
TARGET="gallery"
poetry run isort $TARGET
poetry run black $TARGET -q
+5 -1
View File
@@ -2,4 +2,8 @@
set -e set -e
cd "$(dirname $(dirname "$0"))" || exit cd "$(dirname $(dirname "$0"))" || exit
poetry run pylint gallery TARGET="gallery"
poetry run pylint $TARGET -sn
poetry run isort $TARGET --check-only
poetry run black $TARGET -q --check --diff
Executable
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -e
cd "$(dirname $(dirname "$0"))" || exit
# env
if [[ ! -f .env ]]; then
cp .env-base .env
fi
source .env
# python
poetry env use ${PYTHON_VERSION}
poetry install
.venv/bin/playwright install chromium --with-deps --only-shell
# static
cd static || exit
if [[ -f $HOME/.nvm/nvm.sh ]]; then
source "$HOME/.nvm/nvm.sh"
nvm use
fi
npm ci
+1 -1
View File
@@ -2,4 +2,4 @@
set -e set -e
cd "$(dirname $(dirname "$0"))" || exit cd "$(dirname $(dirname "$0"))" || exit
poetry run pytest tests OPENWEATHER_KEY="" poetry run pytest tests
+4054 -632
View File
File diff suppressed because it is too large Load Diff
+31 -7
View File
@@ -1,9 +1,10 @@
{ {
"name": "gallery", "name": "gallery",
"version": "0.2.2", "version": "0.8.2",
"type": "module",
"scripts": { "scripts": {
"build": "vite build", "build": "webpack --mode production",
"dev": "vite build --watch" "dev": "webpack --watch --mode development"
}, },
"author": "shmyga <shmyga.z@gmail.com>", "author": "shmyga <shmyga.z@gmail.com>",
"license": "ISC", "license": "ISC",
@@ -12,10 +13,33 @@
"@popperjs/core": "^2.11.8", "@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.8", "bootstrap": "^5.3.8",
"bootstrap-icons": "^1.13.1", "bootstrap-icons": "^1.13.1",
"flag-icons": "^7.5.0", "flag-icons": "^7.5.0"
"sass": "^1.99.0"
}, },
"devDependencies": { "devDependencies": {
"vite": "^8.0.9" "@babel/core": "^8.0.1",
} "@babel/preset-env": "^8.0.2",
"@types/bootstrap": "^5.2.11",
"@types/node": "^26.1.0",
"autoprefixer": "^10.5.4",
"babel-loader": "^10.1.1",
"copy-webpack-plugin": "^14.0.0",
"core-js": "^3.49.0",
"css-loader": "^7.1.4",
"file-loader": "^6.2.0",
"mini-css-extract-plugin": "^2.10.2",
"postcss": "^8.5.22",
"postcss-loader": "^8.2.1",
"sass": "^1.101.0",
"sass-loader": "^17.0.0",
"style-loader": "^4.0.0",
"ts-loader": "^9.6.2",
"ts-node": "^10.9.2",
"typescript": "^6.0.3",
"webpack": "^5.108.3",
"webpack-cli": "^7.1.0"
},
"browserslist": [
"> 0.5%",
"last 2 versions"
]
} }
+196
View File
@@ -0,0 +1,196 @@
export interface Type<T> extends Function {
new (...args: any[]): T;
}
export abstract class ValueElement<T, O> extends HTMLElement {
static observedAttributes = ["value"];
private _value: T | null = null;
get value(): T | null {
return this._value;
}
set value(value: T | null) {
if (value) {
this.setAttribute("value", JSON.stringify(value));
} else if (this.hasAttribute("value")) {
this.removeAttribute("value");
}
}
options: O | null;
constructor(value: T | null = null, options: O | null = null) {
super();
if (value) {
this.value = value;
}
this.options = options;
this.onInit();
}
onInit() {}
beforeRefresh() {}
onRefresh() {}
abstract buildHTML(): string;
refresh() {
const rawValue = this.getAttribute("value");
if (rawValue) {
this._value = JSON.parse(rawValue);
} else {
this._value = null;
}
if (this.className) {
this.classList = this.className;
}
this.beforeRefresh();
this.innerHTML = this.buildHTML();
this.onRefresh();
}
connectedCallback() {
this.refresh();
}
attributeChangedCallback(name: string, oldValue: any, newValue: any) {
setTimeout(() => this.refresh());
}
}
export interface ListOptions<T> {
onClick?: (element: ListItemElement<T>) => void;
onAdd?: (element: ListItemElement<T>) => void;
onRemove?: (element: ListItemElement<T>) => void;
}
export abstract class ListItemElement<T> extends ValueElement<T, ListOptions<T>> {
abstract getHref(value: T): string;
abstract getContent(value: T): string;
className = "list-group-item list-group-item-action";
onInit(): void {
this.handleClick = this.handleClick.bind(this);
this.handleRemoveClick = this.handleRemoveClick.bind(this);
this.handleAddClick = this.handleAddClick.bind(this);
}
buildHTML(): string {
if (!this.value) {
return "";
}
const href = this.getHref(this.value);
const content = this.getContent(this.value);
return `
<a href="${href}"
class="d-flex justify-content-between align-items-start text-decoration-none">
<span>
<span class="text-success me-2 ${this.options?.onAdd ? "" : "d-none"}" style="color: green;" data-add>
&plus;
</span>
${content}
</span>
<span>
<span class="text-danger ms-2 ${this.options?.onRemove ? "" : "d-none"}" data-remove>
&#x2715;
</span>
</span>
</a>
`;
}
onRefresh(): void {
this.addEventListener("click", this.handleClick);
if (this.options?.onAdd) {
this.querySelector<HTMLElement>("[data-add]")?.addEventListener("click", this.handleAddClick);
} else {
this.querySelector("[data-add]")?.remove();
}
if (this.options?.onRemove) {
this.querySelector<HTMLElement>("[data-remove]")?.addEventListener("click", this.handleRemoveClick);
} else {
this.querySelector("[data-remove]")?.remove();
}
}
handleClick(event: MouseEvent) {
if (this.value && this.options?.onClick) {
this.options.onClick(this);
}
}
handleAddClick(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
if (this.value && this.options?.onAdd) {
this.options.onAdd(this);
}
}
handleRemoveClick(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
if (this.value && this.options?.onRemove) {
this.options.onRemove(this);
}
}
disconnectedCallback() {
this.removeEventListener("click", this.handleClick);
this.querySelector<HTMLElement>("[data-add]")?.removeEventListener("click", this.handleAddClick);
this.querySelector<HTMLElement>("[data-remove]")?.removeEventListener("click", this.handleRemoveClick);
}
}
export abstract class ListElement<T, C extends ListItemElement<T> = ListItemElement<T>> extends ValueElement<
T[],
ListOptions<T>
> {
static observedAttributes = ["value", "onadd", "onremove", "onclick"];
abstract childType: Type<C>;
className = "list-group";
buildHTML(): string {
return "";
}
beforeRefresh() {
if (this.hasAttribute("onclick")) {
const onclick = new Function("element", this.getAttribute("onclick")!) as ListOptions<T>["onClick"];
if (!this.options) {
this.options = {};
}
this.options.onClick = onclick;
}
if (this.hasAttribute("onadd")) {
const onadd = new Function("element", this.getAttribute("onadd")!) as ListOptions<T>["onAdd"];
if (!this.options) {
this.options = {};
}
this.options.onAdd = onadd;
}
if (this.hasAttribute("onremove")) {
const onremove = new Function("element", this.getAttribute("onremove")!) as ListOptions<T>["onRemove"];
if (!this.options) {
this.options = {};
}
this.options.onRemove = onremove;
}
}
onRefresh() {
if (this.value) {
for (const item of this.value) {
this.appendChild(new this.childType(item, this.options));
}
}
}
}
+50
View File
@@ -0,0 +1,50 @@
import { ListElement, ListItemElement } from "./component";
import { DataStorage, StorageValue } from "./storage";
export class DataManager<T extends StorageValue> {
private storage: DataStorage<T>;
private get dataList(): ListElement<T> {
return document.querySelector(this.dataListSelector)!;
}
constructor(
listComponentType: typeof ListElement<T>, //prevent removing as unusing
storageKey: string,
private dataListSelector: string,
) {
this.storage = new DataStorage(storageKey);
this.load = this.load.bind(this);
this.store = this.store.bind(this);
this.add = this.add.bind(this);
this.remove = this.remove.bind(this);
}
load() {
this.dataList.value = this.storage.getAll();
}
store(element: ListItemElement<T>) {
if (element.value) {
this.storage.add(element.value);
}
}
add(element: ListItemElement<T>) {
const value = element.value;
value;
if (value && this.storage.add(value)) {
const clone: ListItemElement<T> = element.cloneNode(true) as ListItemElement<T>;
clone.options = { onRemove: this.remove };
this.dataList.appendChild(clone);
}
}
remove(element: ListItemElement<T>) {
const value = element.value;
if (value) {
this.storage.remove(value.id);
element.remove();
}
}
}
+46
View File
@@ -0,0 +1,46 @@
export interface StorageValue {
id: string;
}
export class DataStorage<T extends StorageValue> {
constructor(private storageKey: string) {}
private readValues(): T[] {
const objects = JSON.parse(window.localStorage.getItem(this.storageKey) || "[]");
if (!Array.isArray(objects)) {
return Object.values(objects);
}
return objects;
}
private writeValues(values: T[]) {
window.localStorage.setItem(this.storageKey, JSON.stringify(values));
}
getAll(): T[] {
return this.readValues();
}
add(value: T): boolean {
const values = this.readValues();
for (const v of values) {
if (v.id == value.id) {
return false;
}
}
values.push(value);
this.writeValues(values);
return true;
}
remove(id: string) {
const values = this.readValues();
for (let i = 0; i < values.length; i++) {
if (values[i].id == id) {
values.splice(i, 1);
this.writeValues(values);
return;
}
}
}
}
@@ -19,7 +19,7 @@
setLanguage(getPreferredLanguage()); setLanguage(getPreferredLanguage());
const showActiveLanguage = (language: string, focus = false) => { const showActiveLanguage = (language: string, focus = false) => {
const languageSwitcher = document.querySelector("#bd-language"); const languageSwitcher = document.querySelector<HTMLElement>("#bd-language");
if (!languageSwitcher) { if (!languageSwitcher) {
return; return;
@@ -27,24 +27,26 @@
const languageSwitcherText = document.querySelector("#bd-language-text"); const languageSwitcherText = document.querySelector("#bd-language-text");
const activeLanguageIcon = document.querySelector(".language-icon-active"); const activeLanguageIcon = document.querySelector(".language-icon-active");
const btnToActive = document.querySelector(`[data-bs-language-value="${language}"]`); const btnToActive = document.querySelector<HTMLElement>(`[data-bs-language-value="${language}"]`);
const activeLanguageIconClass = btnToActive.querySelector(".fi").className.match(/fi-[\w-]+/)[0]; const activeLanguageIconClass = (btnToActive?.querySelector(".fi")?.className.match(/fi-[\w-]+/) || [])[0] || "";
document.querySelectorAll("[data-bs-language-value]").forEach((element) => { document.querySelectorAll("[data-bs-language-value]").forEach((element) => {
element.classList.remove("active"); element.classList.remove("active");
element.setAttribute("aria-pressed", "false"); element.setAttribute("aria-pressed", "false");
}); });
btnToActive.classList.add("active"); btnToActive?.classList.add("active");
btnToActive.setAttribute("aria-pressed", "true"); btnToActive?.setAttribute("aria-pressed", "true");
const classesToRemove = Array.from(activeLanguageIcon.classList).filter((className) => className.startsWith("fi-")); const classesToRemove = Array.from(activeLanguageIcon?.classList || []).filter((className) =>
activeLanguageIcon.classList.remove(...classesToRemove); className.startsWith("fi-"),
activeLanguageIcon.classList.add(activeLanguageIconClass); );
const languageSwitcherLabel = `${languageSwitcherText.textContent} (${btnToActive.dataset.bsLanguageValue})`; activeLanguageIcon?.classList.remove(...classesToRemove);
activeLanguageIcon?.classList.add(activeLanguageIconClass);
const languageSwitcherLabel = `${languageSwitcherText?.textContent} (${btnToActive?.dataset.bsLanguageValue})`;
languageSwitcher.setAttribute("aria-label", languageSwitcherLabel); languageSwitcher.setAttribute("aria-label", languageSwitcherLabel);
if (focus) { if (focus) {
languageSwitcher.focus(); languageSwitcher?.focus();
} }
}; };
@@ -25,7 +25,7 @@
setTheme(getPreferredTheme()); setTheme(getPreferredTheme());
const showActiveTheme = (theme: string, focus = false) => { const showActiveTheme = (theme: string, focus = false) => {
const themeSwitcher = document.querySelector("#bd-theme"); const themeSwitcher = document.querySelector<HTMLElement>("#bd-theme");
if (!themeSwitcher) { if (!themeSwitcher) {
return; return;
@@ -33,24 +33,26 @@
const themeSwitcherText = document.querySelector("#bd-theme-text"); const themeSwitcherText = document.querySelector("#bd-theme-text");
const activeThemeIcon = document.querySelector(".theme-icon-active"); const activeThemeIcon = document.querySelector(".theme-icon-active");
const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`); const btnToActive = document.querySelector<HTMLElement>(`[data-bs-theme-value="${theme}"]`);
const activeThemeIconClass = btnToActive.querySelector(".bi").className.match(/bi-[\w-]+/)[0]; const activeThemeIconClass = (btnToActive?.querySelector(".bi")?.className.match(/bi-[\w-]+/) || [])[0] || "";
document.querySelectorAll("[data-bs-theme-value]").forEach((element) => { document.querySelectorAll("[data-bs-theme-value]").forEach((element) => {
element.classList.remove("active"); element.classList.remove("active");
element.setAttribute("aria-pressed", "false"); element.setAttribute("aria-pressed", "false");
}); });
btnToActive.classList.add("active"); btnToActive?.classList.add("active");
btnToActive.setAttribute("aria-pressed", "true"); btnToActive?.setAttribute("aria-pressed", "true");
const classesToRemove = Array.from(activeThemeIcon.classList).filter((className) => className.startsWith("bi-")); const classesToRemove = Array.from(activeThemeIcon?.classList || []).filter((className) =>
activeThemeIcon.classList.remove(...classesToRemove); className.startsWith("bi-"),
activeThemeIcon.classList.add(activeThemeIconClass); );
const themeSwitcherLabel = `${themeSwitcherText.textContent} (${btnToActive.dataset.bsThemeValue})`; activeThemeIcon?.classList.remove(...classesToRemove);
activeThemeIcon?.classList.add(activeThemeIconClass);
const themeSwitcherLabel = `${themeSwitcherText?.textContent} (${btnToActive?.dataset.bsThemeValue})`;
themeSwitcher.setAttribute("aria-label", themeSwitcherLabel); themeSwitcher.setAttribute("aria-label", themeSwitcherLabel);
if (focus) { if (focus) {
themeSwitcher.focus(); themeSwitcher?.focus();
} }
}; };
@@ -66,7 +68,7 @@
document.querySelectorAll("[data-bs-theme-value]").forEach((toggle) => { document.querySelectorAll("[data-bs-theme-value]").forEach((toggle) => {
toggle.addEventListener("click", () => { toggle.addEventListener("click", () => {
const theme = toggle.getAttribute("data-bs-theme-value") || ''; const theme = toggle.getAttribute("data-bs-theme-value") || "";
setStoredTheme(theme); setStoredTheme(theme);
setTheme(theme); setTheme(theme);
showActiveTheme(theme, true); showActiveTheme(theme, true);
+6
View File
@@ -0,0 +1,6 @@
import { Tooltip } from "bootstrap";
document.addEventListener("DOMContentLoaded", (event) => {
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
const tooltipList = [...tooltipTriggerList].map((tooltipTriggerEl) => new Tooltip(tooltipTriggerEl));
});
@@ -1,10 +1,10 @@
class AppLinkElement extends HTMLElement { class AppLinkElement extends HTMLElement {
static observedAttributes = ["icon", "href"]; static observedAttributes = ["icon", "href", "target"];
constructor() { constructor() {
super(); super();
this.innerHTML = ` this.innerHTML = `
<a href="${this.getAttribute("href")}" <a href="${this.getAttribute("href")}" target="${this.getAttribute("target") || ""}"
class="d-flex align-items-center text-body text-decoration-none"> class="d-flex align-items-center text-body text-decoration-none">
<span class="fs-4"> <span class="fs-4">
<span class="bi bi-${this.getAttribute("icon")} me-1"></span> <span class="bi bi-${this.getAttribute("icon")} me-1"></span>
+52
View File
@@ -0,0 +1,52 @@
import { ListElement, ListItemElement, ValueElement } from "../base/component";
import { Channel } from "./model";
export class ScheduleChannelGroup extends ValueElement<string | Channel[], {}> {
className: string = "list-group-item list-group-item-action";
buildHTML(): string {
const groupName = Array.isArray(this.value) ? "Open All" : this.value;
const groupId = Array.isArray(this.value)
? this.value.map((item) => `${item.provider}:${item.id}`).join(",")
: this.value || "";
return `
<a href="group/${encodeURIComponent(groupId)}"
class="d-flex justify-content-between align-items-start text-decoration-none">
<span>
<span class="text-primary" style="text-transform: capitalize">${groupName}</span>
</span>
</a>`;
}
}
customElements.define("schedule-channel-group", ScheduleChannelGroup);
export class ScheduleChannelItem extends ListItemElement<Channel> {
getHref(value: Channel): string {
return `${value.provider}/${value.id}`;
}
getContent(value: Channel): string {
return `
<span class="badge me-1 text-bg-secondary">${value.provider}</span>
<span class="text-primary">${value.name}</span>
`;
}
}
export class ScheduleChannelList extends ListElement<Channel, ScheduleChannelItem> {
childType = ScheduleChannelItem;
public onRefresh(): void {
super.onRefresh();
if (this.value?.length) {
const groupElement = new ScheduleChannelGroup(this.value);
this.prepend(groupElement);
} else {
this.prepend("Empty");
}
}
}
customElements.define("schedule-channel-item", ScheduleChannelItem);
customElements.define("schedule-channel-list", ScheduleChannelList);
+11
View File
@@ -0,0 +1,11 @@
import { DataManager } from "../base/manager";
import { ScheduleChannelList } from "./component";
import { Channel } from "./model";
declare global {
interface Window {
scheduleChannelManager: DataManager<Channel>;
}
}
window.scheduleChannelManager = new DataManager(ScheduleChannelList, "schedule:channels", "#storedChannels");

Some files were not shown because too many files have changed in this diff Show More