summaryrefslogtreecommitdiffstats
path: root/src/jrummikub/control/network/ConnectionControl.java
blob: 39fabf7c543600fa6ae57a617af87c5353af9491 (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
package jrummikub.control.network;

import java.awt.Color;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.SwingUtilities;

import jrummikub.control.RoundControl.InvalidTurnInfo;
import jrummikub.model.GameSettings;
import jrummikub.model.IRoundState;
import jrummikub.model.ITable;
import jrummikub.model.PlayerSettings;
import jrummikub.util.Event;
import jrummikub.util.Event1;
import jrummikub.util.Event2;
import jrummikub.util.GameData;
import jrummikub.util.IEvent;
import jrummikub.util.IEvent1;
import jrummikub.util.IEvent2;
import jrummikub.util.LoginData;
import jrummikub.view.LoginError;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.XMPPError.Type;
import org.jivesoftware.smack.util.Base64;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.MultiUserChat;

/**
 * Connection control managing network connections, messages and events
 */
public class ConnectionControl implements IConnectionControl {
	private static class TurnEndData implements Serializable {
		private static final long serialVersionUID = -3800572117130220737L;

		private IRoundState roundState;
		private InvalidTurnInfo invalidTurnInfo;

		TurnEndData(IRoundState roundState, InvalidTurnInfo invalidTurnInfo) {
			this.roundState = roundState;
			this.invalidTurnInfo = invalidTurnInfo;
		}

		IRoundState getRoundState() {
			return roundState;
		}

		InvalidTurnInfo getInvalidTurnInfo() {
			return invalidTurnInfo;
		}
	}

	private final static String ELEMENT_NAME = "rummikub";
	private final static String NAMESPACE = "http://home.universe-factory.net/rummikub/";

	private final static Runnable STOP_ACTION = new Runnable() {
		@Override
		public void run() {
		}
	};

	private void fixGameSettings(GameSettings settings) {
		for (PlayerSettings player : settings.getPlayerList()) {
			if (player.getType() == PlayerSettings.Type.HUMAN) {
				player.setType(PlayerSettings.Type.NETWORK);
			}

			if (player.getType() == PlayerSettings.Type.NETWORK
					&& player.getName().equals(getNickname())) {
				player.setType(PlayerSettings.Type.HUMAN);
			}
		}
	}

	private LoginData loginData;
	private volatile Connection connection;
	private volatile MultiUserChat muc;

	private Event connectedEvent = new Event();
	private Event1<LoginError> connectionFailedEvent = new Event1<LoginError>();

	private Event1<GameData> gameOfferEvent = new Event1<GameData>();
	private Event1<UUID> gameWithdrawalEvent = new Event1<UUID>();

	private Event1<String> gameJoinEvent = new Event1<String>();
	private Event1<String> gameLeaveEvent = new Event1<String>();

	private Event1<Boolean> gameJoinAckEvent = new Event1<Boolean>();

	private Event2<String, Color> changeColorEvent = new Event2<String, Color>();

	private Event gameStartEvent = new Event();
	private Event roundStartEvent = new Event();
	private Event redealEvent = new Event();
	private Event1<IRoundState> roundStateUpdateEvent = new Event1<IRoundState>();

	private Event1<ITable> tableUpdateEvent = new Event1<ITable>();
	private Event2<IRoundState, InvalidTurnInfo> turnEndEvent = new Event2<IRoundState, InvalidTurnInfo>();
	private Event nextPlayerEvent = new Event();
	private Event turnStartEvent = new Event();

	private GameData currentGame;

	private BlockingQueue<Runnable> actionQueue = new LinkedBlockingQueue<Runnable>();

	private volatile GameData offeredGame;

	/**
	 * Creates new connection control
	 * 
	 * @param loginData
	 *            player's login data
	 */
	public ConnectionControl(LoginData loginData) {
		this.loginData = loginData;
	}

	@Override
	public String getNickname() {
		return muc.getNickname();
	}

	@Override
	public void connect() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Runnable runner = null;
				do {
					try {
						runner = actionQueue.take();
						runner.run();
					} catch (InterruptedException e) {
					}
				} while (runner != STOP_ACTION);
			}
		}).start();

		run(new ConnectRunner());
	}

	@Override
	public void disconnect() {
		final Connection theConnection = connection;
		connection = null;

		connectedEvent = new Event();
		connectionFailedEvent = new Event1<LoginError>();
		run(new Runnable() {
			@Override
			public void run() {
				if (theConnection != null) {
					theConnection.disconnect();
				}
				ConnectionControl.this.run(STOP_ACTION);
			}
		});
	}

	@Override
	public IEvent getConnectedEvent() {
		return connectedEvent;
	}

	@Override
	public IEvent1<LoginError> getConnectionFailedEvent() {
		return connectionFailedEvent;
	}

	@Override
	public IEvent1<GameData> getGameOfferEvent() {
		return gameOfferEvent;
	}

	@Override
	public IEvent1<UUID> getGameWithdrawalEvent() {
		return gameWithdrawalEvent;
	}

	@Override
	public IEvent1<String> getGameJoinEvent() {
		return gameJoinEvent;
	}

	@Override
	public IEvent1<String> getGameLeaveEvent() {
		return gameLeaveEvent;
	}

	@Override
	public IEvent1<Boolean> getGameJoinAckEvent() {
		return gameJoinAckEvent;
	}

	@Override
	public IEvent2<String, Color> getChangeColorEvent() {
		return changeColorEvent;
	}

	@Override
	public IEvent getGameStartEvent() {
		return gameStartEvent;
	}

	@Override
	public IEvent getRoundStartEvent() {
		return roundStartEvent;
	}

	@Override
	public IEvent getRedealEvent() {
		return redealEvent;
	}

	@Override
	public IEvent1<IRoundState> getRoundStateUpdateEvent() {
		return roundStateUpdateEvent;
	}

	@Override
	public IEvent1<ITable> getTableUpdateEvent() {
		return tableUpdateEvent;
	}

	@Override
	public IEvent2<IRoundState, InvalidTurnInfo> getTurnEndEvent() {
		return turnEndEvent;
	}

	@Override
	public IEvent getNextPlayerEvent() {
		return nextPlayerEvent;
	}

	@Override
	public IEvent getTurnStartEvent() {
		return turnStartEvent;
	}

	@Override
	public void offerGame(GameData data) {
		offeredGame = data;
		currentGame = data;
		sendGameOffer();
	}

	@Override
	public void withdrawGame() {
		offeredGame = null;
		final UUID uuid = currentGame.getGameID();
		currentGame = null;
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_withdrawal");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	@Override
	public GameData getCurrentGame() {
		return currentGame;
	}

	@Override
	public void setCurrentGame(GameData game) {
		this.currentGame = game;
	}

	private void run(Runnable runner) {
		while (true) {
			try {
				actionQueue.put(runner);
				return;
			} catch (InterruptedException e) {
			}
		}
	}

	@Override
	public void joinGame(final GameData game) {
		setCurrentGame(game);
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_join");
				extension.setValue("uuid", game.getGameID().toString());
			}
		});
	}

	@Override
	public void leaveGame() {
		final UUID uuid = currentGame.getGameID();
		currentGame = null;
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_leave");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	@Override
	public void ackJoinGame(final String recipient, final boolean ack) {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_join_ack");
				extension.setValue("uuid", uuid.toString());
				extension.setValue("ack", Boolean.toString(ack));
			}

			@Override
			protected void modifyMessage(Message message) {
				message.setType(Message.Type.normal);
				message.setTo(muc.getRoom() + "/" + recipient);
			}
		});
	}

	@Override
	public void changeColor(final Color color) {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "change_color");
				extension.setValue("uuid", uuid.toString());
				extension.setValue("color",
						Base64.encodeObject(color, Base64.GZIP));
			}
		});
	}

	@Override
	public void startGame() {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_start");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	@Override
	public void startRound() {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "round_start");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	@Override
	public void redeal() {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "redeal");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	@Override
	public void updateRoundState(final IRoundState roundState) {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "round_state_update");
				extension.setValue("uuid", uuid.toString());
				extension.setValue("state",
						Base64.encodeObject(roundState, Base64.GZIP));
			}
		});
	}

	@Override
	public void updateTable(final ITable table) {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "table_update");
				extension.setValue("uuid", uuid.toString());
				extension.setValue("table",
						Base64.encodeObject(table, Base64.GZIP));
			}
		});
	}

	@Override
	public void endTurn(final IRoundState state,
			final InvalidTurnInfo invalidTurnInfo) {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "turn_end");
				extension.setValue("uuid", uuid.toString());
				extension.setValue("data", Base64.encodeObject(new TurnEndData(
						state, invalidTurnInfo), Base64.GZIP));
			}
		});
	}

	@Override
	public void nextPlayer() {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "next_player");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	@Override
	public void startTurn() {
		final UUID uuid = currentGame.getGameID();
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "turn_start");
				extension.setValue("uuid", uuid.toString());
			}
		});
	}

	private void sendGameOffer() {
		final GameData data = offeredGame;
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_offer");
				extension.setValue("uuid", data.getGameID().toString());
				extension.setValue("gameSettings", Base64.encodeObject(
						data.getGameSettings(), Base64.GZIP));
			}
		});
	}

	private void requestGames() {
		run(new SendRunner() {
			@Override
			protected void addData(DefaultPacketExtension extension) {
				extension.setValue("messageType", "game_request");
			}
		});
	}

	private static void emitLater(final Event event) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				event.emit();
			}
		});
	}

	private static <T> void emitLater(final Event1<T> event, final T arg) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				event.emit(arg);
			}
		});
	}

	private Message createMessage(PacketExtension extension) {
		Message message = muc.createMessage();
		message.addExtension(extension);
		return message;
	}

	private static DefaultPacketExtension createJRummikubExtension() {
		return new DefaultPacketExtension(ELEMENT_NAME, NAMESPACE);
	}

	private void processPacket(Packet packet) {
		if (connection == null) {
			return;
		}

		DefaultPacketExtension extension = (DefaultPacketExtension) packet
				.getExtension(ELEMENT_NAME, NAMESPACE);

		if (((Message) packet).getType() == Message.Type.error) {
			System.err.println("Received error message from '"
					+ packet.getFrom() + "'");
			return;
		}

		String sender = packet.getFrom();
		sender = sender.substring(sender.indexOf('/') + 1);

		String messageType = extension.getValue("messageType");

		handleMessageTypes(extension, sender, messageType);
	}

	private void handleMessageTypes(DefaultPacketExtension extension,
			String sender, String messageType) {
		if (messageType.equals("game_offer")) {
			UUID uuid = UUID.fromString(extension.getValue("uuid"));
			GameSettings settings = (GameSettings) Base64
					.decodeToObject(extension.getValue("gameSettings"));
			fixGameSettings(settings);

			GameData gameData = new GameData(uuid, settings, sender);
			gameOfferEvent.emit(gameData);
		} else if (messageType.equals("game_withdrawal")) {
			gameWithdrawalEvent
					.emit(UUID.fromString(extension.getValue("uuid")));
		} else if (messageType.equals("game_request")) {
			if (offeredGame != null) {
				sendGameOffer();
			}
		} else if (currentGame != null) {
			UUID uuid = UUID.fromString(extension.getValue("uuid"));
			if (!currentGame.getGameID().equals(uuid)) {
				return;
			}
			messagesDuringGame(extension, sender, messageType);
		}
	}

	private void messagesDuringGame(DefaultPacketExtension extension,
			String sender, String messageType) {
		if (messageType.equals("game_join")) {
			gameJoinEvent.emit(sender);
		} else if (messageType.equals("game_leave")) {
			gameLeaveEvent.emit(sender);
		} else if (messageType.equals("game_join_ack")) {
			gameJoinAckEvent.emit(Boolean.valueOf(extension.getValue("ack")));
		} else if (messageType.equals("change_color")) {
			changeColorEvent.emit(sender,
					(Color) Base64.decodeToObject(extension.getValue("color")));
		} else if (messageType.equals("game_start")) {
			gameStartEvent.emit();
		} else if (messageType.equals("round_start")) {
			roundStartEvent.emit();
		} else if (messageType.equals("redeal")) {
			redealEvent.emit();
		} else {
			messagesDuringRound(extension, messageType);
		}
	}

	private void messagesDuringRound(DefaultPacketExtension extension,
			String messageType) {
		if (messageType.equals("round_state_update")) {
			IRoundState state = (IRoundState) Base64.decodeToObject(extension
					.getValue("state"));
			fixGameSettings(state.getGameSettings());
			roundStateUpdateEvent.emit(state);
		} else if (messageType.equals("table_update")) {
			tableUpdateEvent.emit((ITable) Base64.decodeToObject(extension
					.getValue("table")));
		} else if (messageType.equals("turn_end")) {
			TurnEndData data = (TurnEndData) Base64.decodeToObject(extension
					.getValue("data"));
			fixGameSettings(data.getRoundState().getGameSettings());
			turnEndEvent.emit(data.getRoundState(), data.getInvalidTurnInfo());
		} else if (messageType.equals("next_player")) {
			nextPlayerEvent.emit();
		} else if (messageType.equals("turn_start")) {
			turnStartEvent.emit();
		} else {
			System.err.println("Received unrecognized message of type '"
					+ messageType + "'");
		}
	}

	private class ConnectRunner implements Runnable {
		@Override
		public void run() {
			ConnectionConfiguration config = new ConnectionConfiguration(
					loginData.getServerName());
			config.setSendPresence(false);
			config.setRosterLoadedAtLogin(false);
			config.setCompressionEnabled(true);

			connection = new XMPPConnection(config);

			connection.addPacketListener(new PacketListener() {
				@Override
				public void processPacket(final Packet packet) {
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							ConnectionControl.this.processPacket(packet);
						}
					});

				}
			}, new AndFilter(new PacketTypeFilter(Message.class),
					new PacketExtensionFilter(ELEMENT_NAME, NAMESPACE)));

			LoginError error = doConnect();
			if (error == null) {
				error = doLogin();
			}
			if (error == null) {
				error = doJoin();
			}

			if (error == null) {
				requestGames();
				emitLater(connectedEvent);
			} else {
				connection.disconnect();
				connection = null;

				emitLater(connectionFailedEvent, error);
			}
		}

		private LoginError doConnect() {
			try {
				connection.connect();
				return null;
			} catch (XMPPException e) {
				XMPPError xmppError = e.getXMPPError();

				if (xmppError != null) {
					if (xmppError.getType() == Type.WAIT
							&& xmppError.getCode() == 504) {
						return LoginError.UNKNOWN_HOST;
					}
				}

				e.printStackTrace();
				return LoginError.UNKNOWN_ERROR;
			}
		}

		private LoginError doLogin() {
			try {
				connection.login(loginData.getUserName(),
						loginData.getPassword(),
						"JRummikub-" + StringUtils.randomString(8));
				return null;
			} catch (XMPPException e) {
				return LoginError.AUTHENTICATION_FAILED;
			}
		}

		private LoginError doJoin() {
			muc = new MultiUserChat(connection, loginData.getChannelName());
			DiscussionHistory history = new DiscussionHistory();
			history.setMaxStanzas(0);

			String nickname = loginData.getUserName();
			// Loop until a unused nickname is found
			while (true) {
				try {
					muc.join(nickname, null, history, 10000);
					return null; // Join was successful, break the loop
				} catch (XMPPException e) {
					XMPPError xmppError = e.getXMPPError();

					if (xmppError != null && xmppError.getType() == Type.CANCEL
							&& xmppError.getCode() == 409) {
						// There was a conflict, try again with another
						// nickname
						nickname += "_";
						continue;
					} else {
						// An unknown error has occurred, cancel connect
						if (xmppError != null
								&& xmppError.getType() == Type.CANCEL
								&& xmppError.getCode() == 404) {
							return LoginError.UNKNOWN_CHANNEL;
						}

						e.printStackTrace();
						return LoginError.UNKNOWN_ERROR;
					}
				}
			}

		}
	}

	private abstract class SendRunner implements Runnable {
		@Override
		public void run() {
			// For thread safety
			Connection theConnection = connection;

			if (theConnection != null) {
				DefaultPacketExtension extension = createJRummikubExtension();
				addData(extension);
				Message message = createMessage(extension);
				modifyMessage(message);
				theConnection.sendPacket(message);
			}
		}

		abstract protected void addData(DefaultPacketExtension extension);

		protected void modifyMessage(Message message) {
		}
	}
}