summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/news/src/NewsDownloader.sys.mjs
blob: be94dfb96e9f3bb8ac06107bacac2f900a323a76 (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
/* 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/. */

var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
var { NntpUtils } = ChromeUtils.import("resource:///modules/NntpUtils.jsm");

/**
 * Download articles in all subscribed newsgroups for offline use.
 */
export class NewsDownloader {
  _logger = NntpUtils.logger;

  /**
   * @param {nsIMsgWindow} msgWindow - The associated msg window.
   * @param {nsIUrlListener} urlListener - Callback for the request.
   */
  constructor(msgWindow, urlListener) {
    this._msgWindow = msgWindow;
    this._urlListener = urlListener;

    this._bundle = Services.strings.createBundle(
      "chrome://messenger/locale/news.properties"
    );
  }

  /**
   * Actually start the download process.
   */
  async start() {
    this._logger.debug("Start downloading articles for offline use");
    let servers = MailServices.accounts.allServers.filter(
      x => x.type == "nntp"
    );
    // Download all servers concurrently.
    await Promise.all(
      servers.map(async server => {
        let folders = server.rootFolder.descendants;
        for (let folder of folders) {
          if (folder.flags & Ci.nsMsgFolderFlags.Offline) {
            // Download newsgroups set for offline use in a server one by one.
            await this._downloadFolder(folder);
          }
        }
      })
    );

    this._urlListener.OnStopRunningUrl(null, Cr.NS_OK);

    this._logger.debug("Finished downloading articles for offline use");
    this._msgWindow.statusFeedback.showStatusString("");
  }

  /**
   * Download articles in a newsgroup one by one.
   *
   * @param {nsIMsgFolder} folder - The newsgroup folder.
   */
  async _downloadFolder(folder) {
    this._logger.debug(`Start downloading ${folder.URI}`);

    folder.QueryInterface(Ci.nsIMsgNewsFolder).saveArticleOffline = true;
    let keysToDownload = await this._getKeysToDownload(folder);

    let i = 0;
    let total = keysToDownload.size;
    for (let key of keysToDownload) {
      await new Promise(resolve => {
        MailServices.nntp.fetchMessage(folder, key, this._msgWindow, null, {
          OnStartRunningUrl() {},
          OnStopRunningUrl() {
            resolve();
          },
        });
      });
      this._msgWindow.statusFeedback.showStatusString(
        this._bundle.formatStringFromName("downloadingArticlesForOffline", [
          ++i,
          total,
          folder.prettyName,
        ])
      );
    }

    folder.saveArticleOffline = false;
  }

  /**
   * Use a search session to find articles that match the download settings
   * and we don't already have.
   *
   * @param {nsIMsgFolder} folder - The newsgroup folder.
   * @returns {Set<number>}
   */
  async _getKeysToDownload(folder) {
    let searchSession = Cc[
      "@mozilla.org/messenger/searchSession;1"
    ].createInstance(Ci.nsIMsgSearchSession);
    let termValue = searchSession.createTerm().value;

    let downloadSettings = folder.downloadSettings;
    if (downloadSettings.downloadUnreadOnly) {
      termValue.attrib = Ci.nsMsgSearchAttrib.MsgStatus;
      termValue.status = Ci.nsMsgMessageFlags.Read;
      searchSession.addSearchTerm(
        Ci.nsMsgSearchAttrib.MsgStatus,
        Ci.nsMsgSearchOp.Isnt,
        termValue,
        true,
        null
      );
    }
    if (downloadSettings.downloadByDate) {
      termValue.attrib = Ci.nsMsgSearchAttrib.AgeInDays;
      termValue.age = downloadSettings.ageLimitOfMsgsToDownload;
      searchSession.addSearchTerm(
        Ci.nsMsgSearchAttrib.AgeInDays,
        Ci.nsMsgSearchOp.IsLessThan,
        termValue,
        true,
        null
      );
    }
    termValue.attrib = Ci.nsMsgSearchAttrib.MsgStatus;
    termValue.status = Ci.nsMsgMessageFlags.Offline;
    searchSession.addSearchTerm(
      Ci.nsMsgSearchAttrib.MsgStatus,
      Ci.nsMsgSearchOp.Isnt,
      termValue,
      true,
      null
    );

    let keysToDownload = new Set();
    await new Promise(resolve => {
      searchSession.registerListener(
        {
          onSearchHit(hdr, folder) {
            if (!(hdr.flags & Ci.nsMsgMessageFlags.Offline)) {
              // Only need to download articles we don't already have.
              keysToDownload.add(hdr.messageKey);
            }
          },
          onSearchDone: status => {
            resolve();
          },
        },
        Ci.nsIMsgSearchSession.allNotifications
      );
      searchSession.addScopeTerm(Ci.nsMsgSearchScope.localNews, folder);
      searchSession.search(this._msgWindow);
    });

    return keysToDownload;
  }
}