-
Notifications
You must be signed in to change notification settings - Fork 0
/
appindicator.py
executable file
·429 lines (325 loc) · 14.1 KB
/
appindicator.py
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
#! /usr/bin/env python
from gi.repository import Gtk, GObject
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Pango
from gi.repository import Notify
import os
import time
import json
import bkup
CONFIGPATH = os.path.join(os.path.expanduser('~'), '.bkup.yaml')
LOGFILEPATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bkuplog.json')
class Indicator:
def __init__(self):
self.ind = appindicator.Indicator.new (
"Bkup",
"brasero-disc-00",
appindicator.IndicatorCategory.APPLICATION_STATUS)
self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)
self.ind.set_attention_icon("brasero-disc-100")
Notify.init('bkup')
self.bkup = bkup.Bkup(CONFIGPATH, bkup.Tarsnap())
# used to check when to remove package file size diff labels
# also used to check if file size diffs have been calculated
self.removeDiffLabelTime = 0
# used to check if backing up is in progress
self.backingup = False
# used to store number of archives that are older than 30 days
# a value of -1 means the number of archives have not been counted
self.numOldArchives = -1
self.logFile = LogFile(LOGFILEPATH)
GObject.timeout_add(60 * 1000, self.updateIconStatus)
# create the menu
menu = Gtk.Menu()
# set a 'title' (disabled menu item)
self.packageTitle = Gtk.MenuItem('Packages from bkup.yaml:')
self.packageTitle.set_sensitive(False)
menu.append(self.packageTitle)
# create a menu item for each package
# also store data about each package in self.packages
self.packages = dict()
for package in self.bkup.getPackageNames():
menuItem = Gtk.CheckMenuItem(package)
self.packages[package] = menuItem
menuItem.set_active(True)
menu.append(menuItem)
# create the backup and diff calc menu items
sep = Gtk.SeparatorMenuItem()
menu.append(sep)
calculateDiffBtn = Gtk.MenuItem('Calculate File Diffs')
calculateDiffBtn.connect('activate', self.calculateDiffs)
menu.append(calculateDiffBtn)
backupBtn = Gtk.MenuItem('Backup Selected Packages')
backupBtn.connect('activate', self.backupSelected)
menu.append(backupBtn)
# create old archive checking and deleting buttons
sep = Gtk.SeparatorMenuItem()
menu.append(sep)
calculateOldBtn = Gtk.MenuItem('Check Number Of Old Archives')
calculateOldBtn.connect('activate', self.checkOldArchives)
menu.append(calculateOldBtn)
deleteOldBtn = Gtk.MenuItem('Delete archives > 30 days old')
deleteOldBtn.connect('activate', self.deleteOldArchives)
menu.append(deleteOldBtn)
# create unsensitive labels for stats
sep = Gtk.SeparatorMenuItem()
menu.append(sep)
self.lastBackupLabel = Gtk.MenuItem('Last backup: unkown')
self.lastBackupLabel.set_sensitive(False)
self.setLastBackupLabel()
menu.append(self.lastBackupLabel)
self.lastBackupFileSize = Gtk.MenuItem('Last backup size: unkown')
self.lastBackupFileSize.set_sensitive(False)
self.setLastBackupFileSizeLabel()
menu.append(self.lastBackupFileSize)
self.totalUsageLabel = Gtk.MenuItem('Total Usage: unkown')
self.totalUsageLabel.set_sensitive(False)
self.setTotalUsageLabel()
menu.append(self.totalUsageLabel)
self.oldArchivesLabel = Gtk.MenuItem('Archives > 30 days old: unknown')
self.oldArchivesLabel.set_sensitive(False)
self.setOldArchivesLabel()
menu.append(self.oldArchivesLabel)
# create the quit menu item
sep = Gtk.SeparatorMenuItem()
menu.append(sep)
quitBtn = Gtk.MenuItem('Quit')
quitBtn.connect('activate', self.closeApp)
menu.append(quitBtn)
self.ind.set_menu(menu)
menu.show_all()
def updateIcon(self, percentage):
# percentage is between 0 and 1
self.ind.set_icon("brasero-disc-" + "%02d" % int(round(percentage, 1) * 100))
def getSelectedPackages(self):
selected = []
for package in self.packages.keys():
if self.packages[package].get_active():
selected.append(package)
return selected
def backupSelected(self, menuItem):
if self.removeDiffLabelTime == 0:
totalDiffs = self.calculateDiffs(None, False)
if totalDiffs > 50 * 1000000:
msg = Notify.Notification.new('Selected packages total file change is above 50Mb', 'Click backup selected packages again if you want to ignore this')
msg.show()
return False
self.packageTitle.set_label('backing up...')
self.setMenuEnabled(False)
self.backingup = True
self.updateIconStatus()
beforeBackupSize = self.bkup.getTotalUsage()
selected = self.getSelectedPackages()
success = True
packageTimes = []
for package in selected:
while Gtk.events_pending():
Gtk.main_iteration()
self.updateIcon(float(selected.index(package)) / float(len(selected)))
#TODO: do this in a new thread
output = self.bkup.backupPackage(package)
if output != True:
print('error, breaking from backups')
print(output)
self.createErrorDialog(output)
success = False
break
else:
packageTimes.append({'name': package, 'time': int(time.time())})
self.packageTitle.set_label('Packages from bkup.yaml:')
self.setMenuEnabled(True)
self.updateIcon(0)
self.removeDiffLabels()
self.backingup = False
backupSizeDiff = self.bkup.getTotalUsage() - beforeBackupSize
self.updateLog(packageTimes, backupSizeDiff)
if success:
msg = Notify.Notification.new('Selected packages backed up', 'Bkup')
msg.show()
def calculateDiffs(self, menuItem, showNotification=True):
self.setMenuEnabled(False)
self.packageTitle.set_label('Calculating file diffs...')
while Gtk.events_pending():
Gtk.main_iteration()
selected = self.getSelectedPackages()
totalDiff = 0
for package in selected:
diff = self.bkup.getFileSizeDiff(package)
totalDiff += diff
print(self.bkup.humanPrint(diff))
humanDiff = self.bkup.humanPrint(diff)
newLabel = package + ' (' + humanDiff + ' change)'
print(self.packages[package].set_label(newLabel))
self.setMenuEnabled(True)
self.packageTitle.set_label('Packages from bkup.yaml:')
self.removeDiffLabelTime = time.time() + 60 * 5
GObject.timeout_add(60 * 1000, self.checkDiffLabelRemovalTime)
if showNotification:
msg = Notify.Notification.new('Calculated file diffs', 'Bkup')
msg.show()
return totalDiff
def checkOldArchives(self, menuItem, showNotification=True):
if showNotification:
msg = Notify.Notification.new('recalculating number of archives older than 30 days', 'Bkup')
msg.show()
# TODO: do this in new thread so the user can click other buttons while
# this is running. Or disable other buttons
self.oldArchives = self.bkup.filterOld(30)
self.numOldArchives = len(self.oldArchives)
if showNotification:
msg = Notify.Notification.new('Number of archives older than 30 days: '
+ str(self.numOldArchives))
msg.show()
self.setOldArchivesLabel()
return self.oldArchives
def deleteOldArchives(self, menuItem):
if self.numOldArchives > 0:
msg = Notify.Notification.new('Deleting ' + str(self.numOldArchives)
+ ' archives', 'Bkup')
msg.show()
output = self.bkup.deleteArchives(self.oldArchives)
if output == True:
msg = Notify.Notification.new('Deleted ' + str(self.numOldArchives)
+ ' archives', 'Bkup')
msg.show()
self.numOldArchives = 0
else:
self.createErrorDialog(output)
self.numOldArchives = -1
setOldArchivesLabel()
elif self.numOldArchives == 0:
msg = Notify.Notification.new('No archives older than 30 days', 'Bkup')
msg.show()
else:
self.createErrorDialog('To delete old archives, '
+ 'it is first required to check number of old archives')
def updateLog(self, packageTimes, backupSize):
log = self.logFile.read()
if log == False:
# log file does not exist
log = {'packages': {}}
for package in packageTimes:
log['packages'][package['name']] = package['time']
if backupSize > 0:
log['lastBackupFileSize'] = backupSize
self.logFile.write(log)
self.setLastBackupLabel()
self.setTotalUsageLabel()
self.setLastBackupFileSizeLabel()
self.updateIconStatus()
def setMenuEnabled(self, enable):
for package in self.packages:
self.packages[package].set_sensitive(enable)
def checkDiffLabelRemovalTime(self):
if self.removeDiffLabelTime < time.time():
self.removeDiffLabels()
self.removeDiffLabelTime = 0
return False
return True
def removeDiffLabels(self):
self.removeDiffLabelTime = 0
for package in self.packages.keys():
self.packages[package].set_label(package)
def setLastBackupLabel(self):
lastBackupTime = self.logFile.getLastBackupTime()
if lastBackupTime == False:
self.lastBackupLabel.set_label('Last: unkown')
else:
self.lastBackupLabel.set_label('Last: ' + time.ctime(lastBackupTime))
def setLastBackupFileSizeLabel(self):
log = self.logFile.read()
if type(log) == dict and 'lastBackupFileSize' in log:
self.lastBackupFileSize.set_label('Last backup size: ' + self.bkup.humanPrint(log['lastBackupFileSize']))
else:
self.lastBackupFileSize.set_label('Last backup size: unknown')
def setTotalUsageLabel(self):
totalUsage = self.bkup.getTotalUsage()
if type(totalUsage) == int:
self.totalUsageLabel.set_label('Total usage: ' + self.bkup.humanPrint(totalUsage))
else:
self.totalUsageLabel.set_label('Total usage: unknown')
def setOldArchivesLabel(self):
if self.numOldArchives != -1:
self.oldArchivesLabel.set_label('Archives older than 30 days: '
+ str(self.numOldArchives))
else:
self.oldArchivesLabel.set_label('Archives > 30 days old: unknown')
def updateIconStatus(self):
# this function changes the icon status if there has been no backup
# done within the last 24 hours. This 24 hours is a constant which will
# be optionally disabled or changed from a config file in the future.
# this is the only function that should be changing the icon status
if self.backingup:
# while backing up, the icon status is active
self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)
return True
lastBackupTime = self.logFile.getLastBackupTime()
remindConstant = 60 * 60 * 24 # 24 hours in seconds
if lastBackupTime == False:
return self.ind.set_status(appindicator.IndicatorStatus.ATTENTION)
if lastBackupTime + remindConstant > int(time.time()):
self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)
else:
self.ind.set_status(appindicator.IndicatorStatus.ATTENTION)
return True
def closeApp(self, menuItem):
Gtk.main_quit()
def createErrorDialog(self, errorMsg):
dialog = Gtk.Dialog(title="Bkup Error", parent=None, flags=0, buttons=(Gtk.STOCK_OK, Gtk.ResponseType.OK))
dialog.set_default_size(700, 400)
box = dialog.get_content_area()
label = Gtk.Label("There was an error with bkup:")
label.set_alignment(0, 0.5)
label.set_padding(20, 0)
textview = Gtk.TextView()
fontdesc = Pango.FontDescription("monospace 10")
textview.modify_font(fontdesc)
textview.set_editable(False)
textbuf = Gtk.TextBuffer()
textbuf.set_text(errorMsg)
textview.set_buffer(textbuf)
scroll = Gtk.ScrolledWindow()
scroll.add(textview)
alignment = Gtk.Alignment()
alignment.set_padding(0, 10, 20, 20)
alignment.add(scroll)
box.pack_start(label, expand=False, fill=False, padding=10)
box.pack_start(alignment, expand=True, fill=True, padding=0)
box.show_all()
dialog.run()
dialog.destroy()
class LogFile:
def __init__(self, logPath):
self.logPath = logPath
def read(self):
log = True
try:
logFile = open(self.logPath)
log = logFile.read()
logFile.close()
except IOError:
log = False
if log == False:
return False
try:
log = json.loads(log)
except:
log = False
return log
def write(self, newLog):
# newLog should be of type dict as it gets converted to str in this function
logFile = open(self.logPath, 'w')
logFile.write(json.dumps(newLog))
logFile.close()
def getLastBackupTime(self):
log = self.read()
if log == False:
return False
biggest = 0
for packageTime in log['packages'].values():
if biggest < packageTime:
biggest = packageTime
return biggest
if __name__ == "__main__":
indicator = Indicator()
Gtk.main()