Poll implementation

This commit is contained in:
purpshell
2022-12-23 12:37:07 +02:00
parent 288a572af6
commit a519105870
6 changed files with 184 additions and 49 deletions

View File

@@ -6,6 +6,7 @@ const Location = require('./Location');
const Order = require('./Order');
const Payment = require('./Payment');
const { MessageTypes } = require('../util/Constants');
const PollVote = require('./PollVote');
/**
* Represents a Message on WhatsApp
@@ -240,6 +241,19 @@ class Message extends Base {
this.selectedRowId = data.listResponse.singleSelectReply.selectedRowId;
}
if (this.type == MessageTypes.POLL_CREATION) {
/** Selectable poll options */
this.pollOptions = data.pollOptions.map(option => {
return option.name;
});
/** Current poll votes, refresh with Message.refreshPollVotes() */
this.pollVotes = data.pollVotes.map((pollVote) => {
return new PollVote(this.client, pollVote);
});
}
return super._patch(data);
}
@@ -527,6 +541,34 @@ class Message extends Base {
}
return undefined;
}
/**
* Refresh the current poll votes
* @returns {Promise<void>}
*/
async refreshPollVotes() {
if (this.type != MessageTypes.POLL_CREATION) throw 'Invalid usage! Can only be used with a pollCreation message';
const pollVotes = await this.client.evaluate((parentMsgId) => {
return Store.PollVote.getForParent(parentMsgId).getModelsArray().map(a => a.serialize())
}, this.id);
this.pollVotes = pollVotes.map((pollVote) => {
return new PollVote(this.client, pollVote);
});
return;
}
/**
* Vote to the poll.
* @param {Array<string>} selectedOptions Array of options selected.
* @returns {Promise<void>}
*/
async vote(selectedOptions) {
if (this.type != MessageTypes.POLL_CREATION) throw 'Invalid usage! Can only be used with a pollCreation message';
return this.client.evaluate((creationMsgId, selectedOptions) => {
window.WWebJS.votePoll(creationMsgId, selectedOptions);
}, this.id, selectedOptions);
}
}
module.exports = Message;

View File

@@ -0,0 +1,32 @@
'use strict';
const Base = require('./Base');
/**
* Represents a Poll Vote on WhatsApp
* @extends {Base}
*/
class PollVote extends Base {
constructor(client, data) {
super(client);
if (data) this._patch(data);
}
_patch(data) {
/** The options selected in this Poll vote */
this.selectedOptions = data.selectedOptionLocalIds.filter(value => value == 1).map((value, selectedOptionLocalId) => {
return data.pollCreationMessage.pollOptions.find(a => a.localId == selectedOptionLocalId).name;
});
/** Sender of the Poll vote */
this.sender = data.sender;
/** Timestamp of the time it was sent in milliseconds */
this.senderTimestampMs = data.senderTimestampMs;
return super._patch(data);
}
}
module.exports = PollVote;