forked from singer-io/tap-appsflyer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
618 lines (511 loc) · 15.9 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#!/usr/bin/env python3
import csv
import datetime
import itertools
import os
import re
import sys
import attr
import backoff
import requests
import singer
import singer.stats
from singer import transform
from singer import utils
LOGGER = singer.get_logger()
SESSION = requests.Session()
CONFIG = {
"app_id": None,
"api_token": None
}
STATE = {}
ENDPOINTS = {
"installs": "/export/{app_id}/installs_report/v5",
"organic_installs": "/export/{app_id}/organic_installs_report/v5",
"in_app_events": "/export/{app_id}/in_app_events_report/v5"
}
def clean_config(config: dict) -> dict:
"""Strips whitespace from any values in the config."""
for key in config.keys():
value = config[key]
if isinstance(value, str):
config[key] = value.strip()
return config
def af_datetime_str_to_datetime(s):
return datetime.datetime.strptime(s.strip(), "%Y-%m-%d %H:%M:%S")
def get_restricted_start_date(date: str) -> datetime.datetime:
# https://support.appsflyer.com/hc/en-us/articles/207034366-API-Policy
restriction_date = datetime.datetime.now() - datetime.timedelta(days=90)
start_date = utils.strptime(date)
return max(start_date, restriction_date)
def get_start(key):
if key in STATE:
return get_restricted_start_date(STATE[key])
if "start_date" in CONFIG:
return get_restricted_start_date(CONFIG["start_date"])
return datetime.datetime.now() - datetime.timedelta(days=30)
def get_stop(start_datetime, stop_time, days=30):
return min(start_datetime + datetime.timedelta(days=days), stop_time)
def get_base_url():
if "base_url" in CONFIG:
return CONFIG["base_url"]
else:
return "https://hq.appsflyer.com"
def get_url(endpoint, **kwargs):
if endpoint not in ENDPOINTS:
raise ValueError("Invalid endpoint {}".format(endpoint))
else:
return get_base_url() + ENDPOINTS[endpoint].format(**kwargs)
def xform_datetime_field(record, field_name):
record[field_name] = af_datetime_str_to_datetime(record[field_name]).isoformat()
def xform_boolean_field(record, field_name):
value = record[field_name]
if value is None:
return
if value.lower() == "TRUE".lower():
record[field_name] = True
else:
record[field_name] = False
def xform_empty_strings_to_none(record):
for key, value in record.items():
if value == "":
record[key] = None
def xform(record, schema):
xform_empty_strings_to_none(record)
xform_boolean_field(record, "wifi")
xform_boolean_field(record, "is_retargeting")
return transform.transform(record, schema)
@attr.s
class Stream(object):
name = attr.ib()
sync = attr.ib()
def get_abs_path(path):
return os.path.join(os.path.dirname(os.path.realpath(__file__)), path)
def load_schema(entity_name):
schema = utils.load_json(get_abs_path('schemas/{}.json'.format(entity_name)))
return schema
def giveup(exc):
return exc.response is not None and 400 <= exc.response.status_code < 500
def parse_source_from_url(url):
url_regex = re.compile(get_base_url() + r'.*/(\w+)_report/v5')
match = url_regex.match(url)
if match:
return match.group(1)
return None
@backoff.on_exception(backoff.expo,
(requests.exceptions.RequestException),
max_tries=5,
giveup=giveup,
factor=2)
@utils.ratelimit(10, 1)
def request(url, params=None):
params = params or {}
headers = {}
if "user_agent" in CONFIG:
headers["User-Agent"] = CONFIG["user_agent"]
req = requests.Request("GET", url, params=params, headers=headers).prepare()
LOGGER.info("GET %s", req.url)
with singer.stats.Timer(source=parse_source_from_url(url)) as stats:
resp = SESSION.send(req)
stats.http_status_code = resp.status_code
if resp.status_code >= 400:
LOGGER.error("GET %s [%s - %s]", req.url, resp.status_code, resp.content)
sys.exit(1)
return resp
class RequestToCsvAdapter:
def __init__(self, request_data):
self.request_data_iter = request_data.iter_lines();
def __iter__(self):
return self
def __next__(self):
return next(self.request_data_iter).decode("utf-8")
def sync_installs():
schema = load_schema("raw_data/installations")
singer.write_schema("installs", schema, [
"event_time",
"event_name",
"appsflyer_id"
])
# This order matters
fieldnames = (
"attributed_touch_type",
"attributed_touch_time",
"install_time",
"event_time",
"event_name",
"event_value",
"event_revenue",
"event_revenue_currency",
"event_revenue_usd",
"event_source",
"is_receipt_validated",
"af_prt",
"media_source",
"af_channel",
"af_keywords",
"campaign",
"af_c_id",
"af_adset",
"af_adset_id",
"af_ad",
"af_ad_id",
"af_ad_type",
"af_siteid",
"af_sub_siteid",
"af_sub1",
"af_sub2",
"af_sub3",
"af_sub4",
"af_sub5",
"af_cost_model",
"af_cost_value",
"af_cost_currency",
"contributor1_af_prt",
"contributor1_media_source",
"contributor1_campaign",
"contributor1_touch_type",
"contributor1_touch_time",
"contributor2_af_prt",
"contributor2_media_source",
"contributor2_campaign",
"contributor2_touch_type",
"contributor2_touch_time",
"contributor3_af_prt",
"contributor3_media_source",
"contributor3_campaign",
"contributor3_touch_type",
"contributor3_touch_time",
"region",
"country_code",
"state",
"city",
"postal_code",
"dma",
"ip",
"wifi",
"operator",
"carrier",
"language",
"appsflyer_id",
"advertising_id",
"idfa",
"android_id",
"customer_user_id",
"imei",
"idfv",
"platform",
"device_type",
"os_version",
"app_version",
"sdk_version",
"app_id",
"app_name",
"bundle_id",
"is_retargeting",
"retargeting_conversion_type",
"af_attribution_lookback",
"af_reengagement_window",
"is_primary_attribution",
"user_agent",
"http_referrer",
"original_url",
)
from_datetime = get_start("installs")
to_datetime = get_stop(from_datetime, datetime.datetime.now())
if to_datetime < from_datetime:
LOGGER.error("to_datetime (%s) is less than from_endtime (%s).", to_datetime, from_datetime)
return
params = dict()
params["from"] = from_datetime.strftime("%Y-%m-%d %H:%M")
params["to"] = to_datetime.strftime("%Y-%m-%d %H:%M")
params["api_token"] = CONFIG["api_token"]
url = get_url("installs", app_id=CONFIG["app_id"])
request_data = request(url, params)
csv_data = RequestToCsvAdapter(request_data)
reader = csv.DictReader(csv_data, fieldnames)
next(reader) # Skip the heading row
bookmark = from_datetime
for i, row in enumerate(reader):
record = xform(row, schema)
singer.write_record("installs", record)
# AppsFlyer returns records in order of most recent first.
try:
if utils.strptime(record["attributed_touch_time"]) > bookmark:
bookmark = utils.strptime(record["attributed_touch_time"])
except:
LOGGER.error("failed to get attributed_touch_time")
# Write out state
utils.update_state(STATE, "installs", bookmark)
singer.write_state(STATE)
def sync_organic_installs():
schema = load_schema("raw_data/organic_installs")
singer.write_schema("organic_installs", schema, [
"event_time",
"event_name",
"appsflyer_id"
])
# This order matters
fieldnames = (
"attributed_touch_type",
"attributed_touch_time",
"install_time",
"event_time",
"event_name",
"event_value",
"event_revenue",
"event_revenue_currency",
"event_revenue_usd",
"event_source",
"is_receipt_validated",
"af_prt",
"media_source",
"af_channel",
"af_keywords",
"campaign",
"af_c_id",
"af_adset",
"af_adset_id",
"af_ad",
"af_ad_id",
"af_ad_type",
"af_siteid",
"af_sub_siteid",
"af_sub1",
"af_sub2",
"af_sub3",
"af_sub4",
"af_sub5",
"af_cost_model",
"af_cost_value",
"af_cost_currency",
"contributor1_af_prt",
"contributor1_media_source",
"contributor1_campaign",
"contributor1_touch_type",
"contributor1_touch_time",
"contributor2_af_prt",
"contributor2_media_source",
"contributor2_campaign",
"contributor2_touch_type",
"contributor2_touch_time",
"contributor3_af_prt",
"contributor3_media_source",
"contributor3_campaign",
"contributor3_touch_type",
"contributor3_touch_time",
"region",
"country_code",
"state",
"city",
"postal_code",
"dma",
"ip",
"wifi",
"operator",
"carrier",
"language",
"appsflyer_id",
"advertising_id",
"idfa",
"android_id",
"customer_user_id",
"imei",
"idfv",
"platform",
"device_type",
"os_version",
"app_version",
"sdk_version",
"app_id",
"app_name",
"bundle_id",
"is_retargeting",
"retargeting_conversion_type",
"af_attribution_lookback",
"af_reengagement_window",
"is_primary_attribution",
"user_agent",
"http_referrer",
"original_url",
)
from_datetime = get_start("organic_installs")
to_datetime = get_stop(from_datetime, datetime.datetime.now())
if to_datetime < from_datetime:
LOGGER.error("to_datetime (%s) is less than from_endtime (%s).", to_datetime, from_datetime)
return
params = dict()
params["from"] = from_datetime.strftime("%Y-%m-%d %H:%M")
params["to"] = to_datetime.strftime("%Y-%m-%d %H:%M")
params["api_token"] = CONFIG["api_token"]
url = get_url("organic_installs", app_id=CONFIG["app_id"])
request_data = request(url, params)
csv_data = RequestToCsvAdapter(request_data)
reader = csv.DictReader(csv_data, fieldnames)
next(reader) # Skip the heading row
bookmark = from_datetime
for i, row in enumerate(reader):
record = xform(row, schema)
singer.write_record("organic_installs", record)
# AppsFlyer returns records in order of most recent first.
if utils.strptime(record["event_time"]) > bookmark:
bookmark = utils.strptime(record["event_time"])
# Write out state
utils.update_state(STATE, "organic_installs", bookmark)
singer.write_state(STATE)
def sync_in_app_events():
schema = load_schema("raw_data/in_app_events")
singer.write_schema("in_app_events", schema, [
"event_time",
"event_name",
"appsflyer_id"
])
# This order matters
fieldnames = (
"attributed_touch_type",
"attributed_touch_time",
"install_time",
"event_time",
"event_name",
"event_value",
"event_revenue",
"event_revenue_currency",
"event_revenue_usd",
"event_source",
"is_receipt_validated",
"af_prt",
"media_source",
"af_channel",
"af_keywords",
"campaign",
"af_c_id",
"af_adset",
"af_adset_id",
"af_ad",
"af_ad_id",
"af_ad_type",
"af_siteid",
"af_sub_siteid",
"af_sub1",
"af_sub2",
"af_sub3",
"af_sub4",
"af_sub5",
"af_cost_model",
"af_cost_value",
"af_cost_currency",
"contributor1_af_prt",
"contributor1_media_source",
"contributor1_campaign",
"contributor1_touch_type",
"contributor1_touch_time",
"contributor2_af_prt",
"contributor2_media_source",
"contributor2_campaign",
"contributor2_touch_type",
"contributor2_touch_time",
"contributor3_af_prt",
"contributor3_media_source",
"contributor3_campaign",
"contributor3_touch_type",
"contributor3_touch_time",
"region",
"country_code",
"state",
"city",
"postal_code",
"dma",
"ip",
"wifi",
"operator",
"carrier",
"language",
"appsflyer_id",
"advertising_id",
"idfa",
"android_id",
"customer_user_id",
"imei",
"idfv",
"platform",
"device_type",
"os_version",
"app_version",
"sdk_version",
"app_id",
"app_name",
"bundle_id",
"is_retargeting",
"retargeting_conversion_type",
"af_attribution_lookback",
"af_reengagement_window",
"is_primary_attribution",
"user_agent",
"http_referrer",
"original_url",
)
stop_time = datetime.datetime.now()
from_datetime = get_start("in_app_events")
to_datetime = get_stop(from_datetime, stop_time, 10)
while from_datetime < stop_time:
LOGGER.info("Syncing data from %s to %s", from_datetime, to_datetime)
params = dict()
params["from"] = from_datetime.strftime("%Y-%m-%d %H:%M")
params["to"] = to_datetime.strftime("%Y-%m-%d %H:%M")
params["api_token"] = CONFIG["api_token"]
url = get_url("in_app_events", app_id=CONFIG["app_id"])
request_data = request(url, params)
csv_data = RequestToCsvAdapter(request_data)
reader = csv.DictReader(csv_data, fieldnames)
next(reader) # Skip the heading row
bookmark = from_datetime
for i, row in enumerate(reader):
record = xform(row, schema)
singer.write_record("in_app_events", record)
# AppsFlyer returns records in order of most recent first.
if utils.strptime(record["event_time"]) > bookmark:
bookmark = utils.strptime(record["event_time"])
# Write out state
utils.update_state(STATE, "in_app_events", bookmark)
singer.write_state(STATE)
# Move the timings forward
from_datetime = to_datetime
to_datetime = get_stop(from_datetime, stop_time, 10)
STREAMS = [
Stream("installs", sync_installs),
Stream("in_app_events", sync_in_app_events)
]
def get_streams_to_sync(streams, state):
target_stream = state.get("this_stream")
result = streams
if "organic_installs" in CONFIG:
if CONFIG["organic_installs"]:
result.append(Stream("organic_installs", sync_organic_installs))
if target_stream:
result = list(itertools.dropwhile(lambda x: x.name != target_stream, streams))
if not result:
raise Exception('Unknown stream {} in state'.format(target_stream))
return result
def do_sync():
LOGGER.info("do_sync()")
streams = get_streams_to_sync(STREAMS, STATE)
LOGGER.info('Starting sync. Will sync these streams: %s', [stream.name for stream in streams])
for stream in streams:
LOGGER.info('Syncing %s', stream.name)
STATE["this_stream"] = stream.name
stream.sync() # pylint: disable=not-callable
STATE["this_stream"] = None
singer.write_state(STATE)
LOGGER.info("Sync completed")
def main():
args = utils.parse_args(
[
"app_id",
"api_token"
])
config = clean_config(args.config)
CONFIG.update(config)
if args.state:
STATE.update(args.state)
do_sync()
if __name__ == '__main__':
main()