nileshtrivedi / Create Google Calendar Event

// ==UserScript==
// @name         Create Google Calendar Event
// @version      1.0
// @description  Create Google Calendar Event from Selected Text using AI models at OpenRouter (needs API Key)
// @match        *://*/*
// @grant        GM_openInTab
// @grant        GM_registerMenuCommand
// @grant        GM_xmlhttpRequest
// @copyright       2024, nileshtrivedi(https://openuserjs.org/users/nileshtrivedi)
// @license         MIT
// ==/UserScript==


(function() {
    'use strict';

    const OPENROUTER_API_KEY = 'your_openrouter_apikey_goes_here';

    // Function to format date for Google Calendar URL
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toISOString().replace(/-|:|\.\d\d\d/g,"");
    }

    // Create a function to handle the selected text
    async function createCalendarEvent() {
        const selectedText = window.getSelection().toString().trim();
        const currentPageUrl = window.location.href;

        if (selectedText) {
            try {
                const event = await extractEventDetails(selectedText);
                const eventDetails = `${event.event_description}\n\nSource: ${currentPageUrl}`;
                const encodedText = encodeURIComponent(eventDetails);
                const encodedTitle = encodeURIComponent(event.event_title);
                const encodedLocation = encodeURIComponent(event.event_location);
                const formattedDate = formatDate(event.event_date);

                const calendarUrl = `https://calendar.google.com/calendar/r/eventedit?text=${encodedTitle}&location=${encodedLocation}&details=${encodedText}&dates=${formattedDate}/${formattedDate}`;

                // Open the Google Calendar link in a new tab
                GM_openInTab(calendarUrl, { active: true });
            } catch (error) {
                console.error('Error creating calendar event:', error);
                alert('An error occurred while creating the event. Please try again.');
            }
        } else {
            alert('Please select some text before creating an event.');
        }
    }

    async function extractEventDetails(selectedText) {
        const prompt = `Analyze the following text and extract event details. Return a JSON object with the following keys: event_title, event_description, event_location, and event_date. Format the event_date as YYYY-MM-DDTHH:mm:ss. If any information is missing, use reasonable defaults or leave the field empty. Ensure the JSON is valid and contains all required keys. Do not include any explanation or comments outside the JSON object.

Text to analyze:
${selectedText}`;

        try {
            const response = await new Promise((resolve, reject) => {
                GM_xmlhttpRequest({
                    method: "POST",
                    url: "https://openrouter.ai/api/v1/chat/completions",
                    headers: {
                        "Authorization": `Bearer ${OPENROUTER_API_KEY}`,
                        "Content-Type": "application/json"
                    },
                    data: JSON.stringify({
                        "model": "google/gemma-2-9b-it:free",
                        "messages": [
                            {"role": "user", "content": prompt},
                        ],
                    }),
                    onload: function(response) {
                        if (response.status === 200) {
                            console.error("openrouter 200");
                            resolve(JSON.parse(response.responseText));
                        } else {
                            console.error(`openrouter ${response.status}`);
                            reject(new Error(`API request failed with status ${response.status}`));
                        }
                    },
                    onerror: function(error) {
                        console.error(`openrouter error`);
                        reject(error);
                    }
                });
            });

            // const content = JSON.parse(response.choices[0].message.content);
            console.error(response);
            return response;
        } catch (error) {
            console.error('Error extracting event details:', error);
            throw error;
        }
    }

    // Create a context menu item
    GM_registerMenuCommand('Create AI-Assisted Calendar Event', createCalendarEvent);

})();