summaryrefslogtreecommitdiffstats
path: root/mailnews/news/src/nsNNTPNewsgroupList.cpp
blob: 3833390c7c29dfff2ff54e0f268d23f2f26812fc (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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
/* -*- Mode: C++; 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/. */

/*
 * formerly listngst.cpp
 * This class should ultimately be part of a news group listing
 * state machine - either by inheritance or delegation.
 * Currently, a folder pane owns one and libnet news group listing
 * related messages get passed to this object.
 */

#include "msgCore.h"    // precompiled header...
#include "MailNewsTypes.h"
#include "nsCOMPtr.h"
#include "nsIDBFolderInfo.h"
#include "nsINewsDatabase.h"
#include "nsIMsgStatusFeedback.h"
#include "nsCOMPtr.h"
#include "nsPIDOMWindow.h"
#include "mozIDOMWindow.h"
#include "nsIMsgMailNewsUrl.h"
#include "nsIMsgAccountManager.h"
#include "nsIMsgIncomingServer.h"
#include "nsINntpIncomingServer.h"
#include "nsMsgBaseCID.h"
#include "nsIMsgFilter.h"
#include "nsNNTPNewsgroupList.h"

#include "nsINNTPArticleList.h"
#include "nsMsgKeySet.h"

#include "nntpCore.h"
#include "nsIStringBundle.h"

#include "plstr.h"
#include "prmem.h"
#include "prprf.h"

#include "nsMsgUtils.h"

#include "nsMsgDatabase.h"

#include "nsIDBFolderInfo.h"

#include "nsNewsUtils.h"

#include "nsMsgDBCID.h"

#include "nsINewsDownloadDialogArgs.h"

#include "nsXPCOM.h"
#include "nsISupportsPrimitives.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIMsgWindow.h"
#include "nsIDocShell.h"
#include "nsIMutableArray.h"
#include "nsIMsgFolderNotificationService.h"
#include "nsIMsgFilterCustomAction.h"
#include "nsComponentManagerUtils.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/Services.h"

// update status on header download once per second
#define MIN_STATUS_UPDATE_INTERVAL PRTime(PR_USEC_PER_SEC)


nsNNTPNewsgroupList::nsNNTPNewsgroupList()
  : m_finishingXover(false),
  m_getOldMessages(false),
  m_promptedAlready(false),
  m_downloadAll(false),
  m_maxArticles(0),
  m_lastPercent(-1),
  m_lastStatusUpdate(0),
  m_lastProcessedNumber(0),
  m_firstMsgNumber(0),
  m_lastMsgNumber(0),
  m_firstMsgToDownload(0),
  m_lastMsgToDownload(0),
  m_set(nullptr)
{
  memset(&m_knownArts, 0, sizeof(m_knownArts));
}

nsNNTPNewsgroupList::~nsNNTPNewsgroupList()
{
  CleanUp();
}

NS_IMPL_ISUPPORTS(nsNNTPNewsgroupList, nsINNTPNewsgroupList, nsIMsgFilterHitNotify)

nsresult
nsNNTPNewsgroupList::Initialize(nsINntpUrl *runningURL, nsIMsgNewsFolder *newsFolder)
{
  m_newsFolder = newsFolder;
  m_runningURL = runningURL;
  m_knownArts.set = nsMsgKeySet::Create();

  nsresult rv = m_newsFolder->GetDatabaseWithoutCache(getter_AddRefs(m_newsDB));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr <nsIMsgFolder> folder = do_QueryInterface(m_newsFolder, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  rv = folder->GetFilterList(m_msgWindow, getter_AddRefs(m_filterList));
  NS_ENSURE_SUCCESS(rv,rv);
  nsCString ngHeaders;
  m_filterList->GetArbitraryHeaders(ngHeaders);
  ParseString(ngHeaders, ' ', m_filterHeaders);

  nsCOMPtr<nsIMsgIncomingServer> server;
  rv = folder->GetServer(getter_AddRefs(server));
  NS_ENSURE_SUCCESS(rv,rv);

  rv = server->GetFilterList(m_msgWindow, getter_AddRefs(m_serverFilterList));
  NS_ENSURE_SUCCESS(rv,rv);
  nsAutoCString servHeaders;
  m_serverFilterList->GetArbitraryHeaders(servHeaders);

  nsTArray<nsCString> servArray;
  ParseString(servHeaders, ' ', servArray);

  // servArray may have duplicates already in m_filterHeaders.
  for (uint32_t i = 0; i < servArray.Length(); i++)
  {
    if (!m_filterHeaders.Contains(servArray[i]))
      m_filterHeaders.AppendElement(servArray[i]);
  }
  return NS_OK;
}

nsresult
nsNNTPNewsgroupList::CleanUp()
{
  // here we make sure that there aren't missing articles in the unread set
  // So if an article is the unread set, and the known arts set, but isn't in the
  // db, then we should mark it read in the unread set.
  if (m_newsDB)
  {
    if (m_knownArts.set && m_knownArts.set->getLength() && m_set->getLength())
    {
      nsCOMPtr <nsIDBFolderInfo> folderInfo;
      m_newsDB->GetDBFolderInfo(getter_AddRefs(folderInfo));
      int32_t firstKnown = m_knownArts.set->GetFirstMember();
      int32_t lastKnown =  m_knownArts.set->GetLastMember();
      if (folderInfo)
      {
        uint32_t lastMissingCheck;
        folderInfo->GetUint32Property("lastMissingCheck", 0, &lastMissingCheck);
        if (lastMissingCheck)
          firstKnown = lastMissingCheck + 1;
      }
      bool foundMissingArticle = false;
      while (firstKnown <= lastKnown)
      {
        int32_t firstUnreadStart, firstUnreadEnd;
        if (firstKnown == 0)
          firstKnown = 1;
        m_set->FirstMissingRange(firstKnown, lastKnown, &firstUnreadStart, &firstUnreadEnd);
        if (firstUnreadStart)
        {
          while (firstUnreadStart <= firstUnreadEnd)
          {
            bool containsKey;
            m_newsDB->ContainsKey(firstUnreadStart, &containsKey);
            if (!containsKey)
            {
              m_set->Add(firstUnreadStart);
              foundMissingArticle = true;
            }
            firstUnreadStart++;
          }
          firstKnown = firstUnreadStart;
        }
        else
          break;

      }
      if (folderInfo)
        folderInfo->SetUint32Property("lastMissingCheck", lastKnown);

      if (foundMissingArticle)
      {
        nsresult rv;
        nsCOMPtr<nsINewsDatabase> db(do_QueryInterface(m_newsDB, &rv));
        NS_ENSURE_SUCCESS(rv,rv);
        db->SetReadSet(m_set);
      }
    }
    m_newsDB->Commit(nsMsgDBCommitType::kSessionCommit);
    m_newsDB->Close(true);
    m_newsDB = nullptr;
  }

  if (m_knownArts.set)
  {
    delete m_knownArts.set;
    m_knownArts.set = nullptr;
  }
  if (m_newsFolder)
    m_newsFolder->NotifyFinishedDownloadinghdrs();

  m_newsFolder = nullptr;
  m_runningURL = nullptr;

  return NS_OK;
}

#ifdef HAVE_CHANGELISTENER
void nsNNTPNewsgroupList::OnAnnouncerGoingAway (ChangeAnnouncer *instigator)
{
}
#endif

static nsresult
openWindow(nsIMsgWindow *aMsgWindow, const char *chromeURL,
           nsINewsDownloadDialogArgs *param)
{
  nsresult rv;
  NS_ENSURE_ARG_POINTER(aMsgWindow);
  nsCOMPtr<nsIDocShell> docShell;
  rv = aMsgWindow->GetRootDocShell(getter_AddRefs(docShell));
  if (NS_FAILED(rv))
      return rv;

  nsCOMPtr<mozIDOMWindowProxy> domWindow(do_GetInterface(docShell));
  NS_ENSURE_TRUE(domWindow, NS_ERROR_FAILURE);
  nsCOMPtr<nsPIDOMWindowOuter> parentWindow = nsPIDOMWindowOuter::From(domWindow);
  parentWindow = parentWindow->GetOuterWindow();
  NS_ENSURE_ARG_POINTER(parentWindow);

  nsCOMPtr<nsISupportsInterfacePointer> ifptr = do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  ifptr->SetData(param);
  ifptr->SetDataIID(&NS_GET_IID(nsINewsDownloadDialogArgs));

  nsCOMPtr<nsPIDOMWindowOuter> dialogWindow;
  rv = parentWindow->OpenDialog(NS_ConvertASCIItoUTF16(chromeURL),
                                NS_LITERAL_STRING("_blank"),
                                NS_LITERAL_STRING("centerscreen,chrome,modal,titlebar"),
                                ifptr, getter_AddRefs(dialogWindow));

  return rv;
}

nsresult
nsNNTPNewsgroupList::GetRangeOfArtsToDownload(nsIMsgWindow *aMsgWindow,
                                              int32_t first_possible,
                                              int32_t last_possible,
                                              int32_t maxextra,
                                              int32_t *first,
                                              int32_t *last,
                                              int32_t *status)
{
  nsresult rv = NS_OK;

  NS_ENSURE_ARG_POINTER(first);
  NS_ENSURE_ARG_POINTER(last);
  NS_ENSURE_ARG_POINTER(status);
  *first = 0;
  *last = 0;

  nsCOMPtr <nsIMsgFolder> folder = do_QueryInterface(m_newsFolder, &rv);
  NS_ENSURE_SUCCESS(rv,rv);
  m_msgWindow = aMsgWindow;

  nsCOMPtr<nsINewsDatabase> db(do_QueryInterface(m_newsDB, &rv));
  NS_ENSURE_SUCCESS(rv,rv);

  rv = db->GetReadSet(&m_set);
  if (NS_FAILED(rv) || !m_set)
    return rv;

  m_set->SetLastMember(last_possible); // make sure highwater mark is valid.

  nsCOMPtr <nsIDBFolderInfo> newsGroupInfo;
  rv = m_newsDB->GetDBFolderInfo(getter_AddRefs(newsGroupInfo));
  if (NS_SUCCEEDED(rv) && newsGroupInfo) {
    nsCString knownArtsString;
    nsMsgKey mark;
    newsGroupInfo->GetKnownArtsSet(getter_Copies(knownArtsString));

    rv = newsGroupInfo->GetHighWater(&mark);
    NS_ENSURE_SUCCESS(rv,rv);

    if (last_possible < ((int32_t)mark))
      newsGroupInfo->SetHighWater(last_possible);
    if (m_knownArts.set)
      delete m_knownArts.set;
    m_knownArts.set = nsMsgKeySet::Create(knownArtsString.get());
  }
  else
  {
    if (m_knownArts.set)
      delete m_knownArts.set;
    m_knownArts.set = nsMsgKeySet::Create();
    nsMsgKey low, high;
    rv = m_newsDB->GetLowWaterArticleNum(&low);
    NS_ENSURE_SUCCESS(rv,rv);
    rv = m_newsDB->GetHighWaterArticleNum(&high);
    NS_ENSURE_SUCCESS(rv,rv);
    m_knownArts.set->AddRange(low,high);
  }

  if (m_knownArts.set->IsMember(last_possible)) {
    nsString statusString;
    nsCOMPtr<nsIStringBundleService> bundleService =
      mozilla::services::GetStringBundleService();
    NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);

    nsCOMPtr<nsIStringBundle> bundle;
    rv = bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(bundle));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = bundle->GetStringFromName(u"noNewMessages", getter_Copies(statusString));
    NS_ENSURE_SUCCESS(rv, rv);

    SetProgressStatus(statusString.get());
  }

  if (maxextra <= 0 || last_possible < first_possible || last_possible < 1)
  {
    *status=0;
    return NS_OK;
  }

  m_knownArts.first_possible = first_possible;
  m_knownArts.last_possible = last_possible;

  nsCOMPtr <nsIMsgIncomingServer> server;
  rv = folder->GetServer(getter_AddRefs(server));
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsINntpIncomingServer> nntpServer = do_QueryInterface(server, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  /* Determine if we only want to get just new articles or more messages.
  If there are new articles at the end we haven't seen, we always want to get those first.
  Otherwise, we get the newest articles we haven't gotten, if we're getting more.
  My thought for now is that opening a newsgroup should only try to get new articles.
  Selecting "More Messages" will first try to get unseen messages, then old messages. */

  if (m_getOldMessages || !m_knownArts.set->IsMember(last_possible))
  {
    bool notifyMaxExceededOn = true;
    rv = nntpServer->GetNotifyOn(&notifyMaxExceededOn);
    if (NS_FAILED(rv)) notifyMaxExceededOn = true;

    // if the preference to notify when downloading more than x headers is not on,
    // and we're downloading new headers, set maxextra to a very large number.
    if (!m_getOldMessages && !notifyMaxExceededOn)
      maxextra = 0x7FFFFFFFL;
        int result =
            m_knownArts.set->LastMissingRange(first_possible, last_possible,
                                              first, last);
    if (result < 0) {
            *status=result;
      return NS_ERROR_NOT_INITIALIZED;
        }
    if (*first > 0 && *last - *first >= maxextra)
    {
      if (!m_getOldMessages && !m_promptedAlready && notifyMaxExceededOn)
      {
        m_downloadAll = false;
        nsCOMPtr<nsINewsDownloadDialogArgs> args = do_CreateInstance("@mozilla.org/messenger/newsdownloaddialogargs;1", &rv);
        if (NS_FAILED(rv)) return rv;
        NS_ENSURE_SUCCESS(rv,rv);

        rv = args->SetArticleCount(*last - *first + 1);
        NS_ENSURE_SUCCESS(rv,rv);

        nsString groupName;
        rv = m_newsFolder->GetUnicodeName(groupName);
        NS_ENSURE_SUCCESS(rv,rv);

        rv = args->SetGroupName(groupName);
        NS_ENSURE_SUCCESS(rv,rv);

        // get the server key
        nsCString serverKey;
        rv = server->GetKey(serverKey);
        NS_ENSURE_SUCCESS(rv,rv);

        rv = args->SetServerKey(serverKey.get());
        NS_ENSURE_SUCCESS(rv,rv);

        // we many not have a msgWindow if we are running an autosubscribe url from the browser
        // and there isn't a 3 pane open.
        //
        // if we don't have one, bad things will happen when we fail to open up the "download headers dialog"
        // (we will subscribe to the newsgroup, but it will appear like there are no messages!)
        //
        // for now, act like the "download headers dialog" came up, and the user hit cancel.  (very safe)
        //
        // TODO, figure out why we aren't opening and using a 3 pane when the autosubscribe url is run.
        // perhaps we can find an available 3 pane, and use it.

        bool download = false;

        if (aMsgWindow) {
          rv = openWindow(aMsgWindow, DOWNLOAD_HEADERS_URL, args);
          NS_ENSURE_SUCCESS(rv,rv);

          rv = args->GetHitOK(&download);
          NS_ENSURE_SUCCESS(rv,rv);
        }

      if (download) {
         rv = args->GetDownloadAll(&m_downloadAll);
         NS_ENSURE_SUCCESS(rv,rv);
         m_maxArticles = 0;
         rv = nntpServer->GetMaxArticles(&m_maxArticles);
         NS_ENSURE_SUCCESS(rv,rv);

          maxextra = m_maxArticles;
          if (!m_downloadAll)
          {
            bool markOldRead = false;

            rv = nntpServer->GetMarkOldRead(&markOldRead);
            if (NS_FAILED(rv)) markOldRead = false;

            if (markOldRead && m_set)
              m_set->AddRange(*first, *last - maxextra);
            *first = *last - maxextra + 1;
          }
        }
        else
          *first = *last = 0;
        m_promptedAlready = true;
      }
      else if (m_promptedAlready && !m_downloadAll)
        *first = *last - m_maxArticles + 1;
      else if (!m_downloadAll)
        *first = *last - maxextra + 1;
    }
  }

  m_firstMsgToDownload = *first;
  m_lastMsgToDownload = *last;
  *status=0;
  return NS_OK;
}

nsresult
nsNNTPNewsgroupList::AddToKnownArticles(int32_t first, int32_t last)
{
  nsresult status;

  if (!m_knownArts.set)
  {
    m_knownArts.set = nsMsgKeySet::Create();
    if (!m_knownArts.set)
      return NS_ERROR_OUT_OF_MEMORY;
  }

  // XXX Casting int to nsresult
  status = static_cast<nsresult>(m_knownArts.set->AddRange(first, last));

  if (m_newsDB) {
    nsresult rv = NS_OK;
    nsCOMPtr <nsIDBFolderInfo> newsGroupInfo;
    rv = m_newsDB->GetDBFolderInfo(getter_AddRefs(newsGroupInfo));
    if (NS_SUCCEEDED(rv) && newsGroupInfo) {
      nsCString output;
      status = m_knownArts.set->Output(getter_Copies(output));
      if (!output.IsEmpty())
        newsGroupInfo->SetKnownArtsSet(output.get());
    }
  }
  return status;
}

nsresult
nsNNTPNewsgroupList::InitXOVER(int32_t first_msg, int32_t last_msg)
{
  /* Consistency checks, not that I know what to do if it fails (it will
   probably handle it OK...) */
  NS_ASSERTION(first_msg <= last_msg, "first > last");

  /* If any XOVER lines from the last time failed to come in, mark those
     messages as read. */
  if (m_lastProcessedNumber < m_lastMsgNumber)
  {
    m_set->AddRange(m_lastProcessedNumber + 1, m_lastMsgNumber);
  }
  m_firstMsgNumber = first_msg;
  m_lastMsgNumber = last_msg;
  m_lastProcessedNumber = first_msg > 1 ? first_msg - 1 : 1;
  m_currentXHDRIndex = -1;
  return NS_OK;
}

// from RFC 822, don't translate
#define FROM_HEADER "From: "
#define SUBJECT_HEADER "Subject: "
#define DATE_HEADER "Date: "

nsresult
nsNNTPNewsgroupList::ParseLine(char *line, uint32_t * message_number)
{
  nsresult rv = NS_OK;
  nsCOMPtr <nsIMsgDBHdr> newMsgHdr;

  if (!line || !message_number) {
    return NS_ERROR_NULL_POINTER;
  }

  char *next = line;

#define GET_TOKEN()                           \
  line = next;                                \
  next = (line ? PL_strchr (line, '\t') : 0); \
  if (next) *next++ = 0

  GET_TOKEN (); /* message number */
  *message_number = atol(line);

  if (atol(line) == 0) /* bogus xover data */
    return NS_ERROR_UNEXPECTED;

  m_newsDB->CreateNewHdr(*message_number, getter_AddRefs(newMsgHdr));

  NS_ASSERTION(newMsgHdr, "CreateNewHdr didn't fail, but it returned a null newMsgHdr");
  if (!newMsgHdr)
    return NS_ERROR_NULL_POINTER;

  GET_TOKEN (); /* subject */
  if (line) {
    const char *subject = line;  /* #### const evilness */

    uint32_t flags = 0;
    // ### should call IsHeaderRead here...
    /* strip "Re: " */
    nsCString modifiedSubject;
    if (NS_MsgStripRE(nsDependentCString(subject), modifiedSubject))
      (void) newMsgHdr->OrFlags(nsMsgMessageFlags::HasRe, &flags);
    
    // this will make sure read flags agree with newsrc
    if (! (flags & nsMsgMessageFlags::Read))
      rv = newMsgHdr->OrFlags(nsMsgMessageFlags::New, &flags);

    rv = newMsgHdr->SetSubject(modifiedSubject.IsEmpty() ? subject : modifiedSubject.get());

    if (NS_FAILED(rv))
      return rv;
  }

  GET_TOKEN (); /* author */
  if (line) {
    rv = newMsgHdr->SetAuthor(line);
    if (NS_FAILED(rv))
      return rv;
  }

  GET_TOKEN ();
  if (line) {
    PRTime date;
    PRStatus status = PR_ParseTimeString (line, false, &date);
    if (PR_SUCCESS == status) {
      rv = newMsgHdr->SetDate(date); /* date */
      if (NS_FAILED(rv))
        return rv;
    }
  }

  GET_TOKEN (); /* message id */
  if (line) {
    char *strippedId = line;
    if (strippedId[0] == '<')
      strippedId++;
    char * lastChar = strippedId + PL_strlen(strippedId) -1;

    if (*lastChar == '>')
      *lastChar = '\0';

    rv = newMsgHdr->SetMessageId(strippedId);
    if (NS_FAILED(rv))
      return rv;
  }

  GET_TOKEN (); /* references */
  if (line) {
    rv = newMsgHdr->SetReferences(line);
    if (NS_FAILED(rv))
      return rv;
  }

  GET_TOKEN (); /* bytes */
  if (line) {
    uint32_t msgSize = 0;
    msgSize = (line) ? atol (line) : 0;

    rv = newMsgHdr->SetMessageSize(msgSize);
    if (NS_FAILED(rv)) return rv;
  }

  GET_TOKEN (); /* lines */
  if (line) {
    uint32_t numLines = 0;
    numLines = line ? atol (line) : 0;
    rv = newMsgHdr->SetLineCount(numLines);
    if (NS_FAILED(rv)) return rv;
  }

  GET_TOKEN (); /* xref */

  m_newHeaders.AppendObject(newMsgHdr);
  return NS_OK;
}

NS_IMETHODIMP nsNNTPNewsgroupList::ApplyFilterHit(nsIMsgFilter *aFilter, nsIMsgWindow *aMsgWindow, bool *aApplyMore)
{
  NS_ENSURE_ARG_POINTER(aFilter);
  NS_ENSURE_ARG_POINTER(aApplyMore);
  NS_ENSURE_TRUE(m_newMsgHdr, NS_ERROR_UNEXPECTED);
  NS_ENSURE_TRUE(m_newsDB, NS_ERROR_UNEXPECTED);

  // you can't move news messages, so applyMore is always true
  *aApplyMore = true;

  nsCOMPtr<nsIArray> filterActionList;

  nsresult rv = aFilter->GetSortedActionList(getter_AddRefs(filterActionList));
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t numActions;
  rv = filterActionList->GetLength(&numActions);
  NS_ENSURE_SUCCESS(rv, rv);

  bool loggingEnabled = false;
  nsCOMPtr<nsIMsgFilterList> currentFilterList;
  rv = aFilter->GetFilterList(getter_AddRefs(currentFilterList));
  if (NS_SUCCEEDED(rv) && currentFilterList && numActions)
    currentFilterList->GetLoggingEnabled(&loggingEnabled);

  for (uint32_t actionIndex = 0; actionIndex < numActions; actionIndex++)
  {
    nsCOMPtr<nsIMsgRuleAction> filterAction;
    rv = filterActionList->QueryElementAt(actionIndex, NS_GET_IID(nsIMsgRuleAction),
                                                       getter_AddRefs(filterAction));
    if (NS_FAILED(rv) || !filterAction)
      continue;

    nsMsgRuleActionType actionType;
    if (NS_SUCCEEDED(filterAction->GetType(&actionType)))
    {
      if (loggingEnabled)
        (void) aFilter->LogRuleHit(filterAction, m_newMsgHdr);

      switch (actionType)
      {
      case nsMsgFilterAction::Delete:
        m_addHdrToDB = false;
        break;
      case nsMsgFilterAction::MarkRead:
        m_newsDB->MarkHdrRead(m_newMsgHdr, true, nullptr);
        break;
      case nsMsgFilterAction::MarkUnread:
        m_newsDB->MarkHdrRead(m_newMsgHdr, false, nullptr);
        break;
      case nsMsgFilterAction::KillThread:
        m_newMsgHdr->SetUint32Property("ProtoThreadFlags", nsMsgMessageFlags::Ignored);
        break;
      case nsMsgFilterAction::KillSubthread:
        {
          uint32_t newFlags;
          m_newMsgHdr->OrFlags(nsMsgMessageFlags::Ignored, &newFlags);
        }
        break;
      case nsMsgFilterAction::WatchThread:
        {
          uint32_t newFlags;
          m_newMsgHdr->OrFlags(nsMsgMessageFlags::Watched, &newFlags);
        }
        break;
      case nsMsgFilterAction::MarkFlagged:
        m_newMsgHdr->MarkFlagged(true);
        break;
      case nsMsgFilterAction::ChangePriority:
        {
          nsMsgPriorityValue filterPriority;
          filterAction->GetPriority(&filterPriority);
          m_newMsgHdr->SetPriority(filterPriority);
        }
        break;
      case nsMsgFilterAction::AddTag:
      {
        nsCString keyword;
        filterAction->GetStrValue(keyword);
        nsCOMPtr<nsIMutableArray> messageArray(do_CreateInstance(NS_ARRAY_CONTRACTID));
        messageArray->AppendElement(m_newMsgHdr, false);
        nsCOMPtr <nsIMsgFolder> folder = do_QueryInterface(m_newsFolder, &rv);
        if (folder)
          folder->AddKeywordsToMessages(messageArray, keyword);
        break;
      }
      case nsMsgFilterAction::Label:
        {
          nsMsgLabelValue filterLabel;
          filterAction->GetLabel(&filterLabel);
          nsMsgKey msgKey;
          m_newMsgHdr->GetMessageKey(&msgKey);
          m_newsDB->SetLabel(msgKey, filterLabel);
        }
        break;

      case nsMsgFilterAction::StopExecution:
      {
        // don't apply any more filters
        *aApplyMore = false;
      }
      break;

      case nsMsgFilterAction::Custom:
      {
        nsCOMPtr<nsIMsgFilterCustomAction> customAction;
        rv = filterAction->GetCustomAction(getter_AddRefs(customAction));
        NS_ENSURE_SUCCESS(rv, rv);

        nsAutoCString value;
        filterAction->GetStrValue(value);

        nsCOMPtr<nsIMutableArray> messageArray(
            do_CreateInstance(NS_ARRAY_CONTRACTID, &rv));
        NS_ENSURE_TRUE(messageArray, rv);
        messageArray->AppendElement(m_newMsgHdr, false);

        customAction->Apply(messageArray, value, nullptr,
                            nsMsgFilterType::NewsRule, aMsgWindow);
      }
      break;

      default:
        NS_ERROR("unexpected action");
        break;
      }
    }
  }
  return NS_OK;
}

nsresult
nsNNTPNewsgroupList::ProcessXOVERLINE(const char *line, uint32_t *status)
{
  uint32_t message_number=0;
  //  int32_t lines;
  nsresult rv = NS_OK;

  NS_ASSERTION(line, "null ptr");
  if (!line)
    return NS_ERROR_NULL_POINTER;

  if (m_newsDB)
  {
    char *xoverline = PL_strdup(line);
    if (!xoverline)
      return NS_ERROR_OUT_OF_MEMORY;
    rv = ParseLine(xoverline, &message_number);
    PL_strfree(xoverline);
    xoverline = nullptr;
    if (NS_FAILED(rv))
      return rv;
  }
  else
    return NS_ERROR_NOT_INITIALIZED;

  NS_ASSERTION(message_number > m_lastProcessedNumber ||
               message_number == 1, "bad message_number");
  if (m_set && message_number > m_lastProcessedNumber + 1)
  {
  /* There are some articles that XOVER skipped; they must no longer
     exist.  Mark them as read in the newsrc, so we don't include them
     next time in our estimated number of unread messages. */
    if (m_set->AddRange(m_lastProcessedNumber + 1, message_number - 1))
    {
    /* This isn't really an important enough change to warrant causing
       the newsrc file to be saved; we haven't gathered any information
       that won't also be gathered for free next time.  */
    }
  }

  m_lastProcessedNumber = message_number;
  if (m_knownArts.set)
  {
    int result = m_knownArts.set->Add(message_number);
    if (result < 0) {
      if (status)
        *status = result;
      return NS_ERROR_NOT_INITIALIZED;
    }
  }

  if (message_number > m_lastMsgNumber)
    m_lastMsgNumber = message_number;
  else if (message_number < m_firstMsgNumber)
    m_firstMsgNumber = message_number;

  if (m_set) {
    (void) m_set->IsMember(message_number);
  }

  /* Update the progress meter with a percentage of articles retrieved */
  if (m_lastMsgNumber > m_firstMsgNumber)
  {
    int32_t totalToDownload = m_lastMsgToDownload - m_firstMsgToDownload + 1;
    int32_t lastIndex = m_lastProcessedNumber - m_firstMsgNumber + 1;
    int32_t numDownloaded = lastIndex;
    int32_t totIndex = m_lastMsgNumber - m_firstMsgNumber + 1;

    PRTime elapsedTime = PR_Now() - m_lastStatusUpdate;

    if (elapsedTime > MIN_STATUS_UPDATE_INTERVAL || lastIndex == totIndex)
      UpdateStatus(false, numDownloaded, totalToDownload);
  }
  return NS_OK;
}

nsresult
nsNNTPNewsgroupList::ResetXOVER()
{
  m_lastMsgNumber = m_firstMsgNumber;
  m_lastProcessedNumber = m_lastMsgNumber;
  return NS_OK;
}

nsresult
nsNNTPNewsgroupList::FinishXOVERLINE(int status, int *newstatus)
{
  nsresult rv;
  struct MSG_NewsKnown* k;

  /* If any XOVER lines from the last time failed to come in, mark those
     messages as read. */

  if (status >= 0 && m_lastProcessedNumber < m_lastMsgNumber) {
    m_set->AddRange(m_lastProcessedNumber + 1, m_lastMsgNumber);
  }

  if (m_lastProcessedNumber)
    AddToKnownArticles(m_firstMsgNumber, m_lastProcessedNumber);

  k = &m_knownArts;

  if (k && k->set)
  {
    int32_t n = k->set->FirstNonMember();
    if (n < k->first_possible || n > k->last_possible)
    {
      /* We know we've gotten all there is to know.
         Take advantage of that to update our counts... */
      // ### dmb
    }
  }

  if (!m_finishingXover)
  {
    // turn on m_finishingXover - this is a horrible hack to avoid recursive
    // calls which happen when the fe selects a message as a result of getting EndingUpdate,
    // which interrupts this url right before it was going to finish and causes FinishXOver
    // to get called again.
    m_finishingXover = true;

    // XXX is this correct?
    m_runningURL = nullptr;

    if (m_lastMsgNumber > 0) {
      nsAutoString firstStr;
      firstStr.AppendInt(m_lastProcessedNumber - m_firstMsgNumber + 1);

      nsAutoString lastStr;
      lastStr.AppendInt(m_lastMsgNumber - m_firstMsgNumber + 1);

      nsString statusString;
      nsCOMPtr<nsIStringBundleService> bundleService =
        mozilla::services::GetStringBundleService();
      NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);

      nsCOMPtr<nsIStringBundle> bundle;
      rv = bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(bundle));
      NS_ENSURE_SUCCESS(rv, rv);

      const char16_t *formatStrings[2] = { firstStr.get(), lastStr.get() };
      rv = bundle->FormatStringFromName(u"downloadingArticles", formatStrings, 2, getter_Copies(statusString));
      NS_ENSURE_SUCCESS(rv, rv);

      SetProgressStatus(statusString.get());
    }
  }

  if (newstatus)
    *newstatus=0;

  return NS_OK;
}

