Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions api/insert_data.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from flask.globals import request
from database import Database
import datetime

from flask import request

import config
import notifications
from database import Database


def insert_data():
Expand All @@ -11,6 +14,21 @@ def insert_data():
print("INSERT >> Received valid data: ", r_data)

database = Database()

# TODO: Implement proper check system
# Check for weight differences > 500g
try:
current = database.get_data(datetime.date.strftime(datetime.date.today()-datetime.timedelta(days=5), "%Y-%m-%d"),
datetime.date.strftime(datetime.date.today(), "%Y-%m-%d"))[-1]
if current["weight"] - float(r_data["w"]) > 0.5:
notifications.Feed().push_notification("warning",
"Gewichtsabfall!",
"Das Gewicht ist bei der aktuellen Messung um %skg abgefallen!"
% str(round(float(r_data["w"]) - current["weight"], 2)))
except Exception as e:
print("Error while performing data checks!\n"
"ignoring to still have data inserted\n%s" % e)

database.insert_data(r_data["t"], r_data["w"], r_data["h"])

return "data inserted"
Expand Down
29 changes: 26 additions & 3 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import config
import os
import sys
import threading

from flask import Flask

import config
from blueprints.api import api
from blueprints.rss import rss
from blueprints.views import views
from flask import Flask
from database import Database
from notifications import Feed
from utils.jsonencoder import CustomJSONEncoder
from telegram import bot as telegram_bot

print("waiting until db is ready")
os.popen(f"/bin/bash ./docker/wait-for-it.sh {config.MySql.host}:{str(config.MySql.port)}").read()
Expand Down Expand Up @@ -43,6 +50,9 @@
# Initialize all routes of the REST API
app.register_blueprint(api, url_prefix='/api')

# Initialize all routes for the RSS feeds
app.register_blueprint(rss, url_prefix='/rss')

# Append headers
@app.after_request
def add_header(r):
Expand All @@ -60,4 +70,17 @@ def add_header(r):

# Start the app
if __name__ == "__main__":
app.run(host='0.0.0.0', port=config.web_port)
if not config.telegram_bot_token == "":
telegram_bot_thread = threading.Thread(target=telegram_bot.infinity_polling)
telegram_bot_thread.daemon = True
telegram_bot_thread.start()
else:
print(">>> Not starting telegram bot because there is no token")

try:
Feed().push_notification("admin", "Beelogger startup event", "Beelogger has been started and is now running...")
app.run(host='0.0.0.0', port=config.web_port)
except (KeyboardInterrupt, SystemExit):
print(">>> Stopping BeeLogger...")
database.connection_pool.close()
sys.exit()
79 changes: 44 additions & 35 deletions backup.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,61 @@
import os
import time
from shutil import copyfile, copytree, make_archive
from shutil import copyfile, make_archive

import notifications
from config import FileBackup, MySql

if not os.path.isfile("backup.py"):
print("You need to start this script from the directory it's contained in. Please cd into that folder.")
exit()

print("checking backup directory")
def run_backup():
if not os.path.isfile("backup.py"):
print("You need to start this script from the directory it's contained in. Please cd into that folder.")
exit()

if not os.path.exists("backup/"):
print("create backup directory")
os.mkdir("backup/")
print("checking backup directory")

print("parsing backup name")
dir_name = time.asctime()
dest = "backup/" + dir_name + "/"
dest = dest.replace(" ", "-")
if not os.path.exists("backup/"):
print("create backup directory")
os.mkdir("backup/")

if os.path.exists(dest):
os.removedirs(dest)
print("parsing backup name")
dir_name = time.asctime()
dest = "backup/" + dir_name + "/"
dest = dest.replace(" ", "-")

os.mkdir(dest)
if os.path.exists(dest):
os.removedirs(dest)

print("downloading MySql database")
os.popen("mysqldump -h %s -u %s -p%s %s > %sdb_backup.sql" % (MySql.host, MySql.user, MySql.password, MySql.db, dest)).readlines()
os.mkdir(dest)

