68 lines
2.6 KiB
JavaScript
68 lines
2.6 KiB
JavaScript
const UserFollowModel = require('../models/UserFollowModel')
|
|
const UserModel = require('../models/UserModel')
|
|
const NotificationModel = require('../models/NotificationModel')
|
|
const { sendPushToTokens } = require('./pushNotification')
|
|
|
|
let ioInstance = null
|
|
|
|
/** یکبار از index.js صدا زده میشه — مثل الگوی OrderLifecycleCron.js */
|
|
function setIo (io) {
|
|
ioInstance = io
|
|
}
|
|
|
|
/**
|
|
* وقتی یه خالق پست جدید میذاره، همهی فالوورهاش رو مطلع میکنه — دستهای، نه یهبهیه،
|
|
* چون برای خالقهای پرفالوور یه حلقهی تکی روی هر فالوور هم به دیتابیس فشار میاره هم به FCM
|
|
*/
|
|
async function notifyFollowers (authorId, post) {
|
|
try {
|
|
const follows = await UserFollowModel.find({ followingId: authorId })
|
|
.select('followerId')
|
|
.lean()
|
|
const followerIds = follows.map((f) => f.followerId)
|
|
if (followerIds.length === 0) return
|
|
|
|
const author = await UserModel.findById(authorId).select('first_name last_name user_name').lean()
|
|
const authorName = [author?.first_name, author?.last_name].filter(Boolean).join(' ') || author?.user_name || 'یکی از دنبالشدههای شما'
|
|
|
|
const notifications = followerIds.map((followerId) => ({
|
|
user_id: followerId,
|
|
type: 'new_post_from_followed',
|
|
title: 'پست جدید',
|
|
description: `${authorName} یک پست جدید منتشر کرد`,
|
|
project_post_id: post._id,
|
|
actor_id: authorId
|
|
}))
|
|
await NotificationModel.insertMany(notifications)
|
|
|
|
if (ioInstance) {
|
|
followerIds.forEach((followerId) => {
|
|
try {
|
|
ioInstance.to(`user:${String(followerId)}`).emit('notification', {
|
|
type: 'new_post_from_followed',
|
|
title: 'پست جدید',
|
|
description: `${authorName} یک پست جدید منتشر کرد`
|
|
})
|
|
} catch (_) {}
|
|
})
|
|
}
|
|
|
|
const followerUsers = await UserModel.find({ _id: { $in: followerIds } })
|
|
.select('fcm_tokens fcm_web_tokens')
|
|
.lean()
|
|
const tokens = followerUsers.flatMap((u) => [...(u.fcm_tokens || []), ...(u.fcm_web_tokens || [])])
|
|
if (tokens.length > 0) {
|
|
await sendPushToTokens(tokens, {
|
|
title: 'پست جدید',
|
|
description: `${authorName} یک پست جدید منتشر کرد`,
|
|
type: 'new_post_from_followed',
|
|
data: { project_post_id: String(post._id) }
|
|
})
|
|
}
|
|
} catch (error) {
|
|
console.error('[notifyFollowers] خطا:', error.message)
|
|
}
|
|
}
|
|
|
|
module.exports = { notifyFollowers, setIo }
|