FIX: Do more to decrypt encrypted results

FIX: Do more to decrypt encrypted results

Sometimes encrypted results are returned to the user (for example when searching for “secret”, part of the encrypted PM placeholder). Usually, the encrypted messages cache stored locally contains a decrypted copy. For these cases, the messages can be decrypted with no additional cost.

This commit also includes various search improvements.

diff --git a/assets/javascripts/discourse/initializers/add-search-results.js b/assets/javascripts/discourse/initializers/add-search-results.js
index b71ef1c..2b2cb88 100644
--- a/assets/javascripts/discourse/initializers/add-search-results.js
+++ b/assets/javascripts/discourse/initializers/add-search-results.js
@@ -1,4 +1,4 @@
-import { Promise } from "rsvp";
+import { iconHTML } from "discourse-common/lib/icon-library";
 import { ajax } from "discourse/lib/ajax";
 import { withPluginApi } from "discourse/lib/plugin-api";
 import Post from "discourse/models/post";
@@ -13,6 +13,7 @@ import {
   importKey,
 } from "discourse/plugins/discourse-encrypt/lib/protocol";
 import I18n from "I18n";
+import { Promise } from "rsvp";
 
 const CACHE_KEY = "discourse-encrypt-cache";
 
@@ -50,7 +51,8 @@ function getOrFetchCache(session) {
             .then((id) => importKey(topic.topic_key, id.encryptPrivate))
             .then((key) => decrypt(key, topic.encrypted_title))
             .then((decrypted) => {
-              topic.title = topic.fancy_title = decrypted.raw;
+              topic.title = decrypted.raw;
+              topic.fancy_title = `${iconHTML("user-secret")} ${decrypted.raw}`;
               addCacheItem(session, "topics", topic);
             })
             .catch(() => {})
@@ -75,32 +77,39 @@ export default {
     const session = container.lookup("session:main");
     withPluginApi("0.11.3", (api) => {
       api.addSearchResultsCallback((results) => {
-        const term = results.grouped_search_result.term;
-        const words = term.split(/\s+/);
-
-        if (!words.some((w) => w === "in:personal")) {
+        if (results.grouped_search_result.type_filter !== "private_messages") {
           return Promise.resolve(results);
         }
 
         return getOrFetchCache(session).then((cache) => {
           const topics = {};
           if (cache.topics) {
-            cache.topics.forEach((topic) => {
-              if (!words.some((word) => topic.title.indexOf(word) !== -1)) {
-                return;
-              }
+            const words = results.grouped_search_result.term
+              .toLowerCase()
+              .split(/\s+/);
 
+            cache.topics.forEach((topic) => {
               const topicObj = results.topics.find((t) => topic.id === t.id);
               if (topicObj) {
                 topicObj.setProperties(topic);
-              } else {
+              } else if (
+                words.some((word) => topic.title.toLowerCase().includes(word))
+              ) {
                 topic = Topic.create(topic);
+                results.topics.unshift(topic);
                 topics[topic.id] = topic;
               }
             });
+
+            // Reset topic_title_headline
+            const encryptedTopicIds = new Set(cache.topics.map((t) => t.id));
+            results.posts.map((post) => {
+              if (encryptedTopicIds.has(post.topic_id)) {
+                post.set("topic_title_headline", "");
+              }
+            });
           }
 
-          const posts = {};
           if (cache.posts) {
             cache.posts.forEach((post) => {
               if (!topics[post.topic_id]) {
@@ -112,19 +121,12 @@ export default {
                 topic: topics[post.topic_id],
                 blurb: I18n.t("encrypt.encrypted_post"),
               });
-              posts[post.topic_id] = post;
+
+              results.posts.unshift(post);
+              results.grouped_search_result.post_ids.unshift(post.id);
             });
           }
 
-          Object.values(topics).forEach((topic) => {
-            results.topics.unshift(topic);
-          });
-
-          Object.values(posts).forEach((p) => {
-            results.posts.unshift(p);
-            results.grouped_search_result.post_ids.unshift(p.id);
-          });
-
           return results;
         });
       });
diff --git a/lib/grouped_search_result_serializer_extension.rb b/lib/grouped_search_result_serializer_extension.rb
new file mode 100644
index 0000000..46324e8
--- /dev/null
+++ b/lib/grouped_search_result_serializer_extension.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+module GroupedSearchResultSerializerExtension
+  def self.prepended(base)
+    base.attributes :type_filter
+  end
+end
diff --git a/plugin.rb b/plugin.rb
index 3b4ea17..eedae6a 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -31,6 +31,7 @@ after_initialize do
   load File.expand_path('../app/models/user_encryption_key.rb', __FILE__)
   load File.expand_path('../lib/email_sender_extensions.rb', __FILE__)
   load File.expand_path('../lib/encrypted_post_creator.rb', __FILE__)
+  load File.expand_path('../lib/grouped_search_result_serializer_extension.rb', __FILE__)
   load File.expand_path('../lib/openssl.rb', __FILE__)
   load File.expand_path('../lib/post_actions_controller_extensions.rb', __FILE__)
   load File.expand_path('../lib/post_extensions.rb', __FILE__)
@@ -67,16 +68,17 @@ after_initialize do
   end
 
   reloadable_patch do |plugin|
-    Email::Sender.class_eval         { prepend EmailSenderExtensions }
-    Post.class_eval                  { prepend PostExtensions }
-    PostActionsController.class_eval { prepend PostActionsControllerExtensions }
-    Topic.class_eval                 { prepend TopicExtensions }
-    TopicGuardian.class_eval         { prepend TopicGuardianExtension }
-    TopicsController.class_eval      { prepend TopicsControllerExtensions }
-    TopicViewSerializer.class_eval   { prepend TopicViewSerializerExtension }
-    UploadValidator.class_eval       { prepend UploadValidatorExtensions }
-    User.class_eval                  { prepend UserExtensions }
-    UserNotifications.class_eval     { prepend UserNotificationsExtensions }
+    Email::Sender.class_eval                 { prepend EmailSenderExtensions }
+    GroupedSearchResultSerializer.class_eval { prepend GroupedSearchResultSerializerExtension }
+    Post.class_eval                          { prepend PostExtensions }
+    PostActionsController.class_eval         { prepend PostActionsControllerExtensions }
+    Topic.class_eval                         { prepend TopicExtensions }
+    TopicGuardian.class_eval                 { prepend TopicGuardianExtension }
+    TopicsController.class_eval              { prepend TopicsControllerExtensions }
+    TopicViewSerializer.class_eval           { prepend TopicViewSerializerExtension }
+    UploadValidator.class_eval               { prepend UploadValidatorExtensions }
+    User.class_eval                          { prepend UserExtensions }
+    UserNotifications.class_eval             { prepend UserNotificationsExtensions }
 
     SiteSetting.singleton_class.prepend SiteSettingExtensions
     UserNotificationRenderer.singleton_class.prepend UserNotificationRendererExtensions

GitHub sha: 82793ab92ee7767f90a188204157f6d42f33b9b2

This commit appears in #104 which was approved by eviltrout. It was merged by udan11.