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