1 | const Promise = require('bluebird');
|
2 |
|
3 | module.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 |
|
9 |
|
10 |
|
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 |
|
29 |
|
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 |
|
52 |
|
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 | };
|