summaryrefslogtreecommitdiffstats
path: root/knode/kngroupmanager.cpp
blob: 151efa0f0b39d28c58ee6e25625040a2b71ef5fd (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
/*
    KNode, the KDE newsreader
    Copyright (c) 1999-2005 the KNode authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US
*/

#include <stdio.h>
#include <stdlib.h>
#include <tqdir.h>

#include <klocale.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kcharsets.h>

#include "articlewidget.h"
#include "knmainwidget.h"
#include "knarticlemanager.h"
#include "kngroupdialog.h"
#include "knnntpaccount.h"
#include "knprotocolclient.h"
#include "kncleanup.h"
#include "knnetaccess.h"
#include "knglobals.h"
#include "knconfigmanager.h"
#include "resource.h"
#include "utilities.h"
#include "knarticlewindow.h"
#include "knmemorymanager.h"

using namespace KNode;


//=================================================================================

// helper classes for the group selection dialog (getting the server's grouplist,
// getting recently created groups)


KNGroupInfo::KNGroupInfo()
{
}


KNGroupInfo::KNGroupInfo(const TQString &n_ame, const TQString &d_escription, bool n_ewGroup, bool s_ubscribed, KNGroup::tqStatus s_tatus)
  : name(n_ame), description(d_escription), newGroup(n_ewGroup), subscribed(s_ubscribed),
    status(s_tatus)
{
}


KNGroupInfo::~KNGroupInfo()
{
}


bool KNGroupInfo::operator== (const KNGroupInfo &gi2)
{
  return (name == gi2.name);
}


bool KNGroupInfo::operator< (const KNGroupInfo &gi2)
{
  return (name < gi2.name);
}


//===============================================================================


KNGroupListData::KNGroupListData()
  : codecForDescriptions(0)
{
  groups = new TQSortedList<KNGroupInfo>;
  groups->setAutoDelete(true);
}



KNGroupListData::~KNGroupListData()
{
  delete groups;
}



bool KNGroupListData::readIn(KNProtocolClient *client)
{
  KNFile f(path+"groups");
  TQCString line;
  int sepPos1,sepPos2;
  TQString name,description;
  bool sub;
  KNGroup::tqStatus status=KNGroup::unknown;
  TQTime timer;
  uint size=f.size()+2;

  timer.start();
  if (client) client->updatePercentage(0);

  if(f.open(IO_ReadOnly)) {
    while(!f.atEnd()) {
      line = f.readLine();
      sepPos1 = line.tqfind(' ');

      if (sepPos1==-1) {        // no description
        name = TQString::fromUtf8(line);
        description = TQString();
        status = KNGroup::unknown;
      } else {
        name = TQString::fromUtf8(line.left(sepPos1));

        sepPos2 = line.tqfind(' ',sepPos1+1);
        if (sepPos2==-1) {        // no status
          description = TQString::fromUtf8(line.right(line.length()-sepPos1-1));
          status = KNGroup::unknown;
        } else {
          description = TQString::fromUtf8(line.right(line.length()-sepPos2-1));
          switch (line[sepPos1+1]) {
            case 'u':   status = KNGroup::unknown;
                        break;
            case 'n':   status = KNGroup::readOnly;
                        break;
            case 'y':   status = KNGroup::postingAllowed;
                        break;
            case 'm':   status = KNGroup::moderated;
                        break;
          }
        }
      }

      if (subscribed.tqcontains(name)) {
        subscribed.remove(name);    // group names are unique, we wont find it again anyway...
        sub = true;
      } else
        sub = false;

      groups->append(new KNGroupInfo(name,description,false,sub,status));

      if (timer.elapsed() > 200) {           // don't flicker
        timer.restart();
        if (client) client->updatePercentage((f.at()*100)/size);
      }
    }

    f.close();
    return true;
  } else {
    kdWarning(5003) << "unable to open " << f.name() << " reason " << f.status() << endl;
    return false;
  }
}



bool KNGroupListData::writeOut()
{
  TQFile f(path+"groups");
  TQCString temp;

  if(f.open(IO_WriteOnly)) {
    for (KNGroupInfo *i=groups->first(); i; i=groups->next()) {
      temp = i->name.utf8();
      switch (i->status) {
        case KNGroup::unknown: temp += " u ";
                               break;
        case KNGroup::readOnly: temp += " n ";
                                break;
        case KNGroup::postingAllowed: temp += " y ";
                                      break;
        case KNGroup::moderated: temp += " m ";
                                 break;
      }
      temp += i->description.utf8() + "\n";
      f.writeBlock(temp.data(),temp.length());
    }
    f.close();
    return true;
  } else {
    kdWarning(5003) << "unable to open " << f.name() << " reason " << f.status() << endl;
    return false;
  }
}



// merge in new groups, we want to preserve the "subscribed"-flag
// of the loaded groups and the "new"-flag of the new groups.
void KNGroupListData::merge(TQSortedList<KNGroupInfo>* newGroups)
{
  bool subscribed;

  for (KNGroupInfo *i=newGroups->first(); i; i=newGroups->next()) {
    if (groups->tqfind(i)>=0) {
      subscribed = groups->current()->subscribed;
      groups->remove();   // avoid duplicates
    } else
      subscribed = false;
    groups->append(new KNGroupInfo(i->name,i->description,true,subscribed,i->status));
  }

  groups->sort();
}


TQSortedList<KNGroupInfo>* KNGroupListData::extractList()
{
  TQSortedList<KNGroupInfo>* temp = groups;
  groups = 0;
  return temp;
}


//===============================================================================


KNGroupManager::KNGroupManager(TQObject * tqparent, const char * name)
  : TQObject(tqparent,name)
{
  c_urrentGroup=0;
  a_rticleMgr = knGlobals.articleManager();
}


KNGroupManager::~KNGroupManager()
{
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it )
    delete (*it);
}


