Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
21478 rajender 1
package com.saholic.profittill.main;
2
 
3
import android.app.AlertDialog;
4
import android.app.Fragment;
5
import android.app.ProgressDialog;
6
import android.content.Context;
7
import android.content.Intent;
8
import android.content.SharedPreferences;
9
import android.graphics.Bitmap;
10
import android.net.ConnectivityManager;
11
import android.net.Uri;
12
import android.os.AsyncTask;
13
import android.os.Bundle;
14
import android.os.Handler;
15
import android.util.Base64;
16
import android.util.Log;
17
import android.view.KeyEvent;
18
import android.view.LayoutInflater;
19
import android.view.View;
20
import android.view.ViewGroup;
21
import android.webkit.CookieManager;
22
import android.webkit.CookieSyncManager;
23
import android.webkit.HttpAuthHandler;
24
import android.webkit.JavascriptInterface;
25
import android.webkit.WebView;
26
import android.webkit.WebViewClient;
27
 
28
import com.google.android.gms.common.ConnectionResult;
29
import com.google.android.gms.common.api.GoogleApiClient;
30
import com.google.android.gms.plus.Plus;
31
import com.mixpanel.android.mpmetrics.MixpanelAPI;
32
import com.saholic.profittill.Constants.ProfitTillConstants;
33
import com.saholic.profittill.R;
34
import com.saholic.profittill.Utils.UtilityFunctions;
35
import com.testin.agent.TestinAgent;
36
 
37
import org.apache.http.HttpEntity;
38
import org.apache.http.HttpResponse;
39
import org.apache.http.NameValuePair;
40
import org.apache.http.client.ClientProtocolException;
41
import org.apache.http.client.HttpClient;
42
import org.apache.http.client.entity.UrlEncodedFormEntity;
43
import org.apache.http.client.methods.HttpPost;
44
import org.apache.http.entity.StringEntity;
45
import org.apache.http.impl.client.DefaultHttpClient;
46
import org.apache.http.message.BasicNameValuePair;
47
import org.apache.http.util.EntityUtils;
48
import org.json.JSONArray;
49
import org.json.JSONException;
50
import org.json.JSONObject;
51
 
52
import java.io.IOException;
53
import java.text.SimpleDateFormat;
54
import java.util.ArrayList;
55
import java.util.Date;
56
import java.util.List;
57
 
58
public class MyWallet extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
59
    WebView myWalletWebView;
60
    SharedPreferences userData;
61
    SharedPreferences apiData;
62
    SharedPreferences.Editor userDataEditor;
63
    SharedPreferences.Editor apiSettingsEditor;
64
    String saholicUrl;
65
    JSONObject jSaholic;
66
    JSONArray jsArraySaholic;
67
    int pageRedirect=0;
68
    boolean displayActionBar;
69
    String type1;
70
    public GoogleApiClient mGoogleApiClient;
71
    ArrayList<NameValuePair> nameValuePairsRawHtml;
72
    public MyWallet() {
73
 
74
    }
75
 
76
 
77
    @Override
