git ssb

1+

Daan Patchwork / patchwork



Tree: 4d9f238ff73f7136cd292da88f06c17fe1a8c445

Files: 4d9f238ff73f7136cd292da88f06c17fe1a8c445 / lib / depject / invite / invite.js

2915 bytesRaw
1'use strict'
2const ref = require('ssb-ref')
3const ssbClient = require('ssb-client')
4const roomUtils = require('ssb-room/utils')
5const Value = require('mutant/value')
6const nest = require('depnest')
7
8exports.needs = nest({
9 'sbot.async.publish': 'first',
10 'sbot.async.connRememberConnect': 'first',
11 'sbot.async.acceptDHT': 'first',
12 'contact.async.followerOf': 'first',
13 'keys.sync.id': 'first',
14 'config.sync.load': 'first'
15})
16
17exports.gives = nest({
18 'invite.async.accept': true,
19 'invite.async.autofollow': true
20})
21
22exports.create = function (api) {
23 function accept (invite, cb) {
24 const progress = Value('Connecting...')
25
26 if (roomUtils.isInvite(invite)) {
27 const address = roomUtils.inviteToAddress(invite)
28 api.sbot.async.connRememberConnect(address, { type: 'room' }, cb)
29 return
30 }
31 if (invite.startsWith('dht:')) {
32 api.sbot.async.acceptDHT(invite, () => {})
33 return cb(null, true)
34 }
35
36 const data = ref.parseInvite(invite)
37 const id = api.keys.sync.id()
38 const config = api.config.sync.load()
39
40 if (!data) return cb(new Error('Not a valid invite code. Please make sure you copied the entire code and try again.'))
41
42 api.sbot.async.connRememberConnect(data.remote, { type: 'pub' }, (err) => {
43 if (err) console.log(err)
44 })
45
46 // connect to the remote pub using the invite code
47 ssbClient(null, {
48 remote: data.invite,
49 manifest: { invite: { use: 'async' }, getAddress: 'async' },
50 appKey: config.caps && config.caps.shs
51 }, function (err, sbot) {
52 if (err) return cb(err)
53 progress.set('Requesting follow...')
54
55 // ask them to follow us
56 sbot.invite.use({ feed: id }, function (err) {
57 if (err) {
58 // the probably already follow us
59 api.contact.async.followerOf(id, data.key, function (_, follows) {
60 if (follows) {
61 cb()
62 } else {
63 next()
64 }
65 })
66 } else {
67 next()
68 }
69 })
70 })
71
72 function next () {
73 progress.set('Following...')
74
75 const address = ref.parseAddress(data.remote)
76
77 if (address.host) {
78 api.sbot.async.publish({
79 type: 'pub',
80 address
81 })
82 }
83
84 api.sbot.async.publish({
85 type: 'contact',
86 contact: data.key,
87 following: true,
88 autofollow: true
89 }, cb)
90 }
91
92 return progress
93 }
94 return nest({
95 'invite.async.accept': accept,
96 // like invite, but check whether we already follow them first
97 'invite.async.autofollow': function (invite, cb) {
98 const id = api.keys.sync.id()
99 const data = ref.parseInvite(invite)
100 api.contact.async.followerOf(id, data.key, function (_, follows) {
101 if (follows) console.log('already following', cb())
102 else console.log('accept invite:' + invite, accept(invite, cb))
103 })
104 }
105 })
106}
107

Built with git-ssb-web