Begin work on v2

This commit is contained in:
Uthman Fatih 2026-10-30 13:35:35 +00:00
parent 59481b1d6f
commit ae06fb2983
6 changed files with 57 additions and 620 deletions

226
.gitignore vendored
View File

@ -1,226 +0,0 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
*.lcov
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
# Pipfile.lock
# uv
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
# poetry.lock
# poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
# pdm.lock
# pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
# pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi/*
!.pixi/config.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule*
celerybeat.pid
# Redis
*.rdb
*.aof
*.pid
# RabbitMQ
mnesia/
rabbitmq/
rabbitmq-data/
# ActiveMQ
activemq-data/
# SageMath parsed files
*.sage.py
# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs/Zensical documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
# .idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer, you
# could uncomment the following to ignore the entire vscode folder
# .vscode/
# Temporary file for partial code execution
tempCodeRunnerFile.py
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# Streamlit
.streamlit/secrets.toml
# Anical
airingdata.json
listdata.json
config.toml
anime.ics

View File

@ -1,6 +0,0 @@
[anilist]
userId = 8283179
mediaType = "ANIME"
[anical]
listNames = ["Completed", "Planning", "Watching", "Rewatching", "Paused"]

388
main.py
View File

@ -1,388 +0,0 @@
import requests
import time
import tomllib
from os import path
import os
import json
from icalendar import Calendar, Event
from datetime import datetime, timezone
if path.exists("config.toml"):
with open("config.toml", "rb") as f:
config = tomllib.load(f)
else:
raise RuntimeError("config.toml not found")
TTL = config["anilist"].get("TTL", 2 * 60 * 60) # 2 hour default if not specificed
def getMediaListCollection(
mediaType=config["anilist"]["mediaType"],
userId=config["anilist"]["userId"],
*,
cachePath="listdata.json"
):
"""
Returns a tuple of (entries, cached)
Entries is a dictionary of the values to be written to the cache file, such as:
- timestamp
- ttl
- params supplied
- response
cached is a boolean indicating whether the cache file was used or not
Takes the following arguments:
- mediaType: the media type to use for the request (if not supplied, defaults to value supplied from config.toml)
- userId: the user id to use for the request (if not supplied, defaults to value supplied from config.toml)
- cachePath: the path to the cache file (if not supplied, defaults to "data.json")
"""
if not mediaType or not userId:
raise RuntimeError("MediaType and UserId must be set")
if path.exists(cachePath):
with open(cachePath, "r") as f:
entries = json.load(f)
if (
"timestamp" in entries
and "ttl" in entries
and "response" in entries
and "params" in entries
):
timestamp = float(entries["timestamp"])
ttl = float(entries["ttl"])
cacheUserId = entries["params"].get("userId")
cacheMediaType = entries["params"].get("mediaType")
cacheExpired = time.time() - timestamp > ttl
parametersChanged = (
cacheUserId != userId
or cacheMediaType != mediaType
)
if not cacheExpired and not parametersChanged:
print("Cache is fresh, using cached data...")
return (entries, True)
if cacheExpired:
print("Cache has gone stale, refreshing...")
elif parametersChanged:
print("Cache parameters changed, refreshing...")
else:
print("Cache is invalid, refreshing...")
# Fetch fresh data from AniList
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 = {}
chunk = 1
while True:
variables = {
"type": mediaType,
"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"]:
entries.setdefault(lst["name"], []).extend(lst["entries"])
if not collection["hasNextChunk"]:
break
chunk += 1
form = {
"timestamp": str(time.time()),
"ttl": str(TTL),
"params": {
"mediaType": mediaType,
"userId": userId,
},
"response": entries
}
return (form, False)
def getAiringScheduleBatch(
animeIds,
*,
ttl=TTL,
cachePath="airingdata.json",
maxRetries=5
):
"""
Returns a tuple of (entries, cached)
Entries is a dictionary of the values to be written to the cache file, such as:
- timestamp
- ttl
- params supplied
- response
response is a dictionary of mediaId (as a string) -> {"title": {"romaji", "english"}, "schedule": [upcoming airing schedule items]}
cached is a boolean indicating whether the cache file was used or not
Takes the following arguments:
- animeIds: list of AniList media ids to fetch airing schedules for
- ttl: seconds the cache stays fresh for. Only applied when the cache is refreshed;
an existing cache keeps the ttl it was written with (defaults to value from config.toml)
- cachePath: the path to the cache file (if not supplied, defaults to "airingdata.json")
- maxRetries: how many times in a row to retry after a 429 before giving up (defaults to 5)
"""
if not animeIds:
raise RuntimeError("animeIds must not be empty")
animeIds = sorted(set(int(i) for i in animeIds))
if path.exists(cachePath):
with open(cachePath, "r") as f:
entries = json.load(f)
if (
"timestamp" in entries
and "ttl" in entries
and "response" in entries
and "params" in entries
):
timestamp = float(entries["timestamp"])
cacheTtl = float(entries["ttl"])
cacheIds = entries["params"].get("animeIds")
cacheExpired = time.time() - timestamp > cacheTtl
parametersChanged = cacheIds != animeIds
if not cacheExpired and not parametersChanged:
print("Airing cache is fresh, using cached data...")
return (entries, True)
if cacheExpired:
print("Airing cache has gone stale, refreshing...")
elif parametersChanged:
print("Airing cache parameters changed, refreshing...")
else:
print("Airing cache is invalid, refreshing...")
query = """
query ($ids: [Int], $page: Int) {
Page(page: $page, perPage: 50) {
pageInfo {
hasNextPage
currentPage
}
airingSchedules(mediaId_in: $ids, notYetAired: true, sort: TIME) {
id
airingAt
timeUntilAiring
episode
mediaId
media {
title {
romaji
english
}
}
}
}
}
"""
schedules = {}
page = 1
retries = 0
while True:
variables = {
"ids": animeIds,
"page": page,
}
resp = requests.post(
"https://graphql.anilist.co",
json={
"query": query,
"variables": variables,
},
timeout=30,
)
# retry if rate limited
if resp.status_code == 429:
retries += 1
if retries > maxRetries:
raise RuntimeError("Rate limited too many times, giving up")
wait = int(resp.headers.get("Retry-After", 60))
print(f"Rate limited, waiting {wait}s...")
time.sleep(wait)
continue
retries = 0
resp.raise_for_status()
data = resp.json()
if "errors" in data:
raise RuntimeError(data["errors"])
pageData = data["data"]["Page"]
for item in pageData["airingSchedules"]:
# media can be null, fall back to empty titles
media = item.pop("media", None) or {}
title = media.get("title") or {}
entry = schedules.setdefault(
str(item["mediaId"]),
{
"title": {
"romaji": title.get("romaji"),
"english": title.get("english"),
},
"schedule": [],
},
)
entry["schedule"].append(item)
if not pageData["pageInfo"]["hasNextPage"]:
break
page += 1
form = {
"timestamp": str(time.time()),
"ttl": str(ttl),
"params": {
"animeIds": animeIds,
},
"response": schedules
}
return (form, False)
def createIcal(
schedules,
*,
name="Anime Airing Schedule",
duration=24 * 60
):
"""
Returns the .ics file contents (bytes) for every upcoming episode in schedules.
Takes the following arguments:
- schedules: the "response" dict from getAiringScheduleBatch (mediaId -> {"title", "schedule"})
- name: the calendar's display name (defaults to "Anime Airing Schedule")
- duration: event length in seconds (defaults to 24 minutes)
"""
cal = Calendar()
cal.add("prodid", "-//anical//AniList airing schedule//EN")
cal.add("version", "2.0")
cal.add("x-wr-calname", name) # display name in Google/Apple Calendar
now = time.time()
stamp = datetime.now(timezone.utc)
for mediaId, anime in schedules.items():
title = anime["title"].get("english") or anime["title"].get("romaji") or f"Anime {mediaId}"
for item in anime["schedule"]:
# the cache can be older than some of its episodes, so skip anything already aired
if item["airingAt"] <= now:
continue
ev = Event()
ev.add("uid", f"anilist-{item['id']}@anilist.co")
ev.add("summary", f"{title} - Episode {item['episode']}")
ev.add("dtstart", datetime.fromtimestamp(item["airingAt"], timezone.utc))
ev.add("dtend", datetime.fromtimestamp(item["airingAt"] + duration, timezone.utc))
ev.add("dtstamp", stamp)
cal.add_component(ev)
return cal.to_ical() # bytes
if __name__ == "__main__":
entries, cached = getMediaListCollection()
if not cached:
with open("listdata.json", "w") as f:
f.write(f"{json.dumps(entries, indent=2)}")
lists = entries["response"]
print("\nList Names updating for:")
for li in config["anical"]["listNames"]:
print(li)
# get a list of all the animes ids in these lists:
animeIds = []
for li in config["anical"]["listNames"]:
if li not in lists:
print(f"Warning: list '{li}' not found, skipping")
continue
for entry in lists[li]:
animeIds.append(entry["media"]["id"])
print(f"\nFound {len(animeIds)} anime ids")
airing, airingCached = getAiringScheduleBatch(animeIds)
if not airingCached:
with open("airingdata.json", "w") as f:
f.write(f"{json.dumps(airing, indent=2)}")
schedules = airing["response"]
print(f"\nGot upcoming episodes for {len(schedules)} anime")
ics = createIcal(schedules)
with open("anime.ics.tmp", "wb") as f:
f.write(ics)
os.replace("anime.ics.tmp", "anime.ics")

