summaryrefslogtreecommitdiff
path: root/libpurple/protocols/gg/gg.c
blob: 16680a71e60469ae01b3afd8c2a485a9e02c8482 (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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
/**
 * @file gg.c Gadu-Gadu protocol plugin
 *
 * purple
 *
 * Copyright (C) 2005  Bartosz Oler <bartosz@bzimage.us>
 *
 * Some parts of the code are adapted or taken from the previous implementation
 * of this plugin written by Arkadiusz Miskiewicz <misiek@pld.org.pl>
 * Some parts Copyright (C) 2009  Krzysztof Klinikowski <grommasher@gmail.com>
 *
 * Thanks to Google's Summer of Code Program.
 *
 * 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; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 */

#include <glib/gi18n-lib.h>

#include <gplugin.h>
#include <gplugin-native.h>

#include <purple.h>

#include "gg.h"
#include "chat.h"
#include "search.h"
#include "blist.h"
#include "utils.h"
#include "resolver-purple.h"
#include "purplew.h"
#include "libgadu-events.h"
#include "multilogon.h"
#include "status.h"
#include "servconn.h"
#include "tcpsocket.h"
#include "pubdir-prpl.h"
#include "message-prpl.h"
#include "html.h"
#include "libgaduw.h"

struct _GGPProtocol {
	PurpleProtocol parent;
};

/* ---------------------------------------------------------------------- */
static PurpleProtocol *my_protocol = NULL;

/* ---------------------------------------------------------------------- */

ggp_buddy_data * ggp_buddy_get_data(PurpleBuddy *buddy)
{
	ggp_buddy_data *buddy_data = purple_buddy_get_protocol_data(buddy);
	if (buddy_data)
		return buddy_data;

	buddy_data = g_new0(ggp_buddy_data, 1); /* TODO: leak */
	purple_buddy_set_protocol_data(buddy, buddy_data);
	return buddy_data;
}

static void
ggp_buddy_free(G_GNUC_UNUSED PurpleProtocolClient *client, PurpleBuddy *buddy)
{
	ggp_buddy_data *buddy_data = purple_buddy_get_protocol_data(buddy);

	if (!buddy_data) {
		return;
	}

	g_free(buddy_data);
	purple_buddy_set_protocol_data(buddy, NULL);
}

const gchar * ggp_get_imtoken(PurpleConnection *gc)
{
	GGPInfo *accdata = purple_connection_get_protocol_data(gc);

	if (accdata->imtoken)
		return accdata->imtoken;

	if (accdata->imtoken_warned)
		return NULL;
	accdata->imtoken_warned = TRUE;

	purple_notify_error(gc, _("Authentication failed"),
		_("IMToken value has not been received."),
		_("Some features will be disabled. "
		"You may try again after a while."),
		purple_request_cpar_from_connection(gc));
	return NULL;
}

uin_t
ggp_own_uin(PurpleConnection *gc) {
	PurpleAccount *account = purple_connection_get_account(gc);
	PurpleContactInfo *info = PURPLE_CONTACT_INFO(account);

	return ggp_str_to_uin(purple_contact_info_get_username(info));
}

/* ---------------------------------------------------------------------- */
/* buddy list import/export from/to file */

static void ggp_callback_buddylist_save_ok(PurpleConnection *gc, const char *filename)
{
	PurpleAccount *account = purple_connection_get_account(gc);

	char *buddylist = ggp_buddylist_dump(account);

	purple_debug_info("gg", "Saving...\n");
	purple_debug_info("gg", "file = %s\n", filename);

	if (buddylist == NULL) {
		purple_notify_info(account, _("Save Buddylist..."), _("Your "
			"buddylist is empty, nothing was written to the file."),
			NULL, purple_request_cpar_from_connection(gc));
		return;
	}

	if (g_file_set_contents(filename, buddylist, -1, NULL)) {
		purple_notify_info(account, _("Save Buddylist..."),
			_("Buddylist saved successfully!"), NULL,
			purple_request_cpar_from_connection(gc));
	} else {
		PurpleContactInfo *info = PURPLE_CONTACT_INFO(account);
		gchar *primary = NULL;

		primary = g_strdup_printf(_("Couldn't write buddy list for %s to %s"),
		                          purple_contact_info_get_username(info),
		                          filename);
		purple_notify_error(account, _("Save Buddylist..."),
			primary, NULL, purple_request_cpar_from_connection(gc));
		g_free(primary);
	}

	g_free(buddylist);
}

static void ggp_callback_buddylist_load_ok(PurpleConnection *gc, gchar *file)
{
	PurpleAccount *account = purple_connection_get_account(gc);
	GError *error = NULL;
	char *buddylist = NULL;
	gsize length;

	purple_debug_info("gg", "file_name = %s\n", file);

	if (!g_file_get_contents(file, &buddylist, &length, &error)) {
		purple_notify_error(account, _("Couldn't load buddylist"),
			_("Couldn't load buddylist"), error->message,
			purple_request_cpar_from_connection(gc));

		purple_debug_error("gg",
			"Couldn't load buddylist. file = %s; error = %s\n",
			file, error->message);

		g_error_free(error);

		return;
	}

	ggp_buddylist_load(gc, buddylist);
	g_free(buddylist);

	purple_notify_info(account, _("Load Buddylist..."),
		_("Buddylist loaded successfully!"), NULL,
		purple_request_cpar_from_connection(gc));
}
/* }}} */

static void
ggp_action_buddylist_save(G_GNUC_UNUSED GSimpleAction *action,
                          GVariant *parameter,
                          G_GNUC_UNUSED gpointer data)
{
	const gchar *account_id = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account = NULL;
	PurpleConnection *connection = NULL;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_STRING)) {
		g_critical("GG save buddylist action parameter is of incorrect type %s",
		           g_variant_get_type_string(parameter));
	}

	account_id = g_variant_get_string(parameter, NULL);
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_by_id(manager, account_id);
	connection = purple_account_get_connection(account);

	purple_request_file(action, _("Save buddylist..."), NULL, TRUE,
		G_CALLBACK(ggp_callback_buddylist_save_ok), NULL,
		purple_request_cpar_from_connection(connection), connection);
}

