она видит её, но не может разглядеть — из этого хронического парадокса, следующего по пятам напоминанием, шен сяотин сплетает для себя кокон для мертворожденной бабочки и занимает его, проибрается в него, ломая когти, возводит короной на голову мантру.
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.5/firebase-app.js";
import { getDatabase, ref, set, get } from "https://www.gstatic.com/firebasejs/10.12.5/firebase-database.js";
import { getAuth, signInAnonymously, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/10.12.5/firebase-auth.js";
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyBeWQX4IQ8rWUNrrtn-J8iu3DFp2mrOH_s",
authDomain: "tbhc-test.firebaseapp.com",
projectId: "tbhc-test",
storageBucket: "tbhc-test.appspot.com",
messagingSenderId: "437889092351",
appId: "1:437889092351:web:4aee82e49a2520e43e9aca",
databaseURL: "https://tbhc-test-default-rtdb.europe-west1.firebasedatabase.app/"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
// Cache for liked posts
const localCache = {};
// Sign in anonymously
signInAnonymously(auth)
.then(() => {
console.log('User signed in anonymously');
})
.catch((error) => {
console.error('Error signing in anonymously:', error);
});
// Handle authentication state
onAuthStateChanged(auth, (user) => {
if (user) {
const userId = user.uid; // The authenticated user ID
console.log('Authenticated User ID:', userId);
const forumUserId = userId; // Use the authenticated user's ID as the forumUserId
console.log('Forum User ID:', forumUserId);
const userLikesRef = ref(db, `likes/${forumUserId}`);
console.log('Firebase path:', userLikesRef.toString());
get(userLikesRef).then((snapshot) => {
localCache[forumUserId] = snapshot.val() || {};
document.querySelectorAll('div[id^="p"][data-posted][data-user-id][data-group-id]').forEach(function(post) {
const postId = post.id.replace('p', '');
const icon = post.querySelector('div.post-body > div.post-box > div.post-rating > p > a');
const postAuthorId = post.getAttribute('data-user-id'); // Assuming post author ID is stored here
console.error(postAuthorId);
// Initialize icon classes based on current state
if (icon) {
updateIconClasses(postId, icon, localCache[forumUserId]);
}
// Listen for like button clicks
if (icon) {
icon.addEventListener('click', function() {
if (postAuthorId !== forumUserId) {
if (!localCache[forumUserId][postId]) {
// Like the post (if not already liked)
localCache[forumUserId][postId] = true;
// Optimistically update UI
if (icon) {
updateIconClasses(postId, icon, localCache[forumUserId]);
}
// Save the like action to Firebase
const postRef = ref(db, `likes/${forumUserId}/${postId}`);
set(postRef, true)
.catch((error) => {
console.error('Error updating like action:', error);
});
}
} else {
console.warn('User cannot like their own post.');
}
});
// MutationObserver to detect changes in the like count
let previousLikeCount = parseInt(icon.textContent, 10);
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
const newLikeCount = parseInt(icon.textContent, 10);
// Check if the like count has increased
if (newLikeCount > previousLikeCount) {
// Update the local cache to reflect the new liked state
localCache[forumUserId][postId] = true;
// Handle the like count change by updating the icon
updateIconClasses(postId, icon, localCache[forumUserId]);
// Save the like action to Firebase if it's not already there
const postRef = ref(db, `likes/${forumUserId}/${postId}`);
set(postRef, true)
.then(() => {
console.log('Like action saved to Firebase due to observed change.');
})
.catch((error) => {
console.error('Error updating like action from MutationObserver:', error);
});
}
// Update previous like count
previousLikeCount = newLikeCount;
}
});
});
// Observe the like element for changes in its child nodes (text content)
observer.observe(icon, {
childList: true, // Monitor changes in the text content
});
}
});
}).catch((error) => {
console.error('Error fetching liked posts:', error);
});
} else {
console.error('No user is signed in.');
}
});
// Function to update icon classes based on user interactions
function updateIconClasses(postId, icon, likedPosts) {
if (likedPosts[postId]) {
icon.classList.add('noNullLiked');
} else {
icon.classList.remove('noNullLiked');
}
}
// Function to extract user ID from a URL
function extractUserId(url) {
// Extract numeric ID from URL using regex
const match = url ? url.match(/id=(\d+)/) : null;
return match ? match[1] : null;
}