78
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
79
                             Bundle savedInstanceState) {
80
        // Inflate the layout for this fragment
81
        View rootView = inflater.inflate(R.layout.fragment_my_wallet, container, false);
82
        TestinAgent.init(getActivity());
83
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(getActivity(), ProfitTillConstants.MIX_PANEL_TOKEN);
84
        userData = getActivity().getSharedPreferences("User_Data", Context.MODE_PRIVATE);
85
        apiData = getActivity().getSharedPreferences("API_Data", Context.MODE_PRIVATE);
86
        userDataEditor = userData.edit();
87
 
88
        apiSettingsEditor = apiData.edit();
89
        TestinAgent.setUserInfo(userData.getString("id", ""));
90
        String url = apiData.getString("mywallet.url",null);
91
        String id = userData.getString("id",null);
92
        String landingUrl = url + "?user_id=" + id;
93
        JSONObject props = new JSONObject();
94
        try {
95
            mixpanel.identify(userData.getString("id",null));
96
            props.put("Screen", "My Wallet");
97
            mixpanel.track("My Wallet", props);
98
        } catch (JSONException e) {
99
            e.printStackTrace();
100
        }
101
        type1 = userData.getString("type",null);
102
        if(isInternetOn()) {
103
            if(type1!=null && type1.equalsIgnoreCase("google")) {
104
                mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
105
                        .addConnectionCallbacks(this)
106
                        .addOnConnectionFailedListener(this).addApi(Plus.API)
107
                        .addScope(Plus.SCOPE_PLUS_LOGIN).build();
108
                mGoogleApiClient.connect();
109
            }
110
            WebClientClass webViewClient = new WebClientClass();
111
            myWalletWebView = (WebView) rootView.findViewById(R.id.myWalletWebView);
112
            myWalletWebView.setClickable(true);
113
            myWalletWebView.setFocusableInTouchMode(true);
114
            myWalletWebView.getSettings().setDomStorageEnabled(true);
115
            myWalletWebView.getSettings().setJavaScriptEnabled(true);
116
            myWalletWebView.addJavascriptInterface(new javascriptInterface(getActivity()), "HTMLOUT");
117
            if(Uri.parse(landingUrl).getHost().contains("api.profittill")) {
118
                userDataEditor.putString("saholic.data", UtilityFunctions.clearCookiesNew(landingUrl,getActivity())).commit();
119
            }
120
            CookieSyncManager.createInstance(getActivity());
121
            CookieManager cookieManager = CookieManager.getInstance();
122
            cookieManager.setCookie(url, "token="+userData.getString("token",""));
123
            cookieManager.setCookie(url, "walletAuthentication=true");
124
            myWalletWebView.loadUrl(landingUrl);
125
            myWalletWebView.setWebViewClient(webViewClient);
126
        }else{
127
            SearchFragment nextFrag= new SearchFragment();
128
            Bundle args = new Bundle();
129
            args.putString("finishingurl", landingUrl);
130
            args.putString("fragmentNumber", "17");
131
            nextFrag.setArguments(args);
132
            getActivity().getFragmentManager().beginTransaction()
133
                    .replace(R.id.frame_container, nextFrag)
134
                    .addToBackStack(null)
135
                    .commit();
136
        }
137
        return rootView;
138
 
139
    }
140
 
141
    @Override
142
    public void onViewCreated(View view, Bundle savedInstanceState) {
143
        super.onViewCreated(view, savedInstanceState);
144
    }
145
 
146
    JSONObject obj;
147
    public void getDisplayActionBar(String url) throws Exception{
148
        String snapdealConfirmation = apiData.getString("snapdeal.order.success.url",null);
149
        String flipkartConfirmation = apiData.getString("flipkart.order.success.url",null);
150
        String amazonConfirmation = apiData.getString("amazon.order.success.url",null);
151
        String amazonThankYouConfirmation = apiData.getString("amazon.order.success.thankyou.url",null);
152
        String saholicConfirmation = apiData.getString("saholic.order.success.url",null);
153
        if(url.contains(snapdealConfirmation) || url.contains(flipkartConfirmation) || url.contains(amazonConfirmation) || url.contains(amazonThankYouConfirmation) || url.contains(saholicConfirmation)){
154
            displayActionBar=true;
155
            String storeID = getStoreId(url);
156
            if(storeID==null){
157
                Log.e("Deals Page Activity", "Null value returned for storeID");
158
            }
159
            else{
160
                nameValuePairsRawHtml=new ArrayList<NameValuePair>();
161
                nameValuePairsRawHtml.add(new BasicNameValuePair("user_id",userData.getString("id",null)));
162
                nameValuePairsRawHtml.add(new BasicNameValuePair("store_id",storeID));
163
                nameValuePairsRawHtml.add(new BasicNameValuePair("order_url",url));
164
                nameValuePairsRawHtml.add(new BasicNameValuePair("sub_tag",userData.getString("subtag",null)));
165
            }
166
        }
167
        else{
168
            displayActionBar = false;
169
        }
170
        return;
171
    }
172
 
173
 
174
    public String getStoreId(String url){
175
        if(url.contains("snapdeal")){
176
            pageRedirect=Integer.parseInt(apiData.getString("pageredirect.snapdeal","0"));
177
            return apiData.getString("store.code.snapdeal",null);
178
        }
179
        else if(url.contains("flipkart")){
180
            pageRedirect=Integer.parseInt(apiData.getString("pageredirect.flipkart","0"));
181
            return apiData.getString("store.code.flipkart",null);
182
        }
183
        else if(url.contains("amazon")){
184
            pageRedirect=Integer.parseInt(apiData.getString("pageredirect.amazon","0"));
185
            return apiData.getString("store.code.amazon",null);
186
        }
187
        else if(url.contains("saholic")){
188
            return apiData.getString("store.code.spice",null);
189
        }
190
        return null;
191
    }
