Compare commits

..

4 Commits

Author SHA1 Message Date
7a5070443b Add github token authentification 2024-03-01 18:43:05 +01:00
dc6d19e98a Add the database for application version 2024-03-01 14:33:49 +01:00
Félix MARQUET
61f49b15b7 Update README.md 2024-03-01 14:14:05 +01:00
910ae52445 Add repo list as enviroment variable 2024-03-01 13:56:29 +01:00
4 changed files with 71 additions and 22 deletions

View File

@@ -5,12 +5,14 @@ LABEL maintainer="BreizhHardware"
ADD ntfy.py /
ADD requirements.txt /
ADD entrypoint.sh /
RUN apk add --no-cache sqlite-dev sqlite-libs gcc musl-dev
RUN pip install -r requirements.txt
# Définir les variables d'environnement pour username et password
ENV USERNAME="" \
PASSWORD="" \
NTFY_URL="" \
GHNTFY_TIMEOUT="3600"
GHNTFY_TIMEOUT="3600" \
GHREPO=""
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -7,8 +7,11 @@ Personal ntfy alerts system
This script is used to watch the github repos and send a notification to the ntfy server when a new release is published.
## Utilisation:
auth and ntfy_url are required to be set as environment variables.
auth: can be generataed by the folowing command: echo -n 'username:password' | base64
ntfy_url: the url of the ntfy server including the topic
````python
python ntfy.py
````
@@ -18,20 +21,21 @@ If you want to use the docker image you can use the following docker-compose fil
version: '3'
services:
github-ntfy:
image: breizhhardware/github-ntfy
image: breizhhardware/github-ntfy:latest
container_name: github-ntfy
environment:
- USERNAME=username
- PASSWORD=password
- NTFY_URL=ntfy_url
- USERNAME=username # Required
- PASSWORD=password # Required
- NTFY_URL=ntfy_url # Required
- GHNTFY_TIMEOUT=timeout # Default is 3600 (1 hour)
- GHREPO=["username/repo1", "username/repo2"] # Default is empty
- GHNTFY_TOKEN= # Default is empty (Github token)
restart: unless-stopped
````
Acctualy the watched repos list is hardcoded in the ntfy.py file under the name of watched_repos_list.
## TODO:
- [x] Dockerize the ntfy.py
- [ ] Add the watched repos list as a parameter
- [ ] Add the watched repos list as a file
- [ ] Add the watched repos list as a database
- [x] Add the watched repos list as a parameter
- [x] Add the application version as a database
- [ ] Add the watched repos list as a web interface
# Bash setup-notify.sh
## Description:
@@ -41,8 +45,11 @@ This script is used to setup the ntfy notification system on ssh login for a new
bash setup-notify.sh <ntfy_url> <username> <password> <topic>
````
ntfy_url: the url of the ntfy server
username: the username of the user
password: the password of the user
topic: the topic of the notification
This script will create a send-notify.sh in the root of your disk and add the login-notify.sh to the /etc/profile.d/ folder.
@@ -54,7 +61,10 @@ This script is used to send a notification to the ntfy server.
bash send-notify.sh <ntfy_url> <basic_auth> <topic> <message>
````
ntfy_url: the url of the ntfy server
basic_auth: the basic auth of the user
topic: the topic of the notification
message: the message of the notification

60
ntfy.py
View File

@@ -2,53 +2,89 @@ import requests
import time
import os
import logging
import json
import sqlite3
# Configurer le logger
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
watched_repos_list = ['dani-garcia/vaultwarden', 'jellyfin/jellyfin', 'linuxserver/Heimdall',
'jlesage/docker-nginx-proxy-manager', 'linuxserver/docker-speedtest-tracker',
'linuxserver/docker-xbackbone', 'Fallenbagel/jellyseerr', 'FlareSolverr/FlareSolverr',
'linuxserver/docker-jackett', 'linuxserver/docker-radarr', 'linuxserver/docker-sonarr']
github_token = os.environ.get('GHNTFY_TOKEN')
github_headers = {}
if github_token:
github_headers['Authorization'] = f"token {github_token}"
# Dictionnaire pour stocker les versions précédentes
previous_versions = {}
repo_list_env = os.environ.get('GHREPO')
watched_repos_list = json.loads(repo_list_env) if repo_list_env else []
if not watched_repos_list:
logger.error("Aucun dépôt n'a été spécifié. Veuillez spécifier les dépôts à surveiller dans l'environnement GHREPO")
exit(1)
# Connexion à la base de données pour stocker les versions précédentes
db_path = 'ghntfy_versions.db'
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Création de la table si elle n'existe pas
cursor.execute('''CREATE TABLE IF NOT EXISTS versions
(repo TEXT PRIMARY KEY, version TEXT, changelog TEXT)''')
conn.commit()
logger.info("Démarrage de la surveillance des versions...")
def get_latest_releases(watched_repos):
releases = []
for repo in watched_repos:
url = f"https://api.github.com/repos/{repo}/releases/latest"
response = requests.get(url)
response = requests.get(url, headers=github_headers)
if response.status_code == 200:
release_info = response.json()
changelog = get_changelog(repo)
releases.append({
"repo": repo,
"name": release_info["name"],
"tag_name": release_info["tag_name"],
"html_url": release_info["html_url"]
"html_url": release_info["html_url"],
"changelog": changelog
})
else:
logger.error(f"Failed to fetch release info for {repo}")
return releases
def get_changelog(repo):
url = f"https://api.github.com/repos/{repo}/releases"
response = requests.get(url, headers=github_headers)
if response.status_code == 200:
releases = response.json()
if releases:
latest_release = releases[0]
if 'body' in latest_release:
return latest_release['body']
return "Changelog non disponible"
def send_to_ntfy(releases, auth, url):
for release in releases:
app_name = release['repo'].split('/')[-1] # Obtenir le nom de l'application à partir du repo
version_number = release['tag_name'] # Obtenir le numéro de version
app_url = release['html_url'] # Obtenir l'URL de l'application
changelog = release['changelog'] # Obtenir le changelog
# Vérifier si la version a changé depuis la dernière fois
if app_name in previous_versions and previous_versions[app_name] == version_number:
cursor.execute("SELECT version FROM versions WHERE repo=?", (app_name,))
previous_version = cursor.fetchone()
if previous_version and previous_version[0] == version_number:
logger.info(f"La version de {app_name} n'a pas changé. Pas de notification envoyée.")
continue # Passer à l'application suivante
message = f"Nouvelle version: {version_number}\nPour: {app_name}\n{app_url}"
message = f"Nouvelle version: {version_number}\nPour: {app_name}\nChangelog:\n{changelog}\n{app_url}"
# Mettre à jour la version précédente pour cette application
previous_versions[app_name] = version_number
cursor.execute("INSERT OR REPLACE INTO versions (repo, version, changelog) VALUES (?, ?, ?)",
(app_name, version_number, changelog))
conn.commit()
headers = {"Authorization": f"Basic {auth}", "Content-Type": "text/plain"}
response = requests.post(f"{url}", headers=headers, data=message)

View File

@@ -1 +1,2 @@
requests==2.31.0
requests==2.31.0
pysqlite3==0.5.2