def inject(): return { "root": _cfg("protocol") + "://" + _cfg("domain"), "domain": _cfg("domain"), "protocol": _cfg("protocol"), "len": len, "any": any, "request": request, "locale": locale, "url_for": url_for, "file_link": file_link, "user": current_user, "_cfg": _cfg, "_cfgi": _cfgi, "debug": app.debug, "str": str, "int": int, }
def check_update(): try: response = requests.get( "https://gitlab.kokakiwi.net/api/v4/projects/82/repository/tags", timeout=1) tags = response.json() if _cfg("branch") == "stable": for tag in tags: if tag["message"] == "stable": checked_version = cversion(tag["name"]) if checked_version > cversion(version()): return "update_available" elif checked_version < cversion(version()): return "woaw" elif _cfg("branch") == "unstable": checked_version = cversion(tags[0]["name"]) if checked_version > cversion(version()): return "update_available" except requests.exceptions.RequestException: return "server_error" return "up_to_date"
def disown_link(path): return _cfg("protocol") + "://" + _cfg( "domain") + "/disown?filename=" + path
def file_link(path): return _cfg("protocol") + "://" + _cfg("domain") + "/" + path
from core.database import db from core.config import _cfg from core.emails import send_thank_you, send_declined from core.app import app from flask_babel import _, ngettext from datetime import datetime, timedelta from babel.dates import format_date, format_time import requests import stripe import subprocess with app.app_context(): stripe.api_key = _cfg("stripe-secret") date = format_date(datetime.now(), locale=_cfg("locale")) time = format_time(datetime.now(), locale=_cfg("locale")) print(_("Processing monthly donations on"), date, time) donations = (Donation.query.filter( Donation.type == DonationType.monthly).filter(Donation.active).all()) limit = datetime.now() - timedelta(days=30) for donation in donations: if donation.updated < limit: print(_("Charging {}").format(donation)) user = donation.user customer = stripe.Customer.retrieve(user.stripe_customer)
#!/usr/bin/env python3 from core.app import app from core.config import _cfg, _cfgi import os app.static_folder = os.path.join(os.getcwd(), "_static") if __name__ == "__main__": app.run(host=_cfg("debug-host"), port=_cfgi("debug-port"), debug=True)
from core.config import _cfg import stripe if _cfg("stripe-secret") != "": stripe.api_key = _cfg("stripe-secret")
from core.config import _cfg class Currency: def __init__(self, symbol, position): self.symbol = symbol self.position = position def amount(self, amount): if self.position == "right": return amount + self.symbol else: return self.symbol + amount currencies = { "usd": Currency("$", "left"), "eur": Currency(" €", "right") # ... More currencies can be added here } currency = currencies[_cfg("currency")]
def index(): if User.query.count() == 0: load_config() return render_template("setup.html") projects = sorted(Project.query.all(), key=lambda p: p.name) if os.path.exists("static/logo.png"): avatar = os.path.join("static/logo.png") else: avatar = ("//www.gravatar.com/avatar/" + hashlib.md5(_cfg("your-email").encode("utf-8")).hexdigest()) selected_project = request.args.get("project") if selected_project: try: selected_project = int(selected_project) except Exception: current_app.logger.exception( "Error while trying to select project: %s" % selected_project, exc_info=True, ) selected_project = None active_recurring = (Donation.query.filter( Donation.type == DonationType.monthly).filter( Donation.active == True).filter(Donation.hidden == False)) recurring_count = active_recurring.count() recurring_sum = sum([d.amount for d in active_recurring]) limit = datetime.now() - timedelta(days=30) month_onetime = Donation.query.filter( Donation.type == DonationType.one_time).filter( Donation.created > limit) onetime_count = month_onetime.count() onetime_sum = sum([d.amount for d in month_onetime]) access_token = _cfg("patreon-access-token") campaign = _cfg("patreon-campaign") if access_token and campaign: try: import patreon client = patreon.API(access_token) campaign = client.fetch_campaign() attrs = campaign.json_data["data"][0]["attributes"] patreon_count = attrs["patron_count"] patreon_sum = attrs["pledge_sum"] except Exception as e: current_app.logger.warning("Error to get patreon information: %s" % e, exc_info=True) patreon_count = 0 patreon_sum = 0 else: patreon_count = 0 patreon_sum = 0 liberapay = _cfg("liberapay-campaign") if liberapay: try: lp = (requests.get( "https://liberapay.com/{}/public.json".format(liberapay), timeout=5)).json() except Exception: traceback.print_exc() print("Error while trying to get data from liberapay") lp_count = 0 lp_sum = 0 else: lp_count = lp["npatrons"] lp_sum = int(float(lp["receiving"]["amount"]) * 100) # Convert from weekly to monthly lp_sum = lp_sum * 52 // 12 else: lp_count = 0 lp_sum = 0 github_token = _cfg("github-token") if github_token: query = """ { viewer { login sponsorsListing { tiers(first:100) { nodes { monthlyPriceInCents adminInfo { sponsorships(includePrivate:true) { totalCount } } } } } } } """ r = requests.post( "https://api.github.com/graphql", json={"query": query}, headers={"Authorization": f"bearer {github_token}"}, ) result = r.json() nodes = result["data"]["viewer"]["sponsorsListing"]["tiers"]["nodes"] cnt = lambda n: n["adminInfo"]["sponsorships"]["totalCount"] gh_count = sum(cnt(n) for n in nodes) gh_sum = sum(n["monthlyPriceInCents"] * cnt(n) for n in nodes) gh_user = result["data"]["viewer"]["login"] else: gh_count = 0 gh_sum = 0 gh_user = 0 return render_template( "index.html", projects=projects, avatar=avatar, selected_project=selected_project, recurring_count=recurring_count, recurring_sum=recurring_sum, onetime_count=onetime_count, onetime_sum=onetime_sum, patreon_count=patreon_count, patreon_sum=patreon_sum, lp_count=lp_count, lp_sum=lp_sum, currency=currency, gh_count=gh_count, gh_sum=gh_sum, gh_user=gh_user, version=version(), )
def donate(): email = request.form.get("email") stripe_token = request.form.get("stripe_token") amount = request.form.get("amount") type = request.form.get("type") comment = request.form.get("comment") project_id = request.form.get("project") # validate and rejigger the form inputs if not email or not stripe_token or not amount or not type: return {"success": False, "reason": "Invalid request"}, 400 try: if project_id is None or project_id == "null": project = None else: project_id = int(project_id) project = Project.query.filter(Project.id == project_id).first() if type == "once": type = DonationType.one_time else: type = DonationType.monthly amount = int(amount) except Exception as e: current_app.logger.exception( "Error, failed to generate a donation because '%s' for the values: '%s'" % (e, request.form.items()), exc_info=True, ) return {"success": False, "reason": "Invalid request"}, 400 new_account = False user = User.query.filter(User.email == email).first() if not user: new_account = True user = User(email, binascii.b2a_hex(os.urandom(20)).decode("utf-8")) user.password_reset = binascii.b2a_hex(os.urandom(20)).decode("utf-8") user.password_reset_expires = datetime.now() + timedelta(days=1) customer = stripe.Customer.create(email=user.email, card=stripe_token) user.stripe_customer = customer.id db.add(user) else: customer = stripe.Customer.retrieve(user.stripe_customer) new_source = customer.sources.create(source=stripe_token) customer.default_source = new_source.id customer.save() donation = Donation(user, type, amount, project, comment) db.add(donation) try: stripe.Charge.create( amount=amount, currency=_cfg("currency"), customer=user.stripe_customer, description="Donation to " + _cfg("your-name"), ) except stripe.error.CardError: db.rollback() db.close() return {"success": False, "reason": "Your card was declined."} db.commit() try: send_thank_you(user, amount, type == DonationType.monthly) send_new_donation(user, donation) except Exception: traceback.print_exc() print("Error while trying to send a email") if new_account: return { "success": True, "new_account": new_account, "password_reset": user.password_reset, } else: return {"success": True, "new_account": new_account}
def logout(): logout_user() return redirect(_cfg("protocol") + "://" + _cfg("domain"))
def get_locale(): return _cfg("locale")
from core.forms import csrf from core.common import file_link from core.blueprints.html import html app = Flask(__name__) babel = Babel(app) csrf.init_app(app) @babel.localeselector def get_locale(): return _cfg("locale") app.secret_key = _cfg("secret-key") app.jinja_env.cache = None init_db() login_manager = LoginManager() login_manager.init_app(app) app.jinja_loader = ChoiceLoader([ FileSystemLoader("overrides"), FileSystemLoader("templates"), ]) stripe.api_key = _cfg("stripe-secret") @login_manager.user_loader def load_user(email):