UNPKG

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