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

81 lines
2.3 KiB
Python
Raw Normal View History

2021-06-25 21:55:40 +02:00
from django.conf import settings
2021-07-22 21:34:05 +02:00
from django.core.cache import cache
2021-06-25 21:55:40 +02:00
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
2021-07-24 15:48:12 +02:00
from social_django.models import UserSocialAuth
from .models import User
2021-06-25 21:55:40 +02:00
GQL_ENDPOINT = 'https://api.github.com/graphql'
2021-07-24 15:48:12 +02:00
CACHE_KEY = 'cached-sponsors:%s'
2021-06-25 21:55:40 +02:00
2021-07-24 15:48:12 +02:00
def check_is_sponsor(user: User) -> bool:
try:
token = user.social_auth.get(provider='github').extra_data.get('access_token')
except UserSocialAuth.DoesNotExist:
return False
if not token:
return False
2021-06-25 21:55:40 +02:00
client = Client(
transport=RequestsHTTPTransport(
url=GQL_ENDPOINT,
use_json=True,
headers={
2021-07-24 15:48:12 +02:00
'Authorization': f'Bearer {token}',
2021-06-25 21:55:40 +02:00
}
)
)
after = None
while True:
params = 'first: 1'
if after:
params += f', after:"{after}"'
query = '''
query {
user (login: "eugeny") {
2021-07-24 15:48:12 +02:00
sponsorshipsAsSponsor(%s) {
pageInfo {
startCursor
hasNextPage
endCursor
}
totalRecurringMonthlyPriceInDollars
nodes {
sponsorable {
... on Organization { login }
... on User { login }
2021-06-25 21:55:40 +02:00
}
}
}
}
}
''' % (params,)
response = client.execute(gql(query))
2021-07-24 15:48:12 +02:00
info = response['user']['sponsorshipsAsSponsor']
after = info['pageInfo']['endCursor']
nodes = info['nodes']
2021-06-25 21:55:40 +02:00
if not len(nodes):
break
for node in nodes:
2021-07-24 15:48:12 +02:00
if node['sponsorable']['login'].lower() not in settings.GITHUB_ELIGIBLE_SPONSORSHIPS:
continue
if info['totalRecurringMonthlyPriceInDollars'] >= settings.GITHUB_SPONSORS_MIN_PAYMENT:
return True
2021-06-25 21:55:40 +02:00
2021-07-24 15:48:12 +02:00
return False
2021-07-22 21:34:05 +02:00
2021-07-24 15:48:12 +02:00
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)