From 4e576ad7e2ac3981eb69c88e27100200ef9c410d Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 14:45:59 +0800 Subject: [PATCH 1/9] =?UTF-8?q?feat:=E4=BD=BF=E7=94=A8sqlite=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E6=96=87=E4=BB=B6=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/templates/files.tmpl | 2 +- assets/templates/footer.tmpl | 24 ++++++++++++-- build.bat | 11 +++++++ conf/conf.go | 9 ++++-- control/control.go | 53 +++++++++++++++++++++++------- control/db.go | 63 ++++++++++++++++++++++++++++++++++++ go.mod | 7 +++- go.sum | 4 +++ main.go | 14 ++++++++ 9 files changed, 168 insertions(+), 19 deletions(-) create mode 100644 build.bat create mode 100644 control/db.go diff --git a/assets/templates/files.tmpl b/assets/templates/files.tmpl index 8659c8a..e48fb8b 100644 --- a/assets/templates/files.tmpl +++ b/assets/templates/files.tmpl @@ -1,6 +1,6 @@ {{template "public/header" .}}

上传文件到 Telegram

+ type="file" name="file" id="uploadFile" class="custom-file-input" multiple>
上传中...
{{template "public/footer" .}} diff --git a/assets/templates/footer.tmpl b/assets/templates/footer.tmpl index ed91446..c531994 100644 --- a/assets/templates/footer.tmpl +++ b/assets/templates/footer.tmpl @@ -58,7 +58,7 @@ function uploadImg(e, ms) { return new Promise((resolve, reject) => { var o = new FormData(); - o.append("image", e); + o.append("file", e); var isImage = e.type.startsWith('image/'); $("#uploadButton").prop("disabled", !0); $("#uploadButton").text("上传中"); @@ -74,7 +74,9 @@ contentType: !1, processData: !1, success: function (e) { + var link = a + e.message; + var proxyUrl = e.proxyUrl var t; if (e.code == 1) { if (ms) { @@ -90,6 +92,17 @@ link + ')">MarkdownBBCode'+ + '
上传成功,代理图片外链:' + + proxyUrl + + '
' ); } else { @@ -98,8 +111,13 @@ link + '">' + link + - "" - ); + "" + + '
上传成功,代理文件外链:' + + proxyUrl + + "
" + ) } } resolve(e.message); diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..56369a2 --- /dev/null +++ b/build.bat @@ -0,0 +1,11 @@ +@echo off +REM 设置目标操作系统为 Linux,架构为 64 位 +set GOOS=freebsd +set GOARCH=amd64 + +REM 编译 Go 程序并输出为指定的二进制文件名 +go build -o tgState main.go + +REM 提示编译完成 +echo 编译完成,生成了 Linux 版本的二进制文件 tgState +pause diff --git a/conf/conf.go b/conf/conf.go index 2d7ac60..4d262e3 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -5,11 +5,14 @@ var ChannelName string var Pass string var Mode string var BaseUrl string +var AllowedExts string +var ProxyUrl string type UploadResponse struct { - Code int `json:"code"` - Message string `json:"message"` - ImgUrl string `json:"url"` + Code int `json:"code"` + Message string `json:"message"` + ImgUrl string `json:"url"` + ProxyUrl string `json:"proxyUrl"` } const FileRoute = "/d/" diff --git a/control/control.go b/control/control.go index 3850919..8081aa7 100644 --- a/control/control.go +++ b/control/control.go @@ -2,10 +2,12 @@ package control import ( "encoding/json" + "fmt" "html/template" "io" "log" "net/http" + "net/url" "path/filepath" "strconv" "strings" @@ -19,9 +21,11 @@ import ( // UploadImageAPI 上传图片api func UploadImageAPI(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") + if r.Method == http.MethodPost { // 获取上传的文件 - file, header, err := r.FormFile("image") + file, header, err := r.FormFile("file") + if err != nil { errJsonMsg("Unable to get file", w) // http.Error(w, "Unable to get file", http.StatusBadRequest) @@ -35,7 +39,14 @@ func UploadImageAPI(w http.ResponseWriter, r *http.Request) { } // 检查文件类型 allowedExts := []string{".jpg", ".jpeg", ".png"} - ext := filepath.Ext(header.Filename) + + // 如果设置了AllowedExts,则使用设置的文件类型 + if len(conf.AllowedExts) > 0 { + allowedExts = append(allowedExts, strings.Split(conf.AllowedExts, ",")...) + } + + var fileName = header.Filename + ext := filepath.Ext(fileName) valid := false for _, allowedExt := range allowedExts { if ext == allowedExt { @@ -44,7 +55,7 @@ func UploadImageAPI(w http.ResponseWriter, r *http.Request) { } } if conf.Mode != "p" && !valid { - errJsonMsg("Invalid file type. Only .jpg, .jpeg, and .png are allowed.", w) + errJsonMsg(fmt.Sprintf("Invalid file type. Only .jpg, .jpeg, and .png %s are allowed.", conf.AllowedExts), w) // http.Error(w, "Invalid file type. Only .jpg, .jpeg, and .png are allowed.", http.StatusBadRequest) return } @@ -52,12 +63,26 @@ func UploadImageAPI(w http.ResponseWriter, r *http.Request) { Code: 0, Message: "error", } - img := conf.FileRoute + utils.UpDocument(utils.TgFileData(header.Filename, file)) - if img != conf.FileRoute { + fileId := utils.UpDocument(utils.TgFileData(fileName, file)) + if "blob" != fileName { + ip := r.RemoteAddr // 获取上传者IP + // 插入数据到数据库 + err := SaveFileRecord(fileId, fileName, ip) + if err != nil { + errJsonMsg("Unable to save file record", w) + } + } + + downloadUrl := conf.FileRoute + fileId + if downloadUrl != conf.FileRoute { + imageUrl := strings.TrimSuffix(conf.BaseUrl, "/") + downloadUrl + // url encode imageUrl + proxyUrl := conf.ProxyUrl + "/" + url.QueryEscape(imageUrl) res = conf.UploadResponse{ - Code: 1, - Message: img, - ImgUrl: strings.TrimSuffix(conf.BaseUrl, "/") + img, + Code: 1, + Message: downloadUrl, + ImgUrl: imageUrl, + ProxyUrl: proxyUrl, } } w.Header().Set("Content-Type", "application/json") @@ -81,8 +106,8 @@ func errJsonMsg(msg string, w http.ResponseWriter) { } func D(w http.ResponseWriter, r *http.Request) { path := r.URL.Path - id := strings.TrimPrefix(path, conf.FileRoute) - if id == "" { + fileId := strings.TrimPrefix(path, conf.FileRoute) + if fileId == "" { // 设置响应的状态码为 404 w.WriteHeader(http.StatusNotFound) // 写入响应内容 @@ -91,7 +116,7 @@ func D(w http.ResponseWriter, r *http.Request) { } // 发起HTTP GET请求来获取Telegram图片 - fileUrl, _ := utils.GetDownloadUrl(id) + fileUrl, _ := utils.GetDownloadUrl(fileId) resp, err := http.Get(fileUrl) if err != nil { http.Error(w, "Failed to fetch content", http.StatusInternalServerError) @@ -156,6 +181,12 @@ func D(w http.ResponseWriter, r *http.Request) { } else { // 使用DetectContentType函数检测文件类型 w.Header().Set("Content-Type", http.DetectContentType(buffer)) + + fileName, err := GetFileNameByID(fileId) + if err == nil && fileName != "" { + w.Header().Set("Content-Disposition", "attachment; filename=\""+fileName+"\"") + } + _, err = w.Write(buffer[:n]) if err != nil { http.Error(w, "Failed to write content", http.StatusInternalServerError) diff --git a/control/db.go b/control/db.go new file mode 100644 index 0000000..053ed6b --- /dev/null +++ b/control/db.go @@ -0,0 +1,63 @@ +package control + +import ( + "database/sql" + "errors" + "fmt" + _ "github.com/mattn/go-sqlite3" + "log" + "sync" +) + +var ( + db *sql.DB + once sync.Once +) + +// InitDB 初始化数据库,创建表结构 +func InitDB() (*sql.DB, error) { + var err error + // 使用 sync.Once 确保数据库只初始化一次 + once.Do(func() { + db, err = sql.Open("sqlite3", "./files.db") + if err != nil { + log.Fatal("Failed to open database:", err) + } + + query := `CREATE TABLE IF NOT EXISTS uploaded_files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + fileId TEXT NOT NULL, + filename TEXT NOT NULL, + ip TEXT NOT NULL, + time TIMESTAMP DEFAULT CURRENT_TIMESTAMP + );` + _, err = db.Exec(query) + if err != nil { + log.Fatal("Failed to create table:", err) + } + }) + + return db, err +} + +// GetFileNameByID 查询文件名 +func GetFileNameByID(id string) (string, error) { + var fileName string + // 执行查询,获取对应id的fileName + query := "SELECT filename FROM uploaded_files WHERE fileId = ?" + err := db.QueryRow(query, id).Scan(&fileName) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return "", fmt.Errorf("no file found with id %s", id) + } + return "", err + } + + return fileName, nil +} + +func SaveFileRecord(fileID string, fileName string, ip string) error { + // 插入数据到数据库 + _, err := db.Exec("INSERT INTO uploaded_files (fileId, filename, ip) VALUES (?, ?, ?)", fileID, fileName, ip) + return err +} diff --git a/go.mod b/go.mod index c744d82..b8a8b53 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,9 @@ module csz.net/tgstate go 1.20 -require github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 +require ( + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/joho/godotenv v1.5.1 +) + +require github.com/mattn/go-sqlite3 v1.14.24 // indirect diff --git a/go.sum b/go.sum index db8e45c..d010c00 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,6 @@ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= +github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= diff --git a/main.go b/main.go index 1191006..b21adb7 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,8 @@ package main import ( "flag" "fmt" + "github.com/joho/godotenv" + "log" "net" "net/http" "os" @@ -47,12 +49,19 @@ func web() { } func init() { + err := godotenv.Load() + if err != nil { + log.Fatal(err) + } + flag.StringVar(&webPort, "port", "8088", "Web Port") flag.StringVar(&conf.BotToken, "token", os.Getenv("token"), "Bot Token") flag.StringVar(&conf.ChannelName, "target", os.Getenv("target"), "Channel Name or ID") flag.StringVar(&conf.Pass, "pass", os.Getenv("pass"), "Visit Password") flag.StringVar(&conf.Mode, "mode", os.Getenv("mode"), "Run mode") flag.StringVar(&conf.BaseUrl, "url", os.Getenv("url"), "Base Url") + flag.StringVar(&conf.AllowedExts, "exts", os.Getenv("exts"), "Allowed Exts") + flag.StringVar(&conf.ProxyUrl, "proxyUrl", os.Getenv("proxyUrl"), "proxy url") flag.Parse() if conf.Mode == "m" { OptApi = false @@ -60,4 +69,9 @@ func init() { if conf.Mode != "p" && conf.Mode != "m" { conf.Mode = "p" } + _, err = control.InitDB() + if err != nil { + log.Fatal(err) + } + } From de81c5fe735ff293fb2d7fbf0f6f52cdc8eb89f0 Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 14:50:02 +0800 Subject: [PATCH 2/9] build:add build_freebsd.sh --- build_freebsd.sh | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 build_freebsd.sh diff --git a/build_freebsd.sh b/build_freebsd.sh new file mode 100644 index 0000000..84d3ebf --- /dev/null +++ b/build_freebsd.sh @@ -0,0 +1,2 @@ +#/bin/bash +sed -i '' 's/go 1.20/go 1.17/' go.mod && go mod tidy && CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -o tgState main.go \ No newline at end of file From fee1c3c74b03685bd92efb9ed5915c186f623040 Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 14:57:32 +0800 Subject: [PATCH 3/9] fix:go-sqlite3 requires cgo to work --- .github/workflows/build-go.yml | 2 +- build_freebsd.sh | 3 ++- main.go | 7 ++----- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build-go.yml b/.github/workflows/build-go.yml index d497cc3..119eae4 100644 --- a/.github/workflows/build-go.yml +++ b/.github/workflows/build-go.yml @@ -26,7 +26,7 @@ jobs: - name: Build Linux arm64 run: | - CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o tgState main.go + CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -o tgState main.go - name: Zip Linux amd64 run: | diff --git a/build_freebsd.sh b/build_freebsd.sh index 84d3ebf..d0f54bd 100644 --- a/build_freebsd.sh +++ b/build_freebsd.sh @@ -1,2 +1,3 @@ #/bin/bash -sed -i '' 's/go 1.20/go 1.17/' go.mod && go mod tidy && CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -o tgState main.go \ No newline at end of file +# fix Failed to create table:Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub +sed -i '' 's/go 1.20/go 1.17/' go.mod && go mod tidy && CGO_ENABLED=1 GOOS=freebsd GOARCH=amd64 go build -o tgState main.go \ No newline at end of file diff --git a/main.go b/main.go index b21adb7..b589488 100644 --- a/main.go +++ b/main.go @@ -49,10 +49,7 @@ func web() { } func init() { - err := godotenv.Load() - if err != nil { - log.Fatal(err) - } + _ = godotenv.Load() flag.StringVar(&webPort, "port", "8088", "Web Port") flag.StringVar(&conf.BotToken, "token", os.Getenv("token"), "Bot Token") @@ -69,7 +66,7 @@ func init() { if conf.Mode != "p" && conf.Mode != "m" { conf.Mode = "p" } - _, err = control.InitDB() + _, err := control.InitDB() if err != nil { log.Fatal(err) } From f7a1b774e6de0b6c68218021b9988d1376965bce Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 15:44:27 +0800 Subject: [PATCH 4/9] =?UTF-8?q?feat:=E6=9F=A5=E7=9C=8B=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 7 ++++-- api/vercel.go | 4 ++-- conf/conf.go | 7 ++++++ control/control.go | 54 +++++++++++++++++++++++++++++++++++----------- control/db.go | 36 +++++++++++++++++++++++++++++++ main.go | 4 +++- 6 files changed, 94 insertions(+), 18 deletions(-) diff --git a/.gitignore b/.gitignore index bccfc20..f59f443 100644 --- a/.gitignore +++ b/.gitignore @@ -23,5 +23,8 @@ mk.txt .idea/* .vscode/* tmp/* -.air.toml -.vercel +.air.toml +.vercel +/.env +/files.db +/tgState.zip diff --git a/api/vercel.go b/api/vercel.go index e97c081..c3dafbf 100644 --- a/api/vercel.go +++ b/api/vercel.go @@ -24,8 +24,8 @@ func Vercel(w http.ResponseWriter, r *http.Request) { } switch path { case "/api": - // 调用 control 包中的 UploadImageAPI 处理函数 - control.Middleware(control.UploadImageAPI)(w, r) + // 调用 control 包中的 UploadAPI 处理函数 + control.Middleware(control.UploadAPI)(w, r) case "/pwd": control.Pwd(w, r) default: diff --git a/conf/conf.go b/conf/conf.go index 4d262e3..1525647 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -3,6 +3,7 @@ package conf var BotToken string var ChannelName string var Pass string +var ApiPass string var Mode string var BaseUrl string var AllowedExts string @@ -15,4 +16,10 @@ type UploadResponse struct { ProxyUrl string `json:"proxyUrl"` } +type ResponseResult struct { + Code int `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data"` +} + const FileRoute = "/d/" diff --git a/control/control.go b/control/control.go index 8081aa7..6d6442f 100644 --- a/control/control.go +++ b/control/control.go @@ -18,8 +18,8 @@ import ( "csz.net/tgstate/utils" ) -// UploadImageAPI 上传图片api -func UploadImageAPI(w http.ResponseWriter, r *http.Request) { +// UploadAPI 上传图片api +func UploadAPI(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == http.MethodPost { @@ -94,16 +94,8 @@ func UploadImageAPI(w http.ResponseWriter, r *http.Request) { // 如果不是POST请求,返回错误响应 http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) } -func errJsonMsg(msg string, w http.ResponseWriter) { - // 这里示例直接返回JSON响应 - response := conf.UploadResponse{ - Code: 0, - Message: msg, - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(response) -} + +// D 下载文件 func D(w http.ResponseWriter, r *http.Request) { path := r.URL.Path fileId := strings.TrimPrefix(path, conf.FileRoute) @@ -111,7 +103,7 @@ func D(w http.ResponseWriter, r *http.Request) { // 设置响应的状态码为 404 w.WriteHeader(http.StatusNotFound) // 写入响应内容 - w.Write([]byte("404 Not Found")) + errJsonMsg("404 Not Found", w) return } @@ -301,6 +293,42 @@ func Pwd(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/", http.StatusSeeOther) } +func FilesAPI(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + password := r.URL.Query().Get("password") + response := conf.ResponseResult{ + Code: 0, + Message: "ok", + } + + if conf.ApiPass != "" && password != conf.ApiPass { + response.Message = "Unauthorized" + response.Code = http.StatusUnauthorized + w.WriteHeader(http.StatusUnauthorized) + json.NewEncoder(w).Encode(response) + return + } + + record, err := SelectAllRecord() + response.Data = record + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + } + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(response) +} + +func errJsonMsg(msg string, w http.ResponseWriter) { + // 这里示例直接返回JSON响应 + response := conf.UploadResponse{ + Code: 0, + Message: msg, + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(response) +} + func Middleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // 只有当密码设置并且不为"none"时,才进行检查 diff --git a/control/db.go b/control/db.go index 053ed6b..88b5831 100644 --- a/control/db.go +++ b/control/db.go @@ -7,6 +7,7 @@ import ( _ "github.com/mattn/go-sqlite3" "log" "sync" + "time" ) var ( @@ -61,3 +62,38 @@ func SaveFileRecord(fileID string, fileName string, ip string) error { _, err := db.Exec("INSERT INTO uploaded_files (fileId, filename, ip) VALUES (?, ?, ?)", fileID, fileName, ip) return err } + +type FileRecord struct { + FileId string `json:"fileId"` + Filename string `json:"filename"` + Ip string `json:"ip"` + Time time.Time `json:"time"` +} + +func SelectAllRecord() ([]FileRecord, error) { + // 查询所有记录 + rows, err := db.Query("SELECT fileId, filename, ip, time FROM uploaded_files") + if err != nil { + return nil, err + } + defer rows.Close() + + var records []FileRecord + + // 迭代查询结果 + for rows.Next() { + var record FileRecord + err := rows.Scan(&record.FileId, &record.Filename, &record.Ip, &record.Time) + if err != nil { + return nil, err + } + records = append(records, record) + } + + // 检查查询错误 + if err = rows.Err(); err != nil { + return nil, err + } + + return records, nil +} diff --git a/main.go b/main.go index b589488..bab7f97 100644 --- a/main.go +++ b/main.go @@ -33,7 +33,8 @@ func web() { if conf.Pass != "" && conf.Pass != "none" { http.HandleFunc("/pwd", control.Pwd) } - http.HandleFunc("/api", control.Middleware(control.UploadImageAPI)) + http.HandleFunc("/api", control.Middleware(control.UploadAPI)) + http.HandleFunc("/files", control.Middleware(control.FilesAPI)) http.HandleFunc("/", control.Middleware(control.Index)) } @@ -55,6 +56,7 @@ func init() { flag.StringVar(&conf.BotToken, "token", os.Getenv("token"), "Bot Token") flag.StringVar(&conf.ChannelName, "target", os.Getenv("target"), "Channel Name or ID") flag.StringVar(&conf.Pass, "pass", os.Getenv("pass"), "Visit Password") + flag.StringVar(&conf.ApiPass, "apiPass", os.Getenv("apiPass"), "API Visit Password") flag.StringVar(&conf.Mode, "mode", os.Getenv("mode"), "Run mode") flag.StringVar(&conf.BaseUrl, "url", os.Getenv("url"), "Base Url") flag.StringVar(&conf.AllowedExts, "exts", os.Getenv("exts"), "Allowed Exts") From 36812f36d162ee905ec7d0bc29a23987c5635b5b Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 16:00:36 +0800 Subject: [PATCH 5/9] =?UTF-8?q?feat:=E9=80=9A=E8=BF=87=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=90=8D=E4=B8=8B=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- control/control.go | 10 ++++++---- control/db.go | 32 ++++++++++++++++---------------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/control/control.go b/control/control.go index 6d6442f..588305b 100644 --- a/control/control.go +++ b/control/control.go @@ -106,7 +106,10 @@ func D(w http.ResponseWriter, r *http.Request) { errJsonMsg("404 Not Found", w) return } - + record, err := GetFileNameByIDOrName(fileId) + if err == nil && record.FileId != "" { + fileId = record.FileId + } // 发起HTTP GET请求来获取Telegram图片 fileUrl, _ := utils.GetDownloadUrl(fileId) resp, err := http.Get(fileUrl) @@ -174,9 +177,8 @@ func D(w http.ResponseWriter, r *http.Request) { // 使用DetectContentType函数检测文件类型 w.Header().Set("Content-Type", http.DetectContentType(buffer)) - fileName, err := GetFileNameByID(fileId) - if err == nil && fileName != "" { - w.Header().Set("Content-Disposition", "attachment; filename=\""+fileName+"\"") + if err == nil && record.Filename != "" { + w.Header().Set("Content-Disposition", "attachment; filename=\""+record.Filename+"\"") } _, err = w.Write(buffer[:n]) diff --git a/control/db.go b/control/db.go index 88b5831..d02b28d 100644 --- a/control/db.go +++ b/control/db.go @@ -41,20 +41,27 @@ func InitDB() (*sql.DB, error) { return db, err } -// GetFileNameByID 查询文件名 -func GetFileNameByID(id string) (string, error) { - var fileName string - // 执行查询,获取对应id的fileName - query := "SELECT filename FROM uploaded_files WHERE fileId = ?" - err := db.QueryRow(query, id).Scan(&fileName) +type FileRecord struct { + FileId string `json:"fileId"` + Filename string `json:"filename"` + Ip string `json:"ip"` + Time time.Time `json:"time"` +} + +// GetFileNameByIDOrName 查询文件名 +func GetFileNameByIDOrName(idOrName string) (FileRecord, error) { + var record FileRecord + // 执行查询,获取对应id或name的file记录 + query := "SELECT fileId, filename, ip, time FROM uploaded_files WHERE fileId = ? OR filename = ? ORDER BY time DESC LIMIT 1" + err := db.QueryRow(query, idOrName, idOrName).Scan(&record.FileId, &record.Filename, &record.Ip, &record.Time) if err != nil { if errors.Is(err, sql.ErrNoRows) { - return "", fmt.Errorf("no file found with id %s", id) + return FileRecord{}, fmt.Errorf("no file found with idOrName %s", idOrName) } - return "", err + return FileRecord{}, err } - return fileName, nil + return record, nil } func SaveFileRecord(fileID string, fileName string, ip string) error { @@ -63,13 +70,6 @@ func SaveFileRecord(fileID string, fileName string, ip string) error { return err } -type FileRecord struct { - FileId string `json:"fileId"` - Filename string `json:"filename"` - Ip string `json:"ip"` - Time time.Time `json:"time"` -} - func SelectAllRecord() ([]FileRecord, error) { // 查询所有记录 rows, err := db.Query("SELECT fileId, filename, ip, time FROM uploaded_files") From 7158f027efd4174c8b30a1faf80092fea2764a31 Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 16:42:15 +0800 Subject: [PATCH 6/9] doc:hidden NSFW --- README.md | 4 ++++ README_en.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/README.md b/README.md index 5b53e45..5b929dc 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,12 @@ https://tgstate.vercel.app / https://tgstate.ikun123.com/ 不限制大小demo(临时) http://tgstate-cdn.ikun123.com/ 演示图片: +
+NSFW ![tgState](https://tgstate.vercel.app/d/BQACAgUAAx0EcyK3ugACByxlOR-Nfl4esavoO4zdaYIP_k1KYQACDAsAAkf4yFVpf_awaEkS8jAE) +
+ # 参数说明 diff --git a/README_en.md b/README_en.md index e258b42..68093ed 100644 --- a/README_en.md +++ b/README_en.md @@ -23,7 +23,11 @@ Hosted on Vercel, resource limitations - files larger than 5MB are not supported Demo image: +
+NSFW + ![tgState](https://tgstate.vercel.app/d/BQACAgUAAx0EcyK3ugACByxlOR-Nfl4esavoO4zdaYIP_k1KYQACDAsAAkf4yFVpf_awaEkS8jAE) +
# Parameter Description From e0a84906249f0fd1f3aeec85d83196683f5d71b6 Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 17:06:27 +0800 Subject: [PATCH 7/9] feat:support proxy web --- assets/templates/footer.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/templates/footer.tmpl b/assets/templates/footer.tmpl index c531994..d75e0ae 100644 --- a/assets/templates/footer.tmpl +++ b/assets/templates/footer.tmpl @@ -69,7 +69,7 @@ (a = a + ":" + window.location.port), $.ajax({ type: "POST", - url: a + "/api", + url: window.location.href + "/api", data: o, contentType: !1, processData: !1, From 18548d915269a18c46a886e38f1eecc060ca2f1a Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Thu, 17 Oct 2024 17:10:12 +0800 Subject: [PATCH 8/9] feat:support proxy web --- assets/templates/footer.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/templates/footer.tmpl b/assets/templates/footer.tmpl index d75e0ae..172540b 100644 --- a/assets/templates/footer.tmpl +++ b/assets/templates/footer.tmpl @@ -75,7 +75,7 @@ processData: !1, success: function (e) { - var link = a + e.message; + var link = window.location.href + e.message; var proxyUrl = e.proxyUrl var t; if (e.code == 1) { From add80a5587fc4395db111cc33f1df2c22c78ccd0 Mon Sep 17 00:00:00 2001 From: liukl <1138493417@qq.com> Date: Fri, 18 Oct 2024 16:23:48 +0800 Subject: [PATCH 9/9] feat:support proxy web --- assets/templates/footer.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/templates/footer.tmpl b/assets/templates/footer.tmpl index 172540b..ab0af6c 100644 --- a/assets/templates/footer.tmpl +++ b/assets/templates/footer.tmpl @@ -69,7 +69,7 @@ (a = a + ":" + window.location.port), $.ajax({ type: "POST", - url: window.location.href + "/api", + url: window.location.href.replace(/\/$/, "") + "/api", data: o, contentType: !1, processData: !1,