void KNGroupManager::syncGroups()
{
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it ) {
    (*it)->syncDynamicData();
    (*it)->saveInfo();
  }
}


void KNGroupManager::loadGroups(KNNntpAccount *a)
{
  KNGroup *group;

  TQString dir(a->path());
  if (dir.isNull())
    return;
  TQDir d(dir);

  TQStringList entries(d.entryList("*.grpinfo"));
  for(TQStringList::Iterator it=entries.begin(); it != entries.end(); ++it) {
    group=new KNGroup(a);
    if (group->readInfo(dir+(*it))) {
      mGroupList.append( group );
      emit groupAdded(group);
    } else {
      delete group;
      kdError(5003) << "Unable to load " << (*it) << "!" << endl;
    }
  }
}


void KNGroupManager::getSubscribed(KNNntpAccount *a, TQStringList &l)
{
  l.clear();
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it )
    if ( (*it)->account() == a )
      l.append( (*it)->groupname() );
}


TQValueList<KNGroup*> KNGroupManager::groupsOfAccount( KNNntpAccount *a )
{
  TQValueList<KNGroup*> ret;
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it )
    if ( (*it)->account() == a )
      ret.append( (*it) );
  return ret;
}


bool KNGroupManager::loadHeaders(KNGroup *g)
{
  if (!g)
    return false;

  if (g->isLoaded())
    return true;

  // we want to delete old stuff first => reduce vm fragmentation
  knGlobals.memoryManager()->prepareLoad(g);

  if (g->loadHdrs()) {
    knGlobals.memoryManager()->updateCacheEntry( g );
    return true;
  }

  return false;
}


bool KNGroupManager::unloadHeaders(KNGroup *g, bool force)
{
  if(!g || g->isLocked())
    return false;

  if(!g->isLoaded())
    return true;

  if (!force && (c_urrentGroup == g))
    return false;

  if (g->unloadHdrs(force))
    knGlobals.memoryManager()->removeCacheEntry(g);
  else
    return false;

  return true;
}


KNGroup* KNGroupManager::group(const TQString &gName, const KNServerInfo *s)
{
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it )
    if ( (*it)->account() == s && (*it)->groupname() == gName )
      return (*it);

  return 0;
}


