-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPyDrive
executable file
·79 lines (67 loc) · 2.94 KB
/
PyDrive
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
#! /Users/benjamin/workspace/projects/uploadToDrive/env/bin/python3.8
import pydrive, os ,re ,time, logging
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
# for some reason terminal only wants full path
uploadFolderDir = '/Users/benjamin/Downloads/Upload/'
credFilePath = '/Users/benjamin/workspace/projects/uploadToDrive/mycreds.txt'
os.makedirs(uploadFolderDir + 'Uploaded', exist_ok= True) # makes dir if ./Uploaded does not exist
# GET DATE AND TIME
from datetime import datetime
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YY H:M:S
# TODO: Finish logging
logging.basicConfig(
filename='/Users/benjamin/Downloads/Upload/.mylog.txt',
filemode = 'a',
format='='*50+ '\n%(levelname)s: %(asctime)s\n%(message)s',
datefmt='%Y/%m/%d %I:%M %p'
)
gdriveLogin = GoogleAuth()
# Try to load saved client credentials
gdriveLogin.LoadCredentialsFile(credFilePath)
if gdriveLogin.credentials is None:
# Authenticate if they're not there
gdriveLogin.LocalWebserverAuth()
elif gdriveLogin.access_token_expired:
gdriveLogin.Refresh()
else:
# Initialize the saved creds
gdriveLogin.Authorize()
# Save the current credentials to a file
gdriveLogin.SaveCredentialsFile(credFilePath)
drive = GoogleDrive(gdriveLogin)
# loops thru all the items in project dir
for entry in os.listdir(uploadFolderDir):
x = re.findall(r'^\.', entry) # remove files that starts with .
# TODO: how to reject weird files?
if x == [] and os.path.isdir(uploadFolderDir + entry) == False:
with open(uploadFolderDir + entry, 'r') as file:
logging.info('Opening ' + uploadFolderDir + entry)
# Excludes the path in the file name in gdrive
file_drive = drive.CreateFile({'title': os.path.basename(file.name)})
file_drive.SetContentFile(file.name)
try:
log = 'Uploading file ' + entry
logging.info(log)
file_drive.Upload()
os.rename(file.name, uploadFolderDir + 'Uploaded/' + entry) # relocates file
except pydrive.files.FileNotUploadedError:
print('There was an error uploading ' + entry)
print('\nChecking age of files in /Uploaded')
# automate deletion of files after a period of time
for entry in os.listdir(uploadFolderDir + 'Uploaded/'):
x = re.findall(r'^\.', entry) # remove files that starts with .
if x == []:
entryPath = uploadFolderDir + 'Uploaded/' + entry
fileLasted = time.time() - os.path.getmtime(entryPath) # in seconds
fileLasted = int((fileLasted/3600)/24) # convert to day
if fileLasted > 30:
print('%s has lasted more than 30 days!')
os.remove(entryPath)
print('%s has been removed successfully' %entry)
print('%s lasted-----%d days' %(entry, fileLasted))
else:
pass
# TODO: catch errors to retry.. or output to stdout
# TODO: add the functionality of uploading folders