Files
tabby-web/backend/tabby/app/sponsors.py

89 lines
2.4 KiB
Python
Raw Normal View History

2021-10-31 18:15:23 +01:00
from django.conf import settings
from django.core.cache import cache
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
from social_django.models import UserSocialAuth
from .models import User
2022-11-07 18:56:10 +01:00
GQL_ENDPOINT = "https://api.github.com/graphql"
CACHE_KEY = "cached-sponsors:%s"
2021-10-31 18:15:23 +01:00
def check_is_sponsor(user: User) -> bool:
try:
2022-11-07 18:56:10 +01:00
token = user.social_auth.get(provider="github").extra_data.get("access_token")
2021-10-31 18:15:23 +01:00
except UserSocialAuth.DoesNotExist:
return False
if not token:
return False
client = Client(
transport=RequestsHTTPTransport(
url=GQL_ENDPOINT,
use_json=True,
headers={
2022-11-07 18:56:10 +01:00
"Authorization": f"Bearer {token}",
},
2021-10-31 18:15:23 +01:00
)
)
after = None
while True:
2022-11-07 18:56:10 +01:00
params = "first: 1"
2021-10-31 18:15:23 +01:00
if after:
params += f', after:"{after}"'
2022-11-07 18:56:10 +01:00
query = """
2021-10-31 18:15:23 +01:00
query {
viewer {
sponsorshipsAsSponsor(%s) {
pageInfo {
startCursor
hasNextPage
endCursor
}
totalRecurringMonthlyPriceInDollars
nodes {
sponsorable {
... on Organization { login }
... on User { login }
}
}
}
}
}
2022-11-07 18:56:10 +01:00
""" % (
params,
)
2021-10-31 18:15:23 +01:00
response = client.execute(gql(query))
2022-11-07 18:56:10 +01:00
info = response["viewer"]["sponsorshipsAsSponsor"]
after = info["pageInfo"]["endCursor"]
nodes = info["nodes"]
2021-10-31 18:15:23 +01:00
if not len(nodes):
break
for node in nodes:
2022-11-07 18:56:10 +01:00
if (
node["sponsorable"]["login"].lower()
not in settings.GITHUB_ELIGIBLE_SPONSORSHIPS
):
2021-10-31 18:15:23 +01:00
continue
2022-11-07 18:56:10 +01:00
if (
info["totalRecurringMonthlyPriceInDollars"]
>= settings.GITHUB_SPONSORS_MIN_PAYMENT
):
2021-10-31 18:15:23 +01:00
return True
return False
def check_is_sponsor_cached(user: User) -> bool:
cache_key = CACHE_KEY % user.id
if not cache.get(cache_key):
cache.set(cache_key, check_is_sponsor(user), timeout=30)
return cache.get(cache_key)