KNGroup* KNGroupManager::firstGroupOfAccount(const KNServerInfo *s)
{
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it )
    if ( (*it)->account() == s )
      return (*it);

  return 0;
}


void KNGroupManager::expireAll(KNCleanUp *cup)
{
  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it ) {
    if( (*it)->isLocked() || (*it)->lockedArticles() > 0 )
      continue;
    if ( !(*it)->activeCleanupConfig()->expireToday() )
      continue;
    cup->appendCollection( *(it) );
  }
}


void KNGroupManager::expireAll(KNNntpAccount *a)
{
  KNCleanUp *cup = new KNCleanUp();

  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it ) {
    if( (*it)->account() != a  || (*it)->isLocked() || (*it)->lockedArticles() > 0 )
      continue;

    KNArticleWindow::closeAllWindowsForCollection( (*it) );
    cup->appendCollection( (*it) );
  }

  cup->start();

  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it ) {
    if( (*it)->account() != a  || (*it)->isLocked() || (*it)->lockedArticles() > 0 )
      continue;

    emit groupUpdated( (*it) );
    if ( (*it) == c_urrentGroup ) {
      if ( loadHeaders( (*it) ) )
        a_rticleMgr->showHdrs();
      else
        a_rticleMgr->setGroup(0);
    }
  }

  delete cup;
}


void KNGroupManager::showGroupDialog(KNNntpAccount *a, TQWidget *tqparent)
{
  KNGroupDialog* gDialog=new KNGroupDialog((tqparent!=0)? tqparent:knGlobals.topWidget, a);

  connect(gDialog, TQT_SIGNAL(loadList(KNNntpAccount*)), this, TQT_SLOT(slotLoadGroupList(KNNntpAccount*)));
  connect(gDialog, TQT_SIGNAL(fetchList(KNNntpAccount*)), this, TQT_SLOT(slotFetchGroupList(KNNntpAccount*)));
  connect(gDialog, TQT_SIGNAL(checkNew(KNNntpAccount*,TQDate)), this, TQT_SLOT(slotCheckForNewGroups(KNNntpAccount*,TQDate)));
  connect(this, TQT_SIGNAL(newListReady(KNGroupListData*)), gDialog, TQT_SLOT(slotReceiveList(KNGroupListData*)));

  if(gDialog->exec()) {
    KNGroup *g=0;

    TQStringList lst;
    gDialog->toUnsubscribe(&lst);
    if (lst.count()>0) {
      if (KMessageBox::Yes == KMessageBox::questionYesNoList((tqparent!=0)? tqparent:knGlobals.topWidget,i18n("Do you really want to unsubscribe\nfrom these groups?"),
                                                              lst, TQString(), i18n("Unsubscribe"), KStdGuiItem::cancel())) {
        for ( TQStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) {
          if((g=group(*it, a)))
            unsubscribeGroup(g);
        }
      }
    }

    TQSortedList<KNGroupInfo> lst2;
    gDialog->toSubscribe(&lst2);
    for(KNGroupInfo *var=lst2.first(); var; var=lst2.next()) {
      subscribeGroup(var, a);
    }
  }

  delete gDialog;
}


void KNGroupManager::subscribeGroup(const KNGroupInfo *gi, KNNntpAccount *a)
{
  KNGroup *grp;

  grp=new KNGroup(a);
  grp->setGroupname(gi->name);
  grp->setDescription(gi->description);
  grp->setqStatus(gi->status);
  grp->saveInfo();
  mGroupList.append( grp );
  emit groupAdded(grp);
}


