A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

820 linhas
21 KiB

  1. /*
  2. * Copyright © 2018-2020 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "bytes"
  13. "crypto/sha256"
  14. "database/sql"
  15. "encoding/base64"
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/http/httputil"
  21. "net/url"
  22. "strconv"
  23. "time"
  24. "github.com/gorilla/mux"
  25. "github.com/writeas/activity/streams"
  26. "github.com/writeas/httpsig"
  27. "github.com/writeas/impart"
  28. "github.com/writeas/nerds/store"
  29. "github.com/writeas/web-core/activitypub"
  30. "github.com/writeas/web-core/activitystreams"
  31. "github.com/writeas/web-core/log"
  32. )
  33. const (
  34. // TODO: delete. don't use this!
  35. apCustomHandleDefault = "blog"
  36. apCacheTime = time.Minute
  37. )
  38. type RemoteUser struct {
  39. ID int64
  40. ActorID string
  41. Inbox string
  42. SharedInbox string
  43. Handle string
  44. }
  45. func (ru *RemoteUser) AsPerson() *activitystreams.Person {
  46. return &activitystreams.Person{
  47. BaseObject: activitystreams.BaseObject{
  48. Type: "Person",
  49. Context: []interface{}{
  50. activitystreams.Namespace,
  51. },
  52. ID: ru.ActorID,
  53. },
  54. Inbox: ru.Inbox,
  55. Endpoints: activitystreams.Endpoints{
  56. SharedInbox: ru.SharedInbox,
  57. },
  58. }
  59. }
  60. func activityPubClient() *http.Client {
  61. return &http.Client{
  62. Timeout: 15 * time.Second,
  63. }
  64. }
  65. func handleFetchCollectionActivities(app *App, w http.ResponseWriter, r *http.Request) error {
  66. w.Header().Set("Server", serverSoftware)
  67. vars := mux.Vars(r)
  68. alias := vars["alias"]
  69. // TODO: enforce visibility
  70. // Get base Collection data
  71. var c *Collection
  72. var err error
  73. if app.cfg.App.SingleUser {
  74. c, err = app.db.GetCollectionByID(1)
  75. } else {
  76. c, err = app.db.GetCollection(alias)
  77. }
  78. if err != nil {
  79. return err
  80. }
  81. silenced, err := app.db.IsUserSilenced(c.OwnerID)
  82. if err != nil {
  83. log.Error("fetch collection activities: %v", err)
  84. return ErrInternalGeneral
  85. }
  86. if silenced {
  87. return ErrCollectionNotFound
  88. }
  89. c.hostName = app.cfg.App.Host
  90. p := c.PersonObject()
  91. setCacheControl(w, apCacheTime)
  92. return impart.RenderActivityJSON(w, p, http.StatusOK)
  93. }
  94. func handleFetchCollectionOutbox(app *App, w http.ResponseWriter, r *http.Request) error {
  95. w.Header().Set("Server", serverSoftware)
  96. vars := mux.Vars(r)
  97. alias := vars["alias"]
  98. // TODO: enforce visibility
  99. // Get base Collection data
  100. var c *Collection
  101. var err error
  102. if app.cfg.App.SingleUser {
  103. c, err = app.db.GetCollectionByID(1)
  104. } else {
  105. c, err = app.db.GetCollection(alias)
  106. }
  107. if err != nil {
  108. return err
  109. }
  110. silenced, err := app.db.IsUserSilenced(c.OwnerID)
  111. if err != nil {
  112. log.Error("fetch collection outbox: %v", err)
  113. return ErrInternalGeneral
  114. }
  115. if silenced {
  116. return ErrCollectionNotFound
  117. }
  118. c.hostName = app.cfg.App.Host
  119. if app.cfg.App.SingleUser {
  120. if alias != c.Alias {
  121. return ErrCollectionNotFound
  122. }
  123. }
  124. res := &CollectionObj{Collection: *c}
  125. app.db.GetPostsCount(res, false)
  126. accountRoot := c.FederatedAccount()
  127. page := r.FormValue("page")
  128. p, err := strconv.Atoi(page)
  129. if err != nil || p < 1 {
  130. // Return outbox
  131. oc := activitystreams.NewOrderedCollection(accountRoot, "outbox", res.TotalPosts)
  132. return impart.RenderActivityJSON(w, oc, http.StatusOK)
  133. }
  134. // Return outbox page
  135. ocp := activitystreams.NewOrderedCollectionPage(accountRoot, "outbox", res.TotalPosts, p)
  136. ocp.OrderedItems = []interface{}{}
  137. posts, err := app.db.GetPosts(app.cfg, c, p, false, true, false)
  138. for _, pp := range *posts {
  139. pp.Collection = res
  140. o := pp.ActivityObject(app)
  141. a := activitystreams.NewCreateActivity(o)
  142. a.Context = nil
  143. ocp.OrderedItems = append(ocp.OrderedItems, *a)
  144. }
  145. setCacheControl(w, apCacheTime)
  146. return impart.RenderActivityJSON(w, ocp, http.StatusOK)
  147. }
  148. func handleFetchCollectionFollowers(app *App, w http.ResponseWriter, r *http.Request) error {
  149. w.Header().Set("Server", serverSoftware)
  150. vars := mux.Vars(r)
  151. alias := vars["alias"]
  152. // TODO: enforce visibility
  153. // Get base Collection data
  154. var c *Collection
  155. var err error
  156. if app.cfg.App.SingleUser {
  157. c, err = app.db.GetCollectionByID(1)
  158. } else {
  159. c, err = app.db.GetCollection(alias)
  160. }
  161. if err != nil {
  162. return err
  163. }
  164. silenced, err := app.db.IsUserSilenced(c.OwnerID)
  165. if err != nil {
  166. log.Error("fetch collection followers: %v", err)
  167. return ErrInternalGeneral
  168. }
  169. if silenced {
  170. return ErrCollectionNotFound
  171. }
  172. c.hostName = app.cfg.App.Host
  173. accountRoot := c.FederatedAccount()
  174. folls, err := app.db.GetAPFollowers(c)
  175. if err != nil {
  176. return err
  177. }
  178. page := r.FormValue("page")
  179. p, err := strconv.Atoi(page)
  180. if err != nil || p < 1 {
  181. // Return outbox
  182. oc := activitystreams.NewOrderedCollection(accountRoot, "followers", len(*folls))
  183. return impart.RenderActivityJSON(w, oc, http.StatusOK)
  184. }
  185. // Return outbox page
  186. ocp := activitystreams.NewOrderedCollectionPage(accountRoot, "followers", len(*folls), p)
  187. ocp.OrderedItems = []interface{}{}
  188. /*
  189. for _, f := range *folls {
  190. ocp.OrderedItems = append(ocp.OrderedItems, f.ActorID)
  191. }
  192. */
  193. setCacheControl(w, apCacheTime)
  194. return impart.RenderActivityJSON(w, ocp, http.StatusOK)
  195. }
  196. func handleFetchCollectionFollowing(app *App, w http.ResponseWriter, r *http.Request) error {
  197. w.Header().Set("Server", serverSoftware)
  198. vars := mux.Vars(r)
  199. alias := vars["alias"]
  200. // TODO: enforce visibility
  201. // Get base Collection data
  202. var c *Collection
  203. var err error
  204. if app.cfg.App.SingleUser {
  205. c, err = app.db.GetCollectionByID(1)
  206. } else {
  207. c, err = app.db.GetCollection(alias)
  208. }
  209. if err != nil {
  210. return err
  211. }
  212. silenced, err := app.db.IsUserSilenced(c.OwnerID)
  213. if err != nil {
  214. log.Error("fetch collection following: %v", err)
  215. return ErrInternalGeneral
  216. }
  217. if silenced {
  218. return ErrCollectionNotFound
  219. }
  220. c.hostName = app.cfg.App.Host
  221. accountRoot := c.FederatedAccount()
  222. page := r.FormValue("page")
  223. p, err := strconv.Atoi(page)
  224. if err != nil || p < 1 {
  225. // Return outbox
  226. oc := activitystreams.NewOrderedCollection(accountRoot, "following", 0)
  227. return impart.RenderActivityJSON(w, oc, http.StatusOK)
  228. }
  229. // Return outbox page
  230. ocp := activitystreams.NewOrderedCollectionPage(accountRoot, "following", 0, p)
  231. ocp.OrderedItems = []interface{}{}
  232. setCacheControl(w, apCacheTime)
  233. return impart.RenderActivityJSON(w, ocp, http.StatusOK)
  234. }
  235. func handleFetchCollectionInbox(app *App, w http.ResponseWriter, r *http.Request) error {
  236. w.Header().Set("Server", serverSoftware)
  237. vars := mux.Vars(r)
  238. alias := vars["alias"]
  239. var c *Collection
  240. var err error
  241. if app.cfg.App.SingleUser {
  242. c, err = app.db.GetCollectionByID(1)
  243. } else {
  244. c, err = app.db.GetCollection(alias)
  245. }
  246. if err != nil {
  247. // TODO: return Reject?
  248. return err
  249. }
  250. silenced, err := app.db.IsUserSilenced(c.OwnerID)
  251. if err != nil {
  252. log.Error("fetch collection inbox: %v", err)
  253. return ErrInternalGeneral
  254. }
  255. if silenced {
  256. return ErrCollectionNotFound
  257. }
  258. c.hostName = app.cfg.App.Host
  259. if debugging {
  260. dump, err := httputil.DumpRequest(r, true)
  261. if err != nil {
  262. log.Error("Can't dump: %v", err)
  263. } else {
  264. log.Info("Rec'd! %q", dump)
  265. }
  266. }
  267. var m map[string]interface{}
  268. if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
  269. return err
  270. }
  271. a := streams.NewAccept()
  272. p := c.PersonObject()
  273. var to *url.URL
  274. var isFollow, isUnfollow bool
  275. fullActor := &activitystreams.Person{}
  276. var remoteUser *RemoteUser
  277. res := &streams.Resolver{
  278. FollowCallback: func(f *streams.Follow) error {
  279. isFollow = true
  280. // 1) Use the Follow concrete type here
  281. // 2) Errors are propagated to res.Deserialize call below
  282. m["@context"] = []string{activitystreams.Namespace}
  283. b, _ := json.Marshal(m)
  284. if debugging {
  285. log.Info("Follow: %s", b)
  286. }
  287. _, followID := f.GetId()
  288. if followID == nil {
  289. log.Error("Didn't resolve follow ID")
  290. } else {
  291. aID := c.FederatedAccount() + "#accept-" + store.GenerateFriendlyRandomString(20)
  292. acceptID, err := url.Parse(aID)
  293. if err != nil {
  294. log.Error("Couldn't parse generated Accept URL '%s': %v", aID, err)
  295. }
  296. a.SetId(acceptID)
  297. }
  298. a.AppendObject(f.Raw())
  299. _, to = f.GetActor(0)
  300. obj := f.Raw().GetObjectIRI(0)
  301. a.AppendActor(obj)
  302. // First get actor information
  303. if to == nil {
  304. return fmt.Errorf("No valid `to` string")
  305. }
  306. fullActor, remoteUser, err = getActor(app, to.String())
  307. if err != nil {
  308. return err
  309. }
  310. return impart.RenderActivityJSON(w, m, http.StatusOK)
  311. },
  312. UndoCallback: func(u *streams.Undo) error {
  313. isUnfollow = true
  314. m["@context"] = []string{activitystreams.Namespace}
  315. b, _ := json.Marshal(m)
  316. if debugging {
  317. log.Info("Undo: %s", b)
  318. }
  319. a.AppendObject(u.Raw())
  320. _, to = u.GetActor(0)
  321. // TODO: get actor from object.object, not object
  322. obj := u.Raw().GetObjectIRI(0)
  323. a.AppendActor(obj)
  324. if to != nil {
  325. // Populate fullActor from DB?
  326. remoteUser, err = getRemoteUser(app, to.String())
  327. if err != nil {
  328. if iErr, ok := err.(*impart.HTTPError); ok {
  329. if iErr.Status == http.StatusNotFound {
  330. log.Error("No remoteuser info for Undo event!")
  331. }
  332. }
  333. return err
  334. } else {
  335. fullActor = remoteUser.AsPerson()
  336. }
  337. } else {
  338. log.Error("No to on Undo!")
  339. }
  340. return impart.RenderActivityJSON(w, m, http.StatusOK)
  341. },
  342. }
  343. if err := res.Deserialize(m); err != nil {
  344. // 3) Any errors from #2 can be handled, or the payload is an unknown type.
  345. log.Error("Unable to resolve Follow: %v", err)
  346. if debugging {
  347. log.Error("Map: %s", m)
  348. }
  349. return err
  350. }
  351. go func() {
  352. if to == nil {
  353. log.Error("No to! %v", err)
  354. return
  355. }
  356. time.Sleep(2 * time.Second)
  357. am, err := a.Serialize()
  358. if err != nil {
  359. log.Error("Unable to serialize Accept: %v", err)
  360. return
  361. }
  362. am["@context"] = []string{activitystreams.Namespace}
  363. err = makeActivityPost(app.cfg.App.Host, p, fullActor.Inbox, am)
  364. if err != nil {
  365. log.Error("Unable to make activity POST: %v", err)
  366. return
  367. }
  368. if isFollow {
  369. t, err := app.db.Begin()
  370. if err != nil {
  371. log.Error("Unable to start transaction: %v", err)
  372. return
  373. }
  374. var followerID int64
  375. if remoteUser != nil {
  376. followerID = remoteUser.ID
  377. } else {
  378. // Add follower locally, since it wasn't found before
  379. res, err := t.Exec("INSERT INTO remoteusers (actor_id, inbox, shared_inbox) VALUES (?, ?, ?)", fullActor.ID, fullActor.Inbox, fullActor.Endpoints.SharedInbox)
  380. if err != nil {
  381. // if duplicate key, res will be nil and panic on
  382. // res.LastInsertId below
  383. t.Rollback()
  384. log.Error("Couldn't add new remoteuser in DB: %v\n", err)
  385. return
  386. }
  387. followerID, err = res.LastInsertId()
  388. if err != nil {
  389. t.Rollback()
  390. log.Error("no lastinsertid for followers, rolling back: %v", err)
  391. return
  392. }
  393. // Add in key
  394. _, err = t.Exec("INSERT INTO remoteuserkeys (id, remote_user_id, public_key) VALUES (?, ?, ?)", fullActor.PublicKey.ID, followerID, fullActor.PublicKey.PublicKeyPEM)
  395. if err != nil {
  396. if !app.db.isDuplicateKeyErr(err) {
  397. t.Rollback()
  398. log.Error("Couldn't add follower keys in DB: %v\n", err)
  399. return
  400. }
  401. }
  402. }
  403. // Add follow
  404. _, err = t.Exec("INSERT INTO remotefollows (collection_id, remote_user_id, created) VALUES (?, ?, "+app.db.now()+")", c.ID, followerID)
  405. if err != nil {
  406. if !app.db.isDuplicateKeyErr(err) {
  407. t.Rollback()
  408. log.Error("Couldn't add follower in DB: %v\n", err)
  409. return
  410. }
  411. }
  412. err = t.Commit()
  413. if err != nil {
  414. t.Rollback()
  415. log.Error("Rolling back after Commit(): %v\n", err)
  416. return
  417. }
  418. } else if isUnfollow {
  419. // Remove follower locally
  420. _, err = app.db.Exec("DELETE FROM remotefollows WHERE collection_id = ? AND remote_user_id = (SELECT id FROM remoteusers WHERE actor_id = ?)", c.ID, to.String())
  421. if err != nil {
  422. log.Error("Couldn't remove follower from DB: %v\n", err)
  423. }
  424. }
  425. }()
  426. return nil
  427. }
  428. func makeActivityPost(hostName string, p *activitystreams.Person, url string, m interface{}) error {
  429. log.Info("POST %s", url)
  430. b, err := json.Marshal(m)
  431. if err != nil {
  432. return err
  433. }
  434. r, _ := http.NewRequest("POST", url, bytes.NewBuffer(b))
  435. r.Header.Add("Content-Type", "application/activity+json")
  436. r.Header.Set("User-Agent", "Go ("+serverSoftware+"/"+softwareVer+"; +"+hostName+")")
  437. h := sha256.New()
  438. h.Write(b)
  439. r.Header.Add("Digest", "SHA-256="+base64.StdEncoding.EncodeToString(h.Sum(nil)))
  440. // Sign using the 'Signature' header
  441. privKey, err := activitypub.DecodePrivateKey(p.GetPrivKey())
  442. if err != nil {
  443. return err
  444. }
  445. signer := httpsig.NewSigner(p.PublicKey.ID, privKey, httpsig.RSASHA256, []string{"(request-target)", "date", "host", "digest"})
  446. err = signer.SignSigHeader(r)
  447. if err != nil {
  448. log.Error("Can't sign: %v", err)
  449. }
  450. if debugging {
  451. dump, err := httputil.DumpRequestOut(r, true)
  452. if err != nil {
  453. log.Error("Can't dump: %v", err)
  454. } else {
  455. log.Info("%s", dump)
  456. }
  457. }
  458. resp, err := activityPubClient().Do(r)
  459. if err != nil {
  460. return err
  461. }
  462. if resp != nil && resp.Body != nil {
  463. defer resp.Body.Close()
  464. }
  465. body, err := ioutil.ReadAll(resp.Body)
  466. if err != nil {
  467. return err
  468. }
  469. if debugging {
  470. log.Info("Status : %s", resp.Status)
  471. log.Info("Response: %s", body)
  472. }
  473. return nil
  474. }
  475. func resolveIRI(hostName, url string) ([]byte, error) {
  476. log.Info("GET %s", url)
  477. r, _ := http.NewRequest("GET", url, nil)
  478. r.Header.Add("Accept", "application/activity+json")
  479. r.Header.Set("User-Agent", "Go ("+serverSoftware+"/"+softwareVer+"; +"+hostName+")")
  480. if debugging {
  481. dump, err := httputil.DumpRequestOut(r, true)
  482. if err != nil {
  483. log.Error("Can't dump: %v", err)
  484. } else {
  485. log.Info("%s", dump)
  486. }
  487. }
  488. resp, err := activityPubClient().Do(r)
  489. if err != nil {
  490. return nil, err
  491. }
  492. if resp != nil && resp.Body != nil {
  493. defer resp.Body.Close()
  494. }
  495. body, err := ioutil.ReadAll(resp.Body)
  496. if err != nil {
  497. return nil, err
  498. }
  499. if debugging {
  500. log.Info("Status : %s", resp.Status)
  501. log.Info("Response: %s", body)
  502. }
  503. return body, nil
  504. }
  505. func deleteFederatedPost(app *App, p *PublicPost, collID int64) error {
  506. if debugging {
  507. log.Info("Deleting federated post!")
  508. }
  509. p.Collection.hostName = app.cfg.App.Host
  510. actor := p.Collection.PersonObject(collID)
  511. na := p.ActivityObject(app)
  512. // Add followers
  513. p.Collection.ID = collID
  514. followers, err := app.db.GetAPFollowers(&p.Collection.Collection)
  515. if err != nil {
  516. log.Error("Couldn't delete post (get followers)! %v", err)
  517. return err
  518. }
  519. inboxes := map[string][]string{}
  520. for _, f := range *followers {
  521. inbox := f.SharedInbox
  522. if inbox == "" {
  523. inbox = f.Inbox
  524. }
  525. if _, ok := inboxes[inbox]; ok {
  526. inboxes[inbox] = append(inboxes[inbox], f.ActorID)
  527. } else {
  528. inboxes[inbox] = []string{f.ActorID}
  529. }
  530. }
  531. for si, instFolls := range inboxes {
  532. na.CC = []string{}
  533. for _, f := range instFolls {
  534. na.CC = append(na.CC, f)
  535. }
  536. da := activitystreams.NewDeleteActivity(na)
  537. // Make the ID unique to ensure it works in Pleroma
  538. // See: https://git.pleroma.social/pleroma/pleroma/issues/1481
  539. da.ID += "#Delete"
  540. err = makeActivityPost(app.cfg.App.Host, actor, si, da)
  541. if err != nil {
  542. log.Error("Couldn't delete post! %v", err)
  543. }
  544. }
  545. return nil
  546. }
  547. func federatePost(app *App, p *PublicPost, collID int64, isUpdate bool) error {
  548. if debugging {
  549. if isUpdate {
  550. log.Info("Federating updated post!")
  551. } else {
  552. log.Info("Federating new post!")
  553. }
  554. }
  555. actor := p.Collection.PersonObject(collID)
  556. na := p.ActivityObject(app)
  557. // Add followers
  558. p.Collection.ID = collID
  559. followers, err := app.db.GetAPFollowers(&p.Collection.Collection)
  560. if err != nil {
  561. log.Error("Couldn't post! %v", err)
  562. return err
  563. }
  564. log.Info("Followers for %d: %+v", collID, followers)
  565. inboxes := map[string][]string{}
  566. for _, f := range *followers {
  567. inbox := f.SharedInbox
  568. if inbox == "" {
  569. inbox = f.Inbox
  570. }
  571. if _, ok := inboxes[inbox]; ok {
  572. // check if we're already sending to this shared inbox
  573. inboxes[inbox] = append(inboxes[inbox], f.ActorID)
  574. } else {
  575. // add the new shared inbox to the list
  576. inboxes[inbox] = []string{f.ActorID}
  577. }
  578. }
  579. var activity *activitystreams.Activity
  580. // for each one of the shared inboxes
  581. for si, instFolls := range inboxes {
  582. // add all followers from that instance
  583. // to the CC field
  584. na.CC = []string{}
  585. for _, f := range instFolls {
  586. na.CC = append(na.CC, f)
  587. }
  588. // create a new "Create" activity
  589. // with our article as object
  590. if isUpdate {
  591. activity = activitystreams.NewUpdateActivity(na)
  592. } else {
  593. activity = activitystreams.NewCreateActivity(na)
  594. activity.To = na.To
  595. activity.CC = na.CC
  596. }
  597. // and post it to that sharedInbox
  598. err = makeActivityPost(app.cfg.App.Host, actor, si, activity)
  599. if err != nil {
  600. log.Error("Couldn't post! %v", err)
  601. }
  602. }
  603. // re-create the object so that the CC list gets reset and has
  604. // the mentioned users. This might seem wasteful but the code is
  605. // cleaner than adding the mentioned users to CC here instead of
  606. // in p.ActivityObject()
  607. na = p.ActivityObject(app)
  608. for _, tag := range na.Tag {
  609. if tag.Type == "Mention" {
  610. activity = activitystreams.NewCreateActivity(na)
  611. activity.To = na.To
  612. activity.CC = na.CC
  613. // This here might be redundant in some cases as we might have already
  614. // sent this to the sharedInbox of this instance above, but we need too
  615. // much logic to catch this at the expense of the odd extra request.
  616. // I don't believe we'd ever have too many mentions in a single post that this
  617. // could become a burden.
  618. remoteUser, err := getRemoteUser(app, tag.HRef)
  619. err = makeActivityPost(app.cfg.App.Host, actor, remoteUser.Inbox, activity)
  620. if err != nil {
  621. log.Error("Couldn't post! %v", err)
  622. }
  623. }
  624. }
  625. return nil
  626. }
  627. func getRemoteUser(app *App, actorID string) (*RemoteUser, error) {
  628. u := RemoteUser{ActorID: actorID}
  629. var handle sql.NullString
  630. err := app.db.QueryRow("SELECT id, inbox, shared_inbox, handle FROM remoteusers WHERE actor_id = ?", actorID).Scan(&u.ID, &u.Inbox, &u.SharedInbox, &handle)
  631. switch {
  632. case err == sql.ErrNoRows:
  633. return nil, impart.HTTPError{http.StatusNotFound, "No remote user with that ID."}
  634. case err != nil:
  635. log.Error("Couldn't get remote user %s: %v", actorID, err)
  636. return nil, err
  637. }
  638. u.Handle = handle.String
  639. return &u, nil
  640. }
  641. // getRemoteUserFromHandle retrieves the profile page of a remote user
  642. // from the @user@server.tld handle
  643. func getRemoteUserFromHandle(app *App, handle string) (*RemoteUser, error) {
  644. u := RemoteUser{Handle: handle}
  645. err := app.db.QueryRow("SELECT id, actor_id, inbox, shared_inbox FROM remoteusers WHERE handle = ?", handle).Scan(&u.ID, &u.ActorID, &u.Inbox, &u.SharedInbox)
  646. switch {
  647. case err == sql.ErrNoRows:
  648. return nil, ErrRemoteUserNotFound
  649. case err != nil:
  650. log.Error("Couldn't get remote user %s: %v", handle, err)
  651. return nil, err
  652. }
  653. return &u, nil
  654. }
  655. func getActor(app *App, actorIRI string) (*activitystreams.Person, *RemoteUser, error) {
  656. log.Info("Fetching actor %s locally", actorIRI)
  657. actor := &activitystreams.Person{}
  658. remoteUser, err := getRemoteUser(app, actorIRI)
  659. if err != nil {
  660. if iErr, ok := err.(impart.HTTPError); ok {
  661. if iErr.Status == http.StatusNotFound {
  662. // Fetch remote actor
  663. log.Info("Not found; fetching actor %s remotely", actorIRI)
  664. actorResp, err := resolveIRI(app.cfg.App.Host, actorIRI)
  665. if err != nil {
  666. log.Error("Unable to get actor! %v", err)
  667. return nil, nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't fetch actor."}
  668. }
  669. if err := unmarshalActor(actorResp, actor); err != nil {
  670. log.Error("Unable to unmarshal actor! %v", err)
  671. return nil, nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't parse actor."}
  672. }
  673. } else {
  674. return nil, nil, err
  675. }
  676. } else {
  677. return nil, nil, err
  678. }
  679. } else {
  680. actor = remoteUser.AsPerson()
  681. }
  682. return actor, remoteUser, nil
  683. }
  684. // unmarshal actor normalizes the actor response to conform to
  685. // the type Person from github.com/writeas/web-core/activitysteams
  686. //
  687. // some implementations return different context field types
  688. // this converts any non-slice contexts into a slice
  689. func unmarshalActor(actorResp []byte, actor *activitystreams.Person) error {
  690. // FIXME: Hubzilla has an object for the Actor's url: cannot unmarshal object into Go struct field Person.url of type string
  691. // flexActor overrides the Context field to allow
  692. // all valid representations during unmarshal
  693. flexActor := struct {
  694. activitystreams.Person
  695. Context json.RawMessage `json:"@context,omitempty"`
  696. }{}
  697. if err := json.Unmarshal(actorResp, &flexActor); err != nil {
  698. return err
  699. }
  700. actor.Endpoints = flexActor.Endpoints
  701. actor.Followers = flexActor.Followers
  702. actor.Following = flexActor.Following
  703. actor.ID = flexActor.ID
  704. actor.Icon = flexActor.Icon
  705. actor.Inbox = flexActor.Inbox
  706. actor.Name = flexActor.Name
  707. actor.Outbox = flexActor.Outbox
  708. actor.PreferredUsername = flexActor.PreferredUsername
  709. actor.PublicKey = flexActor.PublicKey
  710. actor.Summary = flexActor.Summary
  711. actor.Type = flexActor.Type
  712. actor.URL = flexActor.URL
  713. func(val interface{}) {
  714. switch val.(type) {
  715. case []interface{}:
  716. // already a slice, do nothing
  717. actor.Context = val.([]interface{})
  718. default:
  719. actor.Context = []interface{}{val}
  720. }
  721. }(flexActor.Context)
  722. return nil
  723. }
  724. func setCacheControl(w http.ResponseWriter, ttl time.Duration) {
  725. w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.0f", ttl.Seconds()))
  726. }