Skip to content

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

17.6 KB
Raw Blame
package repo

import (
	"context"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
	"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
	"github.com/sysadminsmedia/homebox/backend/internal/sys/config"
	"gocloud.dev/blob"
)

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]

	var ids []uuid.UUID
	t.Cleanup(func() {
		for _, id := range ids {
			_ = tRepos.Attachments.Delete(context.Background(), tGroup.ID, id)
		}
	})

	type args struct {
		ctx      context.Context
		entityID uuid.UUID
		typ      attachment.Type
	}
	tests := []struct {
		name    string
		args    args
		want    *ent.Attachment
		wantErr bool
	}{
		{
			name: "create attachment",
			args: args{
				ctx:      context.Background(),
				entityID: entity.ID,
				typ:      attachment.TypePhoto,
			},
			want: &ent.Attachment{
				Type: attachment.TypePhoto,
			},
		},
		{
			name: "create attachment with invalid entity id",
			args: args{
				ctx:      context.Background(),
				entityID: uuid.New(),
				typ:      "blarg",
			},
			wantErr: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, _ := tRepos.Attachments.Create(tt.args.ctx, tt.args.entityID, ItemCreateAttachment{Title: "Test", Content: strings.NewReader("This is a test")}, tt.args.typ, false)

			if tt.wantErr {
				return
			}

			assert.Equal(t, tt.want.Type, got.Type)

			withEntity, err := tRepos.Attachments.Get(tt.args.ctx, tGroup.ID, got.ID)
			require.NoError(t, err)
			assert.Equal(t, tt.args.entityID, withEntity.Edges.Entity.ID)

			ids = append(ids, got.ID)
		})
	}
}

func useAttachments(t *testing.T, n int) []*ent.Attachment {
	t.Helper()

	entity := useEntities(t, 1)[0]

	ids := make([]uuid.UUID, 0, n)
	t.Cleanup(func() {
		for _, id := range ids {
			_ = tRepos.Attachments.Delete(context.Background(), tGroup.ID, id)
		}
	})

	attachments := make([]*ent.Attachment, n)
	for i := 0; i < n; i++ {
		attach, err := tRepos.Attachments.Create(context.Background(), entity.ID, ItemCreateAttachment{Title: "Test", Content: strings.NewReader("Test String")}, attachment.TypePhoto, true)
		require.NoError(t, err)
		attachments[i] = attach

		ids = append(ids, attach.ID)
	}

	return attachments
}

func TestAttachmentRepo_Update(t *testing.T) {
	entity := useAttachments(t, 1)[0]

	for _, typ := range []attachment.Type{"photo", "manual", "warranty", "attachment"} {
		t.Run(string(typ), func(t *testing.T) {
			_, err := tRepos.Attachments.Update(context.Background(), tGroup.ID, entity.ID, &ItemAttachmentUpdate{
				Type: string(typ),
			})

			require.NoError(t, err)

			updated, err := tRepos.Attachments.Get(context.Background(), tGroup.ID, entity.ID)
			require.NoError(t, err)
			assert.Equal(t, typ, updated.Type)
		})
	}
}

func TestAttachmentRepo_Delete(t *testing.T) {
	entity := useAttachments(t, 1)[0]

	err := tRepos.Attachments.Delete(context.Background(), tGroup.ID, entity.ID)
	require.NoError(t, err)

	_, err = tRepos.Attachments.Get(context.Background(), tGroup.ID, entity.ID)
	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}, nil)
	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)

	setAndVerifyPrimary := func(primaryAttachmentID, nonPrimaryAttachmentID uuid.UUID) {
		primaryAttachment, err := tRepos.Attachments.Update(ctx, tGroup.ID, primaryAttachmentID, &ItemAttachmentUpdate{
			Type:    attachment.TypePhoto.String(),
			Primary: true,
		})
		require.NoError(t, err)

		nonPrimaryAttachment, err := tRepos.Attachments.Get(ctx, tGroup.ID, nonPrimaryAttachmentID)
		require.NoError(t, err)

		assert.True(t, primaryAttachment.Primary)
		assert.False(t, nonPrimaryAttachment.Primary)
	}

	setAndVerifyPrimary(attachments[0].ID, attachments[1].ID)
	setAndVerifyPrimary(attachments[1].ID, attachments[0].ID)
}

