Debian Codegraph @

src/calibre/customize/zipplugin.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2011, Kovid Goyal <[email protected]>
3
4 import importlib
5 import os
6 import posixpath
7 import re
8 import sys
9 import threading
10 import zipfile
11 from collections import OrderedDict
12 from collections.abc import Iterable
13 from functools import lru_cache, partial
14 from importlib.abc import Loader
15 from importlib.machinery import ModuleSpec
16 from importlib.util import decode_source
17
18 from calibre import as_unicode
19 from calibre.customize import InvalidPlugin, Plugin, PluginNotFound, numeric_version, platform
20
21
22 def get_resources(zfp, name_or_list_of_names, print_tracebacks_for_missing_resources=True):
23 """
24 Load resources from the plugin zip file
25
26 :param name_or_list_of_names: List of paths to resources in the zip file using / as
27 separator, or a single path
28
29 :param print_tracebacks_for_missing_resources: When True missing resources are reported to STDERR
30
31 :return: A dictionary of the form ``{name : file_contents}``. Any names
32 that were not found in the zip file will not be present in the
33 dictionary. If a single path is passed in the return value will
34 be just the bytes of the resource or None if it wasn't found.
35 """
36 names = name_or_list_of_names
37 if isinstance(names, (str, bytes)):
38 names = [names]
39 ans = {}
40 with zipfile.ZipFile(zfp) as zf:
41 for name in names:
42 try:
43 ans[name] = zf.read(name)
44 except Exception:
45 if print_tracebacks_for_missing_resources:
46 print('Failed to load resource:', repr(name), 'from the plugin zip file:', zfp, file=sys.stderr)
47 import traceback
48
49 traceback.print_exc()
50 if len(names) == 1:
51 ans = ans.pop(names[0], None)
52
53 return ans
54
55
56 @lru_cache(maxsize=512)
57 def get_icons_cached(
58 zfp: str,
59 namelist: tuple[str, ...],
60 plugin_name: str = '',
61 folder_in_zip_file: str = '',
62 ):
63 from qt.core import QIcon
64
65 ans = {}
66 tracebacks = {}
67 with zipfile.ZipFile(zfp) as zf:
68 for name in namelist:
69 arcname = posixpath.join(folder_in_zip_file, name)
70 theme_name = posixpath.join(plugin_name, name)
71 try:
72 data = zf.read(arcname)
73 except KeyError:
74 import traceback
75
76 data = b''
77 tracebacks[name] = traceback.format_exc()
78 ans[name] = QIcon.ic(theme_name, fallback=data)
79 return ans, tracebacks
80
81
82 def get_icons(
83 zfp: str,
84 name_or_list_of_names: str | Iterable[str],
85 plugin_name: str = '',
86 folder_in_zip_file: str = '',
87 print_tracebacks_for_missing_resources: bool = True,
88 ):
89 """
90 Load icons from the plugin zip file
91
92 :param name_or_list_of_names: List of paths to resources in the zip file using / as
93 separator, or a single path
94
95 :param plugin_name: The human friendly name of the plugin, used to load icons from
96 the current theme, if present.
97
98 :param folder_in_zip_file: Path to a folder in the zip file from which to load the icons.
99 Default is the root of the zip file. Use / as separator.
100
101 :param print_tracebacks_for_missing_resources: When True missing resources are reported to STDERR
102
103 :return: A dictionary of the form ``{name : QIcon}``. Any names
104 that were not found in the zip file will be null QIcons.
105 If a single path is passed in the return value will
106 be a QIcon.
107 """
108 namelist = tuple((name_or_list_of_names,) if isinstance(name_or_list_of_names, (str, bytes)) else name_or_list_of_names)
109 ans, tracebacks = get_icons_cached(zfp, namelist, plugin_name or '', folder_in_zip_file or '')
110 if print_tracebacks_for_missing_resources:
111 for name, tb in tracebacks.items():
112 print('Failed to load resource:', repr(name), 'from the plugin zip file:', zfp, file=sys.stderr)
113 print(tb, file=sys.stderr)
114 if len(namelist) == 1:
115 return ans[namelist[0]]
116 return ans
117
118
119 _translations_cache = {}
120
121
122 def load_translations(namespace, zfp):
123 null = object()
124 trans = _translations_cache.get(zfp, null)
125 if trans is None:
126 return
127 if trans is null:
128 from calibre.utils.localization import get_lang
129
130 lang = get_lang()
131 if not lang or lang == 'en': # performance optimization
132 _translations_cache[zfp] = None
133 return
134 with zipfile.ZipFile(zfp) as zf:
135 mo_path = zipfile.Path(zf, f'translations/{lang}.mo')
136 if not mo_path.exists() and '_' in lang:
137 mo_path = zipfile.Path(zf, f"translations/{lang.split('_')[0]}.mo")
138 if mo_path.exists():
139 mo = mo_path.read_bytes()
140 else:
141 _translations_cache[zfp] = None
142 return
143
144 from gettext import GNUTranslations
145 from io import BytesIO
146
147 trans = _translations_cache[zfp] = GNUTranslations(BytesIO(mo))
148
149 namespace['_'] = trans.gettext
150 namespace['ngettext'] = trans.ngettext
151
152
153 class CalibrePluginLoader(Loader):
154 __slots__ = (
155 '_is_package',
156 'all_names',
157 'filename',
158 'fullname_in_plugin',
159 'names',
160 'plugin_name',
161 'zip_file_path',
162 )
163
164 def __init__(self, plugin_name, fullname_in_plugin, zip_file_path, names, filename, is_package, all_names):
165 self.plugin_name = plugin_name
166 self.fullname_in_plugin = fullname_in_plugin
167 self.zip_file_path = zip_file_path
168 self.names = names
169 self.filename = filename
170 self._is_package = is_package
171 self.all_names = all_names
172
173 def __eq__(self, other):
174 return self.__class__ == other.__class__ and self.plugin_name == other.plugin_name and self.fullname_in_plugin == other.fullname_in_plugin
175
176 def get_resource_reader(self, fullname=None):
177 return self
178
179 def __hash__(self):
180 return hash(self.__class__.__name__) ^ hash(self.plugin_name) ^ hash(self.fullname_in_plugin)
181
182 def create_module(self, spec):
183 pass
184
185 def is_package(self, fullname):
186 return self._is_package
187
188 def get_source_as_bytes(self, fullname=None):
189 src = b''
190 if self.plugin_name and self.fullname_in_plugin and self.zip_file_path:
191 zinfo = self.names.get(self.fullname_in_plugin)
192 if zinfo is not None:
193 with zipfile.ZipFile(self.zip_file_path) as zf:
194 try:
195 src = zf.read(zinfo)
196 except Exception:
197 # Maybe the zip file changed from under us
198 src = zf.read(zinfo.filename)
199 return src
200
201 def get_source(self, fullname=None):
202 raw = self.get_source_as_bytes(fullname)
203 return decode_source(raw)
204
205 def get_filename(self, fullname):
206 return self.filename
207
208 def get_code(self, fullname=None):
209 return compile(
210 self.get_source_as_bytes(fullname),
211 f'calibre_plugins.{self.plugin_name}.{self.fullname_in_plugin}',
212 'exec',
213 dont_inherit=True,
214 )
215
216 def exec_module(self, module):
217 compiled = self.get_code()
218 module.__file__ = self.filename
219 if self.zip_file_path:
220 zfp = self.zip_file_path
221 module.__dict__['get_resources'] = partial(get_resources, zfp)
222 module.__dict__['get_icons'] = partial(get_icons, zfp)
223 module.__dict__['load_translations'] = partial(load_translations, module.__dict__, zfp)
224 exec(compiled, module.__dict__)
225
226 def resource_path(self, name):
227 raise FileNotFoundError(f'{name} is not available as a filesystem path in calibre plugins')
228
229 def contents(self):
230 if not self._is_package:
231 return ()
232 zinfo = self.names.get(self.fullname_in_plugin)
233 if zinfo is None:
234 return ()
235 base = posixpath.dirname(zinfo.filename)
236 if base:
237 base += '/'
238
239 def is_ok(x):
240 if not base or x.startswith(base):
241 rest = x[len(base) :]
242 return '/' not in rest
243 return False
244
245 return tuple(filter(is_ok, self.all_names))
246
247 def is_resource(self, name):
248 zinfo = self.names.get(self.fullname_in_plugin)
249 if zinfo is None:
250 return False
251 base = posixpath.dirname(zinfo.filename)
252 q = posixpath.join(base, name)
253 return q in self.all_names
254
255 def open_resource(self, name):
256 zinfo = self.names.get(self.fullname_in_plugin)
257 if zinfo is None:
258 raise FileNotFoundError(f'{self.fullname_in_plugin} not in plugin zip file')
259 base = posixpath.dirname(zinfo.filename)
260 q = posixpath.join(base, name)
261 with zipfile.ZipFile(self.zip_file_path) as zf:
262 return zf.open(q)
263
264
265 class CalibrePluginFinder:
266 def __init__(self):
267 self.loaded_plugins = {}
268 self._lock = threading.RLock()
269 self._identifier_pat = re.compile(r'[a-zA-Z][_0-9a-zA-Z]*')
270
271 def find_spec(self, fullname, path, target=None):
272 if not fullname.startswith('calibre_plugins'):
273 return
274 parts = fullname.split('.')
275 if parts[0] != 'calibre_plugins':
276 return
277 plugin_name = zip_file_path = filename = None
278 fullname_in_plugin = ''
279 all_names = frozenset()
280 names = OrderedDict()
281
282 if len(parts) > 1:
283 plugin_name = parts[1]
284 with self._lock:
285 zip_file_path, names, all_names = self.loaded_plugins.get(plugin_name, (None, None, None))
286 if zip_file_path is None:
287 return
288 fullname_in_plugin = '.'.join(parts[2:])
289 if not fullname_in_plugin:
290 fullname_in_plugin = '__init__'
291 if fullname_in_plugin not in names:
292 if fullname_in_plugin + '.__init__' in names:
293 fullname_in_plugin += '.__init__'
294 else:
295 return
296 is_package = bool(fullname.count('.') < 2 or fullname_in_plugin == '__init__' or (fullname_in_plugin and fullname_in_plugin.endswith('.__init__')))
297 if zip_file_path:
298 filename = posixpath.join(zip_file_path, *fullname_in_plugin.split('.')) + '.py'
299
300 return ModuleSpec(
301 fullname,
302 CalibrePluginLoader(plugin_name, fullname_in_plugin, zip_file_path, names, filename, is_package, all_names),
303 is_package=is_package,
304 origin=filename,
305 )
306
307 def load(self, path_to_zip_file):
308 if not os.access(path_to_zip_file, os.R_OK):
309 raise PluginNotFound(f'Cannot access {path_to_zip_file!r}')
310
311 with zipfile.ZipFile(path_to_zip_file) as zf:
312 plugin_name = self._locate_code(zf, path_to_zip_file)
313
314 try:
315 ans = None
316 plugin_module = f'calibre_plugins.{plugin_name}'
317 m = sys.modules.get(plugin_module, None)
318 if m is not None:
319 importlib.reload(m)
320 else:
321 m = importlib.import_module(plugin_module)
322 plugin_classes = []
323 for obj in m.__dict__.values():
324 if isinstance(obj, type) and issubclass(obj, Plugin) and obj.name != 'Trivial Plugin':
325 plugin_classes.append(obj)
326 if not plugin_classes:
327 raise InvalidPlugin(f'No plugin class found in {as_unicode(path_to_zip_file)}:{plugin_name}')
328 if len(plugin_classes) > 1:
329 plugin_classes.sort(key=lambda c: (getattr(c, '__module__', None) or '').count('.'))
330
331 ans = plugin_classes[0]
332
333 if ans.minimum_calibre_version > numeric_version:
334 raise InvalidPlugin(
335 'The plugin at {} needs a version of calibre >= {}'.format(as_unicode(path_to_zip_file), '.'.join(map(str, ans.minimum_calibre_version)))
336 )
337
338 if platform not in ans.supported_platforms:
339 raise InvalidPlugin(f'The plugin at {as_unicode(path_to_zip_file)} cannot be used on {platform}')
340
341 return ans
342 except Exception:
343 with self._lock:
344 del self.loaded_plugins[plugin_name]
345 raise
346
347 def _locate_code(self, zf, path_to_zip_file):
348 all_names = frozenset(zf.namelist())
349 names = [x[1:] if x[0] == '/' else x for x in all_names]
350
351 plugin_name = None
352 for name in names:
353 name, ext = posixpath.splitext(name)
354 if name.startswith('plugin-import-name-') and ext == '.txt':
355 plugin_name = name.rpartition('-')[-1]
356
357 if plugin_name is None:
358 c = 0
359 while True:
360 c += 1
361 plugin_name = f'dummy{c}'
362 if plugin_name not in self.loaded_plugins:
363 break
364 elif self._identifier_pat.match(plugin_name) is None:
365 raise InvalidPlugin(f'The plugin at {path_to_zip_file!r} uses an invalid import name: {plugin_name!r}')
366
367 pynames = [x for x in names if x.endswith('.py')]
368
369 candidates = [posixpath.dirname(x) for x in pynames if x.endswith('/__init__.py')]
370 candidates.sort(key=lambda x: x.count('/'))
371 valid_packages = set()
372
373 for candidate in candidates:
374 parts = candidate.split('/')
375 parent = '.'.join(parts[:-1])
376 if parent and parent not in valid_packages:
377 continue
378 valid_packages.add('.'.join(parts))
379
380 names = OrderedDict()
381
382 for candidate in pynames:
383 parts = posixpath.splitext(candidate)[0].split('/')
384 package = '.'.join(parts[:-1])
385 if package and package not in valid_packages:
386 continue
387 name = '.'.join(parts)
388 names[name] = zf.getinfo(candidate)
389
390 # Legacy plugins
391 if '__init__' not in names:
392 for name in tuple(names):
393 if '.' not in name and name.endswith('plugin'):
394 names['__init__'] = names[name]
395 break
396
397 if '__init__' not in names:
398 raise InvalidPlugin(f'The plugin in {path_to_zip_file!r} is invalid. It does not contain a top-level __init__.py file')
399
400 with self._lock:
401 self.loaded_plugins[plugin_name] = path_to_zip_file, names, tuple(all_names)
402
403 return plugin_name
404
405
406 loader = CalibrePluginFinder()
407 sys.meta_path.append(loader)
408
409 if __name__ == '__main__':
410 from tempfile import NamedTemporaryFile
411
412 from calibre import CurrentDir
413 from calibre.customize.ui import add_plugin
414
415 path = sys.argv[-1]
416 with NamedTemporaryFile(suffix='.zip') as f:
417 with zipfile.ZipFile(f, 'w') as zf:
418 with CurrentDir(path):
419 for x in os.listdir('.'):
420 if x[0] != '.':
421 print('Adding', x)
422 zf.write(x)
423 if os.path.isdir(x):
424 for y in os.listdir(x):
425 zf.write(os.path.join(x, y))
426 add_plugin(f.name)
427 print('Added plugin from', sys.argv[-1])