Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
chkpwd committed Oct 22, 2024
0 parents commit bfeed39
Show file tree
Hide file tree
Showing 9 changed files with 209 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

.DS_Store

# build files
vendor/

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
.envrc

# ide files
.idea/
27 changes: 27 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
FROM python:3.12-slim-bookworm

RUN apt-get update && apt-get install -y --no-install-recommends \
git

ENV PYTHONUNBUFFERED=1

ENV ADDRESS=0.0.0.0
ENV PORT=7979

ENV DEBUG=false

WORKDIR /src

COPY requirements.txt /src

RUN pip install --no-cache-dir -r requirements.txt

WORKDIR /src/app

COPY constants/*.py /src/constants/
COPY app/*.py /src/app/
COPY main.py /src

EXPOSE 7979

CMD [ "/usr/local/bin/python", "/src/main.py" ]
Empty file added app/__init__.py
Empty file.
27 changes: 27 additions & 0 deletions app/parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from lxml import html
import logging
import requests


def get_anime_filler_list(anime_name: str):
"""Get the anime filler list."""

base_url = f"https://www.animefillerlist.com/shows/{anime_name}/"
url = f"{base_url}"
data = html.fromstring(requests.get(url).content)
filler_ranges = data.xpath(
'//div[@class="filler"]/span[@class="Episodes"]/a/text()'
)

fillers = []
for text in filler_ranges:
if "-" in text:
start, end = map(int, text.split("-"))
fillers.extend(range(start, end + 1))
else:
fillers.append(int(text))

if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
logging.debug(filler_ranges)

return fillers
54 changes: 54 additions & 0 deletions app/sonarr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import os
import sonarr
import logging


CONFIGURATION = sonarr.Configuration(host="https://sonarr.local.chkpwd.com")
CONFIGURATION.api_key["X-Api-Key"] = os.environ["SONARR_API_KEY"]


def get_sonarr_episodes(series_id: int):
"""Get the sonarr episodes."""
episodes = []

with sonarr.ApiClient(configuration=CONFIGURATION) as api_client:
api_instance = sonarr.EpisodeApi(api_client)
series_id = series_id

try:
api_response = api_instance.list_episode(series_id=series_id)

for item in api_response:
episodes.append(
{
"id": item.id,
"title": item.title,
"number": item.absolute_episode_number,
"monitored": item.monitored,
}
)

except Exception as e:
logging.error("Exception when calling EpisodeApi->list_episode: %s\n" % e)

return episodes


def configure_monitoring(episodes: list):
"""Configure the sonarr episodes to be monitored."""
with sonarr.ApiClient(configuration=CONFIGURATION) as api_client:
api_instance = sonarr.EpisodeApi(api_client)

episodes_monitored_resource = sonarr.EpisodesMonitoredResource(
episodeIds=[*episodes]
)
episodes_monitored_resource.monitored = True

try:
api_instance.put_episode_monitor(
episodes_monitored_resource=episodes_monitored_resource
)
except Exception as e:
logging.error(
"Exception when calling EpisodeApi->put_episode_monitor: %s\n" % e
)
Empty file added constants/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions constants/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import logging

LOG_LEVELS = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL,
}
65 changes: 65 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import os
import sys
import logging

from flask import Flask, jsonify
from app.parser import get_anime_filler_list
from app.sonarr import configure_monitoring, get_sonarr_episodes
from constants.logging import LOG_LEVELS

log_level = os.environ.get("LOG_LEVEL", "INFO").upper()

logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s",
level=LOG_LEVELS.get(log_level, logging.INFO),
handlers=[logging.StreamHandler(sys.stdout)],
)

app = Flask(__name__)

@app.route("/fillers", methods=["GET"])
def get_filler_list():
"""Returns the filler list for the specified anime."""
filler_list = get_anime_filler_list(anime_name=os.environ["ANIME_NAME"])
return jsonify({"value": filler_list})

if __name__ == "__main__":
logging.info("Initializing SOFE API...")
result = []

listen_address = os.environ.get("ADDRESS", "0.0.0.0")
listen_port = os.environ.get("PORT", 7979)

if not os.environ.get("ANIME_NAME"):
logging.error("ANIME_NAME must be set")
sys.exit(1)

if not os.environ.get("SONARR_SERIES_ID"):
logging.error("SERIES_ID must be set")
sys.exit(1)

if not os.environ.get("SONARR_API_KEY"):
logging.error("SONARR_API_KEY not set")
sys.exit(1)

if not os.environ.get("ADDRESS"):
logging.info("Address is not set. Defaulting to 0.0.0.0.")
else:
logging.info("Address is set to '%s'", listen_address)

if not os.environ.get("PORT"):
logging.info("Port is not set. Defaulting to 7979.")
else:
logging.info("Port is set to '%s'", listen_port)

fillers = get_anime_filler_list(os.environ["ANIME_NAME"])
episodes = get_sonarr_episodes(int(os.environ["SONARR_SERIES_ID"]))

for episode in episodes:
if episode['number'] not in fillers:
result.append(episode.get('id'))

configure_monitoring(result)

app.run(host=listen_address, port=int(listen_port))

5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
git+https://github.com/devopsarr/sonarr-py.git
lxml
prometheus_client
requests
flask

0 comments on commit bfeed39

Please sign in to comment.