~quassel-dev/quassel/i18n-master

« back to all changes in this revision

Viewing changes to src/core/backlog.cpp

  • Committer: Manuel Nickschas
  • Date: 2007-06-20 01:21:00 UTC
  • Revision ID: git-v1:077d44f36d2f5c730283ef6be839aea7dd073d56
Starting reorganization of files in preparation of separation of client and GUI.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/***************************************************************************
 
2
 *   Copyright (C) 2005-07 by The Quassel Team                             *
 
3
 *   devel@quassel-irc.org                                                 *
 
4
 *                                                                         *
 
5
 *   This program is free software; you can redistribute it and/or modify  *
 
6
 *   it under the terms of the GNU General Public License as published by  *
 
7
 *   the Free Software Foundation; either version 2 of the License, or     *
 
8
 *   (at your option) any later version.                                   *
 
9
 *                                                                         *
 
10
 *   This program is distributed in the hope that it will be useful,       *
 
11
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 
12
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 
13
 *   GNU General Public License for more details.                          *
 
14
 *                                                                         *
 
15
 *   You should have received a copy of the GNU General Public License     *
 
16
 *   along with this program; if not, write to the                         *
 
17
 *   Free Software Foundation, Inc.,                                       *
 
18
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 
19
 ***************************************************************************/
 
20
 
 
21
#include "backlog.h"
 
22
#include "util.h"
 
23
 
 
24
#define DBVERSION 1
 
25
 
 
26
Backlog::Backlog() {
 
27
 
 
28
 
 
29
}
 
30
 
 
31
 
 
32
Backlog::~Backlog() {
 
33
  logDb.close();
 
34
 
 
35
  // FIXME Old stuff
 
36
  foreach(QDataStream *s, logStreams) {
 
37
    delete s;
 
38
  }
 
39
  foreach(QFile *f, logFiles) {
 
40
    if(f->isOpen()) f->close();
 
41
    delete f;
 
42
  }
 
43
}
 
