forked from billy4479/telegram-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.go
95 lines (77 loc) · 2.06 KB
/
files.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
package api
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/qiangweihewu/telegram-yunpan/backend/bot"
"github.com/qiangweihewu/telegram-yunpan/backend/db"
"github.com/labstack/echo/v4"
)
func GetFile(c echo.Context) error {
id, userid, err := getIDAndUserIDFromContext(c)
if err != nil {
return err
}
content, err := db.GetFileByID(id, userid)
if err = handleDBErr(c, err); err != nil {
return err
}
return c.JSON(http.StatusOK, content)
}
func DownloadFile(i *bot.BotInterface) func(c echo.Context) error {
return func(c echo.Context) error {
id, userid, err := getIDAndUserIDFromContext(c)
if err != nil {
return err
}
f, err := db.GetFileByID(id, userid)
if err = handleDBErr(c, err); err != nil {
return err
}
url, err := i.GetFileURL(f.FileID)
if err != nil {
return returnErrorJSON(c, http.StatusNotFound, err)
}
res, err := http.Get(url)
if err != nil {
return returnErrorJSON(c, http.StatusInternalServerError, err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return returnErrorJSON(c, res.StatusCode, fmt.Errorf(string(b)))
}
// TODO: Fix Content-Type, maybe store it with the file itself
return c.Stream(http.StatusOK, res.Header.Get("Content-Type"), res.Body)
}
}
func DeleteFile(c echo.Context) error {
id, userid, err := getIDAndUserIDFromContext(c)
if err != nil {
return err
}
err = db.DeleteFile(id, userid)
if err = handleDBErr(c, err); err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func UpdateFile(c echo.Context) error {
userid, err := getUserIDFromContext(c)
if err != nil {
return returnErrorJSON(c, http.StatusUnauthorized, err)
}
var file db.File
err = c.Bind(&file)
if err != nil {
return returnErrorJSON(c, http.StatusBadRequest, err)
}
err = db.EditFile(&file, userid)
if err = handleDBErr(c, err); err != nil {
return err
}
return c.JSON(http.StatusOK, file)
}