Subversion Repositories SmartDukaan

Rev

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