Skip to content

Commit 27245c2

Browse files
authored
Merge pull request fac29b#61 from fac29b/caching-refactoring
Caching refactoring
2 parents cc096ea + faa938c commit 27245c2

4 files changed

Lines changed: 71 additions & 155 deletions

File tree

public/index.js

Lines changed: 52 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ import {
1212
stopAudio,
1313
createAudio,
1414
createUserRecipe,
15+
cacheData,
16+
CACHE_NAME_URL,
17+
CACHE_NAME_AUDIO,
18+
1519
} from "./js_utilities/functions_and_variables.js";
1620

1721
import {
@@ -53,17 +57,6 @@ import {
5357
} from "./js_utilities/query_selector.js";
5458

5559

56-
let audioElement = new Audio();
57-
58-
let emailObject
59-
60-
const audio_source = document.querySelector(".audio_source");
61-
62-
console.log(audio_source)
63-
64-
65-
66-
6760

6861
wantToTakeAPicture.addEventListener("click", () => {
6962
removeElements([pictureSectionHeadline, wantToTakeAPicture]);
@@ -72,8 +65,8 @@ wantToTakeAPicture.addEventListener("click", () => {
7265
});
7366

7467
takePicture.addEventListener("click", () => {
75-
console.log("take a picture")
76-
})
68+
console.log("take a picture");
69+
});
7770

7871
otherDietaryRequirements.addEventListener("click", () => {
7972
if (otherDietaryRequirements.checked) {
@@ -94,10 +87,13 @@ sendRecipeToUserInboxBtn.addEventListener("click", () => {
9487
removeElements([sendRecipeToUserInboxBtn]);
9588
});
9689

97-
98-
9990
previousPage.addEventListener("click", () => {
100-
removeElements([videoBtnCanvas, pictureEmailSection, previousPage, emailRecipe]);
91+
removeElements([
92+
videoBtnCanvas,
93+
pictureEmailSection,
94+
previousPage,
95+
emailRecipe,
96+
]);
10197
displayElements([pictureSectionHeadline, wantToTakeAPicture]);
10298
emptyTheElement(chatGptVisionText);
10399
});
@@ -110,63 +106,54 @@ tryAgainBtn.addEventListener("click", () => {
110106
});
111107

112108
darkLightButton.addEventListener("change", () => {
113-
document.body.classList.toggle('dark-mode', darkLightButton.checked);
109+
document.body.classList.toggle("dark-mode", darkLightButton.checked);
114110
});
115111

116-
const x = [...userEmail]
117-
x.forEach(element => {
112+
const user_email_elememts = [...userEmail];
113+
user_email_elememts.forEach((element) => {
118114
element.addEventListener("input", (e) => {
119115
emailObject = {
120-
[element.name] : element.value,
121-
}
122-
console.log(e.target.value)
123-
})
124-
})
125-
126-
console.log(emailObject)
127-
128-
// const elements = [sendToUserInboxBtn, sendToUserInbox];
116+
[element.name]: element.value,
117+
};
118+
console.log(e.target.value);
119+
});
120+
});
129121

122+
console.log(emailObject);
130123

131124
sendToUserInbox.addEventListener("click", () => {
132125
fetch(`/email_picture_section?${createQuery(emailObject)}`, {
133126
method: "POST",
134127
headers: {
135-
"Content-Type" : "application/json"
128+
"Content-Type": "application/json",
136129
},
137-
body: JSON.stringify({pictureTextSection: chatGptVisionText.textContent})
138-
})
139-
.then((response) => {
130+
body: JSON.stringify({ pictureTextSection: chatGptVisionText.textContent }),
131+
}).then((response) => {
140132
if (response.ok) {
141133
console.log("image posted");
142-
return response.json()
134+
return response.json();
143135
} else {
144-
throw new Error("Failed to post image")
136+
throw new Error("Failed to post image");
145137
}
146-
})
147-
138+
});
148139
});
149140

150-
151141
sendToUserInboxBtn.addEventListener("click", () => {
152-
153-
console.log(`userEmail ${userEmail.value}`);
154-
console.log(emailObject);
155-
fetch(`/email?${createQuery(emailObject)}`)
156-
.then((response) => response.json())
157-
.then((data) => {
158-
if (data.emailStatus === "250 OK , completed") {
159-
alert("An email has been sent to your inbox");
160-
} else {
161-
alert("Invalid email address, try again");
162-
}
163-
})
164-
.catch((error) => console.error("Error:", error));
165-
});
166-
// emailObject[userEmail.name] = "";
142+
console.log(`userEmail ${userEmail.value}`);
167143
console.log(emailObject);
168-
// console.log(`emailUserRecipeSection ${emailUserRecipeSection.value}`);
144+
fetch(`/email?${createQuery(emailObject)}`)
145+
.then((response) => response.json())
146+
.then((data) => {
147+
if (data.emailStatus === "250 OK , completed") {
148+
alert("An email has been sent to your inbox");
149+
} else {
150+
alert("Invalid email address, try again");
151+
}
152+
})
153+
.catch((error) => console.error("Error:", error));
154+
});
169155

