mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
cf9e36f10a
Add calendar authentication and event/task actions, plus rich-description styling and setup documentation.
132 lines
4.6 KiB
TypeScript
132 lines
4.6 KiB
TypeScript
import { google, calendar_v3 } from 'googleapis';
|
|
import path from 'path';
|
|
import fs from 'fs';
|
|
|
|
const SCOPES = [
|
|
'https://www.googleapis.com/auth/calendar',
|
|
'https://www.googleapis.com/auth/calendar.events',
|
|
];
|
|
|
|
export interface GoogleClientContext {
|
|
calendar: calendar_v3.Calendar;
|
|
calendarId: string;
|
|
serviceAccountEmail: string;
|
|
authMode: 'oauth2' | 'service_account';
|
|
}
|
|
|
|
export function getGoogleCalendarClient(): GoogleClientContext {
|
|
const calendarId = process.env.GOOGLE_CALENDAR_ID || 'primary';
|
|
|
|
const clientId = process.env.GOOGLE_CLIENT_ID?.trim();
|
|
const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
|
|
const refreshToken = process.env.GOOGLE_REFRESH_TOKEN?.trim();
|
|
const serviceAccountFile = process.env.GOOGLE_CALENDAR_SA_FILE?.trim();
|
|
|
|
// 1. Primary Mode: Single System OAuth2 Refresh Token
|
|
if (clientId && clientSecret && refreshToken) {
|
|
const oauth2Client = new google.auth.OAuth2(
|
|
clientId,
|
|
clientSecret,
|
|
'https://developers.google.com/oauthplayground'
|
|
);
|
|
|
|
oauth2Client.setCredentials({
|
|
refresh_token: refreshToken,
|
|
});
|
|
|
|
const calendar = google.calendar({
|
|
version: 'v3',
|
|
auth: oauth2Client,
|
|
});
|
|
|
|
return {
|
|
calendar,
|
|
calendarId,
|
|
serviceAccountEmail: 'OAuth2 System Account',
|
|
authMode: 'oauth2',
|
|
};
|
|
}
|
|
|
|
// 2. Fallback Mode: Google Service Account
|
|
let clientEmail = process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL;
|
|
let privateKey = process.env.GOOGLE_PRIVATE_KEY;
|
|
|
|
const keyFilePath = path.join(process.cwd(), serviceAccountFile!);
|
|
if (fs.existsSync(keyFilePath)) {
|
|
try {
|
|
const fileData = JSON.parse(fs.readFileSync(keyFilePath, 'utf8'));
|
|
if (fileData.client_email) clientEmail = fileData.client_email;
|
|
if (fileData.private_key) privateKey = fileData.private_key;
|
|
} catch (e) {
|
|
console.warn('[GOOGLE_CALENDAR] Could not parse hats-project-sa-rifail.json:', e);
|
|
}
|
|
}
|
|
|
|
if (!clientEmail || !privateKey) {
|
|
throw new Error(
|
|
'Kredensial Google Calendar tidak ditemukan! Pastikan GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, dan GOOGLE_REFRESH_TOKEN telah dikonfigurasi di file .env.'
|
|
);
|
|
}
|
|
|
|
const formattedPrivateKey = privateKey.replace(/\\n/g, '\n');
|
|
|
|
const auth = new google.auth.JWT({
|
|
email: clientEmail,
|
|
key: formattedPrivateKey,
|
|
scopes: SCOPES,
|
|
});
|
|
|
|
const calendar = google.calendar({
|
|
version: 'v3',
|
|
auth,
|
|
});
|
|
|
|
return {
|
|
calendar,
|
|
calendarId,
|
|
serviceAccountEmail: clientEmail,
|
|
authMode: 'service_account',
|
|
};
|
|
}
|
|
|
|
export function formatGoogleApiError(error: unknown): string {
|
|
if (!error) return 'Terjadi kesalahan internal yang tidak diketahui.';
|
|
|
|
const err = error as { message?: string; code?: number | string };
|
|
const message = err.message || String(error);
|
|
|
|
if (message.includes('unauthorized_client')) {
|
|
return 'OAuth2 Error (unauthorized_client): GOOGLE_REFRESH_TOKEN tidak cocok dengan GOOGLE_CLIENT_ID & GOOGLE_CLIENT_SECRET Anda. Jika membuat token di Google OAuth Playground, pastikan Anda klik ikon Gear (⚙️) di kanan atas dan centang "Use your own OAuth credentials" lalu masukkan Client ID & Client Secret sebelum mengklik Authorize APIs.';
|
|
}
|
|
|
|
if (message.includes('invalid_grant')) {
|
|
return 'OAuth2 Error (invalid_grant): Refresh Token sudah kedaluwarsa, dicabut (revoked), atau aplikasi OAuth masih berstatus "Testing" di Google Cloud Console (token kedaluwarsa setelah 7 hari). Silakan generate ulang GOOGLE_REFRESH_TOKEN.';
|
|
}
|
|
|
|
if (message.includes('Google Calendar API has not been used') || message.includes('disabled')) {
|
|
return 'Google Calendar API belum diaktifkan di Google Cloud Console. Silakan aktifkan Calendar API di Console.';
|
|
}
|
|
|
|
if (message.includes('Domain-Wide Delegation')) {
|
|
return 'Service Account tanpa Domain-Wide Delegation tidak dapat mengirim undangan email (attendees) secara langsung.';
|
|
}
|
|
|
|
if (message.includes('Invalid conference type value')) {
|
|
return 'Pembuatan link Google Meet otomatis gagal ("Invalid conference type value"). Pastikan menggunakan autentikasi OAuth2 System Account atau masukkan link Google Meet secara manual.';
|
|
}
|
|
|
|
if (message.includes('Invalid start time') || message.includes('time range is empty')) {
|
|
return 'Format waktu mulai/selesai tidak valid. Pastikan waktu selesai lebih akhir dari waktu mulai.';
|
|
}
|
|
|
|
if (message.includes('Not Found') || err.code === 404) {
|
|
return 'Kalender tidak ditemukan (404). Pastikan akun Google OAuth2 yang digunakan memiliki akses ke GOOGLE_CALENDAR_ID tersebut (atau ubah GOOGLE_CALENDAR_ID="primary" untuk menggunakan kalender utama akun tersebut).';
|
|
}
|
|
|
|
if (message.includes('forbidden') || err.code === 403) {
|
|
return 'Akses ditolak (403). Pastikan akun yang digunakan memiliki izin "Make changes to events" pada kalender ini.';
|
|
}
|
|
|
|
return message;
|
|
}
|