The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Handle PDF uploads to slack user DMs (#76787)
Nick Fitzpatrick2080e7c13f7f
diff --git a/src/metabase/channel/impl/slack.clj b/src/metabase/channel/impl/slack.cljindex ba3b21fb1c7..61f3ad500b5 100644--- a/src/metabase/channel/impl/slack.clj+++ b/src/metabase/channel/impl/slack.clj@@ -154,8 +154,9 @@(slack/upload-file-to-channel! (:bytes pdf) (:filename pdf) channel (:comment pdf))(catch Throwable e(log/error e "Error sharing dashboard subscription PDF to Slack; posting summary without the PDF")- (when-let [comment (:comment pdf)]- (slack/post-chat-message! {:channel channel :text comment}))))))+ ;; A DM already delivers the caption as the message that opens the conversation, so don't re-post it.+ (when (and (:comment pdf) (not (::slack/caption-already-posted? (ex-data e))))+ (slack/post-chat-message! {:channel channel :text (:comment pdf)}))))));; ------------------------------------------------------------------------------------------------;;;; System Event Notifications ;;diff --git a/src/metabase/channel/settings.clj b/src/metabase/channel/settings.cljindex 80ef4abc1eb..b09b0bc6943 100644--- a/src/metabase/channel/settings.clj+++ b/src/metabase/channel/settings.clj@@ -56,10 +56,10 @@:export? false)(defn process-files-channel-name- "Converts empty strings to `nil`, and removes leading `#` from the channel name if present."+ "Converts empty strings to `nil`, and removes a leading `#` (channel) or `@` (user) from the name if present."[channel-name](when-not (str/blank? channel-name)- (if (str/starts-with? channel-name "#") (subs channel-name 1) channel-name)))+ (if (contains? #{\# \@} (first channel-name)) (subs channel-name 1) channel-name)))(defn find-cached-slack-channel-or-username"Look up a Slack channel or username by name or ID in [[slack-cached-channels-and-usernames]].diff --git a/src/metabase/channel/slack.clj b/src/metabase/channel/slack.cljindex 05720255dbb..aff816adc6d 100644--- a/src/metabase/channel/slack.clj+++ b/src/metabase/channel/slack.clj@@ -324,10 +324,37 @@(catch Throwable e(log/warnf e "Could not join Slack channel %s; a file share may fail" channel-id))))+(declare post-chat-message!)++(def ^:private slack-user-id-pattern+ "Slack user IDs start with U (people) or W (Enterprise Grid). Unlike channel IDs (C/G/D/Z), they are rejected by+ `files.completeUploadExternal`, so a file shared with a user must target their DM channel instead."+ #"^[UW][A-Z0-9]{8,}$")++(defn- open-dm-channel-id!+ "Resolve the direct-message channel ID (`D…`) for Slack user `user-id` by posting `text` via `chat.postMessage`,+ whose response carries the opened DM's channel ID. This needs only `chat:write` (already granted), avoiding the+ `im:write` scope `conversations.open` would require. The caller therefore shares the file into the DM *without* an+ `initial-comment`, since `text` was already delivered as this message."+ [user-id text]+ (:channel (post-chat-message! {:channel user-id, :text text})))++(defn- complete-upload!+ "Get an upload URL from Slack, push the `file` bytes to it, and complete the upload — sharing into `channel-id` with+ `initial-comment` as the message text when provided. Returns the uploaded file URL."+ [file filename channel-id initial-comment]+ (let [{:keys [upload_url file_id]} (get-upload-url! filename file)]+ (upload-file-to-url! upload_url file)+ (complete! {:file-id file_id+ :filename filename+ :channel-id channel-id+ :initial-comment initial-comment})))+(mu/defn upload-file-to-channel!- "Upload `file` bytes to Slack and share them into `channel-id` as a downloadable file. Returns the uploaded file URL.- Joins the channel first, since file sharing requires membership. `initial-comment` (mrkdwn, optional) becomes the- text of the file's message, so the file and a caption arrive as a single message."+ "Upload `file` bytes to Slack and share them as a downloadable file; returns the file URL. `channel-id` may be a+ channel ID, a user ID, or a legacy display name (\"#general\"/\"@bob\") resolved via the cached channel/user list.+ A channel is joined and gets the file with `initial-comment` (mrkdwn, optional) as its caption in one message; a+ user is DM'd, with the caption sent as the DM opener and the file following."([file filename channel-id](upload-file-to-channel! file filename channel-id nil))([file :- NonEmptyByteArray@@ -335,13 +362,19 @@channel-id :- ms/NonBlankStringinitial-comment :- [:maybe :string]]{:pre [(channel.settings/slack-configured?)]}- (join-channel! channel-id)- (let [{:keys [upload_url file_id]} (get-upload-url! filename file)]- (upload-file-to-url! upload_url file)- (complete! {:file-id file_id- :filename filename- :channel-id channel-id- :initial-comment initial-comment}))))+ (let [target (or (:id (channel.settings/find-cached-slack-channel-or-username channel-id)) channel-id)]+ (if (re-matches slack-user-id-pattern target)+ ;; User: open the DM with the caption (chat.postMessage), then share the file — caption already sent.+ (let [dm-channel-id (open-dm-channel-id! target (or (not-empty initial-comment) filename))]+ (try+ (complete-upload! file filename dm-channel-id nil)+ (catch Throwable e+ ;; Caption already went out as the DM opener; flag so `send!`'s fallback doesn't re-post it.+ (throw (ex-info (ex-message e) (assoc (ex-data e) ::caption-already-posted? true) e)))))+ ;; Channel: join (membership required), then share the file with the caption as its message.+ (do+ (join-channel! target)+ (complete-upload! file filename target initial-comment))))))(mu/defn post-chat-message!"Calls Slack API `chat.postMessage` endpoint and posts a message to a channel.diff --git a/test/metabase/channel/impl/slack_test.clj b/test/metabase/channel/impl/slack_test.cljindex b7763226b7e..808f5b152e4 100644--- a/test/metabase/channel/impl/slack_test.clj+++ b/test/metabase/channel/impl/slack_test.clj@@ -42,6 +42,24 @@(is (every? #(<= 1 (count %) 50) @block-inputs))(is (= 423 (reduce + (map count @block-inputs)))))))+(deftest pdf-share-failure-fallback-test+ (let [pdf {:bytes (byte-array [1 2 3]) :filename "dash.pdf" :comment "the caption"}]+ (testing "when sharing the PDF into a channel fails, send! posts the caption as a fallback summary"+ (let [posted (atom [])]+ (mt/with-dynamic-fn-redefs [slack/upload-file-to-channel! (fn [& _] (throw (ex-info "boom" {})))+ slack/post-chat-message! (fn [m] (swap! posted conj m))]+ (channel/send! {:type :channel/slack}+ {:channel "C0CHANNEL" :blocks [] :pdf pdf})+ (is (= [{:channel "C0CHANNEL" :text "the caption"}] @posted)))))+ (testing "when sharing to a DM fails after the caption was delivered as the opener, send! does not re-post it"+ (let [posted (atom [])]+ (mt/with-dynamic-fn-redefs [slack/upload-file-to-channel! (fn [& _]+ (throw (ex-info "boom" {::slack/caption-already-posted? true})))+ slack/post-chat-message! (fn [m] (swap! posted conj m))]+ (channel/send! {:type :channel/slack}+ {:channel "U0USER123" :blocks [] :pdf pdf})+ (is (= [] @posted)))))))+(deftest mkdwn-link-escaping-test(let [parts [{:type :card:card {:id 1diff --git a/test/metabase/channel/settings_test.clj b/test/metabase/channel/settings_test.cljindex bc7957dfcbb..3bf3265b43b 100644--- a/test/metabase/channel/settings_test.clj+++ b/test/metabase/channel/settings_test.clj@@ -92,6 +92,9 @@(testing "finds by name with # prefix"(is (= {:display-name "#data-team" :name "data-team" :id "C002"}(channel.settings/find-cached-slack-channel-or-username "#data-team"))))+ (testing "finds a user by name with @ prefix"+ (is (= {:display-name "@alice" :name "alice" :id "U001"}+ (channel.settings/find-cached-slack-channel-or-username "@alice"))))(testing "finds by ID"(is (= {:display-name "@alice" :name "alice" :id "U001"}(channel.settings/find-cached-slack-channel-or-username "U001"))))diff --git a/test/metabase/channel/slack_test.clj b/test/metabase/channel/slack_test.cljindex a5966692e6a..968af62f29e 100644--- a/test/metabase/channel/slack_test.clj+++ b/test/metabase/channel/slack_test.clj@@ -215,6 +215,98 @@(is (= "C0CHANNEL" (:channel_id params)))(is (= "*Aviary KPIs*" (:initial_comment params))))))))))+(deftest upload-file-to-channel!-user-dm-test+ (testing "upload-file-to-channel! opens a DM and shares the file there when the target is a user ID"+ ;; `files.completeUploadExternal` rejects user IDs (`U…`; its `channel_id` must match `^[CGDZ][A-Z0-9]{8,}$`), so+ ;; a file shared with a user must target the DM channel (`D…`). We resolve it via `chat.postMessage` (which needs+ ;; only `chat:write`) rather than `conversations.open` (which needs `im:write`).+ (let [file-bytes (.getBytes "fake-pdf")+ filename "dashboard.pdf"+ upload-url "https://files.slack.com/upload/v1/CwABAAAAWgoAAZnBg"+ complete-req (atom nil)+ post-req (atom nil)+ open-called? (atom false)+ join-called? (atom false)+ fake-routes {#"^https://slack.com/api/chat\.postMessage.*"+ (fn [req]+ (reset! post-req req)+ (mock-200-response {:ok true :channel "D0DM45678"}))++ #"^https://slack.com/api/conversations\.open.*"+ (fn [_] (reset! open-called? true) (mock-200-response {:ok true :channel {:id "D0DM45678"}}))++ #"^https://slack.com/api/conversations\.join.*"+ (fn [_] (reset! join-called? true)+ (mock-200-response (slurp "./test_resources/slack_conversations_join_response.json")))++ #"^https://slack.com/api/files\.getUploadURLExternal.*"+ (fn [_] (mock-200-response {:ok true+ :upload_url upload-url+ :file_id "DDDDDDDDD-EEEEEEEEE"}))++ upload-url+ (fn [_] (mock-200-response "OK"))++ #"^https://slack.com/api/files\.completeUploadExternal.*"+ (fn [req]+ (reset! complete-req req)+ (mock-200-response (slurp "./test_resources/slack_upload_file_response.json")))}]+ (http-fake/with-fake-routes fake-routes+ (mt/with-temporary-setting-values [slack-app-token "test-token"]+ (is (= "https://files.slack.com/files-pri/DDDDDDDDD-EEEEEEEEE/wow.gif"+ (slack/upload-file-to-channel! file-bytes filename "U0USER123" "*Aviary KPIs*")))+ (testing "opens the DM by posting the caption to the user ID via chat.postMessage"+ (let [b (:body @post-req)+ body (if (string? b) b (slurp b))]+ (is (re-find #"channel=U0USER123" body))+ (is (re-find #"Aviary" body))))+ (testing "uses neither conversations.open (needs im:write) nor conversations.join (DMs need no membership)"+ (is (false? @open-called?))+ (is (false? @join-called?)))+ (testing "shares the file into the resolved DM channel, not the raw user ID"+ (let [params (parse-query-string (:query-string @complete-req))]+ (is (= "D0DM45678" (:channel_id params)))+ (testing "without a duplicate initial_comment (the caption was the chat.postMessage)"+ (is (nil? (:initial_comment params)))))))))))++(deftest upload-file-to-channel!-resolves-display-name-test+ (testing "a legacy display name (\"@bob\") with no stored ID resolves to its user ID via the cache, then DMs the user"+ ;; Subscriptions created before channel-ID storage (GDGT-232) fall back to the display-name `:value`; "@bob" must+ ;; resolve to its `U…` ID through find-cached-slack-channel-or-username before the user-vs-channel routing.+ (let [file-bytes (.getBytes "fake-pdf")+ filename "dashboard.pdf"+ upload-url "https://files.slack.com/upload/v1/CwABAAAAWgoAAZnBg"+ complete-req (atom nil)+ post-req (atom nil)+ fake-routes {#"^https://slack.com/api/chat\.postMessage.*"+ (fn [req]+ (reset! post-req req)+ (mock-200-response {:ok true :channel "D0BOBDM12"}))++ #"^https://slack.com/api/files\.getUploadURLExternal.*"+ (fn [_] (mock-200-response {:ok true :upload_url upload-url :file_id "DDDDDDDDD-EEEEEEEEE"}))++ upload-url+ (fn [_] (mock-200-response "OK"))++ #"^https://slack.com/api/files\.completeUploadExternal.*"+ (fn [req]+ (reset! complete-req req)+ (mock-200-response (slurp "./test_resources/slack_upload_file_response.json")))}]+ (http-fake/with-fake-routes fake-routes+ (mt/with-temporary-setting-values [slack-app-token "test-token"+ slack-cached-channels-and-usernames {:channels [{:display-name "@bob"+ :name "bob"+ :id "U0BOB1234"+ :type "user"}]}]+ (slack/upload-file-to-channel! file-bytes filename "@bob" "*Aviary KPIs*")+ (testing "posts the DM opener to the resolved user ID, not the raw \"@bob\""+ (let [b (:body @post-req)+ body (if (string? b) b (slurp b))]+ (is (re-find #"channel=U0BOB1234" body))))+ (testing "shares the file into the resulting DM channel"+ (is (= "D0BOBDM12" (:channel_id (parse-query-string (:query-string @complete-req)))))))))))+(deftest post-chat-message!-test(testing "post-chat-message!"(http-fake/with-fake-routes {#"^https://slack.com/api/chat\.postMessage.*" (fn [_]