bool KNGroupManager::unsubscribeGroup(KNGroup *g)
{
  KNNntpAccount *acc;
  if(!g) g=c_urrentGroup;
  if(!g) return false;

  if((g->isLocked()) || (g->lockedArticles()>0)) {
    KMessageBox::sorry(knGlobals.topWidget, i18n("The group \"%1\" is being updated currently.\nIt is not possible to unsubscribe from it at the moment.").tqarg(g->groupname()));
    return false;
  }

  KNArticleWindow::closeAllWindowsForCollection(g);
  ArticleWidget::collectionRemoved( g );

  acc=g->account();

  TQDir dir(acc->path(),g->groupname()+"*");
  if (dir.exists()) {
    if (unloadHeaders(g, true)) {
      if(c_urrentGroup==g) {
        setCurrentGroup(0);
        a_rticleMgr->updateStatusString();
      }

      const TQFileInfoList *list = dir.entryInfoList();  // get list of matching files and delete all
      if (list) {
        TQFileInfoListIterator it( *list );
        while (it.current()) {
          if (it.current()->fileName() == g->groupname()+".dynamic" ||
              it.current()->fileName() == g->groupname()+".static" ||
              it.current()->fileName() == g->groupname()+".grpinfo")
          dir.remove(it.current()->fileName());
          ++it;
        }
      }
      kdDebug(5003) << "Files deleted!" << endl;

      emit groupRemoved(g);
      mGroupList.remove( g );
      delete g;

      return true;
    }
  }

  return false;
}


void KNGroupManager::showGroupProperties(KNGroup *g)
{
  if(!g) g=c_urrentGroup;
  if(!g) return;
  g->showProperties();
}


void KNGroupManager::checkGroupForNewHeaders(KNGroup *g)
{
  if(!g) g=c_urrentGroup;
  if(!g) return;
  if(g->isLocked()) {
    kdDebug(5003) << "KNGroupManager::checkGroupForNewHeaders() : group locked - returning" << endl;
    return;
  }

  g->setMaxFetch(knGlobals.configManager()->readNewsGeneral()->maxToFetch());
  emitJob( new KNJobData(KNJobData::JTfetchNewHeaders, this, g->account(), g) );
}


void KNGroupManager::expireGroupNow(KNGroup *g)
{
  if(!g) return;

  if((g->isLocked()) || (g->lockedArticles()>0)) {
    KMessageBox::sorry(knGlobals.topWidget,
      i18n("This group cannot be expired because it is currently being updated.\n Please try again later."));
    return;
  }

  KNArticleWindow::closeAllWindowsForCollection(g);

  KNCleanUp cup;
  cup.expireGroup(g, true);

  emit groupUpdated(g);
  if(g==c_urrentGroup) {
    if( loadHeaders(g) )
      a_rticleMgr->showHdrs();
    else
      a_rticleMgr->setGroup(0);
  }
}


void KNGroupManager::reorganizeGroup(KNGroup *g)
{
  if(!g) g=c_urrentGroup;
  if(!g) return;
  g->reorganize();
  if(g==c_urrentGroup)
    a_rticleMgr->showHdrs();
}


void KNGroupManager::setCurrentGroup(KNGroup *g)
{
  c_urrentGroup=g;
  a_rticleMgr->setGroup(g);
  kdDebug(5003) << "KNGroupManager::setCurrentGroup() : group changed" << endl;

  if(g) {
    if( !loadHeaders(g) ) {
      //KMessageBox::error(knGlobals.topWidget, i18n("Cannot load saved headers"));
      return;
    }
    a_rticleMgr->showHdrs();
    if(knGlobals.configManager()->readNewsGeneral()->autoCheckGroups())
      checkGroupForNewHeaders(g);
  }
}


void KNGroupManager::checkAll(KNNntpAccount *a, bool silent)
{
  if(!a) return;

  for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it ) {
    if ( (*it)->account() == a ) {
      (*it)->setMaxFetch( knGlobals.configManager()->readNewsGeneral()->maxToFetch() );
      if ( silent )
        emitJob( new KNJobData(KNJobData::JTsilentFetchNewHeaders, this, (*it)->account(), (*it) ) );
      else
        emitJob( new KNJobData(KNJobData::JTfetchNewHeaders, this, (*it)->account(), (*it) ) );
    }
  }
}