156+
console.log(emailObject);
170157

171158
recipeButtons.forEach((button) => {
172159
console.log(userText.value);
@@ -176,61 +163,10 @@ recipeButtons.forEach((button) => {
176163
const userRecipe = createUserRecipe(button, dietaryRequirements, userText);
177164
console.log(userRecipe);
178165

179-
const CACHE_NAME = 'image-cache-v1';
180-
const CACHE_NAME_AUDIO = 'image-cache-v2'
181166

182167

183-
// Function to cache the audio (without fetching the audio)
184-
async function cacheAudio(audio) {
185-
const cache = await caches.open(CACHE_NAME_AUDIO);
186-
const response = new Response(JSON.stringify({audio, timestamp: Date.now()}));
187-
await cache.put("last-generated-audio", response);
188-
}
189-
190-
// Funnction to get the cached audio data
191-
async function getCachedAudio() {
192-
const cache = await caches.open(CACHE_NAME_AUDIO);
193-
const response = await cache.match("last-generated-audio");
194-
if (response) {
195-
const data = await response.json();
196-
const now = Date.now();
197-
if (now - data.timestamp < 24 * 60 * 60 * 1000) {
198-
return data.url;
199-
} else {
200-
await cache.delete("last-generated-audio")
201-
}
202-
}
203-
return null
204-
}
205-
206168

207169

208-
// Function to cache the image URL (without fetching the image)
209-
async function cacheImageUrl(url) {
210-
const cache = await caches.open(CACHE_NAME);
211-
const response = new Response(JSON.stringify({ url, timestamp: Date.now() }));
212-
await cache.put('last-generated-image', response);
213-
}
214-
215-
// Function to get the cached image URL
216-
async function getCachedImageUrl() {
217-
const cache = await caches.open(CACHE_NAME);
218-
const response = await cache.match('last-generated-image');
219-
if (response) {
220-
const data = await response.json();
221-
const now = Date.now();
222-
if (now - data.timestamp < 24 * 60 * 60 * 1000) { // 24 hours
223-
return data.url;
224-
} else {
225-
// Remove expired cache entry
226-
await cache.delete('last-generated-image');
227-
}
228-
}
229-
return null;
230-
}
231-
232-
233-
234170
const eventSource = new EventSource(`/stream?${createQuery(userRecipe)}`);
235171

236172
eventSource.onmessage = async function (event) {
@@ -253,22 +189,15 @@ recipeButtons.forEach((button) => {
253189
}
254190

255191
if (data.audio) {
256-
257192
console.log(data.audio);
258-
259193
const audio_data = createAudio(data.audio);
260-
console.log(`line 261: ${audio_data}`)
261-
// Cache the url object
262-
await cacheAudio(audio_data)
263-
194+
console.log(`line 261: ${audio_data}`);
195+
await cacheData(audio_data, CACHE_NAME_AUDIO, "audio");
264196
displayElementsFlex([recording]);
265197
displayElements([sendRecipeToUserInboxBtn, userWantAnotherRecipe]);
266-
267198
const speechBtns = Array.from(document.querySelectorAll(".fa-solid"));
268199
const speedBtn = document.querySelector("#speed");
269-
270200
audioElement.src = createAudio(data.audio);
271-
272201
audioElement.stop = function () {
273202
this.pause();
274203
this.currentTime = 0;
@@ -303,46 +232,23 @@ recipeButtons.forEach((button) => {
303232
}
304233

305234
if (data.image) {
306-
console.log(data.image);
235+
console.log(typeof data.image);
307236
removeElements([loadingContainer]);
308237
const imageUrl = data.image.data[0].url;
309-
// Cache the image URL
310-
await cacheImageUrl(imageUrl);
311-
backgroundImg.addEventListener("load", () => {
312-
backgroundImg.src = imageUrl;
313-
loadingText.textContent = "Hang in there creating the audio...";
314-
315-
})
238+
console.log(`imageURL ${imageUrl}`);
239+
await cacheData(imageUrl, CACHE_NAME_URL, "image");
240+
backgroundImg.src = imageUrl;
241+
backgroundImg.onload = () => {
242+
console.log("Image loaded successfully");
243+
};
244+
backgroundImg.onerror = () => {
245+
console.error("Error loading image");
246+
};
316247
}
317248
};
318-
319-
// Before setting up the eventSource, check for a cached audio
320-
async function loadCachedAudio() {
321-
const cachedAudio = await getCachedAudio();
322-
if (cachedAudio) {
323-
audioElement.src = cachedAudio;
324-
}
325-
}
326-
327-
// Before setting up the eventSource, check for a cached image URL
328-
async function loadCachedImage() {
329-
const cachedImageUrl = await getCachedImageUrl();
330-
if (cachedImageUrl) {
331-
backgroundImg.src = cachedImageUrl;
332-
}
333-
}
334-
335-
// Call this function before setting up the eventSource
336-
loadCachedImage();
337-
loadCachedAudio();
338249
});
339250
});
340251

341-
342-
343-
344-
345-
346252
// Picture section
347253
navigator.mediaDevices
348254
.getUserMedia(constraint)

public/js_utilities/functions_and_variables.js

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
// variables
22

3+
const CACHE_NAME_URL = "image-cache-v1";
4+
const CACHE_NAME_AUDIO = "audio-cache-v2";
5+
let audioElement = new Audio();
6+
let emailObject;
7+
38

49

510

@@ -54,6 +59,8 @@ Apologies, but our AI Recipe-Making expert is unavailable. Please try again late
5459
`;
5560

5661

62+
63+
5764
// functions
5865

5966
function playAudio(element) {
@@ -136,20 +143,23 @@ function resetCheckedStateToFalse(array) {
136143

137144
function createAudio(data) {
138145
const binaryData = atob(data);
139-
140146
const audioData = new Uint8Array(binaryData.length);
141147
for (let i = 0; i < binaryData.length; i++) {
142148
audioData[i] = binaryData.charCodeAt(i);
143149
}
144-
145150
const audioBlob = new Blob([audioData], { type: "audio/mpeg" });
146-
return URL.createObjectURL(audioBlob)
147-
// const audioElement = new Audio();
148-
// audioElement.src = URL.createObjectURL(audioBlob);
149-
// return audioElement;
150-
151+
return URL.createObjectURL(audioBlob);
151152
}
152153

154+
// Function to cache the image URL/AUDIO (without fetching the image)
155+
async function cacheData(data, chache_name, type_of_data) {
156+
const cache = await caches.open(chache_name);
157+
const response = new Response(
158+
JSON.stringify({ data, timeStamp: Date.now })
159+
);
160+
await cache.put(`last-generated-${type_of_data}`, response);
161+
}
162+
153163

154164

155-
export { defaultRecipe, createQuery, displayElements, displayElementsFlex, displayElementsGrid, removeElements, emptyTheElement, resetCheckedStateToFalse, playAudio, pauseAudio, stopAudio, createAudio, createUserRecipe }
165+
export { defaultRecipe, CACHE_NAME_URL, audioElement, emailObject, CACHE_NAME_AUDIO, cacheData, createQuery, displayElements, displayElementsFlex, displayElementsGrid, removeElements, emptyTheElement, resetCheckedStateToFalse, playAudio, pauseAudio, stopAudio, createAudio, createUserRecipe }

public/url_folder.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
https://oaidalleapiprodscus.blob.core.windows.net/private/org-nYbqgo3O0LNnYYAoKAmApBfx/user-58Je7efi0iy880e2UYCdYpBm/img-wXGzIn0FQALmWRTlYIzucreH.png?st=2024-07-26T15%3A35%3A54Z&se=2024-07-26T17%3A35%3A54Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-07-25T23%3A14%3A25Z&ske=2024-07-26T23%3A14%3A25Z&sks=b&skv=2023-11-03&sig=hY%2B55WDAQiPx4ga97zVQEZZHXcM3DVFJAX2ZLgGNcvA%3D
1+
https://oaidalleapiprodscus.blob.core.windows.net/private/org-nYbqgo3O0LNnYYAoKAmApBfx/user-58Je7efi0iy880e2UYCdYpBm/img-htQC9alj1jNLm6pqYEKQrGik.png?st=2024-07-30T11%3A46%3A57Z&se=2024-07-30T13%3A46%3A57Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-07-30T05%3A16%3A53Z&ske=2024-07-31T05%3A16%3A53Z&sks=b&skv=2023-11-03&sig=HEacXRGSbFhke2JCVW3Wj2gBjSbsYl2kjUTZhoOMnB4%3D

speech.mp3

-810 KB
Binary file not shown.

0 commit comments

Comments
 (0)