File size: 1,742 Bytes
38d787b
 
 
 
1185ec1
38d787b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use server"

import { v4 as uuidv4 } from "uuid"

import { CommentInfo, StoredCommentInfo } from "@/types/general"
import { stripHtml } from "@/lib/stripHtml"
import { getCurrentUser, getUsers } from "./users"
import { redis } from "./redis"

export async function submitComment(videoId: string, rawComment: string, apiKey: string): Promise<CommentInfo> {

  // trim, remove HTML, limit the length
  const message = stripHtml(rawComment).trim().slice(0, 1024).trim()

  if (!message) { throw new Error("comment is empty") }

  const user = await getCurrentUser(apiKey)

  const storedComment: StoredCommentInfo = {
    id: uuidv4(),
    userId: user.id,
    inReplyTo: undefined, // undefined means in reply to OP
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    message,
    numberOfLikes: 0,
    numberOfReplies: 0,
    likedByOriginalPoster: false,
  }

  await redis.lpush(`videos:${videoId}:comments`, storedComment)

  const fullComment: CommentInfo = {
    ...storedComment,
    userInfo: {
      ...user,

      // important: we erase all information about the API token!
      hfApiToken: undefined,
    },
  }

  return fullComment
}


export async function getComments(videoId: string): Promise<CommentInfo[]> {
  try {
    const rawList = await redis.lrange<StoredCommentInfo>(`videos:${videoId}:comments`, 0, 100)

    const storedComments = Array.isArray(rawList) ? rawList : []

    const usersById = await getUsers(storedComments.map(u => u.userId))

    const comments: CommentInfo[] = storedComments.map(storedComment => ({
      ...storedComment,
      userInfo: (usersById as any)[storedComment.userId] || undefined,
    }))

    return comments
  } catch (err) {
    return []
  }
}