/
ProfileActivity.java
1282 lines (1122 loc) · 45.4 KB
/
ProfileActivity.java
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
/*
* Copyright 2009 Andrew Shu
*
* This file is part of "reddit is fun".
*
* "reddit is fun" 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 3 of the License, or
* (at your option) any later version.
*
* "reddit is fun" 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 "reddit is fun". If not, see <http://www.gnu.org/licenses/>.
*/
package com.andrewshu.android.reddit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.webkit.CookieSyncManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.andrewshu.android.reddit.ThreadsListActivity.ThreadClickDialogOnClickListenerFactory;
import com.andrewshu.android.reddit.ThreadsListActivity.ThumbnailOnClickListenerFactory;
/**
* Activity to view user submissions and comments.
* Also check their link and comment karma.
*
* @author TalkLittle
*
*/
public final class ProfileActivity extends ListActivity
implements View.OnCreateContextMenuListener {
private static final String TAG = "ProfileActivity";
static final Pattern USER_PATH_PATTERN = Pattern.compile(Constants.USER_PATH_PATTERN_STRING);
// 1: link karma; 2: comment karma
static final Pattern KARMA_PATTERN = Pattern.compile(">(\\d[^<]*)<.{2,20}link karma.+>(\\d[^<]*)<.{2,20}comment karma");
private final ObjectMapper mObjectMapper = Common.getObjectMapper();
private final CommentManager mCommentManager = new CommentManager();
private BitmapManager mBitmapManager = new BitmapManager();
/** Custom list adapter that fits our threads data into the list. */
private ThingsListAdapter mThingsAdapter;
private ArrayList<ThingInfo> mThingsList;
// Lock used when modifying the mMessagesAdapter
private static final Object MESSAGE_ADAPTER_LOCK = new Object();
private final DefaultHttpClient mClient = Common.getGzipHttpClient();
// Common settings are stored here
private final RedditSettings mSettings = new RedditSettings();
// UI State
private View mVoteTargetView = null;
private ThingInfo mVoteTargetThingInfo = null;
private URLSpan[] mVoteTargetSpans = null;
// TODO: String mVoteTargetId so when you rotate, you can find the TargetThingInfo again
private DownloadProfileTask mCurrentDownloadThingsTask = null;
private final Object mCurrentDownloadThingsTaskLock = new Object();
private View mNextPreviousView = null;
private String mUsername = null;
private String mAfter = null;
private String mBefore = null;
private int mCount = 0;
private String mLastAfter = null;
private String mLastBefore = null;
private int mLastCount = 0;
private String[] mKarma = null;
private String mSortByUrl = null;
private String mSortByUrlExtra = null;
private String mJumpToThreadId = null;
private volatile String mCaptchaIden = null;
private volatile String mCaptchaUrl = null;
// ProgressDialogs with percentage bars
// private AutoResetProgressDialog mLoadingCommentsProgress;
// private int mNumVisibleMessages;
private boolean mCanChord = false;
/**
* Called when the activity starts up. Do activity initialization
* here, not in a constructor.
*
* @see Activity#onCreate
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CookieSyncManager.createInstance(getApplicationContext());
mSettings.loadRedditPreferences(this, mClient);
setRequestedOrientation(mSettings.rotation);
setTheme(mSettings.theme);
requestWindowFeature(Window.FEATURE_PROGRESS);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.profile_list_content);
if (savedInstanceState != null) {
if (Constants.LOGGING) Log.d(TAG, "using savedInstanceState");
mUsername = savedInstanceState.getString(Constants.USERNAME_KEY);
mAfter = savedInstanceState.getString(Constants.AFTER_KEY);
mBefore = savedInstanceState.getString(Constants.BEFORE_KEY);
mCount = savedInstanceState.getInt(Constants.THREAD_COUNT_KEY);
mLastAfter = savedInstanceState.getString(Constants.LAST_AFTER_KEY);
mLastBefore = savedInstanceState.getString(Constants.LAST_BEFORE_KEY);
mLastCount = savedInstanceState.getInt(Constants.THREAD_LAST_COUNT_KEY);
mKarma = savedInstanceState.getStringArray(Constants.KARMA_KEY);
mSortByUrl = savedInstanceState.getString(Constants.CommentsSort.SORT_BY_KEY);
mJumpToThreadId = savedInstanceState.getString(Constants.JUMP_TO_THREAD_ID_KEY);
mVoteTargetThingInfo = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);
// try to restore mThingsList using getLastNonConfigurationInstance()
// (separate function to avoid a compiler warning casting ArrayList<ThingInfo>
restoreLastNonConfigurationInstance();
if (mThingsList == null) {
// Load previous page of profile items
if (mLastAfter != null) {
new DownloadProfileTask(mUsername, mLastAfter, null, mLastCount).execute();
} else if (mLastBefore != null) {
new DownloadProfileTask(mUsername, null, mLastBefore, mLastCount).execute();
} else {
new DownloadProfileTask(mUsername).execute();
}
} else {
// Orientation change. Use prior instance.
resetUI(new ThingsListAdapter(this, mThingsList));
setTitle(mUsername + "'s profile");
}
return;
}
// Handle subreddit Uri passed via Intent
else if (getIntent().getData() != null) {
Matcher userPathMatcher = USER_PATH_PATTERN.matcher(getIntent().getData().getPath());
if (userPathMatcher.matches()) {
mUsername = userPathMatcher.group(1);
new DownloadProfileTask(mUsername).execute();
return;
}
}
// No username specified by Intent, so load the logged in user's profile
if (mSettings.isLoggedIn()) {
mUsername = mSettings.username;
new DownloadProfileTask(mUsername).execute();
return;
}
// Can't find a username to use. Quit.
if (Constants.LOGGING) Log.e(TAG, "Could not find a username to use for ProfileActivity");
finish();
}
@Override
protected void onResume() {
super.onResume();
CookieSyncManager.getInstance().startSync();
int previousTheme = mSettings.theme;
boolean previousLoggedIn = mSettings.isLoggedIn();
mSettings.loadRedditPreferences(this, mClient);
setRequestedOrientation(mSettings.rotation);
if (mSettings.theme != previousTheme) {
resetUI(mThingsAdapter);
}
updateNextPreviousButtons();
updateKarma();
if (mSettings.isLoggedIn() != previousLoggedIn) {
new DownloadProfileTask(mSettings.username).execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
}
}
@Override
protected void onPause() {
super.onPause();
CookieSyncManager.getInstance().stopSync();
mSettings.saveRedditPreferences(this);
}
@Override
public Object onRetainNonConfigurationInstance() {
// Avoid having to re-download and re-parse the messages list
// when rotating or opening keyboard.
return mThingsList;
}
@SuppressWarnings("unchecked")
private void restoreLastNonConfigurationInstance() {
mThingsList = (ArrayList<ThingInfo>) getLastNonConfigurationInstance();
}
/**
* Return the ThingInfo based on linear search over the names
*/
private ThingInfo findThingInfoByName(String name) {
if (name == null)
return null;
synchronized(MESSAGE_ADAPTER_LOCK) {
for (int i = 0; i < mThingsAdapter.getCount(); i++) {
if (mThingsAdapter.getItem(i).getName().equals(name))
return mThingsAdapter.getItem(i);
}
}
return null;
}
private final class ThingsListAdapter extends ArrayAdapter<ThingInfo> {
static final int THREAD_ITEM_VIEW_TYPE = 0;
static final int COMMENT_ITEM_VIEW_TYPE = 1;
private static final int VIEW_TYPE_COUNT = 2;
public boolean mIsLoading = true;
private LayoutInflater mInflater;
@Override
public int getItemViewType(int position) {
ThingInfo item = getItem(position);
if (item.getName().startsWith(Constants.THREAD_KIND)) {
return THREAD_ITEM_VIEW_TYPE;
}
if (item.getName().startsWith(Constants.COMMENT_KIND)) {
return COMMENT_ITEM_VIEW_TYPE;
}
return COMMENT_ITEM_VIEW_TYPE;
}
@Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
public boolean isEmpty() {
if (mIsLoading)
return false;
return super.isEmpty();
}
public ThingsListAdapter(Context context, List<ThingInfo> objects) {
super(context, 0, objects);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ThingInfo item = this.getItem(position);
if (getItemViewType(position) == THREAD_ITEM_VIEW_TYPE) {
// Here view may be passed in for re-use, or we make a new one.
if (convertView == null) {
view = mInflater.inflate(R.layout.threads_list_item, null);
} else {
view = convertView;
}
ThreadsListActivity.fillThreadsListItemView(view, item, ProfileActivity.this, mSettings,
mBitmapManager, true, thumbnailOnClickListenerFactory);
}
else if (getItemViewType(position) == COMMENT_ITEM_VIEW_TYPE) {
// Here view may be passed in for re-use, or we make a new one.
if (convertView == null) {
view = mInflater.inflate(R.layout.comments_list_item, null);
} else {
view = convertView;
}
CommentsListActivity.fillCommentsListItemView(view, item, ProfileActivity.this, mSettings, mCommentManager);
view.setPadding(15, 5, 0, 5);
}
return view;
}
} // End of MessagesListAdapter
/**
* Called when user clicks an item in the list. Mark message read.
* If item was already focused, open a dialog.
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
ThingInfo item = mThingsAdapter.getItem(position);
// Mark the message/comment as selected
mVoteTargetThingInfo = item;
mVoteTargetView = v;
if (item.getName().startsWith(Constants.THREAD_KIND)) {
showDialog(Constants.DIALOG_THREAD_CLICK);
} else {
openContextMenu(v);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int rowId = (int) info.id;
ThingInfo item = mThingsAdapter.getItem(rowId);
// Mark the message/comment as selected
mVoteTargetThingInfo = item;
mVoteTargetView = v;
if (item.getName().startsWith(Constants.THREAD_KIND)) {
menu.add(0, Constants.DIALOG_THREAD_CLICK, Menu.NONE, "Go to thread");
} else {
// TODO: include the context!
menu.add(0, Constants.DIALOG_COMMENT_CLICK, Menu.NONE, "Go to comment");
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case Constants.DIALOG_COMMENT_CLICK:
i = new Intent(getApplicationContext(), CommentsListActivity.class);
i.setData(Util.createCommentUri(mVoteTargetThingInfo, 0));
i.putExtra(Constants.EXTRA_SUBREDDIT, mVoteTargetThingInfo.getSubreddit());
i.putExtra(Constants.EXTRA_TITLE, mVoteTargetThingInfo.getTitle());
startActivity(i);
return true;
case Constants.DIALOG_THREAD_CLICK:
// Launch an Intent for CommentsListActivity
CacheInfo.invalidateCachedThread(getApplicationContext());
i = new Intent(getApplicationContext(), CommentsListActivity.class);
i.setData(Util.createThreadUri(mVoteTargetThingInfo));
i.putExtra(Constants.EXTRA_SUBREDDIT, mVoteTargetThingInfo.getSubreddit());
i.putExtra(Constants.EXTRA_TITLE, mVoteTargetThingInfo.getTitle());
i.putExtra(Constants.EXTRA_NUM_COMMENTS, Integer.valueOf(mVoteTargetThingInfo.getNum_comments()));
startActivity(i);
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* Resets the output UI list contents, retains session state.
* @param messagesAdapter A MessagesListAdapter to use. Pass in null if you want a new empty one created.
*/
void resetUI(ThingsListAdapter messagesAdapter) {
setTheme(mSettings.theme);
setContentView(R.layout.profile_list_content);
registerForContextMenu(getListView());
if (mSettings.alwaysShowNextPrevious) {
// Set mNextPreviousView to null; we can use findViewById(R.id.next_previous_layout).
mNextPreviousView = null;
} else {
// If we are not using the persistent navbar, then show as ListView footer instead
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mNextPreviousView = inflater.inflate(R.layout.next_previous_list_item, null);
getListView().addFooterView(mNextPreviousView);
}
synchronized (MESSAGE_ADAPTER_LOCK) {
if (messagesAdapter == null) {
// Reset the list to be empty.
mThingsList = new ArrayList<ThingInfo>();
mThingsAdapter = new ThingsListAdapter(this, mThingsList);
} else {
mThingsAdapter = messagesAdapter;
}
setListAdapter(mThingsAdapter);
mThingsAdapter.mIsLoading = false;
mThingsAdapter.notifyDataSetChanged(); // Just in case
}
getListView().setDivider(null);
Common.updateListDrawables(this, mSettings.theme);
updateNextPreviousButtons();
}
private void enableLoadingScreen() {
if (Util.isLightTheme(mSettings.theme)) {
setContentView(R.layout.loading_light);
} else {
setContentView(R.layout.loading_dark);
}
synchronized (MESSAGE_ADAPTER_LOCK) {
if (mThingsAdapter != null)
mThingsAdapter.mIsLoading = true;
}
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 0);
}
private void disableLoadingScreen() {
resetUI(mThingsAdapter);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 10000);
}
private void updateNextPreviousButtons() {
Common.updateNextPreviousButtons(this, mNextPreviousView, mAfter, mBefore, mCount, mSettings,
downloadAfterOnClickListener, downloadBeforeOnClickListener);
}
private void updateKarma() {
if (mKarma == null)
return;
View karmaLayout = findViewById(R.id.karma_layout);
View karmaLayoutBorder = findViewById(R.id.karma_border_bottom);
if (karmaLayout != null && karmaLayoutBorder != null) {
if (Util.isLightTheme(mSettings.theme)) {
karmaLayout.setBackgroundResource(R.color.white);
karmaLayoutBorder.setBackgroundResource(R.color.black);
} else {
karmaLayoutBorder.setBackgroundResource(R.color.white);
}
TextView linkKarma = (TextView) findViewById(R.id.link_karma);
TextView commentKarma = (TextView) findViewById(R.id.comment_karma);
linkKarma.setText(mKarma[0] + " link karma");
commentKarma.setText(mKarma[1] + " comment karma");
}
}
private class DownloadProfileTask extends AsyncTask<Integer, Long, Void>
implements PropertyChangeListener {
private ArrayList<ThingInfo> _mThingInfos = new ArrayList<ThingInfo>();
private long _mContentLength;
private String mUsername;
private String mAfter;
private String mBefore;
private int mCount;
private String mLastAfter = null;
private String mLastBefore = null;
private int mLastCount = 0;
private String[] mKarma;
private String mSortByUrl;
private String mSortByUrlExtra;
public DownloadProfileTask(String username) {
this(username, null, null, Constants.DEFAULT_THREAD_DOWNLOAD_LIMIT,
ProfileActivity.this.mSortByUrl, ProfileActivity.this.mSortByUrlExtra);
}
public DownloadProfileTask(String username, String after, String before, int count) {
this(username, after, before, count,
ProfileActivity.this.mSortByUrl, ProfileActivity.this.mSortByUrlExtra);
}
/**
* The real constructor
* @param username
* @param after
* @param before
* @param count
* @param sortByUrl
* @param sortByUrlExtra
*/
public DownloadProfileTask(String username, String after, String before, int count,
String sortByUrl, String sortByUrlExtra) {
mUsername = username;
mAfter = after;
mBefore = before;
mCount = count;
mSortByUrl = sortByUrl;
mSortByUrlExtra = sortByUrlExtra;
}
protected void saveState() {
ProfileActivity.this.mLastAfter = mLastAfter;
ProfileActivity.this.mLastBefore = mLastBefore;
ProfileActivity.this.mLastCount = mLastCount;
ProfileActivity.this.mAfter = mAfter;
ProfileActivity.this.mBefore = mBefore;
ProfileActivity.this.mCount = mCount;
ProfileActivity.this.mKarma = mKarma;
ProfileActivity.this.mSortByUrl = mSortByUrl;
ProfileActivity.this.mSortByUrlExtra = mSortByUrlExtra;
}
// XXX: maxComments is unused for now
public Void doInBackground(Integer... maxComments) {
HttpEntity entity = null;
boolean isAfter = false;
boolean isBefore = false;
InputStream in = null;
ProgressInputStream pin = null;
try {
if (mKarma == null)
mKarma = getKarma();
String url;
StringBuilder sb = new StringBuilder("http://api.reddit.com/user/")
.append(mUsername.trim())
.append("/?").append(mSortByUrl).append("&")
.append(mSortByUrlExtra).append("&");
// "before" always comes back null unless you provide correct "count"
if (mAfter != null) {
// count: 25, 50, ...
sb = sb.append("count=").append(mCount)
.append("&after=").append(mAfter).append("&");
isAfter = true;
}
else if (mBefore != null) {
// count: nothing, 26, 51, ...
sb = sb.append("count=").append(mCount + 1 - Constants.DEFAULT_THREAD_DOWNLOAD_LIMIT)
.append("&before=").append(mBefore).append("&");
isBefore = true;
}
url = sb.toString();
if (Constants.LOGGING) Log.d(TAG, "url=" + url);
HttpGet request = new HttpGet(url);
HttpResponse response = mClient.execute(request);
// Read the header to get Content-Length since entity.getContentLength() returns -1
Header contentLengthHeader = response.getFirstHeader("Content-Length");
if (contentLengthHeader != null) {
_mContentLength = Long.valueOf(contentLengthHeader.getValue());
if (Constants.LOGGING) Log.d(TAG, "Content length: "+_mContentLength);
} else {
_mContentLength = -1;
if (Constants.LOGGING) Log.d(TAG, "Content length: UNAVAILABLE");
}
entity = response.getEntity();
in = entity.getContent();
// setup a special InputStream to report progress
pin = new ProgressInputStream(in, _mContentLength);
pin.addPropertyChangeListener(this);
parseThingsJSON(pin);
mLastCount = mCount;
if (isAfter)
mCount += Constants.DEFAULT_THREAD_DOWNLOAD_LIMIT;
else if (isBefore)
mCount -= Constants.DEFAULT_THREAD_DOWNLOAD_LIMIT;
saveState();
} catch (Exception e) {
if (Constants.LOGGING) Log.e(TAG, "failed", e);
} finally {
if (pin != null) {
try {
pin.close();
} catch (IOException e2) {
if (Constants.LOGGING) Log.e(TAG, "pin.close()", e2);
}
}
if (in != null) {
try {
in.close();
} catch (IOException e2) {
if (Constants.LOGGING) Log.e(TAG, "in.close()", e2);
}
}
if (entity != null) {
try {
entity.consumeContent();
} catch (Exception e2) {
if (Constants.LOGGING) Log.e(TAG, "entity.consumeContent()", e2);
}
}
}
return null;
}
private String[] getKarma() throws IOException {
String url;
StringBuilder sb = new StringBuilder("http://www.reddit.com/user/")
.append(mUsername.trim());
url = sb.toString();
if (Constants.LOGGING) Log.d(TAG, "karma url=" + url);
HttpGet request = new HttpGet(url);
HttpResponse response = mClient.execute(request);
HttpEntity entity = null;
BufferedReader in = null;
try {
entity = response.getEntity();
in = new BufferedReader(new InputStreamReader(entity.getContent()));
String line;
while ((line = in.readLine()) != null) {
Matcher m = KARMA_PATTERN.matcher(line);
if (m.find()) {
return new String[] { m.group(1), m.group(2) };
}
}
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
if (Constants.LOGGING) Log.e(TAG, "getKarma", ex);
} finally {
try {
in.close();
} catch (NullPointerException ex2) {
} catch (Exception ex2) {
if (Constants.LOGGING) Log.e(TAG, "in.close()", ex2);
}
try {
entity.consumeContent();
} catch (Exception ex2) {
if (Constants.LOGGING) Log.e(TAG, "entity.consumeContent()", ex2);
}
}
return null;
}
private void parseThingsJSON(InputStream in) throws IOException,
JsonParseException, IllegalStateException {
String genericListingError = "Not a user page listing";
try {
Listing listing = mObjectMapper.readValue(in, Listing.class);
if (!Constants.JSON_LISTING.equals(listing.getKind()))
throw new IllegalStateException(genericListingError);
// Save the modhash, after, and before
ListingData data = listing.getData();
if (Constants.EMPTY_STRING.equals(data.getModhash()))
mSettings.setModhash(null);
else
mSettings.setModhash(data.getModhash());
mLastAfter = mAfter;
mLastBefore = mBefore;
mAfter = data.getAfter();
mBefore = data.getBefore();
// Go through the children and get the ThingInfos
for (ThingListing tiContainer : data.getChildren()) {
if (Constants.COMMENT_KIND.equals(tiContainer.getKind())) {
ThingInfo ti = tiContainer.getData();
// HTML to Spanned
String unescapedHtmlBody = Html.fromHtml(ti.getBody_html()).toString();
Spanned body = Html.fromHtml(Util.convertHtmlTags(unescapedHtmlBody));
// remove last 2 newline characters
if (body.length() > 2)
ti.setSpannedBody(body.subSequence(0, body.length()-2));
else
ti.setSpannedBody(Constants.EMPTY_STRING);
_mThingInfos.add(ti);
} else if (Constants.THREAD_KIND.equals(tiContainer.getKind())) {
ThingInfo ti = tiContainer.getData();
_mThingInfos.add(tiContainer.getData());
}
}
} catch (Exception ex) {
if (Constants.LOGGING) Log.e(TAG, "parseThingsJSON", ex);
}
}
@Override
public void onPreExecute() {
synchronized (mCurrentDownloadThingsTaskLock) {
if (mCurrentDownloadThingsTask != null)
mCurrentDownloadThingsTask.cancel(true);
mCurrentDownloadThingsTask = this;
}
resetUI(null);
enableLoadingScreen();
if (_mContentLength == -1)
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_INDETERMINATE_ON);
}
@Override
public void onPostExecute(Void v) {
synchronized (mCurrentDownloadThingsTaskLock) {
mCurrentDownloadThingsTask = null;
}
synchronized(MESSAGE_ADAPTER_LOCK) {
for (ThingInfo mi : _mThingInfos)
mThingsAdapter.add(mi);
}
if (_mContentLength == -1)
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_INDETERMINATE_OFF);
disableLoadingScreen();
setTitle(String.format(getResources().getString(R.string.user_profile), mUsername));
updateNextPreviousButtons();
updateKarma();
}
@Override
public void onProgressUpdate(Long... progress) {
// 0-9999 is ok, 10000 means it's finished
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress[0].intValue() * 9999 / (int) _mContentLength);
}
public void propertyChange(PropertyChangeEvent event) {
publishProgress((Long) event.getNewValue());
}
}
private class MyLoginTask extends LoginTask {
public MyLoginTask(String username, String password) {
super(username, password, mSettings, mClient, getApplicationContext());
}
@Override
protected void onPreExecute() {
showDialog(Constants.DIALOG_LOGGING_IN);
}
@Override
protected void onPostExecute(Boolean success) {
dismissDialog(Constants.DIALOG_LOGGING_IN);
if (success) {
Toast.makeText(ProfileActivity.this, "Logged in as "+mUsername, Toast.LENGTH_SHORT).show();
showDialog(Constants.DIALOG_COMPOSE);
} else {
Common.showErrorToast(mUserError, Toast.LENGTH_LONG, ProfileActivity.this);
}
}
}
private class MyMessageComposeTask extends MessageComposeTask {
MyMessageComposeTask(Dialog dialog, ThingInfo targetThingInfo, String captcha) {
super(dialog, targetThingInfo, captcha, mCaptchaIden, mSettings, mClient, getApplicationContext());
}
@Override
public void onPreExecute() {
showDialog(Constants.DIALOG_COMPOSING);
}
@Override
public void onPostExecute(Boolean success) {
dismissDialog(Constants.DIALOG_COMPOSING);
if (success) {
Toast.makeText(ProfileActivity.this, "Message sent.", Toast.LENGTH_SHORT).show();
// TODO: add the reply beneath the original, OR redirect to sent messages page
} else {
Common.showErrorToast(_mUserError, Toast.LENGTH_LONG, ProfileActivity.this);
new MyCaptchaDownloadTask(_mDialog).execute();
}
}
}
private class MyVoteTask extends VoteTask {
private int _mPreviousScore;
private Boolean _mPreviousLikes;
private ThingInfo _mTargetThingInfo;
public MyVoteTask(ThingInfo thingInfo, int direction, String subreddit) {
super(thingInfo.getName(), direction, subreddit, getApplicationContext(), mSettings, mClient);
_mTargetThingInfo = thingInfo;
_mPreviousScore = thingInfo.getScore();
_mPreviousLikes = thingInfo.getLikes();
}
@Override
public void onPreExecute() {
if (!_mSettings.isLoggedIn()) {
Common.showErrorToast("You must be logged in to vote.", Toast.LENGTH_LONG, _mContext);
cancel(true);
return;
}
if (_mDirection < -1 || _mDirection > 1) {
if (Constants.LOGGING) Log.e(TAG, "WTF: _mDirection = " + _mDirection);
throw new RuntimeException("How the hell did you vote something besides -1, 0, or 1?");
}
int newScore;
Boolean newLikes;
_mPreviousScore = Integer.valueOf(_mTargetThingInfo.getScore());
_mPreviousLikes = _mTargetThingInfo.getLikes();
if (_mPreviousLikes == null) {
if (_mDirection == 1) {
newScore = _mPreviousScore + 1;
newLikes = true;
} else if (_mDirection == -1) {
newScore = _mPreviousScore - 1;
newLikes = false;
} else {
cancel(true);
return;
}
} else if (_mPreviousLikes == true) {
if (_mDirection == 0) {
newScore = _mPreviousScore - 1;
newLikes = null;
} else if (_mDirection == -1) {
newScore = _mPreviousScore - 2;
newLikes = false;
} else {
cancel(true);
return;
}
} else {
if (_mDirection == 1) {
newScore = _mPreviousScore + 2;
newLikes = true;
} else if (_mDirection == 0) {
newScore = _mPreviousScore + 1;
newLikes = null;
} else {
cancel(true);
return;
}
}
_mTargetThingInfo.setLikes(newLikes);
_mTargetThingInfo.setScore(newScore);
mThingsAdapter.notifyDataSetChanged();
}
@Override
public void onPostExecute(Boolean success) {
if (success) {
CacheInfo.invalidateCachedSubreddit(_mContext);
} else {
// Vote failed. Undo the score.
_mTargetThingInfo.setLikes(_mPreviousLikes);
_mTargetThingInfo.setScore(_mPreviousScore);
mThingsAdapter.notifyDataSetChanged();
Common.showErrorToast(_mUserError, Toast.LENGTH_LONG, _mContext);
}
}
}
private class MyCaptchaCheckRequiredTask extends CaptchaCheckRequiredTask {
Dialog _mDialog;
public MyCaptchaCheckRequiredTask(Dialog dialog) {
super("http://www.reddit.com/message/compose/", mClient);
_mDialog = dialog;
}
@Override
protected void saveState() {
ProfileActivity.this.mCaptchaIden = _mCaptchaIden;
ProfileActivity.this.mCaptchaUrl = _mCaptchaUrl;
}
@Override
public void onPreExecute() {
// Hide send button so user can't send until we know whether he needs captcha
final Button sendButton = (Button) _mDialog.findViewById(R.id.compose_send_button);
sendButton.setVisibility(View.INVISIBLE);
// Show "loading captcha" label
final TextView loadingCaptcha = (TextView) _mDialog.findViewById(R.id.compose_captcha_loading);
loadingCaptcha.setVisibility(View.VISIBLE);
}
@Override
public void onPostExecute(Boolean required) {
final TextView captchaLabel = (TextView) _mDialog.findViewById(R.id.compose_captcha_textview);
final ImageView captchaImage = (ImageView) _mDialog.findViewById(R.id.compose_captcha_image);
final EditText captchaEdit = (EditText) _mDialog.findViewById(R.id.compose_captcha_input);
final TextView loadingCaptcha = (TextView) _mDialog.findViewById(R.id.compose_captcha_loading);
final Button sendButton = (Button) _mDialog.findViewById(R.id.compose_send_button);
if (required == null) {
Common.showErrorToast("Error retrieving captcha. Use the menu to try again.", Toast.LENGTH_LONG, ProfileActivity.this);
return;
}
if (required) {
captchaLabel.setVisibility(View.VISIBLE);
captchaImage.setVisibility(View.VISIBLE);
captchaEdit.setVisibility(View.VISIBLE);
// Launch a task to download captcha and display it
new MyCaptchaDownloadTask(_mDialog).execute();
} else {
captchaLabel.setVisibility(View.GONE);
captchaImage.setVisibility(View.GONE);
captchaEdit.setVisibility(View.GONE);
}
loadingCaptcha.setVisibility(View.GONE);
sendButton.setVisibility(View.VISIBLE);
}
}
private class MyCaptchaDownloadTask extends CaptchaDownloadTask {
Dialog _mDialog;
public MyCaptchaDownloadTask(Dialog dialog) {
super(mCaptchaUrl, mClient);
_mDialog = dialog;
}
@Override
public void onPostExecute(Drawable captcha) {
if (captcha == null) {
Common.showErrorToast("Error retrieving captcha. Use the menu to try again.", Toast.LENGTH_LONG, ProfileActivity.this);
return;
}
final ImageView composeCaptchaView = (ImageView) _mDialog.findViewById(R.id.compose_captcha_image);
composeCaptchaView.setVisibility(View.VISIBLE);
composeCaptchaView.setImageDrawable(captcha);
}
}
/**
* Populates the menu.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.compose_message_menu_id:
if (mSettings.isLoggedIn()) {