44
 
 
45
 
 
46
void Backlog::init(QString _user) {
 
47
  user = _user;
 
48
  QDir backlogDir = QDir(Global::quasselDir);
 
49
  if(!backlogDir.exists()) {
 
50
    qWarning(QString("Creating backlog directory \"%1\"...").arg(backlogDir.absolutePath()).toAscii());
 
51
    if(!backlogDir.mkpath(backlogDir.absolutePath())) {
 
52
      qWarning(QString("Could not create backlog directory! Disabling logging...").toAscii());
 
53
      backlogEnabled = false;
 
54
      return;
 
55
    }
 
56
  }
 
57
  QString backlogFile = Global::quasselDir + "/quassel-backlog.sqlite";
 
58
  logDb = QSqlDatabase::addDatabase("QSQLITE", user);
 
59
  logDb.setDatabaseName(backlogFile);
 
60
  bool ok = logDb.open();
 
61
  if(!ok) {
 
62
    qWarning(tr("Could not open backlog database: %1").arg(logDb.lastError().text()).toAscii());
 
63
    qWarning(tr("Disabling logging...").toAscii());
 
64
    backlogEnabled = false; return;
 
65
  }
 
66
 
 
67
  if(!logDb.transaction()) qWarning(tr("Database driver does not support transactions. This might lead to a corrupt database!").toAscii());
 
68
  QString tname = QString("'Backlog$%1$'").arg(user);
 
69
  QSqlQuery query(logDb);
 
70
  /* DEBUG */
 
71
  //query.exec(QString("DROP TABLE %1").arg(tname)); // DEBUG
 
72
  //query.exec(QString("DROP TABLE 'Senders$%1$'").arg(user));
 
73
  //query.exec(QString("DROP TABLE 'Buffers$%1$'").arg(user));
 
74
  /* END DEBUG */
 
75
  query.exec(QString("CREATE TABLE IF NOT EXISTS %1 ("
 
76
      "MsgId INTEGER PRIMARY KEY AUTOINCREMENT,"
 
77
      "Time INTEGER,"
 
78
      "BufferId INTEGER,"
 
79
      "Type INTEGER,"
 
80
      "Flags INTEGER,"
 
81
      "SenderId INTEGER,"
 
82
      "Text BLOB"
 
83
      ")").arg(tname));
 
84
  query.exec(QString("INSERT OR REPLACE INTO %1 (MsgId, SenderId, Text) VALUES (0, '$VERSION$', %2)").arg(tname).arg(DBVERSION));
 
85
  query.exec(QString("CREATE TABLE IF NOT EXISTS 'Senders$%1$' (SenderId INTEGER PRIMARY KEY AUTOINCREMENT, Sender TEXT)").arg(user));
 
86
  query.exec(QString("CREATE TABLE IF NOT EXISTS 'Buffers$%1$' (BufferId INTEGER PRIMARY KEY AUTOINCREMENT, GroupId INTEGER, Network TEXT, Buffer TEXT)").arg(user));
 
87
  if(query.lastError().isValid()) {
 
88
    qWarning(tr("Could not create backlog table: %1").arg(query.lastError().text()).toAscii());
 
89
    qWarning(tr("Disabling logging...").toAscii());
 
90
    logDb.rollback();
 
91
    backlogEnabled = false; return;
 
92
  }
 
93
  // Find the next free uid numbers
 
94
  query.exec(QString("SELECT MsgId FROM %1 ORDER BY MsgId DESC LIMIT 1").arg(tname));
 
95
  query.first();
 
96
  if(query.value(0).isValid()) nextMsgId = query.value(0).toUInt() + 1;
 
97
  else {
 
98
    qWarning(tr("Something is wrong with the backlog database! %1").arg(query.lastError().text()).toAscii());
 
99
    nextMsgId = 1;
 
100
  }
 
101
  query.exec(QString("SELECT BufferId FROM 'Buffers$%1$' ORDER BY BufferId DESC LIMIT 1").arg(user));
 
102
  if(query.first()) {
 
103
    if(query.value(0).isValid()) nextBufferId = query.value(0).toUInt() + 1;
 
104
    else {
 
105
      qWarning(tr("Something is wrong with the backlog database! %1").arg(query.lastError().text()).toAscii());
 
106
      nextBufferId = 0;
 
107
    }
 
108
  } else nextBufferId = 0;
 
109
  query.exec(QString("SELECT SenderId FROM 'Senders$%1$' ORDER BY SenderId DESC LIMIT 1").arg(user));
 
110
  if(query.first()) {
 
111
    if(query.value(0).isValid()) nextSenderId = query.value(0).toUInt() + 1;
 
112
    else {
 
113
      qWarning(tr("Something is wrong with the backlog database! %1").arg(query.lastError().text()).toAscii());
 
114
      nextSenderId = 0;
 
115
    }
 
116
  } else nextSenderId = 0;
 
117
  logDb.commit();
 
118
  backlogEnabled = true;
 
119
}
 
120
 
 
121
uint Backlog::logMessage(Message msg) {
 
122
  if(!backlogEnabled) return 0;
 
123
  bool ok;
 
124
  logDb.transaction();
 
125
  QSqlQuery query(logDb);
 
126
  QString s = msg.sender; s.replace('\'', "''");
 
127
  QString t = msg.text; t.replace('\'', "''");
 
128
  // Let's do some space-saving optimizations...
 
129
  query.exec(QString("SELECT SenderId FROM 'Senders$%1$' WHERE Sender == '%2'").arg(user).arg(s));
 
130
  int suid;
 
131
  if(!query.first()) {
 
132
    query.exec(QString("INSERT INTO 'Senders$%1$' (SenderId, Sender) VALUES (%2, '%3')").arg(user).arg(nextSenderId).arg(s));
 
133
    suid = nextSenderId;
 
134
  } else suid = query.value(0).toInt();
 
135
  query.exec(QString("INSERT INTO 'Backlog$%1$' (MsgId, Time, BufferId, Type, Flags, SenderId, Text) VALUES (%2, %3, %4, %5, %6, %7, X'%8')").arg(user)
 
136
      .arg(nextMsgId).arg(msg.timeStamp.toTime_t()).arg(msg.buffer.uid()).arg(msg.type).arg(msg.flags).arg(suid).arg(t.toUtf8().toHex().constData()));
 
137
 
 
138
  if(query.lastError().isValid()) {
 
139
    qWarning(tr("Database error while logging: %1").arg(query.lastError().text()).toAscii());
 
140
    logDb.rollback();
 
141
    return 0;
 
142
  }
 
143
 
 
144
  nextMsgId++;
 
145
  if(suid == nextSenderId) nextSenderId++;
 
146
  logDb.commit();
 
147
  return nextMsgId - 1;
 
148
}
 
