Ajouter models/ pour type Bucket #109

Merged
vlbeaudoin merged 8 commits from refactor/models into main 2023-08-19 20:31:38 -04:00
6 changed files with 83 additions and 67 deletions

View file

@ -16,6 +16,8 @@ ADD config/ config/
ADD media/ media/ ADD media/ media/
ADD models/ models/
ADD templates/ templates/ ADD templates/ templates/
ADD serverhandlers/ serverhandlers/ ADD serverhandlers/ serverhandlers/

View file

@ -6,12 +6,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/url" "net/url"
"git.agecem.com/agecem/agecem-org/config" "git.agecem.com/agecem/agecem-org/config"
"git.agecem.com/agecem/agecem-org/models"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -30,17 +30,6 @@ type APIOptions struct {
Password string Password string
} }
type UploadDocumentResponse struct {
Info UploadDocumentResponseInfo `json:"info"`
Message string `json:"message"`
}
type UploadDocumentResponseInfo struct {
Bucket string `json:"bucket"`
Object string `json:"key"`
Size float64 `json:"size"`
}
// NewApiClientFromViper returns a pointer to a new API object, // NewApiClientFromViper returns a pointer to a new API object,
// provided the configuration options are managed by // provided the configuration options are managed by
// https://git.agecem.com/agecem/agecem-org/config // https://git.agecem.com/agecem/agecem-org/config
@ -110,7 +99,7 @@ func (a *API) Call(method, route string) ([]byte, error) {
defer response.Body.Close() defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body) body, err := io.ReadAll(response.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -138,7 +127,7 @@ func (a *API) Call(method, route string) ([]byte, error) {
defer resp.Body.Close() defer resp.Body.Close()
// Read Response Body // Read Response Body
respBody, err := ioutil.ReadAll(resp.Body) respBody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -149,7 +138,8 @@ func (a *API) Call(method, route string) ([]byte, error) {
return nil, errors.New(fmt.Sprintf("method must be 'GET' or 'DELETE', got '%s'", method)) return nil, errors.New(fmt.Sprintf("method must be 'GET' or 'DELETE', got '%s'", method))
} }
func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (UploadDocumentResponse, error) { func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (models.UploadDocumentResponse, error) {
var response models.UploadDocumentResponse
endpoint := fmt.Sprintf("%s://%s:%d", endpoint := fmt.Sprintf("%s://%s:%d",
a.Protocol, a.Protocol,
a.Host, a.Host,
@ -165,34 +155,34 @@ func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (
// Add the file to the request // Add the file to the request
file, err := file_header.Open() file, err := file_header.Open()
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#file_header.Open: %s", err) return response, fmt.Errorf("UploadDocument#file_header.Open: %s", err)
} }
defer file.Close() defer file.Close()
filename_processed, err := url.QueryUnescape(file_header.Filename) filename_processed, err := url.QueryUnescape(file_header.Filename)
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#url.QueryUnescape: %s", err) return response, fmt.Errorf("UploadDocument#url.QueryUnescape: %s", err)
} }
part, err := writer.CreateFormFile("document", filename_processed) part, err := writer.CreateFormFile("document", filename_processed)
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#writer.CreateFormFile: %s", err) return response, fmt.Errorf("UploadDocument#writer.CreateFormFile: %s", err)
} }
_, err = io.Copy(part, file) _, err = io.Copy(part, file)
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#io.Copy: %s", err) return response, fmt.Errorf("UploadDocument#io.Copy: %s", err)
} }
err = writer.Close() err = writer.Close()
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#writer.Close: %s", err) return response, fmt.Errorf("UploadDocument#writer.Close: %s", err)
} }
// Create a new HTTP request with the multipart body // Create a new HTTP request with the multipart body
req, err := http.NewRequest(http.MethodPost, current_url, body) req, err := http.NewRequest(http.MethodPost, current_url, body)
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#http.NewRequest: %s", err) return response, fmt.Errorf("UploadDocument#http.NewRequest: %s", err)
} }
req.Header.Set("Content-Type", writer.FormDataContentType()) req.Header.Set("Content-Type", writer.FormDataContentType())
@ -205,15 +195,12 @@ func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#client.Do: %s", err) return response, fmt.Errorf("UploadDocument#client.Do: %s", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
// Handle the response err = json.NewDecoder(resp.Body).Decode(&response)
var res UploadDocumentResponse return response, err
json.NewDecoder(resp.Body).Decode(&res)
return res, nil
} }
// CallWithData takes data and returns a string representing a response body. // CallWithData takes data and returns a string representing a response body.

View file

