Debian Codegraph @

gallery_dl/cache.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2016-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 """Utilities for caching function results"""
10
11 import os
12 import time
13 import logging
14 from . import config, util
15
16 log = logging.getLogger("cache")
17 DATABASE = PATH = ERR = None
18
19
20 def database():
21 global DATABASE, ERR
22
23 try:
24 path_ = path()
25
26 if path_ != ":memory:":
27 # restrict access permissions for new db files
28 os.close(os.open(path_, os.O_CREAT | os.O_RDONLY, 0o600))
29
30 import sqlite3
31 DATABASE = sqlite3.connect(path_, timeout=60, check_same_thread=False)
32 except Exception as exc:
33 log.debug("Failed to connect to SQLite3 database (%s: %s)",
34 exc.__class__.__name__, exc)
35 ERR = exc
36 else:
37 log.debug("Connected to SQLite3 database '%s'", path_)
38 DATABASE.execute(
39 "CREATE TABLE IF NOT EXISTS data "
40 "(key TEXT PRIMARY KEY, value TEXT, expires INTEGER)")
41
42 globals()["database"] = lambda: DATABASE
43 return DATABASE
44
45
46 def path():
47 global PATH
48
49 path = config.get(("cache",), "file", util.SENTINEL)
50 if path is not util.SENTINEL:
51 return util.expand_path(path)
52
53 if util.WINDOWS:
54 cachedir = os.environ.get("APPDATA", "~")
55 else:
56 cachedir = os.environ.get("XDG_CACHE_HOME", "~/.cache")
57
58 cachedir = util.expand_path(os.path.join(cachedir, "gallery-dl"))
59 os.makedirs(cachedir, exist_ok=True)
60 PATH = os.path.join(cachedir, "cache.sqlite3")
61
62 globals()["path"] = lambda: PATH
63 return PATH
64
65
66 def error(ret=1):
67 log.error("No database connection (%s: %s)", ERR.__class__.__name__, ERR)
68 return ret
69
70
71 def get(module):
72 if (db := database()) is None:
73 return
74
75 try:
76 if module == "ALL":
77 return db.execute(
78 "SELECT * FROM data")
79 if module == "VAL":
80 return db.execute(
81 "SELECT * FROM data WHERE expires > ?",
82 (int(time.time()),))
83 if module == "EXP":
84 return db.execute(
85 "SELECT * FROM data WHERE expires < ? AND expires <> 0",
86 (int(time.time()),))
87
88 module = module.lower()
89 return db.execute(
90 "SELECT * FROM data "
91 "WHERE key LIKE 'gallery_dl.extractor.' || ? || '.%'"
92 "OR key LIKE 'gallery_dl.extractor.utils.' || ? || '_%'",
93 (module, module))
94 except Exception:
95 pass # database not initialized, cannot be modified, etc.
96 return
97
98
99 def clear(module):
100 """Delete database entries for 'module'"""
101 if (db := database()) is None:
102 return
103
104 rowcount = 0
105 cursor = db.cursor()
106
107 try:
108 if module == "ALL":
109 cursor.execute("DELETE FROM data")
110 elif module == "EXP":
111 cursor.execute(
112 "DELETE FROM data WHERE expires < ? AND expires <> 0",
113 (int(time.time()),))
114 else:
115 module = module.lower()
116 cursor.execute(
117 "DELETE FROM data "
118 "WHERE key LIKE 'gallery_dl.extractor.' || ? || '.%'"
119 "OR key LIKE 'gallery_dl.extractor.utils.' || ? || '_%'",
120 (module, module))
121 except Exception:
122 pass # database not initialized, cannot be modified, etc.
123 else:
124 rowcount = cursor.rowcount
125 db.commit()
126 return rowcount