Debian Codegraph @

setup/plugins_mirror.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net>
3
4 # Imports {{{
5 import argparse
6 import ast
7 import atexit
8 import bz2
9 import errno
10 import glob
11 import gzip
12 import io
13 import json
14 import os
15 import random
16 import re
17 import socket
18 import stat
19 import subprocess
20 import sys
21 import tempfile
22 import time
23 import zipfile
24 import zlib
25 from collections import namedtuple
26 from contextlib import closing
27 from datetime import datetime
28 from email.utils import parsedate
29 from functools import partial
30 from multiprocessing.pool import ThreadPool
31 from xml.sax.saxutils import escape, quoteattr
32
33 try:
34 from html import unescape as u
35 except ImportError:
36 from HTMLParser import HTMLParser
37
38 u = HTMLParser().unescape
39
40 try:
41 from urllib.parse import parse_qs, urlparse
42 except ImportError:
43 from urlparse import parse_qs, urlparse
44
45
46 try:
47 from urllib.error import URLError
48 from urllib.request import Request, build_opener, urlopen
49 except Exception:
50 from urllib2 import Request, URLError, build_opener, urlopen
51 # }}}
52
53 USER_AGENT = 'calibre mirror'
54 MR_URL = 'https://www.mobileread.com/forums/'
55 IS_PRODUCTION = os.path.exists('/srv/plugins')
56 PLUGINS = 'plugins.json.bz2'
57 INDEX = MR_URL + 'showpost.php?p=1362767&postcount=1'
58 # INDEX = 'file:///t/raw.html'
59
60 IndexEntry = namedtuple('IndexEntry', 'name url donate history uninstall deprecated thread_id category')
61 socket.setdefaulttimeout(30)
62
63
64 def read(url, get_info=False): # {{{
65 if url.startswith('file://'):
66 return urlopen(url).read()
67 opener = build_opener()
68 opener.addheaders = [
69 ('User-Agent', USER_AGENT),
70 ('Accept-Encoding', 'gzip,deflate'),
71 ]
72 # Sporadic network failures in rackspace, so retry with random sleeps
73 for i in range(10):
74 try:
75 res = opener.open(url)
76 break
77 except URLError as e:
78 if not isinstance(e.reason, socket.timeout) or i == 9:
79 raise
80 time.sleep(random.randint(10, 45))
81 info = res.info()
82 encoding = info.get('Content-Encoding')
83 raw = res.read()
84 res.close()
85 if encoding and encoding.lower() in {'gzip', 'x-gzip', 'deflate'}:
86 if encoding.lower() == 'deflate':
87 raw = zlib.decompress(raw)
88 else:
89 raw = gzip.GzipFile(fileobj=io.BytesIO(raw)).read()
90 if get_info:
91 return raw, info
92 return raw
93
94
95 # }}}
96
97
98 def url_to_plugin_id(url, deprecated):
99 query = parse_qs(urlparse(url).query)
100 ans = (query['t'] if 't' in query else query['p'])[0]
101 if deprecated:
102 ans += '-deprecated'
103 return ans
104
105
106 def decode_html(raw_bytes, info=None):
107 charset = 'cp1252'
108 if info is not None:
109 try:
110 content_type = info.get('Content-Type', '')
111 if 'charset=' in content_type:
112 charset = content_type.split('charset=')[-1].strip()
113 except Exception:
114 pass
115 c = charset.lower().replace('_', '-').replace(' ', '')
116 if c in ('iso-8859-1', 'latin-1', 'latin1', 'iso8859-1', 'iso_8859-1'):
117 charset = 'cp1252'
118 try:
119 return raw_bytes.decode(charset, 'replace')
120 except Exception:
121 return raw_bytes.decode('cp1252', 'replace')
122
123
124 def parse_index(raw=None): # {{{
125 if raw is None:
126 res = read(INDEX, get_info=True)
127 if isinstance(res, tuple):
128 raw_bytes, info = res
129 raw = decode_html(raw_bytes, info)
130 else:
131 raw = decode_html(res)
132
133 dpat = re.compile(r'''(?is)Donate\s*:\s*<a\s+href=['"](.+?)['"]''')
134 key_pat = re.compile(r'''(?is)(History|Uninstall)\s*:\s*([^<;]+)[<;]''')
135 seen = {}
136 dep_start = -1
137 category_offsets = []
138 deprecated_category = 'Deprecated/Renamed/Retired'
139 for match in re.finditer(r'''<b>\s*(.+?)\s*Plugins:?\s*</b>''', raw):
140 category = match.group(1).strip()
141 category_offsets.append((category, match.start()))
142 if category == deprecated_category:
143 dep_start = match.start()
144 if dep_start < 1:
145 raise ValueError('Could not find start of deprecated plugins')
146 category_offsets = tuple(reversed(category_offsets))
147
148 def category_at(offset):
149 for category, q in category_offsets:
150 if offset >= q:
151 return category
152 raise ValueError('Could not find category for offset: ' + str(offset))
153
154 for match in re.finditer(r'''(?is)<li.+?<a\s+href=['"](https://www\.mobileread\.com/forums/showthread\.php\?[pt]=\d+).+?>(.+?)<(.+?)</li>''', raw):
155 name, url, rest = u(match.group(2)), u(match.group(1)), match.group(3)
156 category = category_at(match.start(2))
157 deprecated = category == deprecated_category
158 donate = uninstall = None
159 history = False
160 m = dpat.search(rest)
161 if m is not None:
162 donate = u(m.group(1))
163 for m in key_pat.finditer(rest):
164 k = m.group(1).lower()
165 if k == 'history' and m.group(2).strip().lower() in {'yes', 'true'}:
166 history = True
167 elif k == 'uninstall':
168 uninstall = tuple(x.strip() for x in m.group(2).strip().split(','))
169
170 thread_id = url_to_plugin_id(url, deprecated)
171 if thread_id in seen:
172 raise ValueError(f'thread_id for {seen[thread_id]} and {name} is the same: {thread_id}')
173 seen[thread_id] = name
174 entry = IndexEntry(name, url, donate, history, uninstall, deprecated, thread_id, category)
175 yield entry
176
177
178 # }}}
179
180
181 def parse_plugin_zip_url(raw):
182 for m in re.finditer(r'''(?is)<a\s+href=['"](attachment.php\?[^'"]+?)['"][^>]*>([^<>]+?\.zip)\s*<''', raw):
183 url, name = u(m.group(1)), u(m.group(2).strip())
184 if name.lower().endswith('.zip'):
185 return MR_URL + url, name
186 return None, None
187
188
189 def load_plugins_index():
190 try:
191 with open(PLUGINS, 'rb') as f:
192 raw = f.read()
193 except OSError as err:
194 if err.errno == errno.ENOENT:
195 return {}
196 raise
197 return json.loads(bz2.decompress(raw))
198
199
200 # Get metadata from plugin zip file {{{
201
202
203 def convert_node(fields, x, names={}, import_data=None):
204 name = x.__class__.__name__
205
206 def conv(x):
207 return convert_node(fields, x, names=names, import_data=import_data)
208
209 if name == 'Str':
210 return x.s.decode('utf-8') if isinstance(x.s, bytes) else x.s
211 elif name == 'Num':
212 return x.n
213 elif name == 'Constant':
214 return x.value
215 elif name in {'Set', 'List', 'Tuple'}:
216 func = {'Set': set, 'List': list, 'Tuple': tuple}[name]
217 return func(list(map(conv, x.elts)))
218 elif name == 'Dict':
219 keys, values = list(map(conv, x.keys)), list(map(conv, x.values))
220 return dict(zip(keys, values))
221 elif name == 'Call':
222 if len(x.args) != 1 and len(x.keywords) != 0:
223 raise TypeError(f'Unsupported function call for fields: {fields}')
224 return tuple(map(conv, x.args))[0]
225 elif name == 'Name':
226 if x.id not in names:
227 if import_data is not None and x.id in import_data[0]:
228 return get_import_data(x.id, import_data[0][x.id], *import_data[1:])
229 raise ValueError(f'Could not find name {x.id} for fields: {fields}')
230 return names[x.id]
231 elif name == 'BinOp':
232 if x.right.__class__.__name__ == 'Str':
233 return x.right.s.decode('utf-8') if isinstance(x.right.s, bytes) else x.right.s
234 if x.right.__class__.__name__ == 'Constant' and isinstance(x.right.value, str):
235 return x.right.value
236 elif name == 'Attribute':
237 return conv(getattr(conv(x.value), x.attr))
238 raise TypeError(f'Unknown datatype {x} for fields: {fields}')
239
240
241 Alias = namedtuple('Alias', 'name asname')
242
243
244 class Module:
245 pass
246
247
248 def get_import_data(name, mod, zf, names):
249 mod = mod.split('.')
250 if mod[0] == 'calibre_plugins':
251 mod = mod[2:]
252 is_module_import = not mod
253 if is_module_import:
254 mod = [name]
255 mod = '/'.join(mod) + '.py'
256 if mod in names:
257 raw = zf.open(names[mod]).read()
258 module = ast.parse(raw, filename='__init__.py')
259 top_level_assigments = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'Assign']
260 module = Module()
261 for node in top_level_assigments:
262 targets = {getattr(t, 'id', None) for t in node.targets}
263 targets.discard(None)
264 for x in targets:
265 if is_module_import:
266 setattr(module, x, node.value)
267 elif x == name:
268 return convert_node({x}, node.value)
269 if is_module_import:
270 return module
271 raise ValueError(f'Failed to find name: {name!r} in module: {mod!r}')
272 else:
273 raise ValueError(f'Failed to find module: {mod!r}')
274
275
276 def parse_metadata(raw, namelist, zf):
277 module = ast.parse(raw, filename='__init__.py')
278 top_level_imports = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'ImportFrom']
279 top_level_classes = tuple(x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'ClassDef')
280 top_level_assigments = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'Assign']
281 defaults = {
282 'name': '',
283 'description': '',
284 'supported_platforms': ['windows', 'osx', 'linux'],
285 'version': (1, 0, 0),
286 'author': 'Unknown',
287 'minimum_calibre_version': (0, 9, 42),
288 }
289 field_names = set(defaults)
290 imported_names = {}
291
292 plugin_import_found = set()
293 all_imports = []
294 for node in top_level_imports:
295 names = getattr(node, 'names', [])
296 mod = getattr(node, 'module', None)
297 if names and mod:
298 names = [Alias(n.name, getattr(n, 'asname', None)) for n in names]
299 if (
300 mod
301 in {
302 'calibre.customize',
303 'calibre.customize.conversion',
304 'calibre.ebooks.metadata.sources.base',
305 'calibre.ebooks.metadata.sources.amazon',
306 'calibre.ebooks.metadata.covers',
307 'calibre.devices.interface',
308 'calibre.ebooks.metadata.fetch',
309 'calibre.customize.builtins',
310 }
311 or re.match(r'calibre\.devices\.[a-z0-9]+\.driver', mod) is not None
312 ):
313 inames = {n.asname or n.name for n in names}
314 inames = {x for x in inames if x.lower() != x}
315 plugin_import_found |= inames
316 else:
317 all_imports.append((mod, [n.name for n in names]))
318 for alias in names:
319 imported_names[alias.asname or alias.name] = mod
320 if not plugin_import_found:
321 return all_imports
322
323 import_data = (imported_names, zf, namelist)
324
325 names = {}
326 top_level_ann_assigments = [x for x in ast.iter_child_nodes(module) if x.__class__.__name__ == 'AnnAssign']
327 for node in top_level_assigments:
328 targets = {getattr(t, 'id', None) for t in node.targets}
329 targets.discard(None)
330 for x in targets - field_names:
331 try:
332 val = convert_node({x}, node.value, import_data=import_data)
333 except Exception:
334 pass
335 else:
336 names[x] = val
337 for node in top_level_ann_assigments:
338 if node.value is None:
339 continue
340 x = getattr(node.target, 'id', None)
341 if x is None or x in field_names:
342 continue
343 try:
344 val = convert_node({x}, node.value, import_data=import_data)
345 except Exception:
346 pass
347 else:
348 names[x] = val
349
350 def parse_class(node):
351 class_assigments = [x for x in ast.iter_child_nodes(node) if x.__class__.__name__ == 'Assign']
352 class_ann_assigments = [x for x in ast.iter_child_nodes(node) if x.__class__.__name__ == 'AnnAssign']
353 found = {}
354 for node in class_assigments:
355 targets = {getattr(t, 'id', None) for t in node.targets}
356 targets.discard(None)
357 fields = field_names.intersection(targets)
358 if fields:
359 val = convert_node(fields, node.value, names=names, import_data=import_data)
360 for field in fields:
361 found[field] = val
362 for node in class_ann_assigments:
363 if node.value is None:
364 continue
365 target_id = getattr(node.target, 'id', None)
366 if target_id is None:
367 continue
368 fields = field_names.intersection({target_id})
369 if fields:
370 val = convert_node(fields, node.value, names=names, import_data=import_data)
371 for field in fields:
372 found[field] = val
373 return found
374
375 if top_level_classes:
376 for node in top_level_classes:
377 bases = {getattr(x, 'id', None) for x in node.bases}
378 if not bases.intersection(plugin_import_found):
379 continue
380 found = parse_class(node)
381 if 'name' in found and 'author' in found:
382 defaults.update(found)
383 return defaults
384 for node in top_level_classes:
385 found = parse_class(node)
386 if 'name' in found and 'author' in found and 'version' in found:
387 defaults.update(found)
388 return defaults
389
390 raise ValueError('Could not find plugin class')
391
392
393 def parse_plugin(raw, names, zf):
394 ans = parse_metadata(raw, names, zf)
395 if isinstance(ans, dict):
396 return ans
397 # The plugin is importing its base class from somewhere else, le sigh
398 for mod, _ in ans:
399 mod = mod.split('.')
400 if mod[0] == 'calibre_plugins':
401 mod = mod[2:]
402 mod = '/'.join(mod) + '.py'
403 if mod in names:
404 raw = zf.open(names[mod]).read()
405 ans = parse_metadata(raw, names, zf)
406 if isinstance(ans, dict):
407 return ans
408
409 raise ValueError('Failed to find plugin class')
410
411
412 def get_plugin_init(zf):
413 metadata = None
414 names = {x.decode('utf-8') if isinstance(x, bytes) else x: x for x in zf.namelist()}
415 inits = [x for x in names if x.rpartition('/')[-1] == '__init__.py']
416 inits.sort(key=lambda x: x.count('/'))
417 if inits and inits[0] == '__init__.py':
418 metadata = names[inits[0]]
419 else:
420 # Legacy plugin
421 for name, val in names.items():
422 if name.endswith('plugin.py'):
423 metadata = val
424 break
425 if metadata is None:
426 raise ValueError('No __init__.py found in plugin')
427 return zf.open(metadata).read(), names
428
429
430 def get_plugin_info(raw_zip):
431 with zipfile.ZipFile(io.BytesIO(raw_zip)) as zf:
432 raw, names = get_plugin_init(zf)
433 try:
434 return parse_plugin(raw, names, zf)
435 except (SyntaxError, TabError, IndentationError): # fmt: skip
436 with tempfile.NamedTemporaryFile(suffix='.zip') as f:
437 f.write(raw_zip)
438 f.flush()
439 res = subprocess.run(['python2', __file__, f.name], stdout=subprocess.PIPE)
440 if res.returncode == 0:
441 return json.loads(res.stdout)
442 raise
443
444
445 # }}}
446
447
448 def update_plugin_from_entry(plugin, entry):
449 plugin['index_name'] = entry.name
450 plugin['thread_url'] = entry.url
451 plugin['category'] = entry.category
452 for x in ('donate', 'history', 'deprecated', 'uninstall', 'thread_id'):
453 plugin[x] = getattr(entry, x)
454
455
456 def fetch_plugin(old_index, entry):
457 lm_map = {plugin['thread_id']: plugin for plugin in old_index.values()}
458 res = read(entry.url, get_info=True)
459 raw = decode_html(*res)
460 url, name = parse_plugin_zip_url(raw)
461 if url is None:
462 raise ValueError(f'Failed to find zip file URL for entry: {entry!r}')
463 plugin = lm_map.get(entry.thread_id, None)
464
465 if plugin is not None:
466 # Previously downloaded plugin
467 lm = datetime(*tuple(map(int, re.split(r'\D', plugin['last_modified'])))[:6])
468 request = Request(url)
469 request.get_method = lambda: 'HEAD'
470 with closing(urlopen(request)) as response:
471 info = response.info()
472 slm = datetime(*parsedate(info.get('Last-Modified'))[:6])
473 if lm >= slm:
474 # The previously downloaded plugin zip file is up-to-date
475 update_plugin_from_entry(plugin, entry)
476 return plugin
477
478 raw, info = read(url, get_info=True)
479 slm = datetime(*parsedate(info.get('Last-Modified'))[:6])
480 plugin = get_plugin_info(raw)
481 plugin['last_modified'] = slm.isoformat()
482 plugin['file'] = f'staging_{entry.thread_id}.zip'
483 plugin['size'] = len(raw)
484 plugin['original_url'] = url
485 update_plugin_from_entry(plugin, entry)
486 with open(plugin['file'], 'wb') as f:
487 f.write(raw)
488 return plugin
489
490
491 def parallel_fetch(old_index, entry):
492 try:
493 return fetch_plugin(old_index, entry)
494 except Exception:
495 import traceback
496
497 return traceback.format_exc()
498
499
500 def log(*args, **kwargs):
501 print(*args, **kwargs)
502 with open('log', 'a') as f:
503 kwargs['file'] = f
504 print(*args, **kwargs)
505
506
507 def atomic_write(raw, name):
508 with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
509 f.write(raw)
510 os.fchmod(f.fileno(), stat.S_IREAD | stat.S_IWRITE | stat.S_IRGRP | stat.S_IROTH)
511 os.rename(f.name, name)
512
513
514 def fetch_plugins(old_index, thread_id=None):
515 all_entries = tuple(parse_index())
516 if not all_entries:
517 raise SystemExit('Could not find any plugins, probably the markup on the MR index page has changed')
518 if thread_id is not None:
519 entries = tuple(e for e in all_entries if e.thread_id == thread_id)
520 if not entries:
521 raise SystemExit(f'No plugin with thread_id {thread_id!r} found in the MR index')
522 ans = dict(old_index)
523 else:
524 entries = all_entries
525 ans = {}
526 pool = ThreadPool(processes=min(10, len(entries)))
527 with closing(pool):
528 result = pool.map(partial(parallel_fetch, old_index), entries)
529 for entry, plugin in zip(entries, result):
530 if isinstance(plugin, dict):
531 ans[entry.name] = plugin
532 else:
533 if entry.name in old_index:
534 ans[entry.name] = old_index[entry.name]
535 log('Failed to get plugin', entry.name, 'at', datetime.now().isoformat(), 'with error:')
536 log(plugin)
537 # Move staged files
538 for plugin in ans.values():
539 if plugin['file'].startswith('staging_'):
540 src = plugin['file']
541 plugin['file'] = src.partition('_')[-1]
542 os.rename(src, plugin['file'])
543 raw = bz2.compress(json.dumps(ans, sort_keys=True, indent=4, separators=(',', ': ')).encode('utf-8'))
544 atomic_write(raw, PLUGINS)
545 if thread_id is None:
546 # Cleanup any extra .zip files only on full sync
547 all_plugin_files = {p['file'] for p in ans.values()}
548 extra = set(glob.glob('*.zip')) - all_plugin_files
549 for x in extra:
550 os.unlink(x)
551 return ans
552
553
554 def plugin_to_index(plugin, count):
555 title = '<h3><img src="plugin-icon.png"><a href={} title="Plugin forum thread">{}</a></h3>'.format(quoteattr(plugin['thread_url']), escape(plugin['name']))
556 released = datetime(*tuple(map(int, re.split(r'\D', plugin['last_modified'])))[:6]).strftime('%e %b, %Y').lstrip()
557 details = [
558 'Version: <b>{}</b>'.format(escape('.'.join(map(str, plugin['version'])))),
559 f'Released: <b>{escape(released)}</b>',
560 'Author: {}'.format(escape(plugin['author'])),
561 'calibre: {}'.format(escape('.'.join(map(str, plugin['minimum_calibre_version'])))),
562 'Platforms: {}'.format(escape(', '.join(sorted(plugin['supported_platforms']) or ['all']))),
563 ]
564 if plugin['uninstall']:
565 details.append('Uninstall: {}'.format(escape(', '.join(plugin['uninstall']))))
566 if plugin['donate']:
567 details.append('<a href={} title="Donate">Donate</a>'.format(quoteattr(plugin['donate'])))
568 block = []
569 for li in details:
570 if li.startswith('calibre:'):
571 block.append('<br>')
572 block.append(f'<li>{li}</li>')
573 block = '<ul>{}</ul>'.format('\n'.join(block))
574 downloads = (f'\xa0<span class="download-count">[{count} total downloads]</span>') if count else ''
575 zipfile = '<div class="end"><a href={} title="Download plugin" download={}>Download plugin \u2193</a>{}</div>'.format(
576 quoteattr(plugin['file']), quoteattr(plugin['name'] + '.zip'), downloads
577 )
578 desc = plugin['description'] or ''
579 if desc:
580 desc = f'<p>{desc}</p>'
581 return f'{title}\n{desc}\n{block}\n{zipfile}\n\n'
582
583
584 def create_index(index, raw_stats):
585 plugins = []
586 stats = {}
587 for name in sorted(index):
588 plugin = index[name]
589 if not plugin['deprecated']:
590 count = raw_stats.get(plugin['file'].rpartition('.')[0], 0)
591 if count > 0:
592 stats[plugin['name']] = count
593 plugins.append(plugin_to_index(plugin, count))
594 index = '''\
595 <!DOCTYPE html>
596 <html>
597 <head><meta charset="utf-8"><title>Index of calibre plugins</title>
598 <link rel="icon" type="image/x-icon" href="//calibre-ebook.com/favicon.ico" />
599 <style type="text/css">
600 body { background-color: #eee; }
601 a { text-decoration: none }
602 a:hover, h3:hover { color: red }
603 a:visited { color: blue }
604 ul { list-style-type: none; font-size: smaller }
605 li { display: inline }
606 li+li:before { content: " - " }
607 .end { border-bottom: solid 1pt black; padding-bottom: 0.5ex; margin-bottom: 4ex; }
608 h1 img, h3 img { vertical-align: middle; margin-right: 0.5em; }
609 h1 { text-align: center }
610 .download-count { color: gray; font-size: smaller }
611 </style>
612 </head>
613 <body>
614 <h1><img src="//manual.calibre-ebook.com/_static/logo.png">Index of calibre plugins</h1>
615 <div style="text-align:center"><a href="stats.html">Download counts for all plugins</a></div>
616 %s
617 </body>
618 </html>''' % ('\n'.join(plugins)) # noqa: UP031
619 raw = index.encode('utf-8')
620 try:
621 with open('index.html', 'rb') as f:
622 oraw = f.read()
623 except OSError:
624 oraw = None
625 if raw != oraw:
626 atomic_write(raw, 'index.html')
627
628 def plugin_stats(x):
629 name, count = x
630 return f'<tr><td>{escape(name)}</td><td>{count}</td></tr>\n'
631
632 pstats = list(map(plugin_stats, sorted(stats.items(), reverse=True, key=lambda x: x[1])))
633 stats = '''\
634 <!DOCTYPE html>
635 <html>
636 <head><meta charset="utf-8"><title>Stats for calibre plugins</title>
637 <link rel="icon" type="image/x-icon" href="//calibre-ebook.com/favicon.ico" />
638 <style type="text/css">
639 body { background-color: #eee; }
640 h1 img, h3 img { vertical-align: middle; margin-right: 0.5em; }
641 h1 { text-align: center }
642 </style>
643 </head>
644 <body>
645 <h1><img src="//manual.calibre-ebook.com/_static/logo.png">Stats for calibre plugins</h1>
646 <table>
647 <tr><th>Plugin</th><th>Total downloads</th></tr>
648 %s
649 </table>
650 </body>
651 </html>
652 ''' % ('\n'.join(pstats)) # noqa: UP031
653 raw = stats.encode('utf-8')
654 try:
655 with open('stats.html', 'rb') as f:
656 oraw = f.read()
657 except OSError:
658 oraw = None
659 if raw != oraw:
660 atomic_write(raw, 'stats.html')
661
662
663 _singleinstance = None
664
665
666 def singleinstance():
667 global _singleinstance
668 s = _singleinstance = socket.socket(socket.AF_UNIX)
669 try:
670 s.bind(b'\0calibre-plugins-mirror-singleinstance')
671 except OSError as err:
672 if getattr(err, 'errno', None) == errno.EADDRINUSE:
673 return False
674 raise
675 return True
676
677
678 def update_stats():
679 log = olog = 'stats.log'
680 if not os.path.exists(log):
681 return {}
682 stats = {}
683 if IS_PRODUCTION:
684 try:
685 with open('stats.json', 'rb') as f:
686 stats = json.load(f)
687 except OSError as err:
688 if err.errno != errno.ENOENT:
689 raise
690 if os.geteuid() != 0:
691 return stats
692 log = 'rotated-' + log
693 os.rename(olog, log)
694 subprocess.check_call(['/usr/sbin/nginx', '-s', 'reopen'])
695 atexit.register(os.remove, log)
696 pat = re.compile(rb'GET /(\d+)(?:-deprecated){0,1}\.zip')
697 for line in open(log, 'rb'):
698 m = pat.search(line)
699 if m is not None:
700 plugin = m.group(1).decode('utf-8')
701 stats[plugin] = stats.get(plugin, 0) + 1
702 data = json.dumps(stats, indent=2)
703 if not isinstance(data, bytes):
704 data = data.encode('utf-8')
705 with open('stats.json', 'wb') as f:
706 f.write(data)
707 return stats
708
709
710 def parse_single_plugin(zipfile_path):
711 with zipfile.ZipFile(zipfile_path) as zf:
712 raw, names = get_plugin_init(zf)
713 ans = parse_plugin(raw, names, zf)
714 sys.stdout.write(json.dumps(ans, ensure_ascii=True))
715
716
717 def main():
718 p = argparse.ArgumentParser(description='Mirror calibre plugins from the forums. Or parse a single plugin zip file if specified on the command line')
719 p.add_argument('plugin_path', nargs='?', default='', help='Path to plugin zip file to parse')
720 WORKDIR = '/srv/plugins' if IS_PRODUCTION else '/t/plugins'
721 p.add_argument('-o', '--output-dir', default=WORKDIR, help='Where to place the mirrored plugins. Default is: ' + WORKDIR)
722 p.add_argument('--thread-id', default=None, help='Only download/update the plugin with this thread ID (e.g. 1234 or 1234-deprecated)')
723 args = p.parse_args()
724 if args.plugin_path:
725 return parse_single_plugin(args.plugin_path)
726
727 os.makedirs(args.output_dir, exist_ok=True)
728 os.chdir(args.output_dir)
729 if os.geteuid() == 0 and not singleinstance():
730 print('Another instance of plugins-mirror is running', file=sys.stderr)
731 raise SystemExit(1)
732 open('log', 'w').close()
733 stats = update_stats()
734 try:
735 plugins_index = load_plugins_index()
736 plugins_index = fetch_plugins(plugins_index, thread_id=args.thread_id)
737 create_index(plugins_index, stats)
738 except KeyboardInterrupt:
739 raise SystemExit('Exiting on user interrupt')
740 except Exception:
741 import traceback
742
743 log('Failed to run at:', datetime.now().isoformat())
744 log(traceback.format_exc())
745 raise SystemExit(1)
746
747
748 # }}}
749
750
751 def test_parse_metadata(): # {{{
752 raw = b'''\
753 import os
754 from calibre.customize import FileTypePlugin
755 # import_placeholder
756
757 MV = (0, 7, 53)
758
759 class HelloWorld(FileTypePlugin):
760
761 name: str = _('name') # Name of the plugin
762 description = {1, 2}
763 supported_platforms = ['windows', 'osx', 'linux'] # Platforms this plugin will run on
764 author = 'Acme Inc.' # The author of this plugin
765 version: dict[str, int] = {1:'a', 'b':2}
766 file_types = set(['epub', 'mobi']) # The file types that this plugin will be applied to
767 on_postprocess = True # Run this plugin after conversion is complete
768 minimum_calibre_version = MV
769 '''
770 vals = {
771 'name': 'name',
772 'description': {1, 2},
773 'supported_platforms': ['windows', 'osx', 'linux'],
774 'author': 'Acme Inc.',
775 'version': {1: 'a', 'b': 2},
776 'minimum_calibre_version': (0, 7, 53),
777 }
778 assert parse_metadata(raw, None, None) == vals
779 buf = io.BytesIO()
780 with zipfile.ZipFile(buf, 'w') as zf:
781 zf.writestr('very/lovely.py', raw.replace(b'MV = (0, 7, 53)', b'from very.ver import MV'))
782 zf.writestr('very/ver.py', b'MV = (0, 7, 53)')
783 zf.writestr('__init__.py', b'from xxx import yyy\nfrom very.lovely import HelloWorld')
784 assert get_plugin_info(buf.getvalue()) == vals
785 buf = io.BytesIO()
786 with zipfile.ZipFile(buf, 'w') as zf:
787 zf.writestr('very/ver.py', b'NAME = "name"\nVERSION = (1,2,3)')
788 zf.writestr(
789 '__init__.py',
790 raw.replace(b"_('name')", b'NAME').replace(b"{1:'a', 'b':2}", b'VERSION').replace(b'# import_placeholder', b'from very.ver import NAME, VERSION'),
791 )
792 vals['version'] = (1, 2, 3)
793 assert get_plugin_info(buf.getvalue()) == vals
794
795 # Test: annotated top-level variable used as class attribute value
796 raw2 = b'''\
797 from calibre.customize import FileTypePlugin
798
799 MV: tuple = (0, 8, 0)
800
801 class MyPlugin(FileTypePlugin):
802 name: str = 'TestPlugin'
803 author: str = 'Test Author'
804 version = MV
805 minimum_calibre_version = MV
806 description = 'A test plugin'
807 supported_platforms = ['linux']
808 '''
809 vals2 = {
810 'name': 'TestPlugin',
811 'description': 'A test plugin',
812 'supported_platforms': ['linux'],
813 'author': 'Test Author',
814 'version': (0, 8, 0),
815 'minimum_calibre_version': (0, 8, 0),
816 }
817 assert parse_metadata(raw2, None, None) == vals2
818
819 # Test: annotation without value (bare annotation) is ignored gracefully
820 raw3 = b'''\
821 from calibre.customize import FileTypePlugin
822
823 class MyPlugin(FileTypePlugin):
824 name: str = 'BareAnnot'
825 author: str = 'Some Author'
826 description: str
827 version = (2, 0, 0)
828 minimum_calibre_version = (1, 0, 0)
829 supported_platforms: list = ['windows', 'linux']
830 '''
831 vals3 = {
832 'name': 'BareAnnot',
833 'description': '',
834 'supported_platforms': ['windows', 'linux'],
835 'author': 'Some Author',
836 'version': (2, 0, 0),
837 'minimum_calibre_version': (1, 0, 0),
838 }
839 assert parse_metadata(raw3, None, None) == vals3
840
841 # Test: multiple classes, only the one inheriting from a plugin base is used
842 raw4 = b'''\
843 from calibre.customize import FileTypePlugin
844
845 class Helper:
846 name = 'should-be-ignored'
847 author = 'ignored'
848
849 class RealPlugin(FileTypePlugin):
850 name = 'RealPlugin'
851 author = 'Real Author'
852 version = (3, 1, 4)
853 minimum_calibre_version = (0, 9, 42)
854 supported_platforms = ['windows', 'osx', 'linux']
855 description = 'The real one'
856 '''
857 vals4 = {
858 'name': 'RealPlugin',
859 'description': 'The real one',
860 'supported_platforms': ['windows', 'osx', 'linux'],
861 'author': 'Real Author',
862 'version': (3, 1, 4),
863 'minimum_calibre_version': (0, 9, 42),
864 }
865 assert parse_metadata(raw4, None, None) == vals4
866
867 # Test: all class attributes are type-annotated
868 raw5 = b'''\
869 from calibre.customize import FileTypePlugin
870
871 class FullAnnotPlugin(FileTypePlugin):
872 name: str = 'AllAnnotated'
873 description: str = 'fully annotated plugin'
874 supported_platforms: list = ['osx']
875 author: str = 'Annotated Author'
876 version: tuple = (1, 2, 3)
877 minimum_calibre_version: tuple = (0, 9, 42)
878 '''
879 vals5 = {
880 'name': 'AllAnnotated',
881 'description': 'fully annotated plugin',
882 'supported_platforms': ['osx'],
883 'author': 'Annotated Author',
884 'version': (1, 2, 3),
885 'minimum_calibre_version': (0, 9, 42),
886 }
887 assert parse_metadata(raw5, None, None) == vals5
888
889
890 # }}}
891
892
893 if __name__ == '__main__':
894 # Run test_parse_metadata() with:
895 # python -c 'import runpy; runpy.run_path("setup/plugins_mirror.py")["test_parse_metadata"]()'
896 # import pprint
897 # pprint.pprint(get_plugin_info(open(sys.argv[-1], 'rb').read()))
898
899 # print('\n'.join(map(str, parse_index())))
900
901 main()