<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, logout_user, login_required
from werkzeug.utils import secure_filename
from werkzeug.urls import url_quote_plus
from urllib.parse import urlparse, urljoin
import os
import sys
import time
import logging
import datetime
import random
import functools
import subprocess
from . import apikeys, config, database, oracle, utils, mailer

app = Flask(__name__)

# In production mode, the renderer runs on port 81. In debug, it's on 8889.
renderer_port = 81

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))

@app.template_filter()
def format_seconds(value):
	return datetime.timedelta(seconds=int(value))

# from http://flask.pocoo.org/snippets/62/
def is_safe_url(target):
	ref_url = urlparse(request.host_url)
	test_url = urlparse(urljoin(request.host_url, target))
	return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc

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 admin_required(func):
	"""Like login_required but also checks for admin access"""
	@login_required
	@functools.wraps(func)
	def wrapper(*args, **kwargs):
		if current_user.user_level < 2:
			# TODO: Different error page for non-admin?
			return login_manager.unauthorized()
		return func(*args, **kwargs)
	return wrapper

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()))
	prot = "https" if os.stat("privkey.pem") else "http" # TODO: See if the incoming request was over HTTPS instead
	return render_template("index.html",
		open=True, # Can have this check for server load if we ever care
		renderer="%s://%s:%d/" % (prot, urlparse(request.url_root).netloc.split(":")[0], renderer_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", ".well-known"):
	# 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("/static/flash/soundmanager2_flash9.swf")
def sm_flash():
	return redirect("../static/flash/soundmanager2_flash9.swf")

@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)
<commit_msg>Delivering sm flash backup as a download.<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
from urllib.parse import urlparse, urljoin
import os
import sys
import time
import logging
import datetime
import random
import functools
import subprocess
from . import apikeys, config, database, oracle, utils, mailer

app = Flask(__name__)

# In production mode, the renderer runs on port 81. In debug, it's on 8889.
renderer_port = 81

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))

@app.template_filter()
def format_seconds(value):
	return datetime.timedelta(seconds=int(value))

# from http://flask.pocoo.org/snippets/62/
def is_safe_url(target):
	ref_url = urlparse(request.host_url)
	test_url = urlparse(urljoin(request.host_url, target))
	return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc

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 admin_required(func):
	"""Like login_required but also checks for admin access"""
	@login_required
	@functools.wraps(func)
	def wrapper(*args, **kwargs):
		if current_user.user_level < 2:
			# TODO: Different error page for non-admin?
			return login_manager.unauthorized()
		return func(*args, **kwargs)
	return wrapper

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()))
	prot = "https" if os.stat("privkey.pem") else "http" # TODO: See if the incoming request was over HTTPS instead
	return render_template("index.html",
		open=True, # Can have this check for server load if we ever care
		renderer="%s://%s:%d/" % (prot, urlparse(request.url_root).netloc.split(":")[0], renderer_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", ".well-known"):
	# 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("/static/flash/soundmanager2_flash9.swf")
def sm_flash():
	return send_from_directory("static/flash", 'soundmanager2_flash9.swf', mimetype='application/x-shockwave-flash', attachment_filename='soundmanager2_flash9.swf', as_attachment=False)


@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)

{'fraction_non_alphanumeric': 0.11822660098522167, 'fraction_numerical': 0.006707892254480662, 'mean_word_length': 5.7721788502484035, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2046676', 'n_tokens_mistral': 3250, 'n_tokens_neox': 3111, 'n_words': 892}