Skip to content

Commit 3d3e9b8

Browse files
committed
Refactor ngrokwebhook.py
Apply consistency updates as per other example script updates. Refactor to use ngrok client API and restructure code.
1 parent 591b95b commit 3d3e9b8

File tree

1 file changed

+104
-69
lines changed

1 file changed

+104
-69
lines changed

examples/ngrokwebhook.py

100644100755
Lines changed: 104 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,108 @@
1-
#sample script that reads ngrok info from localhost:4040 and create Cisco Spark Webhook
2-
#typicall ngrok is called "ngrok http 8080" to redirect localhost:8080 to Internet
3-
#accesible ngrok url
4-
#
5-
#To use script simply launch ngrok, then launch this script. After ngrok is killed, run this
6-
#script a second time to remove webhook from Cisco Spark
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""Sample script to read local ngrok info and create a corresponding webhook.
4+
5+
Sample script that reads ngrok info from the local ngrok client api and creates
6+
a Cisco Spark Webhook pointint to the ngrok tunnel's public HTTP URL.
7+
8+
Typically ngrok is called run with the following syntax to redirect an
9+
Internet accesible ngrok url to localhost port 8080:
10+
11+
$ ngrok http 8080
12+
13+
To use script simply launch ngrok, and then launch this script. After ngrok is
14+
killed, run this script a second time to remove webhook from Cisco Spark.
15+
16+
"""
17+
18+
19+
# Use future for Python v2 and v3 compatibility
20+
from __future__ import (
21+
absolute_import,
22+
division,
23+
print_function,
24+
unicode_literals,
25+
)
26+
from builtins import *
27+
28+
29+
__author__ = "Brad Bester"
30+
__author_email__ = "[email protected]"
31+
__contributors__ = ["Chris Lunsford <[email protected]>"]
32+
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
33+
__license__ = "MIT"
734

835

9-
import requests
10-
import json
11-
import re
1236
import sys
13-
import requests.packages.urllib3
14-
requests.packages.urllib3.disable_warnings()
15-
from ciscosparkapi import CiscoSparkAPI, Webhook
16-
17-
def findwebhookidbyname(api, webhookname):
18-
webhooks = api.webhooks.list()
19-
for wh in webhooks:
20-
if wh.name == webhookname:
21-
return wh.id
22-
return "not found"
23-
24-
#Webhook attributes
25-
webhookname="testwebhook"
26-
resource="messages"
27-
event="created"
28-
url_suffix="/sparkwebhook"
29-
30-
#grab the at from a local at.txt file instead of global variable
31-
fat=open ("at.txt","r+")
32-
at=fat.readline().rstrip()
33-
fat.close
34-
35-
api = CiscoSparkAPI(at)
36-
37-
#go to the localhost page for nogrok and grab the public url for http
38-
try:
39-
ngrokpage = requests.get("http://127.0.0.1:4040").text
40-
except:
41-
print ("no ngrok running - deleting webhook if it exists")
42-
whid=findwebhookidbyname(api, webhookname)
43-
if "not found" in whid:
44-
print ("no webhook found")
45-
sys.exit()
46-
else:
47-
print (whid)
48-
dict=api.webhooks.delete(whid)
49-
print (dict)
50-
print ("Webhook deleted")
51-
sys.exit()
52-
53-
for line in ngrokpage.split("\n"):
54-
if "window.common = " in line:
55-
ngrokjson = re.search('JSON.parse\(\"(.+)\"\)\;',line).group(1)
56-
ngrokjson = (ngrokjson.replace('\\',''))
57-
print (ngrokjson)
58-
Url = (json.loads(ngrokjson)["Session"]["Tunnels"]["command_line (http)"]["URL"])+url_suffix
59-
print (Url)
60-
61-
#check if the webhook exists by name and then create it if not
62-
whid=findwebhookidbyname(api, webhookname)
63-
64-
if "not found" in whid:
65-
#create
66-
print ("not found")
67-
dict=api.webhooks.create(webhookname, Url, resource, event)
68-
print (dict)
37+
38+
from ciscosparkapi import CiscoSparkAPI
39+
import requests
40+
41+
42+
# Find and import urljoin
43+
if sys.version_info[0] < 3:
44+
from urlparse import urljoin
6945
else:
70-
#update
71-
print (whid)
72-
dict=api.webhooks.update(whid, name=webhookname, targetUrl=Url)
73-
print (dict)
46+
from urllib.parse import urljoin
47+
48+
49+
# Constants
50+
NGROK_CLIENT_API_BASE_URL = "http://localhost:4040/api"
51+
WEBHOOK_NAME = "ngrok_webhook"
52+
WEBHOOK_URL_SUFFIX = "/sparkwebhook"
53+
WEBHOOK_RESOURCE = "messages"
54+
WEBHOOK_EVENT = "created"
55+
56+
57+
def get_ngrok_public_url():
58+
"""Get the ngrok public HTTP URL from the local client API."""
59+
try:
60+
response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels",
61+
headers={'content-type': 'application/json'})
62+
response.raise_for_status()
63+
64+
except requests.exceptions.RequestException:
65+
print("Could not connect to the ngrok client API; "
66+
"assuming not running.")
67+
return None
68+
69+
else:
70+
for tunnel in response.json()["tunnels"]:
71+
if tunnel.get("public_url", "").startswith("http://"):
72+
print("Found ngrok public HTTP URL:", tunnel["public_url"])
73+
return tunnel["public_url"]
74+
75+
76+
def delete_webhooks_with_name(spark_api, name):
77+
"""Find a webhook by name."""
78+
for webhook in spark_api.webhooks.list():
79+
if webhook.name == name:
80+
print("Deleting Webhook:", webhook.name, webhook.targetUrl)
81+
spark_api.webhooks.delete(webhook.id)
82+
83+
84+
def create_ngrok_webhook(spark_api, ngrok_public_url):
85+
"""Create a Cisco Spark webhook pointing to the public ngrok URL."""
86+
print("Creating Webhook...")
87+
webhook = spark_api.webhooks.create(
88+
name=WEBHOOK_NAME,
89+
targetUrl=urljoin(ngrok_public_url, WEBHOOK_URL_SUFFIX),
90+
resource=WEBHOOK_RESOURCE,
91+
event=WEBHOOK_EVENT,
92+
)
93+
print(webhook)
94+
print("Webhook successfully created.")
95+
return webhook
96+
97+
98+
def main():
99+
"""Delete previous webhooks. If local ngrok tunnel, create a webhook."""
100+
spark_api = CiscoSparkAPI()
101+
delete_webhooks_with_name(spark_api, name=WEBHOOK_NAME)
102+
public_url = get_ngrok_public_url()
103+
if public_url is not None:
104+
create_ngrok_webhook(spark_api, public_url)
105+
106+
107+
if __name__ == '__main__':
108+
main()

0 commit comments

Comments
 (0)