Subversion Repositories SmartDukaan

Rev

Rev 18497 | Rev 21170 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14792 manas 1
package com.saholic.profittill.main;
2
 
3
import android.app.AlertDialog;
4
import android.app.ProgressDialog;
5
import android.content.Context;
6
import android.content.DialogInterface;
7
import android.content.Intent;
8
import android.content.IntentSender;
9
import android.content.SharedPreferences;
10
import android.content.pm.PackageInfo;
11
import android.content.pm.PackageManager;
12
import android.content.res.Configuration;
15356 manas 13
import android.net.ConnectivityManager;
18082 manas 14
import android.net.Uri;
15356 manas 15
import android.os.AsyncTask;
16
import android.os.Bundle;
14792 manas 17
import android.support.v7.app.ActionBarActivity;
18
import android.telephony.TelephonyManager;
19
import android.text.TextUtils;
20
import android.util.Log;
21
import android.view.Menu;
22
import android.view.MenuItem;
23
import android.view.View;
24
import android.widget.EditText;
25
import android.widget.ImageButton;
26
import android.widget.Toast;
27
 
28
import com.facebook.Request;
29
import com.facebook.RequestAsyncTask;
30
import com.facebook.Response;
31
import com.facebook.Session;
32
import com.facebook.SessionState;
33
import com.facebook.UiLifecycleHelper;
34
import com.facebook.model.GraphUser;
35
import com.facebook.widget.LoginButton;
36
import com.google.android.gms.analytics.HitBuilders;
37
import com.google.android.gms.analytics.Tracker;
38
import com.google.android.gms.auth.GoogleAuthException;
39
import com.google.android.gms.auth.GoogleAuthUtil;
40
import com.google.android.gms.auth.UserRecoverableAuthException;
41
import com.google.android.gms.common.ConnectionResult;
42
import com.google.android.gms.common.GooglePlayServicesUtil;
43
import com.google.android.gms.common.Scopes;
44
import com.google.android.gms.common.api.GoogleApiClient;
45
import com.google.android.gms.common.api.ResultCallback;
46
import com.google.android.gms.common.api.Status;
47
import com.google.android.gms.gcm.GoogleCloudMessaging;
48
import com.google.android.gms.plus.Plus;
49
import com.google.android.gms.plus.model.people.Person;
50
import com.mixpanel.android.mpmetrics.MixpanelAPI;
51
import com.saholic.profittill.Constants.ProfitTillConstants;
52
import com.saholic.profittill.R;
14991 manas 53
import com.saholic.profittill.Utils.UtilityFunctions;
14792 manas 54
import com.testin.agent.TestinAgent;
55
 
56
import org.apache.http.HttpEntity;
57
import org.apache.http.HttpResponse;
58
import org.apache.http.NameValuePair;
59
import org.apache.http.client.HttpClient;
60
import org.apache.http.client.entity.UrlEncodedFormEntity;
61
import org.apache.http.client.methods.HttpPost;
62
import org.apache.http.impl.client.DefaultHttpClient;
63
import org.apache.http.message.BasicNameValuePair;
64
import org.apache.http.util.EntityUtils;
65
import org.json.JSONException;
66
import org.json.JSONObject;
67
 
68
import java.io.IOException;
69
import java.util.ArrayList;
70
import java.util.Arrays;
71
import java.util.Date;
72
import java.util.regex.Matcher;
73
import java.util.regex.Pattern;
74
 
75
public class LoginActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
76
    public GoogleApiClient mGoogleApiClient;
77
    String scope = "oauth2:" + Scopes.PLUS_LOGIN;
78
    private UiLifecycleHelper uiHelper;
79
    private boolean mIntentInProgress;
80
    private boolean mSignInClicked;
81
    private ConnectionResult mConnectionResult;
82
    private static final int RC_SIGN_IN = 0;
83
    public static final int REQUEST_CODE_TOKEN_AUTH =1;
84
    ArrayList<NameValuePair> nameValuePairs;
85
    ArrayList<NameValuePair> nameValuePairsGcm;
86
    SharedPreferences userData;
87
    SharedPreferences apiData;
88
    SharedPreferences.Editor inviteDataEditor;
89
    SharedPreferences inviteData;
90
    boolean FLAG=false;
91
    SharedPreferences.Editor userDataEditor;
92
    SharedPreferences.Editor apiSettingsEditor;
93
    SharedPreferences inviteD;
94
    SharedPreferences.Editor inviteDEditor;
95
    LoginButton fb_button;
96
    ImageButton facebookLogin,googlelogin;
97
    String mobile;
98
    MixpanelAPI mixpanel;
99
    GoogleCloudMessaging gcm;
100
    Context context;
101
    String regId;
15588 manas 102
    String msg = "";
14792 manas 103
    public static final String REG_ID = "regId";
104
    private static final String APP_VERSION = "appVersion";
105
    static final String TAG = "Register Activity";
106
    @Override
107
 
