Skip to content

Commit

Permalink
Merge pull request #20 from AvocadoSteam/ben
Browse files Browse the repository at this point in the history
1.0 - Website Complete
  • Loading branch information
Delaney authored Aug 7, 2023
2 parents a3cdc9b + a176b31 commit 56e53be
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 77 deletions.
2 changes: 1 addition & 1 deletion comments.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"comments":[{"image_id":"2","name":"ben","text":"hii"}]}
{"comments":[{"image_id":"1","name":"ben","text":"hello"}]}
2 changes: 1 addition & 1 deletion homepage.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ <h1 id="homepage" style="font-size:32px">Image Board</h1>

<div id="topic-selection" class="navbar" style="margin-top:-2px;padding-top:15px;border-top:none;padding-left:6px;font-size:20px;">
<input type="button" id="lookup-button" value="Search" style="font-size:20px">
<input type="text" name="Topic" id="topic-id-selection" placeholder="Enter tags separated by commas" style="font-size:20px;width:40%;">
<input type="text" name="Topic" id="topic-id-selection" placeholder="Enter tags separated by spaces" style="font-size:20px;width:40%;">
</div>

<div class="navbar" style="margin-top:-2px;padding-top:15px;border-top:none;padding-left:6px;font-size:20px;">
Expand Down
5 changes: 1 addition & 4 deletions homepage.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
"use strict";

$(document).ready(async () => {
sessionStorage.setItem("add_image", "true");
// Creates a cookie to let view_image know which image_id is being accessed
$("#image_id_button").click( async () => {
//const image_id = $("#image_id_text").val();
sessionStorage.setItem("image_id", $("#image_id_text").val())
//document.cookie = `image_id=${image_id}; max-age=7200; path=/`; // establishes the image that should be loaded
location.replace('view_image.html');
});
$("#lookup-button").click( async () => {
const tags = $("#topic-id-selection").val().split(" ");
//const tagsAsCookie = JSON.stringify(tags.split(","));
const filteredTags = tags.map(tag => tag.trim().toLowerCase());
sessionStorage.setItem("tags", JSON.stringify(filteredTags));
//document.cookie = `tags=${tagsAsCookie}; max-age=7200; path=/`; // establishes the image that should be loaded
location.replace('image_list.html');
})
});
14 changes: 14 additions & 0 deletions image_list.css
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ html, body {
border: 2px solid navy;
padding: 4px;
margin-top: -2px;
overflow-y: scroll; height:900px;
}

img {
Expand All @@ -46,6 +47,18 @@ img {
overflow: auto;
position: relative;
cursor: pointer;
}
.add_image_popup {

}
.add_image_container {

}
#image_path {

}
#add_image {

}
#search_for_tags {

Expand All @@ -56,3 +69,4 @@ img {
#search_criteria {

}

7 changes: 6 additions & 1 deletion image_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@
<!-- Returns to previous page -->
<button onClick="location.replace('homepage.html');" class="navbar_content" >Go Back</button>
<input type="button" id="lookup-button" value="Search" class="navbar_content"> <!-- Calls a search on all user entered tags -->
<input type="text" name="Topic" id="topic-id-selection" placeholder="Enter tags separated by commas" class="navbar_content"style="width:40%;"> <!-- Add to user tags when enter is clicked -->
<input type="text" name="Topic" id="topic-id-selection" placeholder="Enter tags separated by spaces" class="navbar_content"style="width:25%;"> <!-- Add to user tags when enter is clicked -->
<!-- List of user entered tags -->
<p class="navbar_content" id="search_criteria"></p>
<form action="" method="GET" style="float:right;">
<input type="text" class="navbar_content" placeholder="Enter image link..." id="image_link">
<input type="text" class="navbar_content" placeholder="Enter tags..." id="image_tags">
<input type="button" class="navbar_content" value="Add Image" id="add_image">
</form>
</div>

<div class="main_area">
Expand Down
69 changes: 62 additions & 7 deletions image_list.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const loadAllImages = async () => {

let count = 0;
for (const img of images) {
console.log(images.length - 1)
console.log(img.id);
// Check if the image matches the search criteria (tagsToSearch)
if (doesImageMatchSearch(img.tags, tagsToSearch)) {
if (count === 0) {
Expand All @@ -24,7 +26,8 @@ const loadAllImages = async () => {
$("#three").append(`<img class="image_content" src="${img.path}" id="${img.id}">`);
count = 0;
}
} else if (sessionStorage.getItem("tags") == '[""]' || sessionStorage.getItem("tags") == null) {
}
else if (sessionStorage.getItem("tags") == '[""]' || sessionStorage.getItem("tags") == null) {
if (count == 0) {
$("#one").append(`<img class="image_content" src="${img.path}" id="${img.id}">`);
count++;
Expand All @@ -36,15 +39,53 @@ const loadAllImages = async () => {
count = 0;
}
}
if (img.id == images.length) {
sessionStorage.setItem("largest_id", img.id);
}
}
}else {
} else {
console.error("Failed to fetch images:", response.status);
}
} catch (error) {
console.log("Error retrieving images: ", error);
console.error("Error retrieving images: ", error);
}
};

