/
extensions.py
1997 lines (1667 loc) · 81.1 KB
/
extensions.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
from datetime import datetime
from bingads.v13.internal.bulk.string_table import _StringTable
import re
import json
from bingads.service_client import _CAMPAIGN_OBJECT_FACTORY_V13, _CAMPAIGN_MANAGEMENT_SERVICE_V13
target_setting_detail_pattern=r'^(Age|Audience|CompanyName|Gender|Industry|JobFunction)$'
DELETE_VALUE = "delete_value"
_BULK_DATETIME_FORMAT = '%m/%d/%Y %H:%M:%S'
_BULK_DATETIME_FORMAT_2 = '%m/%d/%Y %H:%M:%S.%f'
_BULK_DATE_FORMAT = "%m/%d/%Y"
url_splitter = r';\s*(?=https?://)'
custom_param_splitter = r'(?<!\\);\s*'
custom_param_pattern = r'^\{_(.*?)\}=(.*$)'
combine_rule_pattern = r'^(And|Or|Not)\(([\d|\s|,]*?)\)$'
BudgetLimitType = _CAMPAIGN_OBJECT_FACTORY_V13.create('BudgetLimitType')
DynamicSearchAdsSetting = _CAMPAIGN_OBJECT_FACTORY_V13.create('DynamicSearchAdsSetting')
Webpage = _CAMPAIGN_OBJECT_FACTORY_V13.create('Webpage')
WebpageConditionOperand = _CAMPAIGN_OBJECT_FACTORY_V13.create('WebpageConditionOperand')
RemarketingRule = _CAMPAIGN_OBJECT_FACTORY_V13.create('RemarketingRule')
PageVisitorsRule = _CAMPAIGN_OBJECT_FACTORY_V13.create('PageVisitorsRule')
PageVisitorsWhoVisitedAnotherPageRule = _CAMPAIGN_OBJECT_FACTORY_V13.create('PageVisitorsWhoVisitedAnotherPageRule')
PageVisitorsWhoDidNotVisitAnotherPageRule = _CAMPAIGN_OBJECT_FACTORY_V13.create('PageVisitorsWhoDidNotVisitAnotherPageRule')
CustomEventsRule = _CAMPAIGN_OBJECT_FACTORY_V13.create('CustomEventsRule')
StringOperator = _CAMPAIGN_OBJECT_FACTORY_V13.create('StringOperator')
NumberOperator = _CAMPAIGN_OBJECT_FACTORY_V13.create('NumberOperator')
NormalForm = _CAMPAIGN_OBJECT_FACTORY_V13.create('NormalForm')
AudienceCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('AudienceCriterion')
BidMultiplier = _CAMPAIGN_OBJECT_FACTORY_V13.create('BidMultiplier')
CashbackAdjustment = _CAMPAIGN_OBJECT_FACTORY_V13.create('CashbackAdjustment')
AgeCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('AgeCriterion')
DayTimeCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('DayTimeCriterion')
DeviceCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('DeviceCriterion')
GenderCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('GenderCriterion')
HotelAdvanceBookingWindowCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('HotelAdvanceBookingWindowCriterion')
HotelCheckInDateCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('HotelCheckInDateCriterion')
HotelCheckInDayCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('HotelCheckInDayCriterion')
HotelDateSelectionTypeCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('HotelDateSelectionTypeCriterion')
HotelLengthOfStayCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('HotelLengthOfStayCriterion')
LocationCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('LocationCriterion')
LocationIntentCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('LocationIntentCriterion')
RadiusCriterion = _CAMPAIGN_OBJECT_FACTORY_V13.create('RadiusCriterion')
TargetSetting_Type = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('TargetSetting'))
HotelSetting_Type = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('HotelSetting'))
CoOpSetting_Type = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('CoOpSetting'))
TextAsset_Type = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('TextAsset'))
ImageAsset_Type = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ImageAsset'))
VideoAsset_Type = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('VideoAsset'))
KeyValuePairOfstringstring = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ns1:KeyValuePairOfstringstring'))
ArrayOfKeyValuePairOfstringstring = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ns1:ArrayOfKeyValuePairOfstringstring'))
ArrayOfArrayOfKeyValuePairOfstringstring = type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ns1:ArrayOfArrayOfKeyValuePairOfstringstring'))
def bulk_str(value):
if value is None or (hasattr(value, 'value') and value.value is None):
return None
if isinstance(value, str):
return value
return str(value)
def bulk_upper_str(value):
s = bulk_str(value)
if s is None:
return None
return s.upper()
def to_verified_tracking_setting_string(value):
if value is None:
return None
result = []
for s in value:
contracts = []
for setting in s:
if setting is not None and setting.__contains__('key') and setting.__contains__('value'):
contract = {}
contract['key'] = setting['key']
contract['value'] = setting['value']
contracts.append(contract)
result.append(contracts)
return json.dumps(result)
def parse_verified_tracking_setting(str):
if str is None or str == '':
return
two_dims_array = []
results = json.loads(str)
for result in results:
array = []
for res in result:
if res is not None and res.__contains__('key') and res.__contains__('value'):
kv = KeyValuePairOfstringstring()
kv['key'] = res['key']
kv['value'] = res['value']
array.append(kv)
two_dims_array.append(array)
return two_dims_array
def bulk_date_str(value):
if value is None or (value.Day is None and value.Month is None and value.Year is None):
return None
return '{0!s}/{1!s}/{2!s}'.format(value.Month, value.Day, value.Year)
def bulk_datetime_str(value):
if value is None:
return None
return value.strftime(_BULK_DATETIME_FORMAT)
def csv_to_field_Date(entity, property_name, value):
date = parse_date(value)
if date is not None:
setattr(entity, property_name, date)
def _is_daily_budget(budget_type):
if budget_type.lower() == 'DailyBudgetAccelerated'.lower() \
or budget_type.lower() == 'DailyBudgetStandard'.lower():
return True
else:
return False
def csv_to_budget(row_values, bulk_campaign):
success, budget_type = row_values.try_get_value(_StringTable.BudgetType)
if not success or not budget_type:
return
success, budget_row_value = row_values.try_get_value(_StringTable.Budget)
if not success:
return
budget_value = float(budget_row_value) if budget_row_value else None
bulk_campaign.campaign.BudgetType = budget_type
bulk_campaign.campaign.DailyBudget = budget_value
def budget_to_csv(bulk_campaign, row_values):
budget_type = bulk_campaign.campaign.BudgetType
if not budget_type:
return
row_values[_StringTable.Budget] = bulk_str(bulk_campaign.campaign.DailyBudget)
def csv_to_bid_strategy_biddingscheme(row_values, bulk_bid_strategy):
entity_csv_to_biddingscheme(row_values, bulk_bid_strategy.bid_strategy)
def csv_to_campaign_biddingscheme(row_values, bulk_campaign):
entity_csv_to_biddingscheme(row_values, bulk_campaign.campaign)
def entity_csv_to_biddingscheme(row_values, entity):
success, bid_strategy_type = row_values.try_get_value(_StringTable.BidStrategyType)
if not success or not bid_strategy_type:
return
csv_to_field_BidStrategyType(entity, bid_strategy_type)
success, max_cpc_row_value = row_values.try_get_value(_StringTable.BidStrategyMaxCpc)
max_cpc_value = parse_bid(max_cpc_row_value)
success, target_cpa_row_value = row_values.try_get_value(_StringTable.BidStrategyTargetCpa)
target_cpa_value = float(target_cpa_row_value) if target_cpa_row_value else None
success, target_roas_row_value = row_values.try_get_value(_StringTable.BidStrategyTargetRoas)
target_roas_value = float(target_roas_row_value) if target_roas_row_value else None
success, target_impression_share_row_value = row_values.try_get_value(_StringTable.BidStrategyTargetImpressionShare)
target_impression_share_value = float(target_impression_share_row_value) if target_impression_share_row_value else None
success, commission_rate_row_value = row_values.try_get_value(_StringTable.BidStrategyCommissionRate)
commission_rate_value = float(commission_rate_row_value) if commission_rate_row_value else None
success, max_percent_cpc_row_value = row_values.try_get_value(_StringTable.BidStrategyPercentMaxCpc)
max_percent_cpc_value = float(max_percent_cpc_row_value) if max_percent_cpc_row_value else None
success, target_ad_position_value = row_values.try_get_value(_StringTable.BidStrategyTargetAdPosition)
if bid_strategy_type == 'MaxConversions':
entity.BiddingScheme.MaxCpc = max_cpc_value
entity.BiddingScheme.TargetCpa = target_cpa_value
entity.BiddingScheme.Type = "MaxConversions"
elif bid_strategy_type == 'MaxClicks':
entity.BiddingScheme.MaxCpc = max_cpc_value
entity.BiddingScheme.Type = "MaxClicks"
elif bid_strategy_type == 'TargetCpa':
entity.BiddingScheme.MaxCpc = max_cpc_value
entity.BiddingScheme.Type = "TargetCpa"
entity.BiddingScheme.TargetCpa = target_cpa_value
elif bid_strategy_type == 'TargetRoas':
entity.BiddingScheme.MaxCpc = max_cpc_value
entity.BiddingScheme.Type = "TargetRoas"
entity.BiddingScheme.TargetRoas = target_roas_value
elif bid_strategy_type == 'MaxConversionValue':
entity.BiddingScheme.Type = "MaxConversionValue"
entity.BiddingScheme.TargetRoas = target_roas_value
elif bid_strategy_type == 'TargetImpressionShare':
entity.BiddingScheme.Type = "TargetImpressionShare"
entity.BiddingScheme.MaxCpc = max_cpc_value
entity.BiddingScheme.TargetImpressionShare = target_impression_share_value
entity.BiddingScheme.TargetAdPosition = target_ad_position_value
elif bid_strategy_type == "PercentCpc":
entity.BiddingScheme.MaxPercentCpc = max_percent_cpc_value
entity.BiddingScheme.Type = "PercentCpc"
elif bid_strategy_type == "Commission":
entity.BiddingScheme.MaxPercentCpc = commission_rate_value
entity.BiddingScheme.Type = "Commission"
def bid_strategy_biddingscheme_to_csv(bulk_bid_strategy, row_values):
entity_biddingscheme_to_csv(bulk_bid_strategy.bid_strategy, row_values)
def campaign_biddingscheme_to_csv(bulk_campaign, row_values):
entity_biddingscheme_to_csv(bulk_campaign.campaign, row_values)
def entity_biddingscheme_to_csv(entity, row_values):
if not entity:
return
bid_strategy_type = field_to_csv_BidStrategyType(entity)
if not bid_strategy_type:
return
row_values[_StringTable.BidStrategyType] = bid_strategy_type
if bid_strategy_type == 'MaxConversions':
row_values[_StringTable.BidStrategyMaxCpc] = bid_bulk_str(entity.BiddingScheme.MaxCpc, entity.Id)
row_values[_StringTable.BidStrategyTargetCpa] = bulk_str(entity.BiddingScheme.TargetCpa)
elif bid_strategy_type == 'MaxClicks':
row_values[_StringTable.BidStrategyMaxCpc] = bid_bulk_str(entity.BiddingScheme.MaxCpc, entity.Id)
elif bid_strategy_type == 'TargetCpa':
row_values[_StringTable.BidStrategyMaxCpc] = bid_bulk_str(entity.BiddingScheme.MaxCpc, entity.Id)
row_values[_StringTable.BidStrategyTargetCpa] = bulk_str(entity.BiddingScheme.TargetCpa)
elif bid_strategy_type == 'MaxConversionValue':
row_values[_StringTable.BidStrategyTargetRoas] = bulk_str(entity.BiddingScheme.TargetRoas)
elif bid_strategy_type == 'TargetRoas':
row_values[_StringTable.BidStrategyTargetRoas] = bulk_str(entity.BiddingScheme.TargetRoas)
row_values[_StringTable.BidStrategyMaxCpc] = bid_bulk_str(entity.BiddingScheme.MaxCpc, entity.Id)
elif bid_strategy_type == 'TargetImpressionShare':
row_values[_StringTable.BidStrategyMaxCpc] = bid_bulk_str(entity.BiddingScheme.MaxCpc, entity.Id)
row_values[_StringTable.BidStrategyTargetAdPosition] = bulk_optional_str(entity.BiddingScheme.TargetAdPosition, entity.Id)
row_values[_StringTable.TargetImpressionShare] = TargetImpressionShare(entity.BiddingScheme.TargetImpressionShare)
elif bid_strategy_type == 'PercentCpc':
row_values[_StringTable.BidStrategyPercentMaxCpc] = bulk_str(entity.BiddingScheme.MaxPercentCpc)
elif bid_strategy_type == 'Commission':
row_values[_StringTable.BidStrategyCommissionRate] = bulk_str(entity.BiddingScheme.CommissionRate)
def bulk_optional_str(value, id):
if value is None:
return None
if not value and id is not None and id > 0:
return DELETE_VALUE
return value
def csv_to_status(c, v):
if v == 'Expired':
c.ad_group.Status = 'Expired'
c._is_expired = True
else:
c.ad_group.Status = v if v else None
def bulk_device_preference_str(value):
if value is None:
return None
elif value == 0:
return "All"
elif value == 30001:
return "Mobile"
else:
raise ValueError("Unknown device preference")
def parse_datetime(dt_str):
""" Convert the datetime str to datetime object.
:param dt_str: The string representing a datetime object.
:type dt_str: str
:return: The datetime object parsed from the string.
:rtype: datetime | None
"""
if not dt_str or dt_str == DELETE_VALUE:
return None
try:
return datetime.strptime(dt_str, _BULK_DATETIME_FORMAT)
except Exception:
return datetime.strptime(dt_str, _BULK_DATETIME_FORMAT_2)
def parse_date(d_str):
if not d_str or d_str == DELETE_VALUE:
return None
parsed_date = datetime.strptime(d_str, _BULK_DATE_FORMAT)
bing_ads_date = _CAMPAIGN_OBJECT_FACTORY_V13.create('Date')
bing_ads_date.Day = parsed_date.day
bing_ads_date.Month = parsed_date.month
bing_ads_date.Year = parsed_date.year
return bing_ads_date
def parse_device_preference(value):
if not value:
return None
if value.lower() == 'all':
return 0
elif value.lower() == "mobile":
return 30001
else:
return None
def field_to_csv_AudienceIds(entity):
audience_ids = entity.audience_ids
if audience_ids is None or len(audience_ids) == 0:
return None
return ';'.join(str(audience_id) for audience_id in audience_ids)
def csv_to_field_AudienceIds(entity, value):
if value is None or value.strip() == '':
return
entity.audience_ids = [None if i == 'None' else int(i) for i in value.split(';')]
def field_to_csv_AgeRanges(entity):
age_ranges = entity.age_ranges
if age_ranges is None or len(age_ranges) == 0:
return None
return ';'.join(age_range for age_range in age_ranges)
def csv_to_field_AgeRanges(entity, value):
if value is None or value.strip() == '':
return
entity.age_ranges = [None if i == 'None' else i for i in value.split(';')]
def field_to_csv_GenderTypes(entity):
gender_types = entity.gender_types
if gender_types is None or len(gender_types) == 0:
return None
return ';'.join(gender_type for gender_type in gender_types)
def csv_to_field_GenderTypes(entity, value):
if value is None or value.strip() == '':
return
entity.gender_types = [None if i == 'None' else i for i in value.split(';')]
def field_to_csv_MediaIds(entity):
"""
MediaIds field to csv content
:param entity: entity which has MediaIds attribute
:return:
"""
# media_ids? "ns4:ArrayOflong"
media_ids = entity.ImageMediaIds
if media_ids is None or len(media_ids) == 0:
return None
return ';'.join(str(media_id) for media_id in media_ids)
def csv_to_field_MediaIds(entity, value):
"""
MediaIds csv to entity
:param entity:
:return:
"""
if value is None or value.strip() == '':
return
entity.ImageMediaIds = [None if i == 'None' else int(i) for i in value.split(';')]
# None and empty string will set to empty string
def escape_parameter_text(s):
return '' if not s else s.replace('\\', '\\\\').replace(';', '\\;')
def unescape_parameter_text(s):
return '' if not s else s.replace('\\\\', '\\').replace('\\;', ';')
def field_to_csv_UrlCustomParameters(entity):
"""
transfer the CustomParameters of a entity to csv content (string)
:param entity: the entity which contains UrlCustomparameters attribute
:return: csv string content
"""
if entity is None or entity.UrlCustomParameters is None:
return None
if entity.UrlCustomParameters.Parameters is None or entity.UrlCustomParameters.Parameters.CustomParameter is None:
return DELETE_VALUE if entity.Id and entity.Id > 0 else None
# The default case when entity created
if len(entity.UrlCustomParameters.Parameters.CustomParameter) == 0:
return None
params = []
for parameter in entity.UrlCustomParameters.Parameters.CustomParameter:
params.append('{{_{0}}}={1}'.format(parameter.Key, escape_parameter_text(parameter.Value)))
return '; '.join(params)
def dict_bulk_str(parameters, separator):
if parameters is None or len(parameters) == 0:
return None
return separator.join(["{0}={1}".format(key, parameters[key]) for key in parameters])
def parse_dict(value):
if value is None or value.strip() == '':
return
return dict([s.split('=') for s in value.split(';') if len(s) > 0])
pass
def multi_bulk_str(parameters, separator):
if parameters is None or len(parameters) == 0:
return None
return separator.join(parameters)
def parse_multi(value):
if value is None or value.strip() == '':
return
return value.split(';')
def csv_to_field_UrlCustomParameters(entity, value):
if value is None or value.strip() == '':
return
splitter = re.compile(custom_param_splitter)
pattern = re.compile(custom_param_pattern)
params = []
param_strs = splitter.split(value)
for param_str in param_strs:
match = pattern.match(param_str)
if match:
custom_parameter = _CAMPAIGN_OBJECT_FACTORY_V13.create("CustomParameter")
custom_parameter.Key = match.group(1)
custom_parameter.Value = unescape_parameter_text(match.group(2))
params.append(custom_parameter)
if len(params) > 0:
entity.UrlCustomParameters.Parameters.CustomParameter = params
def csv_to_field_Urls(entity, value):
"""
set FinalUrls / FinalMobileUrls string field
:param entity: FinalUrls / FinalMobileUrls
:param value: the content in csv
:return:set field values
"""
if value is None or value == '':
return
splitter = re.compile(url_splitter)
entity.string = splitter.split(value)
def field_to_csv_Urls(entity, id):
"""
parse entity to csv content
:param entity: FinalUrls / FinalMobileUrls
:return: csv content
"""
if entity is None:
return None
if entity.string is None:
return DELETE_VALUE if id and id > 0 else None
if len(entity.string) == 0:
return None
return '; '.join(entity.string)
def csv_to_field_CampaignLanguages(entity, value):
"""
set Languages string field
:param entity: Languages
:param value: the content in csv
:return:set field values
"""
if value is None or value == '':
return
splitter = re.compile(r';')
entity.string = splitter.split(value)
def field_to_csv_CampaignLanguages(entity):
"""
parse entity to csv content
:param entity: Languages
:return: csv content
"""
if entity is None or entity.string is None:
return None
if len(entity.string) == 0:
return None
return ';'.join(entity.string)
def field_to_csv_BidStrategyType(entity):
"""
parse entity to csv content
:param entity: entity which has BiddingScheme attribute
:return: csv content
"""
if entity.BiddingScheme is None or type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('BiddingScheme')):
return None
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('EnhancedCpcBiddingScheme')):
return 'EnhancedCpc'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('InheritFromParentBiddingScheme')):
return 'InheritFromParent'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('MaxConversionsBiddingScheme')):
return 'MaxConversions'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpcBiddingScheme')):
return 'ManualCpc'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpmBiddingScheme')):
return 'ManualCpcm'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpvBiddingScheme')):
return 'ManualCpv'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('TargetCpaBiddingScheme')):
return 'TargetCpa'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('MaxClicksBiddingScheme')):
return 'MaxClicks'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('MaxConversionValueBiddingScheme')):
return 'MaxConversionValue'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('TargetRoasBiddingScheme')):
return 'TargetRoas'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('TargetImpressionShareBiddingScheme')):
return 'TargetImpressionShare'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('MaxRoasBiddingScheme')):
return 'MaxRoas'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('PercentCpcBiddingScheme')):
return 'PercentCpc'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('CommissionBiddingScheme')):
return 'Commission'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpaBiddingScheme')):
return 'ManualCpa'
elif type(entity.BiddingScheme) == type(_CAMPAIGN_OBJECT_FACTORY_V13.create('CostPerSaleBiddingScheme')):
return 'CostPerSale'
else:
raise TypeError('Unsupported Bid Strategy Type')
def csv_to_field_BidStrategyType(entity, value):
"""
set BiddingScheme
:param entity: entity which has BiddingScheme attribute
:param value: the content in csv
:return:
"""
if value is None or value == '':
return
elif value == 'EnhancedCpc':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('EnhancedCpcBiddingScheme')
elif value == 'InheritFromParent':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('InheritFromParentBiddingScheme')
elif value == 'MaxConversions':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('MaxConversionsBiddingScheme')
elif value == 'ManualCpc':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpcBiddingScheme')
elif value == 'ManualCpm':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpmBiddingScheme')
elif value == 'ManualCpv':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpvBiddingScheme')
elif value == 'TargetCpa':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('TargetCpaBiddingScheme')
elif value == 'MaxClicks':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('MaxClicksBiddingScheme')
elif value == 'MaxConversionValue':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('MaxConversionValueBiddingScheme')
elif value == 'TargetRoas':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('TargetRoasBiddingScheme')
elif value == 'TargetImpressionShare':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('TargetImpressionShareBiddingScheme')
elif value == 'MaxRoas':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('MaxRoasBiddingScheme')
elif value == 'PercentCpc':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('PercentCpcBiddingScheme')
elif value == 'Commission':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('CommissionBiddingScheme')
elif value == 'ManualCpa':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('ManualCpaBiddingScheme')
elif value == 'CostPerSale':
entity.BiddingScheme = _CAMPAIGN_OBJECT_FACTORY_V13.create('CostPerSaleBiddingScheme')
else:
return None
entity.BiddingScheme.Type = value
def csv_to_field_delimited_strings(entity, value):
if value is not None and value != '':
entity.string = value.split(';')
def field_to_csv_delimited_strings(entity):
if entity is not None and entity.string is not None and len(entity.string) > 0:
return ';'.join(entity.string)
return None
def field_to_csv_VideoAssetLinks(assetLinks):
if assetLinks is None or assetLinks.AssetLink is None:
return None
assetLinkContracts = []
for assetLink in assetLinks.AssetLink:
if assetLink.Asset is not None and isinstance(assetLink.Asset, VideoAsset_Type):
contract = {}
contract['assetPerformanceLabel'] = assetLink.AssetPerformanceLabel if hasattr(assetLink, 'AssetPerformanceLabel') else None
contract['editorialStatus'] = assetLink.EditorialStatus if hasattr(assetLink, 'EditorialStatus') else None
contract['id'] = assetLink.Asset.Id if hasattr(assetLink.Asset, 'Id') else None
contract['name'] = assetLink.Asset.Name if hasattr(assetLink.Asset, 'Name') else None
contract['pinnedField'] = assetLink.PinnedField if hasattr(assetLink, 'PinnedField') else None
contract['subType'] = assetLink.Asset.SubType if hasattr(assetLink.Asset, 'SubType') else None
thumbnailImage = assetLink.Asset.ThumbnailImage if hasattr(assetLink.Asset, 'ThumbnailImage') else None
if thumbnailImage != None:
contract['thumbnailImage'] = {}
contract['thumbnailImage']['id'] = thumbnailImage.Id
contract['thumbnailImage']['name'] = thumbnailImage.Name
contract['thumbnailImage']['type'] = thumbnailImage.Type
contract['thumbnailImage']['subType'] = thumbnailImage.SubType
contract['thumbnailImage']['cropX'] = thumbnailImage.CropX
contract['thumbnailImage']['cropY'] = thumbnailImage.CropY
contract['thumbnailImage']['cropWidth'] = thumbnailImage.CropWidth
contract['thumbnailImage']['cropHeight'] = thumbnailImage.CropHeight
assetLinkContracts.append(contract)
if len(assetLinkContracts) > 0:
return json.dumps(assetLinkContracts, sort_keys = True)
return None
pass
def csv_to_field_VideoAssetLinks(assetLinks, value):
if value is None or value == '':
return
assetLinkContracts = json.loads(value)
for assetLinkContract in assetLinkContracts:
asset_link = _CAMPAIGN_OBJECT_FACTORY_V13.create('AssetLink')
asset_link.Asset = _CAMPAIGN_OBJECT_FACTORY_V13.create('VideoAsset')
asset_link.Asset.Type = 'VideoAsset'
asset_link.Asset.Id = assetLinkContract.get('id')
asset_link.Asset.Name = assetLinkContract.get('name')
asset_link.Asset.SubType = assetLinkContract.get('subType')
asset_link.AssetPerformanceLabel = assetLinkContract.get('assetPerformanceLabel')
asset_link.PinnedField = assetLinkContract.get('pinnedField')
asset_link.EditorialStatus = assetLinkContract.get('editorialStatus')
thumbnailImageContract = assetLinkContract.get('thumbnailImage')
if thumbnailImageContract != None :
asset_link.Asset.ThumbnailImage = _CAMPAIGN_OBJECT_FACTORY_V13.create('ImageAsset')
asset_link.Asset.ThumbnailImage.Type = 'ImageAsset'
asset_link.Asset.ThumbnailImage.Id = thumbnailImageContract.get('id')
asset_link.Asset.ThumbnailImage.Name = thumbnailImageContract.get('name')
asset_link.Asset.ThumbnailImage.SubType = thumbnailImageContract.get('subType')
asset_link.Asset.ThumbnailImage.CropX = thumbnailImageContract.get('cropX')
asset_link.Asset.ThumbnailImage.CropY = thumbnailImageContract.get('cropY')
asset_link.Asset.ThumbnailImage.CropWidth = thumbnailImageContract.get('cropWidth')
asset_link.Asset.ThumbnailImage.CropHeight = thumbnailImageContract.get('cropHeight')
assetLinks.AssetLink.append(asset_link)
def csv_to_field_TextAssetLinks(assetLinks, value):
if value is None or value == '':
return
assetLinkContracts = json.loads(value)
for assetLinkContract in assetLinkContracts:
asset_link = _CAMPAIGN_OBJECT_FACTORY_V13.create('AssetLink')
asset_link.Asset = _CAMPAIGN_OBJECT_FACTORY_V13.create('TextAsset')
asset_link.Asset.Type = 'TextAsset'
asset_link.Asset.Id = assetLinkContract.get('id')
asset_link.Asset.Text = assetLinkContract.get('text')
asset_link.Asset.Name = assetLinkContract.get('name')
asset_link.AssetPerformanceLabel = assetLinkContract.get('assetPerformanceLabel')
asset_link.PinnedField = assetLinkContract.get('pinnedField')
asset_link.EditorialStatus = assetLinkContract.get('editorialStatus')
assetLinks.AssetLink.append(asset_link)
def field_to_csv_ImageAssetLinks(entity):
if entity is None or entity.AssetLink is None:
return None
assetLinkContracts = []
for assetLink in entity.AssetLink:
if assetLink.Asset is not None and isinstance(assetLink.Asset, ImageAsset_Type):
contract = {}
contract['cropHeight'] = assetLink.Asset.CropHeight if hasattr(assetLink.Asset, 'CropHeight') else None
contract['cropWidth'] = assetLink.Asset.CropWidth if hasattr(assetLink.Asset, 'CropWidth') else None
contract['cropX'] = assetLink.Asset.CropX if hasattr(assetLink.Asset, 'CropX') else None
contract['cropY'] = assetLink.Asset.CropY if hasattr(assetLink.Asset, 'CropY') else None
contract['id'] = assetLink.Asset.Id if hasattr(assetLink.Asset, 'Id') else None
contract['name'] = assetLink.Asset.Name if hasattr(assetLink.Asset, 'Name') else None
contract['assetPerformanceLabel'] = assetLink.AssetPerformanceLabel if hasattr(assetLink, 'AssetPerformanceLabel') else None
contract['editorialStatus'] = assetLink.EditorialStatus if hasattr(assetLink, 'EditorialStatus') else None
contract['pinnedField'] = assetLink.PinnedField if hasattr(assetLink, 'PinnedField') else None
assetLinkContracts.append(contract)
if len(assetLinkContracts) > 0:
return json.dumps(assetLinkContracts)
return None
def csv_to_field_ImageAssetLinks(assetLinks, value):
if value is None or value == '':
return
assetLinkContracts = json.loads(value)
for assetLinkContract in assetLinkContracts:
asset_link = _CAMPAIGN_OBJECT_FACTORY_V13.create('AssetLink')
asset_link.Asset = _CAMPAIGN_OBJECT_FACTORY_V13.create('ImageAsset')
asset_link.Asset.Type = 'ImageAsset'
asset_link.Asset.CropHeight = assetLinkContract.get('cropHeight')
asset_link.Asset.CropWidth = assetLinkContract.get('cropWidth')
asset_link.Asset.CropX = assetLinkContract.get('cropX')
asset_link.Asset.CropY = assetLinkContract.get('cropY')
asset_link.Asset.Id = assetLinkContract.get('id')
asset_link.Asset.Name = assetLinkContract.get('name')
asset_link.AssetPerformanceLabel = assetLinkContract.get('assetPerformanceLabel')
asset_link.PinnedField = assetLinkContract.get('pinnedField')
asset_link.EditorialStatus = assetLinkContract.get('editorialStatus')
assetLinks.AssetLink.append(asset_link)
def field_to_csv_TextAssetLinks(entity):
if entity is None or entity.AssetLink is None:
return None
assetLinkContracts = []
for assetLink in entity.AssetLink:
if assetLink.Asset is not None and isinstance(assetLink.Asset, TextAsset_Type):
contract = {}
contract['id'] = assetLink.Asset.Id if hasattr(assetLink.Asset, 'Id') else None
contract['name'] = assetLink.Asset.Name if hasattr(assetLink.Asset, 'Name') else None
contract['text'] = assetLink.Asset.Text if hasattr(assetLink.Asset, 'Text') else None
contract['assetPerformanceLabel'] = assetLink.AssetPerformanceLabel if hasattr(assetLink, 'AssetPerformanceLabel') else None
contract['editorialStatus'] = assetLink.EditorialStatus if hasattr(assetLink, 'EditorialStatus') else None
contract['pinnedField'] = assetLink.PinnedField if hasattr(assetLink, 'PinnedField') else None
assetLinkContracts.append(contract)
if len(assetLinkContracts) > 0:
return json.dumps(assetLinkContracts, sort_keys = True)
return None
def ad_rotation_bulk_str(value, id):
if value is None:
return None
elif value.Type is None:
return DELETE_VALUE if id and id > 0 else None
else:
return bulk_str(value.Type)
def parse_ad_rotation(value):
if not value:
return None
ad_rotation = _CAMPAIGN_OBJECT_FACTORY_V13.create('AdRotation')
ad_rotation.Type = None if value == DELETE_VALUE else value
return ad_rotation
def parse_ad_group_bid(value):
if not value:
return None
bid = _CAMPAIGN_OBJECT_FACTORY_V13.create('Bid')
bid.Amount = float(value)
return bid
def ad_group_bid_bulk_str(value):
if value is None or value.Amount is None:
return None
return bulk_str(value.Amount)
def keyword_bid_bulk_str(value, id):
if value is None:
return DELETE_VALUE if id and id > 0 else None
if value.Amount is None:
return None
return bulk_str(value.Amount)
def parse_keyword_bid(value):
bid = _CAMPAIGN_OBJECT_FACTORY_V13.create('Bid')
if not value or value == DELETE_VALUE:
bid.Amount = None
else:
bid.Amount = float(value)
return bid
def bid_bulk_str(value, id):
if value is None:
return DELETE_VALUE if id and id > 0 else None
if value.Amount is None:
return None
return bulk_str(value.Amount)
def parse_bid(value):
bid = _CAMPAIGN_OBJECT_FACTORY_V13.create('Bid')
if not value:
bid.Amount = None
else:
bid.Amount = float(value)
return bid
def minute_bulk_str(value):
if value == 'Zero':
return '0'
elif value == 'Fifteen':
return '15'
elif value == 'Thirty':
return '30'
elif value == 'FortyFive':
return '45'
else:
raise ValueError('Unknown minute')
def parse_fixed_bid(value):
if not value:
return None
fixed_bid = _CAMPAIGN_OBJECT_FACTORY_V13.create('FixedBid')
fixed_bid.Amount = float(value)
return fixed_bid
def fixed_bid_bulk_str(value):
if value is None or not hasattr(value, 'Amount') or value.Amount is None:
return None
return bulk_str(value.Amount)
def bid_multiplier_bulk_str(value):
if value is None or not hasattr(value, 'Multiplier') or value.Multiplier is None:
return None
return bulk_str(value.Multiplier)
def parse_minute(value):
minute_number = int(value)
if minute_number == 0:
return 'Zero'
elif minute_number == 15:
return 'Fifteen'
elif minute_number == 30:
return 'Thirty'
elif minute_number == 45:
return 'FortyFive'
raise ValueError('Unknown minute')
def format_Day(value):
Day = _CAMPAIGN_OBJECT_FACTORY_V13.create('Day')
if value.lower() == 'monday':
return Day.Monday
elif value.lower() == 'tuesday':
return Day.Tuesday
elif value.lower() == 'wednesday':
return Day.Wednesday
elif value.lower() == 'thursday':
return Day.Thursday
elif value.lower() == 'friday':
return Day.Friday
elif value.lower() == 'saturday':
return Day.Saturday
elif value.lower() == 'sunday':
return Day.Sunday
raise ValueError('Unable to parse day: {0}'.format(value))
def parse_location_target_type(value):
if value == 'Metro Area':
return 'MetroArea'
elif value == 'Postal Code':
return 'PostalCode'
else:
return value
def location_target_type_bulk_str(value):
if value == 'MetroArea':
return 'Metro Area'
elif value == 'PostalCode':
return 'Postal Code'
else:
return value
def field_to_csv_AdSchedule(entity, id):
"""
get the bulk string for Scheduling DayTimeRanges
:param entity: Scheduling entity
:return: bulk str
"""
if entity is None:
return None
if entity.DayTimeRanges is None:
return DELETE_VALUE if id and id > 0 else None
return ';'.join('({0}[{1:02d}:{2:02d}-{3:02d}:{4:02d}])'
.format(d.Day, d.StartHour, int(minute_bulk_str(d.StartMinute)), d.EndHour, int(minute_bulk_str(d.EndMinute)))
for d in entity.DayTimeRanges.DayTime
)
def csv_to_field_AdSchedule(entity, value):
if value is None or value.strip() == '' or value == DELETE_VALUE:
return
daytime_strs = value.split(';')
ad_schedule_pattern = r'\((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\[(\d\d?):(\d\d)-(\d\d?):(\d\d)\]\)'
pattern = re.compile(ad_schedule_pattern, re.IGNORECASE)
daytimes = []
for daytime_str in daytime_strs:
match = pattern.match(daytime_str)
if match:
daytime = _CAMPAIGN_OBJECT_FACTORY_V13.create('DayTime')
daytime.Day = format_Day(match.group(1))
daytime.StartHour = int(match.group(2))
daytime.StartMinute = parse_minute(match.group(3))
daytime.EndHour = int(match.group(4))
daytime.EndMinute = parse_minute(match.group(5))
daytimes.append(daytime)
else:
raise ValueError('Unable to parse DayTime: {0}'.format(daytime_str))
entity.DayTimeRanges.DayTime = daytimes
def field_to_csv_FeedItemAdSchedule(entity, id):
"""
get the bulk string for FeedItem DayTimeRanges
:param entity: Scheduling entity
:return: bulk str
"""
if entity is None:
return None
if entity.daytime_ranges is None:
return DELETE_VALUE if id and id > 0 else None
return ';'.join('({0}[{1:02d}:{2:02d}-{3:02d}:{4:02d}])'
.format(d.Day, d.StartHour, int(minute_bulk_str(d.StartMinute)), d.EndHour, int(minute_bulk_str(d.EndMinute)))
for d in entity.daytime_ranges
)
def csv_to_field_FeedItemAdSchedule(entity, value):
if value is None or value.strip() == '' or value == DELETE_VALUE:
return
daytime_strs = value.split(';')
ad_schedule_pattern = r'\((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\[(\d\d?):(\d\d)-(\d\d?):(\d\d)\]\)'
pattern = re.compile(ad_schedule_pattern, re.IGNORECASE)
daytimes = []
for daytime_str in daytime_strs:
match = pattern.match(daytime_str)
if match:
daytime = _CAMPAIGN_OBJECT_FACTORY_V13.create('DayTime')
daytime.Day = format_Day(match.group(1))
daytime.StartHour = int(match.group(2))
daytime.StartMinute = parse_minute(match.group(3))
daytime.EndHour = int(match.group(4))
daytime.EndMinute = parse_minute(match.group(5))
daytimes.append(daytime)
else:
raise ValueError('Unable to parse DayTime: {0}'.format(daytime_str))
entity.daytime_ranges = daytimes
def field_to_csv_SchedulingDate(theDate, id):
"""
write scheduling StartDate to bulk string
:param theDate: Date obj to convert
:return: date bulk string
"""
if theDate is None or (theDate.Day == 0 and theDate.Month == 0 and theDate.Year == 0):
return DELETE_VALUE if id and id > 0 else None
# this case is what the suds creates by default. return None instead of a delete value
elif theDate.Day is None and theDate.Month is None and theDate.Year is None:
return None
return '{0!s}/{1!s}/{2!s}'.format(theDate.Month, theDate.Day, theDate.Year)
def field_to_csv_SchedulingStartDate(entity, id):
"""
write scheduling StartDate to bulk string
:param entity: Scheduling entity
:return: date bulk string
"""
if entity is None:
return None
elif entity.StartDate is None:
return DELETE_VALUE if id and id > 0 else None
# this case is what the suds creates by default. return None instead of a delete value
elif entity.StartDate.Day is None and entity.StartDate.Month is None and entity.StartDate.Year is None:
return None
return '{0!s}/{1!s}/{2!s}'.format(entity.StartDate.Month, entity.StartDate.Day, entity.StartDate.Year)
def field_to_csv_SchedulingEndDate(entity, id):
"""
write scheduling EndDate to bulk string
:param entity: Scheduling entity
:return: date bulk string
"""
if entity is None:
return None
elif entity.EndDate is None:
return DELETE_VALUE if id and id > 0 else None
# this case is what the suds creates by default. return None instead of a delete value
elif entity.EndDate.Day is None and entity.EndDate.Month is None and entity.EndDate.Year is None:
return None