Subversion Repositories SmartDukaan

Rev

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