summaryrefslogtreecommitdiffstats
path: root/static/js/app.js
blob: dd2aa75327da0076d57ec45a1471a1fb69b1ae03 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
// Application state and configuration
const App = {
    apiBase: "/api",
    elements: {
        connectionList: document.getElementById('connections__container'),
        statusArea: document.getElementById('status__container'),
        messageArea: document.getElementById('notifications__container')
    }
};

// Utility functions
const Utils = {
    // Show message to user
    renderError(element, message) {
        Utils.renderMessage(element, message, "error");
    },
    renderWarning(element, message) {
        Utils.renderMessage(element, message, "warning");
    },
    renderSuccess(element, message) {
        Utils.renderMessage(element, message, "success");
    },
    renderMessage(element, message, type = '') {
        element.innerHTML = `
            <div class="message ${type}">${message}</div>
        `;
    },
    // Make API calls with proper error handling
    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${App.apiBase}${endpoint}`, {
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || `HTTP ${response.status}`);
            }

            if (!data.success) {
                throw new Error(data.error || 'API request failed');
            }

            return data.data;
        } catch (error) {
            console.error('API call failed:', error);
            throw error;
        }
    }
};

// Connection management
const ConnectionManager = {
    // Load and display all connections
    async loadConnections() {
        try {
            const connections = await Utils.apiCall('/connections');
            this.renderConnections(connections);
        } catch (error) {
            Utils.renderError(App.elements.connectionList,
                `Failed to load connections: ${error.message}`);
        }
    },

    // Render connections to the DOM
    renderConnections(connections) {
        if (!connections || connections.length === 0) {
            Utils.renderWarning(App.elements.connectionList,
                "No WireGuard connections found in /etc/wireguard/");
            return;
        }

        const html = connections.map(conn => `
            <div class="connection ${conn.active ? 'active' : ''}"
                    data-connection="${conn.name}"
                    onclick="ConnectionManager.toggleConnection('${conn.name}')">
                <div class="connection__name ${conn.active ? 'active' : ''}">${conn.name}</div>
            </div>
        `).join('');
        App.elements.connectionList.innerHTML = html;
    },

    // Toggle connection state
    async toggleConnection(name) {
        const connection = document.querySelector(`[data-connection="${name}"]`);

        try {
            connection.disabled = true;
            connection.textContent = 'Processing...';
            connection.className = "connection loading"

            await Utils.apiCall('/connections/toggle', {
                method: 'POST',
                body: JSON.stringify({ name })
            });
            await this.loadConnections(); // Refresh the list
            await StatusManager.loadStatus(); // Refresh the status
            Utils.renderSuccess(App.elements.messageArea, `No Errors Found.`);
        } catch (error) {
            Utils.renderError(App.elements.messageArea, `Failed to toggle ${name}: ${error.message}`);
            connection.disabled = false;
            connection.textContent = name;
            connection.className = "connection"
        }
    }
};

// Status management
const StatusManager = {
    intervalId: null,

    // Load and display WireGuard status
    async loadStatus() {
        try {
            const statusData = await Utils.apiCall('/status');
            const statusText = statusData.status;
            if (statusText) {
                Utils.renderSuccess(App.elements.statusArea, statusText);
            } else {
                Utils.renderWarning(App.elements.statusArea, "No active connections.");
            }
        } catch (error) {
            Utils.renderError(App.elements.statusArea, error.message);
        }
    },

    startAutoRefresh() {
        // Clear any existing interval first
        this.stopAutoRefresh();
        // Start new interval
        this.intervalId = setInterval(() => this.loadStatus(), 5000);
    },

    stopAutoRefresh() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
    }
};

// Initialize the application
document.addEventListener('DOMContentLoaded', () => {
    StatusManager.loadStatus();
    ConnectionManager.loadConnections();
    StatusManager.startAutoRefresh();
});

// Pause when tab is hidden, resume when visible
document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        StatusManager.stopAutoRefresh();
    } else {
        StatusManager.loadStatus(); // Immediate refresh when back
        StatusManager.startAutoRefresh();
    }
});