fixing a big oopsie that would cause the creation of a new empty buffer on any observ...
[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   /* Identity handling */
83   static inline IdentityId createIdentity(UserId user, CoreIdentity &identity) {
84     return instance()->storage->createIdentity(user, identity);
85   }
86   static bool updateIdentity(UserId user, const CoreIdentity &identity) {
87     return instance()->storage->updateIdentity(user, identity);
88   }
89   static void removeIdentity(UserId user, IdentityId identityId) {
90     instance()->storage->removeIdentity(user, identityId);
91   }
92   static QList<CoreIdentity> identities(UserId user) {
93     return instance()->storage->identities(user);
94   }
95
96   //! Create a Network in the Storage and store it's Id in the given NetworkInfo
97   /** \note This method is thredsafe.
98    *
99    *  \param user        The core user
100    *  \param networkInfo a NetworkInfo definition to store the newly created ID in
101    *  \return true if successfull.
102    */
103   static bool createNetwork(UserId user, NetworkInfo &info);
104
105   //! Apply the changes to NetworkInfo info to the storage engine
106   /** \note This method is thredsafe.
107    *
108    *  \param user        The core user
109    *  \param networkInfo The Updated NetworkInfo
110    *  \return true if successfull.
111    */
112   static inline bool updateNetwork(UserId user, const NetworkInfo &info) {
113     return instance()->storage->updateNetwork(user, info);
114   }
115
116   //! Permanently remove a Network and all the data associated with it.
117   /** \note This method is thredsafe.
118    *
119    *  \param user        The core user
120    *  \param networkId   The network to delete
121    *  \return true if successfull.
122    */
123   static inline bool removeNetwork(UserId user, const NetworkId &networkId) {
124     return instance()->storage->removeNetwork(user, networkId);
125   }
126
127   //! Returns a list of all NetworkInfos for the given UserId user
128   /** \note This method is thredsafe.
129    *
130    *  \param user        The core user
131    *  \return QList<NetworkInfo>.
132    */
133   static inline QList<NetworkInfo> networks(UserId user) {
134     return instance()->storage->networks(user);
135   }
136
137   //! Get the NetworkId for a network name.
138   /** \note This method is threadsafe.
139    *
140    *  \param user    The core user
141    *  \param network The name of the network
142    *  \return The NetworkId corresponding to the given network.
143    */
144   static inline NetworkId networkId(UserId user, const QString &network) {
145     return instance()->storage->getNetworkId(user, network);
146   }
147
148   //! Get a list of Networks to restore
149   /** Return a list of networks the user was connected at the time of core shutdown
150    *  \note This method is threadsafe.
151    *
152    *  \param user  The User Id in question
153    */
154   static inline QList<NetworkId> connectedNetworks(UserId user) {
155     return instance()->storage->connectedNetworks(user);
156   }
157
158   //! Update the connected state of a network
159   /** \note This method is threadsafe
160    *
161    *  \param user        The Id of the networks owner
162    *  \param networkId   The Id of the network
163    *  \param isConnected whether the network is connected or not
164    */
165   static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) {
166     return instance()->storage->setNetworkConnected(user, networkId, isConnected);
167   }
168
169   //! Get a hash of channels with their channel keys for a given network
170   /** The keys are channel names and values are passwords (possibly empty)
171    *  \note This method is threadsafe
172    *
173    *  \param user       The id of the networks owner
174    *  \param networkId  The Id of the network
175    */
176   static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId) {
177     return instance()->storage->persistentChannels(user, networkId);
178   }
179
180   //! Update the connected state of a channel
181   /** \note This method is threadsafe
182    *
183    *  \param user       The Id of the networks owner
184    *  \param networkId  The Id of the network
185    *  \param channel    The name of the channel
186    *  \param isJoined   whether the channel is connected or not
187    */
188   static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) {
189     return instance()->storage->setChannelPersistent(user, networkId, channel, isJoined);
190   }
191
192   //! Update the key of a channel
193   /** \note This method is threadsafe
194    *
195    *  \param user       The Id of the networks owner
196    *  \param networkId  The Id of the network
197    *  \param channel    The name of the channel
198    *  \param key        The key of the channel (possibly empty)
199    */
200   static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) {
201     return instance()->storage->setPersistentChannelKey(user, networkId, channel, key);
202   }
203
204   //! Get the unique BufferInfo for the given combination of network and buffername for a user.
205   /** \note This method is threadsafe.
206    *
207    *  \param user      The core user who owns this buffername
208    *  \param networkId The network id
209    *  \param type      The type of the buffer (StatusBuffer, Channel, etc.)
210    *  \param buffer    The buffer name (if empty, the net's status buffer is returned)
211    *  \param create    Whether or not the buffer should be created if it doesnt exist
212    *  \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
213    */
214   static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) {
215     return instance()->storage->bufferInfo(user, networkId, type, buffer, create);
216   }
217
218   //! Get the unique BufferInfo for a bufferId
219   /** \note This method is threadsafe
220    *  \param user      The core user who owns this buffername
221    *  \param bufferId  The id of the buffer
222    *  \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
223    */
224   static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) {
225     return instance()->storage->getBufferInfo(user, bufferId);
226   }
227
228   //! Store a Message in the backlog.
229   /** \note This method is threadsafe.
230    *
231    *  \param msg  The message object to be stored
232    *  \return The globally unique id for the stored message
233    */
234   static inline MsgId storeMessage(const Message &message) {
235     return instance()->storage->logMessage(message);
236   }
237
238   //! Request a certain number messages stored in a given buffer.
239   /** \param buffer   The buffer we request messages from
240    *  \param first    if != -1 return only messages with a MsgId >= first
241    *  \param last     if != -1 return only messages with a MsgId < last
242    *  \param limit    if != -1 limit the returned list to a max of \limit entries
243    *  \return The requested list of messages
244    */
245   static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) {
246     return instance()->storage->requestMsgs(user, bufferId, first, last, limit);
247   }
248
249   //! Request a certain number of messages across all buffers
250   /** \param first    if != -1 return only messages with a MsgId >= first
251    *  \param last     if != -1 return only messages with a MsgId < last
252    *  \param limit    Max amount of messages
253    *  \return The requested list of messages
254    */
255   static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) {
256     return instance()->storage->requestAllMsgs(user, first, last, limit);
257   }
258
259   //! Request a list of all buffers known to a user.
260   /** This method is used to get a list of all buffers we have stored a backlog from.
261    *  \note This method is threadsafe.
262    *
263    *  \param user  The user whose buffers we request
264    *  \return A list of the BufferInfos for all buffers as requested
265    */
266   static inline QList<BufferInfo> requestBuffers(UserId user) {
267     return instance()->storage->requestBuffers(user);
268   }
269
270   //! Request a list of BufferIds for a given NetworkId
271   /** \note This method is threadsafe.
272    *
273    *  \param user  The user whose buffers we request
274    *  \param networkId  The NetworkId of the network in question
275    *  \return List of BufferIds belonging to the Network
276    */
277   static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId) {
278     return instance()->storage->requestBufferIdsForNetwork(user, networkId);
279   }
280
281   //! Remove permanently a buffer and it's content from the storage backend
282   /** This call cannot be reverted!
283    *  \note This method is threadsafe.
284    *
285    *  \param user      The user who is the owner of the buffer
286    *  \param bufferId  The bufferId
287    *  \return true if successfull
288    */
289   static inline bool removeBuffer(const UserId &user, const BufferId &bufferId) {
290     return instance()->storage->removeBuffer(user, bufferId);
291   }
292
293   //! Rename a Buffer
294   /** \note This method is threadsafe.
295    *  \param user      The id of the buffer owner
296    *  \param bufferId  The bufferId
297    *  \param newName   The new name of the buffer
298    *  \return true if successfull
299    */
300   static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) {
301     return instance()->storage->renameBuffer(user, bufferId, newName);
302   }
303
304   //! Merge the content of two Buffers permanently. This cannot be reversed!
305   /** \note This method is threadsafe.
306    *  \param user      The id of the buffer owner
307    *  \param bufferId1 The bufferId of the remaining buffer
308    *  \param bufferId2 The buffer that is about to be removed
309    *  \return true if successfulln
310    */
311   static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) {
312     return instance()->storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
313   }
314
315   //! Update the LastSeenDate for a Buffer
316   /** This Method is used to make the LastSeenDate of a Buffer persistent
317    *  \note This method is threadsafe.
318    *
319    * \param user      The Owner of that Buffer
320    * \param bufferId  The buffer id
321    * \param MsgId     The Message id of the message that has been just seen
322    */
323   static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) {
324     return instance()->storage->setBufferLastSeenMsg(user, bufferId, msgId);
325   }
326
327   //! Get a Hash of all last seen message ids
328   /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
329    *  \note This method is threadsafe.
330    *
331    * \param user      The Owner of the buffers
332    */
333   static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) {
334     return instance()->storage->bufferLastSeenMsgIds(user);
335   }
336
337   const QDateTime &startTime() const { return _startTime; }
338
339   static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
340
341 public slots:
342   //! Make storage data persistent
343   /** \note This method is threadsafe.
344    */
345   void syncStorage();
346   void setupInternalClientSession(SignalProxy *proxy);
347 signals:
348   //! Sent when a BufferInfo is updated in storage.
349   void bufferInfoUpdated(UserId user, const BufferInfo &info);
350
351   //! Relay From CoreSession::sessionState(const QVariant &). Used for internal connection only
352   void sessionState(const QVariant &);
353
354 private slots:
355   bool startListening();
356   void stopListening(const QString &msg = QString());
357   void incomingConnection();
358   void clientHasData();
359   void clientDisconnected();
360
361   bool initStorage(QVariantMap dbSettings, bool setup = false);
362
363 #ifdef HAVE_SSL
364   void sslErrors(const QList<QSslError> &errors);
365 #endif
366   void socketError(QAbstractSocket::SocketError);
367
368 private:
369   Core();
370   ~Core();
371   void init();
372   static Core *instanceptr;
373
374   SessionThread *createSession(UserId userId, bool restoreState = false);
375   void setupClientSession(QTcpSocket *socket, UserId uid);
376   void processClientMessage(QTcpSocket *socket, const QVariantMap &msg);
377   //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
378   QString setupCoreForInternalUsage();
379   QString setupCore(QVariantMap setupData);
380
381   bool registerStorageBackend(Storage *);
382   void unregisterStorageBackend(Storage *);
383
384   QHash<UserId, SessionThread *> sessions;
385   Storage *storage;
386   QTimer _storageSyncTimer;
387
388 #ifdef HAVE_SSL
389   SslServer _server, _v6server;
390 #else
391   QTcpServer _server, _v6server;
392 #endif
393
394   QHash<QTcpSocket *, quint32> blocksizes;
395   QHash<QTcpSocket *, QVariantMap> clientInfo;
396
397   QHash<QString, Storage *> _storageBackends;
398
399   QDateTime _startTime;
400
401   bool configured;
402 };
403
404 #endif