2026-02-17 23:03:48 -05:00

71 lines
2.5 KiB
JavaScript

import { google } from 'googleapis';
import http from 'http';
import { execSync } from 'child_process';
const CLIENT_ID = '689689127579-1it7eeinkckf1qgrvs2g9nvkjk1f960h.apps.googleusercontent.com';
const CLIENT_SECRET = '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';
const REDIRECT_URI = 'http://localhost:3847/oauth2callback';
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
const TOPIC = 'projects/key-utility-477818-t4/topics/upwork-email-notifications';
const oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
login_hint: 'jake@localbosses.org',
prompt: 'consent',
});
console.log('Opening browser for auth...');
console.log('AUTH_URL:', authUrl);
execSync(`open "${authUrl}"`);
const server = http.createServer(async (req, res) => {
if (req.url.startsWith('/oauth2callback')) {
const url = new URL(req.url, 'http://localhost:3847');
const code = url.searchParams.get('code');
try {
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
console.log('Got tokens! Calling Gmail watch...');
const gmail = google.gmail({ version: 'v1', auth: oauth2Client });
const watchResponse = await gmail.users.watch({
userId: 'me',
requestBody: {
topicName: TOPIC,
labelIds: ['INBOX'],
labelFilterBehavior: 'INCLUDE',
},
});
console.log('Watch response:', JSON.stringify(watchResponse.data, null, 2));
// Save refresh token for renewal
if (tokens.refresh_token) {
const fs = await import('fs');
fs.writeFileSync('/Users/jakeshore/.clawdbot/workspace/upwork-email-trigger/gmail-refresh-token.json',
JSON.stringify({ refresh_token: tokens.refresh_token, expiration: watchResponse.data.expiration }));
console.log('Refresh token saved!');
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Gmail Watch Set Up Successfully!</h1><p>Expiration: ' + watchResponse.data.expiration + '</p><p>You can close this tab.</p>');
setTimeout(() => process.exit(0), 1000);
} catch (err) {
console.error('Error:', err.message);
res.writeHead(500);
res.end('Error: ' + err.message);
setTimeout(() => process.exit(1), 1000);
}
}
});
server.listen(3847, () => {
console.log('Waiting for OAuth callback on http://localhost:3847...');
});