sift_drive.py 13 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import argparse
import csv
import logging
import logging.handlers
import os
import yaml

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
22
        self.logger = logging.getLogger(__name__)
23
24
25
26
27
28

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

    def sift(self, folder_id, in_private=False):
Rob Carleski's avatar
Rob Carleski committed
60
        self.logger.info(
61
            'message=Processing folder {}'.format(folder_id),
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
            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
83
            self.logger.error(e.output, extra={'entity': self.account})
84
85
86
87
88
89
90
            return None
        if len(folderFiles) > 0:
            children = csv.DictReader(
                folderFiles,
                delimiter=',',
                quotechar='"'
            )
91
92
93
94
95
            try:
                for child in children:
                    if not hasattr(self, 'ignore_owner'):
                        if self.account != child['owners.0.emailAddress']:
                            continue
96

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

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
                    _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}
                )
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

        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'],
                            'link': item['alternateLink'],
                            'parent': self.root_folder
                        }
        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
241
            ], stderr=devnull)
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
269
                ], stderr=devnull
                )
        except CalledProcessError as e:
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
290

        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
                    )
            except CalledProcessError as e:
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339

        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.",
        required=True
    )
    parser.add_argument(
        '--root_folder',
        '-r',
        help='Use a particular folder as root.',
        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.',
340
        default=False
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    )
    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()

    # 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
362
    logger = logging.getLogger(__name__)
363
364
365
366
367
368
369
370
371
372
373
374
375
    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()
376
377
378
379
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
380
381
382
    ch.setFormatter(formatter)
    logger.addHandler(ch)

383
    sifter = Sifter(vars(args), config)
384
385
386
387
388
389
390
391
392
393
394
395
396
    sifter.sift(args.root_folder)
    sifter.find_unorganized()
    sifter.find_shared()
    sifter.scrub_duplicates()
    sifter.write_logfiles()
    if args.skip_upload:
        pass
    else:
        sifter.upload_logfiles()


if __name__ == '__main__':
    main()