Examples

Code examples can be found in the examples directory on GitHub

Also take a look at the unit tests in the tests directory.

Get all calling users

Source: calling_users.py

 1#!/usr/bin/env python
 2"""
 3Example script
 4Get all calling users within the org
 5"""
 6
 7from dotenv import load_dotenv
 8
 9from wxc_sdk import WebexSimpleApi
10
11load_dotenv()
12
13api = WebexSimpleApi()
14
15# using wxc_sdk.people.PeopleApi.list to iterate over persons
16# Parameter calling_data needs to be set to true to gat calling specific information
17# calling users have the attribute location_id set
18calling_users = [user for user in api.people.list(calling_data=True)
19                 if user.location_id]
20print(f'{len(calling_users)} users:')
21print('\n'.join(user.display_name for user in calling_users))

Get all calling users (async variant)

Source: calling_users_async.py

 1#!/usr/bin/env python
 2"""
 3Example script
 4Get all calling users within the org using the (experimental) async API
 5"""
 6import asyncio
 7import time
 8
 9from dotenv import load_dotenv
10
11from wxc_sdk.as_api import AsWebexSimpleApi
12
13load_dotenv()
14
15
16async def get_calling_users():
17    """
18    Get details of all calling enabled users by:
19    1) getting all calling users
20    2) collecting all users that have a calling license
21    3) getting details for all users
22    """
23    async with AsWebexSimpleApi(concurrent_requests=40) as api:
24        print('Collecting calling licenses')
25        calling_license_ids = set(lic.license_id for lic in await api.licenses.list()
26                                  if lic.webex_calling)
27
28        # get users with a calling license
29        calling_users = [user async for user in api.people.list_gen()
30                         if any(lic_id in calling_license_ids for lic_id in user.licenses)]
31        print(f'{len(calling_users)} users:')
32        print('\n'.join(user.display_name for user in calling_users))
33
34        # get details for all users
35        start = time.perf_counter()
36        details = await asyncio.gather(*[api.people.details(person_id=user.person_id, calling_data=True)
37                                         for user in calling_users])
38        expired = time.perf_counter() - start
39        print(f'Got details for {len(details)} users in {expired * 1000:.3f} ms')
40
41
42if __name__ == '__main__':
43    asyncio.run(get_calling_users())

Get all users without phones

Source: users_wo_devices.py

  1#!/usr/bin/env python
  2"""
  3Get calling users without devices
  4"""
  5import asyncio
  6import logging
  7import os
  8from itertools import chain
  9from typing import Optional
 10
 11from dotenv import load_dotenv
 12
 13from wxc_sdk import Tokens
 14from wxc_sdk.as_api import AsWebexSimpleApi
 15from wxc_sdk.common import UserType
 16from wxc_sdk.integration import Integration
 17from wxc_sdk.person_settings import DeviceList
 18from wxc_sdk.scopes import parse_scopes
 19
 20
 21def env_path() -> str:
 22    """
 23    determine path for .env to load environment variables from; based on name of this file
 24    :return: .env file path
 25    """
 26    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.env')
 27
 28
 29def yml_path() -> str:
 30    """
 31    determine path of YML file to persist tokens
 32    :return: path to YML file
 33    :rtype: str
 34    """
 35    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.yml')
 36
 37
 38def build_integration() -> Integration:
 39    """
 40    read integration parameters from environment variables and create an integration
 41    :return: :class:`wxc_sdk.integration.Integration` instance
 42    """
 43    client_id = os.getenv('INTEGRATION_CLIENT_ID')
 44    client_secret = os.getenv('INTEGRATION_CLIENT_SECRET')
 45    scopes = parse_scopes(os.getenv('INTEGRATION_SCOPES'))
 46    redirect_url = 'http://localhost:6001/redirect'
 47    if not all((client_id, client_secret, scopes)):
 48        raise ValueError('failed to get integration parameters from environment')
 49    return Integration(client_id=client_id, client_secret=client_secret, scopes=scopes,
 50                       redirect_url=redirect_url)
 51
 52
 53def get_tokens() -> Optional[Tokens]:
 54    """
 55    Tokens are read from a YML file. If needed an OAuth flow is initiated.
 56
 57    :return: tokens
 58    :rtype: :class:`wxc_sdk.tokens.Tokens`
 59    """
 60
 61    integration = build_integration()
 62    tokens = integration.get_cached_tokens_from_yml(yml_path=yml_path())
 63    return tokens
 64
 65
 66async def main():
 67    # get environment variables from .env; required for integration parameters
 68    load_dotenv(env_path())
 69
 70    # get tokens from cache or create a new set of tokens using the integration defined in .env
 71    tokens = get_tokens()
 72
 73    async with AsWebexSimpleApi(tokens=tokens) as api:
 74        # get calling users
 75        calling_users = [user for user in await api.people.list(calling_data=True)
 76                         if user.location_id]
 77
 78        # get device info for all users
 79        user_device_infos = await asyncio.gather(*[api.person_settings.devices(person_id=user.person_id)
 80                                                   for user in calling_users])
 81        user_device_infos: list[DeviceList]
 82        users_wo_devices = [user for user, device_info in zip(calling_users, user_device_infos)
 83                            if not device_info.devices]
 84
 85        # alternatively we can collect all device owners
 86        device_owner_ids = set(owner.owner_id
 87                               for device in chain.from_iterable(udi.devices for udi in user_device_infos)
 88                               if (owner := device.owner) and owner.owner_type == UserType.people)
 89
 90        # ... and collect all other users (the ones not owning a device)
 91        users_not_owning_a_device = [user for user in calling_users
 92                                     if user.person_id not in device_owner_ids]
 93
 94    users_wo_devices.sort(key=lambda u: u.display_name)
 95    print(f'{len(users_wo_devices)} users w/o devices:')
 96    print('\n'.join(f'{user.display_name} ({user.emails[0]})'
 97                    for user in users_wo_devices))
 98
 99    print()
100    users_not_owning_a_device.sort(key=lambda u: u.display_name)
101    print(f'{len(users_not_owning_a_device)} users not owning a device:')
102    print('\n'.join(f'{user.display_name} ({user.emails[0]})'
103                    for user in users_not_owning_a_device))
104
105
106if __name__ == '__main__':
107    # enable DEBUG logging to a file; REST log shows all requests
108    logging.basicConfig(filename=os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.log'),
109                        filemode='w', level=logging.DEBUG, format='%(asctime)s %(threadName)s %(message)s')
110    asyncio.run(main())

Default call forwarding settings for all users

This example start with the list of all calling users and then calls wxc_sdk.person_settings.forwarding.PersonForwardingApi.configure() for each user. To speed up things a ThreadPoolExecutor is used and all update operations are scheduled for execution by the thread pool.

Source: reset_call_forwarding.py

 1#!/usr/bin/env python
 2"""
 3Example script
 4Reset call forwarding to default for all users in the org
 5"""
 6import asyncio
 7import logging
 8import time
 9
10from dotenv import load_dotenv
11
12from wxc_sdk.all_types import PersonForwardingSetting
13from wxc_sdk.as_api import AsWebexSimpleApi
14
15
16async def main():
17    # load environment. SDk fetches the access token from WEBEX_ACCESS_TOKEN environment variable
18    load_dotenv()
19
20    logging.basicConfig(level=logging.INFO)
21
22    # set to DEBUG to see the actual requests
23    logging.getLogger('wxc_sdk.rest').setLevel(logging.INFO)
24
25    async with AsWebexSimpleApi() as api:
26
27        # get all calling users
28        start = time.perf_counter_ns()
29        calling_users = [user for user in await api.people.list(calling_data=True)
30                         if user.location_id]
31        print(f'Got {len(calling_users)} calling users in '
32              f'{(time.perf_counter_ns() - start) / 1e6:.3f} ms')
33
34        # set call forwarding to default for all users
35        # default call forwarding settings
36        forwarding = PersonForwardingSetting.default()
37
38        # schedule update for each user and wait for completion
39        start = time.perf_counter_ns()
40        await asyncio.gather(*[api.person_settings.forwarding.configure(entity_id=user.person_id,
41                                                                        forwarding=forwarding)
42                               for user in calling_users])
43        print(f'Reset call forwarding to default for {len(calling_users)} users in '
44              f'{(time.perf_counter_ns() - start) / 1e6:.3f} ms')
45
46if __name__ == '__main__':
47    asyncio.run(main())

Modify number of rings configuration for users read from CSV

Here we read a bunch of user email addresses from a CSV. The CSV as an ERROR column and we only want to consider users without errors.

For all these users a VM setting is updated and the results are written to a CSV for further processing.

Source: modify_voicemail.py

 1#!/usr/bin/env python
 2"""
 3Example Script
 4Modifying number of rings configuration in voicemail settings
 5Run -> python3 modify_voicemail.py modify_voicemail.csv
 6"""
 7import csv
 8import sys
 9import traceback
10from concurrent.futures import ThreadPoolExecutor
11
12from dotenv import load_dotenv
13
14from wxc_sdk import WebexSimpleApi
15from wxc_sdk.all_types import *
16
17VOICEMAIL_SETTINGS_NUMBER_OF_RINGS = 6
18
19# loading environment variables - use .env file for development
20load_dotenv()
21
22
23def update_vm_settings():
24    """
25    actually update VM settings for all users present in input CSV
26    """
27    api = WebexSimpleApi()
28    final_report = []
29    mail_ids = []
30    # using wxc_sdk.people.PeopleApi.list to iterate over persons
31    # Parameter calling_data needs to be set to true to gat calling specific information
32    # calling users have the attribute location_id set
33    calling_users = [user for user in api.people.list(calling_data=True)
34                     if user.location_id]
35    print(f'{len(calling_users)} users:')
36    print('\n'.join(user.display_name for user in calling_users))
37
38    # get CSV file name from command line
39    with open(str(sys.argv[1]), 'r') as csv_file:
40        reader = csv.DictReader(csv_file)
41        # read all records from CSV. Ony consider records w/o error
42        for col in reader:
43            if not col['ERROR']:
44                # collect email address from USERNAME column for further processing
45                mail_ids.append(col['USERNAME'])
46            else:
47                final_report.append((col['USERNAME'], 'FAILED DUE TO ERROR REASON IN INPUT FILE'))
48
49    # work on calling users that have an email address that we read from the CSV
50    filteredUsers = [d for d in calling_users if d.emails[0] in mail_ids]
51
52    print("\nCalling Users in CI  - Count ", len(calling_users))
53    print("Mail IDs from input file after removing error columns - Count ", len(mail_ids))
54    print("FilteredUsers Users -  Count", len(filteredUsers))
55
56    def set_number_of_rings(user: Person):
57        """
58        Read VM config for a user
59        :param user: user to update
60        """
61        try:
62            # shortcut
63            vm = api.person_settings.voicemail
64
65            # Read Current configuration
66            vm_settings = vm.read(person_id=user.person_id)
67            print(f'\n Existing Configuration: {vm_settings} ')
68
69            # Modify number of rings value
70            vm_settings.send_unanswered_calls.number_of_rings = VOICEMAIL_SETTINGS_NUMBER_OF_RINGS
71            vm.configure(user.person_id, settings=vm_settings)
72            # Read configuration after changes
73            vm_settings = vm.read(user.person_id)
74            print(f'\n New Configuration: {vm_settings} ')
75            final_report.append((user.display_name, 'SUCCESS'))
76        except Exception as e:
77            final_report.append((user.display_name, 'FAILURE'))
78            print("type error: " + str(e))
79            print(traceback.format_exc())
80        return
81
82    # Modify settings for the filtered users
83    with ThreadPoolExecutor() as pool:
84        list(pool.map(lambda user: set_number_of_rings(user),
85                      filteredUsers))
86
87    print(final_report)
88    with open('output.csv', 'w') as f:
89        write = csv.writer(f)
90        write.writerow(["USERNAME", "STATUS"])
91        write.writerows(final_report)
92
93
94if __name__ == '__main__':
95    update_vm_settings()

Holiday schedule w/ US national holidays for all US locations

This example uses the Calendarific API at https://calendarific.com/ to get a list of national US holidays and creates a “National Holidays” holiday schedule for all US locations with all these national holidays.

A rudimentary API implementation in calendarific.py is used for the requests to https://calendarific.com/. Calendarific APIs require all requests to be authenticated using an API key. You can sign up for a free account to get a free API account key which then is read from environment variable CALENDARIFIC_KEY.

Source: us_holidays.py

  1#!/usr/bin/env python
  2"""
  3Example script
  4Create a holiday schedule for all US locations with all national holidays
  5"""
  6
  7import logging
  8from collections import defaultdict
  9from concurrent.futures import ThreadPoolExecutor
 10from datetime import date
 11from threading import Lock
 12from typing import List
 13
 14from dotenv import load_dotenv
 15
 16from calendarific import CalendarifiyApi, Holiday
 17from wxc_sdk import WebexSimpleApi
 18from wxc_sdk.locations import Location
 19from wxc_sdk.all_types import ScheduleType, Event, Schedule
 20
 21log = logging.getLogger(__name__)
 22
 23# a lock per location to protect observe_in_location()
 24location_locks: dict[str, Lock] = defaultdict(Lock)
 25
 26# Use parallel threads for provisioning?
 27USE_THREADING = True
 28
 29# True: delete holiday schedule instead of creating one
 30CLEAN_UP = False
 31
 32# first and last year for which to create public holiday events
 33FIRST_YEAR = 2022
 34LAST_YEAR = 2024
 35
 36LAST_YEAR = not CLEAN_UP and LAST_YEAR or FIRST_YEAR
 37
 38
 39def observe_in_location(*, api: WebexSimpleApi, location: Location, holidays: List[Holiday]):
 40    """
 41    create/update a "National Holiday" schedule in one location
 42
 43    :param api: Webex api
 44    :type api: WebexSimpleApi
 45    :param location: location to work on
 46    :type location: Location
 47    :param holidays: list of holidays to observe
 48    :type holidays: List[Holiday]
 49    """
 50    # there should always only one thread messing with the holiday schedule of a location
 51    with location_locks[location.location_id]:
 52        year = holidays[0].date.year
 53        schedule_name = 'National Holidays'
 54
 55        # shortcut
 56        ats = api.telephony.schedules
 57
 58        # existing "National Holiday" schedule or None
 59        schedule = next((schedule
 60                         for schedule in ats.list(obj_id=location.location_id,
 61                                                  schedule_type=ScheduleType.holidays,
 62                                                  name=schedule_name)
 63                         if schedule.name == schedule_name),
 64                        None)
 65        if CLEAN_UP:
 66            if schedule:
 67                log.info(f'Delete schedule {schedule.name} in location {schedule.location_name}')
 68                ats.delete_schedule(obj_id=location.location_id,
 69                                    schedule_type=ScheduleType.holidays,
 70                                    schedule_id=schedule.schedule_id)
 71            return
 72        if schedule:
 73            # we need the details: list response doesn't have events
 74            schedule = ats.details(obj_id=location.location_id,
 75                                   schedule_type=ScheduleType.holidays,
 76                                   schedule_id=schedule.schedule_id)
 77        # create list of desired schedule entries
 78        #   * one per holiday
 79        #   * only future holidays
 80        #   * not on a Sunday
 81        today = date.today()
 82        events = [Event(name=f'{holiday.name} {holiday.date.year}',
 83                        start_date=holiday.date,
 84                        end_date=holiday.date,
 85                        all_day_enabled=True)
 86                  for holiday in holidays
 87                  if holiday.date >= today and holiday.date.weekday() != 6]
 88
 89        if not schedule:
 90            # create new schedule
 91            log.debug(f'observe_in_location({location.name}, {year}): no existing schedule')
 92            if not events:
 93                log.info(f'observe_in_location({location.name}, {year}): no existing schedule, no events, done')
 94                return
 95            schedule = Schedule(name=schedule_name,
 96                                schedule_type=ScheduleType.holidays,
 97                                events=events)
 98            log.debug(
 99                f'observe_in_location({location.name}, {year}): creating schedule "{schedule_name}" with {len(events)} '
100                f'events')
101            schedule_id = ats.create(obj_id=location.location_id, schedule=schedule)
102            log.info(f'observe_in_location({location.name}, {year}): new schedule id: {schedule_id}, done')
103            return
104
105        # update existing schedule
106        with ThreadPoolExecutor() as pool:
107            # delete existing events in the past
108            to_delete = [event
109                         for event in schedule.events
110                         if event.start_date < today]
111            if to_delete:
112                log.debug(f'observe_in_location({location.name}, {year}): deleting {len(to_delete)} outdated events')
113                if USE_THREADING:
114                    list(pool.map(
115                        lambda event: ats.event_delete(obj_id=location.location_id,
116                                                       schedule_type=ScheduleType.holidays,
117                                                       schedule_id=schedule.schedule_id,
118                                                       event_id=event.event_id),
119                        to_delete))
120                else:
121                    for event in to_delete:
122                        ats.event_delete(obj_id=location.location_id,
123                                         schedule_type=ScheduleType.holidays,
124                                         schedule_id=schedule.schedule_id,
125                                         event_id=event.event_id)
126
127            # add events which don't exist yet
128            existing_dates = set(event.start_date
129                                 for event in schedule.events)
130            to_add = [event
131                      for event in events
132                      if event.start_date not in existing_dates]
133            if not to_add:
134                log.info(f'observe_in_location({location.name}, {year}): no events to add, done.')
135                return
136            log.debug(f'observe_in_location({location.name}, {year}): creating {len(to_add)} new events.')
137            if USE_THREADING:
138                list(pool.map(
139                    lambda event: ats.event_create(
140                        obj_id=location.location_id,
141                        schedule_type=ScheduleType.holidays,
142                        schedule_id=schedule.schedule_id,
143                        event=event),
144                    to_add))
145            else:
146                for event in to_add:
147                    ats.event_create(
148                        obj_id=location.location_id,
149                        schedule_type=ScheduleType.holidays,
150                        schedule_id=schedule.schedule_id,
151                        event=event)
152        log.info(f'observe_in_location({location.name}, {year}): done.')
153    return
154
155
156def observe_national_holidays(*, api: WebexSimpleApi, locations: List[Location],
157                              year: int = None):
158    """
159    US national holidays for given locations
160
161    :param api: Webex api
162    :type api: WebexSimpleApi
163    :param locations: list of locations in which US national holidays should be observed
164    :type locations: List[Location]
165    :param year: year for national holidays. Default: current year
166    :type year: int
167    """
168    # default: this year
169    year = year or date.today().year
170
171    # get national holidays for specified year
172    holidays = CalendarifiyApi().holidays(country='US', year=year, holiday_type='national')
173
174    # update holiday schedule for each location
175    with ThreadPoolExecutor() as pool:
176        if USE_THREADING:
177            list(pool.map(
178                lambda location: observe_in_location(api=api, location=location, holidays=holidays),
179                locations))
180        else:
181            for location in locations:
182                observe_in_location(api=api, location=location, holidays=holidays)
183    return
184
185
186if __name__ == '__main__':
187    # read dotenv which has some environment variables like Webex API token and Calendarify
188    # API key.
189    load_dotenv()
190
191    # enable logging
192    logging.basicConfig(level=logging.DEBUG,
193                        format='%(asctime)s %(levelname)s %(threadName)s %(name)s: %(message)s')
194    logging.getLogger('urllib3').setLevel(logging.INFO)
195    logging.getLogger('wxc_sdk.rest').setLevel(logging.INFO)
196
197    # the actual action
198    with WebexSimpleApi(concurrent_requests=5) as wx_api:
199        # get all US locations
200        log.info('Getting locations...')
201        us_locations = [location
202                        for location in wx_api.locations.list()
203                        if location.address.country == 'US']
204
205        # set up location locks
206        # location_locks is a defaultdict -> accessing with all potential keys creates the locks
207        list(location_locks[loc.location_id] for loc in us_locations)
208
209        # create national holiday schedule for given year(s) and locations
210        if USE_THREADING:
211            with ThreadPoolExecutor() as pool:
212                list(pool.map(
213                    lambda year: observe_national_holidays(api=wx_api, year=year, locations=us_locations),
214                    range(FIRST_YEAR, LAST_YEAR + 1)))
215        else:
216            for year in range(FIRST_YEAR, LAST_YEAR + 1):
217                observe_national_holidays(api=wx_api, year=year, locations=us_locations)

Holiday schedule w/ US national holidays for all US locations (async variant)

This example uses the Calendarific API at https://calendarific.com/ to get a list of national US holidays and creates a “National Holidays” holiday schedule for all US locations with all these national holidays.

