all repos — honk @ ae62659c3be421818be2278a121e73b94a3679bc

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	"crypto/rsa"
  21	"database/sql"
  22	"fmt"
  23	"html"
  24	"io"
  25	"log"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"regexp"
  31	"strings"
  32	"sync"
  33	"time"
  34
  35	"humungus.tedunangst.com/r/webs/cache"
  36	"humungus.tedunangst.com/r/webs/httpsig"
  37	"humungus.tedunangst.com/r/webs/image"
  38	"humungus.tedunangst.com/r/webs/junk"
  39)
  40
  41var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  42var thefakename = `application/activity+json`
  43var falsenames = []string{
  44	`application/ld+json`,
  45	`application/activity+json`,
  46}
  47var itiswhatitis = "https://www.w3.org/ns/activitystreams"
  48var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
  49
  50func friendorfoe(ct string) bool {
  51	ct = strings.ToLower(ct)
  52	for _, at := range falsenames {
  53		if strings.HasPrefix(ct, at) {
  54			return true
  55		}
  56	}
  57	return false
  58}
  59
  60func PostJunk(keyname string, key *rsa.PrivateKey, url string, j junk.Junk) error {
  61	return PostMsg(keyname, key, url, j.ToBytes())
  62}
  63
  64func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error {
  65	client := http.DefaultClient
  66	req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
  67	if err != nil {
  68		return err
  69	}
  70	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
  71	req.Header.Set("Content-Type", theonetruename)
  72	httpsig.SignRequest(keyname, key, req, msg)
  73	resp, err := client.Do(req)
  74	if err != nil {
  75		return err
  76	}
  77	resp.Body.Close()
  78	switch resp.StatusCode {
  79	case 200:
  80	case 201:
  81	case 202:
  82	default:
  83		return fmt.Errorf("http post status: %d", resp.StatusCode)
  84	}
  85	log.Printf("successful post: %s %d", url, resp.StatusCode)
  86	return nil
  87}
  88
  89type JunkError struct {
  90	Junk junk.Junk
  91	Err  error
  92}
  93
  94func GetJunk(url string) (junk.Junk, error) {
  95	return GetJunkTimeout(url, 30*time.Second)
  96}
  97
  98func GetJunkFast(url string) (junk.Junk, error) {
  99	return GetJunkTimeout(url, 5*time.Second)
 100}
 101
 102func GetJunkHardMode(url string) (junk.Junk, error) {
 103	j, err := GetJunk(url)
 104	if err != nil {
 105		emsg := err.Error()
 106		if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
 107			log.Printf("trying again after error: %s", emsg)
 108			time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
 109			j, err = GetJunk(url)
 110			if err != nil {
 111				log.Printf("still couldn't get it")
 112			} else {
 113				log.Printf("retry success!")
 114			}
 115		}
 116	}
 117	return j, err
 118}
 119
 120var flightdeck = make(map[string][]chan JunkError)
 121var decklock sync.Mutex
 122
 123func GetJunkTimeout(url string, timeout time.Duration) (junk.Junk, error) {
 124	decklock.Lock()
 125	inflight, ok := flightdeck[url]
 126	if ok {
 127		log.Printf("awaiting result for %s", url)
 128		c := make(chan JunkError)
 129		flightdeck[url] = append(inflight, c)
 130		decklock.Unlock()
 131		je := <-c
 132		close(c)
 133		return je.Junk, je.Err
 134	}
 135	flightdeck[url] = inflight
 136	decklock.Unlock()
 137
 138	at := thefakename
 139	if strings.Contains(url, ".well-known/webfinger?resource") {
 140		at = "application/jrd+json"
 141	}
 142	j, err := junk.Get(url, junk.GetArgs{
 143		Accept:  at,
 144		Agent:   "honksnonk/5.0; " + serverName,
 145		Timeout: timeout,
 146	})
 147
 148	decklock.Lock()
 149	inflight = flightdeck[url]
 150	delete(flightdeck, url)
 151	decklock.Unlock()
 152	if len(inflight) > 0 {
 153		je := JunkError{Junk: j, Err: err}
 154		go func() {
 155			for _, c := range inflight {
 156				log.Printf("returning awaited result for %s", url)
 157				c <- je
 158			}
 159		}()
 160	}
 161	return j, err
 162}
 163
 164func savedonk(url string, name, desc, media string, localize bool) *Donk {
 165	if url == "" {
 166		return nil
 167	}
 168	donk := finddonk(url)
 169	if donk != nil {
 170		return donk
 171	}
 172	donk = new(Donk)
 173	log.Printf("saving donk: %s", url)
 174	xid := xfiltrate()
 175	data := []byte{}
 176	if localize {
 177		resp, err := http.Get(url)
 178		if err != nil {
 179			log.Printf("error fetching %s: %s", url, err)
 180			localize = false
 181			goto saveit
 182		}
 183		defer resp.Body.Close()
 184		if resp.StatusCode != 200 {
 185			localize = false
 186			goto saveit
 187		}
 188		var buf bytes.Buffer
 189		limiter := io.LimitReader(resp.Body, 10*1024*1024)
 190		io.Copy(&buf, limiter)
 191
 192		data = buf.Bytes()
 193		if len(data) == 10*1024*1024 {
 194			log.Printf("truncation likely")
 195		}
 196		if strings.HasPrefix(media, "image") {
 197			img, err := image.Vacuum(&buf,
 198				image.Params{LimitSize: 4200 * 4200, MaxWidth: 2048, MaxHeight: 2048})
 199			if err != nil {
 200				log.Printf("unable to decode image: %s", err)
 201				localize = false
 202				data = []byte{}
 203				goto saveit
 204			}
 205			data = img.Data
 206			format := img.Format
 207			media = "image/" + format
 208			if format == "jpeg" {
 209				format = "jpg"
 210			}
 211			xid = xid + "." + format
 212		} else if len(data) > 100000 {
 213			log.Printf("not saving large attachment")
 214			localize = false
 215			data = []byte{}
 216		}
 217	}
 218saveit:
 219	fileid, err := savefile(xid, name, desc, url, media, localize, data)
 220	if err != nil {
 221		log.Printf("error saving file %s: %s", url, err)
 222		return nil
 223	}
 224	donk.FileID = fileid
 225	donk.XID = xid
 226	return donk
 227}
 228
 229func iszonked(userid int64, xid string) bool {
 230	row := stmtFindZonk.QueryRow(userid, xid)
 231	var id int64
 232	err := row.Scan(&id)
 233	if err == nil {
 234		return true
 235	}
 236	if err != sql.ErrNoRows {
 237		log.Printf("error querying zonk: %s", err)
 238	}
 239	return false
 240}
 241
 242func needxonk(user *WhatAbout, x *Honk) bool {
 243	if rejectxonk(x) {
 244		return false
 245	}
 246	return needxonkid(user, x.XID)
 247}
 248func needxonkid(user *WhatAbout, xid string) bool {
 249	if strings.HasPrefix(xid, user.URL+"/") {
 250		return false
 251	}
 252	if rejectorigin(user.ID, xid) {
 253		return false
 254	}
 255	if iszonked(user.ID, xid) {
 256		log.Printf("already zonked: %s", xid)
 257		return false
 258	}
 259	row := stmtFindXonk.QueryRow(user.ID, xid)
 260	var id int64
 261	err := row.Scan(&id)
 262	if err == nil {
 263		return false
 264	}
 265	if err != sql.ErrNoRows {
 266		log.Printf("error querying xonk: %s", err)
 267	}
 268	return true
 269}
 270
 271func eradicatexonk(userid int64, xid string) {
 272	xonk := getxonk(userid, xid)
 273	if xonk != nil {
 274		deletehonk(xonk.ID)
 275	}
 276	_, err := stmtSaveZonker.Exec(userid, xid, "zonk")
 277	if err != nil {
 278		log.Printf("error eradicating: %s", err)
 279	}
 280}
 281
 282func savexonk(x *Honk) {
 283	log.Printf("saving xonk: %s", x.XID)
 284	go prehandle(x.Honker)
 285	go prehandle(x.Oonker)
 286	savehonk(x)
 287}
 288
 289type Box struct {
 290	In     string
 291	Out    string
 292	Shared string
 293}
 294
 295var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
 296	var info string
 297	row := stmtGetXonker.QueryRow(ident, "boxes")
 298	err := row.Scan(&info)
 299	if err == nil {
 300		m := strings.Split(info, " ")
 301		b := &Box{In: m[0], Out: m[1], Shared: m[2]}
 302		return b, true
 303	}
 304	j, err := GetJunk(ident)
 305	if err != nil {
 306		log.Printf("error getting boxes: %s", err)
 307		return nil, false
 308	}
 309	inbox, _ := j.GetString("inbox")
 310	outbox, _ := j.GetString("outbox")
 311	sbox, _ := j.GetString("endpoints", "sharedInbox")
 312	b := &Box{In: inbox, Out: outbox, Shared: sbox}
 313	if inbox != "" {
 314		m := strings.Join([]string{inbox, outbox, sbox}, " ")
 315		_, err = stmtSaveXonker.Exec(ident, m, "boxes")
 316		if err != nil {
 317			log.Printf("error saving boxes: %s", err)
 318		}
 319	}
 320	return b, true
 321}})
 322
 323func gimmexonks(user *WhatAbout, outbox string) {
 324	log.Printf("getting outbox: %s", outbox)
 325	j, err := GetJunk(outbox)
 326	if err != nil {
 327		log.Printf("error getting outbox: %s", err)
 328		return
 329	}
 330	t, _ := j.GetString("type")
 331	origin := originate(outbox)
 332	if t == "OrderedCollection" {
 333		items, _ := j.GetArray("orderedItems")
 334		if items == nil {
 335			items, _ = j.GetArray("items")
 336		}
 337		if items == nil {
 338			obj, ok := j.GetMap("first")
 339			if ok {
 340				items, _ = obj.GetArray("orderedItems")
 341			} else {
 342				page1, ok := j.GetString("first")
 343				if ok {
 344					j, err = GetJunk(page1)
 345					if err != nil {
 346						log.Printf("error gettings page1: %s", err)
 347						return
 348					}
 349					items, _ = j.GetArray("orderedItems")
 350				}
 351			}
 352		}
 353		if len(items) > 20 {
 354			items = items[0:20]
 355		}
 356		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 357			items[i], items[j] = items[j], items[i]
 358		}
 359		for _, item := range items {
 360			obj, ok := item.(junk.Junk)
 361			if ok {
 362				xonksaver(user, obj, origin)
 363				continue
 364			}
 365			xid, ok := item.(string)
 366			if ok {
 367				if !needxonkid(user, xid) {
 368					continue
 369				}
 370				obj, err = GetJunk(xid)
 371				if err != nil {
 372					log.Printf("error getting item: %s", err)
 373					continue
 374				}
 375				xonksaver(user, obj, originate(xid))
 376			}
 377		}
 378	}
 379}
 380
 381func whosthere(xid string) ([]string, string) {
 382	obj, err := GetJunk(xid)
 383	if err != nil {
 384		log.Printf("error getting remote xonk: %s", err)
 385		return nil, ""
 386	}
 387	convoy, _ := obj.GetString("context")
 388	if convoy == "" {
 389		convoy, _ = obj.GetString("conversation")
 390	}
 391	return newphone(nil, obj), convoy
 392}
 393
 394func newphone(a []string, obj junk.Junk) []string {
 395	for _, addr := range []string{"to", "cc", "attributedTo"} {
 396		who, _ := obj.GetString(addr)
 397		if who != "" {
 398			a = append(a, who)
 399		}
 400		whos, _ := obj.GetArray(addr)
 401		for _, w := range whos {
 402			who, _ := w.(string)
 403			if who != "" {
 404				a = append(a, who)
 405			}
 406		}
 407	}
 408	return a
 409}
 410
 411func extractattrto(obj junk.Junk) string {
 412	who, _ := obj.GetString("attributedTo")
 413	if who != "" {
 414		return who
 415	}
 416	o, ok := obj.GetMap("attributedTo")
 417	if ok {
 418		id, ok := o.GetString("id")
 419		if ok {
 420			return id
 421		}
 422	}
 423	arr, _ := obj.GetArray("attributedTo")
 424	for _, a := range arr {
 425		o, ok := a.(junk.Junk)
 426		if ok {
 427			t, _ := o.GetString("type")
 428			id, _ := o.GetString("id")
 429			if t == "Person" || t == "" {
 430				return id
 431			}
 432		}
 433		s, ok := a.(string)
 434		if ok {
 435			return s
 436		}
 437	}
 438	return ""
 439}
 440
 441func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 442	depth := 0
 443	maxdepth := 10
 444	currenttid := ""
 445	goingup := 0
 446	var xonkxonkfn func(item junk.Junk, origin string) *Honk
 447
 448	saveonemore := func(xid string) {
 449		log.Printf("getting onemore: %s", xid)
 450		if depth >= maxdepth {
 451			log.Printf("in too deep")
 452			return
 453		}
 454		obj, err := GetJunkHardMode(xid)
 455		if err != nil {
 456			log.Printf("error getting onemore: %s: %s", xid, err)
 457			return
 458		}
 459		depth++
 460		xonkxonkfn(obj, originate(xid))
 461		depth--
 462	}
 463
 464	xonkxonkfn = func(item junk.Junk, origin string) *Honk {
 465		// id, _ := item.GetString( "id")
 466		what, _ := item.GetString("type")
 467		dt, _ := item.GetString("published")
 468
 469		var err error
 470		var xid, rid, url, content, precis, convoy string
 471		var replies []string
 472		var obj junk.Junk
 473		var ok bool
 474		isUpdate := false
 475		switch what {
 476		case "Delete":
 477			obj, ok = item.GetMap("object")
 478			if ok {
 479				xid, _ = obj.GetString("id")
 480			} else {
 481				xid, _ = item.GetString("object")
 482			}
 483			if xid == "" {
 484				return nil
 485			}
 486			if originate(xid) != origin {
 487				log.Printf("forged delete: %s", xid)
 488				return nil
 489			}
 490			log.Printf("eradicating %s", xid)
 491			eradicatexonk(user.ID, xid)
 492			return nil
 493		case "Tombstone":
 494			xid, _ = item.GetString("id")
 495			if xid == "" {
 496				return nil
 497			}
 498			if originate(xid) != origin {
 499				log.Printf("forged delete: %s", xid)
 500				return nil
 501			}
 502			log.Printf("eradicating %s", xid)
 503			eradicatexonk(user.ID, xid)
 504			return nil
 505		case "Announce":
 506			obj, ok = item.GetMap("object")
 507			if ok {
 508				xid, _ = obj.GetString("id")
 509			} else {
 510				xid, _ = item.GetString("object")
 511			}
 512			if !needxonkid(user, xid) {
 513				return nil
 514			}
 515			log.Printf("getting bonk: %s", xid)
 516			obj, err = GetJunkHardMode(xid)
 517			if err != nil {
 518				log.Printf("error getting bonk: %s: %s", xid, err)
 519			}
 520			origin = originate(xid)
 521			what = "bonk"
 522		case "Update":
 523			isUpdate = true
 524			fallthrough
 525		case "Create":
 526			obj, ok = item.GetMap("object")
 527			if !ok {
 528				xid, _ = item.GetString("object")
 529				log.Printf("getting created honk: %s", xid)
 530				obj, err = GetJunkHardMode(xid)
 531				if err != nil {
 532					log.Printf("error getting creation: %s", err)
 533				}
 534			}
 535			what = "honk"
 536			if obj != nil {
 537				t, _ := obj.GetString("type")
 538				switch t {
 539				case "Event":
 540					what = "event"
 541				}
 542			}
 543		case "Read":
 544			xid, ok = item.GetString("object")
 545			if ok {
 546				if !needxonkid(user, xid) {
 547					log.Printf("don't need read obj: %s", xid)
 548					return nil
 549				}
 550				obj, err = GetJunkHardMode(xid)
 551				if err != nil {
 552					log.Printf("error getting read: %s", err)
 553					return nil
 554				}
 555				return xonkxonkfn(obj, originate(xid))
 556			}
 557			return nil
 558		case "Audio":
 559			fallthrough
 560		case "Video":
 561			fallthrough
 562		case "Question":
 563			fallthrough
 564		case "Note":
 565			fallthrough
 566		case "Article":
 567			fallthrough
 568		case "Page":
 569			obj = item
 570			what = "honk"
 571		case "Event":
 572			obj = item
 573			what = "event"
 574		default:
 575			log.Printf("unknown activity: %s", what)
 576			fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 577			item.Write(fd)
 578			io.WriteString(fd, "\n")
 579			fd.Close()
 580			return nil
 581		}
 582
 583		if obj != nil {
 584			_, ok := obj.GetString("diaspora:guid")
 585			if ok {
 586				// friendica does the silliest bonks
 587				c, ok := obj.GetString("source", "content")
 588				if ok {
 589					re_link := regexp.MustCompile(`link='([^']*)'`)
 590					m := re_link.FindStringSubmatch(c)
 591					if len(m) > 1 {
 592						xid := m[1]
 593						log.Printf("getting friendica flavored bonk: %s", xid)
 594						if !needxonkid(user, xid) {
 595							return nil
 596						}
 597						newobj, err := GetJunkHardMode(xid)
 598						if err != nil {
 599							log.Printf("error getting bonk: %s: %s", xid, err)
 600						} else {
 601							obj = newobj
 602							origin = originate(xid)
 603							what = "bonk"
 604						}
 605					}
 606				}
 607			}
 608		}
 609
 610		var xonk Honk
 611		// early init
 612		xonk.UserID = user.ID
 613		xonk.Honker, _ = item.GetString("actor")
 614		if xonk.Honker == "" {
 615			xonk.Honker, _ = item.GetString("attributedTo")
 616		}
 617		if obj != nil {
 618			if xonk.Honker == "" {
 619				xonk.Honker = extractattrto(obj)
 620			}
 621			xonk.Oonker = extractattrto(obj)
 622			if xonk.Oonker == xonk.Honker {
 623				xonk.Oonker = ""
 624			}
 625			xonk.Audience = newphone(nil, obj)
 626		}
 627		xonk.Audience = append(xonk.Audience, xonk.Honker)
 628		xonk.Audience = oneofakind(xonk.Audience)
 629
 630		var mentions []string
 631		if obj != nil {
 632			ot, _ := obj.GetString("type")
 633			url, _ = obj.GetString("url")
 634			dt2, ok := obj.GetString("published")
 635			if ok {
 636				dt = dt2
 637			}
 638			xid, _ = obj.GetString("id")
 639			precis, _ = obj.GetString("summary")
 640			if precis == "" {
 641				precis, _ = obj.GetString("name")
 642			}
 643			content, _ = obj.GetString("content")
 644			if !strings.HasPrefix(content, "<p>") {
 645				content = "<p>" + content
 646			}
 647			sens, _ := obj["sensitive"].(bool)
 648			if sens && precis == "" {
 649				precis = "unspecified horror"
 650			}
 651			rid, ok = obj.GetString("inReplyTo")
 652			if !ok {
 653				robj, ok := obj.GetMap("inReplyTo")
 654				if ok {
 655					rid, _ = robj.GetString("id")
 656				}
 657			}
 658			convoy, _ = obj.GetString("context")
 659			if convoy == "" {
 660				convoy, _ = obj.GetString("conversation")
 661			}
 662			if ot == "Question" {
 663				if what == "honk" {
 664					what = "qonk"
 665				}
 666				content += "<ul>"
 667				ans, _ := obj.GetArray("oneOf")
 668				for _, ai := range ans {
 669					a, ok := ai.(junk.Junk)
 670					if !ok {
 671						continue
 672					}
 673					as, _ := a.GetString("name")
 674					content += "<li>" + as
 675				}
 676				ans, _ = obj.GetArray("anyOf")
 677				for _, ai := range ans {
 678					a, ok := ai.(junk.Junk)
 679					if !ok {
 680						continue
 681					}
 682					as, _ := a.GetString("name")
 683					content += "<li>" + as
 684				}
 685				content += "</ul>"
 686			}
 687			if what == "honk" && rid != "" {
 688				what = "tonk"
 689			}
 690			atts, _ := obj.GetArray("attachment")
 691			for i, atti := range atts {
 692				att, ok := atti.(junk.Junk)
 693				if !ok {
 694					continue
 695				}
 696				at, _ := att.GetString("type")
 697				mt, _ := att.GetString("mediaType")
 698				u, _ := att.GetString("url")
 699				name, _ := att.GetString("name")
 700				desc, _ := att.GetString("summary")
 701				if desc == "" {
 702					desc = name
 703				}
 704				localize := false
 705				if i > 4 {
 706					log.Printf("excessive attachment: %s", at)
 707				} else if at == "Document" || at == "Image" {
 708					mt = strings.ToLower(mt)
 709					log.Printf("attachment: %s %s", mt, u)
 710					if mt == "text/plain" || strings.HasPrefix(mt, "image") {
 711						localize = true
 712					}
 713				} else {
 714					log.Printf("unknown attachment: %s", at)
 715				}
 716				if skipMedia(&xonk) {
 717					localize = false
 718				}
 719				donk := savedonk(u, name, desc, mt, localize)
 720				if donk != nil {
 721					xonk.Donks = append(xonk.Donks, donk)
 722				}
 723			}
 724			tags, _ := obj.GetArray("tag")
 725			for _, tagi := range tags {
 726				tag, ok := tagi.(junk.Junk)
 727				if !ok {
 728					continue
 729				}
 730				tt, _ := tag.GetString("type")
 731				name, _ := tag.GetString("name")
 732				desc, _ := tag.GetString("summary")
 733				if desc == "" {
 734					desc = name
 735				}
 736				if tt == "Emoji" {
 737					icon, _ := tag.GetMap("icon")
 738					mt, _ := icon.GetString("mediaType")
 739					if mt == "" {
 740						mt = "image/png"
 741					}
 742					u, _ := icon.GetString("url")
 743					donk := savedonk(u, name, desc, mt, true)
 744					if donk != nil {
 745						xonk.Donks = append(xonk.Donks, donk)
 746					}
 747				}
 748				if tt == "Hashtag" {
 749					if name == "" || name == "#" {
 750						// skip it
 751					} else {
 752						if name[0] != '#' {
 753							name = "#" + name
 754						}
 755						xonk.Onts = append(xonk.Onts, name)
 756					}
 757				}
 758				if tt == "Place" {
 759					p := new(Place)
 760					p.Name = name
 761					p.Latitude, _ = tag["latitude"].(float64)
 762					p.Longitude, _ = tag["longitude"].(float64)
 763					p.Url, _ = tag.GetString("url")
 764					xonk.Place = p
 765				}
 766				if tt == "Mention" {
 767					m, _ := tag.GetString("href")
 768					mentions = append(mentions, m)
 769				}
 770			}
 771			starttime, ok := obj.GetString("startTime")
 772			if ok {
 773				start, err := time.Parse(time.RFC3339, starttime)
 774				if err == nil {
 775					t := new(Time)
 776					t.StartTime = start
 777					endtime, _ := obj.GetString("endTime")
 778					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 779					dura, _ := obj.GetString("duration")
 780					if strings.HasPrefix(dura, "PT") {
 781						dura = strings.ToLower(dura[2:])
 782						d, _ := time.ParseDuration(dura)
 783						t.Duration = Duration(d)
 784					}
 785					xonk.Time = t
 786				}
 787			}
 788			loca, ok := obj.GetMap("location")
 789			if ok {
 790				tt, _ := loca.GetString("type")
 791				name, _ := loca.GetString("name")
 792				if tt == "Place" {
 793					p := new(Place)
 794					p.Name = name
 795					p.Latitude, _ = loca["latitude"].(float64)
 796					p.Longitude, _ = loca["longitude"].(float64)
 797					p.Url, _ = loca.GetString("url")
 798					xonk.Place = p
 799				}
 800			}
 801
 802			xonk.Onts = oneofakind(xonk.Onts)
 803			replyobj, ok := obj.GetMap("replies")
 804			if ok {
 805				items, ok := replyobj.GetArray("items")
 806				if !ok {
 807					first, ok := replyobj.GetMap("first")
 808					if ok {
 809						items, _ = first.GetArray("items")
 810					}
 811				}
 812				for _, repl := range items {
 813					s, ok := repl.(string)
 814					if ok {
 815						replies = append(replies, s)
 816					}
 817				}
 818			}
 819
 820		}
 821		if originate(xid) != origin {
 822			log.Printf("original sin: %s <> %s", xid, origin)
 823			item.Write(os.Stdout)
 824			return nil
 825		}
 826
 827		if currenttid == "" {
 828			currenttid = convoy
 829		}
 830
 831		if len(content) > 90001 {
 832			log.Printf("content too long. truncating")
 833			content = content[:90001]
 834		}
 835
 836		// init xonk
 837		xonk.What = what
 838		xonk.XID = xid
 839		xonk.RID = rid
 840		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 841		xonk.URL = url
 842		xonk.Noise = content
 843		xonk.Precis = precis
 844		xonk.Format = "html"
 845		xonk.Convoy = convoy
 846		for _, m := range mentions {
 847			if m == user.URL {
 848				xonk.Whofore = 1
 849			}
 850		}
 851		imaginate(&xonk)
 852
 853		if isUpdate {
 854			log.Printf("something has changed! %s", xonk.XID)
 855			prev := getxonk(user.ID, xonk.XID)
 856			if prev == nil {
 857				log.Printf("didn't find old version for update: %s", xonk.XID)
 858				isUpdate = false
 859			} else {
 860				prev.Noise = xonk.Noise
 861				prev.Precis = xonk.Precis
 862				prev.Date = xonk.Date
 863				prev.Donks = xonk.Donks
 864				prev.Onts = xonk.Onts
 865				prev.Place = xonk.Place
 866				updatehonk(prev)
 867			}
 868		}
 869		if !isUpdate && needxonk(user, &xonk) {
 870			if strings.HasSuffix(convoy, "#context") {
 871				// friendica...
 872				if rid != "" {
 873					convoy = ""
 874				} else {
 875					convoy = url
 876				}
 877			}
 878			if rid != "" {
 879				if needxonkid(user, rid) {
 880					goingup++
 881					saveonemore(rid)
 882					goingup--
 883				}
 884				if convoy == "" {
 885					xx := getxonk(user.ID, rid)
 886					if xx != nil {
 887						convoy = xx.Convoy
 888					}
 889				}
 890			}
 891			if convoy == "" {
 892				convoy = currenttid
 893			}
 894			if convoy == "" {
 895				convoy = "missing-" + xfiltrate()
 896				currenttid = convoy
 897			}
 898			xonk.Convoy = convoy
 899			savexonk(&xonk)
 900		}
 901		if goingup == 0 {
 902			for _, replid := range replies {
 903				if needxonkid(user, replid) {
 904					log.Printf("missing a reply: %s", replid)
 905					saveonemore(replid)
 906				}
 907			}
 908		}
 909		return &xonk
 910	}
 911
 912	return xonkxonkfn(item, origin)
 913}
 914
 915func rubadubdub(user *WhatAbout, req junk.Junk) {
 916	xid, _ := req.GetString("id")
 917	actor, _ := req.GetString("actor")
 918	j := junk.New()
 919	j["@context"] = itiswhatitis
 920	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 921	j["type"] = "Accept"
 922	j["actor"] = user.URL
 923	j["to"] = actor
 924	j["published"] = time.Now().UTC().Format(time.RFC3339)
 925	j["object"] = req
 926
 927	deliverate(0, user.ID, actor, j.ToBytes())
 928}
 929
 930func itakeitallback(user *WhatAbout, xid string) {
 931	j := junk.New()
 932	j["@context"] = itiswhatitis
 933	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 934	j["type"] = "Undo"
 935	j["actor"] = user.URL
 936	j["to"] = xid
 937	f := junk.New()
 938	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 939	f["type"] = "Follow"
 940	f["actor"] = user.URL
 941	f["to"] = xid
 942	f["object"] = xid
 943	j["object"] = f
 944	j["published"] = time.Now().UTC().Format(time.RFC3339)
 945
 946	deliverate(0, user.ID, xid, j.ToBytes())
 947}
 948
 949func subsub(user *WhatAbout, xid string, owner string) {
 950	if xid == "" {
 951		log.Printf("can't subscribe to empty")
 952		return
 953	}
 954	j := junk.New()
 955	j["@context"] = itiswhatitis
 956	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 957	j["type"] = "Follow"
 958	j["actor"] = user.URL
 959	j["to"] = owner
 960	j["object"] = xid
 961	j["published"] = time.Now().UTC().Format(time.RFC3339)
 962
 963	deliverate(0, user.ID, owner, j.ToBytes())
 964}
 965
 966// returns activity, object
 967func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 968	dt := h.Date.Format(time.RFC3339)
 969	var jo junk.Junk
 970	j := junk.New()
 971	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 972	j["actor"] = user.URL
 973	j["published"] = dt
 974	if h.Public {
 975		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 976	} else {
 977		j["to"] = h.Audience[0]
 978	}
 979	if len(h.Audience) > 1 {
 980		j["cc"] = h.Audience[1:]
 981	}
 982
 983	switch h.What {
 984	case "update":
 985		fallthrough
 986	case "tonk":
 987		fallthrough
 988	case "event":
 989		fallthrough
 990	case "honk":
 991		j["type"] = "Create"
 992		if h.What == "update" {
 993			j["type"] = "Update"
 994		}
 995
 996		jo = junk.New()
 997		jo["id"] = h.XID
 998		jo["type"] = "Note"
 999		if h.What == "event" {
1000			jo["type"] = "Event"
1001		}
1002		jo["published"] = dt
1003		jo["url"] = h.XID
1004		jo["attributedTo"] = user.URL
1005		if h.RID != "" {
1006			jo["inReplyTo"] = h.RID
1007		}
1008		if h.Convoy != "" {
1009			jo["context"] = h.Convoy
1010			jo["conversation"] = h.Convoy
1011		}
1012		jo["to"] = h.Audience[0]
1013		if len(h.Audience) > 1 {
1014			jo["cc"] = h.Audience[1:]
1015		}
1016		if !h.Public {
1017			jo["directMessage"] = true
1018		}
1019		translate(h, true)
1020		h.Noise = re_memes.ReplaceAllString(h.Noise, "")
1021		jo["summary"] = html.EscapeString(h.Precis)
1022		jo["content"] = ontologize(mentionize(h.Noise))
1023		if strings.HasPrefix(h.Precis, "DZ:") {
1024			jo["sensitive"] = true
1025		}
1026
1027		var replies []string
1028		for _, reply := range h.Replies {
1029			replies = append(replies, reply.XID)
1030		}
1031		if len(replies) > 0 {
1032			jr := junk.New()
1033			jr["type"] = "Collection"
1034			jr["totalItems"] = len(replies)
1035			jr["items"] = replies
1036			jo["replies"] = jr
1037		}
1038
1039		var tags []junk.Junk
1040		for _, m := range bunchofgrapes(h.Noise) {
1041			t := junk.New()
1042			t["type"] = "Mention"
1043			t["name"] = m.who
1044			t["href"] = m.where
1045			tags = append(tags, t)
1046		}
1047		for _, o := range h.Onts {
1048			t := junk.New()
1049			t["type"] = "Hashtag"
1050			o = strings.ToLower(o)
1051			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1052			t["name"] = o
1053			tags = append(tags, t)
1054		}
1055		for _, e := range herdofemus(h.Noise) {
1056			t := junk.New()
1057			t["id"] = e.ID
1058			t["type"] = "Emoji"
1059			t["name"] = e.Name
1060			i := junk.New()
1061			i["type"] = "Image"
1062			i["mediaType"] = "image/png"
1063			i["url"] = e.ID
1064			t["icon"] = i
1065			tags = append(tags, t)
1066		}
1067		if p := h.Place; p != nil {
1068			t := junk.New()
1069			t["type"] = "Place"
1070			t["name"] = p.Name
1071			t["latitude"] = p.Latitude
1072			t["longitude"] = p.Longitude
1073			t["url"] = p.Url
1074			if h.What == "event" {
1075				jo["location"] = t
1076			} else {
1077				tags = append(tags, t)
1078			}
1079		}
1080		if len(tags) > 0 {
1081			jo["tag"] = tags
1082		}
1083		if t := h.Time; t != nil {
1084			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1085			if t.Duration != 0 {
1086				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1087			}
1088		}
1089		var atts []junk.Junk
1090		for _, d := range h.Donks {
1091			if re_emus.MatchString(d.Name) {
1092				continue
1093			}
1094			jd := junk.New()
1095			jd["mediaType"] = d.Media
1096			jd["name"] = d.Name
1097			jd["summary"] = html.EscapeString(d.Desc)
1098			jd["type"] = "Document"
1099			jd["url"] = d.URL
1100			atts = append(atts, jd)
1101		}
1102		if len(atts) > 0 {
1103			jo["attachment"] = atts
1104		}
1105		j["object"] = jo
1106	case "bonk":
1107		j["type"] = "Announce"
1108		if h.Convoy != "" {
1109			j["context"] = h.Convoy
1110		}
1111		j["object"] = h.XID
1112	case "unbonk":
1113		b := junk.New()
1114		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1115		b["type"] = "Announce"
1116		b["actor"] = user.URL
1117		if h.Convoy != "" {
1118			b["context"] = h.Convoy
1119		}
1120		b["object"] = h.XID
1121		j["type"] = "Undo"
1122		j["object"] = b
1123	case "zonk":
1124		j["type"] = "Delete"
1125		j["object"] = h.XID
1126	case "ack":
1127		j["type"] = "Read"
1128		j["object"] = h.XID
1129	case "deack":
1130		b := junk.New()
1131		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1132		b["type"] = "Read"
1133		b["actor"] = user.URL
1134		b["object"] = h.XID
1135		j["type"] = "Undo"
1136		j["object"] = b
1137	}
1138
1139	return j, jo
1140}
1141
1142var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1143	row := stmtAnyXonk.QueryRow(xid)
1144	honk := scanhonk(row)
1145	if honk == nil || !honk.Public {
1146		return nil, true
1147	}
1148	user, _ := butwhatabout(honk.Username)
1149	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1150	reversehonks(rawhonks)
1151	for _, h := range rawhonks {
1152		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1153			honk.Replies = append(honk.Replies, h)
1154		}
1155	}
1156	donksforhonks([]*Honk{honk})
1157	_, j := jonkjonk(user, honk)
1158	j["@context"] = itiswhatitis
1159
1160	return j.ToBytes(), true
1161}})
1162
1163func gimmejonk(xid string) ([]byte, bool) {
1164	var j []byte
1165	ok := oldjonks.Get(xid, &j)
1166	return j, ok
1167}
1168
1169func honkworldwide(user *WhatAbout, honk *Honk) {
1170	jonk, _ := jonkjonk(user, honk)
1171	jonk["@context"] = itiswhatitis
1172	msg := jonk.ToBytes()
1173
1174	rcpts := make(map[string]bool)
1175	for _, a := range honk.Audience {
1176		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1177			continue
1178		}
1179		var box *Box
1180		ok := boxofboxes.Get(a, &box)
1181		if ok && honk.Public && box.Shared != "" {
1182			rcpts["%"+box.Shared] = true
1183		} else {
1184			rcpts[a] = true
1185		}
1186	}
1187	if honk.Public {
1188		for _, h := range getdubs(user.ID) {
1189			if h.XID == user.URL {
1190				continue
1191			}
1192			var box *Box
1193			ok := boxofboxes.Get(h.XID, &box)
1194			if ok && box.Shared != "" {
1195				rcpts["%"+box.Shared] = true
1196			} else {
1197				rcpts[h.XID] = true
1198			}
1199		}
1200	}
1201	for a := range rcpts {
1202		go deliverate(0, user.ID, a, msg)
1203	}
1204	if honk.Public && len(honk.Onts) > 0 {
1205		collectiveaction(honk)
1206	}
1207}
1208
1209func collectiveaction(honk *Honk) {
1210	user := getserveruser()
1211	for _, ont := range honk.Onts {
1212		dubs := getnameddubs(serverUID, ont)
1213		if len(dubs) == 0 {
1214			continue
1215		}
1216		j := junk.New()
1217		j["@context"] = itiswhatitis
1218		j["type"] = "Add"
1219		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1220		j["actor"] = user.URL
1221		j["object"] = honk.XID
1222		j["target"] = fmt.Sprintf("https://%s/o/%s", ont[1:])
1223		rcpts := make(map[string]bool)
1224		for _, dub := range dubs {
1225			var box *Box
1226			ok := boxofboxes.Get(dub.XID, &box)
1227			if ok && box.Shared != "" {
1228				rcpts["%"+box.Shared] = true
1229			} else {
1230				rcpts[dub.XID] = true
1231			}
1232		}
1233		msg := j.ToBytes()
1234		for a := range rcpts {
1235			go deliverate(0, user.ID, a, msg)
1236		}
1237	}
1238}
1239
1240func junkuser(user *WhatAbout) []byte {
1241	about := markitzero(user.About)
1242
1243	j := junk.New()
1244	j["@context"] = itiswhatitis
1245	j["id"] = user.URL
1246	j["inbox"] = user.URL + "/inbox"
1247	j["outbox"] = user.URL + "/outbox"
1248	j["name"] = user.Display
1249	j["preferredUsername"] = user.Name
1250	j["summary"] = about
1251	if user.ID > 0 {
1252		j["type"] = "Person"
1253		j["url"] = user.URL
1254		j["followers"] = user.URL + "/followers"
1255		j["following"] = user.URL + "/following"
1256		a := junk.New()
1257		a["type"] = "Image"
1258		a["mediaType"] = "image/png"
1259		a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1260		j["icon"] = a
1261	} else {
1262		j["type"] = "Service"
1263	}
1264	k := junk.New()
1265	k["id"] = user.URL + "#key"
1266	k["owner"] = user.URL
1267	k["publicKeyPem"] = user.Key
1268	j["publicKey"] = k
1269
1270	return j.ToBytes()
1271}
1272
1273var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1274	user, err := butwhatabout(name)
1275	if err != nil {
1276		return nil, false
1277	}
1278	return junkuser(user), true
1279}, Duration: 1 * time.Minute})
1280
1281func asjonker(name string) ([]byte, bool) {
1282	var j []byte
1283	ok := oldjonkers.Get(name, &j)
1284	return j, ok
1285}
1286
1287var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1288	m := strings.Split(name, "@")
1289	if len(m) != 2 {
1290		log.Printf("bad fish name: %s", name)
1291		return "", true
1292	}
1293	row := stmtGetXonker.QueryRow(name, "fishname")
1294	var href string
1295	err := row.Scan(&href)
1296	if err == nil {
1297		return href, true
1298	}
1299	log.Printf("fishing for %s", name)
1300	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1301	if err != nil {
1302		log.Printf("failed to go fish %s: %s", name, err)
1303		return "", true
1304	}
1305	links, _ := j.GetArray("links")
1306	for _, li := range links {
1307		l, ok := li.(junk.Junk)
1308		if !ok {
1309			continue
1310		}
1311		href, _ := l.GetString("href")
1312		rel, _ := l.GetString("rel")
1313		t, _ := l.GetString("type")
1314		if rel == "self" && friendorfoe(t) {
1315			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1316			if err != nil {
1317				log.Printf("error saving fishname: %s", err)
1318			}
1319			return href, true
1320		}
1321	}
1322	return href, true
1323}})
1324
1325func gofish(name string) string {
1326	if name[0] == '@' {
1327		name = name[1:]
1328	}
1329	var href string
1330	handfull.Get(name, &href)
1331	return href
1332}
1333
1334func investigate(name string) (*SomeThing, error) {
1335	if name == "" {
1336		return nil, fmt.Errorf("no name")
1337	}
1338	if name[0] == '@' {
1339		name = gofish(name)
1340	}
1341	if name == "" {
1342		return nil, fmt.Errorf("no name")
1343	}
1344	obj, err := GetJunkFast(name)
1345	if err != nil {
1346		return nil, err
1347	}
1348	return somethingabout(obj)
1349}
1350
1351func somethingabout(obj junk.Junk) (*SomeThing, error) {
1352	info := new(SomeThing)
1353	t, _ := obj.GetString("type")
1354	switch t {
1355	case "Person":
1356		fallthrough
1357	case "Organization":
1358		fallthrough
1359	case "Application":
1360		fallthrough
1361	case "Service":
1362		info.What = SomeActor
1363	case "OrderedCollection":
1364		fallthrough
1365	case "Collection":
1366		info.What = SomeCollection
1367	default:
1368		return nil, fmt.Errorf("unknown object type")
1369	}
1370	info.XID, _ = obj.GetString("id")
1371	info.Name, _ = obj.GetString("preferredUsername")
1372	if info.Name == "" {
1373		info.Name, _ = obj.GetString("name")
1374	}
1375	info.Owner, _ = obj.GetString("attributedTo")
1376	if info.Owner == "" {
1377		info.Owner = info.XID
1378	}
1379	return info, nil
1380}