NS_IMETHODIMP
nsNNTPNewsgroupList::InitXHDR(nsACString &header)
{
  if (++m_currentXHDRIndex >= m_filterHeaders.Length())
    header.Truncate();
  else
    header.Assign(m_filterHeaders[m_currentXHDRIndex]);
  // Don't include these in our XHDR bouts, as they are already provided through
  // XOVER. 
  if (header.EqualsLiteral("message-id") ||
      header.EqualsLiteral("references"))
    return InitXHDR(header);
  return NS_OK;
}

NS_IMETHODIMP
nsNNTPNewsgroupList::ProcessXHDRLine(const nsACString &line)
{
  int32_t middle = line.FindChar(' ');
  nsCString value, key = PromiseFlatCString(line);
  if (middle == -1)
    return NS_OK;
  value = Substring(line, middle+1);
  key.SetLength((uint32_t)middle);

  // According to RFC 2980, some will send (none) instead.
  // So we don't treat this is an error.
  if (key.CharAt(0) < '0' || key.CharAt(0) > '9')
    return NS_OK;

  nsresult rv;
  int32_t number = key.ToInteger(&rv);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
  // RFC 2980 specifies one or more spaces.
  value.Trim(" ");

  nsCOMPtr<nsIMsgDBHdr> header;
  rv = m_newsDB->GetMsgHdrForKey(number, getter_AddRefs(header));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = header->SetStringProperty(m_filterHeaders[m_currentXHDRIndex].get(), value.get());
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t totalToDownload = m_lastMsgToDownload - m_firstMsgToDownload + 1;
  int32_t numDownloaded = number - m_firstMsgNumber + 1;

  PRTime elapsedTime = PR_Now() - m_lastStatusUpdate;

  if (elapsedTime > MIN_STATUS_UPDATE_INTERVAL)
    UpdateStatus(true, numDownloaded, totalToDownload);
  return rv;
}