A rudimentary API implementation in calendarific.py is used for the requests to https://calendarific.com/. Calendarific APIs require all requests to be authenticated using an API key. You can sign up for a free account to get a free API account key which then is read from environment variable CALENDARIFIC_KEY.

Source: us_holidays_async.py

  1#!/usr/bin/env python
  2"""
  3Example script
  4Create a holiday schedule for all US locations with all national holidays
  5
  6Using the asyc SDK variant
  7"""
  8import asyncio
  9import functools
 10import logging
 11from collections import defaultdict
 12from datetime import date
 13from typing import List
 14
 15from dotenv import load_dotenv
 16
 17from calendarific import CalendarifiyApi, Holiday
 18from wxc_sdk.all_types import ScheduleType, Event, Schedule
 19from wxc_sdk.as_api import AsWebexSimpleApi
 20from wxc_sdk.locations import Location
 21
 22log = logging.getLogger(__name__)
 23
 24# a lock per location to protect observe_in_location()
 25location_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
 26
 27# Use parallel tasks for provisioning?
 28USE_TASKS = True
 29
 30# True: delete holiday schedule instead of creating one
 31CLEAN_UP = False
 32
 33# first and last year for which to create public holiday events
 34FIRST_YEAR = 2024
 35LAST_YEAR = 2026
 36
 37LAST_YEAR = not CLEAN_UP and LAST_YEAR or FIRST_YEAR
 38
 39
 40async def observe_in_location(*, api: AsWebexSimpleApi, location: Location, holidays: List[Holiday]):
 41    """
 42    create/update a "National Holiday" schedule in one location
 43
 44    :param api: Webex api
 45    :type api: WebexSimpleApi
 46    :param location: location to work on
 47    :type location: Location
 48    :param holidays: list of holidays to observe
 49    :type holidays: List[Holiday]
 50    """
 51    # there should always only one thread messing with the holiday schedule of a location
 52    async with location_locks[location.location_id]:
 53        year = holidays[0].date.year
 54        schedule_name = 'National Holidays'
 55
 56        # shortcut
 57        ats = api.telephony.schedules
 58
 59        # existing "National Holiday" schedule or None
 60        schedule = next((schedule
 61                         for schedule in await ats.list(obj_id=location.location_id,
 62                                                        schedule_type=ScheduleType.holidays,
 63                                                        name=schedule_name)
 64                         if schedule.name == schedule_name),
 65                        None)
 66        if CLEAN_UP:
 67            if schedule:
 68                log.info(f'Delete schedule {schedule.name} in location {schedule.location_name}')
 69                await ats.delete_schedule(obj_id=location.location_id,
 70                                          schedule_type=ScheduleType.holidays,
 71                                          schedule_id=schedule.schedule_id)
 72            return
 73        if schedule:
 74            # we need the details: list response doesn't have events
 75            schedule = await ats.details(obj_id=location.location_id,
 76                                         schedule_type=ScheduleType.holidays,
 77                                         schedule_id=schedule.schedule_id)
 78        # create list of desired schedule entries
 79        #   * one per holiday
 80        #   * only future holidays
 81        #   * not on a Sunday
 82        today = date.today()
 83        events = [Event(name=f'{holiday.name} {holiday.date.year}',
 84                        start_date=holiday.date,
 85                        end_date=holiday.date,
 86                        all_day_enabled=True)
 87                  for holiday in holidays
 88                  if holiday.date >= today and holiday.date.weekday() != 6]
 89
 90        if not schedule:
 91            # create new schedule
 92            log.debug(f'observe_in_location({location.name}, {year}): no existing schedule')
 93            if not events:
 94                log.info(f'observe_in_location({location.name}, {year}): no existing schedule, no events, done')
 95                return
 96            schedule = Schedule(name=schedule_name,
 97                                schedule_type=ScheduleType.holidays,
 98                                events=events)
 99            log.debug(
100                f'observe_in_location({location.name}, {year}): creating schedule "{schedule_name}" with {len(events)} '
101                f'events')
102            schedule_id = await ats.create(obj_id=location.location_id, schedule=schedule)
103            log.info(f'observe_in_location({location.name}, {year}): new schedule id: {schedule_id}, done')
104            return
105
106        # update existing schedule
107        # delete existing events in the past
108        to_delete = [event
109                     for event in schedule.events
110                     if event.start_date < today]
111        if to_delete:
112            log.debug(f'observe_in_location({location.name}, {year}): deleting {len(to_delete)} outdated events')
113            if USE_TASKS:
114                await asyncio.gather(*[ats.event_delete(obj_id=location.location_id,
115                                                        schedule_type=ScheduleType.holidays,
116                                                        schedule_id=schedule.schedule_id,
117                                                        event_id=event.event_id)
118                                       for event in to_delete])
119            else:
120                for event in to_delete:
121                    await ats.event_delete(obj_id=location.location_id,
122                                           schedule_type=ScheduleType.holidays,
123                                           schedule_id=schedule.schedule_id,
124                                           event_id=event.event_id)
125
126        # add events which don't exist yet
127        existing_dates = set(event.start_date
128                             for event in schedule.events)
129        to_add = [event
130                  for event in events
131                  if event.start_date not in existing_dates]
132        if not to_add:
133            log.info(f'observe_in_location({location.name}, {year}): no events to add, done.')
134            return
135        log.debug(f'observe_in_location({location.name}, {year}): creating {len(to_add)} new events.')
136        if USE_TASKS:
137            await asyncio.gather(*[ats.event_create(obj_id=location.location_id,
138                                                    schedule_type=ScheduleType.holidays,
139                                                    schedule_id=schedule.schedule_id,
140                                                    event=event)
141                                   for event in to_add])
142        else:
143            for event in to_add:
144                await ats.event_create(obj_id=location.location_id,
145                                       schedule_type=ScheduleType.holidays,
146                                       schedule_id=schedule.schedule_id,
147                                       event=event)
148        log.info(f'observe_in_location({location.name}, {year}): done.')
149    return
150
151
152async def observe_national_holidays(*, api: AsWebexSimpleApi, locations: List[Location],
153                                    year: int = None):
154    """
155    US national holidays for given locations
156
157    :param api: Webex api
158    :type api: WebexSimpleApi
159    :param locations: list of locations in which US national holidays should be observed
160    :type locations: List[Location]
161    :param year: year for national holidays. Default: current year
162    :type year: int
163    """
164    # default: this year
165    year = year or date.today().year
166
167    # get national holidays for specified year
168    loop = asyncio.get_running_loop()
169    # avoid sync all:
170    # holidays = CalendarifiyApi().holidays(country='US', year=year, holiday_type='national')
171    holidays = await loop.run_in_executor(None, functools.partial(CalendarifiyApi().holidays,
172                                                                  country='US', year=year, holiday_type='national'))
173
174    # update holiday schedule for each location
175    if USE_TASKS:
176        await asyncio.gather(*[observe_in_location(api=api, location=location, holidays=holidays)
177                               for location in locations])
178    else:
179        for location in locations:
180            await observe_in_location(api=api, location=location, holidays=holidays)
181    return
182
183
184if __name__ == '__main__':
185    # read dotenv which has some environment variables like Webex API token and Calendarify
186    # API key.
187    load_dotenv()
188
189    # enable logging
190    logging.basicConfig(level=logging.DEBUG,
191                        format='%(asctime)s %(levelname)s %(threadName)s %(name)s: %(message)s')
192    logging.getLogger('urllib3').setLevel(logging.INFO)
193    logging.getLogger('wxc_sdk.as_rest').setLevel(logging.INFO)
194
195    # the actual action
196    async def do_provision():
197
198        async with AsWebexSimpleApi(concurrent_requests=5) as wx_api:
199            # get all US locations
200            log.info('Getting locations...')
201            us_locations = [location
202                            for location in await wx_api.locations.list()
203                            if location.address.country == 'US']
204
205            # set up location locks
206            # location_locks is a defaultdict -> accessing with all potential keys creates the locks
207            list(location_locks[loc.location_id] for loc in us_locations)
208
209            # create national holiday schedule for given year(s) and locations
210            if USE_TASKS:
211                await asyncio.gather(*[observe_national_holidays(api=wx_api, year=year, locations=us_locations)
212                                       for year in range(FIRST_YEAR, LAST_YEAR + 1)])
213            else:
214                for year in range(FIRST_YEAR, LAST_YEAR + 1):
215                    await observe_national_holidays(api=wx_api, year=year, locations=us_locations)
216
217    asyncio.run(do_provision())

Persist tokens and obtain new tokens interactively

A typical problem specifically when creating CLI scripts is how to obtain valid access tokens for the API operations. If your code wants to invoke Webex REST APIs on behalf of a user then an integration is needed. The concepts of integrations are explained at the “Integrations” page on developer.cisco.com.

This example code shows how an OAUth Grant flow for an integration can be initiated from a script by using the Python webbrowser module and calling the open() method with the authorization URL of a given integration to open that URL in the system web browser. The user can then authenticate and grant access to the integration. In the last step of a successful authorization flow the web browser is redirected to the redirect_url of the integration.

The example code starts a primitive web server serving GET requests to http://localhost:6001/redirect. This URL has to be the redirect URL of the integration you create under My Webex Apps on developer.webex.com.

The sample script reads the integration parameters from environment variables (TOKEN_INTEGRATION_CLIENT_ID, TOKEN_INTEGRATION_CLIENT_SECRET, TOKEN_INTEGRATION_CLIENT_SCOPES). These variables can also be defined in get_tokens.env in the current directory:

# rename this to get_tokens.env and set values

# client ID for integration to be used.
TOKEN_INTEGRATION_CLIENT_ID=

# client secret of integration
TOKEN_INTEGRATION_CLIENT_SECRET=

# scopes to request. Use these scopes when creating the integration at developer.webex.com
# scopes can be in any form supported by wxc_sdk.scopes.parse_scopes()
TOKEN_INTEGRATION_CLIENT_SCOPES="spark:calls_write spark:kms spark:calls_read spark-admin:telephony_config_read spark:people_read"

The sample code persists the tokens in get_tokens.yml in the current directory. On startup the sample code tries to read tokens from that file. If needed a new access token is obtained using the refresh token.

An OAuth flow is only initiated if no (valid) tokens could be read from get_tokens.yml

Source: get_tokens.py

 1#!/usr/bin/env python
 2"""
 3Example script
 4read tokens from file or interactively obtain token by starting a local web server and open the authorization URL in
 5the local web browser
 6"""
 7import logging
 8import os
 9from typing import Optional
10
11from dotenv import load_dotenv
12
13from wxc_sdk import WebexSimpleApi
14from wxc_sdk.integration import Integration
15from wxc_sdk.scopes import parse_scopes
16from wxc_sdk.tokens import Tokens
17
18log = logging.getLogger(__name__)
19
20
21def env_path() -> str:
22    """
23    determine path for .env to load environment variables from
24
25    :return: .env file path
26    """
27    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.env')
28
29
30def yml_path() -> str:
31    """
32    determine path of YML file to persist tokens
33
34    :return: path to YML file
35    :rtype: str
36    """
37    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.yml')
38
39
40def build_integration() -> Integration:
41    """
42    read integration parameters from environment variables and create an integration
43
44    :return: :class:`wxc_sdk.integration.Integration` instance
45    """
46    client_id = os.getenv('TOKEN_INTEGRATION_CLIENT_ID')
47    client_secret = os.getenv('TOKEN_INTEGRATION_CLIENT_SECRET')
48    scopes = parse_scopes(os.getenv('TOKEN_INTEGRATION_CLIENT_SCOPES'))
49    redirect_url = 'http://localhost:6001/redirect'
50    if not all((client_id, client_secret, scopes)):
51        raise ValueError('failed to get integration parameters from environment')
52    return Integration(client_id=client_id, client_secret=client_secret, scopes=scopes,
53                       redirect_url=redirect_url)
54
55
56def get_tokens() -> Optional[Tokens]:
57    """
58
59    Tokens are read from a YML file. If needed an OAuth flow is initiated.
60
61    :return: tokens
62    :rtype: :class:`wxc_sdk.tokens.Tokens`
63    """
64
65    integration = build_integration()
66    tokens = integration.get_cached_tokens_from_yml(yml_path=yml_path())
67    return tokens
68
69
70if __name__ == '__main__':
71    logging.basicConfig(level=logging.DEBUG)
72
73    # load environment variables from .env
74    path = env_path()
75    log.info(f'reading {path}')
76    load_dotenv(env_path())
77
78    tokens = get_tokens()
79
80    # use the tokens to get identity of authenticated user
81    api = WebexSimpleApi(tokens=tokens)
82    me = api.people.me()
83    print(f'authenticated as {me.display_name} ({me.emails[0]}) ')

Read/update call intercept settings of a user

usage: call_intercept.py [-h] [--token TOKEN] user_email [{on,off}]

positional arguments:
  user_email     email address of user
  {on,off}       operation to apply

options:
 -h, --help     show this help message and exit
 --token TOKEN  admin access token to use

The script uses the access token passed via the CLI, reads one from the WEBEX_ACCESS_TOKEN environment variable or obtains tokens via an OAuth flow. For the last option the integration parameters are read from environment variables which can be set in a .env file

Source: call_intercept.py

  1#!/usr/bin/env python
  2"""
  3Script to read/update call intercept settings of a calling user.
  4
  5The script uses the access token passed via the CLI, reads one from the WEBEX_ACCESS_TOKEN environment variable or
  6obtains tokens via an OAuth flow.
  7
  8    usage: call_intercept.py [-h] [--token TOKEN] user_email [{on,off}]
  9
 10    positional arguments:
 11      user_email     email address of user
 12      {on,off}       operation to apply
 13
 14    options:
 15      -h, --help     show this help message and exit
 16      --token TOKEN  admin access token to use
 17"""
 18import argparse
 19import logging
 20import os
 21import re
 22import sys
 23from json import loads
 24from typing import Optional
 25
 26from dotenv import load_dotenv
 27from wxc_sdk import WebexSimpleApi
 28from wxc_sdk.integration import Integration
 29from wxc_sdk.person_settings.call_intercept import InterceptSetting
 30from wxc_sdk.rest import RestError
 31from wxc_sdk.scopes import parse_scopes
 32from wxc_sdk.tokens import Tokens
 33from yaml import safe_dump, safe_load
 34
 35log = logging.getLogger(__name__)
 36
 37
 38def env_path() -> str:
 39    """
 40    determine path for .env to load environment variables from
 41
 42    :return: .env file path
 43    """
 44    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.env')
 45
 46
 47def yml_path() -> str:
 48    """
 49    determine path of YML file to persist tokens
 50
 51    :return: path to YML file
 52    :rtype: str
 53    """
 54    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.yml')
 55
 56
 57def build_integration() -> Integration:
 58    """
 59    read integration parameters from environment variables and create an integration
 60
 61    :return: :class:`wxc_sdk.integration.Integration` instance
 62    """
 63    client_id = os.getenv('TOKEN_INTEGRATION_CLIENT_ID')
 64    client_secret = os.getenv('TOKEN_INTEGRATION_CLIENT_SECRET')
 65    scopes = os.getenv('TOKEN_INTEGRATION_CLIENT_SCOPES')
 66    if scopes:
 67        scopes = parse_scopes(scopes)
 68    if not all((client_id, client_secret, scopes)):
 69        raise ValueError('failed to get integration parameters from environment')
 70    redirect_url = 'http://localhost:6001/redirect'
 71    return Integration(client_id=client_id, client_secret=client_secret, scopes=scopes,
 72                       redirect_url=redirect_url)
 73
 74
 75def get_tokens() -> Optional[Tokens]:
 76    """
 77
 78    Tokens are read from a YML file. If needed an OAuth flow is initiated.
 79
 80    :return: tokens
 81    :rtype: :class:`wxc_sdk.tokens.Tokens`
 82    """
 83
 84    def write_tokens(tokens_to_cache: Tokens):
 85        with open(yml_path(), mode='w') as f:
 86            safe_dump(loads(tokens_to_cache.json()), f)
 87        return
 88
 89    def read_tokens() -> Optional[Tokens]:
 90        try:
 91            with open(yml_path(), mode='r') as f:
 92                data = safe_load(f)
 93                tokens_read = Tokens.model_validate(data)
 94        except Exception as e:
 95            log.info(f'failed to read tokens from file: {e}')
 96            tokens_read = None
 97        return tokens_read
 98
 99    integration = build_integration()
100    tokens = integration.get_cached_tokens(read_from_cache=read_tokens,
101                                           write_to_cache=write_tokens)
102    return tokens
103
104
105RE_EMAIL = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
106
107
108def email_type(value):
109    if not RE_EMAIL.match(value):
110        raise argparse.ArgumentTypeError(f"'{value}' is not a valid email")
111    return value
112
113
114def main():
115    """
116    where the magic happens
117    """
118    # read .env file with the settings for the integration to be used to obtain tokens
119    load_dotenv(env_path())
120
121    parser = argparse.ArgumentParser()
122    parser.add_argument('user_email', type=email_type, help='email address of user')
123    parser.add_argument('on_off', choices=['on', 'off'], nargs='?', help='operation to apply')
124    parser.add_argument('--token', type=str, required=False, help='admin access token to use')
125    args = parser.parse_args()
126
127    if args.token:
128        tokens = args.token
129    elif (tokens := os.getenv('WEBEX_ACCESS_TOKEN')) is None:
130        tokens = get_tokens()
131
132    if not tokens:
133        print('Failed to get tokens', file=sys.stderr)
134        exit(1)
135
136    # set level to DEBUG to see debug of REST requests
137    logging.basicConfig(level=(gt := getattr(sys, 'gettrace', None)) and gt() and logging.DEBUG or logging.INFO)
138
139    with WebexSimpleApi(tokens=tokens) as api:
140        # get user
141        email = args.user_email.lower()
142        user = next((user
143                     for user in api.people.list(email=email)
144                     if user.emails[0] == email), None)
145        if user is None:
146            print(f'User "{email}" not found', file=sys.stderr)
147            exit(1)
148
149        # display call intercept status
150        try:
151            intercept = api.person_settings.call_intercept.read(user.person_id)
152        except RestError as e:
153            print(f'Failed to read call intercept settings: {e.response.status_code}, {e.description}')
154            exit(1)
155
156        print('on' if intercept.enabled else 'off')
157        if args.on_off:
158            # action: turn on/off
159            intercept = InterceptSetting.default()
160            intercept.enabled = args.on_off == 'on'
161            try:
162                api.person_settings.call_intercept.configure(user.person_id,
163                                                             intercept=intercept)
164            except RestError as e:
165                print(f'Failed to update call intercept settings: {e.response.status_code}, {e.description}')
166                exit(1)
167
168            # read call intercept again
169            try:
170                intercept = api.person_settings.call_intercept.read(user.person_id)
171            except RestError as e:
172                print(f'Failed to read call intercept settings: {e.response.status_code}, {e.description}')
173                exit(1)
174
175            # display state after update
176            print(f"set to {'on' if intercept.enabled else 'off'}")
177
178    exit(0)
179
180
181if __name__ == '__main__':
182    main()

Read/update call queue agent join states

usage: queue_helper.py [-h] [--location LOCATION [LOCATION ...]]
                       [--queue QUEUE [QUEUE ...]]
                       [--join JOIN_AGENT [JOIN_AGENT ...]]
                       [--unjoin UNJOIN_AGENT [UNJOIN_AGENT ...]]
                       [--remove REMOVE_USER [REMOVE_USER ...]]
                       [--add ADD_USER [ADD_USER ...]] [--dryrun]
                       [--token TOKEN]

Modify call queue settings from the CLI

optional arguments:
  -h, --help            show this help message and exit
  --location LOCATION [LOCATION ...], -l LOCATION [LOCATION ...]
                        name of location to work on. If missing then work on
                        all locations.
  --queue QUEUE [QUEUE ...], -q QUEUE [QUEUE ...]
                        name(s) of queue(s) to operate on. If missing then
                        work on all queues in location.
  --join JOIN_AGENT [JOIN_AGENT ...], -j JOIN_AGENT [JOIN_AGENT ...]
                        Join given user(s) on given queue(s). Can be "all" to
                        act on all agents.
  --unjoin UNJOIN_AGENT [UNJOIN_AGENT ...], -u UNJOIN_AGENT [UNJOIN_AGENT ...]
                        Unjoin given agent(s) from given queue(s). Can be
                        "all" to act on all agents.
  --remove REMOVE_USER [REMOVE_USER ...], -r REMOVE_USER [REMOVE_USER ...]
                        Remove given agent from given queue(s). Can be "all"
                        to act on all agents.
  --add ADD_USER [ADD_USER ...], -a ADD_USER [ADD_USER ...]
                        Add given users to given queue(s).
  --dryrun, -d          Dry run; don't apply any changes
  --token TOKEN         admin access token to use

