Skip to content
Merged

Dev #63

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,61 @@ notices:
задайте `notices: []` или удалите файл. Все объявления — обычные ссылки,
которые открываются без JavaScript.

## Пользовательские спрайты

Слоистые спрайты сообщества задаются в `community-sprites.json` в корне
**es-doc-assets**. Формат: `groups` → название группы → `variations` →
вариант с `name` и `distances`. Каждая дистанция (`normal`, `close`, `far`)
содержит непустой массив путей к слоям, от нижнего к верхнему.

```json
{
"groups": {
"Лена в полицейской форме": {
"author": {"name": "Имя художника", "link": "https://example.com/artist"},
"description": "Спрайт из модификации «Главный Атрибут Пионера»",
"variations": [
{
"name": "Улыбается",
"distances": {
"normal": [
"/resource/raw/images/sprites/normal/un/un_1_body.png",
"sprites/lena_police/normal/clothes.png",
"sprites/lena_police/normal/smile.png"
],
"close": ["sprites/lena_police/close/smile.png"],
"far": ["sprites/lena_police/far/smile.png"]
}
}
]
}
}
}
```

Это пример структуры: пользовательские файлы нужно добавить в репозиторий.
Относительные пути отсчитываются от `community/`;
`/resource/community/…` адресует ту же папку, `/resource/raw/…` — `game/`.
Используйте `/` в путях. Внешние ссылки и выход за пределы этих папок запрещены.
Поддерживаются PNG, WebP и JPG; для прозрачных слоёв используйте PNG или WebP.
Все слои одной дистанции должны иметь одинаковые размеры и совмещаться
от левого верхнего угла. Один готовый спрайт — массив из одного файла.

Необязательно задавать все дистанции: показываются только перечисленные.
Первой выбирается `normal`, затем `close`, затем `far`. Названия вариантов
внутри группы должны быть уникальны. `author` и `description` необязательны;
пустые поля не выводятся, ссылка автора поддерживает HTTP(S).
В JSON нельзя писать комментарии `//`.

Группы доступны на `/resources/community/sprites`, участвуют в поиске,
поддерживают выбор дистанции, просмотр и скачивание собранного WebP.
Сборка и миниатюры создаются при первом обращении и кэшируются.
Изменения JSON и изображений подхватываются без перезапуска. Некорректные
дистанции пропускаются с предупреждением в журнале; при ошибке синтаксиса
JSON сохраняется предыдущий каталог. `{"groups": {}}` или удаление файла
очищает каталог. Отдельные спрайты продолжают находиться автоматически;
слои, использованные в каталоге, повторно отдельными картинками не выводятся.

## Каталог специалистов

Страница `/specialists` объединяет художников, нейрохудожников, композиторов,
Expand Down
23 changes: 15 additions & 8 deletions app/routes/res.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@ def _artist_img_lock(url, kind):
lock = _artist_img_locks[(url, kind)] = asyncio.Lock()
return lock

async def _ensure_composed(sprite):
async def _ensure_composed(sprite, community=False):

if sprite not in CONFIG.sprite_layers:
if sprite not in (CONFIG.community_sprite_layers if community else CONFIG.sprite_layers):
raise HTTPException(404, f'Спрайт "{sprite}" не существует.')

if not is_composed(sprite):
if not is_composed(sprite, community):
async with compose_lock:
# Re-check: the request holding the lock before us may have
# composed this very sprite.
if not is_composed(sprite):
if not is_composed(sprite, community):
try:
await asyncio.to_thread(compose_sprite, sprite)
await asyncio.to_thread(compose_sprite, sprite, community)
except Exception:
logger.exception(f'Composing sprite "{sprite}" failed.')
raise HTTPException(500, f'Не удалось собрать спрайт "{sprite}".') from None
Expand All @@ -71,6 +71,13 @@ async def sprite_page(sprite, request: Request):

return FileResponse(str(sprite_file(sprite)), media_type='image/webp', headers=cache_headers(precompressed=True))


@router.get('/community-sprite/{sprite}')
async def community_sprite_page(sprite: str):
await _ensure_composed(sprite, community=True)
return FileResponse(str(sprite_file(sprite, community=True)), media_type='image/webp',
headers=cache_headers(precompressed=True))

