<commit_before>from flask import Flask, render_template, request, redirect, url_for, Response, send_from_directory, jsonify, flash
from flask_login import LoginManager, current_user, login_user, login_required
from werkzeug.utils import secure_filename
from werkzeug.urls import url_quote_plus
import os
import time
import logging
import datetime
import random
import threading
import subprocess
from . import config
from . import database
from . import oracle
from . import utils

app = Flask(__name__)


UPLOAD_FOLDER = 'uploads'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login_get"
app.config["SECRET_KEY"] = os.urandom(12)
ALLOWED_EXTENSIONS = set(['mp3', 'png', 'jpg', 'jpeg', 'gif'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@login_manager.user_loader
def load_user(id):
	return database.User.from_id(int(id))

started_at_timestamp = time.time()
started_at = datetime.datetime.utcnow()

page_title = "Infinite Glitch - The World's Longest Recorded Pop Song, by <NAME>."
og_description = """I don't remember if he said it or if I said it or if the caffeine said it but suddenly we're both giggling 'cause the problem with the song isn't that it's too long it's that it's too short."""	
meta_description = """I don't remember if he said it or if I said it or if the caffeine said it but suddenly we're both giggling 'cause the problem with the song isn't that it's too long it's that it's too short."""	

def couplet_count(lyrics):
	total = 0
	for count in lyrics:
		total += count.track_lyrics['couplet_count']
	return total

@app.route("/")
def home():
	lyrics = database.get_all_lyrics()
	complete_length = datetime.timedelta(seconds=int(database.get_complete_length()))
	return render_template("index.html",
		open=True, # Can have this check for server load if we ever care
		endpoint="http://localhost:8889/all.mp3", # TODO: Make configurable (or better still, multiplex the port)
		complete_length=complete_length,
		couplet_count=couplet_count(lyrics),
		lyrics=lyrics,
		og_url=config.server_domain,
		og_description=og_description,
		meta_description=meta_description
	)

def _make_route(dir):
	# Use a closure to early-bind the 'dir'
	def non_caching_statics(path):
		response = send_from_directory("../"+dir, path)
		response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
		response.headers['Pragma'] = 'no-cache'
		return response
	app.add_url_rule('/'+dir+'/<path:path>', 'non_caching_'+dir, non_caching_statics)
for _dir in ("audio", "audition_audio", "transition_audio"):
	# audition_audio and transition_audio aren't currently used, but
	# will be part of the admin panel that we haven't yet ported.
	_make_route(_dir)

@app.route("/artwork/<int:id>.jpg")
def track_artwork(id):
	art = database.get_track_artwork(int(id))
	# TODO: If the track hasn't been approved yet, return 404 unless the user is an admin.
	if not art:
		return redirect('../static/img/Default-artwork-200.png')
	return bytes(art)

@app.route("/timing.json")
def timing():
	return jsonify({"time": time.time() * 1000})

@app.route("/credits")
def credits():
	og_description="The world's longest recorded pop song. (Credits)"
	page_title="Credits: Infinite Glitch - the world's longest recorded pop song, by <NAME>."
	meta_description="The people below are partially responsible for bringing you Infinite Glitch - the world's longest recorded pop song."
	og_url="http://www.infiniteglitch.net/credits"
	return render_template("credits.html",
				og_description=og_description, page_title=page_title,
				meta_description=meta_description,og_url=og_url)

@app.route("/view_artist/<artist>")
def tracks_by_artist(artist):
	# TODO: Clean up the whole sposplit/fposplit stuff, maybe by slash-separating
	artist_for_db = url_artist = artist
	if artist[:8] == 'sposplit':
		artist = artist[9:]
		artist_formatting = artist.split('fposplit',1)
		artist_for_db = ', '.join([part.strip() for part in artist_formatting])
		artist = ' '.join([part.strip() for part in artist_formatting[::-1]])
	tracks_by = database.tracks_by(artist_for_db)
	og_description= artist+" contributions to The world's longest recorded pop song."
	page_title=artist+": Infinite Glitch - the world's longest recorded pop song, by <NAME>."
	meta_description="Browse the artists who have added to the Infinite Glitch - the world's longest recorded pop song."
	og_url = url_for("tracks_by_artist", artist=url_artist)
	return render_template("view_artist.html", tracks_by=tracks_by, og_description=og_description, 
				page_title=page_title, meta_description=meta_description, og_url=og_url)


@app.route("/choice_chunks")
def choice_chunks():
	og_description= "You can select any individual chunk of The Infinite Glitch to listen to."
	page_title="Browse Artists: Infinite Glitch - the world's longest recorded pop song, by <NAME>."
	meta_description="You can select any individual chunk of The Infinite Glitch to listen to."
	og_url=config.server_domain+"/choice_chunks"
	letter = request.args.get("letters", "")
	if letter:
		artist_tracks = database.browse_tracks(letter)
		ordered_artists = utils.alphabetize_ignore_the(artist_tracks)
	else:
		ordered_artists = ""
	recent_submitters = database.get_recent_tracks(10)
	ordered_submitters = utils.alphabetize_ignore_the(recent_submitters)
	return render_template("choice_chunks.html", recent_submitters=ordered_submitters, artist_tracks=ordered_artists, letter=letter,
				og_description=og_description, page_title=page_title, meta_description=meta_description, og_url=og_url)

@app.route("/login")
def login_get():
	return render_template("login.html")

@app.route("/login", methods=["POST"])
def login_post():
	user = database.User.from_credentials(request.form["email"], request.form["password"])
	if user: login_user(user)
	return redirect("/")
# TODO: /logout

@app.route("/create_account")
def create_account_get():
	return render_template("create_account.html", page_title="Glitch Account Sign-Up")

@app.route("/create_account", methods=["POST"])
def create_account_post():
	if request.form["password"] != request.form["password2"]:
		return redirect("/create_account")
	info = database.create_user(request.form["username"], request.form["email"], request.form["password"])
	if isinstance(info, str):
		# There's an error.
		return render_template("create_account.html", page_title="Glitch Account Sign-Up", error=info)
	# TODO: Send the email
	# mailer.AlertMessage(admin_message, 'New Account Created')<commit_msg>Implement /logout<commit_after>from flask import Flask, render_template, request, redirect, url_for, Response, send_from_directory, jsonify, flash
from flask_login import LoginManager, current_user, login_user, logout_user, login_required
from werkzeug.utils import secure_filename
from werkzeug.urls import url_quote_plus
import os
import time
import logging
import datetime
import random
import threading
import subprocess
from . import config
from . import database
from . import oracle
from . import utils

app = Flask(__name__)


UPLOAD_FOLDER = 'uploads'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login_get"
app.config["SECRET_KEY"] = os.urandom(12)
ALLOWED_EXTENSIONS = set(['mp3', 'png', 'jpg', 'jpeg', 'gif'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@login_manager.user_loader
def load_user(id):
	return database.User.from_id(int(id))

started_at_timestamp = time.time()
started_at = datetime.datetime.utcnow()

page_title = "Infinite Glitch - The World's Longest Recorded Pop Song, by <NAME>."
og_description = """I don't remember if he said it or if I said it or if the caffeine said it but suddenly we're both giggling 'cause the problem with the song isn't that it's too long it's that it's too short."""	
meta_description = """I don't remember if he said it or if I said it or if the caffeine said it but suddenly we're both giggling 'cause the problem with the song isn't that it's too long it's that it's too short."""	

def couplet_count(lyrics):
	total = 0
	for count in lyrics:
		total += count.track_lyrics['couplet_count']
	return total

@app.route("/")
def home():
	lyrics = database.get_all_lyrics()
	complete_length = datetime.timedelta(seconds=int(database.get_complete_length()))
	return render_template("index.html",
		open=True, # Can have this check for server load if we ever care
		endpoint="http://localhost:8889/all.mp3", # TODO: Make configurable (or better still, multiplex the port)
		complete_length=complete_length,
		couplet_count=couplet_count(lyrics),
		lyrics=lyrics,
		og_url=config.server_domain,
		og_description=og_description,
		meta_description=meta_description
	)

def _make_route(dir):
	# Use a closure to early-bind the 'dir'
	def non_caching_statics(path):
		response = send_from_directory("../"+dir, path)
		response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
		response.headers['Pragma'] = 'no-cache'
		return response
	app.add_url_rule('/'+dir+'/<path:path>', 'non_caching_'+dir, non_caching_statics)
for _dir in ("audio", "audition_audio", "transition_audio"):
	# audition_audio and transition_audio aren't currently used, but
	# will be part of the admin panel that we haven't yet ported.
	_make_route(_dir)

@app.route("/artwork/<int:id>.jpg")
def track_artwork(id):
	art = database.get_track_artwork(int(id))
	# TODO: If the track hasn't been approved yet, return 404 unless the user is an admin.
	if not art:
		return redirect('../static/img/Default-artwork-200.png')
	return bytes(art)

@app.route("/timing.json")
def timing():
	return jsonify({"time": time.time() * 1000})

@app.route("/credits")
def credits():
	og_description="The world's longest recorded pop song. (Credits)"
	page_title="Credits: Infinite Glitch - the world's longest recorded pop song, by <NAME>."
	meta_description="The people below are partially responsible for bringing you Infinite Glitch - the world's longest recorded pop song."
	og_url="http://www.infiniteglitch.net/credits"
	return render_template("credits.html",
				og_description=og_description, page_title=page_title,
				meta_description=meta_description,og_url=og_url)

@app.route("/view_artist/<artist>")
def tracks_by_artist(artist):
	# TODO: Clean up the whole sposplit/fposplit stuff, maybe by slash-separating
	artist_for_db = url_artist = artist
	if artist[:8] == 'sposplit':
		artist = artist[9:]
		artist_formatting = artist.split('fposplit',1)
		artist_for_db = ', '.join([part.strip() for part in artist_formatting])
		artist = ' '.join([part.strip() for part in artist_formatting[::-1]])
	tracks_by = database.tracks_by(artist_for_db)
	og_description= artist+" contributions to The world's longest recorded pop song."
	page_title=artist+": Infinite Glitch - the world's longest recorded pop song, by <NAME>."
	meta_description="Browse the artists who have added to the Infinite Glitch - the world's longest recorded pop song."
	og_url = url_for("tracks_by_artist", artist=url_artist)
	return render_template("view_artist.html", tracks_by=tracks_by, og_description=og_description, 
				page_title=page_title, meta_description=meta_description, og_url=og_url)


@app.route("/choice_chunks")
def choice_chunks():
	og_description= "You can select any individual chunk of The Infinite Glitch to listen to."
	page_title="Browse Artists: Infinite Glitch - the world's longest recorded pop song, by <NAME>."
	meta_description="You can select any individual chunk of The Infinite Glitch to listen to."
	og_url=config.server_domain+"/choice_chunks"
	letter = request.args.get("letters", "")
	if letter:
		artist_tracks = database.browse_tracks(letter)
		ordered_artists = utils.alphabetize_ignore_the(artist_tracks)
	else:
		ordered_artists = ""
	recent_submitters = database.get_recent_tracks(10)
	ordered_submitters = utils.alphabetize_ignore_the(recent_submitters)
	return render_template("choice_chunks.html", recent_submitters=ordered_submitters, artist_tracks=ordered_artists, letter=letter,
				og_description=og_description, page_title=page_title, meta_description=meta_description, og_url=og_url)

@app.route("/login")
def login_get():
	return render_template("login.html")

@app.route("/login", methods=["POST"])
def login_post():
	user = database.User.from_credentials(request.form["email"], request.form["password"])
	if user: login_user(user)
	return redirect("/")

@app.route("/logout")
def logout():
	logout_user()
	return redirect("/")

@app.route("/create_account")
def create_account_get():
	return render_template("create_account.html", page_title="Glitch Account Sign-Up")

@app.route("/create_account", methods=["POST"])
def create_account_post():
	if request.form["password"] != request.form["<PASSWORD>"]:
		return redirect("/create_account")
	info = database.create_user(request.form["username"], request.form["email"], request.form["password"])
	if isinstance(info, str):
		# There's an error.
		return render_template("create_account.html", page_title="Glitch Account Sign-Up", error=info)
	# TODO: Send the email
	# mailer.AlertMessage(admin_message, 'New Account Created')
{'fraction_non_alphanumeric': 0.11839291170180263, 'fraction_numerical': 0.004048273754964864, 'mean_word_length': 6.170317634173056, 'pattern_counts': {'":': 4, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3168690', 'n_tokens_mistral': 4358, 'n_tokens_neox': 4171, 'n_words': 1129}