The script uses the access token passed via the CLI, reads one from the WEBEX_ACCESS_TOKEN environment variable or obtains tokens via an OAuth flow. For the last option the integration parameters are read from environment variables which can be set in a queue_helper.env file in the current directory.

Source: queue_helper.py

  1#!/usr/bin/env python
  2"""
  3usage: queue_helper.py [-h] [--location LOCATION [LOCATION ...]] [--queue QUEUE [QUEUE ...]]
  4                       [--join JOIN_AGENT [JOIN_AGENT ...]] [--unjoin UNJOIN_AGENT [UNJOIN_AGENT ...]]
  5                       [--remove REMOVE_USER [REMOVE_USER ...]] [--add ADD_USER [ADD_USER ...]] [--dryrun]
  6                       [--token TOKEN]
  7
  8Modify call queue settings from the CLI
  9
 10optional arguments:
 11  -h, --help            show this help message and exit
 12  --location LOCATION [LOCATION ...], -l LOCATION [LOCATION ...]
 13                        name of location to work on. If missing then work on all locations.
 14  --queue QUEUE [QUEUE ...], -q QUEUE [QUEUE ...]
 15                        name(s) of queue(s) to operate on. If missing then work on all queues in location.
 16  --join JOIN_AGENT [JOIN_AGENT ...], -j JOIN_AGENT [JOIN_AGENT ...]
 17                        Join given user(s) on given queue(s). Can be "all" to act on all agents.
 18  --unjoin UNJOIN_AGENT [UNJOIN_AGENT ...], -u UNJOIN_AGENT [UNJOIN_AGENT ...]
 19                        Unjoin given agent(s) from given queue(s). Can be "all" to act on all agents.
 20  --remove REMOVE_USER [REMOVE_USER ...], -r REMOVE_USER [REMOVE_USER ...]
 21                        Remove given agent from given queue(s). Can be "all" to act on all agents.
 22  --add ADD_USER [ADD_USER ...], -a ADD_USER [ADD_USER ...]
 23                        Add given users to given queue(s).
 24  --dryrun, -d          Dry run; don't apply any changes
 25  --token TOKEN         admin access token to use
 26"""
 27import asyncio
 28import logging
 29import os
 30import sys
 31from argparse import ArgumentParser
 32from collections.abc import AsyncGenerator
 33from typing import Optional
 34
 35from dotenv import load_dotenv
 36
 37from wxc_sdk.as_api import AsWebexSimpleApi
 38from wxc_sdk.integration import Integration
 39from wxc_sdk.people import Person
 40from wxc_sdk.scopes import parse_scopes
 41from wxc_sdk.telephony.callqueue import CallQueue
 42from wxc_sdk.tokens import Tokens
 43from wxc_sdk.telephony.hg_and_cq import Agent
 44
 45
 46def agent_name(agent: Agent) -> str:
 47    return f'{agent.first_name} {agent.last_name}'
 48
 49
 50def env_path() -> str:
 51    """
 52    determine path for .env to load environment variables from; based on name of this file
 53    :return: .env file path
 54    """
 55    return f'{os.path.splitext(__file__)[0]}.env'
 56
 57
 58def yml_path() -> str:
 59    """
 60    determine path of YML file to persist tokens
 61    :return: path to YML file
 62    :rtype: str
 63    """
 64    return f'{os.path.splitext(__file__)[0]}.yml'
 65
 66
 67def build_integration() -> Integration:
 68    """
 69    read integration parameters from environment variables and create an integration
 70    :return: :class:`wxc_sdk.integration.Integration` instance
 71    """
 72    client_id = os.getenv('INTEGRATION_CLIENT_ID')
 73    client_secret = os.getenv('INTEGRATION_CLIENT_SECRET')
 74    scopes = parse_scopes(os.getenv('INTEGRATION_SCOPES'))
 75    redirect_url = 'http://localhost:6001/redirect'
 76    if not all((client_id, client_secret, scopes)):
 77        raise ValueError('failed to get integration parameters from environment')
 78    return Integration(client_id=client_id, client_secret=client_secret, scopes=scopes,
 79                       redirect_url=redirect_url)
 80
 81
 82def get_tokens() -> Optional[Tokens]:
 83    """
 84    Tokens are read from a YML file. If needed an OAuth flow is initiated.
 85
 86    :return: tokens
 87    :rtype: :class:`wxc_sdk.tokens.Tokens`
 88    """
 89
 90    integration = build_integration()
 91    tokens = integration.get_cached_tokens_from_yml(yml_path=yml_path())
 92    return tokens
 93
 94
 95async def main():
 96    async def act_on_queue(queue: CallQueue):
 97        """
 98        Act on a single queue
 99        """
100        # we need the queue details b/c the queue instance passed as parameter is from a list() call
101        # ... and thus is missing all the details like agents
102        details = await api.telephony.callqueue.details(location_id=queue.location_id, queue_id=queue.id)
103        agent_names = set(map(agent_name, details.agents))
104
105        def notify(message: str) -> str:
106            """
107            an action notification with queue information
108            """
109            return f'queue "{details.name:{queue_len}}" in "{queue.location_name:{location_len}}": {message}'
110
111        def validate_agents(names: list[str], operation: str) -> list[str]:
112            """
113            check if all names in given list exist as agents on current queue
114            """
115            if 'all' in names:
116                return set(agent_names)
117
118            not_found = [name for name in names if name not in agent_names]
119            if not_found:
120                print('\n'.join(notify(f'{name} not found for {operation}"')
121                                for name in not_found),
122                      file=sys.stderr)
123            return set(name for name in names if name not in set(not_found))
124
125        # validate list of names or join, unjoin, and remove against actual list of agents
126        to_join = validate_agents(join_agents, 'join')
127        to_unjoin = validate_agents(unjoin_agents, 'unjoin')
128        to_remove = validate_agents(remove_users, 'remove')
129
130        # check for agents we are asked to add but which already exist as agents on the queue
131        existing_agent_ids = set(agent.agent_id for agent in details.agents)
132        agent_exists = [agent_name(user) for user in add_users
133                        if user.person_id in existing_agent_ids]
134        if agent_exists:
135            print('\n'.join(notify(f'{name} already is agent')
136                            for name in agent_exists),
137                  file=sys.stderr)
138            # reduced set of users to add
139            to_add = [user for user in add_users
140                      if agent_name(user) not in set(agent_exists)]
141        else:
142            # ...  or add all users
143            to_add = add_users
144
145        # the updated list of agents for the current queue
146        new_agents = []
147
148        # do we actually need an update?
149        update_needed = False
150
151        # create copy of each agent instance; we don't want to update the original agent objects
152        # to make sure that details still holds the state before any update
153        agents = [agent.copy(deep=True) for agent in details.agents]
154
155        # iterate through the existing agents and see if we have to apply any change
156        for agent in agents:
157            name = agent_name(agent)
158            # do we have to take action to join this agent?
159            if name in to_join and not agent.join_enabled:
160                print(notify(f'{name}, join'))
161                update_needed = True
162                agent.join_enabled = True
163            # do we have to take action to unjoin this agent?
164            if name in to_unjoin and agent.join_enabled:
165                print(notify(f'{name}, unjoin'))
166                update_needed = True
167                agent.join_enabled = False
168            # do we have to remove this agent?
169            if name in to_remove:
170                print(notify(f'{name}, remove'))
171                update_needed = True
172                # skip to next agent; so that we don't add this agent to the updated list of agents
173                continue
174            new_agents.append(agent)
175
176        # add new agents
177        new_agents.extend(Agent(id=user.person_id)
178                          for user in to_add)
179
180        # update the queue
181        if (update_needed or to_add) and not args.dryrun:
182            # simplified update: we only messed with the agents
183            update = CallQueue(agents=new_agents)
184            await api.telephony.callqueue.update(location_id=queue.location_id, queue_id=queue.id,
185                                                 update=update)
186            print(notify('queue updated'))
187            # and get details after the update
188            details = await api.telephony.callqueue.details(location_id=queue.location_id, queue_id=queue.id)
189            print(notify('got details after update'))
190
191        # print summary
192        print(f'queue "{queue.name:{queue_len}}" in "{queue.location_name}"')
193        print(f'  phone number: {details.phone_number}')
194        print(f'  extension: {details.extension}')
195        print('  agents')
196        if details.agents:
197            name_len = max(map(len, map(agent_name, details.agents)))
198            for agent in details.agents:
199                print(f'    {agent_name(agent):{name_len}}: {"not " if not agent.join_enabled else ""}joined')
200        return
201
202    async def validate_users(user_names: list[str]) -> AsyncGenerator[Person, None, None]:
203        """
204        Validate list of names of users to be added and yield a Person instance for each one
205        """
206        # search for all names in parallel
207        lists: list[list[Person]] = await asyncio.gather(
208            *[api.people.list(display_name=name) for name in user_names], return_exceptions=True)
209        for name, user_list in zip(user_names, lists):
210            if isinstance(user_list, Exception):
211                user = None
212            else:
213                user = next((u for u in user_list if name == agent_name(u)), None)
214            if user is None:
215                print(f'user "{name}" not found', file=sys.stderr)
216                continue
217            yield user
218        return
219
220    # parse command line
221    parser = ArgumentParser(description='Modify call queue settings from the CLI')
222    parser.add_argument('--location', '-l', type=str, required=False, nargs='+',
223                        help='name of location to work on. If missing then work on all locations.')
224
225    parser.add_argument('--queue', '-q', type=str, required=False, nargs='+',
226                        help='name(s) of queue(s) to operate on. If missing then work on all queues in location.')
227
228    parser.add_argument('--join', '-j', type=str, required=False, nargs='+', dest='join_agent',
229                        help='Join given user(s) on given queue(s). Can be "all" to act on all agents.')
230
231    parser.add_argument('--unjoin', '-u', type=str, required=False, nargs='+', dest='unjoin_agent',
232                        help='Unjoin given agent(s) from given queue(s). Can be "all" to act on all agents.')
233
234    parser.add_argument('--remove', '-r', type=str, required=False, nargs='+', dest='remove_user',
235                        help='Remove given agent from given queue(s). Can be "all" to act on all agents.')
236
237    parser.add_argument('--add', '-a', type=str, required=False, nargs='+', dest='add_user',
238                        help='Add given users to given queue(s).')
239    parser.add_argument('--dryrun', '-d', required=False, action='store_true',
240                        help='Dry run; don\'t apply any changes')
241    parser.add_argument('--token', type=str, required=False, help='admin access token to use')
242
243    args = parser.parse_args()
244
245    # get environment variables from .env; required for integration parameters
246    load_dotenv(env_path())
247
248    tokens = args.token or None
249    if tokens is None:
250        # get tokens from cache or create a new set of tokens using the integration defined in .env
251        tokens = get_tokens()
252
253    async with AsWebexSimpleApi(tokens=tokens) as api:
254        # validate location parameter
255        location_names = args.location or []
256
257        # list of all locations with names matching one of the provided names
258        locations = [loc for loc in await api.locations.list()
259                     if not location_names or loc.name in set(location_names)]
260
261        if not location_names:
262            print(f'Considering all {len(locations)} locations')
263
264        # set of names of matching locations
265        found_location_names = set(loc.name for loc in locations)
266
267        # Error message for each location name argument not matching an actual location
268        for location_name in location_names:
269            if location_name not in found_location_names:
270                print(f'location "{location_name}" not found', file=sys.stderr)
271
272        if not locations:
273            print('Found no locations to work on', file=sys.stderr)
274            exit(1)
275
276        # which queues do we need to operate on?
277        location_ids = set(loc.location_id for loc in locations)
278        queue_names = args.queue
279        all_queues = queue_names is None
280        # full list of queues
281        queues = await api.telephony.callqueue.list()
282        # filter based on location parameter
283        queues = [queue for queue in queues
284                  if (all_queues or queue.name in queue_names) and queue.location_id in location_ids]
285
286        # len of queue names for nicer output
287        queue_len = max(len(queue.name) for queue in queues)
288
289        # now we can actually go back and re-evaluate the list of locations; for the location length we only need
290        # to consider locations we actually have a target queue in
291        location_ids = set(queue.location_id for queue in queues)
292
293        # max length of location names for nicely formatted output
294        location_len = max(len(loc.name)
295                           for loc in locations
296                           if loc.location_id in location_ids)
297
298        # get the names for join, unjoin, remove, and add
299        join_agents = args.join_agent or []
300        unjoin_agents = args.unjoin_agent or []
301        remove_users = args.remove_user or []
302        add_users = args.add_user or []
303
304        # validate users; make sure that users exist with the provided names
305        add_users = [u async for u in validate_users(user_names=add_users)]
306
307        # apply actions to all queues
308        await asyncio.gather(*[act_on_queue(queue) for queue in queues])
309
310
311if __name__ == '__main__':
312    # enable DEBUG logging to a file; REST log shows all requests
313    logging.basicConfig(filename=os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.log'),
314                        filemode='w', level=logging.DEBUG)
315    asyncio.run(main())

Using service APP tokens to access a API endpoints

The script uses service app credentials to get an access token and then use this access token to call Webex Calling APIs.

Source: service_app.py

  1#!/usr/bin/env python
  2"""
  3Demo for Webex service app: using service APP tokens to access a API endpoints
  4"""
  5import inspect
  6import logging
  7import os
  8import sys
  9from json import dumps, loads
 10from os import getenv
 11from typing import Optional
 12
 13import yaml
 14from dotenv import load_dotenv
 15
 16from wxc_sdk import WebexSimpleApi
 17from wxc_sdk.integration import Integration
 18from wxc_sdk.tokens import Tokens
 19
 20SERVICE_APP_ENVS = ('SERVICE_APP_REFRESH_TOKEN', 'SERVICE_APP_CLIENT_ID', 'SERVICE_APP_CLIENT_SECRET')
 21
 22def yml_path(*, client_id: str) -> str:
 23    """
 24    Get filename for YML file to cache access and refresh token
 25    """
 26    return f'tokens_{client_id}.yml'
 27
 28
 29def env_path() -> str:
 30    """
 31    Get path to .env file to read service app settings from
 32    """
 33    # get the file name of the calling script to determine the name of the .env file
 34    frame = inspect.currentframe().f_back
 35    file_name = inspect.getframeinfo(frame).filename
 36    env_name = f'{os.path.splitext(os.path.basename(file_name))[0]}.env'
 37    return env_name
 38
 39
 40
 41def read_tokens_from_file(*, client_id: str) -> Optional[Tokens]:
 42    """
 43    Get service app tokens from cache file, return None if cache does not exist or read fails
 44    """
 45    path = yml_path(client_id=client_id)
 46    if not os.path.isfile(path):
 47        return None
 48    try:
 49        with open(path, mode='r') as f:
 50            data = yaml.safe_load(f)
 51        tokens = Tokens.model_validate(data)
 52    except Exception:
 53        return None
 54    return tokens
 55
 56
 57def write_tokens_to_file(*, client_id: str, tokens: Tokens):
 58    """
 59    Write tokens to cache
 60    """
 61    with open(yml_path(client_id=client_id), mode='w') as f:
 62        yaml.safe_dump(tokens.model_dump(exclude_none=True), f)
 63
 64
 65def get_access_token(*, client_id: str, client_secret: str, refresh: str) -> Tokens:
 66    """
 67    Get a new access token using refresh token, service app client id, service app client secret
 68    """
 69    tokens = Tokens(refresh_token=refresh)
 70    integration = Integration(client_id=client_id,
 71                              client_secret=client_secret,
 72                              scopes=[], redirect_url=None)
 73    integration.refresh(tokens=tokens)
 74    write_tokens_to_file(client_id=client_id, tokens=tokens)
 75    return tokens
 76
 77
 78def get_tokens() -> Optional[Tokens]:
 79    """
 80    Get tokens from environment variable, cache or create new access token using service app credentials
 81    """
 82    refresh, client_id, client_secret = (os.getenv(env) for env in SERVICE_APP_ENVS)
 83    if not all((refresh, client_id, client_secret)):
 84        token = os.getenv('WEBEX_ACCESS_TOKEN')
 85        if token is None:
 86            return None
 87        tokens = Tokens(access_token=token)
 88    else:
 89        # try to read from file
 90        tokens = read_tokens_from_file(client_id=client_id)
 91        # .. or create new access token using refresh token
 92        if tokens is None:
 93            tokens = get_access_token(client_id=client_id, client_secret=client_secret, refresh=refresh)
 94        if tokens.expires_in is not None and tokens.remaining < 24 * 60 * 60:
 95            tokens = get_access_token(client_id=client_id, client_secret=client_secret, refresh=refresh)
 96    return tokens
 97
 98
 99def service_app():
100    """
101    Use service app access token to call Webex Calling API endpoints
102    :return:
103    """
104    load_dotenv(env_path())
105    # assert that all required environment variable are set
106    if not all(getenv(s) for s in SERVICE_APP_ENVS):
107        print(
108            f'{", ".join(SERVICE_APP_ENVS)} environment variables need to be defined in '
109            f'environment or in "{env_path()}"',
110            file=sys.stderr)
111        exit(1)
112
113    # get tokens and dump to console
114    tokens = get_tokens()
115
116    print(dumps(loads(tokens.json()), indent=2))
117    print()
118    print('scopes:')
119    print('\n'.join(f' * {s}' for s in sorted(tokens.scope.split())))
120
121    # use tokens to access APIs
122    api = WebexSimpleApi(tokens=tokens)
123
124    users = list(api.people.list())
125    print(f'{len(users)} users')
126
127    queues = list(api.telephony.callqueue.list())
128    print(f'{len(queues)} call queues')
129
130
131if __name__ == '__main__':
132    logging.basicConfig(level=logging.DEBUG)
133    service_app()

Pool unassigned TNs on hunt groups to catch calls to unassigned TNs

This script looks for unassigned TNs and assigns them to HGs that are forwarded to the locations main number. The idea is to catch all incoming calls to unassigned TNs and handle them accordingly.

usage: catch_tns.py [-h] [--test] [--location LOCATION] [--token TOKEN]
                    [--cleanup]

optional arguments:
  -h, --help           show this help message and exit
  --test               test only; don't actually apply any config
  --location LOCATION  Location to work on
  --token TOKEN        admin access token to use.
  --cleanup            remove all pooling HGs

