Skip to content

Commit 41da052

Browse files
committed
[slack] Aggregate link_unfurl logic and its UTs
1 parent 1833c2d commit 41da052

File tree

2 files changed

+73
-83
lines changed

2 files changed

+73
-83
lines changed

desktop/core/src/desktop/lib/botserver/views.py

Lines changed: 29 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def parse_events(event):
7878

7979

8080
def handle_on_message(channel_id, bot_id, text, user_id):
81-
# ignore bot's own message since that will cause an infinite loop of messages if we respond.
81+
# Ignore bot's own message since that will cause an infinite loop of messages if we respond.
8282
if bot_id:
8383
return HttpResponse(status=200)
8484

@@ -93,84 +93,26 @@ def handle_on_message(channel_id, bot_id, text, user_id):
9393
def handle_on_link_shared(channel_id, message_ts, links):
9494
for item in links:
9595
path = urlsplit(item['url'])[2]
96-
queryid_or_uuid = urlsplit(item['url'])[3] # if /hue/editor/ then query_id else if /hue/gist then uuid
97-
98-
if path == '/hue/editor':
99-
query_id = queryid_or_uuid.split('=')[1]
100-
doc2 = Document2.objects.get(id=query_id)
101-
doc2_data = json.loads(doc2.data)
102-
103-
statement = doc2_data['snippets'][0]['statement_raw']
104-
dialect = doc2_data['dialect'].capitalize()
105-
database = doc2_data['snippets'][0]['database'].capitalize()
106-
107-
payload = make_query_history_payload(item['url'], statement, dialect, database)
108-
response = slack_client.chat_unfurl(channel=channel_id, ts=message_ts, unfurls=payload)
109-
if response['ok']:
110-
raise PopupException(_("Cannot unfurl query history link"), detail=response["error"])
111-
112-
if path == '/hue/gist' and ENABLE_GIST_PREVIEW.get():
113-
gist_uuid = queryid_or_uuid.split('=')[1]
114-
gist_doc = _get_gist_document(uuid=gist_uuid)
115-
gist_doc_data = json.loads(gist_doc.data)
116-
117-
statement = gist_doc_data['statement_raw']
118-
created_by = gist_doc.owner.get_full_name() or gist_doc.owner.username
119-
dialect = gist_doc.extra.capitalize()
120-
121-
payload = make_gist_payload(item['url'], statement, dialect, created_by)
122-
response = slack_client.chat_unfurl(channel=channel_id, ts=message_ts, unfurls=payload)
123-
if not response['ok']:
124-
raise PopupException(_("Cannot unfurl gist link"), detail=response["error"])
125-
126-
def say_hi_user(channel_id, user_id):
127-
"""
128-
Sends Hi<user_id> message in a specific channel.
129-
130-
"""
131-
bot_message = 'Hi <@{}> :wave:'.format(user_id)
132-
return slack_client.api_call(api_method='chat.postMessage', json={'channel': channel_id, 'text': bot_message})
133-
134-
135-
def make_gist_payload(url, statement, dialect, created_by):
136-
gist_payload = {
137-
url: {
138-
"color": "#025BA6",
139-
"blocks": [
140-
{
141-
"type": "section",
142-
"text": {
143-
"type": "mrkdwn",
144-
"text": "\n*<{}|Hue - SQL Gist>*".format(url)
145-
}
146-
},
147-
{
148-
"type": "section",
149-
"text": {
150-
"type": "mrkdwn",
151-
"text": statement if len(statement) < 150 else (statement[:150] + '...')
152-
}
153-
},
154-
{
155-
"type": "section",
156-
"fields": [
157-
{
158-
"type": "mrkdwn",
159-
"text": "*Dialect:*\n{}".format(dialect)
160-
},
161-
{
162-
"type": "mrkdwn",
163-
"text": "*Created By:*\n{}".format(created_by)
164-
}
165-
]
166-
}
167-
]
168-
}
169-
}
170-
return gist_payload
171-
172-
173-
def make_query_history_payload(url, statement, dialect, database):
96+
id_type, qid_or_uuid = urlsplit(item['url'])[3].split('=')
97+
98+
if path == '/hue/editor' and id_type == 'editor':
99+
doc = Document2.objects.get(id=qid_or_uuid)
100+
elif path == '/hue/gist' and id_type == 'uuid' and ENABLE_GIST_PREVIEW.get():
101+
doc = _get_gist_document(uuid=qid_or_uuid)
102+
else:
103+
raise PopupException(_("Cannot unfurl link"))
104+
105+
doc_data = json.loads(doc.data)
106+
statement = doc_data['snippets'][0]['statement_raw'] if id_type == 'editor' else doc_data['statement_raw']
107+
dialect = doc_data['dialect'].capitalize() if id_type == 'editor' else doc.extra.capitalize()
108+
created_by = doc.owner.get_full_name() or doc.owner.username
109+
110+
payload = _make_unfurl_payload(item['url'], statement, dialect, created_by)
111+
response = slack_client.chat_unfurl(channel=channel_id, ts=message_ts, unfurls=payload)
112+
if not response['ok']:
113+
raise PopupException(_("Cannot unfurl link"), detail=response["error"])
114+
115+
def _make_unfurl_payload(url, statement, dialect, created_by):
174116
payload = {
175117
url: {
176118
"color": "#025BA6",
@@ -198,7 +140,7 @@ def make_query_history_payload(url, statement, dialect, database):
198140
},
199141
{
200142
"type": "mrkdwn",
201-
"text": "*Database:*\n{}".format(database)
143+
"text": "*Created By:*\n{}".format(created_by)
202144
}
203145
]
204146
}
@@ -207,3 +149,10 @@ def make_query_history_payload(url, statement, dialect, database):
207149
}
208150
return payload
209151

