Просмотр исходного кода

Added routes and updated templates to only refresh when goals, lists or votes change.

deadtom 1 месяц назад
Родитель
Сommit
abff30d6df

+ 40 - 16
ownchatbot/templates/goals.html

@@ -3,62 +3,86 @@
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <meta http-equiv="refresh" content="5">
-    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
     <title>Active goals</title>
+    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
     <style>
         body {
             background-color: transparent;
             color: white;
             width: 600px;
             text-align: left;
-	    font-weight: bold;
+            font-weight: bold;
         }
+        body { position: absolute; bottom: 0; left: 0; }
     </style>
+    <script>
+      function checkForGoalUpdates() {
+          fetch('/updateGoals')
+              .then(response => response.json())
+              .then(data => {
+                  const newGoals = data.goals;
+                  const currentGoals = Array.from(document.querySelectorAll('tbody tr')).map(tr => {
+                      const goalData = {
+                          name: tr.children[0].textContent.trim(),
+                          current: parseInt(tr.children[2].textContent.split('/')[0].trim()),
+                          target: parseInt(tr.children[2].textContent.split('/')[1].trim())
+                      };
+                      return goalData;
+                  });
+
+                  if (JSON.stringify(newGoals) !== JSON.stringify(currentGoals)) {
+                      window.location.reload();  // Refresh if goals have changed
+                  }
+              })
+              .catch(error => console.error('Error fetching updated goals:', error));
+      }
+
+      setInterval(checkForGoalUpdates, 15 * 1000); // Check every 15 seconds
+    </script>
 </head>
-<body style="position: absolute; 
-                            bottom: 0; left: 0;">
+<body>
     {% if goals %}
         <table>
             <thead>
                 <tr>
-                    <th></th>
+                    <th>Description</th>
                     <th style="width: 50%"></th>
-                    <th></th>
+                    <th>Progress</th>
                 </tr>
             </thead>
             <tbody>
             {% for goal in goals %}
                 <tr>
-                    <td style="text-align: left;"> {{ goal[3] }} </td>
+                    <td style="text-align: left;">{{ goal[3] }}</td>
                     {% set progress = goal[1] / goal[2] * 100 %}
                     <td>
                         <div class="bar-light-grey bar-tiny bar-round" style="position: relative;">
-                            <div class="bar-round bar-blue" style="text-align: center; width:{{ progress }}%;">{{ '%0.0f'| format(progress| float) }}%
+                            <div class="bar-round bar-blue" style="text-align: center; width:{{ progress }}%;">{{ '%0.0f' | format(progress | float) }}%
                             </div>
                             {% set milestones = rewards[goal[0]]["milestones"] %}
                             {% for milestone_key, milestone in milestones.items() %}
                                 {% if milestones[milestone_key][0] and milestones[milestone_key][1] %}
                                     {% if milestones[milestone_key][1] < goal[2] %}
                                         {% set milestone_progress = milestones[milestone_key][1] / goal[2] * 100 %}
-                                            <div class="milestone-marker" style="position: absolute; left: {{ milestone_progress }}%; transform: translateX(-50%);">
-                                                <img src="/static/img/milestone.png" style="width: 16px; height: 16px;" title="{{ milestones[milestone_key][1] }} points. {{ milestones[milestone_key][0] }}">
-                                            </div>
-                                        {% endif %}
+                                        <div class="milestone-marker" style="position: absolute; left: {{ milestone_progress }}%; transform: translateX(-50%);">
+                                            <img src="/static/img/milestone.png" style="width: 16px; height: 16px;" title="{{ milestones[milestone_key][1] }} points. {{ milestones[milestone_key][0] }}">
+                                        </div>
                                     {% endif %}
-                                {% endfor %}
+                                {% endif %}
+                            {% endfor %}
                         </div>
                     </td>
                     {% if goal[1] == goal[2] %}
-                    <td style="text-align: right;">{{ goal[1] }} / {{ goal[2] }}  <img src=/static/img/tada.png style="width: 24px; height: 24px;"></td>
+                    <td style="text-align: right;">{{ goal[1] }} / {{ goal[2] }} <img src="/static/img/tada.png" style="width: 24px; height: 24px;"></td>
                     {% else %}
                     <td style="text-align: right;">{{ goal[1] }} / {{ goal[2] }}</td>
                     {% endif %}
-                    
                 </tr>
             {% endfor %}
             </tbody>
         </table>
+    {% else %}
+        <p>No active goals at the moment.</p>
     {% endif %}
 </body>
 </html>

+ 18 - 6
ownchatbot/templates/list.html

@@ -3,7 +3,6 @@
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <meta http-equiv="refresh" content="10">
     <title>Today's to-do List</title>
     <style>
         body {
@@ -13,17 +12,30 @@
         }
     </style>
     <script>
