const UserFollowModel = require('../models/UserFollowModel') const { isHiddenFromPublic } = require('./accountLifecycle') async function viewerCanSeeUserContent (viewerId, profileUser) { if (!profileUser) return false if (isHiddenFromPublic(profileUser)) return false if (!profileUser.is_private) return true if (!viewerId) return false if (String(viewerId) === String(profileUser._id)) return true return !!(await UserFollowModel.exists({ followerId: viewerId, followingId: profileUser._id, })) } async function filterPostsHiddenByPrivateProfile (posts, viewerId) { if (!posts?.length) return posts const authorIds = [...new Set(posts.map((p) => String(p.user_id)))] const UserModel = require('../models/UserModel') const authors = await UserModel.find({ _id: { $in: authorIds } }) .select('_id is_private account_status') .lean() const authorsById = Object.fromEntries(authors.map((u) => [String(u._id), u])) const privateAuthorIds = authors .filter((u) => u.is_private && !isHiddenFromPublic(u)) .map((u) => String(u._id)) let visiblePrivateIds = new Set() if (privateAuthorIds.length && viewerId) { if (privateAuthorIds.includes(String(viewerId))) { visiblePrivateIds.add(String(viewerId)) } const follows = await UserFollowModel.find({ followerId: viewerId, followingId: { $in: privateAuthorIds }, }) .select('followingId') .lean() follows.forEach((f) => visiblePrivateIds.add(String(f.followingId))) } return posts.filter((post) => { const author = authorsById[String(post.user_id)] if (!author || isHiddenFromPublic(author)) return false if (!author.is_private) return true if (!viewerId) return false if (String(viewerId) === String(author._id)) return true return visiblePrivateIds.has(String(author._id)) }) } async function filterStoryUserIdsByPrivateProfile (userIds, viewerId) { if (!userIds?.length) return [] const UserModel = require('../models/UserModel') const users = await UserModel.find({ _id: { $in: userIds } }) .select('_id is_private account_status') .lean() const visible = [] for (const user of users) { // eslint-disable-next-line no-await-in-loop if (await viewerCanSeeUserContent(viewerId, user)) { visible.push(String(user._id)) } } return visible } module.exports = { viewerCanSeeUserContent, filterPostsHiddenByPrivateProfile, filterStoryUserIdsByPrivateProfile, }