Skip to content

P #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

P #2

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions entry/authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Initialize Spotify client details
const SPOTIFY_CLIENT_ID = 'your-client-id'; // Your Spotify Client ID
const SPOTIFY_CLIENT_SECRET = 'your-client-secret'; // Your Spotify Client Secret
const SPOTIFY_REDIRECT_URI = 'your-redirect-uri'; // Redirect URI you set in the Spotify Developer Dashboard
const SPOTIFY_AUTH_URL = `https://accounts.spotify.com/authorize?response_type=code&client_id=${SPOTIFY_CLIENT_ID}&redirect_uri=${encodeURIComponent(SPOTIFY_REDIRECT_URI)}&scope=playlist-read-private user-library-read`;

// Function to handle authentication
function authenticateSpotify() {
const authUrl = SPOTIFY_AUTH_URL;
window.location.href = authUrl;
}

// Get the authorization code from the URL
function getSpotifyAuthCode() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('code');
}

// Exchange the authorization code for an access token
async function exchangeSpotifyAuthCodeForToken(code) {
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(SPOTIFY_CLIENT_ID + ':' + SPOTIFY_CLIENT_SECRET),
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `grant_type=authorization_code&code=${code}&redirect_uri=${encodeURIComponent(SPOTIFY_REDIRECT_URI)}`
});

const data = await response.json();
return data.access_token;
}

// Fetch Spotify playlists
async function fetchSpotifyPlaylists() {
const accessToken = localStorage.getItem('spotify_access_token');
if (!accessToken) {
alert('Spotify access token not found.');
return;
}

const response = await fetch('https://api.spotify.com/v1/me/playlists', {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`
}
});

const data = await response.json();
console.log(data); // Log playlists or display them in your app
}
function checkApiKey() {
const key = localStorage.getItem("openai_api_key");
apiKeyModal.style.display = key ? "none" : "flex"; // Shows the modal if no API key is stored
}

// Check if the user is authenticated
function checkSpotifyAuth() {
const code = getSpotifyAuthCode();
if (code) {
exchangeSpotifyAuthCodeForToken(code).then(accessToken => {
localStorage.setItem('spotify_access_token', accessToken);
fetchSpotifyPlaylists();
});
}
}

// Handle the authentication process when the page loads
document.addEventListener('DOMContentLoaded', () => {
checkSpotifyAuth();

});
17 changes: 9 additions & 8 deletions entry/entry.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,13 @@
</head>
<body>

<div id="apiKeyModal">
<div id="apiKeyModalContent">
<h3>Enter your OpenAI API Key</h3>
<input type="password" id="apiKeyInput" placeholder="sk-..." />
<button id="saveApiKeyBtn">Save API Key</button>
</div>
</div>

<div class="phone-frame">
<div class="top-bar">
<img src="images/arrow-left.svg" alt="Back" class="icon" id="backIcon" />
<img src="images/attachment-01.svg" alt="Attachment" class="icon" id="attachmentIcon" />
</div>


<div class="content">
<div class="journal-title">
This is a journal about my life
Expand All @@ -40,6 +33,14 @@ <h3>Enter your OpenAI API Key</h3>
</div>
</div>

<div id="spotifyLoginModal" class="modal">
<div class="modal-content">
<h2>Please log in to Spotify</h2>
<button id="spotifyLoginBtn">Log in to Spotify</button>
</div>
</div>


<input type="file" id="fileInput" accept="image/*,.pdf,.doc,.docx" />

<script src="script.js"></script>
Expand Down
113 changes: 97 additions & 16 deletions entry/script.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,99 @@
// Spotify Authentication
const spotifyLoginBtn = document.getElementById("spotifyLoginBtn");
const spotifyLoginModal = document.getElementById("spotifyLoginModal");

// Check if the user is already logged in
function checkSpotifyLogin() {
const spotifyAuthToken = localStorage.getItem("spotifyAuthToken");
if (spotifyAuthToken) {
// Hide the login modal if user is already logged in
spotifyLoginModal.style.display = "none";
} else {
// Show the login modal if user is not logged in
spotifyLoginModal.style.display = "flex";
}
}

// Get the Spotify authorization URL for OAuth login
function getSpotifyAuthUrl() {
const clientId = localStorage.getItem("spotifyClientId");
const redirectUri = encodeURIComponent(window.location.href); // Redirect back to the same page

// Return the Spotify OAuth authorization URL
return `https://accounts.spotify.com/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=playlist-read-private%20user-read-private`;
}

// Check for the authorization code in the URL (Spotify redirects here after login)
function checkSpotifyAuthCode() {
const urlParams = new URLSearchParams(window.location.search);
const authCode = urlParams.get("code");

if (authCode) {
exchangeAuthCodeForToken(authCode);
}
}

// Exchange the authorization code for an access token
async function exchangeAuthCodeForToken(authCode) {
const clientId = localStorage.getItem("spotifyClientId");
const clientSecret = localStorage.getItem("spotifyClientSecret");
const redirectUri = encodeURIComponent(window.location.href);

const authHeader = btoa(`${clientId}:${clientSecret}`);

try {
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Authorization": `Basic ${authHeader}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: `grant_type=authorization_code&code=${authCode}&redirect_uri=${redirectUri}`,
});

const data = await response.json();
const accessToken = data.access_token;

if (accessToken) {
// Store the Spotify access token
localStorage.setItem("spotifyAuthToken", accessToken);
alert("Successfully logged in to Spotify!");
spotifyLoginModal.style.display = "none"; // Hide login modal
} else {
alert("Failed to authenticate with Spotify.");
}
} catch (error) {
console.error("Spotify authentication error:", error);
alert("Error during Spotify authentication.");
}
}

