about summary refs log tree commit diff
path: root/app/services/activitypub
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2019-03-03 22:18:23 +0100
committerGitHub <noreply@github.com>2019-03-03 22:18:23 +0100
commit230a012f0090c496fc5cdb011bcc8ed732fd0f5c (patch)
treeca589b040b2d5c440e75e53d528f908cafe65d3a /app/services/activitypub
parent99dc212ae5d7b2527d835744bf903293398ce946 (diff)
Add polls (#10111)
* Add polls

Fix #1629

* Add tests

* Fixes

* Change API for creating polls

* Use name instead of content for votes

* Remove poll validation for remote polls

* Add polls to public pages

* When updating the poll, update options just in case they were changed

* Fix public pages showing both poll and other media
Diffstat (limited to 'app/services/activitypub')
-rw-r--r--app/services/activitypub/fetch_remote_poll_service.rb51
1 files changed, 51 insertions, 0 deletions
diff --git a/app/services/activitypub/fetch_remote_poll_service.rb b/app/services/activitypub/fetch_remote_poll_service.rb
new file mode 100644
index 000000000..6f0ac5624
--- /dev/null
+++ b/app/services/activitypub/fetch_remote_poll_service.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+class ActivityPub::FetchRemotePollService < BaseService
+  include JsonLdHelper
+
+  def call(poll, on_behalf_of = nil)
+    @json = fetch_resource(poll.status.uri, true, on_behalf_of)
+
+    return unless supported_context? && expected_type?
+
+    expires_at = begin
+      if @json['closed'].is_a?(String)
+        @json['closed']
+      elsif !@json['closed'].is_a?(FalseClass)
+        Time.now.utc
+      else
+        @json['endTime']
+      end
+    end
+
+    items = begin
+      if @json['anyOf'].is_a?(Array)
+        @json['anyOf']
+      else
+        @json['oneOf']
+      end
+    end
+
+    latest_options = items.map { |item| item['name'].presence || item['content'] }
+
+    # If for some reasons the options were changed, it invalidates all previous
+    # votes, so we need to remove them
+    poll.votes.delete_all if latest_options != poll.options
+
+    poll.update!(
+      expires_at: expires_at,
+      options: latest_options,
+      cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 }
+    )
+  end
+
+  private
+
+  def supported_context?
+    super(@json)
+  end
+
+  def expected_type?
+    equals_or_includes_any?(@json['type'], 'Question')
+  end
+end