192
 
193
    @Override
194
    public void onConnected(Bundle bundle) {
195
 
196
    }
197
 
198
    @Override
199
    public void onConnectionSuspended(int i) {
200
 
201
    }
202
 
203
    @Override
204
    public void onConnectionFailed(ConnectionResult connectionResult) {
205
 
206
    }
207
 
208
    public class WebClientClass extends WebViewClient {
209
        ProgressDialog pd = null;
210
 
211
        @Override
212
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
213
            super.onPageStarted(view, url, favicon);
214
          try {
215
                getDisplayActionBar(url);
216
            }catch (Exception e){
217
                e.printStackTrace();
218
            }
219
        }
220
        @Override
221
        public void onPageFinished(WebView view, String url) {
222
            super.onPageFinished(view, url);
223
            obj = new JSONObject();
224
            try {
225
                if(Uri.parse(url).getHost().contains("saholic") && userData.getString("saholic.data","false").equalsIgnoreCase("true")){
226
                    saholicUrl=url;
227
                    view.loadUrl("javascript:window.HTMLOUT.saholicHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
228
                }else {
229
                    JSONObject j = new JSONObject();
230
                    JSONArray jsArray = new JSONArray();
231
                    j.put("url", url);
232
                    j.put("user_id", userData.getString("id", null));
233
                    j.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
234
                    jsArray.put(j);
235
                    obj.put("pushdata", jsArray);
236
                    new pushData().execute();
237
                }
238
            } catch (JSONException e) {
239
                e.printStackTrace();
240
            }
241
 
242
            if(displayActionBar){
243
                view.loadUrl("javascript:window.HTMLOUT.flipkartHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
244
            }
245
            view.setOnKeyListener(new View.OnKeyListener()
246
            {
247
                @Override
248
                public boolean onKey(View v, int keyCode, KeyEvent event)
249
                {
250
                    if(event.getAction() == KeyEvent.ACTION_DOWN)
251
                    {
252
                        WebView webView = (WebView) v;
253
 
254
                        switch(keyCode)
255
                        {
256
                            case KeyEvent.KEYCODE_BACK:
257
                                if(webView.canGoBack())
258
                                {
259
                                    webView.goBack();
260
                                    return true;
261
                                }
262
                                else{
263
                                    Intent i = new Intent(getActivity(),MainActivity.class);
264
                                    i.putExtra("displayView","0");
265
                                    startActivity(i);
266
                                }
267
                                break;
268
                        }
269
                    }
270
 
271
                    return false;
272
                }
273
            });
274
 
275
        }
276
        @Override
277
        public void onReceivedHttpAuthRequest(WebView view,
278
                                              HttpAuthHandler handler, String host, String realm) {
279
 
280
            handler.proceed("dtr", "dtr18Feb2015");
281
 
282
        }
283
 
284
        @Override
285
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
286
            super.onReceivedError(view, errorCode, description, failingUrl);
287
            SearchFragment nextFrag= new SearchFragment();
288
            Bundle args = new Bundle();
289
            args.putString("finishingurl",failingUrl);
290
            nextFrag.setArguments(args);
291
            getActivity().getFragmentManager().beginTransaction()
292
                    .replace(R.id.frame_container, nextFrag)
293
                    .addToBackStack(null)
294
                    .commit();
295
        }
296
 
297
        @Override
298
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
299
 
300
            if(url.contains(apiData.getString("wallet.auth","api.profittill.com/special/native/login"))){
301
                /*Toast.makeText(getActivity(), apiData.getString("wallet.error", "Error while logging in to the wallet. Please log in again"), Toast.LENGTH_LONG).show();*/
302
                AlertDialog alert;
303
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
304
                builder.setMessage(apiData.getString("wallet.auth.message","You are not authenticated. Please log in again")).setCancelable(false);
305
                alert = builder.create();
306
                alert.show();
307
                android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
308
                android.webkit.CookieSyncManager.createInstance(getActivity());
309
                cookieManager.removeAllCookie();
310
                try{
311
                    if (mGoogleApiClient.isConnected()) {
312
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
313
                        mGoogleApiClient.disconnect();
314
                        mGoogleApiClient.connect();
315
                        redirectPage(alert);
316
                        /*userDataEditor.clear().commit();
317
                        startActivity(new Intent(getActivity(), LoginActivity.class));*/
318
                    }
319
                    else{
320
                        if(!mGoogleApiClient.isConnected()){
321
                            redirectPage(alert);
322
                        /*    userDataEditor.clear().commit();
323
                            startActivity(new Intent(getActivity(), LoginActivity.class));*/
324
                        }
325
                    }
326
                }catch (Exception e){
327
                    redirectPage(alert);
328
                   /* userDataEditor.clear().commit();
329
                    startActivity(new Intent(getActivity(), LoginActivity.class));*/
330
                }
331
                return true;
332
            }
333
            return false;
334
        }
