File size: 6,394 Bytes
b55a115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package controllers

import (
    "compress/gzip"
    "errors"
    "io"
    "net/http"
    "path/filepath"
    "strings"
    "fmt"

    "github.com/gin-gonic/gin"
    "github.com/google/uuid"

    "abdanhafidz.com/go-boilerplate/models/dto"
    http_error "abdanhafidz.com/go-boilerplate/models/error"
    "abdanhafidz.com/go-boilerplate/services"
)

type UploadController interface{
	Upload(ctx *gin.Context)
	GetFileByID(ctx *gin.Context)
}

type uploadController struct{uploadService services.UploadService}

func NewUploadController(uploadService services.UploadService) UploadController { return &uploadController{ uploadService: uploadService } }

func (c *uploadController) Upload(ctx *gin.Context) {
    fmt.Println("👉 Content-Type:", ctx.GetHeader("Content-Type"))

    if !strings.Contains(ctx.GetHeader("Content-Type"), "multipart/form-data") {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "status":  "error",
            "code":    "INVALID_FORM",
            "message": "Content-Type must be multipart/form-data",
        })
        return
    }

    if strings.EqualFold(ctx.GetHeader("Content-Encoding"), "gzip") {
        gz, err := gzip.NewReader(ctx.Request.Body)
        if err != nil {
            ctx.JSON(http.StatusBadRequest, gin.H{
                "status":  "error",
                "code":    "INVALID_FORM",
                "message": "Failed to decode gzip request body",
            })
            return
        }
        ctx.Request.Body = io.NopCloser(gz)
    }

    // Gunakan limit 32MB
    if err := ctx.Request.ParseMultipartForm(32 << 20); err != nil {
        
        // 🔴 DEBUG: Print error ASLI ke terminal
        fmt.Println("❌ ERROR ParseMultipartForm:", err.Error())

        // Respon sementara dengan error asli agar terlihat di Postman
        ctx.JSON(http.StatusBadRequest, gin.H{
            "status":      "error",
            "code":        "INVALID_FORM",
            "message":     "Failed to parse form data",
            "debug_error": err.Error(), // <--- Kita butuh baca ini
        })
        return
    }

	form, err := ctx.MultipartForm()
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  "error",
			"code":    "INVALID_DATA",
			"message": "Invalid form data",
		})
		return
	}

	files := form.File["files"]
	if len(files) == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  "error",
			"message": "No files uploaded",
		})
		return
	}

	uploadContext := ctx.PostForm("context")
	if uploadContext == "" {
		ext := strings.ToLower(filepath.Ext(files[0].Filename))
		uploadContext = c.inferContextFromExt(ext)
	}

	accountIDStr := ctx.GetString("account_id")
	if accountIDStr == "" {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "Unauthorized: Missing account ID",
		})
		return
	}

	accountID, err := uuid.Parse(accountIDStr)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "Unauthorized: Invalid UUID format",
		})
		return
	}

	uploadedFiles, err := c.uploadService.UploadFiles(ctx, files, uploadContext, accountID)
	if err != nil {
		if strings.Contains(err.Error(), "Invalid Compact JWS") {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"status":  "error",
				"message": "Storage misconfiguration: invalid Supabase service key",
			})
			return
		}
		if errors.Is(err, http_error.FILE_TOO_LARGE) ||
			errors.Is(err, http_error.INVALID_FILE_TYPE) ||
			errors.Is(err, http_error.BAD_REQUEST_ERROR) ||
			errors.Is(err, http_error.INVALID_DATA_PAYLOAD) {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"status":  "error",
				"message": err.Error(),
			})
			return
		}

		if errors.Is(err, http_error.PARTIAL_UPLOAD_FAILURE) {
			ctx.JSON(http.StatusUnprocessableEntity, gin.H{
				"status":  "error",
				"message": err.Error(),
				"data":    uploadedFiles,
			})
			return
		}

		ctx.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": err.Error(),
		})
		return
	}

	var fileResponses []dto.FileResponse
	for _, f := range uploadedFiles {
		fileResponses = append(fileResponses, dto.FileResponse{
			Id:           f.Id,
			OriginalName: f.OriginalName,
			URL:          f.Path,
			MimeType:     f.MimeType,
			Size:         f.Size,
			CreatedAt:    f.CreatedAt,
		})
	}

	ctx.JSON(http.StatusCreated, dto.FileUploadResponse{
		Status:  "success",
		Message: "Files uploaded successfully",
		Data:    fileResponses,
	})
}

func (c *uploadController) GetFileByID(ctx *gin.Context) {
	fileIDStr := ctx.Param("id")
	fileID, err := uuid.Parse(fileIDStr)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  "error",
			"message": "Invalid file ID format",
		})
		return
	}

	accountIDStr := ctx.GetString("account_id")
	if accountIDStr == "" {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "Unauthorized: Missing account ID",
		})
		return
	}

	accountID, err := uuid.Parse(accountIDStr)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"status":  "error",
			"message": "Unauthorized: Invalid UUID format",
		})
		return
	}

	fileData, err := c.uploadService.GetFileByID(ctx, fileID, accountID)
	if err != nil {
		if errors.Is(err, http_error.NOT_FOUND_ERROR) {
			ctx.JSON(http.StatusNotFound, gin.H{
				"status":  "error",
				"message": "File not found or access denied",
			})
			return
		}

		ctx.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": err.Error(),
		})
		return
	}

	response := dto.FileResponse{
		Id:           fileData.Id,
		OriginalName: fileData.OriginalName,
		URL:          fileData.Path,
		MimeType:     fileData.MimeType,
		Size:         fileData.Size,
		CreatedAt:    fileData.CreatedAt,
	}

	ctx.JSON(http.StatusOK, dto.FileResponseSingle{
		Status:  "success",
		Message: "File retrieved successfully",
		Data:    response,
	})
}

func (c *uploadController) inferContextFromExt(ext string) string {
	images := map[string]bool{
		".jpg": true, ".jpeg": true, ".png": true, ".webp": true,
	}
	isSourceCode := map[string]bool{
		".cpp": true, ".c": true, ".py": true, ".java": true,
		".go": true, ".js": true, ".txt": true,
	}
	isDocument := map[string]bool{
		".pdf": true,
	}

	if images[ext] {
		return "image"
	}
	if isSourceCode[ext] {
		return "submission"
	}
	if isDocument[ext] {
		return "material"
	}
	return ""
}