summaryrefslogtreecommitdiff
path: root/plugins/AutoShutdown/src/watcher.cpp
blob: fbd2987e8b0fe515d1c2df165f5be659432650d6 (plain)
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
/*

'AutoShutdown'-Plugin for Miranda IM

Copyright 2004-2007 H. Herkenrath

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 program (Shutdown-License.txt); if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "stdafx.h"

/* Msg Shutdown */
static HANDLE hHookEventAdded;
/* Transfer Shutdown */
static HANDLE hHookProtoAck;
/* Idle Shutdown */
static HANDLE hHookIdleChanged;
/* Status Shutdown */
static HANDLE hHookSettingChanged;
/* Weather Shutdown */
static HANDLE hHookWeatherUpdated;
/* Services */
static HANDLE hEventWatcherChanged;
/* Misc */
static HANDLE hHookModulesLoaded;

/************************* Shared *************************************/

static WORD currentWatcherType;

static void __stdcall MainThreadMapping(void *param)
{
	HANDLE *phDoneEvent = (HANDLE*)param;
	ServiceShutdown(0, TRUE); /* ensure main thread (for cpu usage shutdown) */
	ServiceStopWatcher(0, 0);
	if (*phDoneEvent != nullptr)
		SetEvent(*phDoneEvent);
}

static void __inline ShutdownAndStopWatcher(void)
{
	HANDLE hDoneEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
	CallFunctionAsync(MainThreadMapping, &hDoneEvent);
	if (hDoneEvent != nullptr) {
		WaitForSingleObject(hDoneEvent, INFINITE);
		CloseHandle(hDoneEvent);
	}
}

/************************* Msg Shutdown *******************************/

// ppBlob might get reallocated, must have been allocated using mir_alloc()
static wchar_t* GetMessageText(BYTE **ppBlob, DWORD *pcbBlob)
{
	(*ppBlob)[*pcbBlob] = 0;
	size_t cb = mir_strlen((char*)*ppBlob);
	/* use Unicode data if present */
	if (*pcbBlob > (cb + 3)) {
		(*ppBlob)[*pcbBlob - 1] = 0;
		return (WCHAR*)&(*ppBlob)[cb];
	}
	/* no Unicode data present, convert from ANSI */
	int len = MultiByteToWideChar(CP_ACP, 0, (char*)*ppBlob, -1, nullptr, 0);
	if (!len)
		return nullptr;

	BYTE *buf = (BYTE*)mir_realloc(*ppBlob, (*pcbBlob) + (len*sizeof(WCHAR)));
	if (buf == nullptr)
		return nullptr;

	*pcbBlob += len*sizeof(WCHAR);
	*ppBlob = buf;
	buf = &(*ppBlob)[cb];
	MultiByteToWideChar(CP_ACP, 0, (char*)*ppBlob, -1, (WCHAR*)buf, len);
	((WCHAR*)buf)[len - 1] = 0;
	return (WCHAR*)buf;
}

static int MsgEventAdded(WPARAM, LPARAM hDbEvent)
{
	if (currentWatcherType & SDWTF_MESSAGE) {
		DBEVENTINFO dbe = {};
		dbe.cbBlob = db_event_getBlobSize(hDbEvent);
		dbe.pBlob = (BYTE*)mir_alloc(dbe.cbBlob + 2); /* ensure term zero */
		if (dbe.pBlob == nullptr)
			return 0;
		if (!db_event_get(hDbEvent, &dbe))
			if (dbe.eventType == EVENTTYPE_MESSAGE && !(dbe.flags & DBEF_SENT)) {
				DBVARIANT dbv;
				if (!db_get_ws(NULL, MODULENAME, "Message", &dbv)) {
					TrimString(dbv.ptszVal);
					wchar_t *pszMsg = GetMessageText(&dbe.pBlob, &dbe.cbBlob);
					if (pszMsg != nullptr && wcsstr(pszMsg, dbv.ptszVal) != nullptr)
						ShutdownAndStopWatcher(); /* msg with specified text recvd */
					mir_free(dbv.ptszVal); /* does NULL check */
				}
			}
		mir_free(dbe.pBlob);
	}
	return 0;
}

/************************* Transfer Shutdown **************************/

static HANDLE *transfers;
static int nTransfersCount;

