main_routes.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import os
  2. import time
  3. from typing import Any
  4. from flask import Blueprint, flash, jsonify, redirect, render_template, request
  5. from flask_babel import gettext as _
  6. from loguru import logger
  7. from config import Config
  8. from parsers.connections import group_by_user, parse_raw_data
  9. from parsers.squid_info import fetch_squid_info_stats
  10. from routes.admin.helpers import json_error, json_success, sanitize_error_page_message
  11. from services.notifications.notifications import get_all_notifications
  12. from services.squid.fetch_data import fetch_all_squid_data
  13. from services.system.system_info import get_system_type
  14. from utils.updateSquid import check_squid_update, update_squid
  15. from utils.updateSquidStats import (
  16. check_web_update,
  17. is_deb_installation,
  18. updateSquidStats,
  19. )
  20. main_bp = Blueprint("main", __name__)
  21. # Caché simple en memoria para el estado de actualizaciones (5 minutos)
  22. _update_status_cache = {"data": None, "timestamp": 0}
  23. _UPDATE_STATUS_TTL = 300
  24. def filter_valid_users(grouped_connections):
  25. """
  26. Filter valid users by removing anonymous and empty users
  27. This function centralizes the filtering logic that was previously in the template
  28. """
  29. valid_users = {}
  30. for user, user_data in grouped_connections.items():
  31. if user and user != "-" and user != "Anónimo":
  32. valid_users[user] = user_data
  33. return valid_users
  34. @main_bp.app_context_processor
  35. def inject_app_version():
  36. """Inject the application version into all templates"""
  37. version = getattr(Config, "VERSION", None) or os.getenv("VERSION", "-")
  38. return {"app_version": version, "is_deb_install": is_deb_installation()}
  39. def _build_error_page(message: str, status: int = 500):
  40. """
  41. Build a standardized error page
  42. """
  43. safe_message = sanitize_error_page_message(message)
  44. return (
  45. render_template(
  46. "error.html",
  47. message=safe_message,
  48. ),
  49. status,
  50. )
  51. @main_bp.route("/api/update-status")
  52. def update_status():
  53. """Devuelve el estado de actualizaciones disponibles para Squid y la web.
  54. Utiliza un caché en memoria de 5 minutos para no saturar las APIs de GitHub.
  55. """
  56. global _update_status_cache
  57. now = time.time()
  58. cached = _update_status_cache
  59. if cached["data"] and (now - cached["timestamp"] < _UPDATE_STATUS_TTL):
  60. return jsonify(cached["data"])
  61. try:
  62. squid_status = check_squid_update()
  63. except Exception:
  64. logger.exception("Error checking Squid update status")
  65. squid_status = {
  66. "available": False,
  67. "current": None,
  68. "latest": None,
  69. "error": "Error interno al verificar actualización de Squid",
  70. }
  71. try:
  72. current_version = getattr(Config, "VERSION", None) or os.getenv("VERSION", "0")
  73. web_status = check_web_update(current_version)
  74. except Exception:
  75. logger.exception("Error checking SquidStats update status")
  76. web_status = {
  77. "available": False,
  78. "current": getattr(Config, "VERSION", None) or os.getenv("VERSION", "0"),
  79. "latest": None,
  80. "error": "Error interno al verificar actualización de SquidStats",
  81. }
  82. data = {
  83. "squid": squid_status,
  84. "web": web_status,
  85. }
  86. _update_status_cache = {"data": data, "timestamp": now}
  87. return jsonify(data)
  88. def _get_dashboard_context() -> tuple[dict[str, Any] | None, tuple[Any, int] | None]:
  89. """
  90. Get and process the context for the dashboard
  91. Returns: (context_dict, error_response) - only one will be not None
  92. """
  93. t0 = time.time()
  94. try:
  95. proxy_results = fetch_all_squid_data()
  96. # Collect per-proxy status for the UI
  97. proxy_statuses: list[dict] = []
  98. all_connections: list = []
  99. for proxy in proxy_results:
  100. raw_data = proxy["data"]
  101. label = proxy["label"]
  102. ok = proxy["ok"]
  103. proxy_statuses.append({"label": label, "ok": ok})
  104. if not ok:
  105. logger.warning(f"Could not fetch data from proxy {label}: {raw_data}")
  106. continue
  107. try:
  108. conns = parse_raw_data(raw_data, source_host=label)
  109. all_connections.extend(conns)
  110. except Exception:
  111. logger.exception(f"Error parsing connections from proxy {label}")
  112. # if not all_connections and all(not p["ok"] for p in proxy_results):
  113. # logger.error("All Squid proxies returned errors")
  114. # return None, _build_error_page("No data from any Squid proxy", 502)
  115. connections = all_connections
  116. try:
  117. grouped_connections = group_by_user(connections)
  118. except Exception:
  119. logger.exception("Error grouping connections by user")
  120. grouped_connections = {}
  121. # CENTRALIZED FILTERING: Generate valid users here instead of in the template
  122. valid_users = filter_valid_users(grouped_connections)
  123. try:
  124. squid_info_stats = fetch_squid_info_stats()
  125. except Exception:
  126. logger.exception("Error getting detailed Squid statistics")
  127. squid_info_stats = {}
  128. squid_version = (
  129. connections[0].get("squid_version", "No disponible")
  130. if connections
  131. else "No disponible"
  132. )
  133. multi_proxy = len(proxy_results) > 1
  134. context: dict[str, Any] = {
  135. "grouped_connections": grouped_connections,
  136. "valid_users": valid_users,
  137. "squid_version": squid_version,
  138. "squid_info_stats": squid_info_stats,
  139. "page_icon": "favicon.ico",
  140. "page_title": _("Inicio Dashboard"),
  141. "build_time_ms": int((time.time() - t0) * 1000),
  142. "connection_count": len(connections),
  143. "system_type": get_system_type(),
  144. "proxy_statuses": proxy_statuses,
  145. "multi_proxy": multi_proxy,
  146. }
  147. return context, None
  148. except Exception: # Fallback catch-all
  149. logger.exception("Unexpected failure building dashboard context")
  150. return None, _build_error_page("Unexpected internal failure", 500)
  151. @main_bp.route("/")
  152. def index():
  153. # CHANGE: Detect if this is a request for partial content
  154. is_partial_request = request.args.get("partial") == "true"
  155. context, error_response = _get_dashboard_context()
  156. if error_response:
  157. return error_response
  158. # CHANGE: If it's a partial request, return only the connections template
  159. if is_partial_request:
  160. return render_template(
  161. "partials/conexiones.html",
  162. grouped_connections=context["grouped_connections"],
  163. valid_users=context["valid_users"],
  164. squid_version=context["squid_version"],
  165. squid_info_stats=context["squid_info_stats"],
  166. build_time_ms=context["build_time_ms"],
  167. connection_count=context["connection_count"],
  168. system_type=context["system_type"],
  169. proxy_statuses=context["proxy_statuses"],
  170. multi_proxy=context["multi_proxy"],
  171. )
  172. # Normal request: return the complete page
  173. return render_template("index.html", **context)
  174. @main_bp.route("/install", methods=["POST"])
  175. def install_package():
  176. """Route to install/update Squid packages"""
  177. try:
  178. ok, error_message = update_squid()
  179. if ok:
  180. logger.info("SquidStats update (install) completed successfully")
  181. message = _("Squid actualizado correctamente.")
  182. if request.accept_mimetypes.best == "application/json":
  183. return json_success(message)
  184. flash(message, "success")
  185. return redirect("/")
  186. logger.warning("update_squid() returned False in /install")
  187. message = error_message or _(
  188. "Error al actualizar Squid. Revise los logs del servidor."
  189. )
  190. if request.accept_mimetypes.best == "application/json":
  191. return json_error(message, 503)
  192. flash(message, "error")
  193. except Exception:
  194. logger.exception("Error executing update in /install")
  195. message = _(
  196. "Error inesperado al actualizar Squid. Revise los logs del servidor."
  197. )
  198. if request.accept_mimetypes.best == "application/json":
  199. return json_error(message, 500)
  200. flash(message, "error")
  201. return redirect("/")
  202. @main_bp.route("/update", methods=["POST"])
  203. def update_web():
  204. """Route to update the web application"""
  205. logger.info("Received web update request")
  206. ok = False
  207. try:
  208. ok = updateSquidStats()
  209. if ok:
  210. logger.info("SquidStats web update completed")
  211. flash(
  212. _(
  213. "SquidStats actualizado correctamente. El servicio se ha reiniciado."
  214. ),
  215. "success",
  216. )
  217. else:
  218. logger.warning("updateSquidStats() returned False in /update")
  219. flash(
  220. _("Error al actualizar SquidStats. Revise los logs del servidor."),
  221. "error",
  222. )
  223. except Exception:
  224. logger.exception("Error executing update in /update")
  225. flash(
  226. _(
  227. "Error inesperado al actualizar SquidStats. Revise los logs del servidor."
  228. ),
  229. "error",
  230. )
  231. return redirect("/")
  232. @main_bp.route("/all-notifications")
  233. def all_notifications():
  234. """Page to view all notifications with pagination"""
  235. try:
  236. # Get pagination parameters
  237. page = request.args.get("page", 1, type=int)
  238. per_page = request.args.get("per_page", 20, type=int)
  239. # Validate parameters
  240. if page < 1:
  241. page = 1
  242. if per_page not in [10, 20, 50, 100]:
  243. per_page = 20
  244. # Get notifications with pagination
  245. notifications_data = get_all_notifications(
  246. limit=None, page=page, per_page=per_page
  247. )
  248. return render_template(
  249. "all_notifications.html",
  250. page_title=_("Todas las Notificaciones"),
  251. page_icon="favicon.ico",
  252. subtitle=_("Historial completo de notificaciones del sistema"),
  253. icon="fas fa-bell",
  254. notifications=notifications_data["notifications"],
  255. unread_count=notifications_data["unread_count"],
  256. pagination=notifications_data.get(
  257. "pagination",
  258. {
  259. "current_page": page,
  260. "per_page": per_page,
  261. "total_pages": 1,
  262. "total_notifications": len(notifications_data["notifications"]),
  263. "has_prev": False,
  264. "has_next": False,
  265. },
  266. ),
  267. )
  268. except Exception as e:
  269. logger.error(f"Error loading notifications page: {e}")
  270. return render_template(
  271. "all_notifications.html",
  272. page_title=_("Todas las Notificaciones"),
  273. page_icon="favicon.ico",
  274. subtitle=_("Error al cargar las notificaciones"),
  275. icon="fa-bell",
  276. notifications=[],
  277. unread_count=0,
  278. pagination=None,
  279. )