Coverage for pdfcompress/tasks.py: 100%

83 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-27 10:10 +0000

1import logging 

2import re 

3import shutil 

4import subprocess 

5import threading 

6from collections import deque 

7from datetime import timedelta 

8from pathlib import Path 

9 

10from django.conf import settings 

11from django.core.files.storage import default_storage 

12from django.utils import timezone 

13 

14from .models import PdfJob 

15 

16logger = logging.getLogger(__name__) 

17 

18# Ghostscript meldet ohne -q: "Processing pages 1 through 12." und dann "Page 1", ... 

19TOTAL_RE = re.compile(r"^Processing pages (\d+) through (\d+)\.") 

20PAGE_RE = re.compile(r"^Page \d+") 

21 

22 

23def compress_pdf(job_id): 

24 # Atomar von PENDING auf RUNNING: verhindert doppelte Ausführung bei Retries 

25 claimed = PdfJob.objects.filter(pk=job_id, status=PdfJob.Status.PENDING).update( 

26 status=PdfJob.Status.RUNNING 

27 ) 

28 if not claimed: 

29 return 

30 job = PdfJob.objects.get(pk=job_id) 

31 qs = PdfJob.objects.filter(pk=job_id) 

32 src = Path(job.input_file.path) 

33 dst = src.with_name("output.pdf") 

34 

35 try: 

36 _run_ghostscript(src, dst, job.quality, qs) 

37 output_name = str(Path(job.input_file.name).with_name("output.pdf")) 

38 # Schon optimierte PDFs können größer werden -> dann Original ausliefern 

39 if dst.stat().st_size >= job.input_size: 

40 dst.unlink() 

41 output_name = job.input_file.name 

42 output_size = job.input_size 

43 else: 

44 output_size = dst.stat().st_size 

45 qs.update( 

46 status=PdfJob.Status.DONE, 

47 progress=100, 

48 output_file=output_name, 

49 output_size=output_size, 

50 ) 

51 except Exception as exc: 

52 logger.exception("PDF-Komprimierung fehlgeschlagen: %s", job_id) 

53 dst.unlink(missing_ok=True) 

54 # Dem Nutzer keine Serverpfade zeigen; Details stehen im Log 

55 message = str(exc) if isinstance(exc, CompressionError) else "Interner Fehler." 

56 qs.update(status=PdfJob.Status.FAILED, error=message) 

57 

58 

59class CompressionError(Exception): 

60 pass 

61 

62 

63def _run_ghostscript(src, dst, quality, qs): 

64 cmd = [ 

65 getattr(settings, "GHOSTSCRIPT_BINARY", "gs"), 

66 "-dSAFER", 

67 "-dBATCH", 

68 "-dNOPAUSE", 

69 "-sDEVICE=pdfwrite", 

70 "-dCompatibilityLevel=1.5", 

71 f"-dPDFSETTINGS=/{quality}", 

72 f"-sOutputFile={dst}", 

73 str(src), 

74 ] 

75 timeout = getattr(settings, "PDFCOMPRESS_TIMEOUT", 600) 

76 timed_out = threading.Event() 

77 tail = deque(maxlen=20) # letzte Zeilen fürs Log 

78 total = done = last = 0 

79 

80 with subprocess.Popen( 

81 cmd, 

82 stdout=subprocess.PIPE, 

83 stderr=subprocess.STDOUT, # eine Pipe -> kein Deadlock 

84 text=True, 

85 errors="replace", 

86 bufsize=1, 

87 ) as proc: 

88 

89 def kill(): 

90 timed_out.set() 

91 proc.kill() 

92 

93 # Watchdog: greift auch, wenn gs hängt und nichts mehr ausgibt 

94 watchdog = threading.Timer(timeout, kill) 

95 watchdog.start() 

96 try: 

97 for line in proc.stdout: 

98 tail.append(line.rstrip()) 

99 if match := TOTAL_RE.match(line): 

100 total = int(match[2]) - int(match[1]) + 1 

101 elif total and PAGE_RE.match(line): 

102 done += 1 

103 # "Page n" kommt zu Beginn der Seite; 100 % erst nach Exit 

104 percent = min(99, (done - 1) * 100 // total) 

105 if percent > last: # max. ~100 DB-Writes pro Job 

106 last = percent 

107 qs.update(progress=percent) 

108 returncode = proc.wait() 

109 finally: 

110 watchdog.cancel() 

111 if proc.poll() is None: 

112 proc.kill() 

113 

114 if timed_out.is_set(): 

115 raise CompressionError("Zeitlimit überschritten.") 

116 # gs liefert bei manchen kaputten/verschlüsselten PDFs trotzdem Exit-Code 0 

117 if returncode != 0 or not total or done < total or not dst.exists(): 

118 logger.error("Ghostscript (rc=%s):\n%s", returncode, "\n".join(tail)) 

119 raise CompressionError("Die PDF-Datei ist beschädigt oder passwortgeschützt.") 

120 

121 

122def cleanup_old_jobs(hours=24): 

123 """Als django-q2-Schedule einplanen (z. B. stündlich).""" 

124 limit = timezone.now() - timedelta(hours=hours) 

125 for job in PdfJob.objects.filter(created__lt=limit): 

126 # Jeder Job hat ein eigenes Verzeichnis: komplett entfernen, inklusive 

127 # Resten eines abgebrochenen Workers. Schlägt das fehl, bleibt der 

128 # Datensatz erhalten und der nächste Lauf versucht es erneut. 

129 directory = default_storage.path(f"pdfcompress/{job.pk}") 

130 try: 

131 shutil.rmtree(directory) 

132 except FileNotFoundError: 

133 pass 

134 except OSError: 

135 logger.exception("Aufräumen fehlgeschlagen: %s", directory) 

136 continue 

137 job.delete()