3
src/go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.uthmn.com/boiabba/anical
go 1.27.3

7
src/main.go Normal file
View File

@ -0,0 +1,7 @@
package main
import "fmt"
func main() {
fmt.Println("Cooking up v2")
}

47
todo.md Normal file
View File

@ -0,0 +1,47 @@
> [!NOTE]
> This is simply a guidance for development. Nothing here is final or guranteed.
| Command | Description |
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `anical generate --id <id> <path>` | Generates an ICS file at `<path>`. The `--id` flag is optional and takes priority over the AniList ID set in the environment. |
| `anical fetch --id <id>` | Fetches dates and returns to STDOUT without saving. The `--id` flag is optional and takes priority over the AniList ID set in the environment |
| `anical install [--user]` | Installs the AniCal server as a systemd service. System-wide by default; `--user` installs it as a user service using `systemctl --user`. |
| `anical uninstall [--user]` | Removes the AniCal server service. Use `--user` to remove a user service instead of the system-wide one. |
| `anical serve [flags] [--config <path>]` | Runs the server directly without installing it. Reads the config file at `<path>` if given, otherwise uses the flags. Flags take priority over the config file. |
| `anical config set <path> <value>` | Sets a config value by dotted path, such as `global.notify.email.username`. Checks that the value matches the expected type before writing. |
| `anical config get <path>` | Prints the value at a dotted config path, such as `global.notify.email.username`. |
The project is written in Go, and it uses Lua for scripting.
TOML, YAML, or JSON config all works
WebDAV support which alters a webdav to add the dates directly via the WebDAV subset of commands (i.e. `anical webdav fetch --id ...`). WebDaV and normal installations can live side by side without breaking.
WebDAV serve can either periodically modify an existing webdav or serve a custom implemented read only.
Manga support for notifications on new chapters
Proper credits to services I use and clean up github.
Proper documentation and cleaned up repo. Utilise gitea wiki.
Proper utilisation of ical format (i.e. for weekly releases, auto detect and use repeating event, or event length be the real episode length).
Movie detection (either based on length, or if possible anilist api)
More granualar cache (based on show release schedule)
These configs are just an idea and can be added to or changed
| Config | Description |
| --------------- | ------------------------------------------------------------------------------------------------------------------ |
| Cache lifetime | How long the cache can be before declared stale (on request with stale cache, refetch and regenerate just in time) |
| Anilist user id | Anilist user id |
| Media format | Manga, Anime or both |
| Lists | Anilists to fetch from |
| Split data | True or false, either combine manga.ics and anime.ics or serve from two different paths. |
Plugin support written in Lua
- Hooks e.g. when regenerating or when someone fetches the list
- Middleware e.g. altering the web fetching or any component really such as altering returned ics
- Plugins e.g. api that adds new webserver paths
To install a plugin you just make a folder pluginname and then inside you populate with subfolders required for the plugin:
| Folder | Description |
| ---------- | ---------------------- |
| hooks | Hook lua scripts |
| middleware | Middleware lua scripts |
| plugins | Plugin lua scripts |
Custom folders can be created and will be ignored by anical, i.e. a config folder which a plugin reads and generates hooks and middleware files from. Plugins cannot be created at runtime, hooks and middleware can.
Running hooks and middleware is atomic so it never exits unfinished