NS_IMETHODIMP
nsNNTPNewsgroupList::InitHEAD(int32_t number)
{
  if (m_newMsgHdr)
  {
    // Finish processing for this header
    // If HEAD didn't properly return, then the header won't be set
    m_newHeaders.AppendObject(m_newMsgHdr);

    int32_t totalToDownload = m_lastMsgToDownload - m_firstMsgToDownload + 1;
    int32_t lastIndex = m_lastProcessedNumber - m_firstMsgNumber + 1;
    int32_t numDownloaded = lastIndex;
    int32_t totIndex = m_lastMsgNumber - m_firstMsgNumber + 1;

    PRTime elapsedTime = PR_Now() - m_lastStatusUpdate;

    if (elapsedTime > MIN_STATUS_UPDATE_INTERVAL || lastIndex == totIndex)
      UpdateStatus(false, numDownloaded, totalToDownload);
  }

  if (number >= 0)
  {
    if (m_newHeaders.Count() > 0 && m_lastMsgNumber == m_lastProcessedNumber)
    {
      // We have done some processing of messages. This means that we have
      // relics of headers from XOVER. Since we will get everything from HEAD
      // anyways, just clear the array.
      m_newHeaders.Clear();
    }

    nsresult rv = m_newsDB->CreateNewHdr(number, getter_AddRefs(m_newMsgHdr));
    m_lastProcessedNumber = number;
    NS_ENSURE_SUCCESS(rv, rv);
  }
  else
  {
    AddToKnownArticles(m_firstMsgNumber, m_lastProcessedNumber);
  }
  return NS_OK;
}

