Explorar o código

feat: implement commit notifications system with API endpoint and dynamic updates in navbar

Manuel hai 1 ano
pai
achega
bec2ff5e3b
Modificáronse 4 ficheiros con 126 adicións e 81 borrados
  1. 12 0
      app.py
  2. 7 0
      routes/api_routes.py
  3. 64 0
      services/notifications.py
  4. 43 81
      templates/components/navbar.html

+ 12 - 0
app.py

@@ -12,6 +12,10 @@ from routes import register_routes
 from routes.main_routes import initialize_proxy_detection
 from routes.stats_routes import realtime_data_thread
 from services.metrics_service import MetricsService
+from services.notifications import (
+    has_remote_commits_with_messages,
+    set_commit_notifications,
+)
 from utils.filters import register_filters
 
 # Load environment variables
@@ -57,6 +61,14 @@ def create_app():
 
 
 def setup_scheduler_tasks(scheduler):
+    @scheduler.task(
+        "interval", id="check_notifications", minutes=30, misfire_grace_time=1800
+    )
+    def check_notifications_task():
+        repo_path = os.path.dirname(os.path.abspath(__file__))
+        has_updates, messages = has_remote_commits_with_messages(repo_path)
+        set_commit_notifications(has_updates, messages)
+
     @scheduler.task("interval", id="do_job_1", seconds=30, misfire_grace_time=900)
     def init_scheduler():
         log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")

+ 7 - 0
routes/api_routes.py

@@ -15,6 +15,7 @@ from services.auditoria_service import (
     get_user_activity_summary,
 )
 from services.metrics_service import MetricsService
+from services.notifications import get_commit_notifications
 
 api_bp = Blueprint("api", __name__)
 
@@ -123,3 +124,9 @@ def api_run_audit():
         return jsonify({"error": "Internal server error"}), 500
     finally:
         db.close()
+
+
+# API para notificaciones del sistema
+@api_bp.route("/notifications", methods=["GET"])
+def api_get_notifications():
+    return jsonify(get_commit_notifications())

+ 64 - 0
services/notifications.py

@@ -0,0 +1,64 @@
+import os
+import subprocess
+
+notifications_data = {"commits": [], "has_updates": False}
+
+
+def set_commit_notifications(has_updates, messages):
+    notifications_data["has_updates"] = has_updates
+    notifications_data["commits"] = messages
+
+
+def get_commit_notifications():
+    return notifications_data
+
+
+def has_remote_commits_with_messages(
+    repo_path: str, branch: str = "main"
+) -> tuple[bool, list[str]]:
+    if not os.path.isdir(os.path.join(repo_path, ".git")):
+        raise ValueError(f"No es un repositorio Git válido: {repo_path}")
+    try:
+        subprocess.run(
+            ["git", "fetch"],
+            cwd=repo_path,
+            check=True,
+            stdout=subprocess.DEVNULL,
+            stderr=subprocess.DEVNULL,
+        )
+        result = subprocess.run(
+            [
+                "git",
+                "rev-list",
+                "--left-right",
+                "--count",
+                f"origin/{branch}...{branch}",
+            ],
+            cwd=repo_path,
+            capture_output=True,
+            text=True,
+            check=True,
+        )
+        ahead_behind = result.stdout.strip().split()
+        remote_ahead = int(ahead_behind[0])
+
+        if remote_ahead > 0:
+            log_result = subprocess.run(
+                ["git", "log", f"{branch}..origin/{branch}", "--pretty=format:%s"],
+                cwd=repo_path,
+                capture_output=True,
+                text=True,
+                check=True,
+            )
+            commit_messages = (
+                log_result.stdout.strip().split("\n")
+                if log_result.stdout.strip()
+                else []
+            )
+            return True, commit_messages
+
+        return False, []
+
+    except subprocess.CalledProcessError as e:
+        print(f"Error al ejecutar comandos git: {e.stderr}")
+        return False, []

+ 43 - 81
templates/components/navbar.html

@@ -68,11 +68,11 @@
     </div>
 
     <!-- Notificaciones y Action Buttons -->
-    <!-- <div class="flex items-center gap-3">
+     <div class="flex items-center gap-3">
       <div class="relative" x-data="{ open: false }">
         <button
           @click="open = !open"
-          class="relative inline-flex items-center justify-center w-12 h-12 rounded-xl bg-gradient-to-br from-slate-50 to-slate-100 border border-slate-200 shadow-sm hover:shadow-md hover:from-blue-50 hover:to-indigo-50 hover:border-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 transition-all duration-200 group"
+          class="relative inline-flex items-center justify-center w-8 h-8 rounded-lg bg-gradient-to-br from-slate-50 to-slate-100 border border-slate-200 shadow-sm hover:shadow-md hover:from-blue-50 hover:to-indigo-50 hover:border-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 transition-all duration-200 group"
           aria-label="Notificaciones"
         >
           <i class="fas fa-bell text-slate-600 group-hover:text-blue-600 transition-colors duration-200"></i>
