File: pepchangenotifyplugin.cpp

package info (click to toggle)
psi-plugins 1.5-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 4,368 kB
  • sloc: cpp: 42,063; xml: 714; ansic: 84; makefile: 61; sh: 12
file content (585 lines) | stat: -rw-r--r-- 17,009 bytes parent folder | download
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*
 * pepchangenotifyplugin.cpp - plugin
 * Copyright (C) 2010  Evgeny Khryukin
 *
 * 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; either version 2
 * of the License, or (at your option) any later version.
 *
 * 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 library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

#include <QFileDialog>
#include <QDomElement>
#ifndef HAVE_QT5
#include <QTextDocument>
#endif
#include "psiplugin.h"
#include "stanzafilter.h"
#include "accountinfoaccessor.h"
#include "accountinfoaccessinghost.h"
#include "optionaccessor.h"
#include "optionaccessinghost.h"
#include "popupaccessor.h"
#include "popupaccessinghost.h"
#include "plugininfoprovider.h"
#include "applicationinfoaccessinghost.h"
#include "applicationinfoaccessor.h"
#include "contactinfoaccessor.h"
#include "contactinfoaccessinghost.h"
#include "iconfactoryaccessinghost.h"
#include "iconfactoryaccessor.h"
#include "soundaccessinghost.h"
#include "soundaccessor.h"

#include "ui_options.h"

#define cVer "0.1.0"
#define constSoundFile "sndfl"
#define constInterval "intrvl"
#define constTune "tune"
#define constMood "mood"
#define constActivity "act"
//#define constGeoloc "geo"
#define constDisableDnd "dsbldnd"
#define constContactDelay "contactdelay"

#define POPUP_OPTION_NAME "PEP Change Notify Plugin"

//delays in secconds
const int connectDelay = 30;

class PepPlugin: public QObject, public PsiPlugin, public StanzaFilter, public AccountInfoAccessor,
			public OptionAccessor, public PopupAccessor, public PluginInfoProvider, public SoundAccessor,
			public ApplicationInfoAccessor, public ContactInfoAccessor, public IconFactoryAccessor
{
	Q_OBJECT
#ifdef HAVE_QT5
	Q_PLUGIN_METADATA(IID "com.psi-plus.PepPlugin")
#endif
	Q_INTERFACES(PsiPlugin StanzaFilter AccountInfoAccessor OptionAccessor PopupAccessor SoundAccessor
		     PluginInfoProvider ApplicationInfoAccessor ContactInfoAccessor IconFactoryAccessor)

public:
	PepPlugin();
	virtual QString name() const;
	virtual QString shortName() const;
	virtual QString version() const;
        virtual QWidget* options();
	virtual bool enable();
        virtual bool disable();
        virtual void applyOptions();
        virtual void restoreOptions();
        virtual bool incomingStanza(int account, const QDomElement& xml);
	virtual bool outgoingStanza(int account, QDomElement& xml);
        virtual void setAccountInfoAccessingHost(AccountInfoAccessingHost* host);
        virtual void setOptionAccessingHost(OptionAccessingHost* host);
	virtual void optionChanged(const QString& /*option*/) {};
        virtual void setPopupAccessingHost(PopupAccessingHost* host);
	virtual void setApplicationInfoAccessingHost(ApplicationInfoAccessingHost* host);
	virtual void setContactInfoAccessingHost(ContactInfoAccessingHost* host);
	virtual void setIconFactoryAccessingHost(IconFactoryAccessingHost* host);
	virtual void setSoundAccessingHost(SoundAccessingHost* host);
	virtual QString pluginInfo();
	virtual QPixmap icon() const;


private:
        bool enabled;
        OptionAccessingHost* psiOptions;
	AccountInfoAccessingHost *accInfoHost;
        PopupAccessingHost* popup;
	ApplicationInfoAccessingHost* appInfo;
	ContactInfoAccessingHost* contactInfo;
	IconFactoryAccessingHost* iconHost;
	SoundAccessingHost* sound_;
	QString soundFile;
	//int interval;
	int delay;
	bool showMood, showTune, showActivity;//, showGeoloc;
	bool disableDnd;
	int popupId;
	QPointer<QWidget> options_;
	Ui::Options ui_;

	struct ContactState
	{
		ContactState(const QString& j = QString())
		{
			jid = j;
		}
		enum Event {
			EventTune,
			EventMood,
			EventActivity
			//,EventGeolocation
		};
		QString jid;
		QMap<Event, QTime> events;
		bool operator==(const ContactState& s)
		{
			return jid == s.jid;
		}
	};
	QList<ContactState> states_;
	QHash<int, QTime> lastConnectionTime_; // <int account, QTime connection_time>
	QHash<QString, QTime> contactsOnlineTime_; // <JID, time when contact goes online>

	QList<ContactState>::iterator findContactStateIndex(const QString& jid);
	bool checkContactState(QList<ContactState>::iterator it, ContactState::Event e);
	bool checkContactStatus(const QString& jid);
	bool processJid(const QString& jid, ContactState::Event e);
	void playSound(const QString& soundFile);
	void showPopup(const QString& title, const QString& text, const QString& icon);
	QDomElement getFirstChildElement(const QDomElement& elem);

private slots:
        void checkSound();
        void getSound();
	void doNotification(const QString& title, const QString& text, const QString& icon);
    };

