aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/view/dialog/UserDetailDialogFragment.java
blob: 9e036d326627ea3157fd190a6406c5a83160c739 (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
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2012-2014 lacolaco.net
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package net.lacolaco.smileessence.view.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import net.lacolaco.smileessence.Application;
import net.lacolaco.smileessence.R;
import net.lacolaco.smileessence.activity.MainActivity;
import net.lacolaco.smileessence.data.Account;
import net.lacolaco.smileessence.data.ImageCache;
import net.lacolaco.smileessence.entity.RBinding;
import net.lacolaco.smileessence.entity.User;
import net.lacolaco.smileessence.twitter.task.Timelines;
import net.lacolaco.smileessence.twitter.task.Users;
import net.lacolaco.smileessence.util.IntentUtils;
import net.lacolaco.smileessence.util.UIHandler;
import net.lacolaco.smileessence.util.UIObserverBundle;
import net.lacolaco.smileessence.view.DialogHelper;
import net.lacolaco.smileessence.view.ThreeStateButton;
import net.lacolaco.smileessence.view.adapter.TimelineAdapter;

public class UserDetailDialogFragment extends StackableDialogFragment implements View.OnClickListener,
        PullToRefreshBase.OnRefreshListener2<ListView> {

    // ------------------------------ FIELDS ------------------------------

    private static final String KEY_USER_ID = "userID";
    private TimelineAdapter adapter;
    private TextView textViewScreenName;
    private TextView textViewName;
    private TextView textViewURL;
    private TextView textViewLocate;
    private TextView textViewFollowed;
    private TextView textViewProtected;
    private TextView textViewDescription;
    private TextView textViewTweetCount;
    private TextView textViewFriendCount;
    private TextView textViewFollowerCount;
    private TextView textViewFavoriteCount;
    private NetworkImageView imageViewIcon;
    private NetworkImageView imageViewHeader;
    private ThreeStateButton buttonFollow;
    private PullToRefreshListView listViewTimeline;
    private TabHost tabHost;
    private UIObserverBundle observerBundle;
    private User user;

    // --------------------- GETTER / SETTER METHODS ---------------------

    public long getUserID() {
        return getArguments().getLong(KEY_USER_ID);
    }

    public void setUserID(long userID) {
        Bundle args = new Bundle();
        args.putLong(KEY_USER_ID, userID);
        setArguments(args);
    }

    // ------------------------ INTERFACE METHODS ------------------------


    // --------------------- Interface OnClickListener ---------------------

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.imageview_user_detail_menu: {
                openUserMenu();
                break;
            }
            case R.id.imageview_user_detail_icon: {
                IntentUtils.openUri(getActivity(), user.getProfileImageUrlOriginal());
                break;
            }
            case R.id.textview_user_detail_screenname:
            case R.id.textview_user_detail_tweet_count: {
                IntentUtils.openUri(getActivity(), user.getUserHomeURL());
                break;
            }
            case R.id.textview_user_detail_friend_count: {
                IntentUtils.openUri(getActivity(), String.format("%s/following", user.getUserHomeURL()));
                break;
            }
            case R.id.textview_user_detail_follower_count: {
                IntentUtils.openUri(getActivity(), String.format("%s/followers", user.getUserHomeURL()));
                break;
            }
            case R.id.textview_user_detail_favorite_count: {
                IntentUtils.openUri(getActivity(), String.format("%s/favorites", user.getUserHomeURL()));
                break;
            }
            case R.id.button_user_detail_follow: {
                ConfirmDialogFragment.show(getActivity(), getString(R.string.dialog_confirm_commands), this::toggleFollowing);
                break;
            }
        }
    }

    // --------------------- Interface OnRefreshListener2 ---------------------

    @Override
    public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
        Account currentAccount = getWorld().getAccount();
        new Timelines.UserTimelineTask(currentAccount, getUserID())
                .setCount(200)
                .setSinceId(adapter.getTopID())
                .onFail(x -> getWorld().notifyError(R.string.notice_error_get_user_timeline))
                .onDoneUI(tweets -> {
                    adapter.addAll(tweets);
                    updateListView(refreshView.getRefreshableView(), adapter, true);
                    refreshView.onRefreshComplete();
                })
                .execute();
    }

    @Override
    public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {
        Account currentAccount = getWorld().getAccount();
        new Timelines.UserTimelineTask(currentAccount, getUserID())
                .setCount(200)
                .setMaxId(adapter.getLastID() - 1)
                .onFail(x -> getWorld().notifyError(R.string.notice_error_get_user_timeline))
                .onDoneUI(tweets -> {
                    adapter.addAll(tweets);
                    updateListView(refreshView.getRefreshableView(), adapter, false);
                    refreshView.onRefreshComplete();
                })
                .execute();
    }

    // ------------------------ OVERRIDE METHODS ------------------------

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = User.fetch(getUserID());
        observerBundle = new UIObserverBundle();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        observerBundle.detachAll();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        MainActivity activity = (MainActivity) getActivity();
        if (user == null) {
            getWorld().notify(R.string.notice_error_show_user);
            return new DisposeDialog(activity);
        }

        View v = activity.getLayoutInflater().inflate(R.layout.dialog_user_detail, null);
        View menu = v.findViewById(R.id.imageview_user_detail_menu);
        menu.setOnClickListener(this);
        textViewScreenName = (TextView) v.findViewById(R.id.textview_user_detail_screenname);
        textViewScreenName.setOnClickListener(this);
        textViewName = (TextView) v.findViewById(R.id.textview_user_detail_name);
        textViewURL = (TextView) v.findViewById(R.id.textview_user_detail_url);
        textViewLocate = (TextView) v.findViewById(R.id.textview_user_detail_locate);
        textViewFollowed = (TextView) v.findViewById(R.id.textview_user_detail_followed);
        textViewProtected = (TextView) v.findViewById(R.id.texttview_user_detail_protected);
        textViewDescription = (TextView) v.findViewById(R.id.textview_user_detail_description);
        textViewDescription.setMovementMethod(LinkMovementMethod.getInstance());
        textViewTweetCount = (TextView) v.findViewById(R.id.textview_user_detail_tweet_count);
        textViewTweetCount.setOnClickListener(this);
        textViewFriendCount = (TextView) v.findViewById(R.id.textview_user_detail_friend_count);
        textViewFriendCount.setOnClickListener(this);
        textViewFollowerCount = (TextView) v.findViewById(R.id.textview_user_detail_follower_count);
        textViewFollowerCount.setOnClickListener(this);
        textViewFavoriteCount = (TextView) v.findViewById(R.id.textview_user_detail_favorite_count);
        textViewFavoriteCount.setOnClickListener(this);
        imageViewIcon = (NetworkImageView) v.findViewById(R.id.imageview_user_detail_icon);
        imageViewIcon.setOnClickListener(this);
        imageViewHeader = (NetworkImageView) v.findViewById(R.id.imageview_user_detail_header);
        buttonFollow = (ThreeStateButton) v.findViewById(R.id.button_user_detail_follow);
        buttonFollow.setOnClickListener(this);
        listViewTimeline = (PullToRefreshListView) v.findViewById(R.id.listview_user_detail_timeline);
        listViewTimeline.setOnRefreshListener(this);

        tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
        tabHost.setup();
        TabHost.TabSpec tab1 = tabHost.newTabSpec("tab1").setContent(R.id.tab1).setIndicator(getString(R.string.user_detail_tab_info));
        tabHost.addTab(tab1);
        TabHost.TabSpec tab2 = tabHost.newTabSpec("tab2").setContent(R.id.tab2).setIndicator(getString(R.string.user_detail_tab_timeline));
        tabHost.addTab(tab2);
        tabHost.setCurrentTab(0);

        initUserData();

        return new AlertDialog.Builder(activity)
                .setView(v)
                .setCancelable(true)
                .create();
    }

    private void executeUserTimelineTask(final TimelineAdapter adapter) {
        Account account = getWorld().getAccount();
        tabHost.getTabWidget().getChildTabViewAt(1).setVisibility(View.GONE);
        new Timelines.UserTimelineTask(account, user.getId())
                .setCount(200)
                .onFail(x -> getWorld().notifyError(R.string.notice_error_get_user_timeline))
                .onDoneUI(tweets -> {
                    adapter.addAll(tweets);
                    adapter.updateForce();
                    tabHost.getTabWidget().getChildTabViewAt(1).setVisibility(View.VISIBLE);
                })
                .execute();
    }

    private String getHtmlDescription() {
        String description = user.getDescription();
        if (TextUtils.isEmpty(description)) {
            return "";
        }
        String html = description;
        html = html.replaceAll("https?://[\\w/:%#$&?()~.=+-]+", "<a href=\"$0\">$0</a>");
        html = html.replaceAll("@([a-zA-Z0-9_]+)", "<a href=\"https://twitter.com/$1\">$0</a>");
        html = html.replaceAll("\r\n", "<br />");
        return html;
    }

    private void updateUserDataBasic() {
        textViewName.setText(user.getName());
        textViewScreenName.setText(user.getScreenName());
        textViewProtected.setVisibility(user.isProtected() ? View.VISIBLE : View.GONE);
        ImageCache.getInstance().setImageToView(user.getProfileImageUrlOriginal(), imageViewIcon);
    }

    private void updateUserDataDetail() {
        if (TextUtils.isEmpty(user.getLocation())) {
            textViewLocate.setVisibility(View.GONE);
        } else {
            textViewLocate.setText(user.getLocation());
            textViewLocate.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(user.getUrl())) {
            textViewURL.setVisibility(View.GONE);
        } else {
            textViewURL.setText(user.getUrl());
            textViewURL.setVisibility(View.VISIBLE);
        }
        textViewDescription.setText(Html.fromHtml(getHtmlDescription()));

        textViewTweetCount.setText(String.valueOf(user.getStatusesCount()));
        textViewFriendCount.setText(String.valueOf(user.getFriendsCount()));
        textViewFollowerCount.setText(String.valueOf(user.getFollowersCount()));
        textViewFavoriteCount.setText(String.valueOf(user.getFavoritesCount()));

        ImageCache.getInstance().setImageToView(user.getProfileBannerUrl(), imageViewHeader);
    }

    private void initUserData() {
        updateUserDataBasic();
        updateUserDataDetail();

        MainActivity activity = (MainActivity) getActivity();
        adapter = new TimelineAdapter(activity);
        listViewTimeline.setAdapter(adapter);
        executeUserTimelineTask(adapter);
        updateRelationship();

        observerBundle.attach(user, changes -> {
            if (getActivity() != null) {
                if (changes.contains(RBinding.BASIC))
                    updateUserDataBasic();
                if (changes.contains(RBinding.DETAIL))
                    updateUserDataDetail();
            }
        });
    }

    private void openUserMenu() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("@" + user.getScreenName())
                .setItems(R.array.user_commands, (dialog, which) -> {
                    // XXX
                    new UIHandler().postDelayed(() -> {
                        if (UserDetailDialogFragment.this.isAdded()) {
                            updateRelationship();
                        }
                    }, 1000);
                    switch (which) {
                        case 0:
                            String text = String.format("@%s ", user.getScreenName());
                            getWorld().getPostState().beginTransaction().insertText(0, text).moveCursor(text.length()).commit();
                            getWorld().notify(R.string.notice_add_to_reply);
                            break;
                        case 1:
                            DialogHelper.showDialog(getActivity(), SendMessageDialogFragment.newInstance(user));
                            break;
                        case 2:
                            ConfirmDialogFragment.show(getActivity(), getString(R.string.dialog_confirm_commands), () ->
                                    new Users.BlockTask(getWorld().getAccount(), user.getId())
                                            .onDone(user -> getWorld().notify(R.string.notice_block_succeeded))
                                            .onFail(ex -> getWorld().notifyError(R.string.notice_block_failed))
                                            .execute());
                            break;
                        case 3:
                            ConfirmDialogFragment.show(getActivity(), getString(R.string.dialog_confirm_commands), () ->
                                    new Users.UnblockTask(getWorld().getAccount(), user.getId())
                                            .onDone(user -> getWorld().notify(R.string.notice_unblock_succeeded))
                                            .onFail(x -> getWorld().notifyError(R.string.notice_unblock_failed))
                                            .execute());
                            break;
                        case 4:
                            ConfirmDialogFragment.show(getActivity(), getString(R.string.dialog_confirm_commands), () ->
                                    new Users.ReportForSpamTask(getWorld().getAccount(), user.getId())
                                            .onDone(user -> getWorld().notify(R.string.notice_r4s_succeeded))
                                            .onFail(ex -> getWorld().notifyError(R.string.notice_r4s_failed))
                                            .execute());
                            break;
                        case 5:
                            IntentUtils.openUri(getActivity(), user.getAclogTimelineURL());
                            break;
                        default:
                            throw new IllegalStateException();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void setFollowButtonState(boolean isFollowing) {
        MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity != null) {
            buttonFollow.setState(isFollowing ? ThreeStateButton.STATE_ON : ThreeStateButton.STATE_OFF);
        }
    }

    private void toggleFollowing() {
        Account account = getWorld().getAccount();
        Boolean isFollowing = buttonFollow.getState() == ThreeStateButton.STATE_ON;
        buttonFollow.setState(ThreeStateButton.STATE_LOCKED);
        if (isFollowing) {
            new Users.UnfollowTask(account, user.getId())
                    .onDoneUI(result -> {
                        getWorld().notify(R.string.notice_unfollow_succeeded);
                        updateRelationship();
                    })
                    .onFail(x ->
                            getWorld().notifyError(R.string.notice_unfollow_failed))
                    .execute();
        } else {
            new Users.FollowTask(account, user.getId())
                    .onDoneUI(result -> {
                        getWorld().notify(R.string.notice_follow_succeeded);
                        updateRelationship();
                    })
                    .onFail(x -> getWorld().notifyError(R.string.notice_follow_failed))
                    .execute();
        }
    }

    private void updateListView(AbsListView absListView, TimelineAdapter adapter, boolean addedToTop) {
        int before = adapter.getCount();
        adapter.notifyDataSetChanged(); // synchronized call (not adapter#updateForce())
        int after = adapter.getCount();
        int increments = after - before;
        if (increments > 0) {
            if (addedToTop) {
                absListView.setSelection(increments + 1);
                absListView.smoothScrollToPositionFromTop(increments, 0);
                absListView.setSelection(increments);
            } else {
                absListView.smoothScrollToPositionFromTop(before, 0);
            }
        }
    }

    private void updateRelationship() {
        Account account = getWorld().getAccount();
        if (user == account.getUser()) {
            textViewFollowed.setText(R.string.user_detail_followed_is_me);
            buttonFollow.setVisibility(View.GONE);
        } else {
            buttonFollow.setState(ThreeStateButton.STATE_LOCKED);
            textViewFollowed.setText(R.string.user_detail_loading);
            new Users.ShowFriendshipTask(account, user.getId()).onDoneUI(relationship -> {
                boolean isFollowing = relationship.isSourceFollowingTarget();
                boolean isFollowed = relationship.isSourceFollowedByTarget();
                setFollowButtonState(isFollowing);
                textViewFollowed.setText(isFollowed ? R.string.user_detail_followed : R.string.user_detail_not_followed);
            }).execute();
        }
    }
}