File network-v2.js of Package PersistenceOS
/**
* PersistenceOS Network Management Module v2
* Network interface and configuration management for PersistenceOS
* Extracted for Phase 4 modular architecture
*/
/**
* Network Configuration
*/
const NETWORK_CONFIG = {
REFRESH_INTERVAL: 10000, // 10 seconds
API_ENDPOINTS: {
INTERFACES: '/api/network/interfaces',
CONNECTIONS: '/api/network/connections',
ROUTES: '/api/network/routes',
DNS: '/api/network/dns',
FIREWALL: '/api/network/firewall/status'
},
DEBUG: true
};
/**
* Network Management System
* Handles all network operations and state management
*/
class PersistenceNetwork {
constructor() {
this.interfaces = [];
this.connections = [];
this.routes = [];
this.dnsServers = [];
this.firewallStatus = 'unknown';
this.isRefreshing = false;
this.refreshInterval = null;
this.init();
}
init() {
if (NETWORK_CONFIG.DEBUG) {
console.log('đ PersistenceOS Network Management Module v2 initialized');
}
// Start auto-refresh
this.startAutoRefresh();
}
/**
* Get all network interfaces
*/
getInterfaces() {
return [...this.interfaces];
}
/**
* Get interface by ID
*/
getInterface(id) {
return this.interfaces.find(iface => iface.id === id);
}
/**
* Get all network connections
*/
getConnections() {
return [...this.connections];
}
/**
* Get all routes
*/
getRoutes() {
return [...this.routes];
}
/**
* Get DNS servers
*/
getDNSServers() {
return [...this.dnsServers];
}
/**
* Get firewall status
*/
getFirewallStatus() {
return this.firewallStatus;
}
/**
* Get network statistics for dashboard
*/
getNetworkStats() {
const activeInterfaces = this.interfaces.filter(iface =>
iface.status === 'up' && iface.type !== 'loopback'
);
return {
interfaces: activeInterfaces.map(iface => ({
name: iface.name,
rx: iface.rx,
tx: iface.tx
}))
};
}
/**
* Configure network interface
*/
async configureInterface(id, config) {
if (NETWORK_CONFIG.DEBUG) {
console.log(`âī¸ Configuring interface ${id}:`, config);
}
const iface = this.getInterface(id);
if (!iface) {
throw new Error(`Interface ${id} not found`);
}
// Simulate API call
await this.simulateAPICall();
// Update interface configuration
Object.assign(iface, config);
this.notifyNetworkUpdate();
if (NETWORK_CONFIG.DEBUG) {
console.log(`â
Interface ${id} configured successfully`);
}
}
/**
* Enable/disable interface
*/
async toggleInterface(id, enable) {
if (NETWORK_CONFIG.DEBUG) {
console.log(`${enable ? 'đĸ' : 'đ´'} ${enable ? 'Enabling' : 'Disabling'} interface: ${id}`);
}
const iface = this.getInterface(id);
if (!iface) {
throw new Error(`Interface ${id} not found`);
}
// Simulate API call
await this.simulateAPICall();
iface.status = enable ? 'up' : 'down';
if (!enable) {
iface.rx = '0.0 MB/s';
iface.tx = '0.0 MB/s';
}
this.notifyNetworkUpdate();
if (NETWORK_CONFIG.DEBUG) {
console.log(`â
Interface ${id} ${enable ? 'enabled' : 'disabled'} successfully`);
}
}
/**
* Update DNS servers
*/
async updateDNS(servers) {
if (NETWORK_CONFIG.DEBUG) {
console.log('đ§ Updating DNS servers:', servers);
}
if (!Array.isArray(servers) || servers.length === 0) {
throw new Error('Invalid DNS servers: must be a non-empty array');
}
// Simulate API call
await this.simulateAPICall();
this.dnsServers = [...servers];
this.notifyNetworkUpdate();
if (NETWORK_CONFIG.DEBUG) {
console.log('â
DNS servers updated successfully');
}
}
/**
* Toggle firewall
*/
async toggleFirewall(enable) {
if (NETWORK_CONFIG.DEBUG) {
console.log(`đĄī¸ ${enable ? 'Enabling' : 'Disabling'} firewall`);
}
// Simulate API call
await this.simulateAPICall();
this.firewallStatus = enable ? 'active' : 'inactive';
this.notifyNetworkUpdate();
if (NETWORK_CONFIG.DEBUG) {
console.log(`â
Firewall ${enable ? 'enabled' : 'disabled'} successfully`);
}
}
/**
* Refresh network information
*/
async refreshNetwork() {
if (this.isRefreshing) return;
this.isRefreshing = true;
if (NETWORK_CONFIG.DEBUG) {
console.log('đ Refreshing network information...');
}
try {
// Simulate API call with random updates
await this.simulateNetworkRefresh();
if (NETWORK_CONFIG.DEBUG) {
console.log('â
Network information refreshed successfully');
}
this.notifyNetworkUpdate();
} catch (error) {
if (NETWORK_CONFIG.DEBUG) {
console.error('â Network refresh failed:', error);
}
throw error;
} finally {
this.isRefreshing = false;
}
}
/**
* Simulate API call delay
*/
async simulateAPICall() {
return new Promise((resolve) => {
setTimeout(resolve, 800 + Math.random() * 1000);
});
}
/**
* Simulate network refresh with random updates
*/
async simulateNetworkRefresh() {
return new Promise((resolve) => {
setTimeout(() => {
// Update interface traffic with random values
this.interfaces.forEach(iface => {
if (iface.status === 'up' && iface.type !== 'loopback') {
iface.rx = (Math.random() * 5).toFixed(1) + ' MB/s';
iface.tx = (Math.random() * 2).toFixed(1) + ' MB/s';
// Update total bytes
const rxGB = (Math.random() * 10).toFixed(1);
const txGB = (Math.random() * 5).toFixed(1);
iface.rx_bytes = rxGB + ' GB';
iface.tx_bytes = txGB + ' GB';
}
});
resolve();
}, 800);
});
}
/**
* Start auto-refresh timer
*/
startAutoRefresh() {
if (this.refreshInterval) {
clearInterval(this.refreshInterval);
}
this.refreshInterval = setInterval(() => {
this.refreshNetwork().catch(error => {
if (NETWORK_CONFIG.DEBUG) {
console.warn('â ī¸ Network auto-refresh failed:', error);
}
});
}, NETWORK_CONFIG.REFRESH_INTERVAL);
if (NETWORK_CONFIG.DEBUG) {
console.log('â° Network auto-refresh started (10s interval)');
}
}
/**
* Stop auto-refresh timer
*/
stopAutoRefresh() {
if (this.refreshInterval) {
clearInterval(this.refreshInterval);
this.refreshInterval = null;
if (NETWORK_CONFIG.DEBUG) {
console.log('âšī¸ Network auto-refresh stopped');
}
}
}
/**
* Notify network update listeners
*/
notifyNetworkUpdate() {
// Dispatch custom event for Vue reactivity
window.dispatchEvent(new CustomEvent('networkDataUpdate', {
detail: {
interfaces: this.getInterfaces(),
connections: this.getConnections(),
routes: this.getRoutes(),
dns: this.getDNSServers(),
firewall: this.getFirewallStatus(),
stats: this.getNetworkStats()
}
}));
}
/**
* Cleanup resources
*/
destroy() {
this.stopAutoRefresh();
if (NETWORK_CONFIG.DEBUG) {
console.log('đī¸ Network Management module destroyed');
}
}
}
// Create global network management instance
window.PersistenceNetwork = new PersistenceNetwork();
// Backward compatibility
window.Network = window.PersistenceNetwork;
// Export for module systems
if (typeof module !== 'undefined' && module.exports) {
module.exports = { PersistenceNetwork, NETWORK_CONFIG };
}
console.log('â
PersistenceOS Network Management Module v2 loaded successfully');