Debian Codegraph @

gallery_dl/path.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2021-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Filesystem path handling"""
10
11 import os
12 import shutil
13 import functools
14 from . import util, formatter, exception
15
16 WINDOWS = util.WINDOWS
17 EXTENSION_MAP = {
18 "jpeg": "jpg",
19 "jpe" : "jpg",
20 "jfif": "jpg",
21 "jif" : "jpg",
22 "jfi" : "jpg",
23 "html": "htm",
24 }
25
26
27 class PathFormat():
28
29 def __init__(self, extractor):
30 config = extractor.config
31 kwdefault = config("keywords-default")
32 if kwdefault is None:
33 kwdefault = util.NONE
34
35 self.filename_conditions = self.directory_conditions = None
36
37 filename_fmt = config("filename")
38 try:
39 if filename_fmt is None:
40 filename_fmt = extractor.filename_fmt
41 elif isinstance(filename_fmt, dict):
42 self.filename_conditions = [
43 (util.compile_filter(expr),
44 formatter.parse(fmt, kwdefault).format_map)
45 for expr, fmt in filename_fmt.items() if expr
46 ]
47 filename_fmt = filename_fmt.get("", extractor.filename_fmt)
48
49 self.filename_formatter = formatter.parse(
50 filename_fmt, kwdefault).format_map
51 except Exception as exc:
52 raise exception.FilenameFormatError(exc)
53
54 directory_fmt = config("directory")
55 try:
56 if directory_fmt is None:
57 directory_fmt = extractor.directory_fmt
58 elif isinstance(directory_fmt, dict):
59 self.directory_conditions = [
60 (util.compile_filter(expr), [
61 formatter.parse(fmt, kwdefault).format_map
62 for fmt in fmts
63 ])
64 for expr, fmts in directory_fmt.items() if expr
65 ]
66 directory_fmt = directory_fmt.get("", extractor.directory_fmt)
67
68 self.directory_formatters = [
69 formatter.parse(dirfmt, kwdefault).format_map
70 for dirfmt in directory_fmt
71 ]
72 except Exception as exc:
73 raise exception.DirectoryFormatError(exc)
74
75 self.kwdict = {}
76 self.delete = False
77 self.prefix = ""
78 self.filename = ""
79 self.extension = ""
80 self.directory = ""
81 self.realdirectory = ""
82 self.path = ""
83 self.realpath = ""
84 self.temppath = ""
85 self.part = False
86
87 extension_map = config("extension-map")
88 if extension_map is None:
89 extension_map = EXTENSION_MAP
90 self.extension_map = extension_map.get
91
92 restrict = config("path-restrict", "auto")
93 replace = config("path-replace", "_")
94 conv = config("path-convert")
95 if restrict == "auto":
96 restrict = "\\\\|/<>:\"?*" if WINDOWS else "/"
97 elif restrict == "unix":
98 restrict = "/"
99 elif restrict == "windows":
100 restrict = "\\\\|/<>:\"?*"
101 elif restrict == "windows+":
102 restrict = {"\\": "⧹", "|": "|", "/": "⧸", "<": "<", ">": ">",
103 ":": ":", '"': """, "?": "?", "*": "*"}
104 elif restrict == "ascii":
105 restrict = "^0-9A-Za-z_."
106 elif restrict == "ascii+":
107 restrict = "^0-9@-[\\]-{ #-)+-.;=!}~"
108 self.clean_segment = _build_cleanfunc(restrict, replace, conv)
109
110 remove = config("path-remove", "\x00-\x1f\x7f")
111 self.clean_path = _build_cleanfunc(remove, "")
112
113 strip = config("path-strip", "auto")
114 if strip == "auto":
115 strip = ". " if WINDOWS else ""
116 elif strip == "unix":
117 strip = ""
118 elif strip == "windows":
119 strip = ". "
120 self.strip = strip
121 self.sub = sub if (sub := config("path-sub")) else None
122
123 if WINDOWS:
124 self.extended = config("path-extended", True)
125
126 self.basedirectory_conditions = None
127 basedir = extractor._parentdir
128 if not basedir:
129 basedir = config("base-directory")
130 if basedir is None:
131 basedir = self.clean_path(f".{os.sep}gallery-dl{os.sep}")
132 elif basedir:
133 if isinstance(basedir, dict):
134 self.basedirectory_conditions = conds = []
135 for expr, bdir in basedir.items():
136 if not expr:
137 basedir = bdir
138 continue
139 conds.append((util.compile_filter(expr),
140 self._prepare_basedirectory(bdir)))
141 basedir = self._prepare_basedirectory(basedir)
142 self.basedirectory = basedir
143
144 def _prepare_basedirectory(self, basedir):
145 basedir = util.expand_path(basedir)
146 if os.altsep and os.altsep in basedir:
147 basedir = basedir.replace(os.altsep, os.sep)
148 if basedir[-1] != os.sep:
149 basedir += os.sep
150 return self.clean_path(basedir)
151
152 def __str__(self):
153 return self.realpath
154
155 def open(self, mode="wb"):
156 """Open file and return a corresponding file object"""
157 try:
158 return open(self.temppath, mode)
159 except FileNotFoundError:
160 if "r" in mode:
161 # '.part' file no longer exists
162 return util.NullContext()
163 os.makedirs(self.realdirectory)
164 return open(self.temppath, mode)
165
166 def exists(self):
167 """Return True if the file exists on disk"""
168 if self.extension:
169 try:
170 os.lstat(self.realpath) # raises OSError if file doesn't exist
171 return self.check_file()
172 except OSError:
173 pass
174 return False
175
176 def check_file(self):
177 return True
178
179 def _enum_file(self):
180 num = 1
181 try:
182 while True:
183 prefix = format(num) + "."
184 self.kwdict["extension"] = prefix + self.extension
185 self.build_path()
186 os.lstat(self.realpath) # raises OSError if file doesn't exist
187 num += 1
188 except OSError:
189 pass
190 self.prefix = prefix
191 return False
192
193 def set_directory(self, kwdict):
194 """Build directory path and create it if necessary"""
195 self.kwdict = kwdict
196
197 if self.basedirectory_conditions is None:
198 basedir = self.basedirectory
199 else:
200 for condition, basedir in self.basedirectory_conditions:
201 if condition(kwdict):
202 break
203 else:
204 basedir = self.basedirectory
205
206 if segments := self.build_directory(kwdict):
207 self.directory = directory = \
208 f"{basedir}{self.clean_path(os.sep.join(segments))}{os.sep}"
209 else:
210 self.directory = directory = basedir
211
212 if WINDOWS and self.extended:
213 directory = self._extended_path(directory)
214 self.realdirectory = directory
215
216 def _extended_path(self, path):
217 # Enable longer-than-260-character paths
218 path = os.path.abspath(path)
219 if not path.startswith("\\\\"):
220 path = "\\\\?\\" + path
221 elif not path.startswith("\\\\?\\"):
222 path = "\\\\?\\UNC\\" + path[2:]
223
224 # abspath() in Python 3.7+ removes trailing path separators (#402)
225 if path[-1] != os.sep:
226 return path + os.sep
227 return path
228
229 def set_filename(self, kwdict):
230 """Set general filename data"""
231 self.part = False
232 self.kwdict = kwdict
233 self.filename = self.temppath = self.prefix = ""
234
235 ext = kwdict["extension"]
236 kwdict["extension"] = self.extension = self.extension_map(ext, ext)
237
238 def set_extension(self, extension, real=True):
239 """Set filename extension"""
240 self.extension = extension = self.extension_map(extension, extension)
241 self.kwdict["extension"] = self.prefix + extension
242
243 def fix_extension(self, _=None):
244 """Fix filenames without a given filename extension"""
245 try:
246 if not self.extension:
247 self.kwdict["extension"] = \
248 self.prefix + self.extension_map("", "")
249 self.build_path()
250 if self.path[-1] == ".":
251 self.path = self.path[:-1]
252 self.temppath = self.realpath = self.realpath[:-1]
253 elif not self.temppath:
254 self.build_path()
255 except exception.GalleryDLException:
256 raise
257 except Exception:
258 self.path = self.directory + "?"
259 self.realpath = self.temppath = self.realdirectory + "?"
260 return True
261
262 def build_filename(self, kwdict):
263 """Apply 'kwdict' to filename format string"""
264 try:
265 if self.filename_conditions is None:
266 fmt = self.filename_formatter
267 else:
268 for condition, fmt in self.filename_conditions:
269 if condition(kwdict):
270 break
271 else:
272 fmt = self.filename_formatter
273 return self.clean_path(self.clean_segment(fmt(kwdict)))
274 except Exception as exc:
275 raise exception.FilenameFormatError(exc)
276
277 def build_directory(self, kwdict, segments=None):
278 """Apply 'kwdict' to directory format strings"""
279 try:
280 if segments is None:
281 if self.directory_conditions is None:
282 formatters = self.directory_formatters
283 else:
284 for condition, formatters in self.directory_conditions:
285 if condition(kwdict):
286 break
287 else:
288 formatters = self.directory_formatters
289 else:
290 formatters = [formatter.parse(fmt).format_map
291 for fmt in segments]
292
293 segments = []
294 sub = self.sub
295 strip = self.strip
296 for fmt in formatters:
297 segment = fmt(kwdict)
298 if segment.__class__ is str:
299 segment = segment.strip()
300 if strip and segment not in {".", ".."}:
301 segment = segment.rstrip(strip)
302 if sub is not None and segment in sub:
303 segment = sub[segment]
304 if segment:
305 segments.append(self.clean_segment(segment))
306 else: # assume list
307 for segment in segment:
308 segment = segment.strip()
309 if strip and segment not in {".", ".."}:
310 segment = segment.rstrip(strip)
311 if sub is not None and segment in sub:
312 segment = sub[segment]
313 if segment:
314 segments.append(self.clean_segment(segment))
315 return segments
316 except Exception as exc:
317 raise exception.DirectoryFormatError(exc)
318
319 def build_path(self):
320 """Combine directory and filename to full paths"""
321 self.filename = filename = self.build_filename(self.kwdict)
322 self.path = self.directory + filename
323 self.realpath = self.realdirectory + filename
324 if not self.temppath:
325 self.temppath = self.realpath
326
327 def generate_path(self, segments):
328 if not segments:
329 return ""
330
331 root = segments[0]
332 if root[0] == ":":
333 if ":basedirectory".startswith(root):
334 root = self.basedirectory
335 elif ":directory".startswith(root):
336 root = self.realdirectory
337 elif root.startswith(":~"):
338 root = os.path.expanduser(root[1:])
339 elif root.startswith(":$"):
340 root = os.environ.get(root[2:])
341 elif WINDOWS:
342 s = root[:3].replace("/", "\\")
343 if not s.startswith(":", 1) and not s.startswith("\\\\"):
344 root = None
345 elif not root.startswith("/"):
346 root = None
347
348 if root is None:
349 path = self.clean_path(os.sep.join(self.build_directory(
350 self.kwdict, segments)))
351 else:
352 if root[-1] != os.sep:
353 root += os.sep
354 path = root + self.clean_path(os.sep.join(self.build_directory(
355 self.kwdict, segments[1:])))
356
357 return path
358
359 def part_enable(self, part_directory=None):
360 """Enable .part file usage"""
361 if self.part:
362 return
363 if self.extension:
364 self.temppath += ".part"
365 else:
366 self.kwdict["extension"] = self.prefix + self.extension_map(
367 "part", "part")
368 self.build_path()
369
370 if part_directory is not None:
371 if isinstance(part_directory, list):
372 for condition, part_directory in part_directory:
373 if condition(self.kwdict):
374 break
375 else:
376 return
377
378 self.temppath = os.path.join(
379 part_directory,
380 os.path.basename(self.temppath),
381 )
382 self.part = True
383
384 def part_size(self):
385 """Return size of .part file"""
386 try:
387 return os.stat(self.temppath).st_size
388 except OSError:
389 pass
390 return 0
391
392 def set_mtime(self, path=None):
393 if (mtime := (self.kwdict.get("_mtime_meta") or
394 self.kwdict.get("_mtime_http"))):
395 util.set_mtime(self.realpath if path is None else path, mtime)
396
397 def finalize(self):
398 """Move tempfile to its target location"""
399 self.part = False
400
401 if self.delete:
402 self.delete = False
403 os.unlink(self.temppath)
404 return
405
406 if self.temppath != self.realpath:
407 # Move temp file to its actual location
408 while True:
409 try:
410 os.replace(self.temppath, self.realpath)
411 except FileNotFoundError:
412 try:
413 # delayed directory creation
414 os.makedirs(self.realdirectory)
415 except FileExistsError:
416 # file at self.temppath does not exist
417 return False
418 continue
419 except OSError:
420 # move across different filesystems
421 try:
422 shutil.copyfile(self.temppath, self.realpath)
423 except FileNotFoundError:
424 try:
425 os.makedirs(self.realdirectory)
426 except FileExistsError:
427 return False
428 shutil.copyfile(self.temppath, self.realpath)
429 os.unlink(self.temppath)
430 break
431
432 self.set_mtime()
433
434
435 def _build_convertfunc(func, conv):
436 if len(conv) <= 1:
437 conv = formatter._CONVERSIONS[conv]
438 return lambda x: conv(func(x))
439
440 def convert_many(x):
441 x = func(x)
442 for conv in convs:
443 x = conv(x)
444 return x
445 convs = [formatter._CONVERSIONS[c] for c in conv]
446 return convert_many
447
448
449 def _build_cleanfunc(chars, repl, conv=None):
450 if not chars:
451 func = util.identity
452 elif isinstance(chars, dict):
453 if 0 not in chars:
454 chars = _process_repl_dict(chars)
455 chars[0] = None
456
457 def func(x):
458 return x.translate(table)
459 table = str.maketrans(chars)
460 elif len(chars) == 1:
461 def func(x):
462 return x.replace(chars, repl)
463 else:
464 func = functools.partial(util.re(f"[{chars}]").sub, repl)
465 return _build_convertfunc(func, conv) if conv else func
466
467
468 def _process_repl_dict(chars):
469 # can't modify 'chars' while *directly* iterating over its keys
470 for char in [c for c in chars if len(c) > 1]:
471 if len(char) == 3 and char[1] == "-":
472 citer = range(ord(char[0]), ord(char[2])+1)
473 else:
474 citer = char
475
476 repl = chars.pop(char)
477 for c in citer:
478 chars[c] = repl
479
480 return chars