108
    protected void onCreate(Bundle savedInstanceState) {
109
 
110
        context = getApplicationContext();
111
        mixpanel= MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
112
        super.onCreate(savedInstanceState);
113
        uiHelper = new UiLifecycleHelper(this, statusCallback);
114
        uiHelper.onCreate(savedInstanceState);
115
        setContentView(R.layout.activity_login);
116
        TestinAgent.init(this);
117
        getSupportActionBar().hide();
118
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
119
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
120
        userDataEditor = userData.edit();
121
        apiSettingsEditor = apiData.edit();
122
        inviteData = context.getSharedPreferences("Invite_Data", Context.MODE_PRIVATE);
123
        inviteDataEditor = inviteData.edit();
124
        inviteD = getApplicationContext().getSharedPreferences("Invite", MODE_PRIVATE);
125
        inviteDEditor = inviteD.edit();
126
        facebookLogin =(ImageButton)findViewById(R.id.facebook_login_button);
127
        googlelogin =(ImageButton)findViewById(R.id.google_login_button);
128
 
129
        if(getIntent().getAction()=="Login"){
130
            nameValuePairsGcm = new ArrayList<>();
131
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
132
            nameValuePairsGcm.add(new BasicNameValuePair("result","login"));
15356 manas 133
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
14792 manas 134
            getIntent().getExtras().remove("cid");
135
            new NotificationOpenedData().execute(nameValuePairsGcm);
18082 manas 136
        }else if(getIntent().getAction()=="31"){
137
            String emailURL = String.valueOf(getIntent().getData());
138
            Uri url = Uri.parse(emailURL);
139
            String campaignId = url.getQueryParameter("campaign");
140
            if(url.getQueryParameter("intent_type").equalsIgnoreCase("url")) {
141
                Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
142
                        GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
143
                t.send(new HitBuilders.EventBuilder()
144
                        .setCategory("Message/Email")
145
                        .setAction("Message/Email Opened For User Id " + UtilityFunctions.campaignUserId(url))
146
                        .setLabel("Campaign Id " + campaignId)
147
                        .build());
148
                nameValuePairsGcm = new ArrayList<>();
149
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", UtilityFunctions.campaignUserId(url)));
150
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
151
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
152
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
153
                new NotificationOpenedData().execute(nameValuePairsGcm);
154
            }else{
155
                nameValuePairsGcm = new ArrayList<>();
156
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id","")));
157
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
158
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
159
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_login"));
160
                new NotificationOpenedData().execute(nameValuePairsGcm);
161
            }
14792 manas 162
        }
163
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
164
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
165
        t.setScreenName("Login Screen");
166
        t.send(new HitBuilders.ScreenViewBuilder().build());
167
 
168
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
169
        JSONObject props = new JSONObject();
170
        try {
171
            props.put("Screen", "Login Screen");
172
            mixpanel.track("Login Page", props);
173
        } catch (JSONException e) {
174
            e.printStackTrace();
175
        }
176
        if (Session.getActiveSession() != null) {
177
            Session.getActiveSession().closeAndClearTokenInformation();
178
        }
179
 
180
 
181
        Session.setActiveSession(null);
182
 
183
        fb_button=(LoginButton)findViewById(R.id.facebook_class_login_button);
184
 
185
        fb_button.setReadPermissions(Arrays.asList("email"));
186
 
187
        facebookLogin.setOnClickListener(new View.OnClickListener() {
188
            @Override
189
            public void onClick(View v) {
190
                if(isInternetOn()) {
191
                    if (TextUtils.isEmpty(regId)) {
192
                        regId = registerGCM();
193
                    } else {
194
 
195
                    }
196
                    fb_button.performClick();
197
                    /*if(!(inviteData.getBoolean("inviteCodeRequired",true))) {
198
                        fb_button.performClick();
199
                    }else {
200
                        if (apiData.getString("profitmandi.invitation", "false").equalsIgnoreCase("true")) {
201
                            if (inviteD.getString("invite_added", "").equalsIgnoreCase("added")) {
202
                                fb_button.performClick();
203
                            } else {
204
                                String referalCode1 = referralCode.getText().toString();
205
                                if (referalCode1.isEmpty()) {
206
                                    if (Session.getActiveSession() != null) {
207
                                        Session.getActiveSession().closeAndClearTokenInformation();
208
                                    }
209
                                    Session.setActiveSession(null);
210
                                inviteError.setVisibility(View.VISIBLE);
211
                                inviteError.setText(apiData.getString("invite.message", ""));
212
 
213
                                } else {
214
                                    for (String s : invitationCodeList) {
215
                                        if (referalCode1.equalsIgnoreCase(s)) {
216
                                            FLAG = true;
217
                                            break;
218
                                        }
219
                                    }
220
                                    if (FLAG) {
221
                                        if (Session.getActiveSession() != null) {
222
                                            Session.getActiveSession().closeAndClearTokenInformation();
223
                                        }
224
                                        Session.setActiveSession(null);
225
                                        fb_button.performClick();
226
                                    } else {
227
                                        if (Session.getActiveSession() != null) {
228
                                            Session.getActiveSession().closeAndClearTokenInformation();
229
                                        }
230
                                        Session.setActiveSession(null);
231
                                    inviteError.setVisibility(View.VISIBLE);
232
                                    inviteError.setText(apiData.getString("invite.error.message", ""));
233
                                   }
234
                                }
235
                            }
236
                        } else if (apiData.getString("profitmandi.invitation", "").equalsIgnoreCase("false")) {
237
                            fb_button.performClick();
238
                        } else {
239
                        }
240
                    }*/
241
                }
242
                else{
243
                    Toast.makeText(getApplicationContext(),"Sorry your internet is not working. Please check again",Toast.LENGTH_SHORT).show();
244
                }
245
 
246
            }
247
        });
248
        googlelogin.setOnClickListener(new View.OnClickListener() {
249
            @Override
250
            public void onClick(View v) {
251
                if(isInternetOn()) {
252
                    if (TextUtils.isEmpty(regId)) {
253
                        regId = registerGCM();
254
                        Log.d("RegisterActivity", "GCM RegId: " + regId);
255
                    } else {
256
                    }
257
                    signInWithGplus();
258
                    /*if(!(inviteData.getBoolean("inviteCodeRequired",true))) {
259
                        signInWithGplus();
260
                    }else {
261
                        if (apiData.getString("profitmandi.invitation", "false").equalsIgnoreCase("true")) {
262
                            if (inviteD.getString("invite_added", "").equalsIgnoreCase("added")) {
263
                                signInWithGplus();
264
                            } else {
265
                                String referalCode1 = referralCode.getText().toString();
266
                                if (referalCode1.isEmpty()) {
267
                                inviteError.setVisibility(View.VISIBLE);
268
                                inviteError.setText(apiData.getString("invite.error.message", ""));
269
                                } else {
270
                                    for (String s : invitationCodeList) {
271
                                        if (referalCode1.equalsIgnoreCase(s)) {
272
                                            FLAG = true;
273
                                            break;
274
                                        }
275
                                    }
276
                                    if (FLAG) {
277
                                        signInWithGplus();
278
                                    } else {
279
                                    inviteError.setVisibility(View.VISIBLE);
280
                                    inviteError.setText(apiData.getString("invite.error.message", ""));
281
 
282
                                    }
283
                                }
284
                            }
285
                        } else if (apiData.getString("profitmandi.invitation", "").equalsIgnoreCase("false")) {
286
                            signInWithGplus();
287
                        }
288
                    }*/
289
                }
290
                else{
291
                    Toast.makeText(getApplicationContext(),"Sorry your internet is not working. Please check again",Toast.LENGTH_SHORT).show();
292
                }
293
            }
294
        });
295
 
296
 
297
        mGoogleApiClient = new GoogleApiClient.Builder(this)
298
                .addConnectionCallbacks(this)
299
                .addOnConnectionFailedListener(this).addApi(Plus.API)
300
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
301
    }