func TestAttachmentRepo_UpdateNonPhotoDoesNotAffectPrimaryPhoto(t *testing.T) {
	ctx := context.Background()
	entity := useEntities(t, 1)[0]

	// Create a photo attachment that will be primary
	photoAttachment, err := tRepos.Attachments.Create(ctx, entity.ID, ItemCreateAttachment{Title: "Test Photo", Content: strings.NewReader("Photo content")}, attachment.TypePhoto, true)
	require.NoError(t, err)

	// Create a manual attachment (non-photo)
	manualAttachment, err := tRepos.Attachments.Create(ctx, entity.ID, ItemCreateAttachment{Title: "Test Manual", Content: strings.NewReader("Manual content")}, attachment.TypeManual, false)
	require.NoError(t, err)

	// Cleanup
	t.Cleanup(func() {
		_ = tRepos.Attachments.Delete(ctx, tGroup.ID, photoAttachment.ID)
		_ = tRepos.Attachments.Delete(ctx, tGroup.ID, manualAttachment.ID)
	})

	// Verify photo is primary initially
	photoAttachment, err = tRepos.Attachments.Get(ctx, tGroup.ID, photoAttachment.ID)
	require.NoError(t, err)
	assert.True(t, photoAttachment.Primary)

	// Update the manual attachment (this should NOT affect the photo's primary status)
	_, err = tRepos.Attachments.Update(ctx, tGroup.ID, manualAttachment.ID, &ItemAttachmentUpdate{
		Type:    attachment.TypeManual.String(),
		Title:   "Updated Manual",
		Primary: false,
	})
	require.NoError(t, err)

	// Verify photo is still primary after updating the manual
	photoAttachment, err = tRepos.Attachments.Get(ctx, tGroup.ID, photoAttachment.ID)
	require.NoError(t, err)
	assert.True(t, photoAttachment.Primary, "Photo attachment should remain primary after updating non-photo attachment")

	// Verify manual attachment is not primary
	manualAttachment, err = tRepos.Attachments.Get(ctx, tGroup.ID, manualAttachment.ID)
	require.NoError(t, err)
	assert.False(t, manualAttachment.Primary)
}

func TestAttachmentRepo_AddingPDFAfterPhotoKeepsPhotoAsPrimary(t *testing.T) {
	ctx := context.Background()
	entity := useEntities(t, 1)[0]

	// Step 1: Upload a photo first (this should become primary since it's the first photo)
	photoAttachment, err := tRepos.Attachments.Create(ctx, entity.ID, ItemCreateAttachment{Title: "Item Photo", Content: strings.NewReader("Photo content")}, attachment.TypePhoto, false)
	require.NoError(t, err)

	// Cleanup
	t.Cleanup(func() {
		_ = tRepos.Attachments.Delete(ctx, tGroup.ID, photoAttachment.ID)
	})

	// Verify photo becomes primary automatically (since it's the first photo)
	photoAttachment, err = tRepos.Attachments.Get(ctx, tGroup.ID, photoAttachment.ID)
	require.NoError(t, err)
	assert.True(t, photoAttachment.Primary, "First photo should automatically become primary")

	// Step 2: Add a PDF receipt (this should NOT affect the photo's primary status)
	pdfAttachment, err := tRepos.Attachments.Create(ctx, entity.ID, ItemCreateAttachment{Title: "Receipt PDF", Content: strings.NewReader("PDF content")}, attachment.TypeReceipt, false)
	require.NoError(t, err)

	// Add to cleanup
	t.Cleanup(func() {
		_ = tRepos.Attachments.Delete(ctx, tGroup.ID, pdfAttachment.ID)
	})

	// Step 3: Verify photo is still primary after adding PDF
	photoAttachment, err = tRepos.Attachments.Get(ctx, tGroup.ID, photoAttachment.ID)
	require.NoError(t, err)
	assert.True(t, photoAttachment.Primary, "Photo should remain primary after adding PDF attachment")

	// Verify PDF is not primary
	pdfAttachment, err = tRepos.Attachments.Get(ctx, tGroup.ID, pdfAttachment.ID)
	require.NoError(t, err)
	assert.False(t, pdfAttachment.Primary)

	// Step 4: Test the actual entity summary mapping (this is what determines the card display)
	updatedEntity, err := tRepos.Entities.GetOne(ctx, entity.ID)
	require.NoError(t, err)

	// The entity should have the photo's ID as the imageId
	assert.NotNil(t, updatedEntity.ImageID, "Entity should have an imageId")
	assert.Equal(t, photoAttachment.ID, *updatedEntity.ImageID, "Entity's imageId should match the photo attachment ID")
}

