JAL-4001 GA4 tracking is now ENABLED. Currently logging a page_view like the website...
[jalview.git] / src / jalview / analytics / GoogleAnalytics4.java
1 package jalview.analytics;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.net.HttpURLConnection;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.net.URLConnection;
9 import java.net.URLEncoder;
10 import java.nio.charset.StandardCharsets;
11 import java.util.AbstractMap;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Random;
18 import java.util.UUID;
19
20 import jalview.bin.Cache;
21 import jalview.bin.Console;
22 import jalview.util.ChannelProperties;
23
24 public class GoogleAnalytics4
25 {
26   private static final String JALVIEW_ID = "Jalview Desktop";
27
28   private static final String SESSION_ID = new Random().toString();
29
30   private static final String MEASUREMENT_ID = "G-6TMPHMXEQ0";
31
32   private static final String API_SECRET = "Qb9NSbqkRDqizG6j2BBJ2g";
33
34   // This will generate a different CLIENT_ID each time the application is
35   // launched. Do we want to store it in .jalview_properties?
36   private static final String CLIENT_ID = UUID.randomUUID().toString();
37
38   private static final String BASE_URL = "https://www.google-analytics.com/mp/collect";
39
40   private List<Map.Entry<String, String>> queryStringValues;
41
42   private List<Map.Entry<String, Object>> jsonObject;
43
44   private List<Event> events;
45
46   private List<Map.Entry<String, String>> cookieValues;
47
48   private static boolean ENABLED = false;
49
50   private static GoogleAnalytics4 instance = null;
51
52   private static final String appName;
53
54   private static final String version;
55
56   static
57   {
58     appName = ChannelProperties.getProperty("app_name") + " Desktop";
59     version = Cache.getProperty("VERSION") + "_"
60             + Cache.getDefault("BUILD_DATE", "unknown");
61   }
62
63   private GoogleAnalytics4()
64   {
65     this.resetLists();
66   }
67
68   public static void setEnabled(boolean b)
69   {
70     ENABLED = b;
71   }
72
73   public void sendAnalytics(String eventName, String... paramsStrings)
74   {
75     // clear out old lists
76     this.resetLists();
77
78     if (!ENABLED)
79     {
80       Console.debug("GoogleAnalytics4 not enabled.");
81       return;
82     }
83     Map<String, String> params = new HashMap<>();
84
85     // add these to all events from this application instance
86     params.put("app_name", appName);
87     params.put("version", version);
88     params.put("TEST", "you've got to pick a pocket or twoooooo");
89
90     // can be overwritten by passed in params
91     if (paramsStrings != null && paramsStrings.length > 0)
92     {
93       if (paramsStrings.length % 2 != 0)
94       {
95         Console.warn(
96                 "Cannot addEvent with odd number of paramsStrings.  Ignoring the last one.");
97       }
98       for (int i = 0; i < paramsStrings.length - 1; i += 2)
99       {
100         String key = paramsStrings[i];
101         String value = paramsStrings[i + 1];
102         params.put(key, value);
103       }
104     }
105
106     addEvent(eventName, params);
107     addQueryStringValue("measurement_id", MEASUREMENT_ID);
108     addQueryStringValue("api_secret", API_SECRET);
109     addJsonValue("client_id", CLIENT_ID);
110     addJsonValues("events", Event.toObjectList(events));
111     StringBuilder urlSb = new StringBuilder();
112     urlSb.append(BASE_URL);
113     urlSb.append('?');
114     urlSb.append(buildQueryString());
115     try
116     {
117       URL url = new URL(urlSb.toString());
118       URLConnection urlConnection = url.openConnection();
119       HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
120       httpURLConnection.setRequestMethod("POST");
121       httpURLConnection.setDoOutput(true);
122
123       String jsonString = buildJson();
124
125       Console.debug("GA4: HTTP Request is: '" + urlSb.toString() + "'");
126       Console.debug("GA4: POSTed JSON is:\n" + jsonString);
127
128       byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
129       int jsonLength = jsonBytes.length;
130
131       httpURLConnection.setFixedLengthStreamingMode(jsonLength);
132       httpURLConnection.setRequestProperty("Content-Type",
133               "application/json; charset=UTF-8");
134       httpURLConnection.connect();
135       try (OutputStream os = httpURLConnection.getOutputStream())
136       {
137         os.write(jsonBytes);
138       }
139       int responseCode = httpURLConnection.getResponseCode();
140       String responseMessage = httpURLConnection.getResponseMessage();
141       if (responseCode < 200 || responseCode > 299)
142       {
143         Console.warn("GoogleAnalytics4 connection failed: '" + responseCode
144                 + " " + responseMessage + "'");
145       }
146       else
147       {
148         Console.debug("GoogleAnalytics4 connection succeeded: '"
149                 + responseCode + " " + responseMessage + "'");
150       }
151     } catch (MalformedURLException e)
152     {
153       Console.debug(
154               "Somehow the GoogleAnalytics4 BASE_URL and queryString is malformed.",
155               e);
156       return;
157     } catch (IOException e)
158     {
159       Console.debug("Connection to GoogleAnalytics4 BASE_URL '" + BASE_URL
160               + "' failed.", e);
161     } catch (ClassCastException e)
162     {
163       Console.debug(
164               "Couldn't cast URLConnection to HttpURLConnection in GoogleAnalytics4.",
165               e);
166     }
167   }
168
169   public void addEvent(String name, Map<String, String> params)
170   {
171     Event event = new Event(name);
172     if (params != null && params.size() > 0)
173     {
174       for (String key : params.keySet())
175       {
176         String value = params.get(key);
177         event.addParam(key, value);
178       }
179     }
180     events.add(event);
181   }
182
183   private void addJsonObject(String key,
184           List<Map.Entry<String, Object>> object)
185   {
186     jsonObject.add(objectEntry(key, object));
187   }
188
189   private void addJsonValues(String key, List<Object> values)
190   {
191     jsonObject.add(objectEntry(key, values));
192   }
193
194   private void addJsonValue(String key, String value)
195   {
196     jsonObject.add(objectEntry(key, value));
197   }
198
199   private void addJsonValue(String key, int value)
200   {
201     jsonObject.add(objectEntry(key, Integer.valueOf(value)));
202   }
203
204   private void addJsonValue(String key, boolean value)
205   {
206     jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
207   }
208
209   private void addQueryStringValue(String key, String value)
210   {
211     queryStringValues.add(stringEntry(key, value));
212   }
213
214   private void addCookieValue(String key, String value)
215   {
216     cookieValues.add(stringEntry(key, value));
217   }
218
219   private void resetLists()
220   {
221     jsonObject = new ArrayList<>();
222     events = new ArrayList<Event>();
223     queryStringValues = new ArrayList<>();
224     cookieValues = new ArrayList<>();
225   }
226
227   public static GoogleAnalytics4 getInstance()
228   {
229     if (instance == null)
230     {
231       instance = new GoogleAnalytics4();
232     }
233     return instance;
234   }
235
236   public static void reset()
237   {
238     getInstance().resetLists();
239   }
240
241   private String buildQueryString()
242   {
243     StringBuilder sb = new StringBuilder();
244     for (Map.Entry<String, String> entry : queryStringValues)
245     {
246       if (sb.length() > 0)
247       {
248         sb.append('&');
249       }
250       sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
251       sb.append('=');
252       sb.append(
253               URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
254     }
255     return sb.toString();
256   }
257
258   private void buildCookieHeaders()
259   {
260     // TODO not needed yet
261   }
262
263   private String buildJson()
264   {
265     StringBuilder sb = new StringBuilder();
266     addJsonObject(sb, 0, jsonObject);
267     return sb.toString();
268   }
269
270   private void addJsonObject(StringBuilder sb, int indent,
271           List<Map.Entry<String, Object>> entries)
272   {
273     indent(sb, indent);
274     sb.append('{');
275     newline(sb);
276     Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
277     while (entriesI.hasNext())
278     {
279       Map.Entry<String, Object> entry = entriesI.next();
280       String key = entry.getKey();
281       // TODO sensibly escape " characters in key
282       Object value = entry.getValue();
283       indent(sb, indent + 1);
284       sb.append('"').append(quoteEscape(key)).append('"').append(':');
285       space(sb);
286       if (value != null && value instanceof List)
287       {
288         newline(sb);
289       }
290       addJsonValue(sb, indent + 2, value);
291       if (entriesI.hasNext())
292       {
293         sb.append(',');
294       }
295       newline(sb);
296     }
297     indent(sb, indent);
298     sb.append('}');
299   }
300
301   private void addJsonValue(StringBuilder sb, int indent, Object value)
302   {
303     if (value == null)
304     {
305       return;
306     }
307     try
308     {
309       if (value instanceof Map.Entry)
310       {
311         Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
312         List<Map.Entry<String, Object>> object = new ArrayList<>();
313         object.add(entry);
314         addJsonObject(sb, indent, object);
315       }
316       else if (value instanceof List)
317       {
318         // list of Map.Entries or list of values?
319         List<Object> valueList = (List<Object>) value;
320         if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
321         {
322           // entries
323           // indent(sb, indent);
324           List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
325           addJsonObject(sb, indent, entryList);
326         }
327         else
328         {
329           // values
330           indent(sb, indent);
331           sb.append('[');
332           newline(sb);
333           Iterator<Object> valueListI = valueList.iterator();
334           while (valueListI.hasNext())
335           {
336             Object v = valueListI.next();
337             addJsonValue(sb, indent + 1, v);
338             if (valueListI.hasNext())
339             {
340               sb.append(',');
341             }
342             newline(sb);
343           }
344           indent(sb, indent);
345           sb.append("]");
346         }
347       }
348       else if (value instanceof String)
349       {
350         sb.append('"').append(quoteEscape((String) value)).append('"');
351       }
352       else if (value instanceof Integer)
353       {
354         sb.append(((Integer) value).toString());
355       }
356       else if (value instanceof Boolean)
357       {
358         sb.append('"').append(((Boolean) value).toString()).append('"');
359       }
360     } catch (ClassCastException e)
361     {
362       Console.debug(
363               "Could not deal with type of json Object " + value.toString(),
364               e);
365     }
366   }
367
368   private static String quoteEscape(String s)
369   {
370     if (s == null)
371     {
372       return null;
373     }
374     // this escapes quotation marks (") that aren't already escaped (in the
375     // string) ready to go into a quoted JSON string value
376     return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
377   }
378
379   private static void prettyWhitespace(StringBuilder sb, String whitespace,
380           int repeat)
381   {
382     // only add whitespace if we're in DEBUG mode
383     if (!Console.getLogger().isDebugEnabled())
384     {
385       return;
386     }
387     if (repeat >= 0 && whitespace != null)
388     {
389       sb.append(whitespace.repeat(repeat));
390     }
391     else
392     {
393       sb.append(whitespace);
394     }
395   }
396
397   private static void indent(StringBuilder sb, int indent)
398   {
399     prettyWhitespace(sb, "  ", indent);
400   }
401
402   private static void newline(StringBuilder sb)
403   {
404     prettyWhitespace(sb, "\n", -1);
405   }
406
407   private static void space(StringBuilder sb)
408   {
409     prettyWhitespace(sb, " ", -1);
410   }
411
412   protected static Map.Entry<String, Object> objectEntry(String s, Object o)
413   {
414     return new AbstractMap.SimpleEntry<String, Object>(s, o);
415   }
416
417   protected static Map.Entry<String, String> stringEntry(String s, String v)
418   {
419     return new AbstractMap.SimpleEntry<String, String>(s, v);
420   }
421 }
422
423 class Event
424 {
425   private String name;
426
427   private List<Map.Entry<String, String>> params;
428
429   @SafeVarargs
430   public Event(String name, Map.Entry<String, String>... paramEntries)
431   {
432     this.name = name;
433     this.params = new ArrayList<Map.Entry<String, String>>();
434     for (Map.Entry<String, String> paramEntry : paramEntries)
435     {
436       if (paramEntry == null)
437       {
438         continue;
439       }
440       params.add(paramEntry);
441     }
442   }
443
444   public void addParam(String param, String value)
445   {
446     params.add(GoogleAnalytics4.stringEntry(param, value));
447   }
448
449   protected List<Map.Entry<String, Object>> toObject()
450   {
451     List<Map.Entry<String, Object>> object = new ArrayList<>();
452     object.add(GoogleAnalytics4.objectEntry("name", (Object) name));
453     if (params.size() > 0)
454     {
455       object.add(GoogleAnalytics4.objectEntry("params", (Object) params));
456     }
457     return object;
458   }
459
460   protected static List<Object> toObjectList(List<Event> events)
461   {
462     List<Object> eventObjectList = new ArrayList<>();
463     for (Event event : events)
464     {
465       eventObjectList.add((Object) event.toObject());
466     }
467     return eventObjectList;
468   }
469 }