static void
ggp_action_buddylist_load(G_GNUC_UNUSED GSimpleAction *action,
                          GVariant *parameter,
                          G_GNUC_UNUSED gpointer data)
{
	const gchar *account_id = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account = NULL;
	PurpleConnection *connection = NULL;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_STRING)) {
		g_critical("GG load buddylist action parameter is of incorrect type %s",
		           g_variant_get_type_string(parameter));
	}

	account_id = g_variant_get_string(parameter, NULL);
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_by_id(manager, account_id);
	connection = purple_account_get_connection(account);

	purple_request_file(action, _("Load buddylist from file..."), NULL,
		FALSE, G_CALLBACK(ggp_callback_buddylist_load_ok), NULL,
		purple_request_cpar_from_connection(connection), connection);
}

/* ----- BLOCK BUDDIES -------------------------------------------------- */

#if 0
static void ggp_add_deny(PurpleProtocolPrivacy *privacy, PurpleConnection *gc,
                         const char *who)
{
	GGPInfo *info = purple_connection_get_protocol_data(gc);
	uin_t uin = ggp_str_to_uin(who);

	purple_debug_info("gg", "ggp_add_deny: %u\n", uin);

	gg_remove_notify_ex(info->session, uin, GG_USER_NORMAL);
	gg_add_notify_ex(info->session, uin, GG_USER_BLOCKED);
}

static void ggp_remove_deny(PurpleProtocolPrivacy *privacy,
                            PurpleConnection *gc, const char *who)
{
	GGPInfo *info = purple_connection_get_protocol_data(gc);
	uin_t uin = ggp_str_to_uin(who);

	purple_debug_info("gg", "ggp_rem_deny: %u\n", uin);

	gg_remove_notify_ex(info->session, uin, GG_USER_BLOCKED);
	gg_add_notify_ex(info->session, uin, GG_USER_NORMAL);
}
#endif

/* ---------------------------------------------------------------------- */
/* ----- INTERNAL CALLBACKS --------------------------------------------- */
/* ---------------------------------------------------------------------- */

static void ggp_typing_notification_handler(PurpleConnection *gc, uin_t uin, int length) {
	gchar *from;

	from = g_strdup_printf("%u", uin);
	if (length)
		purple_serv_got_typing(gc, from, 0, PURPLE_IM_TYPING);
	else
		purple_serv_got_typing_stopped(gc, from);
	g_free(from);
}

/**
 * Handling of XML events.
 *
 * @param gc PurpleConnection.
 * @param data Raw XML contents.
 *
 * @see http://toxygen.net/libgadu/protocol/#ch1.13
 * @todo: this may not be necessary anymore
 */
static void
ggp_xml_event_handler(G_GNUC_UNUSED PurpleConnection *gc, char *data)
{
	PurpleXmlNode *xml = NULL;
	PurpleXmlNode *xmlnode_next_event;

	xml = purple_xmlnode_from_str(data, -1);
	if (xml == NULL) {
		purple_debug_error("gg", "ggp_xml_event_handler: "
			"invalid xml: [%s]\n", data);
		goto out;
	}

	xmlnode_next_event = purple_xmlnode_get_child(xml, "event");
	while (xmlnode_next_event != NULL) {
		PurpleXmlNode *xmlnode_current_event = xmlnode_next_event;

		PurpleXmlNode *xmlnode_type;
		char *event_type_raw;
		int event_type = 0;

		PurpleXmlNode *xmlnode_sender;
		char *event_sender_raw;
		uin_t event_sender = 0;

		xmlnode_next_event = purple_xmlnode_get_next_twin(xmlnode_next_event);

		xmlnode_type = purple_xmlnode_get_child(xmlnode_current_event, "type");
		if (xmlnode_type == NULL)
			continue;
		event_type_raw = purple_xmlnode_get_data(xmlnode_type);
		if (event_type_raw != NULL)
			event_type = atoi(event_type_raw);
		g_free(event_type_raw);

		xmlnode_sender = purple_xmlnode_get_child(xmlnode_current_event, "sender");
		if (xmlnode_sender != NULL) {
			event_sender_raw = purple_xmlnode_get_data(xmlnode_sender);
			if (event_sender_raw != NULL)
				event_sender = ggp_str_to_uin(event_sender_raw);
			g_free(event_sender_raw);
		}

		switch (event_type)
		{
			case 28: /* avatar update */
				purple_debug_info("gg",
					"ggp_xml_event_handler: avatar updated (uid: %u)\n",
					event_sender);
				break;
			default:
				purple_debug_error("gg",
					"ggp_xml_event_handler: unsupported event type=%d from=%u\n",
					event_type, event_sender);
		}
	}

	out:
		if (xml)
			purple_xmlnode_free(xml);
}

