File size: 23,386 Bytes
5dfc565
 
bda5f6b
44fe180
a65e95e
4ddd98f
44fe180
955ce73
e4e0e54
 
652f343
5dfc565
e4e0e54
 
 
 
 
955ce73
e4e0e54
955ce73
 
096584a
955ce73
 
 
 
 
63a66b5
652f343
9571f2e
 
 
652f343
bda5f6b
 
 
 
7139c79
 
60b29ba
ab89c61
 
 
60b29ba
ab89c61
60b29ba
8ce416b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d1cac2
f6f0c40
 
 
 
5d1cac2
f6f0c40
8ce416b
 
 
 
 
 
 
 
4ddd98f
f6f0c40
4ddd98f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63a66b5
 
4ddd98f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce416b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63a66b5
8ce416b
977a154
7139c79
977a154
92ae21d
 
 
 
 
 
 
 
07d10ce
44fe180
 
 
07d10ce
7139c79
 
 
 
 
 
 
c4b02b2
5d1cac2
c4b02b2
 
 
5d1cac2
c4b02b2
 
 
 
 
5d1cac2
c4b02b2
 
 
5d1cac2
44fe180
 
096584a
 
 
ef22617
cb7d06b
6a3d22f
07d10ce
 
 
44fe180
7139c79
096584a
7139c79
 
096584a
7139c79
 
096584a
5d1cac2
7139c79
096584a
7139c79
 
096584a
7139c79
 
096584a
7139c79
 
 
 
 
096584a
7139c79
 
 
977a154
 
92ae21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185eaaf
92ae21d
 
 
185eaaf
92ae21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
096584a
 
 
 
 
 
 
 
 
 
 
 
 
44fe180
c4b02b2
44fe180
 
5d1cac2
44fe180
 
 
c4b02b2
44fe180
c4b02b2
44fe180
 
 
096584a
 
 
 
cb7d06b
096584a
6a3d22f
096584a
 
 
c4b02b2
096584a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4e0e54
 
c5b0dde
278d122
 
652f343
 
9658ad9
 
 
c5b0dde
e4e0e54
652f343
e4e0e54
 
652f343
e4e0e54
bda5f6b
 
 
 
e4e0e54
 
 
5d1cac2
5fa1539
 
 
 
 
 
 
652f343
e4e0e54
652f343
e4e0e54
9571f2e
e4e0e54
9571f2e
 
 
 
e4e0e54
c8231d6
e4e0e54
c8231d6
e4e0e54
c8231d6
 
 
 
e4e0e54
c8231d6
 
 
 
e4e0e54
278d122
9571f2e
 
 
 
278d122
 
 
 
 
 
 
9571f2e
278d122
e4e0e54
ccd48b8
9571f2e
 
 
 
 
 
 
 
 
e4e0e54
9571f2e
 
 
 
 
652f343
9571f2e
 
 
e4e0e54
9571f2e
e4e0e54
9571f2e
652f343
 
9571f2e
652f343
9571f2e
652f343
9658ad9
e4e0e54
9571f2e
 
 
 
 
 
 
278d122
 
 
 
9571f2e
5dfc565
9571f2e
 
 
 
 
 
 
 
 
 
 
 
5dfc565
9571f2e
 
 
5dfc565
 
9571f2e
 
e4e0e54
 
 
9571f2e
 
 
 
 
 
 
5dfc565
e4e0e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dfc565
e4e0e54
5dfc565
e4e0e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97fe33c
e4e0e54
97fe33c
e4e0e54
 
 
 
 
 
 
 
 
955ce73
2ca9f9b
955ce73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca9f9b
 
e4e0e54
 
 
 
 
 
 
05d68e7
e4e0e54
 
 
 
 
 
 
 
 
 
 
 
5dfc565
 
 
 
e4e0e54
5dfc565
 
 
 
e4e0e54
 
 
278d122
 
 
 
 
 
 
 
 
e4e0e54
c5b0dde
9571f2e
e4e0e54
652f343
e4e0e54
9571f2e
 
 
 
e4e0e54
9571f2e
 
e4e0e54
9571f2e
e4e0e54
652f343
 
 
bda5f6b
e4e0e54
652f343
e4e0e54
 
 
 
 
 
