UNPKG

2.03 kBJavaScriptView Raw
1const About = require('ssb-ooo-about');
2const Promise = require('bluebird');
3
4module.exports = (sbot, myIdent) => {
5 const about = About(sbot, {});
6 const getLatestAboutMsgIds = Promise.promisify(about.async.getLatestMsgIds);
7
8 function inviteToPlay(invitingPubKey, asWhite, rematchFromGameId) {
9 return new Promise((resolve, reject) => {
10 // Give some messages that give both player's latest 'about' messages
11 // so that their name (about about) can be displayed to spectators who
12 // don't have one of the players in their follow graph using ssb-ooo.
13 const aboutMsgs = Promise.all(
14 [
15 getLatestAboutMsgIds(invitingPubKey),
16 getLatestAboutMsgIds(myIdent),
17 ],
18 ).then(arr => arr.reduce((a, b) => a.concat(b), []));
19
20 aboutMsgs.then((aboutInfo) => {
21 const post = {
22 type: 'chess_invite',
23 inviting: invitingPubKey,
24 myColor: asWhite ? 'white' : 'black',
25 };
26
27 if (rematchFromGameId) {
28 post.root = rematchFromGameId;
29
30 // TODO: Make this branch off the previous game's 'chess_game_end'
31 // message to support ssb-ooo. Not important for now.
32 }
33
34 if (aboutInfo && aboutInfo.length != 0) {
35 post.branch = aboutInfo;
36 }
37
38 sbot.publish(post, (err, msg) => {
39 if (err) {
40 reject(err);
41 } else {
42 resolve(msg);
43 }
44 });
45 });
46 });
47 }
48
49 function acceptChallenge(gameRootMessage) {
50 const post = {
51 type: 'chess_invite_accept',
52 root: gameRootMessage,
53 // Used for ssb-ooo which allows clients to request messages from peers
54 // that are outside their follow graph.
55 branch: gameRootMessage,
56 };
57
58 return new Promise((resolve, reject) => {
59 sbot.publish(post, (err, msg) => {
60 if (err) {
61 reject(err);
62 } else {
63 resolve(msg);
64 }
65 });
66 });
67 }
68
69 return {
70 inviteToPlay,
71 acceptChallenge
72 };
73};