const express = require('express'); const mysql = require('mysql'); const cors = require('cors'); const { google } = require('googleapis'); const { OAuth2Client } = require('google-auth-library'); const app = express(); const port = 3000; require('dotenv').config(); app.use(cors()); const corsOptions = { origin: [ 'http://69.174.114.36', 'http://sd308.net', 'http://sd308.org', 'http://www.sd308.net', 'http://www.sd308.org', ], }; app.use(cors(corsOptions)); const dbPool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_DATABASE, }); const googleSheetsConfig = { client_id: process.env.GOOGLE_CLIENT_ID, client_secret: process.env.GOOGLE_CLIENT_SECRET, key: process.env.GOOGLE_API_KEY, redirect_uris: ['https://www.sd308.net/latebus/auth/callback'], }; const oAuth2Client = new OAuth2Client( googleSheetsConfig.client_id, googleSheetsConfig.client_secret, googleSheetsConfig.redirect_uris[0] ); const sheetsAPI = google.sheets('v4'); // Generate authentication URL and prompt user to authorize app.get('/latebus/firstrun', (req, res) => { const authorizeUrl = oAuth2Client.generateAuthUrl({ client_id: googleSheetsConfig.client_id, access_type: 'offline', scope: 'https://www.googleapis.com/auth/spreadsheets', }); const html = ` Authorize App

Authorize this app by visiting the following link:

${authorizeUrl}

${googleSheetsConfig.client_id}

${process.env.DB_USER}

`; res.send(html); }); app.get('/latebus/auth/callback', async (req, res) => { const code = req.query.code; // Get the authorization code from the query parameters // Exchange the authorization code for tokens const { tokens } = await oAuth2Client.getToken(code); oAuth2Client.setCredentials(tokens); // Redirect back to the homepage or wherever you want res.redirect('/'); }); //Fetch data from Google Sheets and update MySQL database app.get('/latebus/update', async (req, res) => { try { // Use the stored refresh token to refresh the access token if needed if (oAuth2Client.isTokenExpiring()) { const { tokens } = await oAuth2Client.refreshAccessToken(); oAuth2Client.setCredentials(tokens); } const access_token = oAuth2Client.credentials.access_token; const sheets = sheetsAPI({ version: 'v4', auth: access_token }); const response = await sheets.spreadsheets.values.get({ spreadsheetId: '1DuQLObIlPL1TQHY4Mk76xEve7j6qUsnOLCL0VnIr6HA', range: 'LateToday!A:E', }); const query = ` INSERT INTO LateToday (school_building_shortcode, route_number, running_late_minutes, date, time_logged, time_expired) VALUES ? ON DUPLICATE KEY UPDATE school_building_shortcode = VALUES(school_building_shortcode), route_number = VALUES(route_number), running_late_minutes = VALUES(running_late_minutes), date = VALUES(date), time_logged = VALUES(time_logged), time_expired = VALUES(time_expired) `; const values = rows.map(row => { return [ row[0], // School Building Shortcode row[1], // Route Number row[2], // Running Late (Minutes) row[3], // Date row[4], // Time Logged row[5] // Time Expired ]; }); dbPool.query(query, [values], (error, results) => { if (error) { console.error('Error inserting/updating data:', error); res.status(500).send('An error occurred while inserting/updating data.'); } else { // You might want to handle deletions here if applicable console.log('Data inserted/updated successfully.'); res.send('Data inserted/updated successfully.'); } }); } catch (error) { console.error('Error updating data:', error); res.status(500).send('An error occurred while updating data.'); } }); app.get('/latebus/latetoday', (req, res) => { const query = 'SELECT * FROM LateToday'; // Change if needed dbPool.getConnection((error, connection) => { if (error) { console.error('Error getting connection from pool:', error); res.status(500).json({ error: 'Internal Server Error' }); } else { connection.query(query, (error, results) => { connection.release(); // Release the connection back to the pool if (error) { console.error('Error fetching data from database:', error); res.status(500).json({ error: 'Internal Server Error' }); } else { res.json(results); } }); } }); }); app.get('/latebus', (req, res) => { res.send('Thank you for visiting the Late Bus page!'); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });