From 9d4b96fcb623c6bf9b215fe2ff9680602fafe68e Mon Sep 17 00:00:00 2001 From: Niko Abeler Date: Wed, 24 Aug 2022 22:11:39 +0200 Subject: [PATCH] don't overwrite webmentions if added multiple times --- post.go | 7 ++++++- post_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/post.go b/post.go index cbb8a34..4107741 100644 --- a/post.go +++ b/post.go @@ -151,7 +151,12 @@ func (post *Post) AddWebmention(source string) error { hash := sha256.Sum256([]byte(source)) hashStr := base64.URLEncoding.EncodeToString(hash[:]) data := "source: " + source - return os.WriteFile(path.Join(post.WebmentionDir(), hashStr+".yml"), []byte(data), 0644) + // Check if file already exists + fileName := path.Join(post.WebmentionDir(), hashStr+".yml") + if fileExists(fileName) { + return nil + } + return os.WriteFile(fileName, []byte(data), 0644) } func (post *Post) Webmentions() []string { diff --git a/post_test.go b/post_test.go index 72616b8..bb09bba 100644 --- a/post_test.go +++ b/post_test.go @@ -163,3 +163,48 @@ func TestLoadMeta(t *testing.T) { } } + +func TestAddWebmentionCreatesFile(t *testing.T) { + repo := getTestRepo() + repo.SetAllowRawHtml(true) + user, _ := repo.CreateUser("testuser") + post, _ := user.CreateNewPost("testpost") + + post.AddWebmention("https://example.com") + dir, _ := os.Open(post.WebmentionDir()) + defer dir.Close() + files, _ := dir.Readdirnames(-1) + + if len(files) != 1 { + t.Error("No file created for webmention") + } +} + +func TestAddWebmentionNotOverwritingFile(t *testing.T) { + repo := getTestRepo() + repo.SetAllowRawHtml(true) + user, _ := repo.CreateUser("testuser") + post, _ := user.CreateNewPost("testpost") + + post.AddWebmention("https://example.com") + dir, _ := os.Open(post.WebmentionDir()) + defer dir.Close() + files, _ := dir.Readdirnames(-1) + + if len(files) != 1 { + t.Error("No file created for webmention") + } + + content := "url: https://example.com\n" + content += "verified: true" + os.WriteFile(path.Join(post.WebmentionDir(), files[0]), []byte(content), 0644) + + post.AddWebmention("https://example.com") + + fileContent, _ := os.ReadFile(path.Join(post.WebmentionDir(), files[0])) + if string(fileContent) != content { + t.Error("File content was modified.") + t.Errorf("Got: %v", fileContent) + t.Errorf("Expected: %v", content) + } +}