#ifndef HAVE_QT5
Q_EXPORT_PLUGIN(PepPlugin);
#endif

PepPlugin::PepPlugin()
	: enabled(false)
	, psiOptions(0)
	, accInfoHost(0)
	, popup(0)
	, appInfo(0)
	, contactInfo(0)
	, iconHost(0)
	, sound_(0)
	, soundFile("sound/pepnotify.wav")
	//, interval(5)
	, delay(60)
	, showMood(false)
	, showTune(true)
	, showActivity(false)
//	, showGeoloc(false)
	, disableDnd(false)
	, popupId(0)
{
}

QString PepPlugin::name() const
{
	return "PEP Change Notify Plugin";
}

QString PepPlugin::shortName() const
{
	return "pepplugin";
}

QString PepPlugin::version() const
{
	return cVer;
}

bool PepPlugin::enable()
{
	states_.clear();
	lastConnectionTime_.clear();
	contactsOnlineTime_.clear();
	if(psiOptions) {
		enabled = true;
		soundFile = psiOptions->getPluginOption(constSoundFile, QVariant(soundFile)).toString();
		showMood = psiOptions->getPluginOption(constMood, QVariant(showMood)).toBool();
		showTune = psiOptions->getPluginOption(constTune, QVariant(showTune)).toBool();
		showActivity = psiOptions->getPluginOption(constActivity, QVariant(showActivity)).toBool();
//		showGeoloc = psiOptions->getPluginOption(constGeoloc, QVariant(showGeoloc)).toBool();
		disableDnd = psiOptions->getPluginOption(constDisableDnd, QVariant(disableDnd)).toBool();
		delay = psiOptions->getPluginOption(constContactDelay, QVariant(delay)).toInt();

		int interval = psiOptions->getPluginOption(constInterval, QVariant(5000)).toInt()/1000;
		popupId = popup->registerOption(POPUP_OPTION_NAME, interval, "plugins.options."+shortName()+"."+constInterval);
	}
	return enabled;
}

bool PepPlugin::disable()
{
	states_.clear();
	lastConnectionTime_.clear();
	contactsOnlineTime_.clear();
	popup->unregisterOption(POPUP_OPTION_NAME);
	enabled = false;
	return true;
}

QWidget* PepPlugin::options()
{
	if(!enabled)
		return 0;

	options_ = new QWidget();
	ui_.setupUi(options_);

	ui_.cb_geoloc->setVisible(false); //FIXME

	ui_.pb_check->setIcon(iconHost->getIcon("psi/play"));
	ui_.pb_get->setIcon(iconHost->getIcon("psi/browse"));

	connect(ui_.pb_check, SIGNAL(clicked()), SLOT(checkSound()));
	connect(ui_.pb_get, SIGNAL(clicked()), SLOT(getSound()));

	restoreOptions();

	return options_;
}

