Add rough instructions for synchronizing the i18n repository
[quassel.git] / src / client / client.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "client.h"
22
23 #include <cstdio>
24 #include <cstdlib>
25
26 #include "abstractmessageprocessor.h"
27 #include "abstractui.h"
28 #include "bufferinfo.h"
29 #include "buffermodel.h"
30 #include "buffersettings.h"
31 #include "buffersyncer.h"
32 #include "bufferviewconfig.h"
33 #include "bufferviewoverlay.h"
34 #include "clientaliasmanager.h"
35 #include "clientauthhandler.h"
36 #include "clientbacklogmanager.h"
37 #include "clientbufferviewmanager.h"
38 #include "clientidentity.h"
39 #include "clientignorelistmanager.h"
40 #include "clientirclisthelper.h"
41 #include "clienttransfermanager.h"
42 #include "clientuserinputhandler.h"
43 #include "coreaccountmodel.h"
44 #include "coreconnection.h"
45 #include "dccconfig.h"
46 #include "ircchannel.h"
47 #include "ircuser.h"
48 #include "message.h"
49 #include "messagemodel.h"
50 #include "network.h"
51 #include "networkconfig.h"
52 #include "networkmodel.h"
53 #include "quassel.h"
54 #include "signalproxy.h"
55 #include "transfermodel.h"
56 #include "util.h"
57
58 Client::Client(std::unique_ptr<AbstractUi> ui, QObject* parent)
59     : QObject(parent)
60     , Singleton<Client>(this)
61     , _signalProxy(new SignalProxy(SignalProxy::Client, this))
62     , _mainUi(std::move(ui))
63     , _networkModel(new NetworkModel(this))
64     , _bufferModel(new BufferModel(_networkModel))
65     , _backlogManager(new ClientBacklogManager(this))
66     , _bufferViewOverlay(new BufferViewOverlay(this))
67     , _coreInfo(new CoreInfo(this))
68     , _ircListHelper(new ClientIrcListHelper(this))
69     , _inputHandler(new ClientUserInputHandler(this))
70     , _transferModel(new TransferModel(this))
71     , _messageModel(_mainUi->createMessageModel(this))
72     , _messageProcessor(_mainUi->createMessageProcessor(this))
73     , _coreAccountModel(new CoreAccountModel(this))
74     , _coreConnection(new CoreConnection(this))
75 {
76 #ifdef EMBED_DATA
77     Q_INIT_RESOURCE(data);
78 #endif
79
80     connect(mainUi(), &AbstractUi::disconnectFromCore, this, &Client::disconnectFromCore);
81     connect(this, &Client::connected, mainUi(), &AbstractUi::connectedToCore);
82     connect(this, &Client::disconnected, mainUi(), &AbstractUi::disconnectedFromCore);
83
84     connect(this, &Client::networkRemoved, _networkModel, &NetworkModel::networkRemoved);
85     connect(this, &Client::networkRemoved, _messageProcessor, &AbstractMessageProcessor::networkRemoved);
86
87     connect(backlogManager(), &ClientBacklogManager::messagesReceived, _messageModel, &MessageModel::messagesReceived);
88     connect(coreConnection(), &CoreConnection::stateChanged, this, &Client::connectionStateChanged);
89
90     SignalProxy* p = signalProxy();
91
92     p->attachSlot(SIGNAL(displayMsg(Message)), this, &Client::recvMessage);
93     p->attachSlot(SIGNAL(displayStatusMsg(QString,QString)), this, &Client::recvStatusMsg);
94
95     p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, &NetworkModel::bufferUpdated);
96     p->attachSignal(inputHandler(), &ClientUserInputHandler::sendInput);
97     p->attachSignal(this, &Client::requestNetworkStates);
98
99     p->attachSignal(this, &Client::requestCreateIdentity, SIGNAL(createIdentity(Identity,QVariantMap)));
100     p->attachSignal(this, &Client::requestRemoveIdentity, SIGNAL(removeIdentity(IdentityId)));
101     p->attachSlot(SIGNAL(identityCreated(Identity)), this, &Client::coreIdentityCreated);
102     p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, &Client::coreIdentityRemoved);
103
104     p->attachSignal(this, &Client::requestCreateNetwork, SIGNAL(createNetwork(NetworkInfo,QStringList)));
105     p->attachSignal(this, &Client::requestRemoveNetwork, SIGNAL(removeNetwork(NetworkId)));
106     p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, &Client::coreNetworkCreated);
107     p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, &Client::coreNetworkRemoved);
108
109     p->attachSignal(this, &Client::requestPasswordChange, SIGNAL(changePassword(PeerPtr,QString,QString,QString)));
110     p->attachSlot(SIGNAL(passwordChanged(PeerPtr,bool)), this, &Client::corePasswordChanged);
111
112     p->attachSignal(this, &Client::requestKickClient, SIGNAL(kickClient(int)));
113     p->attachSlot(SIGNAL(disconnectFromCore()), this, &Client::disconnectFromCore);
114
115     p->synchronize(backlogManager());
116     p->synchronize(coreInfo());
117     p->synchronize(_ircListHelper);
118
119     coreAccountModel()->load();
120     coreConnection()->init();
121 }
122
123 Client::~Client()
124 {
125     disconnectFromCore();
126 }
127
128 AbstractUi* Client::mainUi()
129 {
130     return instance()->_mainUi.get();
131 }
132
133 bool Client::isCoreFeatureEnabled(Quassel::Feature feature)
134 {
135     return coreConnection()->peer() ? coreConnection()->peer()->hasFeature(feature) : false;
136 }
137
138 bool Client::isConnected()
139 {
140     return instance()->_connected;
141 }
142
143 bool Client::internalCore()
144 {
145     return currentCoreAccount().isInternal();
146 }
147
148 void Client::onDbUpgradeInProgress(bool inProgress)
149 {
150     emit dbUpgradeInProgress(inProgress);
151 }
152
153 void Client::onExitRequested(int exitCode, const QString& reason)
154 {
155     if (!reason.isEmpty()) {
156         qCritical() << reason;
157         emit exitRequested(reason);
158     }
159     QCoreApplication::exit(exitCode);
160 }
161
162 /*** Network handling ***/
163
164 QList<NetworkId> Client::networkIds()
165 {
166     return instance()->_networks.keys();
167 }
168
169 const Network* Client::network(NetworkId networkid)
170 {
171     if (instance()->_networks.contains(networkid))
172         return instance()->_networks[networkid];
173     else
174         return nullptr;
175 }
176
177 void Client::createNetwork(const NetworkInfo& info, const QStringList& persistentChannels)
178 {
179     emit instance()->requestCreateNetwork(info, persistentChannels);
180 }
181
182 void Client::removeNetwork(NetworkId id)
183 {
184     emit instance()->requestRemoveNetwork(id);
185 }
186
187 void Client::updateNetwork(const NetworkInfo& info)
188 {
189     Network* netptr = instance()->_networks.value(info.networkId, 0);
190     if (!netptr) {
191         qWarning() << "Update for unknown network requested:" << info;
192         return;
193     }
194     netptr->requestSetNetworkInfo(info);
195 }
196
197 void Client::addNetwork(Network* net)
198 {
199     net->setProxy(signalProxy());
200     signalProxy()->synchronize(net);
201     networkModel()->attachNetwork(net);
202     connect(net, &QObject::destroyed, instance(), &Client::networkDestroyed);
203     instance()->_networks[net->networkId()] = net;
204     emit instance()->networkCreated(net->networkId());
205 }
206
207 void Client::coreNetworkCreated(NetworkId id)
208 {
209     if (_networks.contains(id)) {
210         qWarning() << "Creation of already existing network requested!";
211         return;
212     }
213     auto* net = new Network(id, this);
214     addNetwork(net);
215 }
216
217 void Client::coreNetworkRemoved(NetworkId id)
218 {
219     if (!_networks.contains(id))
220         return;
221     Network* net = _networks.take(id);
222     emit networkRemoved(net->networkId());
223     net->deleteLater();
224 }
225
226 /*** Identity handling ***/
227
228 QList<IdentityId> Client::identityIds()
229 {
230     return instance()->_identities.keys();
231 }
232
233 const Identity* Client::identity(IdentityId id)
234 {
235     if (instance()->_identities.contains(id))
236         return instance()->_identities[id];
237     else
238         return nullptr;
239 }
240
241 void Client::createIdentity(const CertIdentity& id)
242 {
243     QVariantMap additional;
244     additional["KeyPem"] = id.sslKey().toPem();
245     additional["CertPem"] = id.sslCert().toPem();
246     emit instance()->requestCreateIdentity(id, additional);
247 }
248
249 void Client::updateIdentity(IdentityId id, const QVariantMap& ser)
250 {
251     Identity* idptr = instance()->_identities.value(id, 0);
252     if (!idptr) {
253         qWarning() << "Update for unknown identity requested:" << id;
254         return;
255     }
256     idptr->requestUpdate(ser);
257 }
258
259 void Client::removeIdentity(IdentityId id)
260 {
261     emit instance()->requestRemoveIdentity(id);
262 }
263
264 void Client::coreIdentityCreated(const Identity& other)
265 {
266     if (!_identities.contains(other.id())) {
267         auto* identity = new Identity(other, this);
268         _identities[other.id()] = identity;
269         identity->setInitialized();
270         signalProxy()->synchronize(identity);
271         emit identityCreated(other.id());
272     }
273     else {
274         qWarning() << tr("Identity already exists in client!");
275     }
276 }
277
278 void Client::coreIdentityRemoved(IdentityId id)
279 {
280     if (_identities.contains(id)) {
281         emit identityRemoved(id);
282         Identity* i = _identities.take(id);
283         i->deleteLater();
284     }
285 }
286
287 /*** User input handling ***/
288
289 void Client::userInput(const BufferInfo& bufferInfo, const QString& message)
290 {
291     // we need to make sure that AliasManager is ready before processing input
292     if (aliasManager() && aliasManager()->isInitialized())
293         inputHandler()->handleUserInput(bufferInfo, message);
294     else
295         instance()->_userInputBuffer.append(qMakePair(bufferInfo, message));
296 }
297
298 void Client::sendBufferedUserInput()
299 {
300     for (int i = 0; i < _userInputBuffer.count(); i++)
301         userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
302
303     _userInputBuffer.clear();
304 }
305
306 /*** core connection stuff ***/
307
308 void Client::connectionStateChanged(CoreConnection::ConnectionState state)
309 {
310     switch (state) {
311     case CoreConnection::Disconnected:
312         setDisconnectedFromCore();
313         break;
314     case CoreConnection::Synchronized:
315         setSyncedToCore();
316         break;
317     default:
318         break;
319     }
320 }
321
322 void Client::setSyncedToCore()
323 {
324     // create buffersyncer
325     Q_ASSERT(!_bufferSyncer);
326     _bufferSyncer = new BufferSyncer(this);
327     connect(bufferSyncer(), &BufferSyncer::lastSeenMsgSet, _networkModel, &NetworkModel::setLastSeenMsgId);
328     connect(bufferSyncer(), &BufferSyncer::markerLineSet, _networkModel, &NetworkModel::setMarkerLineMsgId);
329     connect(bufferSyncer(), &BufferSyncer::bufferRemoved, this, &Client::bufferRemoved);
330     connect(bufferSyncer(), &BufferSyncer::bufferRenamed, this, &Client::bufferRenamed);
331     connect(bufferSyncer(), &BufferSyncer::buffersPermanentlyMerged, this, &Client::buffersPermanentlyMerged);
332     connect(bufferSyncer(), &BufferSyncer::buffersPermanentlyMerged, _messageModel, &MessageModel::buffersPermanentlyMerged);
333     connect(bufferSyncer(), &BufferSyncer::bufferMarkedAsRead, this, &Client::bufferMarkedAsRead);
334     connect(bufferSyncer(), &BufferSyncer::bufferActivityChanged, _networkModel, &NetworkModel::bufferActivityChanged);
335     connect(bufferSyncer(), &BufferSyncer::highlightCountChanged, _networkModel, &NetworkModel::highlightCountChanged);
336     connect(networkModel(), &NetworkModel::requestSetLastSeenMsg, bufferSyncer(), &BufferSyncer::requestSetLastSeenMsg);
337
338     SignalProxy* p = signalProxy();
339     p->synchronize(bufferSyncer());
340
341     // create a new BufferViewManager
342     Q_ASSERT(!_bufferViewManager);
343     _bufferViewManager = new ClientBufferViewManager(p, this);
344     connect(_bufferViewManager, &SyncableObject::initDone, _bufferViewOverlay, &BufferViewOverlay::restore);
345
346     // create AliasManager
347     Q_ASSERT(!_aliasManager);
348     _aliasManager = new ClientAliasManager(this);
349     connect(aliasManager(), &SyncableObject::initDone, this, &Client::sendBufferedUserInput);
350     p->synchronize(aliasManager());
351
352     // create NetworkConfig
353     Q_ASSERT(!_networkConfig);
354     _networkConfig = new NetworkConfig("GlobalNetworkConfig", this);
355     p->synchronize(networkConfig());
356
357     // create IgnoreListManager
358     Q_ASSERT(!_ignoreListManager);
359     _ignoreListManager = new ClientIgnoreListManager(this);
360     p->synchronize(ignoreListManager());
361
362     // create Core-Side HighlightRuleManager
363     Q_ASSERT(!_highlightRuleManager);
364     _highlightRuleManager = new HighlightRuleManager(this);
365     p->synchronize(highlightRuleManager());
366     // Listen to network removed events
367     connect(this, &Client::networkRemoved, _highlightRuleManager, &HighlightRuleManager::networkRemoved);
368
369     /*  not ready yet
370         // create TransferManager and DccConfig if core supports them
371         Q_ASSERT(!_dccConfig);
372         Q_ASSERT(!_transferManager);
373         if (isCoreFeatureEnabled(Quassel::Feature::DccFileTransfer)) {
374             _dccConfig = new DccConfig(this);
375             p->synchronize(dccConfig());
376             _transferManager = new ClientTransferManager(this);
377             _transferModel->setManager(_transferManager);
378             p->synchronize(transferManager());
379         }
380     */
381
382     // trigger backlog request once all active bufferviews are initialized
383     connect(bufferViewOverlay(), &BufferViewOverlay::initDone, this, &Client::finishConnectionInitialization);
384
385     _connected = true;
386     emit connected();
387     emit coreConnectionStateChanged(true);
388 }
389
390 void Client::finishConnectionInitialization()
391 {
392     // usually it _should_ take longer until the bufferViews are initialized, so that's what
393     // triggers this slot. But we have to make sure that we know all buffers yet.
394     // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
395     if (!bufferSyncer()->isInitialized()) {
396         disconnect(bufferViewOverlay(), &BufferViewOverlay::initDone, this, &Client::finishConnectionInitialization);
397         connect(bufferSyncer(), &SyncableObject::initDone, this, &Client::finishConnectionInitialization);
398         return;
399     }
400     disconnect(bufferViewOverlay(), &BufferViewOverlay::initDone, this, &Client::finishConnectionInitialization);
401     disconnect(bufferSyncer(), &SyncableObject::initDone, this, &Client::finishConnectionInitialization);
402
403     requestInitialBacklog();
404     if (isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) {
405         bufferSyncer()->markActivitiesChanged();
406         bufferSyncer()->markHighlightCountsChanged();
407     }
408 }
409
410 void Client::requestInitialBacklog()
411 {
412     _backlogManager->requestInitialBacklog();
413 }
414
415 void Client::requestLegacyCoreInfo()
416 {
417     // On older cores, the CoreInfo object was only synchronized on demand.  Synchronize now if
418     // needed.
419     if (isConnected() && !isCoreFeatureEnabled(Quassel::Feature::SyncedCoreInfo)) {
420         // Delete the existing core info object (it will always exist as client is single-threaded)
421         _coreInfo->deleteLater();
422         // No need to set to null when creating new one immediately after
423
424         // Create a fresh, unsynchronized CoreInfo object, emulating legacy behavior of CoreInfo not
425         // persisting
426         _coreInfo = new CoreInfo(this);
427         // Synchronize the new object
428         signalProxy()->synchronize(_coreInfo);
429
430         // Let others know signal handlers have been reset
431         emit coreInfoResynchronized();
432     }
433 }
434
435 void Client::disconnectFromCore()
436 {
437     if (!coreConnection()->isConnected())
438         return;
439
440     coreConnection()->disconnectFromCore();
441 }
442
443 void Client::setDisconnectedFromCore()
444 {
445     _connected = false;
446
447     emit disconnected();
448     emit coreConnectionStateChanged(false);
449
450     backlogManager()->reset();
451     messageProcessor()->reset();
452
453     // Clear internal data. Hopefully nothing relies on it at this point.
454
455     if (_bufferSyncer) {
456         _bufferSyncer->deleteLater();
457         _bufferSyncer = nullptr;
458     }
459
460     _coreInfo->reset();
461
462     if (_bufferViewManager) {
463         _bufferViewManager->deleteLater();
464         _bufferViewManager = nullptr;
465     }
466
467     _bufferViewOverlay->reset();
468
469     if (_aliasManager) {
470         _aliasManager->deleteLater();
471         _aliasManager = nullptr;
472     }
473
474     if (_ignoreListManager) {
475         _ignoreListManager->deleteLater();
476         _ignoreListManager = nullptr;
477     }
478
479     if (_highlightRuleManager) {
480         _highlightRuleManager->deleteLater();
481         _highlightRuleManager = nullptr;
482     }
483
484     if (_transferManager) {
485         _transferModel->setManager(nullptr);
486         _transferManager->deleteLater();
487         _transferManager = nullptr;
488     }
489
490     if (_dccConfig) {
491         _dccConfig->deleteLater();
492         _dccConfig = nullptr;
493     }
494
495     // we probably don't want to save pending input for reconnect
496     _userInputBuffer.clear();
497
498     _messageModel->clear();
499     _networkModel->clear();
500
501     QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
502     while (netIter != _networks.end()) {
503         Network* net = netIter.value();
504         emit networkRemoved(net->networkId());
505         disconnect(net, &Network::destroyed, this, nullptr);
506         netIter = _networks.erase(netIter);
507         net->deleteLater();
508     }
509     Q_ASSERT(_networks.isEmpty());
510
511     QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
512     while (idIter != _identities.end()) {
513         emit identityRemoved(idIter.key());
514         Identity* id = idIter.value();
515         idIter = _identities.erase(idIter);
516         id->deleteLater();
517     }
518     Q_ASSERT(_identities.isEmpty());
519
520     if (_networkConfig) {
521         _networkConfig->deleteLater();
522         _networkConfig = nullptr;
523     }
524 }
525
526 /*** ***/
527
528 void Client::networkDestroyed()
529 {
530     auto* net = static_cast<Network*>(sender());
531     QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
532     while (netIter != _networks.end()) {
533         if (*netIter == net) {
534             netIter = _networks.erase(netIter);
535             break;
536         }
537         else {
538             ++netIter;
539         }
540     }
541 }
542
543 // Hmm... we never used this...
544 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/)
545 {
546     // recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
547 }
548
549 void Client::recvMessage(const Message& msg)
550 {
551     Message msg_ = msg;
552     messageProcessor()->process(msg_);
553 }
554
555 void Client::setBufferLastSeenMsg(BufferId id, const MsgId& msgId)
556 {
557     if (bufferSyncer())
558         bufferSyncer()->requestSetLastSeenMsg(id, msgId);
559 }
560
561 void Client::setMarkerLine(BufferId id, const MsgId& msgId)
562 {
563     if (bufferSyncer())
564         bufferSyncer()->requestSetMarkerLine(id, msgId);
565 }
566
567 MsgId Client::markerLine(BufferId id)
568 {
569     if (id.isValid() && networkModel())
570         return networkModel()->markerLineMsgId(id);
571     return {};
572 }
573
574 void Client::removeBuffer(BufferId id)
575 {
576     if (!bufferSyncer())
577         return;
578     bufferSyncer()->requestRemoveBuffer(id);
579 }
580
581 void Client::renameBuffer(BufferId bufferId, const QString& newName)
582 {
583     if (!bufferSyncer())
584         return;
585     bufferSyncer()->requestRenameBuffer(bufferId, newName);
586 }
587
588 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2)
589 {
590     if (!bufferSyncer())
591         return;
592     bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
593 }
594
595 void Client::purgeKnownBufferIds()
596 {
597     if (!bufferSyncer())
598         return;
599     bufferSyncer()->requestPurgeBufferIds();
600 }
601
602 void Client::bufferRemoved(BufferId bufferId)
603 {
604     // select a sane buffer (status buffer)
605     /* we have to manually select a buffer because otherwise inconsitent changes
606      * to the model might occur:
607      * the result of a buffer removal triggers a change in the selection model.
608      * the newly selected buffer might be a channel that hasn't been selected yet
609      * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
610      * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
611      */
612     QModelIndex current = bufferModel()->currentIndex();
613     if (current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
614         bufferModel()->setCurrentIndex(current.sibling(0, 0));
615     }
616
617     // and remove it from the model
618     networkModel()->removeBuffer(bufferId);
619 }
620
621 void Client::bufferRenamed(BufferId bufferId, const QString& newName)
622 {
623     QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
624     if (bufferIndex.isValid()) {
625         networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
626     }
627 }
628
629 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2)
630 {
631     QModelIndex idx = networkModel()->bufferIndex(bufferId1);
632     bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
633     networkModel()->removeBuffer(bufferId2);
634 }
635
636 void Client::markBufferAsRead(BufferId id)
637 {
638     if (bufferSyncer() && id.isValid())
639         bufferSyncer()->requestMarkBufferAsRead(id);
640 }
641
642 void Client::refreshLegacyCoreInfo()
643 {
644     instance()->requestLegacyCoreInfo();
645 }
646
647 void Client::changePassword(const QString& oldPassword, const QString& newPassword)
648 {
649     CoreAccount account = currentCoreAccount();
650     account.setPassword(newPassword);
651     coreAccountModel()->createOrUpdateAccount(account);
652     emit instance()->requestPasswordChange(nullptr, account.user(), oldPassword, newPassword);
653 }
654
655 void Client::kickClient(int peerId)
656 {
657     emit instance()->requestKickClient(peerId);
658 }
659
660 void Client::corePasswordChanged(PeerPtr, bool success)
661 {
662     if (success)
663         coreAccountModel()->save();
664     emit passwordChanged(success);
665 }