summaryrefslogtreecommitdiffstats
path: root/mobile/android/chrome/content/Reader.js
blob: d0f3d7801a7a748141c6b7b6d1cdbd44368477e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

XPCOMUtils.defineLazyModuleGetter(this, "Snackbars", "resource://gre/modules/Snackbars.jsm");

/*globals MAX_URI_LENGTH, MAX_TITLE_LENGTH */

var Reader = {
  // These values should match those defined in BrowserContract.java.
  STATUS_UNFETCHED: 0,
  STATUS_FETCH_FAILED_TEMPORARY: 1,
  STATUS_FETCH_FAILED_PERMANENT: 2,
  STATUS_FETCH_FAILED_UNSUPPORTED_FORMAT: 3,
  STATUS_FETCHED_ARTICLE: 4,

  get _hasUsedToolbar() {
    delete this._hasUsedToolbar;
    return this._hasUsedToolbar = Services.prefs.getBoolPref("reader.has_used_toolbar");
  },

  /**
   * BackPressListener (listeners / ReaderView Ids).
   */
  _backPressListeners: [],
  _backPressViewIds: [],

  /**
   * Set a backPressListener for this tabId / ReaderView Id pair.
   */
  _addBackPressListener: function(tabId, viewId, listener) {
    this._backPressListeners[tabId] = listener;
    this._backPressViewIds[viewId] = tabId;
  },

  /**
   * Remove a backPressListener for this ReaderView Id.
   */
  _removeBackPressListener: function(viewId) {
    let tabId = this._backPressViewIds[viewId];
    if (tabId != undefined) {
      this._backPressListeners[tabId] = null;
      delete this._backPressViewIds[viewId];
    }
  },

  /**
   * If the requested tab has a backPress listener, return its results, else false.
   */
  onBackPress: function(tabId) {
    let listener = this._backPressListeners[tabId];
    return { handled: (listener ? listener() : false) };
  },

  observe: function Reader_observe(aMessage, aTopic, aData) {
    switch (aTopic) {
      case "Reader:RemoveFromCache": {
        ReaderMode.removeArticleFromCache(aData).catch(e => Cu.reportError("Error removing article from cache: " + e));
        break;
      }

      case "Reader:AddToCache": {
        let tab = BrowserApp.getTabForId(aData);
        if (!tab) {
          throw new Error("No tab for tabID = " + aData + " when trying to save reader view article");
        }

        // If the article is coming from reader mode, we must have fetched it already.
        this._getArticleData(tab.browser).then((article) => {
          ReaderMode.storeArticleInCache(article);
        }).catch(e => Cu.reportError("Error storing article in cache: " + e));
        break;
      }
    }
  },

  receiveMessage: function(message) {
    switch (message.name) {
      case "Reader:ArticleGet":
        this._getArticle(message.data.url).then((article) => {
          // Make sure the target browser is still alive before trying to send data back.
          if (message.target.messageManager) {
            message.target.messageManager.sendAsyncMessage("Reader:ArticleData", { article: article });
          }
        }, e => {
          if (e && e.newURL) {
            message.target.loadURI("about:reader?url=" + encodeURIComponent(e.newURL));
          }
        });
        break;

      // On DropdownClosed in ReaderView, we cleanup / clear existing BackPressListener.
      case "Reader:DropdownClosed": {
        this._removeBackPressListener(message.data);
        break;
      }

      // On DropdownOpened in ReaderView, we add BackPressListener to handle a subsequent BACK request.
      case "Reader:DropdownOpened": {
        let tabId = BrowserApp.selectedTab.id;
        this._addBackPressListener(tabId, message.data, () => {
          // User hit BACK key while ReaderView has the banner font-dropdown opened.
          // Close it and return prevent-default.
          if (message.target.messageManager) {
            message.target.messageManager.sendAsyncMessage("Reader:CloseDropdown");
            return true;
          }
          // We can assume ReaderView banner's font-dropdown doesn't need to be closed.
          return false;
        });

        break;
      }

      case "Reader:FaviconRequest": {
        Messaging.sendRequestForResult({
          type: "Reader:FaviconRequest",
          url: message.data.url
        }).then(data => {
          message.target.messageManager.sendAsyncMessage("Reader:FaviconReturn", JSON.parse(data));
        });
        break;
      }

      case "Reader:SystemUIVisibility":
        Messaging.sendRequest({
          type: "SystemUI:Visibility",
          visible: message.data.visible
        });
        break;

      case "Reader:ToolbarHidden":
        if (!this._hasUsedToolbar) {
          Snackbars.show(Strings.browser.GetStringFromName("readerMode.toolbarTip"), Snackbars.LENGTH_LONG);
          Services.prefs.setBoolPref("reader.has_used_toolbar", true);
          this._hasUsedToolbar = true;
        }
        break;

      case "Reader:UpdateReaderButton": {
        let tab = BrowserApp.getTabForBrowser(message.target);
        tab.browser.isArticle = message.data.isArticle;
        this.updatePageAction(tab);
        break;
      }
    }
  },

  pageAction: {
    readerModeCallback: function(browser) {
      let url = browser.currentURI.spec;
      if (url.startsWith("about:reader")) {
        UITelemetry.addEvent("action.1", "button", null, "reader_exit");
      } else {
        UITelemetry.addEvent("action.1", "button", null, "reader_enter");
      }
      browser.messageManager.sendAsyncMessage("Reader:ToggleReaderMode");
    },
  },

  updatePageAction: function(tab) {
    if (!tab.getActive()) {
      return;
    }

    if (this.pageAction.id) {
      PageActions.remove(this.pageAction.id);
      delete this.pageAction.id;
    }

    let showPageAction = (icon, title) => {
      this.pageAction.id = PageActions.add({
        icon: icon,
        title: title,
        clickCallback: () => this.pageAction.readerModeCallback(browser),
        important: true
      });
    };

    let browser = tab.browser;
    if (browser.currentURI.spec.startsWith("about:reader")) {
      showPageAction("drawable://reader_active", Strings.reader.GetStringFromName("readerView.close"));
      // Only start a reader session if the viewer is in the foreground. We do
      // not track background reader viewers.
      UITelemetry.startSession("reader.1", null);
      return;
    }

    // Only stop a reader session if the foreground viewer is not visible.
    UITelemetry.stopSession("reader.1", "", null);

    if (browser.isArticle) {
      showPageAction("drawable://reader", Strings.reader.GetStringFromName("readerView.enter"));
      UITelemetry.addEvent("show.1", "button", null, "reader_available");
    } else {
      UITelemetry.addEvent("show.1", "button", null, "reader_unavailable");
    }
  },

  /**
   * Gets an article for a given URL. This method will download and parse a document
   * if it does not find the article in the cache.
   *
   * @param url The article URL.
   * @return {Promise}
   * @resolves JS object representing the article, or null if no article is found.
   */
  _getArticle: Task.async(function* (url) {
    // First try to find a parsed article in the cache.
    let article = yield ReaderMode.getArticleFromCache(url);
    if (article) {
      return article;
    }

    // Article hasn't been found in the cache, we need to
    // download the page and parse the article out of it.
    return yield ReaderMode.downloadAndParseDocument(url).catch(e => {
      if (e && e.newURL) {
        // Pass up the error so we can navigate the browser in question to the new URL:
        throw e;
      }
      Cu.reportError("Error downloading and parsing document: " + e);
      return null;
    });
  }),

  _getArticleData: function(browser) {
    return new Promise((resolve, reject) => {
      if (browser == null) {
        reject("_getArticleData needs valid browser");
      }

      let mm = browser.messageManager;
      let listener = (message) => {
        mm.removeMessageListener("Reader:StoredArticleData", listener);
        resolve(message.data.article);
      };
      mm.addMessageListener("Reader:StoredArticleData", listener);
      mm.sendAsyncMessage("Reader:GetStoredArticleData");
    });
  },


  /**
   * Migrates old indexedDB reader mode cache to new JSON cache.
   */
  migrateCache: Task.async(function* () {
    let cacheDB = yield new Promise((resolve, reject) => {
      let request = window.indexedDB.open("about:reader", 1);
      request.onsuccess = event => resolve(event.target.result);
      request.onerror = event => reject(request.error);

      // If there is no DB to migrate, don't do anything.
      request.onupgradeneeded = event => resolve(null);
    });

    if (!cacheDB) {
      return;
    }

    let articles = yield new Promise((resolve, reject) => {
      let articles = [];

      let transaction = cacheDB.transaction(cacheDB.objectStoreNames);
      let store = transaction.objectStore(cacheDB.objectStoreNames[0]);

      let request = store.openCursor();
      request.onsuccess = event => {
        let cursor = event.target.result;
        if (!cursor) {
          resolve(articles);
        } else {
          articles.push(cursor.value);
          cursor.continue();
        }
      };
      request.onerror = event => reject(request.error);
    });

    for (let article of articles) {
      yield ReaderMode.storeArticleInCache(article);
    }

    // Delete the database.
    window.indexedDB.deleteDatabase("about:reader");
  }),
};