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 |
43 |
Url = get_url(), |
14 |
43 |
lists:map( |
15 |
|
fun(TrackingId) -> |
16 |
45 |
flush_reports(Url, Reports, ClientId, TrackingId) |
17 |
|
end, TrackingIds), |
18 |
43 |
ok. |
19 |
|
|
20 |
|
get_url() -> |
21 |
43 |
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 |
179 |
Headers = [], |
30 |
179 |
ContentType = "application/json", |
31 |
179 |
Body = jiffy:encode(#{client_id => list_to_binary(ClientId), events => Reports}), |
32 |
179 |
ReportUrl2 = uri_string:normalize( |
33 |
|
ReportUrl ++ "?api_secret=" ++ TrackingSecret ++ "&measurement_id=" ++ TrackingId), |
34 |
179 |
Request = {ReportUrl2, Headers, ContentType, Body}, |
35 |
179 |
httpc:request(post, Request, [{ssl, [{verify, verify_none}]}], []); |
36 |
|
flush_reports(ReportUrl, Reports, ClientId, TrackingId) -> |
37 |
134 |
{NewBatch, RemainingLines} = lists:split(25, Reports), |
38 |
134 |
flush_reports(ReportUrl, NewBatch, ClientId, TrackingId), |
39 |
134 |
flush_reports(ReportUrl, RemainingLines, ClientId, TrackingId). |