Subversion Repositories SmartDukaan

Rev

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