Source: catch_tns.py

  1#!/usr/bin/env python
  2"""
  3This script looks for unassigned TNs and assigns them to HGs that are forwarded to the locations main number.
  4The idea is to catch all incoming calls to unassigned TNs and handle them accordingly
  5
  6    usage: catch_tns.py [-h] [--test] [--location LOCATION] [--token TOKEN]
  7                        [--cleanup]
  8
  9    optional arguments:
 10      -h, --help           show this help message and exit
 11      --test               test only; don't actually apply any config
 12      --location LOCATION  Location to work on
 13      --token TOKEN        admin access token to use.
 14      --cleanup            remove all pooling HGs
 15"""
 16import asyncio
 17import logging
 18import os
 19import sys
 20from argparse import ArgumentParser, Namespace
 21from collections import defaultdict
 22from operator import attrgetter
 23from typing import Optional, Union
 24
 25from dotenv import load_dotenv
 26
 27from wxc_sdk.as_api import AsWebexSimpleApi
 28from wxc_sdk.common import IdAndName, AlternateNumber, RingPattern
 29from wxc_sdk.integration import Integration
 30from wxc_sdk.scopes import parse_scopes
 31from wxc_sdk.telephony import NumberListPhoneNumber
 32from wxc_sdk.telephony.forwarding import CallForwarding
 33from wxc_sdk.telephony.huntgroup import HuntGroup
 34from wxc_sdk.tokens import Tokens
 35
 36POOL_HG_NAME = 'POOL_'
 37
 38
 39def env_path() -> str:
 40    """
 41    determine path for .env to load environment variables from; based on name of this file
 42    :return: .env file path
 43    """
 44    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.env')
 45
 46
 47def yml_path() -> str:
 48    """
 49    determine path of YML file to persist tokens
 50    :return: path to YML file
 51    :rtype: str
 52    """
 53    return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.yml')
 54
 55
 56def build_integration() -> Integration:
 57    """
 58    read integration parameters from environment variables and create an integration
 59    :return: :class:`wxc_sdk.integration.Integration` instance
 60    """
 61    client_id = os.getenv('INTEGRATION_CLIENT_ID')
 62    client_secret = os.getenv('INTEGRATION_CLIENT_SECRET')
 63    scopes = parse_scopes(os.getenv('INTEGRATION_SCOPES'))
 64    redirect_url = 'http://localhost:6001/redirect'
 65    if not all((client_id, client_secret, scopes)):
 66        raise ValueError('failed to get integration parameters from environment')
 67    return Integration(client_id=client_id, client_secret=client_secret, scopes=scopes,
 68                       redirect_url=redirect_url)
 69
 70
 71def get_tokens() -> Optional[Tokens]:
 72    """
 73    Tokens are read from a YML file. If needed an OAuth flow is initiated.
 74
 75    :return: tokens
 76    :rtype: :class:`wxc_sdk.tokens.Tokens`
 77    """
 78
 79    integration = build_integration()
 80    tokens = integration.get_cached_tokens_from_yml(yml_path=yml_path())
 81    return tokens
 82
 83
 84async def location_id_from_args(api: AsWebexSimpleApi, args: Namespace) -> Optional[str]:
 85    """
 86    Get location id for --location parameter
 87    """
 88    if not args.location:
 89        return None
 90    location = next((loc
 91                     for loc in await api.locations.list(name=args.location)
 92                     if loc.name == args.location),
 93                    None)
 94    return location and location.location_id
 95
 96
 97async def cleanup(api: AsWebexSimpleApi, args: Namespace):
 98    """
 99    clean up (delete) pooling HGs
100    """
101    location_id = await location_id_from_args(api, args)
102    existing_hg_list = [hg for hg in await api.telephony.huntgroup.list(location_id=location_id)
103                        if hg.name.startswith(POOL_HG_NAME)]
104
105    async def delete_one(hg: HuntGroup):
106        if not args.test:
107            await api.telephony.huntgroup.delete_huntgroup(location_id=hg.location_id,
108                                                           huntgroup_id=hg.id)
109        print(f'Deleted HG "{hg.name}" in location "{hg.location_name}"')
110
111    await asyncio.gather(*[delete_one(hg)
112                           for hg in existing_hg_list])
113
114
115async def pool_tns_location(api: AsWebexSimpleApi, args: Namespace, location: IdAndName,
116                            tns: list[NumberListPhoneNumber]):
117    """
118    Pool unassigned TNs for a given location
119    """
120
121    async def add_to_hg(hg: Union[HuntGroup, str],
122                        tns: list[NumberListPhoneNumber]):
123        """
124        Add a bunch of TNs to given HG
125        :param hg: can be an existing HG or a name of a HG to be created
126        :param tns: list of TNs to be added to the HG
127        """
128        if isinstance(hg, str):
129            # create new HG
130            print(f'Creating HG "{hg}" in location "{location.name}" for: '
131                  f'{", ".join(tn.phone_number for tn in tns)}')
132            if args.test:
133                return
134            settings = HuntGroup.create(name=hg,
135                                        phone_number=tns[0].phone_number)
136            new_id = await api.telephony.huntgroup.create(location_id=location.id,
137                                                          settings=settings)
138            # Get details of new HG and also the forwarding settings
139            # * details are needed for the recursive call to add_to_hg .. in case we have more than one TN to add
140            # * ... and forwarding settings are needed b/c we want to set CFwdAll to location's main number
141            details, forwarding = await asyncio.gather(
142                api.telephony.huntgroup.details(location_id=location.id, huntgroup_id=new_id),
143                api.telephony.huntgroup.forwarding.settings(location_id=location.id, feature_id=new_id))
144            forwarding: CallForwarding
145            details: HuntGroup
146
147            # set call forwarding
148            print(f'HG "{hg}" in location "{location.name}": set CFwdAll to {main_number}')
149            forwarding.always.enabled = True
150            forwarding.always.destination = main_number
151            await api.telephony.huntgroup.forwarding.update(location_id=location.id, feature_id=new_id,
152                                                            forwarding=forwarding)
153            if len(tns) > 1:
154                # add the remaining as alternate numbers
155                await add_to_hg(hg=details, tns=tns[1:])
156            return
157
158        # add tns as alternate numbers
159        print(f'HG "{hg.name}" in location "{location.name}", adding: '
160              f'{", ".join(tn.phone_number for tn in tns)}')
161        if args.test:
162            return
163        # weirdly on GET alternate numbers are returned in alternate_number_settings ...
164        alternate_numbers = hg.alternate_number_settings.alternate_numbers
165        alternate_numbers.extend(AlternateNumber(phone_number=tn.phone_number,
166                                                 ring_pattern=RingPattern.normal)
167                                 for tn in tns)
168        # ... while for an update Wx expects the alternate numbers in an alternate_number attribute
169        update = HuntGroup(alternate_numbers=alternate_numbers)
170        await api.telephony.huntgroup.update(location_id=location.id,
171                                             huntgroup_id=hg.id,
172                                             update=update)
173
174        return
175
176    # if the list of available TNs includes the main number then something is wonky. The main number should be owned
177    # by something
178    main_number = next((tn for tn in tns if tn.main_number), None)
179    if main_number is not None:
180        print(f'Error: main number {main_number.phone_number} in location "{location.name}" is not assigned to '
181              f'anything!', file=sys.stderr)
182        return
183
184    # get main number of location
185    main_number = (await api.telephony.location.details(location_id=location.id)).calling_line_id.phone_number
186
187    # get list if "pool" HGs in location
188    existing_hg_list = [hg for hg in await api.telephony.huntgroup.list(location_id=location.id)
189                        if hg.name.startswith(POOL_HG_NAME)]
190
191    # we need the details for all HGs: list() response is missing the alternate number list
192    # get all HG details in parallel
193    existing_hg_list = await asyncio.gather(*[api.telephony.huntgroup.details(location_id=location.id,
194                                                                              huntgroup_id=hg.id)
195                                              for hg in existing_hg_list])
196    existing_hg_list: list[HuntGroup]
197
198    # start with an empty list of tasks
199    tasks = []
200
201    # assign TNs to existing "pool" HGs
202
203    # these are the HGs we can still assign some TNs to
204    hgs_with_open_slots = (hg
205                           for hg in existing_hg_list
206                           if len(hg.alternate_number_settings.alternate_numbers) < 10)
207    tns.sort(key=attrgetter('phone_number'))
208    while tns:
209        hg_with_open_slots = next(hgs_with_open_slots, None)
210        if hg_with_open_slots is None:
211            # no more HGs we can assign TNs to --> we are done here
212            break
213
214        # add some tns to this hg; hg can have max 10 alternate numbers
215        tns_to_add = 10 - len(hg_with_open_slots.alternate_number_settings.alternate_numbers)
216        tasks.append(add_to_hg(hg=hg_with_open_slots, tns=tns[:tns_to_add]))
217
218        # continue w/ remaining TNs
219        tns = tns[tns_to_add:]
220
221    # assign remaining TNs to new "pool" HGs
222    # .. in batches of 11
223    existing_names = set(hg.name for hg in existing_hg_list)
224    new_hg_names = (name
225                    for i in range(1, 1000)
226                    if (name := f'{POOL_HG_NAME}{i:03d}') not in existing_names)
227    while tns:
228        tasks.append(add_to_hg(hg=next(new_hg_names), tns=tns[:11]))
229        tns = tns[11:]
230
231    # Now run all tasks
232    await asyncio.gather(*tasks)
233    return
234
235
236async def pool_tns(api: AsWebexSimpleApi, args: Namespace):
237    """
238    Assign unassigned numbers to pool HGs
239    """
240    location_id = await location_id_from_args(api, args)
241
242    # get available TNs. If a location argument was present then limit to that location
243    numbers = await api.telephony.phone_numbers(available=True, location_id=location_id)
244
245    # we need to work on TNs by location ...
246    tns_by_location: dict[str, list[NumberListPhoneNumber]] = defaultdict(list)
247    # ... and we want to collect location information (specifically the name)
248    locations: dict[str, IdAndName] = dict()
249    for tn in numbers:
250        locations[tn.location.id] = tn.location
251        tns_by_location[tn.location.id].append(tn)
252
253    # work on all locations in parallel
254    await asyncio.gather(*[pool_tns_location(api=api, args=args,
255                                             location=locations[location_id], tns=tns)
256                           for location_id, tns in tns_by_location.items()])
257
258
259async def catch_tns():
260    """
261    Main async logic
262    """
263    parser = ArgumentParser()
264    parser.add_argument('--test', required=False, help='test only; don\'t actually apply any config',
265                        action='store_true')
266    parser.add_argument('--location', required=False, help='Location to work on', type=str)
267    parser.add_argument('--token', type=str, required=False, help='admin access token to use.')
268    parser.add_argument('--cleanup', required=False, help='remove all pooling HGs', action='store_true')
269    args = parser.parse_args()
270
271    load_dotenv(env_path())
272
273    tokens = args.token or None
274
275    if tokens is None:
276        # get tokens from cache or create a new set of tokens using the integration defined in .env
277        tokens = get_tokens()
278    async with AsWebexSimpleApi(tokens=tokens) as api:
279        if args.cleanup:
280            await cleanup(api, args)
281        else:
282            await pool_tns(api, args)
283
284
285if __name__ == '__main__':
286    logging.basicConfig(level=logging.INFO)
287    asyncio.run(catch_tns())

Downgrade room device workspaces from Webex Calling to free calling

This script looks for workspaces in a given location (or all workspaces) and downgrades them from Webex Calling to free calling.

usage: room_devices.py [-h] [--location LOCATION] [--wsnames WSNAMES] [--test] {show,clear}

CLI tool to manage room device calling entitlements

positional arguments:
  {show,clear}         show: show all room devices with their calling settings, clear:
                       remove calling license from devices

options:
  -h, --help           show this help message and exit
  --location LOCATION  work on devices in given location
  --wsnames WSNAMES    file name of a file with workspace names to operate on; one name per
                       line
  --test               test run only
(wxc-sdk-py3.11) ➜  examples git:(master) ✗ ./room_devices.py --help
usage: room_devices.py [-h] [--location LOCATION] [--wsnames WSNAMES] [--test] {show,clear}

CLI tool to manage room device calling entitlements

positional arguments:
  {show,clear}         show: show all room devices with their calling settings, clear: remove
                       calling license from devices

options:
  -h, --help           show this help message and exit
  --location LOCATION  work on devices in given location
  --wsnames WSNAMES    file name of a file with workspace names to operate on; one name per
                       line
  --test               test run only

Source: room_devices.py

  1#!/usr/bin/env python
  2"""
  3    usage: room_devices.py [-h] [--location LOCATION] [--wsnames WSNAMES] [--test] {show,clear}
  4
  5    CLI tool to manage room device calling entitlements
  6
  7    positional arguments:
  8      {show,clear}         show: show all room devices with their calling settings, clear: remove calling
  9                           license from devices
 10
 11    optional arguments:
 12      -h, --help           show this help message and exit
 13      --location LOCATION  work on devices in given location
 14      --wsnames WSNAMES    file name of a file with workspace names to operate on; one name per line
 15      --test               test run only
 16
 17    The tool reads environment variables from room_devices.env:
 18        SERVICE_APP_CLIENT_ID=<clients id of a service app created on developer.webex.com>
 19        SERVICE_APP_CLIENT_SECRET=<clients secret of a service app created on developer.webex.com>
 20        SERVICE_APP_REFRESH_TOKEN=<refresh token of the service app obtained after the service app has been
 21                                        authorized for an org>
 22
 23    This information is used to obtain an access token required to authorize API access
 24
 25    This is a super-set of the scopes the service app needs:
 26        * spark-admin:workspaces_write
 27        * Identity:one_time_password
 28        * identity:placeonetimepassword_create
 29        * spark:people_read
 30        * spark-admin:workspace_locations_read
 31        * spark-admin:workspaces_read
 32        * spark:devices_write
 33        * spark:devices_read
 34        * spark:kms
 35        * spark-admin:devices_read
 36        * spark-admin:workspace_locations_write
 37        * spark-admin:licenses_read
 38        * spark-admin:telephony_config_read
 39        * spark-admin:telephony_config_write
 40        * spark-admin:devices_write
 41        * spark-admin:people_read
 42
 43    More service app details: https://developer.webex.com/docs/service-apps
 44
 45    Tokens get persisted in room_devices.yml.
 46"""
 47import asyncio
 48import logging
 49import sys
 50import time
 51from argparse import ArgumentParser
 52from collections import defaultdict
 53from functools import reduce
 54from itertools import chain
 55from os import getenv, getcwd
 56from os.path import splitext, basename, isfile, join
 57from typing import Optional
 58
 59from dotenv import load_dotenv
 60from yaml import safe_load, safe_dump
 61
 62from wxc_sdk.as_api import AsWebexSimpleApi
 63from wxc_sdk.base import webex_id_to_uuid
 64from wxc_sdk.common import OwnerType
 65from wxc_sdk.devices import Device
 66from wxc_sdk.integration import Integration
 67from wxc_sdk.locations import Location
 68from wxc_sdk.telephony import NumberListPhoneNumber
 69from wxc_sdk.tokens import Tokens
 70from wxc_sdk.workspace_locations import WorkspaceLocation
 71from wxc_sdk.workspaces import Workspace, WorkspaceSupportedDevices, CallingType, WorkspaceCalling
 72
 73
 74def yml_path() -> str:
 75    """
 76    Get filename for YML file to cache access and refresh token
 77    """
 78    return f'{splitext(basename(__file__))[0]}.yml'
 79
 80
 81def env_path() -> str:
 82    """
 83    Get path to .env file to read service app settings from
 84    """
 85    return f'{splitext(basename(__file__))[0]}.env'
 86
 87
 88def read_tokens_from_file() -> Optional[Tokens]:
 89    """
 90    Get service app tokens from cache file, return None if cache does not exist or read fails
 91    """
 92    path = yml_path()
 93    if not isfile(path):
 94        return None
 95    try:
 96        with open(path, mode='r') as f:
 97            data = safe_load(f)
 98        tokens = Tokens.model_validate(data)
 99    except Exception:
100        return None
101    return tokens
102
103
104def write_tokens_to_file(tokens: Tokens):
105    """
106    Write tokens to cache
107    """
108    with open(yml_path(), mode='w') as f:
109        safe_dump(tokens.model_dump(exclude_none=True), f)
110
111
112def get_access_token() -> Tokens:
113    """
114    Get a new access token using refresh token, service app client id, service app client secret
115    """
116    tokens = Tokens(refresh_token=getenv('SERVICE_APP_REFRESH_TOKEN'))
117    integration = Integration(client_id=getenv('SERVICE_APP_CLIENT_ID'),
118                              client_secret=getenv('SERVICE_APP_CLIENT_SECRET'),
119                              scopes=[], redirect_url=None)
120    integration.refresh(tokens=tokens)
121    write_tokens_to_file(tokens)
122    return tokens
123
124
125def get_tokens() -> Optional[Tokens]:
126    """
127    Get tokens from cache or create new access token using service app credentials
128    """
129    # try to read from file
130    tokens = read_tokens_from_file()
131    # .. or create new access token using refresh token
132    if tokens is None:
133        tokens = get_access_token()
134    if tokens.remaining < 24 * 60 * 60:
135        tokens = get_access_token()
136    return tokens
137
138
139def main() -> int:
140    """
141    Main code
142    """
143    # parse args
144    parser = ArgumentParser(prog=basename(__file__), description='CLI tool to manage room device calling entitlements')
145    parser.add_argument('operation', choices=['show', 'clear'], help='show: show all room devices with their calling '
146                                                                     'settings, clear: remove calling license from '
147                                                                     'devices')
148    parser.add_argument('--location', type=str, help='work on devices in given location')
149    parser.add_argument('--wsnames', type=str, help='file name of a file with workspace names to operate on; '
150                                                    'one name per line')
151    parser.add_argument('--test', action='store_true', help='test run only')
152    args = parser.parse_args()
153    operation = args.operation
154    test_run = args.test
155    location = args.location
156    ws_names = args.wsnames
157
158    # get tokens; as an alternative you can just get a developer token from developer.webex.com and use:
159    #   tokens = '<developer token from developer.webex.com>'
160    load_dotenv(dotenv_path=env_path())
161    err = ''
162    tokens = None
163    try:
164        tokens = get_tokens()
165    except Exception as e:
166        err = f'{e}'
167    if not tokens:
168        print(f'failed to obtain access tokens: {err}', file=sys.stderr)
169        return 1
170
171    async def as_main() -> int:
172        """
173        Async main to be able to use concurrency
174        """
175
176        async def downgrade_workspace(ws: Workspace):
177            """
178            Downgrade one workspace to free calling
179            """
180
181            def log(s: str, file=sys.stdout):
182                print(f'downgrade workspace "{ws.display_name:{ws_name_len}}": {s}', file=file)
183
184            if ws.calling.type != CallingType.webex:
185                raise ValueError(f'calling type is "{ws.calling.type}", not "{CallingType.webex.value}"')
186            if test_run:
187                log('skipping update, test run only')
188            else:
189                log('updating calling settings')
190                update = ws.model_copy(deep=True)
191                update.calling = WorkspaceCalling(type=CallingType.free)
192                update.workspace_location_id = None
193                update.location_id = None
194                await api.workspaces.update(workspace_id=ws.workspace_id, settings=update)
195            log('done')
196
197        async with AsWebexSimpleApi(tokens=tokens) as api:
198
199            # get list of locations and workspace locations
200            ws_location_list, location_list = await asyncio.gather(
201                api.workspace_locations.list(display_name=location),
202                api.locations.list(name=location))
203            location_list: list[Location]
204            ws_location_list: list[WorkspaceLocation]
205
206            # validate location argument
207            if location:
208                target_location = next((loc for loc in location_list if loc.name == location), None)
209                target_ws_location = next((loc for loc in ws_location_list if loc.display_name == location), None)
210                if not all((target_ws_location, target_location)):
211                    print(f'location "{location}" not found', file=sys.stderr)
212                    return 1
213            else:
214                target_location = None
215                target_ws_location = None
216
217            # get workspaces, numbers, and devices (in target location)
218            workspaces, numbers, devices = await asyncio.gather(
219                api.workspaces.list(workspace_location_id=target_ws_location and target_ws_location.id),
220                api.telephony.phone_numbers(location_id=target_location and target_location.location_id,
221                                            owner_type=OwnerType.place),
222                api.devices.list(workspace_location_id=target_ws_location and target_ws_location.id,
223                                 product_type='roomdesk')
224            )
225            workspaces: list[Workspace]
226            numbers: list[NumberListPhoneNumber]
227            devices: list[Device]
228
229            # only workspaces supporting desk devices
230            workspaces = [ws for ws in workspaces
231                          if ws.supported_devices == WorkspaceSupportedDevices.collaboration_devices]
232
233            # if a path to a file with workspace names was given, then filter based on the file contents
234            if ws_names:
235                with open(ws_names, mode='r') as f:
236                    workspace_names = set(s_line for line in f if (s_line := line.strip()))
237                workspaces = [ws for ws in workspaces
238                              if ws.display_name in workspace_names]
239            if not workspaces:
240                print('No workspaces', file=sys.stderr)
241                return 1
242
243            # only devices in workspaces (no personal devices)
244            devices = [d for d in devices if d.workspace_id is not None]
245
246            # prepare some lookups
247            workspace_locations_by_id: dict[str, WorkspaceLocation] = {wsl.id: wsl for wsl in ws_location_list}
248            numbers_by_workspace_uuid: dict[str, list[NumberListPhoneNumber]] = reduce(
249                lambda r, el: r[webex_id_to_uuid(el.owner.owner_id)].append(el) or r,
250                numbers,
251                defaultdict(list))
252            devices_by_workspace_id: dict[str, list[Device]] = reduce(
253                lambda r, el: r[el.workspace_id].append(el) or r,
254                devices,
255                defaultdict(list))
256
257            # sort workspaces by workspace location name and workspace name; workspace location can be unset
258            workspaces.sort(key=lambda ws: ('' if not ws.workspace_location_id else
259                                            workspace_locations_by_id[ws.workspace_location_id].display_name,
260                                            ws.display_name))
261            # some field lengths for nicer output
262            wsl_name_len = max(len(wsl.display_name) for wsl in ws_location_list)
263            ws_name_len = max(len(ws.display_name) for ws in workspaces)
264
265            # ... chain([1], ...) to avoid max() on empty sequence
266            pn_len = max(chain([1], (len(n.phone_number) for n in numbers if n.phone_number)))
267            ext_len = max(chain([1], (len(n.extension) for n in numbers if n.extension)))
268
269            # print workspaces with workspace locations, numbers, and devices
270            for workspace in workspaces:
271                if not workspace.workspace_location_id:
272                    wsl_name = ''
273                else:
274                    wsl_name = workspace_locations_by_id[workspace.workspace_location_id].display_name
275                print(f'workspace location "{wsl_name:{wsl_name_len}}", '
276                      f'workspace "{workspace.display_name:{ws_name_len}}"')
277
278                # are there any numbers in that workspace?
279                numbers = numbers_by_workspace_uuid.get(webex_id_to_uuid(workspace.workspace_id))
280                if numbers:
281                    for number in numbers:
282                        print(f'  number: {number.phone_number or "-" * pn_len:{pn_len}}/'
283                              f'{number.extension or "-" * ext_len:{ext_len}}')
284                devices = devices_by_workspace_id.get(workspace.workspace_id)
285                if devices:
286                    for device in devices:
287                        print(f'  device: {device.display_name}')
288
289            if operation == 'show':
290                # we are done here
291                return 0
292
293            # now we want to downgrade (disable calling) on all workspaces
294            print()
295            print('Starting downgrade')
296            results = await asyncio.gather(*[downgrade_workspace(ws) for ws in workspaces], return_exceptions=True)
297
298            # print errors ... if any
299            for ws, result in zip(workspaces, results):
300                ws: Workspace
301                if isinstance(result, Exception):
302                    print(f'Failed to downgrade "{ws.display_name:{ws_name_len}}": {result}', file=sys.stderr)
303
304            if any(isinstance(r, Exception) for r in results):
305                return 1
306            return 0
307
308    return asyncio.run(as_main())
309
310
311if __name__ == '__main__':
312    root_logger = logging.getLogger()
313    h = logging.StreamHandler(stream=sys.stderr)
314    h.setLevel(logging.INFO)
315    root_logger.setLevel(logging.INFO)
316    root_logger.addHandler(h)
317
318    # log REST API interactions to file
319    file_fmt = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s')
320    file_fmt.converter = time.gmtime
321
322    rest_log_name = join(getcwd(), f'{splitext(basename(__file__))[0]}.log')
323    rest_log_handler = logging.FileHandler(rest_log_name, mode='w')
324    rest_log_handler.setLevel(logging.DEBUG)
325    rest_log_handler.setFormatter(file_fmt)
326    rest_logger = logging.getLogger('wxc_sdk.as_rest')
327    rest_logger.setLevel(logging.DEBUG)
328    rest_logger.addHandler(rest_log_handler)
329
330    exit(main())

