YANZ UPLOAD ANJG

/** * CV-Plus Life Assistant - Comprehensive API Integration Module * Integrates Google APIs (Tasks, Calendar, Fit, Reminders) and IFTTT * Version: 2.0 - Ultimate Edition */ class CVPlusAPIIntegration { constructor() { this.googleAccessToken = null; this.googleUserId = null; this.iftttKey = 'YOUR_IFTTT_WEBHOOK_KEY'; this.googleClientId = 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'; this.isAuthenticated = false; this.syncInterval = 30000; // 30 seconds this.dataCache = {}; this.initializeIntegration(); } // ===== INITIALIZATION ===== initializeIntegration() { console.log('CV-Plus API Integration initialized'); this.setupEventListeners(); this.loadCachedData(); } setupEventListeners() { // Listen for authentication events document.addEventListener('googleSignIn', (e) => this.onGoogleSignIn(e)); document.addEventListener('googleSignOut', (e) => this.onGoogleSignOut(e)); } // ===== GOOGLE AUTHENTICATION ===== async authenticateGoogle(token) { try { this.googleAccessToken = token; this.isAuthenticated = true; console.log('Google authentication successful'); await this.fetchUserProfile(); return true; } catch (error) { console.error('Google authentication failed:', error); return false; } } async fetchUserProfile() { try { const response = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', { headers: { 'Authorization': `Bearer ${this.googleAccessToken}` } }); const data = await response.json(); this.googleUserId = data.id; console.log('User profile fetched:', data.name); return data; } catch (error) { console.error('Failed to fetch user profile:', error); } } // ===== GOOGLE TASKS API ===== async getTasks() { try { const response = await fetch('https://www.googleapis.com/tasks/v1/users/@me/lists', { headers: { 'Authorization': `Bearer ${this.googleAccessToken}` } }); const data = await response.json(); this.dataCache.tasks = data.items || []; return this.dataCache.tasks; } catch (error) { console.error('Failed to fetch tasks:', error); return []; } } async createTask(title, notes = '', dueDate = null) { try { // First get the default task list const lists = await this.getTasks(); const defaultList = lists[0].id; const response = await fetch(`https://www.googleapis.com/tasks/v1/lists/${defaultList}/tasks`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.googleAccessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ title: title, notes: notes, due: dueDate }) }); const data = await response.json(); console.log('Task created:', data.title); return data; } catch (error) { console.error('Failed to create task:', error); } } async updateTask(taskId, listId, updates) { try { const response = await fetch(`https://www.googleapis.com/tasks/v1/lists/${listId}/tasks/${taskId}`, { method: 'PATCH', headers: { 'Authorization': `Bearer ${this.googleAccessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify(updates) }); const data = await response.json(); console.log('Task updated:', data.title); return data; } catch (error) { console.error('Failed to update task:', error); } } // ===== GOOGLE CALENDAR API ===== async getCalendarEvents(timeMin = null, timeMax = null) { try { const now = new Date(); const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); const response = await fetch( `https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=${(timeMin || startOfDay).toISOString()}&timeMax=${(timeMax || endOfDay).toISOString()}`, { headers: { 'Authorization': `Bearer ${this.googleAccessToken}` } } ); const data = await response.json(); this.dataCache.events = data.items || []; return this.dataCache.events; } catch (error) { console.error('Failed to fetch calendar events:', error); return []; } } async createCalendarEvent(title, startTime, endTime, description = '') { try { const response = await fetch('https://www.googleapis.com/calendar/v3/calendars/primary/events', { method: 'POST', headers: { 'Authorization': `Bearer ${this.googleAccessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ summary: title, description: description, start: { dateTime: startTime.toISOString() }, end: { dateTime: endTime.toISOString() } }) }); const data = await response.json(); console.log('Calendar event created:', data.summary); return data; } catch (error) { console.error('Failed to create calendar event:', error); } } // ===== GOOGLE FIT API ===== async getFitnessData(dataType = 'com.google.step_count.delta') { try { const now = new Date(); const startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000); // Last 24 hours const response = await fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', { method: 'POST', headers: { 'Authorization': `Bearer ${this.googleAccessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ aggregateBy: [{ dataTypeName: dataType }], bucketByTime: { durationMillis: 86400000 }, startTimeMillis: startTime.getTime(), endTimeMillis: now.getTime() }) }); const data = await response.json(); this.dataCache.fitness = data.bucket || []; return this.dataCache.fitness; } catch (error) { console.error('Failed to fetch fitness data:', error); return []; } } async insertFitnessData(dataType, value, startTime = null, endTime = null) { try { const now = new Date(); const start = startTime || new Date(now.getTime() - 60 * 60 * 1000); const end = endTime || now; const response = await fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', { method: 'POST', headers: { 'Authorization': `Bearer ${this.googleAccessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ dataSourceId: `derived:com.google.${dataType}:com.google.android.gms`, point: [{ startTimeNanos: start.getTime() * 1000000, endTimeNanos: end.getTime() * 1000000, dataTypeName: dataType, value: [{ intVal: value }] }] }) }); console.log('Fitness data inserted:', dataType, value); return true; } catch (error) { console.error('Failed to insert fitness data:', error); return false; } } // ===== GOOGLE REMINDERS API ===== async getReminders() { try { const response = await fetch('https://www.googleapis.com/reminders/v1/reminders', { headers: { 'Authorization': `Bearer ${this.googleAccessToken}` } }); const data = await response.json(); this.dataCache.reminders = data.items || []; return this.dataCache.reminders; } catch (error) { console.error('Failed to fetch reminders:', error); return []; } } async createReminder(title, dueTime, description = '') { try { const response = await fetch('https://www.googleapis.com/reminders/v1/reminders', { method: 'POST', headers: { 'Authorization': `Bearer ${this.googleAccessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ title: title, notes: description, dueDate: dueTime.toISOString().split('T')[0], dueTime: dueTime.toISOString().split('T')[1] }) }); const data = await response.json(); console.log('Reminder created:', data.title); return data; } catch (error) { console.error('Failed to create reminder:', error); } } // ===== IFTTT INTEGRATION ===== async triggerIFTTTEvent(eventName, value1 = '', value2 = '', value3 = '') { try { const response = await fetch(`https://maker.ifttt.com/trigger/${eventName}/with/key/${this.iftttKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value1: value1, value2: value2, value3: value3 }) }); console.log('IFTTT event triggered:', eventName); return response.ok; } catch (error) { console.error('Failed to trigger IFTTT event:', error); return false; } } async logHealthMetric(metricType, value) { // Trigger IFTTT event for health metric logging await this.triggerIFTTTEvent('log_health_metric', metricType, value, new Date().toISOString()); } async sendNotification(title, message) { // Trigger IFTTT event for notifications await this.triggerIFTTTEvent('send_notification', title, message); } // ===== BLUETOOTH INTEGRATION ===== async scanBluetoothDevices() { try { if (!navigator.bluetooth) { console.warn('Bluetooth API not supported'); return []; } const device = await navigator.bluetooth.requestDevice({ filters: [ { services: ['heart_rate'] }, { services: ['generic_access'] } ] }); console.log('Bluetooth device found:', device.name); return [device]; } catch (error) { console.error('Bluetooth scan failed:', error); return []; } } async connectBluetoothDevice(device) { try { const server = await device.gatt.connect(); console.log('Connected to GATT server'); return server; } catch (error) { console.error('Failed to connect to Bluetooth device:', error); } } async readHeartRate(server) { try { const service = await server.getPrimaryService('heart_rate'); const characteristic = await service.getCharacteristic('heart_rate_measurement'); const value = await characteristic.readValue(); const heartRate = value.getUint8(1); console.log('Heart rate:', heartRate); return heartRate; } catch (error) { console.error('Failed to read heart rate:', error); } } // ===== DATA SYNC ===== async syncAllData() { try { console.log('Starting comprehensive data sync...'); if (!this.isAuthenticated) { console.warn('Not authenticated. Skipping sync.'); return false; } const results = await Promise.all([ this.getTasks(), this.getCalendarEvents(), this.getFitnessData(), this.getReminders() ]); console.log('Data sync completed successfully'); return true; } catch (error) { console.error('Data sync failed:', error); return false; } } // ===== DATA CACHING ===== loadCachedData() { const cached = localStorage.getItem('cvplus_data_cache'); if (cached) { this.dataCache = JSON.parse(cached); console.log('Cached data loaded'); } } saveCachedData() { localStorage.setItem('cvplus_data_cache', JSON.stringify(this.dataCache)); console.log('Data cached'); } // ===== HEALTH METRICS CALCULATION ===== calculateWellnessScore(metrics) { const weights = { meditation: 0.20, nutrition: 0.20, fitness: 0.15, sleep: 0.15, stress: 0.15, workLifeBalance: 0.15 }; let score = 0; for (const [key, weight] of Object.entries(weights)) { if (metrics[key] !== undefined) { score += metrics[key] * weight; } } return Math.round(score); } getWellnessCategory(score) { if (score >= 85) return 'EXCELLENT'; if (score >= 70) return 'GOOD'; if (score >= 50) return 'FAIR'; return 'NEEDS IMPROVEMENT'; } // ===== ADVANCED HEALTH ANALYTICS ===== analyzeHeartRateVariability(heartRateData) { if (heartRateData.length < 2) return null; const differences = []; for (let i = 1; i < heartRateData.length; i++) { differences.push(Math.abs(heartRateData[i] - heartRateData[i - 1])); } const mean = differences.reduce((a, b) => a + b) / differences.length; const variance = differences.reduce((a, b) => a + Math.pow(b - mean, 2)) / differences.length; const standardDeviation = Math.sqrt(variance); return { mean: Math.round(mean), standardDeviation: Math.round(standardDeviation), health: standardDeviation > 20 ? 'EXCELLENT' : 'GOOD' }; } calculateVO2Max(age, restingHeartRate, maxHeartRate) { // Karvonen formula approximation const vo2Max = 15.3 * (maxHeartRate / restingHeartRate); return Math.round(vo2Max * 10) / 10; } analyzeRecoveryIndex(sleepHours, stressLevel, exerciseIntensity) { let recovery = 100; // Sleep impact (0-30 points) if (sleepHours >= 8) recovery += 30; else if (sleepHours >= 7) recovery += 20; else if (sleepHours >= 6) recovery += 10; // Stress impact (0-30 points) recovery -= (stressLevel * 3); // Exercise impact (0-20 points) if (exerciseIntensity <= 5) recovery += 20; else if (exerciseIntensity <= 7) recovery += 10; return Math.max(0, Math.min(100, recovery)); } // ===== PREDICTIVE ANALYTICS ===== predictHealthTrend(historicalData) { if (historicalData.length < 3) return null; const trend = { improving: false, declining: false, stable: false, prediction: null }; const recent = historicalData.slice(-3); const average = recent.reduce((a, b) => a + b) / recent.length; const older = historicalData.slice(-6, -3); const olderAverage = older.reduce((a, b) => a + b) / older.length; if (average > olderAverage) { trend.improving = true; trend.prediction = 'Your health metrics are improving. Keep up the good work!'; } else if (average < olderAverage) { trend.declining = true; trend.prediction = 'Your health metrics are declining. Consider adjusting your routine.'; } else { trend.stable = true; trend.prediction = 'Your health metrics are stable. Maintain your current routine.'; } return trend; } // ===== EXPORT & REPORTING ===== generateHealthReport() { const report = { timestamp: new Date().toISOString(), user: this.googleUserId, data: this.dataCache, summary: { tasksCompleted: this.dataCache.tasks?.length || 0, eventsScheduled: this.dataCache.events?.length || 0, remindersSet: this.dataCache.reminders?.length || 0 } }; return report; } exportDataAsJSON() { const data = this.generateHealthReport(); const json = JSON.stringify(data, null, 2); const blob = new Blob([json], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `cvplus_health_report_${Date.now()}.json`; a.click(); URL.revokeObjectURL(url); } exportDataAsCSV() { const data = this.generateHealthReport(); let csv = 'Metric,Value\n'; csv += `Timestamp,${data.timestamp}\n`; csv += `Tasks,${data.summary.tasksCompleted}\n`; csv += `Events,${data.summary.eventsScheduled}\n`; csv += `Reminders,${data.summary.remindersSet}\n`; const blob = new Blob([csv], { type: 'text/csv' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `cvplus_health_report_${Date.now()}.csv`; a.click(); URL.revokeObjectURL(url); } // ===== EVENT HANDLERS ===== onGoogleSignIn(event) { console.log('Google sign-in event received'); this.authenticateGoogle(event.detail.token); } onGoogleSignOut(event) { console.log('Google sign-out event received'); this.googleAccessToken = null; this.isAuthenticated = false; } // ===== UTILITY FUNCTIONS ===== setIFTTTKey(key) { this.iftttKey = key; console.log('IFTTT key updated'); } setGoogleClientId(clientId) { this.googleClientId = clientId; console.log('Google Client ID updated'); } getAuthenticationStatus() { return { isAuthenticated: this.isAuthenticated, userId: this.googleUserId, hasAccessToken: !!this.googleAccessToken }; } getCachedData() { return this.dataCache; } clearCache() { this.dataCache = {}; localStorage.removeItem('cvplus_data_cache'); console.log('Cache cleared'); } } // Initialize the API integration const cvplusAPI = new CVPlusAPIIntegration(); // Export for use in other modules if (typeof module !== 'undefined' && module.exports) { module.exports = CVPlusAPIIntegration; }