Search in sources :

Example 1 with WorkerThread

use of androidx.annotation.WorkerThread in project k-9 by k9mail.

the class AttachmentInfoExtractor method extractAttachmentInfoForView.

@WorkerThread
public List<AttachmentViewInfo> extractAttachmentInfoForView(List<Part> attachmentParts) throws MessagingException {
    List<AttachmentViewInfo> attachments = new ArrayList<>();
    for (Part part : attachmentParts) {
        AttachmentViewInfo attachmentViewInfo = extractAttachmentInfo(part);
        attachments.add(attachmentViewInfo);
    }
    return attachments;
}
Also used : Part(com.fsck.k9.mail.Part) LocalPart(com.fsck.k9.mailstore.LocalPart) ArrayList(java.util.ArrayList) AttachmentViewInfo(com.fsck.k9.mailstore.AttachmentViewInfo) WorkerThread(androidx.annotation.WorkerThread)

Example 2 with WorkerThread

use of androidx.annotation.WorkerThread in project k-9 by k9mail.

the class AttachmentTempFileProvider method createTempUriForContentUri.

@WorkerThread
public static Uri createTempUriForContentUri(Context context, Uri uri) throws IOException {
    Context applicationContext = context.getApplicationContext();
    File tempFile = getTempFileForUri(uri, applicationContext);
    writeUriContentToTempFileIfNotExists(context, uri, tempFile);
    Uri tempFileUri = FileProvider.getUriForFile(context, AUTHORITY, tempFile);
    registerFileCleanupReceiver(applicationContext);
    return tempFileUri;
}
Also used : Context(android.content.Context) File(java.io.File) Uri(android.net.Uri) WorkerThread(androidx.annotation.WorkerThread)

Example 3 with WorkerThread

use of androidx.annotation.WorkerThread in project kdeconnect-android by KDE.

the class BluetoothLink method sendPacket.

@WorkerThread
@Override
public boolean sendPacket(NetworkPacket np, final Device.SendPacketStatusCallback callback) {
    try {
        UUID transferUuid = null;
        if (np.hasPayload()) {
            transferUuid = connection.newChannel();
            JSONObject payloadTransferInfo = new JSONObject();
            payloadTransferInfo.put("uuid", transferUuid.toString());
            np.setPayloadTransferInfo(payloadTransferInfo);
        }
        sendMessage(np);
        if (transferUuid != null) {
            try (OutputStream payloadStream = connection.getChannelOutputStream(transferUuid)) {
                int BUFFER_LENGTH = 1024;
                byte[] buffer = new byte[BUFFER_LENGTH];
                int bytesRead;
                long progress = 0;
                InputStream stream = np.getPayload().getInputStream();
                while ((bytesRead = stream.read(buffer)) != -1) {
                    progress += bytesRead;
                    payloadStream.write(buffer, 0, bytesRead);
                    if (np.getPayloadSize() > 0) {
                        callback.onProgressChanged((int) (100 * progress / np.getPayloadSize()));
                    }
                }
                payloadStream.flush();
            } catch (Exception e) {
                callback.onFailure(e);
                return false;
            }
        }
        callback.onSuccess();
        return true;
    } catch (Exception e) {
        callback.onFailure(e);
        return false;
    }
}
Also used : JSONObject(org.json.JSONObject) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) UUID(java.util.UUID) IOException(java.io.IOException) JSONException(org.json.JSONException) WorkerThread(androidx.annotation.WorkerThread)

Example 4 with WorkerThread

use of androidx.annotation.WorkerThread in project kdeconnect-android by KDE.

the class LanLink method sendPacket.

