Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

feat: add support for external URL attachments (#1481)

Sebastian Zaiser82f76063e92e
diff --git a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go
index fe5d4417..da0f8e6f 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go
@@ -230,6 +230,19 @@ func (ctrl *V1Controller) handleEntityAttachmentsHandler(w http.ResponseWriter,
attribute.String("attachment.title", doc.Title),
)
+ if doc.MimeType == repo.MimeTypeLinkURL {
+ parsed, ok := parseExternalHTTPURL(doc.Path)
+ if !ok {
+ err = errors.New("invalid external URL attachment")
+ recordCtrlSpanError(getSpan, err)
+ recordCtrlSpanError(span, err)
+ return validate.NewRequestError(err, http.StatusUnprocessableEntity)
+ }
+
+ http.Redirect(w, r, parsed.String(), http.StatusFound)
+ return nil
+ }
+
bucketCtx, bucketSpan := startEntityCtrlSpan(getCtx, "controller.V1.handleEntityAttachmentsHandler.openBucket")
bucket, err := blob.OpenBucket(bucketCtx, ctrl.repo.Attachments.GetConnString())
if err != nil {
diff --git a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments_external.go b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments_external.go
new file mode 100644
index 00000000..480af193
--- /dev/null
+++ b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments_external.go
@@ -0,0 +1,146 @@
+package v1
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "github.com/google/uuid"
+ "github.com/hay-kot/httpkit/errchain"
+ "github.com/rs/zerolog/log"
+ "github.com/sysadminsmedia/homebox/backend/internal/core/services"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
+ "github.com/sysadminsmedia/homebox/backend/internal/web/adapters"
+ "go.opentelemetry.io/otel/attribute"
+)
+
+type externalAttachmentRequest struct {
+ SourceType string `json:"source_type"`
+ ExternalID string `json:"external_id"`
+ Title string `json:"title"`
+ AttachmentType string `json:"attachment_type"`
+}
+
+func parseExternalHTTPURL(raw string) (*url.URL, bool) {
+ u, err := url.ParseRequestURI(strings.TrimSpace(raw))
+ if err != nil {
+ return nil, false
+ }
+ if !strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, schemeHTTPS) {
+ return nil, false
+ }
+ if u.Host == "" || u.User != nil {
+ return nil, false
+ }
+ return u, true
+}
+
+func redactExternalURLForTrace(raw string) string {
+ u, ok := parseExternalHTTPURL(raw)
+ if !ok {
+ return ""
+ }
+ u.User = nil
+ u.RawQuery = ""
+ u.Fragment = ""
+ return u.String()
+}
+
+func sanitizeExternalURLTitle(raw string) string {
+ u, ok := parseExternalHTTPURL(raw)
+ if !ok {
+ return ""
+ }
+ u.User = nil
+ u.RawQuery = ""
+ u.Fragment = ""
+ return u.String()
+}
+
+// HandleEntityAttachmentExternalCreate godoc
+//
+// @Summary Create External Link Attachment
+// @Description Links an entity to a document or URL in an external system without copying
+// the file into Homebox. The source is identified by source_type.
+// @Tags Entities Attachments
+// @Accept json
+// @Produce json
+// @Param id path string true "Entity ID"
+// @Param payload body externalAttachmentRequest true "External document reference"
+// @Success 201 {object} repo.EntityOut
+// @Failure 400 {object} validate.ErrorResponse
+// @Router /v1/entities/{id}/attachments/external [POST]
+// @Security Bearer
+func (ctrl *V1Controller) HandleEntityAttachmentExternalCreate() errchain.HandlerFunc {
+ fn := func(r *http.Request, id uuid.UUID, body externalAttachmentRequest) (repo.EntityOut, error) {
+ _, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityAttachmentExternalCreate")
+ defer span.End()
+
+ body.SourceType = strings.TrimSpace(body.SourceType)
+ body.ExternalID = strings.TrimSpace(body.ExternalID)
+
+ if body.SourceType == "" {
+ return repo.EntityOut{}, validate.NewRequestError(
+ validate.NewFieldErrors().Append("source_type", "source_type is required"),
+ http.StatusBadRequest,
+ )
+ }
+ if body.ExternalID == "" {
+ return repo.EntityOut{}, validate.NewRequestError(
+ validate.NewFieldErrors().Append("external_id", "external_id is required"),
+ http.StatusBadRequest,
+ )
+ }
+ if _, ok := repo.MimeTypeForSourceType(body.SourceType); !ok {
+ return repo.EntityOut{}, validate.NewRequestError(
+ validate.NewFieldErrors().Append("source_type", fmt.Sprintf("unknown source_type %q", body.SourceType)),
+ http.StatusBadRequest,
+ )
+ }
+ if body.SourceType == "link" {
+ if _, ok := parseExternalHTTPURL(body.ExternalID); !ok {
+ return repo.EntityOut{}, validate.NewRequestError(
+ validate.NewFieldErrors().Append("external_id", "external_id must be a valid http/https URL"),
+ http.StatusBadRequest,
+ )
+ }
+ }
+
+ title := strings.TrimSpace(body.Title)
+ if title == "" {
+ title = sanitizeExternalURLTitle(body.ExternalID)
+ }
+
+ span.SetAttributes(
+ attribute.String("entity.id", id.String()),
+ attribute.String("integration.source_type", body.SourceType),
+ attribute.String("integration.external_id", redactExternalURLForTrace(body.ExternalID)),
+ )
+
+ ctx := services.NewContext(r.Context())
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
+
+ attType := attachment.Type(strings.TrimSpace(body.AttachmentType))
+ switch attType {
+ case attachment.TypePhoto, attachment.TypeManual, attachment.TypeWarranty,
+ attachment.TypeAttachment, attachment.TypeReceipt:
+ // valid
+ default:
+ attType = attachment.TypeAttachment
+ }
+
+ item, err := ctrl.svc.Entities.AttachmentAddExternalLink(ctx, id, body.SourceType, body.ExternalID, title, attType)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ log.Err(err).Msg("failed to add external link attachment")
+ return repo.EntityOut{}, validate.NewRequestError(err, http.StatusInternalServerError)
+ }
+
+ return item, nil
+ }
+
+ return adapters.ActionID("id", fn, http.StatusCreated)
+}
diff --git a/backend/app/api/routes.go b/backend/app/api/routes.go
index 47779bc4..4cbc9fdc 100644
--- a/backend/app/api/routes.go
+++ b/backend/app/api/routes.go
@@ -172,6 +172,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
// Entity attachment endpoints
r.Post("/entities/{id}/attachments", chain.ToHandlerFunc(v1Ctrl.HandleEntityAttachmentCreate(), userMW...))
+ r.Post("/entities/{id}/attachments/external", chain.ToHandlerFunc(v1Ctrl.HandleEntityAttachmentExternalCreate(), userMW...))
r.Put("/entities/{id}/attachments/{attachment_id}", chain.ToHandlerFunc(v1Ctrl.HandleEntityAttachmentUpdate(), userMW...))
r.Delete("/entities/{id}/attachments/{attachment_id}", chain.ToHandlerFunc(v1Ctrl.HandleEntityAttachmentDelete(), userMW...))
diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.go
index 046ed44a..4fd78299 100644
--- a/backend/app/api/static/docs/docs.go
+++ b/backend/app/api/static/docs/docs.go
@@ -688,6 +688,58 @@ const docTemplate = `{
}
}
},
+ "/v1/entities/{id}/attachments/external": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "Links an entity to a document or URL in an external system without copying",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Entities Attachments"
+ ],
+ "summary": "Create External Link Attachment",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Entity ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "External document reference",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.externalAttachmentRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.EntityOut"
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/validate.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
"/v1/entities/{id}/attachments/{attachment_id}": {
"get": {
"security": [
@@ -5760,6 +5812,23 @@ const docTemplate = `{
"item": {}
}
},
+ "v1.externalAttachmentRequest": {
+ "type": "object",
+ "properties": {
+ "attachment_type": {
+ "type": "string"
+ },
+ "external_id": {
+ "type": "string"
+ },
+ "source_type": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ }
+ },
"validate.ErrorResponse": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.json
index bf4b6ed1..6df20892 100644
--- a/backend/app/api/static/docs/openapi-3.json
+++ b/backend/app/api/static/docs/openapi-3.json
@@ -741,6 +741,64 @@
}
}
},
+ "/v1/entities/{id}/attachments/external": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "Links an entity to a document or URL in an external system without copying",
+ "tags": [
+ "Entities Attachments"
+ ],
+ "summary": "Create External Link Attachment",
+ "parameters": [
+ {
+ "description": "Entity ID",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.externalAttachmentRequest"
+ }
+ }
+ },
+ "description": "External document reference",
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.EntityOut"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/validate.ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/v1/entities/{id}/attachments/{attachment_id}": {
"get": {
"security": [
@@ -5954,6 +6012,23 @@
"item": {}
}
},
+ "v1.externalAttachmentRequest": {
+ "type": "object",
+ "properties": {
+ "attachment_type": {
+ "type": "string"
+ },
+ "external_id": {
+ "type": "string"
+ },
+ "source_type": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ }
+ },
"validate.ErrorResponse": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yaml
index 5a1b846d..4c7fd14f 100644
--- a/backend/app/api/static/docs/openapi-3.yaml
+++ b/backend/app/api/static/docs/openapi-3.yaml
@@ -441,6 +441,42 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/validate.ErrorResponse"
+ "/v1/entities/{id}/attachments/external":
+ post:
+ security:
+ - Bearer: []
+ description: Links an entity to a document or URL in an external system without
+ copying
+ tags:
+ - Entities Attachments
+ summary: Create External Link Attachment
+ parameters:
+ - description: Entity ID
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.externalAttachmentRequest"
+ description: External document reference
+ required: true
+ responses:
+ "201":
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.EntityOut"
+ "400":
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/validate.ErrorResponse"
"/v1/entities/{id}/attachments/{attachment_id}":
get:
security:
@@ -3807,6 +3843,17 @@ components:
type: object
properties:
item: {}
+ v1.externalAttachmentRequest:
+ type: object
+ properties:
+ attachment_type:
+ type: string
+ external_id:
+ type: string
+ source_type:
+ type: string
+ title:
+ type: string
validate.ErrorResponse:
type: object
properties:
diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.json
index f9c9bd75..03988e58 100644
--- a/backend/app/api/static/docs/swagger.json
+++ b/backend/app/api/static/docs/swagger.json
@@ -685,6 +685,58 @@
}
}
},
+ "/v1/entities/{id}/attachments/external": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "Links an entity to a document or URL in an external system without copying",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Entities Attachments"
+ ],
+ "summary": "Create External Link Attachment",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Entity ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "External document reference",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.externalAttachmentRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.EntityOut"
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/validate.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
"/v1/entities/{id}/attachments/{attachment_id}": {
"get": {
"security": [
@@ -5757,6 +5809,23 @@
"item": {}
}
},
+ "v1.externalAttachmentRequest": {
+ "type": "object",
+ "properties": {
+ "attachment_type": {
+ "type": "string"
+ },
+ "external_id": {
+ "type": "string"
+ },
+ "source_type": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ }
+ },
"validate.ErrorResponse": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yaml
index dfca1378..a94de2f1 100644
--- a/backend/app/api/static/docs/swagger.yaml
+++ b/backend/app/api/static/docs/swagger.yaml
@@ -2029,6 +2029,17 @@ definitions:
properties:
item: {}
type: object
+ v1.externalAttachmentRequest:
+ properties:
+ attachment_type:
+ type: string
+ external_id:
+ type: string
+ source_type:
+ type: string
+ title:
+ type: string
+ type: object
validate.ErrorResponse:
properties:
error:
@@ -2437,6 +2448,40 @@ paths:
summary: Update Entity Attachment
tags:
- Entities Attachments
+ /v1/entities/{id}/attachments/external:
+ post:
+ consumes:
+ - application/json
+ description: Links an entity to a document or URL in an external system without
+ copying
+ parameters:
+ - description: Entity ID
+ in: path
+ name: id
+ required: true
+ type: string
+ - description: External document reference
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.externalAttachmentRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.EntityOut'
+ "400":
+ description: Bad Request
+ schema:
+ $ref: '#/definitions/validate.ErrorResponse'
+ security:
+ - Bearer: []
+ summary: Create External Link Attachment
+ tags:
+ - Entities Attachments
/v1/entities/{id}/duplicate:
post:
parameters:
diff --git a/backend/go.sum b/backend/go.sum
index b125519e..bb664ea6 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -135,6 +135,12 @@ github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1x
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/clipperhouse/displaywidth v0.6.2 h1:ZDpTkFfpHOKte4RG5O/BOyf3ysnvFswpyYrV7z2uAKo=
+github.com/clipperhouse/displaywidth v0.6.2/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
+github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
+github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
+github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
+github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
@@ -332,6 +338,8 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
+github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
+github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
@@ -354,6 +362,14 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/olahol/melody v1.4.0 h1:Pa5SdeZL/zXPi1tJuMAPDbl4n3gQOThSL6G1p4qZ4SI=
github.com/olahol/melody v1.4.0/go.mod h1:GgkTl6Y7yWj/HtfD48Q5vLKPVoZOH+Qqgfa7CvJgJM4=
+github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc=
+github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6/go.mod h1:rEKTHC9roVVicUIfZK7DYrdIoM0EOr8mK1Hj5s3JjH0=
+github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
+github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
+github.com/olekukonko/ll v0.1.4-0.20260115111900-9e59c2286df0 h1:jrYnow5+hy3WRDCBypUFvVKNSPPCdqgSXIE9eJDD8LM=
+github.com/olekukonko/ll v0.1.4-0.20260115111900-9e59c2286df0/go.mod h1:b52bVQRRPObe+yyBl0TxNfhesL0nedD4Cht0/zx55Ew=
+github.com/olekukonko/tablewriter v1.1.3 h1:VSHhghXxrP0JHl+0NnKid7WoEmd9/urKRJLysb70nnA=
+github.com/olekukonko/tablewriter v1.1.3/go.mod h1:9VU0knjhmMkXjnMKrZ3+L2JhhtsQ/L38BbL3CRNE8tM=
github.com/onsi/ginkgo/v2 v2.9.2 h1:BA2GMJOtfGAfagzYtrAlufIP0lq6QERkFmHLMLPwFSU=
github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts=
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
@@ -397,6 +413,10 @@ github.com/shirou/gopsutil/v4 v4.26.3 h1:2ESdQt90yU3oXF/CdOlRCJxrP+Am1aBYubTMTfx
github.com/shirou/gopsutil/v4 v4.26.3/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
+github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
diff --git a/backend/internal/core/services/service_items_attachments.go b/backend/internal/core/services/service_items_attachments.go
index 4e1db467..b96eedcb 100644
--- a/backend/internal/core/services/service_items_attachments.go
+++ b/backend/internal/core/services/service_items_attachments.go
@@ -2,6 +2,7 @@ package services
import (
"context"
+ "fmt"
"io"
"github.com/google/uuid"
@@ -113,6 +114,52 @@ func (svc *EntityService) AttachmentAdd(ctx Context, entityID uuid.UUID, filenam
return out, err
}
+func (svc *EntityService) AttachmentAddExternalLink(ctx Context, entityID uuid.UUID, sourceType, externalID, title string, attType attachment.Type) (repo.EntityOut, error) {
+ spanCtx, span := entityServiceTracer().Start(ctx.Context, "service.EntityService.AttachmentAddExternalLink",
+ trace.WithAttributes(
+ attribute.String("group.id", ctx.GID.String()),
+ attribute.String("entity.id", entityID.String()),
+ attribute.String("integration.source_type", sourceType),
+ attribute.String("integration.external_id", externalID),
+ ))
+ defer span.End()
+ ctx.Context = spanCtx
+
+ mimeType, ok := repo.MimeTypeForSourceType(sourceType)
+ if !ok {
+ err := fmt.Errorf("unknown source_type %q", sourceType)
+ recordServiceSpanError(span, err)
+ return repo.EntityOut{}, err
+ }
+
+ verifyCtx, verifySpan := entityServiceTracer().Start(spanCtx, "service.EntityService.AttachmentAddExternalLink.verifyEntity")
+ _, err := svc.repo.Entities.GetOneByGroup(verifyCtx, ctx.GID, entityID)
+ if err != nil {
+ recordServiceSpanError(verifySpan, err)
+ verifySpan.End()
+ recordServiceSpanError(span, err)
+ return repo.EntityOut{}, err
+ }
+ verifySpan.End()
+
+ createCtx, createSpan := entityServiceTracer().Start(spanCtx, "service.EntityService.AttachmentAddExternalLink.create")
+ _, err = svc.repo.Attachments.CreateExternalLink(createCtx, entityID, externalID, title, mimeType, attType)
+ if err != nil {
+ recordServiceSpanError(createSpan, err)
+ createSpan.End()
+ recordServiceSpanError(span, err)
+ log.Err(err).Msg("failed to create external link attachment")
+ return repo.EntityOut{}, err
+ }
+ createSpan.End()
+
+ out, err := svc.repo.Entities.GetOneByGroup(ctx, ctx.GID, entityID)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
+}
+
func (svc *EntityService) AttachmentDelete(ctx context.Context, gid uuid.UUID, attachmentID uuid.UUID) error {
ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.AttachmentDelete",
trace.WithAttributes(
diff --git a/backend/internal/core/services/service_items_attachments_external_test.go b/backend/internal/core/services/service_items_attachments_external_test.go
new file mode 100644
index 00000000..29e0aca5
--- /dev/null
+++ b/backend/internal/core/services/service_items_attachments_external_test.go
@@ -0,0 +1,141 @@
+package services
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+)
+
+func newExternalLinkEntity(t *testing.T) repo.EntityOut {
+ t.Helper()
+
+ loc, err := tRepos.Entities.CreateContainer(context.Background(), tGroup.ID, repo.EntityCreate{Name: fk.Str(10)})
+ require.NoError(t, err)
+
+ entity, err := tRepos.Entities.Create(context.Background(), tGroup.ID, repo.EntityCreate{
+ Name: fk.Str(10),
+ ParentID: loc.ID,
+ })
+ require.NoError(t, err)
+
+ t.Cleanup(func() {
+ _ = tRepos.Entities.Delete(context.Background(), entity.ID)
+ })
+
+ return entity
+}
+
+func TestEntityService_AttachmentAddExternalLink_DefaultType(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+ entity := newExternalLinkEntity(t)
+
+ out, err := svc.AttachmentAddExternalLink(tCtx, entity.ID, "link", "https://example.com/doc/42", "Example Doc", "")
+ require.NoError(t, err)
+ require.NotEmpty(t, out.Attachments)
+
+ var found bool
+ for _, att := range out.Attachments {
+ if att.Path == "https://example.com/doc/42" {
+ found = true
+ assert.Equal(t, repo.MimeTypeLinkURL, att.MimeType)
+ assert.Equal(t, "Example Doc", att.Title)
+ assert.Equal(t, string(attachment.TypeAttachment), att.Type)
+ }
+ }
+ assert.True(t, found)
+}
+
+func TestEntityService_AttachmentAddExternalLink_ManualType(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+ entity := newExternalLinkEntity(t)
+
+ out, err := svc.AttachmentAddExternalLink(tCtx, entity.ID, "link", "https://example.com/manual", "Manual", attachment.TypeManual)
+ require.NoError(t, err)
+
+ var found bool
+ for _, att := range out.Attachments {
+ if att.Path == "https://example.com/manual" {
+ found = true
+ assert.Equal(t, string(attachment.TypeManual), att.Type)
+ }
+ }
+ assert.True(t, found)
+}
+
+func TestEntityService_AttachmentAddExternalLink_WarrantyType(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+ entity := newExternalLinkEntity(t)
+
+ out, err := svc.AttachmentAddExternalLink(tCtx, entity.ID, "link", "https://example.com/warranty", "Warranty", attachment.TypeWarranty)
+ require.NoError(t, err)
+
+ var found bool
+ for _, att := range out.Attachments {
+ if att.Path == "https://example.com/warranty" {
+ found = true
+ assert.Equal(t, string(attachment.TypeWarranty), att.Type)
+ }
+ }
+ assert.True(t, found)
+}
+
+func TestEntityService_AttachmentAddExternalLink_ReceiptType(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+ entity := newExternalLinkEntity(t)
+
+ out, err := svc.AttachmentAddExternalLink(tCtx, entity.ID, "link", "https://example.com/receipt", "Receipt", attachment.TypeReceipt)
+ require.NoError(t, err)
+
+ var found bool
+ for _, att := range out.Attachments {
+ if att.Path == "https://example.com/receipt" {
+ found = true
+ assert.Equal(t, string(attachment.TypeReceipt), att.Type)
+ }
+ }
+ assert.True(t, found)
+}
+
+func TestEntityService_AttachmentAddExternalLink_InvalidEntity(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+
+ _, err := svc.AttachmentAddExternalLink(tCtx, uuid.New(), "link", "https://example.com/missing", "Missing", attachment.TypeAttachment)
+ assert.Error(t, err)
+}
+
+func TestEntityService_AttachmentAddExternalLink_UnknownSourceType(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+ entity := newExternalLinkEntity(t)
+
+ _, err := svc.AttachmentAddExternalLink(tCtx, entity.ID, "paperless", "42", "Paperless", attachment.TypeAttachment)
+ assert.Error(t, err)
+}
+
+func TestEntityService_AttachmentDelete_ExternalLink(t *testing.T) {
+ svc := &EntityService{repo: tRepos}
+ entity := newExternalLinkEntity(t)
+
+ out, err := svc.AttachmentAddExternalLink(tCtx, entity.ID, "link", "https://example.com/delete", "Delete Me", attachment.TypeAttachment)
+ require.NoError(t, err)
+ require.NotEmpty(t, out.Attachments)
+
+ var createdID uuid.UUID
+ for _, att := range out.Attachments {
+ if att.Path == "https://example.com/delete" {
+ createdID = att.ID
+ break
+ }
+ }
+ require.NotEqual(t, uuid.Nil, createdID)
+
+ err = svc.AttachmentDelete(tCtx, tCtx.GID, createdID)
+ require.NoError(t, err)
+
+ _, err = tRepos.Attachments.Get(context.Background(), tCtx.GID, createdID)
+ assert.Error(t, err)
+}
diff --git a/backend/internal/data/repo/repo_item_attachments.go b/backend/internal/data/repo/repo_item_attachments.go
index 6efd2df9..db8f5914 100644
--- a/backend/internal/data/repo/repo_item_attachments.go
+++ b/backend/internal/data/repo/repo_item_attachments.go
@@ -84,6 +84,30 @@ type (
}
)
+const MimeTypeLinkURL = "link/url"
+
+var externalLinkMimeTypes = []string{
+ MimeTypeLinkURL,
+}
+
+func MimeTypeForSourceType(sourceType string) (string, bool) {
+ switch sourceType {
+ case "link":
+ return MimeTypeLinkURL, true
+ default:
+ return "", false
+ }
+}
+
+func isExternalLink(mimeType string) bool {
+ for _, m := range externalLinkMimeTypes {
+ if m == mimeType {
+ return true
+ }
+ }
+ return false
+}
+
func ToItemAttachment(attachment *ent.Attachment) ItemAttachment {
return ItemAttachment{
ID: attachment.ID,
@@ -404,6 +428,32 @@ func (r *AttachmentRepo) Create(ctx context.Context, itemID uuid.UUID, doc ItemC
return attachmentDb, nil
}
+func (r *AttachmentRepo) CreateExternalLink(ctx context.Context, entityID uuid.UUID, externalID string, title string, mimeType string, attType attachment.Type) (*ent.Attachment, error) {
+ ctx, span := otel.Tracer("data").Start(ctx, "repo.AttachmentRepo.CreateExternalLink")
+ defer span.End()
+
+ if attType == "" {
+ attType = attachment.TypeAttachment
+ }
+
+ att, err := r.db.Attachment.Create().
+ SetID(uuid.New()).
+ SetCreatedAt(time.Now()).
+ SetUpdatedAt(time.Now()).
+ SetType(attType).
+ SetEntityID(entityID).
+ SetTitle(title).
+ SetPath(externalID).
+ SetMimeType(mimeType).
+ SetPrimary(false).
+ Save(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return att, nil
+}
+
func (r *AttachmentRepo) Get(ctx context.Context, gid uuid.UUID, id uuid.UUID) (*ent.Attachment, error) {
first, err := r.db.Attachment.Query().Where(attachment.ID(id)).Only(ctx)
if err != nil {
@@ -500,6 +550,10 @@ func (r *AttachmentRepo) Delete(ctx context.Context, gid uuid.UUID, id uuid.UUID
return err
}
+ if isExternalLink(doc.MimeType) {
+ return r.db.Attachment.DeleteOneID(id).Exec(ctx)
+ }
+
all, err := r.db.Attachment.Query().Where(attachment.Path(doc.Path)).All(ctx)
if err != nil {
return err
diff --git a/backend/internal/data/repo/repo_item_attachments_test.go b/backend/internal/data/repo/repo_item_attachments_test.go
index dc1e8099..1bcfbfd6 100644
--- a/backend/internal/data/repo/repo_item_attachments_test.go
+++ b/backend/internal/data/repo/repo_item_attachments_test.go
@@ -15,6 +15,16 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/sys/config"
)
+func TestMimeTypeForSourceType(t *testing.T) {
+ mime, ok := MimeTypeForSourceType("link")
+ assert.True(t, ok)
+ assert.Equal(t, MimeTypeLinkURL, mime)
+
+ mime, ok = MimeTypeForSourceType("unknown")
+ assert.False(t, ok)
+ assert.Empty(t, mime)
+}
+
func TestAttachmentRepo_Create(t *testing.T) {
entity := useEntities(t, 1)[0]
@@ -128,6 +138,73 @@ func TestAttachmentRepo_Delete(t *testing.T) {
require.Error(t, err)
}
+func TestAttachmentRepo_CreateExternalLink(t *testing.T) {
+ ctx := context.Background()
+ entity := useEntities(t, 1)[0]
+
+ att, err := tRepos.Attachments.CreateExternalLink(
+ ctx,
+ entity.ID,
+ "https://example.com/manual",
+ "Example Manual",
+ MimeTypeLinkURL,
+ attachment.TypeManual,
+ )
+ require.NoError(t, err)
+ require.NotNil(t, att)
+
+ t.Cleanup(func() {
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, att.ID)
+ })
+
+ assert.Equal(t, "https://example.com/manual", att.Path)
+ assert.Equal(t, "Example Manual", att.Title)
+ assert.Equal(t, MimeTypeLinkURL, att.MimeType)
+ assert.Equal(t, attachment.TypeManual, att.Type)
+ assert.False(t, att.Primary)
+}
+
+func TestAttachmentRepo_DeleteExternalLink(t *testing.T) {
+ ctx := context.Background()
+ entity := useEntities(t, 1)[0]
+
+ att, err := tRepos.Attachments.CreateExternalLink(
+ ctx,
+ entity.ID,
+ "https://example.com/receipt",
+ "Example Receipt",
+ MimeTypeLinkURL,
+ attachment.TypeReceipt,
+ )
+ require.NoError(t, err)
+
+ err = tRepos.Attachments.Delete(ctx, tGroup.ID, att.ID)
+ require.NoError(t, err)
+
+ _, err = tRepos.Attachments.Get(ctx, tGroup.ID, att.ID)
+ require.Error(t, err)
+}
+
+func TestAttachmentRepo_DeleteExternalLink_DoesNotRequireBlobStorage(t *testing.T) {
+ ctx := context.Background()
+
+ repos := New(tClient, tbus, config.Storage{PrefixPath: "/", ConnString: "mem://"}, "mem://{{ .Topic }}", config.Thumbnail{Enabled: false})
+ entity := useEntities(t, 1)[0]
+
+ att, err := repos.Attachments.CreateExternalLink(
+ ctx,
+ entity.ID,
+ "https://example.com/no-blob",
+ "No Blob",
+ MimeTypeLinkURL,
+ attachment.TypeAttachment,
+ )
+ require.NoError(t, err)
+
+ err = repos.Attachments.Delete(ctx, tGroup.ID, att.ID)
+ require.NoError(t, err)
+}
+
func TestAttachmentRepo_EnsureSinglePrimaryAttachment(t *testing.T) {
ctx := context.Background()
attachments := useAttachments(t, 2)
diff --git a/docs/public/api/openapi-3.0.json b/docs/public/api/openapi-3.0.json
index bf4b6ed1..6df20892 100644
--- a/docs/public/api/openapi-3.0.json
+++ b/docs/public/api/openapi-3.0.json
@@ -741,6 +741,64 @@
}
}
},
+ "/v1/entities/{id}/attachments/external": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "Links an entity to a document or URL in an external system without copying",
+ "tags": [
+ "Entities Attachments"
+ ],
+ "summary": "Create External Link Attachment",
+ "parameters": [
+ {
+ "description": "Entity ID",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.externalAttachmentRequest"
+ }
+ }
+ },
+ "description": "External document reference",
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.EntityOut"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/validate.ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/v1/entities/{id}/attachments/{attachment_id}": {
"get": {
"security": [
@@ -5954,6 +6012,23 @@
"item": {}
}
},
+ "v1.externalAttachmentRequest": {
+ "type": "object",
+ "properties": {
+ "attachment_type": {
+ "type": "string"
+ },
+ "external_id": {
+ "type": "string"
+ },
+ "source_type": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ }
+ },
"validate.ErrorResponse": {
"type": "object",
"properties": {
diff --git a/docs/public/api/openapi-3.0.yaml b/docs/public/api/openapi-3.0.yaml
index 5a1b846d..4c7fd14f 100644
--- a/docs/public/api/openapi-3.0.yaml
+++ b/docs/public/api/openapi-3.0.yaml
@@ -441,6 +441,42 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/validate.ErrorResponse"
+ "/v1/entities/{id}/attachments/external":
+ post:
+ security:
+ - Bearer: []
+ description: Links an entity to a document or URL in an external system without
+ copying
+ tags:
+ - Entities Attachments
+ summary: Create External Link Attachment
+ parameters:
+ - description: Entity ID
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.externalAttachmentRequest"
+ description: External document reference
+ required: true
+ responses:
+ "201":
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.EntityOut"
+ "400":
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/validate.ErrorResponse"
"/v1/entities/{id}/attachments/{attachment_id}":
get:
security:
@@ -3807,6 +3843,17 @@ components:
type: object
properties:
item: {}
+ v1.externalAttachmentRequest:
+ type: object
+ properties:
+ attachment_type:
+ type: string
+ external_id:
+ type: string
+ source_type:
+ type: string
+ title:
+ type: string
validate.ErrorResponse:
type: object
properties:
diff --git a/docs/public/api/swagger-2.0.json b/docs/public/api/swagger-2.0.json
index f9c9bd75..03988e58 100644
--- a/docs/public/api/swagger-2.0.json
+++ b/docs/public/api/swagger-2.0.json
@@ -685,6 +685,58 @@
}
}
},
+ "/v1/entities/{id}/attachments/external": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "Links an entity to a document or URL in an external system without copying",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Entities Attachments"
+ ],
+ "summary": "Create External Link Attachment",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Entity ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "External document reference",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.externalAttachmentRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.EntityOut"
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/validate.ErrorResponse"
+ }
+ }
+ }
+ }
+ },
"/v1/entities/{id}/attachments/{attachment_id}": {
"get": {
"security": [
@@ -5757,6 +5809,23 @@
"item": {}
}
},
+ "v1.externalAttachmentRequest": {
+ "type": "object",
+ "properties": {
+ "attachment_type": {
+ "type": "string"
+ },
+ "external_id": {
+ "type": "string"
+ },
+ "source_type": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ }
+ },
"validate.ErrorResponse": {
"type": "object",
"properties": {
diff --git a/docs/public/api/swagger-2.0.yaml b/docs/public/api/swagger-2.0.yaml
index dfca1378..a94de2f1 100644
--- a/docs/public/api/swagger-2.0.yaml
+++ b/docs/public/api/swagger-2.0.yaml
@@ -2029,6 +2029,17 @@ definitions:
properties:
item: {}
type: object
+ v1.externalAttachmentRequest:
+ properties:
+ attachment_type:
+ type: string
+ external_id:
+ type: string
+ source_type:
+ type: string
+ title:
+ type: string
+ type: object
validate.ErrorResponse:
properties:
error:
@@ -2437,6 +2448,40 @@ paths:
summary: Update Entity Attachment
tags:
- Entities Attachments
+ /v1/entities/{id}/attachments/external:
+ post:
+ consumes:
+ - application/json
+ description: Links an entity to a document or URL in an external system without
+ copying
+ parameters:
+ - description: Entity ID
+ in: path
+ name: id
+ required: true
+ type: string
+ - description: External document reference
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.externalAttachmentRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.EntityOut'
+ "400":
+ description: Bad Request
+ schema:
+ $ref: '#/definitions/validate.ErrorResponse'
+ security:
+ - Bearer: []
+ summary: Create External Link Attachment
+ tags:
+ - Entities Attachments
/v1/entities/{id}/duplicate:
post:
parameters:
diff --git a/frontend/components/Item/AttachmentsList.vue b/frontend/components/Item/AttachmentsList.vue
index fbda89f7..5140821c 100644
--- a/frontend/components/Item/AttachmentsList.vue
+++ b/frontend/components/Item/AttachmentsList.vue
@@ -5,34 +5,66 @@
:key="attachment.id"
class="flex items-center justify-between py-3 pl-3 pr-4 text-sm"
>
- <div class="flex w-0 flex-1 items-center">
- <MdiPaperclip class="size-5 shrink-0 text-gray-400" aria-hidden="true" />
- <span class="ml-2 w-0 flex-1 truncate"> {{ attachment.title }}</span>
- </div>
- <div class="ml-4 flex shrink-0 gap-2">
- <TooltipProvider :delay-duration="0">
- <Tooltip>
- <TooltipTrigger as-child>
- <a
- :class="buttonVariants({ size: 'icon' })"
- :href="attachmentURL(attachment.id)"
- :download="attachment.title"
- >
- <MdiDownload />
- </a>
- </TooltipTrigger>
- <TooltipContent> {{ $t("components.item.attachments_list.download") }} </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger as-child>
- <a :class="buttonVariants({ size: 'icon' })" :href="attachmentURL(attachment.id)" target="_blank">
- <MdiOpenInNew />
- </a>
- </TooltipTrigger>
- <TooltipContent> {{ $t("components.item.attachments_list.open_new_tab") }} </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
+ <template v-if="isExternalURLAttachment(attachment)">
+ <div class="flex w-0 flex-1 items-center">
+ <MdiLinkVariant class="size-5 shrink-0 text-gray-400" aria-hidden="true" />
+ <a
+ class="ml-2 w-0 flex-1 truncate text-primary underline"
+ :href="attachment.path"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {{ attachment.title }}
+ </a>
+ </div>
+ <div class="ml-4 flex shrink-0 gap-2">
+ <TooltipProvider :delay-duration="0">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <a
+ :class="buttonVariants({ size: 'icon' })"
+ :href="attachment.path"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <MdiOpenInNew />
+ </a>
+ </TooltipTrigger>
+ <TooltipContent> {{ $t("components.item.attachments_list.open_new_tab") }} </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </template>
+ <template v-else>
+ <div class="flex w-0 flex-1 items-center">
+ <MdiPaperclip class="size-5 shrink-0 text-gray-400" aria-hidden="true" />
+ <span class="ml-2 w-0 flex-1 truncate"> {{ attachment.title }}</span>
+ </div>
+ <div class="ml-4 flex shrink-0 gap-2">
+ <TooltipProvider :delay-duration="0">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <a
+ :class="buttonVariants({ size: 'icon' })"
+ :href="attachmentURL(attachment.id)"
+ :download="attachment.title"
+ >
+ <MdiDownload />
+ </a>
+ </TooltipTrigger>
+ <TooltipContent> {{ $t("components.item.attachments_list.download") }} </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <a :class="buttonVariants({ size: 'icon' })" :href="attachmentURL(attachment.id)" target="_blank">
+ <MdiOpenInNew />
+ </a>
+ </TooltipTrigger>
+ <TooltipContent> {{ $t("components.item.attachments_list.open_new_tab") }} </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </template>
</li>
</ul>
</template>
@@ -40,6 +72,7 @@
<script setup lang="ts">
import type { ItemAttachment } from "~~/lib/api/types/data-contracts";
import MdiPaperclip from "~icons/mdi/paperclip";
+ import MdiLinkVariant from "~icons/mdi/link-variant";
import MdiDownload from "~icons/mdi/download";
import MdiOpenInNew from "~icons/mdi/open-in-new";
import { buttonVariants } from "@/components/ui/button";
@@ -61,6 +94,13 @@
function attachmentURL(attachmentId: string) {
return api.authURL(`/entities/${props.itemId}/attachments/${attachmentId}`);
}
+
+ function isExternalURLAttachment(attachment: ItemAttachment) {
+ if (attachment.mimeType === "link/url") {
+ return true;
+ }
+ return attachment.path.startsWith("http://") || attachment.path.startsWith("https://");
+ }
</script>
<style scoped></style>
diff --git a/frontend/lib/api/classes/items.ts b/frontend/lib/api/classes/items.ts
index 11f35172..65f40ee8 100644
--- a/frontend/lib/api/classes/items.ts
+++ b/frontend/lib/api/classes/items.ts
@@ -67,6 +67,13 @@ export class AttachmentsAPI extends BaseAPI {
body: data,
});
}
+
+ addExternalLink(id: string, sourceType: string, externalId: string, title: string, attachmentType?: string) {
+ return this.http.post<{ source_type: string; external_id: string; title: string; attachment_type?: string }, EntityOut>({
+ url: route(`/entities/${id}/attachments/external`),
+ body: { source_type: sourceType, external_id: externalId, title, attachment_type: attachmentType },
+ });
+ }
}
export class FieldsAPI extends BaseAPI {
diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.ts
index 1a869f98..982c0c4e 100644
--- a/frontend/lib/api/types/data-contracts.ts
+++ b/frontend/lib/api/types/data-contracts.ts
@@ -1240,6 +1240,13 @@ export interface Wrapped {
item: any;
}
+export interface ExternalAttachmentRequest {
+ attachment_type: string;
+ external_id: string;
+ source_type: string;
+ title: string;
+}
+
export interface ValidateErrorResponse {
error: string;
fields: string;
diff --git a/frontend/pages/item/[id]/index/edit.vue b/frontend/pages/item/[id]/index/edit.vue
index 123fa0aa..8255d9ff 100644
--- a/frontend/pages/item/[id]/index/edit.vue
+++ b/frontend/pages/item/[id]/index/edit.vue
@@ -11,6 +11,7 @@
import MdiPencil from "~icons/mdi/pencil";
import MdiContentSaveOutline from "~icons/mdi/content-save-outline";
import MdiImageOutline from "~icons/mdi/image-outline";
+ import MdiOpenInNew from "~icons/mdi/open-in-new";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useDialog } from "@/components/ui/dialog-provider";
@@ -319,6 +320,77 @@
const dropManual = (files: File[] | null) => uploadAttachment(files, AttachmentTypes.Manual);
const dropReceipt = (files: File[] | null) => uploadAttachment(files, AttachmentTypes.Receipt);
+ function getDroppedURL(event: DragEvent): string {
+ const dt = event.dataTransfer;
+ if (!dt) return "";
+
+ const mozUrl = dt.getData("text/x-moz-url").split("\n")[0]?.trim() || "";
+ const uriList = dt
+ .getData("text/uri-list")
+ .split("\n")
+ .find(u => u.trim() && !u.startsWith("#"))
+ ?.trim();
+
+ return (mozUrl || uriList || dt.getData("text/plain").trim()).trim();
+ }
+
+ function isValidHttpURL(value: string): boolean {
+ try {
+ const parsed = new URL(value);
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
+ } catch {
+ return false;
+ }
+ }
+
+ function fallbackLinkTitle(value: string): string {
+ try {
+ const parsed = new URL(value);
+ return parsed.hostname + parsed.pathname;
+ } catch {
+ return value;
+ }
+ }
+
+ async function handleAttachmentCardDrop(event: DragEvent) {
+ event.preventDefault();
+ const dt = event.dataTransfer;
+ if (!dt) return;
+
+ if (dt.files && dt.files.length > 0) {
+ return;
+ }
+
+ const droppedURL = getDroppedURL(event);
+ if (!droppedURL) return;
+
+ if (!isValidHttpURL(droppedURL)) {
+ toast.error(t("items.toast.failed_upload_attachment"));
+ return;
+ }
+
+ const targetEl = event.target as Element | null;
+ const zoneEl = targetEl?.closest("[data-link-type]");
+ const attachmentType = zoneEl?.getAttribute("data-link-type") || "attachment";
+
+ const title = fallbackLinkTitle(droppedURL);
+ const { data, error } = await api.items.attachments.addExternalLink(
+ itemId.value,
+ "link",
+ droppedURL,
+ title,
+ attachmentType,
+ );
+
+ if (error) {
+ toast.error(t("items.toast.failed_upload_attachment"));
+ return;
+ }
+
+ toast.success(t("items.toast.attachment_uploaded"));
+ item.value.attachments = data.attachments;
+ }
+
async function uploadAttachment(files: File[] | null, type: AttachmentTypes | null) {
if (!files || files.length === 0 || !files[0]) {
return;
@@ -680,21 +752,22 @@
</div>
</BaseCard>
- <Card ref="attDropZone" class="overflow-visible shadow-xl">
+ <Card ref="attDropZone" class="overflow-visible shadow-xl" @dragover.prevent @drop.prevent="handleAttachmentCardDrop">
<div class="px-4 py-5 sm:px-6">
<h3 class="text-lg font-medium leading-6">{{ $t("items.attachments") }}</h3>
<p class="text-xs">{{ $t("items.changes_persisted_immediately") }}</p>
</div>
<div class="border-t p-4">
<div v-if="attDropZoneActive" class="grid grid-cols-4 gap-4">
- <DropZone @drop="dropPhoto"> {{ $t("items.photos") }} </DropZone>
- <DropZone @drop="dropWarranty"> {{ $t("items.warranty") }} </DropZone>
- <DropZone @drop="dropManual"> {{ $t("items.manuals") }} </DropZone>
- <DropZone @drop="dropAttachment"> {{ $t("items.attachments") }} </DropZone>
- <DropZone @drop="dropReceipt"> {{ $t("items.receipts") }} </DropZone>
+ <DropZone data-link-type="photo" @drop="dropPhoto"> {{ $t("items.photos") }} </DropZone>
+ <DropZone data-link-type="warranty" @drop="dropWarranty"> {{ $t("items.warranty") }} </DropZone>
+ <DropZone data-link-type="manual" @drop="dropManual"> {{ $t("items.manuals") }} </DropZone>
+ <DropZone data-link-type="attachment" @drop="dropAttachment"> {{ $t("items.attachments") }} </DropZone>
+ <DropZone data-link-type="receipt" @drop="dropReceipt"> {{ $t("items.receipts") }} </DropZone>
</div>
<button
v-else
+ data-link-type="attachment"
class="grid h-24 w-full place-content-center border-2 border-dashed border-primary"
@click="clickUpload"
>
@@ -744,6 +817,20 @@
</TooltipTrigger>
<TooltipContent>{{ $t("items.edit.view_image") }}</TooltipContent>
</Tooltip>
+ <Tooltip
+ v-if="attachment.mimeType === 'link/url' || (attachment.path ?? '').startsWith('http://') || (attachment.path ?? '').startsWith('https://')"
+ >
+ <TooltipTrigger as-child>
+ <a :href="attachment.path" target="_blank" rel="noopener noreferrer">
+ <Button variant="outline" size="icon">
+ <MdiOpenInNew />
+ </Button>
+ </a>
+ </TooltipTrigger>
+ <TooltipContent>
+ {{ $t("components.item.attachments_list.open_new_tab") }}
+ </TooltipContent>
+ </Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="destructive" size="icon" @click="deleteAttachment(attachment.id)">