This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.py
1815 lines (1489 loc) · 57.5 KB
/
api.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3.6
# -*- coding: utf8 -*-
'''
ELQuent.api
Eloqua API functions for other modules
Mateusz Dąbrowski
github.com/MateuszDabrowski
linkedin.com/in/mateusz-dabrowski-marketing/
'''
# Python imports
import os
import re
import sys
import json
import time
import base64
import pickle
import getpass
import webbrowser
import pyperclip
import requests
from colorama import Fore, Style, init
# Globals
naming = None
eloqua_key = None
eloqua_bulk = None
eloqua_rest = None
shared_list = None
asset_names = None
source_country = None
# Initialize colorama
init(autoreset=True)
# Predefined messege elements
ERROR = f'{Fore.WHITE}[{Fore.RED}ERROR{Fore.WHITE}] {Fore.YELLOW}'
WARNING = f'{Fore.WHITE}[{Fore.YELLOW}WARNING{Fore.WHITE}] '
SUCCESS = f'{Fore.WHITE}[{Fore.GREEN}SUCCESS{Fore.WHITE}] '
YES = f'{Style.BRIGHT}{Fore.GREEN}y{Fore.WHITE}{Style.NORMAL}'
NO = f'{Style.BRIGHT}{Fore.RED}n{Fore.WHITE}{Style.NORMAL}'
'''
=================================================================================
File Path Getter
=================================================================================
'''
def file(file_path):
'''
Returns file path to template files
'''
def find_data_file(filename):
'''
Returns correct file path for both script and frozen app
'''
if getattr(sys, 'frozen', False):
datadir = os.path.dirname(sys.executable)
return os.path.join(datadir, 'utils', 'api', filename)
else:
datadir = os.path.dirname(os.path.dirname(__file__))
return os.path.join(datadir, 'api', filename)
file_paths = {
'click': find_data_file('click.p'),
'eloqua': find_data_file('eloqua.p'),
'country': find_data_file('country.p'),
'naming': find_data_file('naming.json'),
'image': find_data_file('image.jpg')
}
return file_paths.get(file_path)
'''
=================================================================================
Main API functions
=================================================================================
'''
def status_code(response, root):
'''
Arguments:
reponse - response from api_request function
root - root URL of API call
Returns boolean of API connection.
'''
if (response.status_code >= 200) and (response.status_code < 400):
print(f'{Fore.YELLOW}» {root} '
f'{Fore.GREEN}({response.status_code})')
connected = True
elif response.status_code >= 400:
print(f'{Fore.YELLOW}» {root} '
f'{Fore.RED}({response.status_code})')
connected = False
else:
print(f'{Fore.YELLOW}» {root} '
f'{Fore.BLUE}({response.status_code})')
connected = False
return connected
def api_request(root, call='get', api='eloqua', params=None, debug=False, data=None, files=None):
'''
Arguments:
root - root URL of API call
call - GET/POST/PUT/DELETE
api - either elouqa or click
also: params, data, files for calls
Returns response from API call
If you want to print API connection status codes, set debug to True
'''
# Assings correct authorization method
if api == 'eloqua':
headers = {'Authorization': 'Basic ' + eloqua_key}
elif api == 'click':
click_api_key = pickle.load(open(file('click'), 'rb'))
headers = {'X-Api-Key': click_api_key}
if not files:
headers['Content-Type'] = 'application/json'
# Assings correct api call
if call == 'get':
response = requests.get(
root,
headers=headers,
params=params)
elif call == 'post':
response = requests.post(
root,
headers=headers,
data=data,
files=files)
elif call == 'put':
response = requests.put(
root,
headers=headers,
data=data,
files=files)
elif call == 'delete':
response = requests.delete(root, headers=headers)
# Prints status code
if debug:
status_code(response, root)
return response
'''
=================================================================================
Eloqua Asset Helpers
=================================================================================
'''
def get_asset_id(asset):
'''
Returns valid ID of chosen Eloqua asset [integer]
'''
while True:
print(
f'\n{Fore.WHITE}» [{Fore.YELLOW}{asset.capitalize()}{Fore.WHITE}]',
f'{Fore.WHITE}Write or copypaste {asset} ID or copy the code and click [Enter]', end='')
asset_id = input(' ')
if not asset_id:
asset_id = pyperclip.paste()
if len(asset_id) > 10:
return None
# Checks if input in numerical value
try:
asset_id = int(asset_id)
except ValueError:
print(f'{ERROR}It is not valid Eloqua {asset} ID')
continue
# Checks if there is asset with that ID
try:
asset_exists = eloqua_asset_get(asset_id, asset_type=asset)
except json.decoder.JSONDecodeError:
asset_exists = False
# Gets ID confirmation from user
if asset_exists:
choice = ''
while choice.lower() != 'y' and choice.lower() != 'n':
print(
f'{Fore.WHITE}» Continue with {Fore.YELLOW}{asset_exists[0]}{Fore.WHITE}? {Fore.WHITE}({YES}/{NO}):', end=' ')
choice = input('')
if choice.lower() == 'y':
return asset_id
elif choice.lower() == 'n':
continue
else:
print(f'{ERROR}Not found Eloqua {asset} with given ID')
def eloqua_asset_exist(name, asset):
'''
Returns True if there is already asset in Eloqua instance with that name
'''
# Gets required endpoint
endpoint = asset_names.get(asset)
endpoint += 's' # for multiple assets endpoint
# Gets data of requested asset
root = f'{eloqua_rest}assets/{endpoint}'
params = {'search': name}
response = api_request(root, params=params)
elq_asset = response.json()
if elq_asset['total']:
asset_id = elq_asset['elements'][0]['id']
print(
f'\n {WARNING}{asset} "{name}" already exists! [ID: {asset_id}]')
while True:
print(
f' {Fore.WHITE}» Click [Enter] to continue with current name or [Q] to quit', end='')
choice = input(' ')
if not choice:
return asset_id
elif choice.lower() == 'q':
print(f'\n{Fore.GREEN}Ahoj!')
raise SystemExit
else:
print(
f'\n{ERROR}Entered value is not a valid choice!')
else:
return False
def eloqua_asset_html_name(name):
'''
Returns correct html_name for the asset
'''
html_name = ''
date_element = re.compile(r'\d\d', re.UNICODE)
local_name = name.split('_')[-2] # Gets local name from asset name
for part in local_name.split('-'):
# Skip if part belongs to PSP
if part.startswith(tuple(naming[source_country]['psp'])):
continue
# Skip if part is a date
elif date_element.search(part):
continue
else:
html_name += f'{part[:20]}-'
# Gets asset type last part of html_name
html_name += name.split('_')[-1]
return html_name
def eloqua_asset_name():
'''
Returns correct name for the asset
'''
while True:
name = input(' ')
if not name:
name = pyperclip.paste()
name_check = name.split('_')
if len(name_check) != 5:
print(
f'{ERROR}Expected 5 name elements, found {len(name_check)}')
elif '/' in name:
print(
f'{ERROR}"/PSP" is expected only in the camapign name')
elif name_check[0][:2] != 'WK':
print(
f'{ERROR}"{name_check[0]}" is not existing country code')
elif name_check[1] not in naming[source_country]['segment']:
print(
f'{ERROR}"{name_check[1]}" is not existing segment name')
elif name_check[2] not in naming['campaign']:
print(
f'{ERROR}"{name_check[2]}" is not existing campaign type')
else:
return name
print(f'{Fore.YELLOW}Please write or copypaste correct name:')
def eloqua_asset_get(asset_id, asset_type, depth=''):
'''
Requires asset_id, asset_type and optionally depth
Returns name and optionally code of Eloqua asset of given ID
'''
# Gets required endpoint
endpoint = asset_names.get(asset_type)
# Gets data of requested asset
root = f'{eloqua_rest}assets/{endpoint}/{asset_id}'
params = {'depth': 'complete'}
response = api_request(root, params=params)
asset_response = response.json()
# Returns full response
if depth == 'complete':
return asset_response
# Gets name and code of the asset
name = asset_response['name']
if asset_type in ['landingPage', 'email']:
code = asset_response['htmlContent']['html']
elif asset_type == 'form':
code = asset_response['customCSS'] + asset_response['html']
elif asset_type == 'sharedContent':
code = asset_response['contentHtml']
if asset_type in ['landingPage', 'email', 'form']:
return (name, code)
else:
return name
def eloqua_get_assets(query, asset_type, count='', page='1', depth='complete'):
'''
Requires query string, asset_type and optionally count, pagination, depth
Returns partial list of assets and their full count
'''
# Sets output page element count to bigger for smaller response depth
if not count and depth == 'minimal':
count = 500
elif not count:
count = 20
# Gets required endpoint
endpoint = asset_names.get(asset_type) + 's'
# Builds the API request
payload = {
'search': query, # Filter by query
'depth': depth, # Sets required depth of data output
'orderBy': 'id DESC', # Sorts from newest to oldest to get most important first
'count': count, # Sets count according to depth
'page': page # Pagination of outcomes
}
# Creating a get call to Eloqua API
root = f'{eloqua_rest}assets/{endpoint}'
response = api_request(root, params=payload)
assets = response.json()
if assets['total'] > count:
print(f'{Fore.GREEN}|', end='', flush=True)
return assets
def eloqua_get_dependencies(asset_id, asset_type, depth='minimal'):
'''
Requires asset_id, asset_type and optionally count, pagination, depth
Returns partial list of dependencies and their full count
'''
# Gets required endpoint
endpoint = asset_names.get(asset_type) + '/' + asset_id + '/dependencies'
# Builds the API request
payload = {
'depth': depth, # Sets required depth of data output
}
# Creating a get call to Eloqua API
root = f'{eloqua_rest}assets/{endpoint}'
response = api_request(root, params=payload)
try:
dependencies = response.json()
except json.decoder.JSONDecodeError:
dependencies = []
return dependencies
'''
=================================================================================
Eloqua Authentication
=================================================================================
'''
def get_eloqua_auth(country):
'''
Returns Eloqua Root URL and creates globals with auth and bulk/rest roots
'''
# Creates global source_country from main module
global source_country
source_country = country
global asset_names
asset_names = {
'landingPage': 'landingPage',
'form': 'form',
'email': 'email',
'campaign': 'campaign',
'program': 'program',
'sharedFilter': 'contact/filter',
'segment': 'contact/segment',
'image': 'image',
'file': 'importedFile',
'sharedContent': 'contentSection',
'dynamicContent': 'dynamicContent',
'fieldMerge': 'fieldMerge'
}
# Gets data from naming.json
with open(file('naming'), 'r', encoding='utf-8') as f:
global naming
naming = json.load(f)
def get_eloqua_root():
'''
Returns Eloqua base URL for your instance.
'''
root = 'https://login.eloqua.com/id'
response = api_request(root=root)
login_data = response.json()
return login_data
while True:
# Gets Eloqua user details if they are already stored
print()
if not os.path.isfile(file('eloqua')):
print(f'{Fore.YELLOW}» {Fore.WHITE}Enter Eloqua Company name: ', end='')
eloqua_domain = input(' ')
print(f'{Fore.YELLOW}» {Fore.WHITE}Enter Eloqua User name: ', end='')
eloqua_user = input(' ')
eloqua_auth = (eloqua_domain, eloqua_user)
pickle.dump(eloqua_auth, open(file('eloqua'), 'wb'))
eloqua_domain, eloqua_user = pickle.load(open(file('eloqua'), 'rb'))
print(f'{Fore.YELLOW}» {Fore.WHITE}Enter Eloqua Password: ', end='')
eloqua_password = getpass.getpass(' ')
# Converts domain, user and to Eloqua Auth Key
global eloqua_key
eloqua_key = bytes(eloqua_domain + '\\' +
eloqua_user + ':' +
eloqua_password, 'utf-8')
eloqua_key = str(base64.b64encode(eloqua_key), 'utf-8')
# Gets Eloqua root URL
try:
login_data = get_eloqua_root()
eloqua_root = login_data['urls']['base']
except TypeError:
print(f'{ERROR}Login failed!')
os.remove(file('eloqua'))
continue
if eloqua_root:
break
# Creates globals related to Eloqua API
global eloqua_bulk
eloqua_bulk = eloqua_root + '/api/BULK/2.0/'
global eloqua_rest
eloqua_rest = eloqua_root + '/api/REST/2.0/'
return eloqua_key
'''
=================================================================================
Upload Contacts API Flow
=================================================================================
'''
def eloqua_create_sharedlist(export, choice):
'''
Creates shared list for contacts
Requires 'export' dict with webinars and conctacts in format:
{'listName': ['email', 'email']}
'''
outcome = []
print(f'\n{Fore.BLUE}Saving to shared list:', end='')
# Unpacks export
for name, contacts in export.items():
root = f'{eloqua_rest}assets/contact/list'
data = {'name': f'{name}',
'description': 'ELQuent API Upload',
'folderId': f'{shared_list}'}
response = api_request(
root, call='post', data=json.dumps(data))
sharedlist = response.json()
print(
f'\n{Fore.WHITE}» [{Fore.YELLOW}{len(contacts)}{Fore.WHITE}] {name}')
# Simple shared list creation
if response.status_code == 201:
print(f'{Fore.GREEN} [Created]', end=' ')
list_id = int(sharedlist['id'])
# Shared list already exists
else:
while True: # Asks user what to do next
if not choice:
print(f'\n{Fore.YELLOW}Shared list with that name already exist.',
f'\n{Fore.WHITE}[{Fore.YELLOW}0{Fore.WHITE}]\tStop importing to Eloqua',
f'\n{Fore.WHITE}[{Fore.YELLOW}1{Fore.WHITE}]\tAppend contacts to existing shared list')
if len(export) == 1:
print(
f'{Fore.WHITE}[{Fore.YELLOW}2{Fore.WHITE}]\tChange upload name')
print(
f'{Fore.WHITE}Enter number associated with your choice:', end='')
choice = input(' ')
if not choice or choice == '0': # Dropping import
return False
elif choice == '1' or choice == 'append': # Appending data to existing shared list
print(
f'{Fore.YELLOW} [Exists]{Fore.GREEN} » [Append]', end=' ')
list_id = sharedlist[0]['requirement']['conflictingId']
break
# Changing name and trying again
elif choice == '2' and len(export) == 1:
name_split = name.split('_')
print(
f'\n{Fore.WHITE}» Write different name ending for the shared list upload: ', end='')
ending = input(' ')
new_name = '_'.join(name_split[:4] + [ending])
new_export = {new_name: contacts}
outcome = eloqua_create_sharedlist(new_export, '')
return outcome
uri = eloqua_import_contact_definition(name, list_id)
count = eloqua_import_contacts(contacts, uri)
status = eloqua_post_sync(uri)
if status == 'success':
# Sync_id is syncedInstanceUri from sync response
import_id = (uri.split('/'))[-1]
root = eloqua_bulk + f'contacts/imports/{import_id}'
response = api_request(root, call='delete')
outcome.append((list_id, name, count, status))
return outcome
def eloqua_import_contact_definition(name, list_id):
'''
Request to obtain uri key for data upload
Requires name of import and ID of shared list
Returns uri key needed for data upload
'''
data = {'name': name,
'fields': {
'SourceCountry': '{{Contact.Field(C_Source_Country1)}}',
'EmailAddress': '{{Contact.Field(C_EmailAddress)}}'},
'identifierFieldName': 'EmailAddress',
'isSyncTriggeredOnImport': 'false',
'syncActions': {
'action': 'add',
'destination': '{{ContactList[%s]}}' % list_id}}
root = eloqua_bulk + 'contacts/imports'
response = api_request(root, call='post', data=json.dumps(data))
import_eloqua = response.json()
uri = import_eloqua['uri'][1:]
return uri
def eloqua_import_contacts(contacts, uri):
'''
Uploads contacts from ClickWebinar to Eloqua
Requires list of contacts for upload and uri key
Returns count of uploaded contacts
'''
count = 0
upload = []
record = {}
for user in contacts:
record = {'SourceCountry': source_country,
'EmailAddress': user}
upload.append(record)
count += 1
root = eloqua_bulk + uri + '/data'
api_request(root, call='post', data=json.dumps(upload))
return count
'''
=================================================================================
Upload External Activities API Flow
=================================================================================
'''
def eloqua_create_webinar_activity(attendees, activities):
'''
Requires list of attendee e-mails and list of list containg activities in format:
[E-mail, CampaignId, AssetName, AssetType, AssetDate, ActivityType]
'''
# Upload contacts to shared list for correct CLS
print(f'\n{Fore.YELLOW}» Uploading attendees')
list_id = naming[source_country]['id']['activity_shared_list']
contact_uri = eloqua_import_contact_definition(
'WKPL_ELQuent_Webinar-attendees-upload', list_id)
eloqua_import_contacts(attendees, contact_uri)
contact_status = eloqua_post_sync(contact_uri)
if contact_status == 'success':
# Sync_id is syncedInstanceUri from sync response
import_id = (contact_uri.split('/'))[-1]
root = eloqua_bulk + f'contacts/imports/{import_id}'
api_request(root, call='delete')
# Upload external activities
print(f'\n{Fore.YELLOW}» Uploading activities')
activity_uri = eloqua_import_webinar_activity_definition()
eloqua_import_webinar_activity(activities, activity_uri)
activity_status = eloqua_post_sync(activity_uri)
if activity_status == 'success':
# Sync_id is syncedInstanceUri from sync response
import_id = (activity_uri.split('/'))[-1]
root = eloqua_bulk + f'contacts/imports/{import_id}'
api_request(root, call='delete')
return
def eloqua_import_webinar_activity_definition():
'''
Returns uri key of import defininition needed for data upload
'''
data = {
'name': f'WK{source_country}_Webinar_ExternalActivityImport_ELQuent',
'fields': {
'C_EmailAddress': '{{Activity.Contact.Field(C_EmailAddress)}}',
'CampaignID': '{{Activity.Campaign.Id}}',
'AssetName': '{{Activity.Asset.Name}}',
'AssetType': '{{Activity.Asset.Type}}',
'AssetDate': '{{Activity.CreatedAt}}',
'ActivityType': '{{Activity.Type}}'
},
'updateRule': 'always',
'dataRetentionDuration': 'PT1H',
}
root = eloqua_bulk + 'activities/imports'
response = api_request(root, call='post', data=json.dumps(data))
import_eloqua = response.json()
uri = import_eloqua['uri'][1:]
return uri
def eloqua_import_webinar_activity(activities, uri):
'''
Uploads contacts from ClickWebinar to Eloqua
Requires list of contacts for upload and uri key
Returns count of uploaded contacts
'''
count = 0
upload = []
for activity in activities:
record = {
'C_EmailAddress': activity[0],
'CampaignID': activity[1],
'AssetName': activity[2],
'AssetType': activity[3],
'AssetDate': activity[4],
'ActivityType': activity[5]
}
upload.append(record)
count += 1
root = eloqua_bulk + uri + '/data'
api_request(root, call='post', data=json.dumps(upload))
return count
'''
=================================================================================
Contact Segment API
=================================================================================
'''
def eloqua_segment_refresh(segment_id):
'''
Returns segment count when segment is refreshed (string)
'''
# Post refresh queue
root = eloqua_rest + 'assets/contact/segment/queue/' + segment_id
queue = api_request(root, call='post')
queue_data = queue.json()
queued_at = queue_data['queuedAt']
# Check if queue has been resolved and segment is refreshed
root = eloqua_rest + 'assets/contact/segment/' + segment_id + '/count'
while True:
time.sleep(10)
refresh = api_request(root)
refresh_data = refresh.json()
calculated_at = refresh_data.get('lastCalculatedAt', '0')
if int(calculated_at) > int(queued_at):
break
return refresh_data['count']
'''
=================================================================================
Export Bouncebacks Activity API Flow
=================================================================================
'''
def eloqua_post_export(data, export_type):
'''
Creates definition for activity export
Requires data and type (for example 'activity')
Returns uri key needed for data download
'''
if export_type == 'activity':
endpoint = 'activities'
root = eloqua_bulk + f'{endpoint}/exports'
response = api_request(root, call='post', data=json.dumps(data))
export_eloqua = response.json()
uri = export_eloqua['uri'][1:]
return uri
'''
=================================================================================
Eloqua Sync API
=================================================================================
'''
def eloqua_post_sync(uri, return_uri=False):
'''
Requests to sync import
Checks status of sync
Requires uri key
Returns status of sync
'''
# Requests sync
root = eloqua_bulk + 'syncs'
sync_body = {'syncedInstanceUri': f'/{uri}'}
response = api_request(root, call='post', data=json.dumps(sync_body))
sync_eloqua = response.json()
# Checks stats of sync
sync_uri = sync_eloqua['uri']
status = sync_eloqua['status']
sync_counter = 1
while True:
root = eloqua_bulk + sync_uri
sync_body = {'syncedInstanceUri': f'/{sync_uri}'}
response = api_request(root)
sync_status = response.json()
status = sync_status['status']
print(f'{Fore.BLUE}{status}/', end='', flush=True)
if status in ['warning', 'error', 'success']:
eloqua_log_sync(sync_uri)
break
time.sleep(5 * sync_counter)
sync_counter += 1
if return_uri:
return sync_uri
return status
def eloqua_log_sync(sync_uri):
'''
Shows log for problematic sync
Requires uri key to get id of sync
Returns logs of sync
'''
print(f'{Fore.WHITE}{sync_uri[1:]}')
sync_id = (sync_uri.split('/'))[-1]
root = eloqua_bulk + f'syncs/{sync_id}/logs'
response = api_request(root)
logs_eloqua = response.json()
for item in logs_eloqua['items']:
if item['severity'] == 'warning':
print(f'\t{Fore.YELLOW}› {item["count"]} {item["message"]}')
if item['message'] in ['Contacts created.', 'Contacts updated.']:
print(f'\t{Fore.GREEN}› {item["count"]} {item["message"]}')
return logs_eloqua
def eloqua_sync_data(sync_uri):
'''
Returns json of data from response
'''
offset = 0
response = []
while True:
root = eloqua_bulk + f'{sync_uri}/data'
params = {'limit': '50000',
'offset': str(offset)}
partial_response = api_request(root, params=params)
partial_response = partial_response.json()
if partial_response['totalResults'] > 0:
response.extend(partial_response['items'])
if not partial_response['hasMore']:
break
offset += 50000
return response
'''
=================================================================================
Landing Page API
=================================================================================
'''
def eloqua_create_landingpage(name, code):
'''
Requires name and code of the landing page to create LP in Eloqua
Returns Landing Page ID, eloqua asset url and direct url
'''
# Adds source contry to received asset name
name = f'WK{source_country}_{name}'
# Checks if there already is LP with that name
eloqua_asset_exist(name, asset='landingPage')
# Chosses correct folder ID for upload
segment = name.split('_')[1]
folder_id = naming[source_country]['id']['landingpage'].get(segment)
# Creates correct html_name
html_name = eloqua_asset_html_name(name)
# Gets id and url of microsite
microsite_id = naming[source_country]['id']['microsite'][0]
microsite_link = naming[source_country]['id']['microsite'][1]
while True:
# Creating a post call to Eloqua API
root = f'{eloqua_rest}assets/landingPage'
data = {
'name': name, # asset name
'description': 'ELQuent API Upload',
'folderId': folder_id,
'micrositeId': microsite_id, # html name domain
'relativePath': f'/{html_name}', # html name path
'htmlContent': {
'type': 'RawHtmlContent',
'html': code
}
}
response = api_request(
root, call='post', data=json.dumps(data))
landing_page = response.json()
# Checks if there is error
if isinstance(landing_page, list)\
and len(landing_page) == 1\
and landing_page[0]['type'] == 'ObjectValidationError'\
and landing_page[0]['property'] == 'relativePath'\
and landing_page[0]['requirement']['type'] == 'UniquenessRequirement':
print(
f'\n {ERROR}URL ending "/{html_name}" already exists!',
f'\n {Fore.WHITE}» Enter new URL ending:', end='')
html_name = input(' ')
if not html_name:
html_name = pyperclip.paste()
continue
elif isinstance(landing_page, list): # Other errors
print(f'{Fore.YELLOW}{landing_page}')
elif landing_page['type'] == 'LandingPage':
break
else: # Weird cases
print(f'{Fore.YELLOW}{landing_page}')
# Open in new tab
lp_id = landing_page['id']
asset_url = naming['root'] + '#landing_pages&id=' + lp_id
direct_url = microsite_link + landing_page['relativePath']
print(f'{Fore.WHITE}» {SUCCESS}Created Eloqua Landing Page ID: {lp_id}')
webbrowser.open(asset_url, new=2, autoraise=False)
return (lp_id, asset_url, direct_url)
def eloqua_put_landingpage(lp_id, data):
'''
Requires id and data of the landing page to update LP in Eloqua
Returns success bool
'''
# Creating a put call to Eloqua API
root = f'{eloqua_rest}assets/landingPage/{lp_id}'
response = api_request(
root, call='put', data=json.dumps(data))
landing_page = response.json()
# Checks if there is error
if isinstance(landing_page, list) or landing_page['type'] != 'LandingPage':
print(f'{Fore.YELLOW}{landing_page}')
return False
return True
'''
=================================================================================
SharedFilter API
=================================================================================
'''
def eloqua_create_filter(name, data):
'''
Requires name and json data of the shared filter to create it in Eloqua
Returns Filter ID and response of created filter
'''
# Checks if there already is Form with that name
eloqua_asset_exist(name, asset='sharedFilter')
# Creating a post call to Eloqua API
root = f'{eloqua_rest}assets/contact/filter'
response = api_request(
root, call='post', data=json.dumps(data))
sharedfilter = response.json()
# Open in new tab
sharedfilter_id = sharedfilter['id']
print(f'{Fore.WHITE}» {SUCCESS}Created Eloqua Filter ID: {sharedfilter_id}')
return (sharedfilter_id, sharedfilter)
'''
=================================================================================
Form API
=================================================================================
'''
def eloqua_get_form_data(form_id):
'''
Returns form data of Form with given ID
'''
all_fills = []
page = 1
while True:
# Gets fills of requested form
root = f'{eloqua_rest}data/form/{form_id}'
params = {'depth': 'complete',
'count': '100',
'page': page}
response = api_request(root, params=params)
fills = response.json()
all_fills.extend(fills['elements'])
# Stops iteration when full list is obtained
if fills['total'] - page * int(params.get('count')) < 0:
break
# Increments page to get next part of outcomes
page += 1
return (all_fills, fills['total'])
def eloqua_create_form(name, data):
'''
Requires name and json data of the form to create it in Eloqua
Returns Form ID and response of created form
'''
# Checks if there already is Form with that name
eloqua_asset_exist(name, asset='form')
# Creating a post call to Eloqua API
root = f'{eloqua_rest}assets/form'
response = api_request(
root, call='post', data=json.dumps(data))
form = response.json()
# Open in new tab