Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SocialAuthDialogFragment.java « auth « maps « mapswithme « com « src « android - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 40cf9f8c76e09f4937d23b8f71ff29b5fe47fc8a (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
package com.mapswithme.maps.auth;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.TextView;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.PrivateVariables;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmDialogFragment;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import com.mapswithme.util.statistics.Statistics;

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

public class SocialAuthDialogFragment extends BaseMwmDialogFragment
{
  private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.MISC);
  private static final String TAG = SocialAuthDialogFragment.class.getSimpleName();
  @SuppressWarnings("NullableProblems")
  @NonNull
  private GoogleSignInClient mGoogleSignInClient;
  @NonNull
  private final CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
  @NonNull
  private final List<TokenHandler> mTokenHandlers = Arrays.asList(
      new FacebookTokenHandler(), new GoogleTokenHandler(), new PhoneTokenHandler());
  @Nullable
  private TokenHandler mCurrentTokenHandler;
  @NonNull
  private final View.OnClickListener mPhoneClickListener = (View v) ->
  {
    PhoneAuthActivity.startForResult(this);
  };
  @NonNull
  private final View.OnClickListener mGoogleClickListener = new View.OnClickListener()
  {
    @Override
    public void onClick(View v)
    {
      Intent intent = mGoogleSignInClient.getSignInIntent();
      startActivityForResult(intent, Constants.REQ_CODE_GOOGLE_SIGN_IN);
    }
  };
  @NonNull
  private final View.OnClickListener mFacebookClickListener = v -> {
    LoginManager lm = LoginManager.getInstance();
    lm.logInWithReadPermissions(SocialAuthDialogFragment.this,
                                  Constants.FACEBOOK_PERMISSIONS);
    lm.registerCallback(mFacebookCallbackManager, new FBCallback(SocialAuthDialogFragment.this));
  };
  @SuppressWarnings("NullableProblems")
  @NonNull
  private CheckBox mPrivacyPolicyCheck;
  @SuppressWarnings("NullableProblems")
  @NonNull
  private CheckBox mTermOfUseCheck;
  @SuppressWarnings("NullableProblems")
  @NonNull
  private CheckBox mPromoCheck;
  @Nullable
  private TargetFragmentCallback mTargetCallback;

  @NonNull
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState)
  {
    Dialog res = super.onCreateDialog(savedInstanceState);
    res.requestWindowFeature(Window.FEATURE_NO_TITLE);
    return res;
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setTargetCallback();
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(PrivateVariables.googleWebClientId())
        .requestEmail()
        .build();
    mGoogleSignInClient = GoogleSignIn.getClient(getActivity(), gso);
  }

  private void setTargetCallback()
  {
    try
    {
      mTargetCallback = (TargetFragmentCallback) getParentFragment();
    }
    catch (ClassCastException e)
    {
      throw new ClassCastException("Caller must implement TargetFragmentCallback interface!");
    }
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState)
  {
    View view = inflater.inflate(R.layout.fragment_auth_passport_dialog, container, false);

    setLoginButton(view, R.id.google_button, mGoogleClickListener);
    setLoginButton(view, R.id.facebook_button, mFacebookClickListener);
    setLoginButton(view, R.id.phone_button, mPhoneClickListener);

    mPromoCheck = view.findViewById(R.id.newsCheck);
    mPrivacyPolicyCheck = view.findViewById(R.id.privacyPolicyCheck);
    mPrivacyPolicyCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
      setButtonAvailability(view, isChecked && mTermOfUseCheck.isChecked(),
                            R.id.google_button, R.id.facebook_button, R.id.phone_button);
    });

    mTermOfUseCheck = view.findViewById(R.id.termOfUseCheck);
    mTermOfUseCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
      setButtonAvailability(view, isChecked && mPrivacyPolicyCheck.isChecked(),
                            R.id.google_button, R.id.facebook_button, R.id.phone_button);
    });

    linkifyPolicyView(view, R.id.privacyPolicyLink, R.string.sign_agree_pp_gdpr,
                      Framework.nativeGetPrivacyPolicyLink());

    linkifyPolicyView(view, R.id.termOfUseLink, R.string.sign_agree_tof_gdpr,
                      Framework.nativeGetTermsOfUseLink());

    setButtonAvailability(view, false, R.id.google_button, R.id.facebook_button,
                          R.id.phone_button);
    return view;
  }

  private static void setLoginButton(@NonNull View root, @IdRes int id,
                                     @NonNull View.OnClickListener clickListener)
  {
    View button = root.findViewById(id);
    button.setOnClickListener(clickListener);
  }

  private static void linkifyPolicyView(@NonNull View root, @IdRes int id, @StringRes int stringId,
                                        @NonNull String link)
  {
    TextView policyView = root.findViewById(id);
    Resources rs = policyView.getResources();
    policyView.setText(Html.fromHtml(rs.getString(stringId, link)));
    policyView.setMovementMethod(LinkMovementMethod.getInstance());
  }

  private static void setButtonAvailability(@NonNull View root, boolean available, @IdRes int... ids)
  {
    for (int id : ids)
    {
      View button = root.findViewById(id);
      button.setEnabled(available);
    }
  }

  @Override
  public void onResume()
  {
    super.onResume();
    Statistics.INSTANCE.trackEvent(Statistics.EventName.UGC_AUTH_SHOWN);
  }

  private void sendResult(int resultCode, @Nullable String socialToken,
                          @Framework.AuthTokenType int type, @Nullable String error,
                          boolean isCancel)
  {
    if (mTargetCallback == null || !mTargetCallback.isTargetAdded())
      return;

    Intent data = new Intent();
    data.putExtra(Constants.EXTRA_SOCIAL_TOKEN, socialToken);
    data.putExtra(Constants.EXTRA_TOKEN_TYPE, type);
    data.putExtra(Constants.EXTRA_AUTH_ERROR, error);
    data.putExtra(Constants.EXTRA_IS_CANCEL, isCancel);
    data.putExtra(Constants.EXTRA_PRIVACY_POLICY_ACCEPTED, mPrivacyPolicyCheck.isChecked());
    data.putExtra(Constants.EXTRA_TERMS_OF_USE_ACCEPTED, mTermOfUseCheck.isChecked());
    data.putExtra(Constants.EXTRA_PROMO_ACCEPTED, mPromoCheck.isChecked());
    mTargetCallback.onTargetFragmentResult(resultCode, data);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data)
  {
    super.onActivityResult(requestCode, resultCode, data);
    mFacebookCallbackManager.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK || data == null)
      return;

    for (TokenHandler handler : mTokenHandlers)
    {
      if (handler.checkToken(requestCode, data))
      {
        mCurrentTokenHandler = handler;
        break;
      }
    }

    if (mCurrentTokenHandler == null)
      return;

    dismissAllowingStateLoss();
  }

  @Override
  public void onDismiss(DialogInterface dialog)
  {
    int resultCode;
    String token;
    @Framework.AuthTokenType
    int type;
    if (mCurrentTokenHandler == null)
    {
      resultCode = Activity.RESULT_CANCELED;
      token = null;
      type = Framework.SOCIAL_TOKEN_INVALID;
    }
    else
    {
      resultCode = Activity.RESULT_OK;
      token = mCurrentTokenHandler.getToken();
      type = mCurrentTokenHandler.getType();
      if (TextUtils.isEmpty(token))
        throw new AssertionError("Token must be non-null while token handler is non-null!");
      if (type == Framework.SOCIAL_TOKEN_INVALID)
        throw new AssertionError("Token type must be non-invalid while token handler is non-null!");
    }

    sendResult(resultCode, token, type, null, true);
    super.onDismiss(dialog);
  }

  private static class FBCallback implements FacebookCallback<LoginResult>
  {
    @NonNull
    private final WeakReference<SocialAuthDialogFragment> mFragmentRef;

    private FBCallback(@NonNull SocialAuthDialogFragment fragment)
    {
      mFragmentRef = new WeakReference<>(fragment);
    }

    @Override
    public void onSuccess(LoginResult loginResult)
    {
      Statistics.INSTANCE.trackUGCExternalAuthSucceed(Statistics.ParamValue.FACEBOOK);
      LOGGER.d(TAG, "onSuccess");
    }

    @Override
    public void onCancel()
    {
      LOGGER.w(TAG, "onCancel");
      sendEmptyResult(Activity.RESULT_CANCELED, Framework.SOCIAL_TOKEN_FACEBOOK,
                      null, true);
    }

    @Override
    public void onError(FacebookException error)
    {
      LOGGER.e(TAG, "onError", error);
      sendEmptyResult(Activity.RESULT_CANCELED, Framework.SOCIAL_TOKEN_FACEBOOK,
                 error != null ? error.getMessage() : null, false);
    }

    private void sendEmptyResult(int resultCode, @Framework.AuthTokenType int type,
                                 @Nullable String error, boolean isCancel)
    {
      SocialAuthDialogFragment fragment = mFragmentRef.get();
      if (fragment == null)
        return;

      fragment.sendResult(resultCode, null, type, error, isCancel);
    }
  }
}