diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.ts index 6ec77b6..222beed 100644 --- a/src/entrypoints/background/index.ts +++ b/src/entrypoints/background/index.ts @@ -1,6 +1,7 @@ import { applyUserAgentRule } from '@/entrypoints/background/net-rules' import { autoLogIn } from '@/features/autologin/background' import { fetchCourses } from '@/features/courses/background' +import { syncMoodleCalendarUrl } from '@/features/moodle-calendar-url/background' import { sendSyncProgress, stopSync, syncCourses } from '@/features/search-sync/background' import { onMessage, sendMessageToMoodleTabs } from '@/shared/messages' import { refreshToken } from '@/shared/moodle-ws-api/token-store' @@ -14,6 +15,7 @@ onMessage('POPUP_OPEN', () => { console.log('Background has received a message POPUP_OPEN') fetchCourses() syncCourses() + syncMoodleCalendarUrl() }) onMessage('MOODLE_LOAD', () => { @@ -36,6 +38,8 @@ onMessage('MOODLE_LOAD', () => { else { // Run the worker if needed syncCourses() + // Sync the calendar url if needed + syncMoodleCalendarUrl() } }) } diff --git a/src/features/moodle-calendar-url/background.ts b/src/features/moodle-calendar-url/background.ts new file mode 100644 index 0000000..5174cda --- /dev/null +++ b/src/features/moodle-calendar-url/background.ts @@ -0,0 +1,42 @@ +import { events } from '@/shared/innohassle-api/events' +import { moodle } from '@/shared/moodle-ws-api' +import { getStored } from '@/shared/storage' + +export async function syncMoodleCalendarUrl() { + console.log('Syncing Moodle calendar URL...') + + const userId = await getStored('userId') + if (!userId) { + console.log('Warning: No user ID found') + return false + } + + const user = await events.usersGetMe() + if (!user) { + console.log('Warning: No InNoHassle user found') + return false + } + + if (user.moodle_userid === userId) { + console.log('Moodle userid is already connected with InNoHassle') + return false + } + + try { + const { token } = await moodle.core.calendar.getCalendarExportToken({}) + if (!token) { + console.log('Error: No Moodle calendar token found') + return false + } + + await events.usersSetUserMoodleData({ + moodle_userid: userId, + moodle_calendar_authtoken: token, + }) + + console.log('Moodle calendar URL have been synced successfully') + } + catch (e) { + console.log('Error: Couldn\'t get Moodle calendar token') + } +}