302
    //
303
    /**
304
     * Sign-in into google
305
     * */
306
    private void signInWithGplus() {
307
        if (!mGoogleApiClient.isConnecting()) {
308
            mSignInClicked = true;
309
            resolveSignInError();
310
        }
311
    }
312
    private Session.StatusCallback statusCallback = new Session.StatusCallback() {
313
        @Override
314
        public void call(final Session session, SessionState state,
315
                         Exception exception) {
316
            if (state.isOpened()) {
317
                nameValuePairs = new ArrayList<NameValuePair>();
318
                nameValuePairs.add(new BasicNameValuePair("type","facebook"));
319
                nameValuePairs.add(new BasicNameValuePair("token",session.getAccessToken()+""));
320
                Request mRequest = Request.newMeRequest(session,new Request.GraphUserCallback() {
321
                    @Override
322
                    public void onCompleted(GraphUser graphUser, Response response) {
323
                        if(response.getError()==null)
324
                        {
325
                            nameValuePairs.add(new BasicNameValuePair("id",graphUser.getId()));
326
                            nameValuePairs.add(new BasicNameValuePair("name",graphUser.getName()));
327
                            //nameValuePairs.add(new BasicNameValuePair("mobile_number",mobile));
328
                            // nameValuePairs.add(new BasicNameValuePair("referrer",referalCode.getText().toString()));
329
                            Log.d("Invite Code Boolean","Boolean" +inviteData.getBoolean("inviteCodeRequired",true));
330
                            if(!(inviteData.getBoolean("inviteCodeRequired",true))) {
331
                                nameValuePairs.add(new BasicNameValuePair("utm_source",inviteData.getString("utm_source","")));
332
                                nameValuePairs.add(new BasicNameValuePair("utm_medium",inviteData.getString("utm_medium","")));
333
                                nameValuePairs.add(new BasicNameValuePair("utm_content",inviteData.getString("utm_content","")));
334
                                nameValuePairs.add(new BasicNameValuePair("utm_term",inviteData.getString("utm_term","")));
335
                                nameValuePairs.add(new BasicNameValuePair("utm_campaign",inviteData.getString("utm_campaign","")));
336
 
337
                            }/*else{
338
                                if (inviteD.getString("invite_added", "").equalsIgnoreCase("added")) {
339
                                    nameValuePairs.add(new BasicNameValuePair("referrer",inviteD.getString("ref","")));
340
                                }else {
341
                                    nameValuePairs.add(new BasicNameValuePair("referrer", referralCode.getText().toString()));
342
                                    inviteDEditor.putString("ref", referralCode.getText().toString());
343
                                    inviteDEditor.commit();
344
                                }
345
                            }*/
346
                            nameValuePairs.add(new BasicNameValuePair("profile_pic","http://graph.facebook.com/"+graphUser.getId()+"/picture"));
347
 
348
                            try{
349
                                if(graphUser.getProperty("email").toString()==null){
350
                                    //Toast.makeText(getApplicationContext(),"In if",Toast.LENGTH_SHORT).show();
351
                                    //Toast.makeText(getApplicationContext(),"User Name " + graphUser.toString(),Toast.LENGTH_SHORT).show();
352
                                }
353
                                else{
354
                                    nameValuePairs.add(new BasicNameValuePair("email",graphUser.getProperty("email").toString()));
355
                                    nameValuePairs.add(new BasicNameValuePair("gender",graphUser.getProperty("gender").toString()));
356
                                    userDataEditor.putString("email",graphUser.getProperty("email").toString());
357
                                    userDataEditor.commit();
358
                                    // Toast.makeText(getApplicationContext(),"User Name " + graphUser.getName(),Toast.LENGTH_SHORT).show();
359
                                    // Toast.makeText(getApplicationContext(),"Email " + graphUser.getProperty("email").toString(),Toast.LENGTH_SHORT).show();
360
                                    new loadData().execute();
361
                                }
362
                            }
363
                            catch (Exception e){
364
                                AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
365
                                alert.setMessage("Enter Email Id to complete registration: ");
366
                                final EditText input = new EditText(LoginActivity.this);
367
                                alert.setView(input);
368
                                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
369
                                    public void onClick(DialogInterface dialog, int whichButton) {
370
                                        String value = input.getText().toString();
371
                                        Pattern pattern;
372
                                        Matcher matcher;
373
                                        pattern = Pattern.compile(ProfitTillConstants.EMAIL_PATTERN);
374
                                        matcher = pattern.matcher(value);
375
                                        if( matcher.matches()){
376
                                            nameValuePairs.add(new BasicNameValuePair("email",value.toString()));
377
                                            userDataEditor.putString("email",value.toString());
378
                                            userDataEditor.commit();
379
                                            new loadData().execute();
380
                                        }
381
                                        else{
382
                                            Toast.makeText(getApplicationContext(),"Please enter a valid Email id",Toast.LENGTH_SHORT ).show();
383
                                            if (Session.getActiveSession() != null) {
384
                                                Session.getActiveSession().closeAndClearTokenInformation();
385
                                            }
386
                                            Session.setActiveSession(null);
387
                                        }
388
                                    }
389
                                });
390
                                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
391
                                    public void onClick(DialogInterface dialog, int whichButton) {
392
                                        // Canceled.
393
                                        if (Session.getActiveSession() != null) {
394
                                            Session.getActiveSession().closeAndClearTokenInformation();
395
                                        }
396
                                        Session.setActiveSession(null);
397
                                    }
398
                                });
399
 
400
                                alert.show();
401
                            }
402
 
403
 
404
                        }
405
                        else{
406
                            Log.e("Login Activity Facebook",response.getError()+"");
407
                        }
408
                    }
409
                });
