File: birthdayreminderplugin.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 (549 lines) | stat: -rw-r--r-- 16,239 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
/*
 * birthdayreminderplugin.cpp - plugin
 * Copyright (C) 2009-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>

#include "psiplugin.h"
#include "stanzafilter.h"
#include "accountinfoaccessor.h"
#include "accountinfoaccessinghost.h"
#include "applicationinfoaccessor.h"
#include "applicationinfoaccessinghost.h"
#include "stanzasender.h"
#include "stanzasendinghost.h"
#include "optionaccessor.h"
#include "optionaccessinghost.h"
#include "popupaccessor.h"
#include "popupaccessinghost.h"
#include "iconfactoryaccessinghost.h"
#include "iconfactoryaccessor.h"
#include "plugininfoprovider.h"
#include "soundaccessinghost.h"
#include "soundaccessor.h"
#include "contactinfoaccessor.h"
#include "contactinfoaccessinghost.h"

#include "ui_options.h"

#define cVer "0.4.1"
#define constLastCheck "lstchck"
#define constDays "days"
#define constInterval "intrvl"
#define constTimeout "timeout"
#define constStartCheck "strtchck"
#define constCheckFromRoster "chckfrmrstr"
#define constLastUpdate "lstupdate"
#define constUpdateInterval "updtintvl"
#define constSoundFile "sndfl"

#define POPUP_OPTION_NAME  "Birthday Reminder Plugin"

static const QString id = "bdreminder_1";
static const QString dirName = "Birthdays";

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

	public:
	Reminder();
	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 setApplicationInfoAccessingHost(ApplicationInfoAccessingHost* host);
	virtual void setStanzaSendingHost(StanzaSendingHost *host);
	virtual void setOptionAccessingHost(OptionAccessingHost* host);
	virtual void optionChanged(const QString& ){}
	virtual void setPopupAccessingHost(PopupAccessingHost* host);
	virtual void setIconFactoryAccessingHost(IconFactoryAccessingHost* host);
	virtual void setSoundAccessingHost(SoundAccessingHost* host);
	virtual void setContactInfoAccessingHost(ContactInfoAccessingHost *host);
	virtual QString pluginInfo();
	virtual QPixmap icon() const;

private:
	QString checkBirthdays();
	QString bdaysDir() const;

private slots:
	void updateVCard();
	bool check();
	void clearCache();
	void getSound();
	void checkSound();
	void playSound(const QString&);
	void timeoutStopUpdate();

private:
	bool enabled;
	OptionAccessingHost *psiOptions;
	AccountInfoAccessingHost *accInfoHost;
	ApplicationInfoAccessingHost *appInfoHost;
	StanzaSendingHost *stanzaHost;
	PopupAccessingHost* popup;
	IconFactoryAccessingHost* icoHost;
	SoundAccessingHost* sound_;
	ContactInfoAccessingHost* contactInfo;
	QString lastCheck;
	int days_;
	int interval;
	//int timeout;
	bool startCheck;
	bool checkFromRoster;
	QString lastUpdate;
	int updateInterval;
	QString soundFile;
	bool updateInProgress;
	int popupId;

	QPointer<QWidget> options_;
	Ui::Options ui_;
};

#ifndef HAVE_QT5
Q_EXPORT_PLUGIN(Reminder)
#endif

Reminder::Reminder()
: enabled(false)
 , psiOptions(0)
 , accInfoHost(0)
 , appInfoHost(0)
 , stanzaHost(0)
 , popup(0)
 , icoHost(0)
 , lastCheck("1901010101")
 , days_(5)
 , interval(24)
//, timeout(15)
 , startCheck(true)
 , checkFromRoster(true)
 , lastUpdate("19010101")
 , updateInterval(30)
 , soundFile("sound/reminder.wav")
 , updateInProgress(false)
 , popupId(0)
{
}

QString Reminder::name() const {
	return "Birthday Reminder Plugin";
}

QString Reminder::shortName() const {
	return "reminder";
}

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

bool Reminder::enable() {
	if(!psiOptions)
		return enabled;

	QFile file(":/reminder/birthday.png");
	if ( file.open(QIODevice::ReadOnly) ) {
		QByteArray image = file.readAll();
		icoHost->addIcon("reminder/birthdayicon",image);
		file.close();
	} else {
		return enabled;
	}

	enabled = true;

	lastCheck = psiOptions->getPluginOption(constLastCheck, lastCheck).toString();
	days_ = psiOptions->getPluginOption(constDays, days_).toInt();
	interval = psiOptions->getPluginOption(constInterval, interval).toInt();
	startCheck = psiOptions->getPluginOption(constStartCheck, startCheck).toBool();
	checkFromRoster = psiOptions->getPluginOption(constCheckFromRoster, checkFromRoster).toBool();
	updateInterval = psiOptions->getPluginOption(constUpdateInterval, updateInterval).toInt();
	lastUpdate = psiOptions->getPluginOption(constLastUpdate, lastUpdate).toString();
	soundFile = psiOptions->getPluginOption(constSoundFile, QVariant(soundFile)).toString();

	int timeout = psiOptions->getPluginOption(constTimeout, QVariant(15000)).toInt()/1000;
	popupId = popup->registerOption(POPUP_OPTION_NAME, timeout, "plugins.options."+shortName()+"."+constTimeout);

	QDir dir(bdaysDir());
	if(!dir.exists()) {
		dir.cdUp();
		dir.mkdir(dirName);
		return enabled;
	}
	if(startCheck) {
		lastCheck = QDateTime::currentDateTime().toString("yyyyMMddhh");
		psiOptions->setPluginOption(constLastCheck, QVariant(lastCheck));
		QTimer::singleShot(4000, this, SLOT(check())); //необходимо для инициализации приложения
	}

	return enabled;
}

bool Reminder::disable() {
	enabled = false;
	popup->unregisterOption(POPUP_OPTION_NAME);
	return true;
}

QString Reminder::bdaysDir() const {
	static QString dir(appInfoHost->appVCardDir() + QDir::separator() + dirName);
	return dir;
}

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

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

	ui_.tb_get->setIcon(icoHost->getIcon("psi/browse"));
	ui_.tb_check->setIcon(icoHost->getIcon("psi/play"));


	connect(ui_.pb_update, SIGNAL(clicked()), SLOT(updateVCard()));
	connect(ui_.pb_check, SIGNAL(clicked()), SLOT(check()));
	connect(ui_.pb_clear_cache, SIGNAL(clicked()), SLOT(clearCache()));
	connect(ui_.tb_check, SIGNAL(clicked()), SLOT(checkSound()));
	connect(ui_.tb_get, SIGNAL(clicked()), SLOT(getSound()));

	restoreOptions();

	return options_;
}

bool Reminder::incomingStanza(int account, const QDomElement& stanza) {
	if (enabled) {
		if(stanza.tagName() == "iq" && stanza.attribute("id") == id) {
			QDomNode VCard = stanza.firstChild();
			QDomElement BDay = VCard.firstChildElement("BDAY");
			if(!BDay.isNull()) {
				QString Jid = stanza.attribute("from");
				QString Nick = contactInfo->name(account, Jid);
				if(Nick == Jid)
					Nick = VCard.firstChildElement("NICKNAME").text();
				QString Date = BDay.text();
				if(!Date.isEmpty()) {
					Jid.replace("@", "_at_");
					QFile file(bdaysDir() + QDir::separator() + Jid);
					if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
						QTextStream out(&file);
						out.setCodec("UTF-8");
						out.setGenerateByteOrderMark(false);
						out << Date << "__" << Nick << endl;
					}
				}
			}
			return true;
		}

		if(stanza.tagName() == "presence") {
			QDateTime cur = QDateTime::currentDateTime();
			if((lastCheck.toLong() + interval) <= cur.toString("yyyyMMddhh").toLong()) {
				lastCheck = QDateTime::currentDateTime().toString("yyyyMMddhh");
				psiOptions->setPluginOption(constLastCheck, QVariant(lastCheck));
				check();
			}
			if(updateInterval) {
				if((lastUpdate.toLong() + updateInterval) <= cur.toString("yyyyMMdd").toLong()) {
					lastUpdate = QDateTime::currentDateTime().toString("yyyyMMdd");
					psiOptions->setPluginOption(constLastUpdate, QVariant(lastUpdate));
					updateVCard();
				}
			}
		}
	}
	return false;
}

bool Reminder::outgoingStanza(int /*account*/, QDomElement& /*xml*/) {
	return false;
}

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

