aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/cgeoauth.java
blob: a9f9eea3924e6c682864e5797e8da3f1aacc3920 (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
package cgeo.geocaching;

import cgeo.geocaching.activity.AbstractActivity;

import org.apache.commons.lang3.StringUtils;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;

public class cgeoauth extends AbstractActivity {
    private String OAtoken = null;
    private String OAtokenSecret = null;
    private final Pattern paramsPattern1 = Pattern.compile("oauth_token=([a-zA-Z0-9\\-\\_.]+)");
    private final Pattern paramsPattern2 = Pattern.compile("oauth_token_secret=([a-zA-Z0-9\\-\\_.]+)");
    private Button startButton = null;
    private EditText pinEntry = null;
    private Button pinEntryButton = null;
    private ProgressDialog requestTokenDialog = null;
    private ProgressDialog changeTokensDialog = null;
    private Handler requestTokenHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (requestTokenDialog != null && requestTokenDialog.isShowing()) {
                requestTokenDialog.dismiss();
            }

            startButton.setOnClickListener(new startListener());
            startButton.setEnabled(true);

            if (msg.what == 1) {
                startButton.setText(res.getString(R.string.auth_again));

                pinEntry.setVisibility(View.VISIBLE);
                pinEntryButton.setVisibility(View.VISIBLE);
                pinEntryButton.setOnClickListener(new confirmPINListener());
            } else {
                showToast(res.getString(R.string.err_auth_initialize));
                startButton.setText(res.getString(R.string.auth_start));
            }
        }
    };
    private Handler changeTokensHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (changeTokensDialog != null && changeTokensDialog.isShowing()) {
                changeTokensDialog.dismiss();
            }

            pinEntryButton.setOnClickListener(new confirmPINListener());
            pinEntryButton.setEnabled(true);

            if (msg.what == 1) {
                showToast(res.getString(R.string.auth_dialog_completed));

                pinEntryButton.setVisibility(View.GONE);

                finish();
            } else {
                showToast(res.getString(R.string.err_auth_process));

                pinEntry.setVisibility(View.GONE);
                pinEntryButton.setVisibility(View.GONE);
                startButton.setText(res.getString(R.string.auth_start));
            }
        }
    };

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

        // init
        app.setAction("setting up");

        setTheme();
        setContentView(R.layout.auth);
        setTitle(res.getString(R.string.auth_twitter));

        init();
    }

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

    }

    private void init() {
        startButton = (Button) findViewById(R.id.start);
        pinEntry = (EditText) findViewById(R.id.pin);
        pinEntryButton = (Button) findViewById(R.id.pin_button);

        OAtoken = prefs.getString("temp-token-public", null);
        OAtokenSecret = prefs.getString("temp-token-secret", null);

        startButton.setEnabled(true);
        startButton.setOnClickListener(new startListener());

        if (StringUtils.isBlank(OAtoken) && StringUtils.isBlank(OAtokenSecret)) {
            // start authorization process
            startButton.setText(res.getString(R.string.auth_start));
        } else {
            // already have temporary tokens, continue from pin
            startButton.setText(res.getString(R.string.auth_again));

            pinEntry.setVisibility(View.VISIBLE);
            pinEntryButton.setVisibility(View.VISIBLE);
            pinEntryButton.setOnClickListener(new confirmPINListener());
        }
    }

    private void requestToken() {
        final String host = "twitter.com";
        final String pathRequest = "/oauth/request_token";
        final String pathAuthorize = "/oauth/authorize";
        final String method = "GET";

        int status = 0;
        try {
            String lineOne = null;
            HttpsURLConnection connection = null;

            try {
                final StringBuilder sb = new StringBuilder();
                final String params = cgOAuth.signOAuth(host, pathRequest, method, true, new Parameters(), null, null);

                int code = -1;
                int retries = 0;

                do {
                    // base.trustAllHosts();
                    Log.d(Settings.tag, "https://" + host + pathRequest + "?" + params);
                    final URL u = new URL("https://" + host + pathRequest + "?" + params);
                    final URLConnection uc = u.openConnection();
                    connection = (HttpsURLConnection) uc;

                    // connection.setHostnameVerifier(base.doNotVerify);
                    connection.setReadTimeout(30000);
                    connection.setRequestMethod(method);
                    HttpURLConnection.setFollowRedirects(true);
                    connection.setDoInput(true);
                    connection.setDoOutput(false);

                    final InputStream in = connection.getInputStream();
                    final InputStreamReader ins = new InputStreamReader(in);
                    final BufferedReader br = new BufferedReader(ins, 16 * 1024);

                    while ((lineOne = br.readLine()) != null) {
                        sb.append(lineOne);
                        sb.append('\n');
                    }

                    code = connection.getResponseCode();
                    retries++;

                    Log.i(Settings.tag, host + ": " + connection.getResponseCode() + " " + connection.getResponseMessage());

                    br.close();
                    in.close();
                    ins.close();
                } while (code == -1 && retries < 5);

                final String line = sb.toString();

                if (StringUtils.isNotBlank(line)) {
                    final Matcher paramsMatcher1 = paramsPattern1.matcher(line);
                    if (paramsMatcher1.find() && paramsMatcher1.groupCount() > 0) {
                        OAtoken = paramsMatcher1.group(1);
                    }
                    final Matcher paramsMatcher2 = paramsPattern2.matcher(line);
                    if (paramsMatcher2.find() && paramsMatcher2.groupCount() > 0) {
                        OAtokenSecret = paramsMatcher2.group(1);
                    }

                    if (StringUtils.isNotBlank(OAtoken) && StringUtils.isNotBlank(OAtokenSecret)) {
                        final SharedPreferences.Editor prefsEdit = getSharedPreferences(Settings.preferences, 0).edit();
                        prefsEdit.putString("temp-token-public", OAtoken);
                        prefsEdit.putString("temp-token-secret", OAtokenSecret);
                        prefsEdit.commit();

                        try {
                            final Parameters paramsPre = new Parameters();
                            paramsPre.put("oauth_callback", "oob");

                            final String paramsBrowser = cgOAuth.signOAuth(host, pathAuthorize, "GET", true, paramsPre, OAtoken, OAtokenSecret);

                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + host + pathAuthorize + "?" + paramsBrowser)));

                            status = 1;
                        } catch (Exception e) {
                            Log.e(Settings.tag, "cgeoauth.requestToken(2): " + e.toString());
                        }
                    }
                }
            } catch (IOException eio) {
                Log.e(Settings.tag, "cgeoauth.requestToken(IO): " + eio.toString() + " ~ " + connection.getResponseCode() + ": " + connection.getResponseMessage());
            } catch (Exception e) {
                Log.e(Settings.tag, "cgeoauth.requestToken(1): " + e.toString());
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        } catch (Exception e2) {
            Log.e(Settings.tag, "cgeoauth.requestToken(3): " + e2.toString());
        }

        requestTokenHandler.sendEmptyMessage(status);
    }

    private void changeToken() {
        final String host = "twitter.com";
        final String path = "/oauth/access_token";
        final String method = "POST";

        int status = 0;
        String lineOne = null;

        try {
            final Parameters paramsPre = new Parameters();
            paramsPre.put("oauth_verifier", pinEntry.getText().toString());

            int code = -1;
            int retries = 0;

            final String params = cgOAuth.signOAuth(host, path, method, true, paramsPre, OAtoken, OAtokenSecret);
            final StringBuilder sb = new StringBuilder();
            do {
                // base.trustAllHosts();
                final URL u = new URL("https://" + host + path);
                final URLConnection uc = u.openConnection();
                final HttpsURLConnection connection = (HttpsURLConnection) uc;

                // connection.setHostnameVerifier(base.doNotVerify);
                connection.setReadTimeout(30000);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(true);
                connection.setDoOutput(true);
                connection.setDoInput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);

                wr.write(params);
                wr.flush();
                wr.close();
                out.close();

                final InputStream in = connection.getInputStream();
                final InputStreamReader ins = new InputStreamReader(in);
                final BufferedReader br = new BufferedReader(ins, 16 * 1024);

                while ((lineOne = br.readLine()) != null) {
                    sb.append(lineOne);
                    sb.append('\n');
                }

                code = connection.getResponseCode();
                retries++;

                Log.i(Settings.tag, host + ": " + connection.getResponseCode() + " " + connection.getResponseMessage());

                br.close();
                ins.close();
                in.close();
                connection.disconnect();
            } while (code == -1 && retries < 5);

            final String line = sb.toString();

            OAtoken = "";
            OAtokenSecret = "";

            final Matcher paramsMatcher1 = paramsPattern1.matcher(line);
            if (paramsMatcher1.find() && paramsMatcher1.groupCount() > 0) {
                OAtoken = paramsMatcher1.group(1);
            }
            final Matcher paramsMatcher2 = paramsPattern2.matcher(line);
            if (paramsMatcher2.find() && paramsMatcher2.groupCount() > 0) {
                OAtokenSecret = paramsMatcher2.group(1);
            }

            if (StringUtils.isBlank(OAtoken) && StringUtils.isBlank(OAtokenSecret)) {
                OAtoken = "";
                OAtokenSecret = "";

                final SharedPreferences.Editor prefs = getSharedPreferences(Settings.preferences, 0).edit();
                prefs.putString("tokenpublic", null);
                prefs.putString("tokensecret", null);
                prefs.putInt("twitter", 0);
                prefs.commit();
            } else {
                final SharedPreferences.Editor prefs = getSharedPreferences(Settings.preferences, 0).edit();
                prefs.remove("temp-token-public");
                prefs.remove("temp-token-secret");
                prefs.putString("tokenpublic", OAtoken);
                prefs.putString("tokensecret", OAtokenSecret);
                prefs.putInt("twitter", 1);
                prefs.commit();

                status = 1;
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoauth.changeToken: " + e.toString());
        }

        changeTokensHandler.sendEmptyMessage(status);
    }

    private class startListener implements View.OnClickListener {

        public void onClick(View arg0) {
            if (requestTokenDialog == null) {
                requestTokenDialog = new ProgressDialog(cgeoauth.this);
                requestTokenDialog.setCancelable(false);
                requestTokenDialog.setMessage(res.getString(R.string.auth_dialog_wait));
            }
            requestTokenDialog.show();
            startButton.setEnabled(false);
            startButton.setOnTouchListener(null);
            startButton.setOnClickListener(null);

            final SharedPreferences.Editor prefs = getSharedPreferences(Settings.preferences, 0).edit();
            prefs.putString("temp-token-public", null);
            prefs.putString("temp-token-secret", null);
            prefs.commit();

            (new Thread() {

                @Override
                public void run() {
                    requestToken();
                }
            }).start();
        }
    }

    private class confirmPINListener implements View.OnClickListener {

        public void onClick(View arg0) {
            if (((EditText) findViewById(R.id.pin)).getText().toString().length() == 0) {
                helpDialog(res.getString(R.string.auth_dialog_pin_title), res.getString(R.string.auth_dialog_pin_message));
                return;
            }

            if (changeTokensDialog == null) {
                changeTokensDialog = new ProgressDialog(cgeoauth.this);
                changeTokensDialog.setCancelable(false);
                changeTokensDialog.setMessage(res.getString(R.string.auth_dialog_wait));
            }
            changeTokensDialog.show();
            pinEntryButton.setEnabled(false);
            pinEntryButton.setOnTouchListener(null);
            pinEntryButton.setOnClickListener(null);

            (new Thread() {

                @Override
                public void run() {
                    changeToken();
                }
            }).start();
        }
    }
}