Debian Codegraph @

gallery_dl/archive.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2024-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 """Download Archives"""
10
11 import os
12 import logging
13 from . import util, formatter
14
15 CACHE_CONNECTIONS = {}
16 log = logging.getLogger("archive")
17
18
19 def connect(path, prefix, format, table=None, mode=None, reuse=False,
20 pragma=None, pathfmt=None, cache_key=None):
21 keygen = formatter.parse(prefix + format).format_map
22
23 if isinstance(path, str) and path.startswith(
24 ("postgres://", "postgresql://")):
25 cls = (DownloadArchivePostgresqlMemory if mode == "memory" else
26 DownloadArchivePostgresql)
27 else:
28 if isinstance(path, list):
29 path = pathfmt.generate_path(path)
30 else:
31 if "{" in path:
32 log.error("Replacement fields in 'string' archive paths are "
33 "no longer supported. Use a list of strings "
34 "instead.")
35 path = util.expand_path(path)
36 cls = DownloadArchiveMemory if mode == "memory" else DownloadArchive
37
38 if pathfmt is not None and table:
39 table = formatter.parse(table).format_map(pathfmt.kwdict)
40
41 return cls(path, keygen, table, pragma, cache_key, reuse)
42
43
44 def close_cached():
45 log.debug("Closing database connections")
46 for path, con in CACHE_CONNECTIONS.items():
47 log.debug("- %s", path)
48 con.close()
49
50
51 def sanitize(name):
52 return f'''"{name.replace('"', '_')}"'''
53
54
55 class DownloadArchive():
56 _sqlite3 = None
57
58 def __init__(self, path, keygen, table=None, pragma=None, cache_key=None,
59 reuse=False):
60 self.connection = con = self.connect(path, reuse, pragma)
61 self.keygen = keygen
62 self.close = util.noop if reuse else con.close
63 self.cursor = cursor = con.cursor()
64 self._cache_key = cache_key or "_archive_key"
65
66 table = "archive" if table is None else sanitize(table)
67 self._stmt_select = (
68 f"SELECT 1 "
69 f"FROM {table} "
70 f"WHERE entry=? "
71 f"LIMIT 1")
72 self._stmt_insert = (
73 f"INSERT OR IGNORE INTO {table} "
74 f"(entry) VALUES (?)")
75
76 try:
77 cursor.execute(f"CREATE TABLE IF NOT EXISTS {table} "
78 f"(entry TEXT PRIMARY KEY) WITHOUT ROWID")
79 except self._sqlite3.OperationalError:
80 # fallback for missing WITHOUT ROWID support (#553)
81 cursor.execute(f"CREATE TABLE IF NOT EXISTS {table} "
82 f"(entry TEXT PRIMARY KEY)")
83
84 def connect(self, path, reuse=False, pragma=None):
85 if reuse and (con := CACHE_CONNECTIONS.get(path)):
86 return con
87
88 if self._sqlite3 is None:
89 DownloadArchive._sqlite3 = __import__("sqlite3")
90
91 try:
92 con = self._sqlite3.connect(
93 path, timeout=60, check_same_thread=False)
94 except self._sqlite3.OperationalError:
95 os.makedirs(os.path.dirname(path))
96 con = self._sqlite3.connect(
97 path, timeout=60, check_same_thread=False)
98 con.isolation_level = None
99
100 if pragma:
101 cursor = con.cursor()
102 for stmt in pragma:
103 cursor.execute("PRAGMA " + stmt)
104 if reuse:
105 if not CACHE_CONNECTIONS:
106 import atexit
107 atexit.register(close_cached)
108 CACHE_CONNECTIONS[path] = con
109
110 return con
111
112 def add(self, kwdict):
113 """Add item described by 'kwdict' to archive"""
114 key = kwdict.get(self._cache_key) or self.keygen(kwdict)
115 self.cursor.execute(self._stmt_insert, (key,))
116
117 def check(self, kwdict):
118 """Return True if the item described by 'kwdict' exists in archive"""
119 key = kwdict[self._cache_key] = self.keygen(kwdict)
120 self.cursor.execute(self._stmt_select, (key,))
121 return self.cursor.fetchone()
122
123 def finalize(self):
124 pass
125
126
127 class DownloadArchiveMemory(DownloadArchive):
128
129 def __init__(self, path, keygen, table=None, pragma=None, cache_key=None,
130 reuse=False):
131 DownloadArchive.__init__(
132 self, path, keygen, table, pragma, cache_key, reuse)
133 self.keys = set()
134
135 def add(self, kwdict):
136 self.keys.add(
137 kwdict.get(self._cache_key) or
138 self.keygen(kwdict))
139
140 def check(self, kwdict):
141 key = kwdict[self._cache_key] = self.keygen(kwdict)
142 if key in self.keys:
143 return True
144 self.cursor.execute(self._stmt_select, (key,))
145 return self.cursor.fetchone()
146
147 def finalize(self):
148 if not self.keys:
149 return
150
151 cursor = self.cursor
152 with self.connection:
153 try:
154 cursor.execute("BEGIN")
155 except self._sqlite3.OperationalError:
156 pass
157
158 stmt = self._stmt_insert
159 if len(self.keys) < 100:
160 for key in self.keys:
161 cursor.execute(stmt, (key,))
162 else:
163 cursor.executemany(stmt, ((key,) for key in self.keys))
164
165
166 class DownloadArchivePostgresql():
167 _psycopg = None
168
169 def __init__(self, uri, keygen, table=None, pragma=None, cache_key=None,
170 reuse=False):
171 self.connection = con = self.connect(uri, reuse)
172 self.cursor = cursor = con.cursor()
173 self.close = util.noop if reuse else con.close
174 self.keygen = keygen
175 self._cache_key = cache_key or "_archive_key"
176
177 table = "archive" if table is None else sanitize(table)
178 self._stmt_select = (
179 f"SELECT true "
180 f"FROM {table} "
181 f"WHERE entry=%s "
182 f"LIMIT 1")
183 self._stmt_insert = (
184 f"INSERT INTO {table} (entry) "
185 f"VALUES (%s) "
186 f"ON CONFLICT DO NOTHING")
187
188 try:
189 cursor.execute(f"CREATE TABLE IF NOT EXISTS {table} "
190 f"(entry TEXT PRIMARY KEY)")
191 con.commit()
192 except Exception as exc:
193 log.error("%s: %s when creating '%s' table: %s",
194 con, exc.__class__.__name__, table, exc)
195 con.rollback()
196 raise
197
198 def connect(self, path, reuse=False):
199 if reuse and (con := CACHE_CONNECTIONS.get(path)):
200 return con
201
202 if self._psycopg is None:
203 DownloadArchivePostgresql._psycopg = __import__("psycopg")
204
205 con = self._psycopg.connect(path)
206 if reuse:
207 if not CACHE_CONNECTIONS:
208 import atexit
209 atexit.register(close_cached)
210 CACHE_CONNECTIONS[path] = con
211
212 return con
213
214 def add(self, kwdict):
215 key = kwdict.get(self._cache_key) or self.keygen(kwdict)
216 try:
217 self.cursor.execute(self._stmt_insert, (key,))
218 self.connection.commit()
219 except Exception as exc:
220 log.error("%s: %s when writing entry: %s",
221 self.connection, exc.__class__.__name__, exc)
222 self.connection.rollback()
223
224 def check(self, kwdict):
225 key = kwdict[self._cache_key] = self.keygen(kwdict)
226 try:
227 self.cursor.execute(self._stmt_select, (key,))
228 return self.cursor.fetchone()
229 except Exception as exc:
230 log.error("%s: %s when checking entry: %s",
231 self.connection, exc.__class__.__name__, exc)
232 self.connection.rollback()
233 return False
234
235 def finalize(self):
236 pass
237
238
239 class DownloadArchivePostgresqlMemory(DownloadArchivePostgresql):
240
241 def __init__(self, path, keygen, table=None, pragma=None, cache_key=None,
242 reuse=False):
243 DownloadArchivePostgresql.__init__(
244 self, path, keygen, table, pragma, cache_key, reuse)
245 self.keys = set()
246
247 def add(self, kwdict):
248 self.keys.add(
249 kwdict.get(self._cache_key) or
250 self.keygen(kwdict))
251
252 def check(self, kwdict):
253 key = kwdict[self._cache_key] = self.keygen(kwdict)
254 if key in self.keys:
255 return True
256 try:
257 self.cursor.execute(self._stmt_select, (key,))
258 return self.cursor.fetchone()
259 except Exception as exc:
260 log.error("%s: %s when checking entry: %s",
261 self.connection, exc.__class__.__name__, exc)
262 self.connection.rollback()
263 return False
264
265 def finalize(self):
266 if not self.keys:
267 return
268 try:
269 self.cursor.executemany(
270 self._stmt_insert,
271 ((key,) for key in self.keys))
272 self.connection.commit()
273 except Exception as exc:
274 log.error("%s: %s when writing entries: %s",
275 self.connection, exc.__class__.__name__, exc)
276 self.connection.rollback()