void Reminder::setApplicationInfoAccessingHost(ApplicationInfoAccessingHost* host) {
	appInfoHost = host;
}

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

	days_ = ui_.sb_start->value();
	psiOptions->setPluginOption(constDays, QVariant(days_));

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

	startCheck = ui_.cb_startupcheck->isChecked();
	psiOptions->setPluginOption(constStartCheck, QVariant(startCheck));

	checkFromRoster = ui_.cb_active_accounts->isChecked();
	psiOptions->setPluginOption(constCheckFromRoster, QVariant(checkFromRoster));

	updateInterval = ui_.sb_update_interval->value();
	psiOptions->setPluginOption(constUpdateInterval, QVariant(updateInterval));

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

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

	ui_.sb_start->setValue(days_);
	ui_.sb_check_interval->setValue(interval);
	ui_.cb_startupcheck->setChecked(startCheck);
	ui_.cb_active_accounts->setChecked(checkFromRoster);
	ui_.sb_update_interval->setValue(updateInterval);
	ui_.le_sound->setText(soundFile);
}

void Reminder::setStanzaSendingHost(StanzaSendingHost *host) {
	stanzaHost = host;
}

void Reminder::updateVCard() {
	if(enabled && !updateInProgress) {
		updateInProgress = true;
		const QString path = appInfoHost->appVCardDir();
		QDir dir(path);
		foreach (QString filename, dir.entryList(QDir::Files)) {
			QFile file(path + QDir::separator() + filename);
			if(file.open(QIODevice::ReadOnly)) {
				QTextStream in(&file);
				in.setCodec("UTF-8");
				QDomDocument doc;
				doc.setContent(in.readAll());
				QDomElement vCard = doc.documentElement();
				QDomElement BDay = vCard.firstChildElement("BDAY");
				if(!BDay.isNull()) {
					QString Nick = vCard.firstChildElement("NICKNAME").text();
					QString Date = BDay.text();
					if(!Date.isEmpty()) {
						filename.replace("%5f", "_");
						filename.replace("%2d", "-");
						filename.replace("%25", "%");
						filename.remove(".xml");
						QFile file(bdaysDir() + QDir::separator() + filename);
						if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
							QTextStream out(&file);
							out.setCodec("UTF-8");
							out.setGenerateByteOrderMark(false);
							out << Date << "__" << Nick << endl;
						}
					}
				}
			}
		}

		int accs = -1;
		while(1) {
			QStringList Jids = accInfoHost->getRoster(++accs);
			if(!Jids.isEmpty()) {
				if(Jids.first() == "-1") {
					break;
				}
				else if(accInfoHost->getStatus(accs) != "offline") {
					QString text = "<iq type=\"get\" to=\"%1\" id=\"%2\">"
					"<vCard xmlns=\"vcard-temp\" /></iq>";
					foreach(const QString& Jid, Jids) {
						stanzaHost->sendStanza(accs, text.arg(Jid, id));
					}
				}
			}
		}
		QTimer::singleShot(30000, this, SLOT(timeoutStopUpdate())); //30 секунд дольжно хватить, чтобы получить все vCard'ы
	}
}

