all repos — honk @ dea3cb9d2c80622a1ff6273f60ac0fa87e0d3847

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