Listing Room Usage per User
What are we going to do?
This code snippet shows how you can use the List Room Sessions endpoint of SignalWire's Video API to pull all of the activity sessions within each room, and then use the List a Room Session's Members endpoint to get user data.
Full code example: List Video Room Usage per User
import pandas as pd
import matplotlib.pyplot as plt
import requests
from requests.auth import HTTPBasicAuth
from dateutil import parser
# TODO: Update these variables with your own
SpaceURL = 'YOURSPACENAME.signalwire.com'
projectID = "XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX"
authToken = "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
host = f"https://{SpaceURL}"
# TODO: Pick start and end date to filter with
startDate = "2022/04/04"
endDate = "2022/04/07"
# Function to make requests to a given url endpoint
def getData(url):
payload = {}
headers = {}
response = requests.request(
"GET",
url,
headers = headers,
data = payload,
auth = HTTPBasicAuth(
projectID,
authToken)).json()
allData = response['data']
while "next" in response['links'].keys():
response = requests.get(
host + response['links']['next'],
auth = HTTPBasicAuth(projectID, authToken)
).json()
allData.extend(response['data'])
return allData
# Get all Room Sessions
roomSessions = getData(f"https://{SpaceURL}/api/video/room_sessions?page_size=1000")
# Set up empty array to store session data
roomSessionMemberData = []
# Create variables to keep track of ongoing sessions
ongoingSessions = 0
ongoingSessionsDuration = 0
# Statistics formatting options
pd.set_option('display.colheader_justify', 'center')
pd.set_option('display.max_rows', 1000)
# Convert chosen start and end dates to datetime format
startDateFilter = parser.parse(startDate + 'T00:00:00Z')
endDateFilter = parser.parse(endDate + 'T23:59:59Z')
# Loop through sessions
for session in roomSessions:
# If the session is ongoing
if session['end_time'] == None:
ongoingSessions += 1
ongoingSessionsDuration += session['duration']
continue
else:
sessionStart = parser.parse(session['start_time'])
sessionEnd = parser.parse(session['end_time'])
if (startDateFilter <= sessionStart and sessionStart <= endDateFilter) or (startDateFilter <= sessionEnd and sessionEnd <= endDateFilter):
roomSessionMembers = getData(f"https://{SpaceURL}/api/video/room_sessions/{session['id']}/members?page_size=1000")
for member in roomSessionMembers:
roomSessionMemberData.append((
session['name'],
member['name'],
member['duration'],
session['cost_in_dollars']))
membersDataFrame = pd.DataFrame(
roomSessionMemberData,
columns = (
'Room',
'User Name',
'Duration (sec)',
'Cost in Dollars')
).groupby(
['Room',
'User Name']
).sum(
).sort_values(
['Room',
'Duration (sec)',
'User Name'],
ascending = False)
print(membersDataFrame.to_string())
print("\n")
print(f"Additionally, there are {ongoingSessions} ongoing sessions, with a total duration of {round((ongoingSessionsDuration)/60, 2)} minutes.")
pd.pivot_table(
membersDataFrame.reset_index(),
index = 'User Name',
columns = 'Room',
values = 'Duration (sec)'
).plot(
kind = 'bar',
rot = 45)
plt.tight_layout()
plt.show()
What do I need to run this code?
In order to run this code we're going to need to have the following installed (click on top of them to get instructions on how to install them):
How to get API Credentials
The API also requires that you authenticate yourself using your Project ID, API Token, and Space URL. If you do not know where to find these values, check out our guide here!
How to Run the Snippet?
You first need to copy the code from below and store it in a file.
Full code
import pandas as pd
import matplotlib.pyplot as plt
import requests
from requests.auth import HTTPBasicAuth
from dateutil import parser
# TODO: Update these variables with your own
SpaceURL = 'YOURSPACENAME.signalwire.com'
projectID = "XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX"
authToken = "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
host = f"https://{SpaceURL}"
# TODO: Pick start and end date to filter with
startDate = "2022/04/04"
endDate = "2022/04/07"
# Function to make requests to a given url endpoint
def getData(url):
payload = {}
headers = {}
response = requests.request(
"GET",
url,
headers = headers,
data = payload,
auth = HTTPBasicAuth(
projectID,
authToken)).json()
allData = response['data']
while "next" in response['links'].keys():
response = requests.get(
host + response['links']['next'],
auth = HTTPBasicAuth(projectID, authToken)
).json()
allData.extend(response['data'])
return allData
# Get all Room Sessions
roomSessions = getData(f"https://{SpaceURL}/api/video/room_sessions?page_size=1000")
# Set up empty array to store session data
roomSessionMemberData = []
# Create variables to keep track of ongoing sessions
ongoingSessions = 0
ongoingSessionsDuration = 0
# Statistics formatting options
pd.set_option('display.colheader_justify', 'center')
pd.set_option('display.max_rows', 1000)
# Convert chosen start and end dates to datetime format
startDateFilter = parser.parse(startDate + 'T00:00:00Z')
endDateFilter = parser.parse(endDate + 'T23:59:59Z')
# Loop through sessions
for session in roomSessions:
# If the session is ongoing
if session['end_time'] == None:
ongoingSessions += 1
ongoingSessionsDuration += session['duration']
continue
else:
sessionStart = parser.parse(session['start_time'])
sessionEnd = parser.parse(session['end_time'])
if (startDateFilter <= sessionStart and sessionStart <= endDateFilter) or (startDateFilter <= sessionEnd and sessionEnd <= endDateFilter):
roomSessionMembers = getData(f"https://{SpaceURL}/api/video/room_sessions/{session['id']}/members?page_size=1000")
for member in roomSessionMembers:
roomSessionMemberData.append((
session['name'],
member['name'],
member['duration'],
session['cost_in_dollars']))
membersDataFrame = pd.DataFrame(
roomSessionMemberData,
columns = (
'Room',
'User Name',
'Duration (sec)',
'Cost in Dollars')
).groupby(
['Room',
'User Name']
).sum(
).sort_values(
['Room',
'Duration (sec)',
'User Name'],
ascending = False)
print(membersDataFrame.to_string())
print("\n")
print(f"Additionally, there are {ongoingSessions} ongoing sessions, with a total duration of {round((ongoingSessionsDuration)/60, 2)} minutes.")
pd.pivot_table(
membersDataFrame.reset_index(),
index = 'User Name',
columns = 'Room',
values = 'Duration (sec)'
).plot(
kind = 'bar',
rot = 45)
plt.tight_layout()
plt.show()
Let's say you named the file listRoomUsage.py
. To run the script, you need to open a command-line and type in the word python
, or python3
if you have both versions, followed by the path to your script, just like this:
python3 listRoomUsage.py
Code Walkthrough
What we will need to change
We're going to need to change the following:
spaceURL
- Your space URL is the domain of your space, i.e. example.signalwire.com. This can also be found in an easily copyable format within the API tab in your SignalWire Space;projectID
- Your project ID is an alphanumeric string that tells the SignalWire SDK where to find your project. You can find this in an easily copyable format by going to your SignalWire Portal and clicking the API tab on the lefthand side;authToken
- Your Auth Token is an alphanumeric string that helps to authenticate your HTTP requests to SignalWire. You can create this (if you haven’t already) or copy this in an easily copyable format by going to your SignalWire Portal and clicking the API tab. If you have not created an API token, press the blue new button. If you have, click show and copy the string;startDate
- This is the date from which we wish to look for sessions;endDate
- This is the date until which we wish to look for sessions;
Code portion
import pandas as pd
import matplotlib.pyplot as plt
import requests
from requests.auth import HTTPBasicAuth
from dateutil import parser
# TODO: Update these variables with your own
spaceURL = 'YOURSPACENAME.signalwire.com'
projectID = "XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX"
authToken = "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
host = f"https://{spaceURL}"
# TODO: Pick start and end date to filter with
startDate = "2022/04/04"
endDate = "2022/04/07"
Preparing future requests to endpoints
Here we set up the getData
function. Since we're going to be making two requests that will share the exact same code, we will create the getData
function, which combines results from all pages returned by the endpoint.
Right after the function declaration, we call getData
for the first time to get all Room Sessions.
Code portion
# Function to make requests to a given url endpoint
def getData(url):
payload = {}
headers = {}
response = requests.request(
"GET",
url,
headers = headers,
data = payload,
auth = HTTPBasicAuth(
projectID,
authToken)).json()
allData = response['data']
while "next" in response['links'].keys():
response = requests.get(
host + response['links']['next'],
auth = HTTPBasicAuth(projectID, authToken)
).json()
allData.extend(response['data'])
return allData
# Get all Room Sessions
roomSessions = getData(f"https://{spaceURL}/api/video/room_sessions?page_size=1000"
Preparing data structures, variables, and output preferences
Since we are going to be storing which Members were in which Rooms (and for how long), we create the roomSessionMemberData
list to append this data to later on.
We also create ongoingSession
and ongoingSessionsDuration
to keep track of the total number of ongoing Room Sessions and how long they have been going for.
To make the results of this code snippet more readable, we center the headers and set the max number of rows to 1000, but this can be changed as needed.
In order to filter through all of the previously fetched roomSessions
, since we are going to be comparing datetime
objects, we must convert the initially provided startDate
and endDate
to startDateFilter
and endDateFilter
respectively.
Code portion
# Set up empty array to store session data
roomSessionMemberData = []
# Create variables to keep track of ongoing sessions
ongoingSessions = 0
ongoingSessionsDuration = 0
# Statistics formatting options
pd.set_option('display.colheader_justify', 'center')
pd.set_option('display.max_rows', 1000)
# Convert chosen start and end dates to datetime format
startDateFilter = parser.parse(startDate + 'T00:00:00Z')
endDateFilter = parser.parse(endDate + 'T23:59:59Z')
Retrieving and processing member session data
First, we check if the session is ongoing, so we only process the detailed session data if the session has ended.
Then, we check if the session start or end dates fit inside the dates we set at the beginning of the code. If they do, we go through every user that was in the room and append relevant data to the roomSessionMemberData
list.
Code portion
# Loop through sessions
for session in roomSessions:
# If the session is ongoing
if session['end_time'] == None:
ongoingSessions += 1
ongoingSessionsDuration += session['duration']
continue
else:
sessionStart = parser.parse(session['start_time'])
sessionEnd = parser.parse(session['end_time'])
if (startDateFilter <= sessionStart and sessionStart <= endDateFilter) or (startDateFilter <= sessionEnd and sessionEnd <= endDateFilter):
roomSessionMembers = getData(f"https://{spaceURL}/api/video/room_sessions/{session['id']}/members?page_size=1000")
for member in roomSessionMembers:
roomSessionMemberData.append((
session['name'],
member['name'],
member['duration'],
session['cost_in_dollars']))
Cleaning up the data and printing the results
Here we create the membersDataFrame
DataFrame, using the roomSessionMemberData
list containing all of the data we need. We then print the data frame to the terminal, giving us the following output:
Lastly, we create a pivot table and create a graph from it, resulting in the following:
Code portion
membersDataFrame = pd.DataFrame(
roomSessionMemberData,
columns = (
'Room',
'User Name',
'Duration (sec)',
'Cost in Dollars')
).groupby(
['Room',
'User Name']
).sum(
).sort_values(
['Room',
'Duration (sec)',
'User Name'],
ascending = False)
print(membersDataFrame.to_string())
print("\n")
print(f"Additionally, there are {ongoingSessions} ongoing sessions, with a total duration of {round((ongoingSessionsDuration)/60, 2)} minutes.")
pd.pivot_table(
membersDataFrame.reset_index(),
index = 'User Name',
columns = 'Room',
values = 'Duration (sec)'
).plot(
kind = 'bar',
rot = 45)
plt.tight_layout()
plt.show()
Wrap Up
That's all there is to it - SignalWire's collection of simple Video REST API make for incredibly easy management and administration of your video rooms and sessions!
Sign Up Here
If you would like to test this example out, you can create a SignalWire account and space here.
Please feel free to reach out to us on our Community Slack or create a Support ticket if you need guidance!