Logout users by selectively revoking authorizations

Selectively revoke authorizations.

usage: logout_users.py [-h] [--appname APPNAME] [--test] email

CLI tool to logout users by revoking user authorizations

positional arguments:
  email              single email or path to file w/ email addresses (one email address per
                     line). "all" can be used to print authorizations for all users. "all"
                     cannot be combined with other parameters and no authorizations will be
                     revoked in this case."

options:
  -h, --help         show this help message and exit
  --appname APPNAME  regular expression matching authorization application names. When missing
                     authorizations for all client ids defined in the script are revoked
  --test             test run only

Source: logout_users.py

  1#!/usr/bin/env python
  2"""
  3    usage: logout_users.py [-h] [--appname APPNAME] [--test] email
  4
  5    CLI tool to logout users by revoking user authorizations
  6
  7    positional arguments:
  8      email              single email or path to file w/ email addresses (one email address per line). "all" can be
  9                         used to print authorizations for all users. "all" cannot be combined with other parameters
 10                         and no authorizations will be revoked in this case."
 11
 12    optional arguments:
 13      -h, --help         show this help message and exit
 14      --appname APPNAME  regular expression matching authorization application names. When missing authorizations for
 15                         all client ids defined in the script are revoked
 16      --test             test run only
 17"""
 18import asyncio
 19import logging
 20import re
 21import sys
 22import time
 23from argparse import ArgumentParser
 24from itertools import chain
 25from operator import attrgetter
 26from os import getcwd, getenv
 27from os.path import join, splitext, basename, isfile
 28from typing import Optional
 29
 30from dotenv import load_dotenv
 31from yaml import safe_dump, safe_load
 32
 33from wxc_sdk.as_api import AsWebexSimpleApi
 34from wxc_sdk.authorizations import Authorization, AuthorizationType
 35from wxc_sdk.integration import Integration
 36from wxc_sdk.people import Person
 37from wxc_sdk.tokens import Tokens
 38
 39# list of client ids to revoke authorizations for
 40# add more client ids as needed
 41CLIENT_IDS = {
 42    # Webex Web Client
 43    'C64ab04639eefee4798f58e7bc3fe01d47161be0d97ff0d31e040a6ffe66d7f0a',
 44    # Webex Teams Desktop Client for Mac
 45    'Ccb2581f071a0714c8ab7d4777f70ebed26f1ef5f3261597f00afbb3a53c1ad88',
 46    # add more client ids as required, call the script with "all" parameter to identify more client ids
 47}
 48
 49
 50def yml_path() -> str:
 51    """
 52    Get filename for YML file to cache access and refresh token
 53    """
 54    return f'{splitext(basename(__file__))[0]}.yml'
 55
 56
 57def env_path() -> str:
 58    """
 59    Get path to .env file to read service app settings from
 60    """
 61    return f'{splitext(basename(__file__))[0]}.env'
 62
 63
 64def read_tokens_from_file() -> Optional[Tokens]:
 65    """
 66    Get service app tokens from cache file, return None if cache does not exist or read fails
 67    """
 68    path = yml_path()
 69    if not isfile(path):
 70        return None
 71    try:
 72        with open(path, mode='r') as f:
 73            data = safe_load(f)
 74        tokens = Tokens.model_validate(data)
 75    except Exception:
 76        return None
 77    return tokens
 78
 79
 80def write_tokens_to_file(tokens: Tokens):
 81    """
 82    Write tokens to cache
 83    """
 84    with open(yml_path(), mode='w') as f:
 85        safe_dump(tokens.model_dump(exclude_none=True), f)
 86
 87
 88def get_access_token() -> Tokens:
 89    """
 90    Get a new access token using refresh token, service app client id, service app client secret
 91    """
 92    tokens = Tokens(refresh_token=getenv('SERVICE_APP_REFRESH_TOKEN'))
 93    integration = Integration(client_id=getenv('SERVICE_APP_CLIENT_ID'),
 94                              client_secret=getenv('SERVICE_APP_CLIENT_SECRET'),
 95                              scopes=[], redirect_url=None)
 96    integration.refresh(tokens=tokens)
 97    write_tokens_to_file(tokens)
 98    return tokens
 99
100
101def get_tokens() -> Optional[Tokens]:
102    """
103    Get tokens from cache or create new access token using service app credentials
104    """
105    # try to read from file
106    tokens = read_tokens_from_file()
107    # .. or create new access token using refresh token
108    if tokens is None:
109        tokens = get_access_token()
110    if tokens.remaining < 24 * 60 * 60:
111        tokens = get_access_token()
112    return tokens
113
114
115def auth_str(auth: Authorization) -> str:
116    return f'{auth.type:7}, {auth.client_id} - {auth.application_name}'
117
118
119async def main() -> int:
120    parser = ArgumentParser(prog=basename(__file__),
121                            description='CLI tool to logout users by revoking user authorizations')
122    parser.add_argument('email',
123                        help='single email or path to file w/ email addresses (one email address per line). "all" can '
124                             'be used to print authorizations for all users. "all" cannot be combined with other '
125                             'parameters and no authorizations will be revoked in this case."')
126    parser.add_argument('--appname',
127                        type=str,
128                        help='regular expression matching authorization application names. '
129                             'When missing authorizations for all client ids defined in the '
130                             'script are revoked')
131    parser.add_argument('--test', action='store_true', help='test run only')
132    args = parser.parse_args()
133    email = args.email
134    test_run = args.test
135    appname = args.appname
136
137    if appname:
138        try:
139            appname_re = re.compile(appname)
140        except re.error as e:
141            print(f'invalid regular expression for --appname: {e}')
142            return 1
143
144    async def work_on_one_email(api: AsWebexSimpleApi, user_email: str) -> int:
145        """
146        Work on authorizations for one email
147        """
148        print(f'Getting authorizations for {user_email}')
149        auths = await api.authorizations.list(person_email=user_email)
150
151        auths.sort(key=lambda a: f'{a.application_name}{a.type}')
152
153        # determine set of authorization ids to revoke
154        if appname:
155            auths_to_delete = set(a.id for a in auths
156                                  if appname_re.match(a.application_name))
157        else:
158            auths_to_delete = set(a.id for a in auths
159                                  if a.client_id in CLIENT_IDS)
160        if auths:
161            # show all authorizations and indicate which will be revoked
162            print('\n'.join(f'{user_email}: {auth_str(auth)} '
163                            f'{"--> revoke" if auth.id in auths_to_delete else ""}'
164                            for auth in auths))
165
166        if not auths:
167            print(f'{user_email}: no auths found')
168            return 0
169        if not auths_to_delete:
170            print(f'{user_email}: no auths to revoke')
171            return 0
172        if test_run:
173            print(f'{user_email}: testrun, not revoking any auths')
174            return 0
175        results = await asyncio.gather(*[api.authorizations.delete(authorization_id=a_id)
176                                         for a_id in auths_to_delete],
177                                       return_exceptions=True)
178        err = False
179        for r, auth_id in zip(results, auths_to_delete):
180            if not isinstance(r, Exception):
181                continue
182            auth = next((a for a in auths if a.id == auth_id))
183            if auth.type == AuthorizationType.refresh:
184                # ignore errors on revoking access tokens (race condition)
185                continue
186            print(f'{user_email}: {auth_str(auth)}, error revoking auth: {r}')
187            err = True
188        if err:
189            return 1
190        return 0
191
192    # get tokens; as an alternative you can just get a developer token from developer.webex.com and use:
193    #   tokens = '<developer token from developer.webex.com>'
194    load_dotenv(dotenv_path=env_path())
195    err = ''
196    tokens = None
197    try:
198        tokens = get_tokens()
199    except Exception as e:
200        err = f'{e}'
201    if not tokens:
202        print(f'failed to obtain access tokens: {err}', file=sys.stderr)
203        return 1
204
205    async with AsWebexSimpleApi(tokens=tokens) as api:
206        if email == 'all':
207            print('Getting users...')
208            users = await api.people.list()
209            print(f'Getting authorizations for {len(users)} users...')
210            auth_lists = await asyncio.gather(*[api.authorizations.list(person_id=user.person_id)
211                                                for user in users],
212                                              return_exceptions=True)
213            err = False
214            for user, error in zip(users, auth_lists):
215                user: Person
216                if isinstance(error, Exception):
217                    print(f'{user.emails}: failed to get authorizations: {error}')
218                    err = True
219            if err:
220                return 1
221            auth_dict: dict[str, list[Authorization]] = {person.person_id: auth_list
222                                                         for person, auth_list in zip(users, auth_lists)
223                                                         if auth_list}
224            print('\n'.join(chain.from_iterable((f'{user.emails[0]}: {auth_str(auth)}'
225                                                 for auth in auth_dict.get(user.person_id, []))
226                                                for user in sorted(users, key=attrgetter('display_name')))))
227
228            clients = set(auth_str(auth) for auth in chain.from_iterable(auth_lists))
229            print()
230            print('tokens and clients:')
231            print('\n'.join(sorted(clients)))
232            return 0
233        elif isfile(email):
234            # read email addresses from file, one email address per line
235            with open(email, mode='r') as f:
236                emails = list(sorted(set(s_line for line in f if (s_line := line.strip()))))
237        else:
238            emails = [email]
239
240        if not emails:
241            print('Nothing to do')
242            return 0
243
244        # act on all emails concurrently
245        results = await asyncio.gather(*[work_on_one_email(api, e)
246                                         for e in emails],
247                                       return_exceptions=True)
248    err = next((r for r in results if isinstance(r, Exception)), None)
249    if err:
250        raise err
251    return max(results)
252
253
254if __name__ == '__main__':
255    root_logger = logging.getLogger()
256    h = logging.StreamHandler(stream=sys.stderr)
257    h.setLevel(logging.INFO)
258    root_logger.setLevel(logging.INFO)
259    root_logger.addHandler(h)
260
261    # log REST API interactions to file
262    file_fmt = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s')
263    file_fmt.converter = time.gmtime
264
265    rest_log_name = join(getcwd(), f'{splitext(basename(__file__))[0]}.log')
266    rest_log_handler = logging.FileHandler(rest_log_name, mode='w')
267    rest_log_handler.setLevel(logging.DEBUG)
268    rest_log_handler.setFormatter(file_fmt)
269    rest_logger = logging.getLogger('wxc_sdk.as_rest')
270    rest_logger.setLevel(logging.DEBUG)
271    rest_logger.addHandler(rest_log_handler)
272
273    exit(asyncio.run(main()))

Leave spaces with no activity in the last n days

Leave spaces w/o recent activity.

usage: leave_spaces.py [-h] [--days DAYS] [--token TOKEN] [--no_test] [--no_messages]
                       [--keep KEEP]

leave spaces with no activity

options:
  -h, --help            show this help message and exit
  --days DAYS, -d DAYS  days since last activity; default: 1095
  --token TOKEN         Personal access token to use. If not provided script will try to read
                        token from WEBEX_ACCESS_TOKEN environment variable.
  --no_test             Don't test; actually leave the spaces
  --no_messages         Only leave spaces that have no messages
  --keep KEEP, -k KEEP  file with list of spaces to keep

Source: leave_spaces.py

  1#!/usr/bin/env python
  2import asyncio
  3import logging
  4import os
  5import sys
  6from argparse import ArgumentParser
  7from collections.abc import Iterable
  8from datetime import datetime, timedelta
  9from typing import Optional
 10
 11from dateutil import tz
 12from dotenv import load_dotenv
 13
 14from wxc_sdk.as_api import AsWebexSimpleApi
 15from wxc_sdk.as_rest import AsRestError
 16from wxc_sdk.common import RoomType
 17from wxc_sdk.messages import Message
 18from wxc_sdk.rooms import Room
 19from wxc_sdk.teams import Team
 20
 21
 22async def last_n_messages(api: AsWebexSimpleApi, space: Room, n: int = 10) -> list[Message]:
 23    """
 24    Get last n messages in a space
 25    """
 26    messages = []
 27    if not n:
 28        return messages
 29    async for message in api.messages.list_gen(room_id=space.id, max=min(n, 1000)):
 30        messages.append(message)
 31        n -= 1
 32        if not n:
 33            break
 34    return messages
 35
 36
 37async def latest_message_in_space(api: AsWebexSimpleApi, space: Room) -> Optional[Message]:
 38    """
 39    Get latest message in a space
 40    """
 41    last_messages = await last_n_messages(api, space, 1)
 42    if not last_messages:
 43        return None
 44    return last_messages[0]
 45
 46
 47async def verify_leave_space(api: AsWebexSimpleApi, space: Room, cutoff: datetime) -> bool:
 48    """
 49    Get latest message in a space and check if it's older than cutoff
 50    """
 51    latest = await latest_message_in_space(api, space)
 52    if not latest:
 53        return True
 54    return latest.created <= cutoff
 55
 56
 57async def leave_spaces(api: AsWebexSimpleApi, spaces: Iterable[Room]):
 58    """
 59    Leave some spaces
 60    """
 61    me = await api.people.me()
 62    person_id = me.person_id
 63
 64    async def leave_space(space: Room):
 65        # get membership to delete
 66        try:
 67            memberships = await api.membership.list(room_id=space.id, person_id=person_id)
 68            if not memberships:
 69                print(f'No membership in space "{space.title}", skipping', file=sys.stderr)
 70                return
 71            # delete membership
 72            print(f'Leaving space "{space.title}"...')
 73            await api.membership.delete(memberships[0].id)
 74            print(f'Left space "{space.title}"')
 75        except AsRestError as e:
 76            print(f'Error leaving space "{space.title}": {e}', file=sys.stderr)
 77        return
 78
 79    await asyncio.gather(*[leave_space(space) for space in spaces])
 80
 81
 82async def as_main():
 83    # parse args
 84    parser = ArgumentParser(description='leave spaces with no activity')
 85    parser.add_argument('--days', '-d', type=int, required=False, default=3 * 365,
 86                        help=f'days since last activity; default: {3 * 365}')
 87    parser.add_argument('--token', type=str, required=False,
 88                        help='Personal access token to use. If not provided script will try to read token from '
 89                             'WEBEX_ACCESS_TOKEN environment variable.')
 90    parser.add_argument('--no_test', action='store_true', required=False,
 91                        help='Don\'t test; actually leave the spaces')
 92    parser.add_argument('--no_messages', action='store_true', required=False,
 93                        help='Only leave spaces that have no messages')
 94    parser.add_argument('--keep', '-k', type=str, required=False,
 95                        help='file with list of spaces to keep')
 96    args = parser.parse_args()
 97
 98    load_dotenv()
 99    token = args.token or os.getenv('WEBEX_ACCESS_TOKEN')
100    if not token:
101        print('No token provided and WEBEX_ACCESS_TOKEN not set in environment', file=sys.stderr)
102        exit(1)
103    cutoff = datetime.now(tz=tz.UTC) - timedelta(days=args.days)
104    if args.keep:
105        try:
106            with open(args.keep, mode='r') as f:
107                keep = set(l.strip() for l in f if l)
108        except FileNotFoundError:
109            print(f'file "{args.keep}" not found', file=sys.stderr)
110            exit(1)
111    else:
112        keep = set()
113    async with AsWebexSimpleApi(tokens=token, concurrent_requests=100) as api:
114        # check token
115        try:
116            await api.people.me()
117        except AsRestError as e:
118            if e.status == 401:
119                print(f'Token seems to be invalid: {e}', file=sys.stderr)
120                exit(1)
121            raise
122
123        print('Listing spaces and teams...')
124        spaces, teams_list = await asyncio.gather(api.rooms.list(max=1000), api.teams.list())
125        # we can't leave direct spaces anyway; so ignore them from the start
126        spaces = [space for space in spaces if space.type != RoomType.direct]
127        print(f'Found {len(spaces)} spaces')
128        print(f'Found {len(teams_list)} teams')
129        teams = {team.id: team for team in teams_list}
130
131        # identify spaces to leave based on last activity
132        leave = [space for space in spaces if space.last_activity and space.last_activity <= cutoff]
133
134        # sometimes the last_activity information seems to be "off" try to get the latest message for each space to
135        # verify latest activity
136        print(f'Getting latest message for {len(leave)} spaces...')
137        latest_messages = await asyncio.gather(*[latest_message_in_space(api, space) for space in leave])
138        validated_leave: list[tuple[Room, Optional[datetime]]] = []
139        for space, latest_message in zip(leave, latest_messages):
140            space: Room
141            latest_message: Message
142            # don't leave general spaces of Teams
143            # A general space is a space that has the same name as the Team it belongs to
144            team: Team
145            if space.team_id and (team := teams.get(space.team_id, None)) and space.title == team.name:
146                print(f'Don\'t leave general space "{space.title}" of Team "{team.name}"')
147                continue
148
149            # don't leave spaces in keep file
150            if space.title.strip() in keep:
151                print(f'Don\'t leave space "{space.title}", found space name in keep file')
152                continue
153
154            # if only spaces with no messages should be considered and we have a message in the space then don't leave
155            if args.no_messages and latest_message is not None:
156                print(f'Space "{space.title}" has messages, latest is {latest_message.created:%Y.%m.%d %H:%M:%S}, '
157                      f'last activity is {space.last_activity:%Y.%m.%d %H:%M:%S} - not leaving')
158                continue
159
160            # if no latest message or latest message is older than cutoff, consider leaving
161            if latest_message is None or latest_message.created <= cutoff:
162                latest_messages: Message
163                validated_leave.append((space, latest_message and latest_message.created))
164                continue
165            print(f'Latest message in "{space.title}" is {latest_message.created:%Y.%m.%d %H:%M:%S}, '
166                  f'last activity is {space.last_activity:%Y.%m.%d %H:%M:%S} - not leaving')
167        print()
168        print(f'Found {len(validated_leave)} spaces to leave:')
169
170        # sort spaces by latest activity or latest message
171        validated_leave.sort(key=lambda x: max(x[0].last_activity, x[1]) if x[1] else x[0].last_activity,
172                             reverse=False)
173
174        for space, latest in validated_leave:
175            print(f'Leave "{space.title}"')
176            print(f'   last activity {space.last_activity:%Y.%m.%d %H:%M:%S}, latest message '
177                  f'{f"{latest:%Y.%m.%d %H:%M:%S}" if latest else "none"}')
178
179        if args.no_test:
180            # actually try to leave the spaces
181            await leave_spaces(api, (space for space, _ in validated_leave))
182
183
184if __name__ == '__main__':
185    logging.basicConfig(level=logging.INFO)
186    asyncio.run(as_main())

