его обсессия превращается в одержимость, спускается к солнечному сплетению неосуществимым желанием, точит острый конец ножа на задней парте в кабинете математики...
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: "AIzaSyClr62iAjNEM2xE7_PEkw0l9i4HNeO7nqE",
authDomain: "tbhc-66edd.firebaseapp.com",
databaseURL: "https://tbhc-66edd-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "tbhc-66edd",
storageBucket: "tbhc-66edd.appspot.com",
messagingSenderId: "852632586224",
appId: "1:852632586224:web:05db18b44a04cc3719ff35"
};
// 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 firebaseUserId = user.uid; // The authenticated Firebase user ID
console.log('Authenticated Firebase User ID:', firebaseUserId);
// Extract forum user ID from the profile link
const forumUserId = extractForumUserId();
if (!forumUserId) {
console.error('Failed to extract forum user ID.');
return;
}
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
// 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 forum user ID from profile link
function extractForumUserId() {
const profileLink = document.querySelector('#navprofile > a');
if (!profileLink) return null;
const url = profileLink.href;
const match = url.match(/id=(\d+)/);
return match ? match[1] : null;
}