NS_IMETHODIMP
nsNNTPNewsgroupList::HEADFailed(int32_t number)
{
  m_set->Add(number);
  return NS_OK;
}

NS_IMETHODIMP
nsNNTPNewsgroupList::ProcessHEADLine(const nsACString &line)
{
  int32_t colon = line.FindChar(':');
  nsCString header = PromiseFlatCString(line), value;
  if (colon != -1)
  {
    value = Substring(line, colon+1);
    header.SetLength((uint32_t)colon);
  }
  else if (line.CharAt(0) == ' ' || line.CharAt(0) == '\t') // We are continuing the header
  {
    m_thisLine += header; // Preserve whitespace (should we?)
    return NS_OK;
  }
  else
  {
    return NS_OK; // We are malformed. Just ignore and hope for the best...
  }
  
  nsresult rv;
  if (!m_lastHeader.IsEmpty())
  {
    rv = AddHeader(m_lastHeader.get(), m_thisLine.get());
    NS_ENSURE_SUCCESS(rv,rv);
  }
  
  value.Trim(" ");

  ToLowerCase(header, m_lastHeader);
  m_thisLine.Assign(value);
  return NS_OK;
}

nsresult
nsNNTPNewsgroupList::AddHeader(const char *header, const char *value)
{
  nsresult rv = NS_OK;
  // The From, Date, and Subject headers have special requirements.
  if (PL_strcmp(header, "from") == 0)
  {
    rv = m_newMsgHdr->SetAuthor(value);
  }
  else if (PL_strcmp(header, "date") == 0)
  {
    PRTime date;
    PRStatus status = PR_ParseTimeString (value, false, &date);
    if (PR_SUCCESS == status)
      rv = m_newMsgHdr->SetDate(date);
  }
  else if (PL_strcmp(header, "subject") == 0)
  {
    const char *subject = value;

    uint32_t flags = 0;
    // ### should call IsHeaderRead here...
    /* strip "Re: " */
    nsCString modifiedSubject;
    if (NS_MsgStripRE(nsDependentCString(subject), modifiedSubject))
      // this will make sure read flags agree with newsrc
     (void) m_newMsgHdr->OrFlags(nsMsgMessageFlags::HasRe, &flags);

    if (! (flags & nsMsgMessageFlags::Read))
      rv = m_newMsgHdr->OrFlags(nsMsgMessageFlags::New, &flags);

    rv = m_newMsgHdr->SetSubject(modifiedSubject.IsEmpty() ? subject :
      modifiedSubject.get());
  }
  else if (PL_strcmp(header, "message-id") == 0)
  {
    rv = m_newMsgHdr->SetMessageId(value);
  }
  else if (PL_strcmp(header, "references") == 0)
  {
    rv = m_newMsgHdr->SetReferences(value);
  }
  else if (PL_strcmp(header, "bytes") == 0)
  {
    rv = m_newMsgHdr->SetMessageSize(atol(value));
  }
  else if (PL_strcmp(header, "lines") == 0)
  {
    rv = m_newMsgHdr->SetLineCount(atol(value));
  }
  else if (m_filterHeaders.Contains(nsDependentCString(header)))
  {
    rv = m_newMsgHdr->SetStringProperty(header, value);
  }
  return rv;
}