410
                RequestAsyncTask asyncTask=mRequest.executeAsync();
411
            } else if (state.isClosed()) {
412
            }
413
        }
414
    };
415
    @Override
416
    public boolean onCreateOptionsMenu(Menu menu) {
417
        // Inflate the menu; this adds items to the action bar if it is present.
418
        getMenuInflater().inflate(R.menu.menu_login, menu);
419
        return true;
420
    }
421
 
422
    @Override
423
    public boolean onOptionsItemSelected(MenuItem item) {
424
        // Handle action bar item clicks here. The action bar will
425
        // automatically handle clicks on the Home/Up button, so long
426
        // as you specify a parent activity in AndroidManifest.xml.
427
        int id = item.getItemId();
428
 
429
        //noinspection SimplifiableIfStatement
430
        if (id == R.id.action_settings) {
431
            return true;
432
        }
433
 
434
        return super.onOptionsItemSelected(item);
435
    }
436
 
437
    /**
438
     * Method to resolve any signin errors
439
     * */
440
    private void resolveSignInError() {
441
        if (mConnectionResult.hasResolution()) {
442
            try {
443
                mIntentInProgress = true;
444
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
445
            } catch (IntentSender.SendIntentException e) {
446
                e.printStackTrace();
447
                TestinAgent.uploadException(this,"Exception in Resolve sign in error", new Exception());
448
                mIntentInProgress = false;
449
                //mGoogleApiClient.connect();
450
                revokeGplusAccess();
451
            }
452
        }
453
    }
454
 
455
    /**
456
     * Revoking access from google
457
     * */
458
    private void revokeGplusAccess() {
459
        if (mGoogleApiClient.isConnected()) {
460
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
461
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
462
                    .setResultCallback(new ResultCallback<Status>() {
463
                        @Override
464
                        public void onResult(Status arg0) {
465
                            Log.e(TAG, "User access revoked!");
466
                            mGoogleApiClient.connect();
467
                            //updateUI(false);
468
                        }
469
 
470
                    });
471
        }
472
    }
473
 
474
    @Override
