sift_drive.py 14 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
8
import argparse
import csv
import logging
import logging.handlers
import os
import yaml

9
from .core import arg_prompt
10
11
12
13
14
15
16
17
18
19
20
21
22
from subprocess import CalledProcessError
from subprocess import check_output as cmd
from datetime import datetime
from shutil import rmtree

devnull = open(os.devnull, 'w')


class Sifter:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
Rob Carleski's avatar
Rob Carleski committed
23
        self.logger = logging.getLogger(__name__)
24
25
26
27
28
29

        try:
            cmd([
                config['google']['gam_command'],
                'whatis',
                self.account
Rob Carleski's avatar
Rob Carleski committed
30
            ])
31
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
32
            self.logger.error(e.output, extra={'entity': self.account})
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
            exit(2)

        if '@' not in self.account:
            self.account = '{}@{}'.format(
                self.account,
                config['google']['domain']
            )

        private_folders = ['personal', 'private', 'personal and private']
        if hasattr(self, 'omit_folders'):
            private_folders += self.omit_folders
        self.omit_folders = list(map((lambda x: x.lower()), private_folders))

        self.log_path = '{}/{}-{}'.format(
            self.config['general']['data_dir'],
            self.account,
            datetime.now().strftime('%Y-%m-%d')
        )
        if not os.path.exists(self.log_path):
            os.makedirs(self.log_path, 0o770)

        self.transfer_files = {}
        self.private_files = {}
        self.unknown_files = {}
        self.shared_files = {}
58
        self.parent = [self.root_folder_id]
59
60

    def sift(self, folder_id, in_private=False):
Rob Carleski's avatar
Rob Carleski committed
61
        self.logger.info(
62
            'message=Processing folder {}'.format(folder_id),
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
            extra={'entity': self.account}
        )
        try:
            folderFiles = cmd([
                self.config['google']['gam_command'],
                'user',
                self.account,
                'show',
                'filelist',
                'name',
                'id',
                'alternateLink',
                'mimeType',
                'anyowner',
                'owners',
                'query',
                "'{}' in parents".format(
                    folder_id
                )], stderr=devnull
            ).decode('utf-8').split('\n')[:-1]
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
84
            self.logger.error(e.output, extra={'entity': self.account})
85
86
87
88
89
90
91
            return None
        if len(folderFiles) > 0:
            children = csv.DictReader(
                folderFiles,
                delimiter=',',
                quotechar='"'
            )
92
93
94
95
96
            try:
                for child in children:
                    if not hasattr(self, 'ignore_owner'):
                        if self.account != child['owners.0.emailAddress']:
                            continue
97

98
99
100
101
102
103
104
                    data = {
                        'owner': child['owners.0.emailAddress'],
                        'name': child['title'],
                        'id': child['id'],
                        'link': child['alternateLink'],
                        'parent': '\\'.join(self.parent)
                    }
105

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
                    _title = child['title'].lower()
                    if in_private or _title in self.omit_folders:
                        self.private_files[child['id']] = data
                        if 'folder' in child['mimeType']:
                            self.parent.append(child['title'])
                            self.sift(child['id'], in_private=True)
                    else:
                        self.transfer_files[child['id']] = data
                        if 'folder' in child['mimeType']:
                            self.parent.append(child['title'])
                            self.sift(child['id'], in_private=False)
            except csv.Error:
                self.logger.warning(
                    'Failed reading files in {}.'
                    'Check for bad file title(s)?'.format(self.parent),
                    extra={'entity': self.account}
                )
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

        self.parent.pop()

    def find_unorganized(self):
        try:
            results = cmd([
                self.config['google']['gam_command'],
                'user',
                self.account,
                'show',
                'filelist',
                'name',
                'id',
                'owners',
                'alternateLink'
                ], stderr=devnull
            ).decode('utf-8').split('\n')[:-1]

            allFiles = csv.DictReader(results, delimiter=',', quotechar='"')
            for item in allFiles:
                if item['id'] not in self.transfer_files.keys():
                    if item['id'] not in self.private_files.keys():
                        self.unknown_files[item['id']] = {
                            'owner': item['owners.0.emailAddress'],
                            'name': item['title'],
                            'id': item['id'],
149
                            'link': item['alternateLink']
150
151
                        }
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
152
            self.logger.error(e.output, extra={'entity': self.account})
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

    def find_shared(self):
        try:
            results = cmd([
                self.config['google']['gam_command'],
                'user',
                self.account,
                'show',
                'filelist',
                'name',
                'id',
                'mimetype',
                'alternateLink',
                'anyowner',
                'owners',
                'query',
                'sharedWithMe=True'
                ], stderr=devnull
            ).decode('UTF-8').split('\n')[:-1]

            shared = csv.DictReader(results, delimiter=',', quotechar='"')
            for item in shared:
                if item['owners.0.emailAddress'] != self.account:
                    self.shared_files[item['id']] = {
                        'owner': item['owners.0.emailAddress'],
                        'name': item['title'],
                        'id': item['id'],
                        'link': item['alternateLink']
                    }
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
183
            self.logger.error(e.output, extra={'entity': self.account})
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

    def scrub_duplicates(self):
        for id in self.transfer_files.keys():
            if id in self.private_files.keys():
                del self.transfer_files[id]

    def write_logfiles(self):
        if len(self.transfer_files) > 0:
            target = '{}/transfer_files.csv'.format(self.log_path)
            with open(target, 'w+') as csvfile:
                fieldnames = ['owner', 'name', 'id', 'link', 'parent']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                for item in self.transfer_files:
                    writer.writerow(self.transfer_files[item])
                csvfile.close()

        if len(self.private_files) > 0:
            target = '{}/private_files.csv'.format(self.log_path)
            with open(target, 'w+') as csvfile:
                fieldnames = ['owner', 'name', 'id', 'link', 'parent']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                for item in self.private_files:
                    writer.writerow(self.private_files[item])
                csvfile.close()

        if len(self.unknown_files) > 0:
            target = '{}/unknown_files.csv'.format(self.log_path)
            with open(target, 'w+') as csvfile:
                fieldnames = ['owner', 'name', 'id', 'link', 'parent']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                for item in self.unknown_files:
                    writer.writerow(self.unknown_files[item])
                csvfile.close()

        if len(self.shared_files) > 0:
            target = '{}/shared_files.csv'.format(self.log_path)
            with open(target, 'w+') as csvfile:
                fieldnames = ['owner', 'name', 'id', 'link']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                for item in self.shared_files:
                    writer.writerow(self.shared_files[item])
                csvfile.close()

    def upload_logfiles(self):
        try:
