-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·213 lines (180 loc) · 4.96 KB
/
app.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
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from flask import (
Flask,
render_template,
request,
Response,
session
)
from werkzeug.contrib.fixers import ProxyFix
from flask.ext.scss import Scss
import settings
import logging
from werkzeug.exceptions import Unauthorized, BadRequest
from json import loads, dumps
from formatters import ColorFormatter
from time import time
from copy import copy
from urllib import quote_plus
import urllib2
# Create app
app = Flask(__name__)
app.config.from_object(settings)
app.wsgi_app = ProxyFix(app.wsgi_app)
Scss(app, static_dir='./static/css', asset_dir='./static/scss')
# Set up logging
handler = logging.StreamHandler()
handler.setFormatter(ColorFormatter())
logger = logging.root
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
log = logger
START = time()
INTERVAL = 30
SEASONS_PER_EPISODE = 10
DEFAULT_MOVIES = [
dict(
id=1,
name='Some movie',
url='http://google.com.ua',
last_season=3,
last_episode=5
),
dict(
id=2,
name='Some other movie',
url='http://google.com.ua',
last_season=8,
last_episode=14
),
dict(
id=3,
name='Some completely another movie',
url='http://google.com.ua',
last_season=13,
last_episode=37
),
]
users = {}
ID_SEQ = 4
def jsonify(fn):
'''
Decorator that allows Flask endpoints to return JSON objects.
'''
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
result = dumps(result)
return Response(result, headers={
'Content-type': 'application/json',
})
for param in ('name', 'doc'):
key = '__{}__'.format(param)
setattr(wrapper, key, getattr(fn, key))
return wrapper
def auth_required(fn):
'''
Decorator that requires user to be authenticated in order to get resource.
'''
def wrapper(*args, **kwargs):
if session.get('id', None) is None:
raise Unauthorized
return fn(*args, **kwargs)
for param in ('name', 'doc'):
key = '__{}__'.format(param)
setattr(wrapper, key, getattr(fn, key))
return wrapper
def init_g():
# Assumes that user is authorized.
if not users.get('movies-{}'.format(session['id'])):
users['movies-{}'.format(session['id'])] = copy(DEFAULT_MOVIES)
def urlencode_utf8(params):
if hasattr(params, 'items'):
params = params.items()
return '&'.join(
(quote_plus(k.encode('utf8'), safe='/') + '=' + quote_plus(v.encode('utf8') if isinstance(v, (str,unicode)) else str(v), safe='/')
for k, v in params))
@app.route("/")
def main():
return render_template("index.html")
@app.route("/auth")
def auth():
if request.args.get('email') == 'test' and request.args.get('password') == 'test':
session['id'] = 1337
return dumps({'authorized': True, 'access_token': 12345678})
elif request.args.get('email') == 'test' and request.args.get('password') == 'test':
session['id'] = 1337
return dumps({'authorized': True, 'access_token': 12345678})
else:
raise Unauthorized
@app.route("/episodes/")
@jsonify
@auth_required
def movies():
init_g()
return users.get('movies-{}'.format(session['id']))
@app.route("/episodes/", methods=['POST'])
@jsonify
@auth_required
def add_movie():
init_g()
global ID_SEQ
data = request.get_json()
name = str(data.get('name', ''))
if len(name) == 0:
raise BadRequest('Missing name.')
new_movie = dict(
id=ID_SEQ,
name=name,
url=None,
last_season=None,
last_episode=None
)
users['movies-{}'.format(session['id'])].append(new_movie)
ID_SEQ += 1
return new_movie
@app.route("/episodes/<int:id>", methods=['DELETE'])
@jsonify
@auth_required
def delete_movie(id):
init_g()
global ID_SEQ
user_movies = users.get('movies-{}'.format(session['id']))
for movie in user_movies:
if movie['id'] == id:
user_movies.remove(movie)
return True
@app.route('/rss.xml')
@jsonify
def rss():
result = []
diff = ((time() - START) / INTERVAL) + 10
for i in xrange(0, 10):
result.append({
'title': 'Endless story, season {}, episode {}'.format(int((diff - i)/10) + 1, int((diff - i) % 10) + 1)
})
return result
@app.route('/suggest/<string:query>')
@auth_required
@jsonify
def suggest(query):
args = dict(
callback='search',
q=query,
type='json',
topsuggest='true'
)
headers = {
'Referer': 'http://www.kinopoisk.ru',
'User-Agent': 'Mozilla/5.0',
'Accept-Encoding': 'UTF-8'
}
req = urllib2.Request('http://www.kinopoisk.ru/handler_search.php?{}'.format(urlencode_utf8(args)), headers=headers)
resp = urllib2.urlopen(req)
data = resp.read()
print data
data = loads(data)
return data
if __name__ == '__main__':
# Run app
app.run(host='0.0.0.0', port=8000)