forked from slytomcat/yandex-disk-indicator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyandex-disk-indicator.py
1520 lines (1400 loc) · 74.3 KB
/
yandex-disk-indicator.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
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/env python3
# -*- coding: utf-8 -*-
#
# Yandex.Disk indicator
appVer = '1.9.1'
#
# Copyright 2014-2016 Sly_tom_cat <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os import remove, makedirs, getpid, geteuid, getenv
from pyinotify import ProcessEvent, WatchManager, Notifier, IN_MODIFY
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk
require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3 as appIndicator
require_version('Notify', '0.7')
from gi.repository.Notify import init as NotifyInit, Notification as NotifyNotification
from gi.repository import GLib
from gi.repository.GdkPixbuf import Pixbuf
from subprocess import check_output, call, CalledProcessError
from re import findall as reFindall, sub as reSub, search as reSearch, M as reM, S as reS
from argparse import ArgumentParser
from gettext import translation
from logging import basicConfig, getLogger
from fcntl import flock as filelock, LOCK_UN, LOCK_EX, LOCK_NB
from os.path import exists as pathExists, join as pathJoin, relpath as relativePath
from shutil import copy as fileCopy
from datetime import datetime
from webbrowser import open_new as openNewBrowser
from signal import signal, SIGTERM
from sys import exit as sysExit
#### Common utility functions and classes
def copyFile(src, dst):
try:
fileCopy (src, dst)
except:
logger.error("File Copy Error: from %s to %s" % (src, dst))
def deleteFile(dst):
try:
remove(dst)
except:
logger.error('File Deletion Error: %s' % dst)
def makedirs(dst):
try:
makedirs(dst, exist_ok=True)
except:
logger.error('Dirs creation Error: %s' % dst)
class CVal(object): # Multivalue helper
''' Class to work with value that can be None, scalar item or list of items depending
of number of elementary items added to it or it contain. '''
def __init__(self, initialValue=None):
self.set(initialValue) # store initial value
self.index = None
def get(self): # It just returns the current value of cVal
return self.val
def set(self, value): # Set internal value
self.val = value
if isinstance(self.val, list) and len(self.val) == 1:
self.val = self.val[0]
return self.val
def add(self, item): # Add item
if isinstance(self.val, list): # Is it third, fourth ... value?
self.val.append(item) # Just append new item to list
elif self.val is None: # Is it first item?
self.val = item # Just store item
else: # It is the second item.
self.val = [self.val, item] # Convert scalar value to list of items.
return self.val
def remove(self, item):
if isinstance(self.val, list):
self.val.remove(item)
if len(self.val) == 1:
self.val = self.val[0]
elif self.val is None:
raise ValueError
else:
if self.val == item:
self.val = None
else:
raise ValueError
return self.val
def __iter__(self): # cVal iterator object initialization
if isinstance(self.val, list): # Is CVal a list?
self.index = -1
elif self.val is None: # Is CVal not defined?
self.index = None
else: # CVal is scalar type.
self.index = -2
return self
def __next__(self): # cVal iterator support
if self.index is None: # Is CVal not defined?
raise StopIteration # Stop iterations
self.index += 1
if self.index >= 0: # Is CVal a list?
if self.index < len(self.val): # Is there a next element in list?
return self.val[self.index]
else: # There is no more elements in list.
self.index = None
raise StopIteration # Stop iterations
else: # CVal has scalar type.
self.index = None # Remember that there is no more iterations possible
return self.val
def __str__(self): # String representation of CVal
return str(self.val)
def __getitem__(self, index): # Access to cVal items by index
if isinstance(self.val, list):
return self.val[index] # It raises IndexError when index is out of range(len(cVal))
elif self.val is None:
raise IndexError # None value cannot be received by any index
elif index in [0, -1]: # cVal is scalar and index is 0 (first) or -1 (last)?
return self.val
else:
raise IndexError
def __setitem__(self, index, value):
if isinstance(self.val, list):
self.val[index] = value
elif self.val is None:
raise IndexError # None value cannot be set by any index
elif index in [0, -1]: # cVal is scalar and index is 0 (first) or -1 (last)?
self.val = value
else:
raise IndexError
def __len__(self): # Length of cVal
if isinstance(self.val, list):
return len(self.val)
return 0 if self.val is None else 1
def __contains__(self, item): # 'in' opertor function
if isinstance(self.val, list):
return item in self.val
elif self.val is None:
return item is None
else:
return self.val == item
def __bool__(self):
return self.val is not None
class Config(dict): # Configuration
def __init__(self, fileName, load=True,
bools=[['true', 'yes', 'y'], ['false', 'no', 'n']],
boolval=['yes', 'no'], usequotes=True, delimiter='='):
#super(Config, self).__init__(self)
self.fileName = fileName
self.bools = bools # Values to detect boolean in self.load
self.boolval = boolval # Values to write boolean in self.save
self.usequotes = usequotes # Use quotes for keys and values in self.save
self.delimiter = delimiter # Use specified delimiter between key and value
self.changed = False # Change flag (for use outside of the class)
if load:
self.load()
def decode(self, value): # Convert string to value before store it
#logger.debug("Decoded value: '%s'"%value)
if value.lower() in self.bools[0]:
value = True
elif value.lower() in self.bools[1]:
value = False
return value
def getValue(self, st): # Find value(s) in string after '='
v = CVal() # Value accumulator
st = st.strip() # Remove starting and ending spaces
if st.startswith(','):
return None # Error: String after '=' starts with comma
while True:
s = reSearch(r'^("[^"]*")|^([^",#]+)', st) # Search for quoted or value without quotes
if s is None:
return None # Error: Nothing found but value expected
start, end = s.span()
vv = st[start: end].strip() # Get found value
if vv.startswith('"'):
vv = vv[1: -1] # Remove quotes
v.add(self.decode(vv)) # Decode and store value
st = st[end: ].lstrip() # Remove value and following spaces from string
if st == '':
return v.get() # EOF normaly reached (after last value in string)
else: # String still contain something
if st.startswith(','): # String is continued with comma?
st = st[1:].lstrip() # Remove comma and following spaces
if st != '': # String is continued after comma?
continue # Continue to search values
#else: # Error: No value after comma
#else: # Error: Next symbol is not comma
return None # Error
def load(self, bools=[['true', 'yes', 'y'], ['false', 'no', 'n']], delimiter='='):
"""
Reads config file to dictionary.
Config file should contain key=value rows.
Key can be quoted or not.
Value can be one item or list of comma-separated items. Each value item can be quoted or not.
When value is a single item then it creates key:value item in dictionary
When value is a list of items it creates key:[value, value,...] dictionary's item.
"""
self.bools = bools
self.delimiter = delimiter
try: # Read configuration file into list of tuples ignoring blank
# lines, lines without delimiter, and lines with comments.
with open(self.fileName) as cf:
res = [reFindall(r'^\s*(.+?)\s*%s\s*(.*)$' % self.delimiter, l)[0]
for l in cf if l and self.delimiter in l and l.lstrip()[0] != '#']
self.readSuccess = True
except:
logger.error('Config file read error: %s' % self.fileName)
self.readSuccess = False
return False
for kv, vv in res: # Parse each line
# Check key
key = reFindall(r'^"([^"]+)"$|^([\w-]+)$', kv)
if key == []:
logger.warning('Wrong key in line \'%s %s %s\'' % (kv, self.delimiter, vv))
else: # Key is OK
key = key[0][0] + key[0][1] # Join two possible keys variants (with and without quotes)
if vv.strip() == '':
logger.warning('No value specified in line \'%s %s %s\'' % (kv, self.delimiter, vv))
else: # Value is not empty
value = self.getValue(vv) # Parse values
if value is None:
logger.warning('Wrong value(s) in line \'%s %s %s\'' % (kv, self.delimiter, vv))
else: # Value is OK
if key in self.keys(): # Check double values
logger.warning(('Double values for one key:\n%s = %s\nand\n%s = %s\n' +
'Last one is stored.') % (key,self[key],key,value))
self[key] = value # Store last value
logger.debug('Config value read as: %s = %s' % (key, str(value)))
logger.info('Config read: %s' % self.fileName)
return True
def encode(self, val): # Convert value to string before save it
if isinstance(val, bool): # Treat Boolean
val = self.boolval[0] if val else self.boolval[1]
if self.usequotes:
val = '"' + val + '"' # Put value within quotes
return val
def save(self, boolval=['yes', 'no'], usequotes=True, delimiter='='):
self.usequotes = usequotes
self.boolval = boolval
self.delimiter = delimiter
try: # Read the file in buffer
with open(self.fileName, 'rt') as cf:
buf = cf.read()
except:
logger.warning('Config file access error, a new file (%s) will be created' % self.fileName)
buf = ''
buf = reSub(r'[\n]*$', '\n', buf) # Remove all ending blank lines except the one.
for key, value in self.items():
if value is None:
res = '' # Remove 'key=value' from file if value is None
logger.debug('Config value \'%s\' will be removed' % key)
else: # Make a line with value
res = ''.join([key , self.delimiter,
''.join([self.encode(val) + ', ' for val in CVal(value)])[:-2] + '\n'])
logger.debug('Config value to save: %s'%res[:-1])
# Find line with key in file the buffer
sRe = reSearch(r'^[ \t]*["]?%s["]?[ \t]*%s.+\n' % (key, self.delimiter), buf, flags=reM)
if sRe is not None: # Value has been found
buf = sRe.re.sub(res, buf) # Replace it with new value
elif res != '': # Value was not found and value is not empty
buf += res # Add new value to end of file buffer
try:
with open(self.fileName, 'wt') as cf:
cf.write(buf) # Write updated buffer to file
except:
logger.error('Config file write error: %s' % self.fileName)
return False
logger.info('Config written: %s' % self.fileName)
self.changed = False # Reset flag of change in not stored config
return True
class Timer(object): # Timer for triggering a function periodically
''' Timer class methods:
__init__ - initialize the timer object with specified interval and handler. Start it
if start value is not False. par - is parameter for handler call.
start - Start timer. Optionally the new interval can be specified and if timer is
already running then the interval is updated (timer restarted with new interval).
update - Updates interval. If timer is running it is restarted with new interval. If it
is not running - then new interval is just stored.
stop - Stop running timer or do nothing if it is not running.
Interface variables:
active - True when timer is currently running, otherwise - False
'''
def __init__(self, interval, handler, par = None, start = True):
self.interval = interval # Timer interval (ms)
self.handler = handler # Handler function
self.par = par # Parameter of handler function
self.active = False # Current activity status
if start:
self.start() # Start timer if required
def start(self, interval = None): # Start inactive timer or update if it is active
if interval is None:
interval = self.interval
if not self.active:
self.interval = interval
if self.par is None:
self.timer = GLib.timeout_add(interval, self.handler)
else:
self.timer = GLib.timeout_add(interval, self.handler, self.par)
self.active = True
#logger.debug('timer started %s %s' %(self.timer, interval))
else:
self.update(interval)
def update(self, interval): # Update interval (restart active, not start if inactive)
if interval != self.interval:
self.interval = interval
if self.active:
self.stop()
self.start()
def stop(self): # Stop active timer
if self.active:
#logger.debug('timer to stop %s' %(self.timer))
GLib.source_remove(self.timer)
self.active = False
class Notification(object): # On-screen notification
def __init__(self, app, mode): # Initialize notification engine
NotifyInit(app)
self.notifier = NotifyNotification()
self.switch(mode)
def send(self, title, message): # Send notification
pass # This method is redefined by switch method
def switch(self, mode=True): # Change show mode, by default switch it on
if mode:
self.send = self._message # Redefine send as real notification routine
else:
self.send = lambda t, m: None # Redefine send as fake routine
def _message(self, t, m): # Show on-screen notification message
global logoPath
logger.debug('Message: %s | %s' % (t, m))
try:
self.notifier.update(t, m, logoPath) # Update notification
self.notifier.show() # Display new notification
except:
logger.error('Message engine failure')
#### Main daemon/indicator classes
class YDDaemon(object): # Yandex.Disk daemon interface
'''
This is the fully automated class that serves as daemon interface.
Public methods:
__init__ - Handles initialization of the object and as a part - auto-start daemon if it
is required by configuration settings.
getOuput - Provides daemon output (in user language when optional parameter userLang is
True)
start - Starts daemon if it is not started yet
stop - Stops running daemon
exit - Handles 'Stop on exit' facility according to daemon configuration settings.
change - Call back function for handling daemon status changes outside the class.
It have to be redefined by UI update routine.
The parameters of the call - status values dictionary (see vars description below)
and the UpdateEvent object with with 5 boolean values:
stat is True when status has been changed,
prog is True when synchronization progress has been changed,
size is True when some of sizes has been changed,
last is True when list of last synchronized has been changed,
init is True when initial update event is raised.
Class interface variables:
config - The daemon configuration dictionary (object of _DConfig(Config) class)
vars - status values dictionary with following keys:
'status' - current daemon status
'progress' - synchronization progress or ''
'laststatus' - previous daemon status
'total' - total Yandex disk space
'used' - currently used space
'free' - available space
'trash' - size of trash
'lastitems' - list of last synchronized items or []
ID - the daemon identity string (empty in single daemon configuration)
'''
# Default daemon status values
_dvals = {'status':'none', 'progress':'', 'laststatus':'none', 'total':'...',
'used':'...', 'free':'...', 'trash':'...', 'lastitems':[]}
class UpdateEvent(object): # Changes control class
def __init__(self):
self.reset()
def reset(self): # Set initial values for object variables
self.stat = False # It become True when status changed
self.prog = False # It become True when synchronization progress changed
self.size = False # It become True when some sizes values changed
self.last = False # It become True when when list of last synchronized changed
self.init = False # It become True when initialization event raised
def __bool__(self): # Boolean representation of object
return self.stat or self.prog or self.size or self.last or self.init
def __str__(self): # String representation of object
string = (('stat, ' if self.stat else '') +
('prog, ' if self.prog else '') +
('size, ' if self.size else '') +
('last, ' if self.last else '') +
('init, ' if self.init else ''))
return '{' + (string[: -2] if string != '' else '')+'}'
class _Watcher(object): # Daemon iNotify watcher
'''
iNotify watcher object for monitor of changes daemon internal log for the fastest
reaction on status change.
'''
def __init__(self, handler, par=None):
# Initialize iNotify watcher
class _EH(ProcessEvent): # Event handler class for iNotifier
def process_IN_MODIFY(self, event):
handler(par)
self._watchMngr = WatchManager() # Create watch manager
# Create PyiNotifier
self._iNotifier = Notifier(self._watchMngr, _EH(), timeout=0.5)
# Timer will call iNotifier handler every .7 seconds (not started initially)
self._timer = Timer(700, self._iNhandle, start=False)
def _iNhandle(self): # iNotify working routine (called by timer)
while self._iNotifier.check_events():
self._iNotifier.read_events()
self._iNotifier.process_events()
return True
def start(self, path): # Activate iNotify watching
# Prepare path
self._path = pathJoin(path.replace('~', userHome), '.sync/cli.log')
# Add watch
self._watch = self._watchMngr.add_watch(self._path, IN_MODIFY, rec = False)
# Activate timer
self._timer.start()
def stop(self): # Stop iNotify watching
# Stop timer
self._timer.stop()
# Remove watch
self._watchMngr.rm_watch(self._watch[self._path])
class _DConfig(Config): # Redefined class for daemon config
def save(self): # Update daemon config file
# Make a new Config object
fileConfig = Config(self.fileName, load=False)
# Copy values that could be changed to the new Config object and convert representation
ro = self.get('read-only', False)
fileConfig['read-only'] = '' if ro else None
fileConfig['overwrite'] = '' if self.get('overwrite', False) and ro else None
fileConfig['startonstartofindicator'] = self.get('startonstartofindicator', True)
fileConfig['stoponexitfromindicator'] = self.get('stoponexitfromindicator', False)
exList = self.get('exclude-dirs', None)
fileConfig['exclude-dirs'] = (None if exList is None else
''.join([v + ', ' for v in CVal(exList)])[:-2])
# Store changed values
fileConfig.save()
self.changed=False
def load(self): # Get daemon config from its config file
if super(YDDaemon._DConfig, self).load(): # Load config from file
# Convert values representations
self['read-only'] = (self.get('read-only', None) == '')
self['overwrite'] = (self.get('overwrite', None) == '')
self.setdefault('startonstartofindicator', True) # New value to start daemon individually
self.setdefault('stoponexitfromindicator', False) # New value to stop daemon individually
exDirs = self.setdefault('exclude-dirs', None)
if exDirs is not None and not isinstance(exDirs, list):
# Additional parsing required when quoted value like "dir,dir,dir" is specified.
# When the value specified without quotes it will be already list value [dir, dir, dir].
self['exclude-dirs'] = self.getValue(exDirs)
return True
else:
return False
def __init__(self, cfgFile, ID): # Check that daemon installed and configured
'''
cfgFile - full path to config file
ID - identity string '#<n> ' in multi-instance environment or
'' in single instance environment'''
self.ID = ID # Remember daemon identity
if not pathExists('/usr/bin/yandex-disk'):
self._errorDialog('NOTINSTALLED')
appExit('Daemon is not installed')
# Try to read Yandex.Disk configuration file and make sure that it is correctly configured
self.config = self._DConfig(cfgFile, load=False)
while not (self.config.load() and
pathExists(self.config.get('dir', '')) and
pathExists(self.config.get('auth', ''))):
if self._errorDialog('NOCONFIG') != 0:
if ID != '':
self.config['dir'] = ''
# Exit from loop in multi-instance configuration
break
else:
appExit('Daemon is not configured')
# Initialize watching staff
self._wTimer = Timer(2000, self._eventHandler, par=False, start=True)
self._tCnt = 0
self._iNtfyWatcher = self._Watcher(self._eventHandler, par=True)
self.update = YDDaemon.UpdateEvent() # Initialize changes control object
self.vals = YDDaemon._dvals.copy() # Load default daemon status values
# Check that daemon is running
out = self.getOutput()
if out != '': # Is daemon running?
self._parseOutput(out) # Update status values
#logger.debug('Init status: ' + self.vals['status'])
#logger.debug('Init vals: ' + str(self.vals))
self.vals['laststatus'] = self.vals['status'] # Set unknown last status as current status
self.update.init = True # Remember that it is initial change event
self.change(self.vals, self.update) # Manually raise initial change event
self._iNtfyWatcher.start(self.config['dir']) # Activate iNotify watcher
else: # Daemon is not running
started = False
if self.config.get('startonstartofindicator', True):
started = not self.start() # Start daemon if it is required
if not started:
self.update.init = True # Remember that it is initial change event
self.vals['status'] = 'none' # Set current status as 'none'
self.vals['laststatus'] = 'none' # Set unknown last status also as 'none'
self.change(self.vals, self.update) # Manually raise initial change event
def _eventHandler(self, iNtf): # Daemon event handler
'''
Handle iNotify and and Timer based events.
After receiving and parsing the daemon output it raises outside change event if daemon changes
at least one of its status values.
It can be called by timer (when iNtf=False) or by iNonifier (when iNtf=True)
'''
# Parse fresh daemon output. Parsing returns true when something changed
if self._parseOutput(self.getOutput()):
logger.debug(self.ID + 'Event raised by' + ('iNtfy ' if iNtf else 'Timer '))
self.change(self.vals, self.update) # Raise outside update event
# --- Handle timer delays ---
if iNtf: # True means that it is called by iNonifier
self._wTimer.update(2000) # Set timer interval to 2 sec.
self._tCnt = 0 # Reset counter as it was triggered not by timer
else: # It called by timer
if self.vals['status'] != 'busy': # In 'busy' keep update interval (2 sec.)
if self._tCnt < 9: # Increase interval up to 10 sec (2 + 8)
self._wTimer.update((2 + self._tCnt)*1000)
self._tCnt += 1 # Increase counter to increase delay next activation.
return True # True is required to continue activations by timer.
def change(self, vals, update): # Redefined update handler
logger.debug('Update event: %s \nValues : %s' % (str(update), str(vals)))
def getOutput(self, userLang=False): # Get result of 'yandex-disk status'
cmd = ['yandex-disk', '-c', self.config.fileName, 'status']
if not userLang: # Change locale settings when it required
cmd = ['env', '-i', "LANG='en_US.UTF8'"] + cmd
try:
output = check_output(cmd, universal_newlines=True)
except:
output = '' # daemon is not running or bad
#logger.debug('output = %s' % output)
return output
def _parseOutput(self, out): # Parse the daemon output
'''
It parses the daemon output and check that something changed from last daemon status.
The self.vals dictionary is updated with new daemon statuses and self.update set represents
the changes in self.vals. It returns True is something changed
Daemon status is converted form daemon raw statuses into internal representation.
Internal status can be on of the following: 'busy', 'idle', 'paused', 'none', 'no_net', 'error'.
Conversion is done by following rules:
- empty status (daemon is not running) converted to 'none'
- statuses 'busy', 'idle', 'paused' are passed 'as is'
- 'index' is ignored (previous status is kept)
- 'no internet access' converted to 'no_net'
- 'error' covers all other errors, except 'no internet access'
'''
self.update.reset() # Reset updates object
# Split output on two parts: list of named values and file list
output = out.split('Last synchronized items:')
if len(output) == 2:
files = output[1]
else:
files = ''
output = output[0].splitlines()
# Make a dictionary from named values (use only lines containing ':')
res = dict([reFindall(r'\s*(.+):\s*(.*)', l)[0] for l in output if ':' in l])
# Parse named status values
for srch, key in (('Synchronization core status', 'status'), ('Sync progress', 'progress'),
('Total', 'total'), ('Used', 'used'), ('Available', 'free'),
('Trash size', 'trash')):
val = res.get(srch, '')
if key == 'status': # Convert status to internal representation
#logger.debug('Raw status: \'%s\', previous status: %s'%(val, self.vals['status']))
# Store previous status
self.vals['laststatus'] = self.vals['status']
# Convert daemon raw status to internal representation
val = (# Convert '' into 'none' status
'none' if val == '' else
# Ignore index status
self.vals['laststatus'] if val == 'index' else
# Rename long error status
'no_net' if val == 'no internet access' else
# pass 'busy', 'idle' and 'paused' statuses 'as is'
val if val in ['busy', 'idle', 'paused'] else
# Status 'error' covers 'error', 'failed to connect to daemon process' and other.
'error')
elif key != 'progress' and val == '': # 'progress' can be '' the rest - can't
val = '...' # Make default filling for empty values
# Check value change and store changed
if self.vals[key] != val: # Check change of value
self.vals[key] = val # Store new value
if key == 'status':
self.update.stat = True # Remember that status changed
elif key == 'progress':
self.update.prog = True # Remember that progress changed
else:
self.update.size = True # Remember that something changed in sizes values
# Parse last synchronized items
buf = reFindall(r".*: '(.*)'\n", files)
# Check if file list has been changed
if self.vals['lastitems'] != buf:
self.vals['lastitems'] = buf # Store the new file list
self.update.last = True # Remember that it is changed
return bool(self.update)
def _errorDialog(self, err): # Show error messages according to the error
global logo
logger.error('Daemon initialization failed: %s', err)
if err == 'NOCONFIG' or err == 'CANTSTART':
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK_CANCEL,
_('Yandex.Disk Indicator: daemon start failed'))
if err == 'NOCONFIG':
dialog.format_secondary_text(_('Yandex.Disk daemon failed to start because it is not' +
' configured properly\n To configure it up: press OK button.\n Press Cancel to exit.'))
else:
dialog.format_secondary_text(_('Yandex.Disk daemon failed to start.' +
'\n Press OK to continue without started daemon or Cancel to exit.'))
else:
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK,
_('Yandex.Disk Indicator: daemon start failed'))
if err == 'NONET':
dialog.format_secondary_text(_('Yandex.Disk daemon failed to start due to network' +
' connection issue. \n Check the Internet connection and try to start daemon again.'))
elif err == 'NOTINSTALLED':
dialog.format_secondary_text(_('Yandex.Disk utility is not installed.\n ' +
'Visit www.yandex.ru, download and install Yandex.Disk daemon.'))
else:
dialog.format_secondary_text(_('Yandex.Disk daemon failed to start due to some ' +
'unrecognized error.'))
dialog.set_default_size(400, 250)
dialog.set_icon(logo)
response = dialog.run()
dialog.destroy()
if err == 'NOCONFIG' and response == Gtk.ResponseType.OK: # Launch Set-up utility
logger.debug('starting configuration utility: %s' % pathJoin(installDir, 'ya-setup'))
retCode = call([pathJoin(installDir,'ya-setup'), self.config.fileName])
elif err == 'CANTSTART' and response == Gtk.ResponseType.OK:
retCode = 0
else:
retCode = 0 if err == 'NONET' else 1
dialog.destroy()
return retCode # 0 when error is not critical or fixed (daemon has been configured)
def start(self): # Execute 'yandex-disk start'
'''
Execute 'yandex-disk start' and return '' if success or error message if not
... but sometime it starts successfully with error message
Additionally it starts iNotify monitoring in case of success start
'''
err = ''
while True:
try: # Try to start
msg = check_output(['yandex-disk', '-c', self.config.fileName, 'start'],
universal_newlines=True)
logger.info('Start success, message: %s' % msg)
err = ''
except CalledProcessError as e:
logger.error('Daemon start failed:%s' % e.output)
if e.output == '': # Probably 'os: no file'
return 'NOTINSTALLED'
err = ('NONET' if 'Proxy' in e.output else
'BADDAEMON' if 'daemon' in e.output else
'NOCONFIG' if "'dir'" in e.output or 'OAuth' in e.output else
err)
# Handle the starting error
if err != '' and self._errorDialog(err) == 0:
self.config.load() # Reload created configuration file & try again
else:
break
if err == '':
self.vals = YDDaemon._dvals.copy() # Initialize default values
self._parseOutput(self.getOutput()) # Parse fresh daemon output
self.update.init = True # Remember that it is initial change event
self.vals['status'] = 'paused' # Set current status to avoid index status
self.vals['laststatus'] = 'none' # Set well known previous status
self.change(self.vals, self.update) # Manually raise initial change event
self._iNtfyWatcher.start(self.config['dir']) # Activate watcher with self.handler
return err
def stop(self): # Execute 'yandex-disk stop'
try:
msg = check_output(['yandex-disk', '-c', self.config.fileName, 'stop'],
universal_newlines=True)
except:
msg = ''
if msg != '':
self._iNtfyWatcher.stop()
self._eventHandler(True) # Manually call evetHanler to raise change event
return True
else:
return False
def exit(self): # Handle daemon/indicator closing
# Stop yandex-disk daemon if it is required by its configuration
if self.vals['status'] != 'none' and self.config.get('stoponexitfromindicator', False):
self.stop()
logger.info('Demon %sstopped'%self.ID)
class Indicator(YDDaemon): # Yandex.Disk appIndicator
def __init__(self, path, ID):
indicatorName = "yandex-disk-%s"%ID[1: -1]
# Create indicator notification engine
self.notify = Notification(indicatorName, config['notifications'])
# Setup icons theme
self.setIconTheme(config['theme'])
# Create timer object for icon animation support (don't start it here)
self.timer = Timer(777, self._iconAnimation, start=False)
# Create App Indicator
self.ind = appIndicator.Indicator.new(indicatorName, self.icon['paused'],
appIndicator.IndicatorCategory.APPLICATION_STATUS)
self.ind.set_status(appIndicator.IndicatorStatus.ACTIVE)
self.menu = self.Menu(self, ID) # Create menu for daemon
self.ind.set_menu(self.menu) # Attach menu to indicator
# Initialize Yandex.Disk daemon connection object
super(Indicator, self).__init__(path, ID)
def change(self, vals, update): # Redefinition of daemon class call-back function
'''
It handles daemon status changes by updating icon, creating messages and also update
status information in menu (status, sizes and list of last synchronized items).
It is called when daemon detects any change of its status.
'''
logger.info(self.ID + 'Change event: %s'%str(update))
# Update information in menu
self.menu.update(vals, update, self.config['dir'])
# Handle daemon status change by icon change
if update.stat or update.init:
logger.info('Status: ' + self.vals['laststatus'] + ' -> ' + self.vals['status'])
self.updateIcon() # Update icon
# Create notifications for status change events
if update.stat:
if vals['laststatus'] == 'none': # Daemon has been started
self.notify.send(_('Yandex.Disk ')+self.ID, _('Yandex.Disk daemon has been started'))
if vals['status'] == 'busy': # Just entered into 'busy'
self.notify.send(_('Yandex.Disk ')+self.ID, _('Synchronization started'))
elif vals['status'] == 'idle': # Just entered into 'idle'
if vals['laststatus'] == 'busy': # ...from 'busy' status
self.notify.send(_('Yandex.Disk ')+self.ID, _('Synchronization has been completed'))
elif vals['status'] =='paused': # Just entered into 'paused'
if vals['laststatus'] != 'none': # ...not from 'none' status
self.notify.send(_('Yandex.Disk ')+self.ID, _('Synchronization has been paused'))
elif vals['status'] == 'none': # Just entered into 'none' from some another status
self.notify.send(_('Yandex.Disk ')+self.ID, _('Yandex.Disk daemon has been stopped'))
else: # status is 'error' or 'no-net'
self.notify.send(_('Yandex.Disk ')+self.ID, _('Synchronization ERROR'))
def setIconTheme(self, theme): # Determine paths to icons according to current theme
global installDir, configPath
theme = 'light' if theme else 'dark'
# Determine theme from application configuration settings
defaultPath = pathJoin(installDir, 'icons', theme)
userPath = pathJoin(configPath, 'icons', theme)
# Set appropriate paths to all status icons
self.icon = dict()
for status in ['idle', 'error', 'paused', 'none', 'no_net', 'busy']:
name = ('yd-ind-pause.png' if status in {'paused', 'none', 'no_net'} else
'yd-busy1.png' if status == 'busy' else
'yd-ind-'+status+'.png')
userIcon = pathJoin(userPath, name)
self.icon[status] = userIcon if pathExists(userIcon) else pathJoin(defaultPath, name)
# userIcon corresponds to busy icon on exit from this loop
# Set theme paths according to existence of first busy icon
self.themePath = userPath if pathExists(userIcon) else defaultPath
def updateIcon(self): # Change indicator icon according to just changed daemon status
# Set icon according to the current status
self.ind.set_icon(self.icon[self.vals['status']])
# Handle animation
if self.vals['status'] == 'busy': # Just entered into 'busy' status
self._seqNum = 2 # Next busy icon number for animation
self.timer.start() # Start animation timer
elif self.timer.active:
self.timer.stop() # Stop animation timer when status is not busy
def _iconAnimation(self): # Changes busy icon by loop (triggered by self.timer)
# Set next animation icon
self.ind.set_icon(pathJoin(self.themePath, 'yd-busy' + str(self._seqNum) + '.png'))
# Calculate next icon number
self._seqNum = self._seqNum % 5 + 1 # 5 icon numbers in loop (1-2-3-4-5-1-2-3...)
return True # True required to continue triggering by timer
class Menu(Gtk.Menu): # Indicator menu
def __init__(self, daemon, ID):
self.daemon = daemon # Store reference to daemon object for future usage
Gtk.Menu.__init__(self) # Create menu
self.ID = ID
if self.ID != '': # Add addition field in multidaemon mode
self.yddir = Gtk.MenuItem(''); self.yddir.set_sensitive(False); self.append(self.yddir)
self.status = Gtk.MenuItem(); self.status.connect("activate", self.showOutput)
self.append(self.status)
self.used = Gtk.MenuItem(); self.used.set_sensitive(False)
self.append(self.used)
self.free = Gtk.MenuItem(); self.free.set_sensitive(False)
self.append(self.free)
self.last = Gtk.MenuItem(_('Last synchronized items'))
self.lastItems = Gtk.Menu() # Sub-menu: list of last synchronized files/folders
self.last.set_submenu(self.lastItems) # Add submenu (empty at the start)
self.append(self.last)
self.append(Gtk.SeparatorMenuItem.new()) # -----separator--------
self.daemon_start = Gtk.MenuItem(_('Start Yandex.Disk daemon'))
self.daemon_start.connect("activate", self.startDaemon)
self.append(self.daemon_start)
self.daemon_stop = Gtk.MenuItem(_('Stop Yandex.Disk daemon'))
self.daemon_stop.connect("activate", self.stopDaemon);
self.append(self.daemon_stop)
self.open_folder = Gtk.MenuItem(_('Open Yandex.Disk Folder'))
self.append(self.open_folder)
open_web = Gtk.MenuItem(_('Open Yandex.Disk on the web'))
open_web.connect("activate", self.openInBrowser, _('https://disk.yandex.com'))
self.append(open_web)
self.append(Gtk.SeparatorMenuItem.new()) # -----separator--------
self.preferences = Gtk.MenuItem(_('Preferences'))
self.preferences.connect("activate", Preferences)
self.append(self.preferences)
open_help = Gtk.MenuItem(_('Help'))
m_help = Gtk.Menu()
help1 = Gtk.MenuItem(_('Yandex.Disk daemon'))
help1.connect("activate", self.openInBrowser, _('https://yandex.com/support/disk/'))
m_help.append(help1)
help2 = Gtk.MenuItem(_('Yandex.Disk Indicator'))
help2.connect("activate", self.openInBrowser,
_('https://github.com/slytomcat/yandex-disk-indicator/wiki'))
m_help.append(help2)
open_help.set_submenu(m_help)
self.append(open_help)
self.about = Gtk.MenuItem(_('About')); self.about.connect("activate", self.openAbout)
self.append(self.about)
self.append(Gtk.SeparatorMenuItem.new()) # -----separator--------
close = Gtk.MenuItem(_('Quit'))
close.connect("activate", self.close)
self.append(close)
self.show_all()
# Define user readable statuses dictionary
self.YD_STATUS = {'idle': _('Synchronized'), 'busy': _('Sync.: '), 'none': _('Not started'),
'paused': _('Paused'), 'no_net': _('Not connected'), 'error':_('Error') }
def update(self, vals, update, yddir): # Update information in menu
# Update status data
if update.stat or update.prog or update.init:
self.status.set_label(_('Status: ') + self.YD_STATUS[vals['status']] +
(vals['progress'] if vals['status'] == 'busy' else ''))
# Update sizes data
if update.size or update.init:
self.used.set_label(_('Used: ') + vals['used'] + '/' + vals['total'])
self.free.set_label(_('Free: ') + vals['free'] + _(', trash: ') + vals['trash'])
# Update last synchronized sub-menu when daemon is running
if (update.last or update.init) and vals['status'] != 'none':
for widget in self.lastItems.get_children(): # Clear last synchronized sub-menu
self.lastItems.remove(widget)
for filePath in vals['lastitems']: # Create new sub-menu items
# Create menu label as file path (shorten it down to 50 symbols when path length > 50
# symbols), with replaced underscore (to disable menu acceleration feature of GTK menu).
widget = Gtk.MenuItem.new_with_label(
(filePath[: 20] + '...' + filePath[-27: ] if len(filePath) > 50 else
filePath).replace('_', u'\u02CD'))
filePath = pathJoin(yddir, filePath) # Make full path to file
if pathExists(filePath):
widget.set_sensitive(True) # If it exists then it can be opened
widget.connect("activate", self.openPath, filePath)
else:
widget.set_sensitive(False) # Don't allow to open non-existing path
self.lastItems.append(widget)
widget.show()
if not vals['lastitems']: # No items in list?
self.last.set_sensitive(False)
else: # There are some items in list
self.last.set_sensitive(True)
logger.debug("Sub-menu 'Last synchronized' has been updated")
# Update 'static' elements of menu
if 'none' in (vals['status'], vals['laststatus']) or update.init:
started = vals['status'] != 'none'
self.status.set_sensitive(started)
self.daemon_stop.set_sensitive(started)
self.daemon_start.set_sensitive(not started)
self.last.set_sensitive(started)
if self.ID != '': # Set daemon identity row in multidaemon mode
folder = (yddir.replace('_', u'\u02CD') if yddir else '< NOT CONFIGURED >')
self.yddir.set_label(self.ID + _(' Folder: ') + folder)
if yddir != '': # Activate Open YDfolder if daemon configured
self.open_folder.connect("activate", self.openPath, yddir)
self.open_folder.set_sensitive(True)
else:
self.open_folder.set_sensitive(False)
def openAbout(self, widget): # Show About window
global logo, indicators
for i in indicators:
i.menu.about.set_sensitive(False) # Disable menu item
aboutWindow = Gtk.AboutDialog()
aboutWindow.set_logo(logo); aboutWindow.set_icon(logo)
aboutWindow.set_program_name(_('Yandex.Disk indicator'))
aboutWindow.set_version(_('Version ') + appVer)
aboutWindow.set_copyright('Copyright ' + u'\u00a9' + ' 2013-' +
datetime.now().strftime("%Y") + '\nSly_tom_cat')
aboutWindow.set_license(
'This program is free software: you can redistribute it and/or \n' +
'modify it under the terms of the GNU General Public License as \n' +
'published by the Free Software Foundation, either version 3 of \n' +
'the License, or (at your option) any later version.\n\n' +
'This program is distributed in the hope that it will be useful, \n' +
'but WITHOUT ANY WARRANTY; without even the implied warranty \n' +
'of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n' +
'See the GNU General Public License for more details.\n\n' +
'You should have received a copy of the GNU General Public License \n' +
'along with this program. If not, see http://www.gnu.org/licenses')
aboutWindow.set_authors([_('Sly_tom_cat ([email protected]) '),
_('ya-setup utility author: Snow Dimon (snowdimon.ru)'),
_('\nSpecial thanks to:'),
_(' - Christiaan Diedericks (www.thefanclub.co.za) - autor of Grive tools(used as example)'),
_(' - ryukusu_luminarius ([email protected]) - icons designer'),
_(' - metallcorn ([email protected]) - icons designer'),
_(' - Chibiko ([email protected]) - deb package creation assistance'),
_(' - RingOV ([email protected]) - localization assistance'),
_(' - GreekLUG team (https://launchpad.net/~greeklug) - Greek translation'),
_(' - Peyu Yovev ([email protected]) - Bulgarian translation'),
_(' - Eldar Fahreev ([email protected]) - FM actions for Pantheon-files'),
_(' - Ace Of Snakes ([email protected]) - optimization of FM actions for Dolphin'),
_(' - Ivan Burmin (https://github.com/Zirrald) - ya-setup multilingual support'),
_(' - And to all other people who contributed to this project through'),
_(' the Ubuntu.ru forum http://forum.ubuntu.ru/index.php?topic=241992 and'),
_(' via github.com https://github.com/slytomcat/yandex-disk-indicator') ])
aboutWindow.run()
aboutWindow.destroy()
for i in indicators:
i.menu.about.set_sensitive(True) # Enable menu item
def showOutput(self, widget): # Display daemon output in dialogue window
global lang, logo
widget.set_sensitive(False) # Disable menu item
statusWindow = Gtk.Dialog(_('Yandex.Disk daemon output message'))
statusWindow.set_icon(logo)
statusWindow.set_border_width(6)
statusWindow.add_button(_('Close'), Gtk.ResponseType.CLOSE)
textBox = Gtk.TextView() # Create text-box to display daemon output
# Set output buffer with daemon output in user language
textBox.get_buffer().set_text(self.daemon.getOutput(True))
textBox.set_editable(False)
statusWindow.get_content_area().add(textBox) # Put it inside the dialogue content area
statusWindow.show_all(); statusWindow.run(); statusWindow.destroy()
widget.set_sensitive(True) # Enable menu item
def openInBrowser(self, widget, url): # Open URL
openNewBrowser(url)
def startDaemon(self, widget): # Start daemon
self.daemon.start()
def stopDaemon(self, widget): # Stop daemon
self.daemon.stop()
def openPath(self, widget, path): # Open path