void Reminder::timeoutStopUpdate() {
	updateInProgress = false;
}

QString Reminder::checkBirthdays() {
	if(!enabled)
		return QString();

	QSet<QString> Roster_;
	if(checkFromRoster) {
		int accs = -1;
		while(1) {
			QStringList Jids = accInfoHost->getRoster(++accs);
			if(!Jids.isEmpty()) {
				if(Jids.first() == "-1") {
					break;
				}
				else {
					Roster_ += Jids.toSet();
				}
			}
		}
	}

	QString CheckResult;
	foreach(QString jid, QDir(bdaysDir()).entryList(QDir::Files)) {
		if(jid.contains("_at_")) {
			QFile file(bdaysDir() + QDir::separator() + jid);
			if(file.open(QIODevice::ReadOnly)) {
				QTextStream in(&file);
				in.setCodec("UTF-8");
				QString line = in.readLine();
				QStringList fields = line.split("__");
				QString Date = fields.takeFirst();
				QString Nick = "";
				if(!fields.isEmpty()) {
					Nick = fields.takeFirst();
				}
				QDate Birthday = QDate::currentDate();
				if(Date.contains("-")) {
					Birthday = QDate::fromString(Date, "yyyy-MM-dd");
				}
				else if(Date.contains(".")) {
					Birthday = QDate::fromString(Date, "d.MM.yyyy");
				}
				else if(Date.contains("/")) {
					Birthday = QDate::fromString(Date, "d/MM/yyyy");
				}
				QDate current = QDate::currentDate();
				if(current != Birthday) {
					int years = current.year() - Birthday.year();
					Birthday = Birthday.addYears(years);
					int daysTo = current.daysTo(Birthday);
					QString days;
					days.setNum(daysTo);
					jid.replace("_at_", "@");
					if(!checkFromRoster || Roster_.contains(jid)) {
						if(daysTo == 0) {
							CheckResult += Nick + " (" + jid + ") " + tr("celebrates birthday today!""\n");
						}
						else if(daysTo <= days_ && daysTo > 0) {
							CheckResult += Nick + " (" + jid + ") " + tr("celebrates birthday in %n day(s)\n", "", daysTo);
						}
						else if(daysTo == -1) {
							CheckResult += Nick + " (" + jid + ") " + tr("celebrates birthday yesterday.\n");
						}
					}
				}
			}
		}
	}
	return CheckResult;
}

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

