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