This repository has been archived by the owner on Jul 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
222 lines (185 loc) · 6.19 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
import webapp2
import json
import urllib2
import base64
import time
import yaml
xTransmissionSessionId = None
torrent_fields = [
"addedDate",
"id",
"name",
"error",
"errorString",
"status",
"totalSize",
"downloadedEver",
"rateDownload",
"isFinished",
"rateUpload",
"rateDownload",
"uploadedEver",
"uploadRatio"
]
with open("config.yaml") as data:
config = yaml.load(data)
class Transmission():
def post(self, data):
global xTransmissionSessionId
base64string = base64.encodestring('%s:%s' % (config["rpc"]["user"], config["rpc"]["pw"])).replace('\n', '')
headers = {
"X-Transmission-Session-Id": xTransmissionSessionId,
"Authorization": "Basic %s" % base64string
}
req = urllib2.Request(config["rpc"]["url"], json.dumps(data), headers)
retry = False
res = None
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e
if e.code == 409:
retry = True
xTransmissionSessionId = e.headers.getheader("X-Transmission-Session-Id")
finally:
if retry:
return self.post(data)
else:
result_body = res.read()
return json.loads(result_body)
class ResponseDecorator():
def __init__(self, response):
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Methods", "DELETE, GET, OPTIONS, PATCH, POST, PUT")
response.headers.add("Access-Control-Allow-Headers", "Content-Type, Location")
self.response = response
def write(self, body):
self.response.headers.add("Content-Type", "application/json")
json_body = json.dumps(body)
self.response.write(json_body)
class Torrent(webapp2.RequestHandler):
def options(self, torrent_id):
ResponseDecorator(self.response)
def patch(self, torrent_id):
try:
body = json.loads(self.request.body)
method = body["method"]
except ValueError, e:
print e
data = {
"method": method,
"arguments": {
"ids": [int(torrent_id)]
}
}
transmission = Transmission()
transmission_result = transmission.post(data)
if method == "torrent-stop":
status = 0
else:
status = 6 if body["x_isFinished"] else 4
self.response.set_status(200)
ResponseDecorator(self.response).write({ "status": status })
def put(self, torrent_id):
try:
body = json.loads(self.request.body)
method = body["method"]
except ValueError, e:
print e
data = {
"method": method,
"arguments": {
"ids": [int(torrent_id)]
}
}
transmission = Transmission()
transmission_result = transmission.post(data)
# self.response.headers.add("Location", "/torrent/%s" % torrent_id)
self.response.set_status(202)
ResponseDecorator(self.response)
def delete(self, torrent_id):
delete_local_data = False
if len(self.request.body) > 0:
try:
body = json.loads(self.request.body)
delete_local_data = body["delete_local_data"]
except ValueError, e:
print e
data = {
"method": "torrent-remove",
"arguments": {
"ids": [int(torrent_id)],
"delete-local-data": delete_local_data
}
}
transmission = Transmission()
transmission_result = transmission.post(data)
ResponseDecorator(self.response)
def get(self, torrent_id):
global torrent_fields
data = {
"method": "torrent-get",
"arguments": {
"fields": torrent_fields,
"ids": [int(torrent_id)]
}
}
transmission = Transmission()
transmission_result = transmission.post(data)
torrents = transmission_result["arguments"]["torrents"]
if len(torrents) > 0:
ResponseDecorator(self.response).write(torrents[0])
else:
self.response.set_status(404)
ResponseDecorator(self.response)
class Torrents(webapp2.RequestHandler):
def options(self):
ResponseDecorator(self.response)
def post(self):
body = self.request.body
inputs = json.loads(body)
data = {
"method": "torrent-add",
"arguments": {
"filename": inputs["uri"]
}
}
transmission = Transmission()
transmission_result = transmission.post(data)
result = transmission_result["result"]
if result == "success":
args = transmission_result["arguments"]
try:
torrent_id = args["torrent-added"]["id"]
except KeyError, e:
torrent_id = args["torrent-duplicate"]["id"]
finally:
ResponseDecorator(self.response)
self.response.set_status(201)
self.response.headers.add("Location", "/torrent/%s" % torrent_id)
else:
self.response.set_status(500)
ResponseDecorator(self.response).write(result)
def get(self):
data = {
"method": "torrent-get",
"arguments": {
"fields": torrent_fields
}
}
transmission = Transmission()
transmission_result = transmission.post(data)
torrents = transmission_result["arguments"]["torrents"]
ResponseDecorator(self.response).write(torrents)
allowed_methods = webapp2.WSGIApplication.allowed_methods
new_allowed_methods = allowed_methods.union(('PATCH',))
webapp2.WSGIApplication.allowed_methods = new_allowed_methods
app = webapp2.WSGIApplication([
("/torrent", Torrents),
("/torrent/(.*)", Torrent)
], debug=True)
def main():
from paste import httpserver
httpserver.serve(app, host=config["server"]["ip"], port=config["server"]["port"])
if __name__ == '__main__':
main()