652f343
e4e0e54
 
 
9571f2e
e4e0e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9571f2e
 
 
e4e0e54
 
9571f2e
 
 
 
 
 
652f343
 
 
bda5f6b
9571f2e
5fb05e6
9571f2e
 
5fb05e6
9571f2e
5fb05e6
 
 
 
9571f2e
 
 
 
 
 
 
 
e4e0e54
 
 
 
652f343
e4e0e54
652f343
9571f2e
 
e4e0e54
9571f2e
e4e0e54
9571f2e
 
 
e4e0e54
9571f2e
 
 
 
 
652f343
e4e0e54
652f343
 
bda5f6b
e4e0e54
bda5f6b
 
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
import { createReadStream, existsSync } from "node:fs"
import path from "node:path"

import { validate as uuidValidate } from "uuid"
import express from "express"
import { Video, VideoStatus, VideoAPIRequest, RenderRequest, RenderedScene, ImageAnalysisRequest, ImageAnalysisResponse, SoundAnalysisResponse, SoundAnalysisRequest } from "./types.mts"

import { parseVideoRequest } from "./utils/requests/parseVideoRequest.mts"
import { savePendingVideo } from "./scheduler/savePendingVideo.mts"
import { getVideo } from "./scheduler/getVideo.mts"
import { main } from "./main.mts"
import { completedFilesDirFilePath } from "./config.mts"
import { markVideoAsToDelete } from "./scheduler/markVideoAsToDelete.mts"
import { markVideoAsToAbort } from "./scheduler/markVideoAsToAbort.mts"
import { markVideoAsToPause } from "./scheduler/markVideoAsToPause.mts"
import { markVideoAsPending } from "./scheduler/markVideoAsPending.mts"
import { getPendingVideos } from "./scheduler/getPendingVideos.mts"
import { hasValidAuthorization } from "./utils/requests/hasValidAuthorization.mts"
import { getAllVideosForOwner } from "./scheduler/getAllVideosForOwner.mts"
import { initFolders } from "./utils/filesystem/initFolders.mts"
import { sortVideosByYoungestFirst } from "./scheduler/sortVideosByYoungestFirst.mts"
import { getRenderedScene, renderScene } from "./production/renderScene.mts"
import { parseRenderRequest } from "./utils/requests/parseRenderRequest.mts"
import { loadRenderedSceneFromCache } from "./utils/requests/loadRenderedSceneFromCache.mts"

import { upscaleImage } from "./providers/image-upscaling/upscaleImage.mts"
import { analyzeImage } from "./providers/image-caption/analyzeImageWithIDEFICSAndNastyHack.mts"
// import { speechToText } from "./speechToText/speechToTextWithWhisperLib.mts"

initFolders()
// to disable all processing (eg. to debug)
// then comment the following line:
main()

const app = express()
const port = 7860

let isRendering = false

// fix this error: "PayloadTooLargeError: request entity too large"
// there are multiple version because.. yeah well, it's Express!
// app.use(bodyParser.json({limit: '50mb'}));
//app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));

// an image analyzing pipeline
app.post("/analyze", async (req, res) => {

  const request = req.body as ImageAnalysisRequest

  if (!request.prompt) {
    console.log("Invalid prompt")
    res.status(400)
    res.write(JSON.stringify({ result: "", error: "invalid prompt" }))
    res.end()
    return
  }

  if (!request.image) {
    console.log("Invalid image")
    res.status(400)
    res.write(JSON.stringify({ result: "", error: "invalid image" }))
    res.end()
    return
  }

  /*
  console.log("/analyze called with: ", {
    prompt: request.prompt,
    image: request.image.slice(0, 50)
  })
  */

  const response: ImageAnalysisResponse = {
    result: "",
    error: ""
  }

  try {
    response.result = await analyzeImage(request.image, request.prompt)
  } catch (err) {
    console.log("failed to analyze the image!")
    console.log(err)
    response.error = `failed to analyze the image: ${err}`
  }

  if (response.error.length > 0) {
    // console.log("server error")
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
    return
  } else {
    // console.log("all good")
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  }
})


