RingCentral Team Messaging Compliance Exports

Last updated: 2023-03-24Contributors
Edit this page

Compliance Exports is a special capability specifically built for companies and regulated industries, such as financial services and health care, with compliance requirements for using electronic communication in the workplace. This feature is also a fail-safe way of preserving business communications for compliance and legal discovery or internal review.

Admin priveleges are required to call the Compliance Export APIs

The Compliance Export APIs run at the account level. This means that only users with the admin role are permitted to call these APIs in order to export the data of all users in the entire account.

The Compliance Exports feature must be turned on from the RingCentral App in the Administration settings.

RingCentral's Data Retention Policy

The Compliance Export API allows any data retention practices to be automated and is essential for regulated industries because RingCentral does not retain customer data indefinitely. Our data retention policy is as follows, depending upon whether your account is "HIPAA enabled" (please consult your account representative or support to inquire about your account settings).

Account Data Retention Rule
Non-HIPAA The account admin can set the retention policy to one of the following: 30, 60 and 90 days. Once a policy is set, on a nightly basis all content older than the specified number of days will be deleted permanently.
HIPAA enabled All data will be deleted after 30 days.

Changing your data retention policy

The RingCentral App provides admins with a way of modifying your account's data retention policy. Login to RingCentral App, and navigate to the Settings area. Then select "Administration." There you will see "Manage data retention policy."

Team Messaging Data Export Process

Team Messaging Exports can take some time to compile and make available for download. Therefore, the process is an asynchronous one that follows this simple 3-step flow:

  1. Developer creates an "Export Report" task.
  2. Developer polls to check the status of the created "Export Report" task.
  3. When the task is complete, developer downloads the generated file.

What follows is a more detailed walk-through of this process.

Creating an Export Report Task

A compliance export task can be created by administrators inside of the RingCentral client under the Administration section.

This is helpful to human beings, but is difficult to automate. To create an export task via the API one would need to:

  • Specify the period of time for the archive via the timeFrom and timeTo parameters.
  • Specify a list of users whose data you would like to export via the contacts parameter. A contact is an object and can be specified by an id number or an email address.
  • Specify a list of teams/conversations to export via the chatIds parameter.
  • Finally, make a POST request to the /team-messaging/v1/data-export endpoint.

How to find IDs to filter by

Valid chatIds can be retrieved using the Get Chats API to read all teams/chats/conversations.

Required permission(s): Team Messaging

If successful, the response will contain the task ID and the status of the newly created task as shown below.

{
  "uri":"https://platform.ringcentral.com/team-messaging/v1/data-export/809646016-xx-yy",
  "id":"809646016-xx-yy",
  "creationTime":"2020-01-16T22:12:55Z",
  "lastModifiedTime":"2020-01-16T22:12:55Z",
  "status":"Accepted",
  "creator": {
    "id":"62288329016",
    "firstName":"Paco",
    "lastName":"Vu"},
  "specific": {
    "timeFrom":"2020-01-14T00:00:00Z",
    "timeTo":"2020-01-16T22:12:55Z"
  }
}

Polling the Status of the Export Task

To archive a large data export report (for a long period of time or for an account with a large number of extensions), the report creation process may take several minutes to complete. Therefore, you will need to periodically check the status of a task. When its status is marked as "Completed" you can proceed to get the report. The status of a task can be any of the following values:

  • Accepted
  • Pending
  • InProgress
  • AttemptFailed
  • Failed
  • Completed
  • Cancelled

To check the status of a task, make a GET request to /team-messaging/v1/data-export/[taskId] endpoint. Where the taskId is the value of the id returned in the previous step. If the report is ready, the task status is marked as "Completed."

When successful, the response will contain the id (taskId) and the status of the newly created task.

{
  "uri":"https://platform.ringcentral.com/team-messaging/v1/data-export/809646016-xx-yy",
  "id":"809646016-xx-yy",
  "creationTime":"2020-01-16T22:12:55Z",
  "lastModifiedTime":"2020-01-16T22:12:55Z",
  "status":"Completed",
  "creator": {
    "id":"62288329016",
    "firstName":"Paco",
    "lastName":"Vu"},
  "specific": {
    "timeFrom":"2020-01-14T00:00:00Z",
    "timeTo":"2020-01-16T22:12:55Z"
    },
  "datasets":[
    {
      "id":"1",
      "size":3434,
      "uri":"https://media.ringcentral.com/team-messaging/v1/data-export/809646016-xx-yy/datasets/1"
    }]
}

Authentication and file downloads

When an export task has completed successfully, make a GET request to the uri parameter returned in the response as described in the previous step, and pass your access key via an Authorization header or access_token query parameter as described in Accessing protected content on Working with media content.

