-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp.go
More file actions
983 lines (861 loc) · 26.5 KB
/
Copy pathhttp.go
File metadata and controls
983 lines (861 loc) · 26.5 KB
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
//"mime/multipart"
"encoding/base64"
"github.com/alexedwards/scs/v2"
"github.com/google/uuid"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
//"github.com/timshannon/badgerhold/v4"
"github.com/dgraph-io/badger/v3"
//"regexp"
)
type User struct {
Username string //`json:"username"`
Email string //`json:"email"`
Password string //`json:"password"`
ID string //`json:"password"`
Videos []Video
}
type UploadedVideo struct {
Username string `json:"username"`
VideoName string `json:"videoName"`
FileName string `json:"fileName"`
Thumbnail string `json:"thumbnail"`
Video Video `json: video`
}
type ServerInfo struct {
IP string
Port string
}
type PreSignedURLResponse struct {
Status string `json:"status"`
Body struct {
Uploads []struct {
ID string `json:"id"`
ServiceAccountID string `json:"service_account_id"`
PresignedURL string `json:"presigned_url"`
PresignedURLExpiration string `json:"presigned_url_expiration"`
PresignedURLExpired bool `json:"presigned_url_expired"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
} `json:"uploads"`
} `json:"body"`
}
type TranscodeVideoRequestBody struct {
SourceUploadID string `json:"source_upload_id"`
PlaybackPolicy string `json:"playback_policy"`
}
type Video struct {
ID string `json:"id"`
PlaybackURI string `json:"playback_uri"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
ServiceAccountID string `json:"service_account_id"`
FileName string `json:"file_name"`
State string `json:"state"`
SubState string `json:"sub_state"`
SourceUploadID string `json:"source_upload_id"`
SourceURI string `json:"source_uri"`
PlaybackPolicy string `json:"playback_policy"`
Progress float64 `json:"progress"`
Error string `json:"error"`
Duration string `json:"duration"`
Resolution interface{} `json:"resolution"`
Metadata struct {
} `json:"metadata"`
}
type TranscodeVideoResponse struct {
Status string `json:"status"`
Body struct {
Videos []Video `json:"videos"`
} `json:"body"`
}
//used for svelte
//var testTemplate *template.Template
//
var apiID *string
var apiSecret *string
var uploadedVideos []Video
var wg sync.WaitGroup
var ip *string
var port *string
var defaultIPPort string
var dbPath string
var dbPath2 string
var templates *template.Template
//var options = badgerhold.DefaultOptions
// go-sessions package
//var cookieNameForSessionID = "mycookienamesessionnameid"
//var cookie CookieStruct
//var sess = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
//var mu sync.WaitGroup
//
//scs session package
var sessionManager *scs.SessionManager
func rootHandler(w http.ResponseWriter, r *http.Request) {
//query := r.FormValue("searchQuery")
//source := r.FormValue("mediaSource")
//p := mediaSearch{searchString: query, mediaSource: source}
//fmt.Println(p.mediaSource, p.searchString)
//rootTemplate, _ := template.ParseFiles("./templates/home.html")
if r.Method == "GET" {
//var videos = []UploadedVideo{}
var uploadedVideos []UploadedVideo
var uploadedVideo UploadedVideo
db, err := badger.Open(badger.DefaultOptions(dbPath2))
if err != nil {
fmt.Println(err)
}
defer db.Close()
// search for video_ keys and append to uploadedVideos slice
err = db.View(func(txn *badger.Txn) error {
// Your code here…
opts := badger.DefaultIteratorOptions
//opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
prefix := []byte("video_")
var value []byte
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
videoEntry := it.Item()
//k := videoEntry.Key()
value, err = videoEntry.ValueCopy(nil)
if err != nil {
return err
}
json.Unmarshal(value, &uploadedVideo)
uploadedVideos = append(uploadedVideos, uploadedVideo)
}
return nil
})
if err != nil {
panic(err)
}
// check if user is logged in
if sessionManager.Exists(r.Context(), "username") == true {
username := sessionManager.Get(r.Context(), "username")
//fmt.Fprintf(w, username)
fmt.Println("user:", username, "is logged in!")
templates.ExecuteTemplate(w, "home.html", username)
} else {
templates.ExecuteTemplate(w, "home.html", nil)
}
if err != nil {
fmt.Println(err)
fmt.Println("error grabbing uploaded videos")
}
uploadedVideosBytes, _ := json.Marshal(uploadedVideos)
//fmt.Println(uploadedVideos)
err = templates.ExecuteTemplate(w, "home.html", string(uploadedVideosBytes))
if err != nil {
fmt.Println(err)
}
fmt.Println("new get request")
} else {
fmt.Println("post requests not allowed")
}
}
func videoUploadHandler(w http.ResponseWriter, r *http.Request) {
var newUploadedVideo UploadedVideo
//testString := "input string value"
/*
fmap := template.FuncMap{
"getVideoID": waitForVideoID,
}
t := template.Must(template.New("upload.html").Funcs(fmap).ParseFiles("./templates/upload.html"))
*/
var base64ThumbnailFile string
videoID := ""
isError := false
t, _ := template.ParseFiles("./templates/upload_new.html")
if sessionManager.Exists(r.Context(), "username") == false {
fmt.Fprintf(w, "error 404 user not logged in")
return
}
if r.Method == "GET" {
err := t.Execute(w, nil)
if err != nil {
fmt.Println(err)
}
fmt.Println("new get request")
} else if r.Method == "POST" {
//api_key := *apiID
//api_secret := *apiSecret
//var videoFile *os.File
// get videoFile upload from client browser
fmt.Println("uploading video to theta")
//fmt.Println()
//fmt.Println(httputil.DumpRequest(r, true))
//b, err := io.ReadAll(r.Body)
//fmt.Println(string(b))
maxSize := int64(102400000000) // allow only 1GB of videoFile size
err := r.ParseMultipartForm(maxSize)
if err != nil {
fmt.Println(err)
fmt.Fprintf(w, "Image too large. Max Size: %v", maxSize)
return
}
videoFile, _, err := r.FormFile("videoFile")
thumbnailFile, _, err := r.FormFile("thumbnailFile")
buf := bytes.NewBuffer(nil)
_, err = io.Copy(buf, thumbnailFile)
if err != nil {
fmt.Println(err)
}
base64ThumbnailFile = base64.StdEncoding.EncodeToString(buf.Bytes())
//fmt.Println(base64ThumbnailFile)
if err != nil {
//fmt.Println(headers)
log.Println(err)
fmt.Fprintf(w, "Could not get uploaded videoFile")
return
}
fileName := r.FormValue("fileName")
videoName := r.FormValue("videoName")
defer videoFile.Close()
// end get videoFile upload from client browser
wg.Add(1)
go func() {
defer wg.Done()
var uploadId string
var uploadUrl string
var newVideo Video
//var progress float64
//var playbackURI string
//var state string
fmt.Println("starting theta upload process")
api_key := *apiID
api_secret := *apiSecret
client := &http.Client{}
data := url.Values{}
// submit a post request to theta video api to get a preassignedURL
// preassignedURL is url for an instance of a video upload
req, _ := http.NewRequest("POST", "https://api.thetavideoapi.com/upload", strings.NewReader(data.Encode()))
presignedUrlresponse := PreSignedURLResponse{}
req.Header.Add("x-tva-sa-id", api_key)
req.Header.Add("x-tva-sa-secret", api_secret)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(body, &presignedUrlresponse)
if err != nil {
fmt.Println(err)
}
fmt.Println(presignedUrlresponse)
for index, upload := range presignedUrlresponse.Body.Uploads {
fmt.Println(index)
if len(presignedUrlresponse.Body.Uploads) == 1 {
fmt.Println("number of uploads is 1")
fmt.Println(upload.PresignedURL, upload.ID)
uploadUrl = upload.PresignedURL
uploadId = upload.ID
break
}
}
fmt.Println(presignedUrlresponse)
//t.Execute(w, nil)
// upload video to presigned url
req, _ = http.NewRequest("PUT", uploadUrl, videoFile)
fmt.Println("uploading videoFile to preassigned url")
req.Header.Add("Content-Type", "application/octet-stream")
res, err = client.Do(req)
if err != nil {
fmt.Println(err)
}
//fmt.Println(string(bb))
defer res.Body.Close()
//fmt.Println(res)
// transcode video using an upload
transcodeVideoBody := &TranscodeVideoRequestBody{
SourceUploadID: uploadId,
PlaybackPolicy: "public",
}
b, err := json.Marshal(transcodeVideoBody)
u := bytes.NewReader(b)
transcodeVideoResponse := TranscodeVideoResponse{}
req, _ = http.NewRequest("POST", "https://api.thetavideoapi.com/video", u)
req.Header.Add("x-tva-sa-id", api_key)
req.Header.Add("x-tva-sa-secret", api_secret)
req.Header.Add("Content-Type", "application/json")
res, err = client.Do(req)
//bb, err = io.ReadAll(res.Body)
fmt.Println("send request to transcode video upload")
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&transcodeVideoResponse)
transcodeStatus := transcodeVideoResponse.Status
if transcodeStatus == "success" {
videoID = transcodeVideoResponse.Body.Videos[0].ID
newVideo = transcodeVideoResponse.Body.Videos[0]
progress := newVideo.Progress
playbackURI := newVideo.PlaybackURI
state := newVideo.State
fmt.Println(videoID, progress, playbackURI, state)
} else {
fmt.Println("error transcoding video")
fmt.Fprintf(w, "error transcoding video")
isError = true
w.WriteHeader(501)
//fmt.Fprintf(w, "error transcoding video. Please check the api keys and try again")
return
}
return
}()
wg.Wait()
if isError != false {
fmt.Println("error transcoding video... exiting ")
fmt.Fprintf(w, "error transcoding video")
return
} else if videoID != "" {
fmt.Println(videoID)
fmt.Fprintf(w, videoID)
} else {
fmt.Println("error uploading. Video not found")
fmt.Fprintf(w, "error uploading. Video not found")
}
go func() {
username := sessionManager.GetString(r.Context(), "username")
fmt.Println(username)
//defer wg.Done()
var transcodeVideoResponse2 TranscodeVideoResponse
var progress2 float64
var playbackURI2 string
var state2 string
var newVideo2 Video
api_key := *apiID
api_secret := *apiSecret
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://api.thetavideoapi.com/video/"+videoID, nil)
req.Header.Add("x-tva-sa-id", api_key)
req.Header.Add("x-tva-sa-secret", api_secret)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
err = json.Unmarshal(body, &transcodeVideoResponse2)
progress2 = transcodeVideoResponse2.Body.Videos[0].Progress
playbackURI2 = transcodeVideoResponse2.Body.Videos[0].PlaybackURI
state2 = transcodeVideoResponse2.Body.Videos[0].State
for state2 != "success" || state2 != "failed" {
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://api.thetavideoapi.com/video/"+videoID, nil)
req.Header.Add("x-tva-sa-id", api_key)
req.Header.Add("x-tva-sa-secret", api_secret)
res, _ := client.Do(req)
body, _ := ioutil.ReadAll(res.Body)
err = json.Unmarshal(body, &transcodeVideoResponse2)
newVideo2 = transcodeVideoResponse2.Body.Videos[0]
progress2 = newVideo2.Progress
playbackURI2 = newVideo2.PlaybackURI
state2 = newVideo2.State
fmt.Println(progress2)
if state2 == "success" {
fmt.Println("video successfully transcoded")
fmt.Println("video playback url: " + playbackURI2)
//var user User
//var uploadedVideos []UploadedVideo
newUploadedVideo = UploadedVideo{
Username: username,
VideoName: videoName,
FileName: fileName,
Thumbnail: base64ThumbnailFile,
Video: newVideo2,
}
newUploadedVideoJson, _ := json.Marshal(newUploadedVideo)
// if the uploaded video already exists ignore
/*
err = db.FindOne(&uploadedVideoResult, badgerhold.Where(badgerhold.Key).Eq(videoID))
if err != nil {
fmt.Println(err)
fmt.Println("video not found in db")
return
}
db.Insert(videoID, &newUploadedVideo)
*/
db, err := badger.Open(badger.DefaultOptions(dbPath2).WithSyncWrites(true))
if err != nil {
fmt.Println(err)
}
defer db.Close()
// if the uploadedVideo object doesnt exist, create it
err = db.Update(func(txn *badger.Txn) error {
// Your code here…
videoEntry, err := txn.Get([]byte(videoID))
if err != nil {
fmt.Println(err)
fmt.Println("failed getting video entry")
err = txn.Set([]byte(videoID), newUploadedVideoJson)
if err != nil {
fmt.Println(err)
}
return nil
} else {
var value []byte
value, err = videoEntry.ValueCopy(nil)
fmt.Println(value)
return nil
}
return nil
})
if err != nil {
fmt.Println(err)
}
return
}
//time.Sleep(5 * time.Second)
}
return
}()
//wg.Wait()
if err != nil {
fmt.Println(err)
}
return
}
}
func playVideoHandler(w http.ResponseWriter, r *http.Request) {
(w).Header().Set("Access-Control-Allow-Origin", "*")
halfURI := "https://media.thetavideoapi.com/"
endURI := "/master.m3u8"
reqVideoID := strings.TrimPrefix(r.URL.Path, "/playVideo/")
uri := halfURI + reqVideoID + endURI
//t, _ := template.ParseFiles("./templates/playVideo_new.html")
if r.Method == "GET" {
fmt.Println("new get request to play video")
fmt.Println(uri)
var uploadedVideos []UploadedVideo
var uploadedVideo UploadedVideo
db, err := badger.Open(badger.DefaultOptions(dbPath2).WithReadOnly(true))
if err != nil {
fmt.Println(err)
}
defer db.Close()
// search for video_ keys and append to uploadedVideos slice
err = db.View(func(txn *badger.Txn) error {
// Your code here…
opts := badger.DefaultIteratorOptions
//opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
prefix := []byte("video_")
var value []byte
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
videoEntry := it.Item()
//k := videoEntry.Key()
value, err = videoEntry.ValueCopy(nil)
if err != nil {
return err
}
json.Unmarshal(value, &uploadedVideo)
uploadedVideos = append(uploadedVideos, uploadedVideo)
}
return nil
})
if err != nil {
panic(err)
}
uploadedVideosBytes, _ := json.Marshal(uploadedVideos)
templates.ExecuteTemplate(w, "playVideo_new.html", string(uploadedVideosBytes))
}
}
func listVideosHandler(w http.ResponseWriter, r *http.Request) {
//templ, _ := template.ParseFiles("./templates/videos_new.html")
if r.Method == "GET" {
//var videos = []UploadedVideo{}
var uploadedVideos []UploadedVideo
var uploadedVideo UploadedVideo
db, err := badger.Open(badger.DefaultOptions(dbPath2).WithReadOnly(true))
if err != nil {
fmt.Println(err)
}
defer db.Close()
// search for video_ keys and append to uploadedVideos slice
err = db.View(func(txn *badger.Txn) error {
// Your code here…
opts := badger.DefaultIteratorOptions
//opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
prefix := []byte("video_")
var value []byte
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
videoEntry := it.Item()
//k := videoEntry.Key()
value, err = videoEntry.ValueCopy(nil)
if err != nil {
return err
}
json.Unmarshal(value, &uploadedVideo)
uploadedVideos = append(uploadedVideos, uploadedVideo)
}
return nil
})
if err != nil {
fmt.Println(err)
fmt.Println("error grabbing uploaded videos")
} else {
uploadedVideosBytes, _ := json.Marshal(uploadedVideos)
//fmt.Println(uploadedVideos)
err := templates.ExecuteTemplate(w, "home.html", string(uploadedVideosBytes))
if err != nil {
fmt.Println(err)
}
}
} else {
fmt.Println("no post requests allowed")
}
}
func getApiKey() string {
api_key := *apiID
return api_key
}
func getApiSecret() string {
api_secret := *apiSecret
return api_secret
}
func getUploadStatus(w http.ResponseWriter, r *http.Request) {
//fmt.Println("sending upload status")
//var progressSlice []float64
//fmt.Println("monitoring video transcoding status")
//time.Sleep(2 * time.Second)
//session := sess.Start(w, r)
req_videoID := strings.TrimPrefix(r.URL.Path, "/getUploadStatus/")
/*
if sessionManager.Get(r.Context(), "videoID") == nil {
fmt.Println("no videoID in cookie :(")
wg.Add(1)
go setVideoID(r)
wg.Wait()
} else {
temp_videoID = sessionManager.Get(r.Context(), "videoID").(string)
videoID = ""
}
*/
//fmt.Println(req_videoID)
// trying to use sync to solve the video progress issue
//mu.Unlock()
api_key := *apiID
api_secret := *apiSecret
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://api.thetavideoapi.com/video/"+req_videoID, nil)
req.Header.Add("x-tva-sa-id", api_key)
req.Header.Add("x-tva-sa-secret", api_secret)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
var transcodeVideoResponse TranscodeVideoResponse
err = json.Unmarshal(body, &transcodeVideoResponse)
if err != nil {
fmt.Println(err)
}
//fmt.Println(transcodeVideoResponse)
upload_progress := transcodeVideoResponse.Body.Videos[0].Progress
//upload_playbackURI := transcodeVideoResponse.Body.Videos[0].PlaybackURI
//upload_state := transcodeVideoResponse.Body.Videos[0].State
//fmt.Println(progress)
progressString := fmt.Sprint(upload_progress)
//progressResponse := ProgressResponse{}
if upload_progress == 100 {
w.Write([]byte(progressString))
fmt.Println("upload complete for video: ", req_videoID)
return
} else {
fmt.Println("fetching upload status for: ", req_videoID)
w.Write([]byte(progressString))
}
return
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
//loginTemplate, _ := template.ParseFiles("./templates/login.html")
var errorMessage string
if r.Method == "GET" {
//loginTemplate, _ := template.ParseFiles("./templates/login.html")
//loginTemplate.Execute(w, nil)
if value := sessionManager.Get(r.Context(), "username"); value != nil {
//templates.ExecuteTemplate(w, "login.html", value)
fmt.Println(value, "is already logged in")
templates.ExecuteTemplate(w, "login.html", value)
return
}
templates.ExecuteTemplate(w, "login.html", nil)
return
} else if r.Method == "POST" {
r.ParseForm()
username := r.FormValue("username")
password := r.FormValue("password")
db, err := badger.Open(badger.DefaultOptions(dbPath2).WithReadOnly(true))
defer db.Close()
if err != nil {
fmt.Println(err)
}
err = db.View(func(txn *badger.Txn) error {
// Your code here…
user := User{}
userEntry, err := txn.Get([]byte(username))
if err != nil {
fmt.Println(err)
fmt.Println("username not found")
errorMessage = "incorrect username or password"
//fmt.Fprintf(w, errorMessage)
//loginTemplate.Execute(w, "username not found")
templates.ExecuteTemplate(w, "login.html", errorMessage)
} else {
userByte, err := userEntry.ValueCopy(nil)
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(userByte, &user)
if err != nil {
fmt.Println(err)
}
userHash := user.Password
fmt.Println("stored hash for", username, ":", userHash)
err = bcrypt.CompareHashAndPassword([]byte(userHash), []byte(password))
fmt.Println(err)
if err != nil {
errorMessage = "incorrect username or password"
fmt.Println(errorMessage)
templates.ExecuteTemplate(w, "login.html", errorMessage)
} else {
fmt.Println("dickmabutt")
sessionManager.Put(r.Context(), "username", username)
fmt.Println("session cookie for ", username, "added to sessionManager")
fmt.Println(user.Password, user.Username, user.ID, user.Email)
templates.ExecuteTemplate(w, "login.html", username)
//http.Redirect(w, r, "/", 301)
//loginTemplate.Execute(w, user.Username)
//w.Write([]byte(username))
//w.WriteHeader(http.StatusOK)
}
}
return nil
})
if err != nil {
fmt.Println(err)
}
/*
db, err := bitcask.Open(dbPath, bitcask.WithSync(true))
db.Reopen()
if err != nil {fmt.Println(err)}
defer db.Close()
// check if user is in DB. If not, display error in html
usernameCheck := db.Has([]byte(username))
if usernameCheck == true {
// check password against one stored in db
user := User{}
userByte, _ := db.Get([]byte(username))
_ = json.Unmarshal(userByte, &user)
userPassword := user.Password
err := bcrypt.CompareHashAndPassword([]byte(userPassword), []byte(password))
if err != nil {
fmt.Println()
}
if err != nil {
errorMessage = "Incorrect Password"
//loginTemplate.Execute(w, "incorrect password")
} else {
fmt.Println("dickmabutt")
sessionManager.Put(r.Context(), "username", username)
fmt.Println(user.Password, user.Username, user.ID, user.Email)
http.Redirect(w, r, "/", 302)
}
} else {
errorMessage = "username not found"
//loginTemplate.Execute(w, "username not found")
}
fmt.Fprintf(w, errorMessage)
return
*/
}
return
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
if sessionManager.Exists(r.Context(), "username") == true {
sessionManager.Destroy(r.Context())
fmt.Println("not redirecting")
http.Redirect(w, r, "/", 302)
return
}
http.Redirect(w, r, "/", 302)
}
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
//registerTemplate, err := template.ParseFiles("./templates/register.html")
//fmt.Println(r.Method)
if r.Method == "GET" {
//fmt.Println("we're doing it")
err := templates.ExecuteTemplate(w, "register.html", nil)
if err != nil {
fmt.Println(err)
}
} else if r.Method == "POST" {
videos := make([]Video, 0)
uuidWithHyphen := uuid.New()
userID := strings.Replace(uuidWithHyphen.String(), "-", "", -1)
err := r.ParseForm()
if err != nil {
fmt.Println(err)
}
username := r.FormValue("username")
email := r.FormValue("email")
password := r.FormValue("password")
fmt.Println("new sign in for: ", username)
if password == "" {
fmt.Println("empty password")
}
db, err := badger.Open(badger.DefaultOptions(dbPath2))
if err != nil {
fmt.Println(err)
}
defer db.Close()
err = db.Update(func(txn *badger.Txn) error {
// Your code here…
userEntry, err := txn.Get([]byte(username))
if err != nil {
passwordHashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
fmt.Println("new user registered!", username, email, string(passwordHashed))
if err != nil {
log.Println(err)
}
// create user object
user := User{
Username: username,
Email: email,
Password: string(passwordHashed),
ID: userID,
Videos: videos,
}
fmt.Println(user, "\nregistered")
// serialize user object and send to DB
bytes, _ := json.Marshal(user)
txn.Set([]byte(username), bytes)
fmt.Println("user registered", user)
err = templates.ExecuteTemplate(w, "register.html", "registration successfule :)")
if err != nil {
panic(err)
}
return nil
} else {
bytes, _ := userEntry.ValueCopy(nil)
fmt.Println(bytes)
fmt.Println("username already exists")
templates.ExecuteTemplate(w, "register.html", "username already exists")
}
return nil
})
if err != nil {
fmt.Println(err)
}
/*
db, err := bitcask.Open(dbPath, bitcask.WithSync(true))
db.Reopen()
if err != nil {
fmt.Println(err)
}
defer db.Close()
var bytes []byte
videos := make([]Video, 0)
uuidWithHyphen := uuid.New()
userID := strings.Replace(uuidWithHyphen.String(), "-", "", -1)
err = r.ParseForm()
if err != nil {
fmt.Println(err)
}
username := r.FormValue("username")
email := r.FormValue("email")
password := r.FormValue("password")
fmt.Println(username)
if db.Has([]byte(username)) == true {
fmt.Println("username already exists")
registerTemplate.Execute(w, "username already exists")
return
}
passwordHashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
log.Println(err)
}
// create user object
user := User{
Username: username,
Email: email,
Password: string(passwordHashed),
ID: userID,
Videos: videos,
}
fmt.Println(user, "\nregistered")
// serialize user object and send to DB
bytes, _ = json.Marshal(user)
db.Put([]byte(username), bytes)
*/
http.Redirect(w, r, "/", 302)
return
}
return
}
func main() {
// scs session manager setup - cookie store in memory
sessionManager = scs.New()
sessionManager.Lifetime = 24 * time.Hour
// create temeplate object of all html files
templates, _ = template.ParseGlob("templates/*.html")
apiID = flag.String("api-id", "", "startup")
apiSecret = flag.String("api-secret", "", "startup")
ip = flag.String("ip", "", "startup")
port = flag.String("port", "8001", "startup")
dbPathInit := flag.String("db-path", "/tmp/db", "startup")
flag.Parse()
dbPath = *dbPathInit
dbPath2 = "/tmp/data"
//options.Dir = "data"
//options.ValueDir = "data"
if *apiID == "" || *apiSecret == "" {
fmt.Println("no API keys provided. Exiting")
return
}
defaultIPPort = *ip + ":" + *port
fmt.Println("api-id: ", *apiID)
fmt.Println("api-secret", *apiSecret)
fmt.Println("Listening on", defaultIPPort)
mux := mux.NewRouter()
mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./theta-svelte/public/"))))
//mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./theta-svelteKit/build/"))))
// upload video
mux.HandleFunc("/", rootHandler)
mux.HandleFunc("/login", loginHandler)
mux.HandleFunc("/logout", logoutHandler)
mux.HandleFunc("/register", registerHandler)
mux.HandleFunc("/playVideo/{id:video_[a-z0-9]{26}}", playVideoHandler)
mux.HandleFunc("/videos", listVideosHandler)
mux.HandleFunc("/upload", videoUploadHandler)
mux.HandleFunc("/getUploadStatus/{id:video_[a-z0-9]{26}}", getUploadStatus)
//watch video
http.ListenAndServe(defaultIPPort, sessionManager.LoadAndSave(mux))
}