475
    public void onConfigurationChanged(Configuration newConfig) {
476
        super.onConfigurationChanged(newConfig);
477
    }
478
 
479
    protected void onStart() {
480
        super.onStart();
481
        mGoogleApiClient.connect();
482
    }
483
 
484
    protected void onStop() {
485
        super.onStop();
486
        if (mGoogleApiClient.isConnected()) {
487
            mGoogleApiClient.disconnect();
488
        }
489
    }
490
 
491
    @Override
492
    public void onConnectionFailed(ConnectionResult result) {
493
        if (!result.hasResolution()) {
494
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,0).show();
495
            return;
496
        }
497
 
498
        if (!mIntentInProgress) {
499
            mConnectionResult = result;
500
            if (mSignInClicked) {
501
                resolveSignInError();
502
            }
503
        }
504
    }
505
 
506
    @Override
507
    protected void onActivityResult(int requestCode, int responseCode,
508
                                    Intent intent) {
509
        if (requestCode == RC_SIGN_IN) {
510
            if (responseCode != RESULT_OK) {
511
                mSignInClicked = false;
512
            }
513
 
514
            mIntentInProgress = false;
515
 
516
            if (!mGoogleApiClient.isConnecting()) {
517
                mGoogleApiClient.connect();
518
            }
519
        }
520
        else if (requestCode==REQUEST_CODE_TOKEN_AUTH &&responseCode==RESULT_OK){
521
            getAccessToken();
522
        }
523
        uiHelper.onActivityResult(requestCode, responseCode, intent);
524
    }
525
 
526
    private void getAccessToken() {
527
        new getToken().execute();
528
 
529
    }
530
 
531
    @Override
532
    public void onConnectionSuspended(int arg0) {
533
        mGoogleApiClient.connect();
534
    }
535
    @Override
536
    public void onConnected(Bundle arg0) {
537
        mSignInClicked = false;
538
        getAccessToken();
539
 
540
    }
541
    private void showProgressDialog()
542
    {
543
        pDlg = new ProgressDialog(LoginActivity.this);
544
        pDlg.setMessage("Logging In");
545
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
546
        pDlg.setCancelable(false);
547
        pDlg.show();
548
 
549
    }
550
    private ProgressDialog pDlg = null;
551
    class getToken extends AsyncTask<String,Integer,String> {
552
 
553
        @Override
554
        protected void onPreExecute() {
555
            showProgressDialog();
556
        }
557
        @   Override
558
        protected String doInBackground(String... params) {
559
            String id=null;
560
 
561
 
562
            String token = null;
563
            Bundle appActivities = new Bundle();
564
            appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,"MainActivity");
565
            try {
566
                token = GoogleAuthUtil.getToken(
567
                        LoginActivity.this,
568
                        Plus.AccountApi.getAccountName(mGoogleApiClient),
569
                        scope,appActivities);
570
                if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
571
                    Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
572
                    String imageUrl = currentPerson.getImage().getUrl();
573
                    int i = currentPerson.getGender();
574
                    String gender;
575
                    if(i==0){
576
                        gender="male";
577
                    }
578
                    else if (i==1){
579
                        gender="female";
580
                    }
581
                    else if(i==2) {
582
                        gender = "otherwise";
583
                    }
584
                    else {
585
                        gender = "not available";
586
                    }
587
                    nameValuePairs = new ArrayList<NameValuePair>();
588
                    nameValuePairs.add(new BasicNameValuePair("type","google"));
589
                    nameValuePairs.add(new BasicNameValuePair("id",currentPerson.getId()));
590
                    nameValuePairs.add(new BasicNameValuePair("name",currentPerson.getDisplayName()));
591
                    nameValuePairs.add(new BasicNameValuePair("email",Plus.AccountApi.getAccountName(mGoogleApiClient)));
592
                    userDataEditor.putString("email",Plus.AccountApi.getAccountName(mGoogleApiClient));
593
                    userDataEditor.commit();
594
                    nameValuePairs.add(new BasicNameValuePair("gender",gender));
595
                    nameValuePairs.add(new BasicNameValuePair("token",token));
596
                    Log.d("Invite Code Boolean","Boolean" +inviteData.getBoolean("inviteCodeRequired",true));
597
                    if(!(inviteData.getBoolean("inviteCodeRequired",true))) {
598
                        nameValuePairs.add(new BasicNameValuePair("utm_source",inviteData.getString("utm_source","")));
599
                        nameValuePairs.add(new BasicNameValuePair("utm_medium",inviteData.getString("utm_medium","")));
600
                        nameValuePairs.add(new BasicNameValuePair("utm_content",inviteData.getString("utm_content","")));
601
                        nameValuePairs.add(new BasicNameValuePair("utm_term",inviteData.getString("utm_term","")));
602
                        nameValuePairs.add(new BasicNameValuePair("utm_campaign",inviteData.getString("utm_campaign","")));
603
 
14991 manas 604
                    }
14792 manas 605
 
606
                    nameValuePairs.add(new BasicNameValuePair("profile_pic",currentPerson.getImage().getUrl()));
607
                    HttpClient httpclient = new DefaultHttpClient();
608
                    HttpPost httppost = new HttpPost(apiData.getString("user.registration.api",null));
609
                    httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
610
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
611
                    HttpResponse response = httpclient.execute(httppost);
612
                    HttpEntity entity = response.getEntity();
613
                    JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
614
                    System.out.println("JSON object in Login " + jObjGmail.toString());
615
                    String success = jObjGmail.getString("success");
616
                    if(success.equalsIgnoreCase("true")){
14991 manas 617
                        userDataEditor.putString("token",token);
14792 manas 618
                        userDataEditor.putString("referralCodeRequired",jObjGmail.getString("referrerRequired"));
619
                        userDataEditor.putString("message",jObjGmail.getString("mobileRequired"));
620
                        userDataEditor.putString("type","google");
621
                        id= jObjGmail.getString("id");
622
                        userDataEditor.putString("id",id);
623
                    }
624
                    else{
625
 
626
                    }
627
                }
628
                else{
629
                    return "failure";
630
                }
631
 
632
            } catch (IOException transientEx) {
633
                Log.e("InputOutput", transientEx.toString());
634
 
635
            } catch (UserRecoverableAuthException e) {
636
                Log.d("Here","Here " + e.getMessage());
637
                Intent recover = e.getIntent();
638
                startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
639
            } catch (GoogleAuthException authEx) {
640
                //resolveSignInError();
641
                //revokeGplusAccess();
642
                Log.e("AuthEX", authEx.toString());
643
            }catch (Exception e) {
644
                Log.e("Exception main", e.toString());
645
            }