Provision location level access codes from a CSV file

Provision location level access codes from a CSV file

usage: access_codes.py [-h] [--token TOKEN] csv_file

Provision location level access codes from a CSV file

positional arguments:
  csv_file       CSV file with access codes

options:
  -h, --help     show this help message and exit
  --token TOKEN  API token

Source: access_codes.py

  1#!/usr/bin/env python
  2"""
  3Provision location level access codes from a CSV file
  4the CSV file should have the following columns:
  5- location: location name
  6- code: the access code
  7- description: a description of the access code
  8- operation: one of 'add', 'delete', 'update'
  9
 10usage: access_codes.py [-h] [--token TOKEN] csv_file
 11
 12Provision location level access codes from a CSV file
 13
 14positional arguments:
 15  csv_file       CSV file with access codes
 16
 17options:
 18  -h, --help     show this help message and exit
 19  --token TOKEN  API token
 20
 21
 22"""
 23import asyncio
 24import csv
 25import logging
 26import sys
 27from argparse import ArgumentParser
 28from collections import defaultdict
 29from functools import reduce
 30from os.path import basename, isfile
 31from typing import Literal
 32
 33from pydantic import BaseModel, TypeAdapter
 34
 35from wxc_sdk.as_api import AsWebexSimpleApi
 36from wxc_sdk.common import AuthCode
 37from wxc_sdk.telephony.location import TelephonyLocation
 38
 39
 40class CSVOperation(BaseModel):
 41    location: str
 42    code: str
 43    description: str
 44    operation: Literal['add', 'delete']
 45
 46
 47async def process_operations(operations: list[CSVOperation], token: str):
 48    """
 49    Process the operations from the CSV file in parallel
 50    """
 51    async def process_one_location(location: str, operations: list[CSVOperation]):
 52        """
 53        process operations for one location
 54        """
 55        # find the location
 56        loc = locations.get(location)
 57        if loc is None:
 58            print(f'Location {location} not found', sys.stderr)
 59            return
 60
 61        # get existing codes in location
 62        ac_codes: dict[str, AuthCode] = {ac.code: ac
 63                                         for ac in await api.telephony.access_codes.read(location_id=loc.location_id)}
 64
 65        tasks = []
 66        delete_operations = [operation
 67                             for operation in operations
 68                             if operation.operation == 'delete']
 69        non_existing = [op
 70                        for op in delete_operations
 71                        if op.code not in ac_codes]
 72        if non_existing:
 73            print(f'Location {location}: access codes not found: {", ".join(op.code for op in non_existing)}',
 74                  file=sys.stderr)
 75        to_delete = [ac
 76                     for ac in delete_operations
 77                     if ac.code in ac_codes]
 78        if to_delete:
 79            tasks.append(api.telephony.access_codes.delete_codes(location_id=loc.location_id,
 80                                                                 access_codes=[op.code for op in to_delete]))
 81
 82        add_operations = [operation
 83                          for operation in operations
 84                          if operation.operation == 'add']
 85        existing = [op for op in add_operations if op.code in ac_codes]
 86        if existing:
 87            print(f'Location {location}: access codes already exist: {", ".join(op.code for op in existing)}',
 88                  file=sys.stderr)
 89        to_add = [ac for ac in add_operations if ac.code not in ac_codes]
 90        if to_add:
 91            tasks.append(api.telephony.access_codes.create(location_id=loc.location_id,
 92                                                           access_codes=[AuthCode(code=op.code,
 93                                                                                  description=op.description)
 94                                                                         for op in to_add]))
 95        if tasks:
 96            await asyncio.gather(*tasks)
 97
 98    async with AsWebexSimpleApi(tokens=token) as api:
 99        # get locations
100        locations: dict[str, TelephonyLocation] = {loc.name: loc for loc in await api.telephony.locations.list()}
101
102        # group operations by location
103        operations_by_location: dict[str, list[CSVOperation]] = reduce(
104            lambda acc, op: acc[op.location].append(op) or acc, operations,
105            defaultdict(list))
106
107        # process all locations in parallel
108        await asyncio.gather(*[process_one_location(loc, ops) for loc, ops in operations_by_location.items()])
109
110
111def main():
112    parser = ArgumentParser(prog=basename(__file__),
113                            description='Provision location level access codes from a CSV file')
114    parser.add_argument('csv_file', help='CSV file with access codes')
115    parser.add_argument('--token', help='API token')
116    args = parser.parse_args()
117    csv_file = args.csv_file
118    if not isfile(csv_file):
119        parser.error(f'File {csv_file} not found')
120    # read CSV file
121    with open(csv_file) as f:
122        reader = csv.DictReader(f)
123        data = list(reader)
124
125    # validate the date from the CSV file
126    csv_operations = TypeAdapter(list[CSVOperation]).validate_python(data)
127
128    asyncio.run(process_operations(csv_operations, args.token))
129
130
131if __name__ == '__main__':
132    logging.basicConfig(level=logging.DEBUG)
133    main()

Bulk assign/unassign agents to/from call queues

Bulk assign/unassign agents to/from call queues

usage: queue_agents.py [-h] (--add | --remove) --queues QUEUES --agent AGENT [--token TOKEN]
                       [--debug] [--har] [--dry-run]

Bulk manage agents in call queues

options:
  -h, --help       show this help message and exit
  --add            Add agent(s) to specified queues
  --remove         Remove agent(s) from specified queues
  --queues QUEUES  Text file with list of call queue names (one per line). Each line should
                   be the a location name and a queue name separated by a colon. Example:
                   "Location1:Queue1"
  --agent AGENT    Single agent email address or text file with agent email addresses (one
                   per line)
  --token TOKEN    admin access token to use. If no token is given then the script will try
                   to use service app tokens. The service app parameters are read from
                   environment variables SERVICE_APP_ID, SERvICE_APP_SECRET, and
                   SERVICE_APP_REFRESH. These parameters can also be defined in
                   "queue_agents.env" file. Service app tokens are cached in
                   "queue_agents.yml". If no access token is passed and no service app is
                   defined then the script falls back to try to read an access token from
                   environment variable WEBEX_ACCESS_TOKEN.
  --debug          Enable debug output
  --har            Enable HAR output
  --dry-run        Simulate the operation without making actual changes

Example: queue_agents.py --queues queues.txt --agent agents.txt --add

Source: queue_agents.py

  1#!/usr/bin/env python3
  2"""
  3Bulk manage agents in call queues
  4
  5usage: queue_agents.py [-h] (--add | --remove) --queues QUEUES --agent AGENT [--token TOKEN]
  6
  7Bulk manage agents in call queues
  8
  9options:
 10  -h, --help       show this help message and exit
 11  --add            Add agent(s) to specified queues
 12  --remove         Remove agent(s) from specified queues
 13  --queues QUEUES  Text file with list of call queue names (one per line). Each line should be the a
 14                   location name and a queue name separated by a colon. Example: "Location1:Queue1"
 15  --agent AGENT    Single agent email address or text file with agent email addresses (one per line)
 16  --token TOKEN    admin access token to use. If no token is given then the script will try to use
 17                   service app tokens. The service app parameters are read from environment variables
 18                   SERVICE_APP_ID, SERvICE_APP_SECRET, and SERVICE_APP_REFRESH. These parameters can
 19                   also be defined in "queue_agents.env" file. Service app tokens are cached in
 20                   "queue_agents.yml". If no access token is passed and no service app is defined then
 21                   the script falls back to try to read an access token from environment variable
 22                   WEBEX_ACCESS_TOKEN.
 23
 24Example: queue_agents.py --queues queues.txt --agent agents.txt --add
 25"""
 26import argparse
 27import asyncio
 28import logging
 29import os
 30import sys
 31from contextlib import contextmanager
 32from typing import List, Iterable, Optional
 33
 34import yaml
 35from dotenv import load_dotenv
 36
 37from wxc_sdk import Tokens
 38from wxc_sdk.as_api import AsWebexSimpleApi
 39from wxc_sdk.har_writer import HarWriter
 40from wxc_sdk.integration import Integration
 41from wxc_sdk.people import Person
 42from wxc_sdk.telephony.callqueue import CallQueue
 43from wxc_sdk.telephony.hg_and_cq import Agent
 44
 45
 46def yml_path() -> str:
 47    """
 48    Get filename for YML file to cache access and refresh token
 49    """
 50    return f'{os.path.splitext(os.path.basename(__file__))[0]}.yml'
 51
 52
 53def env_path() -> str:
 54    """
 55    Get path to .env file to read service app settings from
 56    :return:
 57    """
 58    return f'{os.path.splitext(os.path.basename(__file__))[0]}.env'
 59
 60
 61def read_tokens_from_file() -> Optional[Tokens]:
 62    """
 63    Get service app tokens from cache file, return None if cache does not exist
 64    """
 65    path = yml_path()
 66    if not os.path.isfile(path):
 67        return None
 68    try:
 69        with open(path, mode='r') as f:
 70            data = yaml.safe_load(f)
 71        tokens = Tokens.model_validate(data)
 72    except Exception:
 73        return None
 74    return tokens
 75
 76
 77def write_tokens_to_file(tokens: Tokens):
 78    """
 79    Write tokens to cache
 80    """
 81    with open(yml_path(), mode='w') as f:
 82        yaml.safe_dump(tokens.model_dump(exclude_none=True), f)
 83
 84
 85def get_access_token() -> Optional[Tokens]:
 86    """
 87    Get a new access token using refresh token, service app client id, service app client secret
 88    """
 89    env_vars = ('SERVICE_APP_ID', 'SERVICE_APP_SECRET', 'SERVICE_APP_REFRESH')
 90    app_id, app_secret, app_refresh = (os.getenv(var) for var in env_vars)
 91    if not all((app_id, app_secret, app_refresh)):
 92        return None
 93    tokens = Tokens(refresh_token=app_refresh)
 94    integration = Integration(client_id=app_id,
 95                              client_secret=app_secret,
 96                              scopes=[], redirect_url=None)
 97    integration.refresh(tokens=tokens)
 98    write_tokens_to_file(tokens)
 99    return tokens
100
101
102def get_tokens() -> Optional[Tokens]:
103    """
104    Get tokens from cache or create new access token using service app credentials
105    """
106    # try to read from file
107    tokens = read_tokens_from_file()
108    # .. or create new access token using refresh token
109    if tokens is None:
110        tokens = get_access_token()
111        if tokens is None:
112            return None
113    if tokens.remaining < 24 * 60 * 60:
114        tokens = get_access_token()
115    return tokens
116
117
118def read_file_lines(filename: str) -> List[str]:
119    """
120    Read lines from a file, stripping whitespace and removing empty lines.
121
122    Args:
123        filename (str): Path to the input file
124
125    Returns:
126        List[str]: Cleaned list of lines from the file
127
128    Raises:
129        FileNotFoundError: If the specified file does not exist
130        PermissionError: If there are permission issues reading the file
131    """
132    try:
133        with open(filename, 'r') as f:
134            return [line.strip() for line in f if line.strip()]
135    except FileNotFoundError:
136        print(f"Error: File '{filename}' not found.", file=sys.stderr)
137        sys.exit(1)
138    except PermissionError:
139        print(f"Error: Permission denied reading file '{filename}'.", file=sys.stderr)
140        sys.exit(1)
141
142
143async def process_one_queue(*, api: AsWebexSimpleApi, queue: CallQueue, agents: list[Person], action: str,
144                            dry_run: bool = True):
145    """
146    Process adding or removing agents from a single call queue.
147    """
148    # get agents
149    details = await api.telephony.callqueue.details(location_id=queue.location_id, queue_id=queue.id)
150
151    agent: Agent
152    agents_in_queue = set(agent.agent_id for agent in details.agents)
153    agent_ids = set(person.person_id for person in agents)
154    if action == 'add':
155        agents_to_add = agent_ids - agents_in_queue
156        if not agents_to_add:
157            print(f"All agents are already in queue {queue.name} in location {queue.location_name}. Skipping.")
158            return
159        agent_str = ', '.join(sorted(f'{person.display_name}({person.emails[0]})'
160                                     for person in agents if person.person_id in agents_to_add))
161        print(f"Adding agents to queue {queue.name} in location {queue.location_name}: {agent_str}")
162        details.agents.extend([Agent(agent_id=agent_id) for agent_id in agents_to_add])
163    else:
164        agents_to_remove = agents_in_queue & agent_ids
165        if not agents_to_remove:
166            print(f"No agents to remove from queue {queue.name} in location {queue.location_name}. Skipping.")
167            return
168        agent_str = ', '.join(sorted(f'{person.display_name}({person.emails[0]})'
169                                     for person in agents if person.person_id in agents_to_remove))
170        print(f"Removing agents from queue {queue.name} in location {queue.location_name}: {agent_str}")
171        details.agents = [agent for agent in details.agents if agent.agent_id not in agents_to_remove]
172    update = CallQueue(agents=details.agents)
173    if not dry_run:
174        await api.telephony.callqueue.update(location_id=queue.location_id, queue_id=queue.id, update=update)
175
176
177async def validate_queues(api: AsWebexSimpleApi, queues: Iterable[str]) -> list[CallQueue]:
178    """
179    Validate queue names and return a list of CallQueue objects
180    """
181    # validate queue names
182    existing_queues = {f'{queue.location_name}:{queue.name}': queue
183                       for queue in await api.telephony.callqueue.list()}
184    validated_queues = []
185    for queue in queues:
186        if queue not in existing_queues:
187            print(f"Queue '{queue}' does not exist. Skipping.", file=sys.stderr)
188        else:
189            validated_queues.append(existing_queues[queue])
190
191    return validated_queues
192
193
194async def validate_users(api: AsWebexSimpleApi, users: Iterable[str]) -> list[Person]:
195    """
196    Validate user emails and return a list of Person objects
197    """
198    existing_users = {user.emails[0].lower(): user for user in await api.people.list()}
199    validated_users = []
200    for user in users:
201        if user.lower() not in existing_users:
202            print(f"User '{user}' does not exist. Skipping.", file=sys.stderr)
203        else:
204            validated_users.append(existing_users[user.lower()])
205
206    return validated_users
207
208
209def main():
210    """
211    Main CLI script entry point for managing call queue agents.
212    """
213    parser = argparse.ArgumentParser(
214        description='Bulk manage agents in call queues',
215        epilog='Example: %(prog)s --queues queues.txt --agent agents.txt --add'
216    )
217
218    # Mutually exclusive group for add/remove actions
219    action_group = parser.add_mutually_exclusive_group(required=True)
220    action_group.add_argument('--add', action='store_const', const='add', dest='action',
221                              help='Add agent(s) to specified queues')
222    action_group.add_argument('--remove', action='store_const', const='remove', dest='action',
223                              help='Remove agent(s) from specified queues')
224
225    # Input source arguments
226    parser.add_argument('--queues', required=True,
227                        help='Text file with list of call queue names (one per line). Each line should be the a '
228                             'location name and a queue name separated by a colon. Example: "Location1:Queue1"')
229    parser.add_argument('--agent', required=True,
230                        help='Single agent email address or text file with agent email addresses (one per line)')
231    parser.add_argument('--token', type=str, required=False,
232                        help=f'admin access token to use. If no token is given then the script will try to use '
233                             f'service app tokens. The service app parameters are read from environment variables '
234                             f'SERVICE_APP_ID, SERvICE_APP_SECRET, and SERVICE_APP_REFRESH. These parameters can also '
235                             f'be defined in "{os.path.splitext(os.path.basename(__file__))[0]}.env" file. Service '
236                             f'app tokens are cached in "'
237                             f'{os.path.splitext(os.path.basename(__file__))[0]}.yml". If no access token is passed '
238                             f'and no service app '
239                             f'is defined then the script falls back to try to read an access token from environment '
240                             f'variable WEBEX_ACCESS_TOKEN.')
241
242    # Debug and HAR output arguments
243    parser.add_argument('--debug', action='store_true', help='Enable debug output')
244    parser.add_argument('--har', action='store_true', help='Enable HAR output')
245
246    # fry run option
247    parser.add_argument('--dry-run', action='store_true',
248                        help='Simulate the operation without making actual changes')
249
250    # Parse arguments
251    args = parser.parse_args()
252
253    # Get access token
254    token = args.token
255    load_dotenv(os.path.join(os.getcwd(),
256                             f'{os.path.splitext(os.path.basename(__file__))[0]}.env'))
257
258    token = token or (tokens := get_tokens()) and tokens.access_token
259
260    # Read queues from file
261    queues = read_file_lines(args.queues)
262
263    # Determine if agent is a file or a single agent email
264    try:
265        agents = read_file_lines(args.agent) if os.path.isfile(args.agent) else [args.agent]
266    except FileNotFoundError:
267        agents = [args.agent]
268
269    if args.debug:
270        logging.basicConfig(level=logging.DEBUG)
271
272    async def as_main():
273        """
274        Async main entry point
275        """
276        @contextmanager
277        def har_writer():
278            """
279            optional context manager to write HAR file
280            """
281            if args.har:
282                with HarWriter(f'{os.path.splitext(os.path.basename(__file__))[0]}.har', api):
283                    yield None
284            else:
285                yield None
286
287        async with (AsWebexSimpleApi(tokens=token) as api):
288            with har_writer():
289                # validate queues and agents
290                validated_queues, validated_agents = await asyncio.gather(
291                    validate_queues(api, queues),
292                    validate_users(api, agents))
293                if not validated_queues:
294                    print("No valid queues found. Exiting.", file=sys.stderr)
295                    sys.exit(1)
296                if not validated_agents:
297                    print("No valid agents found. Exiting.", file=sys.stderr)
298                    sys.exit(1)
299                validated_queues: List[CallQueue]
300                validated_agents: List[Person]
301
302                # process all queues in parallel
303                await asyncio.gather(
304                    *[process_one_queue(api=api, queue=queue, agents=validated_agents, action=args.action,
305                                        dry_run=args.dry_run)
306                      for queue in validated_queues],
307                    return_exceptions=False)
308            # with
309        return
310
311    asyncio.run(as_main())
312
313    print(f"Completed {args.action} operation for {len(agents)} agent(s) across {len(queues)} queue(s).")
314
315
316if __name__ == '__main__':
317    main()

Bulk add phone numbers to locations

Bulk add TNs to Webex Calling locations

usage: add_numbers.py [-h] [--dry-run] [--verbose] [--log-file LOG_FILE] [--token TOKEN]
                      [--inactive]
                      file

Add TNs to Webex Calling locations

positional arguments:
  file                 CSV file with location names and TNs

optional arguments:
  -h, --help           show this help message and exit
  --dry-run            Do not make any changes
  --verbose            Print debug information
  --log-file LOG_FILE  Log file. If extension is .har, log in HAR format
  --token TOKEN        Access token can be provided using --token argument, set in
                       WEBEX_ACCESS_TOKEN environment variable or can be a service app token. For
                       the latter set environment variables ('SERVICE_APP_REFRESH_TOKEN',
                       'SERVICE_APP_CLIENT_ID', 'SERVICE_APP_CLIENT_SECRET'). Environment variables
                       can also be set in add_numbers.env
  --inactive           Add TNs as inactive

Example: add_numbers.py add_numbers.csv --log-file add_numbers.har --dry-run