static void
ggp_callback_recv(gpointer _gc, G_GNUC_UNUSED gint fd,
                  G_GNUC_UNUSED PurpleInputCondition cond)
{
	PurpleConnection *gc = _gc;
	GGPInfo *info = purple_connection_get_protocol_data(gc);
	struct gg_event *ev;

	if (!(ev = gg_watch_fd(info->session))) {
		purple_debug_error("gg",
			"ggp_callback_recv: gg_watch_fd failed -- CRITICAL!\n");
		purple_connection_error (gc,
			PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
			_("Unable to read from socket"));
		return;
	}

	if (purple_debug_is_verbose()) {
		purple_debug_misc("gg", "ggp_callback_recv: got event %s",
			gg_debug_event(ev->type));
	}

	g_source_remove(info->inpa);
	info->inpa = purple_input_add(info->session->fd,
		ggp_tcpsocket_inputcond_gg_to_purple(info->session->check),
		ggp_callback_recv, gc);

	switch (ev->type) {
		case GG_EVENT_NONE:
			/* Nothing happened. */
			break;
		case GG_EVENT_CONN_FAILED:
			purple_connection_error (gc,
				PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
				_("Server disconnected"));
			break;
		case GG_EVENT_MSG:
			ggp_message_got(gc, &ev->event.msg);
			break;
		case GG_EVENT_ACK:
		case GG_EVENT_ACK110:
			break;
		case GG_EVENT_IMAGE_REPLY:
			ggp_image_recv(gc, &ev->event.image_reply);
			break;
		case GG_EVENT_IMAGE_REQUEST:
			ggp_image_send(gc, &ev->event.image_request);
			break;
		case GG_EVENT_NOTIFY60:
		case GG_EVENT_STATUS60:
			ggp_status_got_others(gc, ev);
			break;
		case GG_EVENT_TYPING_NOTIFICATION:
			ggp_typing_notification_handler(gc, ev->event.typing_notification.uin,
				ev->event.typing_notification.length);
			break;
		case GG_EVENT_XML_EVENT:
			purple_debug_info("gg", "GG_EVENT_XML_EVENT\n");
			ggp_xml_event_handler(gc, ev->event.xml_event.data);
			break;
		case GG_EVENT_USER_DATA:
			ggp_events_user_data(gc, &ev->event.user_data);
			break;
		case GG_EVENT_JSON_EVENT:
			ggp_events_json(gc, &ev->event.json_event);
			break;
		case GG_EVENT_USERLIST100_VERSION:
			ggp_roster_version(gc, &ev->event.userlist100_version);
			break;
		case GG_EVENT_USERLIST100_REPLY:
			ggp_roster_reply(gc, &ev->event.userlist100_reply);
			break;
		case GG_EVENT_MULTILOGON_MSG:
			ggp_message_got_multilogon(gc, &ev->event.multilogon_msg);
			break;
		case GG_EVENT_MULTILOGON_INFO:
			ggp_multilogon_info(gc, &ev->event.multilogon_info);
			break;
		case GG_EVENT_IMTOKEN:
			purple_debug_info("gg", "gg11: got IMTOKEN\n");
			g_free(info->imtoken);
			info->imtoken = g_strdup(ev->event.imtoken.imtoken);
			break;
		case GG_EVENT_PONG110:
			purple_debug_info("gg", "gg11: got PONG110 %lu\n",
				(long unsigned)ev->event.pong110.time);
			break;
		case GG_EVENT_CHAT_INFO:
		case GG_EVENT_CHAT_INFO_GOT_ALL:
		case GG_EVENT_CHAT_INFO_UPDATE:
		case GG_EVENT_CHAT_CREATED:
		case GG_EVENT_CHAT_INVITE_ACK:
			ggp_chat_got_event(gc, ev);
			break;
		case GG_EVENT_DISCONNECT:
			ggp_servconn_remote_disconnect(gc);
			break;
		default:
			purple_debug_warning("gg",
				"unsupported event type=%d\n", ev->type);
			break;
	}

	gg_free_event(ev);
}

void
ggp_async_login_handler(gpointer _gc, G_GNUC_UNUSED gint fd,
                        G_GNUC_UNUSED PurpleInputCondition cond)
{
	PurpleConnection *gc = _gc;
	GGPInfo *info;
	struct gg_event *ev;

	PURPLE_ASSERT_CONNECTION_IS_VALID(gc);

	info = purple_connection_get_protocol_data(gc);

	purple_debug_info("gg", "login_handler: session: check = %d; state = %d;\n",
			info->session->check, info->session->state);

	switch (info->session->state) {
		case GG_STATE_ERROR:
			purple_debug_info("gg", "GG_STATE_ERROR\n");
			break;
		case GG_STATE_RESOLVING:
			purple_debug_info("gg", "GG_STATE_RESOLVING\n");
			break;
		case GG_STATE_RESOLVING_GG:
			purple_debug_info("gg", "GG_STATE_RESOLVING_GG\n");
			break;
		case GG_STATE_CONNECTING_HUB:
			purple_debug_info("gg", "GG_STATE_CONNECTING_HUB\n");
			break;
		case GG_STATE_READING_DATA:
			purple_debug_info("gg", "GG_STATE_READING_DATA\n");
			break;
		case GG_STATE_CONNECTING_GG:
			purple_debug_info("gg", "GG_STATE_CONNECTING_GG\n");
			break;
		case GG_STATE_READING_KEY:
			purple_debug_info("gg", "GG_STATE_READING_KEY\n");
			break;
		case GG_STATE_READING_REPLY:
			purple_debug_info("gg", "GG_STATE_READING_REPLY\n");
			break;
		case GG_STATE_TLS_NEGOTIATION:
			purple_debug_info("gg", "GG_STATE_TLS_NEGOTIATION\n");
			break;
		case GG_STATE_RESOLVING_HUB:
			purple_debug_info("gg", "GG_STATE_RESOLVING_HUB\n");
			break;
		case GG_STATE_READING_HUB:
			purple_debug_info("gg", "GG_STATE_READING_HUB\n");
			break;
		default:
			purple_debug_error("gg", "unknown state = %d\n",
				info->session->state);
		break;
	}

	if (!(ev = gg_watch_fd(info->session))) {
		purple_debug_error("gg", "login_handler: gg_watch_fd failed!\n");
		purple_connection_error (gc,
			PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
			_("Unable to read from socket"));
		return;
	}
	purple_debug_info("gg", "login_handler: session->fd = %d\n", info->session->fd);
	purple_debug_info("gg", "login_handler: session: check = %d; state = %d;\n",
			info->session->check, info->session->state);

	g_source_remove(info->inpa);
	info->inpa = 0;

	/** XXX I think that this shouldn't be done if ev->type is GG_EVENT_CONN_FAILED or GG_EVENT_CONN_SUCCESS -datallah */
	if (info->session->fd >= 0)
		info->inpa = purple_input_add(info->session->fd,
			(info->session->check == 1) ? PURPLE_INPUT_WRITE :
				PURPLE_INPUT_READ,
			ggp_async_login_handler, gc);

	switch (ev->type) {
		case GG_EVENT_NONE:
			/* Nothing happened. */
			purple_debug_info("gg", "GG_EVENT_NONE\n");
			break;
		case GG_EVENT_CONN_SUCCESS:
			{
				purple_debug_info("gg", "GG_EVENT_CONN_SUCCESS:"
					" successfully connected to %s\n",
					info->session->connect_host);
				ggp_servconn_add_server(info->session->
					connect_host);
				g_source_remove(info->inpa);
				info->inpa = purple_input_add(info->session->fd,
					PURPLE_INPUT_READ,
					ggp_callback_recv, gc);

				purple_connection_set_state(gc, PURPLE_CONNECTION_STATE_CONNECTED);

				ggp_buddylist_send(gc);
				ggp_roster_request_update(gc);
			}
			break;
		case GG_EVENT_CONN_FAILED:
			if (info->inpa > 0) {
				g_source_remove(info->inpa);
				info->inpa = 0;
			}
			purple_debug_info("gg", "Connection failure: %d\n",
				ev->event.failure);
			switch (ev->event.failure) {
				case GG_FAILURE_RESOLVING:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
						_("Unable to resolve "
						"hostname"));
					break;
				case GG_FAILURE_PASSWORD:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
						_("Incorrect password"));
					break;
				case GG_FAILURE_TLS:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_ENCRYPTION_ERROR,
						_("SSL Connection Failed"));
					break;
				case GG_FAILURE_INTRUDER:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
						_("Your account has been "
						"disabled because too many "
						"incorrect passwords were "
						"entered"));
					break;
				case GG_FAILURE_UNAVAILABLE:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
						_("Service temporarily "
						"unavailable"));
					break;
				case GG_FAILURE_PROXY:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
						_("Error connecting to proxy "
						"server"));
					break;
				case GG_FAILURE_HUB:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
						_("Error connecting to master "
						"server"));
					break;
				case GG_FAILURE_INTERNAL:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_OTHER_ERROR,
						_("Internal error"));
					break;
				default:
					purple_connection_error(gc,
						PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
						_("Connection failed"));
			}
			break;
		case GG_EVENT_MSG:
			if (ev->event.msg.sender == 0) {
				if (ev->event.msg.message == NULL)
					break;

				/* system messages are mostly ads */
				purple_debug_info("gg", "System message:\n%s\n",
					ev->event.msg.message);
			} else {
				purple_debug_warning("gg", "GG_EVENT_MSG: message from user %u "
					"unexpected while connecting:\n%s\n",
					ev->event.msg.sender,
					ev->event.msg.message);
			}
			break;
		default:
			purple_debug_error("gg", "strange event: %d\n", ev->type);
			break;
	}

	gg_free_event(ev);
}