void KNGroupManager::processJob(KNJobData *j)
{
  if((j->type()==KNJobData::JTLoadGroups)||(j->type()==KNJobData::JTFetchGroups)||(j->type()==KNJobData::JTCheckNewGroups)) {
    KNGroupListData *d=static_cast<KNGroupListData*>(j->data());

    if (!j->canceled()) {
      if (j->success()) {
        if ((j->type()==KNJobData::JTFetchGroups)||(j->type()==KNJobData::JTCheckNewGroups)) {
          // update the descriptions of the subscribed groups
          for ( TQValueList<KNGroup*>::Iterator it = mGroupList.begin(); it != mGroupList.end(); ++it ) {
            if ( (*it)->account() == j->account() ) {
              for ( KNGroupInfo* inf = d->groups->first(); inf; inf = d->groups->next() )
                if ( inf->name == (*it)->groupname() ) {
                  (*it)->setDescription( inf->description );
                  (*it)->setqStatus( inf->status );
                  break;
                }
            }
          }
        }
        emit(newListReady(d));
      } else {
        KMessageBox::error(knGlobals.topWidget, j->errorString());
        emit(newListReady(0));
      }
    } else
      emit(newListReady(0));

    delete j;
    delete d;


  } else {               //KNJobData::JTfetchNewHeaders or KNJobData::JTsilentFetchNewHeaders
    KNGroup *group=static_cast<KNGroup*>(j->data());

    if (!j->canceled()) {
      if (j->success()) {
        if(group->lastFetchCount()>0) {
          group->scoreArticles();
          group->processXPostBuffer(true);
          emit groupUpdated(group);
          group->saveInfo();
          knGlobals.memoryManager()->updateCacheEntry(group);
        }
      } else {
        // ok, hack (?):
        // stop all other active fetch jobs, this prevents that
        // we show multiple error dialogs if a server is unavailable
        knGlobals.netAccess()->stopJobsNntp(KNJobData::JTfetchNewHeaders);
        knGlobals.netAccess()->stopJobsNntp(KNJobData::JTsilentFetchNewHeaders);
        if(!(j->type()==KNJobData::JTsilentFetchNewHeaders)) {
          KMessageBox::error(knGlobals.topWidget, j->errorString());
        }
      }
    }
    if(group==c_urrentGroup)
      a_rticleMgr->showHdrs(false);

    delete j;
  }
}


// load group list from disk (if this fails: ask user if we should fetch the list)
void KNGroupManager::slotLoadGroupList(KNNntpAccount *a)
{
  KNGroupListData *d = new KNGroupListData();
  d->path = a->path();

  if(!TQFileInfo(d->path+"groups").exists()) {
    if (KMessageBox::Yes==KMessageBox::questionYesNo(knGlobals.topWidget,i18n("You do not have any groups for this account;\ndo you want to fetch a current list?"), TQString(), i18n("Fetch List"), i18n("Do Not Fetch"))) {
      delete d;
      slotFetchGroupList(a);
      return;
    } else {
      emit(newListReady(d));
      delete d;
      return;
    }
  }

  getSubscribed(a,d->subscribed);
  d->getDescriptions = a->fetchDescriptions();

  emitJob( new KNJobData(KNJobData::JTLoadGroups, this, a, d) );
}


// fetch group list from server
void KNGroupManager::slotFetchGroupList(KNNntpAccount *a)
{
  KNGroupListData *d = new KNGroupListData();
  d->path = a->path();
  getSubscribed(a,d->subscribed);
  d->getDescriptions = a->fetchDescriptions();
  d->codecForDescriptions=KGlobal::charsets()->codecForName(knGlobals.configManager()->postNewsTechnical()->charset());

  emitJob( new KNJobData(KNJobData::JTFetchGroups, this, a, d) );
}


// check for new groups (created after the given date)
void KNGroupManager::slotCheckForNewGroups(KNNntpAccount *a, TQDate date)
{
  KNGroupListData *d = new KNGroupListData();
  d->path = a->path();
  getSubscribed(a,d->subscribed);
  d->getDescriptions = a->fetchDescriptions();
  d->fetchSince = date;
  d->codecForDescriptions=KGlobal::charsets()->codecForName(knGlobals.configManager()->postNewsTechnical()->charset());

  emitJob( new KNJobData(KNJobData::JTCheckNewGroups, this, a, d) );
}


//--------------------------------

#include "kngroupmanager.moc"

// kate: space-indent on; indent-width 2;