-
Notifications
You must be signed in to change notification settings - Fork 7
/
scrapefolders.py
220 lines (177 loc) · 6.18 KB
/
scrapefolders.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
from __future__ import print_function
#googleapiclient.discovery
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from oauth2client.contrib import gce
from apiclient.http import MediaFileUpload
import numpy as np
import pandas as pd
from pandas import ExcelWriter
import os
import pathlib
from pathlib import Path
import io
import glob
import itertools
import shutil
import openpyxl
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.chart import (
LineChart,
Reference,
Series
)
import random
import time
from time import sleep
import datetime
import csv
CLIENT_SECRET = "/Users/eyana.mallari/Projects-Local/client_secret_eyanag.json"
FOLDER_ID = '19FBo4iSjyCS3NcqX6zaNgxtXWMqW7AyM'
SS_ID = '1qs2GXzxhbn8klcB3Y-qQVJs0CRt8iQ20LyntKP36BRY'
SHEET_ID=227869185
TAB_NAME ='Folders Lookup!A2:H'
CHAR_BEFORE_NAME = 16
now = datetime.datetime.now()
# --------------------------------
# GDrive API: GDrive Authorization
# --------------------------------
SCOPES='https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET, SCOPES)
creds = tools.run_flow(flow, store)
DRIVE_SERVICE = build('drive', 'v3', http=creds.authorize(Http()))
SS_SERVICE = build('sheets', 'v4', http=creds.authorize(Http()))
def countFiles(folder_id):
results = DRIVE_SERVICE.files().list(q="mimeType='application/vnd.google-apps.spreadsheet' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
count = 0
for item in items:
count += 1
return count
def getLatestFile(folder_id):
# Main Folder
results = DRIVE_SERVICE.files().list(q="mimeType='application/vnd.google-apps.spreadsheet' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name, createdTime)", orderBy="createdTime").execute()
#results = DRIVE_SERVICE.files().list(q="parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name, createdTime)", orderBy="createdTime").execute()
items = results.get('files', [])
if not items:
return ""
else:
return items
def retrieveId(items,count):
if not items:
return ""
else:
print(items[count-1]['id'])
return items[count-1]['id']
def retrieveName(items,count):
if not items:
return ""
else:
print(items[count-1]['name'])
return items[count-1]['name']
def retrieveCreatedDate(items,count):
if not items:
return ""
else:
print(items[count-1]['createdTime'])
return items[count-1]['createdTime']
def writeToSheets(values,range,spreadsheet_id):
print("Writing to Sheets")
body = {
'values': values
}
print(values)
SS_SERVICE.spreadsheets().values().update(spreadsheetId=spreadsheet_id,valueInputOption='USER_ENTERED',range=range,body=body).execute()
# -------------------------------------
# GDrive API: Retrieves all Folders
# -------------------------------------
def getAllFolders(folder_id, spreadsheet_id):
folder_id = FOLDER_ID
results = DRIVE_SERVICE.files().list(q="mimeType='application/vnd.google-apps.folder' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name)",pageSize=400).execute()
items = results.get('files', [])
values = []
count = 1
print(len(items))
for item in items:
print(count)
print('{0} ({1})'.format(item['name'], item['id']))
person_name = item['name'][CHAR_BEFORE_NAME:].strip()
file_count = countFiles(item['id'])
latestFileId = '=HYPERLINK("https://docs.google.com/spreadsheets/d/'+retrieveId(getLatestFile(item['id']),file_count)+'","Click")'
latestFile = retrieveName(getLatestFile(item['id']),file_count)
createdDate = retrieveCreatedDate(getLatestFile(item['id']),file_count)
print("----", person_name)
print("----", file_count)
print("----", createdDate)
item['person'] = person_name
item['file_count'] = file_count
item['link'] = '=HYPERLINK("https://drive.google.com/drive/folders/'+item['id']+'","Click")'
values.append([item['person'],item['name'],item['link'],item['id'],item['file_count'],latestFile,latestFileId,createdDate])
count+=1
writeToSheets(values,TAB_NAME,spreadsheet_id)
def colorAndSort(spreadsheet_id):
sheet_id=SHEET_ID
my_range = {
'sheetId': sheet_id,
'startRowIndex': 1,
'endRowIndex': 600,
'startColumnIndex': 4,
'endColumnIndex': 5,
}
requests = [{
'addConditionalFormatRule': {
'rule': {
'ranges': [ my_range ],
'booleanRule': {
'condition': {
'type': 'CUSTOM_FORMULA',
'values': [ { 'userEnteredValue': '=GT($E2,1)'} ]
},
'format': {
'backgroundColor': { 'red': 1, 'green': 1, 'blue': 0 }
}
}
}
}
},
{
"sortRange": {
"range": {
"sheetId": sheet_id,
"startRowIndex": 1,
"endRowIndex": 600,
"startColumnIndex": 0,
"endColumnIndex": 9
},
"sortSpecs": [
{
"dimensionIndex": 6,
"sortOrder": "DESCENDING"
},
{
"dimensionIndex": 7,
"sortOrder": "DESCENDING"
},
{
"dimensionIndex": 0,
"sortOrder": "ASCENDING"
}
]
}
}
]
body = {
'requests': requests
}
response = SS_SERVICE.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute()
print('{0} cells updated.'.format(len(response.get('replies'))));
def main():
getAllFolders(FOLDER_ID,SS_ID)
colorAndSort(SS_ID)
if __name__ == '__main__':
main()