honk/fun.go

682 lines
15 KiB
Go
Raw Normal View History

2019-04-13 19:58:42 +02:00
//
// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package main
import (
"crypto/rand"
"crypto/sha512"
2019-04-13 19:58:42 +02:00
"fmt"
"html/template"
"io"
"net/http"
2019-11-11 05:49:09 +01:00
"net/url"
2019-05-31 06:24:18 +02:00
"os"
2019-04-13 19:58:42 +02:00
"regexp"
"strings"
"time"
2019-05-18 01:37:43 +02:00
2019-09-19 06:50:26 +02:00
"golang.org/x/net/html"
"humungus.tedunangst.com/r/webs/cache"
2019-05-18 01:37:43 +02:00
"humungus.tedunangst.com/r/webs/htfilter"
"humungus.tedunangst.com/r/webs/httpsig"
2020-07-21 05:00:36 +02:00
"humungus.tedunangst.com/r/webs/mz"
2020-07-21 05:28:42 +02:00
"humungus.tedunangst.com/r/webs/templates"
2019-04-13 19:58:42 +02:00
)
var allowedclasses = make(map[string]bool)
func init() {
allowedclasses["kw"] = true
allowedclasses["bi"] = true
allowedclasses["st"] = true
allowedclasses["nm"] = true
allowedclasses["tp"] = true
allowedclasses["op"] = true
allowedclasses["cm"] = true
allowedclasses["al"] = true
allowedclasses["dl"] = true
}
var relingo = make(map[string]string)
func loadLingo() {
for _, l := range []string{"honked", "bonked", "honked back", "qonked", "evented"} {
v := l
k := "lingo-" + strings.ReplaceAll(l, " ", "")
getconfig(k, &v)
relingo[l] = v
}
}
2019-07-10 20:36:14 +02:00
func reverbolate(userid int64, honks []*Honk) {
2020-08-05 21:33:27 +02:00
var user *WhatAbout
somenumberedusers.Get(userid, &user)
2019-04-13 19:58:42 +02:00
for _, h := range honks {
h.What += "ed"
if h.What == "tonked" {
h.What = "honked back"
2019-10-29 21:00:41 +01:00
h.Style += " subtle"
}
if !h.Public {
2019-07-15 03:55:57 +02:00
h.Style += " limited"
}
2022-05-01 23:33:25 +02:00
if h.Whofore == 1 {
h.Style += " atme"
}
2019-12-04 08:30:07 +01:00
translate(h)
local := false
if h.Whofore == 2 || h.Whofore == 3 {
local = true
}
if local && h.What != "bonked" {
2019-12-01 18:34:08 +01:00
h.Noise = re_memes.ReplaceAllString(h.Noise, "")
}
h.Username, h.Handle = handles(h.Honker)
if !local {
short := shortname(userid, h.Honker)
if short != "" {
h.Username = short
} else {
h.Username = h.Handle
if len(h.Username) > 20 {
h.Username = h.Username[:20] + ".."
}
2019-04-13 19:58:42 +02:00
}
}
if user != nil {
if user.Options.MentionAll {
hset := []string{"@" + h.Handle}
for _, a := range h.Audience {
if a == h.Honker || a == user.URL {
continue
}
_, hand := handles(a)
if hand != "" {
hand = "@" + hand
hset = append(hset, hand)
}
2020-08-05 21:33:27 +02:00
}
h.Handles = strings.Join(hset, " ")
} else if h.Honker != user.URL {
h.Handles = "@" + h.Handle
2020-08-05 21:33:27 +02:00
}
}
2019-12-01 18:34:08 +01:00
if h.URL == "" {
h.URL = h.XID
}
2019-07-05 19:07:59 +02:00
if h.Oonker != "" {
_, h.Oondle = handles(h.Oonker)
2019-07-05 19:07:59 +02:00
}
h.Precis = demoji(h.Precis)
h.Noise = demoji(h.Noise)
2019-07-10 20:36:14 +02:00
h.Open = "open"
zap := make(map[string]bool)
{
2019-10-22 08:02:36 +02:00
var htf htfilter.Filter
htf.Imager = replaceimgsand(zap, false)
htf.SpanClasses = allowedclasses
2019-11-11 05:49:09 +01:00
htf.BaseURL, _ = url.Parse(h.XID)
emuxifier := func(e string) string {
for _, d := range h.Donks {
if d.Name == e {
zap[d.XID] = true
if d.Local {
return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
}
}
}
if local && h.What != "bonked" {
var emu Emu
emucache.Get(e, &emu)
if emu.ID != "" {
return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
}
}
return e
}
htf.FilterText = func(w io.Writer, data string) {
data = htfilter.EscapeText(data)
data = re_emus.ReplaceAllStringFunc(data, emuxifier)
io.WriteString(w, data)
}
2019-10-22 08:02:36 +02:00
p, _ := htf.String(h.Precis)
n, _ := htf.String(h.Noise)
h.Precis = string(p)
h.Noise = string(n)
}
j := 0
for i := 0; i < len(h.Donks); i++ {
if !zap[h.Donks[i].XID] {
h.Donks[j] = h.Donks[i]
j++
2019-10-03 06:22:01 +02:00
}
}
h.Donks = h.Donks[:j]
}
unsee(honks, userid)
2019-10-03 06:22:01 +02:00
for _, h := range honks {
renderflags(h)
h.HTPrecis = template.HTML(h.Precis)
h.HTML = template.HTML(h.Noise)
2022-02-09 23:11:55 +01:00
if h.What == "wonked" {
h.HTML = "? wonk ?"
}
if redo := relingo[h.What]; redo != "" {
h.What = redo
}
2019-04-13 19:58:42 +02:00
}
}
2019-10-22 06:19:31 +02:00
func replaceimgsand(zap map[string]bool, absolute bool) func(node *html.Node) string {
return func(node *html.Node) string {
src := htfilter.GetAttr(node, "src")
alt := htfilter.GetAttr(node, "alt")
//title := GetAttr(node, "title")
if htfilter.HasClass(node, "Emoji") && alt != "" {
return alt
}
d := finddonk(src)
if d != nil {
zap[d.XID] = true
2019-10-22 06:19:31 +02:00
base := ""
if absolute {
base = "https://" + serverName
}
return string(templates.Sprintf(`<img alt="%s" title="%s" src="%s/d/%s">`, alt, alt, base, d.XID))
}
2020-01-26 00:08:13 +01:00
return string(templates.Sprintf(`&lt;img alt="%s" src="<a href="%s">%s</a>"&gt;`, alt, src, src))
}
2019-09-19 06:50:26 +02:00
}
2020-07-27 06:30:01 +02:00
func translatechonk(ch *Chonk) {
2020-05-15 05:06:23 +02:00
noise := ch.Noise
if ch.Format == "markdown" {
noise = markitzero(noise)
}
2020-07-27 06:30:01 +02:00
var htf htfilter.Filter
htf.SpanClasses = allowedclasses
htf.BaseURL, _ = url.Parse(ch.XID)
2020-07-26 22:25:28 +02:00
ch.HTML, _ = htf.String(noise)
2020-07-27 06:30:01 +02:00
}
func filterchonk(ch *Chonk) {
translatechonk(ch)
noise := string(ch.HTML)
local := originate(ch.XID) == serverName
2020-07-26 22:25:28 +02:00
zap := make(map[string]bool)
emuxifier := func(e string) string {
for _, d := range ch.Donks {
if d.Name == e {
zap[d.XID] = true
if d.Local {
return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
}
}
}
if local {
var emu Emu
emucache.Get(e, &emu)
if emu.ID != "" {
return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
}
}
return e
}
noise = re_emus.ReplaceAllStringFunc(noise, emuxifier)
j := 0
for i := 0; i < len(ch.Donks); i++ {
if !zap[ch.Donks[i].XID] {
ch.Donks[j] = ch.Donks[i]
j++
}
}
ch.Donks = ch.Donks[:j]
2020-07-26 22:25:28 +02:00
if strings.HasPrefix(noise, "<p>") {
noise = noise[3:]
2020-05-13 23:15:29 +02:00
}
2020-07-26 22:25:28 +02:00
ch.HTML = template.HTML(noise)
2020-05-13 23:15:29 +02:00
if short := shortname(ch.UserID, ch.Who); short != "" {
ch.Handle = short
} else {
2020-05-14 00:05:38 +02:00
ch.Handle, _ = handles(ch.Who)
2020-05-13 23:15:29 +02:00
}
}
func inlineimgsfor(honk *Honk) func(node *html.Node) string {
return func(node *html.Node) string {
src := htfilter.GetAttr(node, "src")
alt := htfilter.GetAttr(node, "alt")
d := savedonk(src, "image", alt, "image", true)
if d != nil {
honk.Donks = append(honk.Donks, d)
}
2022-02-06 06:42:13 +01:00
dlog.Printf("inline img with src: %s", src)
return ""
}
}
2019-10-22 06:19:31 +02:00
func imaginate(honk *Honk) {
2019-10-22 08:02:36 +02:00
var htf htfilter.Filter
htf.Imager = inlineimgsfor(honk)
2019-11-11 05:49:09 +01:00
htf.BaseURL, _ = url.Parse(honk.XID)
2019-10-22 08:02:36 +02:00
htf.String(honk.Noise)
2019-10-22 06:19:31 +02:00
}
2019-12-04 08:30:07 +01:00
func translate(honk *Honk) {
if honk.Format == "html" {
return
}
noise := honk.Noise
if strings.HasPrefix(noise, "DZ:") {
idx := strings.Index(noise, "\n")
if idx == -1 {
honk.Precis = noise
noise = ""
} else {
honk.Precis = noise[:idx]
noise = noise[idx+1:]
}
}
honk.Precis = markitzero(strings.TrimSpace(honk.Precis))
2020-07-21 05:00:36 +02:00
var marker mz.Marker
marker.HashLinker = ontoreplacer
2020-07-21 05:28:42 +02:00
marker.AtLinker = attoreplacer
noise = strings.TrimSpace(noise)
2020-07-21 05:00:36 +02:00
noise = marker.Mark(noise)
honk.Noise = noise
2020-07-21 05:00:36 +02:00
honk.Onts = oneofakind(marker.HashTags)
2020-07-21 05:28:42 +02:00
honk.Mentions = bunchofgrapes(marker.Mentions)
2019-12-04 08:30:07 +01:00
}
2019-10-22 06:19:31 +02:00
2019-12-04 08:30:07 +01:00
func redoimages(honk *Honk) {
zap := make(map[string]bool)
{
var htf htfilter.Filter
htf.Imager = replaceimgsand(zap, true)
htf.SpanClasses = allowedclasses
p, _ := htf.String(honk.Precis)
n, _ := htf.String(honk.Noise)
honk.Precis = string(p)
honk.Noise = string(n)
}
j := 0
for i := 0; i < len(honk.Donks); i++ {
if !zap[honk.Donks[i].XID] {
honk.Donks[j] = honk.Donks[i]
j++
2019-10-22 06:19:31 +02:00
}
}
2019-12-04 08:30:07 +01:00
honk.Donks = honk.Donks[:j]
honk.Noise = re_memes.ReplaceAllString(honk.Noise, "")
honk.Noise = strings.Replace(honk.Noise, "<a href=", "<a class=\"mention u-url\" href=", -1)
}
func xcelerate(b []byte) string {
letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
for i, c := range b {
b[i] = letters[c&63]
}
s := string(b)
return s
}
func shortxid(xid string) string {
h := sha512.New512_256()
io.WriteString(h, xid)
return xcelerate(h.Sum(nil)[:20])
}
2019-04-13 19:58:42 +02:00
func xfiltrate() string {
2019-06-17 01:18:33 +02:00
var b [18]byte
rand.Read(b[:])
return xcelerate(b[:])
2019-04-13 19:58:42 +02:00
}
func grapevine(mentions []Mention) []string {
var s []string
for _, m := range mentions {
s = append(s, m.Where)
}
return s
}
2020-07-21 05:28:42 +02:00
func bunchofgrapes(m []string) []Mention {
2019-04-13 19:58:42 +02:00
var mentions []Mention
for i := range m {
where := gofish(m[i])
if where != "" {
2019-11-27 20:36:29 +01:00
mentions = append(mentions, Mention{Who: m[i], Where: where})
2019-04-13 19:58:42 +02:00
}
}
return mentions
}
type Emu struct {
ID string
Name string
}
2019-07-10 05:04:19 +02:00
var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
2019-04-13 19:58:42 +02:00
var emucache = cache.New(cache.Options{Filler: func(ename string) (Emu, bool) {
fname := ename[1 : len(ename)-1]
_, err := os.Stat(dataDir + "/emus/" + fname + ".png")
if err != nil {
return Emu{Name: ename, ID: ""}, true
}
url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
return Emu{ID: url, Name: ename}, true
}, Duration: 10 * time.Second})
2019-04-13 19:58:42 +02:00
func herdofemus(noise string) []Emu {
m := re_emus.FindAllString(noise, -1)
m = oneofakind(m)
var emus []Emu
for _, e := range m {
var emu Emu
emucache.Get(e, &emu)
if emu.ID == "" {
2019-07-08 02:07:16 +02:00
continue
}
emus = append(emus, emu)
2019-04-13 19:58:42 +02:00
}
return emus
}
var re_memes = regexp.MustCompile("meme: ?([^\n]+)")
var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
2019-05-31 06:24:18 +02:00
2019-07-01 01:04:37 +02:00
func memetize(honk *Honk) {
repl := func(x string) string {
2019-05-31 06:24:18 +02:00
name := x[5:]
if name[0] == ' ' {
name = name[1:]
}
2021-11-15 05:30:41 +01:00
fd, err := os.Open(dataDir + "/memes/" + name)
2019-05-31 06:24:18 +02:00
if err != nil {
2022-02-06 06:42:13 +01:00
ilog.Printf("no meme for %s", name)
2019-07-01 01:04:37 +02:00
return x
2019-05-31 06:24:18 +02:00
}
var peek [512]byte
n, _ := fd.Read(peek[:])
ct := http.DetectContentType(peek[:n])
fd.Close()
url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
fileid, err := savefile(name, name, url, ct, false, nil)
2019-05-31 06:24:18 +02:00
if err != nil {
2022-02-06 06:42:13 +01:00
elog.Printf("error saving meme: %s", err)
2019-07-01 01:04:37 +02:00
return x
2019-05-31 06:24:18 +02:00
}
2019-10-21 07:29:39 +02:00
d := &Donk{
FileID: fileid,
Name: name,
Media: ct,
URL: url,
Local: false,
}
honk.Donks = append(honk.Donks, d)
2019-07-01 01:04:37 +02:00
return ""
2019-05-31 06:24:18 +02:00
}
2019-07-01 01:04:37 +02:00
honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
2019-05-31 06:24:18 +02:00
}
2019-11-29 20:53:25 +01:00
var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]]+([ \n.]|$)")
2019-09-10 20:30:52 +02:00
func quickrename(s string, userid int64) string {
nonstop := true
for nonstop {
nonstop = false
s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
prefix := ""
if m[0] == ' ' || m[0] == '\n' {
prefix = m[:1]
m = m[1:]
}
prefix += "@"
2019-09-10 20:30:52 +02:00
m = m[1:]
tail := ""
2019-11-29 20:53:25 +01:00
if last := m[len(m)-1]; last == ' ' || last == '\n' || last == '.' {
tail = m[len(m)-1:]
2019-10-11 00:51:09 +02:00
m = m[:len(m)-1]
}
2019-09-10 20:30:52 +02:00
xid := fullname(m, userid)
if xid != "" {
_, name := handles(xid)
if name != "" {
nonstop = true
m = name
}
2019-09-10 20:30:52 +02:00
}
return prefix + m + tail
})
}
return s
2019-09-10 20:30:52 +02:00
}
var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
2019-10-12 16:34:23 +02:00
honkers := gethonkers(userid)
m := make(map[string]string)
for _, h := range honkers {
m[h.XID] = h.Name
}
return m, true
}, Invalidator: &honkerinvalidator})
2019-10-12 16:34:23 +02:00
func shortname(userid int64, xid string) string {
var m map[string]string
ok := shortnames.Get(userid, &m)
if ok {
return m[xid]
}
return ""
}
var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
honkers := gethonkers(userid)
m := make(map[string]string)
for _, h := range honkers {
m[h.Name] = h.XID
}
return m, true
}, Invalidator: &honkerinvalidator})
func fullname(name string, userid int64) string {
var m map[string]string
ok := fullnames.Get(userid, &m)
if ok {
return m[name]
}
return ""
}
2020-07-21 05:28:42 +02:00
func attoreplacer(m string) string {
2020-04-23 00:31:33 +02:00
fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
2020-07-21 05:28:42 +02:00
where := gofish(m)
if where == "" {
return m
}
who := m[0 : 1+strings.IndexByte(m[1:], '@')]
return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
2019-04-13 19:58:42 +02:00
}
2020-07-21 05:00:36 +02:00
func ontoreplacer(h string) string {
return fmt.Sprintf(`<a href="https://%s/o/%s">%s</a>`, serverName,
2020-07-21 05:28:42 +02:00
strings.ToLower(h[1:]), h)
}
2019-04-13 19:58:42 +02:00
var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
2019-04-13 19:58:42 +02:00
func originate(u string) string {
m := re_urlhost.FindStringSubmatch(u)
if len(m) > 1 {
return m[1]
}
return ""
}
var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
2022-02-09 23:11:55 +01:00
handle := getxonker(xid, "handle")
if handle == "" {
2022-02-06 06:42:13 +01:00
dlog.Printf("need to get a handle: %s", xid)
info, err := investigate(xid)
if err != nil {
m := re_unurl.FindStringSubmatch(xid)
if len(m) > 2 {
handle = m[2]
} else {
handle = xid
}
} else {
handle = info.Name
2019-08-16 06:05:22 +02:00
}
2019-04-13 19:58:42 +02:00
}
return handle, true
}})
// handle, handle@host
func handles(xid string) (string, string) {
2020-08-05 21:33:27 +02:00
if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
return "", ""
}
var handle string
allhandles.Get(xid, &handle)
if handle == xid {
return xid, xid
}
return handle, handle + "@" + originate(xid)
}
func butnottooloud(aud []string) {
for i, a := range aud {
if strings.HasSuffix(a, "/followers") {
aud[i] = ""
}
}
}
func loudandproud(aud []string) bool {
for _, a := range aud {
if a == thewholeworld {
return true
}
}
return false
}
2019-08-24 02:35:58 +02:00
func firstclass(honk *Honk) bool {
return honk.Audience[0] == thewholeworld
}
2019-04-13 19:58:42 +02:00
func oneofakind(a []string) []string {
seen := make(map[string]bool)
seen[""] = true
j := 0
for _, s := range a {
if !seen[s] {
seen[s] = true
a[j] = s
j++
2019-04-13 19:58:42 +02:00
}
}
return a[:j]
2019-04-13 19:58:42 +02:00
}
var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
var user *WhatAbout
ok := somenumberedusers.Get(userid, &user)
if !ok {
return nil, false
2019-04-13 19:58:42 +02:00
}
ki := new(KeyInfo)
ki.keyname = user.URL + "#key"
ki.seckey = user.SecKey
return ki, true
}})
func ziggy(userid int64) *KeyInfo {
var ki *KeyInfo
ziggies.Get(userid, &ki)
return ki
2019-04-13 19:58:42 +02:00
}
2020-01-19 09:44:38 +01:00
var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
2022-02-09 23:11:55 +01:00
data := getxonker(keyname, "pubkey")
if data == "" {
var key httpsig.PublicKey
2022-02-06 06:42:13 +01:00
dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
j, err := GetJunk(keyname)
if err != nil {
2022-02-06 06:42:13 +01:00
ilog.Printf("error getting %s pubkey: %s", keyname, err)
when := time.Now().UTC().Format(dbtimeformat)
stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
2020-01-19 09:44:38 +01:00
return key, true
}
allinjest(originate(keyname), j)
2022-02-09 23:11:55 +01:00
data = getxonker(keyname, "pubkey")
if data == "" {
2022-02-06 06:42:13 +01:00
ilog.Printf("key not found after ingesting")
when := time.Now().UTC().Format(dbtimeformat)
stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
2020-01-19 09:44:38 +01:00
return key, true
2019-04-13 19:58:42 +02:00
}
}
2022-02-09 23:11:55 +01:00
_, key, err := httpsig.DecodeKey(data)
if err != nil {
2022-02-06 06:42:13 +01:00
ilog.Printf("error decoding %s pubkey: %s", keyname, err)
2020-01-19 09:44:38 +01:00
return key, true
}
return key, true
}, Limit: 512})
2019-10-30 08:31:16 +01:00
2022-02-27 21:38:19 +01:00
func zaggy(keyname string) (httpsig.PublicKey, error) {
2020-01-19 09:44:38 +01:00
var key httpsig.PublicKey
2019-10-30 08:31:16 +01:00
zaggies.Get(keyname, &key)
2022-02-27 21:38:19 +01:00
return key, nil
}
func savingthrow(keyname string) {
when := time.Now().Add(-30 * time.Minute).UTC().Format(dbtimeformat)
stmtDeleteXonker.Exec(keyname, "pubkey", when)
zaggies.Clear(keyname)
}
func keymatch(keyname string, actor string) string {
hash := strings.IndexByte(keyname, '#')
if hash == -1 {
hash = len(keyname)
}
owner := keyname[0:hash]
if owner == actor {
return originate(actor)
}
return ""
2019-04-13 19:58:42 +02:00
}