summaryrefslogtreecommitdiffstats
path: root/pica-client/msguirouter.cpp
blob: 88a272c93637abc62dc4c5adfcb207381e1a2a1b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*
	(c) Copyright  2012 - 2018 Anton Sviridenko
	https://picapica.im

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, version 3.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
#include "msguirouter.h"
#include "dialogs/forgedcertdialog.h"
#include "history.h"
#include "mainwindow.h"
#include "accountswindow.h"
#include "picasystray.h"
#include "globals.h"
#include "sound.h"

/*
  этот класс должен обеспечивать связь между приёмом-отправкой сообщений и их отображением в пользовательском интерфейсе.
  Класс SkyNet отвечает только за прием и отправку сообщений, пересылку через сеть и работу с протоколом, ему пофиг,
  как они показываются юзеру. Данный класс должен работать с GUI, например, по приходу нового сообщения (через сигнал от
  класса SkyNet) либо помигать иконкой в трее, либо создать новое окно чата, либо развернуть уже имеющееся, либо помигать
  свернутым окном на таскбаре. Это поведение может настраиваться, настройки хранить в базе и загружать в конструкторе из
  базы sqlite. Например, данный класс должен управлять экземплярами ChatWindow, создавать новые при необходимости либо
  активировать имеющиеся.
 */
MsgUIRouter::MsgUIRouter(QObject *parent) :
	QObject(parent)
{
	connect(skynet, SIGNAL(MessageReceived(QByteArray, QString)), this, SLOT(msg_from_peer(QByteArray, QString)));
	connect(skynet, SIGNAL(UnableToDeliver(QByteArray, QString)), this, SLOT(delivery_failed(QByteArray, QString)));
	connect(skynet, SIGNAL(Delivered(QByteArray)), this, SLOT(delivered(QByteArray)));
	connect(skynet, SIGNAL(CertificateForged(QByteArray, QString, QString)), this, SLOT(scary_cert_message(QByteArray, QString, QString)));
	connect(skynet, SIGNAL(StatusMsg(QString, bool)), this, SLOT(notification(QString, bool)));
	connect(systray, SIGNAL(doubleclicked()), this, SLOT(trayicon_dclick()));
	connect(skynet, SIGNAL(ConnectionStatusUpdated(QByteArray,QString)), this, SLOT(update_status(QByteArray,QString)));

}

void MsgUIRouter::trayicon_dclick()
{
	if (mainwindow == NULL)
	{
		accwindow->showNormal();
		accwindow->activateWindow();
		accwindow->raise();
		return;
	}


	if (blinkqueue.isEmpty())
	{
		mainwindow->showNormal();
		mainwindow->activateWindow();
		mainwindow->raise();
	}
	else
	{
		QByteArray blinker_id = blinkqueue.takeFirst();

		if (chatwindows.contains(blinker_id))
		{
			chatwindows[blinker_id]->showNormal();
			chatwindows[blinker_id]->activateWindow();
			chatwindows[blinker_id]->raise();
		}

		if (blinkqueue.isEmpty())
		{
			systray->StopBlinking();
		}
	}
}

void MsgUIRouter::update_status(QByteArray peer_id, QString status)
{
	connstatus[peer_id] = status;

	if (chatwindows.contains(peer_id))
		chatwindows[peer_id]->update_status(status);
}

void MsgUIRouter::create_chatwindow(QByteArray peer_id)
{
	ChatWindow *cw;

	if (!connstatus.contains(peer_id))
		connstatus[peer_id] = QString(tr("Disconnected"));

	cw = new ChatWindow(peer_id, connstatus[peer_id]);

	chatwindows[peer_id] = cw;

	connect(cw, SIGNAL(msg_input(QString, ChatWindow*)), this, SLOT(msg_to_peer(QString, ChatWindow*)));
	connect(cw, SIGNAL(chatwindow_close(ChatWindow*)), this, SLOT(chatwindow_closed(ChatWindow*)));
	connect(cw, SIGNAL(contacts_update()), skynet, SIGNAL(ContactsUpdated()));
	connect(skynet, SIGNAL(ContactsUpdated()), cw, SLOT(set_peer_name()));

	cw->show();
}

void MsgUIRouter::msg_from_peer(QByteArray from, QString msg)
{
	Sound::play(snd_newmessage);

	if ( ! chatwindows.contains(from))
	{
		create_chatwindow(from);
	}

	chatwindows[from]->msg_from_peer(msg);

	if (!chatwindows[from]->isActiveWindow())
	{
		if (blinkqueue.isEmpty())
		{
			systray->StartBlinking();
			blinkqueue.append(from);
		}
		else if (!blinkqueue.contains(from))
		{
			blinkqueue.append(from);
		}

	}
}

void MsgUIRouter::msg_to_peer(QString msg, ChatWindow *sender_window)
{
	skynet->SendMessage(sender_window->getPeerId(), msg);

	if (!blinkqueue.isEmpty())
	{
		blinkqueue.removeAll(sender_window->getPeerId());
		if (blinkqueue.isEmpty())
		{
			systray->StopBlinking();
		}
	}
}

void MsgUIRouter::start_chat(QByteArray peer_id)
{
	if ( ! chatwindows.contains(peer_id))
	{
		create_chatwindow(peer_id);
	}
	else
	{
		chatwindows[peer_id]->showNormal();
		chatwindows[peer_id]->activateWindow();
		chatwindows[peer_id]->raise();
	}
}

void MsgUIRouter::chatwindow_closed(ChatWindow *sender_window)
{
	chatwindows.remove(sender_window->getPeerId());
}

void MsgUIRouter::delivery_failed(QByteArray to, QString msg)
{
//  if (chatwindows.contains(to))
//  {
//    chatwindows[to]->msg_informational(tr("failed to deliver"));
//  }
}

void MsgUIRouter::delivered(QByteArray to)
{
	if (chatwindows.contains(to))
	{
		chatwindows[to]->msg_delivered();
	}
	else
	{
		History h(config_dbname, Accounts::GetCurrentAccount().id);

		h.SetDelivered(to);
	}
}

void MsgUIRouter::scary_cert_message(QByteArray peer_id, QString received_cert, QString stored_cert)
{
	ForgedCertDialog fcd(peer_id, received_cert, stored_cert);
	fcd.exec();
}

void MsgUIRouter::notification(QString text, bool is_critical)
{
	if (mainwindow)
		mainwindow->AddNotification(text, is_critical);
}