feta/database/storageconnector.go

75 lines
1.8 KiB
Go
Raw Normal View History

2020-03-28 02:57:58 +00:00
package database
import (
"fmt"
"html"
2020-03-28 02:57:58 +00:00
"strings"
"git.eeqj.de/sneak/feta/toot"
"github.com/google/uuid"
hstg "github.com/grokify/html-strip-tags-go"
_ "github.com/jinzhu/gorm/dialects/postgres"
2020-03-28 02:57:58 +00:00
)
func (m *Manager) TootInsertHashCacheSize() uint {
m.cachelock.Lock()
defer m.cachelock.Unlock()
2020-04-05 01:17:35 +00:00
return uint(m.recentlyInsertedTootHashCache.Len())
}
2020-03-28 02:57:58 +00:00
func (m *Manager) TootExists(t *toot.Toot) bool {
var try StoredToot
2020-04-05 01:17:35 +00:00
// check cache
m.cachelock.Lock()
2020-04-05 01:17:35 +00:00
if _, ok := m.recentlyInsertedTootHashCache.Get(t.GetHash()); ok {
m.cachelock.Unlock()
return true
}
m.cachelock.Unlock()
2020-03-28 02:57:58 +00:00
if m.db.Where("Hash = ?", t.GetHash()).First(&try).RecordNotFound() {
return false
} else {
return true
}
}
func (m *Manager) StoreToot(t *toot.Toot) error {
nt := new(StoredToot)
nt.UUID = uuid.New()
nt.ServerCreated = t.Parsed.CreatedAt
nt.Original = t.Original
// FIXME add better validation to the parsed stuff here
2020-03-28 02:57:58 +00:00
nt.Acct = fmt.Sprintf("%s@%s", t.Parsed.Account.Acct, strings.ToLower(t.FromHost))
nt.URL = t.Parsed.URL
nt.Content = []byte(t.Parsed.Content)
// FIXME replace tags with spaces, don't just strip them, otherwise text
// gets messed up.
nt.TextContent = []byte(html.UnescapeString(hstg.StripTags(t.Parsed.Content)))
2020-03-28 02:57:58 +00:00
nt.Hostname = strings.ToLower(t.FromHost)
nt.Hash = t.GetHash()
//TODO: detect hashtags and insert hashtag records
//TODO: detect URLs and insert URL records
2020-03-28 02:57:58 +00:00
r := m.db.Create(&nt)
// put it in the cache to avoid relying on db for dedupe:
m.cachelock.Lock()
2020-04-05 01:17:35 +00:00
m.recentlyInsertedTootHashCache.Add(nt.Hash, true)
m.cachelock.Unlock()
2020-03-28 02:57:58 +00:00
//panic(fmt.Sprintf("%+v", t))
return r.Error
}
func (m *Manager) StoreToots(tc []*toot.Toot) error {
for _, item := range tc {
err := m.StoreToot(item)
if err != nil {
return err
}
}
return nil
}