// a sound recognition pipeline
// it is currently broken
/*
app.post("/listen", async (req, res) => {

  const request = req.body as SoundAnalysisRequest

  if (!request.sound) {
    console.log("Invalid sound")
    res.status(400)
    res.write(JSON.stringify({ result: "", error: "invalid sound" }))
    res.end()
    return
  }

  console.log("/listen called with: ", {
    sound: request.sound.slice(0, 50)
  })

  const response: SoundAnalysisResponse = {
    result: "",
    error: ""
  }

  try {
    response.result = await speechToText(request.sound)
  } catch (err) {
    console.log("failed to listen to the sound!")
    console.log(err)
    response.error = `failed to listen to the sound: ${err}`
  }

  if (response.error.length > 0) {
    // console.log("server error")
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
    return
  } else {
    // console.log("all good")
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  }
})
*/

// a "fast track" pipeline
app.post("/render", async (req, res) => {

  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }
  
  console.log(req.body)

  const request = parseRenderRequest(req.body as RenderRequest)

  if (!request.prompt) {
    console.log("Invalid prompt")
    res.status(400)
    res.write(JSON.stringify({ url: "", error: "invalid prompt" }))
    res.end()
    return
  }

  if (request.cache === "use") {
    // console.log("client requested to use the cache")
    try {
      const cached = await loadRenderedSceneFromCache(request)
      const cachedJson = JSON.stringify(cached)
      // console.log(`request ${request} is in cache!`)
      res.status(200)
      res.write(cachedJson)
      res.end()
      return
    } catch (err) {
      // console.log("request not found in cache: "+ err)
      // move along
    }
  } else if (request.cache === "renew") {
    // console.log("client requested to renew the cache")
  }

  let response: RenderedScene = {
    renderId: "",
    status: "pending",
    assetUrl: "",
    alt: request.prompt || "",
    maskUrl: "",
    error: "",
    segments: []
  }

  try {
    response = await renderScene(request)
  } catch (err) {
    // console.log("failed to render scene!")
    response.error = `failed to render scene: ${err}`
  }

  if (response.error === "already rendering") {
    // console.log("server busy")
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  } else if (response.error.length > 0) {
    // console.log("server error")
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
    return
  } else {
    // console.log("all good")
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  }
})

// upscale an arbitrary image
app.post("/upscale", async (req, res) => {

  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }

  const image = `${req.body.image}`

  if (!image) {
    console.error("invalid input image")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid input image` }))
    res.end()
    return
  }

  let response = {
    assetUrl: "",
    error: "",
  }

  let assetUrl = ""
  try {
    try {
      assetUrl = await upscaleImage(image, req.body.factor)
    } catch (err) {
      // hmm.. let's try again?
      try {
        assetUrl = await upscaleImage(image, req.body.factor)
      } catch (err) {
        throw new Error(`second attempt to upscale the image failed (${err})`)
      }
    }
    if (!assetUrl) {
      throw new Error(`no image to return`)
    }

    response.assetUrl = assetUrl
    // console.log(`request ${renderId} is already in cache, so we return that`)
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  } catch (err) {
    response.error = `${err}`
    console.error(`${err}`)
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
  }
})


// used to upscale an existing image
// the image has to be completed for this to work
// ie it has to be in cache
// it's a bit of a hack endpoint I've added to reduce the laod
// on the AI Comic Factory, but we don't really need it for other applications
app.post("/upscale/:renderId", async (req, res) => {

  const renderId = `${req.params.renderId}`

  if (!uuidValidate(renderId)) {
    console.error("invalid render id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid render id` }))
    res.end()
    return
  }

  let response = {
    assetUrl: "",
    error: "",
  }

  let assetUrl = ""
  try {
    // we still try to search for it in the cache
    const cached = await loadRenderedSceneFromCache(undefined, renderId)
    try {
      assetUrl = await upscaleImage(cached.assetUrl, 2)
    } catch (err) {
      // hmm.. let's try again?
      try {
        assetUrl = await upscaleImage(cached.assetUrl, 2)
      } catch (err) {
        throw new Error(`second attempt to upscale the image failed (${err})`)
      }
    }
    if (!assetUrl) {
      throw new Error(`no image to return`)
    }

    response.assetUrl = assetUrl
    // console.log(`request ${renderId} is already in cache, so we return that`)
    res.status(200)
    res.write(response)
    res.end()
    return
  } catch (err) {
    // console.log("renderId not found in cache: "+ err)
    // move along
    response.error = `${err}`
    console.error(`${err}`)
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
  }
})

