46 lines
2.0 KiB
Python
46 lines
2.0 KiB
Python
"""Ce qu'aimsight-app appelle pour pomper les conversations (son onglet Conversations), le jumeau d'extraction/pumping.py
|
|
d'aimsight-data : lancer pomper.sh, savoir s'il tourne, lire la fin de son journal. Importé comme module simple (sys.path =
|
|
conversations/) : aucun import du paquet ici."""
|
|
import fcntl
|
|
import os
|
|
import re
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
JOUR = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
PLAGE = "a range: From and To, YYYY-MM-DD, From before To" # les mots de pumping.py, montrés tels quels par l'app
|
|
|
|
|
|
def running() -> bool:
|
|
"""Un pompage en cours : le verrou de pomper.sh est tenu."""
|
|
try:
|
|
with open(ROOT / "out" / "conversations.lock") as verrou:
|
|
fcntl.flock(verrou, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except FileNotFoundError:
|
|
return False
|
|
except BlockingIOError:
|
|
return True
|
|
return False
|
|
|
|
|
|
def log(lines: int = 40) -> list[str]:
|
|
"""Les dernières lignes de out/conversations.log."""
|
|
try:
|
|
with open(ROOT / "out" / "conversations.log", "rb") as f:
|
|
f.seek(max(0, f.seek(0, os.SEEK_END) - 300 * lines))
|
|
return f.read().decode(errors="replace").splitlines()[-lines:]
|
|
except FileNotFoundError:
|
|
return []
|
|
|
|
|
|
def start(depuis: str, jusqu_a: str, sortie: str) -> subprocess.Popen:
|
|
"""pomper.sh en arrière-plan, dans sortie ; avec une plage (AAAA-MM-JJ, jusqu_a exclu) ou sans (ce qui a changé)."""
|
|
if bool(depuis) != bool(jusqu_a) or (depuis and not (JOUR.fullmatch(depuis) and JOUR.fullmatch(jusqu_a) and depuis < jusqu_a)):
|
|
raise ValueError(PLAGE)
|
|
if running():
|
|
raise ValueError("a pumping of the conversations is already running")
|
|
plage = ["--depuis", depuis, "--jusqu-a", jusqu_a] if depuis else []
|
|
return subprocess.Popen([str(ROOT / "conversations" / "pomper.sh"), "--sortie", str(sortie), *plage], cwd=ROOT,
|
|
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|