nsresult
nsNNTPNewsgroupList::CallFilters()
{
  nsresult rv;
  nsCString filterString;
  
  nsCOMPtr <nsIMsgFolder> folder = do_QueryInterface(m_newsFolder, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  uint32_t filterCount = 0;
  if (m_filterList)
  {
    rv = m_filterList->GetFilterCount(&filterCount);
    NS_ENSURE_SUCCESS(rv,rv);
  }

  uint32_t serverFilterCount = 0;
  if (m_serverFilterList)
  {
    rv = m_serverFilterList->GetFilterCount(&serverFilterCount);
    NS_ENSURE_SUCCESS(rv,rv);
  }

  uint32_t count = m_newHeaders.Count();

  // Notify MsgFolderListeners of message adds
  nsCOMPtr<nsIMsgFolderNotificationService> notifier(do_GetService(NS_MSGNOTIFICATIONSERVICE_CONTRACTID));

  for (uint32_t i = 0; i < count; i++)
  {
    m_newMsgHdr = m_newHeaders[i];
    if (!filterCount && !serverFilterCount)
    {
      m_newsDB->AddNewHdrToDB(m_newMsgHdr, true);

      if (notifier)
        notifier->NotifyMsgAdded(m_newMsgHdr);
      // mark the header as not yet reported classified
      nsMsgKey msgKey;
      m_newMsgHdr->GetMessageKey(&msgKey);
      folder->OrProcessingFlags(msgKey,
                                nsMsgProcessingFlags::NotReportedClassified);

      continue;
    }
    m_addHdrToDB = true;

    // build up a "headers" for filter code
    nsCString subject, author, date;
    rv = m_newMsgHdr->GetSubject(getter_Copies(subject));
    NS_ENSURE_SUCCESS(rv,rv);
    rv = m_newMsgHdr->GetAuthor(getter_Copies(author));
    NS_ENSURE_SUCCESS(rv,rv);

    nsCString fullHeaders;
    if (!(author.IsEmpty()))
    {
      fullHeaders.AppendLiteral(FROM_HEADER);
      fullHeaders += author;
      fullHeaders += '\0';
    }

    if (!(subject.IsEmpty()))
    {
      fullHeaders.AppendLiteral(SUBJECT_HEADER);
      fullHeaders += subject;
      fullHeaders += '\0';
    }

    for (uint32_t header = 0; header < m_filterHeaders.Length(); header++)
    {
      nsCString retValue;
      m_newMsgHdr->GetStringProperty(m_filterHeaders[header].get(),
                                     getter_Copies(retValue));
      if (!retValue.IsEmpty())
      {
        fullHeaders += m_filterHeaders[header];
        fullHeaders.AppendLiteral(": ");
        fullHeaders += retValue;
        fullHeaders += '\0';
      }
    }

    // The per-newsgroup filters should go first. If something stops filter
    // execution, then users should be able to override the global filters in
    // the per-newsgroup filters.
    if (filterCount)
    {
      rv = m_filterList->ApplyFiltersToHdr(nsMsgFilterType::NewsRule,
          m_newMsgHdr, folder, m_newsDB, fullHeaders.get(),
          fullHeaders.Length(), this, m_msgWindow);
    }
    if (serverFilterCount)
    {
      rv = m_serverFilterList->ApplyFiltersToHdr(nsMsgFilterType::NewsRule,
          m_newMsgHdr, folder, m_newsDB, fullHeaders.get(),
          fullHeaders.Length(), this, m_msgWindow);
    }

    NS_ENSURE_SUCCESS(rv,rv);

    if (m_addHdrToDB)
    {
      m_newsDB->AddNewHdrToDB(m_newMsgHdr, true);
      if (notifier)
        notifier->NotifyMsgAdded(m_newMsgHdr);
      // mark the header as not yet reported classified
      nsMsgKey msgKey;
      m_newMsgHdr->GetMessageKey(&msgKey);
      folder->OrProcessingFlags(msgKey,
                                nsMsgProcessingFlags::NotReportedClassified);
    }
  }
  m_newHeaders.Clear();
  return NS_OK;
}

void
nsNNTPNewsgroupList::SetProgressBarPercent(int32_t percent)
{
  if (!m_runningURL)
    return;

  nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL);
  if (mailnewsUrl) {
    nsCOMPtr <nsIMsgStatusFeedback> feedback;
    mailnewsUrl->GetStatusFeedback(getter_AddRefs(feedback));

    if (feedback) {
      feedback->ShowProgress(percent);
    }
  }
}