static gboolean
gg_uri_handler_find_account(PurpleAccount *account,
                            G_GNUC_UNUSED gconstpointer data)
{
	const gchar *protocol_id;

	protocol_id = purple_account_get_protocol_id(account);

	return (purple_strequal(protocol_id, "prpl-gg") &&
	        purple_account_is_connected(account));
}

static gboolean
gg_uri_handler(const gchar *scheme, const gchar *screenname,
               G_GNUC_UNUSED GHashTable *params)
{
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account;
	PurpleConversation *im;

	g_return_val_if_fail(screenname != NULL, FALSE);

	if (!purple_strequal(scheme, "gg")) {
		return FALSE;
	}

	if (screenname[0] == '\0') {
		purple_debug_warning("gg", "Invalid empty screenname in URI");
		return FALSE;
	}

	/* Find online Gadu-Gadu account */
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_custom(manager,
	                                             (GEqualFunc)gg_uri_handler_find_account,
	                                             NULL);

	if (account == NULL) {
		return FALSE;
	}

	im = purple_im_conversation_new(account, screenname);
	purple_conversation_present(im);

	return TRUE;
}

/* ---------------------------------------------------------------------- */
/* ----- PurpleProtocol ----------------------------------------- */
/* ---------------------------------------------------------------------- */

static PurpleBuddyIconSpec *
ggp_protocol_get_buddy_icon_spec(G_GNUC_UNUSED PurpleProtocol *protocol) {
	return purple_buddy_icon_spec_new("png",
	                                  1, 1, 200, 200, 0,
	                                  PURPLE_ICON_SCALE_DISPLAY |
	                                  PURPLE_ICON_SCALE_SEND);
}

static GList *
ggp_protocol_get_account_options(G_GNUC_UNUSED PurpleProtocol *protocol) {
	PurpleAccountOption *option = NULL;
	PurpleKeyValuePair *kvp = NULL;
	GList *encryption_options = NULL;
	GList *protocol_version = NULL;
	GList *opts = NULL;

	option = purple_account_option_string_new(_("GG server"), "gg_server", "");
	opts = g_list_append(opts, option);

	/* setup encryption options */
	kvp = purple_key_value_pair_new(_("Use encryption if available"),
	                                "opportunistic_tls");
	encryption_options = g_list_append(encryption_options, kvp);

	kvp = purple_key_value_pair_new(_("Require encryption"), "require_tls");
	encryption_options = g_list_append(encryption_options, kvp);

	kvp = purple_key_value_pair_new(_("Don't use encryption"), "none");
	encryption_options = g_list_append(encryption_options, kvp);

	option = purple_account_option_list_new(_("Connection security"),
	                                        "encryption", encryption_options);
	opts = g_list_append(opts, option);

	/* setup the protocol version */
	kvp = purple_key_value_pair_new(_("Default"), "default");
	protocol_version = g_list_append(protocol_version, kvp);

	kvp = purple_key_value_pair_new("GG 10", "gg10");
	protocol_version = g_list_append(protocol_version, kvp);

	kvp = purple_key_value_pair_new("GG 11", "gg11");
	protocol_version = g_list_append(protocol_version, kvp);

	option = purple_account_option_list_new(_("Protocol version"),
	                                        "protocol_version",
	                                        protocol_version);
	opts = g_list_append(opts, option);

	option = purple_account_option_bool_new(_("Show links from strangers"),
	                                        "show_links_from_strangers", 1);
	opts = g_list_append(opts, option);

	return opts;
}

static const char *
ggp_normalize(G_GNUC_UNUSED PurpleProtocolClient *client,
              G_GNUC_UNUSED PurpleAccount *account, const char *who)
{
	static char normalized[21]; /* maximum unsigned long long int size */

	uin_t uin = ggp_str_to_uin(who);
	if(uin <= 0) {
		return NULL;
	}

	g_snprintf(normalized, sizeof(normalized), "%u", uin);

	return normalized;
}

/* TODO:
 * - move to status.c ?
 * - add information about not adding to his buddy list (not_a_friend)
 */