bool PepPlugin::incomingStanza(int account, const QDomElement& stanza)
{
	if (enabled) {
		if(stanza.tagName() == "presence") {
			QString type = stanza.attribute("type");
			QString jid = stanza.attribute("from").split("/").first().toLower();
			if(type == "unavailable") {
				contactsOnlineTime_.remove(jid);
			}
			else if(!contactsOnlineTime_.contains(jid)) {
				contactsOnlineTime_.insert(jid, QTime::currentTime());
			}
			return false;
		}

		if(stanza.tagName() == "message") {
			if(lastConnectionTime_.value(account).secsTo(QTime::currentTime()) < connectDelay) {
				return false;
			}
			if(disableDnd && accInfoHost->getStatus(account) == "dnd") {
				return false;
			}

			QString jid = stanza.attribute("from").split("/").first().toLower();
			if(jid == accInfoHost->getJid(account).toLower())
				return false;

			QDomElement event = stanza.firstChildElement("event");
			if(!event.isNull() && event.attribute("xmlns").contains("http://jabber.org/protocol/pubsub")) {
				QDomElement items = event.firstChildElement("items");
				if(items.isNull())
					return false;
				QDomElement item = items.firstChildElement("item");
				if(item.isNull())
					return false;

				if(showTune) {
					QDomElement tune = item.firstChildElement("tune");
					if(!tune.isNull()
					 && tune.attribute("xmlns") == "http://jabber.org/protocol/tune") {
						if(!processJid(jid, ContactState::EventTune)) {
							return false;
						}
						QString artist = tune.firstChildElement("artist").text();
						QString title = tune.firstChildElement("title").text();
						if(!artist.isEmpty() || !title.isEmpty()) {
							QString str = tr("Now listening: ");
							if(artist.isEmpty()) {
								str += title;
							}
							else {
								str += artist;
								if(!title.isEmpty()) {
									str += " - " + title;
								}
							}
							QMetaObject::invokeMethod(this, "doNotification", Qt::QueuedConnection,
										  Q_ARG(const QString&, contactInfo->name(account, jid)),
										  Q_ARG(const QString&, str),
										  Q_ARG(const QString&, "pep/tune"));
						}
						return false;
					}
				}
				if(showMood) {
					QDomElement mood = item.firstChildElement("mood");
					if(!mood.isNull()
					 && mood.attribute("xmlns") == "http://jabber.org/protocol/mood") {
						if(!processJid(jid, ContactState::EventMood)) {
							return false;
						}

						QString type = getFirstChildElement(mood).tagName();
						if(!type.isEmpty()) {
							QString text = mood.firstChildElement("text").text();
							QString str = tr("Mood changed to \"%1").arg(type);
							if(!text.isEmpty()) {
								str += ": " + text;
							}
							str += "\"";
							QMetaObject::invokeMethod(this, "doNotification", Qt::QueuedConnection,
										  Q_ARG(const QString&, contactInfo->name(account, jid)),
										  Q_ARG(const QString&, str),
										  Q_ARG(const QString&, "mood/"+type));
						}
						return false;
					}
				}
				if(showActivity) {
					QDomElement act = item.firstChildElement("activity");
					if(!act.isNull()
					 && act.attribute("xmlns") == "http://jabber.org/protocol/activity") {
						if(!processJid(jid, ContactState::EventActivity)) {
							return false;
						}

						QString icon;
						QString type, secType;
						QDomElement t = getFirstChildElement(act);
						if(!t.isNull()) {
							icon = type = t.tagName();
							secType = getFirstChildElement(t).tagName();
							if(!secType.isEmpty())
								icon += "_"+secType;
						}
						if(!type.isEmpty()) {
							QString text = act.firstChildElement("text").text();
							QString str = tr("Activity changed to \"%1").arg(type);
							if(!secType.isEmpty()) {
								str += " - " + secType;
							}
							if(!text.isEmpty()) {
								str += ": " + text;
							}
							str += "\"";
							QMetaObject::invokeMethod(this, "doNotification", Qt::QueuedConnection,
										  Q_ARG(const QString&, contactInfo->name(account, jid)),
										  Q_ARG(const QString&, str),
										  Q_ARG(const QString&, "activities/"+icon));
						}
						return false;
					}
				}
			}
		}
	}
	return false;
 }

bool PepPlugin::outgoingStanza(int account, QDomElement &xml)
{
	if(enabled) {
		if(xml.tagName() == "iq"
		   && xml.attribute("type") == "set"
		   && !xml.firstChildElement("session").isNull()) {
			lastConnectionTime_.insert(account, QTime::currentTime());
		}
	}

	return false;
}

void PepPlugin::applyOptions()
{
	if(!options_)
		return;

	soundFile = ui_.le_sound->text();
	psiOptions->setPluginOption(constSoundFile, QVariant(soundFile));

//	interval = ui_.sb_interval->value();
//	psiOptions->setPluginOption(constInterval, QVariant(interval));

	showActivity = ui_.cb_activity->isChecked();
	psiOptions->setPluginOption(constActivity, QVariant(showActivity));

//	showGeoloc = ui_.cb_geoloc->isChecked();
//	psiOptions->setPluginOption(constGeoloc, QVariant(showGeoloc));

	showMood = ui_.cb_mood->isChecked();
	psiOptions->setPluginOption(constMood, QVariant(showMood));

	showTune = ui_.cb_tune->isChecked();
	psiOptions->setPluginOption(constTune, QVariant(showTune));

	disableDnd = ui_.cb_disable_dnd->isChecked();
	psiOptions->setPluginOption(constDisableDnd, QVariant(disableDnd));

	delay = ui_.sb_delay->value();
	psiOptions->setPluginOption(constContactDelay, QVariant(delay));
}

void PepPlugin::restoreOptions()
{
	if(!options_)
		return;

	ui_.le_sound->setText(soundFile);
//	ui_.sb_interval->setValue(interval);
	ui_.cb_activity->setChecked(showActivity);
//	ui_.cb_geoloc->setChecked(showGeoloc);
	ui_.cb_mood->setChecked(showMood);
	ui_.cb_tune->setChecked(showTune);
	ui_.cb_disable_dnd->setChecked(disableDnd);
	ui_.sb_delay->setValue(delay);
}

