com.rothconsulting.android.websms.connector.mbudget.ConnectorMBudget.java Source code

Java tutorial

Introduction

Here is the source code for com.rothconsulting.android.websms.connector.mbudget.ConnectorMBudget.java

Source

/*
 * Copyright (C) 2012 Koni
 *
 * This file is only usefull as part of WebSMS.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; If not, see <http://www.gnu.org/licenses/>.
 */
package com.rothconsulting.android.websms.connector.mbudget;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;

import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.ub0r.android.websms.connector.common.Connector;
import de.ub0r.android.websms.connector.common.ConnectorCommand;
import de.ub0r.android.websms.connector.common.ConnectorSpec;
import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec;
import de.ub0r.android.websms.connector.common.Utils;
import de.ub0r.android.websms.connector.common.Utils.HttpOptions;
import de.ub0r.android.websms.connector.common.WebSMSException;

/**
 * AsyncTask to manage IO to M-Budget Mobile API.
 *
 * @author koni
 */
public class ConnectorMBudget extends Connector {
    /**
     * Tag for output.
     */
    private static final String TAG = "M-Budget";
    /**
     * Dummy String
     */
    private static final String DUMMY = "???";
    /**
     * Login Page.
     */
    private static final String URL_LOGIN_PAGE = "http://www.company.ecall.ch/ecompany/ecompany.asp?LinkID=mbudget";
    /**
     * Login Action.
     */
    private static final String URL_LOGIN_ACTION = "http://www.company.ecall.ch/ecompany/ecompany.ASP?WCI=Login_Welcome&WCE=CheckLogin&WCU=";
    /**
     * SMS URL with E-Mail.
     */
    private static final String URL_SENDSMS = "http://www.company.ecall.ch/ecompany/ecompany.ASP?WCI=Message_Create&WCE=UserAction&WCU=";
    /**
     * HTTP User agent.
     */
    private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0";
    /**
     * SMS Encoding
     */
    private static final String ENCODING = "ISO-8859-1";
    /**
     * My Ad-ID
     */
    private static final String AD_UNITID = "ca-app-pub-5619114666968507/9953800139";
    /**
     * Check whether this connector is bootstrapping.
     */
    private static boolean inBootstrap = false;
    /**
     * SMS Credit
     */
    private String SMS_CREDIT = DUMMY;
    /**
     * WCU Part of Login + Send URL.
     */
    private String WCU = "";
    /**
     * Login Cookie
     */
    private String COOKIE = "";
    /**
     * SendID
     */
    private String SEND_ID = "";
    /**
     * txtCallBack
     */
    private String TXT_CALL_BACK = "";

    /**
     * {@inheritDoc}
     */
    @Override
    public final ConnectorSpec initSpec(final Context context) {
        final String name = context.getString(R.string.connector_mbudget_name);
        ConnectorSpec c = new ConnectorSpec(name);
        c.setAuthor(context.getString(R.string.connector_mbudget_author));
        c.setBalance(null);
        c.setLimitLength(127);
        c.setAdUnitId(AD_UNITID);
        c.setCapabilities(ConnectorSpec.CAPABILITIES_BOOTSTRAP | ConnectorSpec.CAPABILITIES_UPDATE
                | ConnectorSpec.CAPABILITIES_SEND | ConnectorSpec.CAPABILITIES_PREFS);
        c.addSubConnector("mbudget", c.getName(), SubConnectorSpec.FEATURE_MULTIRECIPIENTS);
        return c;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final ConnectorSpec updateSpec(final Context context, final ConnectorSpec connectorSpec) {
        this.log("*************************************");
        this.log("** Start updateSpec");
        this.log("*************************************");
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
        if (p.getBoolean(Preferences.PREFS_ENABLED, false)) {
            if (p.getString(Preferences.PREFS_USER, "").length() > 0 && p.getString(Preferences.PREFS_PASSWORD, "") // .
                    .length() > 0) {
                connectorSpec.setReady();
            } else {
                connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED);
            }
        } else {
            connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE);
        }
        this.log("*************************************");
        this.log("** Ende updateSpec");
        this.log("*************************************");
        return connectorSpec;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected final void doBootstrap(final Context context, final Intent intent) throws WebSMSException {
        this.log("*************************************");
        this.log("** Start doBootstrap");
        this.log("*************************************");
        if (inBootstrap && !this.SMS_CREDIT.equals(DUMMY)) {
            this.log("already in bootstrap: skip bootstrap");
            return;
        }
        if (this.COOKIE.equals("") || this.WCU.equals("")) {
            // To get Session Cookie and WCU key
            this.sendData(URL_LOGIN_PAGE, context, null);
        }

        inBootstrap = true;
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);

