forked from yavfast/dbg-spider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuGA.pas
527 lines (426 loc) · 12.8 KB
/
uGA.pas
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
unit uGA;
interface
uses System.Classes, System.SysUtils, System.Generics.Collections, IdHTTP;
type
TGAType = (gatPageview, gatAppview, gatEvent, gatTransaction, gatItem, gatSocial, gatException, gatTiming);
TGAParamType = (
// General
gapVersion, gapTrackingID, gapAnonymizeIP, gapQueueTime, gapCacheBuster,
// Visitor
gapClientID,
// Session
gapSessionControl,
// Traffic Sources
gapDocumentReferrer, gapCampaignName, gapCampaignSource, gapCampaignMedium, gapCampaignKeyword, gapCampaignContent,
gapCampaignID, gapGoogleAdWordsID, gapGoogleDisplayAdsID,
// System Info
gapScreenResolution, gapViewportSize, gapDocumentEncoding, gapScreenColors, gapUserLanguage, gapJavaEnabled, gapFlashVersion,
// Hit
gapHitType, gapNonInteractionHit,
// Content Information
gapDocumentLocationURL, gapDocumentHostName, gapDocumentPath, gapDocumentTitle, gapContentDescription,
// App Tracking
gapApplicationName, gapApplicationVersion,
// Event Tracking
gapEventCategory, gapEventAction, gapEventLabel, gapEventValue,
// E-Commerce
gapTransactionID, gapTransactionAffiliation, gapTransactionRevenue, gapTransactionShipping, gapTransactionTax,
gapItemName, gapItemPrice, gapItemQuantity, gapItemCode, gapItemCategory, gapCurrencyCode,
// Social Interactions
gapSocialNetwork, gapSocialAction, gapSocialActionTarget,
// Timing
gapUserTimingCategory, gapUserTimingVariableName, gapUserTimingTime, gapUserTimingLabel, gapPageLoadTime,
gapDNSTime, gapPageDownloadTime, gapRedirectResponseTime, gapTCPConnectTime, gapServerResponseTime,
// Exceptions
gapExceptionDescription, gapIsExceptionFatal,
// Custom Dimensions / Metrics
gapCustomDimension1, gapCustomMetric1
);
TGAParam = TPair<TGAParamType, string>;
TGAParams = TDictionary<TGAParamType, string>;
TGA = class
private
FBaseParams: TGAParams;
FParams: TGAParams;
FSendFilterList: TStringList;
function GetTrackingID: string;
procedure SetTrackingID(const Value: string);
function GetAppName: string;
procedure SetAppName(const Value: string);
function GetAppVersion: string;
procedure SetAppVersion(const Value: string);
function GetClientID: string;
procedure SetClientID(const Value: string);
function GetUserLanguage: string;
procedure SetUserLanguage(const Value: string);
function GetHTTP: TIdHTTP;
function GetSendFilter: string;
procedure SetSendFilter(const Value: string);
protected
function GetParamStr: string;
procedure DoSend; virtual;
function CheckFilter(const Str: String): Boolean; virtual;
property Params: TGAParams read FParams;
property BaseParams: TGAParams read FBaseParams;
public
constructor Create;
destructor Destroy; override;
procedure SendEvent(const Category, Action: string; const ELabel: string = ''; const Value: Integer = 0;
const ExtParam1: String = '');
procedure SendException(const Description: string; const IsFatal: Boolean = False);
procedure SendFeedback(const SocialNetwork, SocialAction, SocialActionTarget: String);
procedure SessionStart;
procedure SessionEnd;
property HTTP: TIdHTTP read GetHTTP;
property TrackingID: string read GetTrackingID write SetTrackingID;
property ClientID: string read GetClientID write SetClientID;
property AppName: string read GetAppName write SetAppName;
property AppVersion: string read GetAppVersion write SetAppVersion;
property UserLanguage: string read GetUserLanguage write SetUserLanguage;
property SendFilter: string read GetSendFilter write SetSendFilter;
end;
implementation
uses IdGlobal, IdUriUtils, System.SyncObjs, Winapi.Windows;
const
GA_URL = 'http://www.google-analytics.com/collect';
GA_VERSION = '1';
GA_HIT_TYPES: array[Low(TGAType)..High(TGAType)] of string =
('pageview', 'appview', 'event', 'transaction', 'item', 'social', 'exception', 'timing');
GA_PARAMS: array[Low(TGAParamType)..High(TGAParamType)] of string = (
'v', 'tid', 'aip', 'qt', 'z', 'cid', 'sc', 'dr', 'cn', 'cs', 'cm', 'ck', 'cc', 'ci', 'gclid', 'dclid', 'sr',
'vp', 'de', 'sd', 'ul', 'je', 'fl', 't', 'ni', 'dl', 'dh', 'dp', 'dt', 'cd', 'an', 'av', 'ec', 'ea', 'el', 'ev',
'ti', 'ta', 'tr', 'ts', 'tt', 'in', 'ip', 'iq', 'ic', 'iv', 'cu', 'sn', 'sa', 'st', 'utc', 'utv', 'utt', 'utl',
'plt', 'dns', 'pdt', 'rrt', 'tcp', 'srt', 'exd', 'exf', 'cd1', 'cm1'
);
GA_TIMEOUT = 1000;
type
TGAQueue = TQueue<string>;
TGASender = class(TThread)
private
FQueue: TGAQueue;
FQueueEvent: TEvent;
FQueueCS: TCriticalSection;
FHTTP: TIdHTTP;
procedure ThSleep(const MSec: Integer);
protected
function DoSend(const Data: string): Boolean;
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure Send(const Data: string);
property HTTP: TIdHTTP read FHTTP;
end;
var
gvGASender: TGASender = nil;
function ParamEncode(const ASrc: string): string;
const
_VALID_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_~';
var
I, J, CharLen, ByteLen: Integer;
Buf: TIdBytes;
LChar: WideChar;
AByteEncoding: IIdTextEncoding;
begin
Result := '';
if ASrc = '' then
Exit;
AByteEncoding := nil;
EnsureEncoding(AByteEncoding, encUTF8);
SetLength(Buf, AByteEncoding.GetMaxByteCount(2));
I := 1;
while I <= Length(ASrc) do
begin
LChar := ASrc[I];
if Pos(LChar, _VALID_CHARS) = 0 then
begin
CharLen := CalcUTF16CharLength(ASrc, I);
ByteLen := AByteEncoding.GetBytes(ASrc, I, CharLen, Buf, 0);
for J := 0 to ByteLen - 1 do
Result := Result + '%' + IntToHex(Ord(Buf[J]), 2);
Inc(I, CharLen);
end
else
begin
Result := Result + Char(LChar);
Inc(I);
end;
end;
end;
{ TGA }
function TGA.CheckFilter(const Str: String): Boolean;
begin
Result := (FSendFilterList.IndexOf(Str) = -1);
end;
constructor TGA.Create;
begin
inherited Create;
FBaseParams := TGAParams.Create;
FParams := TGAParams.Create;
FSendFilterList := TStringList.Create;
FSendFilterList.Delimiter := ',';
FSendFilterList.StrictDelimiter := True;
FSendFilterList.CaseSensitive := False;
FBaseParams.Add(gapVersion, GA_VERSION);
end;
destructor TGA.Destroy;
begin
FreeAndNil(FBaseParams);
FreeAndNil(FParams);
FreeAndNil(FSendFilterList);
inherited;
end;
procedure TGA.DoSend;
begin
gvGASender.Send(GetParamStr);
end;
function TGA.GetAppName: string;
begin
Result := FBaseParams[gapApplicationName];
end;
function TGA.GetAppVersion: string;
begin
Result := FBaseParams[gapApplicationVersion];
end;
function TGA.GetClientID: string;
begin
Result := FBaseParams[gapClientID];
end;
function TGA.GetHTTP: TIdHTTP;
begin
Result := gvGASender.HTTP;
end;
function TGA.GetParamStr: string;
var
P: TGAParam;
begin
Result := '';
for P in FBaseParams Do
begin
if Result <> '' then
Result := Result + '&';
Result := Result + GA_PARAMS[P.Key] + '=' + ParamEncode(P.Value);
end;
for P in FParams Do
begin
if Result <> '' then
Result := Result + '&';
Result := Result + GA_PARAMS[P.Key] + '=' + ParamEncode(P.Value);
end;
end;
function TGA.GetSendFilter: string;
begin
Result := FSendFilterList.DelimitedText;
end;
function TGA.GetTrackingID: string;
begin
Result := FBaseParams[gapTrackingID];
end;
function TGA.GetUserLanguage: string;
begin
Result := FBaseParams[gapUserLanguage];
end;
procedure TGA.SendEvent(const Category, Action: string; const ELabel: string = ''; const Value: Integer = 0;
const ExtParam1: String = '');
begin
if not CheckFilter(Category) or not CheckFilter(Action) or not CheckFilter(ELabel) then Exit;
Params.Clear;
Params.Add(gapHitType, GA_HIT_TYPES[gatEvent]);
Params.Add(gapEventCategory, Category);
Params.Add(gapEventAction, Action);
Params.Add(gapEventLabel, ELabel);
Params.Add(gapEventValue, IntToStr(Value));
if ExtParam1 <> '' then
begin
Params.Add(gapCustomDimension1, ExtParam1);
end;
DoSend;
end;
procedure TGA.SendException(const Description: string; const IsFatal: Boolean);
begin
Params.Clear;
Params.Add(gapHitType, GA_HIT_TYPES[gatException]);
Params.Add(gapExceptionDescription, Description);
if IsFatal then
Params.Add(gapIsExceptionFatal, '1')
else
Params.Add(gapIsExceptionFatal, '0');
DoSend;
end;
procedure TGA.SendFeedback(const SocialNetwork, SocialAction, SocialActionTarget: String);
begin
Params.Clear;
Params.Add(gapHitType, GA_HIT_TYPES[gatSocial]);
Params.Add(gapSocialNetwork, SocialNetwork);
Params.Add(gapSocialAction, SocialAction);
Params.Add(gapSocialActionTarget, SocialActionTarget);
DoSend;
end;
procedure TGA.SessionEnd;
begin
Params.Clear;
Params.Add(gapHitType, GA_HIT_TYPES[gatEvent]); //???
Params.Add(gapSessionControl, 'end');
DoSend;
end;
procedure TGA.SessionStart;
begin
Params.Clear;
Params.Add(gapHitType, GA_HIT_TYPES[gatEvent]); //???
Params.Add(gapSessionControl, 'start');
DoSend;
end;
procedure TGA.SetAppName(const Value: string);
begin
FBaseParams.AddOrSetValue(gapApplicationName, Value);
end;
procedure TGA.SetAppVersion(const Value: string);
begin
FBaseParams.AddOrSetValue(gapApplicationVersion, Value);
end;
procedure TGA.SetClientID(const Value: string);
begin
FBaseParams.AddOrSetValue(gapClientID, Value);
end;
procedure TGA.SetSendFilter(const Value: string);
var
S: String;
begin
FSendFilterList.Clear;
if Value <> '' then
begin
S := StringReplace(Value, ' ', '', [rfReplaceAll]);
if S <> '' then
begin
if (S[1] = '(') and (S[Length(S)] = ')') then
S := Copy(S, 2, Length(S) - 2);
if S <> '' then
FSendFilterList.DelimitedText := S;
end;
end;
end;
procedure TGA.SetTrackingID(const Value: string);
begin
FBaseParams.AddOrSetValue(gapTrackingID, Value);
end;
procedure TGA.SetUserLanguage(const Value: string);
begin
FBaseParams.AddOrSetValue(gapUserLanguage, Value);
end;
{ TGASender }
constructor TGASender.Create;
begin
inherited Create(False);
FreeOnTerminate := False; // free on finalization
//FHTTP := TIdHTTP.Create(nil);
FQueue := TGAQueue.Create;
FQueueEvent := TEvent.Create;
FQueueCS := TCriticalSection.Create;
end;
destructor TGASender.Destroy;
begin
try
FQueueCS.Enter;
try
FQueue.Clear;
FreeAndNil(FQueue);
finally
FQueueCS.Leave;
end;
FreeAndNil(FQueueCS);
FreeAndNil(FQueueEvent);
//FreeAndNil(FHTTP);
except
// Çäåñü Log óæå óáèòûé
end;
inherited;
end;
function TGASender.DoSend(const Data: string): Boolean;
var
S: TStringStream;
begin
{$IFDEF DEBUG}
Result := True;
Exit;
{$ENDIF}
if (Self = Nil) or Terminated then
begin
Result := True;
Exit;
end;
Result := False;
S := TStringStream.Create(Data);
try
try
FHTTP.Post(GA_URL, S);
if (Self <> Nil) and not Terminated then
Result := (FHTTP.ResponseCode = 200);
except
// Èãíîðèì âñå îøèáêè
end;
finally
FreeAndNil(S);
end;
end;
procedure TGASender.Execute;
var
Data: string;
begin
NameThreadForDebugging('TGASender');
try
FHTTP := TIdHTTP.Create(nil);
try
FHTTP.HandleRedirects := True;
while (Self <> nil) and not Terminated do
begin
if FQueueEvent.WaitFor(100) = wrSignaled then
while not Terminated and (FQueue.Count > 0) do
begin
FQueueCS.Enter;
try
Data := FQueue.Dequeue;
FQueueEvent.ResetEvent;
finally
FQueueCS.Leave;
end;
while not DoSend(Data) do
begin
if (Self = Nil) or Terminated then Exit;
ThSleep(GA_TIMEOUT * 60);
end;
ThSleep(GA_TIMEOUT);
end;
end;
finally
FreeAndNil(FHTTP);
end;
except
// Èãíîðèì âñå îøèáêè
end;
end;
procedure TGASender.Send(const Data: string);
begin
FQueueCS.Enter;
try
FQueue.Enqueue(Data);
FQueueEvent.SetEvent;
finally
FQueueCS.Leave;
end;
end;
procedure TGASender.ThSleep(const MSec: Integer);
var
StartTime: Cardinal;
begin
StartTime := GetTickCount;
while (Self <> Nil) and not Terminated and (Abs(GetTickCount - StartTime) < MSec) do
Sleep(50);
end;
initialization
gvGASender := TGASender.Create;
finalization
try
gvGASender.Terminate;
FreeAndNil(gvGASender);
except end;
end.