~ubuntu-branches/ubuntu/natty/knemo/natty

« back to all changes in this revision

Viewing changes to src/knemod/interfacestatistics.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Felix Geyer
  • Date: 2011-02-22 16:36:22 UTC
  • mfrom: (1.1.13 upstream)
  • Revision ID: james.westby@ubuntu.com-20110222163622-d8i62gy1stn7tydv
Tags: 0.7.0-0ubuntu1
* New upstream release.
* Switch to source format 3.0 (quilt).
* Make knemo depend on libqt4-sql-sqlite.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* This file is part of KNemo
2
2
   Copyright (C) 2005, 2006 Percy Leonhardt <percy@eris23.de>
3
 
   Copyright (C) 2009 John Stamp <jstamp@users.sourceforge.net>
 
3
   Copyright (C) 2009, 2010 John Stamp <jstamp@users.sourceforge.net>
4
4
 
5
5
   KNemo is free software; you can redistribute it and/or modify
6
6
   it under the terms of the GNU Library General Public License as
18
18
   Boston, MA 02110-1301, USA.
19
19
*/
20
20
 
21
 
#include <QDomNode>
22
 
#include <QFile>
23
21
#include <QTimer>
24
22
 
25
23
#include <KCalendarSystem>
32
30
#include "global.h"
33
31
#include "interface.h"
34
32
#include "interfacestatistics.h"
 
33
#include "statisticsmodel.h"
35
34
#include "syncstats/statsfactory.h"
36
 
 
37
 
static const char statistics_prefix[] = "/statistics_";
38
 
 
39
 
static const char doc_name[]     = "statistics";
40
 
 
41
 
static const char attrib_calendar[] = "calendar";
42
 
static const char attrib_version[]  = "version";
43
 
static const char attrib_updated[]  = "lastUpdated";
44
 
static const char attrib_span[]     = "span";
45
 
static const char attrib_rx[]       = "rxBytes";
46
 
static const char attrib_tx[]       = "txBytes";
47
 
 
48
 
static const char* intervals[] = { "hour", "day", "week", "month", "year" };
 
35
#include "storage/sqlstorage.h"
 
36
#include "storage/xmlstorage.h"
 
37
 
 
38
static bool statsLessThan( const StatsRule& s1, const StatsRule& s2 )
 
39
{
 
40
    if ( s1.startDate < s2.startDate )
 
41
        return true;
 
42
    else
 
43
        return false;
 
44
}
49
45
 
50
46
InterfaceStatistics::InterfaceStatistics( Interface* interface )
51
47
    : QObject(),
 
48
      mInterface( interface ),
52
49
      mSaveTimer( new QTimer() ),
53
 
      mInterface( interface ),
54
 
      mAllMonths( true )
 
50
      mWarnTimer( new QTimer() ),
 
51
      mEntryTimer( new QTimer() ),
 
52
      mTrafficChanged( false )
55
53
{
56
 
    StatisticsModel * s = new StatisticsModel( StatisticsModel::Hour, this );
57
 
    mModels.insert( StatisticsModel::Hour, s );
58
 
    s = new StatisticsModel( StatisticsModel::Day, this );
59
 
    mModels.insert( StatisticsModel::Day, s );
60
 
    s = new StatisticsModel( StatisticsModel::Week, this );
61
 
    mModels.insert( StatisticsModel::Week, s );
62
 
    s = new StatisticsModel( StatisticsModel::Month, this );
63
 
    mModels.insert( StatisticsModel::Month, s );
64
 
    s = new StatisticsModel( StatisticsModel::Year, this );
65
 
    mModels.insert( StatisticsModel::Year, s );
 
54
    StatisticsModel * s = new StatisticsModel( KNemoStats::Hour, this );
 
55
    mModels.insert( KNemoStats::Hour, s );
 
56
    s = new StatisticsModel( KNemoStats::Day, this );
 
57
    mModels.insert( KNemoStats::Day, s );
 
58
    s = new StatisticsModel( KNemoStats::Week, this );
 
59
    mModels.insert( KNemoStats::Week, s );
 
60
    s = new StatisticsModel( KNemoStats::Month, this );
 
61
    mModels.insert( KNemoStats::Month, s );
 
62
    s = new StatisticsModel( KNemoStats::Year, this );
 
63
    mModels.insert( KNemoStats::Year, s );
 
64
    s = new StatisticsModel( KNemoStats::BillPeriod, this );
 
65
    mModels.insert( KNemoStats::BillPeriod, s );
 
66
    s = new StatisticsModel( KNemoStats::HourArchive, this );
 
67
    mModels.insert( KNemoStats::HourArchive, s );
 
68
 
 
69
    foreach ( StatisticsModel *s, mModels )
 
70
    {
 
71
        mStorageData.saveFromId.insert( s->periodType(), 0 );
 
72
    }
66
73
 
67
74
    connect( mSaveTimer, SIGNAL( timeout() ), this, SLOT( saveStatistics() ) );
 
75
    connect( mWarnTimer, SIGNAL( timeout() ), this, SLOT( checkWarnings() ) );
 
76
    connect( mEntryTimer, SIGNAL( timeout() ), this, SLOT( checkValidEntry() ) );
68
77
 
69
 
    loadConfig();
70
 
    loadStatistics();
 
78
    KUrl dir( generalSettings->statisticsDir );
 
79
    sql = new SqlStorage( mInterface->ifaceName() );
 
80
    loadStats();
 
81
    syncWithExternal( mStorageData.lastSaved );
 
82
    configChanged();
71
83
}
72
84
 
73
85
InterfaceStatistics::~InterfaceStatistics()
74
86
{
75
87
    mSaveTimer->stop();
 
88
    mWarnTimer->stop();
 
89
    mEntryTimer->stop();
76
90
    delete mSaveTimer;
 
91
    delete mWarnTimer;
 
92
    delete mEntryTimer;
77
93
 
78
94
    saveStatistics();
79
 
 
80
 
    if ( mInterface->getSettings().customBilling )
81
 
    {
82
 
        mInterface->getSettings().billingStart = mBillingStart;
83
 
        KConfig *config = KGlobal::config().data();
84
 
        KConfigGroup interfaceGroup( config, confg_interface + mInterface->getName() );
85
 
        interfaceGroup.writeEntry( conf_billingStart, mBillingStart );
86
 
        config->sync();
87
 
    }
88
 
}
89
 
 
90
 
QString InterfaceStatistics::typeToElem( enum StatisticsModel::GroupType t )
91
 
{
92
 
    int i = 0;
93
 
    int v = t;
94
 
    while ( v > StatisticsModel::Hour )
95
 
    {
96
 
        v = v >> 1;
97
 
        i++;
98
 
    }
99
 
    return intervals[i];
100
 
}
101
 
 
102
 
void InterfaceStatistics::clearStatistics()
103
 
{
104
 
    foreach( StatisticsModel * s, mModels )
105
 
        s->clearRows();
106
 
    emit currentEntryChanged();
107
 
}
108
 
 
109
 
void InterfaceStatistics::loadConfig()
110
 
{
111
 
    mCalendar = KCalendarSystem::create( mInterface->getSettings().calendar );
112
 
    // TODO: Test for a KDE release that contains SVN commit 1013534
113
 
    KGlobal::locale()->setCalendar( mCalendar->calendarType() );
114
 
    foreach( StatisticsModel * s, mModels )
115
 
        s->setCalendar( mCalendar );
116
 
 
117
 
    mWarningDone = false;
118
 
    mBillingStart = mInterface->getSettings().billingStart;
 
95
    delete sql;
 
96
    QSqlDatabase::removeDatabase( mInterface->ifaceName() );
 
97
}
 
98
 
 
99
void InterfaceStatistics::saveStatistics( bool fullSave )
 
100
{
 
101
    sql->saveStats( &mStorageData, &mModels, &mStatsRules, fullSave );
 
102
}
 
103
 
 
104
bool InterfaceStatistics::loadStats()
 
105
{
 
106
    KUrl dir( generalSettings->statisticsDir );
 
107
    if ( !dir.isLocalFile() )
 
108
        return 0;
 
109
 
 
110
    bool loaded = false;
 
111
 
 
112
    if ( sql->dbExists() )
 
113
    {
 
114
        loaded = sql->loadStats( &mStorageData, &mModels, &mStatsRules );
 
115
        qSort( mStatsRules.begin(), mStatsRules.end(), statsLessThan );
 
116
    }
 
117
    else
 
118
    {
 
119
        XmlStorage xml;
 
120
        loaded = xml.loadStats( mInterface->ifaceName(), &mStorageData, &mModels );
 
121
        sql->createDb();
 
122
        if ( loaded )
 
123
        {
 
124
            hoursToArchive( QDateTime::currentDateTime() );
 
125
            checkRebuild( mStorageData.calendar->calendarType(), true );
 
126
        }
 
127
    }
 
128
 
 
129
    if ( !mStorageData.calendar )
 
130
    {
 
131
        mStorageData.calendar = KCalendarSystem::create( mInterface->settings().calendar );
 
132
        foreach( StatisticsModel * s, mModels )
 
133
        {
 
134
            s->setCalendar( mStorageData.calendar );
 
135
        }
 
136
    }
 
137
    return loaded;
 
138
}
 
139
 
 
140
/**********************************
 
141
 * Stats Entry Generators         *
 
142
 **********************************/
 
143
 
 
144
void InterfaceStatistics::resetWarnings( int modelType )
 
145
{
 
146
    for ( int i = 0; i < mInterface->settings().warnRules.count(); ++i )
 
147
    {
 
148
        if ( modelType == mInterface->settings().warnRules[i].periodUnits )
 
149
            mInterface->settings().warnRules[i].warnDone = false;
 
150
    }
 
151
}
 
