-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyncFTP.py
218 lines (172 loc) · 6.24 KB
/
SyncFTP.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
#!/usr/bin/env python3
from ftplib import FTP_TLS
import os
import hashlib
import json
import pickle
import logging
class SyncFile(object):
def __init__(self, root, path, name, checksum):
self.isDirectory = False
self.root = root
self.path = path
self.name = name
self.checksum = checksum
class SyncDirectory(object):
def __init__(self, root, name, directories, files):
self.isDirectory = True
self.root = root
self.directories = directories
self.name = name
self.files = files
class FTP2(FTP_TLS):
def __init__(self, host):
super().__init__(host)
def ftpFileStore(self, filepath, name):
with open(filepath, 'rb') as localfile:
self.storbinary('STOR ' + name, localfile)
def ftpFileRetrevie(self, filepath, name):
with open(filepath, 'wb') as localfile:
self.retrbinary('RETR ' + name, localfile.write, 1024)
class DelException(Exception):
def __init__(self, message):
super().__init__(message)
def enum(**enums):
return type('Enum', (), enums)
# https://stackoverflow.com/questions/3431825/generating-an-md5-checksum-of-a-file
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096*16), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
# create a settings.py file and put all this inside:
# path to local directory where sync should monitor
scanpath = ""
# server path where data should be pushed
virtualpath = ""
# database name where file checksums are stored
filename = ""
# ftp server info
ftpUsername = ''
ftpPassword = ''
ftpURL = ''
HistoryFiles = {}
SyncFiles = {}
if os.path.exists('settings.py'):
from settings import *
lwd = None
Sync = True
# loading previous sync info, folder lists, file lists with their checksum
try:
with open(filename, 'rb') as stream:
HistoryFiles = pickle.load(stream)
except FileNotFoundError as ex:
print("Sync history not found!")
Sync = False
try:
if Sync:
ftps = FTP2(ftpURL)
ftps.login(user=ftpUsername, passwd=ftpPassword, secure=True)
print(ftps.getwelcome())
# scanning directory for folders, files, changes
for root, directories, files in os.walk(scanpath):
froot = root.replace('\\', '/')
# new files, modified files
for fname in files:
fpath = os.path.join(root, fname)
fpath = fpath.replace('\\', '/')
fmd5 = md5(fpath)
if fpath not in HistoryFiles:
push = True
elif HistoryFiles[fpath].checksum != fmd5:
push = True
else:
push = False
if push:
cwd = virtualpath + froot[len(scanpath):]
cwd = cwd.replace('\\', '/')
if Sync:
cwd = cwd.replace('\\', '/')
ftps.cwd(cwd)
ftps.ftpFileStore(fpath, fname)
print('NEWFLE ', fpath, '>', cwd)
SyncFiles[fpath] = HistoryFiles[fpath] = SyncFile(froot, fpath, fname, fmd5)
# new directories
for dname in directories:
dpath = os.path.join(froot, dname)
dpath = dpath.replace('\\', '/')
if dpath not in HistoryFiles:
push = True
else:
push = False
if push:
cwd = virtualpath + froot[len(scanpath):]
cwd = cwd.replace('\\', '/')
if Sync:
ftps.cwd(cwd)
ftps.mkd(dname)
SyncFiles[dpath] = HistoryFiles[dpath] = SyncDirectory(dpath, dname, None, None)
print('NEWDIR ', dname, '>', cwd)
SyncFiles[froot] = HistoryFiles[froot] = SyncDirectory(froot,os.path.basename(froot), directories, files)
def DirectoryDelete(path, syncobj):
# call on subdirectories
for d in syncobj.directories:
i = os.path.join(path, d)
DirectoryDelete(i, HistoryFiles[i])
# delete files in i
for f in syncobj.files:
fpath = os.path.join(path, f)
fpath = fpath.replace('\\', '/')
cwd = virtualpath + syncobj.root[len(scanpath):]
cwd = cwd.replace('\\', '/')
if Sync:
ftps.cwd(cwd)
ftps.delete(f)
del HistoryFiles[fpath]
print('DELFLE', fpath)
# delete directories
cwd = virtualpath + syncobj.root[len(scanpath):]
cwd = cwd[:len(cwd) - len(syncobj.name)]
cwd = cwd.replace('\\', '/')
if Sync:
ftps.cwd(cwd)
ftps.rmd(syncobj.name)
del HistoryFiles[path]
print('DELDIR', path)
# delete
delete = None
while 1:
try:
for i in HistoryFiles:
if i not in SyncFiles:
if HistoryFiles[i].isDirectory:
if HistoryFiles[i].root == scanpath:
continue
delete = HistoryFiles[i]
break
if delete:
raise Exception
else:
break
except:
# first candidate for delete
if delete.isDirectory:
DirectoryDelete(i, delete)
else:
if Sync:
cwd = virtualpath + delete.root[len(scanpath):]
cwd = cwd.replace('\\', '/')
ftps.cwd(cwd)
ftps.delete(delete.name)
del HistoryFiles[delete.path]
print('DELFLE', delete.path)
delete = None
except Exception as ex:
print(ex)
finally:
# updating sync info
with open(filename, 'wb') as stream:
pickle.dump(HistoryFiles, stream)
if Sync:
ftps.quit()