aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/org/connectbot/PortForwardListActivity.java
blob: efd4f7224e3b8086857b44658d2938e93fe31018 (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
/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 * Copyright 2007 Kenny Root, Jeffrey Sharkey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.connectbot;

import java.lang.ref.WeakReference;
import java.util.List;

import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * List all portForwards for a particular host and provide a way for users to add more portForwards,
 * edit existing portForwards, and delete portForwards.
 *
 * @author Kenny Root
 */
public class PortForwardListActivity extends AppCompatListActivity {
	public final static String TAG = "CB.PortForwardListAct";

	private static final int LISTENER_CYCLE_TIME = 500;

	protected HostDatabase hostdb;

	private List<PortForwardBean> portForwards;

	private ServiceConnection connection = null;
	protected TerminalBridge hostBridge = null;
	protected LayoutInflater inflater = null;


	protected Handler updateHandler = new Handler(new WeakReference<>(this));

	private HostBean host;

	@Override
	public void onStart() {
		super.onStart();

		this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);

		hostdb = HostDatabase.get(this);
	}

	@Override
	public void onStop() {
		super.onStop();

		this.unbindService(connection);

		hostdb = null;
	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);

		setContentView(R.layout.act_portforwardlist);

		mListView = (RecyclerView) findViewById(R.id.list);
		mListView.setHasFixedSize(true);
		mListView.setLayoutManager(new LinearLayoutManager(this));
		mListView.addItemDecoration(new ListItemDecoration(this));

		mEmptyView = findViewById(R.id.empty);

		// connect with hosts database and populate list
		this.hostdb = HostDatabase.get(this);
		host = hostdb.findHostById(hostId);

		{
			final String nickname = host != null ? host.getNickname() : null;
			final Resources resources = getResources();

			if (nickname != null) {
				this.setTitle(String.format("%s (%s)",
						resources.getText(R.string.title_port_forwards_list),
						nickname));
			}
		}

		connection = new ServiceConnection() {
			public void onServiceConnected(ComponentName className, IBinder service) {
				TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();

				hostBridge = bound.getConnectedBridge(host);
				updateHandler.sendEmptyMessage(-1);
			}

			public void onServiceDisconnected(ComponentName name) {
				hostBridge = null;
			}
		};

		this.updateList();

		this.registerForContextMenu(mListView);

		this.inflater = LayoutInflater.from(this);

		FloatingActionButton addPortForwardButton =
				(FloatingActionButton) findViewById(R.id.add_port_forward_button);
		addPortForwardButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// build dialog to prompt user about updating
				final View portForwardView = View.inflate(PortForwardListActivity.this, R.layout.dia_portforward, null);
				final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
				final Spinner typeSpinner = (Spinner) portForwardView.findViewById(R.id.portforward_type);

				typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> value, View view,
							int position, long id) {
						destEdit.setEnabled(position != 2);
					}
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

				new android.support.v7.app.AlertDialog.Builder(
								PortForwardListActivity.this, R.style.AlertDialogTheme)
						.setView(portForwardView)
						.setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								try {
									final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
									final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);

									String type = HostDatabase.PORTFORWARD_LOCAL;
									switch (typeSpinner.getSelectedItemPosition()) {
									case 0:
										type = HostDatabase.PORTFORWARD_LOCAL;
										break;
									case 1:
										type = HostDatabase.PORTFORWARD_REMOTE;
										break;
									case 2:
										type = HostDatabase.PORTFORWARD_DYNAMIC5;
										break;
									}

									// Why length(), not isEmpty(), is used: http://stackoverflow.com/q/10606725
									String sourcePort = sourcePortEdit.getText().toString();
									if (sourcePort.length() == 0) {
										sourcePort = sourcePortEdit.getHint().toString();
									}

									String destination = destEdit.getText().toString();
									if (destination.length() == 0) {
										destination = destEdit.getHint().toString();
									}

									PortForwardBean portForward = new PortForwardBean(
											host != null ? host.getId() : -1,
											nicknameEdit.getText().toString(),
											type,
											sourcePort,
											destination);

									if (hostBridge != null) {
										hostBridge.addPortForward(portForward);
										hostBridge.enablePortForward(portForward);
									}

									if (host != null && !hostdb.savePortForward(portForward)) {
										throw new SQLException("Could not save port forward");
									}

									updateHandler.sendEmptyMessage(-1);
								} catch (Exception e) {
									Log.e(TAG, "Could not update port forward", e);
									// TODO Show failure dialog.
								}
							}
						})
						.setNegativeButton(R.string.delete_neg, null).create().show();
			}

			public void onNothingSelected(AdapterView<?> arg0) {}
		});
	}

	protected void updateList() {
		if (hostBridge != null) {
			this.portForwards = hostBridge.getPortForwards();
		} else {
			if (this.hostdb == null) return;
			this.portForwards = this.hostdb.getPortForwardsForHost(host);
		}

		mAdapter = new PortForwardAdapter(this, portForwards);
		mListView.setAdapter(mAdapter);
		adjustViewVisibility();
	}

	private class PortForwardViewHolder extends ItemViewHolder {
		public final TextView nickname;
		public final TextView caption;

		public PortForwardBean portForward;

		public PortForwardViewHolder(View v) {
			super(v);

			nickname = (TextView) v.findViewById(android.R.id.text1);
			caption = (TextView) v.findViewById(android.R.id.text2);
		}

		@Override
		public void onClick(View v) {
			if (hostBridge != null) {
				if (portForward.isEnabled())
					hostBridge.disablePortForward(portForward);
				else {
					if (!hostBridge.enablePortForward(portForward))
						Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
				}

				updateHandler.sendEmptyMessage(-1);
			}
		}

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
			// Create menu to handle deleting and editing port forward
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

			menu.setHeaderTitle(portForward.getNickname());

			MenuItem edit = menu.add(R.string.portforward_edit);
			edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				public boolean onMenuItemClick(MenuItem item) {
					final View editTunnelView = View.inflate(PortForwardListActivity.this, R.layout.dia_portforward, null);

					final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
					if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType()))
						typeSpinner.setSelection(0);
					else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType()))
						typeSpinner.setSelection(1);
					else
						typeSpinner.setSelection(2);

					final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
					nicknameEdit.setText(portForward.getNickname());

					final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
					sourcePortEdit.setText(String.valueOf(portForward.getSourcePort()));

					final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
					if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
						destEdit.setEnabled(false);
					} else {
						destEdit.setText(String.format("%s:%d", portForward.getDestAddr(), portForward.getDestPort()));
					}

					typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
						public void onItemSelected(AdapterView<?> value, View view,
								int position, long id) {
							destEdit.setEnabled(position != 2);
						}

						public void onNothingSelected(AdapterView<?> arg0) {
						}
					});

					new android.support.v7.app.AlertDialog.Builder(
									PortForwardListActivity.this, R.style.AlertDialogTheme)
							.setView(editTunnelView)
							.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									try {
										if (hostBridge != null)
											hostBridge.disablePortForward(portForward);

										portForward.setNickname(nicknameEdit.getText().toString());

										switch (typeSpinner.getSelectedItemPosition()) {
										case 0:
											portForward.setType(HostDatabase.PORTFORWARD_LOCAL);
											break;
										case 1:
											portForward.setType(HostDatabase.PORTFORWARD_REMOTE);
											break;
										case 2:
											portForward.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
											break;
										}

										portForward.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
										portForward.setDest(destEdit.getText().toString());

										// Use the new settings for the existing connection.
										if (hostBridge != null)
											updateHandler.postDelayed(new Runnable() {
												public void run() {
													hostBridge.enablePortForward(portForward);
													updateHandler.sendEmptyMessage(-1);
												}
											}, LISTENER_CYCLE_TIME);


										if (!hostdb.savePortForward(portForward)) {
											throw new SQLException("Could not save port forward");
										}

										updateHandler.sendEmptyMessage(-1);
									} catch (Exception e) {
										Log.e(TAG, "Could not update port forward", e);
										// TODO Show failure dialog.
									}
								}
							})
							.setNegativeButton(android.R.string.cancel, null).create().show();

					return true;
				}
			});

			MenuItem delete = menu.add(R.string.portforward_delete);
			delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				public boolean onMenuItemClick(MenuItem item) {
					// prompt user to make sure they really want this
					new android.support.v7.app.AlertDialog.Builder(
									PortForwardListActivity.this, R.style.AlertDialogTheme)
							.setMessage(getString(R.string.delete_message, portForward.getNickname()))
							.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									try {
										// Delete the port forward from the host if needed.
										if (hostBridge != null)
											hostBridge.removePortForward(portForward);

										hostdb.deletePortForward(portForward);
									} catch (Exception e) {
										Log.e(TAG, "Could not delete port forward", e);
									}

									updateHandler.sendEmptyMessage(-1);
								}
							})
							.setNegativeButton(R.string.delete_neg, null).create().show();

					return true;
				}
			});
		}
	}

	@VisibleForTesting
	private class PortForwardAdapter extends ItemAdapter {
		private final List<PortForwardBean> portForwards;

		public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
			super(context);
			this.portForwards = portForwards;
		}

		@Override
		public PortForwardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			View v = LayoutInflater.from(parent.getContext())
					.inflate(R.layout.item_portforward, parent, false);
			PortForwardViewHolder vh = new PortForwardViewHolder(v);
			return vh;
		}

		@Override
		public void onBindViewHolder(ItemViewHolder holder, int position) {
			PortForwardViewHolder portForwardHolder = (PortForwardViewHolder) holder;
			PortForwardBean portForward = portForwards.get(position);

			portForwardHolder.portForward = portForward;
			portForwardHolder.nickname.setText(portForward.getNickname());
			portForwardHolder.caption.setText(portForward.getDescription());

			if (hostBridge != null && !portForward.isEnabled()) {
				portForwardHolder.nickname.setPaintFlags(portForwardHolder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
				portForwardHolder.caption.setPaintFlags(portForwardHolder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
			}
		}

		@Override
		public long getItemId(int position) {
			return portForwards.get(position).getId();
		}

		@Override
		public int getItemCount() {
			return portForwards.size();
		}
	}

	private static class Handler extends android.os.Handler {

		private WeakReference<PortForwardListActivity> mActivity;

		Handler(WeakReference<PortForwardListActivity> activity) {
			mActivity = activity;
		}

		@Override
		public void handleMessage(Message msg) {
			mActivity.get().updateList();
		}
	}
}