|
| 1 | +// Copyright (c) 2025 Z5labs and Contributors |
| 2 | +// |
| 3 | +// This software is released under the MIT License. |
| 4 | +// https://opensource.org/licenses/MIT |
| 5 | + |
| 6 | +package ui |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "encoding/json" |
| 11 | + "fmt" |
| 12 | + "net/http" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/z5labs/journeys/services/poc/storage" |
| 16 | + |
| 17 | + "github.com/dgraph-io/dgo/v240" |
| 18 | + "github.com/z5labs/humus/rest" |
| 19 | +) |
| 20 | + |
| 21 | +type contentPreviewHandler struct { |
| 22 | + dgraph *dgo.Dgraph |
| 23 | + minio *storage.MinioClient |
| 24 | +} |
| 25 | + |
| 26 | +func GetContentPreview(dgraph *dgo.Dgraph, minio *storage.MinioClient) rest.ApiOption { |
| 27 | + h := &contentPreviewHandler{ |
| 28 | + dgraph: dgraph, |
| 29 | + minio: minio, |
| 30 | + } |
| 31 | + |
| 32 | + return rest.Operation( |
| 33 | + http.MethodGet, |
| 34 | + rest.BasePath("/app/content").Param("contentID").Segment("preview"), |
| 35 | + h, |
| 36 | + ) |
| 37 | +} |
| 38 | + |
| 39 | +func (h *contentPreviewHandler) Handle(ctx context.Context, req *rest.EmptyRequest) (*HtmlResponse, error) { |
| 40 | + contentID := rest.PathParamValue(ctx, "contentID") |
| 41 | + if contentID == "" { |
| 42 | + return nil, fmt.Errorf("content ID is required") |
| 43 | + } |
| 44 | + |
| 45 | + query := `query getContent($contentID: string) { |
| 46 | + content(func: eq(content.id, $contentID)) { |
| 47 | + content.minio_key |
| 48 | + } |
| 49 | + }` |
| 50 | + |
| 51 | + vars := map[string]string{"contentID": contentID} |
| 52 | + resp, err := h.dgraph.NewReadOnlyTxn().QueryWithVars(ctx, query, vars) |
| 53 | + if err != nil { |
| 54 | + return nil, fmt.Errorf("failed to query content: %w", err) |
| 55 | + } |
| 56 | + |
| 57 | + var result struct { |
| 58 | + Content []struct { |
| 59 | + MinioKey string `json:"content.minio_key"` |
| 60 | + } `json:"content"` |
| 61 | + } |
| 62 | + if err := json.Unmarshal(resp.Json, &result); err != nil { |
| 63 | + return nil, fmt.Errorf("failed to unmarshal content: %w", err) |
| 64 | + } |
| 65 | + |
| 66 | + if len(result.Content) == 0 { |
| 67 | + return nil, fmt.Errorf("content not found") |
| 68 | + } |
| 69 | + |
| 70 | + minioKey := result.Content[0].MinioKey |
| 71 | + |
| 72 | + presignedURL, err := h.minio.GetFileURL(ctx, minioKey, 15*time.Minute) |
| 73 | + if err != nil { |
| 74 | + return nil, fmt.Errorf("failed to get presigned URL: %w", err) |
| 75 | + } |
| 76 | + |
| 77 | + redirectHTML := fmt.Sprintf(`<!DOCTYPE html> |
| 78 | +<html> |
| 79 | +<head> |
| 80 | + <meta http-equiv="refresh" content="0; url=%s"> |
| 81 | +</head> |
| 82 | +<body> |
| 83 | + <p>Redirecting...</p> |
| 84 | +</body> |
| 85 | +</html>`, presignedURL) |
| 86 | + |
| 87 | + return &HtmlResponse{ |
| 88 | + ContentType: "text/html; charset=utf-8", |
| 89 | + Body: []byte(redirectHTML), |
| 90 | + }, nil |
| 91 | +} |
0 commit comments