// Handle Spotify Login button click
spotifyLoginBtn.addEventListener("click", () => {
const clientId = localStorage.getItem("spotifyClientId");

if (!clientId) {
alert("Please enter your Spotify credentials first.");
return;
}

// Redirect to Spotify login page for OAuth authentication
const authUrl = getSpotifyAuthUrl();
window.location.href = authUrl;
});

// On page load, check if the user is logged in or has an auth code
document.addEventListener("DOMContentLoaded", () => {
checkSpotifyLogin(); // Check if the user is already logged in to Spotify
checkSpotifyAuthCode(); // Check if there's an auth code in the URL
});

// --- OpenAI API Key Modal Handling ---
const apiKeyModal = document.getElementById("apiKeyModal");
const apiKeyInput = document.getElementById("apiKeyInput");
const saveApiKeyBtn = document.getElementById("saveApiKeyBtn");

// Check if API Key is stored
function checkApiKey() {
const key = localStorage.getItem("openai_api_key");
if (!key) {
Expand All @@ -11,6 +103,7 @@ function checkApiKey() {
}
}

// Save API Key to LocalStorage
saveApiKeyBtn.addEventListener("click", () => {
const key = apiKeyInput.value.trim();
if (!key) {
Expand Down Expand Up @@ -53,6 +146,7 @@ async function callOpenAI(messages) {
}
}

// --- Date & Attachment Handling ---
const dateField = document.getElementById("dateField");
const attachmentIcon = document.getElementById("attachmentIcon");
const fileInput = document.getElementById("fileInput");
Expand All @@ -67,8 +161,8 @@ function setCurrentDate() {
const day = String(now.getDate()).padStart(2, "0");
const year = now.getFullYear();
const monthNames = [
"January","February","March","April","May","June",
"July","August","September","October","November","December"
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const monthName = monthNames[now.getMonth()];
dateField.textContent = `Date: ${monthName} ${day}, ${year}`;
Expand All @@ -95,20 +189,7 @@ fileInput.addEventListener("change", () => {
reader.readAsDataURL(file);
});

document.addEventListener("DOMContentLoaded", () => {
checkApiKey();
setCurrentDate();
const storedAttachment = localStorage.getItem("attachment");
if (storedAttachment) {
attachmentPreview.innerHTML = `<img src="${storedAttachment}" alt="Attachment preview" />`;
}
});

// --------------------------
// AI Buttons
// --------------------------

// Finish with feedback button
// --- AI Feedback & Rephrasing ---
feedbackBtn.addEventListener("click", async () => {
const text = journalText.value.trim();
if (!text) {
Expand Down