Spaces:
Sleeping
Sleeping
File size: 16,997 Bytes
8df51fe b63786a 8df51fe b63786a 8df51fe b63786a 4c888b7 b63786a ad2d8ba 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a 4c888b7 b63786a | 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 | const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { normalizeId, normalizeIdList, serializeUser } = require('../utils/userSerializer');
const { getContactFromIdentifier, normalizeEmail, normalizePhone } = require('../utils/validators');
const {
DEFAULT_STARTING_TOKENS,
ensureUserTokenState,
normalizeReferralCode,
} = require('../utils/tokenUtils');
// Use /data directory for persistent storage in production, local path for dev
const isProduction = process.env.NODE_ENV === 'production';
const STORE_FILE_PATH = isProduction
? path.join('/data', 'memory-store.json')
: path.join(__dirname, 'memory-store.json');
const state = {
users: [],
images: [],
galleryPosts: [],
};
const generateId = () => crypto.randomUUID();
const normalizeComment = (comment = {}) => ({
_id: String(comment._id || generateId()),
userId: normalizeId(comment.userId),
username: String(comment.username || '').trim(),
userAvatarUrl: String(comment.userAvatarUrl || '').trim(),
content: String(comment.content || '').trim().slice(0, 500),
createdAt: comment.createdAt || new Date().toISOString(),
});
const normalizeGalleryPost = (post = {}) => ({
...post,
likedBy: normalizeIdList(post.likedBy || post.likedByUserIds),
shareCount: Number(post.shareCount || 0),
authorFollowersCount: Number(post.authorFollowersCount || 0),
comments: Array.isArray(post.comments)
? post.comments.map(normalizeComment).filter((comment) => comment.userId && comment.content)
: [],
});
const loadStore = () => {
try {
if (!fs.existsSync(STORE_FILE_PATH)) {
return;
}
const rawStore = fs.readFileSync(STORE_FILE_PATH, 'utf8');
if (!rawStore.trim()) {
return;
}
const parsedStore = JSON.parse(rawStore);
state.users = Array.isArray(parsedStore.users)
? parsedStore.users.map((user) => ({
...user,
email: user.email ? normalizeEmail(user.email) : undefined,
phone: user.phone ? normalizePhone(user.phone) : undefined,
followers: normalizeIdList(user.followers || user.followerUserIds),
following: normalizeIdList(user.following || user.followingUserIds),
tokenBalance: Number.isFinite(Number(user.tokenBalance)) ? Number(user.tokenBalance) : DEFAULT_STARTING_TOKENS,
referralCode: normalizeReferralCode(user.referralCode),
referredByUserId: normalizeId(user.referredByUserId),
rewardedLikePostIds: normalizeIdList(user.rewardedLikePostIds),
rewardedFollowUserIds: normalizeIdList(user.rewardedFollowUserIds),
tokenHistory: Array.isArray(user.tokenHistory) ? user.tokenHistory : [],
}))
.map((user) => ensureUserTokenState(user))
: [];
state.images = Array.isArray(parsedStore.images) ? parsedStore.images : [];
state.galleryPosts = Array.isArray(parsedStore.galleryPosts)
? parsedStore.galleryPosts.map((post) => normalizeGalleryPost(post))
: [];
} catch (error) {
console.error('Could not load persistent fallback store:', error.message);
}
};
const saveStore = () => {
try {
fs.writeFileSync(
STORE_FILE_PATH,
JSON.stringify(
{
users: state.users,
images: state.images,
galleryPosts: state.galleryPosts,
},
null,
2
),
'utf8'
);
} catch (error) {
console.error('Could not save persistent fallback store:', error.message);
}
};
loadStore();
const sanitizeUser = (user) => {
if (!user) return null;
ensureUserTokenState(user);
return serializeUser(user);
};
const syncGalleryPostsForUser = (userId, updates = {}) => {
state.galleryPosts = state.galleryPosts.map((post) =>
post.userId === userId
? {
...post,
...updates,
}
: post
);
};
const syncGalleryPostsForAuthorFollowers = (userId, authorFollowersCount = 0) => {
syncGalleryPostsForUser(userId, {
authorFollowersCount: Number(authorFollowersCount || 0),
});
};
const createUser = async ({
username,
email,
phone,
password,
tokenBalance = DEFAULT_STARTING_TOKENS,
referralCode = '',
referredByUserId = '',
}) => {
const normalizedEmail = email ? normalizeEmail(email) : '';
const normalizedPhone = phone ? normalizePhone(phone) : '';
const normalizedUsername = username.trim();
const normalizedReferralCode = normalizeReferralCode(referralCode);
const duplicateUser = state.users.find(
(user) =>
user.username === normalizedUsername ||
(normalizedEmail && user.email === normalizedEmail) ||
(normalizedPhone && user.phone === normalizedPhone) ||
(normalizedReferralCode && user.referralCode === normalizedReferralCode)
);
if (duplicateUser) {
const error = new Error('Email or username already exists');
error.code = 11000;
throw error;
}
const user = {
_id: generateId(),
username: normalizedUsername,
email: normalizedEmail || undefined,
phone: normalizedPhone || undefined,
password: await bcrypt.hash(password, 10),
avatarUrl: '',
followers: [],
following: [],
tokenBalance: Number.isFinite(Number(tokenBalance)) ? Number(tokenBalance) : DEFAULT_STARTING_TOKENS,
referralCode: normalizedReferralCode,
referredByUserId: normalizeId(referredByUserId),
rewardedLikePostIds: [],
rewardedFollowUserIds: [],
tokenHistory: [],
createdAt: new Date().toISOString(),
};
ensureUserTokenState(user);
state.users.push(user);
saveStore();
return sanitizeUser(user);
};
// Create demo user if no users exist
const createDemoUser = async () => {
const existingDemoUser = state.users.find(user => user.email === 'demo@example.com');
if (!existingDemoUser) {
try {
await createUser({
username: 'demo',
email: 'demo@example.com',
password: 'demo123'
});
console.log('Demo user created: demo@example.com / demo123');
} catch (error) {
console.error('Failed to create demo user:', error.message);
}
}
};
createDemoUser();
const findUserByEmail = async (email) => {
const normalizedEmail = normalizeEmail(email);
const user = state.users.find((user) => user.email === normalizedEmail) || null;
return user ? sanitizeUser(user) : null;
};
const findUserByIdentifier = async (identifier) => {
const contact = getContactFromIdentifier(identifier);
if (!contact) return null;
const user = state.users.find((entry) =>
contact.type === 'email'
? entry.email === contact.value
: entry.phone === contact.value
) || null;
return user ? sanitizeUser(user) : null;
};
const findUserById = async (userId) => {
const user = state.users.find((entry) => entry._id === userId);
return sanitizeUser(user);
};
const findUserRecordByReferralCode = async (referralCode = '') => {
const normalizedReferralCode = normalizeReferralCode(referralCode);
if (!normalizedReferralCode) return null;
return ensureUserTokenState(
state.users.find((entry) => entry.referralCode === normalizedReferralCode) || null
);
};
const getUserRecordById = async (userId) =>
ensureUserTokenState(state.users.find((entry) => entry._id === userId) || null);
const findUserRecordByIdentifier = async (identifier) => {
const contact = getContactFromIdentifier(identifier);
if (!contact) return null;
return ensureUserTokenState(state.users.find((entry) =>
contact.type === 'email'
? entry.email === contact.value
: entry.phone === contact.value
) || null);
};
const comparePassword = async (user, passwordAttempt) => {
if (!user) return false;
return bcrypt.compare(passwordAttempt, user.password);
};
const updateUserPassword = async (userId, nextPassword) => {
const user = state.users.find((entry) => entry._id === userId);
if (!user) return null;
user.password = await bcrypt.hash(nextPassword, 10);
saveStore();
return sanitizeUser(user);
};
const updateUser = async (userId, updates) => {
const user = state.users.find((entry) => entry._id === userId);
if (!user) return null;
const nextUsername = updates.username?.trim();
if (nextUsername) {
const duplicateUser = state.users.find(
(entry) => entry._id !== userId && entry.username === nextUsername
);
if (duplicateUser) {
const error = new Error('Username already exists');
error.code = 11000;
throw error;
}
user.username = nextUsername;
}
if (typeof updates.avatarUrl === 'string') {
user.avatarUrl = updates.avatarUrl;
}
if (nextUsername || typeof updates.avatarUrl === 'string') {
syncGalleryPostsForUser(userId, {
username: user.username,
userAvatarUrl: user.avatarUrl || '',
});
saveStore();
}
return sanitizeUser(user);
};
const createImage = async ({ userId, prompt, imageUrl, ratio, quality }) => {
const image = {
_id: generateId(),
userId,
prompt,
imageUrl,
ratio,
quality,
generatedAt: new Date().toISOString(),
};
state.images.push(image);
saveStore();
return image;
};
const getImagesByUserId = async (userId, page, limit) => {
const numericPage = Number(page) || 1;
const numericLimit = Number(limit) || 10;
const userImages = state.images
.filter((image) => image.userId === userId)
.sort((left, right) => new Date(right.generatedAt) - new Date(left.generatedAt));
const start = (numericPage - 1) * numericLimit;
return {
images: userImages.slice(start, start + numericLimit),
total: userImages.length,
pages: Math.max(1, Math.ceil(userImages.length / numericLimit)),
currentPage: numericPage,
};
};
const findImageById = async (imageId) => state.images.find((image) => image._id === imageId) || null;
const deleteImageById = async (imageId) => {
const imageIndex = state.images.findIndex((image) => image._id === imageId);
if (imageIndex === -1) return null;
const [deletedImage] = state.images.splice(imageIndex, 1);
saveStore();
return deletedImage;
};
const createGalleryPost = async ({
userId,
username,
userAvatarUrl,
authorFollowersCount = 0,
title,
description,
prompt,
imageUrl,
source,
}) => {
const galleryPost = {
_id: generateId(),
userId,
username,
userAvatarUrl: userAvatarUrl || '',
title: title.trim(),
description: (description || '').trim(),
prompt: (prompt || '').trim(),
imageUrl,
source: source || 'upload',
likedBy: [],
shareCount: 0,
authorFollowersCount: Number(authorFollowersCount || 0),
comments: [],
createdAt: new Date().toISOString(),
};
const normalizedGalleryPost = normalizeGalleryPost(galleryPost);
state.galleryPosts.push(normalizedGalleryPost);
saveStore();
return normalizedGalleryPost;
};
const serializeGalleryPost = (post, viewerUserId = '') => {
const normalizedViewerUserId = normalizeId(viewerUserId);
const viewer = normalizedViewerUserId
? state.users.find((user) => user._id === normalizedViewerUserId)
: null;
const viewerFollowing = viewer?.following || [];
const likedBy = normalizeIdList(post.likedBy);
const comments = Array.isArray(post.comments) ? post.comments.map(normalizeComment) : [];
const normalizedPostUserId = normalizeId(post.userId);
return {
...post,
_id: normalizeId(post._id),
userId: normalizedPostUserId,
likedByCurrentUser: normalizedViewerUserId ? likedBy.includes(normalizedViewerUserId) : false,
followingAuthor: normalizedViewerUserId ? viewerFollowing.includes(normalizedPostUserId) : false,
likesCount: likedBy.length,
shareCount: Number(post.shareCount || 0),
authorFollowersCount: Number(post.authorFollowersCount || 0),
commentsCount: comments.length,
comments,
};
};
const getPublicGalleryPosts = async ({ search = '', page = 1, limit = 12, viewerUserId = '' }) => {
const normalizedSearch = search.trim().toLowerCase();
const numericPage = Number(page) || 1;
const numericLimit = Number(limit) || 12;
const filteredPosts = state.galleryPosts
.filter((post) => {
if (!normalizedSearch) return true;
const haystack = [
post.title,
post.description,
post.prompt,
post.username,
]
.filter(Boolean)
.join(' ')
.toLowerCase();
return haystack.includes(normalizedSearch);
})
.sort((left, right) => new Date(right.createdAt) - new Date(left.createdAt));
const start = (numericPage - 1) * numericLimit;
return {
posts: filteredPosts
.slice(start, start + numericLimit)
.map((post) => serializeGalleryPost(post, viewerUserId)),
total: filteredPosts.length,
pages: Math.max(1, Math.ceil(filteredPosts.length / numericLimit)),
currentPage: numericPage,
};
};
const getPublicUserProfile = async ({ targetUserId, viewerUserId = '' }) => {
const targetUser = state.users.find((entry) => entry._id === targetUserId);
if (!targetUser) return null;
const viewer = viewerUserId
? state.users.find((entry) => entry._id === viewerUserId) || null
: null;
const viewerFollowing = normalizeIdList(viewer?.following);
const publicUser = sanitizeUser(targetUser);
const posts = state.galleryPosts
.filter((post) => normalizeId(post.userId) === targetUserId)
.sort((left, right) => new Date(right.createdAt) - new Date(left.createdAt))
.map((post) => serializeGalleryPost(post, viewerUserId));
return {
user: publicUser
? {
_id: publicUser.id,
id: publicUser.id,
username: publicUser.username,
avatarUrl: publicUser.avatarUrl,
createdAt: publicUser.createdAt,
followersCount: publicUser.followersCount,
followingCount: publicUser.followingCount,
}
: null,
posts,
totalPublicPosts: posts.length,
isCurrentUser: viewerUserId === targetUserId,
isFollowing: viewerFollowing.includes(targetUserId),
canFollow: Boolean(viewerUserId && viewerUserId !== targetUserId),
};
};
const toggleFollowUser = async (currentUserId, targetUserId) => {
if (currentUserId === targetUserId) {
throw new Error('You cannot follow yourself');
}
const currentUser = state.users.find((entry) => entry._id === currentUserId);
const targetUser = state.users.find((entry) => entry._id === targetUserId);
if (!currentUser || !targetUser) {
throw new Error('User not found');
}
const isFollowing = currentUser.following.includes(targetUserId);
currentUser.following = isFollowing
? currentUser.following.filter((id) => id !== targetUserId)
: [...currentUser.following, targetUserId];
targetUser.followers = isFollowing
? targetUser.followers.filter((id) => id !== currentUserId)
: [...targetUser.followers, currentUserId];
syncGalleryPostsForUser(targetUserId, {
authorFollowersCount: targetUser.followers.length,
});
saveStore();
return {
following: !isFollowing,
currentUser: sanitizeUser(currentUser),
targetUser: sanitizeUser(targetUser),
};
};
const findGalleryPostById = async (postId) =>
state.galleryPosts.find((post) => post._id === postId) || null;
const toggleGalleryPostLike = async (postId, userId) => {
const post = state.galleryPosts.find((entry) => entry._id === postId);
if (!post) return null;
const normalizedUserId = normalizeId(userId);
const likedBy = normalizeIdList(post.likedBy);
const isLiked = likedBy.includes(normalizedUserId);
post.likedBy = isLiked
? likedBy.filter((id) => id !== normalizedUserId)
: [...likedBy, normalizedUserId];
saveStore();
return serializeGalleryPost(post, normalizedUserId);
};
const incrementGalleryPostShare = async (postId, viewerUserId = '') => {
const post = state.galleryPosts.find((entry) => entry._id === postId);
if (!post) return null;
post.shareCount = Number(post.shareCount || 0) + 1;
saveStore();
return serializeGalleryPost(post, viewerUserId);
};
const persistStore = async () => {
saveStore();
};
module.exports = {
comparePassword,
createGalleryPost,
createImage,
createUser,
deleteImageById,
findImageById,
findGalleryPostById,
findUserByIdentifier,
findUserByEmail,
findUserById,
findUserRecordByIdentifier,
findUserRecordByReferralCode,
getImagesByUserId,
getPublicGalleryPosts,
getPublicUserProfile,
getUserRecordById,
incrementGalleryPostShare,
persistStore,
sanitizeUser,
syncGalleryPostsForAuthorFollowers,
toggleFollowUser,
toggleGalleryPostLike,
updateUser,
updateUserPassword,
};
|