// Blocking, do not call from main thread
@WorkerThread
@Override
public boolean sendPacket(NetworkPacket np, final Device.SendPacketStatusCallback callback) {
    if (socket == null) {
        Log.e("KDE/sendPacket", "Not yet connected");
        callback.onFailure(new NotYetConnectedException());
        return false;
    }
    try {
        // Prepare socket for the payload
        final ServerSocket server;
        if (np.hasPayload()) {
            server = LanLinkProvider.openServerSocketOnFreePort(LanLinkProvider.PAYLOAD_TRANSFER_MIN_PORT);
            JSONObject payloadTransferInfo = new JSONObject();
            payloadTransferInfo.put("port", server.getLocalPort());
            np.setPayloadTransferInfo(payloadTransferInfo);
        } else {
            server = null;
        }
        // Send body of the network package
        try {
            OutputStream writer = socket.getOutputStream();
            writer.write(np.serialize().getBytes(Charsets.UTF_8));
            writer.flush();
        } catch (Exception e) {
            // main socket is broken, disconnect
            disconnect();
            throw e;
        }
        // Send payload
        if (server != null) {
            Socket payloadSocket = null;
            OutputStream outputStream = null;
            InputStream inputStream;
            try {
                // Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards
                server.setSoTimeout(10 * 1000);
                payloadSocket = server.accept();
                // Convert to SSL if needed
                payloadSocket = SslHelper.convertToSslSocket(context, payloadSocket, getDeviceId(), true, false);
                outputStream = payloadSocket.getOutputStream();
                inputStream = np.getPayload().getInputStream();
                Log.i("KDE/LanLink", "Beginning to send payload");
                byte[] buffer = new byte[4096];
                int bytesRead;
                long size = np.getPayloadSize();
                long progress = 0;
                long timeSinceLastUpdate = -1;
                while (!np.isCanceled() && (bytesRead = inputStream.read(buffer)) != -1) {
                    // Log.e("ok",""+bytesRead);
                    progress += bytesRead;
                    outputStream.write(buffer, 0, bytesRead);
                    if (size > 0) {
                        if (timeSinceLastUpdate + 500 < System.currentTimeMillis()) {
                            // Report progress every half a second
                            long percent = ((100 * progress) / size);
                            callback.onProgressChanged((int) percent);
                            timeSinceLastUpdate = System.currentTimeMillis();
                        }
                    }
                }
                outputStream.flush();
                Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)");
            } catch (SSLHandshakeException e) {
                // The exception can be due to several causes. "Connection closed by peer" seems to be a common one.
                // If we could distinguish different cases we could react differently for some of them, but I haven't found how.
                Log.e("sendPacket", "Payload SSLSocket failed");
                e.printStackTrace();
            } finally {
                try {
                    server.close();
                } catch (Exception ignored) {
                }
                try {
                    payloadSocket.close();
                } catch (Exception ignored) {
                }
                np.getPayload().close();
                try {
                    outputStream.close();
                } catch (Exception ignored) {
                }
            }
        }
        if (!np.isCanceled()) {
            callback.onSuccess();
        }
        return true;
    } catch (Exception e) {
        if (callback != null) {
            callback.onFailure(e);
        }
        return false;
    } finally {
        // Make sure we close the payload stream, if any
        if (np.hasPayload()) {
            np.getPayload().close();
        }
    }
}
Also used : JSONObject(org.json.JSONObject) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ServerSocket(java.net.ServerSocket) NotYetConnectedException(java.nio.channels.NotYetConnectedException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) NotYetConnectedException(java.nio.channels.NotYetConnectedException) SocketTimeoutException(java.net.SocketTimeoutException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) WorkerThread(androidx.annotation.WorkerThread)

Example 5 with WorkerThread

use of androidx.annotation.WorkerThread in project materialistic by hidroh.

the class FileDownloader method downloadFile.

@WorkerThread
public void downloadFile(String url, String mimeType, FileDownloaderCallback callback) {
    File outputFile = new File(mCacheDir, new File(url).getName());
    if (outputFile.exists()) {
        mMainHandler.post(() -> callback.onSuccess(outputFile.getPath()));
        return;
    }
    final Request request = new Request.Builder().url(url).addHeader("Content-Type", mimeType).build();
    mCallFactory.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            mMainHandler.post(() -> callback.onFailure(call, e));
        }

        @Override
        public void onResponse(Call call, Response response) {
            try {
                BufferedSink sink = Okio.buffer(Okio.sink(outputFile));
                sink.writeAll(response.body().source());
                sink.close();
                mMainHandler.post(() -> callback.onSuccess(outputFile.getPath()));
            } catch (IOException e) {
                this.onFailure(call, e);
            }
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) File(java.io.File) WorkerThread(androidx.annotation.WorkerThread)

Aggregations

WorkerThread (androidx.annotation.WorkerThread)204 NonNull (androidx.annotation.NonNull)77 IOException (java.io.IOException)45 Recipient (org.thoughtcrime.securesms.recipients.Recipient)41 Nullable (androidx.annotation.Nullable)26 RecipientId (org.thoughtcrime.securesms.recipients.RecipientId)23 Cursor (android.database.Cursor)22 ArrayList (java.util.ArrayList)22 Context (android.content.Context)20 Uri (android.net.Uri)18 LinkedList (java.util.LinkedList)15 List (java.util.List)15 HashMap (java.util.HashMap)14 RecipientDatabase (org.thoughtcrime.securesms.database.RecipientDatabase)14 Stream (com.annimon.stream.Stream)13 Log (org.signal.core.util.logging.Log)13 HashSet (java.util.HashSet)12 InputStream (java.io.InputStream)11 Bitmap (android.graphics.Bitmap)10 Collections (java.util.Collections)10