static void
ggp_tooltip_text(G_GNUC_UNUSED PurpleProtocolClient *client, PurpleBuddy *b,
                 PurpleNotifyUserInfo *user_info,
                 G_GNUC_UNUSED gboolean full)
{
	PurpleStatus *status;
	char *tmp;
	const char *name, *alias;
	gchar *msg;

	g_return_if_fail(b != NULL);

	status = purple_presence_get_active_status(purple_buddy_get_presence(b));
	name = purple_status_get_name(status);
	alias = purple_buddy_get_alias(b);
	ggp_status_from_purplestatus(status, &msg);

	purple_notify_user_info_add_pair_plaintext(user_info, _("Alias"), alias);

	if (msg != NULL) {
		if (PURPLE_BUDDY_IS_ONLINE(b)) {
			tmp = g_strdup_printf("%s: %s", name, msg);
			purple_notify_user_info_add_pair_plaintext(user_info, _("Status"), tmp);
			g_free(tmp);
		} else {
			purple_notify_user_info_add_pair_plaintext(user_info, _("Message"), msg);
		}
		g_free(msg);
	/* We don't want to duplicate 'Status: Offline'. */
	} else if (PURPLE_BUDDY_IS_ONLINE(b)) {
		purple_notify_user_info_add_pair_plaintext(user_info, _("Status"), name);
	}
}

static void
ggp_login(G_GNUC_UNUSED PurpleProtocol *protocol, PurpleAccount *account) {
	PurpleConnection *gc = purple_account_get_connection(account);
	PurpleContactInfo *contact_info = PURPLE_CONTACT_INFO(account);
	struct gg_login_params *glp;
	GGPInfo *info;
	const char *address;
	const gchar *encryption_type, *protocol_version;
	GProxyResolver *resolver;
	GError *error = NULL;

	purple_connection_set_flags(gc,
		PURPLE_CONNECTION_FLAG_HTML |
		PURPLE_CONNECTION_FLAG_NO_URLDESC);

	resolver = purple_proxy_get_proxy_resolver(account, &error);
	if (resolver == NULL) {
		purple_debug_error("gg", "Unable to get account proxy resolver: %s",
		                   error->message);
		purple_connection_take_error(gc, error);
		return;
	}

	glp = g_new0(struct gg_login_params, 1);
	glp->struct_size = sizeof(struct gg_login_params);
	info = g_new0(GGPInfo, 1);

	purple_connection_set_protocol_data(gc, info);

	info->http = soup_session_new_with_options("proxy-resolver", resolver,
	                                           NULL);

	ggp_tcpsocket_setup(gc, glp);
	ggp_image_setup(gc);
	ggp_avatar_setup(gc);
	ggp_roster_setup(gc);
	ggp_multilogon_setup(gc);
	ggp_status_setup(gc);
	ggp_chat_setup(gc);
	ggp_message_setup(gc);
	ggp_edisc_setup(gc, resolver);
	g_object_unref(resolver);

	glp->uin = ggp_str_to_uin(purple_contact_info_get_username(contact_info));
	glp->password =
		ggp_convert_to_cp1250(purple_connection_get_password(gc));

	if (glp->uin == 0) {
		purple_connection_error(gc,
			PURPLE_CONNECTION_ERROR_INVALID_USERNAME,
			_("The username specified is invalid."));
		purple_str_wipe(glp->password);
		g_free(glp);
		return;
	}

	glp->image_size = 255;
	glp->status_flags = GG_STATUS_FLAG_UNKNOWN;

	if (purple_account_get_bool(account, "show_links_from_strangers", 1))
		glp->status_flags |= GG_STATUS_FLAG_SPAM;

	glp->encoding = GG_ENCODING_UTF8;
	glp->protocol_features = (GG_FEATURE_DND_FFC |
		GG_FEATURE_TYPING_NOTIFICATION | GG_FEATURE_MULTILOGON |
		GG_FEATURE_USER_DATA);

	glp->async = 1;

	encryption_type = purple_account_get_string(account, "encryption",
		"opportunistic_tls");
	purple_debug_info("gg", "Requested encryption type: %s\n",
		encryption_type);
	if (purple_strequal(encryption_type, "opportunistic_tls"))
		glp->tls = GG_SSL_ENABLED;
	else if (purple_strequal(encryption_type, "require_tls")) {
		if (gg_libgadu_check_feature(GG_LIBGADU_FEATURE_SSL))
			glp->tls = GG_SSL_REQUIRED;
		else {
			purple_connection_error(gc,
				PURPLE_CONNECTION_ERROR_NO_SSL_SUPPORT,
				_("SSL support unavailable"));
			purple_str_wipe(glp->password);
			g_free(glp);
			return;
		}
	}
	else /* encryption_type == "none" */
		glp->tls = GG_SSL_DISABLED;
	purple_debug_misc("gg", "TLS mode: %d\n", glp->tls);

	protocol_version = purple_account_get_string(account,
		"protocol_version", "default");
	purple_debug_info("gg", "Requested protocol version: %s\n",
		protocol_version);
	if (purple_strequal(protocol_version, "gg10"))
		glp->protocol_version = GG_PROTOCOL_VERSION_100;
	else if (purple_strequal(protocol_version, "gg11"))
		glp->protocol_version = GG_PROTOCOL_VERSION_110;
	glp->compatibility = GG_COMPAT_1_12_0;

	ggp_status_set_initial(gc, glp);

	address = purple_account_get_string(account, "gg_server", "");
	if (address && *address)
		glp->connect_host = g_strdup(address);

	info->session = gg_login(glp);
	g_free(glp->connect_host);
	purple_str_wipe(glp->password);
	g_free(glp);

	if (info->session == NULL) {
		purple_connection_error (gc,
			PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
			_("Connection failed"));
		return;
	}

	if (info->session->fd > 0) {
		info->inpa = purple_input_add(info->session->fd,
			PURPLE_INPUT_READ, ggp_async_login_handler, gc);
	}
}

