Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
126d5310f5 | ||
|
|
ee3003c09a | ||
|
|
b556f2f948 | ||
|
|
d9016a0cb0 | ||
|
|
41914d7f74 | ||
|
|
de466de805 | ||
|
|
1bffafd6a3 | ||
|
|
46e72feb82 | ||
|
|
fdf6e0eac3 | ||
|
|
60651de186 | ||
|
|
bed8d7af7b | ||
|
|
6683b7b5b0 | ||
|
|
fa0edca522 | ||
|
|
f76f33b501 | ||
|
|
a6f6586969 | ||
|
|
1835935eaf | ||
|
|
5db61da32b | ||
|
|
d44c8076b4 | ||
|
|
24214ebc3a | ||
|
|
b5a8a1536c | ||
|
|
4aafe720dd | ||
|
|
7c2436fb57 | ||
|
|
d6487facf4 | ||
|
|
86879a3219 | ||
|
|
aa0d5a7a41 | ||
|
|
bec48e3289 | ||
|
|
d8ee66480c | ||
|
|
9f5c43ce92 | ||
|
|
60c0a7a6fc | ||
|
|
50c4221b8d | ||
|
|
a92b63b855 | ||
|
|
712c7615a6 | ||
|
|
1b5d009cdf | ||
|
|
ca08bc282d | ||
|
|
a19de3e01d | ||
|
|
f79f754f1b | ||
|
|
555b7f4392 | ||
|
|
b412a9cee3 | ||
|
|
b0245a1714 | ||
|
|
91b530f84c | ||
|
|
2b1dfad929 | ||
|
|
1df83ec34d | ||
|
|
1c4dac74ca | ||
|
|
75343a21b9 | ||
|
|
83fabdd538 | ||
|
|
29364bb7d4 | ||
|
|
195bd76608 | ||
|
|
436c6c7364 | ||
|
|
0a734f9c43 | ||
|
|
6171ec8a26 | ||
|
|
72fd148a54 | ||
|
|
12774db70f | ||
|
|
0008e99c66 | ||
|
|
bad5dff2b2 | ||
|
|
e2af31b812 | ||
|
|
6c76dae760 | ||
|
|
28951df9b5 | ||
|
|
5aa290c772 | ||
|
|
13a70990e5 | ||
|
|
a3fab92e3d | ||
|
|
4fdb7e9717 | ||
|
|
1d13f6e05d | ||
|
|
fcb000afb0 | ||
|
|
0730b9f567 | ||
|
|
081aa8d17f | ||
|
|
29fe06462e | ||
|
|
8b20eb1220 | ||
|
|
5333690c47 | ||
|
|
d82fc4ea46 | ||
|
|
df2f1d0d81 | ||
|
|
9192ca3e4a | ||
|
|
e37ca6eeac | ||
|
|
657a62eab5 | ||
|
|
d8e2be013a | ||
|
|
a91ec12d22 | ||
|
|
9c862863e5 | ||
|
|
fc59e52337 | ||
|
|
3e93a41400 | ||
|
|
c2cd18386b | ||
|
|
2bca3dd75a | ||
|
|
469bd9bc1f | ||
|
|
027d1e2d55 | ||
|
|
7cf0012229 | ||
|
|
edc014d98c | ||
|
|
1813ec213b | ||
|
|
1b700086f2 | ||
|
|
02a6ffc931 | ||
|
|
2dfedfea57 | ||
|
|
8012d9b8ed | ||
|
|
3a6faa85be | ||
|
|
1af61aa3c7 | ||
|
|
315838604e | ||
|
|
f368e6717c | ||
|
|
91e2c9d123 | ||
|
|
91d9c37612 | ||
|
|
b5f2c272bb | ||
|
|
eec72c77ab |
+1
-1
@@ -10,4 +10,4 @@ max_line_length = 120
|
||||
|
||||
[*.md]
|
||||
max_line_length = off
|
||||
trim_trailing_whitespace = false
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
@@ -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")
|
||||
@@ -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=""
|
||||
@@ -5,3 +5,5 @@
|
||||
#.vscode
|
||||
static/node_modules
|
||||
static/dist
|
||||
.env
|
||||
dist
|
||||
@@ -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,23 +4,12 @@ ignore=.venv
|
||||
[MESSAGES CONTROL]
|
||||
disable=
|
||||
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,
|
||||
invalid-name,
|
||||
duplicate-code,
|
||||
|
||||
extension-pkg-allow-list=
|
||||
lxml,
|
||||
GeoIP,
|
||||
pydantic
|
||||
too-few-public-methods,
|
||||
too-many-locals,
|
||||
no-else-return,
|
||||
|
||||
[MISCELLANEOUS]
|
||||
notes=FIXME,TODO
|
||||
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"python-envs.pythonProjects": [
|
||||
{
|
||||
"path": ".",
|
||||
"envManager": "ms-python.python:poetry",
|
||||
"packageManager": "ms-python.python:poetry"
|
||||
}
|
||||
]
|
||||
}
|
||||
+17
-6
@@ -1,4 +1,4 @@
|
||||
FROM python:3.12 AS builder
|
||||
FROM python:3.14 AS builder
|
||||
ENV POETRY_HOME="/opt/poetry"
|
||||
ENV PATH="$POETRY_HOME/bin:$PATH"
|
||||
RUN apt update && \
|
||||
@@ -7,7 +7,9 @@ WORKDIR /app
|
||||
RUN curl -sSL https://install.python-poetry.org | python3 -
|
||||
COPY pyproject.toml poetry.lock README.md ./
|
||||
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
|
||||
RUN cd locales/ru/LC_MESSAGES && msgfmt messages.po
|
||||
|
||||
@@ -15,19 +17,28 @@ FROM node:24 AS node-builder
|
||||
ENV PATH=/app/node_modules/.bin:$PATH
|
||||
WORKDIR /app
|
||||
COPY static/package.json static/package-lock.json ./
|
||||
RUN npm ci
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm ci
|
||||
COPY static ./
|
||||
RUN npm run build
|
||||
|
||||
FROM python:3.12-slim
|
||||
FROM python:3.14-slim
|
||||
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH="/opt/playwright-browsers"
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,sharing=locked \
|
||||
pip install playwright && \
|
||||
playwright install --with-deps chromium
|
||||
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV TZ="Europe/Moscow"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV TZ="Europe/Moscow"
|
||||
COPY --from=builder /app ./
|
||||
COPY --from=node-builder /app/dist ./static/dist
|
||||
|
||||
COPY gallery gallery/
|
||||
#COPY --from=builder /app/gallery/easel/route/view/locales /app/gallery/easel/route/view/locales
|
||||
COPY --from=builder --parents locales/**/*.mo ./
|
||||
|
||||
CMD ["uvicorn", "gallery.main:app", "--host", "0.0.0.0", "--port", "80", "--log-config", "gallery/logging.yaml"]
|
||||
|
||||
@@ -1,9 +1,75 @@
|
||||
# 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
|
||||
|
||||
## Swagger
|
||||
|
||||
https://api.shmyga.ru/docs
|
||||

