82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package file
|
|
|
|
import (
|
|
"donat-widget/internal/model"
|
|
"donat-widget/internal/model/api"
|
|
"github.com/labstack/echo/v4"
|
|
"log/slog"
|
|
"mime"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"path"
|
|
)
|
|
|
|
import (
|
|
"context"
|
|
)
|
|
|
|
func New(
|
|
authClient model.AuthClient,
|
|
fileRepo model.FileRepo,
|
|
) *ServiceFile {
|
|
return &ServiceFile{
|
|
authClient: authClient,
|
|
fileRepo: fileRepo,
|
|
}
|
|
}
|
|
|
|
type ServiceFile struct {
|
|
authClient model.AuthClient
|
|
fileRepo model.FileRepo
|
|
}
|
|
|
|
func (fileService *ServiceFile) AddNewFile(
|
|
ctx context.Context,
|
|
file multipart.FileHeader,
|
|
streamerID int,
|
|
) (string, error) {
|
|
fileExt := path.Ext(file.Filename)
|
|
|
|
mimeType := mime.TypeByExtension(fileExt)
|
|
if mimeType == "" {
|
|
mimeType = "application/octet-stream"
|
|
}
|
|
|
|
fileID, err := fileService.fileRepo.AddNew(
|
|
ctx,
|
|
streamerID,
|
|
file,
|
|
file.Filename,
|
|
fileExt,
|
|
mimeType,
|
|
)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return fileID, nil
|
|
}
|
|
|
|
func (fileService *ServiceFile) CheckToken(
|
|
request echo.Context,
|
|
) (api.CheckTokenResponse, error) {
|
|
accessToken := model.Token(request.Request().Header.Get("Authorization"))
|
|
|
|
checkTokenResponse, err := fileService.authClient.CheckToken(accessToken)
|
|
if err != nil {
|
|
slog.Error("Failed to check token", "error", err.Error())
|
|
return api.CheckTokenResponse{}, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
|
|
}
|
|
|
|
if checkTokenResponse.AccountID == 0 {
|
|
slog.Error("Unauthorized account")
|
|
return api.CheckTokenResponse{}, echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized account")
|
|
}
|
|
|
|
if checkTokenResponse.AccountID == -1 {
|
|
slog.Error("Expired token")
|
|
return api.CheckTokenResponse{}, echo.NewHTTPError(http.StatusUnauthorized, "Expired token")
|
|
}
|
|
|
|
return checkTokenResponse, nil
|
|
}
|