forked from thurloat/fosspay
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cronjob.py
executable file
·76 lines (64 loc) · 2.39 KB
/
cronjob.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python3
import sys
from fosspay.app import app
from fosspay.objects import *
from fosspay.database import db
from fosspay.config import _cfg
from fosspay.email import send_thank_you, send_declined
from fosspay.currency import currency
from datetime import datetime, timedelta
import requests
import stripe
with app.app_context():
stripe.api_key = _cfg("stripe-secret")
# Date in global standard
print("Processing monthly donations @ {}".format(datetime.now().strftime('%d-%m-%Y %H:%M:%S')))
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)
try:
charge = stripe.Charge.create(
amount=donation.amount,
currency=_cfg("currency"),
customer=user.stripe_customer,
description="Donation to " + _cfg("your-name")
)
except stripe.error.CardError as e:
donation.active = False
db.commit()
send_declined(user, donation.amount)
print("Declined")
continue
send_thank_you(user, donation.amount, donation.type == DonationType.monthly)
donation.updated = datetime.now()
donation.payments += 1
db.commit()
else:
print("Skipping {}".format(donation))
print("{} records processed.\n".format(len(donations)))
if _cfg("patreon-refresh-token"):
print("Updating Patreon API token")
r = requests.post('https://www.patreon.com/api/oauth2/token', params={
'grant_type': 'refresh_token',
'refresh_token': _cfg("patreon-refresh-token"),
'client_id': _cfg("patreon-client-id"),
'client_secret': _cfg("patreon-client-secret")
})
if r.status_code != 200:
print("Failed to update Patreon API token")
sys.exit(1)
resp = r.json()
with open("config.ini") as f:
config = f.read()
config = config.replace(_cfg("patreon-access-token"), resp["access_token"])
config = config.replace(_cfg("patreon-refresh-token"), resp["refresh_token"])
with open("config.ini", "w") as f:
f.write(config)
print("Refreshed Patreon API token")