Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add a feedback dialog box #93

Closed
wants to merge 30 commits into from
Closed
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
b25c109
Initial commit
Jun 13, 2019
faf06fc
Don't use relative imports
Jun 13, 2019
644b52a
Specifying bot OAuth token should be user-developer's concern
Jun 13, 2019
9dc5122
Unify image interface
Jun 13, 2019
8e9dcc8
Further simplify image interface
Jun 14, 2019
f2fb60b
Modify import
Jun 17, 2019
fc6e146
Use single name field and use property for message
Jun 17, 2019
4057d6d
Fix bug in msg getter
Jun 17, 2019
2afabb7
Added comments
Jun 17, 2019
b94d489
Added comment regarding asynchronous functionality.
Jun 18, 2019
b6e7b01
Refactor send function
Jun 19, 2019
82bd9dc
Better error handling and notification dialogs in controller.
Jun 19, 2019
40bcab8
Refactor logic and introduce logging.
Jun 20, 2019
a5471da
Improve comments
Jun 20, 2019
2a304a8
Use HasRequiredTraits
Jun 21, 2019
beb3813
Add tests.
Jun 21, 2019
7c407d7
Bugfix in example
Jun 21, 2019
40f47fd
Use custom style for Description field
Jun 21, 2019
b7da2c2
PEP8 compliance
Jun 21, 2019
0db10aa
Put error dialog test in a helper function.
Jun 24, 2019
f60992c
Compress image inside send function.
Jun 25, 2019
1a61255
Fix incorrect syntax for metadata dependence.
Jun 25, 2019
b34a768
Add test to ensure files_upload is called correctly
Jun 27, 2019
ef1a643
Remove trailing _
Jun 27, 2019
1ee8f74
Remove trailing _
Jun 27, 2019
d7ffe07
Move example file
Jun 27, 2019
e659e49
Add comments + fix typos
Jun 27, 2019
133a35f
Add README
Jun 28, 2019
12691b6
Fix typos in README
Jun 28, 2019
d651bf8
Fixed typo in function name
Jun 28, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions apptools/feedback/examples/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is better placed in /examples/feedback instead of apptools/feedback/examples.

Feedback Dialog Example
=========================

This example shows how the feedback dialog can be included in an application.
The client-user interface is described in the
FeedbackExampleApp.client_user_explanation attribute. All other comments are
aimed at the developer interested in including the feedback dialog in their
app (see especially `feedback_example_view` and the `FeedbackExampleHandler`
class).

"""

import os

from traits.api import HasTraits, Str
from traitsui.api import (
Item, Menu, MenuBar, OKCancelButtons, View, Action, Handler
)

from apptools.feedback.feedbackbot.utils import initiate_feedback_dialog_


class FeedbackExampleApp(HasTraits):
""" A simple model to demonstrate the feedback dialog."""

#: This attribute explains the client-user interface.
client_user_explanation = Str

def _client_user_explanation_default(self):

return """
This app demonstrates how to use the feedback dialog.

To begin, click on Feedback/Bugs in the Help menu. This will
automatically take a screenshot of this app, and launch the feedback
dialog box. You should be able to see a preview of the
screenshot in the dialog box.

Next, enter your details, and a description of the problem. All fields
are mandatory, and you can't send the message till you type something
in each field. When you're done, click on the Send button. The dialog
is pre-configured by our developers to ensure it reaches
the right team.

The dialog will notify you of successful delivery of the message, or if
any problems occured."""


# View for the example app. The feedbackbot module provides a helper function
# `initiate_feedback_dialog_` that launches the feedback dialog box. To include
# the feedback dialog box in the app, simply call this function from an
# appropriate place. In this example, we call it from the Feedback/Bugs menu
# item in the Help menu.
feedback_example_view = View(
Item('client_user_explanation', style='readonly', show_label=False),
menubar=MenuBar(
Menu(
Action(name='Feedback/Bugs', action='initiate_feedback_dialog'),
name='Help'),
),
buttons=OKCancelButtons,
width=480,
height=320,
title='Example App',
resizable=True,
)


class FeedbackExampleHandler(Handler):
""" Simple handler for the FeedbackExampleApp. """

def initiate_feedback_dialog(self, ui_info):
""" Initiates the feedback dialog. """

# As mentioned earlier, the feedback dialog can be initiated by
# invoking the `initiate_feedback_dialog_` function. The first argument
# to this function is the control object whose screenshot will be
# grabbed. The second argument is the OAuth token for the bot (see
# the feedbackbot README for an explanation). In practice, you (the
# user-developer) will have to decide on an appropriate way to
# pass around the token (again, see the README for a discussion on what
# could go wrong if the token gets leaked.). The third argument is the
# channel where you'd like messages from this app to go. The value for
# this argument must start with '#'.
initiate_feedback_dialog_(ui_info.ui.control,
os.environ['FEEDBACKBOT_OAUTH_TOKEN'],
'#general')


if __name__ == '__main__':

app = FeedbackExampleApp()

app.configure_traits(view=feedback_example_view,
handler=FeedbackExampleHandler())
Empty file.
100 changes: 100 additions & 0 deletions apptools/feedback/feedbackbot/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""
This module implements a class that provides logic for a simple plugin
for sending messages to a developer team's slack channel.
"""

