199 lines
6.5 KiB
Python
199 lines
6.5 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import secrets
|
|
from datetime import datetime
|
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
|
|
|
from . import config
|
|
from .i18n import tr
|
|
|
|
ACCEPTED_SUFFIXES = (".geojson", ".json", ".csv", ".kml", ".zip")
|
|
|
|
SUFFIX = ".geojson"
|
|
|
|
|
|
def boundary() -> str:
|
|
return "----GeoDonkeyQGIS" + secrets.token_hex(16)
|
|
|
|
|
|
def multipart(fields: Mapping[str, str], filename: str, data: bytes,
|
|
field: str = "file",
|
|
content_type: str = "application/geo+json",
|
|
mark: str = "") -> Tuple[bytes, str]:
|
|
line = mark or boundary()
|
|
out: List[bytes] = []
|
|
for name, value in fields.items():
|
|
out.append(b"--" + line.encode("ascii") + b"\r\n")
|
|
out.append(('Content-Disposition: form-data; name="%s"\r\n\r\n'
|
|
% name).encode("utf-8"))
|
|
out.append(("%s\r\n" % value).encode("utf-8"))
|
|
out.append(b"--" + line.encode("ascii") + b"\r\n")
|
|
out.append(('Content-Disposition: form-data; name="%s"; filename="%s"\r\n'
|
|
% (field, filename)).encode("utf-8"))
|
|
out.append(("Content-Type: %s\r\n\r\n" % content_type).encode("ascii"))
|
|
out.append(data)
|
|
out.append(b"\r\n--" + line.encode("ascii") + b"--\r\n")
|
|
return b"".join(out), "multipart/form-data; boundary=" + line
|
|
|
|
|
|
def filename_for(name: str) -> str:
|
|
clean = re.sub(r"[^0-9A-Za-zÄÖÜäöüß._ -]+", "", (name or "").strip())
|
|
clean = re.sub(r"[\s_]+", "_", clean).strip("._-")
|
|
if not clean:
|
|
clean = "qgis-layer"
|
|
if len(clean) > 60:
|
|
clean = clean[:60].rstrip("._-")
|
|
lower = clean.lower()
|
|
for suffix in ACCEPTED_SUFFIXES:
|
|
if lower.endswith(suffix):
|
|
return clean[:-len(suffix)] + SUFFIX
|
|
return clean + SUFFIX
|
|
|
|
|
|
def complaint(objects: int, size: int = 0, pro: bool = False) -> str:
|
|
count = int(objects or 0)
|
|
if count <= 0:
|
|
return tr("The layer has no features to upload.")
|
|
limit = config.upload_object_limit(pro)
|
|
if count > limit:
|
|
if pro:
|
|
return tr("At most {limit} features per dataset.").format(limit=limit)
|
|
return tr("At most {limit} features per dataset. Larger datasets need "
|
|
"an active Pro subscription.").format(limit=limit)
|
|
if size and size > config.UPLOAD_MAX_BYTES:
|
|
return tr("The file would be {size}; the limit is {limit}.").format(
|
|
size=pretty_size(size), limit=pretty_size(config.UPLOAD_MAX_BYTES))
|
|
return ""
|
|
|
|
|
|
def clamp_ttl(days: int, pro: bool = False) -> int:
|
|
try:
|
|
value = int(days)
|
|
except (TypeError, ValueError):
|
|
value = config.UPLOAD_DEFAULT_TTL_DAYS
|
|
return max(1, min(value, config.upload_ttl_limit(pro)))
|
|
|
|
|
|
def pretty_size(size: int) -> str:
|
|
value = float(size or 0)
|
|
for unit in ("B", "kB", "MB"):
|
|
if value < 1024.0 or unit == "MB":
|
|
if unit == "B":
|
|
return "%d %s" % (int(value), unit)
|
|
return ("%.1f %s" % (value, unit)).replace(".0 ", " ")
|
|
value /= 1024.0
|
|
return "%d B" % int(size or 0)
|
|
|
|
|
|
def parse_time(text: str) -> Optional[datetime]:
|
|
raw = (text or "").strip()
|
|
if not raw:
|
|
return None
|
|
if raw.endswith("Z"):
|
|
raw = raw[:-1]
|
|
try:
|
|
stamp = datetime.fromisoformat(raw)
|
|
except ValueError:
|
|
return None
|
|
return stamp.replace(tzinfo=None)
|
|
|
|
|
|
def days_left(expires_at: str, now: Optional[datetime] = None) -> Optional[int]:
|
|
stamp = parse_time(expires_at)
|
|
if stamp is None:
|
|
return None
|
|
moment = now or datetime.utcnow()
|
|
seconds = (stamp - moment).total_seconds()
|
|
if seconds <= 0:
|
|
return 0
|
|
return int((seconds + 86399) // 86400)
|
|
|
|
|
|
def describe(meta: Mapping[str, Any], now: Optional[datetime] = None) -> str:
|
|
name = str(meta.get("filename") or meta.get("upload_id") or "?")
|
|
parts = [name]
|
|
count = meta.get("object_count")
|
|
if isinstance(count, int):
|
|
parts.append(tr("{count} feature(s)").format(count=count))
|
|
left = days_left(str(meta.get("expires_at") or ""), now)
|
|
if left is None:
|
|
pass
|
|
elif left <= 0:
|
|
parts.append(tr("expired"))
|
|
elif left == 1:
|
|
parts.append(tr("1 more day"))
|
|
else:
|
|
parts.append(tr("{days} more days").format(days=left))
|
|
return " · ".join(parts)
|
|
|
|
|
|
def datasets(payload: Any) -> List[Dict[str, Any]]:
|
|
if isinstance(payload, Mapping):
|
|
rows = payload.get("datasets")
|
|
elif isinstance(payload, Sequence) and not isinstance(payload, (str, bytes)):
|
|
rows = payload
|
|
else:
|
|
rows = None
|
|
if not isinstance(rows, (list, tuple)):
|
|
return []
|
|
return [dict(row) for row in rows if isinstance(row, Mapping)]
|
|
|
|
|
|
GEOJSON_PATH = "/uploads/{id}/geojson"
|
|
|
|
|
|
def dataset_path(upload_id: str) -> str:
|
|
from urllib.parse import quote
|
|
|
|
return GEOJSON_PATH.format(id=quote((upload_id or "").strip(), safe=""))
|
|
|
|
|
|
def share_url(base_url: str, upload_id: str) -> str:
|
|
ident = (upload_id or "").strip()
|
|
if not ident:
|
|
return ""
|
|
return config.api_endpoint(base_url, dataset_path(ident))
|
|
|
|
|
|
VIEW_PATH = "/view/{id}"
|
|
|
|
|
|
def viewer_url(base_url: str, upload_id: str) -> str:
|
|
from urllib.parse import quote
|
|
|
|
ident = (upload_id or "").strip()
|
|
if not ident:
|
|
return ""
|
|
base = (base_url or config.DEFAULT_API_URL).strip().rstrip("/")
|
|
if base.lower() != config.DEFAULT_API_URL.rstrip("/").lower():
|
|
return ""
|
|
return (config.WEBSITE_URL.rstrip("/")
|
|
+ VIEW_PATH.format(id=quote(ident, safe="")))
|
|
|
|
|
|
def share_warning(viewer: bool = True) -> str:
|
|
if viewer:
|
|
return tr("The link opens the dataset on a map at geodonkey.com - no "
|
|
"account and no API key needed. For colleagues working in "
|
|
"QGIS, 'Copy data address' gives the direct link to the "
|
|
"features instead.")
|
|
return tr("The link returns the data as a GeoJSON file and needs no API key: "
|
|
"anyone who has it can download them, and in QGIS it opens "
|
|
"directly as a vector layer.")
|
|
|
|
|
|
def receipt(meta: Mapping[str, Any]) -> str:
|
|
count = meta.get("object_count")
|
|
coins = meta.get("cost")
|
|
parts = [tr("{count} feature(s) uploaded.").format(
|
|
count=count if isinstance(count, int) else 0)]
|
|
if isinstance(coins, int) and coins > 0:
|
|
parts.append(tr("{coins} DC charged.").format(coins=coins))
|
|
else:
|
|
parts.append(tr("Free of charge."))
|
|
left = days_left(str(meta.get("expires_at") or ""))
|
|
if left:
|
|
parts.append(tr("Stored for {days} more day(s).").format(days=left))
|
|
return " ".join(parts)
|