Source: add_numbers.py

  1#!/usr/bin/env python
  2"""
  3Add TNs to a locations.
  4usage: add_numbers.py [-h] [--dry-run] [--verbose] [--log-file LOG_FILE] [--token TOKEN]
  5                      [--inactive]
  6                      file
  7
  8Add TNs to Webex Calling locations
  9
 10positional arguments:
 11  file                 CSV file with location names and TNs
 12
 13optional arguments:
 14  -h, --help           show this help message and exit
 15  --dry-run            Do not make any changes
 16  --verbose            Print debug information
 17  --log-file LOG_FILE  Log file. If extension is .har, log in HAR format
 18  --token TOKEN        Access token can be provided using --token argument, set in
 19                       WEBEX_ACCESS_TOKEN environment variable or can be a service app token. For
 20                       the latter set environment variables ('SERVICE_APP_REFRESH_TOKEN',
 21                       'SERVICE_APP_CLIENT_ID', 'SERVICE_APP_CLIENT_SECRET'). Environment variables
 22                       can also be set in add_numbers.env
 23  --inactive           Add TNs as inactive
 24
 25Example: add_numbers.py add_numbers.csv --log-file add_numbers.har --dry-run
 26
 27"""
 28import argparse
 29import asyncio
 30import csv
 31import logging
 32import os
 33import sys
 34from argparse import Namespace
 35from collections import defaultdict, Counter
 36from contextlib import contextmanager
 37from itertools import chain
 38from typing import Optional
 39
 40from dotenv import load_dotenv
 41
 42from examples.service_app import SERVICE_APP_ENVS, env_path, get_tokens
 43from wxc_sdk.as_api import AsWebexSimpleApi
 44from wxc_sdk.common import NumberState
 45from wxc_sdk.har_writer import HarWriter
 46from wxc_sdk.tokens import Tokens
 47
 48BATCH_SIZE = 10
 49
 50
 51@contextmanager
 52def setup_logging(args: Namespace, api: AsWebexSimpleApi):
 53    """
 54    Set up logging
 55    """
 56
 57    @contextmanager
 58    def file_handler(log_file: str):
 59        if not log_file:
 60            yield
 61        else:
 62            # log to file or to HAR
 63            if os.path.splitext(log_file)[-1].lower() == '.har':
 64                with HarWriter(api=api, path=log_file):
 65                    yield
 66            else:
 67                f_handler = logging.FileHandler(args.log_file)
 68                f_handler.setLevel(logging.DEBUG)
 69                f_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
 70                logging.getLogger().addHandler(f_handler)
 71                yield
 72        return
 73
 74    logging.getLogger().setLevel(logging.DEBUG)
 75    # create a console logging handler
 76    console_handler = logging.StreamHandler()
 77    console_handler.setLevel(logging.DEBUG if args.verbose else logging.INFO)
 78    # console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
 79    logging.getLogger().addHandler(console_handler)
 80    with file_handler(args.log_file):
 81        yield
 82
 83
 84def read_csv(file: str) -> dict[str, list[str]]:
 85    """
 86    Read CSV file with location names and TNs
 87    """
 88    if not os.path.isfile(file):
 89        logging.error(f'File {file} does not exist')
 90        exit(1)
 91    err = False
 92    locations_and_tns: dict[str, list[str]] = defaultdict(list)
 93    with open(file, mode='r') as f:
 94        reader = csv.reader(f)
 95        for row in reader:
 96            if not row:
 97                continue
 98            if len(row) != 2:
 99                logging.error(f'Invalid row: {row}')
100                err = True
101                continue
102            location, tn = row
103            logging.debug(f'Location: {location}, TN: {tn}')
104            locations_and_tns[location].append(tn)
105    if err:
106        logging.error('Errors in the CSV file')
107        exit(1)
108    return locations_and_tns
109
110
111async def verify_location(api: AsWebexSimpleApi, location_name: str) -> Optional[str]:
112    """
113    Verify that a location exists and return location id
114    """
115    try:
116        location = next((l
117                         for l in await api.telephony.locations.list(name=location_name)
118                         if l.name == location_name),
119                        None)
120        return location and location.location_id
121    except Exception as e:
122        logging.error(f'Failed to get location {location_name}: {e}')
123        return None
124
125
126async def validate_tns(api: AsWebexSimpleApi, tns: list[str]) -> bool:
127    """
128    Validate TNs and return validity
129    """
130    tn_counter = Counter(tns)
131    err = False
132    for tn, count in tn_counter.items():
133        if count > 1:
134            err = True
135            logging.error(f'TN {tn} is duplicated')
136    if err:
137        return False
138
139    # validate numbers in batches
140    try:
141        validations = await asyncio.gather(*[api.telephony.validate_phone_numbers(tns[i:i + BATCH_SIZE])
142                                             for i in range(0, len(tns), BATCH_SIZE)])
143    except Exception as e:
144        logging.error(f'Failed to validate TNs: {e}')
145        return False
146
147    ok_tns = []
148    err = False
149    for status in chain.from_iterable(v.phone_numbers for v in validations):
150        if status.ok:
151            ok_tns.append(status.phone_number)
152        else:
153            err = True
154            logging.error(f'TN {status.phone_number}: {status.state} ')
155    return not err
156
157
158async def add_tns(api: AsWebexSimpleApi, location_id: str, tns: list[str], inactive: bool):
159    """
160    Add TNs to a location
161    """
162    number_state = NumberState.inactive if inactive else NumberState.active
163    try:
164        # add TNs in batches
165        await asyncio.gather(*[api.telephony.location.number.add(location_id=location_id,
166                                                                 phone_numbers=tns[i:i + BATCH_SIZE],
167                                                                 state=number_state)
168                               for i in range(0, len(tns), BATCH_SIZE)])
169    except Exception as e:
170        logging.error(f'Failed to add TNs: {e}')
171        return False
172    return True
173
174
175async def add_numbers():
176    """
177    Add TNs to Webex Calling locations
178    """
179    # get commandline arguments
180    parser = argparse.ArgumentParser(description='Add TNs to Webex Calling locations',
181                                     epilog='Example: %(prog)s add_numbers.csv --log-file add_numbers.har --dry-run')
182    parser.add_argument('file', help='CSV file with location names and TNs')
183    parser.add_argument('--dry-run', action='store_true', help='Do not make any changes')
184    parser.add_argument('--verbose', action='store_true', help='Print debug information')
185    parser.add_argument('--log-file', help='Log file. If extension is .har, log in HAR format')
186    parser.add_argument('--token', help=f'Access token can be provided using --token argument, set in '
187                                        f'WEBEX_ACCESS_TOKEN environment variable or can be a service app token. For '
188                                        f'the latter set environment variables {SERVICE_APP_ENVS}. Environment '
189                                        f'variables can also be set in {env_path()}')
190    parser.add_argument('--inactive', action='store_true', help='Add TNs as inactive')
191    args = parser.parse_args()
192    load_dotenv(env_path())
193    tokens = get_tokens() if args.token is None else Tokens(access_token=args.token)
194    if tokens is None:
195        print(f'Access token can be provided using --token argument, set in WEBEX_ACCESS_TOKEN environment variable or '
196              f'can be a service app token. For the latter set environment variables {SERVICE_APP_ENVS}. Environment '
197              f'variables can '
198              f'also be set in {env_path()}', file=sys.stderr)
199        exit(1)
200
201    async with AsWebexSimpleApi(tokens=tokens) as api:
202        with setup_logging(args, api):
203            # validate the access token
204            try:
205                await api.people.me()
206            except Exception as e:
207                logging.error(f'Failed to get identity: {e}')
208                logging.error('Token might be invalid')
209                exit(1)
210            # read location names and TNs from a CSV file
211            logging.info(f'Reading file {args.file}')
212            locations_and_tns = read_csv(args.file)
213
214            # validate the location names
215            logging.info('Validating location names...')
216            location_ids = await asyncio.gather(*[verify_location(api, location)
217                                                  for location in locations_and_tns.keys()])
218            if not all(location_ids):
219                for location_name, location_id in zip(locations_and_tns.keys(), location_ids):
220                    if not location_id:
221                        logging.error(f'Location {location_name} does not exist')
222                exit(1)
223
224            # validate the TNs
225            logging.info('Validating TNs...')
226            tn_list = list(chain.from_iterable(locations_and_tns.values()))
227            validation = await validate_tns(api, tn_list)
228            if not validation:
229                exit(1)
230
231            # add TNs to the locations
232            if not args.dry_run:
233                logging.info('Adding TNs...')
234                results = await asyncio.gather(*[add_tns(api, location_id, tns, args.inactive)
235                                                 for location_id, tns in zip(location_ids,
236                                                                             locations_and_tns.values())])
237                if not all(results):
238                    exit(1)
239            #
240            logging.info('Done')
241        # end of logging context
242    # end of API context
243    return
244
245
246if __name__ == '__main__':
247    asyncio.run(add_numbers())

Bulk add outgoing call permission patterns to locations

Bulk add outgoing call permission patterns to locations

usage: ocp_pattern.py [-h] [--token TOKEN] [--dry-run] [--verbose] [--log-file LOG_FILE]
                      location patterns

Provision OCP patterns for one or all locations

positional arguments:
  location             Location to provision OCP patterns for. Use "all" to provision for
                       all locations
  patterns             File with patterns to provision. File has one pattern per line. Use
                       "remove" to remove all patterns previously provisioned by the
                       script

optional arguments:
  -h, --help           show this help message and exit
  --token TOKEN        Access token can be provided using --token argument, set in
                       WEBEX_ACCESS_TOKEN environment variable or can be a service app
                       token. For the latter set environment variables
                       ('SERVICE_APP_REFRESH_TOKEN', 'SERVICE_APP_CLIENT_ID',
                       'SERVICE_APP_CLIENT_SECRET'). Environment variables can also be set
                       in ocp_pattern.env
  --dry-run            Dry run, do not provision anything
  --verbose            Print debug information
  --log-file LOG_FILE  Log file. If extension is .har, log in HAR format

Example: ocp_pattern.py all ocp_pattern.txt --log-file ocp_pattern.har --dry-run

Source: ocp_pattern.py

  1#!/usr/bin/env python3
  2"""
  3Provision OCP patterns for one or all locations
  4
  5usage: ocp_pattern.py [-h] [--token TOKEN] [--dry-run] [--verbose] [--log-file LOG_FILE]
  6                      location patterns
  7
  8Provision OCP patterns for one or all locations
  9
 10positional arguments:
 11  location             Location to provision OCP patterns for. Use "all" to provision for
 12                       all locations
 13  patterns             File with patterns to provision. File has one pattern per line. Use
 14                       "remove" to remove all patterns previously provisioned by the
 15                       script
 16
 17optional arguments:
 18  -h, --help           show this help message and exit
 19  --token TOKEN        Access token can be provided using --token argument, set in
 20                       WEBEX_ACCESS_TOKEN environment variable or can be a service app
 21                       token. For the latter set environment variables
 22                       ('SERVICE_APP_REFRESH_TOKEN', 'SERVICE_APP_CLIENT_ID',
 23                       'SERVICE_APP_CLIENT_SECRET'). Environment variables can also be set
 24                       in ocp_pattern.env
 25  --dry-run            Dry run, do not provision anything
 26  --verbose            Print debug information
 27  --log-file LOG_FILE  Log file. If extension is .har, log in HAR format
 28
 29Example: ocp_pattern.py all ocp_pattern.txt --log-file ocp_pattern.har --dry-run
 30"""
 31import argparse
 32import asyncio
 33import logging
 34import os
 35import sys
 36from contextlib import contextmanager
 37
 38from dotenv import load_dotenv
 39
 40from examples.service_app import SERVICE_APP_ENVS, env_path, get_tokens
 41from wxc_sdk.as_api import AsWebexSimpleApi
 42from wxc_sdk.as_rest import AsRestError
 43from wxc_sdk.har_writer import HarWriter
 44from wxc_sdk.person_settings.permissions_out import DigitPattern, Action
 45from wxc_sdk.telephony.location import TelephonyLocation
 46from wxc_sdk.tokens import Tokens
 47
 48
 49async def work_on_one_location(api: AsWebexSimpleApi, location: TelephonyLocation, pattern_list: list[str],
 50                               dry_run: bool):
 51    """
 52    Work on one location, create, update or remove patterns
 53    """
 54
 55    async def create(pattern: str):
 56        try:
 57            await dapi.create(location.location_id,
 58                              DigitPattern(pattern=pattern,
 59                                           name=f'ocp-{pattern}',
 60                                           action=Action.allow,
 61                                           transfer_enabled=True))
 62            print(f'{location.name}: created pattern {pattern}')
 63        except AsRestError as e:
 64            print(f'{location.name}: failed to create pattern {pattern}, error: {e}')
 65            raise
 66
 67    async def remove(pattern: DigitPattern):
 68        try:
 69            await dapi.delete(location.location_id, pattern.id)
 70            print(f'{location.name}: removed pattern {pattern.pattern}')
 71        except AsRestError as e:
 72            print(f'{location.name}: failed to remove pattern {pattern.pattern}, error: {e}')
 73            raise
 74
 75    async def update(pattern: DigitPattern):
 76        try:
 77            await dapi.update(location.location_id,
 78                              DigitPattern(pattern=pattern.pattern,
 79                                           name=f'ocp-{pattern.pattern}',
 80                                           action=Action.allow,
 81                                           transfer_enabled=True))
 82            print(f'{location.name}: updated pattern {pattern.pattern}')
 83        except AsRestError as e:
 84            print(f'{location.name}: failed to update pattern {pattern.pattern}, error: {e}')
 85            raise
 86
 87    pattern_set = set(pattern_list)
 88    dapi = api.telephony.permissions_out.digit_patterns
 89
 90    # get ocp patterns for location
 91    location_digit_patterns = await dapi.get_digit_patterns(location.location_id)
 92
 93    existing_patterns = [pattern for pattern in location_digit_patterns.digit_patterns
 94                         if pattern.pattern in pattern_set]
 95    missing_patterns = [pattern
 96                        for pattern in pattern_list
 97                        if pattern not in set(map(lambda p: p.pattern, location_digit_patterns.digit_patterns))]
 98    to_be_removed = [pattern for pattern in location_digit_patterns.digit_patterns
 99                     if pattern.name.startswith('ocp-') and pattern.pattern not in pattern_set]
100    tasks = []
101
102    # remove patterns
103    for remove_pattern in to_be_removed:
104        # remove pattern
105        print(f'{location.name}: remove pattern {remove_pattern.pattern}')
106        if not dry_run:
107            tasks.append(remove(remove_pattern))
108
109    # add missing patterns
110    for pattern in missing_patterns:
111        # add pattern
112        print(f'{location.name}: add pattern {pattern}')
113        if not dry_run:
114            tasks.append(create(pattern))
115
116    # check existing patterns and update if action is not "allow"
117    for existing in existing_patterns:
118        if existing.action == Action.allow and existing.transfer_enabled:
119            # pattern already exists and is allowed
120            continue
121        # update existing pattern
122        print(f'{location.name}: update pattern {existing.pattern}')
123        if not dry_run:
124            tasks.append(update(existing))
125    if tasks:
126        # run tasks
127        await asyncio.gather(*tasks)
128    return
129
130
131@contextmanager
132def setup_logging(args: argparse.Namespace, api: AsWebexSimpleApi):
133    """
134    Set up logging
135    """
136
137    @contextmanager
138    def file_handler(log_file: str):
139        if not log_file:
140            yield
141        else:
142            # log to file or to HAR
143            if os.path.splitext(log_file)[-1].lower() == '.har':
144                with HarWriter(api=api, path=log_file):
145                    yield
146            else:
147                f_handler = logging.FileHandler(args.log_file)
148                f_handler.setLevel(logging.DEBUG)
149                f_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
150                logging.getLogger().addHandler(f_handler)
151                yield
152        return
153
154    logging.getLogger().setLevel(logging.DEBUG)
155    # create a console logging handler
156    console_handler = logging.StreamHandler()
157    console_handler.setLevel(logging.DEBUG if args.verbose else logging.INFO)
158    console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
159    logging.getLogger().addHandler(console_handler)
160    with file_handler(args.log_file):
161        yield
162
163
164async def main():
165    parser = argparse.ArgumentParser(
166        description="Provision OCP patterns for one or all locations",
167        epilog='Example: %(prog)s all ocp_pattern.txt --log-file ocp_pattern.har --dry-run')
168    parser.add_argument('location', type=str, help='Location to provision OCP patterns for. Use "all" to '
169                                                   'provision for all locations')
170    parser.add_argument('patterns', type=str, help='File with patterns to provision. File has one pattern '
171                                                   'per line. Use "remove" to remove all patterns previously '
172                                                   'provisioned '
173                                                   'by the script')
174    parser.add_argument('--token',
175                        help=f'Access token can be provided using --token argument, set in '
176                             f'WEBEX_ACCESS_TOKEN environment variable or can be a service app token. For '
177                             f'the latter set environment variables {SERVICE_APP_ENVS}. Environment '
178                             f'variables can also be set in {env_path()}')
179    parser.add_argument('--dry-run', action='store_true', help='Dry run, do not provision anything')
180    parser.add_argument('--verbose', action='store_true', help='Print debug information')
181    parser.add_argument('--log-file', help='Log file. If extension is .har, log in HAR format')
182
183    args = parser.parse_args()
184    location_name = args.location
185    pattern_file = args.patterns
186    dry_run = args.dry_run
187
188    # get tokens
189    # if token is provided use that token, else try to read from file
190    load_dotenv(env_path())
191    tokens = get_tokens() if args.token is None else Tokens(access_token=args.token)
192    if tokens is None:
193        print(
194            f'Access token can be provided using --token argument, set in WEBEX_ACCESS_TOKEN environment variable '
195            f'or '
196            f'can be a service app token. For the latter set environment variables {SERVICE_APP_ENVS}. Environment '
197            f'variables can '
198            f'also be set in {env_path()}', file=sys.stderr)
199        exit(1)
200    async with AsWebexSimpleApi(tokens=tokens, concurrent_requests=100) as api:
201        with setup_logging(args, api):
202            # validate location
203            if location_name.lower() == 'all':
204                # all locations
205                location_list = await api.telephony.locations.list()
206                location_list.sort(key=lambda loc: loc.name)
207            else:
208                # single location
209                location_list = [loc
210                                 for loc in await api.telephony.locations.list(name=location_name)
211                                 if loc.name == location_name]
212                if not location_list:
213                    print(f'Location {location_name} not found', file=sys.stderr)
214                    exit(1)
215
216            # read patterns from given file
217            if pattern_file.lower() == 'remove':
218                # remove all patterns
219                pattern_list = []
220            else:
221                try:
222                    with open(pattern_file, mode='r') as f:
223                        pattern_list = [ps for p in f.readlines()
224                                        if (ps := p.strip()) and not p.startswith('#')]
225                except FileNotFoundError:
226                    print(f'File {pattern_file} not found', file=sys.stderr)
227                    exit(1)
228
229            # apply changes to all locations
230            print(f'Working on {len(location_list)} location(s), {len(pattern_list)} patterns')
231            await asyncio.gather(*[work_on_one_location(api, loc, pattern_list, dry_run)
232                                   for loc in location_list])
233    return
234
235
236if __name__ == '__main__':
237    asyncio.run(main())

Bulk provisioning of 3rd party devices in Workspaces

Bulk provisioning of 3rd party devices in Workspaces

usage: workspace_w_3rd_party.py [-h] [--token TOKEN] [--dry-run]
                                [--log-file LOG_FILE] [--cleanup]
                                csv [output]

Provision workspaces with 3rd party devices.

