Skip to content

Commit

Permalink
delta.py basis
Browse files Browse the repository at this point in the history
  • Loading branch information
hegstadjosh committed Oct 5, 2024
1 parent 49270fc commit 459241b
Show file tree
Hide file tree
Showing 5 changed files with 158 additions and 81 deletions.
40 changes: 20 additions & 20 deletions src/extension/manifest.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
{
"manifest_version": 3,
"name": "AI Notetaking Extension",
"version": "1.0",
"description": "Take notes and get AI-generated prompts.",
"action": {
"default_popup": "popup.html"
},
"permissions": [
"storage",
"identity"
],
"host_permissions": [
"http://localhost:3000/*",
"https://accounts.google.com/*",
"https://www.googleapis.com/*"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
}
"manifest_version": 3,
"name": "AI Notetaking Extension",
"version": "1.0",
"description": "Take notes, categorize them, and get AI-generated prompts.",
"action": {
"default_popup": "popup.html"
},
"permissions": [
"storage",
"identity"
],
"host_permissions": [
"http://localhost:3000/*",
"https://accounts.google.com/*",
"https://www.googleapis.com/*"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
}

}


13 changes: 13 additions & 0 deletions src/extension/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,24 @@
</head>
<body>
<h1>Notetaking</h1>

<!-- Category Selection -->
<label for="categorySelect">Category:</label>
<select id="categorySelect">
<option value="Personal">Personal</option>
<option value="Work">Work</option>
<option value="Ideas">Ideas</option>
<option value="Other">Other</option>
</select>

<!-- Note Textarea -->
<textarea id="noteArea" placeholder="Type your note here..."></textarea>

<div class="buttons">
<button id="saveNote">Save Note</button>
<button id="getPrompt">Get AI Prompt</button>
</div>

<script src="popup.js"></script>
</body>
</html>
113 changes: 83 additions & 30 deletions src/extension/popup.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,19 @@
// Google Docs Chrome Extension
// This script allows users to save notes to Google Docs and fetch AI-generated prompts.
const CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
const REDIRECT_URI = `https://${chrome.runtime.id}.chromiumapp.org/`;
const SCOPES = [
'https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/drive.file'
];

// Constants for Google OAuth
const CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID'; // Replace with your actual Google Client ID
const REDIRECT_URI = `https://${chrome.runtime.id}.chromiumapp.org/`; // Chrome extension's redirect URI
const SCOPES = ['https://www.googleapis.com/auth/documents']; // Required scope for Google Docs API

// Event listeners for UI buttons
document.getElementById('saveNote').addEventListener('click', saveNote);
document.getElementById('getPrompt').addEventListener('click', getAIPrompt);

/**
* Saves the content of the noteArea to a Google Doc.
*/
function saveNote() {
const noteContent = document.getElementById('noteArea').value;
saveNoteToGoogleDoc(noteContent);
const category = document.getElementById('categorySelect').value;
saveNoteToGoogleDoc(noteContent, category);
}

/**
* Fetches an AI-generated prompt from a local server and populates the noteArea.
*/
function getAIPrompt() {
fetch('http://localhost:3000/get-prompt')
.then(response => response.json())
Expand All @@ -33,11 +26,7 @@ function getAIPrompt() {
});
}

/**
* Retrieves an access token for Google OAuth.
* @param {boolean} interactive - Whether to show the auth prompt to the user.
* @returns {Promise<string>} A promise that resolves with the access token.
*/
// OAuth2 Authentication
function getAccessToken(interactive) {
return new Promise((resolve, reject) => {
const authUrl =
Expand Down Expand Up @@ -71,30 +60,94 @@ function getAccessToken(interactive) {
});
}

/**
* Saves the given content to a new Google Doc.
* @param {string} content - The text content to save in the Google Doc.
*/
async function saveNoteToGoogleDoc(content) {
// Function to get or create a folder in Google Drive
async function getOrCreateFolder(accessToken, category) {
// Search for an existing folder
const searchResponse = await fetch(
`https://www.googleapis.com/drive/v3/files?q=name='${encodeURIComponent(category)}'+and+mimeType='application/vnd.google-apps.folder'&fields=files(id,name)&spaces=drive`,
{
headers: {
'Authorization': 'Bearer ' + accessToken,
},
}
);

const searchData = await searchResponse.json();

if (searchData.files && searchData.files.length > 0) {
// Folder exists
return searchData.files[0].id;
} else {
// Create a new folder
const createFolderResponse = await fetch('https://www.googleapis.com/drive/v3/files', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: category,
mimeType: 'application/vnd.google-apps.folder',
}),
});

const folderData = await createFolderResponse.json();
return folderData.id;
}
}

