all repos — honk @ c8fa51ec3cb7addf83cbd703585e4500ab64076c

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