Skip to content

Commit

Permalink
Merge pull request #69 from tylerlong/master
Browse files Browse the repository at this point in the history
Add heartbeat feature to WebSocket, fix #68
  • Loading branch information
DaKingKong authored Dec 12, 2023
2 parents 1e64ac6 + 88fea17 commit 0d79ad4
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 23 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ from ringcentral import SDK

sdk = SDK('CLIENT_ID', 'CLIENT_SECRET', 'SERVER')
platform = sdk.platform()
platform.login('USERNAME', 'EXTENSION', 'PASSWORD')
platform.login(jwt='JWT_TOKEN')
```

res = platform.get('/account/~/extension/~')
print('User loaded ' + res.json().name)
Expand Down Expand Up @@ -110,7 +111,7 @@ database.append({"Customer":"Lukas","Payment":"Due","PhoneNumber":"xxxxxxxxxxx"}

sdk = SDK('CLIENT_ID', 'CLIENT_SECRET', 'SERVER')
platform = sdk.platform()
platform.login('USERNAME', 'EXTENSION', 'PASSWORD')
platform.login(jwt='JWT_TOKEN')

def sendSMS(message, number):
params = {'from': {'phoneNumber': 'USERNAME'},'to': [{'phoneNumber': number}],'text': message}
Expand Down
2 changes: 1 addition & 1 deletion dev-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Edit `.env` to specify credentials
Run a demo file like this:

```
python demo_sms.py
python3 ringcentral/demos/demo_fax.py
```


Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ observable==0.3.*
pubnub==4.*
pycryptodome==3.*
requests==2.*
websockets==11.*
websockets==11.*
25 changes: 12 additions & 13 deletions ringcentral/demos/demo_fax.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import os,time,ssl
from dotenv import load_dotenv
from ringcentral import SDK
import certifi
import urllib.request
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) # Add the project root to sys.path
from ringcentral import SDK

load_dotenv()
#env = dotenv_values(".env")
Expand All @@ -23,17 +25,14 @@ def send_fax():
'coverPageText': "This is a demo Fax page from Python"
})

with open('test.txt', "r") as f:
content = f.read()
#attachment = ('test.jpg', content)
attachment = (
'test.png',
urllib.request.urlopen('https://www.ringcentral.com/content/dam/rc-2018/en_us/images/logo.jpg',
context=ssl.create_default_context(cafile=certifi.where())).read(),
'image/png'
)
builder.add(attachment)
request = builder.request('/restapi/v1.0/account/~/extension/~/fax')
attachment = (
'test.png',
urllib.request.urlopen('https://www.ringcentral.com/content/dam/rc-2018/en_us/images/logo.jpg',
context=ssl.create_default_context(cafile=certifi.where())).read(),
'image/png'
)
builder.add(attachment)
request = builder.request('/restapi/v1.0/account/~/extension/~/fax')
resp = platform.send_request(request)
jsonObj = resp.json()
print ("Fax sent. Message id: " + str(jsonObj.id))
Expand All @@ -59,7 +58,7 @@ def check_fax_message_status(messageId):
# Authenticate a user using a personal JWT token
def login():
try:
platform.login( jwt=os.environ.get('RINGCENTRAL_JWT_TOKEN') )
platform.login(jwt=os.environ.get('RINGCENTRAL_JWT_TOKEN') )
send_fax()
except Exception as e:
print ("Unable to authenticate to platform. Check credentials." + str(e))
Expand Down
11 changes: 7 additions & 4 deletions ringcentral/demos/demo_web_socket.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
from dotenv import load_dotenv
from ringcentral import SDK
from ringcentral.websocket.events import WebSocketEvents
import json
import uuid
import os
import asyncio
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) # Add the project root to sys.path
from ringcentral import SDK
from ringcentral.websocket.events import WebSocketEvents


def on_message(message):
print("\n WebSocket message:\n")
print(json.loads(message))
print("\n User email:\n")
print(json.loads(message)[1]["contact"]["email"])
if(len(json.loads(message)) > 1):
print("\n User email:\n")
print(json.loads(message)[1]["contact"]["email"])


def on_created(web_socket_client):
Expand Down
2 changes: 1 addition & 1 deletion ringcentral/test/testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_sdk(self, mock):
sdk = SDK('whatever', 'whatever', 'https://whatever', redirect_uri='https://whatever-redirect')

self.authentication_mock(mock)
sdk.platform().login('18881112233', None, 'password')
sdk.platform().login(jwt='jwt-token')

matcher = re.compile('pubsub\.pubnub\.com')

Expand Down
13 changes: 12 additions & 1 deletion ringcentral/websocket/web_socket_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .events import WebSocketEvents
import json
import asyncio

import uuid

class WebSocketClient(Observable):
def __init__(self, platform):
Expand Down Expand Up @@ -48,6 +48,17 @@ async def open_connection(self, ws_uri, ws_access_token):
self._web_socket = connection_info
self._is_ready = True
self.trigger(WebSocketEvents.connectionCreated, self)

# heartbeat every 10 minutes
async def timer_function():
while True:
if self._done:
timer.cancel()
break
await asyncio.sleep(600)
await self.send_message([{"type": "Heartbeat", "messageId": str(uuid.uuid4())}])
timer = asyncio.create_task(timer_function())

await asyncio.sleep(0)
while True:
message = await websocket.recv()
Expand Down

0 comments on commit 0d79ad4

Please sign in to comment.