Sample Code: Export Team Messaging Data

The following code sample shows how to call the Compliance Export API to export the team messaging data and save it to a local machine.

const RC = require('@ringcentral/sdk').SDK
var fs    = require('fs')
var https = require('https')
var url = require('url')
const path = require('path')
// Remember to modify the path to where you saved your .env file!
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

var rcsdk = new RC({
    'server':       process.env.RC_SERVER_URL,
    'clientId':     process.env.RC_CLIENT_ID,
    'clientSecret': process.env.RC_CLIENT_SECRET
});
var platform = rcsdk.platform();
platform.login({ 'jwt':  process.env.RC_JWT })

platform.on(platform.events.loginSuccess, () => {
    create_compliance_export_task()
})

/*
* Create a task to export the Team Messaging store for a period of time.
*/
async function create_compliance_export_task() {
    console.log("Create export task.")
  try {
    let bodyParams = {
        timeFrom: "2023-01-01T00:00:00.000Z",
        timeTo: "2023-01-31T23:59:59.999Z"
    }
    let endpoint = "/team-messaging/v1/data-export"
    var resp = await platform.post(endpoint, bodyParams)
    var jsonObj = await resp.json()
    get_compliance_export_task(jsonObj.id)
  } catch (e) {
      console.log(e.message)
  }
}

/*
* Check the status of the task using the taskId.
*/
async function get_compliance_export_task(taskId) {
  console.log("Check export task status ...")
  try {
    let endpoint = `/team-messaging/v1/data-export/${taskId}`
    var resp = await platform.get(endpoint)
    var jsonObj = await resp.json()
    if (jsonObj.status == "Completed") {
      for (var i = 0; i < jsonObj.datasets.length; i++) {
        var fileName = `rc-export-reports-${jsonObj.creationTime}_${i}.zip`
        get_report_archive_content(jsonObj.datasets[i].uri, fileName)
      }
    } else if (jsonObj.status == "Accepted" || jsonObj.status == "InProgress") {
      setTimeout(function() {
        get_compliance_export_task(taskId)
      }, 5000);
    } else {
      console.log(jsonObj.status)
    }
  } catch (e) {
    console.log(e)
  }
}

/*
* Download the task compressed file and save to a local storage.
*/
async function get_report_archive_content(contentUri, fileName){
  var u = url.parse(contentUri)
  var tokenObj = await platform.auth().data()
  var accessToken = tokenObj.access_token
  download(u.host, u.path, accessToken, fileName, function(){
    console.log("Save atttachment to the local machine.")
  })
}

const download = function(domain, path, accessToken, dest, cb) {
  var file = fs.createWriteStream(dest);
  var options = {
          host: domain,
          path: path,
          method: "GET",
          headers: {
            Authorization: `Bearer ${accessToken}`
          }
      }
  const req = https.request(options, res => {
    res.pipe(file);
    file.on('finish', function() {
      file.close(cb);
    });
  })
  req.on('error', error => {
    console.error(error)
  })
  req.end()
}
#!/usr/bin/python

# You get the environment parameters from your
# application dashbord in your developer account
# https://developers.ringcentral.com

import os
import sys
import time
import requests

#from urllib.request import urlopen
from ringcentral import SDK
from ringcentral.http.api_exception import ApiException
from dotenv import load_dotenv

load_dotenv()

rcsdk = SDK( os.environ.get('RC_CLIENT_ID'),
             os.environ.get('RC_CLIENT_SECRET'),
             os.environ.get('RC_SERVER_URL') )
platform = rcsdk.platform()

#
# Create a task to export the Team Messaging store for a period of time.
#
def create_compliance_export_task():
    print("Create export task.")
    try:
        bodyParams = {
        'timeFrom': "2023-01-01T00:00:00.000Z",
        'timeTo': "2023-01-31T23:59:59.999Z"
        }
        endpoint = "/team-messaging/v1/data-export"
        resp = platform.post(endpoint, bodyParams)
        jsonObj = resp.json()
        get_compliance_export_task(jsonObj.id)
    except ApiException as e:
        print (e)
#
# Check the status of the task using the taskId.
#
def get_compliance_export_task(taskId):
    print("Check export task status ...")
    try:
        endpoint = "/team-messaging/v1/data-export/" + taskId
        resp = platform.get(endpoint)
        jsonObj = resp.json()
        if jsonObj.status == "Completed":
            length = len(jsonObj.datasets)
            for i in range(length):
                fileName = "rc-export-reports_" + jsonObj.creationTime + "_" + str(i) + ".zip"
                get_report_archived_content(jsonObj.datasets[i].uri, fileName)
        elif jsonObj.status == "Accepted" or jsonObj.status == "InProgress":
            time.sleep(5)
            get_compliance_export_task(taskId)
        else:
            print (jsonObj.status)
    except ApiException as e:
        print (e)

