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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
|
/* 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/. */
/* functions use for junk processing commands
*
* TODO: These functions make the false assumption that a view only contains
* a single folder. This is not true for XF saved searches.
*
* globals prerequisites used:
*
* window.MsgStatusFeedback
*
* One of:
* GetSelectedIndices(view) (in suite)
* gFolderDisplay (in mail)
*
* messenger
* gMessengerBundle
* gDBView
* either gMsgFolderSelected or gFolderDisplay
* MsgJunkMailInfo(aCheckFirstUse)
* SetNextMessageAfterDelete()
* pref
* msgWindow
*/
Components.utils.import("resource:///modules/mailServices.js");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource://gre/modules/Services.jsm");
/*
* determineActionsForJunkMsgs
*
* Determines the actions that should be carried out on the messages
* that are being marked as junk
*
* @param aFolder
* the folder with messages being marked as junk
*
* @return an object with two properties: 'markRead' (boolean) indicating
* whether the messages should be marked as read, and 'junkTargetFolder'
* (nsIMsgFolder) specifying where the messages should be moved, or
* null if they should not be moved.
*/
function determineActionsForJunkMsgs(aFolder)
{
var actions = { markRead: false, junkTargetFolder: null };
var spamSettings = aFolder.server.spamSettings;
// note we will do moves/marking as read even if the spam
// feature is disabled, since the user has asked to use it
// despite the disabling
actions.markRead = spamSettings.markAsReadOnSpam;
actions.junkTargetFolder = null;
// move only when the corresponding setting is activated
// and the currently viewed folder is not the junk folder.
if (spamSettings.moveOnSpam &&
!(aFolder.flags & Components.interfaces.nsMsgFolderFlags.Junk))
{
var spamFolderURI = spamSettings.spamFolderURI;
if (!spamFolderURI)
{
// XXX TODO
// we should use nsIPromptService to inform the user of the problem,
// e.g. when the junk folder was accidentally deleted.
dump('determineActionsForJunkMsgs: no spam folder found, not moving.');
}
else
actions.junkTargetFolder = MailUtils.getFolderForURI(spamFolderURI);
}
return actions;
}
/**
* performActionsOnJunkMsgs
*
* Performs required operations on a list of newly-classified junk messages
*
* @param aFolder
* the folder with messages being marked as junk
*
* @param aJunkMsgHdrs
* nsIArray containing headers (nsIMsgDBHdr) of new junk messages
*
* @param aGoodMsgHdrs
* nsIArray containing headers (nsIMsgDBHdr) of new good messages
*/
function performActionsOnJunkMsgs(aFolder, aJunkMsgHdrs, aGoodMsgHdrs)
{
if (aFolder instanceof Components.interfaces.nsIMsgImapMailFolder) // need to update IMAP custom flags
{
if (aJunkMsgHdrs.length)
{
var junkMsgKeys = new Array();
for (var i = 0; i < aJunkMsgHdrs.length; i++)
junkMsgKeys[i] = aJunkMsgHdrs.queryElementAt(i, Components.interfaces.nsIMsgDBHdr).messageKey;
aFolder.storeCustomKeywords(null, "Junk", "NonJunk", junkMsgKeys, junkMsgKeys.length);
}
if (aGoodMsgHdrs.length)
{
var goodMsgKeys = new Array();
for (var i = 0; i < aGoodMsgHdrs.length; i++)
goodMsgKeys[i] = aGoodMsgHdrs.queryElementAt(i, Components.interfaces.nsIMsgDBHdr).messageKey;
aFolder.storeCustomKeywords(null, "NonJunk", "Junk", goodMsgKeys, goodMsgKeys.length);
}
}
if (aJunkMsgHdrs.length)
{
var actionParams = determineActionsForJunkMsgs(aFolder);
if (actionParams.markRead)
aFolder.markMessagesRead(aJunkMsgHdrs, true);
if (actionParams.junkTargetFolder)
MailServices.copy
.CopyMessages(aFolder, aJunkMsgHdrs, actionParams.junkTargetFolder,
true /* isMove */, null, msgWindow, true /* allow undo */);
}
}
/**
* MessageClassifier
*
* Helper object storing the list of pending messages to process,
* and implementing junk processing callback
*
* @param aFolder
* the folder with messages to be analyzed for junk
* @param aTotalMessages
* Number of messages to process, used for progress report only
*/
function MessageClassifier(aFolder, aTotalMessages)
{
this.mFolder = aFolder;
this.mJunkMsgHdrs = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
this.mGoodMsgHdrs = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
this.mMessages = new Object();
this.mMessageQueue = new Array();
this.mTotalMessages = aTotalMessages;
this.mProcessedMessages = 0;
this.firstMessage = true;
this.lastStatusTime = Date.now();
}
MessageClassifier.prototype =
{
/**
* analyzeMessage
*
* Starts the message classification process for a message. If the message
* sender's address is whitelisted, the message is skipped.
*
* @param aMsgHdr
* The header (nsIMsgDBHdr) of the message to classify.
* @param aSpamSettings
* nsISpamSettings object with information about whitelists
*/
analyzeMessage: function(aMsgHdr, aSpamSettings)
{
var junkscoreorigin = aMsgHdr.getStringProperty("junkscoreorigin");
if (junkscoreorigin == "user") // don't override user-set junk status
return;
// check whitelisting
if (aSpamSettings.checkWhiteList(aMsgHdr))
{
// message is ham from whitelist
var db = aMsgHdr.folder.msgDatabase;
db.setStringProperty(aMsgHdr.messageKey, "junkscore",
Components.interfaces.nsIJunkMailPlugin.IS_HAM_SCORE);
db.setStringProperty(aMsgHdr.messageKey, "junkscoreorigin", "whitelist");
this.mGoodMsgHdrs.appendElement(aMsgHdr, false);
return;
}
var messageURI = aMsgHdr.folder.generateMessageURI(aMsgHdr.messageKey) + "?fetchCompleteMessage=true";
this.mMessages[messageURI] = aMsgHdr;
if (this.firstMessage)
{
this.firstMessage = false;
MailServices.junk.classifyMessage(messageURI, msgWindow, this);
}
else
this.mMessageQueue.push(messageURI);
},
/*
* nsIJunkMailClassificationListener implementation
* onMessageClassified
*
* Callback function from nsIJunkMailPlugin with classification results
*
* @param aClassifiedMsgURI
* URI of classified message
* @param aClassification
* Junk classification (0: UNCLASSIFIED, 1: GOOD, 2: JUNK)
* @param aJunkPercent
* 0 - 100 indicator of junk likelihood, with 100 meaning probably junk
*/
onMessageClassified: function(aClassifiedMsgURI, aClassification, aJunkPercent)
{
if (!aClassifiedMsgURI)
return; // ignore end of batch
var nsIJunkMailPlugin = Components.interfaces.nsIJunkMailPlugin;
var score = (aClassification == nsIJunkMailPlugin.JUNK) ?
nsIJunkMailPlugin.IS_SPAM_SCORE : nsIJunkMailPlugin.IS_HAM_SCORE;
const statusDisplayInterval = 1000; // milliseconds between status updates
// set these props via the db (instead of the message header
// directly) so that the nsMsgDBView knows to update the UI
//
var msgHdr = this.mMessages[aClassifiedMsgURI];
var db = msgHdr.folder.msgDatabase;
db.setStringProperty(msgHdr.messageKey, "junkscore", score);
db.setStringProperty(msgHdr.messageKey, "junkscoreorigin", "plugin");
db.setStringProperty(msgHdr.messageKey, "junkpercent", aJunkPercent);
if (aClassification == nsIJunkMailPlugin.JUNK)
this.mJunkMsgHdrs.appendElement(msgHdr, false);
else if (aClassification == nsIJunkMailPlugin.GOOD)
this.mGoodMsgHdrs.appendElement(msgHdr, false);
var nextMsgURI = this.mMessageQueue.shift();
if (nextMsgURI)
{
++this.mProcessedMessages;
if (Date.now() > this.lastStatusTime + statusDisplayInterval)
{
this.lastStatusTime = Date.now();
var percentDone = 0;
if (this.mTotalMessages)
percentDone = Math.round(this.mProcessedMessages * 100 / this.mTotalMessages);
var percentStr = percentDone + "%";
window.MsgStatusFeedback.showStatusString(
document.getElementById("bundle_messenger")
.getFormattedString("junkAnalysisPercentComplete",
[percentStr]));
}
MailServices.junk.classifyMessage(nextMsgURI, msgWindow, this);
}
else
{
window.MsgStatusFeedback.showStatusString(
document.getElementById("bundle_messenger")
.getString("processingJunkMessages"));
performActionsOnJunkMsgs(this.mFolder, this.mJunkMsgHdrs, this.mGoodMsgHdrs);
window.MsgStatusFeedback.showStatusString("");
}
}
}
/*
* filterFolderForJunk
*
* Filter all messages in the current folder for junk
*/
function filterFolderForJunk() { processFolderForJunk(true); }
/*
* analyzeMessagesForJunk
*
* Filter selected messages in the current folder for junk
*/
function analyzeMessagesForJunk() { processFolderForJunk(false); }
/*
* processFolderForJunk
*
* Filter messages in the current folder for junk
*
* @param aAll: true to filter all messages, else filter selection
*/
function processFolderForJunk(aAll)
{
MsgJunkMailInfo(true);
if (aAll)
{
// need to expand all threads, so we analyze everything
gDBView.doCommand(nsMsgViewCommandType.expandAll);
var treeView = gDBView.QueryInterface(Components.interfaces.nsITreeView);
var count = treeView.rowCount;
if (!count)
return;
}
else
{
// suite uses GetSelectedIndices, mail uses gFolderDisplay.selectedMessages
var indices = typeof GetSelectedIndices != "undefined" ?
GetSelectedIndices(gDBView) :
gFolderDisplay.selectedIndices;
if (!indices || !indices.length)
return;
}
var totalMessages = aAll ? count : indices.length;
// retrieve server and its spam settings via the header of an arbitrary message
for (var i = 0; i < totalMessages; i++)
{
var index = aAll ? i : indices[i];
try
{
var tmpMsgURI = gDBView.getURIForViewIndex(index);
break;
}
catch (e)
{
// dummy headers will fail, so look for another
continue;
}
}
if (!tmpMsgURI)
return;
var tmpMsgHdr = messenger.messageServiceFromURI(tmpMsgURI).messageURIToMsgHdr(tmpMsgURI);
var spamSettings = tmpMsgHdr.folder.server.spamSettings;
// create a classifier instance to classify messages in the folder.
var msgClassifier = new MessageClassifier(tmpMsgHdr.folder, totalMessages);
for ( i = 0; i < totalMessages; i++)
{
var index = aAll ? i : indices[i];
try
{
var msgURI = gDBView.getURIForViewIndex(index);
var msgHdr = messenger.messageServiceFromURI(msgURI).messageURIToMsgHdr(msgURI);
msgClassifier.analyzeMessage(msgHdr, spamSettings);
}
catch (ex)
{
// blow off errors here - dummy headers will fail
var msgURI = null;
}
}
if (msgClassifier.firstMessage) // the async plugin was not used, maybe all whitelisted?
performActionsOnJunkMsgs(msgClassifier.mFolder,
msgClassifier.mJunkMsgHdrs,
msgClassifier.mGoodMsgHdrs);
}
function JunkSelectedMessages(setAsJunk)
{
MsgJunkMailInfo(true);
// When the user explicitly marks a message as junk, we can mark it as read,
// too. This is independent of the "markAsReadOnSpam" pref, which applies
// only to automatically-classified messages.
// Note that this behaviour should match the one in the back end for marking
// as junk via clicking the 'junk' column.
if (setAsJunk && Services.prefs.getBoolPref("mailnews.ui.junk.manualMarkAsJunkMarksRead"))
MarkSelectedMessagesRead(true);
gDBView.doCommand(setAsJunk ? nsMsgViewCommandType.junk
: nsMsgViewCommandType.unjunk);
}
/**
* Delete junk messages in the current folder. This provides the guarantee that
* the method will be synchronous if no messages are deleted.
*
* @returns The number of messages deleted.
*/
function deleteJunkInFolder()
{
MsgJunkMailInfo(true);
// use direct folder commands if possible so we don't mess with the selection
let selectedFolder = gFolderDisplay.displayedFolder;
if ( !(selectedFolder.flags & Components.interfaces.nsMsgFolderFlags.Virtual) )
{
var junkMsgHdrs = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
var enumerator = gDBView.msgFolder.messages;
while (enumerator.hasMoreElements())
{
var msgHdr = enumerator.getNext().QueryInterface(Components.interfaces.nsIMsgDBHdr);
var junkScore = msgHdr.getStringProperty("junkscore");
if (junkScore == Components.interfaces.nsIJunkMailPlugin.IS_SPAM_SCORE)
junkMsgHdrs.appendElement(msgHdr, false);
}
if (junkMsgHdrs.length)
gDBView.msgFolder.deleteMessages(junkMsgHdrs, msgWindow, false, false, null, true);
return junkMsgHdrs.length;
}
// Folder is virtual, let the view do the work (but we lose selection)
// need to expand all threads, so we find everything
gDBView.doCommand(nsMsgViewCommandType.expandAll);
var treeView = gDBView.QueryInterface(Components.interfaces.nsITreeView);
var count = treeView.rowCount;
if (!count)
return 0;
var treeSelection = treeView.selection;
var clearedSelection = false;
// select the junk messages
var messageUri;
let numMessagesDeleted = 0;
for (var i = 0; i < count; ++i)
{
try {
messageUri = gDBView.getURIForViewIndex(i);
}
catch (ex) {continue;} // blow off errors for dummy rows
var msgHdr = messenger.messageServiceFromURI(messageUri).messageURIToMsgHdr(messageUri);
var junkScore = msgHdr.getStringProperty("junkscore");
var isJunk = (junkScore == Components.interfaces.nsIJunkMailPlugin.IS_SPAM_SCORE);
// if the message is junk, select it.
if (isJunk)
{
// only do this once
if (!clearedSelection)
{
// clear the current selection
// since we will be deleting all selected messages
treeSelection.clearSelection();
clearedSelection = true;
treeSelection.selectEventsSuppressed = true;
}
treeSelection.rangedSelect(i, i, true /* augment */);
numMessagesDeleted++;
}
}
// if we didn't clear the selection
// there was no junk, so bail.
if (!clearedSelection)
return 0;
treeSelection.selectEventsSuppressed = false;
// delete the selected messages
//
// We'll leave no selection after the delete
gNextMessageViewIndexAfterDelete = nsMsgViewIndex_None;
gDBView.doCommand(nsMsgViewCommandType.deleteMsg);
treeSelection.clearSelection();
ClearMessagePane();
return numMessagesDeleted;
}
|