all repos — honk @ c2664b500d197b9cecf1a8adb0fca2c6705cb687

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					dura, _ := obj.GetString("duration")
 721					if strings.HasPrefix(dura, "PT") {
 722						dura = strings.ToLower(dura[2:])
 723						d, _ := time.ParseDuration(dura)
 724						t.Duration = Duration(d)
 725					}
 726					xonk.Time = t
 727				}
 728			}
 729			loca, ok := obj.GetMap("location")
 730			if ok {
 731				tt, _ := loca.GetString("type")
 732				name, _ := loca.GetString("name")
 733				if tt == "Place" {
 734					p := new(Place)
 735					p.Name = name
 736					p.Latitude, _ = loca["latitude"].(float64)
 737					p.Longitude, _ = loca["longitude"].(float64)
 738					p.Url, _ = loca.GetString("url")
 739					xonk.Place = p
 740				}
 741			}
 742
 743			xonk.Onts = oneofakind(xonk.Onts)
 744			replyobj, ok := obj.GetMap("replies")
 745			if ok {
 746				items, ok := replyobj.GetArray("items")
 747				if !ok {
 748					first, ok := replyobj.GetMap("first")
 749					if ok {
 750						items, _ = first.GetArray("items")
 751					}
 752				}
 753				for _, repl := range items {
 754					s, ok := repl.(string)
 755					if ok {
 756						replies = append(replies, s)
 757					}
 758				}
 759			}
 760
 761		}
 762		if originate(xid) != origin {
 763			log.Printf("original sin: %s <> %s", xid, origin)
 764			item.Write(os.Stdout)
 765			return nil
 766		}
 767
 768		if currenttid == "" {
 769			currenttid = convoy
 770		}
 771
 772		if len(content) > 90001 {
 773			log.Printf("content too long. truncating")
 774			content = content[:90001]
 775		}
 776
 777		// grab any inline imgs
 778		imgfilt := htfilter.New()
 779		imgfilt.Imager = inlineimgs
 780		imgfilt.String(content)
 781
 782		// init xonk
 783		xonk.What = what
 784		xonk.XID = xid
 785		xonk.RID = rid
 786		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 787		xonk.URL = url
 788		xonk.Noise = content
 789		xonk.Precis = precis
 790		xonk.Format = "html"
 791		xonk.Convoy = convoy
 792
 793		if isUpdate {
 794			log.Printf("something has changed! %s", xonk.XID)
 795			prev := getxonk(user.ID, xonk.XID)
 796			if prev == nil {
 797				log.Printf("didn't find old version for update: %s", xonk.XID)
 798				return nil
 799			}
 800			prev.Noise = xonk.Noise
 801			prev.Precis = xonk.Precis
 802			prev.Date = xonk.Date
 803			prev.Donks = xonk.Donks
 804			prev.Onts = xonk.Onts
 805			prev.Place = xonk.Place
 806			updatehonk(prev)
 807		} else if needxonk(user, &xonk) {
 808			if rid != "" {
 809				if needxonkid(user, rid) {
 810					goingup++
 811					saveonemore(rid)
 812					goingup--
 813				}
 814				if convoy == "" {
 815					xx := getxonk(user.ID, rid)
 816					if xx != nil {
 817						convoy = xx.Convoy
 818					}
 819				}
 820			}
 821			if convoy == "" {
 822				convoy = currenttid
 823			}
 824			savexonk(&xonk)
 825		}
 826		if goingup == 0 {
 827			for _, replid := range replies {
 828				if needxonkid(user, replid) {
 829					log.Printf("missing a reply: %s", replid)
 830					saveonemore(replid)
 831				}
 832			}
 833		}
 834		return &xonk
 835	}
 836
 837	return xonkxonkfn(item, origin)
 838}
 839
 840func rubadubdub(user *WhatAbout, req junk.Junk) {
 841	xid, _ := req.GetString("id")
 842	actor, _ := req.GetString("actor")
 843	j := junk.New()
 844	j["@context"] = itiswhatitis
 845	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 846	j["type"] = "Accept"
 847	j["actor"] = user.URL
 848	j["to"] = actor
 849	j["published"] = time.Now().UTC().Format(time.RFC3339)
 850	j["object"] = req
 851
 852	var buf bytes.Buffer
 853	j.Write(&buf)
 854	msg := buf.Bytes()
 855
 856	deliverate(0, user.Name, actor, msg)
 857}
 858
 859func itakeitallback(user *WhatAbout, xid string) {
 860	j := junk.New()
 861	j["@context"] = itiswhatitis
 862	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 863	j["type"] = "Undo"
 864	j["actor"] = user.URL
 865	j["to"] = xid
 866	f := junk.New()
 867	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 868	f["type"] = "Follow"
 869	f["actor"] = user.URL
 870	f["to"] = xid
 871	f["object"] = xid
 872	j["object"] = f
 873	j["published"] = time.Now().UTC().Format(time.RFC3339)
 874
 875	var buf bytes.Buffer
 876	j.Write(&buf)
 877	msg := buf.Bytes()
 878
 879	deliverate(0, user.Name, xid, msg)
 880}
 881
 882func subsub(user *WhatAbout, xid string) {
 883	j := junk.New()
 884	j["@context"] = itiswhatitis
 885	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 886	j["type"] = "Follow"
 887	j["actor"] = user.URL
 888	j["to"] = xid
 889	j["object"] = xid
 890	j["published"] = time.Now().UTC().Format(time.RFC3339)
 891
 892	var buf bytes.Buffer
 893	j.Write(&buf)
 894	msg := buf.Bytes()
 895
 896	deliverate(0, user.Name, xid, msg)
 897}
 898
 899// returns activity, object
 900func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 901	dt := h.Date.Format(time.RFC3339)
 902	var jo junk.Junk
 903	j := junk.New()
 904	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 905	j["actor"] = user.URL
 906	j["published"] = dt
 907	if h.Public {
 908		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 909	} else {
 910		j["to"] = h.Audience[0]
 911	}
 912	if len(h.Audience) > 1 {
 913		j["cc"] = h.Audience[1:]
 914	}
 915
 916	switch h.What {
 917	case "update":
 918		fallthrough
 919	case "tonk":
 920		fallthrough
 921	case "event":
 922		fallthrough
 923	case "honk":
 924		j["type"] = "Create"
 925		if h.What == "update" {
 926			j["type"] = "Update"
 927		}
 928
 929		jo = junk.New()
 930		jo["id"] = h.XID
 931		jo["type"] = "Note"
 932		if h.What == "event" {
 933			jo["type"] = "Event"
 934		}
 935		jo["published"] = dt
 936		jo["url"] = h.XID
 937		jo["attributedTo"] = user.URL
 938		if h.RID != "" {
 939			jo["inReplyTo"] = h.RID
 940		}
 941		if h.Convoy != "" {
 942			jo["context"] = h.Convoy
 943			jo["conversation"] = h.Convoy
 944		}
 945		jo["to"] = h.Audience[0]
 946		if len(h.Audience) > 1 {
 947			jo["cc"] = h.Audience[1:]
 948		}
 949		if !h.Public {
 950			jo["directMessage"] = true
 951		}
 952		translate(h)
 953		h.Noise = re_memes.ReplaceAllString(h.Noise, "")
 954		jo["summary"] = h.Precis
 955		jo["content"] = ontologize(mentionize(h.Noise))
 956		if strings.HasPrefix(h.Precis, "DZ:") {
 957			jo["sensitive"] = true
 958		}
 959
 960		var replies []string
 961		for _, reply := range h.Replies {
 962			replies = append(replies, reply.XID)
 963		}
 964		if len(replies) > 0 {
 965			jr := junk.New()
 966			jr["type"] = "Collection"
 967			jr["totalItems"] = len(replies)
 968			jr["items"] = replies
 969			jo["replies"] = jr
 970		}
 971
 972		var tags []junk.Junk
 973		g := bunchofgrapes(h.Noise)
 974		for _, m := range g {
 975			t := junk.New()
 976			t["type"] = "Mention"
 977			t["name"] = m.who
 978			t["href"] = m.where
 979			tags = append(tags, t)
 980		}
 981		for _, o := range h.Onts {
 982			t := junk.New()
 983			t["type"] = "Hashtag"
 984			o = strings.ToLower(o)
 985			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
 986			t["name"] = o
 987			tags = append(tags, t)
 988		}
 989		herd := herdofemus(h.Noise)
 990		for _, e := range herd {
 991			t := junk.New()
 992			t["id"] = e.ID
 993			t["type"] = "Emoji"
 994			t["name"] = e.Name
 995			i := junk.New()
 996			i["type"] = "Image"
 997			i["mediaType"] = "image/png"
 998			i["url"] = e.ID
 999			t["icon"] = i
1000			tags = append(tags, t)
1001		}
1002		if p := h.Place; p != nil {
1003			t := junk.New()
1004			t["type"] = "Place"
1005			t["name"] = p.Name
1006			t["latitude"] = p.Latitude
1007			t["longitude"] = p.Longitude
1008			t["url"] = p.Url
1009			tags = append(tags, t)
1010		}
1011		if len(tags) > 0 {
1012			jo["tag"] = tags
1013		}
1014		if t := h.Time; t != nil {
1015			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1016			if t.Duration != 0 {
1017				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1018			}
1019		}
1020		var atts []junk.Junk
1021		for _, d := range h.Donks {
1022			if re_emus.MatchString(d.Name) {
1023				continue
1024			}
1025			jd := junk.New()
1026			jd["mediaType"] = d.Media
1027			jd["name"] = d.Name
1028			jd["summary"] = d.Desc
1029			jd["type"] = "Document"
1030			jd["url"] = d.URL
1031			atts = append(atts, jd)
1032		}
1033		if len(atts) > 0 {
1034			jo["attachment"] = atts
1035		}
1036		j["object"] = jo
1037	case "bonk":
1038		j["type"] = "Announce"
1039		if h.Convoy != "" {
1040			j["context"] = h.Convoy
1041		}
1042		j["object"] = h.XID
1043	case "unbonk":
1044		b := junk.New()
1045		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1046		b["type"] = "Announce"
1047		b["actor"] = user.URL
1048		if h.Convoy != "" {
1049			b["context"] = h.Convoy
1050		}
1051		b["object"] = h.XID
1052		j["type"] = "Undo"
1053		j["object"] = b
1054	case "zonk":
1055		j["type"] = "Delete"
1056		j["object"] = h.XID
1057	case "ack":
1058		j["type"] = "Read"
1059		j["object"] = h.XID
1060	case "deack":
1061		b := junk.New()
1062		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1063		b["type"] = "Read"
1064		b["actor"] = user.URL
1065		b["object"] = h.XID
1066		j["type"] = "Undo"
1067		j["object"] = b
1068	}
1069
1070	return j, jo
1071}
1072
1073func honkworldwide(user *WhatAbout, honk *Honk) {
1074	jonk, _ := jonkjonk(user, honk)
1075	jonk["@context"] = itiswhatitis
1076	var buf bytes.Buffer
1077	jonk.Write(&buf)
1078	msg := buf.Bytes()
1079
1080	rcpts := make(map[string]bool)
1081	for _, a := range honk.Audience {
1082		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1083			continue
1084		}
1085		box, _ := getboxes(a)
1086		if box != nil && honk.Public && box.Shared != "" {
1087			rcpts["%"+box.Shared] = true
1088		} else {
1089			rcpts[a] = true
1090		}
1091	}
1092	if honk.Public {
1093		for _, f := range getdubs(user.ID) {
1094			if f.XID == user.URL {
1095				continue
1096			}
1097			box, _ := getboxes(f.XID)
1098			if box != nil && box.Shared != "" {
1099				rcpts["%"+box.Shared] = true
1100			} else {
1101				rcpts[f.XID] = true
1102			}
1103		}
1104	}
1105	for a := range rcpts {
1106		go deliverate(0, user.Name, a, msg)
1107	}
1108}
1109
1110func asjonker(user *WhatAbout) junk.Junk {
1111	about := obfusbreak(user.About)
1112
1113	j := junk.New()
1114	j["@context"] = itiswhatitis
1115	j["id"] = user.URL
1116	j["type"] = "Person"
1117	j["inbox"] = user.URL + "/inbox"
1118	j["outbox"] = user.URL + "/outbox"
1119	j["followers"] = user.URL + "/followers"
1120	j["following"] = user.URL + "/following"
1121	j["name"] = user.Display
1122	j["preferredUsername"] = user.Name
1123	j["summary"] = about
1124	j["url"] = user.URL
1125	a := junk.New()
1126	a["type"] = "Image"
1127	a["mediaType"] = "image/png"
1128	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1129	j["icon"] = a
1130	k := junk.New()
1131	k["id"] = user.URL + "#key"
1132	k["owner"] = user.URL
1133	k["publicKeyPem"] = user.Key
1134	j["publicKey"] = k
1135
1136	return j
1137}
1138
1139var handfull = make(map[string]string)
1140var handlock sync.Mutex
1141
1142func gofish(name string) string {
1143	if name[0] == '@' {
1144		name = name[1:]
1145	}
1146	m := strings.Split(name, "@")
1147	if len(m) != 2 {
1148		log.Printf("bad fish name: %s", name)
1149		return ""
1150	}
1151	handlock.Lock()
1152	ref, ok := handfull[name]
1153	handlock.Unlock()
1154	if ok {
1155		return ref
1156	}
1157	row := stmtGetXonker.QueryRow(name, "fishname")
1158	var href string
1159	err := row.Scan(&href)
1160	if err == nil {
1161		handlock.Lock()
1162		handfull[name] = href
1163		handlock.Unlock()
1164		return href
1165	}
1166	log.Printf("fishing for %s", name)
1167	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1168	if err != nil {
1169		log.Printf("failed to go fish %s: %s", name, err)
1170		handlock.Lock()
1171		handfull[name] = ""
1172		handlock.Unlock()
1173		return ""
1174	}
1175	links, _ := j.GetArray("links")
1176	for _, li := range links {
1177		l, ok := li.(junk.Junk)
1178		if !ok {
1179			continue
1180		}
1181		href, _ := l.GetString("href")
1182		rel, _ := l.GetString("rel")
1183		t, _ := l.GetString("type")
1184		if rel == "self" && friendorfoe(t) {
1185			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1186			if err != nil {
1187				log.Printf("error saving fishname: %s", err)
1188			}
1189			handlock.Lock()
1190			handfull[name] = href
1191			handlock.Unlock()
1192			return href
1193		}
1194	}
1195	handlock.Lock()
1196	handfull[name] = ""
1197	handlock.Unlock()
1198	return ""
1199}
1200
1201func isactor(t string) bool {
1202	switch t {
1203	case "Person":
1204	case "Organization":
1205	case "Application":
1206	case "Service":
1207	default:
1208		return false
1209	}
1210	return true
1211}
1212
1213func investigate(name string) (*Honker, error) {
1214	if name == "" {
1215		return nil, fmt.Errorf("no name")
1216	}
1217	if name[0] == '@' {
1218		name = gofish(name)
1219	}
1220	if name == "" {
1221		return nil, fmt.Errorf("no name")
1222	}
1223	log.Printf("digging up some info on %s", name)
1224	obj, err := GetJunkFast(name)
1225	if err != nil {
1226		log.Printf("error investigating honker: %s", err)
1227		return nil, err
1228	}
1229	t, _ := obj.GetString("type")
1230	if !isactor(t) {
1231		log.Printf("it's not a person! %s", name)
1232		return nil, err
1233	}
1234	xid, _ := obj.GetString("id")
1235	handle, _ := obj.GetString("preferredUsername")
1236	return &Honker{XID: xid, Handle: handle}, nil
1237}