// Function to move a file to a folder in Google Drive
async function moveFileToFolder(accessToken, fileId, folderId) {
// Retrieve the existing parents to remove
const getFileResponse = await fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?fields=parents`, {
headers: {
'Authorization': 'Bearer ' + accessToken,
},
});

const fileData = await getFileResponse.json();
const previousParents = fileData.parents ? fileData.parents.join(',') : '';

// Move the file to the new folder
await fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?addParents=${folderId}&removeParents=${previousParents}&fields=id, parents`, {
method: 'PATCH',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json',
},
});
}

async function saveNoteToGoogleDoc(content, category) {
try {
// Get the access token
const accessToken = await getAccessToken(true);

// Get or create the category folder
const folderId = await getOrCreateFolder(accessToken, category);

// Create a new Google Doc
const docTitle = `${category} Note - ${new Date().toLocaleDateString()}`;
const createDocResponse = await fetch('https://docs.googleapis.com/v1/documents', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'My Note',
title: docTitle,
}),
});

const doc = await createDocResponse.json();
const documentId = doc.documentId;

// Move the document to the category folder
await moveFileToFolder(accessToken, documentId, folderId);

// Prepare the content with timestamp
const timestamp = new Date().toLocaleString();
const contentWithTimestamp = `Date: ${timestamp}\n\n${content}`;

// Insert text into the new Google Doc
await fetch(`https://docs.googleapis.com/v1/documents/${documentId}:batchUpdate`, {
method: 'POST',
Expand All @@ -106,7 +159,7 @@ async function saveNoteToGoogleDoc(content) {
requests: [
{
insertText: {
text: content,
text: contentWithTimestamp,
location: {
index: 1,
},
Expand All @@ -116,9 +169,9 @@ async function saveNoteToGoogleDoc(content) {
}),
});

alert('Note saved to Google Docs!');
alert('Note saved to Google Docs in category folder!');
} catch (error) {
console.error('Error saving to Google Docs:', error);
alert('Failed to save note to Google Docs.');
}
}
}
5 changes: 3 additions & 2 deletions src/extension/server.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// server.js
const express = require('express');
const cors = require('cors');
const axios = require('axios');
Expand Down Expand Up @@ -28,11 +29,11 @@ app.get('/get-prompt', async (req, res) => {
const prompt = response.data.choices[0].text.trim();
res.json({ prompt });
} catch (error) {
console.error('Error generating AI prompt:', error.response.data);
console.error('Error generating AI prompt:', error.response ? error.response.data : error);
res.status(500).send('Error generating prompt');
}
});

app.listen(3000, () => {
console.log('Backend server running on port 3000');
});
});
68 changes: 39 additions & 29 deletions src/extension/styles.css
Original file line number Diff line number Diff line change
@@ -1,30 +1,40 @@
body {
font-family: Arial, sans-serif;
width: 300px;
padding: 10px;
}

h1 {
text-align: center;
}

#noteArea {
width: 100%;
height: 150px;
margin-top: 10px;
padding: 5px;
box-sizing: border-box;
}

.buttons {
display: flex;
justify-content: space-between;
margin-top: 10px;
}

button {
padding: 10px;
cursor: pointer;
width: 45%;
}

font-family: Arial, sans-serif;
width: 300px;
padding: 10px;
}

h1 {
text-align: center;
}

label {
display: block;
margin-top: 10px;
}

#categorySelect {
width: 100%;
padding: 5px;
margin-bottom: 10px;
}

#noteArea {
width: 100%;
height: 150px;
margin-top: 10px;
padding: 5px;
box-sizing: border-box;
}

.buttons {
display: flex;
justify-content: space-between;
margin-top: 10px;
}

button {
padding: 10px;
cursor: pointer;
width: 45%;
}

0 comments on commit 459241b

Please sign in to comment.