// a "fast track" pipeline
app.get("/render/:renderId", async (req, res) => {

  const renderId = `${req.params.renderId}`

  if (!uuidValidate(renderId)) {
    console.error("invalid render id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid render id` }))
    res.end()
    return
  }

  try {
    // we still try to search for it in the cache
    const cached = await loadRenderedSceneFromCache(undefined, renderId)
    const cachedJson = JSON.stringify(cached)
    // console.log(`request ${renderId} is already in cache, so we return that`)
    res.status(200)
    res.write(cachedJson)
    res.end()
    return
  } catch (err) {
    // console.log("renderId not found in cache: "+ err)
    // move along
  }

  let response: RenderedScene = {
    renderId: "",
    status: "pending",
    assetUrl: "",
    alt: "",
    error: "",
    maskUrl: "",
    segments: []
  }

  // console.log("going to render the scene!")
  try {
    response = await getRenderedScene(renderId)
  } catch (err) {
    // console.log("failed to render scene!")
    response.error = `failed to render scene: ${err}`
  }

  if (response.error === "already rendering") {
    console.log("server busy")
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  } else if (response.error.length > 0) {
    // console.log("server error")
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
    return
  } else {
    // console.log("all good")
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  }
})

app.post("/:ownerId", async (req, res) => {
  const request = req.body as VideoAPIRequest

  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }
  
  const ownerId = req.params.ownerId

  if (!uuidValidate(ownerId)) {
    console.error("invalid owner id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid owner id` }))
    res.end()
    return
  }

  let video: Video = null

  console.log(`creating video from request..`)
  // console.log(`request: `, JSON.stringify(request))
  if (!request?.prompt?.length) {
    console.error(`failed to create video (prompt is empty})`)
    res.status(400)
    res.write(JSON.stringify({ error: "prompt is empty" }))
    res.end()
    return
  }
  try {
    video = await parseVideoRequest(ownerId, request)
  } catch (err) {
    console.error(`failed to create video: ${video} (${err})`)
    res.status(400)
    res.write(JSON.stringify({ error: "query seems to be malformed" }))
    res.end()
    return
  }

  console.log(`saving video ${video.id}`)
  try {
    await savePendingVideo(video)
    res.status(200)
    res.write(JSON.stringify(video))
    res.end()
  } catch (err) {
    console.error(err)
    res.status(500)
    res.write(JSON.stringify({ error: "couldn't save the video" }))
    res.end()
  }
})

app.get("/:ownerId/:videoId\.mp4", async (req, res) => {
    
  /*
  for simplicity, let's skip auth when fetching videos
  the UUIDs cannot easily be guessed anyway

  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }
  */

  const ownerId = req.params.ownerId
  console.log("downloading..")

  if (!uuidValidate(ownerId)) {
    console.error("invalid owner id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid owner id` }))
    res.end()
    return
  }

  const videoId = req.params.videoId

  if (!uuidValidate(videoId)) {
    console.error("invalid video id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid video id` }))
    res.end()
    return
  }

  let video: Video = null
  try {
    video = await getVideo(ownerId, videoId)
    console.log(`returning video ${videoId} to owner ${ownerId}`)
  } catch (err) {
    res.status(404)
    res.write(JSON.stringify({ error: "this video doesn't exist" }))
    res.end()
    return
  }

  const completedFilePath = path.join(completedFilesDirFilePath, video.fileName)

  // note: we DON'T want to use the pending file path, as there may be operations on it
  // (ie. a process might be busy writing stuff to it)
  const filePath = existsSync(completedFilePath) ? completedFilePath : ""
  if (!filePath) {
    res.status(400)
    res.write(JSON.stringify({ error: "video exists, but cannot be previewed yet" }))
    res.end()
    return
  }

  // file path exists, let's try to read it
  try {
    // do we need this?
    // res.status(200)
    // res.setHeader("Content-Type", "media/mp4")
    console.log(`creating a video read stream from ${filePath}`)
    const stream = createReadStream(filePath)
  
    stream.on('close', () => {
      console.log(`finished streaming the video`)
      res.end()
    })
    
    stream.pipe(res)
  } catch (err) {
    console.error(`failed to read the video file at ${filePath}: ${err}`)
    res.status(500)
    res.write(JSON.stringify({ error: "failed to read the video file" }))
    res.end()
  }
})

// get metadata (json)
app.get("/:ownerId/:videoId", async (req, res) => {
    
  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }

  const ownerId = req.params.ownerId

  if (!uuidValidate(ownerId)) {
    console.error("invalid owner id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid owner id` }))
    res.end()
    return
  }

  const videoId = req.params.videoId

  if (!uuidValidate(videoId)) {
    console.error("invalid video id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid video id` }))
    res.end()
    return
  }

  try {
    const video = await getVideo(ownerId, videoId)
    res.status(200)
    res.write(JSON.stringify(video))
    res.end()
  } catch (err) {
    console.error(err)
    res.status(404)
    res.write(JSON.stringify({ error: "couldn't find this video" }))
    res.end()
  }
})

// only get the videos for a specific owner
app.get("/:ownerId", async (req, res) => {
  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }

  const ownerId = req.params.ownerId

  if (!uuidValidate(ownerId)) {
    console.error(`invalid owner d ${ownerId}`)
    res.status(400)
    res.write(JSON.stringify({ error: `invalid owner id ${ownerId}` }))
    res.end()
    return
  }

  try {
    const videos = await getAllVideosForOwner(ownerId)
    sortVideosByYoungestFirst(videos)

    res.status(200)
    res.write(JSON.stringify(videos.filter(video => video.status !== "delete"), null, 2))
    res.end()
  } catch (err) {
    console.error(err)
    res.status(500)
    res.write(JSON.stringify({ error: `couldn't get the videos for owner ${ownerId}` }))
    res.end()
  }
})

// caption an audio sample
/*
app.post("/audio/caption", async (req, res) => {

  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }

  const image = `${req.body.image}`

  if (!image) {
    console.error("invalid input image")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid input image` }))
    res.end()
    return
  }

  let response = {
    caption: "",
    error: "",
  }

  let caption = ""
  try {
    try {
      caption = await audioToCaption(audio, req.body.factor)
    } catch (err) {
      // hmm.. let's try again?
      try {
        caption = await audioToCaption(audio, req.body.factor)
      } catch (err) {
        throw new Error(`second attempt to caption the audio failed (${err})`)
      }
    }
    if (!caption) {
      throw new Error(`no caption to return`)
    }

    response.caption = caption
    res.status(200)
    res.write(JSON.stringify(response))
    res.end()
    return
  } catch (err) {
    response.error = `${err}`
    console.error(`${err}`)
    res.status(500)
    res.write(JSON.stringify(response))
    res.end()
  }
})

*/

// get all pending videos - this is for admin usage only
app.get("/", async (req, res) => {
  if (!hasValidAuthorization(req.headers)) {
    // this is what users will see in the space - but no need to show something scary
    console.log("Invalid authorization")
    res.status(200)
    res.write(`<html><head></head><body>
VideoChain is a toolchain to render scenes using AI. It is used by <a href="https://jbilcke-hf-videoquest.hf.space" target="_blank">VideoQuest</a>, a generative AI game.
    </body></html>`)
    res.end()
    // res.status(401)
    // res.write(JSON.stringify({ error: "invalid token" }))
    // res.end()
    return
  }

  try {
    const videos = await getPendingVideos()
    res.status(200)
    res.write(JSON.stringify(videos, null, 2))
    res.end()
  } catch (err) {
    console.error(err)
    res.status(500)
    res.write(JSON.stringify({ error: "couldn't get the videos" }))
    res.end()
  }
})


// edit a video
app.patch("/:ownerId/:videoId", async (req, res) => {
    
  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }

  const ownerId = req.params.ownerId

  if (!uuidValidate(ownerId)) {
    console.error(`invalid owner id ${ownerId}`)
    res.status(400)
    res.write(JSON.stringify({ error: `invalid owner id ${ownerId}` }))
    res.end()
    return
  }

  const videoId = req.params.videoId

  if (!uuidValidate(videoId)) {
    console.error(`invalid video id ${videoId}`)
    res.status(400)
    res.write(JSON.stringify({ error: `invalid video id ${videoId}` }))
    res.end()
    return
  }

  let status: VideoStatus = "unknown"
  try {
    const request = req.body as { status: VideoStatus }
    if (['pending', 'abort', 'delete', 'pause'].includes(request.status)) {
      status = request.status
    } else {
      throw new Error(`invalid video status "${request.status}"`)
    }
  } catch (err) {
    console.error(`invalid parameter (${err})`)
    res.status(401)
    res.write(JSON.stringify({ error: `invalid parameter (${err})` }))
    res.end()
    return
  }

  switch (status) {
    case 'delete': 
      try {
        await markVideoAsToDelete(ownerId, videoId)
        console.log(`deleting video ${videoId}`)
        res.status(200)
        res.write(JSON.stringify({ success: true }))
        res.end()
      } catch (err) {
        console.error(`failed to delete video ${videoId} (${err})`)
        res.status(500)
        res.write(JSON.stringify({ error: `failed to delete video ${videoId}` }))
        res.end()
      }
      break

    case 'abort': 
      try {
        await markVideoAsToAbort(ownerId, videoId)
        console.log(`aborted video ${videoId}`)
        res.status(200)
        res.write(JSON.stringify({ success: true }))
        res.end()
      } catch (err) {
        console.error(`failed to abort video ${videoId} (${err})`)
        res.status(500)
        res.write(JSON.stringify({ error: `failed to abort video ${videoId}` }))
        res.end()
      }
      break

    case 'pause': 
      try {
        await markVideoAsToPause(ownerId, videoId)
        console.log(`paused video ${videoId}`)
        res.status(200)
        res.write(JSON.stringify({ success: true }))
        res.end()
      } catch (err) {
        console.error(`failed to pause video ${videoId} (${err})`)
        res.status(500)
        res.write(JSON.stringify({ error: `failed to pause video ${videoId}` }))
        res.end()
      }
      break
    
    case 'pending': 
      try {
        await markVideoAsPending(ownerId, videoId)
        console.log(`unpausing video ${videoId}`)
        res.status(200)
        res.write(JSON.stringify({ success: true }))
        res.end()
      } catch (err) {
        console.error(`failed to unpause video ${videoId} (${err})`)
        res.status(500)
        res.write(JSON.stringify({ error: `failed to unpause video ${videoId}` }))
        res.end()
      }
      break

    default:
      console.log(`unsupported status ${status}`)
      res.status(401)
      res.write(JSON.stringify({ error: `unsupported status ${status}` }))
      res.end()
  }
})

// delete a video - this is legacy, we should use other functions instead
/*
app.delete("/:id", async (req, res) => {
    
  if (!hasValidAuthorization(req.headers)) {
    console.log("Invalid authorization")
    res.status(401)
    res.write(JSON.stringify({ error: "invalid token" }))
    res.end()
    return
  }

  const [ownerId, videoId] = `${req.params.id}`.split("_")

  if (!uuidValidate(ownerId)) {
    console.error("invalid owner id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid owner id` }))
    res.end()
    return
  }

  if (!uuidValidate(videoId)) {
    console.error("invalid video id")
    res.status(400)
    res.write(JSON.stringify({ error: `invalid video id` }))
    res.end()
    return
  }

  // ecurity note: we always check the existence if the video first
  // that's because we are going to delete all the associated files with a glob,
  // so we must be sure the id is not a system path or something ^^
  let video: Video = null
  try {
    video = await getVideo(ownerId, videoId)
  } catch (err) {
    console.error(err)
    res.status(404)
    res.write(JSON.stringify({ error: "couldn't find this video" }))
    res.end()
    return
  }

  try {
    await markVideoAsToDelete(ownerId, videoId)
    res.status(200)
    res.write(JSON.stringify({ success: true }))
    res.end()
  } catch (err) {
    console.error(err)
    res.status(500)
    res.write(JSON.stringify({ success: false, error: "failed to delete the video" }))
    res.end()
  }
})
*/

app.listen(port, () => { console.log(`Open http://localhost:${port}`) })