release: Евномия, новая версия, линейка юристов
This commit is contained in:
@@ -0,0 +1,506 @@
|
||||
"""Loopback-only HTTP surface. Network updates belong to background_corpus."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import secrets
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import background_corpus
|
||||
import legal_graph
|
||||
from eunomia.library import Library, stamp
|
||||
from eunomia.graph_view import GraphViewCache
|
||||
from eunomia.practice import Practice, PracticeError, progress, request_walk, walk
|
||||
|
||||
CODE_ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = Path(__file__).parent / 'web'
|
||||
# Карточки «Состояние базы» опрашивают полосы раз в 5 с; подсчет СудАкта по диску идет до 0,5 с.
|
||||
CACHE_SECONDS = 5
|
||||
SPEED_WINDOW = 600 # скорость очереди законов - за 10 минут, как у СудАкта
|
||||
# Расписание сверено с кодом 03.10.2026: background_corpus повторно проверяет документ, когда его last_checked
|
||||
# старше 7 суток (_enqueue_validated), задача частей обходит СудАкт раз в сутки (practice.next_day).
|
||||
LAW_DAYS, PRACTICE_DAYS = 7, 1
|
||||
SHOWN = 5 # пунктов недостачи на карточке: остальное - числом
|
||||
REASONS = (('job превысил', 'проверка не уложилась в срок задания, повтор позже'),
|
||||
('deadline exhausted', 'не хватило времени проверки, повтор позже'),
|
||||
('generic candidate failed', 'разбор документа не прошел, повтор позже'),
|
||||
('source body too short', 'источник отдал пустую страницу, повтор позже'),
|
||||
('review_parser_not_verified', 'разборщик обзоров не принят'),
|
||||
('worker не запустился', 'обработчик не запустился, повтор позже'))
|
||||
STATES = {'queued': 'ждет очереди', 'running': 'проверяется сейчас', 'deferred': 'повтор позже',
|
||||
'blocked': 'источник недоступен', 'failed': 'ошибка проверки'}
|
||||
|
||||
|
||||
def _moment(value):
|
||||
try:
|
||||
moment = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
return None
|
||||
return moment if moment.tzinfo else moment.replace(tzinfo=UTC)
|
||||
|
||||
|
||||
def _day(moment):
|
||||
return moment.astimezone().strftime('%d.%m.%Y')
|
||||
|
||||
|
||||
def _plural(n, one, few, many):
|
||||
return one if n % 10 == 1 and n % 100 != 11 else few if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14 else many
|
||||
|
||||
|
||||
def law_freshness(jobs, titles, now=None):
|
||||
"""Отметка законов (решение владельца 03.10.2026): «Корпус полный · актуально на ДД.ММ.ГГГГ», если каждый
|
||||
документ очереди в состоянии current или updated и проверен не раньше 7 суток назад; дата - самой старой
|
||||
проверки. Иначе - сколько и какие не готовы, с причиной."""
|
||||
now = now or datetime.now(UTC)
|
||||
missing, oldest = [], None
|
||||
for job in jobs:
|
||||
checked = _moment(job.get('last_checked')) if job.get('last_checked') else None
|
||||
if (job.get('state') in ('current', 'updated') and checked
|
||||
and now - timedelta(days=LAW_DAYS) <= checked <= now + timedelta(minutes=5)):
|
||||
oldest = min(oldest or checked, checked)
|
||||
continue
|
||||
detail = str(job.get('detail') or '')
|
||||
reason = next((text for mark, text in REASONS if mark in detail), None)
|
||||
if reason is None and job.get('state') in ('current', 'updated'):
|
||||
reason = f'проверен {_day(checked)}, больше недели назад' if checked else 'дата проверки неизвестна'
|
||||
reason = reason or STATES.get(job.get('state'), str(job.get('state'))) + (f': {detail[:80]}' if detail else '')
|
||||
missing.append({'id': job['id'], 'title': titles.get(job['id']) or job['id'].rsplit(':', 1)[-1],
|
||||
'reason': reason})
|
||||
if jobs and not missing:
|
||||
return {'full': True, 'label': f'Корпус полный · актуально на {_day(oldest)}', 'as_of': _day(oldest),
|
||||
'missing': [], 'interval_days': LAW_DAYS}
|
||||
label = (f"Корпус неполный: не {_plural(len(missing), 'готов', 'готовы', 'готовы')} {len(missing)} "
|
||||
f"{_plural(len(missing), 'документ', 'документа', 'документов')} из {len(jobs)}"
|
||||
if jobs else 'Корпус пуст: очередь не заполнена')
|
||||
return {'full': False, 'label': label, 'as_of': None, 'missing': missing, 'interval_days': LAW_DAYS}
|
||||
|
||||
|
||||
def practice_freshness(value, now=None):
|
||||
"""Отметка практики (решение владельца 03.10.2026): «Актуально на сегодня», если ежедневный обход СудАкта
|
||||
закончился сегодня по часам Mac и новых актов к докачке нет. Иначе - почему нет."""
|
||||
walk, today = value.get('walk') or {}, (now or datetime.now(UTC)).astimezone().date()
|
||||
left, at = max(value.get('total', 0) - value.get('done', 0), 0), _moment(walk.get('at')) if walk.get('at') else None
|
||||
if walk.get('stopped'):
|
||||
label = f"Не актуально: обход остановлен ({walk['stopped']})"
|
||||
elif walk.get('running'):
|
||||
label = 'Не актуально: идет обход СудАкта'
|
||||
elif left:
|
||||
label = f"Не актуально: не {_plural(left, 'скачан', 'скачаны', 'скачаны')} {left:,} {_plural(left, 'акт', 'акта', 'актов')}".replace(',', ' ')
|
||||
elif at is None:
|
||||
label = 'Не актуально: обхода СудАкта еще не было'
|
||||
elif at.astimezone().date() != today:
|
||||
label = f'Не актуально: последний обход {_day(at)}, сегодняшний еще не прошел'
|
||||
else:
|
||||
return {'fresh': True, 'label': 'Актуально на сегодня', 'as_of': _day(at), 'interval_days': PRACTICE_DAYS}
|
||||
return {'fresh': False, 'label': label, 'as_of': _day(at) if at else None, 'interval_days': PRACTICE_DAYS}
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, root):
|
||||
self.root = Path(root).resolve()
|
||||
self.library = Library(root)
|
||||
self.csrf = secrets.token_urlsafe(32)
|
||||
self.actions_lock = threading.Lock()
|
||||
self.processes = {}
|
||||
self.action_results = {}
|
||||
self.graph_views = GraphViewCache(self.root)
|
||||
self.practice = Practice(self.root, self.library)
|
||||
self.cache, self.cache_lock = {}, threading.Lock()
|
||||
self.graph_views.ensure()
|
||||
|
||||
def cached(self, key, build):
|
||||
"""Один подсчет на CACHE_SECONDS, сколько бы вкладок ни опрашивало полосу."""
|
||||
with self.cache_lock:
|
||||
at, value = self.cache.get(key, (0.0, None))
|
||||
if value is None or time.monotonic() - at >= CACHE_SECONDS:
|
||||
value = build()
|
||||
self.cache[key] = (time.monotonic(), value)
|
||||
return value
|
||||
|
||||
def practice_progress(self):
|
||||
try:
|
||||
value = progress(self.root)
|
||||
except Exception: # карты или индекса Lynceuz еще нет: полоса честно пустая
|
||||
value = {'done': 0, 'total': 0, 'per_min': 0.0, 'eta_min': None, 'updated_at': stamp(),
|
||||
'error': 'Корпус СудАкта пока не скачан.'}
|
||||
value = {**value, 'walk': walk(self.root)}
|
||||
return {**value, 'freshness': practice_freshness(value)}
|
||||
|
||||
def law_progress(self):
|
||||
"""Полоса законов из очереди background_corpus.status(): готово - все, кроме queued и running.
|
||||
Отложенные и недоступные источники очередь не держат: их повторит обработчик, счет - в states."""
|
||||
queue, now = background_corpus.status(self.root), time.time()
|
||||
jobs = queue.get('jobs') or []
|
||||
left = sum(job.get('state') in ('queued', 'running') for job in jobs)
|
||||
recent = sum(isinstance(job.get('finished_at'), (int, float)) and now - job['finished_at'] <= SPEED_WINDOW
|
||||
for job in jobs)
|
||||
moved = max((job['updated_at'] for job in jobs if isinstance(job.get('updated_at'), (int, float))), default=0)
|
||||
per_min = recent * 60 / SPEED_WINDOW
|
||||
titles = {key: (item.get('document') or {}).get('title') for key, item in self.library.documents.items()}
|
||||
return {'done': len(jobs) - left, 'total': len(jobs), 'per_min': round(per_min, 1),
|
||||
'eta_min': 0 if not left else round(left / per_min) if per_min else None,
|
||||
'running': bool(left) and now - moved < SPEED_WINDOW, 'states': queue.get('queue') or {},
|
||||
'updated_at': stamp(), 'freshness': law_freshness(jobs, titles)}
|
||||
|
||||
def graph_page(self, params):
|
||||
status = self.graph_views.ensure()
|
||||
view = self.graph_views.get()
|
||||
if view is None:
|
||||
return {'nodes': [], 'edges': [], 'loading': status.get('loading', False), 'total': 0,
|
||||
'warnings': ['Снимок графа пока недоступен. Тексты и поиск продолжают работать.']}
|
||||
limit = max(1, min(60, int(params.get('limit', '40'))))
|
||||
if params.get('node_id'):
|
||||
value = view.ego(params['node_id'], limit=limit, offset=max(0, int(params.get('offset', '0'))))
|
||||
else:
|
||||
value = view.clustered(kind=params.get('kind'), query=params.get('q'),
|
||||
limit=limit, offset=max(0, int(params.get('offset', '0'))),
|
||||
resource_id=params.get('resource_id'))
|
||||
if not view.snapshot and not value.get('warnings'):
|
||||
value['warnings'] = ['Сохраненный снимок графа отсутствует. Тексты и поиск продолжают работать.']
|
||||
for node in value.get('nodes', []):
|
||||
doc = self.library.documents.get(node.get('resource_id'), {}).get('document', {})
|
||||
node['document_kind'] = doc.get('kind', node.get('document_kind'))
|
||||
node['document_title'] = doc.get('subject') or doc.get('title')
|
||||
node['document_number'] = doc.get('number')
|
||||
node['document_date'] = doc.get('act_date') or doc.get('date')
|
||||
node['reader_id'] = self.reader_id(node)
|
||||
return value
|
||||
|
||||
def graph_network(self, params):
|
||||
status = self.graph_views.ensure()
|
||||
view = self.graph_views.get()
|
||||
if view is None or (not self.library.documents and not self.library.indexed_at):
|
||||
return {'nodes': [], 'edges': [], 'loading': status.get('loading', False) or not self.library.indexed_at, 'total_nodes': 0,
|
||||
'total_edges': 0, 'displayed_nodes': 0, 'displayed_edges': 0, 'truncated': False,
|
||||
'warnings': ['Снимок графа пока недоступен.']}
|
||||
resource_id = params.get('resource_id', '')
|
||||
node_id = params.get('node_id', '')
|
||||
fragment = params.get('fragment', '')
|
||||
if not node_id and resource_id and fragment:
|
||||
if fragment in view.nodes and view.nodes[fragment].get('resource_id') == resource_id:
|
||||
node_id = fragment
|
||||
else:
|
||||
try:
|
||||
part, _ = self.library.resolve_fragment(resource_id, fragment)
|
||||
except (KeyError, TypeError):
|
||||
part = None
|
||||
if part:
|
||||
matches = [n for n in view.nodes.values()
|
||||
if n.get('resource_id') == resource_id and n.get('kind') == part.get('kind')
|
||||
and ((part.get('source_location') and n.get('source_location') == part.get('source_location'))
|
||||
or n.get('label') == part.get('label')
|
||||
or n.get('id', '').endswith(':' + part.get('id', '')))]
|
||||
if len(matches) == 1:
|
||||
node_id = matches[0]['id']
|
||||
if fragment != part.get('id'):
|
||||
points = [n for n in view.nodes.values()
|
||||
if n.get('resource_id') == resource_id
|
||||
and n.get('kind') == 'point'
|
||||
and n.get('id', '').startswith(node_id + ':')
|
||||
and self.reader_id(n) == fragment]
|
||||
node_id = points[0]['id'] if len(points) == 1 else '__unknown_fragment__'
|
||||
else:
|
||||
node_id = '__unknown_fragment__'
|
||||
else:
|
||||
node_id = '__unknown_fragment__'
|
||||
include_contains = str(params.get('include_contains', '1')).casefold() not in {'0', 'false', 'no'}
|
||||
try:
|
||||
limit = int(params.get('limit', '1000'))
|
||||
except (TypeError, ValueError):
|
||||
limit = 1000
|
||||
value = view.network(level=params.get('level', 'atoms'), query=params.get('q', ''),
|
||||
kind=params.get('kind', ''), resource_id=resource_id, node_id=node_id,
|
||||
include_contains=include_contains, max_nodes=limit, max_edges=5000)
|
||||
for node in value.get('nodes', []):
|
||||
doc = self.library.documents.get(node.get('resource_id'), {}).get('document', {})
|
||||
node['document_kind'] = doc.get('kind', node.get('document_kind'))
|
||||
node['document_title'] = doc.get('subject') or doc.get('title')
|
||||
node['document_number'] = doc.get('number')
|
||||
node['document_date'] = doc.get('act_date') or doc.get('date')
|
||||
node['reader_id'] = self.reader_id(node)
|
||||
return value
|
||||
|
||||
def reader_id(self, node):
|
||||
# Узел вне библиотеки (индекс практики practice:index) - без адреса для чтения, а не KeyError
|
||||
# и 404 на всю связь статьи (приемка практики 03.10.2026, ст. 333 ГК РФ).
|
||||
if node.get('kind') == 'document' or node.get('resource_id') not in self.library.documents:
|
||||
return ''
|
||||
nested = re.search(r':article:(\d+(?:\.\d+)*):point:(\d+(?:\.\d+)*)$', node.get('id', ''))
|
||||
if nested:
|
||||
item = self.library.documents.get(node.get('resource_id'), {})
|
||||
article_suffix = '_article_' + nested[1].replace('.', '_')
|
||||
anchors = [anchor for part in item.get('fragments', [])
|
||||
if part['id'].endswith(article_suffix)
|
||||
for anchor in part.get('anchors', [])
|
||||
if anchor.get('number') == nested[2]]
|
||||
if len(anchors) == 1:
|
||||
return anchors[0]['id']
|
||||
if anchors:
|
||||
# Articles can contain both 1. and 1). Match the stored text,
|
||||
# never guess between repeated numbers or a stale source line.
|
||||
label = re.sub(r'^(?:Пункт|п\.)\s*\d+(?:\.\d+)*[.\s]*', '', node.get('label', ''), flags=re.I)
|
||||
normalize = lambda text: ' '.join(text.split()).rstrip('. ')
|
||||
exact = []
|
||||
for part in item.get('fragments', []):
|
||||
if not part['id'].endswith(article_suffix):
|
||||
continue
|
||||
for anchor in anchors:
|
||||
line = part['text'][anchor['offset']:].lstrip().split('\n', 1)[0]
|
||||
text = re.sub(r'^\d+(?:\.\d+)*[.)]\s*', '', line)
|
||||
if normalize(text) == normalize(label):
|
||||
exact.append(anchor['id'])
|
||||
if len(exact) == 1:
|
||||
return exact[0]
|
||||
return self.library.reader_location(node.get('resource_id'), node.get('label', ''), node.get('source_location', ''))
|
||||
|
||||
def related_data(self, resource_id, fragment=''):
|
||||
status = self.graph_views.ensure()
|
||||
view = self.graph_views.get()
|
||||
if view is None:
|
||||
return {'related': [], 'loading': status.get('loading', False)}
|
||||
node_id = fragment if fragment in view.nodes else ''
|
||||
if fragment and not node_id:
|
||||
part, _ = self.library.resolve_fragment(resource_id, fragment)
|
||||
if part:
|
||||
label = part.get('label', '')
|
||||
if part.get('kind') == 'point':
|
||||
label = re.sub(r'^п\.\s*', 'Пункт ', label)
|
||||
found = view.find_node(resource_id, part.get('kind'), label)
|
||||
node_id = found.get('id', '') if found else ''
|
||||
if not node_id:
|
||||
return {'related': [], 'loading': False, 'note': 'Фрагмент отсутствует в графе.'}
|
||||
result = view.related(resource_id, node_id)
|
||||
for edge in result.get('related', []):
|
||||
for side in ('source_node', 'target_node'):
|
||||
node = edge.get(side, {})
|
||||
node['reader_id'] = self.reader_id(node)
|
||||
doc = self.library.documents.get(node.get('resource_id'), {}).get('document', {})
|
||||
node['document_title'] = doc.get('subject') or doc.get('title')
|
||||
result['loading'] = False
|
||||
result['node_id'] = node_id
|
||||
return result
|
||||
|
||||
def status(self):
|
||||
try:
|
||||
queue = background_corpus.status(self.root)
|
||||
except Exception as exc:
|
||||
queue = {'queue': {}, 'jobs': [], 'error': str(exc)}
|
||||
try:
|
||||
graph = legal_graph.status(self.root)
|
||||
except Exception as exc:
|
||||
graph = {'available': False, 'error': str(exc)}
|
||||
enabled = background_corpus.enabled(self.root)
|
||||
schedule_fn = getattr(background_corpus, 'schedule', None)
|
||||
try:
|
||||
schedule = schedule_fn(self.root) if schedule_fn else None
|
||||
except Exception:
|
||||
schedule = None
|
||||
schedule = schedule or {
|
||||
'enabled': enabled, 'interval_days': 7, 'next_run': None,
|
||||
'detail': 'Штатный обработчик Themiz проверяет очередь каждые 5 минут; каждый источник — раз в семь дней.' if enabled else 'Фоновое расписание Themiz не установлено. Ручные задания сохраняются в очереди.'}
|
||||
try:
|
||||
practice = self.practice.summary()
|
||||
except Exception as exc:
|
||||
practice = {'ready': False, 'error': type(exc).__name__}
|
||||
running = {}
|
||||
with self.actions_lock:
|
||||
for key, proc in self.processes.items():
|
||||
running[key] = {'running': proc.poll() is None, 'exit_code': proc.poll()}
|
||||
return {**queue, 'schedule': schedule, 'graph': graph, 'practice': practice, 'processes': running,
|
||||
'index': {'ready': bool(self.library.documents), 'indexing': self.library.lock.locked(),
|
||||
'indexed_at': self.library.indexed_at, 'error': self.library.error},
|
||||
'actions': self.action_results}
|
||||
|
||||
def _spawn(self, action):
|
||||
old = self.processes.get(action)
|
||||
if old and old.poll() is None:
|
||||
return False
|
||||
script, args = ('background_corpus.py', ['--tick']) if action == 'update' else ('legal_graph.py', ['--refresh', '--force', '--json'])
|
||||
# Detached from both HTTP worker and browser; original corpus lock arbitrates.
|
||||
log = self.library.state / (action + '.log')
|
||||
with log.open('ab') as output:
|
||||
proc = subprocess.Popen([sys.executable, str(CODE_ROOT / 'scripts' / script), '--root', str(self.root), *args],
|
||||
stdin=subprocess.DEVNULL, stdout=output, stderr=output,
|
||||
start_new_session=True, cwd=CODE_ROOT, close_fds=True)
|
||||
self.processes[action] = proc
|
||||
return True
|
||||
|
||||
def action(self, path, payload):
|
||||
with self.actions_lock:
|
||||
if path == '/api/update':
|
||||
resource_id = payload.get('id')
|
||||
if resource_id is not None and (not isinstance(resource_id, str) or resource_id not in self.library.documents):
|
||||
raise ValueError('Документ не зарегистрирован')
|
||||
if resource_id:
|
||||
jobs = [background_corpus.enqueue_id(self.root, resource_id, force=True)]
|
||||
else:
|
||||
jobs = background_corpus.enqueue_all(self.root, force=True)
|
||||
started = self._spawn('update')
|
||||
result = {'ok': True, 'jobs': jobs, 'started': started, 'detail': 'Задание сохранено в очереди Themiz.'}
|
||||
if not background_corpus.enabled(self.root):
|
||||
result['detail'] += ' Фоновый обработчик отключён: требуется штатная установка расписания.'
|
||||
with self.cache_lock: # подсчет, начатый до просьбы, не вернется в кеш
|
||||
self.cache.pop('law', None)
|
||||
elif path == '/api/practice/refresh': # сборку ведет задача частей, сервер только просит
|
||||
result = request_walk(self.root)
|
||||
result['detail'] = ('Обход СудАкта начнется в течение минуты.' if result['started']
|
||||
else 'Обход СудАкта уже идет.')
|
||||
with self.cache_lock: # подсчет, начатый до просьбы, не вернется в кеш
|
||||
self.cache.pop('practice', None)
|
||||
elif path == '/api/graph/rebuild':
|
||||
started = self._spawn('graph')
|
||||
result = {'ok': True, 'started': started, 'deduplicated': not started,
|
||||
'detail': 'Пересборка графа запущена.' if started else 'Граф уже собирается.'}
|
||||
else:
|
||||
raise KeyError('Маршрут не найден')
|
||||
self.action_results[path] = {'at': stamp(), 'detail': result['detail']}
|
||||
return result
|
||||
|
||||
|
||||
def handler(app):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = 'Eunomia'
|
||||
|
||||
def log_message(self, *_):
|
||||
pass # Queries and client questions must never enter access logs.
|
||||
|
||||
def allowed(self, write=False):
|
||||
expected = f'127.0.0.1:{self.server.server_port}'
|
||||
if self.headers.get('Host') != expected:
|
||||
return False
|
||||
origin = self.headers.get('Origin')
|
||||
if origin is not None and origin != 'http://' + expected:
|
||||
return False
|
||||
if self.headers.get('Sec-Fetch-Site') not in (None, 'none', 'same-origin'):
|
||||
return False
|
||||
if write:
|
||||
return (origin == 'http://' + expected
|
||||
and hmac.compare_digest(self.headers.get('X-Eunomia-CSRF', ''), app.csrf)
|
||||
and self.headers.get('Content-Type', '').split(';')[0] == 'application/json')
|
||||
return True
|
||||
|
||||
def respond(self, data, status=200, content_type='application/json; charset=utf-8'):
|
||||
raw = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', content_type)
|
||||
self.send_header('Content-Length', str(len(raw)))
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
self.send_header('Referrer-Policy', 'no-referrer')
|
||||
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'")
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def do_GET(self):
|
||||
if not self.allowed():
|
||||
return self.respond({'error': 'Недопустимый источник запроса'}, 403)
|
||||
parsed = urlsplit(self.path)
|
||||
params = {k: v[-1] for k, v in parse_qs(parsed.query).items()}
|
||||
try:
|
||||
if parsed.path == '/api/bootstrap':
|
||||
value = {'name': 'Eunomia', 'csrf': app.csrf, 'documents': app.library.summaries(), 'status': app.status()}
|
||||
elif parsed.path == '/api/status':
|
||||
value = app.status()
|
||||
elif parsed.path == '/api/document':
|
||||
value = app.library.document(params.get('id', ''))
|
||||
elif parsed.path == '/api/reader':
|
||||
value = app.library.reader(params.get('id', ''), params.get('fragment', ''))
|
||||
elif parsed.path == '/api/related':
|
||||
value = app.related_data(params.get('id', ''), params.get('fragment', ''))
|
||||
elif parsed.path == '/api/search':
|
||||
value = app.library.search(params.get('q', ''), params.get('kind', ''))
|
||||
elif parsed.path == '/api/practice':
|
||||
value = app.practice.browse(params)
|
||||
elif parsed.path == '/api/practice/facets':
|
||||
value = app.practice.facets()
|
||||
elif parsed.path == '/api/practice/act':
|
||||
value = app.practice.act(params.get('id', ''))
|
||||
elif parsed.path == '/api/practice/tree':
|
||||
value = app.practice.tree()
|
||||
elif parsed.path == '/api/practice/area':
|
||||
value = app.practice.area(params.get('id', ''))
|
||||
elif parsed.path == '/api/practice/norm':
|
||||
value = app.practice.norm(params.get('id', ''), params.get('fragment', ''))
|
||||
elif parsed.path == '/api/practice/progress':
|
||||
value = app.cached('practice', app.practice_progress)
|
||||
elif parsed.path == '/api/update/progress':
|
||||
value = app.cached('law', app.law_progress)
|
||||
elif parsed.path == '/api/graph':
|
||||
value = app.graph_page(params)
|
||||
elif parsed.path == '/api/graph/network':
|
||||
value = app.graph_network(params)
|
||||
elif parsed.path == '/api/history':
|
||||
value = app.library.history(params.get('id', ''))
|
||||
elif parsed.path == '/api/diff':
|
||||
value = app.library.diff(params.get('id', ''), params.get('before', ''), params.get('after', ''), params.get('fragment', ''))
|
||||
else:
|
||||
filename = {'/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/graph.js': 'graph.js', '/codebook.png': 'codebook.png', '/styles.css': 'styles.css', '/polish.css': 'polish.css', '/favicon.svg': 'favicon.svg', '/eunomia-goddess.png': 'eunomia-goddess.png'}.get(parsed.path)
|
||||
if filename == 'index.html' and (WEB / 'dist/index.html').is_file():
|
||||
filename = 'dist/index.html'
|
||||
if re.fullmatch(r'/assets/(?:books/|pantheon/)?[A-Za-z0-9_-]+\.(?:png|webp|js|css|woff2)', parsed.path):
|
||||
relative = parsed.path.lstrip('/')
|
||||
filename = 'dist/' + relative if (WEB / 'dist' / relative).is_file() else relative
|
||||
target = (WEB / filename).resolve() if filename else None
|
||||
if target is None or not target.is_relative_to(WEB.resolve()) or not target.is_file():
|
||||
return self.respond({'error': 'Страница не найдена'}, 404)
|
||||
mime = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
if mime.startswith('text/') or mime in ('application/javascript', 'application/json'):
|
||||
mime += '; charset=utf-8'
|
||||
return self.respond(target.read_bytes(), content_type=mime)
|
||||
self.respond(value)
|
||||
except (KeyError, FileNotFoundError) as exc:
|
||||
self.respond({'error': str(exc)}, 404)
|
||||
except (ValueError, TypeError) as exc:
|
||||
self.respond({'error': str(exc)}, 400)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
except Exception:
|
||||
self.respond({'error': 'Компонент временно недоступен. Рабочие копии сохранены.'}, 503)
|
||||
|
||||
def do_POST(self):
|
||||
if not self.allowed(write=True):
|
||||
return self.respond({'error': 'Управляющий запрос отклонён'}, 403)
|
||||
try:
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
if not 0 < length <= 4096 or self.headers.get('Transfer-Encoding'):
|
||||
raise ValueError('Недопустимый размер запроса')
|
||||
self.connection.settimeout(5)
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
if not isinstance(payload, dict) or set(payload) - {'id'}:
|
||||
raise ValueError('Недопустимые параметры')
|
||||
self.respond(app.action(urlsplit(self.path).path, payload), 202)
|
||||
except PracticeError as exc: # части остановлены отказом СудАкта: просьба не поставлена
|
||||
self.respond({'error': str(exc)}, 409)
|
||||
except KeyError as exc:
|
||||
self.respond({'error': str(exc)}, 404)
|
||||
except (ValueError, TypeError) as exc:
|
||||
self.respond({'error': str(exc)}, 400)
|
||||
except Exception:
|
||||
self.respond({'error': 'Не удалось поставить задание. Рабочие копии сохранены.'}, 503)
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def serve(root, port=18765):
|
||||
app = App(root)
|
||||
server = ThreadingHTTPServer(('127.0.0.1', port), handler(app))
|
||||
server.daemon_threads = True
|
||||
|
||||
def indexing():
|
||||
while True:
|
||||
app.library.refresh()
|
||||
time.sleep(30)
|
||||
|
||||
threading.Thread(target=indexing, daemon=True, name='eunomia-index').start()
|
||||
print(f'http://127.0.0.1:{server.server_port}', flush=True)
|
||||
server.serve_forever()
|
||||
Reference in New Issue
Block a user