chamesle-store (46847B)
1 #!/usr/bin/python3 2 # Chamesle Store: apps from Flathub and from the Chamesle repo in one place, plus .deb/.rpm files through pkgimport, 3 # firmware through fwupd. ratings and reviews are gnome's odrs, the ones gnome software shows 4 import gettext, gzip, hashlib, json, os, re, subprocess, sys, threading, time, urllib.request 5 import xml.etree.ElementTree as ET 6 7 import gi 8 gi.require_version("Gtk", "4.0") 9 gi.require_version("Adw", "1") 10 from gi.repository import Adw, Gdk, Gio, GLib, GObject, Gtk, Pango 11 12 gettext.textdomain("chamesle") 13 _, ngettext = gettext.gettext, gettext.ngettext 14 15 APPSTREAM = "/var/lib/flatpak/appstream/flathub/x86_64/active" 16 CACHE = os.path.join(GLib.get_user_cache_dir(), "chamesle-store") 17 HELPER = "/usr/libexec/chamesle-store-helper" 18 ODRS = "https://odrs.gnome.org/1.0/reviews/api" 19 AUTO_CONF = "/etc/chamesle/updates.conf" 20 AUTO_STATE = "/var/lib/chamesle/auto-update" 21 # bump when the flathub cache gets new fields 22 CACHE_V = 2 23 # de_DE from de_DE.UTF-8, what odrs wants 24 LANG = next((l for l in GLib.get_language_names() if "." not in l and "@" not in l and l != "C"), "en_US") 25 XML_LANG = "{http://www.w3.org/XML/1998/namespace}lang" 26 27 CSS = b""" 28 .stars { color: #e5a50a; } 29 .stars-off { color: alpha(currentColor, .25); } 30 .shot { border-radius: 8px; } 31 """ 32 33 FEATURED = ["com.spotify.Client", "com.discordapp.Discord", "com.valvesoftware.Steam", "com.obsproject.Studio", 34 "org.gimp.GIMP", "org.libreoffice.LibreOffice", "org.videolan.VLC", "org.telegram.desktop", 35 "org.kde.krita", "org.blender.Blender", "com.visualstudio.code", "org.inkscape.Inkscape"] 36 37 # freedesktop categories -> what the store shows 38 CATEGORIES = [ 39 (_("Games"), "Game", "applications-games-symbolic"), 40 (_("Internet"), "Network", "applications-internet-symbolic"), 41 (_("Music & Video"), "AudioVideo", "applications-multimedia-symbolic"), 42 (_("Graphics & Photos"), "Graphics", "applications-graphics-symbolic"), 43 (_("Office"), "Office", "x-office-document-symbolic"), 44 (_("Development"), "Development", "applications-engineering-symbolic"), 45 (_("Education & Science"), "Education", "applications-science-symbolic"), 46 (_("Utilities"), "Utility", "applications-utilities-symbolic"), 47 (_("System"), "System", "applications-system-symbolic"), 48 ] 49 50 51 class Source: 52 def __init__(self, kind, ref, summary="", description="", icon=None, shots=None, version=""): 53 self.kind, self.ref, self.summary, self.description, self.icon = kind, ref, summary, description, icon 54 self.shots, self.version = shots or [], version 55 56 @property 57 def label(self): 58 return "Flathub" if self.kind == "flathub" else "Chamesle" 59 60 61 class App: 62 def __init__(self, name): 63 self.name, self.sources, self.categories = name, [], set() 64 65 def source(self, kind): 66 return next((s for s in self.sources if s.kind == kind), None) 67 68 @property 69 def summary(self): 70 return next((s.summary for s in self.sources if s.summary), "") 71 72 @property 73 def icon(self): 74 return next((s.icon for s in self.sources if s.icon), None) 75 76 @property 77 def flathub(self): 78 return self.source("flathub") 79 80 81 def run(cmd): 82 return subprocess.run(cmd, capture_output=True, text=True) 83 84 85 def repo_url(): 86 try: 87 for line in open("/etc/apk/repositories"): 88 parts = line.split() 89 if parts and not line.startswith("#"): 90 url = parts[-1] 91 if url.startswith("http"): 92 return url.rstrip("/") + "/x86_64" 93 except OSError: 94 pass 95 return None 96 97 98 def localized(comp, tag): 99 # the element in the user's language, or the untranslated one 100 els = {e.get(XML_LANG): e for e in comp.findall(tag)} 101 return next((els[l] for l in GLib.get_language_names() if l in els), els.get(None)) 102 103 104 def text_of(el): 105 # appstream descriptions: <p> and <li>, as plain paragraphs 106 out = [] 107 for c in el: 108 if c.get(XML_LANG): 109 continue 110 if c.tag == "p": 111 out.append("".join(c.itertext()).strip()) 112 elif c.tag in ("ul", "ol"): 113 out += ["• " + "".join(li.itertext()).strip() for li in c] 114 return "\n\n".join(x for x in out if x) 115 116 117 def user_hash(): 118 # odrs knows a reviewer by this, never by name: the same on every run, different on every machine 119 try: 120 mid = open("/etc/machine-id").read().strip() 121 except OSError: 122 mid = "" 123 return hashlib.sha1(("chamesle-store[%s:%s]" % (GLib.get_user_name(), mid)).encode()).hexdigest() 124 125 126 def post(url, data): 127 req = urllib.request.Request(url, json.dumps(data).encode(), {"Content-Type": "application/json"}) 128 return json.load(urllib.request.urlopen(req, timeout=20)) 129 130 131 def stars(avg, size=None): 132 # five stars, the filled ones gold 133 box = Gtk.Box(spacing=1) 134 for i in range(5): 135 l = Gtk.Label(label="★", css_classes=["stars" if avg >= i + 0.5 else "stars-off"]) 136 if size: 137 l.add_css_class(size) 138 box.append(l) 139 return box 140 141 142 class Catalog: 143 def __init__(self): 144 self.apps = {} 145 self.ratings = {} 146 self.by_flathub, self.by_pkg = {}, {} 147 self.installed_apk, self.installed_flatpak = set(), set() 148 149 def add(self, name, source, categories): 150 key = name.lower() 151 app = self.apps.setdefault(key, App(name)) 152 if not app.source(source.kind): 153 app.sources.append(source) 154 app.categories |= set(categories) 155 (self.by_flathub if source.kind == "flathub" else self.by_pkg)[source.ref] = app 156 157 def load_flathub(self): 158 path = None 159 for p in ("appstream.xml.gz", "appstream.xml"): 160 if os.path.exists(os.path.join(APPSTREAM, p)): 161 path = os.path.join(APPSTREAM, p) 162 break 163 if not path: 164 run(["flatpak", "update", "--appstream", "flathub"]) 165 return self.load_flathub() if os.path.exists(os.path.join(APPSTREAM, "appstream.xml.gz")) else None 166 # parsing flathub's list takes a while: keep the result until flatpak downloads a new one 167 cached = os.path.join(CACHE, "flathub.json") 168 stamp = os.path.getmtime(path) 169 try: 170 c = json.load(open(cached)) 171 if c["stamp"] == stamp and c.get("v") == CACHE_V and c.get("lang") == LANG: 172 for a in c["apps"]: 173 self.add(a[0], Source("flathub", a[1], a[2], a[3], a[4], a[6], a[7]), a[5]) 174 return 175 except (OSError, ValueError, KeyError): 176 pass 177 keep = [] 178 data = gzip.open(path).read() if path.endswith(".gz") else open(path, "rb").read() 179 for comp in ET.fromstring(data).iter("component"): 180 if comp.get("type") not in ("desktop-application", "desktop"): 181 continue 182 cid = comp.findtext("id") 183 name = next((n.text for n in comp.findall("name") if not n.get(XML_LANG)), None) 184 if not cid or not name: 185 continue 186 summary = localized(comp, "summary") 187 summary = summary.text or "" if summary is not None else "" 188 desc = localized(comp, "description") 189 icon = None 190 for ic in comp.findall("icon"): 191 if ic.get("type") == "cached": 192 for size in ("128x128", "64x64"): 193 p = os.path.join(APPSTREAM, "icons", size, ic.text) 194 if os.path.exists(p): 195 icon = p 196 break 197 if icon: 198 break 199 cats = [c.text for c in comp.iter("category") if c.text] 200 desc = text_of(desc) if desc is not None else "" 201 # screenshots: flathub's 624 wide thumbnails, or the closest it has 202 shots = [] 203 for sh in comp.iter("screenshot"): 204 imgs = [(int(i.get("width") or 0), i.text) for i in sh.findall("image") if i.text] 205 thumbs = [x for x in imgs if 500 <= x[0] <= 800] or sorted(imgs) 206 if thumbs: 207 shots.append(thumbs[0][1].strip()) 208 rel = comp.find("releases/release") 209 version = rel.get("version", "") if rel is not None else "" 210 self.add(name, Source("flathub", cid, summary, desc, icon, shots[:6], version), cats) 211 keep.append([name, cid, summary, desc, icon, cats, shots[:6], version]) 212 os.makedirs(CACHE, exist_ok=True) 213 json.dump({"stamp": stamp, "v": CACHE_V, "lang": LANG, "apps": keep}, open(cached, "w")) 214 215 def load_repo(self): 216 url = repo_url() 217 os.makedirs(os.path.join(CACHE, "icons"), exist_ok=True) 218 local = os.path.join(CACHE, "apps.json") 219 try: 220 urllib.request.urlretrieve(url + "/apps.json", local) 221 except Exception: 222 pass 223 if not os.path.exists(local): 224 return 225 for a in json.load(open(local)): 226 icon = ("repo", a["icon"]) if a.get("icon") else None 227 self.add(a["name"], Source("apk", a["pkg"], a.get("summary", ""), "", icon), a.get("categories", [])) 228 229 def load_ratings(self): 230 # every app's star counts in one 2 MB file, fetched again once a day 231 path = os.path.join(CACHE, "ratings.json") 232 try: 233 if not os.path.exists(path) or time.time() - os.path.getmtime(path) > 86400: 234 urllib.request.urlretrieve(ODRS + "/ratings", path + ".new") 235 os.replace(path + ".new", path) 236 self.ratings = json.load(open(path)) 237 except Exception: 238 pass 239 240 def rating(self, app): 241 # (average out of 5, how many), or None 242 f = app.flathub 243 r = f and (self.ratings.get(f.ref) or self.ratings.get(f.ref + ".desktop")) 244 if not r or not r.get("total"): 245 return None 246 n = sum(r.get("star%d" % i, 0) for i in range(1, 6)) 247 if not n: 248 return None 249 return sum(i * r.get("star%d" % i, 0) for i in range(1, 6)) / n, n 250 251 def load_installed(self): 252 self.installed_apk = set(run(["apk", "info", "--quiet"]).stdout.split()) 253 self.installed_flatpak = set(run(["flatpak", "list", "--app", "--columns=application"]).stdout.split()) 254 255 def installed(self, app): 256 return [s for s in app.sources if (s.kind == "apk" and s.ref in self.installed_apk) or 257 (s.kind == "flathub" and s.ref in self.installed_flatpak)] 258 259 def updates(self): 260 # "bash-5.3-r2 < 5.3-r3": installed, newer one in the repo (works without root) 261 apk = [] 262 for line in run(["apk", "version", "-l", "<"]).stdout.splitlines(): 263 m = re.match(r"(\S+)-([^-\s]+-r\d+)\s+<\s+(\S+)", line) 264 if m: 265 apk.append(m.groups()) 266 flat = run(["flatpak", "remote-ls", "--updates", "--app", "--columns=application"]).stdout.split() 267 return apk, flat 268 269 def firmware(self): 270 # devices fwupd has a newer firmware for: [(device id, name, version now, release)], None without fwupd 271 if not os.path.exists("/usr/bin/fwupdmgr"): 272 return None 273 p = run(["fwupdmgr", "get-updates", "--json"]) 274 try: 275 devs = json.loads(p.stdout).get("Devices", []) 276 except ValueError: 277 return [] 278 out = [] 279 for d in devs: 280 rels = d.get("Releases") or [] 281 if rels and d.get("DeviceId"): 282 out.append((d["DeviceId"], d.get("Name", _("Device")), d.get("Version", ""), rels[0])) 283 return out 284 285 def needs_reboot(self): 286 try: 287 devs = json.loads(run(["fwupdmgr", "get-devices", "--json"]).stdout).get("Devices", []) 288 except ValueError: 289 return False 290 return any("needs-reboot" in (d.get("Flags") or []) for d in devs) 291 292 293 def icon_widget(app, size): 294 img = Gtk.Image(pixel_size=size) 295 icon = app.icon 296 if icon is None: 297 img.set_from_icon_name("application-x-executable") 298 elif isinstance(icon, tuple): 299 # our repo's icons are fetched the first time they're shown 300 name = icon[1] 301 path = os.path.join(CACHE, "icons", name) 302 if os.path.exists(path): 303 img.set_from_file(path) 304 else: 305 img.set_from_icon_name("application-x-executable") 306 307 def fetch(): 308 try: 309 urllib.request.urlretrieve(repo_url() + "/icons/" + name, path) 310 GLib.idle_add(img.set_from_file, path) 311 except Exception: 312 pass 313 threading.Thread(target=fetch, daemon=True).start() 314 else: 315 img.set_from_file(icon) 316 return img 317 318 319 class Store(Adw.Application): 320 def __init__(self, updates=False): 321 super().__init__(application_id="org.chamesle.Store", flags=Gio.ApplicationFlags.HANDLES_OPEN) 322 self.catalog = Catalog() 323 self.busy = False 324 self.start_on_updates = updates 325 326 # ---- window 327 328 def do_activate(self): 329 win = self.get_active_window() 330 if win: 331 win.present() 332 return 333 css = Gtk.CssProvider() 334 css.load_from_data(CSS, -1) 335 Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 336 self.win = Adw.ApplicationWindow(application=self, title=_("Store"), default_width=1000, default_height=720) 337 self.toasts = Adw.ToastOverlay() 338 self.nav = Adw.NavigationView() 339 self.prog = Gtk.ProgressBar(hexpand=True, valign=Gtk.Align.CENTER) 340 self.prog_label = Gtk.Label(xalign=0, ellipsize=Pango.EllipsizeMode.END, width_chars=30) 341 bar = Gtk.Box(spacing=12, margin_top=8, margin_bottom=8, margin_start=12, margin_end=12) 342 bar.append(Gtk.Spinner(spinning=True)) 343 bar.append(self.prog_label) 344 bar.append(self.prog) 345 inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 346 inner.append(Gtk.Separator()) 347 inner.append(bar) 348 self.prog_bar = Gtk.Revealer(child=inner, transition_type=Gtk.RevealerTransitionType.SLIDE_UP) 349 outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 350 self.nav.set_vexpand(True) 351 outer.append(self.nav) 352 outer.append(self.prog_bar) 353 self.toasts.set_child(outer) 354 self.win.set_content(self.toasts) 355 356 self.stack = Adw.ViewStack() 357 self.explore = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 358 self.installed_page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 359 self.updates_page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 360 self.stack.add_titled_with_icon(self.scrolled(self.explore), "explore", _("Explore"), "system-search-symbolic") 361 self.stack.add_titled_with_icon(self.scrolled(self.installed_page), "installed", _("Installed"), "emblem-ok-symbolic") 362 self.updates_title = self.stack.add_titled_with_icon(self.scrolled(self.updates_page), "updates", _("Updates"), 363 "software-update-available-symbolic") 364 self.stack.connect("notify::visible-child-name", lambda *a: self.refresh_tab()) 365 366 header = Adw.HeaderBar() 367 header.set_title_widget(Adw.ViewSwitcher(stack=self.stack, policy=Adw.ViewSwitcherPolicy.WIDE)) 368 self.search_button = Gtk.ToggleButton(icon_name="system-search-symbolic", tooltip_text=_("Search")) 369 header.pack_start(self.search_button) 370 menu = Gio.Menu() 371 menu.append(_("Install a .deb or .rpm file…"), "app.import") 372 header.pack_end(Gtk.MenuButton(icon_name="open-menu-symbolic", menu_model=menu)) 373 act = Gio.SimpleAction.new("import", None) 374 act.connect("activate", lambda *a: self.pick_file()) 375 self.add_action(act) 376 377 self.search = Gtk.SearchEntry(placeholder_text=_("Search apps"), hexpand=True) 378 bar = Gtk.SearchBar(child=Adw.Clamp(child=self.search, maximum_size=600)) 379 bar.connect_entry(self.search) 380 bar.set_key_capture_widget(self.win) 381 self.search_button.bind_property("active", bar, "search-mode-enabled", 382 GObject.BindingFlags.BIDIRECTIONAL) 383 self.search.connect("search-changed", lambda e: self.do_search(e.get_text())) 384 385 self.results = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 386 self.main_stack = Gtk.Stack() 387 self.main_stack.add_named(self.stack, "tabs") 388 self.main_stack.add_named(self.scrolled(self.results), "search") 389 self.loading = Adw.StatusPage(title=_("Getting the app lists ready"), description=_("This takes a moment the first time.")) 390 self.loading.set_child(Gtk.Spinner(spinning=True, width_request=32, height_request=32)) 391 self.main_stack.add_named(self.loading, "loading") 392 self.main_stack.set_visible_child_name("loading") 393 394 view = Adw.ToolbarView() 395 view.add_top_bar(header) 396 view.add_top_bar(bar) 397 view.set_content(self.main_stack) 398 self.nav.add(Adw.NavigationPage(child=view, title=_("Store"), tag="main")) 399 self.win.present() 400 threading.Thread(target=self.load, daemon=True).start() 401 402 def do_open(self, files, n, hint): 403 # double-clicked .deb/.rpm files can be opened with the store too 404 self.activate() 405 for f in files: 406 self.import_file(f.get_path()) 407 408 def scrolled(self, child): 409 clamp = Adw.Clamp(child=child, maximum_size=1000, margin_top=18, margin_bottom=24, margin_start=12, margin_end=12) 410 return Gtk.ScrolledWindow(child=clamp, vexpand=True, hscrollbar_policy=Gtk.PolicyType.NEVER) 411 412 def toast(self, text): 413 self.toasts.add_toast(Adw.Toast(title=text, timeout=4)) 414 415 # ---- data 416 417 def load(self): 418 self.catalog.load_flathub() 419 self.catalog.load_repo() 420 self.catalog.load_ratings() 421 self.catalog.load_installed() 422 GLib.idle_add(self.loaded) 423 424 def loaded(self): 425 self.main_stack.set_visible_child_name("tabs") 426 if self.start_on_updates: 427 self.stack.set_visible_child_name("updates") 428 self.fill_explore() 429 self.refresh_tab() 430 threading.Thread(target=self.check_updates, daemon=True).start() 431 432 def check_updates(self): 433 apk, flat = self.catalog.updates() 434 GLib.idle_add(self.show_updates, apk, flat, None) 435 fw = self.catalog.firmware() 436 GLib.idle_add(self.show_updates, apk, flat, fw) 437 438 # ---- pages 439 440 def clear(self, box): 441 while box.get_first_child(): 442 box.remove(box.get_first_child()) 443 444 def heading(self, text): 445 return Gtk.Label(label=text, xalign=0, css_classes=["title-2"], margin_top=18, margin_bottom=10) 446 447 def tile(self, app): 448 b = Gtk.Button(css_classes=["card"], width_request=220) 449 box = Gtk.Box(spacing=12, margin_top=12, margin_bottom=12, margin_start=12, margin_end=12) 450 box.append(icon_widget(app, 48)) 451 text = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, valign=Gtk.Align.CENTER) 452 text.append(Gtk.Label(label=app.name, xalign=0, css_classes=["heading"], ellipsize=Pango.EllipsizeMode.END)) 453 text.append(Gtk.Label(label=app.summary, xalign=0, css_classes=["dim-label", "caption"], 454 ellipsize=Pango.EllipsizeMode.END, max_width_chars=28)) 455 r = self.catalog.rating(app) 456 if r and r[1] >= 5: 457 line = Gtk.Box(spacing=6) 458 line.append(stars(r[0], "caption")) 459 line.append(Gtk.Label(label=str(r[1]), css_classes=["dim-label", "caption"])) 460 text.append(line) 461 box.append(text) 462 b.set_child(box) 463 b.connect("clicked", lambda *a: self.show_app(app)) 464 return b 465 466 def grid(self, apps): 467 flow = Gtk.FlowBox(selection_mode=Gtk.SelectionMode.NONE, homogeneous=True, max_children_per_line=4, 468 column_spacing=12, row_spacing=12) 469 for a in apps: 470 flow.append(self.tile(a)) 471 return flow 472 473 def fill_explore(self): 474 self.clear(self.explore) 475 featured = [self.catalog.by_flathub[i] for i in FEATURED if i in self.catalog.by_flathub] 476 if featured: 477 self.explore.append(self.heading(_("Popular"))) 478 self.explore.append(self.grid(featured)) 479 self.explore.append(self.heading(_("Categories"))) 480 flow = Gtk.FlowBox(selection_mode=Gtk.SelectionMode.NONE, homogeneous=True, max_children_per_line=3, 481 column_spacing=12, row_spacing=12) 482 for title, cat, icon in CATEGORIES: 483 b = Gtk.Button(css_classes=["card"]) 484 box = Gtk.Box(spacing=10, margin_top=16, margin_bottom=16, margin_start=16, margin_end=16) 485 box.append(Gtk.Image(icon_name=icon, pixel_size=24)) 486 box.append(Gtk.Label(label=title, css_classes=["heading"])) 487 b.set_child(box) 488 b.connect("clicked", lambda w, t=title, c=cat: self.show_category(t, c)) 489 flow.append(b) 490 self.explore.append(flow) 491 n = len(self.catalog.apps) 492 self.explore.append(Gtk.Label(label=ngettext("%d app from Flathub and the Chamesle repo", "%d apps from Flathub and the Chamesle repo", n) % n, 493 css_classes=["dim-label", "caption"], margin_top=24)) 494 495 def show_category(self, title, cat): 496 apps = sorted((a for a in self.catalog.apps.values() if cat in a.categories), key=lambda a: a.name.lower()) 497 box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) 498 box.append(self.grid(apps[:300])) 499 view = Adw.ToolbarView() 500 view.add_top_bar(Adw.HeaderBar()) 501 view.set_content(self.scrolled(box)) 502 self.nav.push(Adw.NavigationPage(child=view, title=title)) 503 504 def do_search(self, text): 505 text = text.strip().lower() 506 if not text: 507 self.main_stack.set_visible_child_name("tabs") 508 return 509 self.main_stack.set_visible_child_name("search") 510 self.clear(self.results) 511 hits = [a for a in self.catalog.apps.values() if text in a.name.lower() or text in a.summary.lower()] 512 hits.sort(key=lambda a: (not a.name.lower().startswith(text), text not in a.name.lower(), a.name.lower())) 513 if not hits: 514 self.results.append(Adw.StatusPage(icon_name="system-search-symbolic", title=_("Nothing found"), 515 description=_("Try another word, or install a .deb or .rpm file from the menu."))) 516 return 517 self.results.append(self.grid(hits[:120])) 518 519 def refresh_tab(self): 520 name = self.stack.get_visible_child_name() 521 if name == "installed": 522 self.clear(self.installed_page) 523 apps = sorted((a for a in self.catalog.apps.values() if self.catalog.installed(a)), key=lambda a: a.name.lower()) 524 self.installed_page.append(self.heading(_("Installed apps"))) 525 group = Adw.PreferencesGroup() 526 for a in apps: 527 row = Adw.ActionRow(title=GLib.markup_escape_text(a.name), 528 subtitle=", ".join(s.label for s in self.catalog.installed(a)), activatable=True) 529 row.add_prefix(icon_widget(a, 32)) 530 row.connect("activated", lambda r, a=a: self.show_app(a)) 531 group.add(row) 532 self.installed_page.append(group) 533 534 def auto_group(self): 535 # updates on their own, and when they last happened 536 group = Adw.PreferencesGroup(margin_bottom=18) 537 on = True 538 try: 539 on = not any(l.strip() == "auto=no" for l in open(AUTO_CONF)) 540 except OSError: 541 pass 542 row = Adw.SwitchRow(title=_("Install updates automatically"), active=on, 543 subtitle=_("Once a day while plugged in. A snapshot is taken first, so an update can be " 544 "undone from the boot menu.")) 545 row.connect("notify::active", lambda r, *a: self.set_auto(r)) 546 group.add(row) 547 try: 548 when, n = open(AUTO_STATE).read().split()[:2] 549 last = GLib.DateTime.new_from_unix_local(int(when)).format("%c") 550 group.add(Adw.ActionRow(title=_("Last automatic update"), subtitle=ngettext( 551 "%(when)s, %(n)d update", "%(when)s, %(n)d updates", int(n)) % {"when": last, "n": int(n)})) 552 except (OSError, ValueError): 553 pass 554 return group 555 556 def set_auto(self, row): 557 # the switch flipping back after a cancelled password asks nothing 558 if getattr(self, "reverting", False): 559 self.reverting = False 560 return 561 want = row.get_active() 562 563 def go(): 564 ok = subprocess.run(["pkexec", HELPER, "auto", "on" if want else "off"], capture_output=True).returncode == 0 565 GLib.idle_add(done, ok) 566 567 def done(ok): 568 if ok: 569 self.toast(_("Updates will install automatically") if want else _("Updates wait for you now")) 570 else: 571 self.reverting = True 572 row.set_active(not want) 573 threading.Thread(target=go, daemon=True).start() 574 575 def show_updates(self, apk, flat, fw): 576 self.clear(self.updates_page) 577 self.updates_page.append(self.auto_group()) 578 total = len(apk) + len(flat) + len(fw or []) 579 self.updates_title.set_needs_attention(total > 0) 580 self.updates_title.set_badge_number(total) 581 if not len(apk) + len(flat): 582 self.updates_page.append(Adw.StatusPage(icon_name="emblem-ok-symbolic", title=_("Everything is up to date"), 583 vexpand=False)) 584 else: 585 top = Gtk.Box(spacing=12, margin_top=6, margin_bottom=12) 586 n = len(apk) + len(flat) 587 top.append(Gtk.Label(label=ngettext("%d update", "%d updates", n) % n, xalign=0, hexpand=True, 588 css_classes=["title-2"])) 589 go = Gtk.Button(label=_("Update all"), css_classes=["suggested-action", "pill"]) 590 go.connect("clicked", lambda *a: self.update_all()) 591 top.append(go) 592 self.updates_page.append(top) 593 group = Adw.PreferencesGroup() 594 for name, old, new in apk: 595 group.add(Adw.ActionRow(title=name, subtitle="%s → %s" % (old, new))) 596 for ref in flat: 597 app = self.catalog.by_flathub.get(ref) 598 group.add(Adw.ActionRow(title=GLib.markup_escape_text(app.name if app else ref), subtitle="Flathub")) 599 self.updates_page.append(group) 600 self.updates_page.append(self.firmware_group(fw)) 601 602 def firmware_group(self, fw): 603 # the computer's own firmware: bios, ssd, docks, touchpads... from the vendors, through lvfs 604 group = Adw.PreferencesGroup(title=_("Firmware"), margin_top=24, 605 description=_("Updates for the BIOS, the SSD and other parts, from the people " 606 "who made them.")) 607 if fw is None and not os.path.exists("/usr/bin/fwupdmgr"): 608 group.add(Adw.ActionRow(title=_("Firmware updates aren't installed"), subtitle="sudo apk add fwupd")) 609 elif fw is None: 610 row = Adw.ActionRow(title=_("Checking for firmware updates…")) 611 row.add_suffix(Gtk.Spinner(spinning=True)) 612 group.add(row) 613 elif not fw: 614 group.add(Adw.ActionRow(title=_("Your firmware is up to date"))) 615 for dev, name, now, rel in fw or []: 616 row = Adw.ActionRow(title=GLib.markup_escape_text(name), 617 subtitle=GLib.markup_escape_text("%s → %s%s" % ( 618 now, rel.get("Version", "?"), 619 (" · " + rel["Summary"]) if rel.get("Summary") else ""))) 620 b = Gtk.Button(label=_("Update"), valign=Gtk.Align.CENTER, css_classes=["pill"]) 621 b.connect("clicked", lambda w, d=dev, n=name: self.update_firmware(d, n)) 622 row.add_suffix(b) 623 group.add(row) 624 return group 625 626 def update_firmware(self, dev, name): 627 d = Adw.AlertDialog(heading=_("Update the firmware of %s?") % name, 628 body=_("Keep the computer plugged in. Some firmware is installed while the computer " 629 "restarts: don't turn it off until it's back.")) 630 d.add_response("cancel", _("Cancel")) 631 d.add_response("go", _("Update")) 632 d.set_response_appearance("go", Adw.ResponseAppearance.SUGGESTED) 633 634 def answered(d, r): 635 if r != "go": 636 return 637 title = _("Updating the firmware of %s") % name 638 639 def after(): 640 if self.catalog.needs_reboot(): 641 self.toast(_("Restart the computer to finish the firmware update")) 642 self.job(title, self.apk_job(["firmware", dev], title), _("Firmware updated"), after) 643 d.connect("response", answered) 644 d.present(self.win) 645 646 def show_app(self, app): 647 page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12) 648 top = Gtk.Box(spacing=18) 649 top.append(icon_widget(app, 96)) 650 info = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, valign=Gtk.Align.CENTER, hexpand=True, spacing=4) 651 info.append(Gtk.Label(label=app.name, xalign=0, css_classes=["title-1"], wrap=True)) 652 info.append(Gtk.Label(label=app.summary, xalign=0, wrap=True, css_classes=["dim-label"])) 653 top.append(info) 654 page.append(top) 655 656 # where to get it from, flathub first when both have it 657 sources = sorted(app.sources, key=lambda s: s.kind != "flathub") 658 choice = Gtk.DropDown.new_from_strings([s.label for s in sources]) 659 row = Gtk.Box(spacing=12) 660 if len(sources) > 1: 661 row.append(Gtk.Label(label=_("From"))) 662 row.append(choice) 663 else: 664 row.append(Gtk.Label(label=_("From %s") % sources[0].label, css_classes=["dim-label"])) 665 spacer = Gtk.Box(hexpand=True) 666 row.append(spacer) 667 button = Gtk.Button(css_classes=["pill"]) 668 row.append(button) 669 page.append(row) 670 r = self.catalog.rating(app) 671 if r: 672 line = Gtk.Box(spacing=8) 673 line.append(Gtk.Label(label="%.1f" % r[0], css_classes=["title-3"])) 674 line.append(stars(r[0])) 675 line.append(Gtk.Label(label=ngettext("%d rating", "%d ratings", r[1]) % r[1], css_classes=["dim-label"])) 676 info.append(line) 677 f = app.flathub 678 if f and f.shots: 679 page.append(self.screenshots(f.shots)) 680 desc = Gtk.Label(xalign=0, wrap=True, selectable=True, margin_top=12) 681 page.append(desc) 682 if f: 683 page.append(self.reviews(app, f)) 684 685 def update(*a): 686 s = sources[choice.get_selected()] 687 inst = s in self.catalog.installed(app) 688 button.set_label(_("Remove") if inst else _("Install")) 689 button.set_css_classes(["pill", "destructive-action" if inst else "suggested-action"]) 690 desc.set_label(s.description or s.summary or "") 691 choice.connect("notify::selected", update) 692 button.connect("clicked", lambda *a: self.install_or_remove(app, sources[choice.get_selected()], update)) 693 update() 694 695 view = Adw.ToolbarView() 696 view.add_top_bar(Adw.HeaderBar()) 697 view.set_content(self.scrolled(page)) 698 self.nav.push(Adw.NavigationPage(child=view, title=app.name)) 699 700 def screenshots(self, urls): 701 # a row you swipe or click through, each picture fetched once into the cache 702 car = Adw.Carousel(allow_scroll_wheel=False, spacing=12, height_request=360) 703 os.makedirs(os.path.join(CACHE, "shots"), exist_ok=True) 704 for url in urls: 705 pic = Gtk.Picture(content_fit=Gtk.ContentFit.CONTAIN, hexpand=True, css_classes=["shot"]) 706 path = os.path.join(CACHE, "shots", hashlib.sha1(url.encode()).hexdigest() + ".png") 707 708 def fetch(url=url, path=path, pic=pic): 709 try: 710 if not os.path.exists(path): 711 urllib.request.urlretrieve(url, path + ".part") 712 os.replace(path + ".part", path) 713 GLib.idle_add(pic.set_filename, path) 714 except Exception: 715 pass 716 threading.Thread(target=fetch, daemon=True).start() 717 car.append(pic) 718 box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6, margin_top=12) 719 over = Gtk.Overlay(child=car) 720 for icon, step, align in (("go-previous-symbolic", -1, Gtk.Align.START), ("go-next-symbolic", 1, Gtk.Align.END)): 721 b = Gtk.Button(icon_name=icon, halign=align, valign=Gtk.Align.CENTER, margin_start=6, margin_end=6, 722 css_classes=["circular", "osd"], visible=len(urls) > 1) 723 724 def go(b, step=step): 725 i = int(round(car.get_position())) + step 726 if 0 <= i < car.get_n_pages(): 727 car.scroll_to(car.get_nth_page(i), True) 728 b.connect("clicked", go) 729 over.add_overlay(b) 730 box.append(over) 731 if len(urls) > 1: 732 box.append(Adw.CarouselIndicatorDots(carousel=car)) 733 return box 734 735 def reviews(self, app, src): 736 box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12) 737 top = Gtk.Box(spacing=12, margin_top=18) 738 top.append(Gtk.Label(label=_("Reviews"), xalign=0, hexpand=True, css_classes=["title-2"])) 739 write = Gtk.Button(label=_("Write a review"), css_classes=["pill"]) 740 write.connect("clicked", lambda *a: self.write_review(app, src)) 741 write.set_sensitive(src in self.catalog.installed(app)) 742 write.set_tooltip_text(None if write.get_sensitive() else _("Install it first, then tell people what you think")) 743 top.append(write) 744 box.append(top) 745 group = Adw.PreferencesGroup() 746 box.append(group) 747 wait = Adw.ActionRow(title=_("Getting reviews…")) 748 group.add(wait) 749 750 def fetch(): 751 try: 752 got = post(ODRS + "/fetch", {"app_id": src.ref, "locale": LANG, "distro": "Chamesle", 753 "version": src.version or "unknown", "user_hash": user_hash(), "limit": 5}) 754 except Exception: 755 got = None 756 GLib.idle_add(show, got) 757 758 def show(got): 759 group.remove(wait) 760 got = [g for g in got or [] if isinstance(g, dict)] 761 # the key to write a review with. an app without reviews gets it alone, in an empty one 762 if got: 763 self.skeys = getattr(self, "skeys", {}) 764 self.skeys[src.ref] = got[0].get("user_skey") 765 got = [g for g in got if g.get("summary")] 766 if not got: 767 group.add(Adw.ActionRow(title=_("No reviews yet"))) 768 return 769 for g in got[:5]: 770 r = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4, margin_top=12, margin_bottom=12, 771 margin_start=12, margin_end=12) 772 head = Gtk.Box(spacing=8) 773 head.append(stars(g.get("rating", 0) / 20)) 774 head.append(Gtk.Label(label=g["summary"], xalign=0, css_classes=["heading"], wrap=True)) 775 r.append(head) 776 when = GLib.DateTime.new_from_unix_local(int(g.get("date_created", 0))).format("%x") 777 r.append(Gtk.Label(label="%s · %s" % (g.get("user_display") or _("Someone"), when), xalign=0, 778 css_classes=["dim-label", "caption"])) 779 r.append(Gtk.Label(label=g.get("description", ""), xalign=0, wrap=True, selectable=True)) 780 group.add(r) 781 threading.Thread(target=fetch, daemon=True).start() 782 return box 783 784 def write_review(self, app, src): 785 d = Adw.AlertDialog(heading=_("Review %s") % app.name, 786 body=_("Your review is shared with everyone who uses GNOME Software or the Chamesle Store.")) 787 form = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) 788 picked = {"n": 0} 789 row = Gtk.Box(spacing=2, halign=Gtk.Align.CENTER) 790 btns = [] 791 792 def pick(b, n): 793 picked["n"] = n 794 for i, x in enumerate(btns): 795 x.get_child().set_css_classes(["title-1", "stars" if i < n else "stars-off"]) 796 d.set_response_enabled("send", ready()) 797 for i in range(5): 798 b = Gtk.Button(child=Gtk.Label(label="★", css_classes=["title-1", "stars-off"]), css_classes=["flat"]) 799 b.connect("clicked", pick, i + 1) 800 btns.append(b) 801 row.append(b) 802 form.append(row) 803 name = Gtk.Entry(placeholder_text=_("Your name (shown with the review)"), text=GLib.get_real_name()) 804 summary = Gtk.Entry(placeholder_text=_("In a few words")) 805 text = Gtk.TextView(wrap_mode=Gtk.WrapMode.WORD_CHAR, top_margin=6, bottom_margin=6, left_margin=6, 806 right_margin=6) 807 form.append(name) 808 form.append(summary) 809 form.append(Gtk.Frame(child=Gtk.ScrolledWindow(child=text, min_content_height=120))) 810 811 def ready(*a): 812 b = text.get_buffer() 813 return bool(picked["n"] and summary.get_text().strip() and 814 b.get_text(b.get_start_iter(), b.get_end_iter(), False).strip()) 815 summary.connect("changed", lambda *a: d.set_response_enabled("send", ready())) 816 text.get_buffer().connect("changed", lambda *a: d.set_response_enabled("send", ready())) 817 d.set_extra_child(form) 818 d.add_response("cancel", _("Cancel")) 819 d.add_response("send", _("Send")) 820 d.set_response_appearance("send", Adw.ResponseAppearance.SUGGESTED) 821 d.set_response_enabled("send", False) 822 823 def answered(d, r): 824 if r != "send": 825 return 826 b = text.get_buffer() 827 body = {"app_id": src.ref, "locale": LANG, "distro": "Chamesle", "version": src.version or "unknown", 828 "user_hash": user_hash(), "user_skey": getattr(self, "skeys", {}).get(src.ref, ""), 829 "user_display": name.get_text().strip() or _("Someone"), "rating": picked["n"] * 20, 830 "summary": summary.get_text().strip(), 831 "description": b.get_text(b.get_start_iter(), b.get_end_iter(), False).strip()} 832 833 def send(): 834 try: 835 got = post(ODRS + "/submit", body) 836 ok = got.get("success", False) 837 msg = got.get("msg", "") 838 except Exception as e: 839 ok, msg = False, str(e) 840 GLib.idle_add(self.toast, _("Thanks, your review is sent") if ok else _("The review didn't go through: %s") % msg) 841 threading.Thread(target=send, daemon=True).start() 842 d.connect("response", answered) 843 d.present(self.win) 844 845 # ---- doing things 846 847 def show_progress(self, text, frac): 848 # frac None: no numbers yet, just keep the bar moving 849 self.prog_label.set_label(text) 850 if frac is None: 851 self.prog.pulse() 852 else: 853 self.prog.set_fraction(max(0.0, min(1.0, frac))) 854 self.prog_bar.set_reveal_child(True) 855 856 def job(self, title, work, done_text, then=None): 857 """run work(report) in a thread; report(text, fraction) moves the bar; work returns an error or None""" 858 if self.busy: 859 self.toast(_("One thing at a time, the last one is still going")) 860 return 861 self.busy = True 862 self.show_progress(title, 0.0) 863 pulse = GLib.timeout_add(250, lambda: (self.prog.get_fraction() == 0 and self.prog.pulse(), True)[1]) 864 865 def report(text, frac): 866 GLib.idle_add(self.show_progress, text, frac) 867 868 def go(): 869 try: 870 err = work(report) 871 except Exception as e: 872 err = str(e) 873 GLib.idle_add(finish, err) 874 875 def finish(err): 876 self.busy = False 877 GLib.source_remove(pulse) 878 self.prog_bar.set_reveal_child(False) 879 if not err: 880 self.toast(done_text) 881 elif err == "cancelled": 882 self.toast(_("Cancelled")) 883 else: 884 # the whole error, scrollable and copyable, and kept in a file to send to someone 885 log = os.path.join(CACHE, "last-error.txt") 886 os.makedirs(CACHE, exist_ok=True) 887 with open(log, "w") as f: 888 f.write(title + "\n\n" + err + "\n") 889 text = Gtk.TextView(editable=False, monospace=True, wrap_mode=Gtk.WrapMode.WORD_CHAR, 890 top_margin=8, bottom_margin=8, left_margin=8, right_margin=8) 891 text.get_buffer().set_text(err) 892 box = Gtk.ScrolledWindow(child=text, min_content_height=220, min_content_width=480) 893 d = Adw.AlertDialog(heading=_("That didn't work"), body=_("The full error is also saved in %s") % log) 894 d.set_extra_child(box) 895 d.add_response("ok", _("OK")) 896 d.present(self.win) 897 self.catalog.load_installed() 898 self.refresh_tab() 899 if then: 900 then() 901 threading.Thread(target=self.check_updates, daemon=True).start() 902 threading.Thread(target=go, daemon=True).start() 903 904 def apk_job(self, args, title): 905 # the helper runs apk with --progress-fd 1: lines like "1234/56789" (bytes done/total) on stdout 906 def work(report): 907 p = subprocess.Popen(["pkexec", HELPER] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) 908 err = [] 909 t = threading.Thread(target=lambda: err.extend(p.stderr.readlines()), daemon=True) 910 t.start() 911 out, label = [], title 912 for line in p.stdout: 913 # "85973/14385942 install" is progress, "(2/9) Installing glibc (2.41-r1)" says what it's on 914 m = re.match(r"(\d+)/(\d+)\b", line) 915 step = re.match(r"\((\d+)/(\d+)\) \w+ (\S+)", line) 916 if m and int(m.group(2)): 917 report(label, int(m.group(1)) / int(m.group(2))) 918 elif step: 919 label = _("%(what)s · %(pkg)s (%(n)s of %(total)s)") % {"what": title, "pkg": step.group(3), "n": step.group(1), 920 "total": step.group(2)} 921 out.append(line) 922 else: 923 out.append(line) 924 p.wait() 925 t.join() 926 if p.returncode in (126, 127): 927 return "cancelled" 928 return None if p.returncode == 0 else ("".join(err) or "".join(out)).strip() 929 return work 930 931 def flatpak_job(self, refs, title, remove=False, update=False): 932 # through libflatpak, so there are real numbers to show 933 def work(report): 934 gi.require_version("Flatpak", "1.0") 935 from gi.repository import Flatpak 936 inst = Flatpak.Installation.new_system(None) 937 t = Flatpak.Transaction.new_for_installation(inst, None) 938 arch = Flatpak.get_default_arch() 939 for ref in refs: 940 full = ref if ref.startswith("app/") else "app/%s/%s/stable" % (ref, arch) 941 if remove: 942 t.add_uninstall(full) 943 elif update: 944 t.add_update(full, None, None) 945 else: 946 t.add_install("flathub", full, None) 947 state = {"n": 0} 948 949 def new_op(t, op, progress): 950 state["n"] += 1 951 total = max(len(t.get_operations()), 1) 952 name = op.get_ref().split("/")[1] 953 progress.set_update_frequency(300) 954 955 def changed(progress): 956 frac = (state["n"] - 1 + progress.get_progress() / 100) / total 957 report(_("%(what)s (%(n)d of %(total)d: %(name)s)") % {"what": title, "n": state["n"], "total": total, "name": name}, frac) 958 progress.connect("changed", changed) 959 changed(progress) 960 t.connect("new-operation", new_op) 961 try: 962 t.run(None) 963 except GLib.Error as e: 964 return "cancelled" if "cancel" in e.message.lower() else e.message 965 return None 966 return work 967 968 def install_or_remove(self, app, src, then): 969 inst = src in self.catalog.installed(app) 970 title = (_("Removing %s") if inst else _("Installing %s")) % app.name 971 if src.kind == "flathub": 972 work = self.flatpak_job([src.ref], title, remove=inst) 973 else: 974 work = self.apk_job(["del" if inst else "add", src.ref], title) 975 self.job(title, work, (_("%s removed") if inst else _("%s installed")) % app.name, then) 976 977 def update_all(self): 978 def work(report): 979 err = self.apk_job(["upgrade"], _("Updating the system"))(report) 980 if err: 981 return err 982 from gi.repository import Flatpak 983 refs = [r.format_ref() for r in Flatpak.Installation.new_system(None).list_installed_refs_for_update(None) 984 if r.get_kind() == Flatpak.RefKind.APP] 985 return self.flatpak_job(refs, _("Updating apps"), update=True)(report) if refs else None 986 gi.require_version("Flatpak", "1.0") 987 self.job(_("Updating everything"), work, _("Everything is up to date")) 988 989 def pick_file(self): 990 f = Gtk.FileFilter(name=_(".deb and .rpm packages")) 991 for p in ("*.deb", "*.rpm"): 992 f.add_pattern(p) 993 filters = Gio.ListStore.new(Gtk.FileFilter) 994 filters.append(f) 995 d = Gtk.FileDialog(title=_("Install a .deb or .rpm file"), filters=filters) 996 d.open(self.win, None, lambda d, res: self.picked(d, res)) 997 998 def picked(self, d, res): 999 try: 1000 self.import_file(d.open_finish(res).get_path()) 1001 except GLib.Error: 1002 pass 1003 1004 def import_file(self, path): 1005 title = _("Installing %s") % os.path.basename(path) 1006 self.job(title, self.apk_job(["import", path], title), _("%s is installed") % os.path.basename(path)) 1007 1008 1009 if __name__ == "__main__": 1010 # --updates: open on the updates tab (the update notifier does that) 1011 updates = "--updates" in sys.argv 1012 sys.exit(Store(updates).run([a for a in sys.argv if a != "--updates"]))