void Reminder::setIconFactoryAccessingHost(IconFactoryAccessingHost* host) {
	icoHost = host;
}

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

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

bool Reminder::check() {
	QString text = checkBirthdays();
	if(text.isEmpty())
		return false;
	text.chop(1);

	if(psiOptions->getGlobalOption("options.ui.notifications.sounds.enable").toBool())
		playSound(soundFile);

	text = text.replace("\n", "<br>");
	popup->initPopup(text, tr("Birthday Reminder"), "reminder/birthdayicon", popupId);


	return true;
}

void Reminder::clearCache() {
	QDir dir(bdaysDir());
	foreach(const QString& file, dir.entryList(QDir::Files)) {
		QFile File(bdaysDir() + QDir::separator() + file);
		if(File.open(QIODevice::ReadWrite)) {
			File.remove();
		}
	}
	lastUpdate = "19010101";
	psiOptions->setPluginOption(constLastUpdate, QVariant(lastUpdate));
}

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

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

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

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

QString Reminder::pluginInfo() {
	return tr("Author: ") +	 "Dealer_WeARE\n"
		 + tr("Email: ") + "wadealer@gmail.com\n\n"
		 + trUtf8("This plugin is designed to show reminders of upcoming birthdays.\n"
				  "The first time you install this plugin, you need to log on to all of your accounts, go to the plugin settings and click \"Update Birthdays\"."
				  "The plugin will then collect the information about the birthdays of all the users in your roster, but when the 'Use vCards cache' option is"
				  "selected, the users' vCards that are cached on your hard disk will be used. ");
}

QPixmap Reminder::icon() const
{
	return QPixmap(":/reminder/birthday.png");
}

#include "birthdayreminderplugin.moc"