Search in sources :

Example 1 with Interrupter

use of com.genonbeta.TrebleShot.util.Interrupter in project TrebleShot by genonbeta.

the class CommunicationService method onStartCommand.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (intent != null)
        Log.d(TAG, "onStart() : action = " + intent.getAction());
    if (intent != null && AppUtils.checkRunningConditions(this)) {
        if (ACTION_FILE_TRANSFER.equals(intent.getAction())) {
            final int groupId = intent.getIntExtra(EXTRA_GROUP_ID, -1);
            final int notificationId = intent.getIntExtra(NotificationUtils.EXTRA_NOTIFICATION_ID, -1);
            final boolean isAccepted = intent.getBooleanExtra(EXTRA_IS_ACCEPTED, false);
            getNotificationHelper().getUtils().cancel(notificationId);
            try {
                final TransferInstance transferInstance = new TransferInstance(getDatabase(), groupId);
                CommunicationBridge.connect(getDatabase(), new CommunicationBridge.Client.ConnectionHandler() {

                    @Override
                    public void onConnect(CommunicationBridge.Client client) {
                        try {
                            CoolSocket.ActiveConnection activeConnection = client.communicate(transferInstance.getDevice(), transferInstance.getConnection());
                            activeConnection.reply(new JSONObject().put(Keyword.REQUEST, Keyword.REQUEST_RESPONSE).put(Keyword.TRANSFER_GROUP_ID, groupId).put(Keyword.TRANSFER_IS_ACCEPTED, isAccepted).toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                if (isAccepted)
                    startFileReceiving(groupId);
                else
                    mDatabase.remove(transferInstance.getGroup());
            } catch (Exception e) {
                e.printStackTrace();
                if (isAccepted)
                    getNotificationHelper().showToast(R.string.mesg_somethingWentWrong);
            }
        } else if (ACTION_IP.equals(intent.getAction())) {
            String deviceId = intent.getStringExtra(EXTRA_DEVICE_ID);
            boolean isAccepted = intent.getBooleanExtra(EXTRA_IS_ACCEPTED, false);
            int notificationId = intent.getIntExtra(NotificationUtils.EXTRA_NOTIFICATION_ID, -1);
            getNotificationHelper().getUtils().cancel(notificationId);
            NetworkDevice device = new NetworkDevice(deviceId);
            try {
                mDatabase.reconstruct(device);
                device.isRestricted = !isAccepted;
                mDatabase.update(device);
            } catch (Exception e) {
                e.printStackTrace();
                return START_NOT_STICKY;
            }
        } else if (ACTION_CANCEL_INDEXING.equals(intent.getAction())) {
            int notificationId = intent.getIntExtra(NotificationUtils.EXTRA_NOTIFICATION_ID, -1);
            int groupId = intent.getIntExtra(EXTRA_GROUP_ID, -1);
            getNotificationHelper().getUtils().cancel(notificationId);
            Interrupter interrupter = getOngoingIndexList().get(groupId);
            if (interrupter != null)
                interrupter.interrupt();
        } else if (ACTION_CLIPBOARD.equals(intent.getAction()) && intent.hasExtra(EXTRA_CLIPBOARD_ACCEPTED)) {
            int notificationId = intent.getIntExtra(NotificationUtils.EXTRA_NOTIFICATION_ID, -1);
            int clipboardId = intent.getIntExtra(EXTRA_CLIPBOARD_ID, -1);
            boolean isAccepted = intent.getBooleanExtra(EXTRA_CLIPBOARD_ACCEPTED, false);
            TextStreamObject textStreamObject = new TextStreamObject(clipboardId);
            getNotificationHelper().getUtils().cancel(notificationId);
            try {
                getDatabase().reconstruct(textStreamObject);
                if (isAccepted) {
                    ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("receivedText", textStreamObject.text));
                    Toast.makeText(this, R.string.mesg_textCopiedToClipboard, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (ACTION_END_SESSION.equals(intent.getAction())) {
            stopSelf();
        } else if (ACTION_SEAMLESS_RECEIVE.equals(intent.getAction()) && intent.hasExtra(EXTRA_GROUP_ID)) {
            int groupId = intent.getIntExtra(EXTRA_GROUP_ID, -1);
            try {
                CoolTransfer.TransferHandler<ProcessHolder> process = findProcessById(groupId);
                if (process == null)
                    startFileReceiving(groupId);
                else
                    Toast.makeText(this, getString(R.string.mesg_groupOngoingNotice, process.getExtra().transactionObject.friendlyName), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (ACTION_CANCEL_JOB.equals(intent.getAction()) || ACTION_CANCEL_KILL.equals(intent.getAction())) {
            int groupId = intent.getIntExtra(EXTRA_GROUP_ID, -1);
            int notificationId = intent.getIntExtra(NotificationUtils.EXTRA_NOTIFICATION_ID, -1);
            CoolTransfer.TransferHandler<ProcessHolder> handler = findProcessById(groupId);
            if (handler == null || ACTION_CANCEL_KILL.equals(intent.getAction()))
                getNotificationHelper().getUtils().cancel(notificationId);
            if (handler != null) {
                if (ACTION_CANCEL_KILL.equals(intent.getAction())) {
                    try {
                        if (handler instanceof CoolTransfer.Receive.Handler) {
                            CoolTransfer.Receive.Handler receiveHandler = ((CoolTransfer.Receive.Handler) handler);
                            if (receiveHandler.getServerSocket() != null)
                                receiveHandler.getServerSocket().close();
                        }
                        if (handler.getExtra().activeConnection.getSocket() != null)
                            handler.getExtra().activeConnection.getSocket().close();
                        if (handler.getSocket() != null)
                            handler.getSocket().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    handler.getExtra().notification = getNotificationHelper().notifyStuckThread(handler.getExtra().transactionObject);
                    handler.interrupt();
                }
            }
        } else if (ACTION_TOGGLE_SEAMLESS_MODE.equals(intent.getAction())) {
            updateServiceState(!mSeamlessMode);
        } else if (ACTION_TOGGLE_HOTSPOT.equals(intent.getAction()) && (Build.VERSION.SDK_INT < 23 || Settings.System.canWrite(this))) {
            setupHotspot();
        } else if (ACTION_REQUEST_HOTSPOT_STATUS.equals(intent.getAction()))
            sendHotspotStatus(getHotspotUtils().getConfiguration());
    }
    return START_STICKY;
}
Also used : Interrupter(com.genonbeta.TrebleShot.util.Interrupter) TextStreamObject(com.genonbeta.TrebleShot.object.TextStreamObject) CoolTransfer(com.genonbeta.CoolSocket.CoolTransfer) NetworkDevice(com.genonbeta.TrebleShot.object.NetworkDevice) CommunicationBridge(com.genonbeta.TrebleShot.util.CommunicationBridge) IOException(java.io.IOException) TimeoutException(java.util.concurrent.TimeoutException) JSONException(org.json.JSONException) ConnectionNotFoundException(com.genonbeta.TrebleShot.exception.ConnectionNotFoundException) IOException(java.io.IOException) DeviceNotFoundException(com.genonbeta.TrebleShot.exception.DeviceNotFoundException) TransactionGroupNotFoundException(com.genonbeta.TrebleShot.exception.TransactionGroupNotFoundException) JSONObject(org.json.JSONObject) TransferInstance(com.genonbeta.TrebleShot.object.TransferInstance)

Example 2 with Interrupter

use of com.genonbeta.TrebleShot.util.Interrupter in project TrebleShot by genonbeta.

the class CommunicationService method onDestroy.

@Override
public void onDestroy() {
    super.onDestroy();
    mCommunicationServer.stop();
    mSeamlessServer.stop();
    mMediaScanner.disconnect();
    mNsdDiscovery.unregisterService();
    if (getHotspotUtils().unloadPreviousConfig())
        getHotspotUtils().disable();
    if (getWifiLock() != null && getWifiLock().isHeld())
        getWifiLock().release();
    stopForeground(true);
    synchronized (getOngoingIndexList()) {
        for (Interrupter interrupter : getOngoingIndexList().values()) interrupter.interrupt(false);
    }
    synchronized (mReceive.getProcessList()) {
        for (CoolTransfer.TransferHandler<ProcessHolder> transferHandler : mReceive.getProcessList()) transferHandler.interrupt();
    }
    synchronized (mSend.getProcessList()) {
        for (CoolTransfer.TransferHandler<ProcessHolder> transferHandler : mSend.getProcessList()) transferHandler.interrupt();
    }
}
Also used : Interrupter(com.genonbeta.TrebleShot.util.Interrupter) CoolTransfer(com.genonbeta.CoolSocket.CoolTransfer)

Example 3 with Interrupter

use of com.genonbeta.TrebleShot.util.Interrupter in project TrebleShot by genonbeta.

the class HomeActivity method sendThisApplication.

private void sendThisApplication() {
    new Handler(Looper.myLooper()).post(new Runnable() {

        @Override
        public void run() {
            try {
                Interrupter interrupter = new Interrupter();
                PackageManager pm = getPackageManager();
                Intent sendIntent = new Intent(Intent.ACTION_SEND);
                PackageInfo packageInfo = pm.getPackageInfo(getApplicationInfo().packageName, 0);
                String fileName = packageInfo.applicationInfo.loadLabel(pm) + "_" + packageInfo.versionName + ".apk";
                DocumentFile storageDirectory = FileUtils.getApplicationDirectory(getApplicationContext());
                DocumentFile codeFile = DocumentFile.fromFile(new File(getApplicationInfo().sourceDir));
                DocumentFile cloneFile = storageDirectory.createFile(null, FileUtils.getUniqueFileName(storageDirectory, fileName, true));
                FileUtils.copy(HomeActivity.this, codeFile, cloneFile, interrupter);
                try {
                    sendIntent.putExtra(ShareActivity.EXTRA_FILENAME_LIST, fileName).putExtra(Intent.EXTRA_STREAM, FileUtils.getSecureUri(HomeActivity.this, cloneFile)).setType(cloneFile.getType());
                    startActivity(Intent.createChooser(sendIntent, getString(R.string.text_fileShareAppChoose)));
                } catch (IllegalArgumentException e) {
                    Toast.makeText(HomeActivity.this, R.string.mesg_providerNotAllowedError, Toast.LENGTH_LONG).show();
                    openFolder(storageDirectory);
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : Interrupter(com.genonbeta.TrebleShot.util.Interrupter) DocumentFile(com.genonbeta.TrebleShot.io.DocumentFile) PackageManager(android.content.pm.PackageManager) PackageInfo(android.content.pm.PackageInfo) Handler(android.os.Handler) Intent(android.content.Intent) DocumentFile(com.genonbeta.TrebleShot.io.DocumentFile) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException)

Example 4 with Interrupter

use of com.genonbeta.TrebleShot.util.Interrupter in project TrebleShot by genonbeta.

the class ConnectionChooserDialog method show.

@Override
public AlertDialog show() {
    mAdapter.notifyDataSetChanged();
    final ArrayList<NetworkDevice.Connection> tmpList = getConnections();
    if (tmpList.size() > 0) {
        setMessage(null);
        setNeutralButton(R.string.butn_feelLucky, null);
    } else
        setMessage(R.string.text_noNetworkAvailable);
    mDialog = super.show();
    startRefreshing();
    Button buttonPositive = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
    if (buttonPositive != null)
        buttonPositive.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                getContext().startService(new Intent(getContext(), DeviceScannerService.class).setAction(DeviceScannerService.ACTION_SCAN_DEVICES));
            }
        });
    mDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final ProgressDialog feelLucky = new ProgressDialog(getContext());
            final Interrupter interrupter = new Interrupter();
            feelLucky.setTitle(R.string.text_feelLuckyOngoing);
            feelLucky.setMax(tmpList.size());
            feelLucky.setCancelable(false);
            feelLucky.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            feelLucky.setButton(ProgressDialog.BUTTON_NEGATIVE, getContext().getString(R.string.butn_cancel), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    interrupter.interrupt();
                }
            });
            feelLucky.show();
            new Thread() {

                @Override
                public void run() {
                    super.run();
                    Looper.prepare();
                    @SuppressLint("UseSparseArrays") final HashMap<Integer, NetworkDevice.Connection> calculatedConnections = new HashMap<>();
                    for (final NetworkDevice.Connection connection : tmpList) {
                        if (interrupter.interrupted())
                            break;
                        feelLucky.setProgress(feelLucky.getProgress() + 1);
                        if (!NetworkUtils.ping(connection.ipAddress, 500))
                            continue;
                        Integer calculatedTime = CommunicationBridge.connect(mDatabase, Integer.class, new CommunicationBridge.Client.ConnectionHandler() {

                            @Override
                            public void onConnect(CommunicationBridge.Client client) {
                                int outTime = -1;
                                try {
                                    final long startTime = System.currentTimeMillis();
                                    final CoolSocket.ActiveConnection activeConnection = client.connect(connection);
                                    final Interrupter.Closer selfCloser = new Interrupter.Closer() {

                                        @Override
                                        public void onClose(boolean userAction) {
                                            try {
                                                activeConnection.getSocket().close();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    };
                                    interrupter.addCloser(selfCloser);
                                    client.handshake(activeConnection, true);
                                    client.updateDeviceIfOkay(activeConnection, mNetworkDevice);
                                    interrupter.removeCloser(selfCloser);
                                    outTime = (int) (System.currentTimeMillis() - startTime);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    client.setReturn(outTime);
                                }
                            }
                        });
                        if (calculatedTime != null && calculatedTime > -1)
                            calculatedConnections.put(calculatedTime, connection);
                    }
                    feelLucky.cancel();
                    if (!interrupter.interrupted())
                        if (calculatedConnections.size() < 1) {
                            AlertDialog.Builder sorryDialog = new AlertDialog.Builder(getContext());
                            sorryDialog.setTitle(R.string.text_error);
                            sorryDialog.setMessage(R.string.text_feelLuckyFailed);
                            sorryDialog.setNegativeButton(R.string.butn_close, null);
                            sorryDialog.show();
                        } else {
                            final ArrayList<Integer> comparedList = new ArrayList<>(calculatedConnections.keySet());
                            Collections.sort(comparedList, new Comparator<Integer>() {

                                @Override
                                public int compare(Integer integer1, Integer integer2) {
                                    return integer1 < integer2 ? -1 : 1;
                                }
                            });
                            if (mActivity != null)
                                mActivity.runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        mDeviceSelectedListener.onDeviceSelected(calculatedConnections.get(comparedList.get(0)), tmpList);
                                    }
                                });
                            mDialog.cancel();
                        }
                    Looper.loop();
                }
            }.start();
        }
    });
    return mDialog;
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) DialogInterface(android.content.DialogInterface) HashMap(java.util.HashMap) NetworkDevice(com.genonbeta.TrebleShot.object.NetworkDevice) ArrayList(java.util.ArrayList) ProgressDialog(android.app.ProgressDialog) Comparator(java.util.Comparator) Button(android.widget.Button) Interrupter(com.genonbeta.TrebleShot.util.Interrupter) Intent(android.content.Intent) CommunicationBridge(com.genonbeta.TrebleShot.util.CommunicationBridge) IOException(java.io.IOException) View(android.view.View) TextView(android.widget.TextView) IOException(java.io.IOException) SuppressLint(android.annotation.SuppressLint)

Aggregations

Interrupter (com.genonbeta.TrebleShot.util.Interrupter)4 Intent (android.content.Intent)2 CoolTransfer (com.genonbeta.CoolSocket.CoolTransfer)2 NetworkDevice (com.genonbeta.TrebleShot.object.NetworkDevice)2 CommunicationBridge (com.genonbeta.TrebleShot.util.CommunicationBridge)2 IOException (java.io.IOException)2 SuppressLint (android.annotation.SuppressLint)1 ProgressDialog (android.app.ProgressDialog)1 DialogInterface (android.content.DialogInterface)1 PackageInfo (android.content.pm.PackageInfo)1 PackageManager (android.content.pm.PackageManager)1 Handler (android.os.Handler)1 AlertDialog (android.support.v7.app.AlertDialog)1 View (android.view.View)1 Button (android.widget.Button)1 TextView (android.widget.TextView)1 ConnectionNotFoundException (com.genonbeta.TrebleShot.exception.ConnectionNotFoundException)1 DeviceNotFoundException (com.genonbeta.TrebleShot.exception.DeviceNotFoundException)1 TransactionGroupNotFoundException (com.genonbeta.TrebleShot.exception.TransactionGroupNotFoundException)1 DocumentFile (com.genonbeta.TrebleShot.io.DocumentFile)1