-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathmintUpdate.py
More file actions
executable file
·2791 lines (2412 loc) · 133 KB
/
mintUpdate.py
File metadata and controls
executable file
·2791 lines (2412 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import sys
import gi
import tempfile
import threading
import time
import gettext
import io
import json
import locale
import tarfile
import urllib.request
import proxygsettings
import subprocess
import pycurl
import datetime
import configparser
import traceback
import setproctitle
import platform
import re
from kernelwindow import KernelWindow
gi.require_version('Gtk', '3.0')
gi.require_version('Notify', '0.7')
from gi.repository import Gtk, Gdk, Gio, GLib, GObject, Notify, Pango
from Classes import Update, PRIORITY_UPDATES, UpdateTracker
from xapp.GSettingsWidgets import *
settings = Gio.Settings(schema_id="com.linuxmint.updates")
cinnamon_support = False
try:
if settings.get_boolean("show-cinnamon-updates"):
import cinnamon
cinnamon_support = True
except Exception as e:
if os.getenv("DEBUG"):
print("No cinnamon update support:\n%s" % traceback.format_exc())
flatpak_support = False
try:
if settings.get_boolean("show-flatpak-updates"):
import flatpakUpdater
flatpak_support = True
except Exception as e:
if os.getenv("DEBUG"):
print("No flatpak update support:\n%s" % traceback.format_exc())
CINNAMON_SUPPORT = cinnamon_support
FLATPAK_SUPPORT = flatpak_support
# import AUTOMATIONS dict
with open("/usr/share/linuxmint/mintupdate/automation/index.json") as f:
AUTOMATIONS = json.load(f)
try:
os.system("killall -q mintUpdate")
except Exception as e:
print (e)
print(sys.exc_info()[0])
setproctitle.setproctitle("mintUpdate")
# i18n
APP = 'mintupdate'
LOCALE_DIR = "/usr/share/locale"
locale.bindtextdomain(APP, LOCALE_DIR)
gettext.bindtextdomain(APP, LOCALE_DIR)
gettext.textdomain(APP)
_ = gettext.gettext
Notify.init(_("Update Manager"))
(TAB_DESC, TAB_PACKAGES, TAB_CHANGELOG) = range(3)
(UPDATE_CHECKED, UPDATE_DISPLAY_NAME, UPDATE_OLD_VERSION, UPDATE_NEW_VERSION, UPDATE_SOURCE, UPDATE_SIZE, UPDATE_SIZE_STR, UPDATE_TYPE_PIX, UPDATE_TYPE, UPDATE_TOOLTIP, UPDATE_SORT_STR, UPDATE_OBJ) = range(12)
BLACKLIST_PKG_NAME = 0
GIGABYTE = 1000 ** 3
MEGABYTE = 1000 ** 2
KILOBYTE = 1000
def size_to_string(size):
if (size >= GIGABYTE):
return "%d %s" % (size // GIGABYTE, _("GB"))
if (size >= (MEGABYTE)):
return "%d %s" % (size // MEGABYTE, _("MB"))
if (size >= KILOBYTE):
return "%d %s" % (size // KILOBYTE, _("KB"))
return "%d %s" % (size, _("B"))
def name_search_func(model, column, key, iter):
name = model.get_value(iter, column)
return key.lower() not in name.lower() # False is a match
class CacheWatcher(threading.Thread):
""" Monitors package cache and dpkg status and runs RefreshThread() on change """
def __init__(self, application, refresh_frequency=90):
threading.Thread.__init__(self)
self.application = application
self.cachetime = 0
self.statustime = 0
self.paused = False
self.refresh_frequency = refresh_frequency
self.pkgcache = "/var/cache/apt/pkgcache.bin"
self.dpkgstatus = "/var/lib/dpkg/status"
def run(self):
self.refresh_cache()
if os.path.isfile(self.pkgcache) and os.path.isfile(self.dpkgstatus):
self.update_cachetime()
self.loop()
else:
self.application.logger.write("Package cache location not found, disabling cache monitoring")
def loop(self):
while True:
if not self.paused and self.application.window.get_sensitive():
try:
cachetime = os.path.getmtime(self.pkgcache)
statustime = os.path.getmtime(self.dpkgstatus)
if (cachetime != self.cachetime or statustime != self.statustime) and \
not self.application.dpkg_locked():
self.cachetime = cachetime
self.statustime = statustime
self.refresh_cache()
except:
pass
time.sleep(self.refresh_frequency)
def resume(self, update_cachetime=True):
if not self.paused:
return
if update_cachetime:
self.update_cachetime()
self.paused = False
def pause(self):
self.paused = True
def update_cachetime(self):
if os.path.isfile(self.pkgcache) and os.path.isfile(self.dpkgstatus):
self.cachetime = os.path.getmtime(self.pkgcache)
self.statustime = os.path.getmtime(self.dpkgstatus)
def refresh_cache(self):
self.application.logger.write("Changes to the package cache detected, triggering refresh")
self.application.refresh()
class ChangelogRetriever(threading.Thread):
def __init__(self, update, application):
threading.Thread.__init__(self)
self.source_package = update.real_source_name
self.version = update.new_version
self.origin = update.origin
self.application = application
# get the proxy settings from gsettings
self.ps = proxygsettings.get_proxy_settings()
# Remove the epoch if present in the version
if ":" in self.version:
self.version = self.version.split(":")[-1]
def get_ppa_info(self):
ppa_sources_file = "/etc/apt/sources.list"
ppa_sources_dir = "/etc/apt/sources.list.d/"
ppa_words = self.origin.lstrip("LP-PPA-").split("-")
source = ppa_sources_file
if os.path.exists(ppa_sources_dir):
for filename in os.listdir(ppa_sources_dir):
if filename.startswith(self.origin.lstrip("LP-PPA-")):
source = os.path.join(ppa_sources_dir, filename)
break
if not os.path.exists(source):
return None, None
try:
with open(source) as f:
for line in f:
if (not line.startswith("#") and all(word in line for word in ppa_words)):
ppa_info = line.split("://")[1]
break
else:
return None, None
except EnvironmentError as e:
print ("Error encountered while trying to get PPA owner and name: %s" % e)
return None, None
ppa_url, ppa_owner, ppa_name, ppa_x = ppa_info.split("/", 3)
return ppa_owner, ppa_name
def get_ppa_changelog(self, ppa_owner, ppa_name):
max_tarball_size = 1000000
print ("\nFetching changelog for PPA package %s/%s/%s ..." % (ppa_owner, ppa_name, self.source_package))
if self.source_package.startswith("lib"):
ppa_abbr = self.source_package[:4]
else:
ppa_abbr = self.source_package[0]
deb_dsc_uri = "https://ppa.launchpadcontent.net/%s/%s/ubuntu/pool/main/%s/%s/%s_%s.dsc" % (ppa_owner, ppa_name, ppa_abbr, self.source_package, self.source_package, self.version)
try:
deb_dsc = urllib.request.urlopen(deb_dsc_uri, None, 10).read().decode("utf-8")
except Exception as e:
print ("Could not open Launchpad URL %s - %s" % (deb_dsc_uri, e))
return
for line in deb_dsc.split("\n"):
if "debian.tar" not in line:
continue
tarball_line = line.strip().split(" ", 2)
if len(tarball_line) == 3:
deb_checksum, deb_size, deb_filename = tarball_line
break
else:
deb_filename = None
if not deb_filename or not deb_size or not deb_size.isdigit():
print ("Unsupported debian .dsc file format. Skipping this package.")
return
if (int(deb_size) > max_tarball_size):
print ("Tarball size %s B exceeds maximum download size %d B. Skipping download." % (deb_size, max_tarball_size))
return
deb_file_uri = "https://ppa.launchpadcontent.net/%s/%s/ubuntu/pool/main/%s/%s/%s" % (ppa_owner, ppa_name, ppa_abbr, self.source_package, deb_filename)
try:
deb_file = urllib.request.urlopen(deb_file_uri, None, 10).read().decode("utf-8")
except Exception as e:
print ("Could not download tarball from %s - %s" % (deb_file_uri, e))
return
if deb_filename.endswith(".xz"):
cmd = ["xz", "--decompress"]
try:
xz = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
xz.stdin.write(deb_file)
xz.stdin.close()
deb_file = xz.stdout.read()
xz.stdout.close()
except EnvironmentError as e:
print ("Error encountered while decompressing xz file: %s" % e)
return
deb_file = io.BytesIO(deb_file)
try:
with tarfile.open(fileobj = deb_file) as f:
deb_changelog = f.extractfile("debian/changelog").read()
except tarfile.TarError as e:
print ("Error encountered while reading tarball: %s" % e)
return
return deb_changelog
def run(self):
Gdk.threads_enter()
self.application.textview_changes.set_text(_("Downloading changelog..."))
Gdk.threads_leave()
if self.ps == {}:
# use default urllib.request proxy mechanisms (possibly *_proxy environment vars)
proxy = urllib.request.ProxyHandler()
else:
# use proxy settings retrieved from gsettings
proxy = urllib.request.ProxyHandler(self.ps)
opener = urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
changelog = [_("No changelog available")]
changelog_sources = []
if self.origin == "linuxmint":
changelog_sources.append("http://packages.linuxmint.com/dev/" + self.source_package + "_" + self.version + "_amd64.changes")
changelog_sources.append("http://packages.linuxmint.com/dev/" + self.source_package + "_" + self.version + "_i386.changes")
elif self.origin == "ubuntu":
if (self.source_package.startswith("lib")):
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/main/%s/%s/%s_%s/changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/multiverse/%s/%s/%s_%s/changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/universe/%s/%s/%s_%s/changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/restricted/%s/%s/%s_%s/changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
else:
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/main/%s/%s/%s_%s/changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/multiverse/%s/%s/%s_%s/changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/universe/%s/%s/%s_%s/changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
changelog_sources.append("https://changelogs.ubuntu.com/changelogs/pool/restricted/%s/%s/%s_%s/changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
elif self.origin == "debian":
if (self.source_package.startswith("lib")):
changelog_sources.append("https://metadata.ftp-master.debian.org/changelogs/main/%s/%s/%s_%s_changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
changelog_sources.append("https://metadata.ftp-master.debian.org/changelogs/contrib/%s/%s/%s_%s_changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
changelog_sources.append("https://metadata.ftp-master.debian.org/changelogs/non-free/%s/%s/%s_%s_changelog" % (self.source_package[0:4], self.source_package, self.source_package, self.version))
else:
changelog_sources.append("https://metadata.ftp-master.debian.org/changelogs/main/%s/%s/%s_%s_changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
changelog_sources.append("https://metadata.ftp-master.debian.org/changelogs/contrib/%s/%s/%s_%s_changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
changelog_sources.append("https://metadata.ftp-master.debian.org/changelogs/non-free/%s/%s/%s_%s_changelog" % (self.source_package[0], self.source_package, self.source_package, self.version))
elif self.origin.startswith("LP-PPA"):
ppa_owner, ppa_name = self.get_ppa_info()
if ppa_owner and ppa_name:
deb_changelog = self.get_ppa_changelog(ppa_owner, ppa_name)
if not deb_changelog:
changelog_sources.append("https://launchpad.net/~%s/+archive/ubuntu/%s/+files/%s_%s_source.changes" % (ppa_owner, ppa_name, self.source_package, self.version))
else:
changelog = "%s\n" % deb_changelog
else:
print ("PPA owner or name could not be determined")
for changelog_source in changelog_sources:
try:
print("Trying to fetch the changelog from: %s" % changelog_source)
url = urllib.request.urlopen(changelog_source, None, 10)
source = url.read().decode("utf-8")
url.close()
changelog = ""
if "linuxmint.com" in changelog_source:
changes = source.split("\n")
for change in changes:
stripped_change = change.strip()
if stripped_change == ".":
change = ""
if change == "" or stripped_change.startswith("*") or stripped_change.startswith("["):
changelog = changelog + change + "\n"
elif "launchpad.net" in changelog_source:
changes = source.split("Changes:")[1].split("Checksums")[0].split("\n")
for change in changes:
stripped_change = change.strip()
if stripped_change != "":
if stripped_change == ".":
stripped_change = ""
changelog = changelog + stripped_change + "\n"
else:
changelog = source
changelog = changelog.split("\n")
break
except:
pass
Gdk.threads_enter()
self.application.textview_changes.set_text("\n".join(changelog))
Gdk.threads_leave()
class AutomaticRefreshThread(threading.Thread):
def __init__(self, application):
threading.Thread.__init__(self)
self.application = application
def run(self):
minute = 60
hour = 60 * minute
day = 24 * hour
initial_refresh = True
settings_prefix = ""
refresh_type = "initial"
while self.application.refresh_schedule_enabled:
try:
schedule = {
"minutes": self.application.settings.get_int("%srefresh-minutes" % settings_prefix),
"hours": self.application.settings.get_int("%srefresh-hours" % settings_prefix),
"days": self.application.settings.get_int("%srefresh-days" % settings_prefix)
}
timetosleep = schedule["minutes"] * minute + schedule["hours"] * hour + schedule["days"] * day
if not timetosleep:
time.sleep(60) # sleep 1 minute, don't mind the config we don't want an infinite loop to go nuts :)
else:
now = int(time.time())
if not initial_refresh:
refresh_last_run = self.application.settings.get_int("refresh-last-run")
if not refresh_last_run or refresh_last_run > now:
refresh_last_run = now
self.application.settings.set_int("refresh-last-run", now)
time_since_last_refresh = now - refresh_last_run
if time_since_last_refresh > 0:
timetosleep = timetosleep - time_since_last_refresh
# always wait at least 1 minute to be on the safe side
if timetosleep < 60:
timetosleep = 60
schedule["days"] = int(timetosleep / day)
schedule["hours"] = int((timetosleep - schedule["days"] * day) / hour)
schedule["minutes"] = int((timetosleep - schedule["days"] * day - schedule["hours"] * hour) / minute)
self.application.logger.write("%s refresh will happen in %d day(s), %d hour(s) and %d minute(s)" %
(refresh_type.capitalize(), schedule["days"], schedule["hours"], schedule["minutes"]))
time.sleep(timetosleep)
if not self.application.refresh_schedule_enabled:
self.application.logger.write("Auto-refresh disabled in preferences, cancelling %s refresh" % refresh_type)
self.application.uninhibit_pm()
return
if self.application.app_hidden():
self.application.logger.write("Update Manager is in tray mode, performing %s refresh" % refresh_type)
refresh = RefreshThread(self.application, root_mode=True)
refresh.start()
while refresh.is_alive():
time.sleep(5)
else:
if initial_refresh:
self.application.logger.write("Update Manager window is open, skipping %s refresh" % refresh_type)
else:
self.application.logger.write("Update Manager window is open, delaying %s refresh by 60s" % refresh_type)
time.sleep(60)
except Exception as e:
print (e)
self.application.logger.write_error("Exception occurred during %s refresh: %s" % (refresh_type, str(sys.exc_info()[0])))
if initial_refresh:
initial_refresh = False
settings_prefix = "auto"
refresh_type = "recurring"
else:
self.application.logger.write("Auto-refresh disabled in preferences, AutomaticRefreshThread stopped")
class InstallThread(threading.Thread):
def __init__(self, application):
threading.Thread.__init__(self, name="mintupdate-install-thread")
self.application = application
self.application.window.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH))
self.application.window.set_sensitive(False)
self.reboot_required = self.application.reboot_required
def __del__(self):
self.application.cache_watcher.resume(False)
Gdk.threads_enter()
self.application.window.get_window().set_cursor(None)
self.application.window.set_sensitive(True)
Gdk.threads_leave()
def run(self):
self.application.cache_watcher.pause()
self.application.inhibit_pm("Installing updates")
try:
self.application.logger.write("Install requested by user")
Gdk.threads_enter()
aptInstallNeeded = False
packages = []
cinnamon_spices = []
flatpaks = []
model = self.application.treeview.get_model()
Gdk.threads_leave()
iter = model.get_iter_first()
while iter is not None:
checked = model.get_value(iter, UPDATE_CHECKED)
if checked:
update = model.get_value(iter, UPDATE_OBJ)
if update.type == "cinnamon":
cinnamon_spices.append(update)
iter = model.iter_next(iter)
continue
elif update.type == "flatpak":
flatpaks.append(update)
iter = model.iter_next(iter)
continue
aptInstallNeeded = True
if update.type == "kernel":
for pkg in update.package_names:
if "-image-" in pkg:
try:
if self.application.is_lmde:
# In Mint, platform.release() returns the kernel version. In LMDE it returns the kernel
# abi version. So for LMDE, parse platform.version() instead.
version_string = platform.version()
kernel_version = re.search(r"(\d+\.\d+\.\d+)", version_string).group(1)
else:
kernel_version = platform.release().split("-")[0]
if update.old_version.startswith(kernel_version):
self.reboot_required = True
except Exception as e:
print("Warning: Could not assess the current kernel version: %s" % str(e))
self.reboot_required = True
break
if update.type == "security" and \
[True for pkg in update.package_names if "nvidia" in pkg]:
self.reboot_required = True
for package in update.package_names:
packages.append(package)
self.application.logger.write("Will install " + str(package))
iter = model.iter_next(iter)
needs_refresh = False
proceed = True
update_flatpaks = False
if aptInstallNeeded:
try:
pkgs = ' '.join(str(pkg) for pkg in packages)
warnings = subprocess.check_output("/usr/lib/linuxmint/mintUpdate/checkWarnings.py %s" % pkgs, shell = True).decode("utf-8")
#print ("/usr/lib/linuxmint/mintUpdate/checkWarnings.py %s" % pkgs)
warnings = warnings.split("###")
if len(warnings) == 2:
installations = warnings[0].split()
removals = warnings[1].split()
if len(installations) > 0 or len(removals) > 0:
Gdk.threads_enter()
try:
dialog = Gtk.MessageDialog(self.application.window, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK_CANCEL, None)
dialog.set_title("")
dialog.set_markup("<b>" + _("This upgrade will trigger additional changes") + "</b>")
#dialog.format_secondary_markup("<i>" + _("All available upgrades for this package will be ignored.") + "</i>")
dialog.set_icon_name("mintupdate")
dialog.set_default_size(320, 400)
dialog.set_resizable(True)
if len(removals) > 0:
# Removals
label = Gtk.Label()
label.set_text(_("The following packages will be removed:"))
label.set_alignment(0, 0.5)
label.set_padding(20, 0)
scrolledWindow = Gtk.ScrolledWindow()
scrolledWindow.set_shadow_type(Gtk.ShadowType.IN)
scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
treeview = Gtk.TreeView()
column = Gtk.TreeViewColumn("", Gtk.CellRendererText(), text=0)
column.set_sort_column_id(0)
column.set_resizable(True)
treeview.append_column(column)
treeview.set_headers_clickable(False)
treeview.set_reorderable(False)
treeview.set_headers_visible(False)
model = Gtk.TreeStore(str)
removals.sort()
for pkg in removals:
iter = model.insert_before(None, None)
model.set_value(iter, 0, pkg)
treeview.set_model(model)
treeview.show()
scrolledWindow.add(treeview)
dialog.get_content_area().pack_start(label, False, False, 0)
dialog.get_content_area().pack_start(scrolledWindow, True, True, 0)
dialog.get_content_area().set_border_width(6)
if len(installations) > 0:
# Installations
label = Gtk.Label()
label.set_text(_("The following packages will be installed:"))
label.set_alignment(0, 0.5)
label.set_padding(20, 0)
scrolledWindow = Gtk.ScrolledWindow()
scrolledWindow.set_shadow_type(Gtk.ShadowType.IN)
scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
treeview = Gtk.TreeView()
column = Gtk.TreeViewColumn("", Gtk.CellRendererText(), text=0)
column.set_sort_column_id(0)
column.set_resizable(True)
treeview.append_column(column)
treeview.set_headers_clickable(False)
treeview.set_reorderable(False)
treeview.set_headers_visible(False)
model = Gtk.TreeStore(str)
installations.sort()
for pkg in installations:
iter = model.insert_before(None, None)
model.set_value(iter, 0, pkg)
treeview.set_model(model)
treeview.show()
scrolledWindow.add(treeview)
dialog.get_content_area().pack_start(label, False, False, 0)
dialog.get_content_area().pack_start(scrolledWindow, True, True, 0)
dialog.show_all()
if dialog.run() == Gtk.ResponseType.OK:
proceed = True
else:
proceed = False
dialog.destroy()
except Exception as e:
print (e)
print(sys.exc_info()[0])
Gdk.threads_leave()
else:
proceed = True
except Exception as e:
print (e)
print(sys.exc_info()[0])
if len(flatpaks) > 0:
self.application.flatpak_updater.prepare_start_updates(flatpaks)
if self.application.flatpak_updater.confirm_start():
update_flatpaks = True
else:
proceed = False
if aptInstallNeeded and proceed:
Gdk.threads_enter()
self.application.set_status(_("Installing updates"), _("Installing updates"), "mintupdate-installing-symbolic", True)
Gdk.threads_leave()
self.application.logger.write("Ready to launch synaptic")
f = tempfile.NamedTemporaryFile()
cmd = [
"pkexec", "/usr/sbin/synaptic",
"--hide-main-window",
"--non-interactive",
"-o", "Synaptic::closeZvt=true",
"--set-selections-file", "%s" % f.name,
]
if os.environ.get("XDG_SESSION_TYPE", "x11") == "x11":
cmd += ["--parent-window-id", "%s" % self.application.window.get_window().get_xid()]
for pkg in packages:
pkg_line = "%s\tinstall\n" % pkg
f.write(pkg_line.encode("utf-8"))
f.flush()
subprocess.run(["sudo","/usr/lib/linuxmint/mintUpdate/synaptic-workaround.py","enable"])
try:
result = subprocess.run(cmd, stdout=self.application.logger.log, stderr=self.application.logger.log, check=True)
returnCode = result.returncode
except subprocess.CalledProcessError as e:
returnCode = e.returncode
subprocess.run(["sudo","/usr/lib/linuxmint/mintUpdate/synaptic-workaround.py","disable"])
self.application.logger.write("Return code:" + str(returnCode))
f.close()
latest_apt_update = ''
update_successful = False
with open("/var/log/apt/history.log", encoding="utf-8") as apt_history:
for line in reversed(list(apt_history)):
if "Start-Date" in line:
break
else:
latest_apt_update += line
if f.name in latest_apt_update and "End-Date" in latest_apt_update:
update_successful = True
self.application.logger.write("Install finished")
else:
self.application.logger.write("Install failed")
if update_successful:
# override CacheWatcher since there's a forced refresh later already
self.application.cache_watcher.update_cachetime()
if self.reboot_required:
self.application.reboot_required = True
elif self.application.settings.get_boolean("hide-window-after-update"):
Gdk.threads_enter()
self.application.window.hide()
Gdk.threads_leave()
if [pkg for pkg in PRIORITY_UPDATES if pkg in packages]:
# Restart
self.application.uninhibit_pm()
self.application.logger.write("Mintupdate was updated, restarting it...")
self.application.logger.close()
self.application.restart_app()
return
# Refresh
needs_refresh = True
else:
Gdk.threads_enter()
self.application.set_status(_("Could not install the security updates"), _("Could not install the security updates"), "mintupdate-error-symbolic", True)
Gdk.threads_leave()
if update_flatpaks and proceed:
self.application.flatpak_updater.perform_updates()
if self.application.flatpak_updater.error is not None:
self.application.set_status_message_from_thread(self.application.flatpak_updater.error)
needs_refresh = True
if proceed and len(cinnamon_spices) > 0:
Gdk.threads_enter()
spices_install_window = Gtk.Window(title=_("Updating Cinnamon Spices"),
default_width=400,
default_height=100,
deletable=False,
skip_taskbar_hint=True,
skip_pager_hint=True,
resizable=False,
modal=True,
window_position=Gtk.WindowPosition.CENTER_ON_PARENT,
transient_for=self.application.window)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
spacing=10,
margin=10,
valign=Gtk.Align.CENTER)
spinner = Gtk.Spinner(active=True, height_request=32)
box.pack_start(spinner, False, False, 0)
label = Gtk.Label()
box.pack_start(label, False, False, 0)
spices_install_window.add(box)
spices_install_window.show_all()
Gdk.threads_leave()
need_cinnamon_restart = False
for update in cinnamon_spices:
Gdk.threads_enter()
label.set_text("%s (%s)" % (update.name, update.uuid))
Gdk.threads_leave()
self.application.cinnamon_updater.upgrade(update)
try:
if self.application.cinnamon_updater.spice_is_enabled(update):
need_cinnamon_restart = True
except:
need_cinnamon_restart = True
if (not self.reboot_required) \
and os.getenv("XDG_CURRENT_DESKTOP") in ["Cinnamon", "X-Cinnamon"] \
and need_cinnamon_restart:
Gdk.threads_enter()
label.set_text(_("Restarting Cinnamon"))
spinner.hide()
Gdk.threads_leave()
# Keep the dialog from looking funky before it freezes during the restart
time.sleep(.25)
subprocess.run(["cinnamon-dbus-command", "RestartCinnamon", "0"])
# We want to be back from the restart before refreshing or else it looks bad. Restarting can
# take a bit longer than the restart command before it's properly 'running' again.
time.sleep(2)
Gdk.threads_enter()
spices_install_window.destroy()
Gdk.threads_leave()
needs_refresh = True
self.application.uninhibit_pm()
if needs_refresh:
self.application.refresh()
except Exception as e:
print (e)
self.application.logger.write_error("Exception occurred in the install thread: " + str(sys.exc_info()[0]))
Gdk.threads_enter()
self.application.set_status(_("Could not install the security updates"), _("Could not install the security updates"), "mintupdate-error-symbolic", True)
self.application.logger.write_error("Could not install security updates")
Gdk.threads_leave()
self.application.uninhibit_pm()
class RefreshThread(threading.Thread):
def __init__(self, application, root_mode=False):
threading.Thread.__init__(self, name="mintupdate-refresh-thread")
self.root_mode = root_mode
self.application = application
self.running = False
def cleanup(self):
# cleanup when finished refreshing
self.application.refreshing = False
self.application.uninhibit_pm()
if not self.running:
return
self.application.cache_watcher.resume()
Gdk.threads_enter()
self.application.status_refreshing_spinner.stop()
# Make sure we're never stuck on the status_refreshing page:
if self.application.stack.get_visible_child_name() == "status_refreshing":
self.application.stack.set_visible_child_name("updates_available")
# Reset cursor
if not self.application.app_hidden():
self.application.window.get_window().set_cursor(None)
self.application.paned.set_position(self.vpaned_position)
self.application.toolbar.set_sensitive(True)
self.application.menubar.set_sensitive(True)
Gdk.threads_leave()
def show_window(self):
Gdk.threads_enter()
self.application.window.present_with_time(Gtk.get_current_event_time())
Gdk.threads_leave()
def on_notification_action(self, notification, action_name, data):
if action_name == "show_updates":
os.system("/usr/lib/linuxmint/mintUpdate/mintUpdate.py show &")
elif action_name == "enable_automatic_updates":
self.application.open_preferences(None, show_automation=True)
def run(self):
if self.application.refreshing:
return False
if self.application.updates_inhibited:
self.application.logger.write("Updates are inhibited, skipping refresh")
self.show_window()
return False
self.application.refreshing = True
self.running = True
if self.root_mode:
while self.application.dpkg_locked():
self.application.logger.write("Package management system locked by another process, retrying in 60s")
time.sleep(60)
self.application.inhibit_pm("Refreshing available updates")
self.application.cache_watcher.pause()
Gdk.threads_enter()
self.vpaned_position = self.application.paned.get_position()
for child in self.application.infobar.get_children():
child.destroy()
if self.application.reboot_required:
self.application.show_infobar(_("Reboot required"),
_("You have installed updates that require a reboot to take effect, please reboot your system as soon as possible."), icon="system-reboot-symbolic")
Gdk.threads_leave()
try:
if self.root_mode:
self.application.logger.write("Starting refresh (retrieving lists of updates from remote servers)")
else:
self.application.logger.write("Starting refresh (local only)")
Gdk.threads_enter()
# Switch to status_refreshing page
self.application.status_refreshing_spinner.start()
self.application.stack.set_visible_child_name("status_refreshing")
if not self.application.app_hidden():
self.application.window.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH))
self.application.toolbar.set_sensitive(False)
self.application.menubar.set_sensitive(False)
self.application.builder.get_object("tool_clear").set_sensitive(False)
self.application.builder.get_object("tool_select_all").set_sensitive(False)
self.application.builder.get_object("tool_apply").set_sensitive(False)
# Starts the blinking
self.application.set_status(_("Checking for package updates"), _("Checking for updates"), "mintupdate-checking-symbolic", not self.application.settings.get_boolean("hide-systray"))
Gdk.threads_leave()
model = Gtk.TreeStore(bool, str, str, str, str, GObject.TYPE_LONG, str, str, str, str, str, object)
# UPDATE_CHECKED, UPDATE_DISPLAY_NAME, UPDATE_OLD_VERSION, UPDATE_NEW_VERSION, UPDATE_SOURCE,
# UPDATE_SIZE, UPDATE_SIZE_STR, UPDATE_TYPE_PIX, UPDATE_TYPE, UPDATE_TOOLTIP, UPDATE_SORT_STR, UPDATE_OBJ
model.set_sort_column_id(UPDATE_SORT_STR, Gtk.SortType.ASCENDING)
# Refresh the APT cache
if self.root_mode:
refresh_command = ["sudo", "/usr/bin/mint-refresh-cache"]
if (not self.application.app_hidden()) and os.environ.get("XDG_SESSION_TYPE", "x11") == "x11":
refresh_command.extend(["--use-synaptic",
str(self.application.window.get_window().get_xid())])
subprocess.run(refresh_command)
self.application.settings.set_int("refresh-last-run", int(time.time()))
if CINNAMON_SUPPORT:
if self.root_mode:
self.application.logger.write("Refreshing available Cinnamon updates from the server")
self.application.set_status_message_from_thread(_("Checking for Cinnamon spices"))
for spice_type in cinnamon.updates.SPICE_TYPES:
try:
self.application.cinnamon_updater.refresh_cache_for_type(spice_type)
except:
self.application.logger.write_error("Something went wrong fetching Cinnamon %ss: %s" % (spice_type, str(sys.exc_info()[0])))
print("-- Exception occurred fetching Cinnamon %ss:\n%s" % (spice_type, traceback.format_exc()))
if FLATPAK_SUPPORT:
if self.root_mode:
self.application.logger.write("Refreshing available Flatpak updates")
self.application.set_status_message_from_thread(_("Checking for Flatpak updates"))
self.application.flatpak_updater.refresh()
self.application.set_status_message_from_thread(_("Processing updates"))
if os.getenv("MINTUPDATE_TEST") is None:
output = subprocess.run("/usr/lib/linuxmint/mintUpdate/checkAPT.py", stdout=subprocess.PIPE).stdout.decode("utf-8")
else:
if os.path.exists("/usr/share/linuxmint/mintupdate/tests/%s.test" % os.getenv("MINTUPDATE_TEST")):
output = subprocess.run("sleep 1; cat /usr/share/linuxmint/mintupdate/tests/%s.test" % os.getenv("MINTUPDATE_TEST"), shell=True, stdout=subprocess.PIPE).stdout.decode("utf-8")
else:
output = subprocess.run("/usr/lib/linuxmint/mintUpdate/checkAPT.py", stdout=subprocess.PIPE).stdout.decode("utf-8")
error_found = False
# Return on error
if "CHECK_APT_ERROR" in output:
error_found = True
self.application.logger.write_error("Error in checkAPT.py, could not refresh the list of updates")
try:
error_msg = output.split("Error: ")[1].replace("E:", "\n").strip()
if "apt.cache.FetchFailedException" in output and " changed its " in error_msg:
error_msg += "\n\n%s" % _("Run 'apt update' in a terminal window to address this")
except:
error_msg = ""
# Check presence of Mint layer
(mint_layer_found, error_msg) = self.check_policy()
if os.getenv("MINTUPDATE_TEST") == "layer-error" or (not mint_layer_found):
error_found = True
self.application.logger.write_error("Error: The APT policy is incorrect!")
label1 = _("Your APT configuration is corrupt.")
label2 = _("Do not install or update anything, it could break your operating system!")
label3 = _("To switch to a different Linux Mint mirror and solve this problem, click OK.")
msg = _("Your APT configuration is corrupt.")
if error_msg:
error_msg = "\n\n%s\n%s" % (_("APT error:"), error_msg)
else:
error_msg = ""
Gdk.threads_enter()
self.application.show_infobar(_("Please switch to another Linux Mint mirror"),
msg, Gtk.MessageType.ERROR,
callback=self._on_infobar_mintsources_response)
self.application.set_status(_("Could not refresh the list of updates"),
"%s\n%s" % (label1, label2), "mintupdate-error-symbolic", True)
self.application.builder.get_object("label_error_details").set_markup("<b>%s\n%s\n%s%s</b>" % (label1, label2, label3, error_msg))
Gdk.threads_leave()
if error_found:
Gdk.threads_enter()
self.application.set_status(_("Could not refresh the list of updates"),
"%s%s%s" % (_("Could not refresh the list of updates"), "\n\n" if error_msg else "", error_msg),
"mintupdate-error-symbolic", True)
self.application.stack.set_visible_child_name("status_error")
if error_msg:
self.application.builder.get_object("label_error_details").set_text(error_msg)
self.application.builder.get_object("label_error_details").show()
Gdk.threads_leave()
self.cleanup()
return False
# Look at the updates one by one
updates = []
num_visible = 0
num_security = 0
num_software = 0
download_size = 0
is_self_update = False
tracker = UpdateTracker(self.application.settings, self.application.logger)
lines = output.split("---EOL---")
if len(lines):
for line in lines:
if "###" not in line:
continue
# Create update object
update = Update(package=None, input_string=line, source_name=None)
updates.append(update)
if tracker.active and update.type != "unstable":
tracker.update(update)
# Check if self-update is needed
if update.source_name in PRIORITY_UPDATES:
is_self_update = True
iter = model.insert_before(None, None)
model.row_changed(model.get_path(iter), iter)
model.set_value(iter, UPDATE_CHECKED, True)
download_size += update.size
shortdesc = update.short_description
if len(shortdesc) > 100:
try:
shortdesc = shortdesc[:100]
# Remove the last word.. in case we chomped
# a word containing an ê character..
# if we ended up with &.. without the code and ; sign
# pango would fail to set the markup
words = shortdesc.split()
shortdesc = " ".join(words[:-1]) + "..."
except:
pass
if self.application.settings.get_boolean("show-descriptions"):
model.set_value(iter, UPDATE_DISPLAY_NAME,
"<b>%s</b>\n%s" % (GLib.markup_escape_text(update.display_name), GLib.markup_escape_text(shortdesc)))
else:
model.set_value(iter, UPDATE_DISPLAY_NAME,
"<b>%s</b>" % GLib.markup_escape_text(update.display_name))
origin = update.origin
origin = origin.replace("linuxmint", "Linux Mint").replace("ubuntu", "Ubuntu").replace("LP-PPA-", "PPA ").replace("debian", "Debian")
type_sort_key = 0 # Used to sort by type
if update.type == "kernel":
tooltip = _("Kernel update")
type_sort_key = 2
num_security += 1
elif update.type == "security":
tooltip = _("Security update")
type_sort_key = 1
num_security += 1
elif update.type == "unstable":
tooltip = _("Unstable software. Only apply this update to help developers beta-test new software.")
type_sort_key = 7
else:
num_software += 1
if origin in ["Ubuntu", "Debian", "Linux Mint", "Canonical"]:
tooltip = _("Software update")
type_sort_key = 3
else:
update.type = "3rd-party"
tooltip = "%s\n%s" % (_("3rd-party update"), origin)
type_sort_key = 4