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

import java.util.UUID;

import javax.swing.SwingUtilities;

import jrummikub.model.GameSettings;
import jrummikub.util.Event;
import jrummikub.util.Event1;
import jrummikub.util.IEvent;
import jrummikub.util.IEvent1;
import jrummikub.util.LoginData;
import jrummikub.view.IGameListPanel.GameData;

import org.jivesoftware.smack.Connection;
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.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.MultiUserChat;

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

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

	private Event connectedEvent = new Event();
	private Event connectionFailedEvent = new Event();

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

	private volatile GameData offeredGame;

	ConnectionControl(LoginData loginData) {
		this.loginData = loginData;
	}

	void connect() {
		new Thread(new ConnectRunner()).start();
	}

	void disconnect() {
		connectedEvent = new Event();
		connectionFailedEvent = new Event();
		new Thread(new DisconnectRunner()).start();

	}

	IEvent getConnectedEvent() {
		return connectedEvent;
	}

	IEvent getConnectionFailedEvent() {
		return connectionFailedEvent;
	}

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

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

	void offerGame(GameData data) {
		offeredGame = data;

		sendGameOffer();
	}

	void withdrawGame(UUID uuid) {
		offeredGame = null;

		new Thread(new SendGameWithdrawRunner(uuid)).start();
	}

	private void sendGameOffer() {
		new Thread(new SendGameOfferRunner(offeredGame)).start();
	}

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

	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) {
		DefaultPacketExtension extension = (DefaultPacketExtension) packet
				.getExtension(ELEMENT_NAME, NAMESPACE);

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

		if (messageType.equals("game_offer")) {
			String host = packet.getFrom();
			host = host.substring(host.indexOf('/') + 1);

			UUID uuid = UUID.fromString(extension.getValue("uuid"));
			GameSettings settings = (GameSettings) Base64.decodeToObject(extension
					.getValue("gameSettings"));

			GameData gameData = new GameData(uuid, settings, host);
			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();
			}
		}
	}

	private Message createGameOfferMessage(GameData data) {
		DefaultPacketExtension extension = createJRummikubExtension();

		extension.setValue("messageType", "game_offer");
		extension.setValue("uuid", data.getGameID().toString());
		extension.setValue("gameSettings",
				Base64.encodeObject(data.getGameSettings(), Base64.GZIP));

		return createMessage(extension);
	}

	private Message createGameWithdrawMessage(UUID uuid) {
		DefaultPacketExtension extension = createJRummikubExtension();

		extension.setValue("messageType", "game_withdrawal");
		extension.setValue("uuid", uuid.toString());

		return createMessage(extension);
	}

	private Message createGameRequestMessage() {
		DefaultPacketExtension extension = createJRummikubExtension();

		extension.setValue("messageType", "game_request");

		return createMessage(extension);
	}

	private class ConnectRunner implements Runnable {
		@Override
		public void run() {
			synchronized (ConnectionControl.this) {
				connection = new XMPPConnection(loginData.getServerName());

				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)));

				try {
					doConnect();
				} catch (XMPPException e) {
					connection.disconnect();
					connection = null;

					// TODO Auto-generated catch block
					e.printStackTrace();

					emitLater(connectionFailedEvent);
				}
			}
		}

		private void doConnect() throws XMPPException {
			connection.connect();
			connection.login(loginData.getUserName(), loginData.getPassword(),
					"JRummikub");
			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);
					break; // Join was successful, break the loop
				} catch (XMPPException e) {
					XMPPError error = e.getXMPPError();
					if (error.getType() == Type.CANCEL && error.getCode() == 409) {
						// There was a conflict, try again with another
						// nickname
						nickname += "_";
						continue;
					} else {
						// An unknown error has occurred, cancel connect
						throw e;
					}
				}
			}

			emitLater(connectedEvent);

			new Thread(new SendGameRequestRunner()).start();
		}
	}

	private class SendGameOfferRunner implements Runnable {
		private GameData data;

		public SendGameOfferRunner(GameData data) {
			this.data = data;
		}

		@Override
		public void run() {
			synchronized (ConnectionControl.this) {
				if (connection != null) {
					connection.sendPacket(createGameOfferMessage(data));
				}
			}
		}
	}

	private class SendGameWithdrawRunner implements Runnable {
		private UUID uuid;

		public SendGameWithdrawRunner(UUID uuid) {
			this.uuid = uuid;
		}

		@Override
		public void run() {
			synchronized (ConnectionControl.this) {
				if (connection != null) {
					connection.sendPacket(createGameWithdrawMessage(uuid));
				}
			}
		}
	}

	private class SendGameRequestRunner implements Runnable {
		@Override
		public void run() {
			synchronized (ConnectionControl.this) {
				if (connection != null) {
					connection.sendPacket(createGameRequestMessage());
				}
			}
		}
	}

	private class DisconnectRunner implements Runnable {
		@Override
		public void run() {
			synchronized (ConnectionControl.this) {
				if (connection != null) {
					connection.disconnect();
					connection = null;
				}
			}
		}
	}
}