all repos — honk @ 5d1d335ed23a42ecbdfc6a38265d53bd6488345a

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