#
# Download the task compressed file and save to a local storage.
#
def get_report_archived_content(contentUri, fileName):
    print("Save export zip file to the local machine.")
    uri = platform.create_url(contentUri, False, None, True);
    response = requests.get(uri, stream=True)
    file_size = int(response.headers.get("Content-Length", 0))
    with open(fileName,"wb") as output:
        output.write(response.content)
        print ("File has been downloaded successfully and saved in " + fileName)


try:
  platform.login( jwt=os.environ.get('RC_JWT') )
  create_compliance_export_task()
except ApiException as e:
  sys.exit("Unable to authenticate to platform: " + str(e))
<?php
/* You get the environment parameters from your
application dashbord in your developer account
https://developers.ringcentral.com */

require('./../vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

$rcsdk = new RingCentral\SDK\SDK( $_ENV['RC_CLIENT_ID'], $_ENV['RC_CLIENT_SECRET'], $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();
$platform->login( [ "jwt" => $_ENV['RC_JWT'] ] );

create_compliance_export_task();

/*
* Create a task to export the Team Messaging store for a period of time.
*/
function create_compliance_export_task(){
  global $platform;
  echo ("Create export task.\n");
  try {
    $bodyParams = array(
      'timeFrom' => "2023-01-01T00:00:00.000Z",
      'timeTo' => "2023-01-31T23:59:59.999Z"
    );
    $endpoint = "/team-messaging/v1/data-export";
    $response = $platform->post($endpoint, $bodyParams);
    $jsonObj = $response->json();
    get_compliance_export_task($jsonObj->id);
  }catch(\RingCentral\SDK\Http\ApiException $e) {
    print_r ('Error: ' . $e->getMessage() . PHP_EOL);
  }
}

/*
* Check the status of the task using the taskId.
*/
function get_compliance_export_task($taskId){
  global $platform;
  echo ("Check export task status ...\n");
  $endpoint = "/team-messaging/v1/data-export/" . $taskId;
  try {
    $response = $platform->get($endpoint);
    $jsonObj = $response->json();
    if ($jsonObj->status == "Completed"){
      for ($i=0; $i<count($jsonObj->datasets); $i++){
        $fileName = "rc-export-reports_" . $jsonObj->creationTime . "_" . $i . ".zip";
        get_report_archived_content($jsonObj->datasets[$i]->uri, $fileName);
      }
    }else if ($jsonObj->status == "Accepted" || $jsonObj->status == "InProgress"){
      sleep(5);
      get_compliance_export_task($taskId);
    }else
      print_r ($jsonObj->status);
  }catch(\RingCentral\SDK\Http\ApiException $e) {
    print_r ('Error: ' . $e->getMessage() . PHP_EOL);
  }
}

/*
* Download the task compressed file and save to a local storage.
*/
function get_report_archived_content($contentUri, $fileName){
  global $platform;
  echo ("Save export zip file to the local machine.\n");
  $uri = $platform->createUrl($contentUri, array(
    'addServer' => false,
    'addMethod' => 'GET',
    'addToken'  => true
  ));
  file_put_contents($fileName, fopen($uri, 'r'));
}
using System;
using System.Threading.Tasks;
using RingCentral;

namespace Export_Compliance_Data
{
  class Program
  {
    static RestClient restClient;
    static async Task Main(string[] args)
    {
      restClient = new RestClient( Environment.GetEnvironmentVariable("RC_CLIENT_ID"),
                                   Environment.GetEnvironmentVariable("RC_CLIENT_SECRET"),
                                   Environment.GetEnvironmentVariable("RC_SERVER_URL"));

      try
      {
        await restClient.Authorize(Environment.GetEnvironmentVariable("RC_JWT"));
        await create_compliance_export_task();
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
    }
    static private async Task create_compliance_export_task()
    {
        var bodyParams = new CreateDataExportTaskRequest();
        bodyParams.timeFrom = "2019-08-01T00:00:00.000Z";
        bodyParams.timeTo = "2019-08-26T23:59:59.999Z";

        var resp = await restClient.TeamMessaging().V1().DataExport().Post(bodyParams);
        Console.WriteLine("Create export task");
        var taskId = resp.id;
        Boolean polling = true;
        while (polling)
        {
            Console.WriteLine("Check export task status ...");
            try
            {
                Thread.Sleep(5000);
                resp = await restClient.TeamMessaging().V1().DataExport(taskId).Get();
                if (resp.status != "InProgress" ||  resp.status != "Accepted")
                {
                    polling = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        if (resp.status == "Completed")
        {
            for (var i = 0; i < resp.datasets.Length; i++)
            {
                var fileName = "glip-export-reports_" + resp.creationTime + "_" + i + ".zip";
                var contentUrl = resp.datasets[i].uri + "?access_token=" + restClient.token.access_token;
                WebClient webClient = new WebClient();
                webClient.DownloadFile(contentUrl, fileName);
                Console.WriteLine("Save report zip file to the local machine.");
            }
        }
    }
  }
}
package com.ringcentral;

import com.ringcentral.*;
import com.ringcentral.definitions.*;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

public class ComplianceDataExport {
    static RestClient rc;

    public static void main(String[] args) {
    var obj = new ComplianceDataExport();
    rc = new RestClient( System.getenv("RC_CLIENT_ID"),
                 System.getenv("RC_CLIENT_SECRET"),
                 System.getenv("RC_SERVER_URL") );
    try {
        rc.authorize( System.getenv("RC_JWT") );
        obj.create_compliance_export_task();
    } catch (RestException | IOException e) {
        e.printStackTrace();
    }
    }
    public void create_compliance_export_task() throws RestException, IOException {
    var parameters = new CreateDataExportTaskRequest();
    parameters.timeFrom = "2019-08-01T00:00:00.000Z";
    parameters.timeTo = "2019-08-26T23:59:59.999Z";

    var resp = rc.restapi().glip().dataExport().post(parameters);
    var taskId = resp.id;
    System.out.println("Created export task. Task ID: " + taskId);

    boolean polling = true;
    while (polling) {
        System.out.println("Check export task status ...");
        try {
        Thread.sleep(5000);
        resp = rc.restapi().glip().dataExport(taskId).get();
        if (!resp.status.equals("InProgress"))
            polling = false;
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
    }
    if (resp.status.equals("Completed")) {
        for (var i = 0; i < resp.datasets.length; i++) {
        var fileName = "./src/test/resources/export-reports_"
            + resp.creationTime + "_" + i + ".zip";
        var contentUrl = resp.datasets[i].uri
            + "?access_token=" + rc.token.access_token;
        try (BufferedInputStream inputStream =
             new BufferedInputStream(new URL(contentUrl).openStream());
             FileOutputStream fileOS = new FileOutputStream(fileName)) {
            byte data[] = new byte[1024];
            int byteContent;
            while ((byteContent = inputStream.read(data, 0, 1024)) != -1) {
            fileOS.write(data, 0, byteContent);
            }
            System.out.println("Save report zip file to the local machine.");
        } catch (IOException e) {
            // handles IO exceptions
            System.out.println("Error!");
        }
        }
    }
    }
}
#!usr/bin/ruby

# You get the environment parameters from your
# application dashbord in your developer account
# https://developers.ringcentral.com

require 'ringcentral'
require 'open-uri'
require 'dotenv'
# Remember to modify the path to where you installed the RingCentral SDK and saved your .env file!
Dotenv.load("./../.env")

$platform = RingCentral.new( ENV['RC_CLIENT_ID'], ENV['RC_CLIENT_SECRET'], ENV['RC_SERVER_URL'] )


def create_compliance_export_task()
    puts "Create export task."
    bodyParams = {
        'timeFrom': "2023-01-01T00:00:00.000Z",
        'timeTo': "2023-01-31T23:59:59.999Z"
      }
    endpoint = "/team-messaging/v1/data-export"
    response = $platform.post(endpoint, payload: bodyParams)
    get_compliance_export_task(response.body['id'])
end

def get_compliance_export_task(taskId)
    puts "Check export task status ..."
    endpoint = "/team-messaging/v1/data-export/" + taskId
    response = $platform.get(endpoint)
    body = response.body
    if body['status'] == "Completed"
      length = body['datasets'].length
      for i in (0...length)
        fileName = "rc-export-reports_" + body['creationTime'] + "_" + i.to_s + ".zip"
        get_report_archived_content(body['datasets'][i]['uri'], fileName)
      end
    elsif body['status'] == "Accepted" || body['status'] == "InProgress"
      sleep(5)
      get_compliance_export_task(taskId)
    else
         puts body['status']
    end
end

def get_report_archived_content(contentUri, fileName)
    puts "Save report zip file to the local machine."
    uri = contentUri + "?access_token=" + $platform.token['access_token']
    IO.copy_stream(URI.open(uri), fileName)
end

begin
  $platform.authorize(jwt: ENV['RC_JWT'])
  create_compliance_export_task()
rescue StandardError => e
  puts e
end