152
 
 
153
void InterfaceStatistics::hoursToArchive( const QDateTime &dateTime )
 
154
{
 
155
    bool removedRow = false;
 
156
    StatisticsModel* hours = mModels.value( KNemoStats::Hour );
 
157
    StatisticsModel* hourArchives = mModels.value( KNemoStats::HourArchive );
 
158
 
 
159
    // Only 24 hours
 
160
    while ( hours->rowCount() )
 
161
    {
 
162
        if ( hours->dateTime( 0 ) <= dateTime.addDays( -1 ) )
 
163
        {
 
164
            QList<QStandardItem*> row = hours->takeRow( 0 );
 
165
            hourArchives->appendRow( row );
 
166
            hourArchives->setId( mStorageData.nextHourId );
 
167
            mStorageData.nextHourId++;
 
168
            removedRow = true;
 
169
        }
 
170
        else
 
171
            break;
 
172
    }
 
173
    if ( removedRow )
 
174
    {
 
175
        for ( int i = 0; i < hours->rowCount(); ++i )
 
176
        {
 
177
            hours->setId( i, i );
 
178
        }
 
179
        mStorageData.saveFromId.insert( hours->periodType(), 0 );
 
180
        mStorageData.saveFromId.insert( hourArchives->periodType(), hourArchives->id( 0 ) );
 
181
    }
 
182
}
 
183
 
 
184
void InterfaceStatistics::genNewHour( const QDateTime &dateTime )
 
185
{
 
186
    hoursToArchive( dateTime );
 
187
 
 
188
    StatisticsModel* hours = mModels.value( KNemoStats::Hour );
 
189
 
 
190
    if ( hours->dateTime() == dateTime )
 
191
        return;
 
192
 
 
193
    int ruleIndex = ruleForDate( dateTime.date() );
 
194
    if ( ruleIndex >= 0  && isOffpeak( mStatsRules[ruleIndex], dateTime ) )
 
195
    {
 
196
        hours->addTrafficType( KNemoStats::OffpeakTraffic );
 
197
    }
 
198
 
 
199
    hours->createEntry( dateTime );
 
200
 
 
201
    resetWarnings( hours->periodType() );
 
202
}
 
203
 
 
204
bool InterfaceStatistics::genNewCalendarType( const QDate &date, const KNemoStats::PeriodUnits stype )
 
205
{
 
206
    if ( stype < KNemoStats::Day || stype > KNemoStats::Year )
 
207
        return false;
 
208
 
 
209
    StatisticsModel * model = mModels.value( stype );
 
210
    if ( model->rowCount() &&
 
211
         model->date().addDays( model->days() ) > date )
 
212
            return false;
 
213
 
 
214
    QDate newDate;
 
215
    int dayOf;
 
216
    int weekStartDay = mStorageData.calendar->weekStartDay();
 
217
 
 
218
    switch ( stype )
 
219
    {
 
220
        case KNemoStats::Day:
 
221
            newDate = date;
 
222
            break;
 
223
        case KNemoStats::Week:
 
224
            dayOf = mStorageData.calendar->dayOfWeek( date );
 
225
            if ( dayOf >= weekStartDay )
 
226
                newDate = date.addDays( weekStartDay - dayOf );
 
227
            else
 
228
                newDate = date.addDays( weekStartDay - mStorageData.calendar->daysInWeek( date ) - dayOf );
 
229
            break;
 
230
        case KNemoStats::Month:
 
231
            dayOf = mStorageData.calendar->day( date );
 
232
            newDate = date.addDays( 1 - dayOf );
 
233
            break;
 
234
        case KNemoStats::Year:
 
235
            dayOf = mStorageData.calendar->dayOfYear( date );
 
236
            newDate = date.addDays( 1 - dayOf );
 
237
            break;
 
238
        default:
 
239
            return false;
 
240
    }
 
241
 
 
242
    mModels.value( stype )->createEntry( QDateTime( newDate, QTime() ) );
 
243
    resetWarnings( stype );
 
244
 
 
245
    return true;
 
246
}
 
247
 
 
248
// Return true if at least one daily statistic entry is in a span of days
 
249
bool InterfaceStatistics::daysInSpan( const QDate& date, int days )
 
250
{
 
251
    StatisticsModel *model = mModels.value( KNemoStats::Day );
 
252
    if ( !model->rowCount() )
 
253
        return false;
 
254
 
 
255
    QDate nextRuleStart = date.addDays( days );
 
256
    for ( int i = model->rowCount() - 1; i >= 0; --i )
 
257
    {
 
258
        // No others will be valid after this; stop early
 
259
        if ( model->date( i ) < date )
 
260
            return false;
 
261
        if ( model->date( i ) < nextRuleStart && model->date( i ) >= date )
 
262
            return true;
 
263
    }
 
264
    return false;
 
265
}
 
266
 
 
267
QDate InterfaceStatistics::nextBillPeriodStart( const StatsRule &rules, const QDate &date )
 
268
{
 
269
    QDate nextDate;
 
270
    QDate refDay;
 
271
    int modelType = rules.periodUnits;
 
272
    switch ( modelType )
 
273
    {
 
274
        case KNemoStats::Day:
 
275
            nextDate = date.addDays( rules.periodCount );
 
276
            break;
 
277
        case KNemoStats::Week:
 
278
            nextDate = date;
 
279
            for ( int i = 0; i < rules.periodCount; ++i )
 
280
                nextDate = nextDate.addDays( mStorageData.calendar->daysInWeek( nextDate ) );
 
281
            break;
 
282
        default:// KNemoStats::Month:
 
283
            nextDate = mStorageData.calendar->addMonths( date, rules.periodCount );
 
284
            // Example: one month starting Jan 31 = Jan 31 -> Mar 1
 
285
            // This seems the most common way to handle late start dates
 
286
            if ( mStorageData.calendar->day( nextDate ) < mStorageData.calendar->day( date ) )
 
287
                nextDate = nextDate.addDays( 1 );
 
288
            break;
 
289
    }
 
290
    return nextDate;
 
291
}
 
292
 
 
293
void InterfaceStatistics::genNewBillPeriod( const QDate &date )
 
294
{
 
295
    int ruleIndex = ruleForDate( date );
 
296
    if ( ruleIndex < 0 )
 
297
        return;
 
298
 
 
299
    StatisticsModel * billing = mModels.value( KNemoStats::BillPeriod );
 
300
    QDate nextRuleStart;
 
301
 
 
302
    if ( mStatsRules.count() > ruleIndex+1 )
 
303
        nextRuleStart = mStatsRules.at( ruleIndex+1 ).startDate;
 
304
 
 
305
    // Harder to find whether we should skip generating a new billing entry
 
306
    if ( nextRuleStart.isValid() && billing->rowCount() && billing->date().addDays( billing->days() ) >= nextRuleStart )
 
307
        return;
 
308
 
 
309
    int days;
 
310
 
 
311
    // Given a calendar day and a billing period start date, find a
 
312
    // billing period that the day belongs in.
 
313
    QDate newDate;
 
314
    QDate nextStartDate;
 
315
    if ( !billing->rowCount() ||
 
316
         billing->date() < mStatsRules.at( ruleIndex ).startDate )
 
317
    {
 
318
        nextStartDate = mStatsRules.at( ruleIndex ).startDate;
 
319
    }
 
320
    else
 
321
    {
 
322
        nextStartDate = billing->date();
 
323
    }
 
324
 
 
325
    do
 
326
    {
 
327
        newDate = nextStartDate;
 
328
        nextStartDate = nextBillPeriodStart( mStatsRules.at( ruleIndex ), newDate );
 
329
        days = newDate.daysTo( nextStartDate );
 
330
    } while ( nextStartDate <= date || !daysInSpan( newDate, days ) );
 
331
 
 
332
    // Truncate a billing period if necessary
 
333
    if ( nextRuleStart.isValid() && nextRuleStart < nextStartDate )
 
334
        days = newDate.daysTo( nextRuleStart );
 
335
 
 
336
    if ( billing->rowCount() && newDate == billing->date() )
 
337
        return;
 
338
 
 
339
    billing->createEntry( QDateTime( newDate, QTime() ), billing->rowCount(), days );
 
340
 
 
341
    resetWarnings( KNemoStats::BillPeriod );
 
342
}
 
343
 
 
344
 
 
345
// END STATS ENTRY GENERATORS
 
346
 
 
347
void InterfaceStatistics::configChanged()
 
348
{
 
349
    mSaveTimer->stop();
 
350
    mWarnTimer->stop();
 
351
 
 
352
    QString origCalendarType;
 
353
    if ( mStorageData.calendar )
 
354
       origCalendarType = mStorageData.calendar->calendarType();
 
355
 
 
356
    if ( mInterface->settings().calendar != origCalendarType )
 
357
    {
 
358
        mStorageData.calendar = KCalendarSystem::create( mInterface->settings().calendar );
 
359
 
 
360
        foreach( StatisticsModel * s, mModels )
 
361
        {
 
362
            s->setCalendar( mStorageData.calendar );
 
363
        }
 
364
        if ( !origCalendarType.isEmpty() )
 
365
        {
 
366
            StatisticsModel *hours = mModels.value( KNemoStats::Hour );
 
367
            StatisticsModel *days = mModels.value( KNemoStats::Day );
 
368
            for ( int i = 0; i < days->rowCount(); ++i )
 
369
            {
 
370
                days->updateDateText( i );
 
371
            }
 
372
            for ( int i = 0; i < hours->rowCount(); ++i )
 
373
            {
 
374
                hours->updateDateText( i );
 
375
            }
 
376
        }
 
377
    }
 
378
 
 
379
    checkRebuild( origCalendarType );
119
380
 
120
381
    if ( generalSettings->saveInterval > 0 )
121
382
    {
122
383
        mSaveTimer->setInterval( generalSettings->saveInterval * 1000 );
123
384
        mSaveTimer->start();
124
385
    }
125
 
}
126
 
 
127
 