static void
ggp_close(G_GNUC_UNUSED PurpleProtocol *protocol, PurpleConnection *gc) {
	PurpleAccount *account;
	GGPInfo *info;;

	g_return_if_fail(gc != NULL);

	account = purple_connection_get_account(gc);
	info = purple_connection_get_protocol_data(gc);

	purple_notify_close_with_handle(gc);

	if (info) {
		if (info->session != NULL) {
			ggp_status_set_disconnected(account);
			gg_logoff(info->session);
			gg_free_session(info->session);
		}

		ggp_image_cleanup(gc);
		ggp_avatar_cleanup(gc);
		ggp_roster_cleanup(gc);
		ggp_multilogon_cleanup(gc);
		ggp_status_cleanup(gc);
		ggp_chat_cleanup(gc);
		ggp_message_cleanup(gc);
		ggp_edisc_cleanup(gc);

		if (info->inpa > 0)
			g_source_remove(info->inpa);
		g_free(info->imtoken);

		if (info->http) {
			soup_session_abort(info->http);
			g_object_unref(info->http);
		}

		purple_connection_set_protocol_data(gc, NULL);
		g_free(info);
	}

	purple_debug_info("gg", "Connection closed.\n");
}

static unsigned int
ggp_send_typing(G_GNUC_UNUSED PurpleProtocolIM *im, PurpleConnection *gc,
                const char *name, PurpleIMTypingState state)
{
	GGPInfo *info = purple_connection_get_protocol_data(gc);
	int dummy_length; /* we don't send real length of typed message */

	if (state == PURPLE_IM_TYPED) /* not supported */
		return 1;

	if (state == PURPLE_IM_TYPING)
		dummy_length = (int)g_random_int();
	else /* PURPLE_IM_NOT_TYPING */
		dummy_length = 0;

	gg_typing_notification(
		info->session,
		ggp_str_to_uin(name),
		dummy_length);

	return 1; /* wait 1 second before another notification */
}

static void
ggp_add_buddy(PurpleProtocolServer *protocol_server, PurpleConnection *gc,
              PurpleBuddy *buddy, PurpleGroup *group, const gchar *message)
{
	PurpleAccount *account = purple_connection_get_account(gc);
	PurpleContactInfo *contact_info = PURPLE_CONTACT_INFO(account);
	GGPInfo *info = purple_connection_get_protocol_data(gc);
	const gchar *name = purple_buddy_get_name(buddy);

	gg_add_notify(info->session, ggp_str_to_uin(name));

	/* gg server won't tell us our status here */
	if(purple_strequal(purple_contact_info_get_username(contact_info), name)) {
		ggp_status_fake_to_self(gc);
	}

	ggp_roster_add_buddy(protocol_server, gc, buddy, group, message);
	ggp_pubdir_request_buddy_alias(gc, buddy);
}

static void
ggp_remove_buddy(PurpleProtocolServer *protocol_server, PurpleConnection *gc,
                 PurpleBuddy *buddy, PurpleGroup *group)
{
	GGPInfo *info = purple_connection_get_protocol_data(gc);

	gg_remove_notify(info->session, ggp_str_to_uin(purple_buddy_get_name(buddy)));
	ggp_roster_remove_buddy(protocol_server, gc, buddy, group);
}

static void
ggp_keepalive(G_GNUC_UNUSED PurpleProtocolServer *protocol_server,
              PurpleConnection *gc)
{
	GGPInfo *info = purple_connection_get_protocol_data(gc);

	/* purple_debug_info("gg", "Keeping connection alive....\n"); */

	if (gg_ping(info->session) < 0) {
		purple_debug_info("gg", "Not connected to the server "
				"or gg_session is not correct\n");
		purple_connection_error (gc,
			PURPLE_CONNECTION_ERROR_NETWORK_ERROR,
			_("Not connected to the server"));
	}
}

static void
ggp_action_multilogon(G_GNUC_UNUSED GSimpleAction *action,
                      GVariant *parameter,
                      G_GNUC_UNUSED gpointer data)
{
	const gchar *account_id = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account = NULL;
	PurpleConnection *connection = NULL;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_STRING)) {
		g_critical("GG multilogin action parameter is of incorrect type %s",
		           g_variant_get_type_string(parameter));
	}

	account_id = g_variant_get_string(parameter, NULL);
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_by_id(manager, account_id);
	connection = purple_account_get_connection(account);

	ggp_multilogon_dialog(connection);
}

static void
ggp_action_status_broadcasting(G_GNUC_UNUSED GSimpleAction *action,
                               GVariant *parameter,
                               G_GNUC_UNUSED gpointer data)
{
	const gchar *account_id = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account = NULL;
	PurpleConnection *connection = NULL;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_STRING)) {
		g_critical("GG broadcast action parameter is of incorrect type %s",
		           g_variant_get_type_string(parameter));
	}

	account_id = g_variant_get_string(parameter, NULL);
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_by_id(manager, account_id);
	connection = purple_account_get_connection(account);

	ggp_status_broadcasting_dialog(connection);
}

static void
ggp_action_search(G_GNUC_UNUSED GSimpleAction *action,
                  GVariant *parameter,
                  G_GNUC_UNUSED gpointer data)
{
	const gchar *account_id = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account = NULL;
	PurpleConnection *connection = NULL;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_STRING)) {
		g_critical("GG search action parameter is of incorrect type %s",
		           g_variant_get_type_string(parameter));
	}

	account_id = g_variant_get_string(parameter, NULL);
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_by_id(manager, account_id);
	connection = purple_account_get_connection(account);

	ggp_pubdir_search(connection, NULL);
}

static void
ggp_action_set_info(G_GNUC_UNUSED GSimpleAction *action,
                    GVariant *parameter,
                    G_GNUC_UNUSED gpointer data)
{
	const gchar *account_id = NULL;
	PurpleAccountManager *manager = NULL;
	PurpleAccount *account = NULL;
	PurpleConnection *connection = NULL;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_STRING)) {
		g_critical("GG set info action parameter is of incorrect type %s",
		           g_variant_get_type_string(parameter));
	}

	account_id = g_variant_get_string(parameter, NULL);
	manager = purple_account_manager_get_default();
	account = purple_account_manager_find_by_id(manager, account_id);
	connection = purple_account_get_connection(account);

	ggp_pubdir_set_info(connection);
}

static const gchar *
ggp_protocol_actions_get_prefix(G_GNUC_UNUSED PurpleProtocolActions *actions) {
	return "prpl-gg";
}

