2024-09-18 19:54:31 +05:30
|
|
|
import { google } from "googleapis";
|
|
|
|
|
import fs from 'fs';
|
|
|
|
|
import path from 'path';
|
2024-09-19 17:42:20 +05:30
|
|
|
import logger from "../../logger";
|
2024-09-19 17:50:59 +05:30
|
|
|
import { readFile } from "../storage";
|
2024-10-17 21:00:13 +05:30
|
|
|
import Run from "../../models/Run";
|
|
|
|
|
import Robot from "../../models/Robot";
|
|
|
|
|
|
2024-09-19 18:04:32 +05:30
|
|
|
interface GoogleSheetUpdateTask {
|
2024-10-17 23:43:56 +05:30
|
|
|
robotId: string;
|
2024-09-19 18:04:32 +05:30
|
|
|
runId: string;
|
2024-09-19 18:14:56 +05:30
|
|
|
status: 'pending' | 'completed' | 'failed';
|
|
|
|
|
retries: number;
|
2024-09-19 18:04:32 +05:30
|
|
|
}
|
|
|
|
|
|
2024-09-19 18:14:56 +05:30
|
|
|
const MAX_RETRIES = 5;
|
|
|
|
|
|
2024-09-19 18:04:32 +05:30
|
|
|
export let googleSheetUpdateTasks: { [runId: string]: GoogleSheetUpdateTask } = {};
|
|
|
|
|
|
|
|
|
|
|
2024-09-19 17:50:59 +05:30
|
|
|
// *** Temporary Path to the JSON file that will store the integration details ***
|
2024-09-19 18:40:45 +05:30
|
|
|
const getIntegrationsFilePath = (fileName: string) => path.join(__dirname, `integrations-${fileName}.json`);
|
2024-09-19 17:50:59 +05:30
|
|
|
|
2024-09-19 18:40:45 +05:30
|
|
|
export function loadIntegrations(fileName: string) {
|
|
|
|
|
const filePath = getIntegrationsFilePath(fileName);
|
|
|
|
|
if (fs.existsSync(filePath)) {
|
|
|
|
|
const data = fs.readFileSync(filePath, 'utf-8');
|
2024-09-19 17:50:59 +05:30
|
|
|
return JSON.parse(data);
|
|
|
|
|
}
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-19 18:40:45 +05:30
|
|
|
export function saveIntegrations(fileName: string, integrations: any) {
|
|
|
|
|
const filePath = getIntegrationsFilePath(fileName);
|
|
|
|
|
fs.writeFileSync(filePath, JSON.stringify(integrations, null, 2));
|
2024-09-19 17:50:59 +05:30
|
|
|
}
|
|
|
|
|
|
2024-10-17 21:00:13 +05:30
|
|
|
export async function updateGoogleSheet(robotId: string, runId: string) {
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log(`Starting updateGoogleSheet for robotId: ${robotId}, runId: ${runId}`);
|
|
|
|
|
|
2024-09-19 17:50:59 +05:30
|
|
|
try {
|
2024-10-17 21:00:13 +05:30
|
|
|
const run = await Run.findOne({ where: { runId } });
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log('Run found:', run);
|
2024-10-17 21:00:13 +05:30
|
|
|
|
|
|
|
|
if (!run) {
|
|
|
|
|
throw new Error(`Run not found for runId: ${runId}`);
|
|
|
|
|
}
|
2024-09-19 17:50:59 +05:30
|
|
|
|
2024-10-17 21:00:13 +05:30
|
|
|
if (run.status === 'success' && run.serializableOutput) {
|
|
|
|
|
const data = run.serializableOutput['item-0'] as { [key: string]: any }[];
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log('Serializable output data:', data);
|
2024-09-19 17:50:59 +05:30
|
|
|
|
2024-10-17 21:00:13 +05:30
|
|
|
const robot = await Robot.findOne({ where: { 'recording_meta.id': robotId } });
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log('Robot found:', robot);
|
|
|
|
|
|
2024-10-17 21:00:13 +05:30
|
|
|
if (!robot) {
|
|
|
|
|
throw new Error(`Robot not found for robotId: ${robotId}`);
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-18 00:13:43 +05:30
|
|
|
const spreadsheetId = robot.google_sheet_id;
|
2024-10-17 21:00:35 +05:30
|
|
|
if (robot.google_sheet_email && spreadsheetId) {
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log(`Preparing to write data to Google Sheet for robot: ${robotId}, spreadsheetId: ${spreadsheetId}`);
|
|
|
|
|
|
2024-10-17 21:00:35 +05:30
|
|
|
const headers = Object.keys(data[0]);
|
|
|
|
|
const rows = data.map((row: { [key: string]: any }) => Object.values(row));
|
|
|
|
|
const outputData = [headers, ...rows];
|
2024-10-18 00:13:43 +05:30
|
|
|
|
|
|
|
|
console.log('Data to be written to sheet:', outputData);
|
2024-09-19 17:50:59 +05:30
|
|
|
|
2024-10-17 21:00:35 +05:30
|
|
|
await writeDataToSheet(robotId, spreadsheetId, outputData);
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log(`Data written to Google Sheet successfully for Robot: ${robotId} and Run: ${runId}`);
|
|
|
|
|
} else {
|
|
|
|
|
console.log('Google Sheets integration not configured.');
|
2024-09-19 17:50:59 +05:30
|
|
|
}
|
2024-10-18 00:13:43 +05:30
|
|
|
} else {
|
|
|
|
|
console.log('Run status is not success or serializableOutput is missing.');
|
2024-10-17 21:00:35 +05:30
|
|
|
}
|
2024-09-19 17:50:59 +05:30
|
|
|
} catch (error: any) {
|
2024-10-18 00:13:43 +05:30
|
|
|
console.error(`Failed to write data to Google Sheet for Robot: ${robotId} and Run: ${runId}: ${error.message}`);
|
2024-09-19 17:50:59 +05:30
|
|
|
}
|
|
|
|
|
};
|
2024-09-18 19:54:31 +05:30
|
|
|
|
2024-10-18 00:13:43 +05:30
|
|
|
|
2024-10-17 21:22:34 +05:30
|
|
|
export async function writeDataToSheet(robotId: string, spreadsheetId: string, data: any[]) {
|
2024-09-18 19:54:31 +05:30
|
|
|
try {
|
2024-10-17 21:22:34 +05:30
|
|
|
const robot = await Robot.findOne({ where: { 'recording_meta.id': robotId } });
|
|
|
|
|
|
|
|
|
|
if (!robot) {
|
|
|
|
|
throw new Error(`Robot not found for robotId: ${robotId}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!robot.google_access_token || !robot.google_refresh_token) {
|
|
|
|
|
throw new Error('Google Sheets access not configured for user');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const oauth2Client = new google.auth.OAuth2(
|
|
|
|
|
process.env.GOOGLE_CLIENT_ID,
|
|
|
|
|
process.env.GOOGLE_CLIENT_SECRET,
|
2024-10-17 23:43:56 +05:30
|
|
|
process.env.GOOGLE_REDIRECT_URI
|
2024-10-17 21:22:34 +05:30
|
|
|
);
|
|
|
|
|
|
|
|
|
|
oauth2Client.setCredentials({
|
|
|
|
|
access_token: robot.google_access_token,
|
|
|
|
|
refresh_token: robot.google_refresh_token,
|
|
|
|
|
});
|
|
|
|
|
|
2024-10-17 23:43:56 +05:30
|
|
|
// Log tokens and any refresh activity
|
2024-10-17 21:22:34 +05:30
|
|
|
oauth2Client.on('tokens', async (tokens) => {
|
2024-10-17 23:43:56 +05:30
|
|
|
console.log('OAuth2 tokens updated:', tokens);
|
2024-10-17 21:22:34 +05:30
|
|
|
if (tokens.refresh_token) {
|
|
|
|
|
await robot.update({ google_refresh_token: tokens.refresh_token });
|
|
|
|
|
}
|
|
|
|
|
if (tokens.access_token) {
|
|
|
|
|
await robot.update({ google_access_token: tokens.access_token });
|
|
|
|
|
}
|
2024-09-18 19:54:31 +05:30
|
|
|
});
|
|
|
|
|
|
2024-10-17 21:22:34 +05:30
|
|
|
const sheets = google.sheets({ version: 'v4', auth: oauth2Client });
|
2024-09-18 19:54:31 +05:30
|
|
|
|
|
|
|
|
const resource = { values: data };
|
2024-10-17 23:43:56 +05:30
|
|
|
console.log('Attempting to write to spreadsheet:', spreadsheetId);
|
|
|
|
|
console.log('Data being written:', data);
|
2024-09-18 19:54:31 +05:30
|
|
|
|
2024-10-17 23:43:56 +05:30
|
|
|
const response = await sheets.spreadsheets.values.append({
|
2024-09-18 19:54:31 +05:30
|
|
|
spreadsheetId,
|
2024-10-17 21:22:34 +05:30
|
|
|
range: 'Sheet1!A1',
|
2024-09-18 19:54:31 +05:30
|
|
|
valueInputOption: 'USER_ENTERED',
|
|
|
|
|
requestBody: resource,
|
|
|
|
|
});
|
|
|
|
|
|
2024-10-18 00:13:43 +05:30
|
|
|
console.log('Google Sheets API response:', JSON.stringify(response, null, 2));
|
|
|
|
|
|
|
|
|
|
if (response.status === 200) {
|
|
|
|
|
console.log('Data successfully appended to Google Sheet.');
|
|
|
|
|
} else {
|
|
|
|
|
console.error('Google Sheets append failed:', response);
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-17 21:22:34 +05:30
|
|
|
logger.log(`info`, `Data written to Google Sheet: ${spreadsheetId}`);
|
2024-09-18 22:05:06 +05:30
|
|
|
} catch (error: any) {
|
2024-09-19 17:42:20 +05:30
|
|
|
logger.log(`error`, `Error writing data to Google Sheet: ${error.message}`);
|
2024-09-18 19:54:31 +05:30
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-09-19 18:04:32 +05:30
|
|
|
|
2024-10-17 23:43:56 +05:30
|
|
|
|
2024-09-19 19:36:08 +05:30
|
|
|
export const processGoogleSheetUpdates = async () => {
|
2024-09-19 18:04:32 +05:30
|
|
|
while (true) {
|
2024-09-19 18:14:56 +05:30
|
|
|
let hasPendingTasks = false;
|
2024-09-19 18:04:32 +05:30
|
|
|
for (const runId in googleSheetUpdateTasks) {
|
|
|
|
|
const task = googleSheetUpdateTasks[runId];
|
2024-10-17 23:43:56 +05:30
|
|
|
console.log(`Processing task for runId: ${runId}, status: ${task.status}`);
|
|
|
|
|
|
2024-09-19 18:04:32 +05:30
|
|
|
if (task.status === 'pending') {
|
2024-09-19 18:14:56 +05:30
|
|
|
hasPendingTasks = true;
|
2024-09-19 18:04:32 +05:30
|
|
|
try {
|
2024-10-17 23:43:56 +05:30
|
|
|
await updateGoogleSheet(task.robotId, task.runId);
|
|
|
|
|
console.log(`Successfully updated Google Sheet for runId: ${runId}`);
|
2024-09-19 18:04:32 +05:30
|
|
|
delete googleSheetUpdateTasks[runId];
|
|
|
|
|
} catch (error: any) {
|
2024-10-17 23:43:56 +05:30
|
|
|
console.error(`Failed to update Google Sheets for run ${task.runId}:`, error);
|
2024-09-19 18:14:56 +05:30
|
|
|
if (task.retries < MAX_RETRIES) {
|
|
|
|
|
googleSheetUpdateTasks[runId].retries += 1;
|
2024-10-17 23:43:56 +05:30
|
|
|
console.log(`Retrying task for runId: ${runId}, attempt: ${task.retries}`);
|
2024-09-19 18:14:56 +05:30
|
|
|
} else {
|
|
|
|
|
googleSheetUpdateTasks[runId].status = 'failed';
|
2024-10-17 23:43:56 +05:30
|
|
|
console.log(`Max retries reached for runId: ${runId}. Marking task as failed.`);
|
2024-09-19 18:14:56 +05:30
|
|
|
}
|
2024-09-19 18:04:32 +05:30
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-10-17 23:43:56 +05:30
|
|
|
|
2024-09-19 18:04:32 +05:30
|
|
|
if (!hasPendingTasks) {
|
2024-10-17 23:43:56 +05:30
|
|
|
console.log('No pending tasks. Exiting loop.');
|
2024-09-19 18:04:32 +05:30
|
|
|
break;
|
|
|
|
|
}
|
2024-10-17 23:43:56 +05:30
|
|
|
|
|
|
|
|
console.log('Waiting for 5 seconds before checking again...');
|
2024-09-19 18:04:32 +05:30
|
|
|
await new Promise(resolve => setTimeout(resolve, 5000));
|
|
|
|
|
}
|
2024-10-17 23:43:56 +05:30
|
|
|
};
|