def _find_tinted(kind, name):
return next((i for collection in CONFIG.resources.values()
for i in collection.get(kind, [])
Expand Down Expand Up @@ -110,12 +117,12 @@ async def tinted_page(kind, name, request: Request):
@router.get('/thumb/{kind}/{name:path}')
async def thumb_page(kind, name, request: Request):

if kind not in ('bg', 'cg', 'anim', 'sprite', 'community'):
if kind not in ('bg', 'cg', 'anim', 'sprite', 'community', 'community-sprite'):
raise HTTPException(404, f'Категория "{kind}" не существует.')

if kind == 'sprite':
if kind in ('sprite', 'community-sprite'):
# A sprite thumb derives from the composed sprite, so compose first.
await _ensure_composed(name)
await _ensure_composed(name, community=kind == 'community-sprite')
elif kind == 'community':
if not any(i['file'] == name and i['thumb']
for items in CONFIG.resources.get('community', {}).values()
Expand Down
14 changes: 12 additions & 2 deletions app/routes/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ def _count(category, items):
# sit behind their toggle and are not part of the headline numbers.
if category == 'sprites' and items and 'sprites' in items[0]:
return sum(len(group['sprites']) for group in items)
if category == 'sprites':
return sum(len(item.get('variants', [item])) for item in items)
return sum(1 for i in items if i['declared'])


Expand Down Expand Up @@ -309,6 +311,14 @@ async def listing(collection, category, request: Request):
present = {i['time'] for i in items}
bg_times = [(key, label) for key, label in BG_TIME_LABELS.items() if key in present]

community_sprite_groups = {}
if category == 'sprites' and collection == 'community':
for item in items:
group = item.get('sprite_group')
if group:
entry = community_sprite_groups.setdefault(group['rid'], {**group, 'families': []})
entry['families'].append(item)

return templates.TemplateResponse(request, 'resources_list.html', {
'collection': collection,
'collection_meta': COLLECTIONS[collection],
Expand All @@ -317,8 +327,8 @@ async def listing(collection, category, request: Request):
'categories': switcher,
'items': items,
'count': _count(category, items),
'count_all': (len(items) if category != 'sprites' or collection == 'community'
else sum(len(g['sprites']) for g in items)),
'count_all': _count(category, items) if category == 'sprites' else len(items),
'community_sprite_groups': list(community_sprite_groups.values()),
'has_undeclared': (category != 'sprites'
and any(not i['declared'] for i in items)),
'other_href': other_href,
Expand Down
3 changes: 3 additions & 0 deletions app/utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ def __init__(self):
# Sprites are composed lazily on first request and cached on disk.
self.sprite_layers = {}

# Catalogue key -> validated local layer Paths, separate from game sprites.
self.community_sprite_layers = {}

# {'original': {category: items}, 'community': {...}} from the game's
# declarations and community files (see lifespan/resources_cache.py).
self.resources = {}
Expand Down
6 changes: 4 additions & 2 deletions app/utils/lifespan/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import signal
import asyncio, signal, os
from contextlib import asynccontextmanager

from fastapi import FastAPI
Expand Down Expand Up @@ -137,6 +136,9 @@ async def lifespan(app: FastAPI):
# restart (see refresh.py).
worker = asyncio.create_task(worker_refresh_caches())

if os.environ['ES_DOC_DEBUG'] == '1' and os.name == 'nt':
os.system('start "" "http://localhost:8000/"')

yield

shutdown_livereload()
Expand Down
149 changes: 149 additions & 0 deletions app/utils/lifespan/community_sprites.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""Local, layered community sprites declared in the assets catalogue."""

import hashlib
import json
import re
from pathlib import PureWindowsPath
from urllib.parse import unquote, urlsplit

from ..config import CONFIG
from ..logging import root_logger

logger = root_logger.getChild('lifespan').getChild('community-sprites')
DISTANCES = ('normal', 'close', 'far')
IMAGE_EXTS = {'.png', '.webp', '.jpg', '.jpeg'}


def layer_path(value):
"""Resolve a declared image within game/ or community/, never arbitrary files."""
if not isinstance(value, str) or not value.strip():
raise ValueError('A layer must be a non-empty local image path')
value = value.strip()
root = CONFIG.res_path.parent / 'community'
for prefix, directory in (
('/resource/raw/', CONFIG.res_path),
('/resource/community/', root),
):
if value.startswith(prefix):
root, value = directory, unquote(value[len(prefix):])
break
if ('\\' in value or '\x00' in value or ':' in value
or value.startswith('/') or '..' in value.split('/')
or PureWindowsPath(value).drive):
raise ValueError('Layer paths must stay inside game/ or community/')
path = (root / value).resolve()
if not path.is_relative_to(root.resolve()) or path.suffix.lower() not in IMAGE_EXTS:
raise ValueError('Layer must be an image inside game/ or community/')
if not path.is_file():
raise ValueError(f'Layer does not exist: {value}')
return path


def _text(value):
return value.strip() if isinstance(value, str) else ''


def _layer_reference(path):
for folder, root in (('game', CONFIG.res_path),
('community', CONFIG.res_path.parent / 'community')):
if path.is_relative_to(root.resolve()):
return folder + '/' + path.relative_to(root.resolve()).as_posix()
raise ValueError('Layer is outside the resource directories')


def _author(value):
value = value if isinstance(value, dict) else {}
link = _text(value.get('link'))
try:
parsed = urlsplit(link)
safe = (parsed.scheme in ('http', 'https') and parsed.netloc
and not any(c.isspace() or ord(c) < 32 for c in link))
except ValueError:
safe = False
if not safe:
link = ''
return {'name': _text(value.get('name')), 'link': link}


def parse_community_sprites():
"""Return flat families plus their layer map; malformed JSON keeps the last catalogue."""
manifest = CONFIG.res_path.parent / 'community-sprites.json'
if not manifest.exists():
return [], {}
try:
data = json.loads(manifest.read_text('utf-8-sig'))
if not isinstance(data, dict) or not isinstance(data.get('groups'), dict):
raise TypeError('The catalogue must contain a groups object')
except (OSError, ValueError, TypeError):
logger.exception('Invalid community-sprites.json; keeping the previous catalogue.')
previous = CONFIG.resources.get('community', {}).get('sprites', [])
return [i for i in previous if i.get('sprite_group')], CONFIG.community_sprite_layers

families, layer_map = [], {}
for title, group in data['groups'].items():
if (not _text(title) or not isinstance(group, dict)
or not isinstance(group.get('variations'), list)):
logger.warning('Invalid sprite group %r; skipping it.', title)
continue
title = title.strip()
group_meta = {
'title': title, 'desc': _text(group.get('description')),
'author': _author(group.get('author')),
'rid': 'sprite-group-' + hashlib.sha256(title.encode()).hexdigest()[:20],
}
seen = set()
for variation in group['variations']:
if not isinstance(variation, dict):
logger.warning('Invalid variation in %s; skipping it.', title)
continue
name = _text(variation.get('name'))
distances = variation.get('distances')
if not name or name in seen or not isinstance(distances, dict):
logger.warning('Invalid or duplicate variation %r in %s; skipping it.', name, title)
continue
seen.add(name)
variants = []
layer_files = []
for distance in DISTANCES:
if distance not in distances:
continue
try:
layers = distances[distance]
if not isinstance(layers, list) or not layers:
raise ValueError('A distance must contain at least one layer')
paths = [layer_path(layer) for layer in layers]
except (ValueError, OSError) as exc:
logger.warning('Invalid sprite %s / %s / %s: %s', title, name, distance, exc)
continue
# Include source versions so browser caches refresh too. Logical
# paths keep URLs independent of the installation directory.
versions = [(_layer_reference(p), p.stat().st_mtime_ns, p.stat().st_size)
for p in paths]
identity = json.dumps([title, name, distance, versions])
key = hashlib.sha256(identity.encode()).hexdigest()
anchor = hashlib.sha256(json.dumps([title, name, distance]).encode()).hexdigest()
layer_map[key] = paths
layer_files.extend(paths)
filename = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', f'{title} — {name} {distance}')
variants.append({
'name': filename, 'code': name, 'title': name,
'rid': 'r-community-sprite-' + anchor,
'distance': distance,
'raw': f'/resource/community-sprite/{key}',
'thumb': f'/resource/thumb/community-sprite/{key}',
})
if not variants:
continue
primary = variants[0]
search = ' '.join([group_meta['desc'], group_meta['author']['name'],
*(f"{title} {name} {v['distance']}" for v in variants),
*(_layer_reference(p) for p in layer_files)])
families.append({
'name': name, 'title': f'{title} — {name}', 'code': None,
'file': '', 'declared': True, 'captions': [],
'rid': primary['rid'], 'raw': primary['raw'], 'thumb': primary['thumb'],
'desc': group_meta['desc'], 'sprite_group': group_meta,
'variants': variants, 'primary': primary, 'search': search,
'layer_files': layer_files,
})
return families, layer_map
1 change: 1 addition & 0 deletions app/utils/lifespan/refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ def _watchers():
res / 'media.rpy',
assets / 'descriptions.yaml',
assets / 'community-descriptions.yaml',
assets / 'community-sprites.json',
assets / 'nsfw.yaml',
)
community_files = _under(assets / 'community')
Expand Down
10 changes: 9 additions & 1 deletion app/utils/lifespan/resources_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from ..config import CONFIG
from ..logging import root_logger
from .community_sprites import parse_community_sprites

logger = root_logger.getChild('lifespan').getChild('resources-cache')

Expand Down Expand Up @@ -706,7 +707,7 @@ def _build_search_items(collection, collection_name='original'):
}
if collection_name == 'community':
row['context'] = 'Ресурсы сообщества / ' + row['context']
row['keywords'] = ' '.join([item['file'], *item.get('captions', [])])
row['keywords'] = ' '.join([item['file'], item.get('search', ''), *item.get('captions', [])])
# Real descriptions (auto bg/music or hand-written) are searchable
# too; the "уточняется" placeholder would only add noise.
if item['desc'] and item['desc'] not in (PLACEHOLDER_DESC, UNDECLARED_DESC):
Expand All @@ -731,11 +732,18 @@ def parse_resources():
# Community files are independent of the game's Ren'Py declarations.
community_root = CONFIG.res_path.parent / 'community'
community = _parse_community(community_root, _load_community_descriptions())
custom_sprites, custom_layers = parse_community_sprites()
used_layers = {path for item in custom_sprites for path in item['layer_files']}
community['sprites'] = custom_sprites + [
item for item in community['sprites']
if (community_root / item['file']).resolve() not in used_layers
]

# NSFW CG declarations are cut from the original collection and are not
# listed in the community collection either.
original['cg'] = [i for i in original['cg'] if not i['nsfw']]

CONFIG.community_sprite_layers = custom_layers
CONFIG.resources = {'original': original, 'community': community}
# Merged into CONFIG.search_items at startup and after assets refreshes.
CONFIG.resource_search_items = (
Expand Down
Loading