all repos — honk @ d6cf87a29b3e57372e06d933d3a6758d2e550898

my fork of honk

activity.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	"bytes"
  20	"context"
  21	"crypto/tls"
  22	"database/sql"
  23	"fmt"
  24	"html"
  25	"io"
  26	notrand "math/rand"
  27	"net/http"
  28	"os"
  29	"regexp"
  30	"strings"
  31	"time"
  32
  33	"humungus.tedunangst.com/r/webs/cache"
  34	"humungus.tedunangst.com/r/webs/gate"
  35	"humungus.tedunangst.com/r/webs/httpsig"
  36	"humungus.tedunangst.com/r/webs/junk"
  37	"humungus.tedunangst.com/r/webs/templates"
  38)
  39
  40var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  41var thefakename = `application/activity+json`
  42var falsenames = []string{
  43	`application/ld+json`,
  44	`application/activity+json`,
  45}
  46var itiswhatitis = "https://www.w3.org/ns/activitystreams"
  47var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
  48
  49var fastTimeout time.Duration = 5
  50var slowTimeout time.Duration = 30
  51
  52func friendorfoe(ct string) bool {
  53	ct = strings.ToLower(ct)
  54	for _, at := range falsenames {
  55		if strings.HasPrefix(ct, at) {
  56			return true
  57		}
  58	}
  59	return false
  60}
  61
  62var develClient = &http.Client{
  63	Transport: &http.Transport{
  64		TLSClientConfig: &tls.Config{
  65			InsecureSkipVerify: true,
  66		},
  67	},
  68}
  69
  70func PostJunk(keyname string, key httpsig.PrivateKey, url string, j junk.Junk) error {
  71	return PostMsg(keyname, key, url, j.ToBytes())
  72}
  73
  74func PostMsg(keyname string, key httpsig.PrivateKey, url string, msg []byte) error {
  75	client := http.DefaultClient
  76	if develMode {
  77		client = develClient
  78	}
  79	req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
  80	if err != nil {
  81		return err
  82	}
  83	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
  84	req.Header.Set("Content-Type", theonetruename)
  85	httpsig.SignRequest(keyname, key, req, msg)
  86	ctx, cancel := context.WithTimeout(context.Background(), 2*slowTimeout*time.Second)
  87	defer cancel()
  88	req = req.WithContext(ctx)
  89	resp, err := client.Do(req)
  90	if err != nil {
  91		return err
  92	}
  93	resp.Body.Close()
  94	switch resp.StatusCode {
  95	case 200:
  96	case 201:
  97	case 202:
  98	default:
  99		return fmt.Errorf("http post status: %d", resp.StatusCode)
 100	}
 101	ilog.Printf("successful post: %s %d", url, resp.StatusCode)
 102	return nil
 103}
 104
 105func GetJunk(userid int64, url string) (junk.Junk, error) {
 106	return GetJunkTimeout(userid, url, slowTimeout*time.Second)
 107}
 108
 109func GetJunkFast(userid int64, url string) (junk.Junk, error) {
 110	return GetJunkTimeout(userid, url, fastTimeout*time.Second)
 111}
 112
 113func GetJunkHardMode(userid int64, url string) (junk.Junk, error) {
 114	j, err := GetJunk(userid, url)
 115	if err != nil {
 116		emsg := err.Error()
 117		if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
 118			ilog.Printf("trying again after error: %s", emsg)
 119			time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
 120			j, err = GetJunk(userid, url)
 121			if err != nil {
 122				ilog.Printf("still couldn't get it")
 123			} else {
 124				ilog.Printf("retry success!")
 125			}
 126		}
 127	}
 128	return j, err
 129}
 130
 131var flightdeck = gate.NewSerializer()
 132
 133var signGets = true
 134
 135func GetJunkTimeout(userid int64, url string, timeout time.Duration) (junk.Junk, error) {
 136	if rejectorigin(userid, url, false) {
 137		return nil, fmt.Errorf("rejected origin: %s", url)
 138	}
 139	client := http.DefaultClient
 140	sign := func(req *http.Request) error {
 141		var ki *KeyInfo
 142		ok := ziggies.Get(userid, &ki)
 143		if ok {
 144			httpsig.SignRequest(ki.keyname, ki.seckey, req, nil)
 145		}
 146		return nil
 147	}
 148	if develMode {
 149		client = develClient
 150		sign = nil
 151	}
 152	fn := func() (interface{}, error) {
 153		at := thefakename
 154		if strings.Contains(url, ".well-known/webfinger?resource") {
 155			at = "application/jrd+json"
 156		}
 157		j, err := junk.Get(url, junk.GetArgs{
 158			Accept:  at,
 159			Agent:   "honksnonk/5.0; " + serverName,
 160			Timeout: timeout,
 161			Client:  client,
 162			Fixup:   sign,
 163		})
 164		return j, err
 165	}
 166
 167	ji, err := flightdeck.Call(url, fn)
 168	if err != nil {
 169		return nil, err
 170	}
 171	j := ji.(junk.Junk)
 172	return j, nil
 173}
 174
 175func fetchsome(url string) ([]byte, error) {
 176	client := http.DefaultClient
 177	if develMode {
 178		client = develClient
 179	}
 180	req, err := http.NewRequest("GET", url, nil)
 181	if err != nil {
 182		ilog.Printf("error fetching %s: %s", url, err)
 183		return nil, err
 184	}
 185	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
 186	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
 187	defer cancel()
 188	req = req.WithContext(ctx)
 189	resp, err := client.Do(req)
 190	if err != nil {
 191		ilog.Printf("error fetching %s: %s", url, err)
 192		return nil, err
 193	}
 194	defer resp.Body.Close()
 195	switch resp.StatusCode {
 196	case 200:
 197	case 201:
 198	case 202:
 199	default:
 200		return nil, fmt.Errorf("http get not 200: %d %s", resp.StatusCode, url)
 201	}
 202	var buf bytes.Buffer
 203	limiter := io.LimitReader(resp.Body, 10*1024*1024)
 204	io.Copy(&buf, limiter)
 205	return buf.Bytes(), nil
 206}
 207
 208func savedonk(url string, name, desc, media string, localize bool) *Donk {
 209	if url == "" {
 210		return nil
 211	}
 212	if donk := finddonk(url); donk != nil {
 213		return donk
 214	}
 215	ilog.Printf("saving donk: %s", url)
 216	data := []byte{}
 217	if localize {
 218		fn := func() (interface{}, error) {
 219			return fetchsome(url)
 220		}
 221		ii, err := flightdeck.Call(url, fn)
 222		if err != nil {
 223			ilog.Printf("error fetching donk: %s", err)
 224			localize = false
 225			goto saveit
 226		}
 227		data = ii.([]byte)
 228
 229		if len(data) == 10*1024*1024 {
 230			ilog.Printf("truncation likely")
 231		}
 232		if strings.HasPrefix(media, "image") {
 233			img, err := shrinkit(data)
 234			if err != nil {
 235				ilog.Printf("unable to decode image: %s", err)
 236				localize = false
 237				data = []byte{}
 238				goto saveit
 239			}
 240			data = img.Data
 241			media = "image/" + img.Format
 242		} else if media == "application/pdf" {
 243			if len(data) > 1000000 {
 244				ilog.Printf("not saving large pdf")
 245				localize = false
 246				data = []byte{}
 247			}
 248		} else if len(data) > 100000 {
 249			ilog.Printf("not saving large attachment")
 250			localize = false
 251			data = []byte{}
 252		}
 253	}
 254saveit:
 255	fileid, err := savefile(name, desc, url, media, localize, data)
 256	if err != nil {
 257		elog.Printf("error saving file %s: %s", url, err)
 258		return nil
 259	}
 260	donk := new(Donk)
 261	donk.FileID = fileid
 262	return donk
 263}
 264
 265func iszonked(userid int64, xid string) bool {
 266	var id int64
 267	row := stmtFindZonk.QueryRow(userid, xid)
 268	err := row.Scan(&id)
 269	if err == nil {
 270		return true
 271	}
 272	if err != sql.ErrNoRows {
 273		ilog.Printf("error querying zonk: %s", err)
 274	}
 275	return false
 276}
 277
 278func needxonk(user *WhatAbout, x *Honk) bool {
 279	if rejectxonk(x) {
 280		return false
 281	}
 282	return needxonkid(user, x.XID)
 283}
 284func needbonkid(user *WhatAbout, xid string) bool {
 285	return needxonkidX(user, xid, true)
 286}
 287func needxonkid(user *WhatAbout, xid string) bool {
 288	return needxonkidX(user, xid, false)
 289}
 290func needxonkidX(user *WhatAbout, xid string, isannounce bool) bool {
 291	if !strings.HasPrefix(xid, "https://") {
 292		return false
 293	}
 294	if strings.HasPrefix(xid, user.URL+"/") {
 295		return false
 296	}
 297	if rejectorigin(user.ID, xid, isannounce) {
 298		ilog.Printf("rejecting origin: %s", xid)
 299		return false
 300	}
 301	if iszonked(user.ID, xid) {
 302		ilog.Printf("already zonked: %s", xid)
 303		return false
 304	}
 305	var id int64
 306	row := stmtFindXonk.QueryRow(user.ID, xid)
 307	err := row.Scan(&id)
 308	if err == nil {
 309		return false
 310	}
 311	if err != sql.ErrNoRows {
 312		ilog.Printf("error querying xonk: %s", err)
 313	}
 314	return true
 315}
 316
 317func eradicatexonk(userid int64, xid string) {
 318	xonk := getxonk(userid, xid)
 319	if xonk != nil {
 320		deletehonk(xonk.ID)
 321		_, err := stmtSaveZonker.Exec(userid, xid, "zonk")
 322		if err != nil {
 323			elog.Printf("error eradicating: %s", err)
 324		}
 325	}
 326}
 327
 328func savexonk(x *Honk) {
 329	ilog.Printf("saving xonk: %s", x.XID)
 330	go handles(x.Honker)
 331	go handles(x.Oonker)
 332	savehonk(x)
 333}
 334
 335type Box struct {
 336	In     string
 337	Out    string
 338	Shared string
 339}
 340
 341var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
 342	var info string
 343	row := stmtGetXonker.QueryRow(ident, "boxes")
 344	err := row.Scan(&info)
 345	if err != nil {
 346		dlog.Printf("need to get boxes for %s", ident)
 347		var j junk.Junk
 348		j, err = GetJunk(readyLuserOne, ident)
 349		if err != nil {
 350			dlog.Printf("error getting boxes: %s", err)
 351			return nil, false
 352		}
 353		allinjest(originate(ident), j)
 354		row = stmtGetXonker.QueryRow(ident, "boxes")
 355		err = row.Scan(&info)
 356	}
 357	if err == nil {
 358		m := strings.Split(info, " ")
 359		b := &Box{In: m[0], Out: m[1], Shared: m[2]}
 360		return b, true
 361	}
 362	return nil, false
 363}})
 364
 365func gimmexonks(user *WhatAbout, outbox string) {
 366	dlog.Printf("getting outbox: %s", outbox)
 367	j, err := GetJunk(user.ID, outbox)
 368	if err != nil {
 369		ilog.Printf("error getting outbox: %s", err)
 370		return
 371	}
 372	t, _ := j.GetString("type")
 373	origin := originate(outbox)
 374	if t == "OrderedCollection" {
 375		items, _ := j.GetArray("orderedItems")
 376		if items == nil {
 377			items, _ = j.GetArray("items")
 378		}
 379		if items == nil {
 380			obj, ok := j.GetMap("first")
 381			if ok {
 382				items, _ = obj.GetArray("orderedItems")
 383			} else {
 384				page1, ok := j.GetString("first")
 385				if ok {
 386					j, err = GetJunk(user.ID, page1)
 387					if err != nil {
 388						ilog.Printf("error getting page1: %s", err)
 389						return
 390					}
 391					items, _ = j.GetArray("orderedItems")
 392				}
 393			}
 394		}
 395		if len(items) > 20 {
 396			items = items[0:20]
 397		}
 398		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 399			items[i], items[j] = items[j], items[i]
 400		}
 401		for _, item := range items {
 402			obj, ok := item.(junk.Junk)
 403			if ok {
 404				xonksaver(user, obj, origin)
 405				continue
 406			}
 407			xid, ok := item.(string)
 408			if ok {
 409				if !needxonkid(user, xid) {
 410					continue
 411				}
 412				obj, err = GetJunk(user.ID, xid)
 413				if err != nil {
 414					ilog.Printf("error getting item: %s", err)
 415					continue
 416				}
 417				xonksaver(user, obj, originate(xid))
 418			}
 419		}
 420	}
 421}
 422
 423func newphone(a []string, obj junk.Junk) []string {
 424	for _, addr := range []string{"to", "cc", "attributedTo"} {
 425		who, _ := obj.GetString(addr)
 426		if who != "" {
 427			a = append(a, who)
 428		}
 429		whos, _ := obj.GetArray(addr)
 430		for _, w := range whos {
 431			who, _ := w.(string)
 432			if who != "" {
 433				a = append(a, who)
 434			}
 435		}
 436	}
 437	return a
 438}
 439
 440func extractattrto(obj junk.Junk) string {
 441	arr := oneforall(obj, "attributedTo")
 442	for _, a := range arr {
 443		s, ok := a.(string)
 444		if ok {
 445			return s
 446		}
 447		o, ok := a.(junk.Junk)
 448		if ok {
 449			t, _ := o.GetString("type")
 450			id, _ := o.GetString("id")
 451			if t == "Person" || t == "" {
 452				return id
 453			}
 454		}
 455	}
 456	return ""
 457}
 458
 459func oneforall(obj junk.Junk, key string) []interface{} {
 460	if val, ok := obj.GetMap(key); ok {
 461		return []interface{}{val}
 462	}
 463	if str, ok := obj.GetString(key); ok {
 464		return []interface{}{str}
 465	}
 466	arr, _ := obj.GetArray(key)
 467	return arr
 468}
 469
 470func firstofmany(obj junk.Junk, key string) string {
 471	if val, _ := obj.GetString(key); val != "" {
 472		return val
 473	}
 474	if arr, _ := obj.GetArray(key); len(arr) > 0 {
 475		val, ok := arr[0].(string)
 476		if ok {
 477			return val
 478		}
 479	}
 480	return ""
 481}
 482
 483var re_mast0link = regexp.MustCompile(`https://[[:alnum:].]+/users/[[:alnum:]]+/statuses/[[:digit:]]+`)
 484var re_masto1ink = regexp.MustCompile(`https://([[:alnum:].]+)/@([[:alnum:]]+)/([[:digit:]]+)`)
 485var re_misslink = regexp.MustCompile(`https://[[:alnum:].]+/notes/[[:alnum:]]+`)
 486var re_honklink = regexp.MustCompile(`https://[[:alnum:].]+/u/[[:alnum:]]+/h/[[:alnum:]]+`)
 487var re_r0malink = regexp.MustCompile(`https://[[:alnum:].]+/objects/[[:alnum:]-]+`)
 488var re_roma1ink = regexp.MustCompile(`https://[[:alnum:].]+/notice/[[:alnum:]]+`)
 489var re_qtlinks = regexp.MustCompile(`>https://[^\s<]+<`)
 490
 491func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 492	depth := 0
 493	maxdepth := 10
 494	currenttid := ""
 495	goingup := 0
 496	var xonkxonkfn func(junk.Junk, string, bool, string) *Honk
 497
 498	qutify := func(user *WhatAbout, content string) string {
 499		if depth >= maxdepth {
 500			ilog.Printf("in too deep")
 501			return content
 502		}
 503		// well this is gross
 504		malcontent := strings.ReplaceAll(content, `</span><span class="ellipsis">`, "")
 505		malcontent = strings.ReplaceAll(malcontent, `</span><span class="invisible">`, "")
 506		mlinks := re_qtlinks.FindAllString(malcontent, -1)
 507		for _, m := range mlinks {
 508			tryit := false
 509			m = m[1 : len(m)-1]
 510			if re_mast0link.MatchString(m) || re_misslink.MatchString(m) ||
 511				re_honklink.MatchString(m) || re_r0malink.MatchString(m) ||
 512				re_roma1ink.MatchString(m) {
 513				tryit = true
 514			} else if re_masto1ink.MatchString(m) {
 515				m = re_masto1ink.ReplaceAllString(m, "https://$1/users/$2/statuses/$3")
 516				tryit = true
 517			}
 518			if tryit {
 519				if x := getxonk(user.ID, m); x != nil {
 520					content = fmt.Sprintf("%s<blockquote>%s</blockquote>", content, x.Noise)
 521				} else if j, err := GetJunk(user.ID, m); err == nil {
 522					q, ok := j.GetString("content")
 523					if ok {
 524						content = fmt.Sprintf("%s<blockquote>%s</blockquote>", content, q)
 525					}
 526					prevdepth := depth
 527					depth = maxdepth
 528					xonkxonkfn(j, originate(m), false, "")
 529					depth = prevdepth
 530				}
 531			}
 532		}
 533		return content
 534	}
 535
 536	saveonemore := func(xid string) {
 537		dlog.Printf("getting onemore: %s", xid)
 538		if depth >= maxdepth {
 539			ilog.Printf("in too deep")
 540			return
 541		}
 542		obj, err := GetJunkHardMode(user.ID, xid)
 543		if err != nil {
 544			ilog.Printf("error getting onemore: %s: %s", xid, err)
 545			return
 546		}
 547		xonkxonkfn(obj, originate(xid), false, "")
 548	}
 549
 550	xonkxonkfn = func(item junk.Junk, origin string, isUpdate bool, bonker string) *Honk {
 551		id, _ := item.GetString("id")
 552		what := firstofmany(item, "type")
 553		dt, ok := item.GetString("published")
 554		if !ok {
 555			dt = time.Now().Format(time.RFC3339)
 556		}
 557		if depth >= maxdepth+5 {
 558			ilog.Printf("went too deep in xonkxonk")
 559			return nil
 560		}
 561		depth++
 562		defer func() { depth-- }()
 563
 564		var err error
 565		var xid, rid, url, convoy string
 566		var replies []string
 567		var obj junk.Junk
 568		waspage := false
 569		preferorig := false
 570		switch what {
 571		case "Delete":
 572			obj, ok = item.GetMap("object")
 573			if ok {
 574				xid, _ = obj.GetString("id")
 575			} else {
 576				xid, _ = item.GetString("object")
 577			}
 578			if xid == "" {
 579				return nil
 580			}
 581			if originate(xid) != origin {
 582				ilog.Printf("forged delete: %s", xid)
 583				return nil
 584			}
 585			ilog.Printf("eradicating %s", xid)
 586			eradicatexonk(user.ID, xid)
 587			return nil
 588		case "Remove":
 589			xid, _ = item.GetString("object")
 590			targ, _ := obj.GetString("target")
 591			ilog.Printf("remove %s from %s", obj, targ)
 592			return nil
 593		case "Tombstone":
 594			xid, _ = item.GetString("id")
 595			if xid == "" {
 596				return nil
 597			}
 598			if originate(xid) != origin {
 599				ilog.Printf("forged delete: %s", xid)
 600				return nil
 601			}
 602			ilog.Printf("eradicating %s", xid)
 603			eradicatexonk(user.ID, xid)
 604			return nil
 605		case "Announce":
 606			obj, ok = item.GetMap("object")
 607			if ok {
 608				// peek ahead some
 609				what, ok := obj.GetString("type")
 610				if ok && (what == "Create" || what == "Update") {
 611					if what == "Update" {
 612						isUpdate = true
 613					}
 614					inner, ok := obj.GetMap("object")
 615					if ok {
 616						obj = inner
 617					} else {
 618						xid, _ = obj.GetString("object")
 619					}
 620				}
 621				if xid == "" {
 622					xid, _ = obj.GetString("id")
 623				}
 624			} else {
 625				xid, _ = item.GetString("object")
 626			}
 627			if !isUpdate && !needbonkid(user, xid) {
 628				return nil
 629			}
 630			bonker, _ = item.GetString("actor")
 631			origin = originate(xid)
 632			if ok && originate(id) == origin {
 633				dlog.Printf("using object in announce for %s", xid)
 634			} else {
 635				dlog.Printf("getting bonk: %s", xid)
 636				obj, err = GetJunkHardMode(user.ID, xid)
 637				if err != nil {
 638					ilog.Printf("error getting bonk: %s: %s", xid, err)
 639					return nil
 640				}
 641			}
 642			return xonkxonkfn(obj, origin, isUpdate, bonker)
 643		case "Update":
 644			isUpdate = true
 645			fallthrough
 646		case "Create":
 647			obj, ok = item.GetMap("object")
 648			if !ok {
 649				xid, _ = item.GetString("object")
 650				dlog.Printf("getting created honk: %s", xid)
 651				if originate(xid) != origin {
 652					ilog.Printf("out of bounds %s not from %s", xid, origin)
 653					return nil
 654				}
 655				obj, err = GetJunkHardMode(user.ID, xid)
 656				if err != nil {
 657					ilog.Printf("error getting creation: %s", err)
 658				}
 659			}
 660			if obj == nil {
 661				ilog.Printf("no object for creation %s", id)
 662				return nil
 663			}
 664			return xonkxonkfn(obj, origin, isUpdate, bonker)
 665		case "Read":
 666			xid, ok = item.GetString("object")
 667			if ok {
 668				if !needxonkid(user, xid) {
 669					dlog.Printf("don't need read obj: %s", xid)
 670					return nil
 671				}
 672				obj, err = GetJunkHardMode(user.ID, xid)
 673				if err != nil {
 674					ilog.Printf("error getting read: %s", err)
 675					return nil
 676				}
 677				return xonkxonkfn(obj, originate(xid), false, "")
 678			}
 679			return nil
 680		case "Add":
 681			xid, ok = item.GetString("object")
 682			if ok {
 683				// check target...
 684				if !needxonkid(user, xid) {
 685					dlog.Printf("don't need added obj: %s", xid)
 686					return nil
 687				}
 688				obj, err = GetJunkHardMode(user.ID, xid)
 689				if err != nil {
 690					ilog.Printf("error getting add: %s", err)
 691					return nil
 692				}
 693				return xonkxonkfn(obj, originate(xid), false, "")
 694			}
 695			return nil
 696		case "Move":
 697			obj = item
 698			what = "move"
 699		case "Page":
 700			waspage = true
 701			fallthrough
 702		case "Audio":
 703			fallthrough
 704		case "Image":
 705			if what == "Image" {
 706				preferorig = true
 707			}
 708			fallthrough
 709		case "Video":
 710			fallthrough
 711		case "Question":
 712			fallthrough
 713		case "Note":
 714			fallthrough
 715		case "Article":
 716			obj = item
 717			what = "honk"
 718		case "Event":
 719			obj = item
 720			what = "event"
 721		case "ChatMessage":
 722			bonker = ""
 723			obj = item
 724			what = "chonk"
 725		default:
 726			ilog.Printf("unknown activity: %s", what)
 727			dumpactivity(item)
 728			return nil
 729		}
 730		if bonker != "" {
 731			what = "bonk"
 732		}
 733
 734		if obj != nil {
 735			xid, _ = obj.GetString("id")
 736		}
 737
 738		if xid == "" {
 739			ilog.Printf("don't know what xid is")
 740			item.Write(ilog.Writer())
 741			return nil
 742		}
 743		if originate(xid) != origin {
 744			if !develMode && origin != "" {
 745				ilog.Printf("original sin: %s not from %s", xid, origin)
 746				item.Write(ilog.Writer())
 747				return nil
 748			}
 749		}
 750
 751		var xonk Honk
 752		// early init
 753		xonk.XID = xid
 754		xonk.UserID = user.ID
 755		xonk.Honker, _ = item.GetString("actor")
 756		if xonk.Honker == "" {
 757			xonk.Honker, _ = item.GetString("attributedTo")
 758		}
 759		if obj != nil {
 760			if xonk.Honker == "" {
 761				xonk.Honker = extractattrto(obj)
 762			}
 763			if bonker != "" {
 764				xonk.Honker, xonk.Oonker = bonker, xonk.Honker
 765			}
 766			if xonk.Oonker == xonk.Honker {
 767				xonk.Oonker = ""
 768			}
 769			xonk.Audience = newphone(nil, obj)
 770		}
 771		xonk.Audience = append(xonk.Audience, xonk.Honker)
 772		xonk.Audience = oneofakind(xonk.Audience)
 773		xonk.Public = loudandproud(xonk.Audience)
 774
 775		var mentions []Mention
 776		if obj != nil {
 777			ot, _ := obj.GetString("type")
 778			url, _ = obj.GetString("url")
 779			if dt2, ok := obj.GetString("published"); ok {
 780				dt = dt2
 781			}
 782			content, _ := obj.GetString("content")
 783			if !strings.HasPrefix(content, "<p>") {
 784				content = "<p>" + content
 785			}
 786			precis, _ := obj.GetString("summary")
 787			if name, ok := obj.GetString("name"); ok {
 788				if precis != "" {
 789					content = precis + "<p>" + content
 790				}
 791				precis = html.EscapeString(name)
 792			}
 793			if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
 794				precis = "unspecified horror"
 795			}
 796			if waspage {
 797				content += fmt.Sprintf(`<p><a href="%s">%s</a>`, url, url)
 798				url = xid
 799			}
 800			if user.Options.InlineQuotes {
 801				content = qutify(user, content)
 802			}
 803			rid, ok = obj.GetString("inReplyTo")
 804			if !ok {
 805				if robj, ok := obj.GetMap("inReplyTo"); ok {
 806					rid, _ = robj.GetString("id")
 807				}
 808			}
 809			convoy, _ = obj.GetString("context")
 810			if convoy == "" {
 811				convoy, _ = obj.GetString("conversation")
 812			}
 813			if ot == "Question" {
 814				if what == "honk" {
 815					what = "qonk"
 816				}
 817				content += "<ul>"
 818				ans, _ := obj.GetArray("oneOf")
 819				for _, ai := range ans {
 820					a, ok := ai.(junk.Junk)
 821					if !ok {
 822						continue
 823					}
 824					as, _ := a.GetString("name")
 825					content += "<li>" + as
 826				}
 827				ans, _ = obj.GetArray("anyOf")
 828				for _, ai := range ans {
 829					a, ok := ai.(junk.Junk)
 830					if !ok {
 831						continue
 832					}
 833					as, _ := a.GetString("name")
 834					content += "<li>" + as
 835				}
 836				content += "</ul>"
 837			}
 838			if ot == "Move" {
 839				targ, _ := obj.GetString("target")
 840				content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
 841			}
 842			if len(content) > 90001 {
 843				ilog.Printf("content too long. truncating")
 844				content = content[:90001]
 845			}
 846
 847			xonk.Noise = content
 848			xonk.Precis = precis
 849			if rejectxonk(&xonk) {
 850				dlog.Printf("fast reject: %s", xid)
 851				return nil
 852			}
 853
 854			numatts := 0
 855			procatt := func(att junk.Junk) {
 856				at, _ := att.GetString("type")
 857				mt, _ := att.GetString("mediaType")
 858				if mt == "" {
 859					mt = "image"
 860				}
 861				u, ok := att.GetString("url")
 862				if !ok {
 863					u, ok = att.GetString("href")
 864				}
 865				if !ok {
 866					if ua, ok := att.GetArray("url"); ok && len(ua) > 0 {
 867						u, ok = ua[0].(string)
 868						if !ok {
 869							if uu, ok := ua[0].(junk.Junk); ok {
 870								u, _ = uu.GetString("href")
 871								if mt == "" {
 872									mt, _ = uu.GetString("mediaType")
 873								}
 874							}
 875						}
 876					} else if uu, ok := att.GetMap("url"); ok {
 877						u, _ = uu.GetString("href")
 878						if mt == "" {
 879							mt, _ = uu.GetString("mediaType")
 880						}
 881					}
 882				}
 883				name, _ := att.GetString("name")
 884				desc, _ := att.GetString("summary")
 885				desc = html.UnescapeString(desc)
 886				if desc == "" {
 887					desc = name
 888				}
 889				localize := false
 890				if at == "Document" || at == "Image" {
 891					mt = strings.ToLower(mt)
 892					dlog.Printf("attachment: %s %s", mt, u)
 893					if mt == "text/plain" || mt == "application/pdf" ||
 894						strings.HasPrefix(mt, "image") {
 895						if numatts > 4 {
 896							ilog.Printf("excessive attachment: %s", at)
 897						} else {
 898							localize = true
 899						}
 900					}
 901				} else if at == "Link" {
 902					if waspage {
 903						xonk.Noise += fmt.Sprintf(`<p><a href="%s">%s</a>`, u, u)
 904						return
 905					}
 906					if name == "" {
 907						name = u
 908					}
 909				} else {
 910					ilog.Printf("unknown attachment: %s", at)
 911				}
 912				if skipMedia(&xonk) {
 913					localize = false
 914				}
 915				if preferorig && !localize {
 916					return
 917				}
 918				donk := savedonk(u, name, desc, mt, localize)
 919				if donk != nil {
 920					xonk.Donks = append(xonk.Donks, donk)
 921				}
 922				numatts++
 923			}
 924			if img, ok := obj.GetMap("image"); ok {
 925				procatt(img)
 926			}
 927			if preferorig {
 928				atts, _ := obj.GetArray("url")
 929				for _, atti := range atts {
 930					att, ok := atti.(junk.Junk)
 931					if !ok {
 932						ilog.Printf("attachment that wasn't map?")
 933						continue
 934					}
 935					procatt(att)
 936				}
 937				if numatts == 0 {
 938					preferorig = false
 939				}
 940			}
 941			if !preferorig {
 942				atts := oneforall(obj, "attachment")
 943				for _, atti := range atts {
 944					att, ok := atti.(junk.Junk)
 945					if !ok {
 946						ilog.Printf("attachment that wasn't map?")
 947						continue
 948					}
 949					procatt(att)
 950				}
 951			}
 952			proctag := func(tag junk.Junk) {
 953				tt, _ := tag.GetString("type")
 954				name, _ := tag.GetString("name")
 955				desc, _ := tag.GetString("summary")
 956				desc = html.UnescapeString(desc)
 957				if desc == "" {
 958					desc = name
 959				}
 960				if tt == "Emoji" {
 961					icon, _ := tag.GetMap("icon")
 962					mt, _ := icon.GetString("mediaType")
 963					if mt == "" {
 964						mt = "image/png"
 965					}
 966					u, _ := icon.GetString("url")
 967					donk := savedonk(u, name, desc, mt, true)
 968					if donk != nil {
 969						xonk.Donks = append(xonk.Donks, donk)
 970					}
 971				}
 972				if tt == "Hashtag" {
 973					if name == "" || name == "#" {
 974						// skip it
 975					} else {
 976						if name[0] != '#' {
 977							name = "#" + name
 978						}
 979						xonk.Onts = append(xonk.Onts, name)
 980					}
 981				}
 982				if tt == "Place" {
 983					p := new(Place)
 984					p.Name = name
 985					p.Latitude, _ = tag.GetNumber("latitude")
 986					p.Longitude, _ = tag.GetNumber("longitude")
 987					p.Url, _ = tag.GetString("url")
 988					xonk.Place = p
 989				}
 990				if tt == "Mention" {
 991					var m Mention
 992					m.Who, _ = tag.GetString("name")
 993					m.Where, _ = tag.GetString("href")
 994					mentions = append(mentions, m)
 995				}
 996			}
 997			tags := oneforall(obj, "tag")
 998			for _, tagi := range tags {
 999				tag, ok := tagi.(junk.Junk)
1000				if !ok {
1001					continue
1002				}
1003				proctag(tag)
1004			}
1005			if starttime, ok := obj.GetString("startTime"); ok {
1006				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
1007					t := new(Time)
1008					t.StartTime = start
1009					endtime, _ := obj.GetString("endTime")
1010					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
1011					dura, _ := obj.GetString("duration")
1012					if strings.HasPrefix(dura, "PT") {
1013						dura = strings.ToLower(dura[2:])
1014						d, _ := time.ParseDuration(dura)
1015						t.Duration = Duration(d)
1016					}
1017					xonk.Time = t
1018				}
1019			}
1020			if loca, ok := obj.GetMap("location"); ok {
1021				if tt, _ := loca.GetString("type"); tt == "Place" {
1022					p := new(Place)
1023					p.Name, _ = loca.GetString("name")
1024					p.Latitude, _ = loca.GetNumber("latitude")
1025					p.Longitude, _ = loca.GetNumber("longitude")
1026					p.Url, _ = loca.GetString("url")
1027					xonk.Place = p
1028				}
1029			}
1030
1031			xonk.Onts = oneofakind(xonk.Onts)
1032			replyobj, ok := obj.GetMap("replies")
1033			if ok {
1034				items, ok := replyobj.GetArray("items")
1035				if !ok {
1036					first, ok := replyobj.GetMap("first")
1037					if ok {
1038						items, _ = first.GetArray("items")
1039					}
1040				}
1041				for _, repl := range items {
1042					s, ok := repl.(string)
1043					if ok {
1044						replies = append(replies, s)
1045					}
1046				}
1047			}
1048
1049		}
1050
1051		if currenttid == "" {
1052			currenttid = convoy
1053		}
1054
1055		// init xonk
1056		xonk.What = what
1057		xonk.RID = rid
1058		xonk.Date, _ = time.Parse(time.RFC3339, dt)
1059		xonk.URL = url
1060		xonk.Format = "html"
1061		xonk.Convoy = convoy
1062		xonk.Mentions = mentions
1063		for _, m := range mentions {
1064			if m.Where == user.URL {
1065				xonk.Whofore = 1
1066			}
1067		}
1068		imaginate(&xonk)
1069
1070		if what == "chonk" {
1071			target, _ := obj.GetString("to")
1072			if target == user.URL {
1073				target = xonk.Honker
1074			}
1075			ch := Chonk{
1076				UserID: xonk.UserID,
1077				XID:    xid,
1078				Who:    xonk.Honker,
1079				Target: target,
1080				Date:   xonk.Date,
1081				Noise:  xonk.Noise,
1082				Format: xonk.Format,
1083				Donks:  xonk.Donks,
1084			}
1085			savechonk(&ch)
1086			return nil
1087		}
1088
1089		if isUpdate {
1090			dlog.Printf("something has changed! %s", xonk.XID)
1091			prev := getxonk(user.ID, xonk.XID)
1092			if prev == nil {
1093				ilog.Printf("didn't find old version for update: %s", xonk.XID)
1094				isUpdate = false
1095			} else {
1096				xonk.ID = prev.ID
1097				updatehonk(&xonk)
1098			}
1099		}
1100		if !isUpdate && needxonk(user, &xonk) {
1101			if rid != "" && xonk.Public {
1102				if needxonkid(user, rid) {
1103					goingup++
1104					saveonemore(rid)
1105					goingup--
1106				}
1107				if convoy == "" {
1108					xx := getxonk(user.ID, rid)
1109					if xx != nil {
1110						convoy = xx.Convoy
1111					}
1112				}
1113			}
1114			if convoy == "" {
1115				convoy = currenttid
1116			}
1117			if convoy == "" {
1118				convoy = "data:,missing-" + xfiltrate()
1119				currenttid = convoy
1120			}
1121			xonk.Convoy = convoy
1122			savexonk(&xonk)
1123		}
1124		if goingup == 0 {
1125			for _, replid := range replies {
1126				if needxonkid(user, replid) {
1127					dlog.Printf("missing a reply: %s", replid)
1128					saveonemore(replid)
1129				}
1130			}
1131		}
1132		return &xonk
1133	}
1134
1135	return xonkxonkfn(item, origin, false, "")
1136}
1137
1138func dumpactivity(item junk.Junk) {
1139	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
1140	if err != nil {
1141		elog.Printf("error opening inbox! %s", err)
1142		return
1143	}
1144	defer fd.Close()
1145	item.Write(fd)
1146	io.WriteString(fd, "\n")
1147}
1148
1149func rubadubdub(user *WhatAbout, req junk.Junk) {
1150	actor, _ := req.GetString("actor")
1151	j := junk.New()
1152	j["@context"] = itiswhatitis
1153	j["id"] = user.URL + "/dub/" + xfiltrate()
1154	j["type"] = "Accept"
1155	j["actor"] = user.URL
1156	j["to"] = actor
1157	j["published"] = time.Now().UTC().Format(time.RFC3339)
1158	j["object"] = req
1159
1160	deliverate(user.ID, actor, j.ToBytes())
1161}
1162
1163func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
1164	j := junk.New()
1165	j["@context"] = itiswhatitis
1166	j["id"] = user.URL + "/unsub/" + folxid
1167	j["type"] = "Undo"
1168	j["actor"] = user.URL
1169	j["to"] = owner
1170	f := junk.New()
1171	f["id"] = user.URL + "/sub/" + folxid
1172	f["type"] = "Follow"
1173	f["actor"] = user.URL
1174	f["to"] = owner
1175	f["object"] = xid
1176	j["object"] = f
1177	j["published"] = time.Now().UTC().Format(time.RFC3339)
1178
1179	deliverate(user.ID, owner, j.ToBytes())
1180}
1181
1182func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1183	if xid == "" {
1184		ilog.Printf("can't subscribe to empty")
1185		return
1186	}
1187	j := junk.New()
1188	j["@context"] = itiswhatitis
1189	j["id"] = user.URL + "/sub/" + folxid
1190	j["type"] = "Follow"
1191	j["actor"] = user.URL
1192	j["to"] = owner
1193	j["object"] = xid
1194	j["published"] = time.Now().UTC().Format(time.RFC3339)
1195
1196	deliverate(user.ID, owner, j.ToBytes())
1197}
1198
1199func activatedonks(donks []*Donk) []junk.Junk {
1200	var atts []junk.Junk
1201	for _, d := range donks {
1202		if re_emus.MatchString(d.Name) {
1203			continue
1204		}
1205		jd := junk.New()
1206		jd["mediaType"] = d.Media
1207		jd["name"] = d.Name
1208		jd["summary"] = html.EscapeString(d.Desc)
1209		jd["type"] = "Document"
1210		jd["url"] = d.URL
1211		atts = append(atts, jd)
1212	}
1213	return atts
1214}
1215
1216// returns activity, object
1217func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1218	dt := h.Date.Format(time.RFC3339)
1219	var jo junk.Junk
1220	j := junk.New()
1221	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1222	j["actor"] = user.URL
1223	j["published"] = dt
1224	j["to"] = h.Audience[0]
1225	if len(h.Audience) > 1 {
1226		j["cc"] = h.Audience[1:]
1227	}
1228
1229	switch h.What {
1230	case "update":
1231		fallthrough
1232	case "event":
1233		fallthrough
1234	case "honk":
1235		j["type"] = "Create"
1236		jo = junk.New()
1237		jo["id"] = h.XID
1238		jo["type"] = "Note"
1239		if h.What == "event" {
1240			jo["type"] = "Event"
1241		}
1242		if h.What == "update" {
1243			j["type"] = "Update"
1244			jo["updated"] = dt
1245		}
1246		jo["published"] = dt
1247		jo["url"] = h.XID
1248		jo["attributedTo"] = user.URL
1249		if h.RID != "" {
1250			jo["inReplyTo"] = h.RID
1251		}
1252		if h.Convoy != "" {
1253			jo["context"] = h.Convoy
1254			jo["conversation"] = h.Convoy
1255		}
1256		jo["to"] = h.Audience[0]
1257		if len(h.Audience) > 1 {
1258			jo["cc"] = h.Audience[1:]
1259		}
1260		if !h.Public {
1261			jo["directMessage"] = true
1262		}
1263		h.Noise = re_retag.ReplaceAllString(h.Noise, "")
1264		translate(h)
1265		redoimages(h)
1266		if h.Precis != "" {
1267			jo["sensitive"] = true
1268		}
1269
1270		var replies []string
1271		for _, reply := range h.Replies {
1272			replies = append(replies, reply.XID)
1273		}
1274		if len(replies) > 0 {
1275			jr := junk.New()
1276			jr["type"] = "Collection"
1277			jr["totalItems"] = len(replies)
1278			jr["items"] = replies
1279			jo["replies"] = jr
1280		}
1281
1282		var tags []junk.Junk
1283		for _, m := range h.Mentions {
1284			t := junk.New()
1285			t["type"] = "Mention"
1286			t["name"] = m.Who
1287			t["href"] = m.Where
1288			tags = append(tags, t)
1289		}
1290		for _, o := range h.Onts {
1291			t := junk.New()
1292			t["type"] = "Hashtag"
1293			o = strings.ToLower(o)
1294			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1295			t["name"] = o
1296			tags = append(tags, t)
1297		}
1298		for _, e := range herdofemus(h.Noise) {
1299			t := junk.New()
1300			t["id"] = e.ID
1301			t["type"] = "Emoji"
1302			t["name"] = e.Name
1303			i := junk.New()
1304			i["type"] = "Image"
1305			i["mediaType"] = e.Type
1306			i["url"] = e.ID
1307			t["icon"] = i
1308			tags = append(tags, t)
1309		}
1310		for _, e := range fixupflags(h) {
1311			t := junk.New()
1312			t["id"] = e.ID
1313			t["type"] = "Emoji"
1314			t["name"] = e.Name
1315			i := junk.New()
1316			i["type"] = "Image"
1317			i["mediaType"] = "image/png"
1318			i["url"] = e.ID
1319			t["icon"] = i
1320			tags = append(tags, t)
1321		}
1322		if len(tags) > 0 {
1323			jo["tag"] = tags
1324		}
1325		if p := h.Place; p != nil {
1326			t := junk.New()
1327			t["type"] = "Place"
1328			if p.Name != "" {
1329				t["name"] = p.Name
1330			}
1331			if p.Latitude != 0 {
1332				t["latitude"] = p.Latitude
1333			}
1334			if p.Longitude != 0 {
1335				t["longitude"] = p.Longitude
1336			}
1337			if p.Url != "" {
1338				t["url"] = p.Url
1339			}
1340			jo["location"] = t
1341		}
1342		if t := h.Time; t != nil {
1343			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1344			if t.Duration != 0 {
1345				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1346			}
1347		}
1348		atts := activatedonks(h.Donks)
1349		if len(atts) > 0 {
1350			jo["attachment"] = atts
1351		}
1352		jo["summary"] = h.Precis
1353		jo["content"] = h.Noise
1354		j["object"] = jo
1355	case "bonk":
1356		j["type"] = "Announce"
1357		if h.Convoy != "" {
1358			j["context"] = h.Convoy
1359		}
1360		j["object"] = h.XID
1361	case "unbonk":
1362		b := junk.New()
1363		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1364		b["type"] = "Announce"
1365		b["actor"] = user.URL
1366		if h.Convoy != "" {
1367			b["context"] = h.Convoy
1368		}
1369		b["object"] = h.XID
1370		j["type"] = "Undo"
1371		j["object"] = b
1372	case "zonk":
1373		j["type"] = "Delete"
1374		j["object"] = h.XID
1375	case "ack":
1376		j["type"] = "Read"
1377		j["object"] = h.XID
1378		if h.Convoy != "" {
1379			j["context"] = h.Convoy
1380		}
1381	case "react":
1382		j["type"] = "EmojiReact"
1383		j["object"] = h.XID
1384		if h.Convoy != "" {
1385			j["context"] = h.Convoy
1386		}
1387		j["content"] = h.Noise
1388	case "deack":
1389		b := junk.New()
1390		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1391		b["type"] = "Read"
1392		b["actor"] = user.URL
1393		b["object"] = h.XID
1394		if h.Convoy != "" {
1395			b["context"] = h.Convoy
1396		}
1397		j["type"] = "Undo"
1398		j["object"] = b
1399	}
1400
1401	return j, jo
1402}
1403
1404var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1405	row := stmtAnyXonk.QueryRow(xid)
1406	honk := scanhonk(row)
1407	if honk == nil || !honk.Public {
1408		return nil, true
1409	}
1410	user, _ := butwhatabout(honk.Username)
1411	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1412	reversehonks(rawhonks)
1413	for _, h := range rawhonks {
1414		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1415			honk.Replies = append(honk.Replies, h)
1416		}
1417	}
1418	donksforhonks([]*Honk{honk})
1419	_, j := jonkjonk(user, honk)
1420	if j == nil {
1421		elog.Fatalf("what just happened? %v", honk)
1422	}
1423	j["@context"] = itiswhatitis
1424
1425	return j.ToBytes(), true
1426}, Limit: 128})
1427
1428func gimmejonk(xid string) ([]byte, bool) {
1429	var j []byte
1430	ok := oldjonks.Get(xid, &j)
1431	return j, ok
1432}
1433
1434func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1435	rcpts := make(map[string]bool)
1436	for _, a := range addresses {
1437		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1438			continue
1439		}
1440		if a[0] == '%' {
1441			rcpts[a] = true
1442			continue
1443		}
1444		var box *Box
1445		ok := boxofboxes.Get(a, &box)
1446		if ok && useshared && box.Shared != "" {
1447			rcpts["%"+box.Shared] = true
1448		} else {
1449			rcpts[a] = true
1450		}
1451	}
1452	return rcpts
1453}
1454
1455func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1456	dt := ch.Date.Format(time.RFC3339)
1457	aud := []string{ch.Target}
1458
1459	jo := junk.New()
1460	jo["id"] = ch.XID
1461	jo["type"] = "ChatMessage"
1462	jo["published"] = dt
1463	jo["attributedTo"] = user.URL
1464	jo["to"] = aud
1465	jo["content"] = ch.HTML
1466	atts := activatedonks(ch.Donks)
1467	if len(atts) > 0 {
1468		jo["attachment"] = atts
1469	}
1470	var tags []junk.Junk
1471	for _, e := range herdofemus(ch.Noise) {
1472		t := junk.New()
1473		t["id"] = e.ID
1474		t["type"] = "Emoji"
1475		t["name"] = e.Name
1476		i := junk.New()
1477		i["type"] = "Image"
1478		i["mediaType"] = e.Type
1479		i["url"] = e.ID
1480		t["icon"] = i
1481		tags = append(tags, t)
1482	}
1483	if len(tags) > 0 {
1484		jo["tag"] = tags
1485	}
1486
1487	j := junk.New()
1488	j["@context"] = itiswhatitis
1489	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1490	j["type"] = "Create"
1491	j["actor"] = user.URL
1492	j["published"] = dt
1493	j["to"] = aud
1494	j["object"] = jo
1495
1496	return j.ToBytes()
1497}
1498
1499func sendchonk(user *WhatAbout, ch *Chonk) {
1500	msg := chonkifymsg(user, ch)
1501
1502	rcpts := make(map[string]bool)
1503	rcpts[ch.Target] = true
1504	for a := range rcpts {
1505		go deliverate(user.ID, a, msg)
1506	}
1507}
1508
1509func honkworldwide(user *WhatAbout, honk *Honk) {
1510	jonk, _ := jonkjonk(user, honk)
1511	jonk["@context"] = itiswhatitis
1512	msg := jonk.ToBytes()
1513
1514	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1515
1516	if honk.Public {
1517		for _, h := range getdubs(user.ID) {
1518			if h.XID == user.URL {
1519				continue
1520			}
1521			var box *Box
1522			ok := boxofboxes.Get(h.XID, &box)
1523			if ok && box.Shared != "" {
1524				rcpts["%"+box.Shared] = true
1525			} else {
1526				rcpts[h.XID] = true
1527			}
1528		}
1529		for _, f := range getbacktracks(honk.XID) {
1530			if f[0] == '%' {
1531				rcpts[f] = true
1532			} else {
1533				var box *Box
1534				ok := boxofboxes.Get(f, &box)
1535				if ok && box.Shared != "" {
1536					rcpts["%"+box.Shared] = true
1537				} else {
1538					rcpts[f] = true
1539				}
1540			}
1541		}
1542	}
1543	for a := range rcpts {
1544		go deliverate(user.ID, a, msg)
1545	}
1546	if honk.Public && len(honk.Onts) > 0 {
1547		collectiveaction(honk)
1548	}
1549}
1550
1551func collectiveaction(honk *Honk) {
1552	user := getserveruser()
1553	for _, ont := range honk.Onts {
1554		dubs := getnameddubs(readyLuserOne, ont)
1555		if len(dubs) == 0 {
1556			continue
1557		}
1558		j := junk.New()
1559		j["@context"] = itiswhatitis
1560		j["type"] = "Add"
1561		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1562		j["actor"] = user.URL
1563		j["object"] = honk.XID
1564		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1565		rcpts := make(map[string]bool)
1566		for _, dub := range dubs {
1567			var box *Box
1568			ok := boxofboxes.Get(dub.XID, &box)
1569			if ok && box.Shared != "" {
1570				rcpts["%"+box.Shared] = true
1571			} else {
1572				rcpts[dub.XID] = true
1573			}
1574		}
1575		msg := j.ToBytes()
1576		for a := range rcpts {
1577			go deliverate(user.ID, a, msg)
1578		}
1579	}
1580}
1581
1582func junkuser(user *WhatAbout) junk.Junk {
1583	j := junk.New()
1584	j["@context"] = itiswhatitis
1585	j["id"] = user.URL
1586	j["inbox"] = user.URL + "/inbox"
1587	j["outbox"] = user.URL + "/outbox"
1588	j["name"] = user.Display
1589	j["preferredUsername"] = user.Name
1590	j["summary"] = user.HTAbout
1591	var tags []junk.Junk
1592	for _, o := range user.Onts {
1593		t := junk.New()
1594		t["type"] = "Hashtag"
1595		o = strings.ToLower(o)
1596		t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1597		t["name"] = o
1598		tags = append(tags, t)
1599	}
1600	if len(tags) > 0 {
1601		j["tag"] = tags
1602	}
1603
1604	if user.ID > 0 {
1605		j["type"] = "Person"
1606		j["url"] = user.URL
1607		j["followers"] = user.URL + "/followers"
1608		j["following"] = user.URL + "/following"
1609		a := junk.New()
1610		a["type"] = "Image"
1611		a["mediaType"] = "image/png"
1612		a["url"] = avatarURL(user)
1613		j["icon"] = a
1614		if ban := user.Options.Banner; ban != "" {
1615			a := junk.New()
1616			a["type"] = "Image"
1617			a["mediaType"] = "image/jpg"
1618			a["url"] = ban
1619			j["image"] = a
1620		}
1621	} else {
1622		j["type"] = "Service"
1623	}
1624	k := junk.New()
1625	k["id"] = user.URL + "#key"
1626	k["owner"] = user.URL
1627	k["publicKeyPem"] = user.Key
1628	j["publicKey"] = k
1629
1630	return j
1631}
1632
1633var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1634	user, err := butwhatabout(name)
1635	if err != nil {
1636		return nil, false
1637	}
1638	j := junkuser(user)
1639	return j.ToBytes(), true
1640}, Duration: 1 * time.Minute})
1641
1642func asjonker(name string) ([]byte, bool) {
1643	var j []byte
1644	ok := oldjonkers.Get(name, &j)
1645	return j, ok
1646}
1647
1648var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1649	m := strings.Split(name, "@")
1650	if len(m) != 2 {
1651		dlog.Printf("bad fish name: %s", name)
1652		return "", true
1653	}
1654	var href string
1655	row := stmtGetXonker.QueryRow(name, "fishname")
1656	err := row.Scan(&href)
1657	if err == nil {
1658		return href, true
1659	}
1660	dlog.Printf("fishing for %s", name)
1661	j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1662	if err != nil {
1663		ilog.Printf("failed to go fish %s: %s", name, err)
1664		return "", true
1665	}
1666	links, _ := j.GetArray("links")
1667	for _, li := range links {
1668		l, ok := li.(junk.Junk)
1669		if !ok {
1670			continue
1671		}
1672		href, _ := l.GetString("href")
1673		rel, _ := l.GetString("rel")
1674		t, _ := l.GetString("type")
1675		if rel == "self" && friendorfoe(t) {
1676			when := time.Now().UTC().Format(dbtimeformat)
1677			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1678			if err != nil {
1679				elog.Printf("error saving fishname: %s", err)
1680			}
1681			return href, true
1682		}
1683	}
1684	return href, true
1685}, Duration: 1 * time.Minute})
1686
1687func gofish(name string) string {
1688	if name[0] == '@' {
1689		name = name[1:]
1690	}
1691	var href string
1692	handfull.Get(name, &href)
1693	return href
1694}
1695
1696func investigate(name string) (*SomeThing, error) {
1697	if name == "" {
1698		return nil, fmt.Errorf("no name")
1699	}
1700	if name[0] == '@' {
1701		name = gofish(name)
1702	}
1703	if name == "" {
1704		return nil, fmt.Errorf("no name")
1705	}
1706	obj, err := GetJunkFast(readyLuserOne, name)
1707	if err != nil {
1708		return nil, err
1709	}
1710	allinjest(originate(name), obj)
1711	return somethingabout(obj)
1712}
1713
1714func somethingabout(obj junk.Junk) (*SomeThing, error) {
1715	info := new(SomeThing)
1716	t, _ := obj.GetString("type")
1717	isowned := false
1718	switch t {
1719	case "Person":
1720		fallthrough
1721	case "Group":
1722		fallthrough
1723	case "Organization":
1724		fallthrough
1725	case "Application":
1726		fallthrough
1727	case "Service":
1728		info.What = SomeActor
1729	case "OrderedCollection":
1730		isowned = true
1731		fallthrough
1732	case "Collection":
1733		info.What = SomeCollection
1734	default:
1735		return nil, fmt.Errorf("unknown object type")
1736	}
1737	info.XID, _ = obj.GetString("id")
1738	info.Name, _ = obj.GetString("preferredUsername")
1739	if info.Name == "" {
1740		info.Name, _ = obj.GetString("name")
1741	}
1742	if isowned {
1743		info.Owner, _ = obj.GetString("attributedTo")
1744	}
1745	if info.Owner == "" {
1746		info.Owner = info.XID
1747	}
1748	return info, nil
1749}
1750
1751func allinjest(origin string, obj junk.Junk) {
1752	keyobj, ok := obj.GetMap("publicKey")
1753	if ok {
1754		ingestpubkey(origin, keyobj)
1755	}
1756	ingestboxes(origin, obj)
1757	ingesthandle(origin, obj)
1758}
1759
1760func ingestpubkey(origin string, obj junk.Junk) {
1761	keyobj, ok := obj.GetMap("publicKey")
1762	if ok {
1763		obj = keyobj
1764	}
1765	keyname, ok := obj.GetString("id")
1766	var data string
1767	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1768	err := row.Scan(&data)
1769	if err == nil {
1770		return
1771	}
1772	if !ok || origin != originate(keyname) {
1773		ilog.Printf("bad key origin %s <> %s", origin, keyname)
1774		return
1775	}
1776	dlog.Printf("ingesting a needed pubkey: %s", keyname)
1777	owner, ok := obj.GetString("owner")
1778	if !ok {
1779		ilog.Printf("error finding %s pubkey owner", keyname)
1780		return
1781	}
1782	data, ok = obj.GetString("publicKeyPem")
1783	if !ok {
1784		ilog.Printf("error finding %s pubkey", keyname)
1785		return
1786	}
1787	if originate(owner) != origin {
1788		ilog.Printf("bad key owner: %s <> %s", owner, origin)
1789		return
1790	}
1791	_, _, err = httpsig.DecodeKey(data)
1792	if err != nil {
1793		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1794		return
1795	}
1796	when := time.Now().UTC().Format(dbtimeformat)
1797	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1798	if err != nil {
1799		elog.Printf("error saving key: %s", err)
1800	}
1801}
1802
1803func ingestboxes(origin string, obj junk.Junk) {
1804	ident, _ := obj.GetString("id")
1805	if ident == "" {
1806		return
1807	}
1808	if originate(ident) != origin {
1809		return
1810	}
1811	var info string
1812	row := stmtGetXonker.QueryRow(ident, "boxes")
1813	err := row.Scan(&info)
1814	if err == nil {
1815		return
1816	}
1817	dlog.Printf("ingesting boxes: %s", ident)
1818	inbox, _ := obj.GetString("inbox")
1819	outbox, _ := obj.GetString("outbox")
1820	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1821	if inbox != "" {
1822		when := time.Now().UTC().Format(dbtimeformat)
1823		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1824		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1825		if err != nil {
1826			elog.Printf("error saving boxes: %s", err)
1827		}
1828	}
1829}
1830
1831func ingesthandle(origin string, obj junk.Junk) {
1832	xid, _ := obj.GetString("id")
1833	if xid == "" {
1834		return
1835	}
1836	if originate(xid) != origin {
1837		return
1838	}
1839	var handle string
1840	row := stmtGetXonker.QueryRow(xid, "handle")
1841	err := row.Scan(&handle)
1842	if err == nil {
1843		return
1844	}
1845	handle, _ = obj.GetString("preferredUsername")
1846	if handle != "" {
1847		when := time.Now().UTC().Format(dbtimeformat)
1848		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1849		if err != nil {
1850			elog.Printf("error saving handle: %s", err)
1851		}
1852	}
1853}
1854
1855func updateMe(username string) {
1856	var user *WhatAbout
1857	somenamedusers.Get(username, &user)
1858	dt := time.Now().UTC().Format(time.RFC3339)
1859	j := junk.New()
1860	j["@context"] = itiswhatitis
1861	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1862	j["actor"] = user.URL
1863	j["published"] = dt
1864	j["to"] = thewholeworld
1865	j["type"] = "Update"
1866	j["object"] = junkuser(user)
1867
1868	msg := j.ToBytes()
1869
1870	rcpts := make(map[string]bool)
1871	for _, f := range getdubs(user.ID) {
1872		if f.XID == user.URL {
1873			continue
1874		}
1875		var box *Box
1876		boxofboxes.Get(f.XID, &box)
1877		if box != nil && box.Shared != "" {
1878			rcpts["%"+box.Shared] = true
1879		} else {
1880			rcpts[f.XID] = true
1881		}
1882	}
1883	for a := range rcpts {
1884		go deliverate(user.ID, a, msg)
1885	}
1886}
1887
1888func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1889	folxid, _ := j.GetString("id")
1890
1891	ilog.Printf("updating honker follow: %s %s", who, folxid)
1892
1893	var x string
1894	db := opendatabase()
1895	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1896	err := row.Scan(&x)
1897	if err != sql.ErrNoRows {
1898		ilog.Printf("duplicate follow request: %s", who)
1899		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1900		if err != nil {
1901			elog.Printf("error updating honker: %s", err)
1902		}
1903	} else {
1904		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1905	}
1906	go rubadubdub(user, j)
1907}
1908
1909func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1910	var folxid string
1911	if who == "" {
1912		folxid, _ = j.GetString("object")
1913
1914		db := opendatabase()
1915		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1916		err := row.Scan(&who, &name)
1917		if err != nil {
1918			if err != sql.ErrNoRows {
1919				elog.Printf("error scanning honker: %s", err)
1920			}
1921			return
1922		}
1923	}
1924
1925	ilog.Printf("updating honker undo: %s %s", who, folxid)
1926	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1927	if err != nil {
1928		elog.Printf("error updating honker: %s", err)
1929		return
1930	}
1931}
1932
1933func followyou(user *WhatAbout, honkerid int64, sync bool) {
1934	var url, owner string
1935	db := opendatabase()
1936	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1937		honkerid, user.ID)
1938	err := row.Scan(&url, &owner)
1939	if err != nil {
1940		elog.Printf("can't get honker xid: %s", err)
1941		return
1942	}
1943	folxid := xfiltrate()
1944	ilog.Printf("subscribing to %s", url)
1945	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1946	if err != nil {
1947		elog.Printf("error updating honker: %s", err)
1948		return
1949	}
1950	if sync {
1951		subsub(user, url, owner, folxid)
1952	} else {
1953		go subsub(user, url, owner, folxid)
1954	}
1955
1956}
1957func unfollowyou(user *WhatAbout, honkerid int64, sync bool) {
1958	db := opendatabase()
1959	row := db.QueryRow("select xid, owner, folxid, flavor from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1960		honkerid, user.ID)
1961	var url, owner, folxid, flavor string
1962	err := row.Scan(&url, &owner, &folxid, &flavor)
1963	if err != nil {
1964		elog.Printf("can't get honker xid: %s", err)
1965		return
1966	}
1967	if flavor == "peep" {
1968		return
1969	}
1970	ilog.Printf("unsubscribing from %s", url)
1971	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1972	if err != nil {
1973		elog.Printf("error updating honker: %s", err)
1974		return
1975	}
1976	if sync {
1977		itakeitallback(user, url, owner, folxid)
1978	} else {
1979		go itakeitallback(user, url, owner, folxid)
1980	}
1981}
1982
1983func followyou2(user *WhatAbout, j junk.Junk) {
1984	who, _ := j.GetString("actor")
1985
1986	ilog.Printf("updating honker accept: %s", who)
1987	db := opendatabase()
1988	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1989		user.ID, who)
1990	var name, folxid string
1991	err := row.Scan(&name, &folxid)
1992	if err != nil {
1993		elog.Printf("can't get honker name: %s", err)
1994		return
1995	}
1996	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
1997	if err != nil {
1998		elog.Printf("error updating honker: %s", err)
1999		return
2000	}
2001}
2002
2003func nofollowyou2(user *WhatAbout, j junk.Junk) {
2004	who, _ := j.GetString("actor")
2005
2006	ilog.Printf("updating honker reject: %s", who)
2007	db := opendatabase()
2008	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2009		user.ID, who)
2010	var name, folxid string
2011	err := row.Scan(&name, &folxid)
2012	if err != nil {
2013		elog.Printf("can't get honker name: %s", err)
2014		return
2015	}
2016	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
2017	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
2018	if err != nil {
2019		elog.Printf("error updating honker: %s", err)
2020		return
2021	}
2022}