static GActionGroup *
ggp_protocol_actions_get_action_group(G_GNUC_UNUSED PurpleProtocolActions *actions,
                                      G_GNUC_UNUSED PurpleConnection *connection)
{
	GSimpleActionGroup *group = NULL;
	GActionEntry entries[] = {
		{
			.name = "multilogon",
			.activate = ggp_action_multilogon,
			.parameter_type = "s",
		},
		{
			.name = "broadcasting",
			.activate = ggp_action_status_broadcasting,
			.parameter_type = "s",
		},
		{
			.name = "search",
			.activate = ggp_action_search,
			.parameter_type = "s",
		},
		{
			.name = "set-info",
			.activate = ggp_action_set_info,
			.parameter_type = "s",
		},
		{
			.name = "save-buddylist",
			.activate = ggp_action_buddylist_save,
			.parameter_type = "s",
		},
		{
			.name = "load-buddylist",
			.activate = ggp_action_buddylist_load,
			.parameter_type = "s",
		},
	};
	gsize nentries = G_N_ELEMENTS(entries);

	group = g_simple_action_group_new();
	g_action_map_add_action_entries(G_ACTION_MAP(group), entries, nentries,
	                                NULL);

	return G_ACTION_GROUP(group);
}

static GMenu *
ggp_protocol_actions_get_menu(G_GNUC_UNUSED PurpleProtocolActions *actions,
                              G_GNUC_UNUSED PurpleConnection *connection) {
	GMenu *menu = NULL, *submenu = NULL;
	GMenuItem *item = NULL;

	menu = g_menu_new();

	item = g_menu_item_new(_("Show other sessions"), "prpl-gg.multilogon");
	g_menu_item_set_attribute(item, PURPLE_MENU_ATTRIBUTE_DYNAMIC_TARGET, "s",
	                          "account");
	g_menu_append_item(menu, item);
	g_object_unref(item);

	item = g_menu_item_new(_("Show status only for buddies"),
	                       "prpl-gg.broadcasting");
	g_menu_item_set_attribute(item, PURPLE_MENU_ATTRIBUTE_DYNAMIC_TARGET, "s",
	                          "account");
	g_menu_append_item(menu, item);
	g_object_unref(item);

	item = g_menu_item_new(_("Find buddies..."), "prpl-gg.search");
	g_menu_item_set_attribute(item, PURPLE_MENU_ATTRIBUTE_DYNAMIC_TARGET, "s",
	                          "account");
	g_menu_append_item(menu, item);
	g_object_unref(item);

	item = g_menu_item_new(_("Set User Info"), "prpl-gg.set-info");
	g_menu_item_set_attribute(item, PURPLE_MENU_ATTRIBUTE_DYNAMIC_TARGET, "s",
	                          "account");
	g_menu_append_item(menu, item);
	g_object_unref(item);

	/* Buddy list management. */
	submenu = g_menu_new();

	item = g_menu_item_new(_("Save to file..."), "prpl-gg.save-buddylist");
	g_menu_item_set_attribute(item, PURPLE_MENU_ATTRIBUTE_DYNAMIC_TARGET, "s",
	                          "account");
	g_menu_append_item(menu, item);
	g_object_unref(item);

	item = g_menu_item_new(_("Load from file..."), "prpl-gg.load-buddylist");
	g_menu_item_set_attribute(item, PURPLE_MENU_ATTRIBUTE_DYNAMIC_TARGET, "s",
	                          "account");
	g_menu_append_item(menu, item);
	g_object_unref(item);

	g_menu_append_submenu(menu, _("Buddy list"), G_MENU_MODEL(submenu));
	g_object_unref(submenu);

	return menu;
}

static const char *
ggp_list_emblem(G_GNUC_UNUSED PurpleProtocolClient *client,
                PurpleBuddy *buddy)
{
	ggp_buddy_data *buddy_data = ggp_buddy_get_data(buddy);

	if (buddy_data->blocked)
		return "not-authorized";
	if (buddy_data->not_a_friend)
		return "unavailable";

	return NULL;
}

static gboolean
ggp_offline_message(G_GNUC_UNUSED PurpleProtocolClient *client,
                    G_GNUC_UNUSED PurpleBuddy *buddy)
{
	return TRUE;
}

static GHashTable *
ggp_get_account_text_table(G_GNUC_UNUSED PurpleProtocolClient *client,
                           G_GNUC_UNUSED PurpleAccount *account)
{
	GHashTable *table;
	table = g_hash_table_new(g_str_hash, g_str_equal);
	g_hash_table_insert(table, "login_label", (gpointer)_("GG number..."));
	return table;
}

static gssize
ggp_get_max_message_size(G_GNUC_UNUSED PurpleProtocolClient *client,
                         G_GNUC_UNUSED PurpleConversation *conv)
{
	/* TODO: it may depend on protocol version or other factors */
	return 1200; /* no more than 1232 */
}

static void
ggp_protocol_init(G_GNUC_UNUSED GGPProtocol *self) {
}

static void
ggp_protocol_class_init(GGPProtocolClass *klass)
{
	PurpleProtocolClass *protocol_class = PURPLE_PROTOCOL_CLASS(klass);

	protocol_class->login = ggp_login;
	protocol_class->close = ggp_close;
	protocol_class->status_types = ggp_status_types;

	protocol_class->get_account_options = ggp_protocol_get_account_options;
	protocol_class->get_buddy_icon_spec = ggp_protocol_get_buddy_icon_spec;
}

static void
ggp_protocol_class_finalize(G_GNUC_UNUSED GGPProtocolClass *klass)
{
}

static void
ggp_protocol_actions_iface_init(PurpleProtocolActionsInterface *iface)
{
	iface->get_prefix = ggp_protocol_actions_get_prefix;
	iface->get_action_group = ggp_protocol_actions_get_action_group;
	iface->get_menu = ggp_protocol_actions_get_menu;
}

static void
ggp_protocol_client_iface_init(PurpleProtocolClientInterface *client_iface)
{
	client_iface->list_emblem            = ggp_list_emblem;
	client_iface->status_text            = ggp_status_buddy_text;
	client_iface->tooltip_text           = ggp_tooltip_text;
	client_iface->buddy_free             = ggp_buddy_free;
	client_iface->normalize              = ggp_normalize;
	client_iface->offline_message        = ggp_offline_message;
	client_iface->get_account_text_table = ggp_get_account_text_table;
	client_iface->get_max_message_size   = ggp_get_max_message_size;
}