646
            return id;
647
        }
648
        @Override
649
        protected void onPostExecute(String result){
650
            super.onPostExecute(result);
651
            userDataEditor.commit();
18497 manas 652
 
14792 manas 653
            try {
654
                if (userData.getString("id", null) == null)  {
655
                    if(mGoogleApiClient.isConnected()) {
656
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
657
                        mGoogleApiClient.disconnect();
658
                        userDataEditor.clear().commit();
659
                    }
660
                    else{
661
                        userDataEditor.clear().commit();
662
                    }
18497 manas 663
                    if(pDlg!=null){
664
                        pDlg.dismiss();
665
                    }
14792 manas 666
                } else {
14991 manas 667
                    UtilityFunctions utf = new UtilityFunctions();
668
                    new pushApkData().execute(utf.getDeviceInformation(getApplicationContext()));
669
                    //new gcmPushData().execute();
14792 manas 670
                }
671
            }catch (Exception e){
672
                e.printStackTrace();
673
            }
674
        }
675
    }
676
 
677
 
678
    @Override
679
    public void onResume() {
680
        super.onResume();
681
        uiHelper.onResume();
682
    }
683
 
684
    @Override
685
    public void onPause() {
686
        super.onPause();
687
        uiHelper.onPause();
688
    }
689
 
690
    @Override
691
    public void onDestroy() {
692
        super.onDestroy();
693
        uiHelper.onDestroy();
694
        mixpanel.flush();
695
    }
14991 manas 696
 
697
 
14792 manas 698
    @Override
699
    public void onSaveInstanceState(Bundle savedState) {
700
        super.onSaveInstanceState(savedState);
701
        uiHelper.onSaveInstanceState(savedState);
702
    }
703
    class loadData extends AsyncTask<String, Integer, String> {
704
 
705
        @Override
706
        protected void onPreExecute() {
707
            super.onPreExecute();
17463 manas 708
            showProgressDialog();
14792 manas 709
        }
710
 
711
        @Override
712
        protected String doInBackground(String... arg0) {
713
            String id=null;
714
            try {
715
                HttpClient httpclient = new DefaultHttpClient();
716
                HttpPost httppost = new HttpPost(apiData.getString("user.registration.api",null));
717
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
718
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
719
                HttpResponse response = httpclient.execute(httppost);
720
                HttpEntity entity = response.getEntity();
721
                int status = response.getStatusLine().getStatusCode();
722
                JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
723
                String success = jObjGmail.getString("success");
724
                if(success.equalsIgnoreCase("true")){
725
                    id  = jObjGmail.getString("id");
726
                    userDataEditor.putString("type","facebook");
727
                    userDataEditor.putString("id",id);
14991 manas 728
                    userDataEditor.putString("token",Session.getActiveSession().getAccessToken());
14792 manas 729
                    userDataEditor.putString("referralCodeRequired",jObjGmail.getString("referrerRequired"));
730
                    userDataEditor.putString("message",jObjGmail.getString("mobileRequired"));
731
                }
732
                else{
733
                }
734
                nameValuePairs.clear();
735
            } catch (Exception e) {
736
                Log.e("Fail 1", e.toString());
737
            }
738
            return id;
739
        }
740
 
741
        @Override
742
        protected void onPostExecute(String result) {
743
            super.onPostExecute(result);
744
            JSONObject props = new JSONObject();
745
            try {
746
                props.put("ID ", result);
747
            } catch (JSONException e) {
748
                e.printStackTrace();
749
            }
750
            mixpanel.track("Facebook",props);
751
            userDataEditor.commit();
752
            if(userData.getString("id",null)==null){
753
                Session.getActiveSession().closeAndClearTokenInformation();
754
                Session.setActiveSession(null);
755
                userDataEditor.clear().commit();
18497 manas 756
                if(pDlg!=null){
757
                    pDlg.dismiss();
758
                }
14792 manas 759
            }else {
15588 manas 760
                new  pushApkData().execute(new UtilityFunctions().getDeviceInformation(getApplicationContext()));
14991 manas 761
          /*      new gcmPushData().execute();*/
14792 manas 762
            }
763
        }
764
    }
