1 |
|
-module(mongoose_system_metrics_sender). |
2 |
|
|
3 |
|
-define(BASE_URL, "https://www.google-analytics.com/mp/collect"). |
4 |
|
|
5 |
|
-export([send/3]). |
6 |
|
|
7 |
|
-type report_struct() :: mongoose_system_metrics_collector:report_struct(). |
8 |
|
|
9 |
|
-spec send(service_mongoose_system_metrics:client_id(), |
10 |
|
[report_struct()], |
11 |
|
[service_mongoose_system_metrics:tracking_id()]) -> ok. |
12 |
|
send(ClientId, Reports, TrackingIds) -> |
13 |
48 |
Url = get_url(), |
14 |
48 |
lists:map( |
15 |
|
fun(TrackingId) -> |
16 |
50 |
flush_reports(Url, Reports, ClientId, TrackingId) |
17 |
|
end, TrackingIds), |
18 |
48 |
ok. |
19 |
|
|
20 |
|
get_url() -> |
21 |
48 |
mongoose_config:get_opt(google_analytics_url, ?BASE_URL). |
22 |
|
|
23 |
|
% https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#limitations |
24 |
|
% % A maximum of 25 hits can be specified per request. |
25 |
|
flush_reports(_, [], _, _) -> |
26 |
:-( |
{ok, nothing_to_do}; |
27 |
|
flush_reports(ReportUrl, Reports, ClientId, |
28 |
|
#{id := TrackingId, secret := TrackingSecret}) when length(Reports) =< 25 -> |
29 |
201 |
Headers = [], |
30 |
201 |
ContentType = "application/json", |
31 |
201 |
Body = jiffy:encode(#{client_id => list_to_binary(ClientId), events => Reports}), |
32 |
201 |
ReportUrl2 = uri_string:normalize( |
33 |
|
ReportUrl ++ "?api_secret=" ++ TrackingSecret ++ "&measurement_id=" ++ TrackingId), |
34 |
201 |
Request = {ReportUrl2, Headers, ContentType, Body}, |
35 |
201 |
httpc:request(post, Request, [{ssl, [{verify, verify_none}]}], []); |
36 |
|
flush_reports(ReportUrl, Reports, ClientId, TrackingId) -> |
37 |
151 |
{NewBatch, RemainingLines} = lists:split(25, Reports), |
38 |
151 |
flush_reports(ReportUrl, NewBatch, ClientId, TrackingId), |
39 |
151 |
flush_reports(ReportUrl, RemainingLines, ClientId, TrackingId). |