-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.py
178 lines (147 loc) · 5.02 KB
/
server.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
import tornado.ioloop
import tornado.web
import gzip
import logging
import downloader
import os
import sys
import hashlib
hash_lookup = {}
mimetable = {
".css": "text/css",
".eot": "application/octet-stream",
".html": "text/html",
".png": "image/png",
".svg": "image/svg+xml",
".ttf": "application/x-font-ttf",
".woff": "application/octet-stream",
".woff2": "application/octet-stream",
}
def sha_hash(content):
if type(content) == str:
content = content.encode('utf-8')
m = hashlib.sha256()
m.update(content)
return m.hexdigest()
def mime(path):
for i in mimetable:
if path.endswith(i):
return mimetable[i]
logging.warn('Mime type not found for' + path)
return 'text/plain'
def gzip_content(content):
h = sha_hash(content) + '.gzip'
if os.path.isfile(h):
with open(h, 'rb') as fin:
return fin.read()
with gzip.open(h, 'wb') as fout:
if type(content) == str:
content = content.encode('utf-8')
fout.write(content)
fout.close()
with open(h, 'rb') as fin:
return fin.read()
def has_gzip(self):
if 'Accept-Encoding' in self.request.headers:
if 'gzip' in self.request.headers['Accept-Encoding']:
return True
else:
return False
def smart_reply(self, resp):
if self.has_gzip():
if '--no-compress' not in sys.argv:
self.set_header('Content-Encoding', 'gzip')
self.write(gzip_content(resp))
return
self.write(resp)
class MainHandler(tornado.web.RequestHandler):
def get(self):
if self.request.path == '/':
path = os.path.join('web', 'index.html')
else:
if self.request.path.startswith('/'):
path = os.path.join('web', self.request.path[1:])
else:
path = os.path.join('web', self.request.path)
if not os.path.isfile(path):
self.set_status(404, 'Not Found')
self.set_header('Content-Type', 'text/html')
with open('web/404-generic.html') as fin:
resp = fin.read()
self.smart_write(resp)
self.finish()
return
with open(path, 'rb') as fin:
resp = fin.read()
if path in hash_lookup:
h = hash_lookup[path]
else:
h = sha_hash(resp)
hash_lookup[path] = h
if 'If-None-Match' in self.request.headers:
if h == self.request.headers['If-None-Match']:
self.set_status(304, "Unchanged")
self.set_header("Cache-Control", "no-cache, max-age=604800")
self.set_header("ETag", h)
self.finish()
return
self.set_status(200, 'OK')
self.set_header("Cache-Control", "no-cache, max-age=604800")
self.set_header("Content-type", mime(path))
self.set_header("ETag", h)
self.smart_write(resp)
self.finish()
class AudioHandler(tornado.web.RequestHandler):
def get(self):
link = self.get_argument('link')
path = os.path.join('mp3cache/', sha_hash(link))
if not os.path.exists(path):
try:
downloader.download_audio(link)
except Exception:
self.set_status(404, 'Not Found')
self.set_header('Content-Type', 'text/html')
with open('web/404-video.html') as fin:
self.smart_write(fin.read())
self.finish()
return
self.set_status(200, 'OK')
self.set_header('Content-Type', 'application/octet-stream')
with open(path, 'rb') as fin:
self.smart_write(fin.read())
self.finish()
class VideoHandler(tornado.web.RequestHandler):
def get(self):
link = self.get_argument('link')
path = os.path.join('mp4cache/', sha_hash(link))
if not os.path.exists(path):
try:
downloader.download_video(link)
except Exception:
self.set_status(404, 'Not Found')
self.set_header('Content-Type', 'text/html')
with open('web/404-video.html') as fin:
self.smart_write(fin.read())
self.finish()
return
self.set_status(200, 'OK')
self.set_header('Content-Type', 'application/octet-stream')
with open(path, 'rb') as fin:
self.smart_write(fin.read())
self.finish()
def make_app():
return tornado.web.Application([
(r"^/download\.mp3.*$", AudioHandler),
(r"^/download\.mp4.*$", VideoHandler),
(r"/.*", MainHandler),
])
MainHandler.smart_write = smart_reply
MainHandler.has_gzip = has_gzip
AudioHandler.smart_write = smart_reply
AudioHandler.has_gzip = has_gzip
VideoHandler.smart_write = smart_reply
VideoHandler.has_gzip = has_gzip
print("Server listening on {}".format(os.environ['PORT']))
app = make_app()
app.listen(os.environ['PORT'])
tornado.ioloop.IOLoop.current().start()