void
nsNNTPNewsgroupList::SetProgressStatus(const char16_t *aMessage)
{
  if (!m_runningURL)
    return;

  nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(m_runningURL);
  if (mailnewsUrl) {
    nsCOMPtr <nsIMsgStatusFeedback> feedback;
    mailnewsUrl->GetStatusFeedback(getter_AddRefs(feedback));

    if (feedback) {
      // prepending the account name to the status message.
      nsresult rv;
      nsCOMPtr <nsIMsgIncomingServer> server;
      rv = mailnewsUrl->GetServer(getter_AddRefs(server));
      NS_ENSURE_SUCCESS_VOID(rv);
      nsString accountName;
      server->GetPrettyName(accountName);
      nsString statusMessage;
      nsCOMPtr<nsIStringBundleService> sbs =
        mozilla::services::GetStringBundleService();
      nsCOMPtr<nsIStringBundle> bundle;
      rv = sbs->CreateBundle(MSGS_URL,
                             getter_AddRefs(bundle));
      NS_ENSURE_SUCCESS_VOID(rv);
      const char16_t *params[] = { accountName.get(), aMessage };
      bundle->FormatStringFromName(u"statusMessage",
                                   params, 2, getter_Copies(statusMessage));

      feedback->ShowStatusString(statusMessage);
    }
  }
}

