Skip to content

Commit

Permalink
Added templates, fixed testing,
Browse files Browse the repository at this point in the history
Added some templates, fixed testing, fixed issues with resetting, should be good to go for v3.
  • Loading branch information
2blane committed May 12, 2020
1 parent 94db5d1 commit ae74456
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 11 deletions.
11 changes: 9 additions & 2 deletions octoprint_webhooks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ def get_assets(self):
return dict(
css=["css/webhooks.css"],
js=["js/webhooks.js"],
json=["templates/simple.json", "templates/fulldata.json", "templates/snapshot.json", "templates/oauth.json", "templates/dotnotation.json"]
json=["templates/simple.json", "templates/fulldata.json", "templates/snapshot.json",
"templates/oauth.json", "templates/dotnotation.json", "templates/slack.json", "templates/plivo.json"]
)

def register_custom_events(self, *args, **kwargs):
Expand Down Expand Up @@ -327,6 +328,10 @@ def on_event(self, event, payload):
topic = "Error"
message = hook["eventErrorMessage"]
else:
if "hook_index" in payload:
# This is a test event - show a message to the user that they need to enable this event.
msg = "This event is disabled. Please enable the event %s to test." % event
self._plugin_manager.send_plugin_message(self._identifier, dict(type="error", hide=False, msg=msg))
return
self._logger.info("P EVENT " + topic + " - " + message)
# 1) If necessary, make an OAuth request to get back an access token.
Expand Down Expand Up @@ -428,9 +433,11 @@ def on_event(self, event, payload):
values.update(job_values)
# 2.3) Get a snapshot image if necessary
uploading_file = False
try_to_upload_file = False
uploading_file_name = ""
for uk in data:
if data[uk] == "@snapshot":
try_to_upload_file = True
uploading_file = True
uploading_file_name = uk
break
Expand All @@ -454,7 +461,7 @@ def on_event(self, event, payload):
# Note: we can't upload a file with GET.
response = requests.get(url, params=data, headers=headers)
else:
if uploading_file:
if try_to_upload_file:
# Delete the Content-Type header if provided so that requests can set it on its own
to_remove = []
for hk in headers:
Expand Down
1 change: 1 addition & 0 deletions octoprint_webhooks/static/css/webhooks.css
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
}
.webhooksTable td {
padding: 4px;
text-overflow: ellipsis;
}
.webhooksTableActionsTD {
width: 100px;
Expand Down
26 changes: 18 additions & 8 deletions octoprint_webhooks/static/js/webhooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,23 @@ $(function() {
//Select the first hook. There should always be a selected hook.
self.selectHook(0)
//Get the list of available templates.
let templates = ["simple.json", "fulldata.json", "snapshot.json", "oauth.json", "dotnotation.json"]
let templates = ["simple.json", "fulldata.json", "snapshot.json",
"oauth.json", "dotnotation.json", "slack.json", "plivo.json"]
let callbacksLeft = templates.length;
for (let i = 0; i < templates.length; i = i + 1) {
let templateFile = "plugin/webhooks/static/templates/" + templates[i]
console.log("loading template" + templates[i])
$.getJSON(templateFile, function(data) {
console.log("json file: ", data)
self.availableTemplates.push(data)
console.log("available templates: ", self.availableTemplates())
//console.log("available templates: ", self.availableTemplates())
callbacksLeft -= 1;
if (callbacksLeft == 0) {
self.template(self.availableTemplates()[0])
console.log("selected template: ", self.template())
//console.log("selected template: ", self.template())
}
}).fail(function(jqxhr, textStatus, error) {
console.log("Failed to get the template for " + templateFile, jqxhr, textStatus, error)
})
}
}
Expand Down Expand Up @@ -186,27 +190,31 @@ $(function() {
self.selectedIndex(self.settings.settings.plugins.webhooks.hooks().length - 1)
}

self.usingSnapshot = function() {
return false
}

self.resetDataToDefaults = function() {
// Update the data to be defaulted.
self.settings.settings.plugins.webhooks.data('{\n "deviceIdentifier":"@deviceIdentifier",\n "apiSecret":"@apiSecret",\n "topic":"@topic",\n "message":"@message",\n "extra":"@extra",\n "state": "@state",\n "job": "@job",\n "progress": "@progress",\n "currentZ": "@currentZ",\n "offsets": "@offsets",\n "meta": "@meta",\n "currentTime": "@currentTime",\n "snapshot": "@snapshot"\n}')
self.selectedHook().data('{\n "deviceIdentifier":"@deviceIdentifier",\n "apiSecret":"@apiSecret",\n "topic":"@topic",\n "message":"@message",\n "extra":"@extra",\n "state": "@state",\n "job": "@job",\n "progress": "@progress",\n "currentZ": "@currentZ",\n "offsets": "@offsets",\n "meta": "@meta",\n "currentTime": "@currentTime",\n "snapshot": "@snapshot"\n}')
console.log("Webhooks Reset DATA to Defaults Pressed")
}

self.resetHeadersToDefaults = function() {
// Update the data to be defaulted.
self.settings.settings.plugins.webhooks.headers('{\n "Content-Type": "application/json"\n}')
self.selectedHook().headers('{\n "Content-Type": "application/json"\n}')
console.log("Webhooks Reset HEADERS to Defaults Pressed")
}

self.resetOAuthDataToDefaults = function() {
// Update the data to be defaulted.
self.settings.settings.plugins.webhooks.oauth_data('{\n "client_id":"myClient",\n "client_secret":"mySecret",\n "grant_type":"client_credentials"\n}')
self.selectedHook().oauth_data('{\n "client_id":"myClient",\n "client_secret":"mySecret",\n "grant_type":"client_credentials"\n}')
console.log("Webhooks Reset OAUTH_DATA to Defaults Pressed")
}

self.resetOAuthHeadersToDefaults = function() {
// Update the data to be defaulted.
self.settings.settings.plugins.webhooks.oauth_headers('{\n "Content-Type": "application/json"\n}')
self.selectedHook().oauth_headers('{\n "Content-Type": "application/json"\n}')
console.log("Webhooks Reset OAUTH_HEADERS to Defaults Pressed")
}

Expand All @@ -233,12 +241,14 @@ $(function() {
// 1) Save the user settings.
data = ko.mapping.toJS(self.settings.settings.plugins.webhooks);
console.log("WEBHOOKS - ", data)
console.log("SELECT VALUE - ", self.selectedHook().test_event(), document.getElementById("selectTestEvent").value)
return OctoPrint.settings.savePluginSettings("webhooks", data)
.done(function(data, status, xhr) {
//saved
console.log("settings saved")
// 2) Send a test event to the python backend.
event = self.settings.settings.plugins.webhooks.test_event()
event = self.selectedHook().test_event()
console.log("TEST EVENT - ", event)
client.postJson("api/plugin/webhooks", {"command":"testhook", "event":event, "hook_index": self.selectedIndex()})
})
.fail(function(xhr, status, error) {
Expand Down
18 changes: 18 additions & 0 deletions octoprint_webhooks/static/templates/plivo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"url": "https://api.plivo.com/v1/Account/TODO_REPLACE_WITH_YOUR_AUTH_ID/Message/",
"content_type": "JSON",
"data": "{\n \"src\": \"TODO_REPLACE_WITH_YOUR_PLIVO_PHONE_NUMBER\",\n \"dst\": \"TODO_REPLACE_WITH_YOUR_PHONE_NUMBER\",\n \"text\": \"@message on printer @deviceIdentifier\"\n}",
"eventErrorMessage": "There was an error.",
"eventPrintDoneMessage": "Your print is done.",
"eventPrintFailedMessage": "Something went wrong and your print has failed.",
"eventPrintPausedMessage": "Your print has paused. You might need to change the filament color.",
"eventPrintProgressMessage": "Your print is @percentCompleteMilestone % complete.",
"eventPrintStartedMessage": "Your print has started",
"eventUserActionNeededMessage": "User action needed. You might need to change the filament color.",
"event_print_progress_interval": "50",
"headers": "{\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Basic TODO_REPLACE_WITH_YOUR_BASE_64_ENCODED_STRING_OF(auth_id:auth_token)\"\n}",
"http_method": "POST",
"oauth": false,
"_name": "Plivo Message",
"_description": "This template allows you to send a text message to your phone integrating with Plivo. 1) In the URL insert your AUTH_ID found on your Plivo dashboard. 2) Inside Advanced - DATA, replace 'src' and 'dst' with the sending and receiving phone number (src is the Plivo number, dst is your phone number) no spaces or characters. For example: 12223334444 instead of 1 (222) 333-4444. 3) Inside HEADERS, you need to set base64_encode(auth_id:auth_token). You can use this site: https://www.base64encode.org to do that. Just put auth_id:auth_token in the box, hit encode, then copy and paste the response into the HEADERS field where it says TODO. When you are done, it should look similar to 'BASIC AJkldsjfownvdjfosjfOISDfbowef=='"
}
17 changes: 17 additions & 0 deletions octoprint_webhooks/static/templates/slack.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"content_type": "JSON",
"data": "{\n \"text\": \"@message on printer @deviceIdentifier\",\n \"icon_emoji\": \":octopus:\",\n \"username\": \"OctoPrint-Webhooks\"\n}",
"eventErrorMessage": "There was an error.",
"eventPrintDoneMessage": "Your print is done.",
"eventPrintFailedMessage": "Something went wrong and your print has failed.",
"eventPrintPausedMessage": "Your print has paused. You might need to change the filament color.",
"eventPrintProgressMessage": "Your print is @percentCompleteMilestone % complete.",
"eventPrintStartedMessage": "Your print has started",
"eventUserActionNeededMessage": "User action needed. You might need to change the filament color.",
"event_print_progress_interval": "50",
"headers": "{\n \"Content-Type\": \"application/json\"\n}",
"http_method": "POST",
"oauth": false,
"_name": "Slack Message",
"_description": "This template will send a message to your Slack Team. Inside Slack, you need to add an app called 'Incoming WebHooks'. Copy and paste the Webhook URL as the URL for this webhook. Then, you should be able to test out your integration and see a message appear in the channel you defined within Slack. Note: your URL should look something like https://hooks.slack.com/services/ABC/DEF/123"
}
6 changes: 5 additions & 1 deletion octoprint_webhooks/templates/webhooks_settings.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<span class="webhookDisabledTag" data-bind="css: { 'hideElement' : webhook_enabled() }">Disabled</span>
<span class="webhookOAuthTag" data-bind="css: { 'hideElement' : !oauth() }">OAuth</span>
<!-- URL -->
<span data-bind="text: url().length == 0 ? 'New Webhook' : url()" }></span>
<span css="text-overflow:ellipsis;" data-bind="text: url().length == 0 ? 'New Webhook' : url()" }></span>

<br/>
<!-- EVENTS -->
Expand Down Expand Up @@ -385,6 +385,10 @@
<div class="control-description">
Provide a JSON dictionary of parameters that will be passed along with each request.
</div>
<div class="control-description" style="margin-top:-10px;font-weight:600;" data-bind="css: { 'hideElement': !data().includes('@snapshot') }">
NOTE: Because you have used @snapshot, the Content-Type will automatically get overridden to 'form/multipart-data'
so the image can be sent in the API request.
</div>
</div>


Expand Down

0 comments on commit ae74456

Please sign in to comment.