forked from GAM-team/got-your-back
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gyb.py
1590 lines (1513 loc) · 60.2 KB
/
gyb.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
#
# Got Your Back
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""\n%s\n\nGot Your Back (GYB) is a command line tool which allows users to
backup and restore their Gmail.
For more information, see http://git.io/gyb/
"""
global __name__, __author__, __email__, __version__, __license__
__program_name__ = 'Got Your Back: Gmail Backup'
__author__ = 'Jay Lee'
__email__ = 'jay0lee@gmail.com'
__version__ = '1.01'
__license__ = 'Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)'
__website__ = 'http://git.io/gyb'
__db_schema_version__ = '6'
__db_schema_min_version__ = '6' #Minimum for restore
global extra_args, options, allLabelIds, allLabels, gmail, chunksize, reserved_labels, path_divider
extra_args = {'prettyPrint': False}
allLabelIds = dict()
allLabels = dict()
chunksize = 1024 * 1024 * 30
reserved_labels = ['inbox', 'spam', 'trash', 'unread', 'starred', 'important',
'sent', 'draft', 'chat', 'chats', 'migrated', 'todo', 'todos', 'buzz',
'bin', 'allmail', 'drafts']
import argparse
import sys
import os
import os.path
import time
import random
import struct
import platform
import datetime
import sqlite3
import email
import hashlib
import mailbox
import re
from itertools import islice, chain
import base64
import json
import httplib2
import oauth2client.client
import oauth2client.file
from oauth2client.service_account import ServiceAccountCredentials
import oauth2client.tools
import googleapiclient
import googleapiclient.discovery
import googleapiclient.errors
if os.name == 'windows' or os.name == 'nt':
path_divider = '\\'
else:
path_divider = '/'
# Override some oauth2client.tools strings saving us a few GAM-specific mods to oauth2client
oauth2client.tools._FAILED_START_MESSAGE = """
Failed to start a local webserver listening on either port 8080
or port 8090. Please check your firewall settings and locally
running programs that may be blocking or using those ports.
Falling back to nobrowser.txt and continuing with
authorization.
"""
oauth2client.tools._BROWSER_OPENED_MESSAGE = """
Your browser has been opened to visit:
{address}
If your browser is on a different machine then press CTRL+C and
create a file called nobrowser.txt in the same folder as GYB.
"""
oauth2client.tools._GO_TO_LINK_MESSAGE = """
Go to the following link in your browser:
{address}
"""
def SetupOptionParser(argv):
parser = argparse.ArgumentParser(add_help=False)
#parser.usage = parser.print_help()
parser.add_argument('--email',
dest='email',
help='Full email address of user or group to act against')
action_choices = ['backup','restore', 'restore-group', 'restore-mbox',
'count', 'purge', 'purge-labels', 'estimate', 'quota', 'reindex', 'revoke',
'split-mbox']
parser.add_argument('--action',
choices=action_choices,
dest='action',
default='backup',
help='Action to perform. Default is backup.')
parser.add_argument('--search',
dest='gmail_search',
default='-is:chat',
help='Optional: On backup, estimate, count and purge, Gmail search to \
scope operation against')
parser.add_argument('--local-folder',
dest='local_folder',
help='Optional: On backup, restore, estimate, local folder to use. \
Default is GYB-GMail-Backup-<email>',
default='XXXuse-email-addressXXX')
parser.add_argument('--label-restored',
action='append',
dest='label_restored',
help='Optional: On restore, all messages will additionally receive \
this label. For example, "--label_restored gyb-restored" will label all \
uploaded messages with a gyb-restored label.')
parser.add_argument('--strip-labels',
dest='strip_labels',
action='store_true',
default=False,
help='Optional: On restore and restore-mbox, strip existing labels from \
messages except for those explicitly declared with the --label-restored \
parameter.')
parser.add_argument('--vault',
action='store_true',
default=None,
dest='vault',
help='Optional: On restore and restore-mbox, restored messages will not be\
visible in user\'s Gmail but are subject to Vault discovery/retention.')
parser.add_argument('--service-account',
action='store_true',
dest='service_account',
help='Google Apps Business and Education only. Use OAuth 2.0 Service \
Account to authenticate.')
parser.add_argument('--use-admin',
dest='use_admin',
help='Optional: On restore-group, authenticate as this admin user.')
parser.add_argument('--spam-trash',
dest='spamtrash',
action='store_true',
help='Optional: Include Spam and Trash folders in backup, estimate and count actions. This is always enabled for purge.')
parser.add_argument('--batch-size',
dest='batch_size',
metavar='{1 - 100}',
type=int,
choices=list(range(1,101)),
default=0, # default of 0 means use per action default
help='Optional: Sets the number of operations to perform at once.')
parser.add_argument('--noresume',
action='store_true',
help='Optional: On restores, start from beginning. Default is to resume \
where last restore left off.')
parser.add_argument('--fast-restore',
action='store_true',
dest='fast_restore',
help='Optional: On restores, use the fast method. WARNING: using this \
method breaks Gmail deduplication and threading.')
parser.add_argument('--fast-incremental',
dest='refresh',
action='store_false',
default=True,
help='Optional: On backup, skips refreshing labels for existing message')
parser.add_argument('--debug',
action='store_true',
dest='debug',
help='Turn on verbose debugging and connection information \
(troubleshooting)')
parser.add_argument('--version',
action='store_true',
dest='version',
help='print GYB version and quit')
parser.add_argument('--help',
action='help',
help='Display this message.')
return parser.parse_args(argv)
def getProgPath():
return os.path.dirname(os.path.realpath(sys.argv[0]))+path_divider
class cmd_flags(object):
def __init__(self):
self.short_url = True
self.noauth_local_webserver = False
self.logging_level = 'ERROR'
self.auth_host_name = 'localhost'
self.auth_host_port = [8080, 9090]
def requestOAuthAccess():
if options.use_admin:
auth_as = options.use_admin
else:
auth_as = options.email
CLIENT_SECRETS = getProgPath()+'client_secrets.json'
if not os.path.exists(CLIENT_SECRETS) and hasattr(sys, '_MEIPASS'):
CLIENT_SECRETS = os.path.join(sys._MEIPASS, 'client_secrets.json')
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make GYB run you will need to populate the client_secrets.json file
found at:
%s
with information from the APIs Console https://console.developers.google.com.
""" % (CLIENT_SECRETS)
cfgFile = '%s%s.cfg' % (getProgPath(), auth_as)
storage = oauth2client.file.Storage(cfgFile)
credentials = storage.get()
flags = cmd_flags()
if os.path.isfile(getProgPath()+'nobrowser.txt'):
flags.noauth_local_webserver = True
if credentials is None or credentials.invalid:
disable_ssl_certificate_validation = False
if os.path.isfile(getProgPath()+'noverifyssl.txt'):
disable_ssl_certificate_validation = True
http = httplib2.Http(
disable_ssl_certificate_validation=disable_ssl_certificate_validation)
possible_scopes = ['https://www.googleapis.com/auth/gmail.modify',
# Gmail modify
'https://www.googleapis.com/auth/gmail.readonly',
# Gmail readonly
'https://www.googleapis.com/auth/gmail.insert \
https://www.googleapis.com/auth/gmail.labels',
# insert and labels
'https://mail.google.com/',
# Gmail Full Access
'',
# No Gmail
'https://www.googleapis.com/auth/apps.groups.migration',
# Groups Archive Restore
'https://www.googleapis.com/auth/drive.appdata']
# Drive app config (used for quota)
selected_scopes = [' ', ' ', ' ', '*', ' ', '*', '*']
menu = '''Select the actions you wish GYB to be able to perform for %s
[%s] 0) Gmail Backup And Restore - read/write mailbox access
[%s] 1) Gmail Backup Only - read-only mailbox access
[%s] 2) Gmail Restore Only - write-only mailbox access and label management
[%s] 3) Gmail Full Access - read/write mailbox access and message purge
[%s] 4) No Gmail Access
[%s] 5) Groups Restore - write to Google Apps Groups Archive
[%s] 6) Storage Quota - Drive app config scope used for --action quota
7) Continue
'''
os.system(['clear', 'cls'][os.name == 'nt'])
while True:
selection = input(menu % tuple([auth_as]+selected_scopes))
try:
if int(selection) > -1 and int(selection) <= 6:
if selected_scopes[int(selection)] == ' ':
selected_scopes[int(selection)] = '*'
if int(selection) > -1 and int(selection) <= 4:
for i in range(0,5):
if i == int(selection):
continue
selected_scopes[i] = ' '
else:
selected_scopes[int(selection)] = ' '
elif selection == '7':
at_least_one = False
for i in range(0, len(selected_scopes)):
if selected_scopes[i] in ['*',]:
if i == 4:
continue
at_least_one = True
if at_least_one:
break
else:
os.system(['clear', 'cls'][os.name == 'nt'])
print("YOU MUST SELECT AT LEAST ONE SCOPE!\n")
continue
else:
os.system(['clear', 'cls'][os.name == 'nt'])
print('NOT A VALID SELECTION!\n')
continue
os.system(['clear', 'cls'][os.name == 'nt'])
except ValueError:
os.system(['clear', 'cls'][os.name == 'nt'])
print('NOT A VALID SELECTION!\n')
continue
scopes = ['email',]
for i in range(0, len(selected_scopes)):
if selected_scopes[i] == '*':
scopes.append(possible_scopes[i])
FLOW = oauth2client.client.flow_from_clientsecrets(CLIENT_SECRETS,
scope=scopes, message=MISSING_CLIENT_SECRETS_MESSAGE, login_hint=auth_as)
credentials = oauth2client.tools.run_flow(flow=FLOW, storage=storage,
flags=flags, http=http)
disable_ssl_certificate_validation = False
if os.path.isfile(getProgPath()+'noverifyssl.txt'):
disable_ssl_certificate_validation = True
http = httplib2.Http(
disable_ssl_certificate_validation=disable_ssl_certificate_validation)
def doGYBCheckForUpdates():
import urllib.request, urllib.error, urllib.parse, calendar
no_update_check_file = getProgPath()+'noupdatecheck.txt'
last_update_check_file = getProgPath()+'lastcheck.txt'
if os.path.isfile(no_update_check_file): return
try:
current_version = float(__version__)
except ValueError:
return
if os.path.isfile(last_update_check_file):
f = open(last_update_check_file, 'r')
last_check_time = int(f.readline())
f.close()
else:
last_check_time = 0
now_time = calendar.timegm(time.gmtime())
one_week_ago_time = now_time - 604800
if last_check_time > one_week_ago_time: return
try:
checkUrl = 'https://gyb-update.appspot.com/latest-version.txt?v=%s'
c = urllib.request.urlopen(checkUrl % (__version__,))
try:
latest_version = float(c.read())
except ValueError:
return
if latest_version <= current_version:
f = open(last_update_check_file, 'w')
f.write(str(now_time))
f.close()
return
announceUrl = 'https://gyb-update.appspot.com/\
latest-version-announcement.txt?v=%s'
a = urllib.request.urlopen(announceUrl % (__version__,))
announcement = a.read().decode("utf-8")
sys.stderr.write('\nThere\'s a new version of GYB!!!\n\n')
sys.stderr.write(announcement)
visit_gyb = input("\n\nHit Y to visit the GYB website and download \
the latest release. Hit Enter to just continue with this boring old version.\
GYB won't bother you with this announcement for 1 week or you can create a \
file named %s and GYB won't ever check for updates: " % no_update_check_file)
if visit_gyb.lower() == 'y':
import webbrowser
webbrowser.open(__website__)
print('GYB is now exiting so that you can overwrite this old version \
with the latest release')
sys.exit(0)
f = open(last_update_check_file, 'w')
f.write(str(now_time))
f.close()
except urllib.error.HTTPError:
return
except urllib.error.URLError:
return
def getAPIVer(api):
if api == 'oauth2':
return 'v2'
elif api == 'gmail':
return 'v1'
elif api == 'groupsmigration':
return 'v1'
elif api == 'drive':
return 'v2'
return 'v1'
def getAPIScope(api):
if api == 'gmail':
return ['https://mail.google.com/']
elif api == 'groupsmigration':
return ['https://www.googleapis.com/auth/apps.groups.migration']
elif api == 'drive':
return ['https://www.googleapis.com/auth/drive.appdata']
def buildGAPIObject(api):
if options.use_admin:
auth_as = options.use_admin
else:
auth_as = options.email
oauth2file = '%s%s.cfg' % (getProgPath(), auth_as)
storage = oauth2client.file.Storage(oauth2file)
credentials = storage.get()
if credentials is None or credentials.invalid:
doRequestOAuth()
credentials = storage.get()
credentials.user_agent = getGYBVersion(' | ')
disable_ssl_certificate_validation = False
if os.path.isfile(getProgPath()+'noverifyssl.txt'):
disable_ssl_certificate_validation = True
http = httplib2.Http(
disable_ssl_certificate_validation=disable_ssl_certificate_validation)
if options.debug:
httplib2.debuglevel = 4
extra_args['prettyPrint'] = True
if os.path.isfile(getProgPath()+'extra-args.txt'):
import configparser
config = configparser.ConfigParser()
config.optionxform = str
config.read(getProgPath()+'extra-args.txt')
extra_args.update(dict(config.items('extra-args')))
http = credentials.authorize(http)
version = getAPIVer(api)
try:
return googleapiclient.discovery.build(api, version, http=http, cache_discovery=False)
except googleapiclient.errors.UnknownApiNameOrVersion:
disc_file = getProgPath()+'%s-%s.json' % (api, version)
if os.path.isfile(disc_file):
f = file(disc_file, 'r')
discovery = f.read()
f.close()
return googleapiclient.discovery.build_from_document(discovery,
base='https://www.googleapis.com', http=http)
else:
print('No online discovery doc and %s does not exist locally'
% disc_file)
raise
def buildGAPIServiceObject(api, soft_errors=False):
global extra_args
if options.use_admin:
auth_as = options.use_admin
else:
auth_as = options.email
oauth2servicefilejson = getProgPath()+'oauth2service.json'
scopes = getAPIScope(api)
credentials = ServiceAccountCredentials.from_json_keyfile_name(
oauth2servicefilejson, scopes)
credentials = credentials.create_delegated(auth_as)
credentials.user_agent = getGYBVersion(' | ')
disable_ssl_certificate_validation = False
if os.path.isfile(getProgPath()+'noverifyssl.txt'):
disable_ssl_certificate_validation = True
http = httplib2.Http(
disable_ssl_certificate_validation=disable_ssl_certificate_validation)
if options.debug:
httplib2.debuglevel = 4
extra_args['prettyPrint'] = True
if os.path.isfile(getProgPath()+'extra-args.txt'):
import configparser
config = configparser.ConfigParser()
config.optionxform = str
config.read(getGamPath()+'extra-args.txt')
extra_args.update(dict(config.items('extra-args')))
http = credentials.authorize(http)
version = getAPIVer(api)
try:
return googleapiclient.discovery.build(api, version, http=http, cache_discovery=False)
except oauth2client.client.AccessTokenRefreshError as e:
message = e.args[0]
if message in ['access_denied',
'unauthorized_client: Unauthorized client or scope in request.',
'access_denied: Requested client not authorized.']:
print('Error: Access Denied. Please make sure the Client Name:\
\n\n%s\n\nis authorized for the API Scope(s):\n\n%s\n\nThis can be \
configured in your Control Panel under:\n\nSecurity -->\nAdvanced \
Settings -->\nManage third party OAuth Client access'
% (credentials.client_id, ','.join(scopes)))
sys.exit(5)
else:
print('Error: %s' % e)
if soft_errors:
return False
sys.exit(4)
def callGAPI(service, function, soft_errors=False, throw_reasons=[], **kwargs):
retries = 10
parameters = kwargs.copy()
parameters.update(extra_args)
for n in range(1, retries+1):
if function:
method = getattr(service, function)(**parameters)
else:
method = service
try:
return method.execute()
except googleapiclient.errors.HttpError as e:
try:
error = json.loads(e.content.decode('utf-8'))
reason = error['error']['errors'][0]['reason']
http_status = error['error']['code']
message = error['error']['errors'][0]['message']
except (KeyError, json.decoder.JSONDecodeError):
http_status = int(e.resp['status'])
reason = e.content
message = e.content
if reason in throw_reasons:
raise
if n != retries and (http_status >= 500 or
reason in ['rateLimitExceeded', 'userRateLimitExceeded', 'backendError']):
wait_on_fail = (2 ** n) if (2 ** n) < 60 else 60
randomness = float(random.randint(1,1000)) / 1000
wait_on_fail += randomness
if n > 3:
sys.stderr.write('\nTemp error %s. Backing off %s seconds...'
% (reason, int(wait_on_fail)))
time.sleep(wait_on_fail)
if n > 3:
sys.stderr.write('attempt %s/%s\n' % (n+1, retries))
continue
sys.stderr.write('\n%s: %s - %s\n' % (http_status, message, reason))
if soft_errors:
sys.stderr.write(' - Giving up.\n')
return
else:
sys.exit(int(http_status))
except oauth2client.client.AccessTokenRefreshError as e:
sys.stderr.write('Error: Authentication Token Error - %s' % e)
sys.exit(403)
def callGAPIpages(service, function, items='items',
nextPageToken='nextPageToken', page_message=None, message_attribute=None,
**kwargs):
pageToken = None
all_pages = list()
total_items = 0
while True:
this_page = callGAPI(service=service, function=function,
pageToken=pageToken, **kwargs)
if not this_page:
this_page = {items: []}
try:
page_items = len(this_page[items])
except KeyError:
page_items = 0
total_items += page_items
if page_message:
show_message = page_message
try:
show_message = show_message.replace('%%num_items%%', str(page_items))
except (IndexError, KeyError):
show_message = show_message.replace('%%num_items%%', '0')
try:
show_message = show_message.replace('%%total_items%%',
str(total_items))
except (IndexError, KeyError):
show_message = show_message.replace('%%total_items%%', '0')
if message_attribute:
try:
show_message = show_message.replace('%%first_item%%',
str(this_page[items][0][message_attribute]))
show_message = show_message.replace('%%last_item%%',
str(this_page[items][-1][message_attribute]))
except (IndexError, KeyError):
show_message = show_message.replace('%%first_item%%', '')
show_message = show_message.replace('%%last_item%%', '')
rewrite_line(show_message)
try:
all_pages += this_page[items]
pageToken = this_page[nextPageToken]
if pageToken == '':
return all_pages
except (IndexError, KeyError):
if page_message:
sys.stderr.write('\n')
return all_pages
def message_is_backed_up(message_num, sqlcur, sqlconn, backup_folder):
try:
sqlcur.execute('''
SELECT message_filename FROM uids NATURAL JOIN messages
where uid = ?''', ((message_num),))
except sqlite3.OperationalError as e:
if e.message == 'no such table: messages':
print("\n\nError: your backup database file appears to be corrupted.")
else:
print("SQL error:%s" % e)
sys.exit(8)
sqlresults = sqlcur.fetchall()
for x in sqlresults:
filename = x[0]
if os.path.isfile(os.path.join(backup_folder, filename)):
return True
return False
def get_db_settings(sqlcur):
try:
sqlcur.execute('SELECT name, value FROM settings')
db_settings = dict(sqlcur)
return db_settings
except sqlite3.OperationalError as e:
if e.message == 'no such table: settings':
print("\n\nSorry, this version of GYB requires version %s of the \
database schema. Your backup folder database does not have a version."
% (__db_schema_version__))
sys.exit(6)
else:
print("%s" % e)
def check_db_settings(db_settings, action, user_email_address):
if (db_settings['db_version'] < __db_schema_min_version__ or
db_settings['db_version'] > __db_schema_version__):
print("\n\nSorry, this backup folder was created with version %s of the \
database schema while GYB %s requires version %s - %s for restores"
% (db_settings['db_version'], __version__, __db_schema_min_version__,
__db_schema_version__))
sys.exit(4)
# Only restores are allowed to use a backup folder started with another
# account (can't allow 2 Google Accounts to backup/estimate from same folder)
if action not in ['restore', 'restore-group', 'restore-mbox']:
if user_email_address.lower() != db_settings['email_address'].lower():
print("\n\nSorry, this backup folder should only be used with the %s \
account that it was created with for incremental backups. You specified the\
%s account" % (db_settings['email_address'], user_email_address))
sys.exit(5)
def convertDB(sqlconn, uidvalidity, oldversion):
print("Converting database")
try:
with sqlconn:
if oldversion < '3':
# Convert to schema 3
sqlconn.executescript('''
BEGIN;
CREATE TABLE uids
(message_num INTEGER, uid INTEGER PRIMARY KEY);
INSERT INTO uids (uid, message_num)
SELECT message_num as uid, message_num FROM messages;
CREATE INDEX labelidx ON labels (message_num);
CREATE INDEX flagidx ON flags (message_num);
''')
if oldversion < '4':
# Convert to schema 4
sqlconn.execute('''
ALTER TABLE messages ADD COLUMN rfc822_msgid TEXT;
''')
if oldversion < '5':
# Convert to schema 5
sqlconn.executescript('''
DROP INDEX labelidx;
DROP INDEX flagidx;
CREATE UNIQUE INDEX labelidx ON labels (message_num, label);
CREATE UNIQUE INDEX flagidx ON flags (message_num, flag);
''')
if oldversion < '6':
# Convert to schema 6
getMessageIDs(sqlconn, options.local_folder)
rebuildUIDTable(sqlconn)
sqlconn.executemany('REPLACE INTO settings (name, value) VALUES (?,?)',
(('uidvalidity',uidvalidity),
('db_version', __db_schema_version__)) )
sqlconn.commit()
except sqlite3.OperationalError as e:
print("Conversion error: %s" % e.message)
print("GYB database converted to version %s" % __db_schema_version__)
def getMessageIDs (sqlconn, backup_folder):
sqlcur = sqlconn.cursor()
header_parser = email.parser.HeaderParser()
for message_num, filename in sqlconn.execute('''
SELECT message_num, message_filename FROM messages
WHERE rfc822_msgid IS NULL'''):
message_full_filename = os.path.join(backup_folder, filename)
if os.path.isfile(message_full_filename):
f = open(message_full_filename, 'r')
msgid = header_parser.parse(f, True).get('message-id') or '<DummyMsgID>'
f.close()
sqlcur.execute(
'UPDATE messages SET rfc822_msgid = ? WHERE message_num = ?',
(msgid, message_num))
sqlconn.commit()
def rebuildUIDTable(sqlconn):
pass
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def humansize(file_path):
nbytes = os.stat(file_path).st_size
if nbytes == 0: return '0 B'
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s%s' % (f, suffixes[i])
def doesTokenMatchEmail():
if options.use_admin:
auth_as = options.use_admin
else:
auth_as = options.email
oa2 = buildGAPIObject('oauth2')
user_info = callGAPI(service=oa2.userinfo(), function='get',
fields='email')
if user_info['email'].lower() == auth_as.lower():
return True
print("Error: you did not authorize the OAuth token in the browser with the \
%s Google Account. Please make sure you are logged in to the correct account \
when authorizing the token in the browser." % auth_as)
cfgFile = '%s%s.cfg' % (getProgPath(), auth_as)
os.remove(cfgFile)
return False
def rewrite_line(mystring):
print(' ' * 80, end='\r')
print(mystring, end='\r')
def initializeDB(sqlcur, sqlconn, email):
sqlcur.executescript('''
CREATE TABLE messages(message_num INTEGER PRIMARY KEY,
message_filename TEXT,
message_internaldate TIMESTAMP);
CREATE TABLE labels (message_num INTEGER, label TEXT);
CREATE TABLE uids (message_num INTEGER, uid TEXT PRIMARY KEY);
CREATE TABLE settings (name TEXT PRIMARY KEY, value TEXT);
CREATE UNIQUE INDEX labelidx ON labels (message_num, label);
''')
sqlcur.executemany('INSERT INTO settings (name, value) VALUES (?, ?)',
(('email_address', email),
('db_version', __db_schema_version__)))
sqlconn.commit()
def getGYBVersion(divider="\n"):
return ('Got Your Back %s~DIV~%s~DIV~%s - %s~DIV~Python %s.%s.%s %s-bit \
%s~DIV~%s %s' % (__version__, __website__, __author__, __email__,
sys.version_info[0], sys.version_info[1], sys.version_info[2],
struct.calcsize('P')*8, sys.version_info[3], platform.platform(),
platform.machine())).replace('~DIV~', divider)
def labelIdsToLabels(labelIds):
global allLabelIds, gmail
labels = list()
for labelId in labelIds:
if labelId not in allLabelIds:
# refresh allLabelIds from Google
label_results = callGAPI(service=gmail.users().labels(), function='list',
userId='me', fields='labels(name,id,type)')
allLabelIds = dict()
for a_label in label_results['labels']:
if a_label['type'] == 'system':
allLabelIds[a_label['id']] = a_label['id']
else:
allLabelIds[a_label['id']] = a_label['name']
try:
labels.append(allLabelIds[labelId])
except KeyError:
pass
return labels
def labelsToLabelIds(labels):
global allLabels
if len(allLabels) < 1: # first fetch of all labels from Google
label_results = callGAPI(service=gmail.users().labels(), function='list',
userId='me', fields='labels(name,id,type)')
allLabels = dict()
for a_label in label_results['labels']:
if a_label['type'] == 'system':
allLabels[a_label['id']] = a_label['id']
else:
allLabels[a_label['name']] = a_label['id']
labelIds = list()
for label in labels:
base_label = label.split('/')[0]
if base_label in reserved_labels and base_label not in allLabels.keys():
label = '_%s' % (label)
if label not in allLabels.keys():
# create new label (or get it's id if it exists)
label_results = callGAPI(service=gmail.users().labels(), function='create',
body={'labelListVisibility': 'labelShow',
'messageListVisibility': 'show', 'name': label},
userId='me', fields='id')
allLabels[label] = label_results['id']
try:
labelIds.append(allLabels[label])
except KeyError:
pass
if label.find('/') != -1:
# make sure to create parent labels for proper nesting
parent_label = label[:label.rfind('/')]
while True:
if not parent_label in allLabels:
label_result = callGAPI(service=gmail.users().labels(),
function='create', userId='me', body={'name': parent_label})
allLabels[parent_label] = label_result['id']
if parent_label.find('/') == -1:
break
parent_label = parent_label[:parent_label.rfind('/')]
return labelIds
def refresh_message(request_id, response, exception):
if exception is not None:
raise exception
else:
if 'labelIds' in response:
labels = labelIdsToLabels(response['labelIds'])
sqlcur.execute('DELETE FROM current_labels')
sqlcur.executemany(
'INSERT INTO current_labels (label) VALUES (?)',
((label,) for label in labels))
sqlcur.execute("""DELETE FROM labels where message_num =
(SELECT message_num from uids where uid = ?)
AND label NOT IN current_labels""", ((response['id']),))
sqlcur.execute("""INSERT INTO labels (message_num, label)
SELECT message_num, label from uids, current_labels
WHERE uid = ? AND label NOT IN
(SELECT label FROM labels
WHERE message_num = uids.message_num)""",
((response['id']),))
def restored_message(request_id, response, exception):
if exception is not None:
try:
error = json.loads(exception.content.decode('utf-8'))
if error['error']['code'] == 400:
print("\nERROR: %s: %s. Skipping message restore, you can retry later with --fast-restore"
% (error['error']['code'], error['error']['errors'][0]['message']))
return
except:
pass
raise exception
else:
sqlconn.execute(
'''INSERT OR IGNORE INTO restored_messages (message_num) VALUES (?)''',
(request_id,))
def purged_message(request_id, response, exception):
if exception is not None:
raise exception
def estimate_message(request_id, response, exception):
global message_size_estimate
if exception is not None:
raise exception
else:
this_message_size = int(response['sizeEstimate'])
message_size_estimate += this_message_size
def backup_message(request_id, response, exception):
if exception is not None:
print(exception)
else:
if 'labelIds' in response:
labelIds = response['labelIds']
else:
labelIds = list()
if 'CHATS' in labelIds: # skip CHATS
return
labels = labelIdsToLabels(labelIds)
message_file_name = "%s.eml" % (response['id'])
message_time = int(response['internalDate'])/1000
message_date = time.gmtime(message_time)
time_for_sqlite = datetime.datetime.fromtimestamp(message_time)
message_rel_path = os.path.join(str(message_date.tm_year),
str(message_date.tm_mon),
str(message_date.tm_mday))
message_rel_filename = os.path.join(message_rel_path,
message_file_name)
message_full_path = os.path.join(options.local_folder,
message_rel_path)
message_full_filename = os.path.join(options.local_folder,
message_rel_filename)
if not os.path.isdir(message_full_path):
os.makedirs(message_full_path)
f = open(message_full_filename, 'wb')
raw_message = str(response['raw'])
full_message = base64.urlsafe_b64decode(raw_message)
f.write(full_message)
f.close()
sqlcur.execute("""
INSERT INTO messages (
message_filename,
message_internaldate) VALUES (?, ?)""",
(message_rel_filename,
time_for_sqlite))
message_num = sqlcur.lastrowid
sqlcur.execute("""
REPLACE INTO uids (message_num, uid) VALUES (?, ?)""",
(message_num, response['id']))
for label in labels:
sqlcur.execute("""
INSERT INTO labels (message_num, label) VALUES (?, ?)""",
(message_num, label))
def bytes_to_larger(myval):
myval = int(myval)
mysize = 'b'
if myval > 1024:
myval = myval / 1024
mysize = 'kb'
if myval > 1024:
myval = myval / 1024
mysize = 'mb'
if myval > 1024:
myval = myval / 1024
mysize = 'gb'
if myval > 1024:
myval = myval / 1024
mysize = 'tb'
return '%.2f%s' % (myval, mysize)
def main(argv):
global options, gmail
options = SetupOptionParser(argv)
if options.version:
print(getGYBVersion())
sys.exit(0)
if options.local_folder == 'XXXuse-email-addressXXX':
options.local_folder = "GYB-GMail-Backup-%s" % options.email
# SPLIT-MBOX
if options.action == 'split-mbox':
from_pattern = 'From '
max_chunk_size = 100 * 1024 * 1024
for path, subdirs, files in os.walk(options.local_folder):
for filename in files:
if filename[-4:].lower() != '.mbx' and \
filename[-5:].lower() != '.mbox':
continue
file_path = '%s%s%s' % (path, path_divider, filename)
chunk_number = 0
chunk_name_pattern = '%s-%%05d.mbox' % (os.path.splitext(file_path)[0])
print('opening %s' % file_path)
with open(file_path, 'r') as f:
current_email = ''
current_chunk = ''
for line in f:
if line.startswith(from_pattern): # found end of email
if len(current_chunk) + len(current_email) > max_chunk_size: # reached max chunk size
if len(current_email) > max_chunk_size: # email is larger than chunk
print('WARNING: skipping 100mb+ email')
current_email = line
continue
# write chunk and start new
chunk_filename = chunk_name_pattern % (chunk_number)
c = open(chunk_filename, 'w+')
print('writing %s' % chunk_filename)
c.write(current_chunk)
c.close()
chunk_number += 1
current_chunk = current_email
current_email = line
else: # add email to chunk
# add email to chunk and start on next
current_chunk += current_email
current_email = line
continue
else: # read another line
current_email += line
if len(current_chunk) > 0:
# write last chunk
chunk_filename = chunk_name_pattern % (chunk_number)
c = open(chunk_filename, 'w+')
c.write(current_chunk)
c.close()
sys.exit(0)
if not options.email:
print('ERROR: --email is required.')
sys.exit(1)
if not options.service_account: # 3-Legged OAuth
requestOAuthAccess()
if not doesTokenMatchEmail():
sys.exit(9)
gmail = buildGAPIObject('gmail')
else:
gmail = buildGAPIServiceObject('gmail')
if not os.path.isdir(options.local_folder):
if options.action in ['backup',]:
os.mkdir(options.local_folder)
elif options.action in ['restore', 'restore-group']:
print('Error: Folder %s does not exist. Cannot restore.'
% options.local_folder)
sys.exit(3)
sqldbfile = os.path.join(options.local_folder, 'msg-db.sqlite')
# Do we need to initialize a new database?
newDB = (not os.path.isfile(sqldbfile)) and \
(options.action in ['backup', 'restore-mbox'])
# If we're not doing a estimate or if the db file actually exists we open it
# (creates db if it doesn't exist)
if options.action not in ['count', 'purge', 'purge-labels',
'quota', 'revoke']:
if options.action not in ['estimate'] or os.path.isfile(sqldbfile):
print("\nUsing backup folder %s" % options.local_folder)
global sqlconn
global sqlcur
sqlconn = sqlite3.connect(sqldbfile,
detect_types=sqlite3.PARSE_DECLTYPES)
sqlconn.text_factory = str
sqlcur = sqlconn.cursor()
if newDB:
initializeDB(sqlcur, sqlconn, options.email)
db_settings = get_db_settings(sqlcur)
check_db_settings(db_settings, options.action, options.email)