Files

72 lines
2.0 KiB
Python

import logging
logging.basicConfig(level=logging.INFO)
from flask import Flask, jsonify, render_template
from datetime import datetime
import os, sys
from src.analyzer import (
calculate_totals,
get_last_n_days,
get_stats,
)
from src.cache import Cache
from src.web_calendar import Calendar
from src.fetch_job import initial_fetch, background_fetch_job, BGFetchJob
from src import config
# objecgts
app = Flask(__name__)
sessions_cache = Cache()
calendar = Calendar()
daemon = BGFetchJob()
# web ui
@app.route("/")
def index():
sessions = sessions_cache.get()
labels = [s["subject"] for s in sessions]
values = [s["minutes"] for s in sessions]
return render_template("index.html", labels=labels, values=values, sessions=sessions)
# internal api
@app.route("/api/dashboard")
def api_dashboard():
sessions = sessions_cache.get()
totals = calculate_totals(sessions)
return jsonify({
"sessions": sessions,
"subjectTotals": totals,
"dailyMinutes": get_last_n_days(50, sessions),
"stats": get_stats(sessions, totals),
})
# external api
@app.route("/api/sessions")
def api_sessions():
return jsonify(sessions_cache.get())
@app.route("/api/health")
def api_health():
is_alive = daemon.is_alive()
last_fetch = calendar.get_last_fetch_date()
if last_fetch:
min_since_last_fetch = round((datetime.now(tz=config.TIME_ZONE) - last_fetch).total_seconds() / 60)
is_up_to_date = min_since_last_fetch < 4 * config.REFETCH_MINUTES # four fetches failed -> bad health
else:
is_up_to_date = False
healthy = is_alive and is_up_to_date
return jsonify({
"status": "ok" if healthy else "degraded",
"daemon_alive": is_alive,
"last_fetch_success": str(last_fetch) if last_fetch else None
}), 200 if healthy else 503
# data
initial_fetch(calendar, sessions_cache)
daemon.run(calendar, sessions_cache)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=False)