forked from justwatch/facebook-marketing-api-golang-sdk
/
insights.go
281 lines (249 loc) · 9.55 KB
/
insights.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
package v14
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/lavkumarv/facebook-marketing-api-golang-sdk/fb"
)
// InsightsService contains all methods for working on audiences.
type InsightsService struct {
l log.Logger
c *fb.Client
*fb.StatsContainer
}
func newInsightsService(l log.Logger, c *fb.Client) *InsightsService {
return &InsightsService{
l: l,
c: c,
StatsContainer: fb.NewStatsContainer(),
}
}
// NewReport creates a new InsightsRequest.
func (is *InsightsService) NewReport(account string) *InsightsRequest {
return &InsightsRequest{
InsightsService: is,
RouteBuilder: fb.NewRoute(Version, "/act_%s/insights", account),
}
}
// NewReportOfCampaign creates a new InsightsRequest.
func (is *InsightsService) NewReportOfCampaign(campaignID string) *InsightsRequest {
return &InsightsRequest{
InsightsService: is,
RouteBuilder: fb.NewRoute(Version, "/%s/insights", campaignID),
}
}
// InsightsRequest is used to build a new request for creating an insights run.
type InsightsRequest struct {
*InsightsService
*fb.RouteBuilder
}
// Download returns all insights from the request in one slice.
func (ir *InsightsRequest) Download(ctx context.Context) ([]Insight, error) {
res := []Insight{}
err := ir.c.GetList(ctx, ir.RouteBuilder.String(), &res)
if err != nil {
return nil, err
}
return res, nil
}
// GenerateReport creates the insights report, waits until it's finished building, reads to c and then deletes it.
func (ir *InsightsRequest) GenerateReport(ctx context.Context, c chan<- Insight) (uint64, error) {
run := &struct {
ReportRunID string `json:"report_run_id"`
AccountID string `json:"account_id"`
TimeRef int `json:"time_ref"`
TimeCompleted int `json:"time_completed"`
AsyncStatus string `json:"async_status"`
IsRunning bool `json:"is_running"`
AsyncPercentCompletion int `json:"async_percent_completion"`
DateStart string `json:"date_start"`
DateStop string `json:"date_stop"`
}{}
ir.RouteBuilder.DefaultSummary(true)
err := ir.c.PostJSON(ctx, ir.RouteBuilder.String(), nil, run)
if err != nil {
return 0, err
} else if run.ReportRunID == "" {
return 0, errors.New("did not get report run id")
}
stats := ir.StatsContainer.AddStats(run.ReportRunID)
if stats == nil {
return 0, fmt.Errorf("report run %s already being downloaded", run.ReportRunID)
}
defer func() {
ir.StatsContainer.RemoveStats(run.ReportRunID)
url := fb.NewRoute(Version, "/%s", run.ReportRunID).String()
e := ir.c.Delete(ctx, url)
if e != nil {
_ = level.Warn(ir.l).Log("msg", "err deleting report run", "id", run.ReportRunID, "err", e, "url", url)
}
}()
t := time.NewTicker(15 * time.Second)
timeout := time.NewTimer(10 * time.Minute)
lastPercentage := 0
defer timeout.Stop()
defer t.Stop()
for range t.C {
// non blocking timeout
select {
case <-timeout.C:
return 0, errors.New("report timeout")
default:
}
run.IsRunning = false // field is omitted when it is false, so we need to set it to false manually
err = ir.c.GetJSON(ctx, fb.NewRoute(Version, "/%s", run.ReportRunID).String(), run)
if err != nil {
return 0, err
}
if run.AsyncStatus == "Job Completed" && run.AsyncPercentCompletion == 100 && !run.IsRunning {
stats.SetCreated()
break
}
stats.SetProgress(uint64(run.AsyncPercentCompletion), 100)
if run.AsyncStatus == "Job Failed" {
return 0, errors.New("job failed")
}
// update timeline if report progresses
if run.AsyncPercentCompletion > lastPercentage {
lastPercentage = run.AsyncPercentCompletion
timeout.Reset(10 * time.Minute)
}
}
url := fb.NewRoute(Version, "/%s/insights", run.ReportRunID).Limit(100).String()
var count, impressions uint64
for url != "" {
resp := &struct {
fb.Paging
Summary struct {
Impressions uint64 `json:"impressions,string"`
} `json:"summary"`
Data []Insight `json:"data"`
}{}
err := ir.c.GetJSON(ctx, url, resp)
if err != nil {
return 0, err
}
for _, d := range resp.Data {
count++
impressions += d.Impressions
c <- d
}
stats.SetProgress(impressions, resp.Summary.Impressions)
url = resp.Paging.Paging.Next
}
return count, nil
}
// Insight contains insight data for an facebook graph API object, broken down by the desired day.
type Insight struct {
AccountID string `json:"account_id"`
Actions ActionTypeValue `json:"actions"`
AdsetID string `json:"adset_id"`
AdID string `json:"ad_id"`
Objective string `json:"objective"`
AdsetName string `json:"adset_name"`
Age string `json:"age"`
CampaignID string `json:"campaign_id"`
CampaignName string `json:"campaign_name"`
PublisherPlatform string `json:"publisher_platform"`
PlatformPosition string `json:"platform_position"`
Clicks uint64 `json:"clicks,string"`
DateStart string `json:"date_start"`
DateStop string `json:"date_stop"`
Frequency float64 `json:"frequency,string"`
Gender string `json:"gender"`
Impressions uint64 `json:"impressions,string"`
Reach float64 `json:"reach,string"`
Spend float64 `json:"spend,string"`
VideoContinues2SecWatchedActions ActionTypeValue `json:"video_continuous_2_sec_watched_actions"`
Video15SecWatchedActions ActionTypeValue `json:"video_15_sec_watched_actions"`
VideoThruplayWatchedActions ActionTypeValue `json:"video_thruplay_watched_actions"`
Video30SecWatchedActions ActionTypeValue `json:"video_30_sec_watched_actions"`
VideoAvgTimeWatchedActions ActionTypeValue `json:"video_avg_time_watched_actions"`
VideoP100WatchedActions ActionTypeValue `json:"video_p100_watched_actions"`
VideoP25WatchedActions ActionTypeValue `json:"video_p25_watched_actions"`
VideoP50WatchedActions ActionTypeValue `json:"video_p50_watched_actions"`
VideoP75WatchedActions ActionTypeValue `json:"video_p75_watched_actions"`
VideoP95WatchedActions ActionTypeValue `json:"video_p95_watched_actions"`
VideoPlayActions ActionTypeValue `json:"video_play_actions"`
InteractiveComponentTap []InteractiveComponent `json:"interactive_component_tap"`
DeviceType string `json:"impression_device"`
Region string `json:"region"`
Country string `json:"country"`
Conversions ActionTypeValue `json:"conversions"`
}
// GetAge returns the min and max age from the insights age field.
func (i Insight) GetAge() (uint64, uint64, error) {
parts := strings.Split(i.Age, "-")
var minAge, maxAge uint64
if len(parts) == 2 {
var err error
minAge, err = strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return 0, 0, err
}
maxAge, err = strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return 0, 0, err
}
} else if i.Age == "65+" {
minAge = 65
maxAge = 100
}
return minAge, maxAge, nil
}
// ActionTypeValue is a kv store.
type ActionTypeValue []struct {
ActionType string `json:"action_type"`
ActionVideoSound string `json:"action_video_sound"`
ActionReaction string `json:"action_reaction"`
Value float64 `json:"value,string"`
// For action_attribution_windows
View1d float64 `json:"1d_view,string"`
View7d float64 `json:"7d_view,string"`
View28d float64 `json:"28d_view,string"`
Click1d float64 `json:"1d_click,string"`
Click7d float64 `json:"7d_click,string"`
Click28d float64 `json:"28d_click,string"`
}
// GetValue returns the sum of the values with the given action type.
func (atv ActionTypeValue) GetValue(actionType string) float64 {
var value float64
for _, a := range atv {
if a.ActionType == actionType {
value += a.Value
}
}
return value
}
// GetReactions returns a map with reactions.
func (atv ActionTypeValue) GetReactions() map[string]uint64 {
res := map[string]uint64{}
for _, a := range atv {
if a.ActionType == "post_reaction" {
res[a.ActionReaction] = uint64(a.Value)
}
}
return res
}
// FilterByActionTypePrefix returns a slice of ActionTypeValue for which all
// ActionType values starts with the input prefix.
func (atv ActionTypeValue) FilterByActionTypePrefix(prefix string) ActionTypeValue {
customConversions := ActionTypeValue{}
for _, a := range atv {
if strings.HasPrefix(a.ActionType, prefix) {
customConversions = append(customConversions, a)
}
}
return customConversions
}
// InteractiveComponent represents poll results.
type InteractiveComponent struct {
InteractiveComponentStickerID string `json:"interactive_component_sticker_id"`
InteractiveComponentStickerResponse string `json:"interactive_component_sticker_response"`
Value string `json:"value"`
}