Improve HTML

This commit is contained in:
2022-12-07 20:17:52 +01:00
parent b60257f9e9
commit 09fa6ece48
7 changed files with 120 additions and 121 deletions

View File

@ -83,8 +83,7 @@ def add_feed(feed_url: str, webhook: str, exist_ok=False, allow_invalid_url=Fals
Returns: Returns:
IfFeedError: Error or not. IfFeedError: Error or not.
""" """
# Remove spaces from feed_url logger.debug(f"Adding feed: {feed_url}")
feed_url = feed_url.strip()
try: try:
reader.add_feed(feed_url, exist_ok=exist_ok, allow_invalid_url=allow_invalid_url) reader.add_feed(feed_url, exist_ok=exist_ok, allow_invalid_url=allow_invalid_url)
@ -98,7 +97,6 @@ def add_feed(feed_url: str, webhook: str, exist_ok=False, allow_invalid_url=Fals
webhook=webhook, webhook=webhook,
exception=error.message, exception=error.message,
) )
except InvalidFeedURLError as error: except InvalidFeedURLError as error:
error_msg = "Invalid feed URL" error_msg = "Invalid feed URL"
logger.error(error_msg, exc_info=True) logger.error(error_msg, exc_info=True)
@ -109,6 +107,7 @@ def add_feed(feed_url: str, webhook: str, exist_ok=False, allow_invalid_url=Fals
webhook=webhook, webhook=webhook,
exception=error.message, exception=error.message,
) )
logger.debug(f"Successfully added feed: {feed_url}")
return IfFeedError(error=False, feed_url=feed_url, webhook=webhook) return IfFeedError(error=False, feed_url=feed_url, webhook=webhook)

View File