233
            if self.destination_account:
234
235
236
237
238
239
240
                upload_user = self.destination_account
            else:
                upload_user = str(os.getlogin())
            cmd([
                self.config['google']['gam_command'],
                'whatis',
                upload_user
Rob Carleski's avatar
Rob Carleski committed
241
            ])
242
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
243
            self.logger.warning(e.output, extra={'entity': self.account})
244
245
246
247
248
            upload_user = self.config['google']['admin_account']

        # Find available files, then upload them.
        available_files = os.listdir(self.log_path)
        if len(available_files) == 0:
Rob Carleski's avatar
Rob Carleski committed
249
            self.logger.warning(
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
                'No files available for transfer',
                extra={'entity': self.account}
            )
            return None

        gFolderName = self.account + ' Drive Report'
        try:
            cmd([
                self.config['google']['gam_command'],
                'user',
                upload_user,
                'add',
                'drivefile',
                'drivefilename',
                gFolderName,
                'mimetype',
266
                'gdirectory'
267
268
                ], stderr=devnull
                )
269
        except CalledProcessError:
270
271
272
273
            self.logger.error(
                'Unable to create report directory',
                extra={'entity': self.account}
            )
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

        for log_file in available_files:
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'user',
                    upload_user,
                    'add',
                    'drivefile',
                    'localfile',
                    '{}/{}'.format(self.log_path, log_file),
                    'parentname',
                    gFolderName,
                    'convert'
                    ], stderr=devnull
                    )
290
            except CalledProcessError:
291
292
293
294
                self.logger.error(
                    'Error uploading {}'.format(log_file),
                    extra={'entity': self.account}
                )
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

        rmtree(self.log_path)


def main():
    helptext = '''examples:
    google-sift-drive -a alexham -f 'burr_beef' 'duel notes'
    google-sift-drive --account alexham --omit_folders 'burr_beef'
    '''

    parser = argparse.ArgumentParser(
        description='Reports owned Google files and folders for a user',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--account',
        '-a',
        help="The user to sift files for.",
    )
    parser.add_argument(
316
        '--root_folder_id',
317
        '-r',
318
        help='The ID of the folder to use as root.',
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        default='root'
    )
    parser.add_argument(
        '--ignore_owner',
        '-i',
        help='Ignore ownership requirement for reporting.',
        dest='ignore_owner',
        action='store_true'
    )
    parser.add_argument(
        '--omit_folders',
        '-o',
        help='A list of additional private folder names.',
        nargs='+',
        default=[]
    )
    parser.add_argument(
        '--destination_account',
        '-d',
        help='An optional account to upload reports to.',
339
        default=False
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    )
    parser.add_argument(
        '--skip_upload',
        '-u',
        help='Skip upload of logfiles to Drive',
        dest='skip_upload',
        action='store_true'
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use.',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

356
357
358
359
360
361
362
363
364
365
    # Argment prompt fallback
    if not args.account:
        args.account = arg_prompt(
            'Sifter target user'
        )
        args.root_folder_id = arg_prompt(
            '(optional) Use this folder ID as root',
            default='root'
        )
        args.omit_foders = arg_prompt(
Rob Carleski's avatar
Rob Carleski committed
366
            '(optional) Omit these folders (comma-delimited)',
367
            default=''
Rob Carleski's avatar
Rob Carleski committed
368
        ).split(',')
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
        args.destination_account = arg_prompt(
            '(optional) Upload reports to this account. (defaults to you)',
            default=False
        )
        args.skip_upload = arg_prompt(
            '(optional) Skip upload of reports [y/N]',
            default='n'
        ).lower()

    # Argument sanity check
    _required = ['account']
    for r in _required:
        try:
            if isinstance(r, str):
                assert getattr(args, r)
            if isinstance(r, tuple):
                assert getattr(args, r[0]) or getattr(args, r[1])
        except AssertionError:
            print('Missing required argument {}'.format(r))

389
390
391
392
393
    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
394
    logger = logging.getLogger(__name__)
395
396
397
398
399
400
401
402
403
404
405
406
407
    logger.setLevel(logging.DEBUG)

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
408
409
410
411
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
412
413
414
    ch.setFormatter(formatter)
    logger.addHandler(ch)

415
    sifter = Sifter(vars(args), config)
416
417
418
419
    sifter.sift(args.root_folder_id)
    if args.root_folder_id == 'root':
        sifter.find_unorganized()
        sifter.find_shared()
420
421
422
423
424
425
426
427
428
429
    sifter.scrub_duplicates()
    sifter.write_logfiles()
    if args.skip_upload:
        pass
    else:
        sifter.upload_logfiles()


if __name__ == '__main__':
    main()