149
 
 
150
// TODO: optimize by keeping free IDs in memory? What about deleted IDs? Nickchanges for queries?
 
151
BufferId Backlog::getBufferId(QString net, QString buf) {
 
152
  if(!backlogEnabled) {
 
153
    return BufferId(0, net, buf);
 
154
  }
 
155
  //QByteArray n = net.toUtf8().toHex();
 
156
  //QByteArray b = buf.toUtf8().toHex();
 
157
  bool flg = false;
 
158
  logDb.transaction();
 
159
  QSqlQuery query(logDb);
 
160
  int uid = -1;
 
161
  query.exec(QString("SELECT BufferId FROM 'Buffers$%1$' WHERE Network == '%2' AND Buffer == '%3'").arg(user).arg(net).arg(buf));
 
162
  if(!query.first()) {
 
163
    // TODO: joined buffers/queries
 
164
    query.exec(QString("INSERT INTO 'Buffers$%1$' (BufferId, GroupId, Network, Buffer) VALUES (%2, %2, '%3', '%4')").arg(user).arg(nextBufferId).arg(net).arg(buf));
 
165
    uid = nextBufferId++;
 
166
    flg = true;
 
167
  } else uid = query.value(0).toInt();
 
168
  logDb.commit();
 
169
  BufferId id(uid, net, buf, uid);  // FIXME (joined buffers)
 
170
  if(flg) emit bufferIdUpdated(id);
 
171
  return id;  // FIXME (joined buffers)
 
172
}
 
173
 
 
174
QList<BufferId> Backlog::requestBuffers(QDateTime since) {
 
175
  QList<BufferId> result;
 
176
  QSqlQuery query(logDb);
 
177
  if(!since.isValid()) {
 
178
    query.exec(QString("SELECT BufferId, GroupId, Network, Buffer FROM 'Buffers$%1$'").arg(user));
 
179
  } else {
 
180
    query.exec(QString("SELECT DISTINCT 'Buffers$%1$'.BufferId, GroupId, Network, Buffer FROM 'Buffers$%1$' NATURAL JOIN 'Backlog$%1$' "
 
181
                       "WHERE Time >= %2").arg(user).arg(since.toTime_t()));
 
182
  }
 
183
  while(query.next()) {
 
184
    result.append(BufferId(query.value(0).toUInt(), query.value(2).toString(), query.value(3).toString(), query.value(1).toUInt()));
 
185
  }
 
186
  return result;
 
187
}
 
188
 
 
189
QList<Message> Backlog::requestMsgs(BufferId id, int lastlines, int offset) {
 
190
  QList<Message> result;
 
191
  QSqlQuery query(logDb);
 
192
  QString limit;
 
193
  if(lastlines > 0) limit = QString("LIMIT %1").arg(lastlines);
 
194
  query.exec(QString("SELECT MsgId, Time, Type, Flags, Sender, Text FROM 'Senders$%1$' NATURAL JOIN 'Backlog$%1$' "
 
195
                     "WHERE BufferId IN (SELECT BufferId FROM 'Buffers$%1$' WHERE GroupId == %2) ORDER BY MsgId DESC %3").arg(user).arg(id.groupId()).arg(limit));
 
196
  while(query.next()) {
 
197
    if(offset >= 0 && query.value(0).toInt() >= offset) continue;
 
198
    Message msg(QDateTime::fromTime_t(query.value(1).toInt()), id, (Message::Type)query.value(2).toUInt(), QString::fromUtf8(query.value(5).toByteArray()),
 
199
                query.value(4).toString(), query.value(3).toUInt());
 
200
    msg.msgId = query.value(0).toUInt();
 
201
    result.append(msg);
 
202
  }
 
203
  return result;
 
204
}
 
