| 1 |
|
| 2 |
|
| 3 |
n |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 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 |
|
| 86 |
extension_map = config("extension-map") |
| 87 |
if extension_map is None: |
| 88 |
extension_map = EXTENSION_MAP |
| 89 |
self.extension_map = extension_map.get |
| 90 |
|
| 91 |
restrict = config("path-restrict", "auto") |
| 92 |
replace = config("path-replace", "_") |
| 93 |
conv = config("path-convert") |
| 94 |
if restrict == "auto": |
| 95 |
restrict = "\\\\|/<>:\"?*" if WINDOWS else "/" |
| 96 |
elif restrict == "unix": |
| 97 |
restrict = "/" |
| 98 |
elif restrict == "windows": |
| 99 |
restrict = "\\\\|/<>:\"?*" |
| 100 |
elif restrict == "windows+": |
| 101 |
restrict = {"\\": "⧹", "|": "|", "/": "⧸", "<": "<", ">": ">", |
| 102 |
":": ":", '"': """, "?": "?", "*": "*"} |
| 103 |
elif restrict == "ascii": |
| 104 |
restrict = "^0-9A-Za-z_." |
| 105 |
elif restrict == "ascii+": |
| 106 |
restrict = "^0-9@-[\\]-{ #-)+-.;=!}~" |
| 107 |
self.clean_segment = _build_cleanfunc(restrict, replace, conv) |
| 108 |
|
| 109 |
remove = config("path-remove", "\x00-\x1f\x7f") |
| 110 |
self.clean_path = _build_cleanfunc(remove, "") |
| 111 |
|
| 112 |
strip = config("path-strip", "auto") |
| 113 |
if strip == "auto": |
| 114 |
strip = ". " if WINDOWS else "" |
| 115 |
elif strip == "unix": |
| 116 |
strip = "" |
| 117 |
elif strip == "windows": |
| 118 |
strip = ". " |
| 119 |
self.strip = strip |
| 120 |
|
| 121 |
if WINDOWS: |
| 122 |
self.extended = config("path-extended", True) |
| 123 |
|
| 124 |
self.basedirectory_conditions = None |
| 125 |
basedir = extractor._parentdir |
| 126 |
if not basedir: |
| 127 |
basedir = config("base-directory") |
| 128 |
if basedir is None: |
| 129 |
basedir = self.clean_path(f".{os.sep}gallery-dl{os.sep}") |
| 130 |
elif basedir: |
| 131 |
if isinstance(basedir, dict): |
| 132 |
self.basedirectory_conditions = conds = [] |
| 133 |
for expr, bdir in basedir.items(): |
| 134 |
if not expr: |
| 135 |
basedir = bdir |
| 136 |
continue |
| 137 |
conds.append((util.compile_filter(expr), |
| 138 |
self._prepare_basedirectory(bdir))) |
| 139 |
basedir = self._prepare_basedirectory(basedir) |
| 140 |
self.basedirectory = basedir |
| 141 |
|
| 142 |
def _prepare_basedirectory(self, basedir): |
| 143 |
basedir = util.expand_path(basedir) |
| 144 |
if os.altsep and os.altsep in basedir: |
| 145 |
basedir = basedir.replace(os.altsep, os.sep) |
| 146 |
if basedir[-1] != os.sep: |
| 147 |
basedir += os.sep |
| 148 |
return self.clean_path(basedir) |
| 149 |
|
| 150 |
def __str__(self): |
| 151 |
return self.realpath |
| 152 |
|
| 153 |
def open(self, mode="wb"): |
| 154 |
"""Open file and return a corresponding file object""" |
| 155 |
try: |
| 156 |
return open(self.temppath, mode) |
| 157 |
except FileNotFoundError: |
| 158 |
if "r" in mode: |
| 159 |
|
| 160 |
return util.NullContext() |
| 161 |
os.makedirs(self.realdirectory) |
| 162 |
return open(self.temppath, mode) |
| 163 |
|
| 164 |
def exists(self): |
| 165 |
"""Return True if the file exists on disk""" |
| 166 |
if self.extension: |
| 167 |
try: |
| 168 |
os.lstat(self.realpath) |
| 169 |
return self.check_file() |
| 170 |
except OSError: |
| 171 |
pass |
| 172 |
return False |
| 173 |
|
| 174 |
def check_file(self): |
| 175 |
return True |
| 176 |
|
| 177 |
def _enum_file(self): |
| 178 |
num = 1 |
| 179 |
try: |
| 180 |
while True: |
| 181 |
prefix = format(num) + "." |
| 182 |
self.kwdict["extension"] = prefix + self.extension |
| 183 |
self.build_path() |
| 184 |
os.lstat(self.realpath) |
| 185 |
num += 1 |
| 186 |
except OSError: |
| 187 |
pass |
| 188 |
self.prefix = prefix |
| 189 |
return False |
| 190 |
|
| 191 |
def set_directory(self, kwdict): |
| 192 |
"""Build directory path and create it if necessary""" |
| 193 |
self.kwdict = kwdict |
| 194 |
|
| 195 |
if self.basedirectory_conditions is None: |
| 196 |
basedir = self.basedirectory |
| 197 |
else: |
| 198 |
for condition, basedir in self.basedirectory_conditions: |
| 199 |
if condition(kwdict): |
| 200 |
break |
| 201 |
else: |
| 202 |
basedir = self.basedirectory |
| 203 |
|
| 204 |
if segments := self.build_directory(kwdict): |
| 205 |
self.directory = directory = \ |
| 206 |
f"{basedir}{self.clean_path(os.sep.join(segments))}{os.sep}" |
| 207 |
else: |
| 208 |
self.directory = directory = basedir |
| 209 |
|
| 210 |
if WINDOWS and self.extended: |
| 211 |
directory = self._extended_path(directory) |
| 212 |
self.realdirectory = directory |
| 213 |
|
| 214 |
def _extended_path(self, path): |
| 215 |
|
| 216 |
path = os.path.abspath(path) |
| 217 |
if not path.startswith("\\\\"): |
| 218 |
path = "\\\\?\\" + path |
| 219 |
elif not path.startswith("\\\\?\\"): |
| 220 |
path = "\\\\?\\UNC\\" + path[2:] |
| 221 |
|
| 222 |
|
| 223 |
if path[-1] != os.sep: |
| 224 |
return path + os.sep |
| 225 |
return path |
| 226 |
|
| 227 |
def set_filename(self, kwdict): |
| 228 |
"""Set general filename data""" |
| 229 |
self.kwdict = kwdict |
| 230 |
self.filename = self.temppath = self.prefix = "" |
| 231 |
|
| 232 |
ext = kwdict["extension"] |
| 233 |
kwdict["extension"] = self.extension = self.extension_map(ext, ext) |
| 234 |
|
| 235 |
def set_extension(self, extension, real=True): |
| 236 |
"""Set filename extension""" |
| 237 |
self.extension = extension = self.extension_map(extension, extension) |
| 238 |
self.kwdict["extension"] = self.prefix + extension |
| 239 |
|
| 240 |
def fix_extension(self, _=None): |
| 241 |
"""Fix filenames without a given filename extension""" |
| 242 |
try: |
| 243 |
if not self.extension: |
| 244 |
self.kwdict["extension"] = \ |
| 245 |
self.prefix + self.extension_map("", "") |
| 246 |
self.build_path() |
| 247 |
if self.path[-1] == ".": |
| 248 |
self.path = self.path[:-1] |
| 249 |
self.temppath = self.realpath = self.realpath[:-1] |
| 250 |
elif not self.temppath: |
| 251 |
self.build_path() |
| 252 |
except exception.GalleryDLException: |
| 253 |
raise |
| 254 |
except Exception: |
| 255 |
self.path = self.directory + "?" |
| 256 |
self.realpath = self.temppath = self.realdirectory + "?" |
| 257 |
return True |
| 258 |
|
| 259 |
def build_filename(self, kwdict): |
| 260 |
"""Apply 'kwdict' to filename format string""" |
| 261 |
try: |
| 262 |
if self.filename_conditions is None: |
| 263 |
fmt = self.filename_formatter |
| 264 |
else: |
| 265 |
for condition, fmt in self.filename_conditions: |
| 266 |
if condition(kwdict): |
| 267 |
break |
| 268 |
else: |
| 269 |
fmt = self.filename_formatter |
| 270 |
return self.clean_path(self.clean_segment(fmt(kwdict))) |
| 271 |
except Exception as exc: |
| 272 |
raise exception.FilenameFormatError(exc) |
| 273 |
|
| 274 |
def build_directory(self, kwdict, segments=None): |
| 275 |
"""Apply 'kwdict' to directory format strings""" |
| 276 |
try: |
| 277 |
if segments is None: |
| 278 |
if self.directory_conditions is None: |
| 279 |
formatters = self.directory_formatters |
| 280 |
else: |
| 281 |
for condition, formatters in self.directory_conditions: |
| 282 |
if condition(kwdict): |
| 283 |
break |
| 284 |
else: |
| 285 |
formatters = self.directory_formatters |
| 286 |
else: |
| 287 |
formatters = [formatter.parse(fmt).format_map |
| 288 |
for fmt in segments] |
| 289 |
|
| 290 |
segments = [] |
| 291 |
strip = self.strip |
| 292 |
for fmt in formatters: |
| 293 |
segment = fmt(kwdict) |
| 294 |
if segment.__class__ is str: |
| 295 |
segment = segment.strip() |
| 296 |
if strip and segment not in {".", ".."}: |
| 297 |
segment = segment.rstrip(strip) |
| 298 |
if segment: |
| 299 |
segments.append(self.clean_segment(segment)) |
| 300 |
else: |
| 301 |
for segment in segment: |
| 302 |
segment = segment.strip() |
| 303 |
if strip and segment not in {".", ".."}: |
| 304 |
segment = segment.rstrip(strip) |
| 305 |
if segment: |
| 306 |
segments.append(self.clean_segment(segment)) |
| 307 |
return segments |
| 308 |
except Exception as exc: |
| 309 |
raise exception.DirectoryFormatError(exc) |
| 310 |
|
| 311 |
def build_path(self): |
| 312 |
"""Combine directory and filename to full paths""" |
| 313 |
self.filename = filename = self.build_filename(self.kwdict) |
| 314 |
self.path = self.directory + filename |
| 315 |
self.realpath = self.realdirectory + filename |
| 316 |
if not self.temppath: |
| 317 |
self.temppath = self.realpath |
| 318 |
|
| 319 |
def generate_path(self, segments): |
| 320 |
if not segments: |
| 321 |
return "" |
| 322 |
|
| 323 |
root = segments[0] |
| 324 |
if root[0] == ":": |
| 325 |
if ":basedirectory".startswith(root): |
| 326 |
root = self.basedirectory |
| 327 |
elif ":directory".startswith(root): |
| 328 |
root = self.realdirectory |
| 329 |
elif root.startswith(":~"): |
| 330 |
root = os.path.expanduser(root[1:]) |
| 331 |
elif root.startswith(":$"): |
| 332 |
root = os.environ.get(root[2:]) |
| 333 |
elif WINDOWS: |
| 334 |
s = root[:3].replace("/", "\\") |
| 335 |
if not s.startswith(":", 1) and not s.startswith("\\\\"): |
| 336 |
root = None |
| 337 |
elif not root.startswith("/"): |
| 338 |
root = None |
| 339 |
|
| 340 |
if root is None: |
| 341 |
path = self.clean_path(os.sep.join(self.build_directory( |
| 342 |
self.kwdict, segments))) |
| 343 |
else: |
| 344 |
if root[-1] != os.sep: |
| 345 |
root += os.sep |
| 346 |
path = root + self.clean_path(os.sep.join(self.build_directory( |
| 347 |
self.kwdict, segments[1:]))) |
| 348 |
|
| 349 |
return path |
| 350 |
|
| 351 |
def part_enable(self, part_directory=None): |
| 352 |
"""Enable .part file usage""" |
| 353 |
if self.extension: |
| 354 |
self.temppath += ".part" |
| 355 |
else: |
| 356 |
self.kwdict["extension"] = self.prefix + self.extension_map( |
| 357 |
"part", "part") |
| 358 |
self.build_path() |
| 359 |
|
| 360 |
if part_directory is not None: |
| 361 |
if isinstance(part_directory, list): |
| 362 |
for condition, part_directory in part_directory: |
| 363 |
if condition(self.kwdict): |
| 364 |
break |
| 365 |
else: |
| 366 |
return |
| 367 |
|
| 368 |
self.temppath = os.path.join( |
| 369 |
part_directory, |
| 370 |
os.path.basename(self.temppath), |
| 371 |
) |
| 372 |
|
| 373 |
def part_size(self): |
| 374 |
"""Return size of .part file""" |
| 375 |
try: |
| 376 |
return os.stat(self.temppath).st_size |
| 377 |
except OSError: |
| 378 |
pass |
| 379 |
return 0 |
| 380 |
|
| 381 |
def set_mtime(self, path=None): |
| 382 |
if (mtime := (self.kwdict.get("_mtime_meta") or |
| 383 |
self.kwdict.get("_mtime_http"))): |
| 384 |
util.set_mtime(self.realpath if path is None else path, mtime) |
| 385 |
|
| 386 |
def finalize(self): |
| 387 |
"""Move tempfile to its target location""" |
| 388 |
if self.delete: |
| 389 |
self.delete = False |
| 390 |
os.unlink(self.temppath) |
| 391 |
return |
| 392 |
|
| 393 |
if self.temppath != self.realpath: |
| 394 |
|
| 395 |
while True: |
| 396 |
try: |
| 397 |
os.replace(self.temppath, self.realpath) |
| 398 |
except FileNotFoundError: |
| 399 |
try: |
| 400 |
|
| 401 |
os.makedirs(self.realdirectory) |
| 402 |
except FileExistsError: |
| 403 |
|
| 404 |
return False |
| 405 |
continue |
| 406 |
except OSError: |
| 407 |
|
| 408 |
try: |
| 409 |
shutil.copyfile(self.temppath, self.realpath) |
| 410 |
except FileNotFoundError: |
| 411 |
try: |
| 412 |
os.makedirs(self.realdirectory) |
| 413 |
except FileExistsError: |
| 414 |
return False |
| 415 |
shutil.copyfile(self.temppath, self.realpath) |
| 416 |
os.unlink(self.temppath) |
| 417 |
break |
| 418 |
|
| 419 |
self.set_mtime() |
| 420 |
|
| 421 |
|
| 422 |
def _build_convertfunc(func, conv): |
| 423 |
if len(conv) <= 1: |
| 424 |
conv = formatter._CONVERSIONS[conv] |
| 425 |
return lambda x: conv(func(x)) |
| 426 |
|
| 427 |
def convert_many(x): |
| 428 |
x = func(x) |
| 429 |
for conv in convs: |
| 430 |
x = conv(x) |
| 431 |
return x |
| 432 |
convs = [formatter._CONVERSIONS[c] for c in conv] |
| 433 |
return convert_many |
| 434 |
|
| 435 |
|
| 436 |
def _build_cleanfunc(chars, repl, conv=None): |
| 437 |
if not chars: |
| 438 |
func = util.identity |
| 439 |
elif isinstance(chars, dict): |
| 440 |
if 0 not in chars: |
| 441 |
chars = _process_repl_dict(chars) |
| 442 |
chars[0] = None |
| 443 |
|
| 444 |
def func(x): |
| 445 |
return x.translate(table) |
| 446 |
table = str.maketrans(chars) |
| 447 |
elif len(chars) == 1: |
| 448 |
def func(x): |
| 449 |
return x.replace(chars, repl) |
| 450 |
else: |
| 451 |
func = functools.partial(util.re(f"[{chars}]").sub, repl) |
| 452 |
return _build_convertfunc(func, conv) if conv else func |
| 453 |
|
| 454 |
|
| 455 |
def _process_repl_dict(chars): |
| 456 |
|
| 457 |
for char in [c for c in chars if len(c) > 1]: |
| 458 |
if len(char) == 3 and char[1] == "-": |
| 459 |
citer = range(ord(char[0]), ord(char[2])+1) |
| 460 |
else: |
| 461 |
citer = char |
| 462 |
|
| 463 |
repl = chars.pop(char) |
| 464 |
for c in citer: |
| 465 |
chars[c] = repl |
| 466 |
|
| 467 |
return chars |