-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimServer.py
82 lines (60 loc) · 1.92 KB
/
simServer.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
from flask import Flask, url_for, request
from sqlalchemy import create_engine, text
app = Flask(__name__)
app.debug = False
engine = create_engine("postgresql://gaoyb7@localhost/dht_demo")
conn = engine.connect()
search_form = \
"""
<form method="GET" action="/search">
<input id="kw" name="kw" />
<button type="submit">search</button>
</form>
"""
@app.route("/")
def main_page():
return "Total torrents: " + str(torrent_count()) + "</br>" + search_form
@app.route("/about")
def about():
return "A simple Torrent Search Engine based on DHT protocol"
@app.route("/search")
def search():
page = "Total torrent: " + str(torrent_count()) + "</br>" + search_form
page += "</br>"
page += "Result: </br>"
kw = request.args.get("kw").strip().replace("-", " ")
if kw == "":
return "None"
kw = ":* & ".join(kw.split()) + ":*"
precheck_cmd = '''select to_tsquery('english', '%s')''' % kw
r = conn.execute(precheck_cmd)
print(precheck_cmd)
if r.fetchone()[0] == "":
return "None"
cmd = '''select * from hash_tab where to_tsvector('english', name) @@ \
to_tsquery('english', '%s')''' % kw
r = conn.execute(cmd)
page = "Total torrents: " + str(torrent_count()) + "</br>" + search_form
page += "</br>"
page += "Result: " + str(r.rowcount) + " items</br>"
ct = 0
for item in r:
ct += 1
if ct > 100:
break
page += "Name: " + item[1] + "</br>"
page += "Magnet: " + to_magnet(item[0], item[1]) + "</br>"
page += "</br>"
return page
def to_magnet(infohash, name):
magnet = "magnet:?xt=urn:btih:" + infohash
magnet += "&dn=" + name
return magnet
def torrent_count():
cmd = "select count(*) from hash_tab"
r = conn.execute(cmd)
for x in r:
return x[0]
if __name__ == "__main__":
#app.run()
app.run(host="0.0.0.0", port=5000)