765
 
766
    @Override
767
    public void onBackPressed() {
768
        new AlertDialog.Builder(this)
769
                .setIcon(android.R.drawable.ic_dialog_alert)
770
                .setTitle("Exit!")
771
                .setMessage("Are you sure you want to close?")
772
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
773
                {
774
                    @Override
775
                    public void onClick(DialogInterface dialog, int which) {
776
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
777
                        startMain.addCategory(Intent.CATEGORY_HOME);
778
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
779
                        startActivity(startMain);
780
                    }
781
 
782
                })
783
                .setNegativeButton("No", null)
784
                .show();
785
    }
786
 
787
    private static int getAppVersion(Context context) {
788
        try {
789
            PackageInfo packageInfo = context.getPackageManager()
790
                    .getPackageInfo(context.getPackageName(), 0);
791
            return packageInfo.versionCode;
792
        } catch (PackageManager.NameNotFoundException e) {
793
            throw new RuntimeException(e);
794
        }
795
    }
796
 
797
    private void registerInBackground() {
798
        new AsyncTask<Void, Void, String>() {
799
            @Override
800
            protected String doInBackground(Void... params) {
15588 manas 801
 
14792 manas 802
                try {
803
                    if (gcm == null) {
804
                        gcm = GoogleCloudMessaging.getInstance(context);
805
                    }
806
                    regId = gcm.register(ProfitTillConstants.GOOGLE_SENDER_ID);
807
                    Log.d("RegisterActivity", "registerInBackground - regId: "
808
                            + regId);
15588 manas 809
                    msg = "Device registered";
14792 manas 810
 
811
                } catch (IOException ex) {
812
                    msg = "Error :" + ex.getMessage();
813
                    Log.d("RegisterActivity", "Error: " + msg);
814
                }
815
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
816
                return msg;
817
            }
818
 
819
            @Override
820
            protected void onPostExecute(String msg) {
821
                /*Toast.makeText(getApplicationContext(),
822
                        "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
15588 manas 823
                        .show();
824
                        */
14792 manas 825
            }
826
        }.execute(null, null, null);
827
    }
828
 
829
    /*private void storeRegistrationId(Context context, String regId) {
830
        final SharedPreferences prefs = getSharedPreferences(
831
                MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
832
        int appVersion = getAppVersion(context);
833
        Log.i(TAG, "Saving regId on app version " + appVersion);
834
        SharedPreferences.Editor editor = prefs.edit();
835
        editor.putString(REG_ID, regId);
836
        editor.putInt(APP_VERSION, appVersion);
837
        editor.commit();
838
    }*/
839
    public String registerGCM() {
840
 
841
        gcm = GoogleCloudMessaging.getInstance(this);
842
        regId = getRegistrationId(context);
15588 manas 843
        registerInBackground();
14792 manas 844
        return regId;
845
    }
846
 
847
    private String getRegistrationId(Context context) {
848
 
849
        String registrationId = userData.getString("gcm_regid", "");
850
        if (registrationId.isEmpty()) {
851
            Log.i(TAG, "Registration not found.");
852
            return "";
853
        }
854
        return registrationId;
855
    }
856
 
857
    class gcmPushData extends AsyncTask<String, Integer, String> {
858
 
859
        @Override
860
        protected void onPreExecute() {
861
            super.onPreExecute();
862
            MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
863
            MixpanelAPI.People people = mixpanel.getPeople();
864
            JSONObject props = new JSONObject();
865
            try {
866
                mixpanel.identify(userData.getString("id",null));
867
                people.identify(userData.getString("id",null));
868
                props.put("Screen", "Logged In");
869
                people.set("$last_login",new Date());
870
                people.set("user_id" , userData.getString("id",null));
871
                mixpanel.track("Successfully Logged In", props);
872
            } catch (JSONException e) {
873
                e.printStackTrace();
874
            }
875
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
876
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
877
            t.set("&uid",userData.getString("id",null));
878
            t.send(new HitBuilders.EventBuilder()
879
                    .setCategory("Login ")
880
                    .setAction("Login Successful")
881
                    .setLabel("Successful for User" +userData.getString("id",null))
882
                    .build());
883
        }
884
 
885
        @Override
886
        protected String doInBackground(String... arg0) {
887
            String id=null;
888
            try {
889
                HttpClient httpclient = new DefaultHttpClient();
890
                HttpPost httppost = new HttpPost(apiData.getString("gcm.push.url",null));
891
                nameValuePairsGcm = new ArrayList<>();
892
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
893
                nameValuePairsGcm.add(new BasicNameValuePair("gcm_regid",regId));
894
                nameValuePairsGcm.add(new BasicNameValuePair("imeinumber",telephonyManager.getDeviceId()));
19653 manas 895
                nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id", null)));
15588 manas 896
                nameValuePairsGcm.add(new BasicNameValuePair("device_message",arg0[0]));
19653 manas 897
                nameValuePairsGcm.add(new BasicNameValuePair("androidid",UtilityFunctions.androidId(LoginActivity.this)));
14792 manas 898
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
899
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsGcm));
900
                HttpResponse response = httpclient.execute(httppost);
901
                HttpEntity entity = response.getEntity();
902
                int status = response.getStatusLine().getStatusCode();
903
 
904
                if(status == 200){
905
                    Log.d("ResponseCode GCM ",status+"");
906
                } else {
907
                    Log.d("ResponseCode GCM ",status+"");
908
                }
909
 
910
                nameValuePairsGcm.clear();
911
                Log.e("pass 1", "connection success ");
912
            } catch (Exception e) {
913
                Log.e("Fail 1", e.toString());
914
 
915
            }