void
nsNNTPNewsgroupList::UpdateStatus(bool filtering, int32_t numDLed, int32_t totToDL)
{
  int32_t numerator = (filtering ? m_currentXHDRIndex + 1 : 1) * numDLed;
  int32_t denominator = (m_filterHeaders.Length() + 1) * totToDL;
  int32_t percent = numerator * 100 / denominator;
  
  nsAutoString numDownloadedStr;
  numDownloadedStr.AppendInt(numDLed);

  nsAutoString totalToDownloadStr;
  totalToDownloadStr.AppendInt(totToDL);

  nsAutoString newsgroupName;
  nsresult rv = m_newsFolder->GetUnicodeName(newsgroupName);
  if (!NS_SUCCEEDED(rv))
      return;

  nsString statusString;
  nsCOMPtr<nsIStringBundleService> bundleService =
    mozilla::services::GetStringBundleService();
  if (!bundleService)
    return;

  nsCOMPtr<nsIStringBundle> bundle;
  rv = bundleService->CreateBundle(NEWS_MSGS_URL, getter_AddRefs(bundle));
  if (!NS_SUCCEEDED(rv))
    return;

  if (filtering)
  {
    NS_ConvertUTF8toUTF16 header(m_filterHeaders[m_currentXHDRIndex]);
    const char16_t *formatStrings[4] = { header.get(),
      numDownloadedStr.get(), totalToDownloadStr.get(), newsgroupName.get() };
    rv = bundle->FormatStringFromName(u"newNewsgroupFilteringHeaders",
      formatStrings, 4, getter_Copies(statusString));
  }
  else
  {
    const char16_t *formatStrings[3] = { numDownloadedStr.get(),
      totalToDownloadStr.get(), newsgroupName.get() };
    rv = bundle->FormatStringFromName(u"newNewsgroupHeaders",
      formatStrings, 3, getter_Copies(statusString));
  }
  if (!NS_SUCCEEDED(rv))
    return;

  SetProgressStatus(statusString.get());
  m_lastStatusUpdate = PR_Now();

  // only update the progress meter if it has changed
  if (percent != m_lastPercent)
  {
    SetProgressBarPercent(percent);
    m_lastPercent = percent;
  }
}

NS_IMETHODIMP nsNNTPNewsgroupList::SetGetOldMessages(bool aGetOldMessages)
{
  m_getOldMessages = aGetOldMessages;
  return NS_OK;
}

NS_IMETHODIMP nsNNTPNewsgroupList::GetGetOldMessages(bool *aGetOldMessages)
{
  NS_ENSURE_ARG(aGetOldMessages);

  *aGetOldMessages = m_getOldMessages;
  return NS_OK;
}