anical/main.py

78 lines
1.9 KiB
Python

import requests
import time
import tomllib
from os import path
import json
TTL = 2 * 60 * 60 # 2 hours
if path.exists("config.toml"):
with open("config.toml", "rb") as f:
data = tomllib.load(f)
else:
raise RuntimeError("config.toml not found")
def getMediaListCollection(type=data["anilist"]["mediaType"], userId=data["anilist"]["userId"]):
if not type or not userId:
raise RuntimeError("MediaType and UserId must be set")
query = """
query ($type: MediaType!, $userId: Int!, $chunk: Int, $perChunk: Int) {
MediaListCollection(type: $type, userId: $userId, chunk: $chunk, perChunk: $perChunk) {
hasNextChunk
lists {
name
entries {
id
media {
id
title {
english
romaji
}
}
}
}
}
}
"""
entries = {} # keyed by entry id, dedupes custom-list repeats
chunk = 1
while True:
variables = { 'type': type, 'userId': int(userId), 'chunk': chunk, 'perChunk': 500, }
resp = requests.post(
"https://graphql.anilist.co",
json={"query": query, "variables": variables},
timeout=30,
)
resp.raise_for_status()
data = resp.json()
if "errors" in data:
raise RuntimeError(data["errors"])
collection = data["data"]["MediaListCollection"]
for lst in collection["lists"]:
for entry in lst["entries"]:
entries[entry["id"]] = entry
if not collection["hasNextChunk"]:
break
chunk += 1
form = {
"timestamp": str(time.time()),
"ttl": str(TTL),
"response": list(entries.values()),
}
return form
if __name__ == "__main__":
entries = getMediaListCollection()
with open("data.json", "w") as f:
f.write(f"{json.dumps(entries, indent=2)}")