JAL-4001 Plausible class
[jalview.git] / src / jalview / analytics / Plausible.java
1 package jalview.analytics;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.OutputStream;
7 import java.io.UnsupportedEncodingException;
8 import java.lang.invoke.MethodHandles;
9 import java.net.HttpURLConnection;
10 import java.net.MalformedURLException;
11 import java.net.URL;
12 import java.net.URLConnection;
13 import java.net.URLEncoder;
14 import java.nio.charset.StandardCharsets;
15 import java.util.AbstractMap;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Map;
22
23 import jalview.bin.Cache;
24 import jalview.bin.Console;
25 import jalview.util.ChannelProperties;
26
27 public class Plausible
28 {
29   private static final String USER_AGENT = ChannelProperties
30           .getProperty("app_name", "Jalview") + " "
31           + Cache.getDefault("VERSION", "Unknown") + " "
32           + MethodHandles.lookup().lookupClass() + " help@jalview.org";
33
34   private static final String JALVIEW_ID = "Jalview Desktop";
35
36   private static final String DOMAIN = "jalview.org";
37
38   private static final String BASE_URL = "https://plausible.io/api/event";
39
40   public static final String APPLICATION_BASE_URL = "desktop://localhost";
41
42   private List<Map.Entry<String, String>> queryStringValues;
43
44   private List<Map.Entry<String, Object>> jsonObject;
45
46   private List<Event> events;
47
48   private List<Map.Entry<String, String>> cookieValues;
49
50   private static boolean ENABLED = false;
51
52   private static Plausible instance = null;
53
54   private static final Map<String, String> defaultParams;
55
56   static
57   {
58     defaultParams = new HashMap<>();
59     defaultParams.put("app_name",
60             ChannelProperties.getProperty("app_name") + " Desktop");
61     defaultParams.put("version", Cache.getProperty("VERSION"));
62     defaultParams.put("build_date",
63             Cache.getDefault("BUILD_DATE", "unknown"));
64     defaultParams.put("java_version", System.getProperty("java.version"));
65     String val = System.getProperty("sys.install4jVersion");
66     if (val != null)
67     {
68       defaultParams.put("install4j_version", val);
69     }
70     val = System.getProperty("installer_template_version");
71     if (val != null)
72     {
73       defaultParams.put("install4j_template_version", val);
74     }
75     val = System.getProperty("launcher_version");
76     if (val != null)
77     {
78       defaultParams.put("launcher_version", val);
79     }
80     defaultParams.put("java_arch",
81             System.getProperty("os.arch") + " "
82                     + System.getProperty("os.name") + " "
83                     + System.getProperty("os.version"));
84   }
85
86   private Plausible()
87   {
88     this.resetLists();
89   }
90
91   public static void setEnabled(boolean b)
92   {
93     ENABLED = b;
94   }
95
96   public void sendAnalytics(String eventName, String... paramsStrings)
97   {
98     sendAnalytics(eventName, false, paramsStrings);
99   }
100
101   /**
102    * The simplest way to send an analytic event.
103    * 
104    * @param eventName
105    *          The event name. To emulate a webpage view use "page_view" and set
106    *          a "page_location" parameter. See
107    *          https://developers.google.com/analytics/devguides/collection/ga4/events?client_type=gtag
108    * @param sendDefaultParams
109    *          Flag whether to add the default params about the application.
110    * @param paramsStrings
111    *          Optional multiple Strings in key, value pairs (there should be an
112    *          even number of paramsStrings) to be set as parameters of the
113    *          event. To emulate a webpage view use "page_location" as the URL in
114    *          a "page_view" event.
115    */
116   public void sendAnalytics(String eventName, boolean sendDefaultParams,
117           String... paramsStrings)
118   {
119     // clear out old lists
120     this.resetLists();
121
122     if (!ENABLED)
123     {
124       Console.debug("Plausible not enabled.");
125       return;
126     }
127     Map<String, String> params = new HashMap<>();
128
129     // add these to all events from this application instance
130     if (sendDefaultParams)
131     {
132       params.putAll(defaultParams);
133     }
134
135     // add (and overwrite with) the passed in params
136     if (paramsStrings != null && paramsStrings.length > 0)
137     {
138       if (paramsStrings.length % 2 != 0)
139       {
140         Console.warn(
141                 "Cannot addEvent with odd number of paramsStrings.  Ignoring the last one.");
142       }
143       for (int i = 0; i < paramsStrings.length - 1; i += 2)
144       {
145         String key = paramsStrings[i];
146         String value = paramsStrings[i + 1];
147         params.put(key, value);
148       }
149     }
150
151     addEvent(eventName, params);
152     addQueryStringValue("measurement_id", MEASUREMENT_ID);
153     addQueryStringValue("api_secret", API_SECRET);
154     addQueryStringValue("_geo", "1");
155     addQueryStringValue("ep.anonymize_ip", "false");
156     addJsonValue("client_id", CLIENT_ID);
157     addJsonValues("events", Event.toObjectList(events));
158     StringBuilder urlSb = new StringBuilder();
159     urlSb.append(BASE_URL);
160     urlSb.append('?');
161     urlSb.append(buildQueryString());
162     try
163     {
164       URL url = new URL(urlSb.toString());
165       URLConnection urlConnection = url.openConnection();
166       HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
167       httpURLConnection.setRequestMethod("POST");
168       httpURLConnection.setDoOutput(true);
169
170       String jsonString = buildJson();
171
172       Console.debug("GA4: HTTP Request is: '" + urlSb.toString() + "'");
173       Console.debug("GA4: POSTed JSON is:\n" + jsonString);
174
175       byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
176       int jsonLength = jsonBytes.length;
177
178       httpURLConnection.setFixedLengthStreamingMode(jsonLength);
179       httpURLConnection.setRequestProperty("Content-Type",
180               "application/json; charset=UTF-8");
181       httpURLConnection.connect();
182       try (OutputStream os = httpURLConnection.getOutputStream())
183       {
184         os.write(jsonBytes);
185       }
186       int responseCode = httpURLConnection.getResponseCode();
187       String responseMessage = httpURLConnection.getResponseMessage();
188
189       if (responseCode < 200 || responseCode > 299)
190       {
191         Console.warn("Plausible connection failed: '" + responseCode + " "
192                 + responseMessage + "'");
193       }
194       else
195       {
196         Console.debug("Plausible connection succeeded: '" + responseCode
197                 + " " + responseMessage + "'");
198       }
199
200       if (DEBUG)
201       {
202         BufferedReader br = new BufferedReader(new InputStreamReader(
203                 (httpURLConnection.getInputStream())));
204         StringBuilder sb = new StringBuilder();
205         String response;
206         while ((response = br.readLine()) != null)
207         {
208           sb.append(response);
209         }
210         String body = sb.toString();
211         Console.debug("Plausible response content; " + body);
212       }
213     } catch (MalformedURLException e)
214     {
215       Console.debug(
216               "Somehow the Plausible BASE_URL and queryString is malformed: '"
217                       + urlSb.toString() + "'",
218               e);
219       return;
220     } catch (IOException e)
221     {
222       Console.debug(
223               "Connection to Plausible BASE_URL '" + BASE_URL + "' failed.",
224               e);
225     } catch (ClassCastException e)
226     {
227       Console.debug(
228               "Couldn't cast URLConnection to HttpURLConnection in Plausible.",
229               e);
230     }
231   }
232
233   public void addEvent(String name, Map<String, String> params)
234   {
235     Event event = new Event(name);
236     if (params != null && params.size() > 0)
237     {
238       for (String key : params.keySet())
239       {
240         String value = params.get(key);
241         event.addParam(key, value);
242       }
243     }
244     events.add(event);
245   }
246
247   private void addJsonObject(String key,
248           List<Map.Entry<String, Object>> object)
249   {
250     jsonObject.add(objectEntry(key, object));
251   }
252
253   private void addJsonValues(String key, List<Object> values)
254   {
255     jsonObject.add(objectEntry(key, values));
256   }
257
258   private void addJsonValue(String key, String value)
259   {
260     jsonObject.add(objectEntry(key, value));
261   }
262
263   private void addJsonValue(String key, int value)
264   {
265     jsonObject.add(objectEntry(key, Integer.valueOf(value)));
266   }
267
268   private void addJsonValue(String key, boolean value)
269   {
270     jsonObject.add(objectEntry(key, Boolean.valueOf(value)));
271   }
272
273   private void addQueryStringValue(String key, String value)
274   {
275     queryStringValues.add(stringEntry(key, value));
276   }
277
278   private void addCookieValue(String key, String value)
279   {
280     cookieValues.add(stringEntry(key, value));
281   }
282
283   private void resetLists()
284   {
285     jsonObject = new ArrayList<>();
286     events = new ArrayList<Event>();
287     queryStringValues = new ArrayList<>();
288     cookieValues = new ArrayList<>();
289   }
290
291   public static Plausible getInstance()
292   {
293     if (instance == null)
294     {
295       instance = new Plausible();
296     }
297     return instance;
298   }
299
300   public static void reset()
301   {
302     getInstance().resetLists();
303   }
304
305   private String buildQueryString()
306   {
307     StringBuilder sb = new StringBuilder();
308     for (Map.Entry<String, String> entry : queryStringValues)
309     {
310       if (sb.length() > 0)
311       {
312         sb.append('&');
313       }
314       try
315       {
316         sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
317       } catch (UnsupportedEncodingException e)
318       {
319         sb.append(entry.getKey());
320       }
321       sb.append('=');
322       try
323       {
324         sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
325       } catch (UnsupportedEncodingException e)
326       {
327         sb.append(entry.getValue());
328       }
329     }
330     return sb.toString();
331   }
332
333   private void buildCookieHeaders()
334   {
335     // TODO not needed yet
336   }
337
338   private String buildJson()
339   {
340     StringBuilder sb = new StringBuilder();
341     addJsonObject(sb, 0, jsonObject);
342     return sb.toString();
343   }
344
345   private void addJsonObject(StringBuilder sb, int indent,
346           List<Map.Entry<String, Object>> entries)
347   {
348     indent(sb, indent);
349     sb.append('{');
350     newline(sb);
351     Iterator<Map.Entry<String, Object>> entriesI = entries.iterator();
352     while (entriesI.hasNext())
353     {
354       Map.Entry<String, Object> entry = entriesI.next();
355       String key = entry.getKey();
356       // TODO sensibly escape " characters in key
357       Object value = entry.getValue();
358       indent(sb, indent + 1);
359       sb.append('"').append(quoteEscape(key)).append('"').append(':');
360       space(sb);
361       if (value != null && value instanceof List)
362       {
363         newline(sb);
364       }
365       addJsonValue(sb, indent + 2, value);
366       if (entriesI.hasNext())
367       {
368         sb.append(',');
369       }
370       newline(sb);
371     }
372     indent(sb, indent);
373     sb.append('}');
374   }
375
376   private void addJsonValue(StringBuilder sb, int indent, Object value)
377   {
378     if (value == null)
379     {
380       return;
381     }
382     try
383     {
384       if (value instanceof Map.Entry)
385       {
386         Map.Entry<String, Object> entry = (Map.Entry<String, Object>) value;
387         List<Map.Entry<String, Object>> object = new ArrayList<>();
388         object.add(entry);
389         addJsonObject(sb, indent, object);
390       }
391       else if (value instanceof List)
392       {
393         // list of Map.Entries or list of values?
394         List<Object> valueList = (List<Object>) value;
395         if (valueList.size() > 0 && valueList.get(0) instanceof Map.Entry)
396         {
397           // entries
398           // indent(sb, indent);
399           List<Map.Entry<String, Object>> entryList = (List<Map.Entry<String, Object>>) value;
400           addJsonObject(sb, indent, entryList);
401         }
402         else
403         {
404           // values
405           indent(sb, indent);
406           sb.append('[');
407           newline(sb);
408           Iterator<Object> valueListI = valueList.iterator();
409           while (valueListI.hasNext())
410           {
411             Object v = valueListI.next();
412             addJsonValue(sb, indent + 1, v);
413             if (valueListI.hasNext())
414             {
415               sb.append(',');
416             }
417             newline(sb);
418           }
419           indent(sb, indent);
420           sb.append("]");
421         }
422       }
423       else if (value instanceof String)
424       {
425         sb.append('"').append(quoteEscape((String) value)).append('"');
426       }
427       else if (value instanceof Integer)
428       {
429         sb.append(((Integer) value).toString());
430       }
431       else if (value instanceof Boolean)
432       {
433         sb.append('"').append(((Boolean) value).toString()).append('"');
434       }
435     } catch (ClassCastException e)
436     {
437       Console.debug(
438               "Could not deal with type of json Object " + value.toString(),
439               e);
440     }
441   }
442
443   private static String quoteEscape(String s)
444   {
445     if (s == null)
446     {
447       return null;
448     }
449     // this escapes quotation marks (") that aren't already escaped (in the
450     // string) ready to go into a quoted JSON string value
451     return s.replaceAll("((?<!\\\\)(?:\\\\{2})*)\"", "$1\\\\\"");
452   }
453
454   private static void prettyWhitespace(StringBuilder sb, String whitespace,
455           int repeat)
456   {
457     // only add whitespace if we're in DEBUG mode
458     if (!Console.getLogger().isDebugEnabled())
459     {
460       return;
461     }
462     if (repeat >= 0 && whitespace != null)
463     {
464       // sb.append(whitespace.repeat(repeat));
465       sb.append(String.join("", Collections.nCopies(repeat, whitespace)));
466
467     }
468     else
469     {
470       sb.append(whitespace);
471     }
472   }
473
474   private static void indent(StringBuilder sb, int indent)
475   {
476     prettyWhitespace(sb, "  ", indent);
477   }
478
479   private static void newline(StringBuilder sb)
480   {
481     prettyWhitespace(sb, "\n", -1);
482   }
483
484   private static void space(StringBuilder sb)
485   {
486     prettyWhitespace(sb, " ", -1);
487   }
488
489   protected static Map.Entry<String, Object> objectEntry(String s, Object o)
490   {
491     return new AbstractMap.SimpleEntry<String, Object>(s, o);
492   }
493
494   protected static Map.Entry<String, String> stringEntry(String s, String v)
495   {
496     return new AbstractMap.SimpleEntry<String, String>(s, v);
497   }
498
499   private static class Event
500   {
501     private String name;
502
503     private List<Map.Entry<String, String>> params;
504
505     @SafeVarargs
506     public Event(String name, Map.Entry<String, String>... paramEntries)
507     {
508       this.name = name;
509       this.params = new ArrayList<Map.Entry<String, String>>();
510       for (Map.Entry<String, String> paramEntry : paramEntries)
511       {
512         if (paramEntry == null)
513         {
514           continue;
515         }
516         params.add(paramEntry);
517       }
518     }
519
520     public void addParam(String param, String value)
521     {
522       params.add(Plausible.stringEntry(param, value));
523     }
524
525     protected List<Map.Entry<String, Object>> toObject()
526     {
527       List<Map.Entry<String, Object>> object = new ArrayList<>();
528       object.add(Plausible.objectEntry("name", (Object) name));
529       if (params.size() > 0)
530       {
531         object.add(Plausible.objectEntry("params", (Object) params));
532       }
533       return object;
534     }
535
536     protected static List<Object> toObjectList(List<Event> events)
537     {
538       List<Object> eventObjectList = new ArrayList<>();
539       for (Event event : events)
540       {
541         eventObjectList.add((Object) event.toObject());
542       }
543       return eventObjectList;
544     }
545   }
546
547 }