335
    }
336
    public void redirectPage(final AlertDialog builder){
337
        Handler h =new Handler();
338
        h.postDelayed(new Runnable() {
339
            @Override
340
            public void run() {
341
                if(builder!=null){
342
                    builder.dismiss();
343
                }
344
                userDataEditor.clear().commit();
345
                startActivity(new Intent(getActivity(), LoginActivity.class));
346
            }
347
        },3000);
348
 
349
    }
350
    @Override
351
    public void onResume() {
352
        super.onResume();
353
        getView().setFocusableInTouchMode(true);
354
        getView().requestFocus();
355
        getView().setOnKeyListener(new View.OnKeyListener() {
356
            @Override
357
            public boolean onKey(View v, int keyCode, KeyEvent event) {
358
 
359
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
360
                    Intent i = new Intent(getActivity(), MainActivity.class);
361
                    i.putExtra("displayView", "0");
362
                    startActivity(i);
363
                    return true;
364
 
365
                }
366
                return false;
367
            }
368
        });
369
    }
370
 
371
 
372
    class pushData extends AsyncTask<String, Integer, String> {
373
 
374
        @Override
375
        protected void onPreExecute() {
376
            super.onPreExecute();
377
        }
378
 
379
        @Override
380
        protected String doInBackground(String... arg0) {
381
            HttpClient httpclient = new DefaultHttpClient();
382
            try {
383
 
384
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
385
                nameValuePairs.add(new BasicNameValuePair("pushdata",obj.toString()));
386
                HttpPost httppost = new HttpPost(apiData.getString("url.push.api",null));
387
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
388
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
389
                System.out.println(obj.toString());
390
                StringEntity se = new StringEntity(obj.toString());
391
                HttpResponse response = httpclient.execute(httppost);
392
                int status = response.getStatusLine().getStatusCode();
393
 
394
                if(status == 200){
395
                    return "success";
396
                } else {
397
                    return "failure";
398
                }
399
 
400
            } catch (ClientProtocolException e) {
401
                return "failure";
402
            } catch (IOException e) {
403
                return "failure";
404
            }
405
        }
406
 
407
        @Override
408
        protected void onPostExecute(String result) {
409
            super.onPostExecute(result);
410
 
411
        }
412
    }
413
 
414
    public final boolean isInternetOn() {
415
        ConnectivityManager connec =
416
                (ConnectivityManager)getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
417
 
418
        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
419
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
420
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
421
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
422
 
423
            return true;
424
 
425
        } else if (
426
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
427
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
428
            return false;
429
        }
430
        return false;
431
    }
432
    class checkGateWayProblem extends AsyncTask<String, Integer, String> {
433
 
434
        @Override
435
        protected void onPreExecute() {
436
            super.onPreExecute();
437
        }
438
 
439
        @Override
440
        protected String doInBackground(String... arg0) {
441
            HttpClient httpclient = new DefaultHttpClient();
442
            try {
443
                HttpPost httppost = new HttpPost(arg0[0]);
444
                final String basicAuth = "Basic " + Base64.encodeToString("dtr:dtr18Feb2015".getBytes(), Base64.NO_WRAP);
445
                httppost.setHeader("Authorization", basicAuth);
446
                HttpResponse response = httpclient.execute(httppost);
447
                int status = response.getStatusLine().getStatusCode();
448
 
449
                jsArraySaholic = new JSONArray();
450
                jSaholic.put("url", arg0[0]);
451
 
452
                jSaholic.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
453
                jSaholic.put("httpstatus", status);
454
                jSaholic.put("cookies", CookieManager.getInstance().getCookie(arg0[0]));
455
                jsArraySaholic.put(jSaholic);
456
                obj.put("pushdata", jsArraySaholic);
457
                Log.d("status " ,"Status in checkGatewayProbelm " + status);
458
                if(status == 200){
459
                    return "success";
460
                } else {
461
                    return "failure";
462
                }
463
 
464
            } catch (ClientProtocolException e) {
465
                return "failure";
466
            } catch (IOException e) {
467
                return "failure";
468
            }catch (JSONException e){
469
                return "failure";
470
            }
471
        }
472
 
473
        @Override
474
        protected void onPostExecute(String result) {
475
            super.onPostExecute(result);
476
            new pushData1().execute(obj);
477
        }
478
    }