152+
def say_hi_user(channel_id, user_id):
153+
"""
154+
Sends Hi<user_id> message in a specific channel.
155+
156+
"""
157+
bot_message = 'Hi <@{}> :wave:'.format(user_id)
158+
return slack_client.api_call(api_method='chat.postMessage', json={'channel': channel_id, 'text': bot_message})

desktop/core/src/desktop/lib/botserver/views_tests.py

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,16 @@
2020
import unittest
2121
import sys
2222

23-
from nose.tools import assert_equal, assert_true, assert_false
23+
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
2424
from nose.plugins.skip import SkipTest
25-
from django.test import TestCase, Client
25+
from django.test import TestCase
26+
2627
from desktop.lib.botserver.views import *
2728
from desktop import conf
29+
from desktop.models import Document2, _get_gist_document
30+
from desktop.lib.django_test_util import make_logged_in_client
31+
from useradmin.models import User
32+
2833

2934
if sys.version_info[0] > 2:
3035
from unittest.mock import patch
@@ -63,4 +68,40 @@ def test_handle_on_message(self):
6368
assert_false(say_hi_user.called)
6469

6570
handle_on_message("channel", None, "hello hue test", "user_id")
66-
assert_true(say_hi_user.called)
71+
assert_true(say_hi_user.called)
72+
73+
def test_handle_on_link_shared(self):
74+
with patch('desktop.lib.botserver.views.slack_client.chat_unfurl') as chat_unfurl:
75+
with patch('desktop.lib.botserver.views._make_unfurl_payload') as mock_unfurl_payload:
76+
77+
client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False)
78+
user = User.objects.get(username="test")
79+
channel_id = "channel_id"
80+
message_ts = "12345.123"
81+
82+
# qhistory link
83+
links = [{"url": "https://demo.gethue.com/hue/editor?editor=123456"}]
84+
doc_data = {
85+
"dialect": "mysql",
86+
"snippets": [{
87+
"database": "hue",
88+
"statement_raw": "SELECT 5000",
89+
}]
90+
}
91+
92+
Document2.objects.create(id=123456, data=json.dumps(doc_data), owner=user)
93+
handle_on_link_shared(channel_id, message_ts, links)
94+
mock_unfurl_payload.assert_called_with(links[0]["url"], "SELECT 5000", "Mysql", "test")
95+
assert_true(chat_unfurl.called)
96+
97+
# gist link
98+
doc_data = {"statement_raw": "SELECT 98765"}
99+
gist_doc = Document2.objects.create(id=101010, data=json.dumps(doc_data), owner=user, extra='mysql', type='gist')
100+
links = [{"url": "http://demo.gethue.com/hue/gist?uuid="+str(gist_doc.uuid)}]
101+
handle_on_link_shared(channel_id, message_ts, links)
102+
mock_unfurl_payload.assert_called_with(links[0]["url"], "SELECT 98765", "Mysql", "test")
103+
assert_true(chat_unfurl.called)
104+
105+
# Cannot unfurl link
106+
assert_raises(PopupException, handle_on_link_shared, "channel_id", "12345.123", [{"url": "https://demo.gethue.com/hue/editor/?type=4"}])
107+
assert_raises(PopupException, handle_on_link_shared, "channel_id", "12345.123", [{"url": "http://demo.gethue.com/hue/gist?uuids/=something"}])

0 commit comments

Comments
 (0)