/
app.py
357 lines (321 loc) · 13.4 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import json
import os
import time
import traceback
import random
import boto3
from chalice import Chalice, Response
from cachetools import TTLCache
import requests
from durations import Duration
from durations.exceptions import ScaleFormatError, InvalidTokenError
app = Chalice(app_name='hujjatytproxy')
CACHE = TTLCache(maxsize=10, ttl=30)
DYNAMODB_IF_STREAM_TTL = 900
DYNAMODB_IF_NO_STREAM_TTL = 200
BEFORE_GOING_OFFLINE = 900
MIN_TIME_BEFORE_UPSTREAM_CHECKS = 200
MAX_GRACE_PERIOD = 100
GRACE_PERIOD = random.choice(range(MAX_GRACE_PERIOD)) # this is to for all nodes to not go and query at the same time
CHANNELS = {
# "mainhall": "UCSSgKFdC-gRtxIgTrGGqP3g",
"elc": "UCvjUFF1C3yO2KK17EjpiWGQ",
# "ladies": "UCPOs_KwzIUfBq5sNR8IJynw"
}
DEFAULT_PARAMS = {
"order": "date",
"maxResults": "1",
"type": "video",
"eventType": "live",
"safeSearch": "none",
"videoEmbeddable": "true",
"part": "snippet"
}
def reset_cache():
global CACHE
CACHE = TTLCache(maxsize=10, ttl=30)
def get_cache():
return CACHE
def default_expiry(now):
return now + BEFORE_GOING_OFFLINE
class RealYoutubeDynamodb:
@classmethod
def get_from_dynamodb(cls, channel):
try:
client = boto3.client('dynamodb')
if 'TABLE' in os.environ:
result = client.get_item(Key={'channel': {'S': channel}}, TableName=os.environ['TABLE'])
if 'Item' in result:
return result['Item']
except Exception as exc:
print("Exception retrieving from dynamodb: %s" % (exc,))
traceback.print_exc()
return None
@classmethod
def write_to_dynamodb(cls, channel, result, expiry_time=None):
try:
client = boto3.client('dynamodb')
if 'TABLE' in os.environ:
now = time.time()
if not expiry_time:
expiry_time = default_expiry(now)
result = client.put_item(
Item={
'channel': {'S': channel},
'time': {'N': str(now)},
'last_checked_time': {'N': str(now)},
'expiry_time': {'N': str(expiry_time)},
'result': {'S': json.dumps(result)}},
TableName=os.environ['TABLE'])
except Exception as exc:
print("Exception writing to dynamodb: %s" % (exc,))
traceback.print_exc()
return None
@classmethod
def update_dynamodb(cls, channel, result, create_time, expiry_time=None):
try:
client = boto3.client('dynamodb')
if 'TABLE' in os.environ:
print(f"Updating dynamodb for {channel} with a current last_checked_time")
if not expiry_time:
expiry_time = default_expiry(create_time)
result = client.put_item(
Item={
'channel': {'S': channel},
'time': {'N': str(create_time)},
'last_checked_time': {'N': str(time.time())},
'expiry_time': {'N': str(expiry_time)},
'result': {'S': json.dumps(result)}},
TableName=os.environ['TABLE'])
except Exception as exc:
print("Exception writing to dynamodb: %s" % (exc,))
traceback.print_exc()
return None
@classmethod
def request_from_youtube(cls, params, key_origin):
r = requests.get("https://www.googleapis.com/youtube/v3/search", params=params)
print(f"Youtube API Request for {params.get('channelId')} with key origin {key_origin}")
try:
result = r.json()
except json.decoder.JSONDecodeError:
result = r.text
print(f"Youtube API Response code: {r.status_code} for {params.get('channelId')} with key origin {key_origin}")
return r.status_code, result
def are_there_videos(result):
if not result:
return False
return result.get('pageInfo', {}).get('totalResults', 0) > 0
def do_search_on_youtube(params, youtube_and_dynamodb=RealYoutubeDynamodb):
channel = params.get("channelId")
result = CACHE.get(channel)
if result:
return 200, result, 'cache', None, None
else:
dresult = None
decoded_dresult = None
create_time = 0
last_checked_time = 0
expiry_time = 0
item = youtube_and_dynamodb.get_from_dynamodb(channel)
try:
if item:
dresult = item.get('result', {}).get('S')
create_time = item.get('time').get('N')
expiry_time = item.get('expiry_time', {"N": default_expiry(int(float(create_time)))}).get('N')
last_checked_time = item.get('last_checked_time', {"N": "0"}).get('N')
if create_time and dresult:
create_time = int(float(create_time))
decoded_dresult = json.loads(dresult)
ttl = DYNAMODB_IF_STREAM_TTL if are_there_videos(decoded_dresult) else DYNAMODB_IF_NO_STREAM_TTL
now = time.time()
if now - create_time < ttl:
print(f"Using Dynamodb result as within ttl: now={now} create_time={create_time} ttl={ttl}")
return 200, decoded_dresult, 'dynamodb', None, None
except Exception as exc:
print("Exception decoding from dynamodb: %s" % (exc,))
traceback.print_exc()
return request_from_youtube_and_write_to_cache(
params, decoded_dresult, create_time,
int(float(last_checked_time)), int(float(expiry_time)), youtube_and_dynamodb)
def pick_youtube_api_key():
keys = os.environ.get("YOUTUBE_API_KEYS", 'test_key:blah')
all_keys = []
for key in keys.split(','):
origin, value = key.split(':')
all_keys.append((origin, value))
choice = random.choice(all_keys)
return choice
def request_from_youtube_and_write_to_cache(params, decoded_dresult=None, create_time=0, last_checked_time=0,
expiry_time=0, youtube_and_dynamodb=RealYoutubeDynamodb):
channel = params.get("channelId")
try:
key_origin = None
if not params.get("key"):
key_origin, params["key"] = pick_youtube_api_key()
else:
key_origin = "provided_in_apicall"
since_last_check = time.time() - last_checked_time
if since_last_check > MIN_TIME_BEFORE_UPSTREAM_CHECKS + GRACE_PERIOD:
print(f"Going to youtube to check because last check was done {since_last_check} ago")
status_code, result = youtube_and_dynamodb.request_from_youtube(params, key_origin)
if status_code == requests.codes.ok:
now = time.time()
if (are_there_videos(decoded_dresult) and not are_there_videos(result) and
expiry_time > now):
print(
f"Still using dynamodb result because youtube had no videos and "
f"{now - expiry_time} seconds left until expiry")
youtube_and_dynamodb.update_dynamodb(channel, decoded_dresult, create_time, expiry_time)
return (
200, decoded_dresult, 'dynamodb',
f"youtube status {status_code} with data {result}", key_origin)
print(f"Caching result for {channel} from youtube")
CACHE[channel] = result
youtube_and_dynamodb.write_to_dynamodb(channel, result)
return status_code, result, 'youtube', f"youtube status {status_code}", key_origin
else:
print(f"Youtube returned {status_code}")
if decoded_dresult:
youtube_and_dynamodb.update_dynamodb(channel, decoded_dresult, create_time)
return (
200, decoded_dresult, 'dynamodb',
f"youtube status {status_code} with data {result}", key_origin)
else:
return 500, {}, 'youtube', f"youtube status {status_code} with data {result}", key_origin
else:
print(f"Using dynamodb because last check was done {since_last_check} ago")
if decoded_dresult:
return 200, decoded_dresult, 'dynamodb', None, None
except Exception as exc:
print(exc)
return 500, {}, 'youtube', f"error {exc}", key_origin
def force_video_id(video_id, channel, ttl, youtube_and_dynamodb=RealYoutubeDynamodb):
channel_id = CHANNELS[channel]
if video_id:
result = json.loads("""
{
"kind": "youtube#searchListResponse",
"etag": "8jEFfXBrqiSrcF6Ee7MQuz8XuAM/IzvFVgDabZ_mOGJl5FfbgvJqoL4",
"regionCode": "IE",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "8jEFfXBrqiSrcF6Ee7MQuz8XuAM/fu3EinHUWmS-3Hb0Csc8-lKjhpk",
"id": {
"kind": "youtube#video",
"videoId": "KTf2_GL_6lA"
},
"snippet": {
"publishedAt": "2019-09-06T21:35:13.000Z",
"channelId": "UCSSgKFdC-gRtxIgTrGGqP3g",
"title": "The KSIMC of London - Stanmore - Main Hall Live Stream",
"description": "",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/KTf2_GL_6lA/default_live.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/KTf2_GL_6lA/mqdefault_live.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/KTf2_GL_6lA/hqdefault_live.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "The KSIMC of London - Stanmore - Main Hall",
"liveBroadcastContent": "live"
}
}
]
}""")
result["items"][0]["id"]["videoId"] = video_id
else:
result = """
{
"kind": "youtube#searchListResponse",
"etag": "8jEFfXBrqiSrcF6Ee7MQuz8XuAM/nxmhARCBNQQrPOpwtM0UNWBXCsg",
"regionCode": "IE",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 1
},
"items": []
}"""
youtube_and_dynamodb.write_to_dynamodb(channel_id, result, time.time() + ttl)
@app.route('/v3/search', cors=True)
def youtube():
status_code, result, how = do_search_on_youtube(app.current_request.query_params)
if status_code == requests.codes.ok:
return result
else:
return Response(
body=json.dumps(result),
status_code=status_code,
headers={"Content-Type": "application/json"})
@app.route('/live', cors=True)
def any_live():
return live(skip_cache=False)
@app.route('/refresh', cors=True)
def refresh_cache():
return live(skip_cache=True)
def live(skip_cache=False):
results = {}
any_live = False
for channel, id in CHANNELS.items():
params = {}
params.update(DEFAULT_PARAMS)
params["channelId"] = id
if skip_cache:
status_code, result, how, info, key_origin = request_from_youtube_and_write_to_cache(params)
else:
status_code, result, how, info, key_origin = do_search_on_youtube(params)
print(
f"Retrieved {channel} from {how} with status_code {status_code} with info: {info}"
f"and key origin: {key_origin}")
if status_code == requests.codes.ok:
if len(result.get("items", [])) > 0:
any_live = True
results[channel] = {
"status_code": status_code,
"result": result,
"how": how,
"extra_info": info,
"key_origin": key_origin}
results["any_live"] = any_live
return results
@app.route('/ping', cors=True)
def ping():
if False:
client = boto3.client('dynamodb')
result = client.get_item(Key={'channel': {'S': 'mainhall'}}, TableName=os.environ['TABLE'])
client.put_item(
Item={
'channel': {'S': 'mainhall'},
'time': {'N': str(time.time())},
'result': {'S': json.dumps(result['Item'])}},
TableName=os.environ['TABLE'])
return Response(body=json.dumps({}), status_code=200)
@app.route('/forcevideo', cors=True)
def force_video():
video_id = app.current_request.query_params.get('videoId')
channel = app.current_request.query_params.get('channel')
ttl = app.current_request.query_params.get('ttl')
try:
duration = Duration(ttl).to_seconds()
except (InvalidTokenError, ScaleFormatError, ValueError):
return Response(body=json.dumps({}), status_code=400)
if channel not in CHANNELS:
return Response(body=json.dumps({}), status_code=400)
if video_id:
return force_video_id(video_id, channel, duration)
else:
return Response(body=json.dumps({}), status_code=400)