Debian Codegraph @

pkg/apps/watch-appstream.py

raw
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 import gzip
3 import json
4 import os
5 import sys
6 import traceback
7 import xml.etree.ElementTree as ET
8
9 # Our own little abstraction on top of inotify. This only supports
10 # watching directories non-recursively, but it also supports watching
11 # directories that come and go into and out of existence.
12 #
13 # We could use pyinotify for this, but it would only be able to
14 # replace the Inotify class; we would still need all the logic in the
15 # Watcher class.
16
17
18 class Watcher:
19
20 def __init__(self):
21 self.inotify = Inotify()
22 self.watches = {} # path -> wd
23 self.handlers = {} # wd -> set of callbacks
24
25 def __add_watch(self, path, mask, handler):
26 if path in self.watches:
27 wd = self.watches[path]
28 self.handlers[wd] = self.handlers[wd] | frozenset([handler])
29 else:
30 wd = self.inotify.add_watch(path, mask)
31 if wd >= 0:
32 self.watches[path] = wd
33 self.handlers[wd] = frozenset([handler])
34
35 def __rem_watch(self, path, handler):
36 wd = self.watches[path]
37 self.handlers[wd] = self.handlers[wd] - frozenset([handler])
38 if len(self.handlers[wd]) == 0:
39 self.inotify.rem_watch(wd)
40 del self.handlers[wd]
41 del self.watches[path]
42
43 def watch_directory(self, path, callback):
44
45 events = (IN_CREATE |
46 IN_MOVED_TO |
47 IN_MOVED_FROM |
48 IN_DELETE_SELF |
49 IN_CLOSE_WRITE |
50 IN_DELETE |
51 IN_MOVE_SELF)
52
53 def handler(mask, name):
54 if ((mask & IN_CREATE or mask & IN_MOVED_TO) and
55 cur_wait_name and name == cur_wait_name):
56 reset()
57 elif mask & (IN_DELETE_SELF | IN_MOVE_SELF):
58 reset()
59 elif not cur_wait_name and len(name) > 0:
60 if mask & (IN_CLOSE_WRITE | IN_MOVED_TO | IN_DELETE | IN_MOVED_FROM):
61 callback(os.path.join(path, name))
62
63 def reset():
64 self.__rem_watch(cur_path, handler)
65 self.watch_directory(path, callback)
66
67 cur_path = path
68 cur_wait_path = None
69 cur_wait_name = None
70 while not os.path.exists(cur_path):
71 cur_wait_path = cur_path
72 cur_wait_name = os.path.basename(cur_wait_path)
73 cur_path = os.path.dirname(cur_path)
74
75 self.__add_watch(cur_path, events, handler)
76
77 if cur_wait_path and os.path.exists(cur_wait_path):
78 # Directory was created between our check and the watch setup
79 reset()
80 return
81
82 if not cur_wait_name:
83 for f in os.listdir(cur_path):
84 callback(os.path.join(cur_path, f))
85
86 def run(self):
87 def event(wd, mask, name):
88 if wd in self.handlers:
89 for h in self.handlers[wd]:
90 h(mask, name)
91 self.inotify.run(event)
92
93
94 lang = os.environ.get('LANGUAGE')
95
96
97 def attr_lang(elt):
98 return elt.attrib.get('{http://www.w3.org/XML/1998/namespace}lang')
99
100
101 def element(xml, tag):
102 """Get an XML element from the DOM tag
103
104 Retrieves the element with the matching language or by best effort
105 - If element has the selected language (or language selection is none), return it
106 - If the selected language can't be found, use empty language as a fallback
107 - If no elements are found with empty language attribute, use first element found
108 """
109
110 empty_lang = None
111 for elt in xml.iter(tag):
112 language = attr_lang(elt)
113 if language == lang:
114 return elt
115 elif language is None and empty_lang is None:
116 empty_lang = elt
117
118 if empty_lang is not None:
119 return empty_lang
120 return xml.find(tag)
121
122
123 def element_value(xml, tag):
124 elt = element(xml, tag)
125 return elt.text if elt is not None else None
126
127
128 def convert_description(xml, *, use_lang=True):
129 if xml is None:
130 return None
131
132 want_lang = lang if use_lang else None
133
134 # Only the following constructs are allowed, and they all appear
135 # at the top level:
136 #
137 # <p>text</p>
138 # <ul><li>text</li>...</ul>
139 # <ol><li>text</li>...</ol>
140
141 # A description can have 'lang' attributes both on the actual
142 # <description> element and on the contained <p>, <ul>, and <ol>
143 # elements, but probably not on the <li> elements.
144
145 def text(xml):
146 return " ".join(xml.itertext())
147
148 res = []
149 for c in xml:
150 if attr_lang(c) != want_lang:
151 continue
152 if c.tag == 'p':
153 res.append(text(c))
154 elif c.tag == 'ul' or c.tag == 'ol':
155 res.append({'tag': c.tag, 'items': list(map(text, c.findall('li')))})
156
157 # If we found nothing that matches lang, fall back to default
158 if lang is not None and len(res) == 0:
159 res = convert_description(xml, use_lang=False)
160
161 return res
162
163
164 def convert_cached_icon(directory, origin, xml):
165 icon = xml.text
166
167 def try_size(sz):
168 path = os.path.join(directory, "..", "icons", origin, sz, icon)
169 return path if os.path.exists(path) else None
170
171 return try_size("64x64") or try_size("128x128")
172
173
174 def convert_remote_icon(xml):
175 url = xml.text
176 if url.startswith(('http://', 'https://')):
177 return url
178 return None
179
180
181 def convert_local_icon(xml):
182 path = xml.text
183 if path.startswith("/"):
184 return path
185 return None
186
187
188 def convert_stock_icon(xml):
189 icon = xml.text
190
191 def try_size(size: str, extension: str):
192 path = os.path.join("/usr/share/icons/hicolor", size, "apps", f"{icon}.{extension}")
193 return path if os.path.exists(path) else None
194
195 return (try_size("64x64", "svg") or try_size("64x64", "png") or
196 try_size("128x128", "svg") or try_size("128x128", "png"))
197
198
199 def find_and_convert_icon(directory, origin, xml):
200 if xml is None:
201 return None
202
203 # Just use the first icon.
204 icon = xml.find('icon')
205
206 if icon is not None:
207 if icon.attrib['type'] == 'cached':
208 return convert_cached_icon(directory, origin, icon)
209 elif icon.attrib['type'] == 'remote':
210 return convert_remote_icon(icon)
211 elif icon.attrib['type'] == 'local':
212 return convert_local_icon(icon)
213 elif icon.attrib['type'] == 'stock':
214 return convert_stock_icon(icon)
215
216 return None
217
218
219 def convert_screenshots(xml):
220 if xml is None:
221 return []
222
223 shots = []
224 for sh in xml.iter('screenshot'):
225 for img in sh.iter('image'):
226 if img.attrib['type'] == 'source':
227 shots.append({'full': img.text})
228
229 return shots
230
231
232 def convert_launchables(xml):
233 ables = []
234
235 for elt in xml.iter('launchable'):
236 launchable_type = elt.attrib['type']
237 if launchable_type == "cockpit-manifest":
238 ables.append({'name': elt.text, 'type': launchable_type})
239
240 return ables
241
242
243 def convert_urls(xml):
244 urls = []
245
246 for url in xml.iter('url'):
247 urls.append({'type': url.attrib['type'], 'link': url.text})
248
249 return urls
250
251
252 def convert_collection_component(directory, origin, xml):
253 component_id = element_value(xml, 'id')
254 pkgname = element_value(xml, 'pkgname')
255 launchables = convert_launchables(xml)
256 urls = convert_urls(xml)
257
258 if not component_id or not pkgname or len(launchables) == 0:
259 return None
260
261 return {
262 'id': component_id,
263 'pkgname': pkgname,
264 'name': element_value(xml, 'name'),
265 'summary': element_value(xml, 'summary'),
266 'description': convert_description(element(xml, 'description')),
267 'icon': find_and_convert_icon(directory, origin, xml),
268 'screenshots': convert_screenshots(element(xml, 'screenshots')),
269 'launchables': launchables,
270 'urls': urls
271 }
272
273
274 def convert_upstream_component(file, xml):
275 if xml.tag != 'component':
276 return None
277
278 launchables = convert_launchables(xml)
279 if len(launchables) == 0:
280 return None
281
282 urls = convert_urls(xml)
283
284 return {
285 'id': element_value(xml, 'id'),
286 'name': element_value(xml, 'name'),
287 'summary': element_value(xml, 'summary'),
288 'description': convert_description(element(xml, 'description')),
289 'icon': find_and_convert_icon(dir, '', xml),
290 'screenshots': convert_screenshots(element(xml, 'screenshots')),
291 'launchables': launchables,
292 'installed': True,
293 'file': file,
294 'urls': urls
295 }
296
297
298 class MetainfoDB:
299 def __init__(self):
300 self.dumping = False
301 self.installed_by_file = {}
302 self.available_by_file = {}
303
304 def notice_installed(self, file, xml_root):
305 if xml_root is not None:
306 comp = convert_upstream_component(file, xml_root)
307 if comp is not None:
308 self.installed_by_file[file] = comp
309 elif file in self.installed_by_file:
310 del self.installed_by_file[file]
311 if self.dumping:
312 self.dump()
313
314 def notice_available(self, file, xml_root):
315 if xml_root is not None:
316 info = {}
317 origin = xml_root.attrib['origin']
318 for xml_comp in xml_root.iter('component'):
319 try:
320 comp = convert_collection_component(os.path.dirname(file), origin, xml_comp)
321 if comp is not None:
322 if comp['id'] in info:
323 pass # warning: duplicate id
324 else:
325 info[comp['id']] = comp
326 except KeyError:
327 pass
328 self.available_by_file[file] = info
329 elif file in self.available_by_file:
330 del self.available_by_file[file]
331 if self.dumping:
332 self.dump()
333
334 def dump(self):
335 comps = {}
336 for file in self.installed_by_file:
337 comp = self.installed_by_file[file]
338 if comp['id'] in comps:
339 pass # warn dup
340 else:
341 comps[comp['id']] = comp
342 for file in self.available_by_file:
343 for comp_id in self.available_by_file[file]:
344 comp = self.available_by_file[file][comp_id]
345 if comp['id'] not in comps:
346 comps[comp['id']] = comp
347 else:
348 z = comp.copy()
349 z.update(comps[comp['id']])
350 comps[comp['id']] = z
351
352 data = {
353 'components': comps,
354 'origin_files': list(self.available_by_file.keys())
355 }
356
357 sys.stdout.write(json.dumps(data) + '\n')
358 sys.stdout.flush()
359
360 def start_dumping(self):
361 self.dump()
362 self.dumping = True
363
364
365 def watch_db():
366 watcher = Watcher()
367
368 db = MetainfoDB()
369
370 def process_file(path, callback):
371 try:
372 if not os.path.exists(path):
373 callback(path, None)
374 elif path.endswith('.xml'):
375 callback(path, ET.parse(path).getroot())
376 elif path.endswith('.xml.gz'):
377 callback(path, ET.parse(gzip.open(path)).getroot())
378 except Exception:
379 # If we hit an exception during handling a file, pretend
380 # that it doesn't exist instead of keeping old data. This
381 # makes the behavior consistent across restarts of this
382 # watcher.
383 callback(path, None)
384 sys.stderr.write("%s: " % path)
385 sys.stderr.write("".join(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1])))
386 sys.stderr.flush()
387
388 def installed_callback(path):
389 process_file(path, lambda path, xml: db.notice_installed(path, xml))
390
391 def available_callback(path):
392 process_file(path, lambda path, xml: db.notice_available(path, xml))
393
394 # https://www.freedesktop.org/software/appstream/docs/chap-CatalogData.html
395 watcher.watch_directory('/usr/share/swcatalog/xml', available_callback)
396 watcher.watch_directory('/var/cache/swcatalog/xml', available_callback)
397 watcher.watch_directory('/var/lib/swcatalog/xml', available_callback)
398 # legacy paths
399 watcher.watch_directory('/usr/share/app-info/xmls', available_callback)
400 watcher.watch_directory('/var/cache/app-info/xmls', available_callback)
401 # installed packages
402 watcher.watch_directory('/usr/share/metainfo', installed_callback)
403 db.start_dumping()
404 watcher.run()
405
406
407 watch_db()