205
 
 
206
 
 
207
// OBSOLETE
 
208
// This is kept here for importing the old file-based backlog.
 
209
 
 
210
void Backlog::importOldBacklog() {
 
211
  qDebug() << "Deleting backlog database...";
 
212
  logDb.exec(QString("DELETE FROM 'Backlog$%1$' WHERE SenderId != '$VERSION$'").arg(user));
 
213
  logDb.exec(QString("DELETE FROM 'Senders$%1$'").arg(user));
 
214
  logDb.exec(QString("DELETE FROM 'Buffers$%1$'").arg(user));
 
215
  nextMsgId = 1; nextBufferId = 1; nextSenderId = 1;
 
216
  qDebug() << "Importing old backlog files...";
 
217
  initBackLogOld();
 
218
  if(!backLogEnabledOld) return;
 
219
  logDb.exec("VACUUM");
 
220
  qDebug() << "Backlog successfully imported, you have to restart Quassel now!";
 
221
  exit(0);
 
222
 
 
223
}
 
224
 
 
225
// file name scheme: quassel-backlog-2006-29-10.bin
 
226
void Backlog::initBackLogOld() {
 
227
  backLogDir = QDir(Global::quasselDir + "/backlog");
 
228
  if(!backLogDir.exists()) {
 
229
    qWarning(QString("Creating backlog directory \"%1\"...").arg(backLogDir.absolutePath()).toAscii());
 
230
    if(!backLogDir.mkpath(backLogDir.absolutePath())) {
 
231
      qWarning(QString("Could not create backlog directory! Disabling logging...").toAscii());
 
232
      backLogEnabledOld = false;
 
233
      return;
 
234
    }
 
235
  }
 
236
  backLogDir.refresh();
 
237
  //if(!backLogDir.isReadable()) {
 
238
  //  qWarning(QString("Cannot read directory \"%1\". Disabling logging...").arg(backLogDir.absolutePath()).toAscii());
 
239
  //  backLogEnabled = false;
 
240
  //  return;
 
241
  //}
 
242
  QStringList networks = backLogDir.entryList(QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable, QDir::Name);
 
243
  foreach(QString net, networks) {
 
244
    QDir dir(backLogDir.absolutePath() + "/" + net);
 
245
    if(!dir.exists()) {
 
246
      qWarning(QString("Could not change to directory \"%1\"!").arg(dir.absolutePath()).toAscii());
 
247
      continue;
 
248
    }
 
249
    QStringList logs = dir.entryList(QStringList("quassel-backlog-*.bin"), QDir::Files|QDir::Readable, QDir::Name);
 
250
    foreach(QString name, logs) {
 
251
      QFile f(dir.absolutePath() + "/" + name);
 
252
      if(!f.open(QIODevice::ReadOnly)) {
 
253
        qWarning(QString("Could not open \"%1\" for reading!").arg(f.fileName()).toAscii());
 
254
        continue;
 
255
      }
 
256
      QDataStream in(&f);
 
257
      in.setVersion(QDataStream::Qt_4_2);
 
258
      QByteArray verstring; quint8 vernum; in >> verstring >> vernum;
 
259
      if(verstring != BACKLOG_STRING) {
 
260
        qWarning(QString("\"%1\" is not a Quassel backlog file!").arg(f.fileName()).toAscii());
 
261
        f.close(); continue;
 
262
      }
 
263
      if(vernum != BACKLOG_FORMAT) {
 
264
        qWarning(QString("\"%1\": Version mismatch!").arg(f.fileName()).toAscii());
 
265
        f.close(); continue;
 
266
      }
 
267
      qDebug() << "Reading backlog from" << f.fileName();
 
268
      logFileDates[net] = QDate::fromString(f.fileName(),
 
269
                                            QString("'%1/quassel-backlog-'yyyy-MM-dd'.bin'").arg(dir.absolutePath()));
 
270
      if(!logFileDates[net].isValid()) {
 
271
        qWarning(QString("\"%1\" has an invalid file name!").arg(f.fileName()).toAscii());
 
272
      }
 
273
      while(!in.atEnd()) {
 
274
        quint8 t, f;
 
275
        quint32 ts;
 
276
        QByteArray s, m, targ;
 
277
        in >> ts >> t >> f >> targ >> s >> m;
 
278
        QString target = QString::fromUtf8(targ);
 
279
        QString sender = QString::fromUtf8(s);
 
280
        QString text = QString::fromUtf8(m);
 
281
        BufferId id;
 
282
        if((f & Message::PrivMsg) && !(f & Message::Self)) {
 
283
          id = getBufferId(net, sender);
 
284
        } else {
 
285
          id = getBufferId(net, target);
 
286
        }
 
287
        Message msg(QDateTime::fromTime_t(ts), id, (Message::Type)t, text, sender, f);
 
288
        //backLog[net].append(m);
 
289
        logMessage(msg);
 
290
      }
 
291
      f.close();
 
292
    }
 
293
  }
 
294
  backLogEnabledOld = true;
 
295
}
 
