-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
167 lines (143 loc) · 5.02 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Firebase imports
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js";
import { getFirestore, collection, addDoc, getDocs, deleteDoc, doc } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js";
import { getStorage, ref, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-storage.js";
// Firebase configuration and initialization
const firebaseConfig = {
apiKey: "AIzaSyBVh0DfMKE1IKTMadyTLO_c54Y6o5BCnTY",
authDomain: "liebe-f332d.firebaseapp.com",
projectId: "liebe-f332d",
storageBucket: "liebe-f332d.appspot.com",
messagingSenderId: "199124008155",
appId: "1:199124008155:web:04f7f5582811693fdda0fe",
measurementId: "G-TE1VF9N946"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const storage = getStorage(app);
// Function to prompt for a username once and store it in localStorage
function getOrCreateUsername() {
let username = localStorage.getItem("username");
if (!username) {
username = prompt("Enter your username:");
if (username) localStorage.setItem("username", username);
}
return username;
}
// Function to create a new post
async function createPost() {
const postContent = document.getElementById("postContent").value;
const imageUpload = document.getElementById("imageUpload");
const imageFile = imageUpload.files[0];
const username = getOrCreateUsername();
const userID = localStorage.getItem("userID");
if (!postContent.trim()) {
alert("Post content cannot be empty.");
return;
}
const newPost = {
content: postContent,
timestamp: new Date(),
author: username,
userID: userID,
};
// Handle image upload if a file is provided
if (imageFile) {
const imageUrl = await uploadImage(imageFile);
newPost.imageUrl = imageUrl;
}
await savePostToDatabase(newPost);
loadPosts(); // Reload posts to show the new one
document.getElementById("postContent").value = "";
document.getElementById("imageUpload").value = "";
}
// Function to upload image to Firebase Storage
async function uploadImage(file) {
const storageRef = ref(storage, `images/${file.name}`);
await uploadBytes(storageRef, file);
return await getDownloadURL(storageRef);
}
// Function to save post to Firestore
async function savePostToDatabase(post) {
try {
await addDoc(collection(db, "posts"), post);
console.log("Post added successfully");
} catch (error) {
console.error("Error adding post:", error);
}
}
// Function to load posts from Firestore
async function loadPosts() {
const currentUserID = localStorage.getItem("userID");
const querySnapshot = await getDocs(collection(db, "posts"));
const postsContainer = document.getElementById("postsContainer");
postsContainer.innerHTML = "";
querySnapshot.forEach((doc) => {
const post = { id: doc.id, ...doc.data() };
if (post.userID === currentUserID) {
displayPost(post);
}
});
}
// Function to display a post in the DOM
function displayPost(post) {
const postElement = document.createElement("div");
postElement.classList.add("post");
let formattedDate;
if (post.timestamp && post.timestamp.toDate) {
const date = post.timestamp.toDate();
formattedDate = date.toLocaleString('de-DE', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
}).replace("GMT", "um");
} else {
formattedDate = "Datum nicht verfügbar";
}
let postHTML = `
<h3>${post.author} (UserID: ${post.userID})</h3>
<p class="timestamp">${formattedDate}</p>
<p>${post.content}</p>
`;
if (post.imageUrl) {
postHTML += `<img src="${post.imageUrl}" alt="Post Image" style="max-width: 100%; height: auto; margin-top: 10px;">`;
}
postHTML += `<button class="button deleteButton" data-id="${post.id}">Löschen</button>`;
postElement.innerHTML = postHTML;
document.getElementById("postsContainer").appendChild(postElement);
const deleteButton = postElement.querySelector(".deleteButton");
if (deleteButton) {
deleteButton.addEventListener("click", () => {
const confirmDelete = confirm("Do you really want to delete the post?");
if (confirmDelete) {
deletePost(post.id);
}
});
}
}
// Function to delete a post from Firestore
async function deletePost(postId) {
try {
const postRef = doc(db, "posts", postId);
await deleteDoc(postRef);
alert("Post erfolgreich gelöscht.");
loadPosts();
} catch (error) {
console.error("Error deleting post:", error);
alert("Ein Fehler ist beim Löschen des Beitrags aufgetreten.");
}
}
// Generate a unique user ID once if not present
if (!localStorage.getItem("userID")) {
const userID = 'user_' + Math.random().toString(36).substr(2, 9);
localStorage.setItem("userID", userID);
}
// Event listener for the Post button
document.getElementById("postButton").addEventListener("click", createPost);
// Load posts when the page is loaded
window.onload = loadPosts;