try:
print("copying files")
copyfile("logs/insert.log", dest + "insert.log")
# copytree("stats", dest + "stats/")
except FileNotFoundError:
print("no insert.log file, ignoring")
print("downloading MySql database")
os.popen("mysqldump -h %s -u %s -p%s %s > %sdb_backup.sql" % (MySql.host, MySql.user, MySql.password, MySql.db, dest)).readlines()

try:
print("copying files")
copyfile("logs/insert.log", dest + "insert.log")
# copytree("stats", dest + "stats/")
except FileNotFoundError:
print("no insert.log file, ignoring")

print("packing files")
make_archive(dest, "zip", dest)

print("packing files")
make_archive(dest, "zip", dest)
print("cleaning up")
os.popen("rm -r " + dest).readlines()

print("cleaning up")
os.popen("rm -r " + dest).readlines()
print("saving on remote")
if FileBackup.key != "":
cmd = f"scp -o StrictHostKeyChecking=no -i 'secrets/{FileBackup.key}' -P {FileBackup.port} '{dest[:-1]}.zip' '{FileBackup.user}@{FileBackup.host}:{FileBackup.directory}'"
else:
cmd = f"sshpass -p {FileBackup.password} scp -o StrictHostKeyChecking=no -P {FileBackup.port} '{dest[:-1]}.zip' '{FileBackup.user}@{FileBackup.host}:{FileBackup.directory}'"

print("saving on remote")
if FileBackup.key != "":
cmd = f"scp -o StrictHostKeyChecking=no -i 'secrets/{FileBackup.key}' -P {FileBackup.port} '{dest[:-1]}.zip' '{FileBackup.user}@{FileBackup.host}:{FileBackup.directory}'"
else:
cmd = f"sshpass -p {FileBackup.password} scp -o StrictHostKeyChecking=no -P {FileBackup.port} '{dest[:-1]}.zip' '{FileBackup.user}@{FileBackup.host}:{FileBackup.directory}'"
# cmd = "sshpass -p '%s' scp -P %s '%s.zip' '%s@%s:%s'" % (FileBackup.password, FileBackup.port, dest[:-1], FileBackup.user, FileBackup.host, FileBackup.directory)

# cmd = "sshpass -p '%s' scp -P %s '%s.zip' '%s@%s:%s'" % (FileBackup.password, FileBackup.port, dest[:-1], FileBackup.user, FileBackup.host, FileBackup.directory)
print(cmd)
print(os.popen(cmd).read())

print(cmd)
print(os.popen(cmd).read())

try:
run_backup()
except Exception as e:
notifications.Feed().push_notification("admin", "Backup Fehler", "Beim Backupvorgang ist es zu einem Fehler gekommen!\n" + e)
47 changes: 47 additions & 0 deletions blueprints/rss.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from flask import Blueprint, Response, request, jsonify
from flask.templating import render_template
import notifications

Notifications = notifications.Feed()

rss = Blueprint("rss", __name__)

@rss.route("/feeds/", methods=["GET"])
def show_feeds():
return render_template('feeds.html')

@rss.route("/<feed>/", methods=["GET"])
def show_feed(feed):
# Get the HTTP request's GET params
args = dict(request.args)

# Return pretty, HTML-based version of the feed if ?pretty is passed
if "pretty" in args.keys():
feed_data = Notifications.get_feed(feed, rss_format=False)
return render_template("feed.html", feed_name=feed, records=feed_data)
# Return feed as valid JSON if ?json is passed
elif "json" in args.keys():
feed_data = jsonify(Notifications.get_feed(feed, rss_format=False))
return feed_data
# Return feed as valid XML (for instance for RSS readers)
else:
feed_data = Notifications.get_feed(feed, rss_format=True)
return Response(feed_data, mimetype="text/xml")

@rss.route("/<feed>/<feed_id>/", methods=["GET"])
def show_article(feed, feed_id):
# Get the HTTP request's GET params
args = dict(request.args)

feed_data = Notifications.get_feed(feed, rss_format=False)
article = [x for x in feed_data if str(x["id"]) == feed_id][0]

# Return just the text if ?raw is passed
if "raw" in args.keys():
return article["text"]
# Return feed as valid JSON if ?json is passed
elif "json" in args.keys():
return article
# Return pretty, HTML-based version of the feed
else:
return render_template("feed-article.html", feed_name=feed, article=article)
Loading