ownsync/ownssync.py

92 lines
2.1 KiB
Python

import os
from shutil import copy2
sync1 = '/home/yannis/Projects/ownsync/test/s1/'
sync2 = '/home/yannis/Projects/ownsync/test/s2/'
dataname = '.sync'
def readfiletoarray(file):
try:
f = open(file, 'r')
data = f.readlines()
f.close()
return data
except Exception as e:
print('Error reading sync data', e)
return []
def shouldsync(fromfile, tofile, data):
if os.path.exists(tofile):
if getlastchange(tofile) < getlastchange(fromfile): # from file neuer
return True
elif tofile in data:
return False # file existed once, but was deleted
return True # file dont exists and never existed
def getlastchange(file):
return os.path.getmtime(file)
def scandir(dir):
data = []
for file in os.listdir(dir):
if os.path.isfile(dir + file):
data.append(dir + file)
else:
for f in scandir(dir + file + '/'):
data.append(f)
return data
def rm(path):
if os.path.isfile(path):
os.remove(path)
else:
os.rmdir(path)
def syncnew(fro, to):
#read data
data = readfiletoarray(fro + dataname)
print(len(data), 'nodes loaded.')
listffiles = scandir(fro)
#remove prefix
pos = -1
for i in range(0, len(listffiles)):
listffiles[i] = listffiles[i][len(fro):]
if listffiles[i] == dataname:
pos = i
if pos > -1:
del listffiles[pos]
for f in listffiles:
if shouldsync(fro + f, to + f, data):
folder = to + f
folder = folder[:folder.rfind('/')+1]
print('make dir:',folder)
if not os.path.exists(folder):
os.makedirs(folder)
copy2(fro + f, to + f)
print('coping', fro + f)
else:
print('skipping', f)
for f in data:
if not os.path.exists(fro + f):
print('delete file', f)
# rm(fro + f)
#store to file
f = open(fro + dataname, 'w+')
f.writelines(listffiles)
f.close()
#MAIN
syncnew(sync1, sync2)
#syncnew(sync2, sync1)
#print(scandir('/home/yannis/Projects/telegramchatcopy/'))