|
||||
|
||||
@@ -12,6 +12,8 @@ services:
|
||||
build: .
|
||||
environment:
|
||||
- REDIS_HOST=redis
|
||||
- OPENWEATHER_KEY=$OPENWEATHER_KEY
|
||||
- GISMETEO_AUTH=$GISMETEO_AUTH
|
||||
- DEBUG=1
|
||||
ports:
|
||||
- 8000:80
|
||||
|
||||
+6
-4
@@ -1,17 +1,19 @@
|
||||
name: gallery
|
||||
name: gallery-${DOCKER_TAG}
|
||||
|
||||
services:
|
||||
redis:
|
||||
container_name: gallery-redis
|
||||
container_name: gallery-${DOCKER_TAG}-redis
|
||||
image: redis:alpine
|
||||
stop_grace_period: 3s
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
app:
|
||||
container_name: gallery-app
|
||||
image: ${DOCKER_ROOT}/gallery
|
||||
container_name: gallery-${DOCKER_TAG}-app
|
||||
image: ${DOCKER_ROOT}/gallery:${DOCKER_TAG}
|
||||
environment:
|
||||
- REDIS_HOST=redis
|
||||
- OPENWEATHER_KEY=$OPENWEATHER_KEY
|
||||
- GISMETEO_AUTH=$GISMETEO_AUTH
|
||||
depends_on:
|
||||
- redis
|
||||
ports:
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 182 KiB |
@@ -8,6 +8,8 @@
|
||||
"python.testing.pytestArgs": ["tests", "-s"],
|
||||
"python.testing.unittestEnabled": false,
|
||||
"python.testing.pytestEnabled": true,
|
||||
"python.terminal.useEnvFile": true,
|
||||
"python.analysis.importFormat": "relative",
|
||||
"python-envs.pythonProjects": [
|
||||
{
|
||||
"path": ".",
|
||||
@@ -34,6 +36,8 @@
|
||||
"request": "launch",
|
||||
"module": "uvicorn",
|
||||
"args": ["gallery.main:app", "--reload", "--log-config", "gallery/logging.yaml"],
|
||||
"justMyCode": true,
|
||||
"consoleTitle": "gallery:app",
|
||||
},
|
||||
{
|
||||
"name": "gallery:static",
|
||||
@@ -41,6 +45,7 @@
|
||||
"request": "launch",
|
||||
"type": "node-terminal",
|
||||
"command": "npm run dev",
|
||||
"consoleTitle": "gallery:static",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ caches.set_config(
|
||||
{
|
||||
"default": {
|
||||
"cache": "aiocache.SimpleMemoryCache",
|
||||
"serializer": {"class": "aiocache.serializers.StringSerializer"},
|
||||
"serializer": {"class": "aiocache.serializers.PickleSerializer"},
|
||||
},
|
||||
"redis": {
|
||||
"cache": "aiocache.RedisCache",
|
||||
|
||||
@@ -4,8 +4,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
from gallery.sketch.bundle import ApiBundle
|
||||
from gallery.util import root_path
|
||||
|
||||
from .route import api, doc
|
||||
from .route.view import router as view_router
|
||||
from .route import api, doc, view
|
||||
|
||||
|
||||
def build_app(api_bundle: ApiBundle) -> FastAPI:
|
||||
@@ -17,6 +16,6 @@ def build_app(api_bundle: ApiBundle) -> FastAPI:
|
||||
app.state.api = api_bundle
|
||||
app.mount("/static", StaticFiles(directory=root_path / "static/dist"))
|
||||
doc.mount(app)
|
||||
api.mount(app)
|
||||
app.include_router(view_router)
|
||||
app.include_router(api.router)
|
||||
app.include_router(view.router)
|
||||
return app
|
||||
|
||||
@@ -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
|
||||
@@ -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)]
|
||||
@@ -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))]
|
||||
@@ -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))]
|
||||
@@ -1,8 +1,7 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import APIRouter
|
||||
|
||||
from . import schedule, weather
|
||||
|
||||
|
||||
def mount(app: FastAPI):
|
||||
weather.mount(app)
|
||||
schedule.mount(app)
|
||||
router = APIRouter(prefix="/api")
|
||||
router.include_router(weather.router)
|
||||
router.include_router(schedule.router)
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import APIRouter
|
||||
|
||||
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):
|
||||
@app.get("/api/schedule/channels", tags=["API"])
|
||||
async def get_api_schedule_channels(request: AppRequest) -> list[ChannelId]:
|
||||
schedule_api = request.app.state.api.schedule
|
||||
return await schedule_api.get_channels()
|
||||
@router.get("/providers")
|
||||
async def get_api_weather_providers(request: AppRequest) -> list[str]:
|
||||
return request.app.state.api.get_api_providers(ScheduleApi)
|
||||
|
||||
@app.get("/api/schedule/{channel}/{date}", tags=["API"])
|
||||
|
||||
@router.get("/{provider}/channels")
|
||||
async def find_api_schedule_channels(schedule_api: ScheduleApiDepends, query: str) -> list[Channel]:
|
||||
return await schedule_api.find_channels(query)
|
||||
|
||||
|
||||
@router.get("/{provider}/{channel}/{date}")
|
||||
async def get_api_schedule_channel_schedule(
|
||||
request: AppRequest, channel: str, date: datetime.date
|
||||
schedule_api: ScheduleApiDepends, channel: str, date: DateDepends
|
||||
) -> Schedule:
|
||||
schedule_api = request.app.state.api.schedule
|
||||
return await schedule_api.get_channel_schedule(ChannelId(channel), date)
|
||||
return await schedule_api.get_schedule(channel, date)
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import APIRouter
|
||||
|
||||
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 ...depends.date import DateDepends
|
||||
|
||||
def mount(app: FastAPI):
|
||||
@app.get("/api/weather/locations", tags=["API"])
|
||||
async def get_api_weather_locations(
|
||||
request: AppRequest, query: str
|
||||
) -> list[Location]:
|
||||
weather_api = request.app.state.api.weather
|
||||
router = APIRouter(prefix="/weather", tags=["Weather"])
|
||||
|
||||
|
||||
@router.get("/providers")
|
||||
async def get_api_weather_providers(request: AppRequest) -> list[str]:
|
||||
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)
|
||||
|
||||
@app.get("/api/weather/{location}/day/{date}", tags=["API"])
|
||||
async def get_api_weather_day(
|
||||
request: AppRequest, location: str, date: datetime.date
|
||||
) -> WeatherResponse:
|
||||
weather_api = request.app.state.api.weather
|
||||
|
||||
@router.get("/{provider}/{location}/day/{date}")
|
||||
async def get_api_weather_day(weather_api: WeatherApiDepends, location: str, date: DateDepends) -> WeatherResponse:
|
||||
return await weather_api.get_day(location, date)
|
||||
|
||||
@app.get("/api/weather/{location}/days/{days}", tags=["API"])
|
||||
async def get_api_weather_days(
|
||||
request: AppRequest, location: str, days: int
|
||||
) -> WeatherResponse:
|
||||
weather_api = request.app.state.api.weather
|
||||
|
||||
@router.get("/{provider}/{location}/days/{days}")
|
||||
async def get_api_weather_days(weather_api: WeatherApiDepends, location: str, days: int) -> WeatherResponse:
|
||||
return await weather_api.get_days(location, days)
|
||||
|
||||
+346
-290
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -1,11 +1,11 @@
|
||||
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 .translation import set_language
|
||||
from .weather import router as weather_router
|
||||
|
||||
router = APIRouter(dependencies=[Depends(set_language)])
|
||||
router.include_router(common_router)
|
||||
router = APIRouter(tags=["view"], dependencies=[Depends(set_language)], include_in_schema=False)
|
||||
router.include_router(root_router)
|
||||
router.include_router(weather_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"
|
||||
href="/static/gallery.css?v={{version}}">
|
||||
<script type="module"
|
||||
src="/static/gallery.es.js?v={{version}}"></script>
|
||||
src="/static/gallery.js?v={{version}}"></script>
|
||||
<link rel="icon"
|
||||
href="/favicon.ico?v={{version}}"
|
||||
type="image/x-icon">
|
||||
{% endblock %}
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<body class="{{ is_widget and 'widget' or ''}}">
|
||||
<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="/"
|
||||
icon="gear">API Gallery</app-link>
|
||||
{% block header %}{% endblock %}
|
||||
</div>
|
||||
<ul class="navbar-nav flex-row flex-wrap ms-md-auto">
|
||||
<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"
|
||||
@@ -33,7 +36,7 @@
|
||||
aria-expanded="false"
|
||||
data-bs-toggle="dropdown"
|
||||
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"
|
||||
id="bd-language-text">{{_("Select language")}}</span>
|
||||
</button>
|
||||
@@ -44,7 +47,7 @@
|
||||
class="dropdown-item d-flex align-items-center"
|
||||
data-bs-language-value="en"
|
||||
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")}}
|
||||
</button>
|
||||
</li>
|
||||
@@ -53,7 +56,7 @@
|
||||
class="dropdown-item d-flex align-items-center"
|
||||
data-bs-language-value="ru"
|
||||
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")}}
|
||||
</button>
|
||||
</li>
|
||||
@@ -66,7 +69,7 @@
|
||||
aria-expanded="false"
|
||||
data-bs-toggle="dropdown"
|
||||
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"
|
||||
id="bd-theme-text">{{_("Toggle theme")}}</span>
|
||||
</button>
|
||||
@@ -103,22 +106,19 @@
|
||||
</li>
|
||||
</ul>
|
||||
</header>
|
||||
{% endif %}
|
||||
<main>
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
<footer class="pt-5 my-5 text-muted border-top">
|
||||
Created by shmyga · © 2026
|
||||
{% if not is_widget %}
|
||||
<footer class="app-footer pt-5 my-5 text-muted border-top">
|
||||
<div class="d-flex justify-content-between">
|
||||
<span>Created by shmyga · © 2026</span>
|
||||
<span>v{{ version }}</span>
|
||||
</div>
|
||||
</footer>
|
||||
{% endif %}
|
||||
</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>
|
||||
|
||||
</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 %}
|
||||
@@ -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
|
||||
@@ -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 +1 @@
|
||||
import datetime
|
||||
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,
|
||||
},
|
||||
)
|
||||
from .route import router
|
||||
|
||||
@@ -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" %}
|
||||
{% set live = request.query_params.live == '1' %}
|
||||
{% set date = response.date %}
|
||||
|
||||
{% 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 %}
|
||||
|
||||
{% 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>{{response.channel.name}} | {{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 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 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>
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td style="width:100%"></td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for value in response.values %}
|
||||
<tr class="{{'table-success' if value.live else ''}}">
|
||||
<td>{{value.start.strftime('%H:%M')}}</td>
|
||||
<td>{{(value.end - value.start) | timedelta_format}}</td>
|
||||
<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> <span class="small ms-1">({{(value.end - value.start) | timedelta_format}})</span>
|
||||
</td>
|
||||
<td>{{value.label}}</td>
|
||||
</tr>
|
||||
{% 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> <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 %}
|
||||
<h1>{{_("TV program")}}</h1>
|
||||
<div class="list-group mb-5">
|
||||
<a href="schedule/tag/today"
|
||||
class="list-group-item list-group-item-action px-4">
|
||||
<span class="fw-bold">Все</span>
|
||||
</a>
|
||||
{% for channel in channels %}
|
||||
<a href="schedule/{{channel.id}}"
|
||||
class="list-group-item list-group-item-action px-4">
|
||||
<span class="text-primary">{{channel.name}}</span>
|
||||
</a>
|
||||
<form action=""
|
||||
method="get"
|
||||
class="mb-4">
|
||||
<div class="input-group mb-3">
|
||||
<input type="text"
|
||||
class="form-control"
|
||||
id="query"
|
||||
name="query"
|
||||
placeholder="{{_('Enter the channel 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"
|
||||
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>
|
||||
{% 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 %}
|
||||
@@ -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 %}
|
||||
@@ -5,9 +5,7 @@ from fastapi import Cookie, Header, Request
|
||||
|
||||
from gallery.util import root_path
|
||||
|
||||
_translation: ContextVar[gettext.GNUTranslations | gettext.NullTranslations] = (
|
||||
ContextVar("translation")
|
||||
)
|
||||
_translation: ContextVar[gettext.GNUTranslations | gettext.NullTranslations] = ContextVar("translation")
|
||||
|
||||
|
||||
async def set_language(
|
||||
@@ -19,9 +17,7 @@ async def set_language(
|
||||
lang = language or accept_language.split(",")[0].split("-")[0]
|
||||
|
||||
try:
|
||||
t = gettext.translation(
|
||||
"messages", localedir=root_path / "locales", languages=[lang]
|
||||
)
|
||||
t = gettext.translation("messages", localedir=root_path / "locales", languages=[lang])
|
||||
except FileNotFoundError:
|
||||
t = gettext.NullTranslations()
|
||||
|
||||
|
||||
@@ -1,92 +1 @@
|
||||
import datetime
|
||||
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)
|
||||
from .route import router
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import datetime
|
||||
|
||||
from markupsafe import Markup
|
||||
|
||||
from gallery.sketch.weather.model import (
|
||||
Cloudness,
|
||||
Precipitation,
|
||||
@@ -5,44 +9,73 @@ from gallery.sketch.weather.model import (
|
||||
WindDirection,
|
||||
WindDirectionDeg,
|
||||
)
|
||||
from gallery.util import root_path
|
||||
|
||||
|
||||
def wind_direction_icon(wind_direction_deg: float) -> str:
|
||||
wind_direction = WindDirectionDeg(wind_direction_deg).direction
|
||||
return {
|
||||
WindDirection.N: "⬇️",
|
||||
WindDirection.NE: "↙️",
|
||||
WindDirection.E: "⬅️",
|
||||
WindDirection.SE: "↖️",
|
||||
WindDirection.S: "⬆️",
|
||||
WindDirection.SW: "↗️",
|
||||
WindDirection.W: "➡️",
|
||||
WindDirection.NW: "↘️",
|
||||
WindDirection.CALM: "",
|
||||
}.get(wind_direction, wind_direction)
|
||||
if wind_direction == WindDirection.CALM:
|
||||
return "wind-calm"
|
||||
else:
|
||||
return f"wind-from-{wind_direction.name.lower()}"
|
||||
|
||||
|
||||
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 = ""
|
||||
if sky.thunder:
|
||||
if sky.cloudness == Cloudness.CLEAR:
|
||||
main_icon = "🌩️"
|
||||
if sky.precipitation == Precipitation.NO:
|
||||
main_icon = "⚡"
|
||||
else:
|
||||
main_icon = "⛈️"
|
||||
main_icon = {
|
||||
Precipitation.NO: "lightning",
|
||||
Precipitation.SMALL_RAIN: "storm-showers",
|
||||
Precipitation.RAIN: "thunderstorm",
|
||||
Precipitation.HEAVY_RAIN: "thunderstorm",
|
||||
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:
|
||||
main_icon = {
|
||||
Cloudness.CLEAR: "☀️",
|
||||
Cloudness.PARTLY_CLOUDY: "🌤️",
|
||||
Cloudness.CLOUDY: "⛅",
|
||||
Cloudness.MAINLY_CLOUDY: "☁️",
|
||||
Cloudness.CLEAR: "day-sunny" if day else "night-clear",
|
||||
Cloudness.PARTLY_CLOUDY: f"{day_prefix}-cloudy",
|
||||
Cloudness.CLOUDY: "cloud",
|
||||
Cloudness.MAINLY_CLOUDY: "cloudy",
|
||||
}[sky.cloudness]
|
||||
elif sky.precipitation in [Precipitation.SNOW, Precipitation.HEAVY_SNOW]:
|
||||
main_icon = "🌨️"
|
||||
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]
|
||||
if sky.fog:
|
||||
icons.append("🌫️")
|
||||
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)
|
||||
|
||||
@@ -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"
|
||||
name="query"
|
||||
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"
|
||||
type="submit">{{_("Search")}}</button>
|
||||
</div>
|
||||
</form>
|
||||
<ul id="locations"
|
||||
class="list-group mb-5">
|
||||
{% for location in locations %}
|
||||
<a href="weather/{{location.id}}"
|
||||
class="list-group-item list-group-item-action px-4"
|
||||
onclick="saveLocation({id:'{{location.id}}', name:'{{location.name}}'});">
|
||||
<span class="fi fi-{{location.country_code}} me-1"></span>
|
||||
<span class="text-primary">{{location.name}}</span>
|
||||
<span class="small ms-1 text-secondary">
|
||||
{{location.country}}, {{location.district}}, {{location.subdistrict}}
|
||||
</span>
|
||||
<span></span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% if locations %}
|
||||
<div class="mb-4">
|
||||
<weather-location-list value="{{locations | tojson | forceescape}}"
|
||||
onclick="weatherLocationManager.store(element)"
|
||||
onadd="weatherLocationManager.add(element)"></weather-location-list>
|
||||
<hr>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="mb-4">
|
||||
<h3>{{_("Stored locations")}}</h3>
|
||||
<weather-location-list id="storedLocations"
|
||||
onremove="weatherLocationManager.remove(element)"></weather-location-list>
|
||||
</div>
|
||||
<script>
|
||||
(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();">✕</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 searchQuery = params.get('query');
|
||||
if (searchQuery) {
|
||||
document.querySelector('#query').value = searchQuery;
|
||||
} else {
|
||||
document.loadLocations();
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", (event) => {
|
||||
weatherLocationManager.load();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,24 +1,37 @@
|
||||
{% 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 %}
|
||||
<span class="fs-4 text-body ms-2 me-2">/</span>
|
||||
<app-link href="/weather" icon="brightness-high">{{_("Weather")}}</app-link>
|
||||
<app-link href="/weather"
|
||||
icon="brightness-high">{{_("Weather")}}</app-link>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h4>
|
||||
{% if response.period == 'day' %}
|
||||
<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="../tag/days-10">⬆️</a>
|
||||
<span>{{response.location}} | {{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>
|
||||
<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, path=['..', '..', 'days', '10'])}}">
|
||||
<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 %}
|
||||
{% 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 %}
|
||||
</h4>
|
||||
<div class="table-responsive">
|
||||
@@ -37,7 +50,7 @@
|
||||
{% if response.period == 'days' %}
|
||||
<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 ''}}">
|
||||
<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)}}
|
||||
</a>
|
||||
</span>
|
||||
@@ -54,9 +67,12 @@
|
||||
</tr>
|
||||
<tr>
|
||||
{% for value in response.values %}
|
||||
<td class="cloudness">
|
||||
{% for icon in value.sky | cloudness_icon %}
|
||||
<div class="icon">{{icon}}</div>
|
||||
<td class="cloudness"
|
||||
data-bs-toggle="tooltip"
|
||||
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 %}
|
||||
</td>
|
||||
{% endfor %}
|
||||
@@ -89,8 +105,11 @@
|
||||
</tr>
|
||||
<tr>
|
||||
{% for value in response.values %}
|
||||
<td class="wind">
|
||||
<span class="icon">{{value.wind_direction | wind_direction_icon}}</span>
|
||||
<td class="wind"
|
||||
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>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
@@ -106,7 +125,7 @@
|
||||
<td class="wind"
|
||||
style="background-color: rgba(128, 128, 128, {{value.wind_speed * 0.05}});">
|
||||
<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">
|
||||
({{value.wind_gust}})
|
||||
</span>
|
||||
@@ -125,7 +144,7 @@
|
||||
{% for value in response.values %}
|
||||
<td class="precipitation"
|
||||
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>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
@@ -158,7 +177,7 @@
|
||||
{% for value in response.values %}
|
||||
<td class="humidity"
|
||||
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>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
|
||||
@@ -7,7 +7,9 @@ from gallery.easel import build_app
|
||||
from gallery.painting.gismeteo.api import GismeteoApi
|
||||
from gallery.painting.matchtv.api import MatchTvApi
|
||||
from gallery.painting.openweather.api import OpenWeatherApi
|
||||
from gallery.painting.rp5.api import RP5WeatherApi
|
||||
from gallery.painting.yandextv.api import YandexTvApi
|
||||
from gallery.painting.yandexweather.api import YandexWeatherApi
|
||||
from gallery.sketch.bundle import ApiBundle
|
||||
from gallery.sketch.schedule.cached import CachedScheduleApi
|
||||
from gallery.sketch.weather.cached import CachedWeatherApi
|
||||
@@ -18,6 +20,8 @@ api = ApiBundle(
|
||||
CachedScheduleApi(MatchTvApi()),
|
||||
CachedWeatherApi(GismeteoApi()),
|
||||
CachedWeatherApi(OpenWeatherApi()),
|
||||
CachedWeatherApi(YandexWeatherApi()),
|
||||
CachedWeatherApi(RP5WeatherApi()),
|
||||
]
|
||||
)
|
||||
app = build_app(api)
|
||||
|
||||
@@ -1,36 +1,40 @@
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
from os import environ
|
||||
from typing import Any
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from gallery.sketch.source import ApiSource
|
||||
from gallery.sketch.weather.api import WeatherApi
|
||||
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
|
||||
|
||||
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):
|
||||
PROVIDER = "gismeteo"
|
||||
SOURCE = ApiSource(
|
||||
|
||||
def _build_source(self) -> ApiSource:
|
||||
return ApiSource(
|
||||
"https://www.gismeteo.ru",
|
||||
cookies={
|
||||
"cf_clearance": (
|
||||
"zPj8qeaYZWp5BUZsWIRD7kd32s59IDWWaVvD7GGf6b4-1724254262-1.2.1.1-"
|
||||
"R1PaHoqlm4OEgHfrOg6oAJmVmFJ7053JI_QDjIFlCAmbNY0oyw1J4QtgmEkAkTWF4C99X5hpXmZB2en."
|
||||
"9Ey3NL0kzaE10UGBHPli5OLxHNKC3wQ34xmxTxg6GcKouXOPRgqo92lVRpQP7ghvDmvvT_"
|
||||
"S6YXDbRonkamptWhZiAsIhsnIQg2Mt7Lk1fxSEVbaey_RXVQBvaR2ofiFgIavcbQPRFSvJ."
|
||||
"Ct_FujmymTAZWh1XHTptK32kur81NXyPuARThetOKQm8AklaMa855Oom6Bms1a4F9b0yEHSd2inA4j3FR7uauu8hhwO0Z2goa3."
|
||||
"ktpXXAQLz6dm.fBEWIHD7wooda15X57tCcDOely4hxhO4LK2lIH6TbOr."
|
||||
"rZQAiRRhltHiCizP1Ou2SiF_81lb1umoDh739tQD1cnw_USnL."
|
||||
"JwTHvkB00ZnaHRMi4FCBrsKIE0NxJO6kiv1QANqumzf5.8_pSIGRo2cKeO8xCydduDNFbStdOmLR6FU7ZKqVu"
|
||||
)
|
||||
},
|
||||
cookies={"xauth": auth} if (auth := environ.get("GISMETEO_AUTH")) else None,
|
||||
)
|
||||
|
||||
def _parse_oneday(self, date: datetime.date, data: str) -> WeatherResponse:
|
||||
@@ -44,6 +48,12 @@ class GismeteoApi(WeatherApi):
|
||||
result.append({})
|
||||
result[index][parser.KEY] = value
|
||||
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(
|
||||
location=location or "n/a",
|
||||
date=date,
|
||||
@@ -74,7 +84,7 @@ class GismeteoApi(WeatherApi):
|
||||
latitude = 52.968498
|
||||
longitude = 36.0695
|
||||
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"
|
||||
)
|
||||
)
|
||||
@@ -84,11 +94,14 @@ class GismeteoApi(WeatherApi):
|
||||
Location(
|
||||
id=f"{item['slug']}-{item['id']}",
|
||||
name=item["translations"]["kk"]["city"]["name"],
|
||||
provider=self.provider,
|
||||
lat=item["coordinates"]["latitude"],
|
||||
lon=item["coordinates"]["longitude"],
|
||||
country=item["translations"]["kk"]["country"]["name"],
|
||||
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=(
|
||||
item["translations"]["kk"]["subdistrict"]["name"]
|
||||
if "subdistrict" in item["translations"]["kk"]
|
||||
@@ -99,9 +112,14 @@ class GismeteoApi(WeatherApi):
|
||||
return result
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -1,6 +1,7 @@
|
||||
import datetime
|
||||
import logging
|
||||
import re
|
||||
from typing import Iterable
|
||||
from typing import Generic, Iterable, Optional, TypeVar
|
||||
|
||||
import dateparser
|
||||
from bs4 import Tag
|
||||
@@ -10,10 +11,39 @@ from gallery.sketch.weather.model import (
|
||||
Precipitation,
|
||||
Sky,
|
||||
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")
|
||||
DAYS_PARSER = BaseWidgetParser(".widget.widget-days .widget-items")
|
||||
@@ -36,21 +66,22 @@ class DateParser(RowParser[datetime.datetime]):
|
||||
KEY = "date"
|
||||
|
||||
def parse_row(self, tag: Tag) -> Iterable[datetime.datetime]:
|
||||
datetime_date_tag = tag.select_one(
|
||||
".widget-row.widget-row-datetime-date > .row-item"
|
||||
)
|
||||
if datetime_date_tag:
|
||||
date_str = datetime_date_tag.find(text=True, recursive=False).text
|
||||
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)
|
||||
datetime_time_row = tag.select_one(".widget-row.widget-row-datetime-time")
|
||||
if datetime_time_row:
|
||||
for item in datetime_time_row.select(".row-item > time-value"):
|
||||
timestamp = int(item.attrs["timestamp"])
|
||||
time = datetime.datetime.fromtimestamp(timestamp)
|
||||
yield time
|
||||
else:
|
||||
month = None
|
||||
for item in tag.select(".widget-row.widget-row-date > .row-item"):
|
||||
date_str = item.text
|
||||
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
|
||||
|
||||
|
||||
@@ -59,6 +90,7 @@ class SkyParser(RowParser[Sky]):
|
||||
|
||||
CLOUDNESS_MAP: dict[str, Cloudness] = {
|
||||
"ясно": Cloudness.CLEAR,
|
||||
"безоблачно": Cloudness.CLEAR,
|
||||
"малооблачно": Cloudness.PARTLY_CLOUDY,
|
||||
"облачно": Cloudness.CLOUDY,
|
||||
"пасмурно": Cloudness.MAINLY_CLOUDY,
|
||||
@@ -66,8 +98,11 @@ class SkyParser(RowParser[Sky]):
|
||||
|
||||
PRECIPITATION_MAP: dict[str, Precipitation] = {
|
||||
"без осадков": Precipitation.NO,
|
||||
"без существенных осадков": Precipitation.NO,
|
||||
"небольшой дождь": Precipitation.SMALL_RAIN,
|
||||
"сильный дождь": Precipitation.HEAVY_RAIN,
|
||||
"очень сильный дождь": Precipitation.HEAVY_RAIN,
|
||||
"ливневый дождь": Precipitation.SHOWER,
|
||||
"дождь": Precipitation.RAIN,
|
||||
"ливень": Precipitation.SHOWER,
|
||||
"снег": Precipitation.SNOW,
|
||||
@@ -78,24 +113,37 @@ class SkyParser(RowParser[Sky]):
|
||||
"сильный снег с дождём": Precipitation.HEAVY_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]:
|
||||
for item in tag.select(".widget-row[data-row=icon-tooltip] > .row-item"):
|
||||
sky_str = item.attrs["data-tooltip"]
|
||||
values = {item.strip().lower() for item in sky_str.split(",")}
|
||||
cloudness = Cloudness.CLEAR
|
||||
precipitation = Precipitation.NO
|
||||
thunder = "гроза" in values
|
||||
fog = "дымка" in values
|
||||
values, thunder = self._detect_flag(values, self.THUNDER)
|
||||
values, fog = self._detect_flag(values, self.FOG)
|
||||
for k, v in self.CLOUDNESS_MAP.items():
|
||||
if k in values:
|
||||
cloudness = v
|
||||
values.remove(k)
|
||||
break
|
||||
for k, v in self.PRECIPITATION_MAP.items():
|
||||
if k in values:
|
||||
precipitation = v
|
||||
values.remove(k)
|
||||
break
|
||||
if values:
|
||||
logger.warning("unknown sky values: %s:", values)
|
||||
yield Sky(
|
||||
cloudness=cloudness,
|
||||
precipitation=precipitation,
|
||||
@@ -108,21 +156,15 @@ class TemperatureParser(RowParser[list[int]]):
|
||||
KEY = "temperature"
|
||||
|
||||
def parse_row(self, tag: Tag) -> Iterable[list[int]]:
|
||||
for item in tag.select(
|
||||
".widget-row-chart[data-row=temperature-air] > .chart > .values > .value"
|
||||
):
|
||||
yield [
|
||||
int(value.attrs["value"]) for value in item.select("temperature-value")
|
||||
]
|
||||
for item in tag.select(".widget-row-chart[data-row=temperature-air] > .chart > .values > .value"):
|
||||
yield [int(value.attrs["value"]) for value in item.select("temperature-value")]
|
||||
|
||||
|
||||
class WindSpeedParser(RowParser[int]):
|
||||
KEY = "wind_speed"
|
||||
|
||||
def parse_row(self, tag: Tag) -> Iterable[int]:
|
||||
for item in tag.select(
|
||||
".widget-row-wind > .row-item > .wind-speed > speed-value"
|
||||
):
|
||||
for item in tag.select(".widget-row-wind > .row-item > .wind-speed > speed-value"):
|
||||
yield int(item.attrs["value"])
|
||||
|
||||
|
||||
@@ -138,46 +180,29 @@ class WindGustParser(RowParser[int]):
|
||||
class WindDirectionParser(RowParser[WindDirection]):
|
||||
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]:
|
||||
for item in tag.select(
|
||||
".widget-row-wind > .row-item > .wind-speed > .wind-direction"
|
||||
):
|
||||
for item in tag.select(".widget-row-wind > .row-item > .wind-speed > .wind-direction"):
|
||||
wind_direction_str = item.text.lower().strip()
|
||||
yield WindDirectionDeg.from_direction(
|
||||
self.WIND_DIRECTION_MAP[wind_direction_str]
|
||||
).value
|
||||
yield parse_wind_direction(wind_direction_str)
|
||||
|
||||
|
||||
class PrecipitationParser(RowParser[float]):
|
||||
KEY = "precipitation"
|
||||
|
||||
def parse_row(self, tag: Tag) -> Iterable[float]:
|
||||
for item in tag.select(
|
||||
".widget-row[data-row=precipitation-bars] > .row-item > .item-unit"
|
||||
):
|
||||
yield float(item.text.replace(",", "."))
|
||||
for item in tag.select(".widget-row[data-row=precipitation-bars] > .row-item"):
|
||||
value = item.select_one("precipitation-value")
|
||||
if value:
|
||||
yield float(value.attrs["value"])
|
||||
else:
|
||||
yield 0
|
||||
|
||||
|
||||
class PressureParser(RowParser[list[int]]):
|
||||
KEY = "pressure"
|
||||
|
||||
def parse_row(self, tag: Tag) -> Iterable[list[int]]:
|
||||
for item in tag.select(
|
||||
".widget-row-chart[data-row=pressure] > .chart > .values > .value"
|
||||
):
|
||||
for item in tag.select(".widget-row-chart[data-row=pressure] > .chart > .values > .value"):
|
||||
yield [int(value.attrs["value"]) for value in item.select("pressure-value")]
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
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
|
||||
|
||||
logger = logging.getLogger("matchtv")
|
||||
@@ -12,45 +11,34 @@ logger = logging.getLogger("matchtv")
|
||||
|
||||
class MatchTvApi(ScheduleApi):
|
||||
PROVIDER = "matchtv"
|
||||
SOURCE = ApiSource("https://matchtv.ru")
|
||||
|
||||
async def get_channels(self) -> list[ChannelId]:
|
||||
return [
|
||||
ChannelId.MATCH_TV,
|
||||
ChannelId.MATCH_IGRA,
|
||||
ChannelId.MATCH_ARENA,
|
||||
ChannelId.MATCH_FUTBOL_1,
|
||||
ChannelId.MATCH_FUTBOL_2,
|
||||
ChannelId.MATCH_FUTBOL_3,
|
||||
ChannelId.MATCH_STRANA,
|
||||
]
|
||||
def _build_source(self) -> ApiSource:
|
||||
return ApiSource("https://matchtv.ru")
|
||||
|
||||
async def get_channel_schedule(
|
||||
self, channel_id: ChannelId, date: datetime.date
|
||||
) -> Schedule:
|
||||
endpoint = f"tvguide/{channel_id}?date={date:%Y%m%d}"
|
||||
data = await self.SOURCE.request(endpoint)
|
||||
soup = BeautifulSoup(data, features="html.parser")
|
||||
async def find_channels(self, query: str) -> list[Channel]:
|
||||
endpoint = "api/v1/channels"
|
||||
data = json.loads(await self.source.request(endpoint))
|
||||
result = []
|
||||
query = query.lower()
|
||||
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 = []
|
||||
channel_name = (
|
||||
soup.select_one(".p-tv-guide-header__title")
|
||||
.text.replace("Телепрограмма ", "")
|
||||
.strip()
|
||||
)
|
||||
current_day = datetime.datetime.combine(
|
||||
date.today(), datetime.datetime.min.time()
|
||||
)
|
||||
current_day = datetime.datetime.combine(date.today(), datetime.datetime.min.time())
|
||||
end = current_day + datetime.timedelta(days=1, hours=6)
|
||||
prev_value: ScheduleValue | None = None
|
||||
for item in soup.select(
|
||||
".p-tv-guide-schedule-channel-carcass__transmissions .p-tv-guide-schedule-channel-transmission"
|
||||
):
|
||||
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()
|
||||
for item in channel_data["schedule"]:
|
||||
title = item["title"]
|
||||
time_str = item["time"]
|
||||
hours, minutes = map(int, time_str.split(":"))
|
||||
item_date = current_day.replace(hour=hours, minute=minutes)
|
||||
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 = value
|
||||
return Schedule(
|
||||
channel=Channel(id=channel_id, name=channel_name), date=date, values=values
|
||||
channel=channel,
|
||||
date=date,
|
||||
values=values,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import datetime
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from os import environ
|
||||
|
||||
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.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
|
||||
|
||||
logger = logging.getLogger("openweather")
|
||||
|
||||
|
||||
class OpenWeatherApi(WeatherApi):
|
||||
class OpenWeatherApi(WeatherApi[OpenWeather]):
|
||||
PROVIDER = "openweather"
|
||||
SOURCE = OpenWeather("517a6bccceaa1c48127f6199ec3fb7cf")
|
||||
|
||||
def _build_source(self) -> OpenWeather:
|
||||
return OpenWeather(environ["OPENWEATHER_KEY"])
|
||||
|
||||
@classmethod
|
||||
def _parse_location(cls, location_id: str) -> tuple[float, float]:
|
||||
return tuple(map(float, location_id.split(":", maxsplit=2)))
|
||||
|
||||
@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",
|
||||
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:
|
||||
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]:
|
||||
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:
|
||||
location: OpenWeatherLocation = await self._get_location(location_id)
|
||||
data: Forecast = await self._get_location_forecast(location_id)
|
||||
values = []
|
||||
for item in data.list:
|
||||
@@ -42,25 +70,23 @@ class OpenWeatherApi(WeatherApi):
|
||||
if value.date.date() == date:
|
||||
values.append(value)
|
||||
return WeatherResponse(
|
||||
location=location_id,
|
||||
location=location.name,
|
||||
date=date,
|
||||
period="day",
|
||||
values=values,
|
||||
)
|
||||
|
||||
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)
|
||||
values_by_date: dict[datetime.datetime, list[WeatherValue]] = defaultdict(list)
|
||||
for item in data.list:
|
||||
value = FORECAST_ITEM_PARSER.parse(item)
|
||||
item_date = value.date.replace(hour=0, minute=0)
|
||||
values_by_date[item_date].append(value)
|
||||
values = [
|
||||
merge_weather_values(date, values)
|
||||
for date, values in values_by_date.items()
|
||||
]
|
||||
values = [merge_weather_values(date, values) for date, values in values_by_date.items()]
|
||||
return WeatherResponse(
|
||||
location=location_id,
|
||||
location=location.name,
|
||||
date=datetime.date.today(),
|
||||
period="days",
|
||||
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")
|
||||
@@ -53,7 +53,7 @@ class ForecastItem(Model):
|
||||
weather: list[Weather]
|
||||
clouds: Clouds
|
||||
wind: Wind
|
||||
visibility: int
|
||||
visibility: int | None = None
|
||||
pop: float
|
||||
rain: Rain | None = None
|
||||
sys: Sys
|
||||
@@ -67,17 +67,37 @@ class Forecast(Model):
|
||||
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"
|
||||
|
||||
def __init__(self, api_key: str):
|
||||
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:
|
||||
endpoint = (
|
||||
f"data/2.5/forecast?lat={lat}&lon={lon}&appid={self._api_key}&units=metric"
|
||||
)
|
||||
response = await self._source.request(endpoint)
|
||||
endpoint = f"data/2.5/forecast?lat={lat}&lon={lon}&appid={self._api_key}&units=metric"
|
||||
response = await self.request(endpoint)
|
||||
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])
|
||||
|
||||
@@ -24,26 +24,18 @@ class ForecastItemParser:
|
||||
|
||||
def parse(self, item: ForecastItem) -> WeatherValue:
|
||||
item_date = datetime.datetime.fromtimestamp(item.dt, datetime.UTC)
|
||||
item_date = (
|
||||
item_date.replace(tzinfo=datetime.timezone.utc)
|
||||
.astimezone(tz=None)
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
item_date = item_date.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None).replace(tzinfo=None)
|
||||
value = build_weather_value(item_date)
|
||||
# TODO parse temperature interval flag
|
||||
value.temperature = [round(item.main.temp)]
|
||||
# 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.wind_speed = round(item.wind.speed)
|
||||
value.wind_gust = round(item.wind.gust)
|
||||
value.wind_direction = item.wind.deg
|
||||
value.sky.cloudness = self.CLOUDNESS_MAP.get(
|
||||
item.weather[0].description, Cloudness.CLEAR
|
||||
)
|
||||
value.sky.precipitation = self.PRECIPITATION_MAP.get(
|
||||
item.weather[0].description, Precipitation.NO
|
||||
)
|
||||
value.sky.cloudness = self.CLOUDNESS_MAP.get(item.weather[0].description, Cloudness.CLEAR)
|
||||
value.sky.precipitation = self.PRECIPITATION_MAP.get(item.weather[0].description, Precipitation.NO)
|
||||
if item.rain:
|
||||
value.precipitation = round(item.rain.interval_3h, 1)
|
||||
return value
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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 or "завтра" 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
|
||||
@@ -1,78 +1,46 @@
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
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 ...sketch.headers import build_headers
|
||||
|
||||
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):
|
||||
PROVIDER = "yandextv"
|
||||
SOURCE = ApiSource("https://tv.yandex.ru", headers=HEADERS)
|
||||
|
||||
async def get_channels(self) -> list[ChannelId]:
|
||||
return list(CHANNELS_MAP.keys())
|
||||
def _build_source(self) -> ApiSource:
|
||||
return ApiSource("https://tv.yandex.ru", headers=build_headers("tv.yandex.ru"))
|
||||
|
||||
async def get_channel_schedule(
|
||||
self, channel_id: ChannelId, date: datetime.date
|
||||
) -> Schedule:
|
||||
endpoint = f"channel/{CHANNELS_MAP[channel_id]}?date={date:%Y-%m-%d}"
|
||||
data = await self.SOURCE.request(endpoint)
|
||||
async def find_channels(self, query: str) -> list[Channel]:
|
||||
url = (
|
||||
"https://suggest-multi.yandex.ru/suggest-tv2?"
|
||||
f"v=4&uil=ru&lr=10&count_channels=4&count_programs=4&sn=50&part={query}"
|
||||
)
|
||||
_, 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")
|
||||
if soup.select_one(".CheckboxCaptcha") is not None:
|
||||
raise RuntimeError("Captcha")
|
||||
values = []
|
||||
channel_name = soup.select_one(".channel-header__text").text.strip()
|
||||
current_day = datetime.datetime.combine(
|
||||
date.today(), datetime.datetime.min.time()
|
||||
)
|
||||
current_day = datetime.datetime.combine(date.today(), datetime.datetime.min.time())
|
||||
end = current_day + datetime.timedelta(days=1, hours=6)
|
||||
prev_value: ScheduleValue | None = None
|
||||
for item in soup.select(".channel-schedule .channel-schedule__event"):
|
||||
@@ -90,5 +58,7 @@ class YandexTvApi(ScheduleApi):
|
||||
prev_value.end = item_date
|
||||
prev_value = value
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
@@ -1,12 +1,32 @@
|
||||
from typing import TypeVar
|
||||
|
||||
from .source import ApiSource
|
||||
|
||||
class Api:
|
||||
S = TypeVar("S", bound=ApiSource)
|
||||
|
||||
|
||||
class Api[S = ApiSource]:
|
||||
TYPE: str
|
||||
PROVIDER: str
|
||||
|
||||
_source: S | None = None
|
||||
|
||||
def _build_source(self) -> S:
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return self.TYPE
|
||||
|
||||
@property
|
||||
def provider(self) -> str:
|
||||
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)
|
||||
|
||||
+14
-23
@@ -1,28 +1,19 @@
|
||||
from collections import defaultdict
|
||||
|
||||
from .api import API, Api
|
||||
from .schedule.api import ScheduleApi
|
||||
from .weather.api import WeatherApi
|
||||
|
||||
|
||||
class ApiBundle(list[Api]):
|
||||
def __init__(self, values: list[Api]) -> None:
|
||||
super().__init__(values)
|
||||
class ApiBundle:
|
||||
def __init__(self, values: list[Api]):
|
||||
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:
|
||||
for value in self:
|
||||
if value.PROVIDER == provider:
|
||||
return value
|
||||
raise ValueError(provider)
|
||||
def get_api_providers(self, api_type: type[API]) -> list[str]:
|
||||
return self._providers_by_api[api_type.TYPE]
|
||||
|
||||
def get_api_by_type(self, api_type: type[API]) -> API:
|
||||
for value in self:
|
||||
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)
|
||||
def get_api(self, api_type: type[API], provider: str) -> API:
|
||||
return self._api_map[(api_type.TYPE, provider)]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from typing import Generic, NamedTuple
|
||||
|
||||
from gallery.sketch.source import ApiSource
|
||||
from gallery.util import TimeUnit
|
||||
|
||||
from .api import API, Api
|
||||
@@ -19,6 +20,9 @@ class CachedApi(Api, Generic[API]):
|
||||
def __init__(self, api: API):
|
||||
self._api = api
|
||||
|
||||
def _build_source(self) -> ApiSource:
|
||||
raise RuntimeError("Source not used in CachedApi")
|
||||
|
||||
@property
|
||||
def provider(self) -> str:
|
||||
return self._api.provider
|
||||
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -1,28 +1,15 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
|
||||
from ..api import Api
|
||||
from .model import ChannelId, Schedule
|
||||
from ..source import ApiSource
|
||||
from .model import Channel, Schedule
|
||||
|
||||
|
||||
class ScheduleApi(Api):
|
||||
INTERVAL: float = 0.5
|
||||
class ScheduleApi[S = ApiSource](Api[S]):
|
||||
TYPE = "schedule"
|
||||
|
||||
async def get_channels(self) -> list[ChannelId]:
|
||||
async def find_channels(self, query: str) -> list[Channel]:
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_channel_schedule(
|
||||
self, channel_id: ChannelId, date: datetime.date
|
||||
) -> Schedule:
|
||||
async def get_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
|
||||
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
|
||||
|
||||
@@ -6,20 +6,20 @@ from gallery.sketch.cached import CachedApi, CachePreset
|
||||
from gallery.util import TimeUnit
|
||||
|
||||
from .api import ScheduleApi
|
||||
from .model import ChannelId, Schedule
|
||||
from .model import Channel, Schedule
|
||||
|
||||
CACHE_PRESET = CachePreset(ttl=TimeUnit.HOUR * 6)
|
||||
|
||||
|
||||
class CachedScheduleApi(ScheduleApi, CachedApi[ScheduleApi]):
|
||||
CACHE_KEY = "schedule"
|
||||
CACHE_KEY = ScheduleApi.TYPE
|
||||
|
||||
@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(),
|
||||
)
|
||||
async def get_channels(self) -> list[ChannelId]:
|
||||
return await self._api.get_channels()
|
||||
async def find_channels(self, query: str) -> list[Channel]:
|
||||
return await self._api.find_channels(query)
|
||||
|
||||
@cached(
|
||||
key_builder=lambda fun, self, channel_id, date: (
|
||||
@@ -27,16 +27,5 @@ class CachedScheduleApi(ScheduleApi, CachedApi[ScheduleApi]):
|
||||
),
|
||||
**CACHE_PRESET._asdict(),
|
||||
)
|
||||
async def get_channel_schedule(
|
||||
self, channel_id: ChannelId, date: datetime.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)
|
||||
async def get_schedule(self, channel_id: str, date: datetime.date) -> Schedule:
|
||||
return await self._api.get_schedule(channel_id, date)
|
||||
|
||||
@@ -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="Тест"),
|
||||
]
|
||||
)
|
||||
@@ -1,5 +1,4 @@
|
||||
import datetime
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -9,27 +8,10 @@ class Model(BaseModel):
|
||||
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):
|
||||
id: ChannelId
|
||||
id: str
|
||||
name: str
|
||||
provider: str
|
||||
|
||||
|
||||
class ScheduleValue(Model):
|
||||
|
||||
+47
-13
@@ -1,40 +1,74 @@
|
||||
import datetime
|
||||
import logging
|
||||
from typing import Any, Literal
|
||||
|
||||
import aiohttp
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
logger = logging.getLogger("source")
|
||||
|
||||
RequestMode = Literal["base", "browser"]
|
||||
|
||||
DEFAULT_REQUEST_MODE: RequestMode = "base"
|
||||
DEFAULT_METHOD: str = "GET"
|
||||
|
||||
|
||||
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
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url,
|
||||
user_agent: str = DEFAULT_USER_AGENT,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
cookies: dict[str, str] | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
):
|
||||
self._base_url = base_url
|
||||
self._user_agent = user_agent
|
||||
self._timeout = timeout
|
||||
self._cookies = cookies
|
||||
self._headers = headers
|
||||
|
||||
async def request(self, endpoint: str) -> str:
|
||||
url = f"{self._base_url}/{endpoint}"
|
||||
logger.info(url)
|
||||
headers = {"User-Agent": self._user_agent, **(self._headers or {})}
|
||||
async def _base_request(
|
||||
self,
|
||||
url: str,
|
||||
method: str = DEFAULT_METHOD,
|
||||
data: Any | None = None,
|
||||
) -> str:
|
||||
async with aiohttp.ClientSession(
|
||||
headers=headers,
|
||||
headers=self._headers,
|
||||
cookies=self._cookies,
|
||||
raise_for_status=True,
|
||||
) 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()
|
||||
|
||||
# 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)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import datetime
|
||||
|
||||
from ..api import Api
|
||||
from ..source import ApiSource
|
||||
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]:
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -11,7 +11,7 @@ CACHE_PRESET = DEFAULT_CACHE_PRESET
|
||||
|
||||
|
||||
class CachedWeatherApi(WeatherApi, CachedApi[WeatherApi]):
|
||||
CACHE_KEY = "weather"
|
||||
CACHE_KEY = WeatherApi.TYPE
|
||||
|
||||
@cached(
|
||||
key_builder=lambda fun, self, query: f"api.{self.CACHE_KEY}.{self.provider}.locations.{query}",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
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):
|
||||
@@ -12,6 +13,7 @@ class Model(BaseModel):
|
||||
class Location(Model):
|
||||
id: str
|
||||
name: str
|
||||
provider: str
|
||||
lat: float
|
||||
lon: float
|
||||
country: str
|
||||
@@ -20,21 +22,32 @@ class Location(Model):
|
||||
subdistrict: str
|
||||
|
||||
|
||||
class Cloudness(str, Enum):
|
||||
CLEAR = "clear"
|
||||
PARTLY_CLOUDY = "party_cloudy"
|
||||
CLOUDY = "cloudy"
|
||||
MAINLY_CLOUDY = "mainly_cloudy"
|
||||
class Cloudness(StrEnum):
|
||||
CLEAR = auto()
|
||||
PARTLY_CLOUDY = auto()
|
||||
CLOUDY = auto()
|
||||
MAINLY_CLOUDY = auto()
|
||||
|
||||
values: list[Self]
|
||||
|
||||
|
||||
class Precipitation(str, Enum):
|
||||
NO = "no"
|
||||
SMALL_RAIN = "small_rain"
|
||||
RAIN = "rain"
|
||||
HEAVY_RAIN = "heavy_rain"
|
||||
SHOWER = "shower"
|
||||
SNOW = "snow"
|
||||
HEAVY_SNOW = "heavy_snow"
|
||||
Cloudness.values = list(Cloudness)
|
||||
|
||||
|
||||
class Precipitation(StrEnum):
|
||||
NO = auto()
|
||||
SMALL_RAIN = auto()
|
||||
RAIN = auto()
|
||||
HEAVY_RAIN = auto()
|
||||
SHOWER = auto()
|
||||
SNOW = auto()
|
||||
HEAVY_SNOW = auto()
|
||||
HAIL = auto()
|
||||
|
||||
values: list[Self]
|
||||
|
||||
|
||||
Precipitation.values = list(Precipitation)
|
||||
|
||||
|
||||
class Sky(Model):
|
||||
@@ -44,16 +57,16 @@ class Sky(Model):
|
||||
fog: bool
|
||||
|
||||
|
||||
class WindDirection(str, Enum):
|
||||
CALM = "calm"
|
||||
N = "N"
|
||||
NE = "NE"
|
||||
E = "E"
|
||||
SE = "SE"
|
||||
S = "S"
|
||||
SW = "SW"
|
||||
W = "W"
|
||||
NW = "NW"
|
||||
class WindDirection(StrEnum):
|
||||
CALM = auto()
|
||||
N = auto()
|
||||
NE = auto()
|
||||
E = auto()
|
||||
SE = auto()
|
||||
S = auto()
|
||||
SW = auto()
|
||||
W = auto()
|
||||
NW = auto()
|
||||
|
||||
|
||||
class WindDirectionDeg(float):
|
||||
@@ -67,7 +80,9 @@ class WindDirectionDeg(float):
|
||||
|
||||
# pylint:disable=too-many-return-statements
|
||||
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
|
||||
elif self <= 67.5:
|
||||
return WindDirection.NE
|
||||
@@ -84,10 +99,10 @@ class WindDirectionDeg(float):
|
||||
elif self <= 337.5:
|
||||
return WindDirection.NW
|
||||
else:
|
||||
return WindDirection.CALM
|
||||
raise ValueError(self)
|
||||
|
||||
@classmethod
|
||||
def from_direction(cls, direction: WindDirection) -> "WindDirectionDeg":
|
||||
def from_direction(cls, direction: WindDirection) -> Self:
|
||||
return cls(
|
||||
{
|
||||
WindDirection.CALM: -1,
|
||||
@@ -111,8 +126,8 @@ class WeatherValue(Model):
|
||||
wind_gust: int
|
||||
wind_direction: float
|
||||
precipitation: float
|
||||
pressure: list[int]
|
||||
humidity: int
|
||||
pressure: list[int] = Field(default=[])
|
||||
humidity: int = Field(default=-1)
|
||||
|
||||
|
||||
class WeatherResponse(Model):
|
||||
|
||||
@@ -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()])
|
||||
@@ -1,8 +1,11 @@
|
||||
import datetime
|
||||
import statistics
|
||||
from typing import Literal
|
||||
|
||||
from .model import Cloudness, Precipitation, Sky, WeatherValue, WindDirectionDeg
|
||||
|
||||
MergeMode = Literal["interval", "average"]
|
||||
|
||||
|
||||
def build_weather_value(date: datetime.datetime) -> WeatherValue:
|
||||
return WeatherValue(
|
||||
@@ -19,12 +22,24 @@ def build_weather_value(date: datetime.datetime) -> WeatherValue:
|
||||
wind_direction=WindDirectionDeg(-1),
|
||||
precipitation=0,
|
||||
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(
|
||||
date: datetime.datetime, values: list[WeatherValue]
|
||||
date: datetime.datetime,
|
||||
values: list[WeatherValue],
|
||||
mode: MergeMode = "interval",
|
||||
) -> WeatherValue:
|
||||
result = build_weather_value(date)
|
||||
temperatures = []
|
||||
@@ -46,19 +61,17 @@ def merge_weather_values(
|
||||
cloudnesses.append(value.sky.cloudness)
|
||||
precipitations.append(value.sky.precipitation)
|
||||
precipitation += value.precipitation
|
||||
result.temperature = [max(temperatures), min(temperatures)]
|
||||
result.pressure = [max(pressures), min(pressures)]
|
||||
result.temperature = _merge_values(temperatures, mode)
|
||||
result.pressure = _merge_values(pressures, mode)
|
||||
result.humidity = round(statistics.mean(humidities))
|
||||
result.wind_speed = round(statistics.mean(wind_speeds))
|
||||
result.wind_gust = round(statistics.mean(wind_gusts))
|
||||
result.wind_direction = statistics.mean(wind_directions)
|
||||
# TODO: merge cloudnesses
|
||||
for item in cloudnesses:
|
||||
if item != Cloudness.CLEAR:
|
||||
if Cloudness.values.index(item) > Cloudness.values.index(result.sky.cloudness):
|
||||
result.sky.cloudness = item
|
||||
# TODO: merge 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.precipitation = precipitation
|
||||
return result
|
||||
|
||||
+4
-1
@@ -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"]
|
||||
|
||||
@@ -69,9 +69,18 @@ msgstr "Давление, мм рт. ст."
|
||||
msgid "Humidity, %"
|
||||
msgstr "Влажность, %"
|
||||
|
||||
msgid "Stored locations"
|
||||
msgstr "Сохранённые локации"
|
||||
|
||||
# tv
|
||||
msgid "TV program"
|
||||
msgstr "Телепрограмма"
|
||||
|
||||
msgid "Live broadcasts"
|
||||
msgstr "Прямые трансляции"
|
||||
|
||||
msgid "Stored channels"
|
||||
msgstr "Сохранённые каналы"
|
||||
|
||||
msgid "Channel groups"
|
||||
msgstr "Группы каналов"
|
||||
Generated
+2466
-1231
File diff suppressed because it is too large
Load Diff
+36
-30
@@ -1,43 +1,49 @@
|
||||
[tool.poetry]
|
||||
[project]
|
||||
name = "gallery"
|
||||
version = "0.2.2"
|
||||
description = ""
|
||||
authors = ["shmyga <shmyga.z@gmail.com>"]
|
||||
version = "0.8.3"
|
||||
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" }]
|
||||
|
||||
[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"
|
||||
requires-poetry = '>=2.0.0,<3.0.0'
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
requires = ['poetry-core (>=2.0.0,<3.0.0)']
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
gallery = "gallery.main:run"
|
||||
[tool.black]
|
||||
line-length = 120
|
||||
target-version = ["py314"]
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "-p no:warnings"
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.poetry_bumpversion.file."gallery/version.py"]
|
||||
+12
-2
@@ -29,9 +29,19 @@ publish () {
|
||||
for PROJECT in "${DOCKER_PROJECTS[@]}"; do
|
||||
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: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: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
|
||||
}
|
||||
|
||||
|
||||
Executable
+8
@@ -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
@@ -2,4 +2,8 @@
|
||||
set -e
|
||||
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
@@ -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
@@ -2,4 +2,4 @@
|
||||
set -e
|
||||
cd "$(dirname $(dirname "$0"))" || exit
|
||||
|
||||
poetry run pytest tests
|
||||
OPENWEATHER_KEY="" poetry run pytest tests
|
||||
|
||||
Generated
+4038
-616
File diff suppressed because it is too large
Load Diff
+31
-7
@@ -1,9 +1,10 @@
|
||||
{
|
||||
"name": "gallery",
|
||||
"version": "0.2.2",
|
||||
"version": "0.8.3",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite build --watch"
|
||||
"build": "webpack --mode production",
|
||||
"dev": "webpack --watch --mode development"
|
||||
},
|
||||
"author": "shmyga <shmyga.z@gmail.com>",
|
||||
"license": "ISC",
|
||||
@@ -12,10 +13,33 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"bootstrap": "^5.3.8",
|
||||
"bootstrap-icons": "^1.13.1",
|
||||
"flag-icons": "^7.5.0",
|
||||
"sass": "^1.99.0"
|
||||
"flag-icons": "^7.5.0"
|
||||
},
|
||||
"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"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
+
|
||||
</span>
|
||||
${content}
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-danger ms-2 ${this.options?.onRemove ? "" : "d-none"}" data-remove>
|
||||
✕
|
||||
</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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
const showActiveLanguage = (language: string, focus = false) => {
|
||||
const languageSwitcher = document.querySelector("#bd-language");
|
||||
const languageSwitcher = document.querySelector<HTMLElement>("#bd-language");
|
||||
|
||||
if (!languageSwitcher) {
|
||||
return;
|
||||
@@ -27,24 +27,26 @@
|
||||
|
||||
const languageSwitcherText = document.querySelector("#bd-language-text");
|
||||
const activeLanguageIcon = document.querySelector(".language-icon-active");
|
||||
const btnToActive = document.querySelector(`[data-bs-language-value="${language}"]`);
|
||||
const activeLanguageIconClass = btnToActive.querySelector(".fi").className.match(/fi-[\w-]+/)[0];
|
||||
const btnToActive = document.querySelector<HTMLElement>(`[data-bs-language-value="${language}"]`);
|
||||
const activeLanguageIconClass = (btnToActive?.querySelector(".fi")?.className.match(/fi-[\w-]+/) || [])[0] || "";
|
||||
|
||||
document.querySelectorAll("[data-bs-language-value]").forEach((element) => {
|
||||
element.classList.remove("active");
|
||||
element.setAttribute("aria-pressed", "false");
|
||||
});
|
||||
|
||||
btnToActive.classList.add("active");
|
||||
btnToActive.setAttribute("aria-pressed", "true");
|
||||
const classesToRemove = Array.from(activeLanguageIcon.classList).filter((className) => className.startsWith("fi-"));
|
||||
activeLanguageIcon.classList.remove(...classesToRemove);
|
||||
activeLanguageIcon.classList.add(activeLanguageIconClass);
|
||||
const languageSwitcherLabel = `${languageSwitcherText.textContent} (${btnToActive.dataset.bsLanguageValue})`;
|
||||
btnToActive?.classList.add("active");
|
||||
btnToActive?.setAttribute("aria-pressed", "true");
|
||||
const classesToRemove = Array.from(activeLanguageIcon?.classList || []).filter((className) =>
|
||||
className.startsWith("fi-"),
|
||||
);
|
||||
activeLanguageIcon?.classList.remove(...classesToRemove);
|
||||
activeLanguageIcon?.classList.add(activeLanguageIconClass);
|
||||
const languageSwitcherLabel = `${languageSwitcherText?.textContent} (${btnToActive?.dataset.bsLanguageValue})`;
|
||||
languageSwitcher.setAttribute("aria-label", languageSwitcherLabel);
|
||||
|
||||
if (focus) {
|
||||
languageSwitcher.focus();
|
||||
languageSwitcher?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
setTheme(getPreferredTheme());
|
||||
|
||||
const showActiveTheme = (theme: string, focus = false) => {
|
||||
const themeSwitcher = document.querySelector("#bd-theme");
|
||||
const themeSwitcher = document.querySelector<HTMLElement>("#bd-theme");
|
||||
|
||||
if (!themeSwitcher) {
|
||||
return;
|
||||
@@ -33,24 +33,26 @@
|
||||
|
||||
const themeSwitcherText = document.querySelector("#bd-theme-text");
|
||||
const activeThemeIcon = document.querySelector(".theme-icon-active");
|
||||
const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`);
|
||||
const activeThemeIconClass = btnToActive.querySelector(".bi").className.match(/bi-[\w-]+/)[0];
|
||||
const btnToActive = document.querySelector<HTMLElement>(`[data-bs-theme-value="${theme}"]`);
|
||||
const activeThemeIconClass = (btnToActive?.querySelector(".bi")?.className.match(/bi-[\w-]+/) || [])[0] || "";
|
||||
|
||||
document.querySelectorAll("[data-bs-theme-value]").forEach((element) => {
|
||||
element.classList.remove("active");
|
||||
element.setAttribute("aria-pressed", "false");
|
||||
});
|
||||
|
||||
btnToActive.classList.add("active");
|
||||
btnToActive.setAttribute("aria-pressed", "true");
|
||||
const classesToRemove = Array.from(activeThemeIcon.classList).filter((className) => className.startsWith("bi-"));
|
||||
activeThemeIcon.classList.remove(...classesToRemove);
|
||||
activeThemeIcon.classList.add(activeThemeIconClass);
|
||||
const themeSwitcherLabel = `${themeSwitcherText.textContent} (${btnToActive.dataset.bsThemeValue})`;
|
||||
btnToActive?.classList.add("active");
|
||||
btnToActive?.setAttribute("aria-pressed", "true");
|
||||
const classesToRemove = Array.from(activeThemeIcon?.classList || []).filter((className) =>
|
||||
className.startsWith("bi-"),
|
||||
);
|
||||
activeThemeIcon?.classList.remove(...classesToRemove);
|
||||
activeThemeIcon?.classList.add(activeThemeIconClass);
|
||||
const themeSwitcherLabel = `${themeSwitcherText?.textContent} (${btnToActive?.dataset.bsThemeValue})`;
|
||||
themeSwitcher.setAttribute("aria-label", themeSwitcherLabel);
|
||||
|
||||
if (focus) {
|
||||
themeSwitcher.focus();
|
||||
themeSwitcher?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -66,7 +68,7 @@
|
||||
|
||||
document.querySelectorAll("[data-bs-theme-value]").forEach((toggle) => {
|
||||
toggle.addEventListener("click", () => {
|
||||
const theme = toggle.getAttribute("data-bs-theme-value") || '';
|
||||
const theme = toggle.getAttribute("data-bs-theme-value") || "";
|
||||
setStoredTheme(theme);
|
||||
setTheme(theme);
|
||||
showActiveTheme(theme, true);
|
||||
@@ -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 {
|
||||
static observedAttributes = ["icon", "href"];
|
||||
static observedAttributes = ["icon", "href", "target"];
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
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">
|
||||
<span class="fs-4">
|
||||
<span class="bi bi-${this.getAttribute("icon")} me-1"></span>
|
||||
@@ -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);
|
||||
@@ -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
Reference in New Issue
Block a user