@ -21,6 +21,7 @@ import (
"git.agecem.com/agecem/agecem-org/api" "git.agecem.com/agecem/agecem-org/api"
"git.agecem.com/agecem/agecem-org/config" "git.agecem.com/agecem/agecem-org/config"
"git.agecem.com/agecem/agecem-org/media" "git.agecem.com/agecem/agecem-org/media"
"git.agecem.com/agecem/agecem-org/models"
"git.agecem.com/agecem/agecem-org/public" "git.agecem.com/agecem/agecem-org/public"
"git.agecem.com/agecem/agecem-org/serverhandlers" "git.agecem.com/agecem/agecem-org/serverhandlers"
"git.agecem.com/agecem/agecem-org/templates" "git.agecem.com/agecem/agecem-org/templates"
@ -306,13 +307,7 @@ func handleDocumentation(c echo.Context) error {
return c.Render(http.StatusInternalServerError, "documentation-html", nil) return c.Render(http.StatusInternalServerError, "documentation-html", nil)
} }
type Bucket struct { var data []models.Bucket
Name string
DisplayName string
Documents []string
}
var data []Bucket
for bucket, displayName := range buckets { for bucket, displayName := range buckets {
content, err := client.Call(http.MethodGet, fmt.Sprintf("/v1/bucket/%s", bucket)) content, err := client.Call(http.MethodGet, fmt.Sprintf("/v1/bucket/%s", bucket))
@ -345,7 +340,7 @@ func handleDocumentation(c echo.Context) error {
documents_processed := documents documents_processed := documents
*/ */
data = append(data, Bucket{ data = append(data, models.Bucket{
Name: bucket, Name: bucket,
DisplayName: displayName, DisplayName: displayName,
Documents: documents, Documents: documents,
@ -408,19 +403,13 @@ func handleAdminDocumentsUpload(c echo.Context) error {
return c.Render(http.StatusInternalServerError, "documentation-html", nil) return c.Render(http.StatusInternalServerError, "documentation-html", nil)
} }
type Bucket struct {
Name string
DisplayName string
Documents []string
}
var data struct { var data struct {
Buckets []Bucket Buckets []models.Bucket
Message string Message string
} }
for bucketName, displayName := range buckets { for bucketName, displayName := range buckets {
data.Buckets = append(data.Buckets, Bucket{ data.Buckets = append(data.Buckets, models.Bucket{
Name: bucketName, Name: bucketName,
DisplayName: displayName, DisplayName: displayName,
}) })
@ -430,14 +419,8 @@ func handleAdminDocumentsUpload(c echo.Context) error {
} }
func handleAdminDocumentsUploadPOST(c echo.Context) error { func handleAdminDocumentsUploadPOST(c echo.Context) error {
type Bucket struct {
Name string
DisplayName string
Documents []string
}
var data struct { var data struct {
Buckets []Bucket Buckets []models.Bucket
Message string Message string
} }
@ -461,7 +444,7 @@ func handleAdminDocumentsUploadPOST(c echo.Context) error {
} }
for bucketName, displayName := range buckets { for bucketName, displayName := range buckets {
data.Buckets = append(data.Buckets, Bucket{ data.Buckets = append(data.Buckets, models.Bucket{
Name: bucketName, Name: bucketName,
DisplayName: displayName, DisplayName: displayName,
}) })
@ -484,7 +467,7 @@ func handleAdminDocumentsUploadPOST(c echo.Context) error {
// Format response // Format response
var info, status string var info, status string
info = fmt.Sprintf("[%.0f] /public/documentation/%s/%s", response.Info.Size, response.Info.Bucket, response.Info.Object) info = fmt.Sprintf("[%.0f] /public/documentation/%s/%s", response.Data.Size, response.Data.Bucket, response.Data.Object)
status = response.Message status = response.Message

7
models/models.go Normal file
View file

@ -0,0 +1,7 @@
package models
type Bucket struct {
Name string
DisplayName string
Documents []string
}

33
models/responses.go Normal file
View file

@ -0,0 +1,33 @@
package models
type Responder interface {
Respond() Responder
}
type Response struct {
StatusCode int `json:"status_code"`
Message string
Error string
}
func (r Response) Respond() Responder {
return r
}
type UploadDocumentResponse struct {
Response
Data UploadDocumentResponseData
}
type UploadDocumentResponseData struct {
Bucket string
Object string
Size float64
}
type V1SeedResponse struct {
Response
Data struct {
Buckets []string
}
}

View file

@ -7,6 +7,7 @@ import (
"git.agecem.com/agecem/agecem-org/config" "git.agecem.com/agecem/agecem-org/config"
"git.agecem.com/agecem/agecem-org/media" "git.agecem.com/agecem/agecem-org/media"
"git.agecem.com/agecem/agecem-org/models"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -25,34 +26,37 @@ func HandleV1(c echo.Context) error {
// HandleV1Seed créé des buckets dans minio selon la liste de buckets dans server.documents.buckets // HandleV1Seed créé des buckets dans minio selon la liste de buckets dans server.documents.buckets
// Les buckets sont créés avec paramètres par défaut, et sont ensuite visible dans /v1/bucket. // Les buckets sont créés avec paramètres par défaut, et sont ensuite visible dans /v1/bucket.
func HandleV1Seed(c echo.Context) error { func HandleV1Seed(c echo.Context) error {
var response models.V1SeedResponse
mediaClient, err := media.NewMediaClientFromViper() mediaClient, err := media.NewMediaClientFromViper()
if err != nil { if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{ response.StatusCode = http.StatusInternalServerError
"message": "Error during media.NewMediaClientFromViper()", response.Message = "Error during media.NewMediaClientFromViper()"
"error": err.Error(), response.Error = err.Error()
})
return c.JSON(response.StatusCode, response)
} }
new_buckets, err := mediaClient.Seed() new_buckets, err := mediaClient.Seed()
response.Data.Buckets = new_buckets
if err != nil { if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{ response.StatusCode = http.StatusInternalServerError
"message": "Error during mediaClient.Seed()", response.Message = "Error during mediaClient.Seed()"
"error": err.Error(), response.Error = err.Error()
})
return c.JSON(response.StatusCode, response)
} }
var message string
if len(new_buckets) == 0 { if len(new_buckets) == 0 {
message = "All buckets already exist" response.Message = "All buckets already exist"
} else { } else {
message = "Buckets successfully created" response.Message = "Buckets successfully created"
} }
return c.JSON(http.StatusOK, map[string]interface{}{ response.StatusCode = http.StatusOK
"message": message,
"buckets": new_buckets, return c.JSON(response.StatusCode, response)
})
} }
// HandleV1BucketList affiche les buckets permis par server.documents.buckets, qui existent. // HandleV1BucketList affiche les buckets permis par server.documents.buckets, qui existent.