Fix: support secondary Google accounts

When multiple Google accounts are signed in, Google adds an authuser
parameter in the URLs to indicate which account should be used.

This extension adds support for secondary Google Accounts, so the
extension works well when using it with them, by adding the authuser
parameter whenever it is needed.

Before this change, some features were broken if being used with a
secondary account.

Note that this doesn't fix the CC bug which consists in the fact that
URLs formed by the CC don't include the authuser parameter, because this
change only fixes the URLs injected by the extension, and the HTTP
requests made by the extension.

Change-Id: I0da5911f4b41057aa94b2834bd9a4313919fcbd4
diff --git a/src/content_scripts/console_inject.js b/src/content_scripts/console_inject.js
index d804459..ee3bffb 100644
--- a/src/content_scripts/console_inject.js
+++ b/src/content_scripts/console_inject.js
@@ -1,4 +1,4 @@
-var mutationObserver, intersectionObserver, options;
+var mutationObserver, intersectionObserver, options, authuser;
 
 function parseUrl(url) {
   var forum_a = url.match(/forum\/([0-9]+)/i);
@@ -16,12 +16,16 @@
 
 function addProfileHistoryLink(node, type, query) {
   var urlpart = encodeURIComponent('query=' + query);
+  var authuserpart =
+      (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
   var container = document.createElement('div');
   container.style.margin = '3px 0';
 
   var link = document.createElement('a');
   link.setAttribute(
-      'href', 'https://support.google.com/s/community/search/' + urlpart);
+      'href',
+      'https://support.google.com/s/community/search/' + urlpart +
+          authuserpart);
   link.innerText = chrome.i18n.getMessage('inject_previousposts_' + type);
 
   container.appendChild(link);
@@ -118,6 +122,10 @@
 chrome.storage.sync.get(null, function(items) {
   options = items;
 
+  var startup =
+      JSON.parse(document.querySelector('html').getAttribute('data-startup'));
+  authuser = startup[2][1] || '0';
+
   mutationObserver = new MutationObserver(mutationCallback);
   mutationObserver.observe(
       document.querySelector('.scrollable-content'), observerOptions);
diff --git a/src/injections/profileindicator_inject.js b/src/injections/profileindicator_inject.js
index e7935c8..352e3ca 100644
--- a/src/injections/profileindicator_inject.js
+++ b/src/injections/profileindicator_inject.js
@@ -2,6 +2,8 @@
     /^(?:https:\/\/support\.google\.com)?\/s\/community\/forum\/[0-9]*\/user\/(?:[0-9]+)$/;
 var CCRegex = /^https:\/\/support\.google\.com\/s\/community/;
 
+const BASE_URL = 'https://support.google.com/s/community/api/';
+
 const OP_FIRST_POST = 0;
 const OP_OTHER_POSTS_READ = 1;
 const OP_OTHER_POSTS_UNREAD = 2;
@@ -26,6 +28,8 @@
 
 const numPostsForumArraysToSum = [3, 4];
 
+var authuser = null;
+
 function isElementInside(element, outerTag) {
   while (element !== null && ('tagName' in element)) {
     if (element.tagName == outerTag) return true;
@@ -41,42 +45,42 @@
   return username.replace(quoteRegex, '\\"').replace(commentRegex, '');
 }
 
-function getPosts(query, forumId) {
-  return fetch('https://support.google.com/s/community/api/ViewForum', {
+function APIRequest(action, body) {
+  var authuserPart =
+      (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
+
+  return fetch(BASE_URL + action + authuserPart, {
            'credentials': 'include',
            'headers': {'content-type': 'text/plain; charset=utf-8'},
-           'body': JSON.stringify({
-             '1': forumId,
-             '2': {
-               '1': {
-                 '2': 5,
-               },
-               '2': {
-                 '1': 1,
-                 '2': true,
-               },
-               '12': query,
-             },
-           }),
+           'body': JSON.stringify(body),
            'method': 'POST',
            'mode': 'cors',
          })
       .then(res => res.json());
 }
 
+function getPosts(query, forumId) {
+  return APIRequest('ViewForum', {
+    '1': forumId,
+    '2': {
+      '1': {
+        '2': 5,
+      },
+      '2': {
+        '1': 1,
+        '2': true,
+      },
+      '12': query,
+    },
+  });
+}
+
 function getProfile(userId, forumId) {
-  return fetch('https://support.google.com/s/community/api/ViewUser', {
-           'credentials': 'include',
-           'headers': {'content-type': 'text/plain; charset=utf-8'},
-           'body': JSON.stringify({
-             '1': userId,
-             '2': 0,
-             '3': forumId,
-           }),
-           'method': 'POST',
-           'mode': 'cors',
-         })
-      .then(res => res.json());
+  return APIRequest('ViewUser', {
+    '1': userId,
+    '2': 0,
+    '3': forumId,
+  });
 }
 
 // Source:
@@ -192,11 +196,15 @@
       escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
   var encodedQuery =
       encodeURIComponent(query + (isCC ? ' forum:' + forumId : ''));
+  var authuserPart =
+      (authuser == '0' ?
+           '' :
+           (isCC ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
   var searchURL =
       (isCC ? 'https://support.google.com/s/community/search/' +
-               encodeURIComponent('query=' + encodedQuery) :
+               encodeURIComponent('query=' + encodedQuery) + authuserPart :
               document.location.pathname.split('/thread')[0] +
-               '/threads?thread_filter=' + encodedQuery);
+               '/threads?thread_filter=' + encodedQuery + authuserPart);
 
   if (options.numPosts) {
     var profileURL = new URL(sourceNode.href);
@@ -311,6 +319,11 @@
 
 if (CCRegex.test(location.href)) {
   // We are in the Community Console
+  var startup =
+      JSON.parse(document.querySelector('html').getAttribute('data-startup'));
+
+  authuser = startup[2][1] || '0';
+
   function mutationCallback(mutationList, observer) {
     mutationList.forEach((mutation) => {
       if (mutation.type == 'childList') {
@@ -336,6 +349,8 @@
       document.querySelector('.scrollable-content'), observerOptions);
 } else {
   // We are in TW
+  authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
+
   var node =
       document.querySelector('.thread-question a.user-info-display-name');
   if (node !== null)