summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/extensions/newsblog/newsblogOverlay.js
blob: 9145ad0dab0d1b2fd28809d2e252d71f87c56081 (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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/* -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 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/. */

/* globals ReloadMessage, getMessagePaneBrowser, openContentTab,
           GetNumSelectedMessages, gMessageNotificationBar */

var { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);
var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
var { FeedUtils } = ChromeUtils.import("resource:///modules/FeedUtils.jsm");
var { MailE10SUtils } = ChromeUtils.import(
  "resource:///modules/MailE10SUtils.jsm"
);

XPCOMUtils.defineLazyModuleGetters(this, {
  MsgHdrToMimeMessage: "resource:///modules/gloda/MimeMessage.jsm",
});

// This global is for SeaMonkey compatibility.
var gShowFeedSummary;

var FeedMessageHandler = {
  gShowSummary: true,
  gToggle: false,
  kSelectOverrideWebPage: 0,
  kSelectOverrideSummary: 1,
  kSelectFeedDefault: 2,
  kOpenWebPage: 0,
  kOpenSummary: 1,
  kOpenToggleInMessagePane: 2,
  kOpenLoadInBrowser: 3,

  FeedAccountTypes: ["rss"],

  /**
   * How to load message on threadpane select.
   */
  get onSelectPref() {
    return Services.prefs.getIntPref("rss.show.summary");
  },

  set onSelectPref(val) {
    Services.prefs.setIntPref("rss.show.summary", val);
    ReloadMessage();
  },

  /**
   * Load web page on threadpane select.
   */
  get loadWebPageOnSelectPref() {
    return Services.prefs.getIntPref("rss.message.loadWebPageOnSelect");
  },

  /**
   * How to load message on open (enter/dbl click in threadpane, contextmenu).
   */
  get onOpenPref() {
    return Services.prefs.getIntPref("rss.show.content-base");
  },

  set onOpenPref(val) {
    Services.prefs.setIntPref("rss.show.content-base", val);
  },

  /**
   * Determine whether to show a feed message summary or load a web page in the
   * message pane.
   *
   * @param {nsIMsgDBHdr} aMsgHdr - The message.
   * @param {boolean} aToggle - true if in toggle mode, false otherwise.
   *
   * @returns {Boolean} - true if summary is to be displayed, false if web page.
   */
  shouldShowSummary(aMsgHdr, aToggle) {
    // Not a feed message, always show summary (the message).
    if (!FeedUtils.isFeedMessage(aMsgHdr)) {
      return true;
    }

    // Notified of a summary reload when toggling, reset toggle and return.
    if (!aToggle && this.gToggle) {
      return !(this.gToggle = false);
    }

    let showSummary = true;
    this.gToggle = aToggle;

    // Thunderbird 2 rss messages with 'Show article summary' not selected,
    // ie message body constructed to show web page in an iframe, can't show
    // a summary - notify user.
    let browser = getMessagePaneBrowser();
    let contentDoc = browser ? browser.contentDocument : null;
    let rssIframe = contentDoc
      ? contentDoc.getElementById("_mailrssiframe")
      : null;
    if (rssIframe) {
      if (this.gToggle || this.onSelectPref == this.kSelectOverrideSummary) {
        this.gToggle = false;
      }

      return false;
    }

    if (aToggle) {
      // Toggle mode, flip value.
      return (gShowFeedSummary = this.gShowSummary = !this.gShowSummary);
    }

    let wintype = document.documentElement.getAttribute("windowtype");
    let tabMail = document.getElementById("tabmail");
    let messageTab = tabMail && tabMail.currentTabInfo.mode.type == "message";
    let messageWindow = wintype == "mail:messageWindow";

    switch (this.onSelectPref) {
      case this.kSelectOverrideWebPage:
        showSummary = false;
        break;
      case this.kSelectOverrideSummary:
        showSummary = true;
        break;
      case this.kSelectFeedDefault:
        // Get quickmode per feed folder pref from feed subscriptions. If the feed
        // message is not in a feed account folder (hence the folder is not in
        // the feeds database), err on the side of showing the summary.
        // For the former, toggle or global override is necessary; for the
        // latter, a show summary checkbox toggle in Subscribe dialog will set
        // one on the path to bliss.
        let folder = aMsgHdr.folder;
        showSummary = true;
        const ds = FeedUtils.getSubscriptionsDS(folder.server);
        for (let sub of ds.data) {
          if (sub.destFolder == folder.URI) {
            showSummary = sub.quickMode;
            break;
          }
        }
        break;
    }

    gShowFeedSummary = this.gShowSummary = showSummary;

    if (messageWindow || messageTab) {
      // Message opened in either standalone window or tab, due to either
      // message open pref (we are here only if the pref is 0 or 1) or
      // contextmenu open.
      switch (this.onOpenPref) {
        case this.kOpenToggleInMessagePane:
          // Opened by contextmenu, use the value derived above.
          // XXX: allow a toggle via crtl?
          break;
        case this.kOpenWebPage:
          showSummary = false;
          break;
        case this.kOpenSummary:
          showSummary = true;
          break;
      }
    }

    // Auto load web page in browser on select, per pref; shouldShowSummary() is
    // always called first to 1)test if feed, 2)get summary pref, so do it here.
    if (this.loadWebPageOnSelectPref) {
      setTimeout(FeedMessageHandler.loadWebPage, 20, aMsgHdr, {
        browser: true,
      });
    }

    return showSummary;
  },

  /**
   * Load a web page for feed messages. Use MsgHdrToMimeMessage() to get
   * the content-base url from the message headers. We cannot rely on
   * currentHeaderData; it has not yet been streamed at our entry point in
   * displayMessageChanged(), and in the case of a collapsed message pane it
   * is not streamed.
   *
   * @param {nsIMsgDBHdr} aMessageHdr - The message.
   * @param {Object} aWhere - name value=true pair, where name is in:
   *                                    'messagepane', 'browser', 'tab', 'window'.
   * @returns {void}
   */
  loadWebPage(aMessageHdr, aWhere) {
    MsgHdrToMimeMessage(aMessageHdr, null, function (aMsgHdr, aMimeMsg) {
      if (
        aMimeMsg &&
        aMimeMsg.headers["content-base"] &&
        aMimeMsg.headers["content-base"][0]
      ) {
        let url = aMimeMsg.headers["content-base"],
          uri;
        try {
          // The message and headers are stored as a string of UTF-8 bytes
          // and we need to convert that cpp |string| to js UTF-16 explicitly
          // for idn and non-ascii urls with this api.
          url = decodeURIComponent(escape(url));
          uri = Services.io.newURI(url);
        } catch (ex) {
          FeedUtils.log.info(
            "FeedMessageHandler.loadWebPage: " +
              "invalid Content-Base header url - " +
              url
          );
          return;
        }
        if (aWhere.browser) {
          Cc["@mozilla.org/uriloader/external-protocol-service;1"]
            .getService(Ci.nsIExternalProtocolService)
            .loadURI(uri);
        } else if (aWhere.messagepane) {
          let browser = getMessagePaneBrowser();
          // Load about:blank in the browser before (potentially) switching
          // to a remote process. This prevents sandbox flags being carried
          // over to the web document.
          MailE10SUtils.loadAboutBlank(browser);
          MailE10SUtils.loadURI(browser, url);
        } else if (aWhere.tab) {
          openContentTab(url, "tab", null);
        } else if (aWhere.window) {
          openContentTab(url, "window", null);
        }
      } else {
        FeedUtils.log.info(
          "FeedMessageHandler.loadWebPage: could not get " +
            "Content-Base header url for this message"
        );
      }
    });
  },

  /**
   * Display summary or load web page for feed messages. Caller should already
   * know if the message is a feed message.
   *
   * @param {nsIMsgDBHdr} aMsgHdr - The message.
   * @param {Boolean} aShowSummary - true if summary is to be displayed,
   *                                 false if web page.
   * @returns {void}
   */
  setContent(aMsgHdr, aShowSummary) {
    if (aShowSummary) {
      // Only here if toggling to summary in 3pane.
      if (this.gToggle && window.gDBView && GetNumSelectedMessages() == 1) {
        ReloadMessage();
      }
    } else {
      let browser = getMessagePaneBrowser();
      if (browser && browser.contentDocument && browser.contentDocument.body) {
        browser.contentDocument.body.hidden = true;
      }
      // If in a non rss folder, hide possible remote content bar on a web
      // page load, as it doesn't apply.
      gMessageNotificationBar.clearMsgNotifications();

      this.loadWebPage(aMsgHdr, { messagepane: true });
      this.gToggle = false;
    }
  },
};

function openSubscriptionsDialog(aFolder) {
  // Check for an existing feed subscriptions window and focus it.
  let subscriptionsWindow = Services.wm.getMostRecentWindow(
    "Mail:News-BlogSubscriptions"
  );

  if (subscriptionsWindow) {
    if (aFolder) {
      subscriptionsWindow.FeedSubscriptions.selectFolder(aFolder);
      subscriptionsWindow.FeedSubscriptions.mView.tree.ensureRowIsVisible(
        subscriptionsWindow.FeedSubscriptions.mView.selection.currentIndex
      );
    }

    subscriptionsWindow.focus();
  } else {
    window.browsingContext.topChromeWindow.openDialog(
      "chrome://messenger-newsblog/content/feed-subscriptions.xhtml",
      "",
      "centerscreen,chrome,dialog=no,resizable",
      { folder: aFolder }
    );
  }
}

// Special case attempts to reply/forward/edit as new RSS articles. For
// messages stored prior to Tb15, we are here only if the message's folder's
// account server is rss and feed messages moved to other types will have their
// summaries loaded, as viewing web pages only happened in an rss account.
// The user may choose whether to load a summary or web page link by ensuring
// the current feed message is being viewed as either a summary or web page.
function openComposeWindowForRSSArticle(
  aMsgComposeWindow,
  aMsgHdr,
  aMessageUri,
  aType,
  aFormat,
  aIdentity,
  aMsgWindow
) {
  // Ensure right content is handled for web pages in window/tab.
  let tabmail = document.getElementById("tabmail");
  let is3pane =
    tabmail && tabmail.selectedTab && tabmail.selectedTab.mode
      ? tabmail.selectedTab.mode.type == "folder"
      : false;
  let showingwebpage =
    "FeedMessageHandler" in window &&
    !is3pane &&
    FeedMessageHandler.onOpenPref == FeedMessageHandler.kOpenWebPage;

  if (gShowFeedSummary && !showingwebpage) {
    // The user is viewing the summary.
    MailServices.compose.OpenComposeWindow(
      aMsgComposeWindow,
      aMsgHdr,
      aMessageUri,
      aType,
      aFormat,
      aIdentity,
      null,
      aMsgWindow
    );
  } else {
    // Set up the compose message and get the feed message's web page link.
    let msgHdr = aMsgHdr;
    let type = aType;
    let msgComposeType = Ci.nsIMsgCompType;
    let subject = msgHdr.mime2DecodedSubject;
    let fwdPrefix = Services.prefs.getCharPref("mail.forward_subject_prefix");
    fwdPrefix = fwdPrefix ? fwdPrefix + ": " : "";

    let params = Cc[
      "@mozilla.org/messengercompose/composeparams;1"
    ].createInstance(Ci.nsIMsgComposeParams);

    let composeFields = Cc[
      "@mozilla.org/messengercompose/composefields;1"
    ].createInstance(Ci.nsIMsgCompFields);

    if (
      type == msgComposeType.Reply ||
      type == msgComposeType.ReplyAll ||
      type == msgComposeType.ReplyToSender ||
      type == msgComposeType.ReplyToGroup ||
      type == msgComposeType.ReplyToSenderAndGroup ||
      type == msgComposeType.ReplyToList
    ) {
      subject = "Re: " + subject;
    } else if (
      type == msgComposeType.ForwardInline ||
      type == msgComposeType.ForwardAsAttachment
    ) {
      subject = fwdPrefix + subject;
    }

    params.composeFields = composeFields;
    params.composeFields.subject = subject;
    params.composeFields.body = "";
    params.bodyIsLink = false;
    params.identity = aIdentity;

    try {
      // The feed's web page url is stored in the Content-Base header.
      MsgHdrToMimeMessage(
        msgHdr,
        null,
        function (aMsgHdr, aMimeMsg) {
          if (
            aMimeMsg &&
            aMimeMsg.headers["content-base"] &&
            aMimeMsg.headers["content-base"][0]
          ) {
            let url = decodeURIComponent(
              escape(aMimeMsg.headers["content-base"])
            );
            params.composeFields.body = url;
            params.bodyIsLink = true;
            MailServices.compose.OpenComposeWindowWithParams(null, params);
          } else {
            // No content-base url, use the summary.
            MailServices.compose.OpenComposeWindow(
              aMsgComposeWindow,
              aMsgHdr,
              aMessageUri,
              aType,
              aFormat,
              aIdentity,
              null,
              aMsgWindow
            );
          }
        },
        false,
        { saneBodySize: true }
      );
    } catch (ex) {
      // Error getting header, use the summary.
      MailServices.compose.OpenComposeWindow(
        aMsgComposeWindow,
        aMsgHdr,
        aMessageUri,
        aType,
        aFormat,
        aIdentity,
        null,
        aMsgWindow
      );
    }
  }
}