-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathfunctions.ts
More file actions
272 lines (242 loc) · 8.74 KB
/
functions.ts
File metadata and controls
272 lines (242 loc) · 8.74 KB
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
import { Features, IntegrationError, RequestClient, StatsContext } from '@segment/actions-core'
import { Payload } from './addToAudContactInfo/generated-types'
import { Payload as DeviceIdPayload } from './addToAudMobileDeviceId/generated-types'
import { processHashing } from '../../lib/hashing-utils'
import { FIRST_PARTY_DV360_API_VERSION, FIRST_PARTY_DV360_CANARY_API_VERSION } from './versioning-info'
export const API_VERSION = FIRST_PARTY_DV360_API_VERSION
export const CANARY_API_VERSION = FIRST_PARTY_DV360_CANARY_API_VERSION
export const FLAGON_NAME = 'first-party-dv360-canary-version'
const DV360API = `https://displayvideo.googleapis.com/`
const CONSENT_STATUS_GRANTED = 'CONSENT_STATUS_GRANTED' // Define consent status
export function getApiVersion(features?: Features, statsContext?: StatsContext): string {
const statsClient = statsContext?.statsClient
const tags = statsContext?.tags
const version = features && features[FLAGON_NAME] ? CANARY_API_VERSION : API_VERSION
statsClient?.incr('dv360_api_version', 1, [...(tags || []), `version:${version}`])
return version
}
function getAudienceEndpoint(version: string, advertiserId: string, audienceId?: string): string {
if (audienceId) {
return DV360API + `${version}/firstPartyAndPartnerAudiences/` + `${audienceId}?advertiserId=${advertiserId}`
} else {
return DV360API + `${version}/firstPartyAndPartnerAudiences` + `?advertiserId=${advertiserId}`
}
}
function getEditCustomerMatchMembersEndpoint(version: string, audienceId: string): string {
return DV360API + `${version}/firstPartyAndPartnerAudiences/` + audienceId + ':editCustomerMatchMembers'
}
interface createAudienceRequestParams {
advertiserId: string
audienceName: string
description?: string
membershipDurationDays: string
audienceType: string
appId?: string
token?: string
features?: Features
statsContext?: StatsContext
}
interface getAudienceParams {
advertiserId: string
audienceId: string
token?: string
features?: Features
statsContext?: StatsContext
}
interface DV360editCustomerMatchResponse {
firstPartyAndPartnerAudienceId?: string
error: [
{
code: string
message: string
status: string
}
]
}
export const createAudienceRequest = (
request: RequestClient,
params: createAudienceRequestParams
): Promise<Response> => {
const {
advertiserId,
audienceName,
description,
membershipDurationDays,
audienceType,
appId,
token,
features,
statsContext
} = params
const version = getApiVersion(features, statsContext)
const endpoint = getAudienceEndpoint(version, advertiserId)
return request(endpoint, {
method: 'POST',
headers: {
authorization: `Bearer ${token}`,
'Content-Type': 'application/json; charset=utf-8'
},
json: {
displayName: audienceName,
audienceType: audienceType,
membershipDurationDays: membershipDurationDays,
description: description,
audienceSource: 'AUDIENCE_SOURCE_UNSPECIFIED',
firstPartyAndPartnerAudienceType: 'TYPE_FIRST_PARTY',
appId: appId
}
})
}
export const getAudienceRequest = (request: RequestClient, params: getAudienceParams): Promise<Response> => {
const { advertiserId, audienceId, token, features, statsContext } = params
const version = getApiVersion(features, statsContext)
const endpoint = getAudienceEndpoint(version, advertiserId, audienceId)
return request(endpoint, {
method: 'GET',
headers: {
authorization: `Bearer ${token}`,
'Content-Type': 'application/json; charset=utf-8'
}
})
}
export async function editDeviceMobileIds(
request: RequestClient,
payloads: DeviceIdPayload[],
operation: 'add' | 'remove',
statsContext?: StatsContext, // Adjust type based on actual stats context
features?: Features
) {
// Assume all payloads are for the same audience/advertiser (use first)
const { external_id: audienceId, advertiser_id: advertiserId } = payloads[0]
// Collect all mobileDeviceIds into a flat array
const allMobileDeviceIds = payloads.flatMap((p) =>
Array.isArray(p.mobileDeviceIds) ? p.mobileDeviceIds : [p.mobileDeviceIds]
)
//Format the endpoint
const version = getApiVersion(features, statsContext)
const endpoint = getEditCustomerMatchMembersEndpoint(version, audienceId)
// Prepare the request payload
const mobileDeviceIdList = {
mobileDeviceIds: allMobileDeviceIds,
consent: {
adUserData: CONSENT_STATUS_GRANTED,
adPersonalization: CONSENT_STATUS_GRANTED
}
}
// Convert the payload to string if needed
const requestPayload = JSON.stringify({
advertiserId: advertiserId,
...(operation === 'add' ? { addedMobileDeviceIdList: mobileDeviceIdList } : {}),
...(operation === 'remove' ? { removedMobileDeviceIdList: mobileDeviceIdList } : {})
})
const response = await request<DV360editCustomerMatchResponse>(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: requestPayload
})
const responseAudienceId = response.data.firstPartyAndPartnerAudienceId
if (!response.data || !responseAudienceId) {
statsContext?.statsClient?.incr('addCustomerMatchMembers.error', allMobileDeviceIds.length, statsContext?.tags)
throw new IntegrationError(
`API returned error: ${response.data?.error || 'Unknown error'}`,
'API_REQUEST_ERROR',
400
)
}
statsContext?.statsClient?.incr('addCustomerMatchMembers.success', allMobileDeviceIds.length, statsContext?.tags)
return response.data
}
// Helper to build contactInfoList
function buildContactInfoList(contactInfos: Record<string, string>[]): {
contactInfos: Record<string, string>[]
consent: { adUserData: string; adPersonalization: string }
} {
return {
contactInfos,
consent: {
adUserData: CONSENT_STATUS_GRANTED,
adPersonalization: CONSENT_STATUS_GRANTED
}
}
}
// Helper to build request payload
function buildRequestPayload(
advertiserId: string,
contactInfoList: {
contactInfos: Record<string, string>[]
consent: { adUserData: string; adPersonalization: string }
},
operation: 'add' | 'remove'
) {
return JSON.stringify({
advertiserId,
...(operation === 'add' ? { addedContactInfoList: contactInfoList } : {}),
...(operation === 'remove' ? { removedContactInfoList: contactInfoList } : {})
})
}
export async function editContactInfo(
request: RequestClient,
payloads: Payload[],
operation: 'add' | 'remove',
statsContext?: StatsContext,
features?: Features
) {
if (!payloads || payloads.length === 0) return
// TODO: remove this check, the framework should handle this
const validPayloads = payloads.filter(
(payload) =>
payload.emails !== undefined ||
payload.phoneNumbers !== undefined ||
payload.firstName !== undefined ||
payload.lastName !== undefined
)
if (validPayloads.length === 0) return
// Assume all payloads are for the same audience/advertiser (use first)
const { external_id: audienceId, advertiser_id: advertiserId } = validPayloads[0]
if (!audienceId || !advertiserId) {
throw new IntegrationError('Missing required audience or advertiser ID', 'MISSING_REQUIRED_FIELD', 400)
}
const contactInfos = validPayloads.map(processPayload)
const contactInfoList = buildContactInfoList(contactInfos)
const requestPayload = buildRequestPayload(advertiserId, contactInfoList, operation)
const version = getApiVersion(features, statsContext)
const endpoint = getEditCustomerMatchMembersEndpoint(version, audienceId)
const response = await request<DV360editCustomerMatchResponse>(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: requestPayload
})
statsContext?.statsClient?.incr('addCustomerMatchMembers.success', contactInfos.length, statsContext?.tags)
return response.data
}
function normalizeAndHash(data: string) {
// Normalize the data
const normalizedData = data.toLowerCase().trim() // Example: Convert to lowercase and remove leading/trailing spaces
// Hash the normalized data using SHA-256
return processHashing(normalizedData, 'sha256', 'hex')
}
function processPayload(payload: Payload) {
const result: { [key: string]: string } = {}
// Normalize and hash only if the value is defined
if (payload.emails) {
result.hashedEmails = normalizeAndHash(payload.emails)
}
if (payload.phoneNumbers) {
result.hashedPhoneNumbers = normalizeAndHash(payload.phoneNumbers)
}
if (payload.zipCodes) {
result.zipCodes = payload.zipCodes
}
if (payload.firstName) {
result.hashedFirstName = normalizeAndHash(payload.firstName)
}
if (payload.lastName) {
result.hashedLastName = normalizeAndHash(payload.lastName)
}
if (payload.countryCode) {
result.countryCode = payload.countryCode
}
return result
}