static void
ggp_protocol_server_iface_init(PurpleProtocolServerInterface *server_iface)
{
	server_iface->get_info       = ggp_pubdir_get_info_protocol;
	server_iface->set_status     = ggp_status_set_purplestatus;
	server_iface->add_buddy      = ggp_add_buddy;
	server_iface->remove_buddy   = ggp_remove_buddy;
	server_iface->keepalive      = ggp_keepalive;
	server_iface->alias_buddy    = ggp_roster_alias_buddy;
	server_iface->group_buddy    = ggp_roster_group_buddy;
	server_iface->rename_group   = ggp_roster_rename_group;
	server_iface->set_buddy_icon = ggp_avatar_own_set;
}

static void
ggp_protocol_im_iface_init(PurpleProtocolIMInterface *im_iface)
{
	im_iface->send        = ggp_message_send_im;
	im_iface->send_typing = ggp_send_typing;
}

static void
ggp_protocol_chat_iface_init(PurpleProtocolChatInterface *chat_iface)
{
	chat_iface->info          = ggp_chat_info;
	chat_iface->info_defaults = ggp_chat_info_defaults;
	chat_iface->join          = ggp_chat_join;
	chat_iface->get_name      = ggp_chat_get_name;
	chat_iface->invite        = ggp_chat_invite;
	chat_iface->leave         = ggp_chat_leave;
	chat_iface->send          = ggp_chat_send;

	chat_iface->reject        = NULL; /* TODO */
}

static void
ggp_protocol_roomlist_iface_init(PurpleProtocolRoomlistInterface *roomlist_iface)
{
	roomlist_iface->get_list = ggp_chat_roomlist_get_list;
}

static void
ggp_protocol_xfer_iface_init(PurpleProtocolXferInterface *xfer_iface)
{
	xfer_iface->can_receive = ggp_edisc_xfer_can_receive_file;
	xfer_iface->send_file   = ggp_edisc_xfer_send_file;
	xfer_iface->new_xfer    = ggp_edisc_xfer_send_new;
}

G_DEFINE_DYNAMIC_TYPE_EXTENDED(
	GGPProtocol,
	ggp_protocol,
	PURPLE_TYPE_PROTOCOL,
	G_TYPE_FLAG_FINAL,
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_ACTIONS,
	                              ggp_protocol_actions_iface_init)
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_CLIENT,
	                              ggp_protocol_client_iface_init)
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_SERVER,
	                              ggp_protocol_server_iface_init)
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_IM,
	                              ggp_protocol_im_iface_init)
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_CHAT,
	                              ggp_protocol_chat_iface_init)
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_ROOMLIST,
	                              ggp_protocol_roomlist_iface_init)
	G_IMPLEMENT_INTERFACE_DYNAMIC(PURPLE_TYPE_PROTOCOL_XFER,
	                              ggp_protocol_xfer_iface_init))

static PurpleProtocol *
ggp_protocol_new(void) {
	return PURPLE_PROTOCOL(g_object_new(
		GGP_TYPE_PROTOCOL,
		"id", "prpl-gg",
		"name", "Gadu-Gadu",
		"description", _("Gadu-Gadu is a Polish instant messaging network."),
		"icon-name", "im-gadu-gadu",
		"icon-resource-path", "/im/pidgin/libpurple/gg/icons",
		NULL));
}

static GPluginPluginInfo *
gg_query(G_GNUC_UNUSED GError **error)
{
	GPluginPluginInfo *info = NULL;
	gchar *description = NULL;
	const gchar * const authors[] = {
		"boler@sourceforge.net",
		NULL
	};

	description = g_strdup_printf(N_("Polish popular IM\nlibgadu version %s"),
	                              gg_libgadu_version());

	info = purple_plugin_info_new(
		"id",           "prpl-gg",
		"name",         "Gadu-Gadu Protocol",
		"version",      DISPLAY_VERSION,
		"category",     N_("Protocol"),
		"summary",      N_("Gadu-Gadu Protocol Plugin"),
		"description",  description,
		"authors",      authors,
		"website",      PURPLE_WEBSITE,
		"abi-version",  PURPLE_ABI_VERSION,
		"flags",        PURPLE_PLUGIN_INFO_FLAGS_INTERNAL |
		                PURPLE_PLUGIN_INFO_FLAGS_AUTO_LOAD,
		NULL
	);

	g_free(description);

	return info;
}

static gboolean
gg_load(GPluginPlugin *plugin, GError **error)
{
	PurpleProtocolManager *manager = purple_protocol_manager_get_default();

	ggp_protocol_register_type(G_TYPE_MODULE(plugin));

	ggp_xfer_register(G_TYPE_MODULE(plugin));

	my_protocol = ggp_protocol_new();
	if(!purple_protocol_manager_register(manager, my_protocol, error)) {
		g_clear_object(&my_protocol);

		return FALSE;
	}

	purple_prefs_add_none("/plugins/prpl/gg");

	purple_debug_info("gg", "Loading Gadu-Gadu protocol plugin with "
		"libgadu %s...\n", gg_libgadu_version());

	ggp_libgaduw_setup();
	ggp_resolver_purple_setup();
	ggp_servconn_setup(NULL);
	ggp_html_setup();
	ggp_message_setup_global();

	purple_signal_connect(purple_get_core(), "uri-handler", plugin,
			G_CALLBACK(gg_uri_handler), NULL);

	return TRUE;
}

static gboolean
gg_unload(GPluginPlugin *plugin, G_GNUC_UNUSED gboolean shutdown,
          GError **error)
{
	PurpleProtocolManager *manager = purple_protocol_manager_get_default();

	if(!purple_protocol_manager_unregister(manager, my_protocol, error)) {
		return FALSE;
	}

	purple_signal_disconnect(purple_get_core(), "uri-handler", plugin,
			G_CALLBACK(gg_uri_handler));

	ggp_servconn_cleanup();
	ggp_html_cleanup();
	ggp_message_cleanup_global();
	ggp_libgaduw_cleanup();

	g_clear_object(&my_protocol);

	return TRUE;
}

GPLUGIN_NATIVE_PLUGIN_DECLARE(gg)

/* vim: set ts=8 sts=0 sw=8 noet: */