all repos — myprecious @ 8b59845ab9b9df4c76efe688a18d9418435fa850

A lightweight web service to backup precious game saves.

myprecious/games_api.py (view raw)

 1from igdb.wrapper import IGDBWrapper
 2from urllib.parse import urlencode
 3from contextlib import suppress
 4import myprecious.constants as c
 5import requests
 6import os, json
 7
 8def get_token():
 9    if None in [ c.CLIENT_ID, c.CLIENT_SECRET ]:
10        print("Please check your .env file.")
11        exit(1)
12    url = f"{ c.AUTH_URL }?{ urlencode(c.AUTH_URL_PARAMS) }"
13    response = requests.request("POST", url).json()
14    return response['access_token']
15
16def construct_wrapper(token):
17    return IGDBWrapper(c.CLIENT_ID, token)
18
19def get_wrapper():
20    with suppress(FileExistsError):
21        os.makedirs(c.BASE_DIRECTORY)
22    try:
23        with open(c.TOKEN_PATH, "r", encoding="utf-8") as in_file:
24            token = in_file.readline()
25        # we got a token, it may be expired
26        w = construct_wrapper(token)
27        try:
28            w.api_request("games", "limit 1;")
29        except requests.exceptions.HTTPError as e:
30            if e.response.status_code == 401:
31                print("Invalid token. Getting a new one.")
32                raise FileNotFoundError
33            print("API connection error.")
34            exit(1)
35        return w # valid token
36    except FileNotFoundError:
37        # invalid or missing token
38        token = get_token()
39        with open(c.TOKEN_PATH, "w", encoding="utf-8") as out_file:
40            out_file.write(token)
41        return construct_wrapper(token)
42
43def req(endpoint, query):
44    result_bs = wrapper.api_request(endpoint, query)
45    result_str = result_bs.decode("utf-8")
46    return json.loads(result_str)
47
48def search_game(query: str):
49    cleaned_up_query = query.replace('"', '').replace("'","")
50    return req("games", f'search "{ cleaned_up_query }"; fields *, cover.*, platforms.*;')
51
52wrapper = get_wrapper()