void InterfaceStatistics::configChanged()
128
 
{
129
 
    mSaveTimer->stop();
130
 
    QString oldType = mCalendar->calendarType();
131
 
    loadConfig();
132
 
    checkRebuild( oldType );
133
 
}
134
 
 
135
 
void InterfaceStatistics::loadStatsGroup( const KCalendarSystem * cal, const QDomElement& parentItem,
136
 
                                          StatisticsModel* statistics )
137
 
{
138
 
    QDomNode n = parentItem.namedItem( typeToElem(statistics->type()) + "s" );
139
 
    if ( !n.isNull() )
140
 
    {
141
 
        QDomNode node = n.firstChild();
142
 
        while ( !node.isNull() )
143
 
        {
144
 
            QDomElement element = node.toElement();
145
 
            if ( !element.isNull() )
146
 
            {
147
 
                // The following attributes are particular to each statistic category
148
 
                QDate date;
149
 
                QTime time;
150
 
 
151
 
                int year = element.attribute( typeToElem(StatisticsModel::Year) ).toInt();
152
 
                int month = element.attribute( typeToElem(StatisticsModel::Month), "1" ).toInt();
153
 
                int day = element.attribute( typeToElem(StatisticsModel::Day), "1" ).toInt();
154
 
                cal->setDate( date, year, month, day );
155
 
 
156
 
                if ( date.isValid() )
157
 
                {
158
 
                    int days = element.attribute( attrib_span ).toInt();
159
 
                    switch ( statistics->type() )
160
 
                    {
161
 
                        case StatisticsModel::Hour:
162
 
                            time = QTime( element.attribute( typeToElem(StatisticsModel::Hour) ).toInt(), 0 );
163
 
                            break;
164
 
                        case StatisticsModel::Month:
165
 
                            // Old format had no span, so daysInMonth using gregorian
166
 
                            if ( days == 0 )
167
 
                                days = date.daysInMonth();
168
 
                            if ( cal->day( date ) != 1 ||
169
 
                                 days != cal->daysInMonth( date ) )
170
 
                                mAllMonths = false;
171
 
                            break;
172
 
                        case StatisticsModel::Year:
173
 
                            // Old format had no span, so daysInYear using gregorian
174
 
                            if ( days == 0 )
175
 
                                days = date.daysInYear();
176
 
                            break;
177
 
                        case StatisticsModel::Day:
178
 
                            days = 1;
179
 
                        default:
180
 
                            ;;
181
 
                    }
182
 
 
183
 
                    statistics->appendStats( QDateTime( date, time ), days,
184
 
                            element.attribute( attrib_rx ).toULongLong(),
185
 
                            element.attribute( attrib_tx ).toULongLong() );
186
 
                }
187
 
            }
188
 
            node = node.nextSibling();
189
 
        }
190
 
    }
191
 
}
192
 
 
193
 
void InterfaceStatistics::saveStatsGroup( QDomDocument& doc, const StatisticsModel* statistics )
194
 
{
195
 
    QString groupName;
196
 
    QString elementName;
197
 
    QDomElement elements = doc.createElement( QString( typeToElem(statistics->type()) ) + "s" );
198
 
    for ( int i = 0; i < statistics->rowCount(); ++i )
199
 
    {
200
 
        QDomElement element = doc.createElement( typeToElem(statistics->type()) );
201
 
        QDate date = statistics->date( i );
202
 
        element.setAttribute( typeToElem(StatisticsModel::Day), mCalendar->day( date ) );
203
 
        element.setAttribute( typeToElem(StatisticsModel::Month), mCalendar->month( date ) );
204
 
        element.setAttribute( typeToElem(StatisticsModel::Year), mCalendar->year( date ) );
205
 
        if ( statistics->type() == StatisticsModel::Hour )
206
 
            element.setAttribute( typeToElem(StatisticsModel::Hour), statistics->dateTime( i ).time().hour() );
207
 
        else if ( statistics->type() > StatisticsModel::Day )
208
 
            element.setAttribute( attrib_span, statistics->days( i ) );
209
 
        element.setAttribute( attrib_rx, statistics->rxBytes( i ) );
210
 
        element.setAttribute( attrib_tx, statistics->txBytes( i ) );
211
 
        elements.appendChild( element );
212
 
    }
213
 
    QDomElement statElement = doc.elementsByTagName( doc_name ).at( 0 ).toElement();
214
 
    statElement.appendChild( elements );
215
 
}
216
 
 
217
 
void InterfaceStatistics::loadStatistics()
218
 
{
219
 
    QDomDocument doc( doc_name );
220
 
    KUrl dir( generalSettings->statisticsDir );
221
 
    if ( !dir.isLocalFile() )
222
 
        return;
223
 
    QFile file( dir.path() + statistics_prefix + mInterface->getName() );
224
 
 
225
 
    if ( !file.open( QIODevice::ReadOnly ) )
226
 
        return;
227
 
    if ( !doc.setContent( &file ) )
228
 
    {
229
 
        file.close();
230
 
        return;
231
 
    }
232
 
    file.close();
233
 
 
234
 
    QDomElement root = doc.documentElement();
235
 
 
236
 
    uint updated = root.attribute( attrib_updated ).toUInt();
237
 
 
238
 
    // If unknown or empty calendar it will default to gregorian
239
 
    KCalendarSystem *inCal = KCalendarSystem::create( root.attribute( attrib_calendar ) );
240
 
    foreach( StatisticsModel * s, mModels )
241
 
        loadStatsGroup( inCal, root, s );
242
 
 
243
 
    checkRebuild( inCal->calendarType() );
244
 
 
245
 
    syncWithExternal( updated );
 
386
 
 
387
    foreach ( StatisticsModel * s, mModels )
 
388
    {
 
389
        resetWarnings( s->periodType() );
 
390
    }
 
391
 
 
392
    checkValidEntry();
 
393
 
 
394
    mWarnTimer->setInterval( 2000 );
 
395
    mWarnTimer->start();
 
396
}
 
397
 
 
398
int InterfaceStatistics::ruleForDate( const QDate &date )
 
399
{
 
400
    for( int i = mStatsRules.count() - 1; i >= 0; --i )
 
401
    {
 
402
        if ( date >= mStatsRules[i].startDate )
 
403
            return i;
 
404
    }
 
405
    return -1;
246
406
}
247
407
 
248
408
void InterfaceStatistics::syncWithExternal( uint updated )
249
409
{
250
 
    ExternalStats *v = StatsFactory::stats( mInterface );
 
410
    ExternalStats *v = StatsFactory::stats( mInterface, mStorageData.calendar );
251
411
    if ( !v )
252
412
        return;
253
413
 
254
414
    v->importIfaceStats();
255
415
    const StatisticsModel *syncDays = v->days();
256
416
    const StatisticsModel *syncHours = v->hours();
257
 
    StatisticsModel *days = mModels.value( StatisticsModel::Day );
258
 
    StatisticsModel *hours = mModels.value( StatisticsModel::Hour );
 
417
    StatisticsModel *days = mModels.value( KNemoStats::Day );
 
418
    StatisticsModel *hours = mModels.value( KNemoStats::Hour );
259
419
    QDateTime curDateTime = QDateTime( QDate::currentDate(), QTime( QDateTime::currentDateTime().time().hour(), 0 ) );
260
420
 
 
421
    for ( int i = 0; i < syncHours->rowCount(); ++i )
 
422
    {
 
423
        QDateTime syncDateTime = syncHours->dateTime( i );
 
424
 
 
425
        if ( hours->rowCount() && hours->dateTime() > syncDateTime )
 
426
            continue;
 
427
        if ( !hours->rowCount() || hours->dateTime() < syncDateTime )
 
428
            genNewHour( syncDateTime );
 
429
 
 
430
        foreach ( KNemoStats::TrafficType t, hours->trafficTypes() )
 
431
        {
 
432
            hours->addRxBytes( syncHours->rxBytes( i ), t );
 
433
            hours->addTxBytes( syncHours->txBytes( i ), t );
 
434
        }
 
435
    }
 
436
 
261
437
    for ( int i = 0; i < syncDays->rowCount(); ++i )
262
438
    {
263
439
        QDate syncDate = syncDays->date( i );
266
442
            continue;
267
443
        if ( !days->rowCount() || days->date() < syncDate )
268
444
        {
269
 
            genNewDay( syncDate );
270
 
            genNewWeek( syncDate );
271
 
            genNewMonth( syncDate );
272
 
            genNewYear( syncDate );
 
445
            genNewCalendarType( syncDate, KNemoStats::Day );
 
446
            genNewCalendarType( syncDate, KNemoStats::Week );
 
447
            genNewCalendarType( syncDate, KNemoStats::Month );
 
448
            genNewCalendarType( syncDate, KNemoStats::Year );
 
449
            genNewBillPeriod( syncDate );
273
450
        }
274
451
 
275
452
        foreach( StatisticsModel * s, mModels )
276
453
        {
277
 
            if ( s->type() == StatisticsModel::Hour )
 
454
            if ( s->periodType() == KNemoStats::Hour || s->periodType() == KNemoStats::HourArchive )
278
455
               continue;
279
456
 
280
457
            s->addRxBytes( v->addBytes( s->rxBytes(), syncDays->rxBytes( i ) ) );
281
458
            s->addTxBytes( v->addBytes( s->txBytes(), syncDays->txBytes( i ) ) );
 
459
            for ( int j = hours->rowCount() - 1; j >= 0; --j )
 
460
            {
 
461
                if ( hours->date( j ) == syncDate )
 
462
                {
 
463
                    foreach( KNemoStats::TrafficType t, hours->trafficTypes( j ) )
 
464
                    {
 
465
                        if ( t == KNemoStats::AllTraffic )
 
466
                            continue;
 
467
                        s->addRxBytes( hours->rxBytes( j, t ), t );
 
468
                        s->addTxBytes( hours->txBytes( j, t ), t );
 
469
                    }
 
470
                }
 
471
                else if ( hours->date( j ) < syncDate )
 
472
                    break;
 
473
            }
282
474
        }
283
475
    }
284
 
    for ( int i = 0; i < syncHours->rowCount(); ++i )
285
 
    {
286
 
        QDateTime syncDateTime = syncHours->dateTime( i );
287
 
 
288
 
        if ( hours->rowCount() && hours->dateTime() > syncDateTime )
289
 
            continue;
290
 
        if ( !hours->rowCount() || hours->dateTime() < syncDateTime )
291
 
            genNewHour( syncDateTime );
292
 
 
293
 
        hours->addRxBytes( v->addBytes( hours->rxBytes(), syncHours->rxBytes( i ) ) );
294
 
        hours->addTxBytes( v->addBytes( hours->txBytes(), syncHours->txBytes( i ) ) );
295
 
    }
 
476
 
296
477
    StatsPair lag = v->addLagged( updated, days );
297
478
    if ( lag.rxBytes > 0 || lag.txBytes > 0 )
298
479
    {
299
480
        if ( lag.rxBytes || lag.txBytes )
300
481
        {
301
482
            genNewHour( curDateTime );
302
 
            genNewDay( curDateTime.date() );
303
 
            genNewWeek( curDateTime.date() );
304
 
            genNewMonth( curDateTime.date() );
305
 
            genNewYear( curDateTime.date() );
 
483
            genNewCalendarType( curDateTime.date(), KNemoStats::Day );
 
484
            genNewCalendarType( curDateTime.date(), KNemoStats::Week );
 
485
            genNewCalendarType( curDateTime.date(), KNemoStats::Month );
 
486
            genNewCalendarType( curDateTime.date(), KNemoStats::Year );
 
487
            genNewBillPeriod( curDateTime.date() );
306
488
 
307
489
            foreach ( StatisticsModel * s, mModels )
308
490
            {
309
 
                s->addRxBytes( lag.rxBytes );
310
 
                s->addTxBytes( lag.txBytes );
 
491
                if ( s->periodType() == KNemoStats::HourArchive )
 
492
                    continue;
 
493
                foreach ( KNemoStats::TrafficType t, hours->trafficTypes() )
 
494
                {
 
495
                    s->addRxBytes( lag.rxBytes, t );
 
496
                    s->addTxBytes( lag.txBytes, t );
 
497
                }
311
498
            }
312
499
        }
313
500
    }
314
501
    delete v;
315
502
}
316
503
 
