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