about summary refs log tree commit diff
path: root/src/rest-api/handler/handler.go
blob: 1aa618b43bf3362e977edccb187e33ed475b40ff (plain) (blame)
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
package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	"github.com/segmentio/kafka-go"
)

type Handler struct {
	db           DB
	kafka_writer *kafka.Writer
}

func NewHandler(db *sqlx.DB, kafka_writer *kafka.Writer) Handler {
	return Handler{
		db:           NewDB(db),
		kafka_writer: kafka_writer,
	}
}

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	api_key := r.Header.Get("API_KEY")

	log.Println("API KEY: ", api_key)

	user_id, err := h.db.GetUserIDByAPIKey(r.Context(), api_key)
	if err != nil {
		http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
		return
	}
	if user_id == "" {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	log.Println("User ID: ", user_id)

	switch r.Method {
	case http.MethodGet:
		h.handleGet(w, r, user_id)
	case http.MethodPost:
		h.handlePost(w, r, user_id)
	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func (h Handler) handleGet(w http.ResponseWriter, r *http.Request, user_id string) {
	if strings.Contains(r.URL.Path, "/file/") {
		h.handleGetFile(w, r, user_id)
	} else if strings.Contains(r.URL.Path, "/restored-files/") {
		h.handleGetRestoredFiles(w, r, user_id)
	} else {
		fmt.Println("Path: ", r.URL.Path)
		http.NotFound(w, r)
	}

}

func (h Handler) handleGetFile(w http.ResponseWriter, r *http.Request, user_id string) {
	filePath := r.URL.Query().Get("path")
	if filePath == "" {
		http.Error(w, "Invalid file path", http.StatusBadRequest)
		return
	}

	log.Println("File path: ", filePath)

	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()
	file, err := h.db.GetLatestFileByPath(ctx, filePath, user_id)
	if err != nil {
		http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
		return
	}

	bytes, err := json.Marshal(file)
	if err != nil {
		http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
		return
	}

	fmt.Fprint(w, string(bytes))
}

func (h Handler) handleGetRestoredFiles(w http.ResponseWriter, r *http.Request, user_id string) {
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()
	files, err := h.db.GetAndDeleteRestoredFiles(ctx, user_id)
	if err != nil {
		http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
		return
	}

	bytes, err := json.Marshal(files)
	if err != nil {
		http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError)
		return
	}

	fmt.Fprint(w, string(bytes))
}

func (h Handler) handlePost(w http.ResponseWriter, r *http.Request, user_id string) {
	if !strings.Contains(r.URL.Path, "/file/") {
		http.NotFound(w, r)
		return
	}

	bytes, err := io.ReadAll(io.Reader(r.Body))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	err = h.kafka_writer.WriteMessages(ctx, kafka.Message{
		Key:   []byte("key"), //TODO:This routes to a partition. We should probably route by agent UUID TODO: wont this negate having multiple topics
		Value: bytes,
		Headers: []kafka.Header{{
			Key:   "user_id",
			Value: []byte(user_id),
		}},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Fprint(w, "Hello, World!", string(bytes))
	log.Println("Request received :)", r.RemoteAddr, string(bytes))
}