diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..56b002b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,232 @@ +name: CI + +on: + push: + branches: + - main + - 'dev/**' + - 'feat/**' + - 'fix/**' + pull_request: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint & Format + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.26.2' + cache: true + + - name: Check gofmt + run: | + unformatted="$(gofmt -l . | grep -v '^web/' | grep -v '^video-cong-nghe/' || true)" + if [ -n "$unformatted" ]; then + echo "::error::The following files are not gofmt-formatted:" + echo "$unformatted" + echo "" + echo "Run 'gofmt -w .' (or 'make fmt') and commit the result." + exit 1 + fi + echo "All Go files are gofmt-formatted." + + # go vet (and go build) must type-check main.go, which go:embed's the + # frontend build output (web/static/**/*.min.*). Those files are + # gitignored, so they only exist after a frontend build — without this + # step the embed directive fails with "no matching files found". + - name: Set up Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Build frontend assets (required by go:embed) + run: | + cd web + chmod +x build-frontend.sh + ./build-frontend.sh + + - name: Verify go:embed prerequisites + run: | + missing=0 + for p in web/static/css/*.min.css web/static/css/tailwind.css \ + web/static/js/*.min.js web/static/themes/*.min.css \ + web/static/locales/*.min.json web/static/fonts web/static/webfonts; do + if ! ls -d $p >/dev/null 2>&1; then + echo "::error::go:embed prerequisite missing after frontend build: $p" + missing=1 + fi + done + if [ "$missing" -ne 0 ]; then + echo "" + echo "main.go embeds these paths. A common cause is a dependency" + echo "upgrade that changed its file layout (Font Awesome dropping" + echo "webfonts/). Check web/bun.lock is committed and used." + exit 1 + fi + echo "All go:embed prerequisites present." + shell: bash + + - name: go vet + run: go vet ./... + + test: + name: Test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.26.2' + cache: true + + # main.go go:embed's the frontend build output, so it must exist before + # anything compiles. The embedded assets are platform-independent, so + # building them on Linux once per job is enough. + - name: Set up Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Build frontend assets (required by go:embed) + run: | + cd web + chmod +x build-frontend.sh + ./build-frontend.sh + shell: bash + + - name: Debug font layout (temporary) + run: | + echo "--- node_modules fontawesome version ---" + cat web/node_modules/@fortawesome/fontawesome-free/package.json 2>/dev/null | grep '"version"' || echo "package.json not found" + echo "--- node_modules webfonts dir ---" + ls -la web/node_modules/@fortawesome/fontawesome-free/webfonts/ 2>&1 | head -10 || echo "no webfonts in node_modules" + echo "--- static dir listing ---" + ls -la web/static/ 2>&1 | head -20 + echo "--- static/css listing ---" + ls -la web/static/css/ 2>&1 | head -20 + echo "--- url() refs in built css ---" + grep -o 'url([^)]*woff[^)]*)' web/static/css/style.min.css 2>/dev/null | head -5 || echo "no woff refs in css" + shell: bash + + - name: Verify go:embed prerequisites + run: | + missing=0 + for p in web/static/css/*.min.css web/static/css/tailwind.css \ + web/static/js/*.min.js web/static/themes/*.min.css \ + web/static/locales/*.min.json web/static/fonts web/static/webfonts; do + if ! ls -d $p >/dev/null 2>&1; then + echo "::error::go:embed prerequisite missing after frontend build: $p" + missing=1 + fi + done + if [ "$missing" -ne 0 ]; then + echo "" + echo "main.go embeds these paths. A common cause is a dependency" + echo "upgrade that changed its file layout (Font Awesome dropping" + echo "webfonts/). Check web/bun.lock is committed and used." + exit 1 + fi + echo "All go:embed prerequisites present." + shell: bash + + - name: Download modules + run: go mod download + + - name: Build + run: go build -o /dev/null ./... + shell: bash + + - name: Run tests + run: go test -race -count=1 ./... + shell: bash + + coverage: + name: Coverage + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.26.2' + cache: true + + - name: Set up Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Build frontend assets (required by go:embed) + run: | + cd web + chmod +x build-frontend.sh + ./build-frontend.sh + + - name: Verify go:embed prerequisites + run: | + missing=0 + for p in web/static/css/*.min.css web/static/css/tailwind.css \ + web/static/js/*.min.js web/static/themes/*.min.css \ + web/static/locales/*.min.json web/static/fonts web/static/webfonts; do + if ! ls -d $p >/dev/null 2>&1; then + echo "::error::go:embed prerequisite missing after frontend build: $p" + missing=1 + fi + done + if [ "$missing" -ne 0 ]; then + echo "" + echo "main.go embeds these paths. A common cause is a dependency" + echo "upgrade that changed its file layout (Font Awesome dropping" + echo "webfonts/). Check web/bun.lock is committed and used." + exit 1 + fi + echo "All go:embed prerequisites present." + + - name: Generate coverage profile + run: go test -count=1 -covermode=atomic -coverprofile=coverage.out ./... + + - name: Print coverage summary + run: | + go tool cover -func=coverage.out | tail -n 1 + echo "" + echo "### Coverage by package" >> "$GITHUB_STEP_SUMMARY" + echo '```' >> "$GITHUB_STEP_SUMMARY" + go test -count=1 -cover ./... 2>/dev/null | grep -E '^(ok|\?)' >> "$GITHUB_STEP_SUMMARY" || true + echo '```' >> "$GITHUB_STEP_SUMMARY" + + - name: Upload coverage profile + uses: actions/upload-artifact@v4 + with: + name: coverage-profile + path: coverage.out + retention-days: 14 diff --git a/.gitignore b/.gitignore index a8a6a9f..804024c 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,11 @@ Thumbs.db # Go dependencies vendor/ +# Test artifacts +coverage.out +coverage.html +*.test + # Tailwind & Frontend tailwindcss static/css/tailwind.css diff --git a/Makefile b/Makefile index 0621e55..073b592 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: build run test clean fmt tidy frontend docker-build help +.PHONY: build run test test-race cover vet fmt fmt-check check clean tidy frontend docker-build help DEFAULT_API_ID ?= $(shell grep -E "^API_ID=" .env 2>/dev/null | cut -d= -f2) DEFAULT_API_HASH ?= $(shell grep -E "^API_HASH=" .env 2>/dev/null | cut -d= -f2) @@ -18,7 +18,12 @@ help: @echo " make run Build and run application locally" @echo " make frontend Build frontend assets in web directory" @echo " make test Run unit tests for all packages" - @echo " make fmt Format Go source code" + @echo " make test-race Run unit tests with the race detector" + @echo " make cover Run tests and report per-function coverage" + @echo " make vet Run go vet on all packages" + @echo " make fmt Format Go source code (gofmt -w)" + @echo " make fmt-check Verify Go source is gofmt-formatted (no writes)" + @echo " make check Run the full local CI gate: fmt-check + vet + test" @echo " make tidy Tidy Go modules" @echo " make clean Clean build artifacts and temporary files" @echo " make docker-build Build Docker image locally with default API credentials" @@ -40,9 +45,37 @@ test: @echo "===> Running tests..." go test ./... +test-race: + @echo "===> Running tests with race detector..." + go test -race -count=1 ./... + +cover: + @echo "===> Running tests with coverage..." + go test -count=1 -coverprofile=coverage.out ./... + go tool cover -func=coverage.out | tail -n 1 + @echo "===> Full profile written to coverage.out (view with: go tool cover -html=coverage.out)" + +vet: + @echo "===> Running go vet..." + go vet ./... + fmt: @echo "===> Formatting Go code..." - go fmt ./... + gofmt -w $$(git ls-files '*.go' | grep -v '^web/' || find . -name '*.go' -not -path './web/*' -not -path './.git/*') + +fmt-check: + @echo "===> Checking gofmt..." + @unformatted="$$(gofmt -l . | grep -v '^web/' | grep -v '^video-cong-nghe/' || true)"; \ + if [ -n "$$unformatted" ]; then \ + echo "The following files are not gofmt-formatted:"; \ + echo "$$unformatted"; \ + echo "Run 'make fmt' and commit the result."; \ + exit 1; \ + fi; \ + echo "All Go files are gofmt-formatted." + +check: fmt-check vet test + @echo "===> All local CI checks passed." tidy: @echo "===> Running go mod tidy..." diff --git a/api/handlers_settings.go b/api/handlers_settings.go index 8e2ffc1..add5fdd 100644 --- a/api/handlers_settings.go +++ b/api/handlers_settings.go @@ -210,7 +210,7 @@ func (h *Handler) handleGetBotUserSettings(c *gin.Context) { botPoolUploadFolder = "TelegramUpload" } c.JSON(http.StatusOK, gin.H{ - "telegram_user_id": telegramUserID, + "telegram_user_id": telegramUserID, "bot_pool_upload_folder": botPoolUploadFolder, }) } diff --git a/api/handlers_sharing.go b/api/handlers_sharing.go index 632e693..1611d5f 100644 --- a/api/handlers_sharing.go +++ b/api/handlers_sharing.go @@ -494,5 +494,3 @@ func (h *Handler) handleGetShares(c *gin.Context) { "files": files, }) } - - diff --git a/api/middleware.go b/api/middleware.go index be5c7d3..3241f0a 100644 --- a/api/middleware.go +++ b/api/middleware.go @@ -337,8 +337,8 @@ func gzipMiddleware() gin.HandlerFunc { // Avoid compressing stream, download, WebDAV, S3, WebSocket, and large comic/epub page binary data path := c.Request.URL.Path - if strings.Contains(path, "/stream") || - strings.Contains(path, "/dl") || + if strings.Contains(path, "/stream") || + strings.Contains(path, "/dl") || strings.Contains(path, "/download/") || strings.Contains(path, "/cbz/page") || strings.Contains(path, "/epub/resource") || @@ -358,7 +358,7 @@ func gzipMiddleware() gin.HandlerFunc { c.Header("Content-Encoding", "gzip") c.Header("Vary", "Accept-Encoding") - + c.Writer = &gzipResponseWriter{c.Writer, gz} c.Next() } diff --git a/docs/Development.md b/docs/Development.md index 5c640c1..8605c5a 100644 --- a/docs/Development.md +++ b/docs/Development.md @@ -55,7 +55,34 @@ Mã nguồn frontend nằm ở repo: [**dabeecao/telecloud-frontend**](https://g 2. Tạo tệp mới (VD: `fr.json`) và dịch từ `en.json`. 3. Thêm ngôn ngữ vào `availableLangs` trong `static/js/common.js`. 4. Gửi Pull Request vào repository frontend. -### 3. Lưu ý về phát triển Cơ sở dữ liệu (SQL) & Khóa mã hóa + +### 3. Quy trình kiểm tra trước khi gửi Pull Request + +Mọi Pull Request vào `main` đều được kiểm tra tự động bởi workflow [`.github/workflows/ci.yml`](../.github/workflows/ci.yml). Hãy chạy các bước tương tự ở máy cục bộ trước khi push để tránh CI thất bại: + +```bash +make check # gofmt-check + go vet + go test (cổng kiểm tra đầy đủ) +``` + +Các lệnh chi tiết: + +| Lệnh | Mô tả | +|---|---| +| `make fmt` | Định dạng toàn bộ mã Go bằng `gofmt -w` | +| `make fmt-check` | Chỉ kiểm tra định dạng, không ghi file (dùng trong CI) | +| `make vet` | Chạy `go vet` trên tất cả package | +| `make test` | Chạy toàn bộ unit test | +| `make test-race` | Chạy test kèm race detector (CI chạy trên Linux/Windows/macOS) | +| `make cover` | Xuất báo cáo độ phủ ra `coverage.out` | + +**Yêu cầu bắt buộc:** + +- Mã Go phải được định dạng bằng `gofmt` — CI sẽ **thất bại** nếu còn file chưa định dạng. +- `go vet ./...` phải sạch (không có cảnh báo). +- Không được giảm độ phủ test hiện có. Khi thêm logic mới (đặc biệt trong `database/`, `s3/`, `webdav/`), hãy thêm unit test đi kèm. +- Test phải chạy được trên cả Linux, Windows và macOS (tránh phụ thuộc đường dẫn tuyệt đối kiểu `/tmp` hay `C:\`, dùng `t.TempDir()`). + +### 4. Lưu ý về phát triển Cơ sở dữ liệu (SQL) & Khóa mã hóa #### Khóa mã hóa (`master.key`): - Để tránh xung đột đường dẫn lưu trữ khóa `master.key` khi thư mục `data` được tạo sau lúc ứng dụng khởi động, toàn bộ mã nguồn sử dụng hàm `utils.GetMasterKeyFilePath()` để xác định vị trí tệp khóa chủ. @@ -100,8 +127,33 @@ Frontend source: [**dabeecao/telecloud-frontend**](https://github.com/dabeecao/t 2. Add the language to `availableLangs` in `static/js/common.js`. 3. Submit a Pull Request. +### 3. Pre-Pull-Request Checks + +Every Pull Request targeting `main` is validated automatically by [`.github/workflows/ci.yml`](../.github/workflows/ci.yml). Run the same checks locally before pushing to avoid CI failures: + +```bash +make check # gofmt-check + go vet + go test (the full gate) +``` + +Individual targets: + +| Command | Description | +|---|---| +| `make fmt` | Format all Go source with `gofmt -w` | +| `make fmt-check` | Verify formatting without writing (what CI runs) | +| `make vet` | Run `go vet` across all packages | +| `make test` | Run the full unit test suite | +| `make test-race` | Run tests with the race detector (CI runs Linux/Windows/macOS) | +| `make cover` | Write a coverage profile to `coverage.out` | + +**Requirements:** + +- All Go files must be `gofmt`-formatted — CI **fails** on any unformatted file. +- `go vet ./...` must be clean (no findings). +- Do not lower existing test coverage. When adding logic — especially in `database/`, `s3/`, or `webdav/` — add accompanying unit tests. +- Tests must pass on Linux, Windows and macOS alike (avoid absolute paths such as `/tmp` or `C:\`; use `t.TempDir()` instead). -### 3. Database Development & Master Key Guidelines +### 4. Database Development & Master Key Guidelines #### Encryption Key (`master.key`): - To prevent key path conflicts when the `data` directory is created dynamically during runtime, always use `utils.GetMasterKeyFilePath()` to resolve the persistent key path. diff --git a/s3/server.go b/s3/server.go index 86dba79..adc5db7 100644 --- a/s3/server.go +++ b/s3/server.go @@ -92,10 +92,10 @@ func NewHandler(cfg *config.Config) http.Handler { // // If you require strict security, uncomment the block below: /* - if err := verifyS3Signature(r, authHeader, accessKey, secretKey); err != nil { - http.Error(w, "Unauthorized", http.StatusUnauthorized) - return - } + if err := verifyS3Signature(r, authHeader, accessKey, secretKey); err != nil { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } */ // Verify signatures against the external URI clients sign. The rewrite diff --git a/tgclient/client.go b/tgclient/client.go index b5e52b6..b138f93 100644 --- a/tgclient/client.go +++ b/tgclient/client.go @@ -65,9 +65,9 @@ var ( // processing of messages sequentially on a per-bot basis. botMutexes sync.Map - AppConfig *config.Config + AppConfig *config.Config UserbotCooldownUntil time.Time - initializationDone int32 + initializationDone int32 ) func IsAuthorized() bool { @@ -1315,7 +1315,7 @@ func sendDebouncedConfirmation(key confirmKey) { } else { var sb strings.Builder sb.WriteString(fmt.Sprintf("✅ Successfully received %d files:\n", len(filenames))) - + maxShow := 15 for i, name := range filenames { if i >= maxShow { @@ -1324,7 +1324,7 @@ func sendDebouncedConfirmation(key confirmKey) { } sb.WriteString(fmt.Sprintf("• %s\n", name)) } - + sb.WriteString(fmt.Sprintf("\n📂 Folder: /%s\n☁️ TeleCloud upload completed!", folder)) confirmText = sb.String() } diff --git a/tgclient/uploader.go b/tgclient/uploader.go index c38aadc..2bd8faa 100644 --- a/tgclient/uploader.go +++ b/tgclient/uploader.go @@ -364,7 +364,7 @@ func UpdateTaskWithFile(taskID string, status string, percent int, msg string, f case "downloading": progress = (float64(fu) / float64(fs)) * 50 case "telegram": - progress = 50 + (float64(fu) / float64(fs)) * 50 + progress = 50 + (float64(fu)/float64(fs))*50 case "done": progress = 100 } @@ -1996,7 +1996,7 @@ func ResolveTelegramPeer(ctx context.Context, api *tg.Client, username string, c if err != nil { return nil, fmt.Errorf("resolve username failed: %w", err) } - + switch p := res.Peer.(type) { case *tg.PeerChannel: var accessHash int64 @@ -2058,7 +2058,7 @@ func FetchTelegramMessage(ctx context.Context, api *tg.Client, peer tg.InputPeer if err != nil { return nil, fmt.Errorf("channels.getMessages failed: %w", err) } - + switch m := res.(type) { case *tg.MessagesMessages: msgs = m.Messages @@ -2072,7 +2072,7 @@ func FetchTelegramMessage(ctx context.Context, api *tg.Client, peer tg.InputPeer if err != nil { return nil, fmt.Errorf("messages.getMessages failed: %w", err) } - + switch m := res.(type) { case *tg.MessagesMessages: msgs = m.Messages @@ -2113,7 +2113,7 @@ func ExtractTelegramMediaInfo(msg *tg.Message) (*TelegramMediaInfo, error) { if !ok { return nil, fmt.Errorf("document media is empty") } - + filename := "file" for _, attr := range doc.Attributes { if fAttr, ok := attr.(*tg.DocumentAttributeFilename); ok { @@ -2275,7 +2275,7 @@ func downloadTelegramFileToFile(ctx context.Context, api *tg.Client, loc tg.Inpu if err == nil { break } - + // Extract wait time from FLOOD_WAIT if possible errStr := err.Error() if strings.Contains(errStr, "FLOOD_WAIT") { @@ -2286,7 +2286,7 @@ func downloadTelegramFileToFile(ctx context.Context, api *tg.Client, loc tg.Inpu waitSec = sec } } - + if updateProgress != nil { updateProgress(offset, fmt.Sprintf("flood_wait_retry_in|seconds=%d", waitSec)) } diff --git a/web b/web index 067d280..02b1954 160000 --- a/web +++ b/web @@ -1 +1 @@ -Subproject commit 067d2805c63bbe1c8dd80d42e97712624871206a +Subproject commit 02b1954dc6ff6cfc9339ce2f185a888b06cf2fae