@ -26,7 +26,6 @@ Functions:
startup() startup()
Runs on startup. Runs on startup.
""" """
import enum
import sys import sys
from functools import cache from functools import cache
from typing import Any, Iterable from typing import Any, Iterable
@ -37,13 +36,13 @@ from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates from fastapi.templating import Jinja2Templates
from reader import EntryCounts, Feed, FeedCounts, FeedNotFoundError, ReaderError, ResourceNotFoundError, StorageError from reader import EntryCounts, Feed, FeedCounts, FeedNotFoundError, ReaderError, ResourceNotFoundError, StorageError, \
TagNotFoundError
from starlette.templating import _TemplateResponse from starlette.templating import _TemplateResponse
from tomlkit.toml_document import TOMLDocument from tomlkit.toml_document import TOMLDocument
from discord_rss_bot.feeds import IfFeedError, add_feed, send_to_discord, update_feed from discord_rss_bot.feeds import IfFeedError, add_feed, send_to_discord, update_feed
from discord_rss_bot.settings import logger, read_settings_file, reader from discord_rss_bot.settings import logger, read_settings_file, reader
from discord_rss_bot.webhooks import set_hook_by_name
app: FastAPI = FastAPI() app: FastAPI = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/static", StaticFiles(directory="static"), name="static")
@ -73,6 +72,11 @@ async def create_feed(feed_url: str = Form(), webhook_dropdown: str = Form()) ->
Returns: Returns:
dict: The feed that was added. dict: The feed that was added.
""" """
# Remove spaces from feed_url
feed_url = feed_url.strip()
logger.debug(f"Stripped feed_url: {feed_url}")
logger.info(f"Add feed: {feed_url}") logger.info(f"Add feed: {feed_url}")
logger.info(f"Webhook: {webhook_dropdown}") logger.info(f"Webhook: {webhook_dropdown}")
@ -91,29 +95,33 @@ async def create_feed(feed_url: str = Form(), webhook_dropdown: str = Form()) ->
} }
return HTTPException(status_code=500, detail=error_dict) return HTTPException(status_code=500, detail=error_dict)
# Check if set_hook_by_name() was successful. settings: TOMLDocument = read_settings_file()
if isinstance(
set_hook_by_name(name=webhook_dropdown, feed_url=feed_url),
ResourceNotFoundError,
):
return set_hook_by_name(name=webhook_dropdown, feed_url=feed_url)
new_tag: str = str(reader.get_tag(feed_url, "webhook")) logger.debug(f"Webhook name: {webhook_dropdown} with URL: {settings['webhooks'][webhook_dropdown]}")
webhook_url: str = str(settings["webhooks"][webhook_dropdown])
try:
reader.set_tag(feed_url, "webhook", webhook_url)
except ResourceNotFoundError as e:
error_msg: str = f"ResourceNotFoundError: Could not set webhook: {e}"
logger.error(error_msg, exc_info=True)
return HTTPException(status_code=500, detail=error_msg)
new_tag = reader.get_tag(feed_url, "webhook")
logger.info(f"New tag: {new_tag}") logger.info(f"New tag: {new_tag}")
return {"feed_url": str(feed_url), "status": "added"} return {"feed_url": str(feed_url), "status": "added"}
def create_list_of_webhooks() -> enum.EnumMeta: def create_list_of_webhooks() -> list[dict[str, str]]:
"""List with webhooks.""" """List with webhooks."""
logger.info("Creating list with webhooks.") logger.info("Creating list with webhooks.")
settings: TOMLDocument = read_settings_file() settings: TOMLDocument = read_settings_file()
list_of_webhooks = dict() list_of_webhooks = []
for hook in settings["webhooks"]: for hook in settings["webhooks"]:
logger.info(f"Webhook name: {hook} with URL: {settings['webhooks'][hook]}") logger.info(f"Webhook name: {hook} with URL: {settings['webhooks'][hook]}")
list_of_webhooks[hook] = settings["webhooks"][hook] list_of_webhooks.append({"name": hook, "url": settings['webhooks'][hook]})
logger.debug(f"Hook: {hook}, URL: {settings['webhooks'][hook]}")
logger.info(f"List of webhooks: {list_of_webhooks}") logger.info(f"List of webhooks: {list_of_webhooks}")
return enum.Enum("DiscordWebhooks", list_of_webhooks) return list_of_webhooks
@cache @cache
@ -154,6 +162,7 @@ async def get_feed(feed_url: str, request: Request) -> _TemplateResponse:
logger.info(f"Got feed: {feed_url}") logger.info(f"Got feed: {feed_url}")
feed: Feed = reader.get_feed(feed_url) feed: Feed = reader.get_feed(feed_url)
# Get entries from the feed. # Get entries from the feed.
entries: Iterable[EntryCounts] = reader.get_entries(feed=feed_url) entries: Iterable[EntryCounts] = reader.get_entries(feed=feed_url)
@ -191,14 +200,16 @@ def make_context_index(request) -> dict:
dict: The context. dict: The context.
""" """
hooks: enum.EnumMeta = create_list_of_webhooks() hooks = create_list_of_webhooks()
for hook in hooks: feed_list = []
logger.info(f"Webhook name: {hook.name}")
feed_list: list[Feed] = list()
feeds: Iterable[Feed] = reader.get_feeds() feeds: Iterable[Feed] = reader.get_feeds()
for feed in feeds: for feed in feeds:
feed_list.append(feed) logger.debug(f"Feed: {feed}")
try:
hook = reader.get_tag(feed.url, "webhook")
except TagNotFoundError:
hook = "None"
feed_list.append({"feed": feed, "webhook": hook})
feed_count: FeedCounts = reader.get_feed_counts() feed_count: FeedCounts = reader.get_feed_counts()
entry_count: EntryCounts = reader.get_entry_counts() entry_count: EntryCounts = reader.get_entry_counts()

View File