positional arguments:
  csv                  CSV with workspaces to provision. CSV has the
                       following columns: * workspace name: the workspace
                       will be created * location name: must be an
                       existing location * extension (optional); if
                       missing a new extension will be generated starting
                       at 2000 * MAC address; if empty a new (dummy) MAC
                       address will be generated as DEAD-DEAD-XXXX *
                       password (optional); if missing a new (random
                       password will be generated
  output               Output CSV with the provisioning results. Not
                       required in dry-run mode

optional arguments:
  -h, --help           show this help message and exit
  --token TOKEN        Access token can be provided using --token
                       argument, set in WEBEX_ACCESS_TOKEN environment
                       variable or can be a service app token. For the
                       latter set environment variables
                       ('SERVICE_APP_REFRESH_TOKEN',
                       'SERVICE_APP_CLIENT_ID',
                       'SERVICE_APP_CLIENT_SECRET'). Environment variables
                       can also be set in workspace_w_3rd_party.env
  --dry-run            Dry run, do not provision anything
  --log-file LOG_FILE  Log file. If extension is .har, log in HAR format
  --cleanup            remove workspaces

Example: workspace_w_3rd_party.py input.csv output.csv --log-file log.har

Source: workspace_w_3rd_party.py

  1#!/usr/bin/env python
  2"""
  3Create workspaces with 3rd party devices.
  4From a CSV read:
  5    * workspace name: if workspace doesn't exist a new workspace will be created
  6    * location name: must be an existing location
  7    * extension (optional); if missing a new extension will be generated starting at 2000
  8    * MAC address; if empty a new (dummy) MAC address will be generated as DEAD-DEAD-XXXX
  9    * password (optional); if missing a new (random password will be generated
 10The output is a CSV file with the following columns:
 11    * workspace name
 12    * location name
 13    * extension
 14    * MAC address
 15    * password
 16    * outbound proxy
 17    * SIP user name
 18    * line/port
 19
 20usage: workspace_w_3rd_party.py [-h] [--token TOKEN] [--dry-run]
 21                                [--log-file LOG_FILE] [--cleanup]
 22                                csv [output]
 23
 24Provision workspaces with 3rd party devices.
 25
 26positional arguments:
 27  csv                  CSV with workspaces to provision. CSV has the
 28                       following columns: * workspace name: the workspace
 29                       will be created * location name: must be an
 30                       existing location * extension (optional); if
 31                       missing a new extension will be generated starting
 32                       at 2000 * MAC address; if empty a new (dummy) MAC
 33                       address will be generated as DEAD-DEAD-XXXX *
 34                       password (optional); if missing a new (random
 35                       password will be generated
 36  output               Output CSV with the provisioning results. Not
 37                       required in dry-run mode
 38
 39optional arguments:
 40  -h, --help           show this help message and exit
 41  --token TOKEN        Access token can be provided using --token
 42                       argument, set in WEBEX_ACCESS_TOKEN environment
 43                       variable or can be a service app token. For the
 44                       latter set environment variables
 45                       ('SERVICE_APP_REFRESH_TOKEN',
 46                       'SERVICE_APP_CLIENT_ID',
 47                       'SERVICE_APP_CLIENT_SECRET'). Environment variables
 48                       can also be set in workspace_w_3rd_party.env
 49  --dry-run            Dry run, do not provision anything
 50  --log-file LOG_FILE  Log file. If extension is .har, log in HAR format
 51  --cleanup            remove workspaces
 52
 53Example: workspace_w_3rd_party.py input.csv output.csv --log-file log.har
 54"""
 55import argparse
 56import asyncio
 57import csv
 58import logging
 59import os
 60import sys
 61from collections import defaultdict
 62from collections.abc import Generator
 63from contextlib import contextmanager
 64from dataclasses import dataclass, field
 65from itertools import zip_longest, chain
 66
 67from dotenv import load_dotenv
 68
 69from examples.service_app import SERVICE_APP_ENVS, env_path, get_tokens
 70from open_api.generated.Shared.workspaces_auto import WorkspaceType
 71from wxc_sdk.as_api import AsWebexSimpleApi
 72from wxc_sdk.common import DevicePlatform
 73from wxc_sdk.har_writer import HarWriter
 74from wxc_sdk.licenses import License
 75from wxc_sdk.telephony.devices import MACState, MACValidationResponse
 76from wxc_sdk.telephony.location import TelephonyLocation
 77from wxc_sdk.tokens import Tokens
 78from wxc_sdk.workspaces import Workspace, WorkspaceSupportedDevices, WorkspaceCalling, CallingType, \
 79    WorkspaceWebexCalling
 80
 81MAC_VALIDATION_BATCH_SIZE = 100
 82
 83
 84@dataclass
 85class CSVRow:
 86    """
 87    CSV row with workspace and location name
 88    """
 89    workspace_name: str
 90    location_name: str
 91    extension: str
 92    mac_address: str
 93    password: str
 94    workspace: Workspace = field(default=None, init=False)
 95    calling_license_id: str = field(default=None, init=False)
 96    location: TelephonyLocation = field(default=None, init=False)
 97    outbound_proxy: str = field(default=None, init=False)
 98    sip_user_name: str = field(default=None, init=False)
 99    line_port: str = field(default=None, init=False)
100
101    def __post_init__(self):
102        # clean up some data
103        self.workspace_name = self.workspace_name.strip()
104        self.location_name = self.location_name.strip()
105        self.extension = self.extension.strip() or None
106        self.mac_address = self.mac_address.strip().lower() or None
107        self.password = self.password.strip() or None
108
109    @classmethod
110    def from_csv(cls, csv_path: str) -> Generator['CSVRow', None, None]:
111        """
112        Yield CSVRow instances from CSV file
113        """
114        err = False
115        with open(csv_path, newline='') as csv_file:
116            reader = csv.reader(csv_file)
117            for row_number, row in enumerate(reader, 1):
118                try:
119                    yield cls(*row)
120                except TypeError as te:
121                    err = True
122                    print(f'Failed to parse row {row_number}: {te}', file=sys.stderr)
123                    continue
124        if err:
125            print(f'Failed to parse {csv_path}', file=sys.stderr)
126            exit(1)
127        return
128
129
130@contextmanager
131def setup_logging(args: argparse.Namespace, api: AsWebexSimpleApi):
132    """
133    Set up logging
134    """
135
136    @contextmanager
137    def file_handler(log_file: str):
138        if not log_file:
139            yield
140        else:
141            # log to file or to HAR
142            if os.path.splitext(log_file)[-1].lower() == '.har':
143                with HarWriter(api=api, path=log_file):
144                    yield
145            else:
146                f_handler = logging.FileHandler(args.log_file)
147                f_handler.setLevel(logging.DEBUG)
148                f_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
149                logging.getLogger().addHandler(f_handler)
150                yield
151        return
152
153    logging.getLogger().setLevel(logging.DEBUG)
154    # create a console logging handler
155    console_handler = logging.StreamHandler()
156    console_handler.setLevel(logging.INFO)
157    console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
158    logging.getLogger().addHandler(console_handler)
159    with file_handler(args.log_file):
160        yield
161
162
163# list of validation errors
164ValidationResult = list[tuple[int, str]]
165
166
167async def validate_extensions(*, api: AsWebexSimpleApi, location: TelephonyLocation,
168                              indexed_rows: list[tuple[int, CSVRow]]) -> ValidationResult:
169    """
170    Make sure that extensions are unique; if no extension is provided, generate a new one
171    """
172    extensions_in_location = {number.extension for number in
173                              await api.telephony.phone_numbers(location_id=location.location_id)
174                              if number.extension is not None}
175    errors = []
176    for row_index, csv_row in indexed_rows:
177        if csv_row.extension:
178            if csv_row.extension in extensions_in_location:
179                errors.append((row_index, f'Duplicate extension "{csv_row.extension}" in location "{location.name}"'))
180        else:
181            # generate new extension
182            csv_row.extension = next((str(ext) for ext in range(2000, 10000)
183                                      if str(ext) not in extensions_in_location))
184            print(f'Row {row_index}: Generated new extension "{csv_row.extension}"')
185        extensions_in_location.add(csv_row.extension)
186
187    return errors
188
189
190async def generate_passwords(*, api: AsWebexSimpleApi, location: TelephonyLocation,
191                             indexed_rows: list[tuple[int, CSVRow]]) -> ValidationResult:
192    """
193    Generate random passwords for rows without a password
194    """
195    new_passwords = await asyncio.gather(*[api.telephony.location.generate_password(location_id=location.location_id)
196                                           for _, csv_row in indexed_rows
197                                           if not csv_row.password])
198
199    for row_index, csv_row in indexed_rows:
200        if not csv_row.password:
201            # generate new password
202            csv_row.password = new_passwords.pop(0)
203            print(f'Row {row_index}: Generated new password "{csv_row.password}"')
204    return []
205
206
207async def validate_locations_and_extensions(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow],
208                                            cleanup: bool) -> ValidationResult:
209    """
210    Locations must exist and extensions must be unique
211    """
212    if cleanup:
213        return []
214    locations = {location.name: location
215                 for location in await api.telephony.locations.list()}
216    errors = []
217    for row_index, csv_row in enumerate(csv_rows, 1):
218        location = locations.get(csv_row.location_name)
219        if not location:
220            errors.append((row_index, f'Location "{csv_row.location_name}" does not exist'))
221        csv_row.location = location
222
223    # for all existing locations validate extensions
224    csv_rows_by_location: dict[str, list[tuple[int, CSVRow]]] = defaultdict(list)
225    for row_index, csv_row in enumerate(csv_rows, 1):
226        if csv_row.location_name in locations:
227            csv_rows_by_location[csv_row.location_name].append((row_index, csv_row))
228    tasks = [validate_extensions(api=api, location=locations[l_name],
229                                 indexed_rows=indexed_rows)
230             for l_name, indexed_rows in csv_rows_by_location.items()]
231    # also generate passwords for rows without a password
232    tasks.extend(generate_passwords(api=api, location=locations[l_name], indexed_rows=indexed_rows)
233                 for l_name, indexed_rows in csv_rows_by_location.items())
234    location_results = await asyncio.gather(*tasks)
235    errors.extend(chain.from_iterable(location_results))
236    return errors
237
238
239async def assign_new_mac_addresses(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow]) -> ValidationResult:
240    """
241    Get new MAC addresses for rows where no MAC address is provided
242    """
243    number_of_missing_mac_addresses = sum(1
244                                          for csv_row in csv_rows
245                                          if not csv_row.mac_address)
246
247    if not number_of_missing_mac_addresses:
248        return []
249    mac_prefix = 'DEADDEAD'
250    mac_addresses_in_csv = {csv_row.mac_address
251                            for csv_row in csv_rows
252                            if csv_row.mac_address}
253
254    def mac_candidates() -> Generator[str, None, None]:
255        for v in range(0, 65536):
256            candidate = f'{mac_prefix}{hex(v)[2:].zfill(4).upper()}'
257            if candidate in mac_addresses_in_csv:
258                # skip mac addresses that are already in the csv
259                continue
260            yield f'{mac_prefix}{hex(v)[2:].zfill(4).upper()}'
261
262    new_mac_addresses = []
263
264    # test macs in batches
265    batch_args = [mac_candidates()] * MAC_VALIDATION_BATCH_SIZE
266
267    # noinspection PyArgumentList
268    batches = zip_longest(*batch_args)
269    for batch in batches:
270        validation_result = await api.telephony.devices.validate_macs(macs=list(batch))
271        errored_macs = set(ms.mac
272                           for ms in (validation_result.mac_status or [])
273                           if ms.state != MACState.available)
274        new_mac_addresses.extend((mac for mac in batch if mac not in errored_macs))
275        if len(new_mac_addresses) >= number_of_missing_mac_addresses:
276            break
277    for row_index, csv_row in enumerate(csv_rows, 1):
278        if not csv_row.mac_address:
279            # generate new MAC address
280            csv_row.mac_address = new_mac_addresses.pop(0)
281            print(f'Row {row_index}: Generated new MAC address "{csv_row.mac_address}"')
282    return []
283
284
285async def mac_addresses_available(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow]) -> ValidationResult:
286    """
287    Check if MAC addresses provided in CSV are available
288    """
289    errors = []
290    mac_addresses = list(set(csv_row.mac_address for csv_row in csv_rows if csv_row.mac_address))
291    if not mac_addresses:
292        return []
293
294    # validate in batches
295    batches = [mac_addresses[i:i + MAC_VALIDATION_BATCH_SIZE]
296               for i in range(0, len(mac_addresses), MAC_VALIDATION_BATCH_SIZE)]
297    results = await asyncio.gather(*[api.telephony.devices.validate_macs(macs=batch)
298                                     for batch in batches])
299    results: list[MACValidationResponse]
300
301    errored_macs: dict[str, str] = dict()
302    for result in results:
303        errored_macs.update((ms.mac, f'{ms.state}, {ms.message}')
304                            for ms in (result.mac_status or [])
305                            if ms.state != MACState.available)
306
307    if not errored_macs:
308        return []
309    for row_index, csv_row in enumerate(csv_rows, 1):
310        if csv_row.mac_address and csv_row.mac_address in errored_macs:
311            errors.append((row_index, f'MAC address "{csv_row.mac_address}": {errored_macs[csv_row.mac_address]}'))
312    return errors
313
314
315async def validate_mac_addresses(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow],
316                                 cleanup: bool) -> ValidationResult:
317    """
318    mac addresses must be unique and available
319    """
320    if cleanup:
321        return []
322    mac_addresses = set()
323    errors = []
324    # check if provided MAC addresses are unique
325    for row_index, csv_row in enumerate(csv_rows, 1):
326        if csv_row.mac_address:
327            if csv_row.mac_address in mac_addresses:
328                errors.append((row_index, f'Duplicate MAC address "{csv_row.mac_address}"'))
329            mac_addresses.add(csv_row.mac_address)
330
331    results = await asyncio.gather(assign_new_mac_addresses(api=api, csv_rows=csv_rows),
332                                   mac_addresses_available(api=api, csv_rows=csv_rows))
333    errors.extend(chain.from_iterable(results))
334    return errors
335
336
337async def validate_workspaces_and_licenses(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow],
338                                           cleanup: bool) -> ValidationResult:
339    """
340    Workspaces should not exist, also get license for new workspaces
341    """
342    tasks = [api.workspaces.list()]
343    if not cleanup:
344        tasks.append(api.licenses.list())
345    results = await asyncio.gather(*tasks)
346    workspace_list = results[0]
347    if cleanup:
348        licenses = []
349    else:
350        licenses = results[1]
351    workspace_list: list[Workspace]
352    licenses: list[License]
353    workspaces = {ws.display_name: ws
354                  for ws in workspace_list}
355
356    def calling_license_id() -> Generator[str, None, None]:
357        """
358        calling license id for license with available entitlement
359        """
360        candidate_licenses = [lic for lic in licenses
361                              if lic.webex_calling_workspaces or lic.webex_calling_professional]
362        # make sure to consume workspace licenses first
363        candidate_licenses.sort(key=lambda x: x.name, reverse=True)
364        for lic in candidate_licenses:
365            while lic.consumed_units < lic.total_units:
366                lic.consumed_units += 1
367                yield lic.license_id
368        return
369
370    errors = []
371    license_id_gen = calling_license_id()
372    for row_index, csv_row in enumerate(csv_rows, 1):
373        # check if workspace exists
374        ws = workspaces.get(csv_row.workspace_name)
375        csv_row.workspace = ws
376        if cleanup:
377            if not ws:
378                errors.append((row_index, f'Workspace "{csv_row.workspace_name}" does not exist'))
379            continue
380        if ws:
381            errors.append((row_index, f'Workspace "{csv_row.workspace_name}" already exists'))
382        # get a license for the workspace
383        try:
384            license_id = next(license_id_gen)
385        except StopIteration:
386            errors.append((row_index, f'No more licenses available for "{csv_row.workspace_name}"'))
387            continue
388        csv_row.calling_license_id = license_id
389    return errors
390
391
392async def validate_and_prepare(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow], cleanup: bool) -> None:
393    """
394    validate csv and prepare for provisioning
395        * location exists
396        * extensions are unique (if provided)
397        * MAC addresses are unique (if provided)
398        * workspace names are unique
399        * no devices in the workspace
400    """
401    results = await asyncio.gather(validate_locations_and_extensions(api=api, csv_rows=csv_rows, cleanup=cleanup),
402                                   validate_mac_addresses(api=api, csv_rows=csv_rows, cleanup=cleanup),
403                                   validate_workspaces_and_licenses(api=api, csv_rows=csv_rows, cleanup=cleanup))
404    errors = list(chain.from_iterable(results))
405    errors: ValidationResult
406    errors.sort(key=lambda x: x[0])
407    if errors:
408        print('Validation errors:', file=sys.stderr)
409        for row_index, error in errors:
410            print(f'Row {row_index}: {error}', file=sys.stderr)
411        exit(1)
412    return
413
414
415async def delete_workspaces(*, api: AsWebexSimpleApi, csv_rows: list[CSVRow], dry_run: bool) -> None:
416    """
417    cleanup: delete workspaces
418    """
419
420    async def delete_one_workspace(workspace: Workspace) -> None:
421        if dry_run:
422            print(f'Delete workspace "{workspace.display_name}"')
423        else:
424            await api.workspaces.delete_workspace(workspace_id=workspace.workspace_id)
425            print(f'Deleted workspace "{workspace.display_name}"')
426        return
427
428    await asyncio.gather(*[delete_one_workspace(csv_row.workspace)
429                           for csv_row in csv_rows
430                           if csv_row.workspace])
431
432
433async def provision_row(*, api: AsWebexSimpleApi, csv_row: CSVRow) -> None:
434    """
435    Provision a single row
436    """
437    # create workspace
438    settings = Workspace(location_id=csv_row.location.location_id,
439                         display_name=csv_row.workspace_name,
440                         type=WorkspaceType.desk,
441                         capacity=1,
442                         supported_devices=WorkspaceSupportedDevices.phones,
443                         device_platform=DevicePlatform.cisco,
444                         calling=WorkspaceCalling(type=CallingType.webex,
445                                                  webex_calling=WorkspaceWebexCalling(
446                                                      licenses=[csv_row.calling_license_id],
447                                                      extension=csv_row.extension,
448                                                      location_id=csv_row.location.location_id)))
449    workspace = await api.workspaces.create(settings=settings)
450    print(f'Provisioned workspace "{workspace.display_name}"')
451
452    # create device
453    device = await api.devices.create_by_mac_address(mac=csv_row.mac_address,
454                                                     workspace_id=workspace.workspace_id,
455                                                     model='Generic IPPhone Customer Managed',
456                                                     password=csv_row.password)
457
458    details = await api.telephony.devices.details(device_id=device.device_id)
459    print(f'Provisioned device in workspace "{workspace.display_name}"')
460    csv_row.sip_user_name = details.owner.sip_user_name
461    csv_row.line_port = details.owner.line_port
462    csv_row.outbound_proxy = details.proxy.outbound_proxy
463
464    return
465
466
467def main():
468    async def as_main():
469        # read CSV file
470        csv_rows = list(CSVRow.from_csv(csv_file))
471        async with AsWebexSimpleApi(tokens=tokens) as api:
472            with setup_logging(args, api):
473                # validation and preparation for provisioning
474                await validate_and_prepare(api=api, csv_rows=csv_rows, cleanup=args.cleanup)
475                if args.cleanup:
476                    await delete_workspaces(api=api, csv_rows=csv_rows, dry_run=args.dry_run)
477                    return
478
479                if args.dry_run:
480                    print('Dry run, not provisioning anything')
481                    return
482                await asyncio.gather(*[provision_row(api=api, csv_row=csv_row)
483                                       for csv_row in csv_rows])
484                # write output
485                if args.output:
486                    with open(args.output, 'w', newline='') as output:
487                        writer = csv.writer(output)
488                        writer.writerow(['workspace_name', 'location_name', 'extension', 'mac_address',
489                                         'password', 'outbound_proxy', 'sip_user_name', 'line_port'])
490                        for csv_row in csv_rows:
491                            writer.writerow([csv_row.workspace_name, csv_row.location_name,
492                                             csv_row.extension, csv_row.mac_address,
493                                             csv_row.password, csv_row.outbound_proxy,
494                                             csv_row.sip_user_name, csv_row.line_port])
495                    # for
496                # with open
497            # with setup_logging
498        # async with AsWebexSimpleApi
499        return
500
501    # parse arguments
502    parser = argparse.ArgumentParser(
503        description="Provision workspaces with 3rd party devices.",
504        epilog='Example: %(prog)s input.csv output.csv --log-file log.har')
505    parser.add_argument('csv', type=str, help="""CSV with workspaces to provision. CSV has the following columns:
506    * workspace name: the workspace will be created
507    * location name: must be an existing location
508    * extension (optional); if missing a new extension will be generated starting at 2000
509    * MAC address; if empty a new (dummy) MAC address will be generated as DEAD-DEAD-XXXX
510    * password (optional); if missing a new (random password will be generated""")
511    parser.add_argument('output', nargs='?', type=str,
512                        help='Output CSV with the provisioning results. Not required in dry-run mode')
513    parser.add_argument('--token',
514                        help=f'Access token can be provided using --token argument, set in '
515                             f'WEBEX_ACCESS_TOKEN environment variable or can be a service app token. For '
516                             f'the latter set environment variables {SERVICE_APP_ENVS}. Environment '
517                             f'variables can also be set in {env_path()}')
518    parser.add_argument('--dry-run', action='store_true', help='Dry run, do not provision anything')
519    parser.add_argument('--log-file', help='Log file. If extension is .har, log in HAR format')
520    parser.add_argument('--cleanup', action='store_true', help='remove workspaces')
521    args = parser.parse_args()
522    if not any((args.output, args.dry_run, args.cleanup)):
523        parser.error('Output file is required if not dry-run cleanup mode')
524    if args.output and (args.dry_run or args.cleanup):
525        parser.error('Output file is not used in dry-run cleanup mode')
526    csv_file = args.csv
527    if not os.path.isfile(csv_file):
528        print(f'File {csv_file} does not exist', file=sys.stderr)
529        exit(1)
530
531    # read tokens
532    load_dotenv(env_path())
533    tokens = get_tokens() if args.token is None else Tokens(access_token=args.token)
534    if tokens is None:
535        print(
536            f'Access token can be provided using --token argument, set in WEBEX_ACCESS_TOKEN environment variable '
537            f'or can be a service app token. For the latter set environment variables {SERVICE_APP_ENVS}. Environment '
538            f'variables can also be set in {env_path()}', file=sys.stderr)
539        exit(1)
540
541    asyncio.run(as_main())
542
543
544if __name__ == '__main__':
545    main()