296
 
 
297
 
 
298
/** Log a core message (emitted via a displayMsg() signal) to the backlog file.
 
299
 * If a file for the current day does not exist, one will be created. Otherwise, messages will be appended.
 
300
 * The file header is the string defined by BACKLOG_STRING, followed by a quint8 specifying the format
 
301
 * version (BACKLOG_FORMAT). The rest is simply serialized Message objects.
 
302
 */
 
303
void Backlog::logMessageOld(QString net, Message msg) {
 
304
  backLog[net].append(msg);
 
305
  if(!logFileDirs.contains(net)) {
 
306
    QDir dir(backLogDir.absolutePath() + "/" + net);
 
307
    if(!dir.exists()) {
 
308
      qWarning(QString("Creating backlog directory \"%1\"...").arg(dir.absolutePath()).toAscii());
 
309
      if(!dir.mkpath(dir.absolutePath())) {
 
310
        qWarning(QString("Could not create backlog directory!").toAscii());
 
311
        return;
 
312
      }
 
313
    }
 
314
    logFileDirs[net] = dir;
 
315
    Q_ASSERT(!logFiles.contains(net) && !logStreams.contains(net));
 
316
    if(!logFiles.contains(net)) logFiles[net] = new QFile();
 
317
    if(!logStreams.contains(net)) logStreams[net] = new QDataStream();
 
318
  }
 
319
  if(!logFileDates[net].isValid() || logFileDates[net] < QDate::currentDate()) {
 
320
    if(logFiles[net]->isOpen()) logFiles[net]->close();
 
321
    logFileDates[net] = QDate::currentDate();
 
322
  }
 
323
  if(!logFiles[net]->isOpen()) {
 
324
    logFiles[net]->setFileName(QString("%1/%2").arg(logFileDirs[net].absolutePath())
 
325
        .arg(logFileDates[net].toString("'quassel-backlog-'yyyy-MM-dd'.bin'")));
 
326
    if(!logFiles[net]->open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Unbuffered)) {
 
327
      qWarning(QString("Could not open \"%1\" for writing: %2")
 
328
          .arg(logFiles[net]->fileName()).arg(logFiles[net]->errorString()).toAscii());
 
329
      return;
 
330
    }
 
331
    logStreams[net]->setDevice(logFiles[net]); logStreams[net]->setVersion(QDataStream::Qt_4_2);
 
332
    if(!logFiles[net]->size()) *logStreams[net] << BACKLOG_STRING << (quint8)BACKLOG_FORMAT;
 
333
  }
 
334
  *logStreams[net] << msg;
 
335
}
 
336
 
 
337