all repos — honk @ 6b431fc97646d752ba244f696a12d68c8f2c9726

my fork of honk

fun.go (view raw)

  1//
  2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
  3//
  4// Permission to use, copy, modify, and distribute this software for any
  5// purpose with or without fee is hereby granted, provided that the above
  6// copyright notice and this permission notice appear in all copies.
  7//
  8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 15
 16package main
 17
 18import (
 19	"crypto/rand"
 20	"crypto/rsa"
 21	"fmt"
 22	"html/template"
 23	"log"
 24	"net/http"
 25	"os"
 26	"regexp"
 27	"strings"
 28	"sync"
 29
 30	"golang.org/x/net/html"
 31	"humungus.tedunangst.com/r/webs/htfilter"
 32	"humungus.tedunangst.com/r/webs/httpsig"
 33)
 34
 35var allowedclasses = make(map[string]bool)
 36
 37func init() {
 38	allowedclasses["kw"] = true
 39	allowedclasses["bi"] = true
 40	allowedclasses["st"] = true
 41	allowedclasses["nm"] = true
 42	allowedclasses["tp"] = true
 43	allowedclasses["op"] = true
 44	allowedclasses["cm"] = true
 45	allowedclasses["al"] = true
 46	allowedclasses["dl"] = true
 47}
 48
 49func reverbolate(userid int64, honks []*Honk) {
 50	filt := htfilter.New()
 51	filt.Imager = replaceimg
 52	filt.SpanClasses = allowedclasses
 53	for _, h := range honks {
 54		h.What += "ed"
 55		if h.What == "tonked" {
 56			h.What = "honked back"
 57			h.Style = "subtle"
 58		}
 59		if !h.Public {
 60			h.Style += " limited"
 61		}
 62		translate(h)
 63		if h.Whofore == 2 || h.Whofore == 3 {
 64			h.URL = h.XID
 65			if h.What != "bonked" {
 66				h.Noise = re_memes.ReplaceAllString(h.Noise, "")
 67				h.Noise = mentionize(h.Noise)
 68				h.Noise = ontologize(h.Noise)
 69			}
 70			h.Username, h.Handle = handles(h.Honker)
 71		} else {
 72			_, h.Handle = handles(h.Honker)
 73			h.Username = h.Handle
 74			if len(h.Username) > 20 {
 75				h.Username = h.Username[:20] + ".."
 76			}
 77			if h.URL == "" {
 78				h.URL = h.XID
 79			}
 80		}
 81		if h.Oonker != "" {
 82			_, h.Oondle = handles(h.Oonker)
 83		}
 84		zap := make(map[*Donk]bool)
 85		h.Precis = demoji(h.Precis)
 86		h.Noise = demoji(h.Noise)
 87		h.Open = "open"
 88		if userid == -1 {
 89			if h.Precis != "" {
 90				h.Open = ""
 91			}
 92		} else {
 93			unsee(userid, h)
 94			if h.Open == "open" && h.Precis == "unspecified horror" {
 95				h.Precis = ""
 96			}
 97		}
 98		if len(h.Noise) > 6000 && h.Open == "open" {
 99			if h.Precis == "" {
100				h.Precis = "really freaking long"
101			}
102			h.Open = ""
103		}
104
105		h.HTPrecis, _ = filt.String(h.Precis)
106		h.HTML, _ = filt.String(h.Noise)
107		emuxifier := func(e string) string {
108			for _, d := range h.Donks {
109				if d.Name == e {
110					zap[d] = true
111					if d.Local {
112						return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
113					}
114				}
115			}
116			return e
117		}
118		h.HTPrecis = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTPrecis), emuxifier))
119		h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
120		j := 0
121		for i := 0; i < len(h.Donks); i++ {
122			if !zap[h.Donks[i]] {
123				h.Donks[j] = h.Donks[i]
124				j++
125			}
126		}
127		h.Donks = h.Donks[:j]
128	}
129}
130
131func replaceimg(node *html.Node) string {
132	src := htfilter.GetAttr(node, "src")
133	alt := htfilter.GetAttr(node, "alt")
134	//title := GetAttr(node, "title")
135	if htfilter.HasClass(node, "Emoji") && alt != "" {
136		return alt
137	}
138	alt = html.EscapeString(alt)
139	src = html.EscapeString(src)
140	d := finddonk(src)
141	if d != nil {
142		src = fmt.Sprintf("https://%s/d/%s", serverName, d.XID)
143		return fmt.Sprintf(`<img alt="%s" title="%s" src="%s">`, alt, alt, src)
144	}
145	return fmt.Sprintf(`&lt;img alt="%s" src="<a href="%s">%s<a>"&gt;`, alt, src, src)
146}
147
148func inlineimgs(node *html.Node) string {
149	src := htfilter.GetAttr(node, "src")
150	alt := htfilter.GetAttr(node, "alt")
151	//title := GetAttr(node, "title")
152	if htfilter.HasClass(node, "Emoji") && alt != "" {
153		return alt
154	}
155	alt = html.EscapeString(alt)
156	src = html.EscapeString(src)
157	if !strings.HasPrefix(src, "https://"+serverName+"/") {
158		d := savedonk(src, "image", alt, "image", true)
159		if d != nil {
160			src = fmt.Sprintf("https://%s/d/%s", serverName, d.XID)
161		}
162	}
163	log.Printf("inline img with src: %s", src)
164	return fmt.Sprintf(`<img alt="%s" title="%s" src="%s>`, alt, alt, src)
165}
166
167func translate(honk *Honk) {
168	if honk.Format == "html" {
169		return
170	}
171	noise := honk.Noise
172	if strings.HasPrefix(noise, "DZ:") {
173		idx := strings.Index(noise, "\n")
174		if idx == -1 {
175			honk.Precis = noise
176			noise = ""
177		} else {
178			honk.Precis = noise[:idx]
179			noise = noise[idx+1:]
180		}
181	}
182	honk.Precis = strings.TrimSpace(honk.Precis)
183
184	noise = strings.TrimSpace(noise)
185	noise = quickrename(noise, honk.UserID)
186	noise = markitzero(noise)
187
188	honk.Noise = noise
189	honk.Onts = oneofakind(ontologies(honk.Noise))
190}
191
192func shortxid(xid string) string {
193	idx := strings.LastIndexByte(xid, '/')
194	if idx == -1 {
195		return xid
196	}
197	return xid[idx+1:]
198}
199
200func xfiltrate() string {
201	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
202	var b [18]byte
203	rand.Read(b[:])
204	for i, c := range b {
205		b[i] = letters[c&63]
206	}
207	s := string(b[:])
208	return s
209}
210
211var re_hashes = regexp.MustCompile(`(?:^| )#[[:alnum:]][[:alnum:]_-]*`)
212
213func ontologies(s string) []string {
214	m := re_hashes.FindAllString(s, -1)
215	j := 0
216	for _, h := range m {
217		if h[0] == '&' {
218			continue
219		}
220		if h[0] != '#' {
221			h = h[1:]
222		}
223		m[j] = h
224		j++
225	}
226	return m[:j]
227}
228
229type Mention struct {
230	who   string
231	where string
232}
233
234var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]*[[:alnum:]]`)
235var re_urltions = regexp.MustCompile(`@https://\S+`)
236
237func grapevine(s string) []string {
238	var mentions []string
239	m := re_mentions.FindAllString(s, -1)
240	for i := range m {
241		where := gofish(m[i])
242		if where != "" {
243			mentions = append(mentions, where)
244		}
245	}
246	m = re_urltions.FindAllString(s, -1)
247	for i := range m {
248		mentions = append(mentions, m[i][1:])
249	}
250	return mentions
251}
252
253func bunchofgrapes(s string) []Mention {
254	m := re_mentions.FindAllString(s, -1)
255	var mentions []Mention
256	for i := range m {
257		where := gofish(m[i])
258		if where != "" {
259			mentions = append(mentions, Mention{who: m[i], where: where})
260		}
261	}
262	m = re_urltions.FindAllString(s, -1)
263	for i := range m {
264		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
265	}
266	return mentions
267}
268
269type Emu struct {
270	ID   string
271	Name string
272}
273
274var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
275
276func herdofemus(noise string) []Emu {
277	m := re_emus.FindAllString(noise, -1)
278	m = oneofakind(m)
279	var emus []Emu
280	for _, e := range m {
281		fname := e[1 : len(e)-1]
282		_, err := os.Stat("emus/" + fname + ".png")
283		if err != nil {
284			continue
285		}
286		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
287		emus = append(emus, Emu{ID: url, Name: e})
288	}
289	return emus
290}
291
292var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
293
294func memetize(honk *Honk) {
295	repl := func(x string) string {
296		name := x[5:]
297		if name[0] == ' ' {
298			name = name[1:]
299		}
300		fd, err := os.Open("memes/" + name)
301		if err != nil {
302			log.Printf("no meme for %s", name)
303			return x
304		}
305		var peek [512]byte
306		n, _ := fd.Read(peek[:])
307		ct := http.DetectContentType(peek[:n])
308		fd.Close()
309
310		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
311		fileid, err := savefile("", name, name, url, ct, false, nil)
312		if err != nil {
313			log.Printf("error saving meme: %s", err)
314			return x
315		}
316		var d Donk
317		d.FileID = fileid
318		d.XID = ""
319		d.Name = name
320		d.Media = ct
321		d.URL = url
322		d.Local = false
323		honk.Donks = append(honk.Donks, &d)
324		return ""
325	}
326	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
327}
328
329var re_quickmention = regexp.MustCompile("(^| )@[[:alnum:]]+ ")
330
331func quickrename(s string, userid int64) string {
332	nonstop := true
333	for nonstop {
334		nonstop = false
335		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
336			log.Printf("m: %s", m)
337			prefix := ""
338			if m[0] == ' ' {
339				prefix = " "
340				m = m[1:]
341			}
342			prefix += "@"
343			m = m[1:]
344			m = m[:len(m)-1]
345
346			row := stmtOneHonker.QueryRow(m, userid)
347			var xid string
348			err := row.Scan(&xid)
349			if err == nil {
350				_, name := handles(xid)
351				if name != "" {
352					nonstop = true
353					m = name
354				}
355			}
356			return prefix + m + " "
357		})
358	}
359	return s
360}
361
362func mentionize(s string) string {
363	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
364		where := gofish(m)
365		if where == "" {
366			return m
367		}
368		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
369		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
370			html.EscapeString(where), html.EscapeString(who))
371	})
372	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
373		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
374			html.EscapeString(m[1:]), html.EscapeString(m))
375	})
376	return s
377}
378
379func ontologize(s string) string {
380	s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
381		if o[0] == '&' {
382			return o
383		}
384		p := ""
385		h := o
386		if h[0] != '#' {
387			p = h[:1]
388			h = h[1:]
389		}
390		return fmt.Sprintf(`%s<a class="mention u-url" href="https://%s/o/%s">%s</a>`, p, serverName,
391			strings.ToLower(h[1:]), h)
392	})
393	return s
394}
395
396var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
397var re_urlhost = regexp.MustCompile("https://([^/ ]+)")
398
399func originate(u string) string {
400	m := re_urlhost.FindStringSubmatch(u)
401	if len(m) > 1 {
402		return m[1]
403	}
404	return ""
405}
406
407var allhandles = make(map[string]string)
408var handlelock sync.Mutex
409
410// handle, handle@host
411func handles(xid string) (string, string) {
412	if xid == "" {
413		return "", ""
414	}
415	handlelock.Lock()
416	handle := allhandles[xid]
417	handlelock.Unlock()
418	if handle == "" {
419		handle = findhandle(xid)
420		handlelock.Lock()
421		allhandles[xid] = handle
422		handlelock.Unlock()
423	}
424	if handle == xid {
425		return xid, xid
426	}
427	return handle, handle + "@" + originate(xid)
428}
429
430func findhandle(xid string) string {
431	row := stmtGetXonker.QueryRow(xid, "handle")
432	var handle string
433	err := row.Scan(&handle)
434	if err != nil {
435		p, _ := investigate(xid)
436		if p == nil {
437			m := re_unurl.FindStringSubmatch(xid)
438			if len(m) > 2 {
439				handle = m[2]
440			} else {
441				handle = xid
442			}
443		} else {
444			handle = p.Handle
445		}
446		_, err = stmtSaveXonker.Exec(xid, handle, "handle")
447		if err != nil {
448			log.Printf("error saving handle: %s", err)
449		}
450	}
451	return handle
452}
453
454var handleprelock sync.Mutex
455
456func prehandle(xid string) {
457	handleprelock.Lock()
458	defer handleprelock.Unlock()
459	handles(xid)
460}
461
462func prepend(s string, x []string) []string {
463	return append([]string{s}, x...)
464}
465
466// pleroma leaks followers addressed posts to followers
467func butnottooloud(aud []string) {
468	for i, a := range aud {
469		if strings.HasSuffix(a, "/followers") {
470			aud[i] = ""
471		}
472	}
473}
474
475func keepitquiet(aud []string) bool {
476	for _, a := range aud {
477		if a == thewholeworld {
478			return false
479		}
480	}
481	return true
482}
483
484func firstclass(honk *Honk) bool {
485	return honk.Audience[0] == thewholeworld
486}
487
488func oneofakind(a []string) []string {
489	var x []string
490	for n, s := range a {
491		if s != "" {
492			x = append(x, s)
493			for i := n + 1; i < len(a); i++ {
494				if a[i] == s {
495					a[i] = ""
496				}
497			}
498		}
499	}
500	return x
501}
502
503var ziggies = make(map[string]*rsa.PrivateKey)
504var zaggies = make(map[string]*rsa.PublicKey)
505var ziggylock sync.Mutex
506
507func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
508	ziggylock.Lock()
509	key = ziggies[username]
510	ziggylock.Unlock()
511	if key == nil {
512		db := opendatabase()
513		row := db.QueryRow("select seckey from users where username = ?", username)
514		var data string
515		row.Scan(&data)
516		var err error
517		key, _, err = httpsig.DecodeKey(data)
518		if err != nil {
519			log.Printf("error decoding %s seckey: %s", username, err)
520			return
521		}
522		ziggylock.Lock()
523		ziggies[username] = key
524		ziggylock.Unlock()
525	}
526	keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
527	return
528}
529
530func zaggy(keyname string) (key *rsa.PublicKey) {
531	ziggylock.Lock()
532	key = zaggies[keyname]
533	ziggylock.Unlock()
534	if key != nil {
535		return
536	}
537	row := stmtGetXonker.QueryRow(keyname, "pubkey")
538	var data string
539	err := row.Scan(&data)
540	if err != nil {
541		log.Printf("hitting the webs for missing pubkey: %s", keyname)
542		j, err := GetJunk(keyname)
543		if err != nil {
544			log.Printf("error getting %s pubkey: %s", keyname, err)
545			return
546		}
547		keyobj, ok := j.GetMap("publicKey")
548		if ok {
549			j = keyobj
550		}
551		data, ok = j.GetString("publicKeyPem")
552		if !ok {
553			log.Printf("error finding %s pubkey", keyname)
554			return
555		}
556		_, ok = j.GetString("owner")
557		if !ok {
558			log.Printf("error finding %s pubkey owner", keyname)
559			return
560		}
561		_, key, err = httpsig.DecodeKey(data)
562		if err != nil {
563			log.Printf("error decoding %s pubkey: %s", keyname, err)
564			return
565		}
566		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
567		if err != nil {
568			log.Printf("error saving key: %s", err)
569		}
570	} else {
571		_, key, err = httpsig.DecodeKey(data)
572		if err != nil {
573			log.Printf("error decoding %s pubkey: %s", keyname, err)
574			return
575		}
576	}
577	ziggylock.Lock()
578	zaggies[keyname] = key
579	ziggylock.Unlock()
580	return
581}
582
583func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
584	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
585	if err != nil {
586		log.Printf("error deleting key: %s", err)
587	}
588	ziggylock.Lock()
589	delete(zaggies, keyname)
590	ziggylock.Unlock()
591	return httpsig.VerifyRequest(r, payload, zaggy)
592}
593
594func keymatch(keyname string, actor string) string {
595	hash := strings.IndexByte(keyname, '#')
596	if hash == -1 {
597		hash = len(keyname)
598	}
599	owner := keyname[0:hash]
600	if owner == actor {
601		return originate(actor)
602	}
603	return ""
604}