static int ProtoAck(WPARAM, LPARAM lParam)
{
	ACKDATA *ack = (ACKDATA*)lParam;
	if (ack->type != ACKTYPE_FILE)
		return 0;

	switch (ack->result) {
	case ACKRESULT_DATA:
		{
			for (int i = 0; i < nTransfersCount; ++i)
				if (transfers[i] == ack->hProcess)
					break; /* already in list */
			/* insert into list */
			HANDLE *buf = (HANDLE*)mir_realloc(transfers, (nTransfersCount + 1)*sizeof(HANDLE));
			if (buf != nullptr) {
				transfers = buf;
				transfers[nTransfersCount] = ack->hProcess;
				++nTransfersCount;
			}
			break;
		}
	case ACKRESULT_SUCCESS:
	case ACKRESULT_FAILED:
	case ACKRESULT_DENIED:
		for (int i = 0; i < nTransfersCount; ++i) {
			if (transfers[i] == ack->hProcess) {
				/* remove from list */
				if (i < (nTransfersCount - 1))
					memmove(&transfers[i], &transfers[i + 1], (nTransfersCount - i - 1)*sizeof(HANDLE));
				--nTransfersCount;
				HANDLE *buf = (HANDLE*)mir_realloc(transfers, nTransfersCount*sizeof(HANDLE));
				if (buf != nullptr) transfers = buf;
				else if (!nTransfersCount) transfers = nullptr;
				/* stop watcher */
				if (!nTransfersCount && (currentWatcherType&SDWTF_FILETRANSFER))
					ShutdownAndStopWatcher();
				break;
			}
		}
		break;
	}
	return 0;
}

/************************* Idle Shutdown ******************************/

static int IdleChanged(WPARAM, LPARAM lParam)
{
	if (currentWatcherType&SDWTF_IDLE && lParam&IDF_ISIDLE)
		ShutdownAndStopWatcher();
	return 0;
}

/************************* Status Shutdown ****************************/

static BOOL CheckAllContactsOffline(void)
{
	BOOL fSmartCheck, fAllOffline = TRUE; /* tentatively */
	fSmartCheck = db_get_b(NULL, MODULENAME, "SmartOfflineCheck", SETTING_SMARTOFFLINECHECK_DEFAULT);
	for (auto &hContact : Contacts()) {
		char *pszProto = GetContactProto(hContact);
		if (pszProto != nullptr && Proto_GetStatus(pszProto) != ID_STATUS_OFFLINE) {
			if (db_get_b(hContact, pszProto, "ChatRoom", 0)) continue;
			if (db_get_w(hContact, pszProto, "Status", 0) != ID_STATUS_OFFLINE) {
				if (fSmartCheck) {
					if (db_get_b(hContact, "CList", "Hidden", 0)) continue;
					if (db_get_b(hContact, "CList", "NotOnList", 0)) continue;
				}
				fAllOffline = FALSE;
				break;
			}
		}
	}
	return fAllOffline;
}

static int StatusSettingChanged(WPARAM wParam, LPARAM lParam)
{
	if (currentWatcherType&SDWTF_STATUS) {
		DBCONTACTWRITESETTING *dbcws = (DBCONTACTWRITESETTING*)lParam;
		if ((HANDLE)wParam != nullptr && dbcws->value.wVal == ID_STATUS_OFFLINE && !strcmp(dbcws->szSetting, "Status")) {
			char *pszProto = GetContactProto(wParam);
			if (pszProto != nullptr && !strcmp(dbcws->szModule, pszProto))
				if (CheckAllContactsOffline())
					ShutdownAndStopWatcher();
		}
	}
	return 0;
}

/************************* Cpu Shutdown *******************************/

static DWORD idCpuUsageThread;

static BOOL CALLBACK CpuUsageWatcherProc(BYTE nCpuUsage, LPARAM lParam)
{
	static BYTE nTimesBelow = 0; /* only one watcher thread */
	/* terminated? */
	if (idCpuUsageThread != GetCurrentThreadId()) {
		nTimesBelow = 0;
		return FALSE; /* stop poll thread */
	}
	/* ignore random peaks */
	if (nCpuUsage < (BYTE)lParam) ++nTimesBelow;
	else nTimesBelow = 0;
	if (nTimesBelow == 3) {
		nTimesBelow = 0;
		ShutdownAndStopWatcher();
		return FALSE; /* stop poll thread */
	}
	return TRUE;
}

/************************* Weather Shutdown ***************************/

static int WeatherUpdated(WPARAM wParam, LPARAM lParam)
{
	char *pszProto = GetContactProto(wParam);
	if ((BOOL)lParam && pszProto != nullptr && Proto_GetStatus(pszProto) == THUNDER)
		if (db_get_b(NULL, MODULENAME, "WeatherShutdown", SETTING_WEATHERSHUTDOWN_DEFAULT))
			ServiceShutdown(SDSDT_SHUTDOWN, TRUE);
	return 0;
}

/************************* Services ***********************************/

