-
Notifications
You must be signed in to change notification settings - Fork 38
/
__init__.py
462 lines (403 loc) · 17.2 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""
Defines all the sources and resources needed for ZendeskSupport, ZendeskChat and ZendeskTalk
"""
from typing import Iterator, Optional, Iterable, Tuple, List
from itertools import chain
import dlt
from dlt.common import pendulum
from dlt.common.time import ensure_pendulum_datetime
from dlt.common.typing import TDataItem, TDataItems, TAnyDateTime
from dlt.sources import DltResource
from .helpers.api_helpers import process_ticket, process_ticket_field
from .helpers.talk_api import PaginationType, ZendeskAPIClient
from .helpers.credentials import TZendeskCredentials, ZendeskCredentialsOAuth
from .helpers import make_date_ranges
from .settings import (
DEFAULT_START_DATE,
CUSTOM_FIELDS_STATE_KEY,
SUPPORT_ENDPOINTS,
TALK_ENDPOINTS,
INCREMENTAL_TALK_ENDPOINTS,
SUPPORT_EXTRA_ENDPOINTS,
)
@dlt.source(max_table_nesting=2)
def zendesk_talk(
credentials: TZendeskCredentials = dlt.secrets.value,
start_date: Optional[TAnyDateTime] = DEFAULT_START_DATE,
end_date: Optional[TAnyDateTime] = None,
) -> Iterable[DltResource]:
"""
Retrieves data from Zendesk Talk for phone calls and voicemails.
`start_date` argument can be used on its own or together with `end_date`. When both are provided
data is limited to items updated in that time range.
The range is "half-open", meaning elements equal and higher than `start_date` and elements lower than `end_date` are included.
All resources opt-in to use Airflow scheduler if run as Airflow task
Args:
credentials: The credentials for authentication. Defaults to the value in the `dlt.secrets` object.
start_date: The start time of the range for which to load. Defaults to January 1st 2000.
end_date: The end time of the range for which to load data.
If end time is not provided, the incremental loading will be enabled and after initial run, only new data will be retrieved
Yields:
DltResource: Data resources from Zendesk Talk.
"""
# use the credentials to authenticate with the ZendeskClient
zendesk_client = ZendeskAPIClient(credentials)
start_date_obj = ensure_pendulum_datetime(start_date)
end_date_obj = ensure_pendulum_datetime(end_date) if end_date else None
# regular endpoints
for key, talk_endpoint, item_name, cursor_paginated in TALK_ENDPOINTS:
yield dlt.resource(
talk_resource(
zendesk_client,
key,
item_name or talk_endpoint,
PaginationType.CURSOR if cursor_paginated else PaginationType.OFFSET,
),
name=key,
write_disposition="replace",
)
# adding incremental endpoints
for key, talk_incremental_endpoint in INCREMENTAL_TALK_ENDPOINTS.items():
yield dlt.resource(
talk_incremental_resource,
name=f"{key}_incremental",
primary_key="id",
write_disposition="merge",
)(
zendesk_client=zendesk_client,
talk_endpoint_name=key,
talk_endpoint=talk_incremental_endpoint,
updated_at=dlt.sources.incremental[str](
"updated_at",
initial_value=start_date_obj.isoformat(),
end_value=end_date_obj.isoformat() if end_date_obj else None,
allow_external_schedulers=True,
),
)
def talk_resource(
zendesk_client: ZendeskAPIClient,
talk_endpoint_name: str,
talk_endpoint: str,
pagination_type: PaginationType,
) -> Iterator[TDataItem]:
"""
Loads data from a Zendesk Talk endpoint.
Args:
zendesk_client: An instance of ZendeskAPIClient for making API calls to Zendesk Talk.
talk_endpoint_name: The name of the talk_endpoint.
talk_endpoint: The actual URL ending of the endpoint.
pagination: Type of pagination type used by endpoint
Yields:
TDataItem: Dictionary containing the data from the endpoint.
"""
# send query and process it
yield from zendesk_client.get_pages(
talk_endpoint, talk_endpoint_name, pagination_type
)
def talk_incremental_resource(
zendesk_client: ZendeskAPIClient,
talk_endpoint_name: str,
talk_endpoint: str,
updated_at: dlt.sources.incremental[str],
) -> Iterator[TDataItem]:
"""
Loads data from a Zendesk Talk endpoint with incremental loading.
Args:
zendesk_client: An instance of ZendeskAPIClient for making API calls to Zendesk Talk.
talk_endpoint_name: The name of the talk_endpoint.
talk_endpoint: The actual URL ending of the endpoint.
updated_at: Source for the last updated timestamp.
Yields:
TDataItem: Dictionary containing the data from the endpoint.
"""
# send the request and process it
for page in zendesk_client.get_pages(
talk_endpoint,
talk_endpoint_name,
PaginationType.START_TIME,
params={
"start_time": ensure_pendulum_datetime(updated_at.last_value).int_timestamp
},
):
yield page
if updated_at.end_out_of_range:
return
@dlt.source(max_table_nesting=2)
def zendesk_chat(
credentials: ZendeskCredentialsOAuth = dlt.secrets.value,
start_date: Optional[TAnyDateTime] = DEFAULT_START_DATE,
end_date: Optional[TAnyDateTime] = None,
) -> Iterable[DltResource]:
"""
Retrieves data from Zendesk Chat for chat interactions.
`start_date` argument can be used on its own or together with `end_date`. When both are provided
data is limited to items updated in that time range.
The range is "half-open", meaning elements equal and higher than `start_date` and elements lower than `end_date` are included.
All resources opt-in to use Airflow scheduler if run as Airflow task
Args:
credentials: The credentials for authentication. Defaults to the value in the `dlt.secrets` object.
start_date: The start time of the range for which to load. Defaults to January 1st 2000.
end_date: The end time of the range for which to load data.
If end time is not provided, the incremental loading will be enabled and after initial run, only new data will be retrieved
Yields:
DltResource: Data resources from Zendesk Chat.
"""
# Authenticate
zendesk_client = ZendeskAPIClient(credentials, url_prefix="https://www.zopim.com")
start_date_obj = ensure_pendulum_datetime(start_date)
end_date_obj = ensure_pendulum_datetime(end_date) if end_date else None
yield dlt.resource(chats_table_resource, name="chats", write_disposition="merge")(
zendesk_client,
dlt.sources.incremental[str](
"update_timestamp|updated_timestamp",
initial_value=start_date_obj.isoformat(),
end_value=end_date_obj.isoformat() if end_date_obj else None,
allow_external_schedulers=True,
),
)
def chats_table_resource(
zendesk_client: ZendeskAPIClient,
update_timestamp: dlt.sources.incremental[str],
) -> Iterator[TDataItems]:
"""
Resource for Chats
Args:
zendesk_client: The Zendesk API client instance, used to make calls to Zendesk API.
update_timestamp: Incremental source specifying the timestamp for incremental loading.
Yields:
dict: A dictionary representing each row of data.
"""
chat_pages = zendesk_client.get_pages(
"/api/v2/incremental/chats",
"chats",
PaginationType.START_TIME,
params={
"start_time": ensure_pendulum_datetime(
update_timestamp.last_value
).int_timestamp,
"fields": "chats(*)",
},
)
for page in chat_pages:
yield page
if update_timestamp.end_out_of_range:
return
@dlt.source(max_table_nesting=2)
def zendesk_support(
credentials: TZendeskCredentials = dlt.secrets.value,
load_all: bool = True,
pivot_ticket_fields: bool = True,
start_date: Optional[TAnyDateTime] = DEFAULT_START_DATE,
end_date: Optional[TAnyDateTime] = None,
) -> Iterable[DltResource]:
"""
Retrieves data from Zendesk Support for tickets, users, brands, organizations, and groups.
`start_date` argument can be used on its own or together with `end_date`. When both are provided
data is limited to items updated in that time range.
The range is "half-open", meaning elements equal and higher than `start_date` and elements lower than `end_date` are included.
All resources opt-in to use Airflow scheduler if run as Airflow task
Args:
credentials: The credentials for authentication. Defaults to the value in the `dlt.secrets` object.
load_all: Whether to load extra resources for the API. Defaults to True.
pivot_ticket_fields: Whether to pivot the custom fields in tickets. Defaults to True.
start_date: The start time of the range for which to load. Defaults to January 1st 2000.
end_date: The end time of the range for which to load data.
If end time is not provided, the incremental loading will be enabled and after initial run, only new data will be retrieved
Returns:
Sequence[DltResource]: Multiple dlt resources.
"""
start_date_obj = ensure_pendulum_datetime(start_date)
end_date_obj = ensure_pendulum_datetime(end_date) if end_date else None
start_date_ts = start_date_obj.int_timestamp
start_date_iso_str = start_date_obj.isoformat()
end_date_ts: Optional[int] = None
end_date_iso_str: Optional[str] = None
if end_date_obj:
end_date_ts = end_date_obj.int_timestamp
end_date_iso_str = end_date_obj.isoformat()
@dlt.resource(primary_key="id", write_disposition="append")
def ticket_events(
zendesk_client: ZendeskAPIClient,
timestamp: dlt.sources.incremental[int] = dlt.sources.incremental(
"timestamp",
initial_value=start_date_ts,
end_value=end_date_ts,
allow_external_schedulers=True,
),
) -> Iterator[TDataItem]:
# URL For ticket events
# 'https://d3v-dlthub.zendesk.com/api/v2/incremental/ticket_events.json?start_time=946684800'
event_pages = zendesk_client.get_pages(
"/api/v2/incremental/ticket_events.json",
"ticket_events",
PaginationType.STREAM,
params={"start_time": timestamp.last_value},
)
for page in event_pages:
yield page
if timestamp.end_out_of_range:
return
@dlt.resource(
name="tickets",
primary_key="id",
write_disposition="merge",
columns={
"tags": {"data_type": "complex"},
"custom_fields": {"data_type": "complex"},
},
)
def ticket_table(
zendesk_client: ZendeskAPIClient,
pivot_fields: bool = True,
updated_at: dlt.sources.incremental[
pendulum.DateTime
] = dlt.sources.incremental(
"updated_at",
initial_value=start_date_obj,
end_value=end_date_obj,
allow_external_schedulers=True,
),
) -> Iterator[TDataItem]:
"""
Resource for tickets table. Uses DLT state to handle column renaming of custom fields to prevent changing the names of said columns.
This resource uses pagination, loading and side loading to make API calls more efficient.
Args:
zendesk_client: The Zendesk API client instance, used to make calls to Zendesk API.
pivot_fields: Indicates whether to pivot the custom fields in tickets. Defaults to True.
per_page: The number of Ticket objects to load per page. Defaults to 1000.
updated_at: Incremental source for the 'updated_at' column.
Defaults to dlt.sources.incremental("updated_at", initial_value=start_date).
Yields:
TDataItem: Dictionary containing the ticket data.
"""
# grab the custom fields from dlt state if any
if pivot_fields:
load_ticket_fields_state(zendesk_client)
fields_dict = dlt.current.source_state().setdefault(CUSTOM_FIELDS_STATE_KEY, {})
# include_objects = ["users", "groups", "organisation", "brands"]
ticket_pages = zendesk_client.get_pages(
"/api/v2/incremental/tickets",
"tickets",
PaginationType.STREAM,
params={"start_time": updated_at.last_value.int_timestamp},
)
for page in ticket_pages:
yield [
process_ticket(ticket, fields_dict, pivot_custom_fields=pivot_fields)
for ticket in page
]
# stop loading when using end_value and end is reached
if updated_at.end_out_of_range:
return
@dlt.resource(
name="ticket_metric_events", primary_key="id", write_disposition="append"
)
def ticket_metric_table(
zendesk_client: ZendeskAPIClient,
time: dlt.sources.incremental[str] = dlt.sources.incremental(
"time",
initial_value=start_date_iso_str,
end_value=end_date_iso_str,
allow_external_schedulers=True,
),
) -> Iterator[TDataItem]:
"""
Resource for ticket metric events table. Returns all the ticket metric events from the starting date,
with the default starting date being January 1st of the current year.
Args:
zendesk_client: The Zendesk API client instance, used to make calls to Zendesk API.
time: Incremental source for the 'time' column,
indicating the starting date for retrieving ticket metric events.
Defaults to dlt.sources.incremental("time", initial_value=start_date_iso_str).
Yields:
TDataItem: Dictionary containing the ticket metric event data.
"""
# "https://example.zendesk.com/api/v2/incremental/ticket_metric_events?start_time=1332034771"
metric_event_pages = zendesk_client.get_pages(
"/api/v2/incremental/ticket_metric_events",
"ticket_metric_events",
PaginationType.CURSOR,
params={
"start_time": ensure_pendulum_datetime(time.last_value).int_timestamp,
},
)
for page in metric_event_pages:
yield page
if time.end_out_of_range:
return
def ticket_fields_table(zendesk_client: ZendeskAPIClient) -> Iterator[TDataItem]:
"""
Loads ticket fields data from Zendesk API.
Args:
zendesk_client: The Zendesk API client instance, used to make calls to Zendesk API.
Yields:
TDataItem: Dictionary containing the ticket fields data.
"""
# get dlt state
ticket_custom_fields = dlt.current.source_state().setdefault(
CUSTOM_FIELDS_STATE_KEY, {}
)
# get all custom fields and update state if needed, otherwise just load dicts into tables
all_fields = list(
chain.from_iterable(
zendesk_client.get_pages(
"/api/v2/ticket_fields.json", "ticket_fields", PaginationType.OFFSET
)
)
)
# all_fields = zendesk_client.ticket_fields()
for field in all_fields:
yield process_ticket_field(field, ticket_custom_fields)
def load_ticket_fields_state(
zendesk_client: ZendeskAPIClient,
) -> None:
for _ in ticket_fields_table(zendesk_client):
pass
ticket_fields_resource = dlt.resource(
name="ticket_fields", write_disposition="replace"
)(ticket_fields_table)
# Authenticate
zendesk_client = ZendeskAPIClient(credentials)
# loading base tables
resource_list = [
ticket_fields_resource(zendesk_client=zendesk_client),
ticket_events(zendesk_client=zendesk_client),
ticket_table(zendesk_client=zendesk_client, pivot_fields=pivot_ticket_fields),
ticket_metric_table(zendesk_client=zendesk_client),
]
# other tables to be loaded
resources_to_be_loaded = list(SUPPORT_ENDPOINTS) # make a copy
if load_all:
resources_to_be_loaded.extend(SUPPORT_EXTRA_ENDPOINTS)
for resource, endpoint_url, data_key, cursor_paginated in resources_to_be_loaded:
resource_list.append(
dlt.resource(
basic_resource(
zendesk_client, endpoint_url, data_key or resource, cursor_paginated
),
name=resource,
write_disposition="replace",
)
)
return resource_list
def basic_resource(
zendesk_client: ZendeskAPIClient,
endpoint_url: str,
data_key: str,
cursor_paginated: bool,
) -> Iterator[TDataItem]:
"""
Basic loader for most endpoints offered by Zenpy. Supports pagination. Expects to be called as a DLT Resource.
Args:
zendesk_client: The Zendesk API client instance, used to make calls to Zendesk API.
resource: The Zenpy endpoint to retrieve data from, usually directly linked to a Zendesk API endpoint.
cursor_paginated: Tells to use CURSOR pagination or OFFSET/no pagination
Yields:
TDataItem: Dictionary containing the resource data.
"""
pages = zendesk_client.get_pages(
endpoint_url,
data_key,
PaginationType.CURSOR if cursor_paginated else PaginationType.OFFSET,
)
yield from pages