adding new message requesters to the storage backend
[quassel.git] / src / core / core.h
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
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) version 3.                                           *
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 #ifndef CORE_H
22 #define CORE_H
23
24 #include <QDateTime>
25 #include <QString>
26 #include <QVariant>
27 #include <QTimer>
28
29 #ifdef HAVE_SSL
30 #  include <QSslSocket>
31 #  include "sslserver.h"
32 #else
33 #  include <QTcpSocket>
34 #  include <QTcpServer>
35 #endif
36
37 #include "storage.h"
38 #include "bufferinfo.h"
39 #include "message.h"
40 #include "sessionthread.h"
41 #include "types.h"
42
43 class CoreSession;
44 class SessionThread;
45 class SignalProxy;
46 struct NetworkInfo;
47
48 class Core : public QObject {
49   Q_OBJECT
50
51   public:
52   static Core * instance();
53   static void destroy();
54
55   static void saveState();
56   static void restoreState();
57
58   /*** Storage access ***/
59   // These methods are threadsafe.
60
61   //! Store a user setting persistently
62   /**
63    * \param userId       The users Id
64    * \param settingName  The Name of the Setting
65    * \param data         The Value
66    */
67   static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
68     instance()->storage->setUserSetting(userId, settingName, data);
69   }
70
71   //! Retrieve a persistent user setting
72   /**
73    * \param userId       The users Id
74    * \param settingName  The Name of the Setting
75    * \param default      Value to return in case it's unset.
76    * \return the Value of the Setting or the default value if it is unset.
77    */
78   static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &data = QVariant()) {
79     return instance()->storage->getUserSetting(userId, settingName, data);
80   }
81
82
83   //! Create a Network in the Storage and store it's Id in the given NetworkInfo
84   /** \note This method is thredsafe.
85    *
86    *  \param user        The core user
87    *  \param networkInfo a NetworkInfo definition to store the newly created ID in
88    *  \return true if successfull.
89    */
90   static bool createNetwork(UserId user, NetworkInfo &info);
91
92   //! Apply the changes to NetworkInfo info to the storage engine
93   /** \note This method is thredsafe.
94    *
95    *  \param user        The core user
96    *  \param networkInfo The Updated NetworkInfo
97    *  \return true if successfull.
98    */
99   static inline bool updateNetwork(UserId user, const NetworkInfo &info) {
100     return instance()->storage->updateNetwork(user, info);
101   }
102
103   //! Permanently remove a Network and all the data associated with it.
104   /** \note This method is thredsafe.
105    *
106    *  \param user        The core user
107    *  \param networkId   The network to delete
108    *  \return true if successfull.
109    */
110   static inline bool removeNetwork(UserId user, const NetworkId &networkId) {
111     return instance()->storage->removeNetwork(user, networkId);
112   }
113
114   //! Returns a list of all NetworkInfos for the given UserId user
115   /** \note This method is thredsafe.
116    *
117    *  \param user        The core user
118    *  \return QList<NetworkInfo>.
119    */
120   static inline QList<NetworkInfo> networks(UserId user) {
121     return instance()->storage->networks(user);
122   }
123
124   //! Get the NetworkId for a network name.
125   /** \note This method is threadsafe.
126    *
127    *  \param user    The core user
128    *  \param network The name of the network
129    *  \return The NetworkId corresponding to the given network.
130    */
131   static inline NetworkId networkId(UserId user, const QString &network) {
132     return instance()->storage->getNetworkId(user, network);
133   }
134
135   //! Get a list of Networks to restore
136   /** Return a list of networks the user was connected at the time of core shutdown
137    *  \note This method is threadsafe.
138    *
139    *  \param user  The User Id in question
140    */
141   static inline QList<NetworkId> connectedNetworks(UserId user) {
142     return instance()->storage->connectedNetworks(user);
143   }
144
145   //! Update the connected state of a network
146   /** \note This method is threadsafe
147    *
148    *  \param user        The Id of the networks owner
149    *  \param networkId   The Id of the network
150    *  \param isConnected whether the network is connected or not
151    */
152   static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) {
153     return instance()->storage->setNetworkConnected(user, networkId, isConnected);
154   }
155
156   //! Get a hash of channels with their channel keys for a given network
157   /** The keys are channel names and values are passwords (possibly empty)
158    *  \note This method is threadsafe
159    *
160    *  \param user       The id of the networks owner
161    *  \param networkId  The Id of the network
162    */
163   static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId) {
164     return instance()->storage->persistentChannels(user, networkId);
165   }
166
167   //! Update the connected state of a channel
168   /** \note This method is threadsafe
169    *
170    *  \param user       The Id of the networks owner
171    *  \param networkId  The Id of the network
172    *  \param channel    The name of the channel
173    *  \param isJoined   whether the channel is connected or not
174    */
175   static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) {
176     return instance()->storage->setChannelPersistent(user, networkId, channel, isJoined);
177   }
178
179   //! Update the key of a channel
180   /** \note This method is threadsafe
181    *
182    *  \param user       The Id of the networks owner
183    *  \param networkId  The Id of the network
184    *  \param channel    The name of the channel
185    *  \param key        The key of the channel (possibly empty)
186    */
187   static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) {
188     return instance()->storage->setPersistentChannelKey(user, networkId, channel, key);
189   }
190
191   //! Get the unique BufferInfo for the given combination of network and buffername for a user.
192   /** \note This method is threadsafe.
193    *
194    *  \param user      The core user who owns this buffername
195    *  \param networkId The network id
196    *  \param type      The type of the buffer (StatusBuffer, Channel, etc.)
197    *  \param buffer    The buffer name (if empty, the net's status buffer is returned)
198    *  \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
199    */
200   static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "") {
201     return instance()->storage->getBufferInfo(user, networkId, type, buffer);
202   }
203
204   //! Get the unique BufferInfo for a bufferId
205   /** \note This method is threadsafe
206    *  \param user      The core user who owns this buffername
207    *  \param bufferId  The id of the buffer
208    *  \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
209    */
210   static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) {
211     return instance()->storage->getBufferInfo(user, bufferId);
212   }
213
214   //! Store a Message in the backlog.
215   /** \note This method is threadsafe.
216    *
217    *  \param msg  The message object to be stored
218    *  \return The globally unique id for the stored message
219    */
220   static inline MsgId storeMessage(const Message &message) {
221     return instance()->storage->logMessage(message);
222   }
223
224   //! Request a certain number (or all) messages stored in a given buffer.
225   /** \note This method is threadsafe.
226    *
227    *  \param buffer   The buffer we request messages from
228    *  \param limit The number of messages we would like to receive, or -1 if we'd like all messages from that buffername
229    *  \param offset   Do not return (but DO count) messages with MsgId >= offset, if offset >= 0
230    *  \return The requested list of messages
231    */
232   static inline QList<Message> requestMsgs(UserId user, BufferId buffer, int limit = -1, int offset = -1) {
233     return instance()->storage->requestMsgs(user, buffer, limit, offset);
234   }
235
236   //! Request messages stored in a given buffer since a certain point in time.
237   /** \note This method is threadsafe.
238    *
239    *  \param buffer   The buffer we request messages from
240    *  \param since    Only return messages newer than this point in time
241    *  \param offset   Do not return messages with MsgId >= offset, if offset >= 0
242    *  \return The requested list of messages
243    */
244   static inline QList<Message> requestMsgs(UserId user, BufferId buffer, QDateTime since, int offset = -1) {
245     return instance()->storage->requestMsgs(user, buffer, since, offset);
246   }
247
248   //! Request a range of messages stored in a given buffer.
249   /** \note This method is threadsafe.
250    *
251    *  \param buffer   The buffer we request messages from
252    *  \param first    Return messages with first <= MsgId <= last
253    *  \param last     Return messages with first <= MsgId <= last
254    *  \return The requested list of messages
255    */
256   static inline QList<Message> requestMsgRange(UserId user, BufferId buffer, int first, int last) {
257     return instance()->storage->requestMsgRange(user, buffer, first, last);
258   }
259
260   //! Request all unread messages
261   /** \param buffer   The buffer we request messages from
262    *  \param first    Return messages with first <= MsgId
263    *  \param limit    Max amount of messages
264    *  \return The requested list of messages
265    */
266   static inline QList<Message> requestNewMsgs(UserId user, BufferId bufferId, int first, int limit = -1) {
267     return instance()->storage->requestNewMsgs(user, bufferId, first, limit);
268   }
269
270   //! Request all unread messages for all buffers
271   /** \param first    Return messages with first <= MsgId
272    *  \param limit    Max amount of messages
273    *  \return The requested list of messages
274    */
275   static inline QList<Message> requestAllNewMsgs(UserId user, int first, int limit = -1) {
276     return instance()->storage->requestAllNewMsgs(user, first, limit);
277   }
278
279   //! Request a list of all buffers known to a user.
280   /** This method is used to get a list of all buffers we have stored a backlog from.
281    *  \note This method is threadsafe.
282    *
283    *  \param user  The user whose buffers we request
284    *  \return A list of the BufferInfos for all buffers as requested
285    */
286   static inline QList<BufferInfo> requestBuffers(UserId user) {
287     return instance()->storage->requestBuffers(user);
288   }
289
290   //! Request a list of BufferIds for a given NetworkId
291   /** \note This method is threadsafe.
292    *
293    *  \param user  The user whose buffers we request
294    *  \param networkId  The NetworkId of the network in question
295    *  \return List of BufferIds belonging to the Network
296    */
297   static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId) {
298     return instance()->storage->requestBufferIdsForNetwork(user, networkId);
299   }
300
301   //! Remove permanently a buffer and it's content from the storage backend
302   /** This call cannot be reverted!
303    *  \note This method is threadsafe.
304    *
305    *  \param user      The user who is the owner of the buffer
306    *  \param bufferId  The bufferId
307    *  \return true if successfull
308    */
309   static inline bool removeBuffer(const UserId &user, const BufferId &bufferId) {
310     return instance()->storage->removeBuffer(user, bufferId);
311   }
312
313   //! Rename a Buffer
314   /** \note This method is threadsafe.
315    *  \param user      The id of the buffer owner
316    *  \param networkId The id of the network the buffer belongs to
317    *  \param newName   The new name of the buffer
318    *  \param oldName   The previous name of the buffer
319    *  \return the BufferId of the affected buffer or an invalid BufferId if not successfull
320    */
321   static inline BufferId renameBuffer(const UserId &user, const NetworkId &networkId, const QString &newName, const QString &oldName) {
322     return instance()->storage->renameBuffer(user, networkId, newName, oldName);
323   }
324
325   //! Update the LastSeenDate for a Buffer
326   /** This Method is used to make the LastSeenDate of a Buffer persistent
327    *  \note This method is threadsafe.
328    *
329    * \param user      The Owner of that Buffer
330    * \param bufferId  The buffer id
331    * \param MsgId     The Message id of the message that has been just seen
332    */
333   static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) {
334     return instance()->storage->setBufferLastSeenMsg(user, bufferId, msgId);
335   }
336
337   //! Get a Hash of all last seen message ids
338   /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
339    *  \note This method is threadsafe.
340    *
341    * \param user      The Owner of the buffers
342    */
343   static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) {
344     return instance()->storage->bufferLastSeenMsgIds(user);
345   }
346
347   const QDateTime &startTime() const { return _startTime; }
348
349 public slots:
350   //! Make storage data persistent
351   /** \note This method is threadsafe.
352    */
353   void syncStorage();
354   void setupInternalClientSession(SignalProxy *proxy);
355 signals:
356   //! Sent when a BufferInfo is updated in storage.
357   void bufferInfoUpdated(UserId user, const BufferInfo &info);
358
359   //! Relay From CoreSession::sessionState(const QVariant &). Used for internal connection only
360   void sessionState(const QVariant &);
361
362 private slots:
363   bool startListening();
364   void stopListening(const QString &msg = QString());
365   void incomingConnection();
366   void clientHasData();
367   void clientDisconnected();
368
369   bool initStorage(QVariantMap dbSettings, bool setup = false);
370
371 #ifdef HAVE_SSL
372   void sslErrors(const QList<QSslError> &errors);
373 #endif
374   void socketError(QAbstractSocket::SocketError);
375
376 private:
377   Core();
378   ~Core();
379   void init();
380   static Core *instanceptr;
381
382   SessionThread *createSession(UserId userId, bool restoreState = false);
383   void setupClientSession(QTcpSocket *socket, UserId uid);
384   void processClientMessage(QTcpSocket *socket, const QVariantMap &msg);
385   //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
386   QString setupCoreForInternalUsage();
387   QString setupCore(QVariantMap setupData);
388
389   bool registerStorageBackend(Storage *);
390   void unregisterStorageBackend(Storage *);
391
392   QHash<UserId, SessionThread *> sessions;
393   Storage *storage;
394   QTimer _storageSyncTimer;
395
396 #ifdef HAVE_SSL
397   SslServer _server, _v6server;
398 #else
399   QTcpServer _server, _v6server;
400 #endif
401
402   QHash<QTcpSocket *, quint32> blocksizes;
403   QHash<QTcpSocket *, QVariantMap> clientInfo;
404
405   QHash<QString, Storage *> _storageBackends;
406
407   QDateTime _startTime;
408
409   bool configured;
410 };
411
412 #endif