-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_adsense.js
More file actions
342 lines (293 loc) · 11.2 KB
/
google_adsense.js
File metadata and controls
342 lines (293 loc) · 11.2 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
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
/**
* @fileoverview Google AdSense Audit Module
* @version 1.0
*/
// =================================================================
// MODULE CONSTANTS AND CONFIGURATION
// =================================================================
const ADSENSE_ACCOUNTS_HEADERS = [
'Account ID', 'Account Name', 'State', 'Premium', 'Time Zone', 'Currency Code', 'Creation Date', 'Sync Date'
];
const ADSENSE_ADUNITS_HEADERS = [
'Account ID', 'Ad Client ID', 'Ad Unit ID', 'Ad Unit Name', 'State', 'Content Ad Type', 'Display Name', 'Sync Date'
];
const ADSENSE_SITES_HEADERS = [
'Account ID', 'Site ID', 'Domain', 'State', 'Auto Ads Enabled', 'Sync Date'
];
const ADSENSE_CUSTOM_CHANNELS_HEADERS = [
'Account ID', 'Ad Client ID', 'Channel ID', 'Channel Name', 'Active', 'Sync Date'
];
// =================================================================
// SYNCHRONIZATION FUNCTIONS (EXECUTABLE FROM MENU)
// =================================================================
/**
* Main function to synchronize AdSense data.
* @returns {Object} Sync status and record count.
*/
function syncAdSenseCore() {
const startTime = Date.now();
const serviceName = 'adsense';
const results = { accounts: 0, adUnits: 0, sites: 0, customChannels: 0 };
try {
const auth = getAuthConfig(serviceName);
logSyncStart('AdSense_Sync', auth.authUser);
// 1. GET ACCOUNTS
logEvent('AdSense', 'Phase 1: Extracting AdSense accounts...');
const accounts = listAdSenseAccounts();
results.accounts = accounts.length;
if (accounts.length === 0) {
logWarning('AdSense', 'No AdSense accounts found.');
writeAdSenseAccountsToSheet([]); // Will trigger "No account found" via centralized utility
return {
records: 0,
status: 'SUCCESS',
duration: Date.now() - startTime,
details: results
};
}
writeAdSenseAccountsToSheet(accounts);
// 2. PROCESS EACH ACCOUNT FOR AD UNITS, SITES, AND CUSTOM CHANNELS
const allAdUnits = [];
const allSites = [];
const allCustomChannels = [];
for (const account of accounts) {
const accountId = account.accountId;
// Get Ad Clients (required for ad units and custom channels)
try {
const adClients = listAdClients(accountId);
for (const adClient of adClients) {
const adClientId = adClient.name.split('/').pop();
// Get Ad Units
try {
const adUnits = listAdUnits(accountId, adClientId);
allAdUnits.push(...adUnits.map(au => ({
'Account ID': accountId,
...au
})));
} catch (e) {
logWarning('AdSense', `Could not get ad units for ${adClientId}: ${e.message}`);
}
// Get Custom Channels
try {
const customChannels = listCustomChannels(accountId, adClientId);
allCustomChannels.push(...customChannels.map(cc => ({
'Account ID': accountId,
...cc
})));
} catch (e) {
logWarning('AdSense', `Could not get custom channels for ${adClientId}: ${e.message}`);
}
}
} catch (e) {
logWarning('AdSense', `Could not get ad clients for ${accountId}: ${e.message}`);
}
// Get Sites
try {
const sites = listSites(accountId);
allSites.push(...sites.map(s => ({
'Account ID': accountId,
...s
})));
} catch (e) {
logWarning('AdSense', `Could not get sites for ${accountId}: ${e.message}`);
}
Utilities.sleep(200); // Pause between accounts
}
results.adUnits = allAdUnits.length;
results.sites = allSites.length;
results.customChannels = allCustomChannels.length;
writeAdSenseAdUnitsToSheet(allAdUnits);
writeAdSenseSitesToSheet(allSites);
writeAdSenseCustomChannelsToSheet(allCustomChannels);
const totalElements = results.accounts + results.adUnits + results.sites + results.customChannels;
const duration = Date.now() - startTime;
logSyncEnd('AdSense_Sync', totalElements, duration, 'SUCCESS');
return {
records: totalElements,
status: 'SUCCESS',
duration: duration,
details: results
};
} catch (error) {
const duration = Date.now() - startTime;
logSyncEnd('AdSense_Sync', 0, duration, 'ERROR');
logError('AdSense', `Synchronization failed: ${error.message}`);
// Report error in the primary sheet
writeDataToSheet('ADSENSE_ACCOUNTS', ADSENSE_ACCOUNTS_HEADERS, null, 'AdSense', error.message);
return {
records: 0,
status: 'ERROR',
duration: duration,
error: error.message
};
}
}
/**
* Entry point for UI calls.
*/
function syncAdSenseWithUI() {
showLoadingNotification('Syncing Google AdSense assets...');
const result = syncAdSenseCore();
const ui = SpreadsheetApp.getUi();
if (result.status === 'SUCCESS') {
const details = result.details;
const body = `Accounts: ${details.accounts} | Ad Units: ${details.adUnits} | Sites: ${details.sites} | Custom Channels: ${details.customChannels}\n\n` +
`Total: ${result.records} elements | Time: ${Math.round(result.duration / 1000)}s\n\n` +
`Data written to ADSENSE_ACCOUNTS, ADSENSE_ADUNITS, ADSENSE_SITES, ADSENSE_CUSTOM_CHANNELS.`;
ui.alert('AdSense Synchronized', body, ui.ButtonSet.OK);
} else {
const body = `Synchronization failed: ${result.error}\n\n` +
`Action: Verify that you have AdSense account access and that the script has been authorized.\n\n` +
`Details: Check LOGS sheet for more information.`;
ui.alert('AdSense Error', body, ui.ButtonSet.OK);
}
}
// =================================================================
// DATA EXTRACTION HELPERS
// =================================================================
/**
* Lists AdSense accounts for the authenticated user.
* @returns {Array<Object>} Array of account objects.
*/
function listAdSenseAccounts() {
const auth = getAuthConfig('adsense');
const url = 'https://adsense.googleapis.com/v2/accounts';
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, 'AdSense-Accounts');
if (!response || !response.accounts) return [];
return response.accounts.map(account => ({
accountId: account.name.split('/').pop(),
displayName: account.displayName || 'N/A',
state: account.state || 'N/A',
premium: account.premium ? 'Yes' : 'No',
timeZone: account.timeZone?.id || 'N/A',
currencyCode: account.currencyCode || 'N/A',
createTime: account.createTime || 'N/A'
}));
}
/**
* Lists ad clients for a specific account.
* @param {string} accountId - AdSense Account ID
* @returns {Array<Object>} Array of ad client objects.
*/
function listAdClients(accountId) {
const auth = getAuthConfig('adsense');
const url = `https://adsense.googleapis.com/v2/accounts/${accountId}/adclients`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, `AdSense-AdClients-${accountId}`);
if (!response || !response.adClients) return [];
return response.adClients;
}
/**
* Lists ad units for a specific account and ad client.
* @param {string} accountId - AdSense Account ID
* @param {string} adClientId - Ad Client ID
* @returns {Array<Object>} Array of ad unit objects.
*/
function listAdUnits(accountId, adClientId) {
const auth = getAuthConfig('adsense');
const url = `https://adsense.googleapis.com/v2/accounts/${accountId}/adclients/${adClientId}/adunits`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, `AdSense-AdUnits-${adClientId}`);
if (!response || !response.adUnits) return [];
return response.adUnits.map(adUnit => ({
'Ad Client ID': adClientId,
'Ad Unit ID': adUnit.name.split('/').pop(),
'Ad Unit Name': adUnit.name,
'State': adUnit.state || 'N/A',
'Content Ad Type': adUnit.contentAdsSettings?.type || 'N/A',
'Display Name': adUnit.displayName || 'N/A'
}));
}
/**
* Lists sites for a specific account.
* @param {string} accountId - AdSense Account ID
* @returns {Array<Object>} Array of site objects.
*/
function listSites(accountId) {
const auth = getAuthConfig('adsense');
const url = `https://adsense.googleapis.com/v2/accounts/${accountId}/sites`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, `AdSense-Sites-${accountId}`);
if (!response || !response.sites) return [];
return response.sites.map(site => ({
'Site ID': site.name.split('/').pop(),
'Domain': site.domain || 'N/A',
'State': site.state || 'N/A',
'Auto Ads Enabled': site.autoAdsEnabled ? 'Yes' : 'No'
}));
}
/**
* Lists custom channels for a specific account and ad client.
* @param {string} accountId - AdSense Account ID
* @param {string} adClientId - Ad Client ID
* @returns {Array<Object>} Array of custom channel objects.
*/
function listCustomChannels(accountId, adClientId) {
const auth = getAuthConfig('adsense');
const url = `https://adsense.googleapis.com/v2/accounts/${accountId}/adclients/${adClientId}/customchannels`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, `AdSense-CustomChannels-${adClientId}`);
if (!response || !response.customChannels) return [];
return response.customChannels.map(channel => ({
'Ad Client ID': adClientId,
'Channel ID': channel.name.split('/').pop(),
'Channel Name': channel.displayName || 'N/A',
'Active': channel.active ? 'Yes' : 'No'
}));
}
// =================================================================
// SHEET WRITING HELPERS
// =================================================================
function writeAdSenseAccountsToSheet(accounts) {
const syncDate = formatDate(new Date());
const data = accounts.map(a => [
a.accountId,
a.displayName,
a.state,
a.premium,
a.timeZone,
a.currencyCode,
a.createTime,
syncDate
]);
writeDataToSheet('ADSENSE_ACCOUNTS', ADSENSE_ACCOUNTS_HEADERS, data, 'AdSense');
}
function writeAdSenseAdUnitsToSheet(adUnits) {
const syncDate = formatDate(new Date());
const data = adUnits.map(au => [
au['Account ID'],
au['Ad Client ID'],
au['Ad Unit ID'],
au['Ad Unit Name'],
au['State'],
au['Content Ad Type'],
au['Display Name'],
syncDate
]);
writeDataToSheet('ADSENSE_ADUNITS', ADSENSE_ADUNITS_HEADERS, data, 'AdSense');
}
function writeAdSenseSitesToSheet(sites) {
const syncDate = formatDate(new Date());
const data = sites.map(s => [
s['Account ID'],
s['Site ID'],
s['Domain'],
s['State'],
s['Auto Ads Enabled'],
syncDate
]);
writeDataToSheet('ADSENSE_SITES', ADSENSE_SITES_HEADERS, data, 'AdSense');
}
function writeAdSenseCustomChannelsToSheet(customChannels) {
const syncDate = formatDate(new Date());
const data = customChannels.map(cc => [
cc['Account ID'],
cc['Ad Client ID'],
cc['Channel ID'],
cc['Channel Name'],
cc['Active'],
syncDate
]);
writeDataToSheet('ADSENSE_CUSTOM_CHANNELS', ADSENSE_CUSTOM_CHANNELS_HEADERS, data, 'AdSense');
}