Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package renz.javacodez.openvpn;
- import android.support.v7.app.AlertDialog;
- import android.os.*;
- import android.widget.*;
- import android.view.*;
- import android.view.View.*;
- import android.widget.AdapterView.*;
- import de.blinkt.openvpn.core.*;
- import renz.javacodez.openvpn.adapter.AdapterHelper.*;
- import java.util.*;
- import java.io.*;
- import android.preference.*;
- import android.content.*;
- import tsholo.corp.tsholovpn.R;
- import android.support.design.widget.*;
- import static de.blinkt.openvpn.core.ConnectionStatus.*;
- import static renz.javacodez.openvpn.RenzGenerator.*;
- import renz.javacodez.openvpn.helper.NavigationHelper.*;
- import renz.javacodez.openvpn.json.JsonManager.*;
- import renz.javacodez.openvpn.helper.*;
- import android.content.SharedPreferences.*;
- import de.blinkt.openvpn.*;
- import org.json.*;
- import de.blinkt.openvpn.activities.*;
- import android.support.v7.app.*;
- import android.net.*;
- import android.support.v7.widget.Toolbar;
- import android.support.v7.app.ActionBarDrawerToggle;
- import android.support.v4.widget.*;
- import android.support.v4.view.*;
- import android.support.v4.app.ActivityCompat;
- import com.github.angads25.filepicker.model.*;
- import com.github.angads25.filepicker.view.*;
- import com.github.angads25.filepicker.controller.*;
- import android.support.v4.content.*;
- import de.blinkt.openvpn.fragments.*;
- import renz.javacodez.openvpn.util.*;
- import renz.javacodez.openvpn.sshcore.*;
- import renz.javacodez.openvpn.openvpncore.*;
- import renz.javacodez.openvpn.logger.*;
- import renz.javacodez.openvpn.view.LogView;
- import renz.javacodez.openvpn.view.*;
- import renz.javacodez.openvpn.view.DataTransferGraph;
- import android.graphics.*;
- import com.sdsmdg.tastytoast.*;
- import android.content.pm.*;
- import android.*;
- import java.text.*;
- import com.github.mikephil.charting.data.*;
- import com.github.mikephil.charting.charts.*;
- public class Main extends MainBase implements ActivityCompat.OnRequestPermissionsResultCallback, RadioGroup.OnCheckedChangeListener,
- SSHTunnelCore.VPNListener, ServerUpdate.OnUpdateListener,
- OnClickListener, OnItemSelectedListener,
- VpnStatus.StateListener, VpnStatus.ByteCountListener,
- GeneratorHelper.CancelListener, BottomNavigationView.OnNavigationItemSelectedListener,
- ServerDuration.DurationListener
- {
- private String USERNAME = "VPN_USERNAME";
- private String PASSWORD = "VPN_PASSWORD";
- private String SELECTED_SERVER = "SELECTED_SERVER";
- private String SELECTED_NETWORK = "SELECTED_NETWORK";
- private String USE_PAYLOAD = "USE_PAYLOAD";
- private Spinner server_spin;
- private Spinner network_spin;
- private Spinner category_spin;
- private RadioGroup connect_type;
- private TextView status;
- private EditText username;
- private MaterialEditText password;
- private ToggleButton use_payload;
- private SharedPreferences prefs;
- private SharedPreferences.Editor editor;
- private List<JSONObject> listServer;
- private ServerAdapter serverAdapter;
- private List<String> listNetwork;
- private NetworkAdapter networkAdapter;
- private View graphView, bannerView;
- private Button connect,disconnect;
- private BottomNavigationView bottomNavi;
- private TextView configVersion;
- private GeneratorHelper gh;
- private EditText custom_payload_input;
- private TextView prem, vip, priv;
- private ProgressBar pb;
- private LineChart mChart;
- private Thread dataUpdate;
- private Handler vHandler = new Handler();
- DecimalFormat df = new DecimalFormat("#.##");
- private GraphHelper graph;
- private ImageButton bt_toggle_input;
- private Button bt_hide_input;
- private Button bt_save_input;
- private View lyt_expand_input;
- private NestedScrollView nested_scroll_view;
- private TextView upBytes,dlBytes,elapsedTime;
- private Timer timer;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- // TODO: Implement this method
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- prefs = PreferenceManager.getDefaultSharedPreferences(Main.this);
- editor = prefs.edit();
- SSHTunnelCore.setVPNListener(this);
- VpnStatus.addStatusListener(this);
- category_spin = (Spinner)findViewById(R.id.category_spin);
- server_spin = (Spinner)findViewById(R.id.server_list);
- network_spin = (Spinner)findViewById(R.id.network_list);
- status = (TextView)findViewById(R.id.status);
- username = (EditText)findViewById(R.id.vpn_username);
- password = (MaterialEditText)findViewById(R.id.vpn_password);
- connect = (Button)findViewById(R.id.connect_vpn);
- disconnect = (Button)findViewById(R.id.disconnect_vpn);
- use_payload = (ToggleButton)findViewById(R.id.custom_payload);
- connect_type = (RadioGroup)findViewById(R.id.connection_type);
- bottomNavi = (BottomNavigationView)findViewById(R.id.bottom_navi);
- graphView = findViewById(R.id.graphView);
- bannerView = findViewById(R.id.bannerView);
- configVersion = (TextView)findViewById(R.id.config_version);
- upBytes = (TextView)findViewById(R.id.upload);
- dlBytes = (TextView)findViewById(R.id.download);
- elapsedTime = (TextView)findViewById(R.id.duration);
- initComponent();
- String[] categories = new String[]{"PREMIUM"};
- ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, R.layout.category_item, categories);
- category_spin.setAdapter(categoryAdapter);
- listServer = new ArrayList<>();
- serverAdapter = new ServerAdapter(this, listServer);
- server_spin.setAdapter(serverAdapter);
- //setupServer();
- listNetwork = new ArrayList<String>();
- networkAdapter = new NetworkAdapter(this, listNetwork);
- network_spin.setAdapter(networkAdapter);
- configVersion.setText(Util.getConfigVersion(this));
- if (ConfigUtil.getInstance(this).getConnectionType() == 2) {
- loadSSLNetworks();
- } else {
- loadDefaultNetwork();
- }
- Util.disableShiftMode(bottomNavi);
- connect.setOnClickListener(this);
- disconnect.setOnClickListener(this);
- connect_type.setOnCheckedChangeListener(this);
- use_payload.setOnClickListener(this);
- category_spin.setOnItemSelectedListener(this);
- server_spin.setOnItemSelectedListener(this);
- network_spin.setOnItemSelectedListener(this);
- bottomNavi.setOnNavigationItemSelectedListener(this);
- username.setText(prefs.getString(USERNAME, ""));
- password.setText(prefs.getString(PASSWORD, ""));
- category_spin.setSelection(prefs.getInt("Category", 0));
- network_spin.setSelection(prefs.getInt(SELECTED_NETWORK, 0));
- ((RadioButton)connect_type.getChildAt(ConfigUtil.getInstance(this).getConnectionType())).setChecked(true);
- mChart = (LineChart) findViewById(R.id.chart1);
- graph = GraphHelper.getHelper().with(this).color(getColor(R.color.graph_color)).chart(mChart);
- liveData();
- renderLastEvent();
- }
- private void initComponent() {
- // input section
- nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
- bt_toggle_input = (ImageButton) findViewById(R.id.bt_toggle_input);
- bt_hide_input = (Button) findViewById(R.id.bt_hide_input);
- bt_save_input = (Button) findViewById(R.id.bt_save_input);
- lyt_expand_input = (View) findViewById(R.id.lyt_expand_input);
- lyt_expand_input.setVisibility(View.GONE);
- bt_toggle_input.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- toggleSectionInput(bt_toggle_input);
- }
- });
- bt_hide_input.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- toggleSectionInput(bt_toggle_input);
- }
- });
- bt_save_input.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- String user = username.getText().toString();
- String pass = password.getText().toString();
- editor.putString(USERNAME, user).apply();
- editor.putString(PASSWORD, pass).apply();
- toggleSectionInput(bt_toggle_input);
- }
- });
- }
- private void toggleSectionInput(View view) {
- boolean show = toggleArrow(view);
- if (show) {
- ViewAnimation.expand(lyt_expand_input, new ViewAnimation.AnimListener() {
- @Override
- public void onFinish() {
- ViewAnimation.nestedScrollTo(nested_scroll_view, lyt_expand_input);
- }
- });
- } else {
- ViewAnimation.collapse(lyt_expand_input);
- }
- }
- public boolean toggleArrow(View view) {
- if (view.getRotation() == 0) {
- view.animate().setDuration(200).rotation(180);
- return true;
- } else {
- view.animate().setDuration(200).rotation(0);
- return false;
- }
- }
- public void liveData()
- {
- dataUpdate = new Thread(new Runnable() {
- @Override
- public void run()
- {
- while (!dataUpdate.getName().equals("stopped"))
- {
- vHandler.post(new Runnable() {
- @Override
- public void run()
- {
- //addDataSet();
- if (InjectorService.isRunning)
- {
- graph.start();
- }
- else
- {
- graph.stop();
- }
- }
- });
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- // progressStatus--;
- }
- }
- });
- dataUpdate.setName("started");
- dataUpdate.start();
- }
- @Override
- public void onCheckedChanged(RadioGroup p1, int p2)
- {
- switch (p1.getId()) {
- case R.id.connection_type:
- RadioButton v = (RadioButton)p1.findViewById(p2);
- int index = p1.indexOfChild(v);
- if (index == 2) {
- if (listNetwork.size() > 0) {
- listNetwork.clear();
- networkAdapter.notifyDataSetChanged();
- }
- loadSSLNetworks();
- } else {
- if (listNetwork.size() > 0) {
- listNetwork.clear();
- networkAdapter.notifyDataSetChanged();
- }
- loadDefaultNetwork();
- }
- ConfigUtil.getInstance(this).setConnectionType(index);
- break;
- }
- // TODO: Implement this method
- }
- @Override
- public boolean onNavigationItemSelected(MenuItem p1)
- {
- switch (p1.getItemId()) {
- case R.id.menu_update:
- checkUpdates();
- break;
- case R.id.menu_showLog:
- showLog();
- break;
- //case R.id.menu_contact_us:
- //viewWeb(getString(R.string.link_facebook));
- //break;
- case R.id.menu_about:
- about();
- break;
- case R.id.menu_exit:
- finish();
- break;
- }
- // TODO: Implement this method
- return true;
- }
- private void showDurationDialog()
- {
- View v = getLayoutInflater().inflate(R.layout.duration_dialog, null);
- prem = (TextView)v.findViewById(R.id.premium_duration);
- vip = (TextView)v.findViewById(R.id.vip_duration);
- priv = (TextView)v.findViewById(R.id.private_duration);
- pb = (ProgressBar)v.findViewById(R.id.duration_progress);
- Button refresh = (Button)v.findViewById(R.id.refresh_duration);
- Button hide = (Button)v.findViewById(R.id.hide_duration);
- prem.setText("--/--");
- vip.setText("--/--");
- priv.setText("--/--");
- pb.setVisibility(View.VISIBLE);
- final ServerDuration sd = new ServerDuration();
- sd.setListener(this);
- sd.setUserPass(username.getText().toString(), password.getText().toString());
- try {
- sd.start();
- } catch (Exception e) {
- }
- final AlertDialog dialog = new AlertDialog.Builder(this).create();
- dialog.setView(v);
- refresh.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View p1)
- {
- try {
- sd.start();
- } catch (Exception e) {
- }
- pb.setVisibility(View.VISIBLE);
- showToast("Refreshing. Please wait...");
- // TODO: Implement this method
- }
- });
- hide.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View p1)
- {
- dialog.dismiss();
- // TODO: Implement this method
- }
- });
- dialog.show();
- // TODO: Implement this method
- }
- @Override
- public void onShowDuration(ServerDuration.Duration duration)
- {
- pb.setVisibility(View.GONE);
- prem.setText(duration.premium);
- vip.setText(duration.vip);
- priv.setText(duration.priv);
- // TODO: Implement this method
- }
- @Override
- public void onError(String error)
- {
- pb.setVisibility(View.GONE);
- prem.setText("--/--");
- vip.setText("--/--");
- priv.setText("--/--");
- showToast(error);
- // TODO: Implement this method
- }
- private void showLog()
- {
- int type = connect_type.getCheckedRadioButtonId();
- Intent intent = new Intent();
- if (type == R.id.type_openvpn) {
- intent.setClass(this, LogWindow.class);
- } else {
- intent.setClass(this, LogActivity.class);
- }
- startActivity(intent);
- // TODO: Implement this method
- }
- public void checkUpdates()
- {
- final ServerUpdate su = new ServerUpdate(this);
- su.setURL(getString(R.string.link_update));
- su.setUpdateListener(this);
- CharSequence[] titles = {"Online","Offline"};
- AlertDialog.Builder ab = new AlertDialog.Builder(this);
- ab.setIcon(R.drawable.ic_update_dialog);
- ab.setTitle("Updates");
- ab.setSingleChoiceItems(titles, 0, new DialogInterface.OnClickListener()
- {
- @Override
- public void onClick(DialogInterface p1, int p2)
- {
- switch (p2) {
- case 0:
- su.start();
- break;
- case 1:
- startOfflineUpdate();
- break;
- }
- p1.dismiss();
- // TODO: Implement this method
- }
- }).setNegativeButton("Cancel", null);
- ab.show();
- }
- private void startOfflineUpdate()
- {
- String perm = Manifest.permission.READ_EXTERNAL_STORAGE;
- if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
- } else {
- showFilePicker();
- }
- }
- private void showFilePicker()
- {
- DialogProperties dp = new DialogProperties();
- dp.selection_mode = DialogConfigs.SINGLE_MODE;
- dp.selection_type = DialogConfigs.FILE_SELECT;
- dp.root = Environment.getExternalStorageDirectory();
- FilePickerDialog picker = new FilePickerDialog(this, dp);
- picker.setTitle("Select JsonFile");
- picker.setDialogSelectionListener(new DialogSelectionListener()
- {
- @Override
- public void onSelectedFilePaths(String[] files)
- {
- for (String file: files) {
- if (file.endsWith(".js")) {
- startImport(Main.this, file);
- } else {
- showToast("The file extension must end with .js");
- }
- }
- // TODO: Implement this method
- }
- });
- picker.setPositiveBtnName("Select");
- picker.setNegativeBtnName("Cancel");
- picker.show();
- // TODO: Implement this method
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
- {
- switch (requestCode) {
- case 1:
- if (grantResults.length > 0) {
- for (int grantResult: grantResults) {
- if (grantResult == PackageManager.PERMISSION_GRANTED) {
- showFilePicker();
- } else {
- showToast("You need to grant the permission to use offline update!");
- }
- }
- }
- break;
- }
- // TODO: Implement this method
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- }
- @Override
- public void onShowUpdate(String newVersion)
- {
- AlertDialog.Builder ab = new AlertDialog.Builder(this);
- ab.setTitle("Updates Found");
- ab.setMessage("New version found: "+newVersion +", do you want to update?");
- ab.setPositiveButton("Update",new DialogInterface.OnClickListener()
- {
- @Override
- public void onClick(DialogInterface p0, int p1)
- {
- if (getPM().getProfiles().size() > 0) {
- try {
- for (VpnProfile vp: getPM().getProfiles()) {
- getPM().removeProfile(Main.this, vp);
- }
- } catch (Exception e) {
- }
- }
- loadServers(0);
- loadDefaultNetwork();
- showToast("Update Success!");
- }
- });
- ab.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
- {
- @Override
- public void onClick(DialogInterface p0, int p1)
- {
- File file = new File(getFilesDir(), "Servers.js");
- file.delete();
- }
- });
- ab.show();
- }
- @Override
- public void onNoUpdateAvailable(String oldVersion)
- {
- AlertDialog.Builder ab = new AlertDialog.Builder(this);
- ab.setTitle("No Updates");
- ab.setMessage("No updates available, your current server version is: " + oldVersion);
- ab.setPositiveButton("Ok", null);
- ab.show();
- }
- public void loadDefaultNetwork()
- {
- try {
- if (listNetwork.size() > 0) {
- listNetwork.clear();
- networkAdapter.notifyDataSetChanged();
- }
- JSONArray network = getNetworksArray();
- for (int i = 0; i < network.length(); i++) {
- listNetwork.add(network.getJSONObject(i).getString("Name"));
- networkAdapter.notifyDataSetChanged();
- }
- } catch (Exception e) {
- showToast(e.getMessage());
- }
- }
- private void loadSSLNetworks()
- {
- try {
- JSONArray sslNetwork = getSSLNetworksArray();
- for (int i = 0; i < sslNetwork.length(); i++) {
- listNetwork.add(sslNetwork.getJSONObject(i).getString("Name"));
- networkAdapter.notifyDataSetChanged();
- }
- } catch (Exception e) {
- showToast(e.getMessage());
- }
- }
- @Override
- public void onClick(View p1)
- {
- int id = p1.getId();
- switch (id) {
- case R.id.connect_vpn:
- prepareToStart();
- break;
- case R.id.disconnect_vpn:
- stopVPN();
- break;
- case R.id.custom_payload:
- if (use_payload.isChecked()) {
- showCustomPayload();
- }
- break;
- }
- // TODO: Implement this method
- }
- @Override
- public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4)
- {
- switch (p1.getId()) {
- case R.id.category_spin:
- loadServers(p3);
- String str = (String)p1.getSelectedItem();
- server_spin.setSelection(prefs.getInt(SELECTED_SERVER + str, 0));
- editor.putInt("Category", p3).apply();
- break;
- case R.id.server_list:
- String str2 = (String)category_spin.getSelectedItem();
- editor.putInt(SELECTED_SERVER + str2, p3).apply();
- try {
- String serverName = ((JSONObject)p1.getSelectedItem()).getString("Name");
- use_payload.setChecked(prefs.getBoolean(USE_PAYLOAD + serverName, false));
- } catch (Exception e) {
- }
- break;
- case R.id.network_list:
- editor.putInt(SELECTED_NETWORK, p3).apply();
- break;
- }
- // TODO: Implement this method
- }
- public void loadServers(int category)
- {
- try {
- if (listServer.size() > 0) {
- listServer.clear();
- serverAdapter.notifyDataSetChanged();
- }
- ArrayList<JSONObject> listObject = new ArrayList<>();
- JSONArray serverJs = getServersArray();
- JSONObject obj = null;
- if (listObject.size() > 0) {
- listObject.clear();
- }
- for (int i = 0; i < serverJs.length(); i++) {
- obj = serverJs.getJSONObject(i);
- String cat = obj.getString("Category");
- if (obj.has("Category")) {
- if (category == 0) {
- if (cat.equals("PREMIUM")) {
- listObject.add(obj);
- }
- } else if (category == 1) {
- if (cat.equals("VIP")) {
- listObject.add(obj);
- }
- } else if (category == 2) {
- if (cat.equals("PRIVATE")) {
- listObject.add(obj);
- }
- }
- }
- }
- for (JSONObject server: listObject) {
- String name = server.getString("Name");
- ConfigParser parser = new ConfigParser();
- parser.parseConfig(new InputStreamReader(getResources().openRawResource(R.raw.config)));
- VpnProfile vp = parser.convertProfile();
- vp.mName = name +"-"+server.getString("Category");
- vp.mConnections[0].mServerName = server.getString("IP");
- vp.mConnections[0].mServerPort = server.getString("Port");
- vp.mUseLzo = true;
- getPM().saveProfile(this, vp);
- if (getPM().getProfileByName(name) == null) {
- getPM().addProfile(vp);
- }
- getPM().saveProfileList(this);
- listServer.add(server);
- serverAdapter.notifyDataSetChanged();
- }
- } catch (Exception e) {
- showToast("Loading Servers Error: " + e.getMessage());
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data)
- {
- switch (requestCode) {
- case 1:
- if (resultCode == RESULT_OK) {
- startVPN();
- }
- break;
- }
- // TODO: Implement this method
- super.onActivityResult(requestCode, resultCode, data);
- }
- private void prepareToStart()
- {
- Intent intent = VpnService.prepare(this);
- if (intent != null) {
- startActivityForResult(intent, 1);
- } else {
- onActivityResult(1, RESULT_OK, null);
- }
- }
- private void stopVPN()
- {
- getPM().setConntectedVpnProfileDisconnected(this);
- stopVPN(connect_type.getCheckedRadioButtonId());
- StatisticGraphData.getStatisticData().getDataTransferStats().stop();
- graph.stop();
- enabledWidgets(true);
- }
- private void startVPN()
- {
- try {
- ConfigUtil config = ConfigUtil.getInstance(this);
- JSONObject server = (JSONObject)server_spin.getSelectedItem();
- if (server != null) {
- String serverName = server.getString("Name");
- String category = server.getString("Category");
- VpnProfile vp = getPM().getProfileByName(serverName+"-"+category);
- vp.mUsername = username.getText().toString();
- vp.mPassword = password.getText().toString();
- vp.mUseDefaultRoute = true;
- String mConnectRetry = "connect-retry 1";
- String mConnectRetryMax = "connect-retry-max 3";
- String mLocalProxy = String.format("http-proxy 127.0.0.1 %s", Integer.toString(ConfigUtil.LOCAL_PORT));
- vp.mConnections[0].mUseCustomConfig = true;
- vp.mConnections[0].mCustomConfiguration = String.format("%s\n%s\n%s\n", mConnectRetry, mConnectRetryMax, mLocalProxy);
- getPM().saveProfile(this, vp);
- config.setServerName(serverName + "-" + category);
- config.setSshPort(server.getString("SSHPort"));
- config.setSslPort(server.getString("SSLPort"));
- config.setIsCustomPayload(use_payload.isChecked());
- editor.putBoolean(USE_PAYLOAD + serverName, use_payload.isChecked());
- editor.apply();
- startInjector(vp);
- enabledWidgets(false);
- } else {
- showToast("No Server Selected!");
- }
- } catch (Exception e) {
- showToast(e.getMessage());
- }
- }
- private JSONObject getSSLNetworkObject()
- {
- try {
- JSONObject sslObject = getSSLNetworksArray().getJSONObject(network_spin.getSelectedItemPosition());
- return sslObject;
- } catch (Exception e) {
- return null;
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> p1)
- {
- // TODO: Implement this method
- }
- @Override
- public void updateState(String state, String logmessage, int localizedResId, final ConnectionStatus level)
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run()
- {
- show_stats(VpnStatus.getLastCleanLogMessage(Main.this), level);
- // TODO: Implement this method
- }
- });
- // TODO: Implement this method
- }
- @Override
- public void setConnectedVPN(String uuid)
- {
- // TODO: Implement this method
- }
- @Override
- public void updateByteCount(long in, long out, long diffIn, long diffOut)
- {
- StatisticGraphData.DataTransferStats stats = StatisticGraphData.getStatisticData().getDataTransferStats();
- stats.addBytesReceived(in);
- stats.addBytesSent(out);
- DataTransferGraph.GraphData data = new DataTransferGraph.GraphData();
- data.setUp((int)out, 0);
- data.setDown((int)in, 0);
- // TODO: Implement this method
- }
- @Override
- public void updateState(int state)
- {
- if (state != 0) {
- status.setText(state);
- editor.putInt("SSH_STATUS", state).apply();
- }
- switch (state) {
- case R.string.state_connecting:
- case R.string.state_reconnecting:
- case R.string.state_auth:
- //status.setTextColor(Color.WHITE);
- enabledWidgets(false);
- showBanner(false);
- break;
- case R.string.state_connected:
- TastyToast.makeText(this, "Connected Success", TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
- //status.setTextColor(Color.GREEN);
- enabledWidgets(false);
- showBanner(false);
- break;
- case R.string.state_disconnected:
- case R.string.state_auth_failed:
- //status.setTextColor(Color.RED);
- StatisticGraphData.getStatisticData().getDataTransferStats().stop();
- graph.stop();
- enabledWidgets(true);
- showBanner(true);
- break;
- }
- // TODO: Implement this method
- }
- private void renderLastEvent()
- {
- int state = prefs.getInt("SSH_STATUS", R.string.state_disconnected);
- if (ConfigUtil.getInstance(this).getConnectionType() == 0) {
- status.setText(prefs.getString("OPENVPN_STATUS",""));
- } else {
- status.setText(state);
- switch (state) {
- case R.string.state_connecting:
- case R.string.state_reconnecting:
- case R.string.state_auth:
- enabledWidgets(false);
- showBanner(false);
- break;
- case R.string.state_connected:
- TastyToast.makeText(this, "Connected Success", TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
- enabledWidgets(false);
- showBanner(false);
- break;
- case R.string.state_disconnected:
- case R.string.state_auth_failed:
- enabledWidgets(true);
- StatisticGraphData.getStatisticData().getDataTransferStats().stop();
- graph.stop();
- showBanner(true);
- break;
- }
- }
- }
- private void showCustomPayload()
- {
- View v = getLayoutInflater().inflate(R.layout.custom_payload, null);
- custom_payload_input = (EditText)v.findViewById(R.id.custom_payload_input);
- final EditText custom_sni_input = (EditText)v.findViewById(R.id.custom_sni_input);
- final Button advance,cancel,save;
- advance = (Button)v.findViewById(R.id.custom_btn_advance);
- cancel = (Button)v.findViewById(R.id.custom_btn_cancel);
- save = (Button)v.findViewById(R.id.custom_btn_save);
- final ConfigUtil config = ConfigUtil.getInstance(this);
- custom_payload_input.setText(prefs.getString("custom_payload_input", ""));
- custom_sni_input.setText(prefs.getString("custom_sni_input", ""));
- final AlertDialog builder = new AlertDialog.Builder(this).create();
- builder.setTitle("Custom");
- builder.setView(v);
- advance.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v)
- {
- try {
- JSONObject server = ((JSONObject)server_spin.getSelectedItem());
- String serverName = server.getString("Name");
- String category = server.getString("Category");
- VpnProfile vp = getPM().getProfileByName(serverName + "-" + category);
- gh = new GeneratorHelper(Main.this);
- gh.setCancelListener(Main.this);
- gh.setVpnProfile(vp);
- gh.show();
- builder.show();
- } catch (Exception e) {
- showToast(e.getMessage());
- }
- // TODO: Implement this method
- }
- });
- save.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v)
- {
- String payload = custom_payload_input.getText().toString();
- String sni = custom_sni_input.getText().toString();
- if (connect_type.getCheckedRadioButtonId() == R.id.type_ssh_ssl) {
- if (sni.isEmpty()) {
- showToast("SNI Host cannot be empty!");
- builder.show();
- } else {
- editor.putString("custom_sni_input", sni).apply();
- config.setSni(sni);
- builder.dismiss();
- }
- } else {
- if (payload.isEmpty()) {
- showToast("Payload is empty!");
- builder.show();
- } else {
- config.setPayload(payload);
- editor.putString("custom_payload_input",payload).apply();
- builder.dismiss();
- }
- }
- // TODO: Implement this method
- }
- });
- cancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View p1)
- {
- use_payload.setChecked(false);
- builder.dismiss();
- // TODO: Implement this method
- }
- });
- builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
- @Override
- public void onCancel(DialogInterface p1)
- {
- use_payload.setChecked(false);
- // TODO: Implement this method
- }
- });
- builder.show();
- }
- @Override
- public void onCancel(boolean z)
- {
- use_payload.setChecked(!z);
- network_spin.setEnabled(z);
- if (!z) {
- custom_payload_input.setText(ConfigUtil.getInstance(this).getPayload());
- }
- // TODO: Implement this method
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu)
- {
- getMenuInflater().inflate(R.menu.home_menu, menu);
- // TODO: Implement this method
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item)
- {
- switch (item.getItemId()) {
- case R.id.menu_about:
- about();
- break;
- }
- // TODO: Implement this method
- return super.onOptionsItemSelected(item);
- }
- public void viewWeb(String str)
- {
- if (str.isEmpty()) {
- showToast("Link is empty!");
- } else {
- startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));
- }
- }
- public void about()
- {
- View v = getLayoutInflater().inflate(R.layout.about_app, null);
- TextView tvDev = (TextView)v.findViewById(R.id.developer);
- tvDev.setText("Tsholo Corporation");
- int vis = tvDev.getVisibility();
- if (vis == View.GONE) {
- finish();
- } else if (vis == View.INVISIBLE) {
- finish();
- }
- AlertDialog.Builder ab = new AlertDialog.Builder(this);
- ab.setTitle("About");
- ab.setView(v);
- ab.setPositiveButton("Ok", null);
- ab.show();
- }
- /*private String getConfig()
- {
- try {
- return str;
- } catch (Exception e) {
- showToast(e.getMessage());
- }
- return null;
- }*/
- private void startInjector(VpnProfile vp)
- {
- try {
- ConfigUtil config = ConfigUtil.getInstance(this);
- if (!use_payload.isChecked()) {
- if (connect_type.getCheckedRadioButtonId() != R.id.type_ssh_ssl) {
- JSONObject proxySet = ((JSONObject)server_spin.getSelectedItem()).getJSONObject("ProxySettings");
- int position = network_spin.getSelectedItemPosition();
- String payload = getNetworksArray().getJSONObject(position).getString("Payload");
- String proxy = proxySet.getString("Squid");
- String port = proxySet.getString("Port");
- JSONObject sslObject = getSSLNetworkObject();
- if (sslObject != null) {
- String sni = sslObject.getString("SNIHost");
- config.setSni(sni);
- }
- config.setPayload(payload);
- config.setProxy(proxy);
- config.setProxyPort(port);
- }
- }
- } catch (Exception e) {
- showToast("Start VPN Error: " + e.getMessage());
- }
- String user = username.getText().toString();
- String pass = password.getText().toString();
- if (user.isEmpty()) {
- showToast("Username is empty!");
- } else if (pass.isEmpty()) {
- showToast("Password is empty!");
- } else {
- startService(new Intent(this, InjectorService.class).setAction("START").putExtra("UUID", vp.getUUIDString()));
- }
- }
- private void show_stats(String log, ConnectionStatus level)
- {
- if (log != null) {
- if (ConfigUtil.getInstance(this).getConnectionType() == 0) {
- status.setText(log);
- editor.putString("OPENVPN_STATUS", log).apply();
- switch (level) {
- case LEVEL_START:
- case LEVEL_CONNECTING_NO_SERVER_REPLY_YET:
- case LEVEL_CONNECTING_SERVER_REPLIED:
- case LEVEL_VPNPAUSED:
- //status.setTextColor(Color.WHITE);
- enabledWidgets(false);
- showBanner(false);
- break;
- case LEVEL_CONNECTED:
- TastyToast.makeText(this, "Connected Success", TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
- enabledWidgets(false);
- showBanner(false);
- break;
- case LEVEL_NONETWORK:
- enabledWidgets(false);
- break;
- case LEVEL_AUTH_FAILED:
- TastyToast.makeText(this, "Wrong username or password!", TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
- getPM().setConntectedVpnProfileDisconnected(this);
- enabledWidgets(true);
- showBanner(true);
- break;
- case LEVEL_NOTCONNECTED:
- getPM().setConntectedVpnProfileDisconnected(this);
- enabledWidgets(true);
- showBanner(true);
- break;
- }
- }
- }
- }
- private void enabledWidgets(boolean z)
- {
- if (z) {
- graphView.setVisibility(View.GONE);
- connect.setVisibility(View.VISIBLE);
- disconnect.setVisibility(View.GONE);
- } else {
- graphView.setVisibility(View.VISIBLE);
- connect.setVisibility(View.GONE);
- disconnect.setVisibility(View.VISIBLE);
- }
- for (int i = 0; i < connect_type.getChildCount(); i++) {
- View v = connect_type.getChildAt(i);
- v.setEnabled(z);
- }
- username.setEnabled(z);
- password.setEnabled(z);
- use_payload.setEnabled(z);
- //save_pass.setEnabled(z);
- bt_toggle_input.setEnabled(z);
- server_spin.setEnabled(z);
- network_spin.setEnabled(z);
- category_spin.setEnabled(z);
- }
- private void showBanner(boolean z)
- {
- /*if (z) {
- bannerView.setVisibility(View.VISIBLE);
- graphView.setVisibility(View.GONE);
- } else {
- bannerView.setVisibility(View.GONE);
- graphView.setVisibility(View.VISIBLE);
- }*/
- }
- private ProfileManager getPM()
- {
- return ProfileManager.getInstance(this);
- }
- /*@Override
- protected void onStart()
- {
- // TODO: Implement this method
- super.onStart();
- }*/
- @Override
- protected void onResume()
- {
- VpnStatus.addStateListener(this);
- VpnStatus.addByteCountListener(this);
- doBind();
- if (InjectorService.isRunning) {
- enabledWidgets(false);
- } else {
- enabledWidgets(true);
- }
- timer = new Timer();
- timer.schedule(new TimerTask() {
- @Override
- public void run()
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run()
- {
- StatisticGraphData.DataTransferStats stats = StatisticGraphData.getStatisticData().getDataTransferStats();
- upBytes.setText(stats.byteCountToDisplaySize(stats.getBytesSent(), false));
- dlBytes.setText(stats.byteCountToDisplaySize(stats.getBytesReceived(), false));
- String duration = stats.isConnected() ? stats.elapsedTimeToDisplay(stats.getElapsedTime()) : "[00h:00m:00s]";
- elapsedTime.setText(duration);
- // TODO: Implement this method
- }
- });
- // TODO: Implement this method
- }
- },0, 1000);
- // TODO: Implement this method
- super.onResume();
- }
- @Override
- protected void onDestroy()
- {
- try {
- doUnbind();
- VpnStatus.removeStateListener(this);
- VpnStatus.removeByteCountListener(this);
- if (timer != null) {
- timer.cancel();
- }
- } catch (Exception e) {
- //ignore error we just want to remove listeners
- }
- // TODO: Implement this method
- super.onDestroy();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement