-
Notifications
You must be signed in to change notification settings - Fork 18
/
campaigns.go
110 lines (98 loc) · 2.56 KB
/
campaigns.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
package main
import (
"context"
"database/sql"
"github.com/afex/hystrix-go/hystrix"
"regexp"
"time"
)
type Ad struct {
Description string
Image string
Link string
Source string
Company string
ProviderId string
}
type CampaignAd struct {
Ad
Id string
Placeholder string
Ratio float32
Probability float32 `json:"-"`
Fallback bool `json:"-"`
Geo string `json:"-"`
IsTagTargeted bool `json:"-"`
}
type ScheduledCampaignAd struct {
CampaignAd
Start time.Time
End time.Time
}
var cloudinaryRegex = regexp.MustCompile(`(?:res\.cloudinary\.com\/daily-now|daily-now-res\.cloudinary\.com)`)
func mapCloudinaryUrl(url string) string {
return cloudinaryRegex.ReplaceAllString(url, "media.daily.dev")
}
var addCampaign = func(ctx context.Context, camp ScheduledCampaignAd) error {
return hystrix.DoC(ctx, hystrixDb,
func(ctx context.Context) error {
_, err := addCampStmt.ExecContext(ctx, camp.Id, camp.Description, camp.Link, camp.Image, camp.Ratio, camp.Placeholder, camp.Source, camp.Company, camp.Probability, camp.Fallback, camp.Geo, camp.Start, camp.End)
if err != nil {
return err
}
return nil
}, nil)
}
var fetchCampaigns = func(ctx context.Context, timestamp time.Time, userId string) ([]CampaignAd, error) {
output := make(chan []CampaignAd, 1)
errors := hystrix.GoC(ctx, hystrixDb,
func(ctx context.Context) error {
rows, err := campStmt.QueryContext(ctx, userId, timestamp, timestamp)
if err != nil {
return err
}
defer rows.Close()
var res []CampaignAd
for rows.Next() {
var camp CampaignAd
var geo sql.NullString
err = rows.Scan(&camp.Id, &camp.Description, &camp.Link, &camp.Image, &camp.Ratio, &camp.Placeholder, &camp.Source, &camp.Company, &camp.Probability, &camp.Fallback, &geo, &camp.IsTagTargeted)
if err != nil {
return err
}
camp.Image = mapCloudinaryUrl(camp.Image)
if geo.Valid && len(geo.String) > 0 {
camp.Geo = geo.String
if !camp.Fallback {
if camp.IsTagTargeted {
camp.ProviderId = "direct-combined"
} else {
camp.ProviderId = "direct-geo"
}
}
} else {
camp.Geo = ""
if !camp.Fallback {
if camp.IsTagTargeted {
camp.ProviderId = "direct-keywords"
} else {
camp.ProviderId = "direct"
}
}
}
res = append(res, camp)
}
err = rows.Err()
if err != nil {
return err
}
output <- res
return nil
}, nil)
select {
case out := <-output:
return out, nil
case err := <-errors:
return nil, err
}
}