916
            return id;
917
        }
918
 
919
        @Override
920
        protected void onPostExecute(String result) {
921
            super.onPostExecute(result);
14991 manas 922
            if(pDlg!=null){
923
                pDlg.dismiss();
924
            }
14792 manas 925
            userDataEditor.putString("gcm_regid", regId);
926
            userDataEditor.commit();
927
            String check = userData.getString("message","");
928
            if(userData.getString("referralCodeRequired","").equalsIgnoreCase("true")){
929
                Log.d("In if","in if" +inviteD.getString("referrerCode","").equalsIgnoreCase("") + inviteD  .getString("referrerCode","") );
930
                Intent i = new Intent(LoginActivity.this, ReferrerActivity.class);
931
                startActivity(i);
932
            }
933
            else if(check.equalsIgnoreCase("true")){
934
                    Log.d("In if","in else");
935
                    Intent i = new Intent(LoginActivity.this, MobileNumber.class);
936
                    i.putExtra("displayView", "7");
937
                    startActivity(i);
938
            }
939
            else{
940
                Intent i = new Intent(LoginActivity.this,MainActivity.class);
941
                i.putExtra("displayView","0");
942
                startActivity(i);
943
            }
944
        }
945
 
946
 
947
    }
948
 
949
    public final boolean isInternetOn() {
950
 
951
        ConnectivityManager connection =
952
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);
953
 
954
        if ( connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
955
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
956
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
957
                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
958
 
959
            return true;
960
 
961
        } else if (
962
                connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
963
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
964
 
965
            return false;
966
        }
967
        return false;
968
    }
969
    class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
970
 
971
        @Override
972
        protected void onPreExecute() {
973
            super.onPreExecute();
15588 manas 974
            Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
975
                    GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
976
            t.send(new HitBuilders.EventBuilder()
977
                    .setCategory("Notification")
978
                    .setAction("Notification Opened Login")
979
                    .setLabel("For User Id " + userData.getString("id","0"))
980
                    .build());
14792 manas 981
        }
982
 
983
        @Override
984
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
985
 
986
            try {
987
                HttpClient httpclient = new DefaultHttpClient();
988
                HttpPost httppost = new HttpPost(apiData.getString("notication.data.url","http://api.profittill.com/pushnotifications/add"));
989
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
990
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
991
                HttpResponse response = httpclient.execute(httppost);
992
                HttpEntity entity = response.getEntity();
993
                int status = response.getStatusLine().getStatusCode();
994
 
995
                if(status == 200){
996
                    Log.d("Notification Opened","Notication opened and sent to server");
997
                    Log.d("ResponseCode GCM ",status+"");
998
                } else {
999
                    Log.d("ResponseCode GCM ",status+"");
1000
                }
1001
 
1002
                nameValuePairsGcm.clear();
1003
                Log.e("pass 1", "connection success ");
1004
            } catch (Exception e) {
1005
                Log.e("Fail 1", e.toString());
1006
 
1007
            }
1008
            return "success";
1009
        }
1010
 
1011
        @Override
1012
        protected void onPostExecute(String result) {
1013
            super.onPostExecute(result);
1014
            Log.d("Notification Opened","Notication opened and login page");
1015
        }
1016
    }
14991 manas 1017
 
1018
    class pushApkData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {
1019
 
1020
        @Override
1021
        protected void onPreExecute() {
1022
            super.onPreExecute();
1023
        }
1024
 
1025
        @Override
1026
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {
1027
            try {
1028
                HttpClient httpclient = new DefaultHttpClient();
1029
                HttpPost httppost = new HttpPost("http://api.profittill.com/devices/add");
1030
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
1031
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
1032
                HttpResponse response = httpclient.execute(httppost);
1033
                HttpEntity entity = response.getEntity();
1034
                int status = response.getStatusLine().getStatusCode();
1035
                if(status == 200){
1036
                    return "success";
1037
                } else {
1038
                    return "failure";
1039
                }
1040
            } catch (Exception e) {
1041
                return null;
1042
            }
1043
        }
1044
        @Override
1045
        protected void onPostExecute(String result) {
1046
            super.onPostExecute(result);
15588 manas 1047
            new gcmPushData().execute(msg);
14991 manas 1048
        }
1049
    }
14792 manas 1050
}