func TestAttachmentRepo_SettingPhotoPrimaryStillWorks(t *testing.T) {
	ctx := context.Background()
	entity := useEntities(t, 1)[0]

	// Create two photo attachments
	photo1, err := tRepos.Attachments.Create(ctx, entity.ID, ItemCreateAttachment{Title: "Photo 1", Content: strings.NewReader("Photo 1 content")}, attachment.TypePhoto, false)
	require.NoError(t, err)

	photo2, err := tRepos.Attachments.Create(ctx, entity.ID, ItemCreateAttachment{Title: "Photo 2", Content: strings.NewReader("Photo 2 content")}, attachment.TypePhoto, false)
	require.NoError(t, err)

	// Cleanup
	t.Cleanup(func() {
		_ = tRepos.Attachments.Delete(ctx, tGroup.ID, photo1.ID)
		_ = tRepos.Attachments.Delete(ctx, tGroup.ID, photo2.ID)
	})

	// First photo should be primary (since it was created first)
	photo1, err = tRepos.Attachments.Get(ctx, tGroup.ID, photo1.ID)
	require.NoError(t, err)
	assert.True(t, photo1.Primary)

	photo2, err = tRepos.Attachments.Get(ctx, tGroup.ID, photo2.ID)
	require.NoError(t, err)
	assert.False(t, photo2.Primary)

	// Now set photo2 as primary (this should work and remove primary from photo1)
	photo2, err = tRepos.Attachments.Update(ctx, tGroup.ID, photo2.ID, &ItemAttachmentUpdate{
		Type:    attachment.TypePhoto.String(),
		Title:   "Photo 2",
		Primary: true,
	})
	require.NoError(t, err)
	assert.True(t, photo2.Primary)

	// Verify photo1 is no longer primary
	photo1, err = tRepos.Attachments.Get(ctx, tGroup.ID, photo1.ID)
	require.NoError(t, err)
	assert.False(t, photo1.Primary, "Photo 1 should no longer be primary after setting Photo 2 as primary")
}

