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