MarseyWorld/files/__main__.py

273 lines
7.9 KiB
Python
Raw Normal View History

2021-07-21 01:12:26 +00:00
import gevent.monkey
gevent.monkey.patch_all()
2021-07-26 18:47:42 +00:00
from os import environ, path
2021-07-21 01:12:26 +00:00
import secrets
from flask import *
from flask_caching import Cache
from flask_limiter import Limiter
from flask_compress import Compress
2021-07-23 19:47:19 +00:00
2021-07-21 01:12:26 +00:00
from flaskext.markdown import Markdown
from sqlalchemy.ext.declarative import declarative_base
2021-07-23 19:46:20 +00:00
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import sessionmaker, scoped_session, Query as _Query
2021-07-21 01:12:26 +00:00
from sqlalchemy import *
from sqlalchemy.pool import QueuePool
import requests
import redis
import gevent
2021-07-23 19:46:20 +00:00
from redis import ConnectionPool
2021-07-21 01:12:26 +00:00
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__,
template_folder='./templates',
static_folder='./static'
)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=3)
app.url_map.strict_slashes = False
2021-08-04 16:00:57 +00:00
app.config["SITE_NAME"]=environ.get("SITE_NAME").strip()
2021-08-04 18:43:04 +00:00
app.config["coins_name"]=environ.get("coins_name").strip()
2021-07-21 01:12:26 +00:00
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
2021-08-04 16:00:57 +00:00
app.config['DATABASE_URL'] = environ.get("DATABASE_CONNECTION_POOL_URL",environ.get("DATABASE_URL"))
2021-07-21 01:12:26 +00:00
app.config['SECRET_KEY'] = environ.get('MASTER_KEY')
2021-08-02 14:27:20 +00:00
app.config["SERVER_NAME"] = environ.get("domain").strip()
2021-07-21 01:12:26 +00:00
2021-08-04 16:00:57 +00:00
app.config["SESSION_COOKIE_NAME"] = "session_" + environ.get("SITE_NAME").strip().lower()
2021-07-25 21:59:20 +00:00
app.config["VERSION"] = "1.0.0"
2021-07-21 01:12:26 +00:00
app.config['MAX_CONTENT_LENGTH'] = 64 * 1024 * 1024
app.config["SESSION_COOKIE_SECURE"] = bool(int(environ.get("FORCE_HTTPS", 1)))
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["PERMANENT_SESSION_LIFETIME"] = 60 * 60 * 24 * 365
app.config["SESSION_REFRESH_EACH_REQUEST"] = True
app.config["FORCE_HTTPS"] = int(environ.get("FORCE_HTTPS", 1)) if ("localhost" not in app.config["SERVER_NAME"] and "127.0.0.1" not in app.config["SERVER_NAME"]) else 0
app.jinja_env.cache = {}
2021-07-25 21:59:20 +00:00
app.config["UserAgent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"
2021-07-21 01:12:26 +00:00
if "localhost" in app.config["SERVER_NAME"]:
app.config["CACHE_TYPE"] = "null"
else:
2021-08-04 16:00:57 +00:00
app.config["CACHE_TYPE"] = "filesystem"
2021-07-21 01:12:26 +00:00
2021-08-04 16:00:57 +00:00
app.config["CACHE_DIR"] = environ.get("CACHE_DIR", "cache")
2021-07-21 01:12:26 +00:00
# captcha configs
app.config["HCAPTCHA_SITEKEY"] = environ.get("HCAPTCHA_SITEKEY","").strip()
2021-08-04 16:00:57 +00:00
app.config["HCAPTCHA_SECRET"] = environ.get("HCAPTCHA_SECRET","").strip()
2021-07-21 01:12:26 +00:00
# antispam configs
2021-08-04 16:00:57 +00:00
app.config["SPAM_SIMILARITY_THRESHOLD"] = float(environ.get("SPAM_SIMILARITY_THRESHOLD"))
app.config["SPAM_SIMILAR_COUNT_THRESHOLD"] = int(environ.get("SPAM_SIMILAR_COUNT_THRESHOLD"))
app.config["SPAM_URL_SIMILARITY_THRESHOLD"] = float(environ.get("SPAM_URL_SIMILARITY_THRESHOLD"))
app.config["COMMENT_SPAM_SIMILAR_THRESHOLD"] = float(environ.get("COMMENT_SPAM_SIMILAR_THRESHOLD"))
app.config["COMMENT_SPAM_COUNT_THRESHOLD"] = int(environ.get("COMMENT_SPAM_COUNT_THRESHOLD"))
app.config["CACHE_REDIS_URL"] = environ.get("REDIS_URL").strip()
2021-07-21 01:12:26 +00:00
app.config["CACHE_DEFAULT_TIMEOUT"] = 60
app.config["CACHE_KEY_PREFIX"] = "flask_caching_"
2021-08-04 16:00:57 +00:00
app.config["REDIS_POOL_SIZE"] = 10
2021-07-21 01:12:26 +00:00
redispool=ConnectionPool(
max_connections=app.config["REDIS_POOL_SIZE"],
host=app.config["CACHE_REDIS_URL"][8:]
) if app.config["CACHE_TYPE"]=="redis" else None
app.config["CACHE_OPTIONS"]={'connection_pool':redispool} if app.config["CACHE_TYPE"]=="redis" else {}
2021-08-04 16:00:57 +00:00
app.config["READ_ONLY"]=bool(int(environ.get("READ_ONLY")))
2021-07-21 01:12:26 +00:00
app.config["BOT_DISABLE"]=bool(int(environ.get("BOT_DISABLE", False)))
app.config["TENOR_KEY"]=environ.get("TENOR_KEY",'').strip()
Markdown(app)
cache = Cache(app)
Compress(app)
2021-08-04 16:00:57 +00:00
app.config["RATELIMIT_STORAGE_URL"] = environ.get("REDIS_URL").strip()
2021-07-21 01:12:26 +00:00
app.config["RATELIMIT_KEY_PREFIX"] = "flask_limiting_"
app.config["RATELIMIT_ENABLED"] = True
app.config["RATELIMIT_DEFAULTS_DEDUCT_WHEN"]=lambda:True
app.config["RATELIMIT_DEFAULTS_EXEMPT_WHEN"]=lambda:False
app.config["RATELIMIT_HEADERS_ENABLED"]=True
2021-07-26 14:44:52 +00:00
2021-08-04 16:00:57 +00:00
def limiter_key_func(): return request.remote_addr
2021-07-21 01:12:26 +00:00
limiter = Limiter(
app,
key_func=limiter_key_func,
default_limits=["100/minute"],
headers_enabled=True,
strategy="fixed-window"
)
_engine=create_engine(
app.config['DATABASE_URL'],
poolclass=QueuePool,
pool_size=int(environ.get("PG_POOL_SIZE",10)),
pool_use_lifo=True
)
def retry(f):
def wrapper(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except OperationalError as e:
#self.session.rollback()
2021-07-24 19:36:49 +00:00
#raise(DatabaseOverload)
2021-07-24 21:02:39 +00:00
print("sex")
2021-07-21 01:12:26 +00:00
except:
self.session.rollback()
return f(self, *args, **kwargs)
wrapper.__name__=f.__name__
return wrapper
class RetryingQuery(_Query):
@retry
def all(self):
return super().all()
@retry
def count(self):
return super().count()
@retry
def first(self):
return super().first()
db_session=scoped_session(sessionmaker(bind=_engine, query_cls=RetryingQuery))
Base = declarative_base()
#set the shared redis cache for misc stuff
r=redis.Redis(
host=app.config["CACHE_REDIS_URL"][8:],
decode_responses=True,
ssl_cert_reqs=None,
connection_pool=redispool
) if app.config["CACHE_REDIS_URL"] else None
local_ban_cache={}
UA_BAN_CACHE_TTL = int(environ.get("UA_BAN_CACHE_TTL", 3600))
# import and bind all routing functions
2021-08-04 15:35:10 +00:00
import files.classes
from files.routes import *
import files.helpers.jinja2
2021-07-21 01:12:26 +00:00
@cache.memoize(UA_BAN_CACHE_TTL)
def get_useragent_ban_response(user_agent_str):
"""
Given a user agent string, returns a tuple in the form of:
(is_user_agent_banned, (insult, status_code))
"""
#if request.path.startswith("/socket.io/"):
# return False, (None, None)
result = g.db.query(
2021-08-04 15:35:10 +00:00
files.classes.Agent).filter(
files.classes.Agent.kwd.in_(
2021-07-21 01:12:26 +00:00
user_agent_str.split())).first()
if result:
return True, (result.mock or "Follow the robots.txt, dumbass",
result.status_code or 418)
return False, (None, None)
def drop_connection():
g.db.close()
gevent.getcurrent().kill()
# enforce https
@app.before_request
def before_request():
if request.method.lower() != "get" and app.config["READ_ONLY"]:
2021-07-31 05:28:05 +00:00
return {"error":f"{app.config['SITE_NAME']} is currently in read-only mode."}, 500
2021-07-21 01:12:26 +00:00
if app.config["BOT_DISABLE"] and request.headers.get("X-User-Type")=="Bot":
abort(503)
g.db = db_session()
g.timestamp = int(time.time())
session.permanent = True
ua_banned, response_tuple = get_useragent_ban_response(
request.headers.get("User-Agent", "NoAgent"))
if ua_banned and request.path != "/robots.txt":
return response_tuple
if app.config["FORCE_HTTPS"] and request.url.startswith(
"http://") and "localhost" not in app.config["SERVER_NAME"]:
url = request.url.replace("http://", "https://", 1)
return redirect(url, code=301)
if not session.get("session_id"):
session["session_id"] = secrets.token_hex(16)
ua=request.headers.get("User-Agent","")
if "CriOS/" in ua:
g.system="ios/chrome"
elif "Version/" in ua:
g.system="android/webview"
elif "Mobile Safari/" in ua:
g.system="android/chrome"
elif "Safari/" in ua:
g.system="ios/safari"
elif "Mobile/" in ua:
g.system="ios/webview"
else:
g.system="other/other"
@app.after_request
def after_request(response):
2021-07-26 18:20:52 +00:00
try:
g.db.commit()
g.db.close()
except Exception as e:
g.db.rollback()
g.db.close()
2021-07-26 18:20:19 +00:00
print(e)
2021-07-26 18:20:52 +00:00
abort(500)
2021-07-21 01:12:26 +00:00
2021-08-01 04:24:46 +00:00
response.headers.add('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept, x-auth")
2021-07-30 13:36:12 +00:00
response.headers.remove("Cache-Control")
2021-07-30 13:54:39 +00:00
response.headers.add("Cache-Control", "public, max-age=31536000")
2021-07-30 13:36:12 +00:00
response.headers.add("Access-Control-Allow-Origin", app.config["SERVER_NAME"])
2021-07-21 01:12:26 +00:00
response.headers.add("Strict-Transport-Security", "max-age=31536000")
response.headers.add("Referrer-Policy", "same-origin")
2021-08-01 04:24:46 +00:00
response.headers.add("Feature-Policy", "geolocation 'none'; midi 'none'; notifications 'none'; push 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; vibrate 'none'; fullscreen 'none'; payment 'none';")
if not request.path.startswith("/embed/"): response.headers.add("X-Frame-Options", "deny")
2021-07-21 01:12:26 +00:00
return response
@app.route("/<path:path>", subdomain="www")
def www_redirect(path):
return redirect(f"https://{app.config['SERVER_NAME']}/{path}")