-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
232 lines (192 loc) · 6.52 KB
/
main.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
import ipfshttpclient
import requests
import urllib
import os
import json
def makeConnection():
return ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001')
#if __name__ == '__main__':
# makeConnection()
# dison = {}
# dison["A"] = "B"
# dison["C"] = "D"
# lkj = json.dumps(dison)
# file = open("json.txt", "w")
# file.write(json.dumps(dison))
# file.close()
# print (lkj)
class IPFS():
def __init__(self):
print ("Connecting to IPFS")
self.client = ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001')
self.pinLS()
def addPin(self, fileLocation):
return self.client.add(fileLocation, pin = True)
def pinLS(self):
aList = self.client.pin.ls()
json_Obj = aList["Keys"]
self.pins = []
for each in json_Obj:
self.pins.append(each)
#print (json_Obj)
#print (json.dumps(aList["Keys"]).keys())
def createKey(self):
try:
key = self.client.key.gen(type="rsa", size=4096, key_name="HydrusDB")
return key["Id"]
except:
keyEx = self.client.key.list()["Keys"]
lis = []
for each in keyEx:
if each["Name"] == "HydrusDB":
return each["Id"]
#print (keyEx["Keys"].values())
quit()
def jsonPin(self):
if not os.path.exists("hashTags.json"):
hsh = open("hashTags.json", "w")
hsh.close()
self.jsonRef = self.client.add("hashTags.json", pin = True)["Hash"]
#print (self.jsonRef)
def publishChanges(self):
publish = self.client.name.publish(self.jsonRef, key="HydrusDB")
print ("IPNS Name is: ",publish["Name"])
class hydrusSetup():
access_key = None
ip = "localhost"
port = 45869
conf = "conf.json"
searchParams = []
hydrusDBLocation = None
ipfsKey = None
IPFSObj = IPFS()
def __init__(self):
if (os.path.exists(self.conf)):
with open(self.conf, 'r') as myfile:
data=myfile.read()
obj = json.loads(data)
#self. = str(obj[''])
self.access_key = str(obj['access_key'])
self.ip = str(obj['ip'])
self.port = str(obj['port'])
self.hydrusDBLocation = str(obj['hydrusDBLocation'])
self.searchParams = str(obj["searchParams"]).replace("'", '"')
self.ipfsKey = str(obj['ipfsKey'])
myfile.close()
self.startRunning()
else:
self.initialConnect()
dison = {}
#dison[""] = self.
dison["access_key"] = self.access_key
dison["ip"] = self.ip
dison["port"] = self.port
dison["ipfsKey"] = self.IPFSObj.createKey()
print ("Please enter the search terms that you would like hydrus to automatically pin to ipfs.")
self.searchParams = input("Space Seperated: ")
dison["searchParams"] = self.searchParams.split()
print ("Please enter the absolute Location of your hydrus database. (Where Client File is.)")
print ("Cannot use ~ to shorten /home/username/")
self.hydrusDBLocation = input(":")
dison["hydrusDBLocation"] = self.hydrusDBLocation
with open(self.conf, 'w') as myfile:
myfile.write(json.dumps(dison))
myfile.close()
def startRunning(self):
print ("Running Hydrus IPFS Pinner using tags:")
print (self.searchParams)
print ()
self.searchTags()
self.pinFiles()
self.createJSON()
self.manageJSON()
def manageJSON(self):
self.IPFSObj.jsonPin()
self.IPFSObj.publishChanges()
def createJSON(self):
jsonDump = {}
for each in self.IPFSHash:
tag = self.tags[self.IPFSHash.index(each)]
jsonDump[each] = tag
if len(jsonDump) > 0:
with open('hashTags.json', 'w') as outfile:
json.dump(jsonDump, outfile)
def pinFiles(self):
notSucceed = False
self.IPFSHash = []
for each in self.hashes:
if (os.path.exists(self.hydrusDBLocation + "f" + str(each[0])+ str(each[1]))):
#print (self.hashes.index(each))
self.IPFSHash.append(self.IPFSObj.addPin(self.hydrusDBLocation + "f" + str(each[0])+ str(each[1]) + "/" + str(each) + self.exts[self.hashes.index(each)])["Hash"])
else:
notSucceed = True
if (notSucceed):
print ("Could not find your files. Did you set the location correctly?")
quit()
def searchTags(self):
print ("Access Key ",self.access_key)
ReqHeader = {'Hydrus-Client-API-Access-Key': str(self.access_key)}
try:
r = requests.get('http://' + str(self.ip) + ':' + self.port + '/get_files/search_files?' + '&tags=' +
str(urllib.parse.quote(self.searchParams, safe='')),
headers=ReqHeader)
#print (str(self.searchParams))
#print (r)
#print (r.content)
except:
print ("Error Connecting to client: is it currently accepting API Requests?")
print ("Go to Services -> Manage Services -> Client API and uncheck do not run client service.")
quit()
if (r.status_code == 409):
print ("Client is on and not accepting API requests go to:")
print ("Services -> Review Services -> Client API -> add -> from api request")
quit()
else:
#print (str(urllib.parse.quote(str(json.loads(r.content)["file_ids"]), safe='')))
try:
r = requests.get('http://' + str(self.ip) + ':' + self.port + '/get_files/file_metadata?file_ids=' +
str(urllib.parse.quote(str(json.loads(r.content)["file_ids"]), safe='')),
headers=ReqHeader)
except:
print ("A mysterious error has occured lel")
print (r.content)
F = json.loads(r.content)
f = F["metadata"]
self.hashes = []
self.exts = []
self.tags = []
for each in f:
#print (each["hash"])
self.hashes.append(each["hash"])
self.exts.append(each["ext"])
self.tags.append(list(each["service_names_to_statuses_to_tags"]["my tags"].values())[0])
print ("Pulled: " + str(len(self.hashes)) + " Hashes from Hydrus.")
print ("Pinning to IPNS Please Wait")
return
def initialConnect(self):
ReqHeader = {'User-Agent': 'Hydrus Utilize - Mobile'}
try:
r = requests.get('http://' + str(self.ip) + ':' + str(self.port) + '/request_new_permissions?' +
'name=Hydrus%20IPFS%20Searcher&basic_permissions=[0,1,2,3,4]',
headers=ReqHeader)
except Exception as a:
if a != None:
print ("ERROR: ", a)
quit()
print ("Error Connecting to client: is it currently accepting API Requests?")
print ("Go to Services -> Manage Services -> Client API and uncheck do not run client service.")
quit()
if (r.status_code == 409):
print ("Client is on and not accepting API requests go to:")
print ("Services -> Review Services -> Client API -> add -> from api request")
quit()
else:
self.access_key = json.loads(r.content)["access_key"]
return
## Share TCP connections using a context manager
#with ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001') as client:
# hash = client.add('test.txt')['Hash']
# key =client.object.put("HYDRUSDB-FILE")
# print(key)
# print(key["Hash"])
main = hydrusSetup()