void PepPlugin::setAccountInfoAccessingHost(AccountInfoAccessingHost* host)
{
	accInfoHost = host;
}

void PepPlugin::setOptionAccessingHost(OptionAccessingHost* host)
{
	psiOptions = host;
}

void PepPlugin::setPopupAccessingHost(PopupAccessingHost* host)
{
	popup = host;
}

void PepPlugin::setApplicationInfoAccessingHost(ApplicationInfoAccessingHost *host)
{
	appInfo = host;
}

void PepPlugin::setContactInfoAccessingHost(ContactInfoAccessingHost *host)
{
	contactInfo = host;
}

void PepPlugin::setIconFactoryAccessingHost(IconFactoryAccessingHost *host)
{
	iconHost = host;
}

void PepPlugin::setSoundAccessingHost(SoundAccessingHost *host)
{
	sound_ = host;
}

void PepPlugin::playSound(const QString& f)
{
	sound_->playSound(f);
}

void PepPlugin::getSound()
{
	QString fileName = QFileDialog::getOpenFileName(0,tr("Choose a sound file"),"", tr("Sound (*.wav)"));
	if(fileName.isEmpty())
		return;
	ui_.le_sound->setText(fileName);
}

void PepPlugin::checkSound()
{
	playSound(ui_.le_sound->text());
}

void PepPlugin::showPopup(const QString &title, const QString &text, const QString& icon)
{
	QVariant suppressDnd = psiOptions->getGlobalOption("options.ui.notifications.passive-popups.suppress-while-dnd");
	psiOptions->setGlobalOption("options.ui.notifications.passive-popups.suppress-while-dnd", disableDnd);

	int interval = popup->popupDuration(POPUP_OPTION_NAME);
	if(interval) {
#ifdef HAVE_QT5
		popup->initPopup(text.toHtmlEscaped(), title.toHtmlEscaped(), icon, popupId);
#else
		popup->initPopup(Qt::escape(text), Qt::escape(title), icon, popupId);
#endif
	}
	psiOptions->setGlobalOption("options.ui.notifications.passive-popups.suppress-while-dnd", suppressDnd);
}

void PepPlugin::doNotification(const QString &title, const QString &text, const QString &icon)
{
	showPopup(title, text, icon);
	if(psiOptions->getGlobalOption("options.ui.notifications.sounds.enable").toBool()) {
		playSound(soundFile);
	}
}

QList<PepPlugin::ContactState>::iterator PepPlugin::findContactStateIndex(const QString &jid)
{
	QList<ContactState>::iterator it = states_.begin();
	ContactState s(jid);
	for(; it != states_.end(); ++it) {
		if(s == *it) {
			break;
		}
	}
	if(it == states_.end()) {
		it = states_.insert(--it, s);
	}
	return it;
}

bool PepPlugin::checkContactState(QList<ContactState>::iterator it, ContactState::Event e)
{
	QTime time = QTime::currentTime();
	if((*it).events.contains(e)) {
		QTime oldTime = (*it).events.value(e);
		if(oldTime.secsTo(time) < delay) {
			return false;
		}
	}
	(*it).events.insert(e, time);
	return true;
}

bool PepPlugin::checkContactStatus(const QString& jid)
{
	if(!contactsOnlineTime_.contains(jid)) {//такое может произойти, если плагин включили, когда аккаунт уже был в онлайне
		return true;			//а вообще, ивенты от контактов не должны приходить раньше презенсов.
	}					//если такое произойдет - таймаут не сработает
	QTime contactTime = contactsOnlineTime_.value(jid);
	return (contactTime.secsTo(QTime::currentTime()) < delay) ? false : true;
}

bool PepPlugin::processJid(const QString &jid, ContactState::Event e)
{
	if(!checkContactStatus(jid)) {
		return false;
	}
	QList<ContactState>::iterator it = findContactStateIndex(jid);
	if(!checkContactState(it, e)) {
		return false;
	}
	return true;
}

QDomElement PepPlugin::getFirstChildElement(const QDomElement &elem)
{
	QDomElement newElem;
	QDomNode node = elem.firstChild();
	while(!node.isNull()) {
		if(!node.isElement()) {
			node = node.nextSibling();
			continue;
		}

		newElem = node.toElement();
		break;
	}

	return newElem;
}

QString PepPlugin::pluginInfo()
{
	return tr("Author: ") +  "Dealer_WeARE\n"
			+ tr("Email: ") + "wadealer@gmail.com\n\n"
			+ tr("This plugin shows popup notifications when users from your roster changes their mood, tune or activity.");
}

QPixmap PepPlugin::icon() const
{
	return QPixmap(":/icons/pepchangenotify.png");
}

#include "pepchangenotifyplugin.moc"