unoffical wafrn mirror
wafrn.net
atproto
social-network
activitypub
1import { QuestionPoll, QuestionPollQuestion } from '../../models/index.js'
2import { logger } from '../logger.js'
3
4async function loadPoll(apObj: any, internalPostObject: any, user: any) {
5 let res = false
6 if (!apObj || (apObj && apObj.anyOf == undefined && apObj.oneOf == undefined)) {
7 return res
8 }
9 try {
10 const multiChoice = apObj?.anyOf != undefined
11 const remoteQuestions: any[] = apObj.anyOf ? apObj.anyOf : apObj.oneOf
12 const existingPoll = await QuestionPoll.findOne({
13 include: [QuestionPollQuestion],
14 where: {
15 postId: internalPostObject.id
16 }
17 })
18 // sometimes polls dont have expiration date. We set one accordingly
19 let endDate = new Date(new Date().setFullYear(new Date().getFullYear() + 70)) // This way the remaining time will be 69 years and a few months on every update of non finish date polls hehe
20 if (apObj.closed || apObj.endTime) {
21 endDate = new Date(apObj.closed ? apObj.closed : apObj.endTime)
22 }
23 // we check the poll and if it does not exists we create it
24 if (existingPoll) {
25 existingPoll.endDate = endDate
26 await existingPoll.save()
27 }
28 const poll = existingPoll
29 ? existingPoll
30 : await QuestionPoll.create({
31 postId: internalPostObject.id,
32 endDate: endDate,
33 multiChoice: multiChoice
34 })
35 const questions = existingPoll?.questionPollQuestions
36 ? existingPoll.questionPollQuestions
37 : await poll.getQuestionPollQuestions()
38 if (remoteQuestions.length === questions.length) {
39 questions.forEach((elem: any, index: number) => {
40 elem.set({
41 index: index,
42 questionText: remoteQuestions[index].name,
43 remoteReplies: remoteQuestions[index].replies.totalItems ? remoteQuestions[index].replies.totalItems : 0,
44 questionPollId: poll.id,
45 updatedAt: new Date()
46 })
47 elem.save()
48 })
49 } else {
50 // OH NO! the poll has a different number of things. We will assume that is new
51 // just in case we will delete the vote tho
52 for await (const question of questions) {
53 await question.destroy()
54 }
55 for await (const [index, question] of remoteQuestions.entries()) {
56 await QuestionPollQuestion.create({
57 index: index,
58 questionText: question.name,
59 remoteReplies: question.replies.totalItems ? question.replies.totalItems : 0,
60 questionPollId: poll.id
61 })
62 }
63 }
64 res = true
65 } catch (error) {
66 logger.trace({ problem: error, ap: apObj, internalPostObject: internalPostObject })
67 }
68
69 return res
70}
71
72export { loadPoll }