This repository has been archived by the owner on Nov 12, 2019. It is now read-only.
/
app.py
341 lines (298 loc) · 10.1 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
import functools
import os
import re
from collections import namedtuple
from datetime import datetime, time
from dateutil.parser import parse as parse_datetime
from flask import Flask, jsonify, redirect, render_template, request
from flask_sslify import SSLify
from pyquery import PyQuery
import pytz
import requests
app = Flask(__name__)
Division = namedtuple("Division", ["name", "teams"])
Team = namedtuple("Team", ["name", "shortcode", "subreddit", "espn_url"])
DIVISIONS = [
Division("Atlantic", [
Team(
"Boston Celtics", "BOS", "bostonceltics",
"http://espn.go.com/nba/team/_/name/bos/boston-celtics",
),
Team(
"Brooklyn Nets", "BKN", "GoNets",
"http://espn.go.com/nba/team/_/name/bkn/brooklyn-nets",
),
Team(
"New York Knicks", "NYK", "NYKnicks",
"http://espn.go.com/nba/team/_/name/ny/new-york-knicks",
),
Team(
"Philadelphia 76ers", "PHI", "sixers",
"http://espn.go.com/nba/team/_/name/phi/philadelphia-76ers",
),
Team(
"Toronto Raptors", "TOR", "torontoraptors",
"http://espn.go.com/nba/team/_/name/tor/toronto-raptors"
),
]),
Division("Central", [
Team(
"Chicago Bulls", "CHI", "chicagobulls",
"http://espn.go.com/nba/team/_/name/chi/chicago-bulls"
),
Team(
"Cleveland Cavaliers", "CLE", "clevelandcavs",
"http://espn.go.com/nba/team/_/name/cle/cleveland-cavaliers"
),
Team(
"Detroit Pistons", "DET", "DetroitPistons",
"http://espn.go.com/nba/team/_/name/det/detroit-pistons"
),
Team(
"Indiana Pacers", "IND", "pacers",
"http://espn.go.com/nba/team/_/name/ind/indiana-pacers"
),
Team(
"Milwaukee Bucks", "MIL", "mkebucks",
"http://espn.go.com/nba/team/_/name/mil/milwaukee-bucks"
),
]),
Division("Southeast", [
Team(
"Atlanta Hawks", "ATL", "AtlantaHawks",
"http://espn.go.com/nba/team/_/name/atl/atlanta-hawks"
),
Team(
"Charlotte Hornets", "CHA", "CharlotteHornets",
"http://espn.go.com/nba/team/_/name/cha/charlotte-bobcats"
),
Team(
"Miami Heat", "MIA", "heat",
"http://espn.go.com/nba/team/_/name/mia/miami-heat"
),
Team(
"Orlando Magic", "ORL", "orlandomagic",
"http://espn.go.com/nba/team/_/name/orl/orlando-magic"
),
Team(
"Washington Wizards", "WAS", "washingtonwizards",
"http://espn.go.com/nba/team/_/name/wsh/washington-wizards"
),
]),
Division("Pacific", [
Team(
"Golden State Warriors", "GSW", "warriors",
"http://espn.go.com/nba/team/_/name/gs/golden-state-warriors"
),
Team(
"Los Angeles Clippers", "LAC", "LAClippers",
"http://espn.go.com/nba/team/_/name/lac/los-angeles-clippers"
),
Team(
"Los Angeles Lakers", "LAL", "lakers",
"http://espn.go.com/nba/team/_/name/lal/los-angeles-lakers"
),
Team(
"Phoenix Suns", "PHX", "SUNS",
"http://espn.go.com/nba/team/_/name/phx/phoenix-suns"
),
Team(
"Sacramento Kings", "SAC", "kings",
"http://espn.go.com/nba/team/_/name/sac/sacramento-kings"
),
]),
Division("Southwest", [
Team(
"Dallas Mavericks", "DAL", "Mavericks",
"http://espn.go.com/nba/team/_/name/dal/dallas-mavericks"
),
Team(
"Houston Rockets", "HOU", "rockets",
"http://espn.go.com/nba/team/_/name/hou/houston-rockets"
),
Team(
"Memphis Grizzlies", "MEM", "memphisgrizzlies",
"http://espn.go.com/nba/team/_/name/mem/memphis-grizzlies"
),
Team(
"New Orleans Pelicans", "NOP", "NOLAPelicans",
"http://espn.go.com/nba/team/_/name/no/new-orleans-hornets"
),
Team(
"San Antonio Spurs", "SAS", "NBASpurs",
"http://espn.go.com/nba/team/_/name/sa/san-antonio-spurs"
),
]),
Division("Northwest", [
Team(
"Denver Nuggets", "DEN", "denvernuggets",
"http://espn.go.com/nba/team/_/name/den/denver-nuggets"
),
Team(
"Minnesota Timberwolves", "MIN", "timberwolves",
"http://espn.go.com/nba/team/_/name/min/minnesota-timberwolves"
),
Team(
"Oklahoma City Thunder", "OKC", "Thunder",
"http://espn.go.com/nba/team/_/name/okc/oklahoma-city-thunder"
),
Team(
"Portland Trail Blazers", "POR", "ripcity",
"http://espn.go.com/nba/team/_/name/por/portland-trail-blazers"
),
Team(
"Utah Jazz", "UTA", "UtahJazz",
"http://espn.go.com/nba/team/_/name/utah/utah-jazz"
),
]),
]
CBS_SHORTCODE_MAP = {
"NYK": "NY",
"PHX": "PHO",
"NJN": "NJ",
"SAS": "SA",
"NOH": "NO",
"GSW": "GS",
}
def get_team(shortcode):
for div in DIVISIONS:
for team in div.teams:
if team.shortcode == shortcode:
return team
raise LookupError
@app.route("/")
def home():
return render_template("home.html", divisions=DIVISIONS)
@app.route("/reddit-stream/")
def reddit_stream():
if request.referrer is None:
return (
"This link works via magic. Click it from the normal comment page."
)
target = re.sub("pay.reddit.com", "reddit-stream.com", request.referrer)
target = re.sub("reddit.com", "reddit-stream.com", target)
target = re.sub("https://", "http://", target)
return redirect(target)
NBA_URL = (
"http://www.nba.com/games/{year}{month}{day}/"
"{away.shortcode}{home.shortcode}/gameinfo.html"
)
CBS_URL = (
"http://www.cbssports.com/nba/gametracker/preview/"
"NBA_{year}{month}{day}_{away}@{home}"
)
def sub_hours(orig_time, hours):
return time(orig_time.hour - hours, orig_time.minute).strftime("%I:%M")
def error(msg):
return jsonify(error=msg)
def handle_errors(func):
@functools.wraps(func)
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
if sentry is None:
raise
sentry.captureException()
return error(
"Uh oh. Something went wrong on our end. We've dispatched "
"trained monkeys to investigate."
)
return inner
NBA_RECORD_RE = re.compile(r"\((?P<wins>\d+)-(?P<losses>\d+)\)")
def find_espn_record(team):
r = requests.get(team.espn_url)
r.raise_for_status()
page = PyQuery(r.text)
text = page("#sub-branding").find(".sub-title").text()
record = text.split(",", 1)[0]
return record.split("-")
@app.route("/generate/", methods=["POST"])
@handle_errors
def generate():
try:
away = get_team(request.form["away"])
home = get_team(request.form["home"])
except LookupError:
return error("Please select a team.")
today = pytz.timezone("US/Mountain").fromutc(datetime.utcnow()).date()
nba_url = NBA_URL.format(
year=today.year,
month=str(today.month).zfill(2),
day=str(today.day).zfill(2),
away=away,
home=home,
)
cbs_away_shortcode = CBS_SHORTCODE_MAP.get(away.shortcode, away.shortcode)
cbs_home_shortcode = CBS_SHORTCODE_MAP.get(home.shortcode, home.shortcode)
cbs_url = CBS_URL.format(
year=today.year,
month=str(today.month).zfill(2),
day=str(today.day).zfill(2),
away=cbs_away_shortcode,
home=cbs_home_shortcode,
)
r = requests.get(nba_url)
if r.status_code == 404 or "Sorry, Page Not Found" in r.text:
return error(
"These teams don't seem to be playing each other tonight."
)
r.raise_for_status()
nba_page = PyQuery(r.text)
info = nba_page("#nbaGIStation").find(".nbaGITime").text()
if info is None:
return error("It looks like you reversed the home and the away team.")
gametime, stadium = info.split("-", 1)
gametime = parse_datetime(gametime.strip()).time()
gametimes = {
"est": sub_hours(gametime, 0),
"cst": sub_hours(gametime, 1),
"mst": sub_hours(gametime, 2),
"pst": sub_hours(gametime, 3),
}
stadium = stadium.strip()
records = nba_page("#nbaGITeamStats thead th")
home_rec = None
away_rec = None
if records and len(records) == 2:
[away_rec_el, home_rec_el] = records
match = NBA_RECORD_RE.search(home_rec_el.text_content())
if match is not None:
home_rec = match.groups()
match = NBA_RECORD_RE.search(away_rec_el.text_content())
if match is not None:
away_rec = match.groups()
if home_rec is None:
home_rec = find_espn_record(home)
if away_rec is None:
away_rec = find_espn_record(away)
r = requests.get(cbs_url, allow_redirects=False)
r.raise_for_status()
cbs_page = PyQuery(r.text)
tvs = []
for loc in ["National", "Away", "Home"]:
tv = cbs_page("td b:contains('{}:')".format(loc)).parent()
if tv:
tvs.append(tv[0].text_content())
return jsonify(
title=render_template(
"title.txt",
away=away, away_rec=away_rec,
home=home, home_rec=home_rec,
today=today),
body=render_template(
"gamethread.txt",
away=away, home=home, tv=", ".join(tvs),
gametimes=gametimes, stadium=stadium, nba_url=nba_url,
host=request.host,
),
)
def configure_raven(app):
if 'SENTRY_DSN' in os.environ:
from raven.contrib.flask import Sentry
return Sentry(app)
sentry = configure_raven(app)
sslify = SSLify(app, permanent=True)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port, debug=True)