@ -1,13 +1,21 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Index{% endblock %} {% block title %}Index{% endblock %}
{% block content %} {% block content %}
{# Home / Add #}
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="/">Home</a></li>
<li class="breadcrumb-item active" aria-current="page">Add</li>
</ol>
</nav>
<div class="p-2 mb-2 border border-dark rounded"> <div class="p-2 mb-2 border border-dark rounded">
<form action="/add" method="post"> <form action="/add" method="post">
{# Feed URL #} {# Feed URL #}
<div class="row mb-3"> <div class="row mb-3">
<label for="feed_url" class="col-sm-2 col-form-label">Feed URL</label> <label for="feed_url" class="col-sm-2 col-form-label">Feed URL</label>
<div class="col-sm-10"> <div class="col-sm-10">
<input type="text" class="form-control" id="feed_url" <input name="feed_url" type="text" class="form-control" id="feed_url"
placeholder="https://www.reddit.com/r/FreeGameFindings.rss"> placeholder="https://www.reddit.com/r/FreeGameFindings.rss">
</div> </div>
</div> </div>

View File

@ -1,14 +1,13 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
{% block head %}
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
crossorigin="anonymous"> crossorigin="anonymous">
<title>RSS - {% block title %}{% endblock %}</title> <title>RSS - {% block title %}{% endblock %}</title>
{% endblock %} {% block head %}{% endblock %}
</head> </head>
<body class="text-white-50" style="background: #111111;"> <body class="text-white-50" style="background: #111111;">
{% include "nav.html" %} {% include "nav.html" %}
@ -21,13 +20,17 @@
.com/TheLovinator1">TheLovinator</a> .com/TheLovinator1">TheLovinator</a>
</p> </p>
<ul class="nav col-md-4 justify-content-end"> <ul class="nav col-md-4 justify-content-end">
<li class="nav-item"><a href="mailto:tlovinator@gmail.com" <li class="nav-item">
class="nav-link px-2 text-muted">Email</a> <a href="mailto:tlovinator@gmail.com" class="nav-link px-2 text-muted">Email</a>
</li>
<li class="nav-item">
<a href="https://github.com/TheLovinator1/discord-rss-bot/issues"
class="nav-link px-2 text-muted">Report an issue</a>
</li>
<li class="nav-item">
<a href="https://github.com/TheLovinator1/discord-rss-bot/issues"
class="nav-link px-2 text-muted">Send feedback</a>
</li> </li>
<li class="nav-item"><a href="https://github.com/TheLovinator1/discord-rss-bot/issues"
class="nav-link px-2 text-muted">Send an issue</a></li>
<li class="nav-item"><a href="https://github.com/TheLovinator1/discord-rss-bot/issues"
class="nav-link px-2 text-muted">Feature request</a></li>
</ul> </ul>
</footer> </footer>
</div> </div>

View File

@ -13,6 +13,22 @@
{% if feed.last_exception %} Last exception: {{ feed.last_exception }} <br> {% endif %} {% if feed.last_exception %} Last exception: {{ feed.last_exception }} <br> {% endif %}
{% if not feed.updates_enabled %} <span style="color: red"> Updates disabled! </span> <br>{% endif %} {% if not feed.updates_enabled %} <span style="color: red"> Updates disabled! </span> <br>{% endif %}
</div> </div>
<div class="btn-toolbar" role="group">
<div class="btn-group me-2" role="group">
<form action="/check" method="post">
<button class="btn btn-primary" type="submit" name="feed_url" value="{{ feed.url }}">
Send new entries to Discord
</button>
</form>
</div>
<div class="btn-group me-2" role="group">
<form action="/remove" method="post">
<button class="btn btn-danger" type="submit" name="feed_url" value="{{ feed.url }}">
Remove feed
</button>
</form>
</div>
</div>
<div class="p-2 mb-2 border border-dark rounded" style="background:#0F0F0F"> <div class="p-2 mb-2 border border-dark rounded" style="background:#0F0F0F">
{% for entry in entries %} {% for entry in entries %}
{# Only add <hr> if the entry is not the first one #} {# Only add <hr> if the entry is not the first one #}
@ -65,17 +81,5 @@
{% if entry.read_modified %} Read modified: {{ entry.read_modified.strftime('%Y-%m-%d, %T') }} {% if entry.read_modified %} Read modified: {{ entry.read_modified.strftime('%Y-%m-%d, %T') }}
{% endif %} {% endif %}
{% endfor %} {% endfor %}
<form action="/check" method="post">
<button type="submit" name="feed_url" value="{{ feed.url }}">
Send new entries to Discord.
</button>
</form>
<form action="/remove" method="post">
<button type="submit" name="feed_url" value="{{ feed.url }}">
Remove feed.
</button>
</form>
</div> </div>
{% endblock %} {% endblock %}

View File

@ -1,59 +1,60 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Index{% endblock %} {% block title %}Index{% endblock %}
{% block head %}
<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>
{% endblock %}
{% block content %} {% block content %}
<!-- List all feeds --> <!-- List all feeds -->
{% for tag in tags %}
{{ tag }}
{% endfor %}
<ul> <ul>
<!-- Check if any feeds --> <!-- Check if any feeds -->
{% if feeds %} {% if feeds %}
{% for feed in feeds %}
<p><a class="text-muted" href="/feed/{{ feed.url }}">{{ feed.url }}</a></p>
{% if feed.last_exception %}
<li class="text-danger">
Last exception: {{ feed.last_exception.type_name }}: {{ feed.last_exception.value_str }}
</li>
{% endif %}
{% endfor %}
{% else %}
<p>No feeds yet. Add one <a class="text-muted" href="/add">here</a>.</p>
{% endif %}
</ul>
<!-- Feed stats -->
<hr>
<ul>
<li>
<p> <p>
{{ feed_count.total }} feeds {{ feed_count.total }} feeds
{% if feed_count.broken %} {% if feed_count.broken %}
- {{ feed_count.broken }} broken <span class="text-danger">
{% else %}
<span>
{% endif %} {% endif %}
- {{ feed_count.broken }} broken</span>
{% if feed_count.total != feed_count.updates_enabled %} {% if feed_count.total != feed_count.updates_enabled %}
<span class="text-warning">
{% else %}
<span>
{% endif %}
- {{ feed_count.updates_enabled }} enabled - {{ feed_count.updates_enabled }} enabled
{% endif %} </span>
- {{ entry_count.total }} entries
<span data-bs-toggle="tooltip" title="Entries per day average for the past 1, 3 and 12 months">
({{ entry_count.averages[0]|round(1) }},
{{ entry_count.averages[1]|round(1) }},
{{ entry_count.averages[2]|round(1) }})
</span>
</p> </p>
{% for hook_from_context in webhooks %}
<div class="p-2 mb-2 border border-dark">
<ul class="list-group">{{ hook_from_context.name }}
{% for feed_webhook in feeds %}
{% set feed = feed_webhook["feed"] %}
{% set hook_from_feed = feed_webhook["webhook"] %}
{% if hook_from_context.url == hook_from_feed %}
<li class="list-group-item" style="background:#111111">
<a class="text-muted" href="/feed/{{ feed.url }}">{{ feed.url }}</a>
</li> </li>
{% endif %}
{% endfor %}
</ul> </ul>
<!-- Feed entries stats --> </div>
<ul> {% endfor %}
<li> {% else %}
<p>{{ entry_count.total }} entries total</p> <p>
{% if entry_count.read != entry_count.total %} No feeds yet. Add one <a class="text-muted" href="/add">here</a>.
<p>{{ entry_count.total - entry_count.read }} unread entries</p> </p>
{% endif %} {% endif %}
{% if entry_count.important %}
<p>Important: {{ entry_count.important }} entries</p>
{% endif %}
{% if entry_count.has_enclosures %}
<p>Has enclosures: {{ entry_count.has_enclosures }} entries</p>
{% endif %}
<p>1 Month average: {{ entry_count.averages[0]|round(2) }} entries per day</p>
<p>3 Months average: {{ entry_count.averages[1]|round(2) }} entries per day</p>
<p>12 Months average: {{ entry_count.averages[2]|round(2) }} entries per day</p>
</li>
</ul> </ul>
{% endblock %} {% endblock %}

View File

@ -1,27 +0,0 @@
from fastapi import HTTPException
from reader import ResourceNotFoundError
from tomlkit.toml_document import TOMLDocument
from discord_rss_bot.settings import logger, read_settings_file, reader
def set_hook_by_name(name: str, feed_url: str) -> HTTPException:
"""Set a webhook by name.
Args:
name: The name of the webhook.
feed_url: The feed to set the webhook for.
Returns:
HTTPException: The HTTP exception if the webhook was not found, otherwise None.
"""
settings: TOMLDocument = read_settings_file()
logger.debug(f"Webhook name: {name} with URL: {settings['webhooks'][name]}")
webhook_url: str = str(settings["webhooks"][name])
try:
reader.set_tag(feed_url, "webhook", webhook_url)
except ResourceNotFoundError as e:
error_msg: str = f"ResourceNotFoundError: Could not set webhook: {e}"
logger.error(error_msg, exc_info=True)
return HTTPException(status_code=500, detail=error_msg)