func TestAttachmentRepo_PathNormalization(t *testing.T) {
	// Test that paths always use forward slashes
	repo := &AttachmentRepo{
		storage: config.Storage{
			PrefixPath: ".data",
		},
	}

	testGUID := uuid.MustParse("eb6bf410-a1a8-478d-a803-ca3948368a0c")
	testHash := "f295eb01-18a9-4631-a797-70bd9623edd4.png"

	// Test path() method - should always return forward slashes
	relativePath := repo.path(testGUID, testHash)
	assert.Equal(t, "eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", relativePath)
	assert.NotContains(t, relativePath, "\\", "path() should not contain backslashes")

	// Test fullPath() with forward slash input (from database)
	fullPath := repo.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
	assert.Equal(t, ".data/eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPath)
	assert.NotContains(t, fullPath, "\\", "fullPath() should not contain backslashes")

	// Test fullPath() with backslash input (legacy Windows paths from old database)
	fullPathWithBackslash := repo.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c\\documents\\f295eb01-18a9-4631-a797-70bd9623edd4.png")
	assert.Equal(t, ".data/eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPathWithBackslash)
	assert.NotContains(t, fullPathWithBackslash, "\\", "fullPath() should normalize backslashes to forward slashes")

	// Test with Windows-style prefix path
	repoWindows := &AttachmentRepo{
		storage: config.Storage{
			PrefixPath: ".data",
		},
	}
	fullPathWindows := repoWindows.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
	assert.NotContains(t, fullPathWindows, "\\", "fullPath() should normalize Windows paths")

	// Test empty prefix
	repoNoPrefix := &AttachmentRepo{
		storage: config.Storage{
			PrefixPath: "",
		},
	}
	fullPathNoPrefix := repoNoPrefix.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
	assert.Equal(t, "eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPathNoPrefix)

	// Test with single slash prefix (like in tests)
	repoSlashPrefix := &AttachmentRepo{
		storage: config.Storage{
			PrefixPath: "/",
		},
	}
	fullPathSlashPrefix := repoSlashPrefix.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
	assert.Equal(t, "eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPathSlashPrefix)
	assert.NotContains(t, fullPathSlashPrefix, "//", "fullPath() should not have double slashes")
}

func TestAttachmentRepo_MigrateLegacyFlatPaths(t *testing.T) {
	root := t.TempDir()

	// Legacy flat-encoded files written by pre-v0.22.1 homebox on Windows.
	legacy1 := ".data__0x5c__eb6bf410-a1a8-478d-a803-ca3948368a0c__0x5c__documents__0x5c__hash1.png"
	legacy2 := ".data__0x5c__eb6bf410-a1a8-478d-a803-ca3948368a0c__0x5c__documents__0x5c__hash2.png"
	require.NoError(t, os.WriteFile(filepath.Join(root, legacy1), []byte("one"), 0o644))
	require.NoError(t, os.WriteFile(filepath.Join(root, legacy2), []byte("two"), 0o644))

	// Unrelated file at the bucket root must be left alone.
	other := filepath.Join(root, "homebox.db")
	require.NoError(t, os.WriteFile(other, []byte("db"), 0o644))

	r := &AttachmentRepo{storage: config.Storage{ConnString: "file://" + root, PrefixPath: ".data"}}

	require.NoError(t, r.MigrateLegacyFlatPaths())

	for _, name := range []string{legacy1, legacy2} {
		_, err := os.Stat(filepath.Join(root, name))
		assert.True(t, os.IsNotExist(err), "legacy file %s should have been moved", name)
	}
	for _, hash := range []string{"hash1.png", "hash2.png"} {
		want := filepath.Join(root, ".data", "eb6bf410-a1a8-478d-a803-ca3948368a0c", "documents", hash)
		_, err := os.Stat(want)
		require.NoError(t, err, "expected migrated file at %s", want)
	}
	_, err := os.Stat(other)
	require.NoError(t, err, "unrelated files at the bucket root should be left in place")

	// Idempotent: running again should be a no-op and not error.
	require.NoError(t, r.MigrateLegacyFlatPaths())
}

func TestAttachmentRepo_MigrateLegacyFlatPaths_NoOpForCloudBackend(t *testing.T) {
	r := &AttachmentRepo{storage: config.Storage{ConnString: "s3://my-bucket"}}
	require.NoError(t, r.MigrateLegacyFlatPaths())
}

func TestAttachmentRepo_MigrateLegacyFlatPaths_TargetExistsKeepsSource(t *testing.T) {
	root := t.TempDir()

	legacy := "uuid__0x5c__documents__0x5c__hash.png"
	require.NoError(t, os.WriteFile(filepath.Join(root, legacy), []byte("legacy"), 0o644))

	// Pre-existing target — migration should leave the source in place rather
	// than overwrite the (presumably-correct) target.
	target := filepath.Join(root, "uuid", "documents", "hash.png")
	require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755))
	require.NoError(t, os.WriteFile(target, []byte("new"), 0o644))

	r := &AttachmentRepo{storage: config.Storage{ConnString: "file://" + root}}
	require.NoError(t, r.MigrateLegacyFlatPaths())

	src, err := os.ReadFile(filepath.Join(root, legacy))
	require.NoError(t, err)
	assert.Equal(t, "legacy", string(src), "source file should remain untouched when target exists")

	dst, err := os.ReadFile(target)
	require.NoError(t, err)
	assert.Equal(t, "new", string(dst), "target file should not be overwritten")
}

// TestAttachmentRepo_FilesystemRootBucket covers the Docker image defaults,
// where the bucket root is "/" (file:///) and the prefix selects the data
// directory. Keys under a root bucket must be readable and writable.
func TestAttachmentRepo_FilesystemRootBucket(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("filesystem root bucket layout only applies to unix-like systems")
	}

	ctx := context.Background()
	dataDir := t.TempDir()

	r := &AttachmentRepo{storage: config.Storage{
		ConnString: "file:///?no_tmp_dir=true",
		PrefixPath: strings.TrimPrefix(dataDir, "/"),
	}}

	gid := uuid.New()
	key := r.fullPath(r.path(gid, "hash"))

	bucket, err := blob.OpenBucket(ctx, r.GetConnString())
	require.NoError(t, err)
	t.Cleanup(func() { _ = bucket.Close() })

	require.NoError(t, bucket.WriteAll(ctx, key, []byte("hello"), nil))

	got, err := bucket.ReadAll(ctx, key)
	require.NoError(t, err)
	assert.Equal(t, []byte("hello"), got)

	onDisk, err := os.ReadFile(filepath.Join(dataDir, gid.String(), "documents", "hash"))
	require.NoError(t, err)
	assert.Equal(t, []byte("hello"), onDisk)

	require.NoError(t, bucket.Delete(ctx, key))
}