-
Notifications
You must be signed in to change notification settings - Fork 25
/
audience.go
417 lines (359 loc) · 12.2 KB
/
audience.go
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
package v16
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"github.com/justwatch/facebook-marketing-api-golang-sdk/fb"
)
// BatchMaxIDsSequence we upload.
const BatchMaxIDsSequence = 10000
// AudienceService contains all methods for working on audiences.
type AudienceService struct {
c *fb.Client
}
// Create uploads a new custom audience and returns the id of the custom audience.
func (as *AudienceService) Create(ctx context.Context, act string, a CustomAudience) (string, error) {
if a.ID != "" {
return "", fmt.Errorf("cannot create audience that already exists: %s", a.ID)
} else if act == "" {
return "", errors.New("cannot create audience without account id")
}
res := &fb.MinimalResponse{}
err := as.c.PostJSON(ctx, fb.NewRoute(Version, "/act_%s/customaudiences", act).String(), a, res)
if err != nil {
return "", err
} else if err = res.GetError(); err != nil {
return "", err
} else if res.ID == "" {
return "", fmt.Errorf("creating custom audience failed")
}
return res.ID, nil
}
// CreateLookalike creates new lookalike
func (as *AudienceService) CreateLookalike(ctx context.Context, adaccountID, orginAudienceID, customAudienceName string, lookalikeSpec *LookalikeSpec) (string, error) {
type createLookalikeRequest struct {
OriginAudienceID string `json:"origin_audience_id"`
Name string `json:"name"`
Subtype string `json:"subtype"`
LookalikeSpec *LookalikeSpec `json:"lookalike_spec"`
}
res := &fb.MinimalResponse{}
err := as.c.PostJSON(ctx, fb.NewRoute(Version, "/act_%s/customaudiences", adaccountID).String(), createLookalikeRequest{
OriginAudienceID: orginAudienceID,
Name: customAudienceName,
Subtype: "LOOKALIKE",
LookalikeSpec: lookalikeSpec,
}, &res)
if err != nil {
return "", err
} else if err = res.GetError(); err != nil {
return "", err
} else if res.ID == "" {
return "", fmt.Errorf("creating lookalike audience failed")
}
return res.ID, nil
}
// Update updates an audience.
func (as *AudienceService) Update(ctx context.Context, a CustomAudience) error {
if a.ID == "" {
return errors.New("cannot update audience without id")
}
res := &fb.MinimalResponse{}
err := as.c.PostJSON(ctx, fb.NewRoute(Version, "/%s", a.ID).String(), a, res)
if err != nil {
return err
} else if err = res.GetError(); err != nil {
return err
} else if !res.Success && res.ID == "" {
return fmt.Errorf("updating the audience failed")
}
return nil
}
// Share shares a custom audience with the provided adaccounts.
func (as *AudienceService) Share(ctx context.Context, customAudienceID string, adaccountIDs []string) error {
if len(adaccountIDs) == 0 {
return nil
}
ca, err := as.Get(ctx, customAudienceID)
if err != nil {
return err
}
existingAdaccountIDs := []json.Number{}
if ca.AccountID != "" {
existingAdaccountIDs = append(existingAdaccountIDs, json.Number(ca.AccountID))
}
adaccountsData := []json.Number{}
if ca.Adaccounts != nil && ca.Adaccounts.Data != nil {
for _, adaccountID := range ca.Adaccounts.Data {
existingAdaccountIDs = append(existingAdaccountIDs, adaccountID)
adaccountsData = append(adaccountsData, adaccountID)
}
}
changed := false
for _, adaccountIDToShare := range adaccountIDs {
found := false
for _, existingAdAccountID := range existingAdaccountIDs {
if existingAdAccountID == json.Number(adaccountIDToShare) {
found = true
break
}
}
if !found {
adaccountsData = append(adaccountsData, json.Number(adaccountIDToShare))
changed = true
}
}
if changed {
ca.Adaccounts = &Adaccounts{
Data: adaccountsData,
}
}
return as.Update(ctx, *ca)
}
// ShareCustom shares a custom audience with the provided adaccounts.
func (as *AudienceService) ShareCustom(ctx context.Context, customAudienceID string, adaccountIDs, relationshipTypes []string) error {
if len(adaccountIDs) == 0 {
return nil
}
return as.c.PostJSON(ctx, fb.NewRoute(Version, "/%s/adaccounts", customAudienceID).String(), struct {
Adaccounts []string `json:"adaccounts"`
RelationshipType []string `json:"relationship_type"`
}{adaccountIDs, relationshipTypes}, &struct{}{})
}
// UnshareCustom unshares a custom audience with the provided adaccounts.
func (as *AudienceService) UnshareCustom(ctx context.Context, customAudienceID string, adaccountIDs, relationshipTypes []string) error {
if len(adaccountIDs) == 0 {
return nil
}
return as.c.DeleteJSON(ctx, fb.NewRoute(Version, "/%s/adaccounts", customAudienceID).String(), struct {
Adaccounts []string `json:"adaccounts"`
RelationshipType []string `json:"relationship_type"`
}{adaccountIDs, relationshipTypes}, &struct{}{})
}
// ListAdAccounts lists the accounts an audience is shared to.
func (as *AudienceService) ListAdAccounts(ctx context.Context, audienceID string) ([]string, error) {
res := struct {
Data []string `json:"data"`
}{}
err := as.c.GetJSON(ctx, fb.NewRoute(Version, "/%s/adaccounts", audienceID).String(), &res)
if err != nil {
return nil, err
}
return res.Data, nil
}
// Delete removes a single audience.
func (as *AudienceService) Delete(ctx context.Context, id string) error {
return as.c.Delete(ctx, fb.NewRoute(Version, "/%s", id).String())
}
// DeleteLookalikes removes all lookalikes of an audience.
func (as *AudienceService) DeleteLookalikes(ctx context.Context, id string) error {
ca, err := as.Get(ctx, id)
if err != nil {
return err
} else if ca == nil {
return fmt.Errorf("did not find custom audience %s", id)
}
for _, id := range ca.Lookalikes {
err = as.Delete(ctx, id)
if err != nil {
return err
}
}
return nil
}
// Get returns a single audience.
func (as *AudienceService) Get(ctx context.Context, id string) (*CustomAudience, error) {
res := &CustomAudience{}
err := as.c.GetJSON(ctx, fb.NewRoute(Version, "/%s", id).Fields("id", "name", "description", "subtype", "approximate_count_upper_bound", "approximate_count_lower_bound", "rule", "customer_file_source", "lookalike_audience_ids", "adaccounts").String(), res)
if err != nil {
if fb.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return res, nil
}
// ListCustom returns all custom audiences for that account.
func (as *AudienceService) ListCustom(ctx context.Context, act string) ([]CustomAudience, error) {
res := []CustomAudience{}
route := fb.NewRoute(Version, "/act_%s/customaudiences", act).
Limit(250).
Fields("id", "name", "description", "approximate_count_upper_bound", "approximate_count_lower_bound", "subtype", "adaccounts", "lookalike_spec") // , "rule")
err := as.c.GetList(ctx, route.String(), &res)
if err != nil {
return nil, err
}
return res, nil
}
// ListCustomFiltered returns a filtered list of custom audiences for that account.
// ...&filtering=[{field:'subtype',operator:'EQUAL',value:'WEBSITE'}].
func (as *AudienceService) ListCustomFiltered(ctx context.Context, act string, filtering []fb.Filter) ([]CustomAudience, error) {
res := []CustomAudience{}
route := fb.NewRoute(Version, "/act_%s/customaudiences", act).
Limit(250).
Fields("id", "name", "account_id", "description", "approximate_count_upper_bound", "approximate_count_lower_bound", "subtype", "adaccounts"). // , "rule")
Filtering(filtering...)
err := as.c.GetList(ctx, route.String(), &res)
if err != nil {
return nil, err
}
return res, nil
}
// EditIDs starts adding or removing ids from a custom audience.
func (as *AudienceService) EditIDs(ctx context.Context, audienceID string, c <-chan string, doRemove bool) error {
bigN, err := rand.Int(rand.Reader, big.NewInt(math.MaxUint32))
if err != nil {
return fmt.Errorf("failed to generate session ID int EditIDs: %w", err)
}
sessionID := bigN.Int64()
doWork := true
var total, received, failed uint64
var leftOver string
for batchSequence := 1; doWork; batchSequence++ {
var ids []string
ids, leftOver, doWork = readBatch(BatchMaxIDsSequence, c, leftOver)
if len(ids) == 0 {
break
}
total += uint64(len(ids))
route := fb.NewRoute(Version, "/%s/users", audienceID).String()
req := editAudienceIDsRequest{
Session: uploadSession{
SessionID: uint32(sessionID),
BatchSequence: batchSequence,
LastBatchFlag: !doWork,
},
Payload: uploadPayload{
Schema: "MOBILE_ADVERTISER_ID",
Data: ids,
},
}
res := &editAudienceIDsResponse{}
var err error
if doRemove {
err = as.c.DeleteJSON(ctx, route, req, res)
} else {
err = as.c.PostJSON(ctx, route, req, res)
}
if err != nil {
return err
}
received = res.NumReceived
failed = res.NumInvalidEntries
}
if total != received {
return &UploadError{
Total: total,
Received: received,
Failed: failed,
}
}
return nil
}
func readBatch(max int, c <-chan string, leftOver string) ([]string, string, bool) {
s := make([]string, 0, max)
ok := true
index := 0
if leftOver != "" {
s = append(s, leftOver)
leftOver = ""
index++
}
for ; index < max && ok; index++ {
var id string
id, ok = read(c)
if id == "" {
index--
continue
}
s = append(s, id)
}
if len(s) == max {
leftOver, ok = read(c)
}
return s, leftOver, ok
}
func read(c <-chan string) (string, bool) {
var res string
ok := true
for ok && res == "" {
res, ok = <-c
}
return res, ok
}
type editAudienceIDsRequest struct {
Session uploadSession `json:"session"`
Payload uploadPayload `json:"payload"`
}
type uploadSession struct {
SessionID uint32 `json:"session_id"`
BatchSequence int `json:"batch_seq"`
LastBatchFlag bool `json:"last_batch_flag"`
}
type uploadPayload struct {
Schema string `json:"schema"`
Data []string `json:"data"`
}
type editAudienceIDsResponse struct {
UserSegmentID uint64 `json:"user_segment_id"`
SessionID string `json:"session_id"`
NumReceived uint64 `json:"num_received"`
NumInvalidEntries uint64 `json:"num_invalid_entries"`
}
// UploadError gets returned when the number of total lines does not match the number of received lines or when the number of failed lines is greater than zero.
type UploadError struct {
Total uint64
Received uint64
Failed uint64
}
func (ue *UploadError) Error() string {
return fmt.Sprintf("uploaded %d ids, received %d, failed uploading %d", ue.Total, ue.Received, ue.Failed)
}
// CustomAudience https://developers.facebook.com/docs/marketing-api/reference/custom-audience
// unused fields: ApproximateCount int `json:"approximate_count,omitempty"`.
type CustomAudience struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
AccountID string `json:"account_id,omitempty"`
Description string `json:"description,omitempty"`
Subtype string `json:"subtype,omitempty"`
ApproximateCountUpperBound int `json:"approximate_count_upper_bound,omitempty"`
ApproximateCountLowerBound int `json:"approximate_count_lower_bound,omitempty"`
Rule string `json:"rule,omitempty"`
CustomerFileSource string `json:"customer_file_source,omitempty"`
Lookalikes []string `json:"lookalike_audience_ids,omitempty"`
Adaccounts *Adaccounts `json:"adaccounts,omitempty"`
LookalikeSpec *LookalikeSpec `json:"lookalike_spec,omitempty"`
OriginAudienceID string `json:"origin_audience_id,omitempty"`
}
// LookalikeSpec contains the metadata of lookalike audiences.
type LookalikeSpec struct {
Country string `json:"country,omitempty"`
Origin []LookalikeOrigion `json:"origin,omitempty"`
Ratio float64 `json:"ratio,omitempty"`
Type string `json:"type,omitempty"`
}
// LocationSpec ...
type LocationSpec struct {
GeoLocations *GeoLocation `json:"geo_locations,omitempty"`
ExcludedGeoLocations *GeoLocation `json:"excluded_geo_locations,omitempty"`
}
// GeoLocation ...
type GeoLocation struct {
Countries []string `json:"countries,omitempty"`
CountryGroups []string `json:"country_groups,omitempty"`
}
// LookalikeOrigion tells which audience a lookalike one is related to.
type LookalikeOrigion struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
}
// Adaccounts https://developers.facebook.com/docs/marketing-api/reference/custom-audience/adaccounts/
type Adaccounts struct {
Data []json.Number `json:"data,omitempty"`
}