File size: 7,544 Bytes
18e5e63
 
 
 
 
 
2898d65
18e5e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0f34ee
18e5e63
b0f34ee
 
 
18e5e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0f34ee
18e5e63
 
 
 
 
66e6b3f
18e5e63
 
 
 
 
 
 
 
 
 
2898d65
 
18e5e63
 
 
2898d65
18e5e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2898d65
 
 
 
 
 
 
18e5e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6eda94
 
18e5e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use server"

import { v4 as uuidv4 } from "uuid"

import { CreatePostResponse, GetAppPostResponse, GetAppPostsResponse, Post, PostVisibility } from "@/types"
import { filterOutBadWords } from "./censorship"
import { shuffleArray } from "../utils/shuffleArray"

const apiUrl = `${process.env.COMMUNITY_API_URL || ""}`
const apiToken = `${process.env.COMMUNITY_API_TOKEN || ""}`
const appId = `${process.env.COMMUNITY_API_ID || ""}`
const secretModerationKey = `${process.env.MODERATION_KEY || ""}`

export async function postToCommunity({
  prompt = "",
  model = "",
  assetUrl = "",
}: {
  prompt: string
  model: string,
  assetUrl: string
}): Promise<Post> {

  const before = prompt
  prompt = filterOutBadWords(prompt)

  if (prompt !== before) {
    console.log(`user attempted to use bad words! their original prompt is: ${before}`)
  }

  // if the community API is disabled,
  // we don't fail, we just mock
  if (!apiUrl) {
    const mockPost: Post = {
      postId: uuidv4(),
      appId: "mock",
      prompt,
      model,
      previewUrl: assetUrl,
      assetUrl,
      createdAt: new Date().toISOString(),
      visibility: "normal",
      upvotes: 0,
      downvotes: 0
    }
    return mockPost
  }

  if (!prompt) {
    console.error(`cannot call the community API without a prompt, aborting..`)
    throw new Error(`cannot call the community API without a prompt, aborting..`)
  }
  if (!assetUrl) {
    console.error(`cannot call the community API without an assetUrl, aborting..`)
    throw new Error(`cannot call the community API without an assetUrl, aborting..`)
  }

  try {
    console.log(`calling POST ${apiUrl}/posts/${appId} with prompt: ${prompt}`)

    const postId = uuidv4()

    const post: Partial<Post> = { postId, appId, prompt, model, assetUrl }

    console.log(`target url is: ${
      `${apiUrl}/posts/${appId}`
    }`)

    const res = await fetch(`${apiUrl}/posts/${appId}`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiToken}`,
      },
      body: JSON.stringify(post),
      cache: 'no-store',
    // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache)
    // next: { revalidate: 1 }
    })

    // Recommendation: handle errors
    if (res.status !== 201) {
      // This will activate the closest `error.js` Error Boundary
      throw new Error('Failed to fetch data')
    }
    
    const response = (await res.json()) as CreatePostResponse
    // console.log("response:", response)
    return response.post
  } catch (err) {
    const error = `failed to post to community: ${err}`
    console.error(error)
    throw new Error(error)
  }
}

export async function getLatestPosts({
  visibility,
  maxNbPosts = 1000,
  shuffle = true,
}: {
  visibility?: PostVisibility
  maxNbPosts?: number
  shuffle?: boolean
}): Promise<Post[]> {

  let posts: Post[] = []

  // if the community API is disabled we don't fail,
  // we just mock
  if (!apiUrl) {
    return posts
  }

  try {
    // console.log(`calling GET ${apiUrl}/posts with renderId: ${renderId}`)
    // TODO: send the max number of posts
    const res = await fetch(`${apiUrl}/posts/${appId}/${
      visibility || "all"
    }`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiToken}`,
      },
      cache: 'no-store',
    // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache)
    // next: { revalidate: 1 }
    })

    // console.log("res:", res)
    // The return value is *not* serialized
    // You can return Date, Map, Set, etc.
    
    // Recommendation: handle errors
    if (res.status !== 200) {
      // This will activate the closest `error.js` Error Boundary
      throw new Error('Failed to fetch data')
    }
    
    const response = (await res.json()) as GetAppPostsResponse
    // console.log("response:", response)

    const posts: Post[] = Array.isArray(response?.posts) ? response?.posts : []

    if (shuffle) {
      shuffleArray(posts)
    } else {
      posts.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))
    }

    return posts.slice(0, maxNbPosts)
  } catch (err) {
    // const error = `failed to get posts: ${err}`
    // console.error(error)
    // throw new Error(error)
    return []
  }
}

export async function getPost(postId: string): Promise<Post> {

 // if the community API is disabled we don't fail,
  // we just mock
  if (!apiUrl) {
    throw new Error("community API is not enabled")
  }

  try {
    // console.log(`calling GET ${apiUrl}/posts with renderId: ${renderId}`)
    const res = await fetch(`${apiUrl}/posts/${appId}/${postId}`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiToken}`,
      },
      cache: 'no-store',
    // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache)
    // next: { revalidate: 1 }
    })

    // console.log("res:", res)
    // The return value is *not* serialized
    // You can return Date, Map, Set, etc.
    
    // Recommendation: handle errors
    if (res.status !== 200) {
      // This will activate the closest `error.js` Error Boundary
      throw new Error('Failed to fetch data')
    }
    
    const response = (await res.json()) as GetAppPostResponse
    // console.log("response:", response)
    return response.post
  } catch (err) {
    const error = `failed to get post: ${err}`
    console.error(error)
    throw new Error(error)
  }
}

export async function deletePost({
  postId,
  moderationKey,
}: {
  postId: string
  moderationKey: string
}): Promise<boolean> {

  // if the community API is disabled,
  // we don't fail, we just mock
  if (!apiUrl) {
    return false
  }

  if (!postId) {
    console.error(`cannot delete a post without a postId, aborting..`)
    throw new Error(`cannot delete a post without a postId, aborting..`)
  }
  if (!moderationKey) {
    console.error(`cannot delete a post without a moderationKey, aborting..`)
    throw new Error(`cannot delete a post without a moderationKey, aborting..`)
  }

  if (moderationKey !== secretModerationKey) {
    console.error(`invalid moderation key, operation denied! please ask an admin for the mdoeration key`)
    throw new Error(`invalid moderation key, operation denied! please ask an admin for the mdoeration key`)
  }

  try {
    console.log(`calling DELETE ${apiUrl}/posts/${appId}/${postId}`)

    const res = await fetch(`${apiUrl}/posts/${appId}/${postId}`, {
      method: "DELETE",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiToken}`,
      },
      cache: 'no-store',
    // we can also use this (see https://vercel.com/blog/vercel-cache-api-nextjs-cache)
    // next: { revalidate: 1 }
    })

    // console.log("res:", res)
    // The return value is *not* serialized
    // You can return Date, Map, Set, etc.
    
    // Recommendation: handle errors
    if (res.status !== 200) {
      // This will activate the closest `error.js` Error Boundary
      throw new Error('Failed to fetch data')
    }
    
    const response = (await res.json()) as CreatePostResponse
    return true
  } catch (err) {
    const error = `failed to delete the post: ${err}`
    console.error(error)
    throw new Error(error)
  }
}