don't overwrite webmentions if added multiple times

This commit is contained in:
Niko Abeler 2022-08-24 22:11:39 +02:00
parent 1ff5805e18
commit 9d4b96fcb6
2 changed files with 51 additions and 1 deletions

View File

@ -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 {

View File

@ -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)
}
}