-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
416 lines (355 loc) · 11 KB
/
server.go
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
package main
import (
"embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
//go:embed dist/*
var embeddedFiles embed.FS
var BaseDir string
type FileInfo struct {
Name string `json:"name"`
Path string `json:"path"`
IsDirectory bool `json:"isDirectory"`
Size int64 `json:"size"`
ModifiedTime time.Time `json:"modifiedTime"`
}
type Segment struct {
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
}
type VideoEditRequest struct {
VideoPath string `json:"videoPath"`
Segments []Segment `json:"segments"`
}
func toRelativePath(path string) string {
path = filepath.Clean(filepath.FromSlash(path))
baseDir := filepath.Clean(filepath.FromSlash(BaseDir))
rel, err := filepath.Rel(baseDir, path)
if err != nil {
log.Println("Error converting to relative path:", err)
return ""
}
return filepath.ToSlash(rel)
}
func toAbsolutePath(relPath string) (string, error) {
relPath = filepath.Clean(filepath.FromSlash(relPath))
absPath := filepath.Join(BaseDir, relPath)
if !strings.HasPrefix(absPath, BaseDir) {
return "", errors.New("invalid path: outside base directory")
}
return absPath, nil
}
func main() {
flag.StringVar(&BaseDir, "baseDir", "/www", "Base directory to serve files from")
flag.Parse()
if !filepath.IsAbs(BaseDir) {
log.Fatal("BaseDir must be an absolute path")
}
logFile, err := os.OpenFile("server.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatal("Could not open log file:", err)
}
defer logFile.Close()
log.SetOutput(logFile)
mux := http.NewServeMux()
mux.HandleFunc("/api/files", handleFiles)
mux.HandleFunc("/api/media", handleMediaStream)
mux.HandleFunc("/api/edit-video", handleEditVideo)
distFS, err := fs.Sub(embeddedFiles, "dist")
if err != nil {
log.Fatal("Failed to create sub filesystem:", err)
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
http.NotFound(w, r)
return
}
path := r.URL.Path
if path == "/" {
path = "/index.html"
}
path = strings.TrimPrefix(path, "/")
if content, err := fs.ReadFile(distFS, path); err == nil {
ext := filepath.Ext(path)
contentType := mime.TypeByExtension(ext)
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.Write(content)
return
}
content, err := fs.ReadFile(distFS, "index.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write(content)
})
fmt.Println("Server running on http://localhost:3001")
if err := http.ListenAndServe(":3001", mux); err != nil {
log.Fatal(err)
}
}
func handleFiles(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
listFiles(w, r)
} else if r.Method == http.MethodDelete {
deleteFile(w, r)
} else {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
}
func listFiles(w http.ResponseWriter, r *http.Request) {
relPath := r.URL.Query().Get("path")
if relPath == "" {
relPath = "/"
}
absPath, err := toAbsolutePath(relPath)
if err != nil {
log.Println("Invalid path:", err)
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid path"})
return
}
files, err := ioutil.ReadDir(absPath)
if err != nil {
log.Println("Error reading directory:", err)
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to read directory" + absPath})
return
}
var fileList []FileInfo
for _, file := range files {
fullPath := filepath.Join(absPath, file.Name())
fileInfo := FileInfo{
Name: file.Name(),
Path: toRelativePath(fullPath),
IsDirectory: file.IsDir(),
Size: file.Size(),
ModifiedTime: file.ModTime(),
}
fileList = append(fileList, fileInfo)
}
w.Header().Set("Content-Type", "application/json")
if len(fileList) == 0 {
// Return an empty array with 200 status code instead of 204
// This is more appropriate for REST APIs and easier to handle on the client side
json.NewEncoder(w).Encode([]FileInfo{})
return
}
json.NewEncoder(w).Encode(fileList)
}
func deleteFile(w http.ResponseWriter, r *http.Request) {
relPath := r.URL.Query().Get("path")
absPath, err := toAbsolutePath(relPath)
if err != nil {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
if info, err := os.Stat(absPath); err == nil && info.IsDir() {
err = os.RemoveAll(absPath)
} else {
err = os.Remove(absPath)
}
if err != nil {
http.Error(w, "Failed to delete file", http.StatusInternalServerError)
log.Println("Error deleting file:", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"success": true}`))
}
func handleMediaStream(w http.ResponseWriter, r *http.Request) {
relPath := r.URL.Query().Get("path")
absPath, err := toAbsolutePath(relPath)
if err != nil {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
if !fileExists(absPath) {
http.Error(w, "Media not found", http.StatusNotFound)
return
}
file, err := os.Open(absPath)
if err != nil {
http.Error(w, "Failed to open media file", http.StatusInternalServerError)
log.Println("Error opening media file:", err)
return
}
defer file.Close()
contentType := "application/octet-stream"
if strings.HasSuffix(absPath, ".mp4") {
contentType = "video/mp4"
} else if strings.HasSuffix(absPath, ".jpg") || strings.HasSuffix(absPath, ".jpeg") {
contentType = "image/jpeg"
} else if strings.HasSuffix(absPath, ".png") {
contentType = "image/png"
} else {
contentType = "application/file"
}
w.Header().Set("Content-Type", contentType)
http.ServeContent(w, r, filepath.Base(absPath), time.Now(), file)
}
func handleEditVideo(w http.ResponseWriter, r *http.Request) {
var req VideoEditRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
log.Println("Invalid request payload:", err)
return
}
absPath, err := toAbsolutePath(req.VideoPath)
if err != nil {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
log.Printf("Processing video: %s", req.VideoPath)
if len(req.Segments) == 1 {
segment := req.Segments[0]
duration, err := getTimeDifference(segment.StartTime, segment.EndTime)
if err != nil {
http.Error(w, "Invalid time format", http.StatusBadRequest)
log.Println("Invalid time format:", err)
return
}
outputPath := strings.TrimSuffix(absPath, filepath.Ext(absPath)) + "_merge.mp4"
err = processSegment(absPath, outputPath, segment.StartTime, duration)
if err != nil {
http.Error(w, "Failed to edit video", http.StatusInternalServerError)
log.Println("Error processing video segment:", err)
return
}
log.Printf("Video edited successfully, output: %s", outputPath)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"success": true, "output": "%s"}`, toRelativePath(outputPath))))
} else {
segmentFiles, err := processSegments(absPath, req.Segments)
if err != nil {
http.Error(w, "Failed to process segments", http.StatusInternalServerError)
log.Println("Error processing segments:", err)
return
}
defer cleanupFiles(segmentFiles)
outputPath := strings.TrimSuffix(absPath, filepath.Ext(absPath)) + "_merged.mp4"
err = mergeSegments(segmentFiles, outputPath)
if err != nil {
http.Error(w, "Failed to merge video segments", http.StatusInternalServerError)
log.Println("Error merging video segments:", err)
return
}
log.Printf("Video merged successfully, output: %s", outputPath)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"success": true, "output": "%s"}`, toRelativePath(outputPath))))
}
}
func getTimeDifference(start, end string) (string, error) {
startParts := strings.Split(start, ":")
endParts := strings.Split(end, ":")
if len(startParts) != 3 || len(endParts) != 3 {
return "", errors.New("invalid time format")
}
startHours, err := strconv.Atoi(startParts[0])
if err != nil {
return "", err
}
startMinutes, err := strconv.Atoi(startParts[1])
if err != nil {
return "", err
}
startSeconds, err := strconv.Atoi(startParts[2])
if err != nil {
return "", err
}
endHours, err := strconv.Atoi(endParts[0])
if err != nil {
return "", err
}
endMinutes, err := strconv.Atoi(endParts[1])
if err != nil {
return "", err
}
endSeconds, err := strconv.Atoi(endParts[2])
if err != nil {
return "", err
}
startTotalSeconds := startHours*3600 + startMinutes*60 + startSeconds
endTotalSeconds := endHours*3600 + endMinutes*60 + endSeconds
return strconv.Itoa(endTotalSeconds - startTotalSeconds), nil
}
func processSegment(inputPath, outputPath, startTime, duration string) error {
log.Printf("Running ffmpeg command: ffmpeg -i %s -ss %s -t %s -c copy %s", inputPath, startTime, duration, outputPath)
cmd := exec.Command("ffmpeg", "-i", inputPath, "-ss", startTime, "-t", duration, "-c", "copy", outputPath)
err := cmd.Run()
if err != nil {
log.Println("Error running ffmpeg command:", err)
}
return err
}
func processSegments(inputPath string, segments []Segment) ([]string, error) {
tempDir := filepath.Join(filepath.Dir(inputPath), ".temp")
os.MkdirAll(tempDir, 0755)
var segmentFiles []string
for i, segment := range segments {
outputPath := filepath.Join(tempDir, fmt.Sprintf("segment_%d.mp4", i))
duration, err := getTimeDifference(segment.StartTime, segment.EndTime)
if err != nil {
log.Println("Invalid time format:", err)
return nil, err
}
err = processSegment(inputPath, outputPath, segment.StartTime, duration)
if err != nil {
log.Println("Error processing segment:", err)
return nil, err
}
segmentFiles = append(segmentFiles, outputPath)
}
return segmentFiles, nil
}
func mergeSegments(segmentFiles []string, outputPath string) error {
tempDir := filepath.Dir(segmentFiles[0])
concatFile := filepath.Join(tempDir, "concat.txt")
concatContent := ""
for _, file := range segmentFiles {
concatContent += fmt.Sprintf("file '%s'\n", file)
}
err := ioutil.WriteFile(concatFile, []byte(concatContent), 0644)
if err != nil {
log.Println("Error writing concat file:", err)
return err
}
log.Printf("Running ffmpeg command: ffmpeg -f concat -safe 0 -i %s -c copy %s", concatFile, outputPath)
cmd := exec.Command("ffmpeg", "-f", "concat", "-safe", "0", "-i", concatFile, "-c", "copy", outputPath)
err = cmd.Run()
if err != nil {
log.Println("Error merging segments:", err)
}
return err
}
func cleanupFiles(files []string) {
tempDir := filepath.Dir(files[0])
err := os.RemoveAll(tempDir)
if err != nil {
log.Printf("Failed to clean up temp directory %s: %v", tempDir, err)
} else {
log.Printf("Successfully cleaned up temp directory %s", tempDir)
}
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}