const addNewImage = async (path, tags) => {
let new_id;
if (isNaN(parseInt(sessionStorage.getItem("largest_id")))) {
sessionStorage.setItem("largest_id", "1")
new_id = parseInt(sessionStorage.getItem("largest_id"))
}
else {
new_id = parseInt(sessionStorage.getItem("largest_id")) + 1
}

const bodyContents = JSON.stringify({
"id": '' + new_id,
"path": path,
"tags": tags.split(" ") // Convert the tags string to an array of tags
});

try {
const response = await fetch("add_image", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: bodyContents
});

// Check if the image was successfully added
response.ok ? await loadAllImages() : console.error("Failed to add image: ", response.status);

} catch (error) {
console.error("Error adding new image: ", error);
}
};


const getTagsFromStorage = () => {
const tags = sessionStorage.getItem("tags");
return tags ? JSON.parse(tags) : [];
Expand All @@ -57,7 +98,8 @@ const doesImageMatchSearch = (imageTags, searchTags) => {
searchTags.forEach(tag => {
if (tag.startsWith("-")) {
excludedTags.push(tag.substring(1));
} else {
}
else {
includedTags.push(tag);
}
});
Expand All @@ -80,14 +122,27 @@ $("#lookup-button").click(async () => {
});

$(document).ready(async () => {
await loadAllImages();
const tagsToSearch = getTagsFromStorage().join(", ");
$("#search_criteria").append(`<b>Tags:</b> <i>${tagsToSearch}</i>`);

$(".image_content").click(async (e) => {
$("#add_image").click(async () => {
// Opens a window
try {
const image_link = $("#image_link").val();
const image_tags = $("#image_tags").val();
await addNewImage(image_link, image_tags);
await location.reload();
}
catch (error) {
console.error("Image failed to post: ", error);
}
});

$(".main_area").on("click",".image_content",async (e) => {
let image_id = e.target.id;
sessionStorage.clear();
sessionStorage.setItem("image_id", image_id);
location.replace("view_image.html");
})
});
await loadAllImages();
});
46 changes: 1 addition & 45 deletions images.json
Original file line number Diff line number Diff line change
@@ -1,45 +1 @@
{
"images":
[
{
"id" : 1,
"path" : "https://rb.gy/1w97z",
"tags": ["cat"]
},
{
"id" : 2,
"path" : "https://th.bing.com/th?id=OIP.JdjSF7yPa2PodsGvlG0RCQHaE6&w=306&h=203&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2",
"tags": ["cat", "animal"]
},
{
"id" : 3,
"path" : "https://th.bing.com/th/id/OIP.th5M_XAZwlYVpYLHWkJD0wHaE8?w=300&h=200&c=7&r=0&o=5&pid=1.7",
"tags": ["computer", "technology", "pc", "monitor"]
},
{
"id" : 4,
"path" : "https://th.bing.com/th/id/R.8c5650a2070648d9dc695b8f4a027671?rik=RbVtbe892imZEA&pid=ImgRaw&r=0",
"tags": ["dog", "animal"]
},
{
"id" : 5,
"path" : "https://th.bing.com/th/id/OIP.jjJ3IB_Otr3OBm_fgstjVAHaEo?pid=ImgDet&rs=1",
"tags": ["dog", "animal"]
},
{
"id" : 6,
"path" : "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKLWqF7QIhcZOYH-e37DgvCYZJpxaclzZYOVFQ0lsRBBCVUyPF3fXR4EnolFg0QMC5qho&usqp=CAU",
"tags": ["computer", "technology", "monitor"]
},
{
"id" : 7,
"path" : "https://www.ctvnews.ca/polopoly_fs/1.6126898.1666833185!/httpImage/image.jpeg_gen/derivatives/landscape_620/image.jpeg",
"tags": ["computer", "technology", "monitor"]
},
{
"id" : 8,
"path" : "https://img.freepik.com/free-vector/set-wild-animals_1308-29055.jpg?w=2000",
"tags": ["animal"]
}
]
}
{"images":[{"id":"1","path":"https://tinyurl.com/c00lguysdontlookatexplosions","tags":["psy","gangnam","explosion","style"]},{"id":"2","path":"https://www.purina.co.uk/sites/default/files/2020-12/Dog_1098119012_Teaser.jpg","tags":["dog","cool","rottweiler"]},{"id":"3","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ8D-G0b8ka5kyWMioBDY98SOJCYt8Xy7kklA&usqp=CAU","tags":["cute","dog","small"]},{"id":"4","path":"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg","tags":["cat","orange","cute"]},{"id":"5","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGirHEBLmYx44RUZrgtvwReDdxdQU1WojlLQ&usqp=CAU","tags":["cat","tabby","cute","grey"]},{"id":"6","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRE5wkc0OMXsy3CMnmKoKiAlPGZYKVI-IYUqQ&usqp=CAU","tags":["cat","black","cute"]},{"id":"7","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTLIHb2tvkwV-te8nsMUhidX2A8eHgHQfmWkA&usqp=CAU","tags":["computer","laptop"]},{"id":"8","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRn2thLOwkJYSRRNRIJLpyNx1MKGQVS_SuvsA&usqp=CAU","tags":["computer","monitor","keyboard","mouse","plant","desktop"]},{"id":"9","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTVafb-2UxnbY-OpeXoMM62h00b-hUQ48Yjzg&usqp=CAU","tags":["laughing","old"]},{"id":"10","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTN_fUPo4tc3Clb_DrrASlL-ySGXBCWBSq96A&usqp=CAU","tags":["eating","steak"]},{"id":"11","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSOxATK11VrvJQMO5G4dwTtn2DOZlnLFsCIbw&usqp=CAU","tags":["basketball","sport","group"]},{"id":"12","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDFoC5GGwguX1GX880U1ditMTICbpOJa0kMA&usqp=CAU","tags":["basketball","floor"]},{"id":"13","path":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSm8Qhby6sWwbNoI1E_u-FhWAjeh-oEUm4WWw&usqp=CAU","tags":["basketball","holding","red","white"]}]}
13 changes: 2 additions & 11 deletions view_image.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,7 @@ const makePost = async (name, contents) => {
method: "POST",
body: bodyContents
});

if (response.ok) {
// If the response is successful, refresh the comments section to display the updated comments
await refreshComments();
} else {
// Handle errors if the response is not successful
console.error("Failed to post comment:", response.status);
}
response.ok ? await refreshComments() : console.error("Failed to post comment:", response.status);
} catch (error) {
// Handle any other errors that may occur during the POST request
console.error("Error occurred while posting comment:", error);
Expand Down Expand Up @@ -55,7 +48,6 @@ const refreshComments = async () => {
if (commentObj.image_id == sessionStorage.getItem("image_id")) {
$(".comments").append(`<p style="font-size:20px;"><b>${commentObj.name}:</b> ${commentObj.text}</p>`);
}
//$("<p>").text("<b>" + commentObj.name + ":</b>" + commentObj.text).appendTo('.comments');
}
} else {
console.error("Failed to fetch comments:", response.status);
Expand Down Expand Up @@ -105,11 +97,10 @@ $("#post-comment-button").click(async () => {

$("#lookup-button").click( async () => {
const tags = $("#topic-id-selection").val().split(" ");
//const tagsAsCookie = JSON.stringify(tags.split(","));
const filteredTags = tags.map(tag => tag.trim().toLowerCase());

sessionStorage.setItem("tags", JSON.stringify(filteredTags));
//document.cookie = `tags=${tagsAsCookie}; max-age=7200; path=/`; // establishes the image that should be loaded
// establishes the image that should be loaded
location.replace('image_list.html');
})

Expand Down
55 changes: 48 additions & 7 deletions webserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,29 @@ const getImages = async () => {
const content = await fs.readFile("images.json");
return JSON.parse(content);
} catch (error) {
console.error("Error reading comments:", error);
console.error("Error getting Images:", error);
return { images: [] };
}
}

const addImage = async (image_data) => {
try {
const { images } = await getImages(); // Read the existing images from the file
images.push(image_data); // Add the new image data to the existing images
await saveImages(images); // Save the updated images to the file
} catch (error) {
console.error("Error adding image: ", error);
}
}

const saveImages = async (images) => {
try {
await fs.writeFile("images.json", JSON.stringify({ images }));
} catch (error) {
console.error("Error saving images:", error);
}
}

http.createServer(async (req, res) => {
await createCommentsFileIfNotExists();

Expand Down Expand Up @@ -97,26 +115,20 @@ http.createServer(async (req, res) => {
// POST COMMENTS
if (req.method === "POST" && p[1] === "view_image.js") {
let body = "";

req.on("data", (chunk) => {
body += chunk;
});

req.on("end", async () => {
try {
const postData = JSON.parse(body);

// https://developer.mozilla.org/en-US/docs/web/api/document/cookie
const id = postData.image_id;
const userName = postData.name;
const comment = postData.contents;

const { comments } = await getComments();

comments.push({ image_id: id, name: userName, text: comment });

console.log(comments);

await saveComments(comments);

res.writeHead(200, { "Content-Type": "application/json" });
Expand All @@ -128,6 +140,35 @@ http.createServer(async (req, res) => {
}
});
}

// POST IMAGE
if (req.method === "POST" && p[1] === "add_image") {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", async () => {
try {
const imageData = JSON.parse(body);
const image_id = imageData.id;
const link = imageData.path;
const image_tags = imageData.tags;
console.log(imageData);

const newImageData = { id: image_id, path: link, tags: image_tags };

await addImage(newImageData); // Call the function with the new image data

res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "success", message: "Image added successfully" }));

} catch (error) {
console.error("Error occurred while processing POST request:", error);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "error", message: "Internal server error" }));
}
});
}
}).listen(8080, () => {
console.log("Server running on http://localhost:8080/");
});

0 comments on commit 56e53be

Please sign in to comment.