INT_PTR ServiceStartWatcher(WPARAM, LPARAM lParam)
{
	/* passing watcherType as lParam is only to be used internally, undocumented */
	if (lParam == 0)
		lParam = (LPARAM)db_get_w(NULL, MODULENAME, "WatcherFlags", 0);

	/* invalid flags or empty? */
	if (!(lParam&SDWTF_MASK))
		return 1;

	/* no specific time choice? */
	if (lParam&SDWTF_SPECIFICTIME && !(lParam&SDWTF_ST_MASK))
		return 2;

	if (currentWatcherType == (WORD)lParam)
		return 3;

	if (currentWatcherType != 0) {
		/* Time Shutdown */
		CloseCountdownFrame(); /* fails if not opened */
		/* Cpu Shutdown */
		idCpuUsageThread = 0;
	}
	SetShutdownMenuItem(true);
	SetShutdownToolbarButton(true);
	currentWatcherType = (WORD)lParam;
	NotifyEventHooks(hEventWatcherChanged, TRUE, 0);

	/* Time Shutdown */
	if (currentWatcherType&SDWTF_SPECIFICTIME)
		ShowCountdownFrame(currentWatcherType); /* after modules loaded */
	/* Cpu Shutdown */
	if (currentWatcherType&SDWTF_CPUUSAGE)
		idCpuUsageThread = PollCpuUsage(CpuUsageWatcherProc, (LPARAM)DBGetContactSettingRangedByte(NULL, MODULENAME, "CpuUsageThreshold", SETTING_CPUUSAGETHRESHOLD_DEFAULT, 1, 100), 1500);
	/* Transfer Shutdown */
	if (currentWatcherType&SDWTF_FILETRANSFER && !nTransfersCount)
		ShutdownAndStopWatcher();
	/* Status Shutdown */
	if (currentWatcherType&SDWTF_STATUS && CheckAllContactsOffline())
		ShutdownAndStopWatcher();
	return 0;
}

INT_PTR ServiceStopWatcher(WPARAM, LPARAM)
{
	if (currentWatcherType == 0) return 1;

	/* Time Shutdown */
	if (currentWatcherType&SDWTF_SPECIFICTIME)
		CloseCountdownFrame();
	/* Cpu Shutdown */
	idCpuUsageThread = 0;

	currentWatcherType = 0;
	SetShutdownMenuItem(FALSE);
	SetShutdownToolbarButton(FALSE);
	NotifyEventHooks(hEventWatcherChanged, FALSE, 0);
	return 0;
}

INT_PTR ServiceIsWatcherEnabled(WPARAM, LPARAM)
{
	return currentWatcherType != 0;
}

/************************* Misc ***********************************/

void WatcherModulesLoaded(void)
{
	/* Weather Shutdown */
	if (ServiceExists(MS_WEATHER_UPDATE))
		hHookWeatherUpdated = HookEvent(ME_WEATHER_UPDATED, WeatherUpdated);

	/* restore watcher if it was running on last exit */
	if (db_get_b(NULL, MODULENAME, "RememberOnRestart", 0) == SDROR_RUNNING) {
		db_set_b(NULL, MODULENAME, "RememberOnRestart", 1);
		ServiceStartWatcher(0, 0); /* after modules loaded */
	}
}

void InitWatcher(void)
{
	/* Shared */
	currentWatcherType = 0;
	/* Message Shutdown */
	hHookEventAdded = HookEvent(ME_DB_EVENT_ADDED, MsgEventAdded);
	/* Status Shutdown*/
	hHookSettingChanged = HookEvent(ME_DB_CONTACT_SETTINGCHANGED, StatusSettingChanged);
	/* Idle Shutdown */
	hHookIdleChanged = HookEvent(ME_IDLE_CHANGED, IdleChanged);
	/* Transfer Shutdown */
	transfers = nullptr;
	nTransfersCount = 0;
	hHookProtoAck = HookEvent(ME_PROTO_ACK, ProtoAck);
	/* Weather Shutdown */
	hHookWeatherUpdated = nullptr;
	/* Services */
	hEventWatcherChanged = CreateHookableEvent(ME_AUTOSHUTDOWN_WATCHERCHANGED);
	CreateServiceFunction(MS_AUTOSHUTDOWN_STARTWATCHER, ServiceStartWatcher);
	CreateServiceFunction(MS_AUTOSHUTDOWN_STOPWATCHER, ServiceStopWatcher);
	CreateServiceFunction(MS_AUTOSHUTDOWN_ISWATCHERENABLED, ServiceIsWatcherEnabled);
}

void UninitWatcher(void)
{
	/* remember watcher if running */
	if (!ServiceStopWatcher(0, 0))
		if (db_get_b(NULL, MODULENAME, "RememberOnRestart", SETTING_REMEMBERONRESTART_DEFAULT))
			db_set_b(NULL, MODULENAME, "RememberOnRestart", SDROR_RUNNING);

	/* Message Shutdown */
	UnhookEvent(hHookEventAdded);
	/* Status Shutdown*/
	UnhookEvent(hHookSettingChanged);
	/* Idle Shutdown */
	UnhookEvent(hHookIdleChanged);
	/* Transfer Shutdown */
	UnhookEvent(hHookProtoAck);
	mir_free(transfers); /* does NULL check */
	/* Weather Shutdown */
	UnhookEvent(hHookWeatherUpdated); /* does NULL check */
	/* Services */
	DestroyHookableEvent(hEventWatcherChanged);
	/* Misc */
	UnhookEvent(hHookModulesLoaded);
}