/
sync-tsl-to-ipfs.py
executable file
·280 lines (237 loc) · 10.2 KB
/
sync-tsl-to-ipfs.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/bin/env python3
import pprint
import json
import requests
import os
from requests_toolbelt.utils import dump
from requests_toolbelt.multipart.encoder import MultipartEncoder
import argparse
import configparser
from requests.exceptions import HTTPError
from pathlib import Path
pp = pprint.PrettyPrinter(indent=4)
if os.name == 'nt':
DIRECTORY_SEPARATOR='\\'
else:
DIRECTORY_SEPARATOR='/'
###### See if a different config file is specified
parser = argparse.ArgumentParser(
prog='sync-tsl-to-ipfs',
description='This program tries to make sure the local directory matches what the IPFS thinks is correct. It adds/removes files to the IPFS directory as necessary.'
)
parser.add_argument('--config', '-c',
action='store',
default='settings.cfg',
help='configuration filename (default: settings.cfg)'
)
args = parser.parse_args()
###### Settings load
config = configparser.RawConfigParser()
config.read(args.config)
settings = {}
settings['remote'] = dict(config.items('remote'))
settings['options'] = dict(config.items('options'))
settings['local'] = dict(config.items('local'))
def grabCurrentIpfs(settings, directory='/'):
ipfsDb = {}
url = "http://" + settings['remote']['ipfsserver'] + ":" + settings['remote']['ipfsport'] + "/api/v0/files/ls"
args = {
'arg' : directory,
'long' : True
}
r = requests.post(url, params=args)
result = r.json()
# pp.pprint(result)
if "Entries" in result:
if result["Entries"] is not None:
entries = result['Entries']
for entry in entries:
if entry['Type'] == 0:
# file, grab its info.. but we want it to be in the proper structure of the db
entry['Path'] = directory
ipfsDb[entry['Name']] = entry
elif entry['Type'] == 1:
# directory, go deeper
newDirectory = directory + entry['Name'] + '/'
# print("going in " + newDirectory)
# quit()
tmpData = grabCurrentIpfs(settings, newDirectory)
ipfsDb[entry['Name'] + '/'] = tmpData
else:
pp.pprint(entry)
raise Exception('Unknown IPFS type: ' + entry['Type'])
return ipfsDb
def grabCurrentTsl(settings, directory):
tslDb = {}
dir = Path(directory)
for path in dir.iterdir():
# ignore anything starting with a /. in the path (file or directory starting with .)
if DIRECTORY_SEPARATOR + '.' in str(path):
continue
if (path.is_file()):
stats = path.stat()
mfsPath = str(path).replace(settings['local']['tsldirectory'], settings['remote']['mfsrootdirectory']).replace('\\', '/')
fileEntry = {
'name' : path.name,
'size' : stats.st_size,
'remotePath' : str(path).replace(settings['local']['tsldirectory'], settings['remote']['tsldirectory']),
'mfsPath' : mfsPath,
'localPath' : str(path)
}
tslDb[path.name] = fileEntry
elif (path.is_dir()):
# directory, go deeper
newDirectory = str(path)
tempDir = str(path).split(DIRECTORY_SEPARATOR).pop() + '/'
tslDb[tempDir] = grabCurrentTsl(settings, newDirectory)
else:
raise Exception("Not recognised as a file or a directory: " + str(path))
# pp.pprint(tslDb)
return tslDb
def verifyIpfsLibrary(settings):
url = "http://" + settings['remote']['ipfsserver'] + ":" + str(settings['remote']['ipfsport']) + "/api/v0/filestore/verify"
r = requests.post(url)
print(r.json())
def parsePaths(settings, path, ipfsDb, tslDb, fullPath=""):
fullPath += path
for path in ipfsDb:
if path not in tslDb:
# everything in this path needs to be removed from ipfs
# print("remove: " + fullPath + path)
if 'Name' not in ipfsDb[path]:
# this is a directory, make the entry a bit different
entry = {
'Path': '/' + fullPath.replace('\\', '/'),
'Name': path
}
else:
# this is a file, we can use the entry
entry = ipfsDb[path.replace('\\', '/')]
removeEntry(settings, entry)
else:
# compare the entries.
if path.replace('\\', '/').endswith('/'):
# we have a deeper path, check it
parsePaths(settings, path, ipfsDb[path], tslDb[path], fullPath)
else:
if ipfsDb[path]['Size'] != tslDb[path]['size']:
removeEntry(settings, ipfsDb[path])
addEntry(settings, tslDb[path])
for path in tslDb:
if path not in ipfsDb:
# everything in this path needs to be added to ipfs
# print("add: " + fullPath + path)
if path.endswith('/'):
# we have a deeper path, first create the directory on the MFS
# print("creating directory: " + fullPath + path)
addDirectory(settings, ('/' + fullPath + path).replace('\\', '/'))
# now parse that path.
parsePaths(settings, path, {}, tslDb[path], fullPath)
else:
addEntry(settings, tslDb[path])
def removeEntry(settings, entry):
url = "http://" + settings['remote']['ipfsserver'] + ":" + settings['remote']['ipfsport'] + "/api/v0/files/rm"
args = {
'arg' : entry['Path'] + entry['Name'],
'recursive' : True
}
args['arg'] = args['arg'].replace('\\', '/'),
print('Removing ' + entry['Path'] + entry['Name'])
r = requests.post(url, params=args)
r.raise_for_status()
if (r.text == '' or 'file does not exist' in r.text):
return
else:
raise Exception("Could not properly parse the return from a removal attempt of " + entry['Path'] + entry['Name'] + ":\n" + r.text)
def addEntry(settings, entry):
url = "http://" + settings['remote']['ipfsserver'] + ":" + settings['remote']['ipfsport'] + "/api/v0/add"
args = {
'quieter' : 'true',
'nocopy' : 'true',
'to-files' : DIRECTORY_SEPARATOR + entry['mfsPath']
}
args['to-files'] = args['to-files'].replace('\\', '/'),
fileHeaders = {
'Abspath': entry['remotePath']
}
data = MultipartEncoder(
fields= {
'part1': (entry['name'], open(entry['localPath'], 'rb'), 'application/octent-stream', fileHeaders)}
)
headers = {
'Content-Type': data.content_type
}
print('Adding ' + entry['mfsPath'])
try:
r = requests.post(url, data=data, params=args, headers=headers)
# data = dump.dump_all (r)
# print (data.decode ('utf-8'))
# If the response was successful, no Exception will be raised
r.raise_for_status()
except HTTPError as http_err:
if (r.status_code == 500):
err = r.json()
http_err = err['Message']
raise Exception(f'HTTP error occurred: {http_err}')
except Exception as err:
raise Exception(f'Other error occurred: {err}')
else:
result = r.json()
if ('Name' in result):
return
else:
raise Exception("Could not properly parse the return from an addition attempt of " + entry['mfsPath'] + ".\n" + r.content())
def addDirectory(settings, dir):
url = "http://" + settings['remote']['ipfsserver'] + ":" + settings['remote']['ipfsport'] + "/api/v0/files/mkdir"
args = {
'parents' : 'true',
'arg' : dir
}
args['arg'] = args['arg'].replace('\\', '/'),
print('Creating ' + dir)
try:
r = requests.post(url,params=args)
# data = dump.dump_all (r)
# print (data.decode ('utf-8'))
# If the response was successful, no Exception will be raised
r.raise_for_status()
except HTTPError as http_err:
if (r.status_code == 500):
err = r.json()
http_err = err['Message']
raise Exception(f'HTTP error occurred: {http_err}')
except Exception as err:
raise Exception(f'Other error occurred: {err}')
def main():
settings['remote']['ipfsport'] = str(settings['remote']['ipfsport'])
settings['remote']['maddr'] = '/ip4/' + settings['remote']['ipfsserver'] + '/tcp/' + settings['remote']['ipfsport']
# Load/set up the existing ipfs info
ipfsDb = {}
dbFile = Path(settings['options']['ipfsdbfilename'])
if settings['options']['refresh'] or not dbFile.is_file():
print("Loading IPFS info from " + settings['remote']['ipfsserver'] + ":" + settings['remote']['ipfsport'] + ".")
ipfsDb[settings['remote']['mfsrootdirectory'] + '/'] = grabCurrentIpfs(settings, '/' + settings['remote']['mfsrootdirectory'] + '/')
with open(settings['options']['ipfsdbfilename'],"w") as file:
file.write(json.dumps(ipfsDb))
else:
print("Loading IPFS info from existing file " + settings['options']['ipfsdbfilename'] + ".")
with open(settings['options']['ipfsdbfilename'],"r") as file:
ipfsDb = json.load(file)
print("Done loading IPFS info.")
# Load/set up the current TSL info
tslDb = {}
dbFile = Path(settings['options']['tsldbfilename'])
if settings['options']['refresh'] or not dbFile.is_file():
print("Loading TSL Library from " + settings['local']['tsldirectory'])
tslDb[settings['remote']['mfsrootdirectory'] + '/'] = grabCurrentTsl(settings, settings['local']['tsldirectory'])
with open(settings['options']['tsldbfilename'],"w") as file:
file.write(json.dumps(tslDb))
else:
print("Loading TSL Library from existing file " + settings['options']['tsldbfilename'] + ".")
with open(settings['options']['tsldbfilename'],"r") as file:
tslDb = json.load(file)
print("Done loading TSL Library.")
print("Comparing data and making changes.")
parsePaths(settings, '', ipfsDb, tslDb)
print("Done comparing data and making changes.")
main()