51e1d6b2708307fb3f770f19da85a82ae9ebccce
[quassel.git] / core / backlog.cpp
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 BLOB)").arg(user));
86   query.exec(QString("CREATE TABLE IF NOT EXISTS 'Buffers$%1$' (BufferId INTEGER PRIMARY KEY AUTOINCREMENT, GroupId INTEGER, Network BLOB, Buffer BLOB)").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('\'', "''"); QByteArray bs = s.toUtf8().toHex();
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 == X'%2'").arg(user).arg(bs.constData()));
130   int suid;
131   if(!query.first()) {
132     query.exec(QString("INSERT INTO 'Senders$%1$' (SenderId, Sender) VALUES (%2, X'%3')").arg(user).arg(nextSenderId).arg(bs.constData()));
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   logDb.transaction();
158   QSqlQuery query(logDb);
159   int uid = -1;
160   query.exec(QString("SELECT BufferId FROM 'Buffers$%1$' WHERE Network == X'%2' AND Buffer == X'%3'").arg(user).arg(n.constData()).arg(b.constData()));
161   if(!query.first()) {
162     // TODO: joined buffers/queries
163     query.exec(QString("INSERT INTO 'Buffers$%1$' (BufferId, GroupId, Network, Buffer) VALUES (%2, %2, X'%3', X'%4')").arg(user).arg(nextBufferId).arg(n.constData()).arg(b.constData()));
164     uid = nextBufferId++;
165   } else uid = query.value(0).toInt();
166   logDb.commit();
167   return BufferId(uid, net, buf, uid);  // FIXME (joined buffers)
168 }
169
170 QList<BufferId> Backlog::requestBuffers(QDateTime since) {
171   QList<BufferId> result;
172   QSqlQuery query(logDb);
173   if(!since.isValid()) {
174     query.exec(QString("SELECT BufferId, GroupId, Network, Buffer FROM 'Buffers$%1$'").arg(user));
175   } else {
176     query.exec(QString("SELECT DISTINCT 'Buffers$%1$'.BufferId, GroupId, Network, Buffer FROM 'Buffers$%1$' NATURAL JOIN 'Backlog$%1$' "
177                        "WHERE Time >= %2").arg(user).arg(since.toTime_t()));
178   }
179   while(query.next()) {
180     result.append(BufferId(query.value(0).toUInt(), QString::fromUtf8(query.value(2).toByteArray()), QString::fromUtf8(query.value(3).toByteArray()), query.value(1).toUInt()));
181   }
182   return result;
183 }
184
185 QList<Message> Backlog::requestMsgs(BufferId id, int lastlines, int offset) {
186   QList<Message> result;
187   QSqlQuery query(logDb);
188   QString limit;
189   if(lastlines > 0) limit = QString("LIMIT %1").arg(lastlines);
190   query.exec(QString("SELECT MsgId, Time, Type, Flags, Sender, Text FROM 'Senders$%1$' NATURAL JOIN 'Backlog$%1$' "
191                      "WHERE BufferId IN (SELECT BufferId FROM 'Buffers$%1$' WHERE GroupId == %2) ORDER BY MsgId DESC %3").arg(user).arg(id.groupId()).arg(limit));
192   while(query.next()) {
193     if(offset >= 0 && query.value(0).toInt() >= offset) continue;
194     Message msg(QDateTime::fromTime_t(query.value(1).toInt()), id, (Message::Type)query.value(2).toUInt(), QString::fromUtf8(query.value(5).toByteArray()),
195                 QString::fromUtf8(query.value(4).toByteArray()), query.value(3).toUInt());
196     msg.msgId = query.value(0).toUInt();
197     result.append(msg);
198   }
199   return result;
200 }
201
202
203 // OBSOLETE
204 // This is kept here for importing the old file-based backlog.
205
206 void Backlog::importOldBacklog() {
207   qDebug() << "Deleting backlog database...";
208   logDb.exec(QString("DELETE FROM 'Backlog$%1$' WHERE SenderId != '$VERSION$'").arg(user));
209   logDb.exec(QString("DELETE FROM 'Senders$%1$'").arg(user));
210   logDb.exec(QString("DELETE FROM 'Buffers$%1$'").arg(user));
211   nextMsgId = 1; nextBufferId = 1; nextSenderId = 1;
212   qDebug() << "Importing old backlog files...";
213   initBackLogOld();
214   if(!backLogEnabledOld) return;
215   logDb.exec("VACUUM");
216   qDebug() << "Backlog successfully imported, you have to restart Quassel now!";
217   exit(0);
218
219 }
220
221 // file name scheme: quassel-backlog-2006-29-10.bin
222 void Backlog::initBackLogOld() {
223   backLogDir = QDir(Global::quasselDir + "/backlog");
224   if(!backLogDir.exists()) {
225     qWarning(QString("Creating backlog directory \"%1\"...").arg(backLogDir.absolutePath()).toAscii());
226     if(!backLogDir.mkpath(backLogDir.absolutePath())) {
227       qWarning(QString("Could not create backlog directory! Disabling logging...").toAscii());
228       backLogEnabledOld = false;
229       return;
230     }
231   }
232   backLogDir.refresh();
233   //if(!backLogDir.isReadable()) {
234   //  qWarning(QString("Cannot read directory \"%1\". Disabling logging...").arg(backLogDir.absolutePath()).toAscii());
235   //  backLogEnabled = false;
236   //  return;
237   //}
238   QStringList networks = backLogDir.entryList(QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable, QDir::Name);
239   foreach(QString net, networks) {
240     QDir dir(backLogDir.absolutePath() + "/" + net);
241     if(!dir.exists()) {
242       qWarning(QString("Could not change to directory \"%1\"!").arg(dir.absolutePath()).toAscii());
243       continue;
244     }
245     QStringList logs = dir.entryList(QStringList("quassel-backlog-*.bin"), QDir::Files|QDir::Readable, QDir::Name);
246     foreach(QString name, logs) {
247       QFile f(dir.absolutePath() + "/" + name);
248       if(!f.open(QIODevice::ReadOnly)) {
249         qWarning(QString("Could not open \"%1\" for reading!").arg(f.fileName()).toAscii());
250         continue;
251       }
252       QDataStream in(&f);
253       in.setVersion(QDataStream::Qt_4_2);
254       QByteArray verstring; quint8 vernum; in >> verstring >> vernum;
255       if(verstring != BACKLOG_STRING) {
256         qWarning(QString("\"%1\" is not a Quassel backlog file!").arg(f.fileName()).toAscii());
257         f.close(); continue;
258       }
259       if(vernum != BACKLOG_FORMAT) {
260         qWarning(QString("\"%1\": Version mismatch!").arg(f.fileName()).toAscii());
261         f.close(); continue;
262       }
263       qDebug() << "Reading backlog from" << f.fileName();
264       logFileDates[net] = QDate::fromString(f.fileName(),
265                                             QString("'%1/quassel-backlog-'yyyy-MM-dd'.bin'").arg(dir.absolutePath()));
266       if(!logFileDates[net].isValid()) {
267         qWarning(QString("\"%1\" has an invalid file name!").arg(f.fileName()).toAscii());
268       }
269       while(!in.atEnd()) {
270         quint8 t, f;
271         quint32 ts;
272         QByteArray s, m, targ;
273         in >> ts >> t >> f >> targ >> s >> m;
274         QString target = QString::fromUtf8(targ);
275         QString sender = QString::fromUtf8(s);
276         QString text = QString::fromUtf8(m);
277         BufferId id;
278         if((f & Message::PrivMsg) && !(f & Message::Self)) {
279           id = getBufferId(net, sender);
280         } else {
281           id = getBufferId(net, target);
282         }
283         Message msg(QDateTime::fromTime_t(ts), id, (Message::Type)t, text, sender, f);
284         //backLog[net].append(m);
285         logMessage(msg);
286       }
287       f.close();
288     }
289   }
290   backLogEnabledOld = true;
291 }
292
293
294 /** Log a core message (emitted via a displayMsg() signal) to the backlog file.
295  * If a file for the current day does not exist, one will be created. Otherwise, messages will be appended.
296  * The file header is the string defined by BACKLOG_STRING, followed by a quint8 specifying the format
297  * version (BACKLOG_FORMAT). The rest is simply serialized Message objects.
298  */
299 void Backlog::logMessageOld(QString net, Message msg) {
300   backLog[net].append(msg);
301   if(!logFileDirs.contains(net)) {
302     QDir dir(backLogDir.absolutePath() + "/" + net);
303     if(!dir.exists()) {
304       qWarning(QString("Creating backlog directory \"%1\"...").arg(dir.absolutePath()).toAscii());
305       if(!dir.mkpath(dir.absolutePath())) {
306         qWarning(QString("Could not create backlog directory!").toAscii());
307         return;
308       }
309     }
310     logFileDirs[net] = dir;
311     Q_ASSERT(!logFiles.contains(net) && !logStreams.contains(net));
312     if(!logFiles.contains(net)) logFiles[net] = new QFile();
313     if(!logStreams.contains(net)) logStreams[net] = new QDataStream();
314   }
315   if(!logFileDates[net].isValid() || logFileDates[net] < QDate::currentDate()) {
316     if(logFiles[net]->isOpen()) logFiles[net]->close();
317     logFileDates[net] = QDate::currentDate();
318   }
319   if(!logFiles[net]->isOpen()) {
320     logFiles[net]->setFileName(QString("%1/%2").arg(logFileDirs[net].absolutePath())
321         .arg(logFileDates[net].toString("'quassel-backlog-'yyyy-MM-dd'.bin'")));
322     if(!logFiles[net]->open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Unbuffered)) {
323       qWarning(QString("Could not open \"%1\" for writing: %2")
324           .arg(logFiles[net]->fileName()).arg(logFiles[net]->errorString()).toAscii());
325       return;
326     }
327     logStreams[net]->setDevice(logFiles[net]); logStreams[net]->setVersion(QDataStream::Qt_4_2);
328     if(!logFiles[net]->size()) *logStreams[net] << BACKLOG_STRING << (quint8)BACKLOG_FORMAT;
329   }
330   *logStreams[net] << msg;
331 }
332
333