@@ -162,7 +162,7 @@
             >
           </div>
         </div>
-      </div> -->
+      </div> 
 
     <!-- Action Buttons -->
     <div
@@ -337,92 +337,54 @@
 ></script>
 
 <script>
+
   // Enhanced Navbar Functionality
   document.addEventListener("DOMContentLoaded", function () {
-    // Highlight active navigation link
-    const currentPath = window.location.pathname;
-    const navLinks = document.querySelectorAll(".nav-link");
-
-    navLinks.forEach((link) => {
-      const href = link.getAttribute("href");
-      if (href === currentPath || (currentPath === "/" && href === "/")) {
-        link.classList.add("active");
-      }
-    });
+    // ...existing code...
 
-    // Enhanced tooltip positioning
-    const tooltipElements = document.querySelectorAll("[data-tooltip]");
-    tooltipElements.forEach((element) => {
-      element.addEventListener("mouseenter", function (e) {
-        const rect = e.target.getBoundingClientRect();
-        const tooltipWidth = e.target.getAttribute("data-tooltip").length * 8; // Approximate width
-
-        // Adjust tooltip position if it would go off-screen
-        if (rect.left + tooltipWidth > window.innerWidth) {
-          e.target.style.setProperty(
-            "--tooltip-transform",
-            "translateX(-100%)"
-          );
-        }
-      });
-    });
-
-    // Smooth scroll to top when clicking brand
-    const brand = document.querySelector(".navbar-brand");
-    if (brand) {
-      brand.addEventListener("click", function (e) {
-        e.preventDefault();
-        window.scrollTo({
-          top: 0,
-          behavior: "smooth",
+    // Notificaciones dinámicas desde la API
+    function renderNotifications(data) {
+      const ul = document.querySelector(".max-h-72.overflow-y-auto");
+      if (!ul) return;
+      ul.innerHTML = "";
+      if (data.has_updates && data.commits.length > 0) {
+        data.commits.forEach((msg, idx) => {
+          ul.innerHTML += `
+            <li class="px-4 py-3 flex items-start hover:bg-gray-50 cursor-pointer">
+              <span class="inline-flex items-center justify-center h-8 w-8 rounded-full bg-yellow-100 text-yellow-600 mr-3">
+                <i class="fas fa-bell"></i>
+              </span>
+              <div class="flex-1">
+                <p class="text-sm text-gray-700">${msg}</p>
+                <span class="text-xs text-gray-400">Actualización de código</span>
+              </div>
+            </li>
+          `;
         });
-      });
+      } else {
+        ul.innerHTML = `<li class='px-4 py-3 text-gray-500 text-center'>No hay notificaciones nuevas</li>`;
+      }
     }
 
-    // Add loading state to action buttons
-    const actionButtons = document.querySelectorAll(".action-btn");
-    actionButtons.forEach((button) => {
-      button.addEventListener("click", function () {
-        const originalContent = this.innerHTML;
-        this.innerHTML =
-          '<i class="fas fa-spinner fa-spin"></i> <span>Procesando...</span>';
-        this.disabled = true;
+    function fetchNotifications() {
+      fetch("/api/notifications")
+        .then((res) => res.json())
+        .then((data) => {
+          renderNotifications(data);
+          // Actualizar contador
+          const badge = document.querySelector(".fa-bell").parentElement.querySelector(".absolute");
+          if (badge) {
+            badge.textContent = data.has_updates ? data.commits.length : "0";
+          }
+        })
+        .catch(() => {});
+    }
 
-        // Reset after 3 seconds (in case something goes wrong)
-        setTimeout(() => {
-          this.innerHTML = originalContent;
-          this.disabled = false;
-        }, 3000);
-      });
-    });
+    // Llamar al cargar y cada 5 minutos
+    fetchNotifications();
+    setInterval(fetchNotifications, 5 * 60 * 1000);
 
-    // Add keyboard navigation
-    document.addEventListener("keydown", function (e) {
-      if (e.altKey) {
-        switch (e.key) {
-          case "1":
-            e.preventDefault();
-            window.location.href = "/";
-            break;
-          case "2":
-            e.preventDefault();
-            window.location.href = "/stats";
-            break;
-          case "3":
-            e.preventDefault();
-            window.location.href = "/logs";
-            break;
-          case "4":
-            e.preventDefault();
-            window.location.href = "/reports";
-            break;
-          case "5":
-            e.preventDefault();
-            window.location.href = "/blacklist";
-            break;
-        }
-      }
-    });
+    // ...existing code...
   });
 
   // Close modals when clicking outside