        String username = p.getString(Preferences.PREFS_USER, "");
        String password = p.getString(Preferences.PREFS_PASSWORD, "");

        ArrayList<BasicNameValuePair> postParameter = new ArrayList<BasicNameValuePair>();
        postParameter.add(new BasicNameValuePair("Anmelden", "Anmelden"));
        postParameter.add(new BasicNameValuePair("UserName", username));
        postParameter.add(new BasicNameValuePair("password", password));

        this.sendData(URL_LOGIN_ACTION + this.WCU, context, postParameter);

        this.log("*************************************");
        this.log("** Ende doBootstrap");
        this.log("*************************************");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected final void doUpdate(final Context context, final Intent intent) throws WebSMSException {
        this.log("*************************************");
        this.log("** Start doUpdate");
        this.log("*************************************");
        this.doBootstrap(context, intent);

        this.sendData(URL_SENDSMS + this.WCU, context, null);

        this.getSpec(context).setBalance(this.SMS_CREDIT);

        // Google analytics
        AnalyticsUtil.sendEvent(context, TAG, "doUpdate V3", "Balance: " + this.getSpec(context).getBalance());

        this.log("*************************************");
        this.log("** Ende doUpdate");
        this.log("*************************************");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected final void doSend(final Context context, final Intent intent) throws WebSMSException {
        this.log("*************************************");
        this.log("** Start doSend");
        this.log("*************************************");
        this.doBootstrap(context, intent);

        if (this.WCU.equals("")) {
            this.sendData(URL_LOGIN_PAGE, context, null);
        }

        DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy");
        DateFormat timeFormatter = new SimpleDateFormat("hh:mm");
        String txtSendDate = dateFormatter.format(new Date());
        String txtSendTime = timeFormatter.format(new Date());
        this.log("txtSendDate=" + txtSendDate);
        this.log("txtSendTime=" + txtSendTime);
        ConnectorCommand command = new ConnectorCommand(intent);
        // SMS Text
        String text = command.getText();
        this.log("text.length()=" + text.length());
        this.log("text=" + text);

        // Building POST parameter
        ArrayList<BasicNameValuePair> postParameter = new ArrayList<BasicNameValuePair>();

        // SMS Recipients
        String[] to = command.getRecipients();

        if (to.length > 5) {
            throw new WebSMSException(context, R.string.connector_mbudget_max_5_sms);
        }

        if (to != null && to.length > 0) {

            if (Integer.valueOf(this.SMS_CREDIT.substring(0, 1)) < to.length) {
                throw new WebSMSException(context, R.string.connector_mbudget_kein_guthaben_mehr);
            }

            int z = 0;
            for (String number : to) {
                z++;
                // this.log("number=" + this.removeBracket(number));
                postParameter.add(new BasicNameValuePair("CheckFreeNo", "YES"));
                postParameter.add(new BasicNameValuePair("FreeNo", this.getSwissPhoneNumber(number)));
                postParameter.add(new BasicNameValuePair("Message", text.trim()));
                postParameter.add(new BasicNameValuePair("SendID", this.SEND_ID));
                this.log("SEND_ID=" + this.SEND_ID);
                postParameter.add(new BasicNameValuePair("SendJob", "Senden"));
                postParameter.add(new BasicNameValuePair("UsingUnitsIs", ""));
                postParameter.add(new BasicNameValuePair("num", "" + text.length()));
                postParameter.add(new BasicNameValuePair("txtCallBack", this.TXT_CALL_BACK));
                postParameter.add(new BasicNameValuePair("txtSendDate", txtSendDate));
                this.log("txtSendDate=" + txtSendDate);
                postParameter.add(new BasicNameValuePair("txtSendTime", txtSendTime));
                this.log("txtSendTime=" + txtSendTime);
                this.log("WCU=" + this.WCU);

                AnalyticsUtil.sendEvent(context, TAG, "Send SMS", "Count receiver: " + z);

                this.sendData(URL_SENDSMS + this.WCU, context, postParameter);
            }
        }
        this.log("*************************************");
        this.log("** Ende doSend");
        this.log("*************************************");
    }

    /**
     * Sending the SMS
     */
    private void sendData(final String url, final Context context,
            final ArrayList<BasicNameValuePair> postParameter) throws WebSMSException {
        this.log("*************************************");
        this.log("** Start sendData");
        this.log("*************************************");
        try {

            this.log("URL: " + url);
            // send data
            this.log("prepare: getHttpClient(...)");

            HttpOptions httpOptions = new HttpOptions();
            httpOptions.url = url;
            httpOptions.userAgent = USER_AGENT;
            httpOptions.trustAll = true;
            this.log("UrlEncodedFormEntity()");
            // this.printPostParameter(postParameter);
            if (postParameter != null) {
                httpOptions.postData = new UrlEncodedFormEntity(postParameter, ENCODING);
            }
            if (url.contains(URL_LOGIN_ACTION) || url.contains(URL_SENDSMS)) {
                if (url.contains(URL_LOGIN_ACTION) && this.COOKIE.length() > 5) {
                    int index = this.COOKIE.indexOf("=");
                    String cookieName = this.COOKIE.substring(0, index);
                    String cookieValue = this.COOKIE.substring(index + 1, this.COOKIE.length());
                    this.log("Cookies: URL_LOGIN_ACTION !!!!!");
                    this.log("Cookie1: " + this.COOKIE);
                    this.log("Cookie2: " + cookieName + "/" + cookieValue);

                    ArrayList<Cookie> cookies = new ArrayList<Cookie>();
                    Cookie cookie = new BasicClientCookie(cookieName, cookieValue);
                    cookies.add(cookie);
                    httpOptions.cookies = cookies;
                }

                ArrayList<Header> headers = new ArrayList<Header>();
                Header cookieHeader = new BasicHeader("Cookie", this.COOKIE);
                Header accept = new BasicHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                Header acceptEncoding = new BasicHeader("Accept-Encoding", "gzip, deflate");
                Header acceptLanguage = new BasicHeader("Accept-Language",
                        "de-ch,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2");
                Header connection = new BasicHeader("Connection", "keep-alive");
                Header referer = new BasicHeader("Referer", url);
                Header host = new BasicHeader("Host", "www.company.ecall.ch");
                Header dnt = new BasicHeader("DNT", "1");

                headers.add(cookieHeader);
                headers.add(accept);
                headers.add(acceptEncoding);
                headers.add(acceptLanguage);
                headers.add(connection);
                headers.add(referer);
                headers.add(host);
                headers.add(dnt);

                // if (url.contains(URL_LOGIN_ACTION)) {
                this.log("Header: URL_LOGIN_ACTION !!!!!");
                // }
                // if (url.contains(URL_SENDSMS)) {
                this.log("Header: URL_SENDSMS !!!!!");
                // }
                // for (Header headerEntry : headers) {
                // this.log("Header: " + headerEntry.getName() + " / " + headerEntry.getValue());
                // }
                httpOptions.headers = headers;
            }

            this.log("send data: getHttpClient(...)");
            HttpResponse response = Utils.getHttpClient(httpOptions);

            int respStatus = response.getStatusLine().getStatusCode();
            this.log("response status=" + respStatus);
            if (respStatus != HttpURLConnection.HTTP_OK) {
                throw new WebSMSException(context, R.string.error_http, "" + respStatus);
            }

            String htmlText = Utils.stream2str(response.getEntity().getContent()).trim();
            if (htmlText == null || htmlText.length() == 0) {
                throw new WebSMSException(context, R.string.error_service);
            }
            // this.log("----- Start HTTP RESPONSE--");
            // this.log(htmlText);
            // this.log("----- End HTTP RESPONSE--");
            if (url.contains(URL_LOGIN_PAGE)) {
                this.getWCU(htmlText, context);
                this.getCookie(response);
            }
            if (url.contains(URL_LOGIN_ACTION) || url.contains(URL_SENDSMS)) {
                String guthaben = this.getGuthaben(htmlText, context);
                if (guthaben != null && !guthaben.equals("")) {
                    this.SMS_CREDIT = guthaben;
                }
                this.getSpec(context).setBalance(this.SMS_CREDIT);

                this.getSendId(htmlText, context);
                this.getTxtCallback(htmlText, context);
            }
            htmlText = null;

        } catch (Exception e) {
            // Log.e(TAG, null, e);
            throw new WebSMSException(e.getMessage());
        }
        this.log("*************************************");
        this.log("** Ende sendData");
        this.log("*************************************");
    }

    private String getGuthaben(final String htmlText, final Context context) {
        String guthaben = "";
        int indexStartSMSCredit = htmlText.indexOf("SMS heute:");
        if (indexStartSMSCredit > 0) {
            guthaben = htmlText.substring(indexStartSMSCredit + 11, indexStartSMSCredit + 14);
        }
        this.log("indexOf Guthaben= " + indexStartSMSCredit);
        this.log(" ------ Guthaben= " + guthaben);

        return guthaben;
    }

    private void getSendId(final String htmlText, final Context context) {
        int indexStart = -5;
        if (this.SEND_ID.equals("")) {
            indexStart = htmlText.indexOf("SendID value=");
            if (indexStart > 0) {
                this.SEND_ID = htmlText.substring(indexStart + 14, indexStart + 14 + 14);
                // Bsp: 20120810231344
            }
        }

        this.log("indexOf SEND_ID= " + indexStart);
        this.log(" ------ SEND_ID= " + this.SEND_ID);
    }

    private void getTxtCallback(final String htmlText, final Context context) {
        int indexStart = -5;
        if (this.TXT_CALL_BACK.equals("")) {
            indexStart = htmlText.indexOf("txtCallBack value=");
            if (indexStart > 0) {
                this.TXT_CALL_BACK = htmlText.substring(indexStart + 19, indexStart + 19 + 13);
                // Bsp: 0041774163473
            }
        }

        this.log("indexOf TXT_CALL_BACK= " + indexStart);
        this.log(" ------ TXT_CALL_BACK= " + this.TXT_CALL_BACK);
    }

    private void getWCU(final String htmlText, final Context context) {
        if (this.WCU.equals("")) {
            int indexStart = htmlText.indexOf("ecompany.ASP?WCI=Login_Welcome&WCE=CheckLogin&WCU=");
            int addToStart = 50;
            int addToEnd = 50 + 28;
            if (indexStart < 0) {
                indexStart = htmlText.indexOf("ecompany.ASP?WCI=Message_Create&WCU=");
                addToStart = 36;
                addToEnd = 36 + 28;
            }
            if (indexStart > 0) {
                this.WCU = htmlText.substring(indexStart + addToStart, indexStart + addToEnd);
                // 1A787987818273878AA474857E61
            }
            this.log("indexOf WCU= " + indexStart);
            this.log(" ------ WCU= " + this.WCU);
        }
    }

    private void getCookie(final HttpResponse response) {
        if (this.COOKIE.equals("")) {
            Header[] header = response.getAllHeaders();
            for (Header headerEntry : header) {
                if (headerEntry.getName().equalsIgnoreCase("Set-Cookie")) {
                    this.log("++++ Found Set-Cookie1=" + headerEntry.getValue());
                    int index = headerEntry.getValue().indexOf(";");
                    this.COOKIE = headerEntry.getValue().substring(0, index);
                    this.log("++++ Found Set-Cookie2=" + this.COOKIE);
                }
                if (headerEntry.getName().equalsIgnoreCase("Cookie")) {
                    this.log("+++++ Found Cookie1=" + headerEntry.getValue());
                    int index = headerEntry.getValue().indexOf(";");
                    this.COOKIE = headerEntry.getValue().substring(0, index);
                    this.log("+++++ Found Cookie2=" + this.COOKIE);
                }
            }
        } else {
            this.log("++++ Bestehendes Cookie=" + this.COOKIE);
        }
    }

    private String getSwissPhoneNumber(String string) {
        this.log("string vorher=" + string);
        if (string != null && string.contains(">")) {
            int index1 = string.indexOf("<");
            int index2 = string.indexOf(">");
            string = string.substring(index1 + 1, index2);
            string = string.trim();
        }
        this.log("string nachher=" + string);

        if (string != null && !string.trim().equals("")) {
            if (string.trim().startsWith("+417")) {
                string = string.replace("+417", "07");
            } else if (string.trim().startsWith("+4107")) {
                string = string.replace("+41", "");
            } else if (string.trim().startsWith("+41 07")) {
                string = string.replace("+41 ", "");
            } else if (string.trim().startsWith("+41 7")) {
                string = string.replace("+41 ", "0");
            } else if (string.trim().startsWith("00417")) {
                string = string.replace("0041", "0");
            }
        }
        string = string.trim();
        this.log("******* phone =" + string);
        return string;
    }

    private void printHeader(final HttpResponse response) {
        Header[] header = response.getAllHeaders();
        this.log("Header: respone!!!!");
        for (Header headerEntry : header) {
            this.log("Header: " + headerEntry.getName() + " / " + headerEntry.getValue());
            if (headerEntry.getName().equalsIgnoreCase("Set-Cookie")) {
                this.log("++++ Found Set-Cookie1=" + headerEntry.getValue());
                int index = headerEntry.getValue().indexOf(";");
                this.COOKIE = headerEntry.getValue().substring(0, index);
                this.log("++++ Found Set-Cookie2=" + this.COOKIE);
            }
        }
    }

    private void printPostParameter(final List<BasicNameValuePair> postParameter) {
        this.log("POST Parameter!!!!");
        if (postParameter != null) {
            for (BasicNameValuePair nameValue : postParameter) {
                this.log("POST: " + nameValue.getName() + " / " + nameValue.getValue());
            }
        } else {
            this.log("POST Parameter=null");
        }
    }

    /**
     * central logger
     */
    private void log(final String message) {
        // Log.d(TAG, message);
    }

}