/**
* BlackRoad OS Application Modules
* Handles data loading and UI updates for all desktop applications
*/
class BlackRoadApps {
constructor() {
this.api = window.BlackRoadAPI;
this.refreshIntervals = {};
}
/**
* Initialize all apps when user logs in
*/
initialize() {
// Listen for login event
window.addEventListener('auth:login', () => {
this.loadAllApps();
});
// Listen for window open events to load data on-demand
this.setupWindowListeners();
}
/**
* Load all apps data
*/
async loadAllApps() {
// Load critical apps immediately
await Promise.all([
this.loadWallet(),
this.loadMinerStats(),
this.loadBlockchainStats(),
]);
// Load other apps in the background
setTimeout(() => {
this.loadDevices();
this.loadEmailInbox();
this.loadSocialFeed();
this.loadVideos();
}, 1000);
}
/**
* Setup listeners for window open events
*/
setupWindowListeners() {
// Override the global openWindow function to load data when windows open
const originalOpenWindow = window.openWindow;
window.openWindow = (id) => {
originalOpenWindow(id);
this.onWindowOpened(id);
};
}
/**
* Handle window opened event
*/
onWindowOpened(windowId) {
switch (windowId) {
case 'roadcoin-miner':
this.loadMinerStatus();
this.startMinerRefresh();
break;
case 'roadchain':
this.loadBlockchainExplorer();
break;
case 'wallet':
this.loadWallet();
break;
case 'raspberry-pi':
this.loadDevices();
break;
case 'roadmail':
this.loadEmailInbox();
break;
case 'blackroad-social':
this.loadSocialFeed();
break;
case 'blackstream':
this.loadVideos();
break;
case 'ai-chat':
this.loadAIChat();
break;
}
}
/**
* Start auto-refresh for a window
*/
startRefresh(windowId, callback, interval = 5000) {
this.stopRefresh(windowId);
this.refreshIntervals[windowId] = setInterval(callback, interval);
}
/**
* Stop auto-refresh for a window
*/
stopRefresh(windowId) {
if (this.refreshIntervals[windowId]) {
clearInterval(this.refreshIntervals[windowId]);
delete this.refreshIntervals[windowId];
}
}
// ===== MINER APPLICATION =====
async loadMinerStatus() {
try {
const [status, stats, blocks] = await Promise.all([
this.api.getMinerStatus(),
this.api.getMinerStats(),
this.api.getMinedBlocks(5),
]);
this.updateMinerUI(status, stats, blocks);
} catch (error) {
console.error('Failed to load miner status:', error);
}
}
async loadMinerStats() {
try {
const stats = await this.api.getMinerStats();
this.updateMinerStatsInTaskbar(stats);
} catch (error) {
console.error('Failed to load miner stats:', error);
}
}
updateMinerUI(status, stats, blocks) {
const content = document.querySelector('#roadcoin-miner .window-content');
if (!content) return;
const statusColor = status.is_mining ? '#2ecc40' : '#ff4136';
const statusText = status.is_mining ? 'MINING' : 'STOPPED';
content.innerHTML = `
Hashrate
${status.hashrate_mhs.toFixed(2)} MH/s
Shares
${status.shares_accepted}/${status.shares_submitted}
Temperature
${status.temperature_celsius.toFixed(1)}°C
Power
${status.power_watts.toFixed(0)}W
Lifetime Statistics
Blocks Mined:
${stats.blocks_mined}
RoadCoins Earned:
${stats.roadcoins_earned.toFixed(2)} RC
Pool:
${status.pool_url}
Recent Blocks
${blocks.length > 0 ? blocks.map(block => `
Block #${block.block_index}
${block.reward.toFixed(2)} RC
${this.formatTime(block.timestamp)}
`).join('') : '
No blocks mined yet
'}
`;
}
updateMinerStatsInTaskbar(stats) {
// Update system tray icon tooltip or status
const trayIcon = document.querySelector('.system-tray span:last-child');
if (trayIcon) {
trayIcon.title = `Mining: ${stats.blocks_mined} blocks, ${stats.roadcoins_earned.toFixed(2)} RC earned`;
}
}
async toggleMiner() {
try {
const status = await this.api.getMinerStatus();
const action = status.is_mining ? 'stop' : 'start';
await this.api.controlMiner(action);
await this.loadMinerStatus();
} catch (error) {
console.error('Failed to toggle miner:', error);
alert('Failed to control miner: ' + error.message);
}
}
startMinerRefresh() {
this.startRefresh('roadcoin-miner', () => this.loadMinerStatus(), 5000);
}
// ===== BLOCKCHAIN EXPLORER =====
async loadBlockchainExplorer() {
try {
const [stats, blocks] = await Promise.all([
this.api.getBlockchainStats(),
this.api.getBlocks(10),
]);
this.updateBlockchainUI(stats, blocks);
} catch (error) {
console.error('Failed to load blockchain data:', error);
}
}
async loadBlockchainStats() {
try {
const stats = await this.api.getBlockchainStats();
this.updateBlockchainStatsInTaskbar(stats);
} catch (error) {
console.error('Failed to load blockchain stats:', error);
}
}
updateBlockchainUI(stats, blocks) {
const content = document.querySelector('#roadchain .window-content');
if (!content) return;
content.innerHTML = `
Chain Height
${stats.total_blocks}
Transactions
${stats.total_transactions}
Difficulty
${stats.difficulty}
Recent Blocks
${blocks.map(block => `
#${block.index}
${block.hash.substring(0, 16)}...
${block.transactions?.length || 0} txs
${this.formatTime(block.timestamp)}
`).join('')}
`;
}
updateBlockchainStatsInTaskbar(stats) {
// Could update a taskbar indicator
}
async mineNewBlock() {
try {
const result = await this.api.mineBlock();
alert(`Successfully mined block #${result.index}! Reward: ${result.reward} RC`);
await this.loadBlockchainExplorer();
await this.loadWallet();
} catch (error) {
console.error('Failed to mine block:', error);
alert('Failed to mine block: ' + error.message);
}
}
showBlockDetail(blockId) {
// TODO: Open block detail modal
console.log('Show block detail:', blockId);
}
// ===== WALLET =====
async loadWallet() {
try {
const [wallet, balance, transactions] = await Promise.all([
this.api.getWallet(),
this.api.getBalance(),
this.api.getTransactions(10),
]);
this.updateWalletUI(wallet, balance, transactions);
} catch (error) {
console.error('Failed to load wallet:', error);
}
}
updateWalletUI(wallet, balance, transactions) {
const content = document.querySelector('#wallet .window-content');
if (!content) return;
const usdValue = balance.balance * 15; // Mock conversion rate
content.innerHTML = `
${balance.balance.toFixed(8)} RC
≈ $${usdValue.toFixed(2)} USD
Recent Transactions
${transactions.length > 0 ? transactions.map(tx => {
const isReceived = tx.to_address === wallet.address;
const sign = isReceived ? '+' : '-';
const color = isReceived ? '#2ecc40' : '#ff4136';
return `
${sign}${tx.amount.toFixed(4)} RC
${tx.hash.substring(0, 12)}...
${this.formatTime(tx.created_at)}
`;
}).join('') : '
No transactions yet
'}
`;
}
// ===== DEVICES (RASPBERRY PI) =====
async loadDevices() {
try {
const [devices, stats] = await Promise.all([
this.api.getDevices(),
this.api.getDeviceStats(),
]);
this.updateDevicesUI(devices, stats);
} catch (error) {
console.error('Failed to load devices:', error);
// Show stub UI if no devices yet
this.updateDevicesUI([], {
total_devices: 0,
online_devices: 0,
offline_devices: 0,
total_cpu_usage: 0,
total_ram_usage: 0,
average_temperature: 0,
});
}
}
updateDevicesUI(devices, stats) {
const content = document.querySelector('#raspberry-pi .window-content');
if (!content) return;
content.innerHTML = `
${devices.length > 0 ? devices.map(device => {
const statusColor = device.is_online ? '#2ecc40' : '#aaa';
const statusText = device.is_online ? '🟢 Online' : '🔴 Offline';
return `
${device.name}
${device.device_type}
${statusText}
${device.is_online ? `
CPU: ${device.cpu_usage_percent?.toFixed(1) || 0}%
RAM: ${device.ram_usage_percent?.toFixed(1) || 0}%
Temp: ${device.temperature_celsius?.toFixed(1) || 0}°C
` : ''}
`;
}).join('') : `
No devices registered yet.
Deploy a device agent to see your Raspberry Pi, Jetson, and other IoT devices here.
`}
`;
}
// ===== EMAIL =====
async loadEmailInbox() {
try {
const emails = await this.api.getEmails('inbox', 20);
this.updateEmailUI(emails);
} catch (error) {
console.error('Failed to load emails:', error);
}
}
updateEmailUI(emails) {
const emailList = document.querySelector('#roadmail .email-list');
if (!emailList) return;
if (emails.length === 0) {
emailList.innerHTML = 'No emails yet
';
return;
}
emailList.innerHTML = emails.map(email => `
${email.sender || 'Unknown'}
${email.subject}
${this.formatTime(email.created_at)}
`).join('');
}
openEmail(emailId) {
console.log('Open email:', emailId);
// TODO: Show email detail
}
// ===== SOCIAL FEED =====
async loadSocialFeed() {
try {
const feed = await this.api.getSocialFeed(20);
this.updateSocialUI(feed);
} catch (error) {
console.error('Failed to load social feed:', error);
}
}
updateSocialUI(posts) {
const feedContainer = document.querySelector('#blackroad-social .social-feed');
if (!feedContainer) return;
if (posts.length === 0) {
feedContainer.innerHTML = 'No posts yet. Be the first to post!
';
return;
}
feedContainer.innerHTML = posts.map(post => `
${post.author?.username || 'Anonymous'}
${this.formatTime(post.created_at)}
${post.content}
`).join('');
}
async likePost(postId) {
try {
await this.api.likePost(postId);
await this.loadSocialFeed();
} catch (error) {
console.error('Failed to like post:', error);
}
}
// ===== VIDEOS =====
async loadVideos() {
try {
const videos = await this.api.getVideos(20);
this.updateVideosUI(videos);
} catch (error) {
console.error('Failed to load videos:', error);
}
}
updateVideosUI(videos) {
const videoGrid = document.querySelector('#blackstream .video-grid');
if (!videoGrid) return;
if (videos.length === 0) {
videoGrid.innerHTML = 'No videos available
';
return;
}
videoGrid.innerHTML = videos.map(video => `
📹
${video.title}
👁️ ${video.views || 0}
❤️ ${video.likes || 0}
`).join('');
}
playVideo(videoId) {
console.log('Play video:', videoId);
// TODO: Open video player
}
// ===== AI CHAT =====
async loadAIChat() {
const content = document.querySelector('#ai-chat .window-content');
if (!content) return;
content.innerHTML = `
`;
}
async sendAIMessage() {
const input = document.getElementById('ai-chat-input');
const message = input.value.trim();
if (!message) return;
console.log('Send AI message:', message);
// TODO: Implement AI chat
input.value = '';
}
// ===== UTILITY FUNCTIONS =====
formatTime(timestamp) {
const date = new Date(timestamp);
const now = new Date();
const diff = now - date;
if (diff < 60000) return 'Just now';
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`;
return date.toLocaleDateString();
}
}
// Create singleton instance
const blackRoadApps = new BlackRoadApps();
window.BlackRoadApps = blackRoadApps;
// Auto-initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
blackRoadApps.initialize();
});
} else {
blackRoadApps.initialize();
}