317
 
void InterfaceStatistics::saveStatistics()
318
 
{
319
 
    QDomDocument doc( doc_name );
320
 
    QDomElement docElement = doc.createElement( doc_name );
321
 
    docElement.setAttribute( attrib_calendar, mCalendar->calendarType() );
322
 
    docElement.setAttribute( attrib_version, "1.3" );
323
 
    docElement.setAttribute( attrib_updated, QDateTime::currentDateTime().toTime_t() );
324
 
    doc.appendChild( docElement );
325
 
 
326
 
    foreach( StatisticsModel * s, mModels )
327
 
        saveStatsGroup( doc, s );
328
 
 
329
 
    KUrl dir( generalSettings->statisticsDir );
330
 
    if ( !dir.isLocalFile() )
 
504
bool InterfaceStatistics::isOffpeak( const StatsRule &rules, const QDateTime &curDT )
 
505
{
 
506
    if ( !rules.logOffpeak )
 
507
        return false;
 
508
 
 
509
    bool isOffpeak = false;
 
510
    QTime curHour = QTime( curDT.time().hour(), 0 );
 
511
 
 
512
    // This block just tests weekly hours
 
513
    if ( rules.offpeakStartTime < rules.offpeakEndTime &&
 
514
         curHour >= rules.offpeakStartTime && curHour < rules.offpeakEndTime )
 
515
    {
 
516
        isOffpeak = true;
 
517
    }
 
518
    else if ( rules.offpeakStartTime > rules.offpeakEndTime &&
 
519
         ( curHour >= rules.offpeakStartTime || curHour < rules.offpeakEndTime ) )
 
520
    {
 
521
        isOffpeak = true;
 
522
    }
 
523
 
 
524
    if ( rules.weekendIsOffpeak )
 
525
    {
 
526
        int dow = mStorageData.calendar->dayOfWeek( curDT.date() );
 
527
        if ( rules.weekendDayStart <= rules.weekendDayEnd && rules.weekendDayStart <= dow )
 
528
        {
 
529
            QDateTime dayBegin = curDT.addDays( dow - rules.weekendDayStart );
 
530
            dayBegin = QDateTime( dayBegin.date(), rules.weekendTimeStart );
 
531
            QDateTime end = curDT.addDays( rules.weekendDayEnd - dow );
 
532
            end = QDateTime( end.date(), rules.weekendTimeEnd );
 
533
 
 
534
            if ( dayBegin <= curDT && curDT < end )
 
535
                isOffpeak = true;
 
536
        }
 
537
        else if ( rules.weekendDayStart > rules.weekendDayEnd &&
 
538
                ( dow >= rules.weekendDayStart || dow <= rules.weekendDayEnd ) )
 
539
        {
 
540
            QDateTime dayBegin = curDT.addDays( rules.weekendDayStart - dow );
 
541
            dayBegin = QDateTime( dayBegin.date(), rules.weekendTimeStart );
 
542
            QDateTime end = curDT.addDays( mStorageData.calendar->daysInWeek( curDT.date() ) - dow + rules.weekendDayEnd );
 
543
            end = QDateTime( end.date(), rules.weekendTimeEnd );
 
544
 
 
545
            if ( dayBegin <= curDT && curDT < end )
 
546
                isOffpeak = true;
 
547
        }
 
548
    }
 
549
 
 
550
    return isOffpeak;
 
551
}
 
552
 
 
553
 
 
554
/**************************************
 
555
 * Rebuilding Statistics              *
 
556
 **************************************/
 
557
 
 
558
int InterfaceStatistics::rebuildHours( StatisticsModel *s, const StatsRule &rules, const QDate &start, const QDate &nextRuleStart )
 
559
{
 
560
    if ( !s->rowCount() )
 
561
        return 0;
 
562
 
 
563
    int i = s->rowCount();
 
564
    while ( i > 0 && s->date( i - 1 ) >= start )
 
565
    {
 
566
        i--;
 
567
        if ( nextRuleStart.isValid() && s->date( i ) >= nextRuleStart )
 
568
            continue;
 
569
 
 
570
        s->resetTrafficTypes( i );
 
571
        if ( isOffpeak( rules, s->dateTime( i ) ) )
 
572
        {
 
573
            s->setTraffic( i, s->rxBytes( i ), s->txBytes( i ), KNemoStats::OffpeakTraffic );
 
574
            s->addTrafficType( KNemoStats::OffpeakTraffic, i );
 
575
        }
 
576
    }
 
577
    if ( mStorageData.saveFromId.value( s->periodType() ) > s->id( i ) )
 
578
    {
 
579
        mStorageData.saveFromId.insert( s->periodType(), s->id( i ) );
 
580
    }
 
581
 
 
582
    return i;
 
583
}
 
584
 
 
585
int InterfaceStatistics::rebuildDay( int dayIndex, int hourIndex, StatisticsModel *hours )
 
586
{
 
587
    QMap<KNemoStats::TrafficType, QPair<quint64, quint64> > dayTraffic;
 
588
    StatisticsModel *days = mModels.value( KNemoStats::Day );
 
589
    while ( hourIndex >= 0 && hours->date( hourIndex ) > days->date( dayIndex ).addDays( 1 ) )
 
590
    {
 
591
        --hourIndex;
 
592
    }
 
593
    while ( hourIndex >= 0 && hours->date( hourIndex ) == days->date( dayIndex ) )
 
594
    {
 
595
        foreach ( KNemoStats::TrafficType t, hours->trafficTypes( hourIndex ) )
 
596
        {
 
597
            if ( t == KNemoStats::AllTraffic )
 
598
                continue;
 
599
            quint64 rx = hours->rxBytes( hourIndex, t ) + dayTraffic.value( t ).first;
 
600
            quint64 tx = hours->txBytes( hourIndex, t ) + dayTraffic.value( t ).second;
 
601
            dayTraffic.insert( t, QPair<quint64, quint64>( rx, tx ) );
 
602
        }
 
603
        --hourIndex;
 
604
    }
 
605
    foreach (KNemoStats::TrafficType t, dayTraffic.keys() )
 
606
    {
 
607
        days->setTraffic( dayIndex, dayTraffic.value( t ).first, dayTraffic.value( t ).second, t );
 
608
        days->addTrafficType( t, dayIndex );
 
609
    }
 
610
    return hourIndex;
 
611
}
 
612
 
 
613
// A rebuild of hours and days never changes the number of entries
 
614
// We just change what bytes count as off-peak
 
615
void InterfaceStatistics::rebuildBaseUnits( const StatsRule &rules, const QDate &start, const QDate &nextRuleStart )
 
616
{
 
617
    int hIndex = 0;
 
618
    int haIndex = 0;
 
619
 
 
620
    StatisticsModel *hours = mModels.value( KNemoStats::Hour );
 
621
    StatisticsModel *hourArchives = mModels.value( KNemoStats::HourArchive );
 
622
    StatisticsModel *days = mModels.value( KNemoStats::Day );
 
623
    sql->loadHourArchives( hourArchives, start, nextRuleStart );
 
624
    if ( hourArchives->rowCount() )
 
625
        mStorageData.saveFromId.insert( hourArchives->periodType(), hourArchives->id( 0 ) );
 
626
 
 
627
    rebuildHours( hourArchives, rules, start, nextRuleStart );
 
628
    rebuildHours( hours, rules, start, nextRuleStart );
 
629
 
 
630
    if ( hours->rowCount() )
 
631
        hIndex = hours->rowCount() - 1;
 
632
    if ( hourArchives->rowCount() )
 
633
        haIndex = hourArchives->rowCount() - 1;
 
634
 
 
635
    if ( !days->rowCount() )
331
636
        return;
332
637
 
333
 
    QFile file( dir.path() + statistics_prefix + mInterface->getName() );
334
 
    if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
335
 
    {
336
 
        file.write( doc.toByteArray() );
337
 
        fsync( file.handle() );
338
 
        file.close();
 
638
    int dayIndex = days->rowCount();
 
639
    while ( dayIndex > 0 && days->date( dayIndex - 1 ) >= start )
 
640
    {
 
641
        dayIndex--;
 
642
        if ( nextRuleStart.isValid() && days->date( dayIndex ) >= nextRuleStart )
 
643
            continue;
 
644
 
 
645
        days->resetTrafficTypes( dayIndex );
 
646
        if ( rules.logOffpeak )
 
647
        {
 
648
            haIndex = rebuildDay( dayIndex, haIndex, hourArchives );
 
649
            hIndex = rebuildDay( dayIndex, hIndex, hours );
 
650
        }
 
651
    }
 
652
    if ( mStorageData.saveFromId.value( days->periodType() ) > days->id( dayIndex ) )
 
653
    {
 
654
        mStorageData.saveFromId.insert( days->periodType(), days->id( dayIndex ) );
339
655
    }
340
656
}
341
657
 
344
660
 * and a requested rebuild date, how far back to we actually need to go
345
661
 * to accuratly rebuild statistics from the daily stats.
346
662
 */
347
 
QDate InterfaceStatistics::setRebuildDate( StatisticsModel* statistics,
348
 
                                           const QDate &recalcDate )
 
663
QDate InterfaceStatistics::prepareRebuild( StatisticsModel* statistics, const QDate &startDate )
349
664
{
350
 
    QDate returnDate = recalcDate;
351
 
    if ( statistics->type() <= StatisticsModel::Day )
352
 
        return returnDate;
 
665
    QDate newStartDate = startDate;
 
666
    if ( statistics->periodType() <= KNemoStats::Day ||
 
667
         statistics->periodType() > KNemoStats::Year )
 
668
        return newStartDate;
353
669
 
354
 
    // Keep removing entries and rolling back returnDate while
355
 
    // entry's start date + days > returnDate
356
 
    for ( int i = statistics->rowCount() - 1; i >= 0; --i )
 
670
    for ( int i = 0; i < statistics->rowCount(); ++i )
357
671
    {
358
672
        int days = statistics->days( i );
359
 
        QDate date = statistics->date( i ).addDays( days );
360
 
        if ( date > mModels.value( StatisticsModel::Day )->date( 0 ) &&
361
 
             ( date > returnDate || days < 1 )
362
 
           )
 
673
        QDate nextPeriodStart = statistics->date( i ).addDays( days );
 
674
 
 
675
        if ( statistics->periodType() == KNemoStats::BillPeriod )
363
676
        {
364
 
            if ( returnDate > statistics->date( i ) )
365
 
                returnDate = statistics->date( i );
366
 
            statistics->removeRow( i );
 
677
            // Have to check if a billing period's truncation changed
 
678
            int ruleIndex = ruleForDate( statistics->date( i ) );
 
679
            if ( ruleIndex < 0 )
 
680
                break;
 
681
            QDate nextFullPeriodStart = nextBillPeriodStart( mStatsRules.at( ruleIndex ), statistics->date( i ) );
 
682
            if ( nextFullPeriodStart > nextPeriodStart )
 
683
            {
 
684
                if ( mStatsRules.count() == ruleIndex+1 ||
 
685
                     mStatsRules.at( ruleIndex + 1 ).startDate != nextPeriodStart )
 
686
                {
 
687
                    // Truncation changed
 
688
                    // This will make sure the entry gets rebuilt
 
689
                    nextPeriodStart = nextFullPeriodStart;
 
690
                }
 
691
            }
367
692
        }
368
 
        else
 
693
 
 
694
        if ( nextPeriodStart > startDate )
 
695
        {
 
696
            if ( statistics->date( i ) < startDate )
 
697
            {
 
698
                newStartDate = statistics->date( i );
 
699
            }
 
700
            if ( statistics->rowCount() && mStorageData.saveFromId.value( statistics->periodType() ) > statistics->id( i ) )
 
701
            {
 
702
                mStorageData.saveFromId.insert( statistics->periodType(), statistics->id( i ) );
 
703
            }
 
704
            statistics->removeRows( i, statistics->rowCount() - i );
369
705
            break;
370
 
    }
371
 
 
372
 
    // now take care of instances when we're going earlier than the first recorded stats.
373
 
    if ( statistics->type() == StatisticsModel::Week )
374
 
    {
375
 
        returnDate = returnDate.addDays( 1 - mCalendar->dayOfWeek( returnDate ) );
376
 
        while ( returnDate > recalcDate )
377
 
            returnDate = returnDate.addDays( -mCalendar->daysInWeek( returnDate ) );
378
 
    }
379
 
    else if ( statistics->type() == StatisticsModel::Year )
380
 
    {
381
 
        returnDate = returnDate.addDays( 1 - mCalendar->dayOfYear( returnDate ) );
382
 
        while ( returnDate > recalcDate )
383
 
            returnDate = returnDate.addDays( mCalendar->daysInYear( returnDate ) );
384
 
    }
385
 
 
386
 
    return returnDate;
387
 
}
388
 
 
389
 
void InterfaceStatistics::amendStats( int i, StatisticsModel* model )
390
 
{
391
 
    StatisticsModel *days = mModels.value( StatisticsModel::Day );
392
 
    model->addRxBytes( days->rxBytes( i ) );
393
 
    model->addTxBytes( days->txBytes( i ) );
394
 
}
395
 
 
396
 
void InterfaceStatistics::doRebuild( const QDate &date, int groups )
397
 
{
398
 
    QDate recalcDate( date );
399
 
    bool partial = false;
 
706
        }
 
707
    }
 
708
 
 
709
    return newStartDate;
 
710
}
 
711
 
 
712
void InterfaceStatistics::amendStats( int i, const StatisticsModel *source, StatisticsModel* dest )
 
713
{
 
714
    foreach ( KNemoStats::TrafficType t, source->trafficTypes( i ) )
 
715
    {
 
716
        dest->addRxBytes( source->rxBytes( i, t ), t );
 
717
        dest->addTxBytes( source->txBytes( i, t ), t );
 
718
        dest->addTrafficType( t );
 
719
    }
 
720
}
 
721
 
 
722
void InterfaceStatistics::rebuildCalendarPeriods( const QDate &requestedStart, bool weekOnly )
 
723
{
400
724
    QDate weekStart;
401
725
    QDate monthStart;
402
 
    QDate yearStart;
403
726
    QDate walkbackDate;
404
727
 
405
728
    QList<QDate> s;
406
 
    s.append( recalcDate );
407
729
 
408
 
    if ( groups & StatisticsModel::Week )
409
 
    {
410
 
        weekStart = setRebuildDate( mModels.value( StatisticsModel::Week), recalcDate );
411
 
        s.append( weekStart );
412
 
    }
413
 
    if ( groups & StatisticsModel::Month )
414
 
    {
415
 
        monthStart = setRebuildDate( mModels.value( StatisticsModel::Month), recalcDate );
416
 
        // force an old date
417
 
        mBillingStart = monthStart;
418
 
        if ( recalcDate > monthStart )
419
 
            partial = true;
 
730
    weekStart = prepareRebuild( mModels.value( KNemoStats::Week), requestedStart );
 
731
    s.append( weekStart );
 
732
    if ( !weekOnly )
 
733
    {
 
734
        monthStart = prepareRebuild( mModels.value( KNemoStats::Month), requestedStart );
420
735
        s.append( monthStart );
421
736
    }
422
 
    if ( groups & StatisticsModel::Year )
423
 
    {
424
 
        yearStart = setRebuildDate( mModels.value( StatisticsModel::Year ), recalcDate );
425
 
        s.append( yearStart );
426
 
    }
427
737
 
428
738
    // Now find how far back we'll need to go
429
739
    qSort( s );
430
740
    walkbackDate = s.first();
431
741
 
432
 
    StatisticsModel *days = mModels.value( StatisticsModel::Day );
 
742
    StatisticsModel *days = mModels.value( KNemoStats::Day );
433
743
    for ( int i = 0; i < days->rowCount(); ++i )
434
744
    {
435
745
        QDate day = days->date( i );
436
746
        if ( day < walkbackDate )
437
747
            continue;
438
748
 
439
 
        if ( groups & StatisticsModel::Week && day >= weekStart )
440
 
        {
441
 
            genNewWeek( day );
442
 
            amendStats( i, mModels.value( StatisticsModel::Week ) );
443
 
        }
444
 
 
445
 
        if ( groups & StatisticsModel::Month && day >= monthStart )
446
 
        {
447
 
            // Not very pretty
448
 
            StatisticsModel *month = mModels.value( StatisticsModel::Month );
449
 
            if ( !partial )
450
 
            {
451
 
                genNewMonth( day );
452
 
                amendStats( i, month );
453
 
            }
454
 
            else
455
 
            {
456
 
                genNewMonth( monthStart, recalcDate );
457
 
                amendStats( i, month );
458
 
                // Partial month created; next period will begin on recalcDate
459
 
                mBillingStart = recalcDate;
460
 
                partial = false;
461
 
            }
462
 
        }
463
 
        if ( groups & StatisticsModel::Year && day >= yearStart )
464
 
        {
465
 
            genNewYear( day );
466
 
            amendStats( i, mModels.value( StatisticsModel::Year ) );
467
 
        }
468
 
    }
469
 
}
470
 
 
471
 
void InterfaceStatistics::checkRebuild( QString oldType )
472
 
{
473
 
    if ( oldType != mCalendar->calendarType() )
474
 
    {
475
 
        KUrl dir( generalSettings->statisticsDir );
476
 
        if ( dir.isLocalFile() )
477
 
        {
478
 
            QFile file( dir.path() + statistics_prefix + mInterface->getName() );
479
 
            file.copy( dir.path() + statistics_prefix + mInterface->getName() +
480
 
                   QString( "_%1.bak" ).arg( QDateTime::currentDateTime().toString( "yyyy-MM-dd-hhmmss" ) ) );
481
 
        }
482
 
        int modThese = StatisticsModel::Week | StatisticsModel::Year;
483
 
        QDate date = mModels.value( StatisticsModel::Day )->date( 0 );
484
 
        doRebuild( date, modThese );
485
 
    }
486
 
 
487
 
    StatisticsModel *month = mModels.value( StatisticsModel::Month );
488
 
    if ( mInterface->getSettings().customBilling == false )
489
 
    {
490
 
        if ( oldType != mCalendar->calendarType() || mAllMonths == false )
491
 
        {
492
 
            mBillingStart = month->date( 0 ).addDays( 1 - mCalendar->day( month->date( 0 ) ) );
493
 
        }
494
 
    }
495
 
 
496
 
    QDate nextStart = nextMonthDate( mBillingStart );
497
 
    if ( mBillingStart.daysTo( nextStart ) != month->days()
498
 
         || mBillingStart != month->date() )
499
 
        doRebuild( mBillingStart, StatisticsModel::Month );
500
 
 
501
 
    mAllMonths = true;
502
 
    for ( int i = 0; i < month->rowCount(); ++i )
503
 
    {
504
 
        QDate date = month->date( i );
505
 
        if ( mCalendar->day( date ) != 1 ||
506
 
            month->days( i ) != mCalendar->daysInMonth( date ) )
507
 
        {
508
 
            mAllMonths = false;
509
 
        }
510
 
    }
511
 
 
 
749
        if ( day >= weekStart )
 
750
        {
 
751
            genNewCalendarType( day, KNemoStats::Week );
 
752
            amendStats( i, mModels.value( KNemoStats::Day ), mModels.value( KNemoStats::Week ) );
 
753
        }
 
754
 
 
755
        if ( !weekOnly && day >= monthStart )
 
756
        {
 
757
            genNewCalendarType( day, KNemoStats::Month );
 
758
            amendStats( i, mModels.value( KNemoStats::Day ), mModels.value( KNemoStats::Month ) );
 
759
        }
 
760
    }
 
761
 
 
762
    if ( weekOnly )
 
763
        return;
 
764
 
 
765
    // Build years from months...save time
 
766
    QDate yearStart = prepareRebuild( mModels.value( KNemoStats::Year ), requestedStart );
 
767
    StatisticsModel *months = mModels.value( KNemoStats::Month );
 
768
    for ( int i = 0; i < months->rowCount(); ++i )
 
769
    {
 
770
        QDate day = months->date( i );
 
771
        if ( day < yearStart )
 
772
            continue;
 
773
        genNewCalendarType( day, KNemoStats::Year );
 
774
        amendStats( i, mModels.value( KNemoStats::Month ), mModels.value( KNemoStats::Year ) );
 
775
    }
 
776
}
 
777
 
 
778
void InterfaceStatistics::rebuildBillPeriods( const QDate &requestedStart )
 
779
{
 
780
    QDate walkbackDate;
 
781
    StatisticsModel *days = mModels.value( KNemoStats::Day );
 
782
    StatisticsModel *billPeriods = mModels.value( KNemoStats::BillPeriod );
 
783
 
 
784
    if ( billPeriods->rowCount() )
 
785
        walkbackDate = prepareRebuild( mModels.value( KNemoStats::BillPeriod), requestedStart );
 
786
    else
 
787
        walkbackDate = days->date( 0 );
 
788
 
 
789
    for ( int i = 0; i < days->rowCount(); ++i )
 
790
    {
 
791
        QDate day = days->date( i );
 
792
 
 
793
        if ( day >= walkbackDate )
 
794
        {
 
795
            genNewBillPeriod( day );
 
796
            amendStats( i, mModels.value( KNemoStats::Day ), mModels.value( KNemoStats::BillPeriod ) );
 
797
        }
 
798
    }
 
799
}
 
800
 
 
801
void InterfaceStatistics::prependStatsRule( QList<StatsRule> &rules )
 
802
{
 
803
    qSort( rules.begin(), rules.end(), statsLessThan );
 
804
    StatisticsModel * days = mModels.value( KNemoStats::Day );
 
805
    if ( rules.count() == 0 ||
 
806
         ( days->rowCount() > 0 && rules[0].startDate > days->date( 0 ) )
 
807
       )
 
808
    {
 
809
        QDate date;
 
810
        if ( days->rowCount() )
 
811
            date = days->date( 0 );
 
812
        else
 
813
            date = QDate::currentDate();
 
814
        StatsRule s;
 
815
        s.startDate = date.addDays( 1 - mStorageData.calendar->day( date ) );
 
816
        rules.prepend( s );
 
817
    }
 
818
}
 
819
 
 
820
void InterfaceStatistics::checkRebuild( const QString &oldCalendar, bool force )
 
821
{
 
822
    QList<StatsRule> newRules = mInterface->settings().statsRules;
 
823
    bool forceWeek = false;
 
824
 
 
825
    if ( oldCalendar != mInterface->settings().calendar )
 
826
    {
 
827
        StatisticsModel *hours = mModels.value( KNemoStats::Hour );
 
828
        StatisticsModel *days = mModels.value( KNemoStats::Day );
 
829
        for ( int i = 0; i < days->rowCount(); ++i )
 
830
        {
 
831
            days->updateDateText( i );
 
832
        }
 
833
        for ( int i = 0; i < hours->rowCount(); ++i )
 
834
        {
 
835
            hours->updateDateText( i );
 
836
        }
 
837
        force = true;
 
838
    }
 
839
    if ( mModels.value( KNemoStats::Week )->rowCount() )
 
840
    {
 
841
        QDate testDate = mModels.value( KNemoStats::Week )->date( 0 );
 
842
        if ( mStorageData.calendar->dayOfWeek( testDate ) != mStorageData.calendar->weekStartDay() )
 
843
            forceWeek = true;
 
844
    }
 
845
 
 
846
    bool doBilling = newRules.count();
 
847
    int oldRuleCount = mStatsRules.count();
 
848
    QDate bpBeginDate;
 
849
    if ( !doBilling )
 
850
    {
 
851
        mModels.value( KNemoStats::BillPeriod )->clearRows();
 
852
        mStorageData.saveFromId.insert( KNemoStats::BillPeriod, 0 );
 
853
    }
 
854
 
 
855
    // This is just a dummy for calculation
 
856
    prependStatsRule( newRules );
 
857
    prependStatsRule( mStatsRules );
 
858
 
 
859
    if ( !oldRuleCount && mStatsRules[0] == newRules[0] && newRules.count() > mStatsRules.count() )
 
860
        bpBeginDate = mModels.value( KNemoStats::Day )->date( 0 );
 
861
 
 
862
    int j = 0;
 
863
    QDate recalcPos;
 
864
    for ( int i = 0; i < newRules.count(); ++i )
 
865
    {
 
866
 
 
867
        bool rulesMatch = ( newRules[i] == mStatsRules[j] );
 
868
 
 
869
        QDate nextRuleStart;
 
870
        if ( !rulesMatch )
 
871
        {
 
872
            if ( newRules.count() > i + 1 )
 
873
                nextRuleStart = newRules[i+1].startDate;
 
874
            if ( !recalcPos.isValid() )
 
875
                recalcPos = newRules[i].startDate;
 
876
            rebuildBaseUnits( newRules[i], newRules[i].startDate, nextRuleStart );
 
877
        }
 
878
        else
 
879
        {
 
880
            // rules match, now scan forward to see if we need to extend new rule
 
881
            if ( newRules.count() > i + 1 )
 
882
            {
 
883
                int first = -1;
 
884
                int k;
 
885
                // Here we want to skip over any intermediary old rules that will
 
886
                // get taken care of when we recalculate this section.
 
887
                for ( k = 0; k < mStatsRules.count(); ++k )
 
888
                {
 
889
                    if ( mStatsRules[k].startDate > newRules[i].startDate &&
 
890
                         mStatsRules[k].startDate < newRules[i+1].startDate )
 
891
                    {
 
892
                        if ( first < 0 )
 
893
                            first = k;
 
894
                        j = k;
 
895
                        if ( !recalcPos.isValid() )
 
896
                            recalcPos = mStatsRules[j].startDate;
 
897
                    }
 
898
                }
 
899
                if ( first >= 0 )
 
900
                {
 
901
                    rebuildBaseUnits( newRules[i], mStatsRules[first].startDate, newRules[i+1].startDate );
 
902
                }
 
903
            }
 
904
            // We're out of new rules but there's more old ones
 
905
            // so rebuild from next old rule's date using final new rule.
 
906
            else if ( mStatsRules.count() > j + 1 )
 
907
            {
 
908
 
 
909
                if ( !recalcPos.isValid() )
 
910
                    recalcPos = mStatsRules[j+1].startDate;
 
911
                rebuildBaseUnits( newRules[i], recalcPos, nextRuleStart );
 
912
            }
 
913
            if ( mStatsRules.count() > j + 1 )
 
914
                ++j;
 
915
        }
 
916
    }
 
917
 
 
918
    /*
 
919
    now do the rest
 
920
    */
 
921
    mStatsRules = newRules;
 
922
    if ( force )
 
923
        recalcPos = mModels.value( KNemoStats::Day )->date( 0 );
 
924
 
 
925
    if ( recalcPos.isValid() )
 
926
    {
 
927
        rebuildCalendarPeriods( recalcPos );
 
928
 
 
929
        if ( doBilling )
 
930
        {
 
931
            rebuildBillPeriods( recalcPos );
 
932
        }
 
933
    }
 
934
    else if ( forceWeek )
 
935
    {
 
936
        rebuildCalendarPeriods( mModels.value( KNemoStats::Day )->date( 0 ), true );
 
937
    }
 
938
 
 
939
    mStatsRules = mInterface->settings().statsRules;
 
940
    if ( mStatsRules.count() )
 
941
        prependStatsRule( mStatsRules );
 
942
 
 
943
    if ( recalcPos.isValid() )
 
944
    {
 
945
        saveStatistics( true );
 
946
    }
 
947
 
 
948
    mTrafficChanged = true;
512
949
    emit currentEntryChanged();
513
950
}
514
951
 
515
 
/**
516
 
 * Find the next billing period's date.
517
 
 * This is complicated by a few things:
518
 
 *   1. it calculates the date according to whatever calendar type the
519
 
 *      the statistics are using
520
 
 *   2. the period can span one or more localized months
521
 
 *   3. termination dates can be awkward (e.g. if a period starts on
522
 
 *      Dec 30 and spans 2 months, which day should it end on?)
523
 
 **/
524
 
QDate InterfaceStatistics::nextMonthDate( const QDate &date )
525
 
{
526
 
    QDate nextDate( date );
527
 
    int length = mInterface->getSettings().billingMonths;
528
 
    for ( int i = 0; i < length; i++ )
529
 
    {
530
 
        QDate refDay;
531
 
        mCalendar->setDate( refDay, mCalendar->year( nextDate ), mCalendar->month( nextDate ), 1 );
532
 
        refDay = refDay.addDays( mCalendar->daysInMonth( refDay ) );
533
 
 
534
 
        nextDate = nextDate.addDays( mCalendar->daysInMonth( nextDate ) );
535
 
 
536
 
        // Ensure we don't get weird spans like Jan 31 -> Mar 2
537
 
        // Instead, days will drift to a value that all months can handle.
538
 
        // Test for problematic dates in config module!
539
 
        if ( mCalendar->day( mBillingStart ) > 1 )
540
 
        {
541
 
            while ( mCalendar->month( nextDate ) != mCalendar->month( refDay ) )
542
 
                nextDate = nextDate.addDays( -1 );
543
 
        }
544
 
    }
545
 
    return nextDate;
546
 
}
547
 
 
548
 
/**
549
 
 * Return true if at least one daily statistic entry is in a span of days
550
 
 **/
551
 
bool InterfaceStatistics::daysInSpan( const QDate& date, int days )
552
 
{
553
 
    StatisticsModel *model = mModels.value( StatisticsModel::Day );
554
 
    if ( !model->rowCount() )
555
 
        return false;
556
 
 
557
 
    QDate endDate = date.addDays( days );
558
 
    for ( int i = model->rowCount() - 1; i >= 0; --i )
559
 
    {
560
 
        // No others will be valid after this; stop early
561
 
        if ( model->date( i ) < date )
562
 
            return false;
563
 
        if ( model->date( i ) < endDate && model->date( i ) >= date )
564
 
            return true;
565
 
    }
566
 
    return false;
567
 
}
568
 
 
569
 
void InterfaceStatistics::genNewHour( const QDateTime &dateTime )
570
 
{
571
 
    StatisticsModel* hours = mModels.value( StatisticsModel::Hour );
572
 
 
573
 
    // Only 24 hours
574
 
    while ( hours->rowCount() )
575
 
    {
576
 
        if ( hours->dateTime( 0 ) <= dateTime.addDays( -1 ) )
577
 
            hours->removeRow( 0 );
578
 
        else
579
 
            break;
580
 
    }
581
 
 
582
 
    if ( hours->dateTime() == dateTime )
583
 
        return;
584
 
 
585
 
    hours->appendStats( dateTime, 0 );
586
 
 
587
 
    if ( mInterface->getSettings().warnType == NotifyHour ||
588
 
         mInterface->getSettings().warnType == NotifyRoll24Hour )
589
 
        mWarningDone = false;
590
 
}
591
 
 
592
 
void InterfaceStatistics::genNewDay( const QDate &date )
593
 
{
594
 
    StatisticsModel * model = mModels.value( StatisticsModel::Day );
595
 
    if ( model->rowCount() &&
596
 
         model->date().addDays( model->days() ) > date )
597
 
            return;
598
 
 
599
 
    mModels.value( StatisticsModel::Day )->appendStats( date, 1 );
600
 
 
601
 
    if ( mInterface->getSettings().warnType == NotifyDay ||
602
 
         mInterface->getSettings().warnType == NotifyRoll7Day ||
603
 
         mInterface->getSettings().warnType == NotifyRoll30Day )
604
 
        mWarningDone = false;
605
 
}
606
 
 
607
 
void InterfaceStatistics::genNewWeek( const QDate &date )
608
 
{
609
 
    StatisticsModel * model = mModels.value( StatisticsModel::Week );
610
 
    if ( model->rowCount() &&
611
 
         model->date().addDays( model->days() ) > date )
612
 
            return;
613
 
 
614
 
    int dow = mCalendar->dayOfWeek( date );
615
 
    // ISO8601: week always starts on a Monday
616
 
    QDate newDate = date.addDays( 1 - dow );
617
 
    model->appendStats( newDate, mCalendar->daysInWeek( newDate ) );
618
 
}
619
 
 
620
 
void InterfaceStatistics::genNewMonth( const QDate &date, QDate endDate )
621
 
{
622
 
    StatisticsModel * model = mModels.value( StatisticsModel::Month );
623
 
    if ( model->rowCount() &&
624
 
         model->date().addDays( model->days() ) > date )
625
 
            return;
626
 
 
627
 
    int days;
628
 
    // Partial month.  Very little to do.
629
 
    if ( endDate.isValid() )
630
 
    {
631
 
        days = date.daysTo( endDate );
632
 
        if ( daysInSpan( date, date.daysTo( endDate ) ) )
633
 
        {
634
 
            mModels.value( StatisticsModel::Month )->appendStats( date, days );
635
 
            return;
636
 
        }
637
 
        else
638
 
        {
639
 
            // partial month contains no daily stats, so advance start date
640
 
            // and get a new period below
641
 
            mBillingStart = date.addDays( days );
642
 
        }
643
 
    }
644
 
 
645
 
    // Given a calendar day and a billing period start date, find a
646
 
    // billing period that the day belongs in.
647
 
    QDate newDate;
648
 
    QDate nextMonthStart = mBillingStart;
649
 
    do
650
 
    {
651
 
        newDate = nextMonthStart;
652
 
        nextMonthStart = nextMonthDate( newDate );
653
 
        days = newDate.daysTo( nextMonthStart );
654
 
    } while ( nextMonthStart <= date || !daysInSpan( newDate, days ) );
655
 
 
656
 
    mBillingStart = newDate;
657
 
    mModels.value( StatisticsModel::Month )->appendStats( newDate, days );
658
 
 
659
 
    if ( mInterface->getSettings().warnType == NotifyMonth )
660
 
        mWarningDone = false;
661
 
}
662
 
 
663
 
void InterfaceStatistics::genNewYear( const QDate &date )
664
 
{
665
 
    StatisticsModel * model = mModels.value( StatisticsModel::Year );
666
 
    if ( model->rowCount() &&
667
 
         model->date().addDays( model->days() ) > date )
668
 
            return;
669
 
 
670
 
    int doy = mCalendar->dayOfYear( date );
671
 
    QDate newDate = date.addDays( 1 - doy );
672
 
    mModels.value( StatisticsModel::Year )->appendStats( newDate, mCalendar->daysInYear( newDate ) );
673
 
}
674
 
 
675
 
void InterfaceStatistics::checkValidEntry( QDateTime curDateTime )
676
 
{
 
952
// END REBUILDING STATISTICS
 
953
 
 
954
 
 
955
void InterfaceStatistics::checkValidEntry()
 
956
{
 
957
    mEntryTimer->stop();
 
958
    QDateTime curDateTime = QDateTime::currentDateTime();
677
959
    QDate curDate = curDateTime.date();
678
 
    StatisticsModel *days = mModels.value( StatisticsModel::Day );
 
960
    StatisticsModel *days = mModels.value( KNemoStats::Day );
679
961
 
680
 
    StatisticsModel *hours = mModels.value( StatisticsModel::Hour );
681
 
    if ( !hours->rowCount() || hours->dateTime().addSecs( 3600 ) < curDateTime )
 
962
    StatisticsModel *hours = mModels.value( KNemoStats::Hour );
 
963
    if ( !hours->rowCount() || hours->dateTime().addSecs( 3600 ) <= curDateTime )
 
964
    {
682
965
        genNewHour( QDateTime( curDate, QTime( curDateTime.time().hour(), 0 ) ) );
 
966
    }
683
967
 
684
968
    if ( !days->rowCount() || days->date() < curDate )
685
969
    {
686
 
        genNewDay( curDate );
687
 
        genNewWeek( curDate );
688
 
        genNewMonth( curDate );
689
 
        genNewYear( curDate );
690
 
    }
691
 
}
692
 
 
693
 
void InterfaceStatistics::checkThreshold( quint64 currentBytes )
694
 
{
695
 
    int warnMult = pow( 1024, mInterface->getSettings().warnUnits );
696
 
    quint64 thresholdBytes = mInterface->getSettings().warnThreshold * warnMult;
697
 
    if ( currentBytes > thresholdBytes )
698
 
    {
699
 
        mWarningDone = true;
700
 
        emit warnTraffic( thresholdBytes, currentBytes );
701
 
    }
702
 
}
703
 
 
704
 
void InterfaceStatistics::oneUnit( const StatisticsModel* model )
705
 
{
706
 
    if ( mInterface->getSettings().warnTotalTraffic )
707
 
        checkThreshold( model->totalBytes() );
708
 
    else
709
 
        checkThreshold( model->rxBytes() );
710
 
}
711
 
 
712
 
void InterfaceStatistics::rollingUnit( const StatisticsModel* model, int days )
713
 
{
714
 
    quint64 total = 0;
715
 
    QDateTime lowerLimit = model->dateTime().addDays( -days );
716
 
 
717
 
    for ( int i = model->rowCount() - 1; i >= 0; --i )
718
 
    {
719
 
        if ( model->dateTime( i ) > lowerLimit )
 
970
        genNewCalendarType( curDate, KNemoStats::Day );
 
971
        genNewCalendarType( curDate, KNemoStats::Week );
 
972
        genNewCalendarType( curDate, KNemoStats::Month );
 
973
        genNewCalendarType( curDate, KNemoStats::Year );
 
974
        genNewBillPeriod( curDate );
 
975
 
 
976
        // The fancy short date may need updating
 
977
        for ( int i = 0; i < hours->rowCount(); ++i )
 
978
            hours->updateDateText( i );
 
979
    }
 
980
 
 
981
    QDateTime ndt = curDateTime.addSecs( 3600 - curDateTime.time().minute()*60 - curDateTime.time().second() );
 
982
 
 
983
    int secs = curDateTime.secsTo( ndt );
 
984
    mEntryTimer->setInterval( secs * 1000 );
 
985
    mEntryTimer->start();
 
986
}
 
987
 
 
988
void InterfaceStatistics::checkWarnings()
 
989
{
 
990
    if ( !mTrafficChanged )
 
991
        return;
 
992
    mTrafficChanged = false;
 
993
 
 
994
    QList<WarnRule> warn = mInterface->settings().warnRules;
 
995
    for ( int wi=0; wi < warn.count(); ++wi )
 
996
    {
 
997
        if ( warn[wi].warnDone || !warn[wi].threshold > 0.0 )
 
998
            continue;
 
999
 
 
1000
        quint64 total = 0;
 
1001
        StatisticsModel *model = 0;
 
1002
 
 
1003
        model = mModels.value( warn[wi].periodUnits );
 
1004
        if ( !model )
 
1005
            return;
 
1006
 
 
1007
        int lowerIndex = model->rowCount() - warn[wi].periodCount;
 
1008
 
 
1009
        for ( int i = model->rowCount() - 1; i >= 0; --i )
720
1010
        {
721
 
            if ( mInterface->getSettings().warnTotalTraffic )
722
 
                total += model->totalBytes( i );
 
1011
            if ( i >= lowerIndex )
 
1012
            {
 
1013
                switch ( warn[wi].trafficDirection )
 
1014
                {
 
1015
                    case KNemoStats::TrafficIn:
 
1016
                        if ( warn[wi].trafficType == KNemoStats::PeakOffpeak )
 
1017
                            total += model->rxBytes( i );
 
1018
                        else if ( warn[wi].trafficType == KNemoStats::Offpeak )
 
1019
                            total += model->rxBytes( i, KNemoStats::OffpeakTraffic );
 
1020
                        else
 
1021
                            total += model->rxBytes( i ) - model->rxBytes( i, KNemoStats::OffpeakTraffic );
 
1022
                        break;
 
1023
                    case KNemoStats::TrafficOut:
 
1024
                        if ( warn[wi].trafficType == KNemoStats::PeakOffpeak )
 
1025
                            total += model->txBytes( i );
 
1026
                        else if ( warn[wi].trafficType == KNemoStats::Offpeak )
 
1027
                            total += model->txBytes( i, KNemoStats::OffpeakTraffic );
 
1028
                        else
 
1029
                            total += model->txBytes( i ) - model->txBytes( i, KNemoStats::OffpeakTraffic );
 
1030
                        break;
 
1031
                    default:
 
1032
                        if ( warn[wi].trafficType == KNemoStats::PeakOffpeak )
 
1033
                            total += model->totalBytes( i );
 
1034
                        else if ( warn[wi].trafficType == KNemoStats::Offpeak )
 
1035
                            total += model->totalBytes( i, KNemoStats::OffpeakTraffic );
 
1036
                        else
 
1037
                            total += model->totalBytes( i ) - model->totalBytes( i, KNemoStats::OffpeakTraffic );
 
1038
                }
 
1039
            }
723
1040
            else
724
 
                total += model->rxBytes( i );
725
 
        }
726
 
        else
727
 
            break;
 
1041
                break;
 
1042
        }
 
1043
 
 
1044
        int warnMult = pow( 1024, warn[wi].trafficUnits );
 
1045
        quint64 thresholdBytes = warn[wi].threshold * warnMult;
 
1046
        if ( total > thresholdBytes )
 
1047
        {
 
1048
            emit warnTraffic( warn[wi].customText, thresholdBytes, total );
 
1049
            mInterface->settings().warnRules[wi].warnDone = true;
 
1050
        }
728
1051
    }
729
 
    checkThreshold( total );
730
1052
}
731
1053
 
732
 
void InterfaceStatistics::checkTrafficLimit()
 
1054
 
 
1055
 
 
1056
/******************************
 
1057
 * Public Interface           *
 
1058
 ******************************/
 
1059
void InterfaceStatistics::clearStatistics()
733
1060
{
734
 
    int wtype = mInterface->getSettings().warnType;
735
 
 
736
 
    if ( !mWarningDone && mInterface->getSettings().warnThreshold > 0.0 )
 
1061
    foreach( StatisticsModel * s, mModels )
 
1062
        s->clearRows();
 
1063
    mStorageData.nextHourId = 0;
 
1064
    foreach ( StatisticsModel *s, mModels )
737
1065
    {
738
 
        switch ( wtype )
739
 
        {
740
 
            case NotifyHour:
741
 
                oneUnit( mModels.value( StatisticsModel::Hour ) );
742
 
                break;
743
 
            case NotifyDay:
744
 
                oneUnit( mModels.value( StatisticsModel::Day ) );
745
 
                break;
746
 
            case NotifyMonth:
747
 
                oneUnit( mModels.value( StatisticsModel::Month ) );
748
 
                break;
749
 
            case NotifyRoll24Hour:
750
 
                rollingUnit( mModels.value( StatisticsModel::Hour ), 24 );
751
 
                break;
752
 
            case NotifyRoll7Day:
753
 
                rollingUnit( mModels.value( StatisticsModel::Day ), 7 );
754
 
                break;
755
 
            case NotifyRoll30Day:
756
 
                rollingUnit( mModels.value( StatisticsModel::Day ), 30 );
757
 
                break;
758
 
        }
 
1066
        mStorageData.saveFromId.insert( s->periodType(), 0 );
759
1067
    }
 
1068
    sql->clearStats( &mStorageData );
 
1069
    checkValidEntry();
 
1070
    mTrafficChanged = true;
 
1071
    emit currentEntryChanged();
760
1072
}
761
1073
 
762
1074
void InterfaceStatistics::addRxBytes( unsigned long bytes )
764
1076
    if ( bytes == 0 )
765
1077
        return;
766
1078
 
767
 
    checkValidEntry();
768
 
 
769
1079
    foreach( StatisticsModel * s, mModels )
770
 
        s->addRxBytes( bytes );
 
1080
    {
 
1081
        if ( s->periodType() == KNemoStats::HourArchive )
 
1082
            continue;
 
1083
        foreach ( KNemoStats::TrafficType t, mModels.value( KNemoStats::Hour )->trafficTypes() )
 
1084
        {
 
1085
            s->addRxBytes( bytes, t );
 
1086
        }
 
1087
    }
771
1088
 
772
 
    checkTrafficLimit();
 
1089
    mTrafficChanged = true;
773
1090
    emit currentEntryChanged();
774
1091
}
775
1092
 
778
1095
    if ( bytes == 0 )
779
1096
        return;
780
1097
 
781
 
    checkValidEntry();
782
 
 
783
1098
    foreach( StatisticsModel * s, mModels )
784
 
        s->addTxBytes( bytes );
 
1099
    {
 
1100
        if ( s->periodType() == KNemoStats::HourArchive )
 
1101
            continue;
 
1102
        foreach ( KNemoStats::TrafficType t, mModels.value( KNemoStats::Hour )->trafficTypes() )
 
1103
        {
 
1104
            s->addTxBytes( bytes, t );
 
1105
        }
 
1106
    }
785
1107
 
786
 
    checkTrafficLimit();
 
1108
    mTrafficChanged = true;
787
1109
    emit currentEntryChanged();
788
1110
}
789
1111