479
    class javascriptInterface {
480
 
481
        Context mContext;
482
 
483
        /**
484
         * Instantiate the interface and set the context
485
         */
486
        public javascriptInterface(Context c) {
487
            mContext = c;
488
        }
489
 
490
        @JavascriptInterface
491
        public void saholicHTML(String html) {
492
 
493
            try {
494
                obj = new JSONObject();
495
                jSaholic = new JSONObject();
496
                jSaholic.put("html", UtilityFunctions.compress(html));
497
                jSaholic.put("zip", "1");
498
                jSaholic.put("user_id", userData.getString("id", null));
499
            } catch (Exception e) {
500
 
501
            }
502
            new checkGateWayProblem().execute(saholicUrl);
503
        }
504
        @JavascriptInterface
505
        public void flipkartHTML(String html) {
506
            nameValuePairsRawHtml.add(new BasicNameValuePair("rawhtml",UtilityFunctions.compress(html)));
507
            nameValuePairsRawHtml.add(new BasicNameValuePair("zip","1"));
508
            new loadData().execute(nameValuePairsRawHtml);
509
        }
510
    }
511
 
512
    class pushData1 extends AsyncTask<JSONObject, Integer, String> {
513
 
514
        @Override
515
        protected void onPreExecute() {
516
            super.onPreExecute();
517
        }
518
 
519
        @Override
520
        protected String doInBackground(JSONObject... arg0) {
521
            HttpClient httpclient = new DefaultHttpClient();
522
            try {
523
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
524
                nameValuePairs.add(new BasicNameValuePair("pushdata",arg0[0].toString()));
525
                HttpPost httppost = new HttpPost(apiData.getString("url.push.api",null));
526
                final String basicAuth = "Basic " + Base64.encodeToString("dtr:dtr18Feb2015".getBytes(), Base64.NO_WRAP);
527
                httppost.setHeader("Authorization", basicAuth);
528
 
529
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
530
                System.out.println("JSON object in push Data 1 " + arg0[0].toString());
531
                StringEntity se = new StringEntity(arg0[0].toString());
532
                HttpResponse response = httpclient.execute(httppost);
533
                int status = response.getStatusLine().getStatusCode();
534
 
535
                if(status == 200){
536
                    return "success";
537
                } else {
538
                    return "failure";
539
                }
540
 
541
            } catch (ClientProtocolException e) {
542
                return "failure";
543
            } catch (IOException e) {
544
                return "failure";
545
            }
546
        }
547
 
548
        @Override
549
        protected void onPostExecute(String result) {
550
            super.onPostExecute(result);
551
        }
552
    }
553
    class loadData extends AsyncTask<List<NameValuePair>, Integer, JSONObject> {
554
 
555
        @Override
556
        protected void onPreExecute() {
557
            super.onPreExecute();
558
        }
559
 
560
        @Override
561
        protected JSONObject doInBackground(List<NameValuePair>... orderDetail) {
562
 
563
 
564
            try {
565
                HttpClient httpclient = new DefaultHttpClient();
566
                HttpPost httppost = new HttpPost(apiData.getString("orderpagehtml.push.api", null));
567
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
568
 
569
                httppost.setEntity(new UrlEncodedFormEntity(orderDetail[0]));
570
                HttpResponse response = httpclient.execute(httppost);
571
                HttpEntity entity = response.getEntity();
572
                String getJSON = EntityUtils.toString(entity);
573
                if(getJSON==null){
574
                    return null;
575
                }else {
576
                    JSONObject jObjGmail = new JSONObject(getJSON);
577
                    return jObjGmail;
578
                }
579
            } catch (Exception e) {
580
                return null;
581
            }
582
        }
583
 
584
 
585
        @Override
586
        protected void onPostExecute(JSONObject result) {
587
            super.onPostExecute(result);
588
        }
589
    }
590
 
591
}