-      function refreshPage() {
-          window.location.reload();
+      function checkForUpdates() {
+          fetch('/checkTodo')
+              .then(response => response.json())
+              .then(data => {
+                  const newList = data.items; // Assuming LIST is returned as JSON with { items: [...] }
+
+                  // Compare current list with new list (you can customize this comparison)
+                  const currentItems = Array.from(document.querySelectorAll('li')).map(li => li.textContent);
+
+                  if (newList.length !== currentItems.length || !currentItems.every((item, index) => item === newList[index].name)) {
+                      // Refresh the page if the list has changed
+                      window.location.reload();
+                  }
+              })
+              .catch(error => console.error('Error fetching the to-do list:', error));
       }
 
-      setTimeout(refreshPage, 30 * 1000);
+      setInterval(checkForUpdates, 15 * 1000); // Check every 15 seconds
     </script>
 </head>
 <body>
     {% if items %}
         <h4>Today's to-do List</h4>
-        <ul>
+        <ul id="todo-list">
             {% for item in items %}
                 <li style="text-decoration: {{ 'line-through' if item.crossed == 'yes' else 'none' }};">
                     {{ item.name }}
@@ -31,7 +43,7 @@
             {% endfor %}
         </ul>
     {% else %}
-    	<h4>Nothing on the to-do list yet</h4>
+        <h4>Nothing on the to-do list yet</h4>
     {% endif %}
 </body>
 </html>

+ 30 - 12
ownchatbot/templates/votes.html

@@ -3,43 +3,61 @@
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <meta http-equiv="refresh" content="5">
-    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
     <title>Active votes</title>
+    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
     <style>
         body {
             background-color: transparent;
             color: white;
             width: 400px;
-            position: absolute; 
+            position: absolute;
             bottom: 0; left: 0;
-	    font-weight: bold;
+            font-weight: bold;
         }
     </style>
+    <script>
+      function checkForVoteUpdates() {
+          fetch('/updateVotes')
+              .then(response => response.json())
+              .then(data => {
+                  const newVotes = data.votes;
+                  const currentVotes = Array.from(document.querySelectorAll('tbody tr')).map(tr => {
+                      return {
+                          text: tr.children[0].textContent,
+                          count: parseInt(tr.children[1].textContent)
+                      };
+                  });
+
+                  if (JSON.stringify(newVotes) !== JSON.stringify(currentVotes)) {
+                      window.location.reload();  // Refresh if votes have changed
+                  }
+              })
+              .catch(error => console.error('Error fetching updated votes:', error));
+      }
+
+      setInterval(checkForVoteUpdates, 15 * 1000); // Check every 15 seconds
+    </script>
 </head>
 <body>
     {% if votes %}
         <table>
             <thead>
                 <tr>
-                    <th></th>
-                    <th></th>
-                    <th></th>
+                    <th>Item</th>
+                    <th>Votes</th>
                 </tr>
             </thead>
             <tbody>
             {% for vote in votes %}
                 <tr>
                     <td>{{ vote[2] }}</td>
-                    {% if vote[1] == 1 %}
-                    <td>{{ vote[1] }} vote</td>
-                    {% else %}
-                    <td>{{ vote[1] }} votes</td>
-                    {% endif %}
+                    <td>{{ vote[1] }} vote{% if vote[1] != 1 %}s{% endif %}</td>
                 </tr>
             {% endfor %}
             </tbody>
         </table>
+    {% else %}
+        <p>No active votes at the moment.</p>
     {% endif %}
 </body>
 </html>

+ 24 - 3
ownchatbot/web_panels.py

@@ -676,7 +676,7 @@ def ocb_alert(alert_type):
                                alert_name=alert_name)
 
 
-@ocb.route('/goals', methods=['GET'])  # Route for goals overlay
+@ocb.route('/goals')  # Goals overlay
 def goals():
     db = get_db()
     return render_template('goals.html',
@@ -684,14 +684,35 @@ def goals():
                            rewards=all_active_rewards())
 
 
-@ocb.route('/votes', methods=['GET'])  # Route for votes overlay
+@ocb.route('/updateGoals', methods=['GET'])  # Polled by goals.html for updated goals
+def update_goals():
+    db = get_db()
+    goals_data = all_active_goals(db)
+    return jsonify({'goals': [{'name': goal[3], 'current': goal[1], 'target': goal[2]} for goal in goals_data]})
+
+
+@ocb.route('/votes')  # Votes overlay
 def votes():
     db = get_db()
     return render_template('votes.html',
                            votes=all_active_votes(db))
 
 
-@ocb.route('/todo')
+@ocb.route('/updateVotes', methods=['GET'])  # Polled by votes.html for updated votes
+def update_votes():
+    db = get_db()
+    votes_data = all_active_votes(db)
+    return jsonify({'votes': [{'item': vote[2], 'count': vote[1]} for vote in votes_data]})
+
+
+@ocb.route('/todo')  # Todo overlay
 def todo():
     todolist_items = current_app.config['LIST']
     return render_template('list.html', items=todolist_items)
+
+
+@ocb.route('/checkTodo')  # Polled by list.html to check for changes in the to-do list
+def check_todo():
+    todolist_items = current_app.config['LIST']
+    return jsonify({'items': [{'name': item.name, 'crossed': item.crossed} for item in todolist_items]})
+