A platform for community discussion. Free, open, simple.
FEATURE: automatically close a poll on a given date and time
Régis Hanolba14c80b9c7a
diff --git a/app/assets/stylesheets/common/base/modal.scss b/app/assets/stylesheets/common/base/modal.scssindex cd5fe5fabb3..d1d4144c366 100644--- a/app/assets/stylesheets/common/base/modal.scss+++ b/app/assets/stylesheets/common/base/modal.scss@@ -426,21 +426,24 @@}}-.change-timestamp {+.change-timestamp,+.poll-ui-builder {.date-picker {- width: 10em;+ width: 9em;}#date-container {.pika-single {position: relative !important; // overriding another importantdisplay: inline-block;+ margin-top: 5px;}}input[type=time] {width: 6em;+ text-align: center;}form {diff --git a/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6 b/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6index 3a822f139aa..ab97861dfce 100644--- a/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6+++ b/plugins/poll/assets/javascripts/controllers/poll-ui-builder.js.es6@@ -13,13 +13,11 @@ export default Ember.Controller.extend({@computed("regularPollType", "numberPollType", "multiplePollType")pollTypes(regularPollType, numberPollType, multiplePollType) {- let types = [];-- types.push({ name: I18n.t("poll.ui_builder.poll_type.regular"), value: regularPollType });- types.push({ name: I18n.t("poll.ui_builder.poll_type.number"), value: numberPollType });- types.push({ name: I18n.t("poll.ui_builder.poll_type.multiple"), value: multiplePollType });-- return types;+ return [+ { name: I18n.t("poll.ui_builder.poll_type.regular"), value: regularPollType },+ { name: I18n.t("poll.ui_builder.poll_type.number"), value: numberPollType },+ { name: I18n.t("poll.ui_builder.poll_type.multiple"), value: multiplePollType },+ ];},@computed("pollType", "regularPollType")@@ -101,8 +99,8 @@ export default Ember.Controller.extend({return this._comboboxOptions(1, (parseInt(pollMax) || 1) + 1);},- @computed("isNumber", "showMinMax", "pollType", "publicPoll", "pollOptions", "pollMin", "pollMax", "pollStep")- pollOutput(isNumber, showMinMax, pollType, publicPoll, pollOptions, pollMin, pollMax, pollStep) {+ @computed("isNumber", "showMinMax", "pollType", "publicPoll", "pollOptions", "pollMin", "pollMax", "pollStep", "autoClose", "date", "time")+ pollOutput(isNumber, showMinMax, pollType, publicPoll, pollOptions, pollMin, pollMax, pollStep, autoClose, date, time) {let pollHeader = '[poll';let output = '';@@ -113,15 +111,15 @@ export default Ember.Controller.extend({};let step = pollStep;- if (step < 1) {- step = 1;- }+ if (step < 1) { step = 1; }if (pollType) pollHeader += ` type=${pollType}`;if (pollMin && showMinMax) pollHeader += ` min=${pollMin}`;if (pollMax) pollHeader += ` max=${pollMax}`;if (isNumber) pollHeader += ` step=${step}`;- if (publicPoll) pollHeader += ' public=true';+ if (publicPoll) pollHeader += ` public=true`;+ if (autoClose) pollHeader += ` close=${moment(date + " " + time, "YYYY-MM-DD HH:mm").toISOString()}`;+pollHeader += ']';output += `${pollHeader}\n`;@@ -186,7 +184,10 @@ export default Ember.Controller.extend({pollOptions: '',pollMin: 1,pollMax: null,- pollStep: 1+ pollStep: 1,+ autoClose: false,+ date: moment().add(1, "day").format("YYYY-DD-MM"),+ time: moment().add(1, "hour").format("HH:mm"),});},diff --git a/plugins/poll/assets/javascripts/discourse/templates/modal/poll-ui-builder.hbs b/plugins/poll/assets/javascripts/discourse/templates/modal/poll-ui-builder.hbsindex 47eaa0c1a26..aaf375e6d95 100644--- a/plugins/poll/assets/javascripts/discourse/templates/modal/poll-ui-builder.hbs+++ b/plugins/poll/assets/javascripts/discourse/templates/modal/poll-ui-builder.hbs@@ -40,6 +40,14 @@{{/if}}{{/if}}+ {{#unless isNumber}}+ <div class="input-group">+ <label>{{i18n 'poll.ui_builder.poll_options.label'}}</label>+ {{input-tip validation=minNumOfOptionsValidation}}+ {{textarea value=pollOptions}}+ </div>+ {{/unless}}+<div class="input-group"><label>{{input type='checkbox' checked=publicPoll}}@@ -47,13 +55,20 @@</label></div>- {{#unless isNumber}}+ <div class="input-group">+ <label>+ {{input type="checkbox" checked=autoClose}}+ {{i18n "poll.ui_builder.automatic_close.label"}}+ </label>+ </div>++ {{#if autoClose}}<div class="input-group">- <label>{{i18n 'poll.ui_builder.poll_options.label'}}</label>- {{input-tip validation=minNumOfOptionsValidation}}- {{textarea value=pollOptions}}+ {{date-picker-future value=date containerId="date-container"}}+ {{input type="time" value=time}}+ <div id="date-container"></div></div>- {{/unless}}+ {{/if}}</form>{{/d-modal-body}}diff --git a/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6 b/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6index 0138c6f99fa..7325572bb62 100644--- a/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6+++ b/plugins/poll/assets/javascripts/initializers/extend-for-poll.js.es6@@ -22,6 +22,13 @@ function initializePolls(api) {}});+ let _glued = [];+ let _interval = null;++ function rerender() {+ _glued.forEach(g => g.queueRerender());+ }+api.modifyClass('model:post', {_polls: null,pollsObject: null,@@ -41,12 +48,12 @@ function initializePolls(api) {}});this.set("pollsObject", this._polls);- _glued.forEach(g => g.queueRerender());+ rerender();}}});- const _glued = [];+function attachPolls($elem, helper) {const $polls = $('.poll', $elem);if (!$polls.length) { return; }@@ -60,6 +67,8 @@ function initializePolls(api) {const polls = post.get("pollsObject");if (!polls) { return; }+ _interval = _interval || setInterval(rerender, 30000);+$polls.each((idx, pollElem) => {const $poll = $(pollElem);const pollName = $poll.data("poll-name");@@ -81,7 +90,13 @@ function initializePolls(api) {}function cleanUpPolls() {+ if (_interval) {+ clearInterval(_interval);+ _interval = null;+ }+_glued.forEach(g => g.cleanUp());+ _glued = [];}api.includePostAttributes("polls", "polls_votes");diff --git a/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js.es6 b/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js.es6index ca67fa921b4..c29e12d9e4a 100644--- a/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js.es6+++ b/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js.es6@@ -2,35 +2,7 @@const DATA_PREFIX = "data-poll-";const DEFAULT_POLL_NAME = "poll";-const WHITELISTED_ATTRIBUTES = ["type", "name", "min", "max", "step", "order", "status", "public"];--function getHelpText(count, min, max) {-- // default values- if (isNaN(min) || min < 1) { min = 1; }- if (isNaN(max) || max > count) { max = count; }-- // add some help text- let help;-- if (max > 0) {- if (min === max) {- if (min > 1) {- help = I18n.t("poll.multiple.help.x_options", { count: min });- }- } else if (min > 1) {- if (max < count) {- help = I18n.t("poll.multiple.help.between_min_and_max_options", { min: min, max: max });- } else {- help = I18n.t("poll.multiple.help.at_least_min_options", { count: min });- }- } else if (max <= count) {- help = I18n.t("poll.multiple.help.up_to_max_options", { count: max });- }- }-- return help;-}+const WHITELISTED_ATTRIBUTES = ["type", "name", "min", "max", "step", "order", "status", "public", "close"];function replaceToken(tokens, target, list) {let pos = tokens.indexOf(target);@@ -50,7 +22,6 @@ function replaceToken(tokens, target, list) {// analyzes the block to that we have poll optionsfunction getListItems(tokens, startToken) {-let i = tokens.length-1;let listItems = [];let buffer = [];@@ -217,63 +188,13 @@ const rule = {token = state.push('span_open', 'span', 1);token.block = false;- token.attrs = [['class', 'info-text']];+ token.attrs = [['class', 'info-label']];token = state.push('text', '', 0);token.content = I18n.t("poll.voters", { count: 0 });state.push('span_close', 'span', -1);state.push('paragraph_close', 'p', -1);- // multiple help text- if (attributes[DATA_PREFIX + "type"] === "multiple") {- let help = getHelpText(items.length, min, max);- if (help) {- state.push('paragraph_open', 'p', 1);- token = state.push('html_inline', '', 0);- token.content = help;- state.push('paragraph_close', 'p', -1);- }- }-- if (attributes[DATA_PREFIX + 'public'] === 'true') {- state.push('paragraph_open', 'p', 1);- token = state.push('text', '', 0);- token.content = I18n.t('poll.public.title');- state.push('paragraph_close', 'p', -1);- }-- state.push('poll_close', 'div', -1);- state.push('poll_close', 'div', -1);-- token = state.push('poll_open', 'div', 1);- token.attrs = [['class', 'poll-buttons']];-- if (attributes[DATA_PREFIX + 'type'] === 'multiple') {- token = state.push('link_open', 'a', 1);- token.block = false;- token.attrs = [- ['class', 'button cast-votes'],- ['title', I18n.t('poll.cast-votes.title')]- ];-- token = state.push('text', '', 0);- token.content = I18n.t('poll.cast-votes.label');-- state.push('link_close', 'a', -1);- }-- token = state.push('link_open', 'a', 1);- token.block = false;- token.attrs = [- ['class', 'button toggle-results'],- ['title', I18n.t('poll.show-results.title')]- ];-- token = state.push('text', '', 0);- token.content = I18n.t("poll.show-results.label");-- state.push('link_close', 'a', -1);-state.push('poll_close', 'div', -1);state.push('poll_close', 'div', -1);}@@ -299,6 +220,7 @@ export function setup(helper) {'div[data-*]','span.info-number','span.info-text',+ 'span.info-label','a.button.cast-votes','a.button.toggle-results','li[data-*]'diff --git a/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6 b/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6index 53061b420a2..7b9ce4c7749 100644--- a/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6+++ b/plugins/poll/assets/javascripts/widgets/discourse-poll.js.es6@@ -34,7 +34,6 @@ createWidget('discourse-poll-option', {html(attrs) {const result = [];-const { option, vote } = attrs;const chosen = vote.indexOf(option.id) !== -1;@@ -45,6 +44,7 @@ createWidget('discourse-poll-option', {}result.push(' ');result.push(optionHtml(option));+return result;},@@ -235,7 +235,6 @@ createWidget('discourse-poll-number-results', {const { attrs, state } = this;if (state.loaded === 'new') {-fetchVoters({post_id: attrs.post.id,poll_name: attrs.poll.get('name')@@ -258,8 +257,7 @@ createWidget('discourse-poll-number-results', {const voters = poll.voters;const average = voters === 0 ? 0 : round(totalScore / voters, -2);const averageRating = I18n.t("poll.average_rating", { average });- const results = [h('div.poll-results-number-rating',- new RawHtml({ html: `<span>${averageRating}</span>` }))];+ const results = [h('div.poll-results-number-rating', new RawHtml({ html: `<span>${averageRating}</span>` }))];if (isPublic) {this.fetchVoters();@@ -283,7 +281,7 @@ createWidget('discourse-poll-container', {html(attrs) {const { poll } = attrs;- if (attrs.showResults) {+ if (attrs.showResults || attrs.isClosed) {const type = poll.get('type') === 'number' ? 'number' : 'standard';return this.attach(`discourse-poll-${type}-results`, attrs);}@@ -327,29 +325,37 @@ createWidget('discourse-poll-info', {const count = poll.get('voters');const result = [h('p', [h('span.info-number', count.toString()),- h('span.info-text', I18n.t('poll.voters', { count }))+ h('span.info-label', I18n.t('poll.voters', { count }))])];if (attrs.isMultiple) {- if (attrs.showResults) {+ if (attrs.showResults || attrs.isClosed) {const totalVotes = poll.get('options').reduce((total, o) => {return total + parseInt(o.votes, 10);}, 0);result.push(h('p', [h('span.info-number', totalVotes.toString()),- h('span.info-text', I18n.t("poll.total_votes", { count: totalVotes }))+ h('span.info-label', I18n.t("poll.total_votes", { count: totalVotes }))]));} else {const help = this.multipleHelpText(attrs.min, attrs.max, poll.get('options.length'));if (help) {- result.push(new RawHtml({ html: `<span>${help}</span>` }));+ result.push(new RawHtml({ html: `<span class="info-text">${help}</span>` }));}}}- if (!attrs.showResults && attrs.poll.get('public')) {- result.push(h('p', I18n.t('poll.public.title')));+ if (!attrs.isClosed) {+ if (!attrs.showResults && poll.get('public')) {+ result.push(h('span.info-text', I18n.t('poll.public.title')));+ }++ if (poll.close) {+ const closeDate = moment.utc(poll.close);+ const timeLeft = moment().to(closeDate.local(), true);+ result.push(new RawHtml({ html: `<span class="info-text" title="${closeDate.format("LLL")}">${I18n.t("poll.automatic_close.closes_in", { timeLeft })}</span>` }));+ }}return result;@@ -363,8 +369,8 @@ createWidget('discourse-poll-buttons', {const results = [];const { poll, post } = attrs;const topicArchived = post.get('topic.archived');- const isClosed = poll.get('status') === 'closed';- const hideResultsDisabled = isClosed || topicArchived;+ const closed = attrs.isClosed;+ const hideResultsDisabled = closed || topicArchived;if (attrs.isMultiple && !hideResultsDisabled) {const castVotesDisabled = !attrs.canCastVotes;@@ -378,7 +384,7 @@ createWidget('discourse-poll-buttons', {results.push(' ');}- if (attrs.showResults) {+ if (attrs.showResults || hideResultsDisabled) {results.push(this.attach('button', {className: 'btn toggle-results',label: 'poll.hide-results.label',@@ -403,14 +409,16 @@ createWidget('discourse-poll-buttons', {this.currentUser.get("staff")) &&!topicArchived) {- if (isClosed) {- results.push(this.attach('button', {- className: 'btn toggle-status',- label: 'poll.open.label',- title: 'poll.open.title',- icon: 'unlock-alt',- action: 'toggleStatus'- }));+ if (closed) {+ if (!attrs.isAutomaticallyClosed) {+ results.push(this.attach('button', {+ className: 'btn toggle-status',+ label: 'poll.open.label',+ title: 'poll.open.title',+ icon: 'unlock-alt',+ action: 'toggleStatus'+ }));+ }} else {results.push(this.attach('button', {className: 'btn toggle-status btn-danger',@@ -422,7 +430,6 @@ createWidget('discourse-poll-buttons', {}}-return results;}});@@ -437,14 +444,14 @@ export default createWidget('discourse-poll', {"data-poll-type": poll.get('type'),"data-poll-name": poll.get('name'),"data-poll-status": poll.get('status'),- "data-poll-public": poll.get('public')+ "data-poll-public": poll.get('public'),+ "data-poll-close": poll.get('close'),};},defaultState(attrs) {- const { poll, post } = attrs;- return { loading: false,- showResults: poll.get('isClosed') || post.get('topic.archived') };+ const showResults = this.isClosed() || attrs.post.get('topic.archived');+ return { loading: false, showResults };},html(attrs, state) {@@ -452,9 +459,12 @@ export default createWidget('discourse-poll', {const newAttrs = jQuery.extend({}, attrs, {showResults,canCastVotes: this.canCastVotes(),+ isClosed: this.isClosed(),+ isAutomaticallyClosed: this.isAutomaticallyClosed(),min: this.min(),max: this.max()});+return h('div', [this.attach('discourse-poll-container', newAttrs),this.attach('discourse-poll-info', newAttrs),@@ -462,10 +472,6 @@ export default createWidget('discourse-poll', {]);},- isClosed() {- return this.attrs.poll.get('status') === "closed";- },-min() {let min = parseInt(this.attrs.poll.min, 10);if (isNaN(min) || min < 1) { min = 1; }@@ -479,37 +485,51 @@ export default createWidget('discourse-poll', {return max;},+ isAutomaticallyClosed() {+ const { poll } = this.attrs;+ return poll.get("close") && moment.utc(poll.get("close")) <= moment();+ },++ isClosed() {+ const { poll } = this.attrs;+ return poll.get("status") === "closed" || this.isAutomaticallyClosed();+ },+canCastVotes() {const { state, attrs } = this;+if (this.isClosed() || state.showResults || state.loading) {return false;}const selectedOptionCount = attrs.vote.length;+if (attrs.isMultiple) {return selectedOptionCount >= this.min() && selectedOptionCount <= this.max();}+return selectedOptionCount > 0;},toggleStatus() {const { state, attrs } = this;- const { poll } = attrs;- const isClosed = poll.get('status') === 'closed';+ const { post, poll } = attrs;++ if (this.isAutomaticallyClosed()) { return; }bootbox.confirm(- I18n.t(isClosed ? "poll.open.confirm" : "poll.close.confirm"),+ I18n.t(this.isClosed() ? "poll.open.confirm" : "poll.close.confirm"),I18n.t("no_value"),I18n.t("yes_value"),confirmed => {if (confirmed) {state.loading = true;+ const status = this.isClosed() ? "open" : "closed";- const status = isClosed ? "open" : "closed";ajax("/polls/toggle_status", {type: "PUT",data: {- post_id: attrs.post.get('id'),+ post_id: post.get('id'),poll_name: poll.get('name'),status,}@@ -535,15 +555,15 @@ export default createWidget('discourse-poll', {},showLogin() {- const appRoute = this.register.lookup('route:application');- appRoute.send('showLogin');+ this.register.lookup('route:application').send('showLogin');},toggleOption(option) {+ const { attrs } = this;+if (this.isClosed()) { return; }if (!this.currentUser) { this.showLogin(); }- const { attrs } = this;const { vote } = attrs;const chosenIdx = vote.indexOf(option.id);diff --git a/plugins/poll/assets/stylesheets/common/poll.scss b/plugins/poll/assets/stylesheets/common/poll.scssindex 845a2a391ab..ee7239fa9c8 100644--- a/plugins/poll/assets/stylesheets/common/poll.scss+++ b/plugins/poll/assets/stylesheets/common/poll.scss@@ -52,9 +52,14 @@ div.poll {font-size: 3.5em;}- .info-text {+ .info-label {font-size: 1.7em;}++ .info-text {+ margin: 5px 0;+ display: block;+ }}.poll-container {diff --git a/plugins/poll/assets/stylesheets/desktop/poll.scss b/plugins/poll/assets/stylesheets/desktop/poll.scssindex cc8ed28ad2e..79ead5d01fa 100644--- a/plugins/poll/assets/stylesheets/desktop/poll.scss+++ b/plugins/poll/assets/stylesheets/desktop/poll.scss@@ -14,7 +14,7 @@ div.poll {margin: 40px 20px;}- .info-text {+ .info-label {display: block;}}diff --git a/plugins/poll/assets/stylesheets/mobile/poll.scss b/plugins/poll/assets/stylesheets/mobile/poll.scssindex 1c35f64bb3d..2d552a5f6b5 100644--- a/plugins/poll/assets/stylesheets/mobile/poll.scss+++ b/plugins/poll/assets/stylesheets/mobile/poll.scss@@ -8,6 +8,8 @@ div.poll {}.poll-info {- .info-text:before {content:"\00a0";} // nbsp+ .info-label:before {+ content:"\00a0"; //nbsp+ }}}diff --git a/plugins/poll/config/locales/client.en.yml b/plugins/poll/config/locales/client.en.ymlindex 86bae641924..74d6bdf2154 100644--- a/plugins/poll/config/locales/client.en.yml+++ b/plugins/poll/config/locales/client.en.yml@@ -65,6 +65,9 @@ en:label: "Close"confirm: "Are you sure you want to close this poll?"+ automatic_close:+ closes_in: "Closes in <strong>%{timeLeft}</strong>."+error_while_toggling_status: "Sorry, there was an error toggling the status of this poll."error_while_casting_votes: "Sorry, there was an error casting your votes."error_while_fetching_voters: "Sorry, there was an error displaying the voters."@@ -89,3 +92,5 @@ en:label: Show who votedpoll_options:label: Enter one poll option per line+ automatic_close:+ label: Automatically close polldiff --git a/plugins/poll/config/locales/server.en.yml b/plugins/poll/config/locales/server.en.ymlindex a0784017d48..45859bb1894 100644--- a/plugins/poll/config/locales/server.en.yml+++ b/plugins/poll/config/locales/server.en.yml@@ -44,7 +44,7 @@ en:requires_at_least_1_valid_option: "You must select at least 1 valid option."default_cannot_be_made_public: "Poll with votes cannot be made public."- named_cannot_be_made_public: "Poll named <strong>%{name}</strong> has votes cannot be made public."+ named_cannot_be_made_public: "Poll named <strong>%{name}</strong> has votes and cannot be made public."edit_window_expired:op_cannot_edit_options: "You cannot add or remove poll options after the first %{minutes} minutes. Please contact a moderator if you need to edit a poll option."diff --git a/plugins/poll/jobs/regular/close_poll.rb b/plugins/poll/jobs/regular/close_poll.rbnew file mode 100644index 00000000000..b4b25bc3e4e--- /dev/null+++ b/plugins/poll/jobs/regular/close_poll.rb@@ -0,0 +1,11 @@+module Jobs++ class ClosePoll < Jobs::Base++ def execute(args)+ DiscoursePoll::Poll.toggle_status(args[:post_id], args[:poll_name], "closed", -1)+ end++ end++enddiff --git a/plugins/poll/lib/polls_updater.rb b/plugins/poll/lib/polls_updater.rbindex 7f1eed7a74f..8fa46c698f6 100644--- a/plugins/poll/lib/polls_updater.rb+++ b/plugins/poll/lib/polls_updater.rb@@ -1,6 +1,6 @@module DiscoursePollclass PollsUpdater- VALID_POLLS_CONFIGS = %w{type min max public}.map(&:freeze)+ VALID_POLLS_CONFIGS = %w{type min max public close}.map(&:freeze)def self.update(post, polls)# load previous polls@@ -18,28 +18,18 @@ module DiscoursePollpoll_edit_window_mins = SiteSetting.poll_edit_window_minsif post.created_at < poll_edit_window_mins.minutes.ago && has_votes- is_staff = User.staff.where(id: post.last_editor_id).exists?-# deal with option changes- if is_staff+ if User.staff.where(id: post.last_editor_id).exists?# staff can edit optionspolls.each_key do |poll_name|if polls.dig(poll_name, "options")&.size != previous_polls.dig(poll_name, "options")&.size && previous_polls.dig(poll_name, "voters").to_i > 0- post.errors.add(:base, I18n.t(- "poll.edit_window_expired.staff_cannot_add_or_remove_options",- minutes: poll_edit_window_mins- ))-+ post.errors.add(:base, I18n.t("poll.edit_window_expired.staff_cannot_add_or_remove_options", minutes: poll_edit_window_mins))returnendendelse# OP cannot edit poll options- post.errors.add(:base, I18n.t(- "poll.edit_window_expired.op_cannot_edit_options",- minutes: poll_edit_window_mins- ))-+ post.errors.add(:base, I18n.t("poll.edit_window_expired.op_cannot_edit_options", minutes: poll_edit_window_mins))returnendend@@ -93,6 +83,9 @@ module DiscoursePollpost.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD] = pollspost.save_custom_fields(true)+ # re-schedule jobs+ DiscoursePoll::Poll.schedule_jobs(post)+# publish the changesMessageBus.publish("/polls/#{post.topic_id}", post_id: post.id, polls: polls)end@@ -102,9 +95,7 @@ module DiscoursePollreturn true if (current_polls.keys.sort != previous_polls.keys.sort)current_polls.each_key do |poll_name|- if !previous_polls[poll_name] ||- (current_polls[poll_name].values_at(*VALID_POLLS_CONFIGS) != previous_polls[poll_name].values_at(*VALID_POLLS_CONFIGS))-+ if !previous_polls[poll_name] || (current_polls[poll_name].values_at(*VALID_POLLS_CONFIGS) != previous_polls[poll_name].values_at(*VALID_POLLS_CONFIGS))return trueendend@@ -127,12 +118,9 @@ module DiscoursePollcurrent_poll = current_polls[poll_name]if previous_polls["public"].nil? && current_poll["public"] == "true"- error =- if poll_name == DiscoursePoll::DEFAULT_POLL_NAME- I18n.t("poll.default_cannot_be_made_public")- else- I18n.t("poll.named_cannot_be_made_public", name: poll_name)- end+ error = poll_name == DiscoursePoll::DEFAULT_POLL_NAME ?+ I18n.t("poll.default_cannot_be_made_public") :+ I18n.t("poll.named_cannot_be_made_public", name: poll_name)post.errors.add(:base, error)return truediff --git a/plugins/poll/lib/post_validator.rb b/plugins/poll/lib/post_validator.rbindex 7301fdde751..2b6be2b14c0 100644--- a/plugins/poll/lib/post_validator.rb+++ b/plugins/poll/lib/post_validator.rb@@ -6,17 +6,13 @@ module DiscoursePolldef validate_postmin_trust_level = SiteSetting.poll_minimum_trust_level_to_create- trusted = @post&.user&.staff? ||- @post&.user&.trust_level >= TrustLevel[min_trust_level]- if !trusted- message = I18n.t("poll.insufficient_rights_to_create")-- @post.errors.add(:base, message)- return false+ if @post&.user&.staff? || @post&.user&.trust_level >= TrustLevel[min_trust_level]+ true+ else+ @post.errors.add(:base, I18n.t("poll.insufficient_rights_to_create"))+ falseend-- trueendendenddiff --git a/plugins/poll/plugin.rb b/plugins/poll/plugin.rbindex 45fa5686c56..f440e33dbce 100644--- a/plugins/poll/plugin.rb+++ b/plugins/poll/plugin.rb@@ -10,20 +10,21 @@ register_asset "stylesheets/desktop/poll.scss", :desktopregister_asset "stylesheets/mobile/poll.scss", :mobilePLUGIN_NAME ||= "discourse_poll".freeze-DATA_PREFIX ||= "data-poll-".freezeafter_initialize do++ require File.expand_path("../jobs/regular/close_poll", __FILE__)+module ::DiscoursePoll- DEFAULT_POLL_NAME ||= "poll".freeze+ DEFAULT_POLL_NAME ||= "poll".freezePOLLS_CUSTOM_FIELD ||= "polls".freezeVOTES_CUSTOM_FIELD ||= "polls-votes".freeze- MUTEX_PREFIX ||= PLUGIN_NAME- autoload :PostValidator, "#{Rails.root}/plugins/poll/lib/post_validator"+ autoload :PostValidator, "#{Rails.root}/plugins/poll/lib/post_validator"autoload :PollsValidator, "#{Rails.root}/plugins/poll/lib/polls_validator"- autoload :PollsUpdater, "#{Rails.root}/plugins/poll/lib/polls_updater"- autoload :VotesUpdater, "#{Rails.root}/plugins/poll/lib/votes_updater"+ autoload :PollsUpdater, "#{Rails.root}/plugins/poll/lib/polls_updater"+ autoload :VotesUpdater, "#{Rails.root}/plugins/poll/lib/votes_updater"class Engine < ::Rails::Engineengine_name PLUGIN_NAME@@ -62,7 +63,12 @@ after_initialize doraise StandardError.new I18n.t("poll.no_poll_with_this_name", name: poll_name) if poll.blank?raise StandardError.new I18n.t("poll.poll_must_be_open_to_vote") if poll["status"] != "open"- public_poll = (poll["public"] == "true")++ # ensure no race condition when poll is automatically closed+ if poll["close"].present?+ close_date = Time.zone.parse(poll["close"]) rescue nil+ raise StandardError.new I18n.t("poll.poll_must_be_open_to_vote") if close_date && close_date <= Time.zone.now+ end# remove options that aren't available in the pollavailable_options = poll["options"].map { |o| o["id"] }.to_set@@ -83,6 +89,8 @@ after_initialize dopoll["voters"] += 1 if (available_options & votes.to_set).size > 0end+ public_poll = (poll["public"] == "true")+poll["options"].each do |option|anonymous_votes = option["anonymous_votes"] || 0option["votes"] = all_options[option["id"]] + anonymous_votes@@ -102,14 +110,11 @@ after_initialize dopost.save_custom_fields(true)payload = { post_id: post_id, polls: polls }-- if public_poll- payload.merge!(user: UserNameSerializer.new(user).serializable_hash)- end+ payload.merge!(user: UserNameSerializer.new(user).serializable_hash) if public_pollMessageBus.publish("/polls/#{post.topic_id}", payload)- return [poll, options]+ [poll, options]endend@@ -149,36 +154,40 @@ after_initialize doendend+ def schedule_jobs(post)+ post.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD].each do |name, poll|+ Jobs.cancel_scheduled_job(:close_poll, post_id: post.id, poll_name: name)++ if poll["status"] == "open" && poll["close"].present?+ close_date = Time.zone.parse(poll["close"]) rescue nil+ Jobs.enqueue_at(close_date, :close_poll, post_id: post.id, poll_name: name) if close_date && close_date > Time.zone.now+ end+ end+ end+def extract(raw, topic_id, user_id = nil)# TODO: we should fix the callback mess so that the cooked version is available# in the validators instead of cooking twicecooked = PrettyText.cook(raw, topic_id: topic_id, user_id: user_id)- parsed = Nokogiri::HTML(cooked)-- extracted_polls = []- # extract polls- parsed.css("div.poll").each do |p|+ Nokogiri::HTML(cooked).css("div.poll").map do |p|poll = { "options" => [], "voters" => 0 }- # extract attributes+ # attributesp.attributes.values.each do |attribute|if attribute.name.start_with?(DATA_PREFIX)poll[attribute.name[DATA_PREFIX.length..-1]] = CGI.escapeHTML(attribute.value || "")endend- # extract options+ # optionsp.css("li[#{DATA_PREFIX}option-id]").each do |o|option_id = o.attributes[DATA_PREFIX + "option-id"].value || ""poll["options"] << { "id" => option_id, "html" => o.inner_html, "votes" => 0 }end- # add the poll- extracted_polls << poll+ pollend-- extracted_pollsendendend@@ -228,14 +237,13 @@ after_initialize doraise Discourse::InvalidParameters.new("poll_name is invalid") if !pollvoter_limit = (params[:voter_limit] || 25).to_i- voter_limit = 0 if voter_limit < 0+ voter_limit = 0 if voter_limit < 0voter_limit = 50 if voter_limit > 50user_ids = []options = poll["options"]if poll["type"] != "number"-per_option_voters = {}options.each do |option|@@ -256,7 +264,7 @@ after_initialize doresult = {}- User.where(id: user_ids).map do |user|+ User.where(id: user_ids).each do |user|user_hash = UserNameSerializer.new(user).serializable_hashpoll_votes[user.id.to_s][poll_name].each do |option_id|@@ -277,12 +285,7 @@ after_initialize douser_ids.flatten!user_ids.uniq!user_ids = user_ids.slice((params[:offset].to_i || 0) * voter_limit, voter_limit)-- result = []-- User.where(id: user_ids).map do |user|- result << UserNameSerializer.new(user).serializable_hash- end+ result = User.where(id: user_ids).map { |user| UserNameSerializer.new(user).serializable_hash }endrender json: { poll_name => result }@@ -373,18 +376,19 @@ after_initialize doif post.nil? || post.trashed?fragment.css(".poll, [data-poll-name]").each(&:remove)else- post_url = "#{Discourse.base_url}#{post.url}"+ post_url = post.full_urlfragment.css(".poll, [data-poll-name]").each do |poll|poll.replace "<p><a href='#{post_url}'>#{I18n.t("poll.email.link_to_poll")}</a></p>"endendend- # tells the front-end we have a poll for that poston(:post_created) do |post|next if post.is_first_post? || post.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD].blank?- MessageBus.publish("/polls/#{post.topic_id}", post_id: post.id,- polls: post.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD])+ # signals the front-end we have polls for that post+ MessageBus.publish("/polls/#{post.topic_id}", post_id: post.id, polls: post.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD])+ # schedule automatic close jobs+ DiscoursePoll::Poll.schedule_jobs(post)endon(:merging_users) do |source_user, target_user|