def reactivate_dj(setid): djset = DJSet.query.get_or_404(setid) form = DJReactivateForm() # if neither phone nor email is missing, someone is doing silly things if djset.dj.email is not None and djset.dj.phone is not None: return redirect(url_for('.log', setid=setid)) if form.is_submitted(): if form.validate(): djset.dj.email = form.email.data djset.dj.phone = form.phone.data db.session.commit() if request.wants_json(): return jsonify(success=True) else: return redirect(url_for('.log', setid=setid)) elif request.wants_json(): return jsonify(success=False, errors=form.errors) return render_template('trackman/reactivate.html', trackman_name=current_app.config['TRACKMAN_NAME'], form=form, dj=djset.dj)
def search(): incr,start,next,prev = parse_qs(request.args) query = request.args.get('query', None) if not query: if request.wants_json(): return json_nyi() return render_template('search.html', nav=navs) if request.wants_json(): return json_nyi() return render_template('search.html', nav=navs, quotes=db.search(query, incr, start), title="Search Results for '%s'" %(query), next=next, prev=prev, page="search", query=query)
def crack_submissions(password_id): password = Password.query.get_or_404(password_id) submissions = db.session.query(PasswordEntry, Handle).\ filter(PasswordEntry.password == password.id).\ join(Handle, Handle.id == PasswordEntry.handle).\ order_by(PasswordEntry.datetime).all() if request.wants_json(): def serialize_date(item): item['datetime'] = str(item['datetime']) return item subdata = [] for entry, handle in submissions: subdata.append({ 'entry': serialize_date(entry.serialize()), 'handle': handle.serialize(), }) return jsonify({ 'flag': flag.serialize(), 'submissions': subdata, }) return render_template('crack_submissions.html', CTF_NAME=app.config['CTF_NAME'], password=password, submissions=submissions)
def charts_artists(period=None, year=None, month=None): if period == 'dj' and year is not None: return redirect(url_for('.charts_artists_dj', dj_id=year)) try: start, end = charts.get_range(period, year, month) except ValueError: abort(404) results = charts.get( 'artists_{0}_{1}'.format(start, end), Track.query.with_entities(Track.artist, db.func.count( TrackLog.id)).join(TrackLog).filter( db.and_(TrackLog.dj_id > 1, TrackLog.played >= start, TrackLog.played <= end)).group_by( Track.artist).order_by( db.func.count(TrackLog.id).desc())) if request.wants_json(): return jsonify({ 'results': [(x[0], x[1]) for x in results], }) return render_template('chart_artists.html', start=start, end=end, results=results)
def create_quote_form(): ip = request.remote_addr type = request.headers['Content-Type'] tags = [] tags_valid = True body_valid = True content = request.form['quote'] # strip trailing whitespace at each line content_lines = content.splitlines() for i, l in enumerate(content_lines): content_lines[i] = l.rstrip() content = '\n'.join(content_lines) logger.info(content) tags_raw = request.form['tags'] # a smidgen of validation if len(tags_raw) > 100: tags_valid = False else: tags = map(string.strip, tags_raw.split(',')) body_valid, tags_valid = validate_quote(content, tags) quote = None if body_valid and tags_valid: quote = Quote(content, ip) quote.tags = map(Tag, tags) quote = db.put(quote) # grabbing return val isn't strictly necessary if request.wants_json(): return create_quote_resp_json(quote, body_valid, tags_valid) else: return create_quote_resp_html(quote, body_valid, tags_valid)
def create_quote_form(): ip = request.remote_addr type = request.headers['Content-Type'] tags = [] tags_valid = True body_valid = True content = request.form['quote'] # strip trailing whitespace at each line content_lines = content.splitlines() for i,l in enumerate(content_lines): content_lines[i] = l.rstrip() content = '\n'.join(content_lines) logger.info(content) tags_raw = request.form['tags'] # a smidgen of validation if len(tags_raw) > 100: tags_valid = False else: tags = map(string.strip, tags_raw.split(',')) body_valid, tags_valid = validate_quote(content, tags) quote = None if body_valid and tags_valid: quote = Quote(content, ip) quote.tags = map(Tag, tags) quote = db.put(quote) # grabbing return val isn't strictly necessary if request.wants_json(): return create_quote_resp_json(quote, body_valid, tags_valid) else: return create_quote_resp_html(quote, body_valid, tags_valid)
def submit_password(): entered_handle = request.form['handle'].strip() if len(entered_handle) <= 0: return make_error(request, "Please enter a handle.") handle = Handle.get(entered_handle) counts = {'good': 0, 'notfound': 0, 'bad': 0, 'duplicate': 0} entered_pws = request.form['passwords'].strip().splitlines() for entered_pw in entered_pws: entered_pw = entered_pw.split(':', 1) if len(entered_pw) <= 1: return make_error(request, "Cracked passwords must be in the " "hashed:plaintext format.") password = Password.get(entered_pw[0]) if not password: # hash not found in DB counts['notfound'] += 1 elif ctfengine.crack.lib.hashpw(password.algo, entered_pw[1]) !=\ password.password: # plaintext is not correct for hash counts['bad'] += 1 else: if not handle: # handle does not exist, create handle = Handle(entered_handle, 0) db.session.add(handle) db.session.commit() # look for existing entries existing_entry = PasswordEntry.query.filter( PasswordEntry.handle == handle.id, PasswordEntry.password == password.id).first() if existing_entry: counts['duplicate'] += 1 else: counts['good'] += 1 # update points for user handle.score += password.points # log password submission entry = PasswordEntry(handle.id, password.id, entered_pw[1], request.remote_addr, request.user_agent.string) db.session.add(entry) db.session.commit() if counts['good'] > 0: sse.send("score: {handle_id:d}: password".format(handle_id=handle.id)) if request.wants_json(): return jsonify({'status': counts}) flash("{good} passwords accepted, {notfound} not found in database, " "{duplicate} passwords already scored, and {bad} incorrect " "plaintexts.".format(**counts)) return redirect(url_for('index'))
def logout(setid): session.pop('djset_id', None) djset = DJSet.query.get_or_404(setid) if djset.dtend is None: djset.dtend = datetime.datetime.utcnow() else: # This has already been logged out return redirect(url_for('.login')) db.session.commit() redis_conn.publish('trackman_dj_live', json.dumps({ 'event': "session_end", })) # Reset the dj activity timeout period redis_conn.delete('dj_timeout') # Set dj_active expiration to NO_DJ_TIMEOUT to reduce automation start time redis_conn.set('dj_active', 'false') redis_conn.expire('dj_active', int(current_app.config['NO_DJ_TIMEOUT'])) # email playlist if 'email_playlist' in request.form and \ request.form.get('email_playlist') == 'true': email_playlist.delay(djset.id) if request.wants_json(): return jsonify(success=True) else: return redirect(url_for('.login'))
def playlists_dj(): djs = DJ.query.order_by(DJ.airname).filter(DJ.visible == True) if request.wants_json(): return jsonify({'djs': [dj.serialize() for dj in djs]}) return render_template('playlists_dj_list.html', djs=djs)
def charts_dj_spins(): results = call_api("/charts/dj/spins", 'GET') if request.wants_json(): return jsonify(results) return render_template('chart_dj_spins.html', results=results['results'])
def playlists_dj_all(): djs = DJ.query.order_by(DJ.airname).all() if request.wants_json(): return jsonify({'djs': [dj.serialize() for dj in djs]}) return render_template('playlists_dj_list_all.html', djs=djs)
def charts_tracks(period=None): try: start, end = charts.get_range(period, request) except ValueError: abort(400) subquery = TrackLog.query.\ with_entities(TrackLog.track_id, db.func.count(TrackLog.id).label('count')).\ filter(TrackLog.dj_id > 1, TrackLog.played >= start, TrackLog.played <= end).\ group_by(TrackLog.track_id).subquery() results = charts.get( 'tracks_{start}_{end}'.format(start=start, end=end), Track.query.with_entities(Track, subquery.c.count).join(subquery).order_by( db.desc(subquery.c.count))) if request.wants_json(): return jsonify({ 'results': [(x[0].serialize(), x[1]) for x in results], }) return render_template('chart_tracks.html', start=start, end=end, results=results)
def latest(): incr, start, next, prev = parse_qs(request.args) quotes = db.latest(incr, start) admin = authDB.isAuthenticated(request) if request.wants_json(): next_link = '/quotes?start=%s' % (next) prev_link = '/quotes?start=%s' % (prev) json = { 'quotes': quotes, 'links': [ build_link(next_link, 'pyqdb/quotes/next', Quote.list_json_mimetype), build_link(prev_link, 'pyqdb/quotes/prev', Quote.list_json_mimetype) ] } rs = jsonify(json, Quote.list_json_mimetype) add_link_hdr(rs, next_link, 'pyqdb/quotes/next') if start > 0: add_link_hdr(rs, prev_link, 'pyqdb/quotes/prev') return rs return render_template('quotes.html', nav=navs, quotes=quotes, page='quotes', next=next, prev=prev, isAdmin=admin)
def create_quote_form(): ip = request.remote_addr type = request.headers['Content-Type'] tags = [] tags_valid = True body_valid = True content = request.form['quote'] tags_raw = request.form['tags'] # a smidgen of validation if len(tags_raw) > 100: tags_valid = False else: tags = map(string.strip, tags_raw.split(',')) body_valid, tags_valid = validate_quote(content, tags) quote = None if body_valid and tags_valid: quote = Quote(content, ip) quote.tags = map(Tag, tags) quote = db.put(quote) # grabbing return val isn't strictly necessary if request.wants_json(): return create_quote_resp_json(quote, body_valid, tags_valid) else: return create_quote_resp_html(quote, body_valid, tags_valid)
def playlists_dj_all(): results = call_api("/playlists/dj/all", 'GET') if request.wants_json(): return jsonify(results) return render_template('playlists_dj_list_all.html', djs=results['djs'])
def charts_albums(period=None): try: start, end = charts.get_range(period, request) except ValueError: abort(400) results = charts.get( 'albums_{0}_{1}'.format(start, end), Track.query.with_entities( Track.artist, Track.album, db.func.count(TrackLog.id)).join(TrackLog).filter( db.and_(TrackLog.dj_id > 1, TrackLog.played >= start, TrackLog.played <= end)).group_by( Track.artist, Track.album).order_by( db.func.count(TrackLog.id).desc())) if request.wants_json(): return jsonify({ 'results': [(x[0], x[1], x[2]) for x in results], }) return render_template('chart_albums.html', start=start, end=end, results=results)
def submit_password(): entered_handle = request.form['handle'].strip() if len(entered_handle) <= 0: return make_error(request, "Please enter a handle.") handle = Handle.get(entered_handle) counts = {'good': 0, 'notfound': 0, 'bad': 0, 'duplicate': 0} entered_pws = request.form['passwords'].strip().splitlines() for entered_pw in entered_pws: entered_pw = entered_pw.split(':', 1) if len(entered_pw) <= 1: return make_error( request, "Cracked passwords must be in the " "hashed:plaintext format.") password = Password.get(entered_pw[0]) if not password: # hash not found in DB counts['notfound'] += 1 elif ctfengine.crack.lib.hashpw(password.algo, entered_pw[1]) !=\ password.password: # plaintext is not correct for hash counts['bad'] += 1 else: if not handle: # handle does not exist, create handle = Handle(entered_handle, 0) db.session.add(handle) db.session.commit() # look for existing entries existing_entry = PasswordEntry.query.filter( PasswordEntry.handle == handle.id, PasswordEntry.password == password.id).first() if existing_entry: counts['duplicate'] += 1 else: counts['good'] += 1 # update points for user handle.score += password.points # log password submission entry = PasswordEntry(handle.id, password.id, entered_pw[1], request.remote_addr, request.user_agent.string) db.session.add(entry) db.session.commit() if counts['good'] > 0: sse.send("score: {handle_id:d}: password".format(handle_id=handle.id)) if request.wants_json(): return jsonify({'status': counts}) flash("{good} passwords accepted, {notfound} not found in database, " "{duplicate} passwords already scored, and {bad} incorrect " "plaintexts.".format(**counts)) return redirect(url_for('index'))
def make_error(request, msg, code=400): if request.wants_json(): response = jsonify({'message': msg}) response.status_code = code return response else: flash(msg) return redirect(url_for('index'))
def welcome(): if request.wants_json(): links = navs links.append(build_link('/', 'self', 'application/json')) root = {'version': '0.1', 'title': 'VT Bash', 'links': links} return jsonify(root, 'application/json') news = News() return render_template('index.html', nav=navs, news=news.news)
def random(): admin = authDB.isAuthenticated(request) if request.wants_json(): return json_nyi() return render_template('quotes.html', nav=navs, quotes=db.random(15), isAdmin=admin)
def tag(tag): incr,start,next,prev = parse_qs(request.args, tag) quotes = db.tag(tag, incr, start) admin = authDB.isAuthenticated(request) page = 'tags/%s' % (tag) if request.wants_json(): return json_nyi() return render_template('quotes.html', nav=navs, quotes=quotes, page=page, next=next, prev=prev, title="Quotes Tagged '%s'" %(tag), isAdmin=admin)
def single(quote_id): quotes = [ db.get(quote_id) ] admin = authDB.isAuthenticated(request) if None in quotes: abort(404) if request.wants_json(): return json_nyi() return render_template('quotes.html', nav=navs, quotes=quotes, isAdmin=admin)
def search(): incr, start, next, prev = parse_qs(request.args) query = request.args.get('query', None) if not query: if request.wants_json(): return json_nyi() return render_template('search.html', nav=navs) if request.wants_json(): return json_nyi() return render_template('search.html', nav=navs, quotes=db.search(query, incr, start), title="Search Results for '%s'" % (query), next=next, prev=prev, page="search", query=query)
def charts_tracks_dj(dj_id): results = call_api("/charts/dj/{0}/tracks", 'GET', dj_id) if request.wants_json(): return jsonify(results) return render_template('chart_tracks_dj.html', dj=results['dj'], results=results['results'])
def last15(): tracks = TrackLog.query.order_by(db.desc(TrackLog.id)).limit(15).all() if request.wants_json(): return jsonify({ 'tracks': [t.full_serialize() for t in tracks], }) return render_template('last15.html', tracklogs=tracks)
def last15(): result = call_api("/playlists/last15", 'GET') if request.wants_json(): return jsonify({ 'tracks': [tracklog_full_serialize(t) for t in result['tracks']], }) return render_template('last15.html', tracklogs=result['tracks'], feedlink=url_for('.last15_feed'))
def welcome(): if request.wants_json(): links = navs links.append(build_link('/', 'self', 'application/json')) root = { 'version': '0.1', 'title': 'VT Bash', 'links': links } return jsonify(root, 'application/json') news = News() return render_template('index.html', nav=navs, news=news.news)
def playlists_date_sets(year, month, day): dtstart = datetime.datetime(year, month, day, 0, 0, 0) sets = DJSet.query.filter(DJSet.dtstart >= dtstart).all() if request.wants_json(): return jsonify({ 'dtstart': dtstart, 'sets': [s.serialize() for s in sets], }) return render_template('playlists_date_sets.html', date=dtstart, sets=sets)
def last15(): tracks = TrackLog.query.order_by(db.desc(TrackLog.id)).limit(15).all() if request.wants_json(): return jsonify({ 'tracks': [t.full_serialize() for t in tracks], }) return render_template('last15.html', tracklogs=tracks, feedlink=url_for('.last15_feed'))
def single(quote_id): quotes = [db.get(quote_id)] admin = authDB.isAuthenticated(request) if None in quotes: abort(404) if request.wants_json(): return json_nyi() return render_template('quotes.html', nav=navs, quotes=quotes, isAdmin=admin)
def charts_dj_spins(): results = TrackLog.query.\ with_entities(TrackLog.dj_id, DJ, db.func.count(TrackLog.id)).\ join(DJ).filter(DJ.visible == True).group_by(TrackLog.dj_id).\ order_by(db.func.count(TrackLog.id).desc()).all() if request.wants_json(): return jsonify({ 'results': [(x[1].serialize(), x[2]) for x in results], }) return render_template('chart_dj_spins.html', results=results)
def top(): incr, start, next, prev = parse_qs(request.args) admin = authDB.isAuthenticated(request) if request.wants_json(): return json_nyi() return render_template('quotes.html', nav=navs, quotes=db.top(incr, start), page='top', next=next, prev=prev, isAdmin=admin)
def list_hashes(algo): passwords = Password.query.filter(Password.algo == algo).all() if not passwords: abort(404) hashed = [pw.password for pw in passwords] if request.wants_json(): return jsonify({ 'algo': algo, 'hashes': hashed, }) return Response("\n".join(hashed), mimetype="text/plain")
def register(): form = DJRegisterForm() if form.is_submitted(): if form.validate(): newdj = DJ(form.airname.data, form.name.data) newdj.email = form.email.data newdj.phone = form.phone.data newdj.genres = form.genres.data db.session.add(newdj) db.session.commit() if request.wants_json(): return jsonify(success=True) else: flash("DJ added") return redirect(url_for('.login')) elif request.wants_json(): return jsonify(success=False, errors=form.errors) return render_template('trackman/register.html', trackman_name=current_app.config['TRACKMAN_NAME'], form=form)
def playlists_track(track_id): track = Track.query.get_or_404(track_id) tracklogs = TrackLog.query.filter(TrackLog.track_id == track.id).\ order_by(TrackLog.played).all() if request.wants_json(): data = track.serialize() data['plays'] = [tl.serialize() for tl in tracklogs] return jsonify(data) return render_template('playlists_track.html', track=track, tracklogs=tracklogs)
def playlists_dj_sets(dj_id): dj = DJ.query.get(dj_id) if not dj: abort(404) sets = DJSet.query.filter(DJSet.dj_id == dj_id).all() if request.wants_json(): return jsonify({ 'dj': dj.serialize(), 'sets': [s.serialize() for s in sets], }) return render_template('playlists_dj_sets.html', dj=dj, sets=sets)
def latest_track_clean(): naughty_word_re = re.compile( r'shit|piss|f**k|c**t|c********r|t**s|twat|asshole', re.IGNORECASE) track = trackinfo() for k, v in track.items(): if type(v) == str or type(v) == unicode: track[k] = naughty_word_re.sub(u'****', v) if request.wants_json(): return jsonify(track) output = u"{artist} - {title} [DJ: {dj}]".format(**track) return Response(output, mimetype="text/plain")
def playlists_dj_sets(dj_id): dj = DJ.query.get(dj_id) if not dj: abort(404) sets = DJSet.query.filter(DJSet.dj_id == dj_id).order_by( DJSet.dtstart).all() if request.wants_json(): return jsonify({ 'dj': dj.serialize(), 'sets': [s.serialize() for s in sets], }) return render_template('playlists_dj_sets.html', dj=dj, sets=sets)
def index(): scores = Handle.top_scores() total_points = Flag.total_points() + Password.total_points() if request.wants_json(): return jsonify({ 'scores': [(x.id, x.handle, x.score) for x in scores], 'total_points': total_points, }) return render_template('index.html', CTF_NAME=app.config['CTF_NAME'], scores=scores, total_points=total_points)
def register(): errors = {} if request.method == 'POST': airname = request.form['airname'].strip() if len(airname) <= 0: errors['airname'] = "You must enter an on-air name." matching = DJ.query.filter(DJ.airname == airname).count() print(matching) if matching > 0: errors['airname'] = "Your on-air name must be unique." name = request.form['name'].strip() if len(name) <= 0: errors['name'] = "You must enter your name." email = request.form['email'].strip() if len(email) <= 0: errors['email'] = "You must enter your email address." phone = request.form['phone'].strip() if len(phone) <= 0: errors['phone'] = "You must enter your phone number." genres = request.form['genres'].strip() if len(genres) <= 0: errors['genres'] = "You must enter the genres you can DJ." if len(errors.items()) <= 0: newdj = DJ(airname, name) newdj.email = email newdj.phone = phone newdj.genres = genres db.session.add(newdj) db.session.commit() flash("DJ added") return redirect(url_for('.login')) if request.wants_json(): if len(errors) <= 0: return jsonify(success=True) else: return jsonify(success=False, errors=errors) else: return render_template( 'trackman/register.html', trackman_name=current_app.config['TRACKMAN_NAME'], errors=errors)
def role_remove_group(id): group_role = GroupRole.query.get_or_404(id) db.session.delete(group_role) try: db.session.commit() except: db.session.rollback() raise if request.method == 'DELETE' or request.wants_json(): return jsonify({ '_csrf_token': app.jinja_env.globals['csrf_token'](), }) else: return redirect(url_for('.roles', 303))
def charts_tracks_dj(dj_id): dj = DJ.query.get_or_404(dj_id) results = Track.query.\ with_entities(Track, db.func.count(TrackLog.id)).\ join(TrackLog).filter(TrackLog.dj_id == dj.id).\ group_by(TrackLog.track_id).\ order_by(db.func.count(TrackLog.id).desc()).limit(250) if request.wants_json(): return jsonify({ 'dj': dj.serialize(), 'results': [(x[0].serialize(), x[1]) for x in results], }) return render_template('chart_tracks_dj.html', dj=dj, results=results)
def charts_artists(period=None): start, end = charts_period(period) results = Track.query.\ with_entities(Track.artist, db.func.count(TrackLog.id)).\ join(TrackLog).filter(db.and_( TrackLog.played >= start, TrackLog.played <= end)).\ group_by(Track.artist).\ order_by(db.func.count(TrackLog.id).desc()).limit(250) if request.wants_json(): return jsonify({'results': results}) return render_template('chart_artists.html', start=start, end=end, results=results)
def playlist(set_id): results = call_api("/playlists/set/{0:d}", 'GET', set_id) if request.wants_json(): results.update({ 'archives': [a[0] for a in results['archives']], 'tracks': [ tracklog_full_serialize(t) for t in results['tracks']], }) return jsonify(results) return render_template('playlist.html', archives=results['archives'], djset=results, tracklogs=results['tracks'])
def playlists_date_data(): try: start = datetime.datetime.strptime(request.args['start'], "%Y-%m-%dT%H:%M:%S.%fZ") end = datetime.datetime.strptime(request.args['end'], "%Y-%m-%dT%H:%M:%S.%fZ") except ValueError: abort(400) sets = DJSet.query.filter(db.and_(DJSet.dtstart >= start, DJSet.dtstart <= end)).\ order_by(db.desc(DJSet.dtstart)).limit(300).all() if request.wants_json(): return jsonify({'sets': [s.serialize() for s in sets]}) return Response("{start} {end}".format(start=start, end=end))
def create_quote_json(): ip = request.remote_addr data = request.json body_valid, tags_valid = validate_quote(data['body'], data['tags']) if body_valid and tags_valid: quote = Quote(data['body'], ip) quote.tags = map(Tag, data['tags']) quote = db.put(quote) # grabbing return val isn't strictly necessary if request.wants_json(): return create_quote_resp_json(quote, body_valid, tags_valid) else: return create_quote_resp_html(quote, body_valid, tags_valid)
def playlist(set_id): djset = DJSet.query.get_or_404(set_id) tracks = TrackLog.query.filter(TrackLog.djset_id == djset.id).order_by( TrackLog.played).all() archives = list_archives(djset) if request.wants_json(): data = djset.serialize() data.update({ 'archives': [a[0] for a in archives], 'tracks': [t.full_serialize() for t in tracks], }) return jsonify(data) return render_template('playlist.html', archives=archives, djset=djset, tracklogs=tracks)
def charts_tracks(period=None): start, end = charts_period(period) results = Track.query.with_entities(Track, db.func.count(TrackLog.id)).\ join(TrackLog).filter(db.and_( TrackLog.played >= start, TrackLog.played <= end)).\ group_by(TrackLog.track_id).\ order_by(db.func.count(TrackLog.id).desc()).limit(250) if request.wants_json(): return jsonify({ 'results': [(x[0].serialize(), x[1]) for x in results], }) return render_template('chart_tracks.html', start=start, end=end, results=results)