import io
import logging

import slack
from PIL import Image

from traits.api import (
HasRequiredTraits, Str, Property, Array, String, Any)

logger = logging.getLogger(__name__)


class FeedbackMessage(HasRequiredTraits):
""" Model for the feedback message.

Notes
-----
The user-developer must specify the slack channel that the message must be
sent to, as well as provide raw screenshot data.

"""

#: Name of the client user
name = Str(msg_meta=True)

#: Name of the client organization.
organization = Str(msg_meta=True)

# TODO: Slack supports some markdown in messages, provide
# some details here.
#: Main body of the feedback message.
description = Str(msg_meta=True)

#: The target slack channel that the bot will post to, must start with #
# and must be provided by the user-developer.
channels = String(minlen=2, regex='#.*', required=True)

#: OAuth token for the slackbot, must be provided by the user-developer.
token = Str(required=True)

#: The final message that gets posted to Slack.
msg = Property(Str, depends_on='msg_meta')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this should be depends_on='+msg_meta'. It would be good to make this consistent with the syntax in the view.


#: 3D numpy array to hold three channel (RGB) screenshot pixel data.
img_data = Array(shape=(None, None, 3), dtype='uint8', required=True)

# FIXME: Not sure if this the right way to go about initiating a
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The right way to do this would be
compressed_img_buf = Instance(io.BytesIO, args=()).

The args= part says what to use when initializing the type (io.BytesIO).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(That said, this works. I've never seen it done this way before.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Upon closer inspection, this is only used by the send method. It's probably best to not make it a trait and create the buffer as needed inside of send.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved it out assuming that it would reduce time spent in the send function. Some more experiments revealed that while time spent in send is reduced (1.57s to 1.5s), the difference is barely noticeable by the user, so now it's back in. (Note to self: time everything)

# non-Trait.
#: In-memory file buffer to store the compressed screenshot.
compressed_img_buf = Any(io.BytesIO())

def _get_msg(self):

feedback_template = 'Name: {name}\n' \
+ 'Organization: {org}\nDescription: {desc}'

return feedback_template.format(
name=self.name,
org=self.organization,
desc=self.description)

def _img_data_changed(self):

Image.fromarray(self.img_data).save(self.compressed_img_buf, 'PNG')
self.compressed_img_buf.seek(0)

def send(self):
""" Send feedback message and screenshot to Slack. """

# Set up object that talks to Slack's API. Note that the run_async
# flag is False. This ensures that each HTTP request is blocking. More
# precisely, the WebClient sets up an event loop with just a single
# HTTP request in it, and ensures that the event loop runs to
# completion before returning.
client = slack.WebClient(token=self.token,
timeout=5,
ssl=True,
run_async=False)

logger.info("Attempting to send message: <%s> to channel: <%s>",
self.msg, self.channels)

# Send message.
response = client.files_upload(
channels=self.channels,
initial_comment=self.msg,
filetype='png',
filename='screenshot.png',
file=self.compressed_img_buf)

logger.info("Message sent."
+ " Slack responded with OK : {ok_resp}".format(
ok_resp=response['ok']))

return response
43 changes: 43 additions & 0 deletions apptools/feedback/feedbackbot/tests/test_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
Tests for FeedbackMessage model.
"""

import numpy as np
import unittest

from traits.api import TraitError
from traits.testing.unittest_tools import UnittestTools

from apptools.feedback.feedbackbot.model import FeedbackMessage


class TestFeedbackMessage(unittest.TestCase, UnittestTools):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are essentially testing traits. It would be better to test the logic in the send method. This can be done by mocking slack.WebClient.files_upload and checking that the right information is passed.


def test_invalid_img_data_raises_error(self):
""" Test that setting img_data to an incorrectly shaped array
raises a TraitError.

"""

with self.assertRaises(TraitError):

FeedbackMessage(img_data=np.empty((2, 2)),
token='xoxb-123456',
channels='#general')

def test_invalid_channel_raises_error(self):
""" Test that passing a channel name that doesn't begin with
'#' raises TraitError.

"""

with self.assertRaises(TraitError):

FeedbackMessage(img_data=np.empty((1, 1, 3)),
token='xoxb-123456',
channels='general')


if __name__ == '__main__':

unittest.main()
Loading