Search in sources :

Example 31 with Stopwatch

use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.

the class ConversationDataSource method load.

@Override
@NonNull
public List<ConversationMessage> load(int start, int length, @NonNull CancellationSignal cancellationSignal) {
    Stopwatch stopwatch = new Stopwatch("load(" + start + ", " + length + "), thread " + threadId);
    MmsSmsDatabase db = SignalDatabase.mmsSms();
    List<MessageRecord> records = new ArrayList<>(length);
    MentionHelper mentionHelper = new MentionHelper();
    AttachmentHelper attachmentHelper = new AttachmentHelper();
    ReactionHelper reactionHelper = new ReactionHelper();
    try (MmsSmsDatabase.Reader reader = MmsSmsDatabase.readerFor(db.getConversation(threadId, start, length))) {
        MessageRecord record;
        while ((record = reader.getNext()) != null && !cancellationSignal.isCanceled()) {
            records.add(record);
            mentionHelper.add(record);
            reactionHelper.add(record);
            attachmentHelper.add(record);
        }
    }
    if (messageRequestData.includeWarningUpdateMessage() && (start + length >= size())) {
        records.add(new InMemoryMessageRecord.NoGroupsInCommon(threadId, messageRequestData.isGroup()));
    }
    if (showUniversalExpireTimerUpdate) {
        records.add(new InMemoryMessageRecord.UniversalExpireTimerUpdate(threadId));
    }
    stopwatch.split("messages");
    mentionHelper.fetchMentions(context);
    stopwatch.split("mentions");
    reactionHelper.fetchReactions(context);
    stopwatch.split("reactions");
    records = reactionHelper.buildUpdatedModels(context, records);
    stopwatch.split("reaction-models");
    attachmentHelper.fetchAttachments(context);
    stopwatch.split("attachments");
    records = attachmentHelper.buildUpdatedModels(context, records);
    stopwatch.split("attachment-models");
    List<ConversationMessage> messages = Stream.of(records).map(m -> ConversationMessageFactory.createWithUnresolvedData(context, m, mentionHelper.getMentions(m.getId()))).toList();
    stopwatch.split("conversion");
    stopwatch.stop(TAG);
    return messages;
}
Also used : Context(android.content.Context) MessageRequestData(org.thoughtcrime.securesms.conversation.ConversationData.MessageRequestData) MmsSmsDatabase(org.thoughtcrime.securesms.database.MmsSmsDatabase) SignalDatabase(org.thoughtcrime.securesms.database.SignalDatabase) Stream(com.annimon.stream.Stream) Util(org.thoughtcrime.securesms.util.Util) NonNull(androidx.annotation.NonNull) HashMap(java.util.HashMap) Mention(org.thoughtcrime.securesms.database.model.Mention) MessageRecord(org.thoughtcrime.securesms.database.model.MessageRecord) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) ArrayList(java.util.ArrayList) Map(java.util.Map) MediaMmsMessageRecord(org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord) LinkedList(java.util.LinkedList) ConversationMessageFactory(org.thoughtcrime.securesms.conversation.ConversationMessage.ConversationMessageFactory) MessageId(org.thoughtcrime.securesms.database.model.MessageId) PagedDataSource(org.signal.paging.PagedDataSource) ApplicationDependencies(org.thoughtcrime.securesms.dependencies.ApplicationDependencies) Collection(java.util.Collection) ReactionRecord(org.thoughtcrime.securesms.database.model.ReactionRecord) InMemoryMessageRecord(org.thoughtcrime.securesms.database.model.InMemoryMessageRecord) Collectors(java.util.stream.Collectors) Log(org.signal.core.util.logging.Log) List(java.util.List) Nullable(androidx.annotation.Nullable) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) MessageDatabase(org.thoughtcrime.securesms.database.MessageDatabase) SmsMessageRecord(org.thoughtcrime.securesms.database.model.SmsMessageRecord) Collections(java.util.Collections) InMemoryMessageRecord(org.thoughtcrime.securesms.database.model.InMemoryMessageRecord) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) ArrayList(java.util.ArrayList) MmsSmsDatabase(org.thoughtcrime.securesms.database.MmsSmsDatabase) MessageRecord(org.thoughtcrime.securesms.database.model.MessageRecord) MediaMmsMessageRecord(org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord) InMemoryMessageRecord(org.thoughtcrime.securesms.database.model.InMemoryMessageRecord) SmsMessageRecord(org.thoughtcrime.securesms.database.model.SmsMessageRecord) NonNull(androidx.annotation.NonNull)

Example 32 with Stopwatch

use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.

the class CreateGroupActivity method handleNextPressed.

private void handleNextPressed() {
    Stopwatch stopwatch = new Stopwatch("Recipient Refresh");
    SimpleProgressDialog.DismissibleDialog dismissibleDialog = SimpleProgressDialog.showDelayed(this);
    SimpleTask.run(getLifecycle(), () -> {
        List<RecipientId> ids = contactsFragment.getSelectedContacts().stream().map(selectedContact -> selectedContact.getOrCreateRecipientId(this)).collect(Collectors.toList());
        List<Recipient> resolved = Recipient.resolvedList(ids);
        stopwatch.split("resolve");
        Set<Recipient> registeredChecks = resolved.stream().filter(r -> r.getRegistered() == RecipientDatabase.RegisteredState.UNKNOWN).collect(Collectors.toSet());
        Log.i(TAG, "Need to do " + registeredChecks.size() + " registration checks.");
        for (Recipient recipient : registeredChecks) {
            try {
                DirectoryHelper.refreshDirectoryFor(this, recipient, false);
            } catch (IOException e) {
                Log.w(TAG, "Failed to refresh registered status for " + recipient.getId(), e);
            }
        }
        if (registeredChecks.size() > 0) {
            resolved = Recipient.resolvedList(ids);
        }
        stopwatch.split("registered");
        List<Recipient> recipientsAndSelf = new ArrayList<>(resolved);
        recipientsAndSelf.add(Recipient.self().resolve());
        boolean neededRefresh = false;
        if (!SignalStore.internalValues().gv2DoNotCreateGv2Groups()) {
            try {
                neededRefresh = GroupsV2CapabilityChecker.refreshCapabilitiesIfNecessary(recipientsAndSelf);
            } catch (IOException e) {
                Log.w(TAG, "Failed to refresh all recipient capabilities.", e);
            }
        }
        if (neededRefresh) {
            resolved = Recipient.resolvedList(ids);
        }
        stopwatch.split("capabilities");
        Pair<Boolean, List<RecipientId>> result;
        boolean gv2 = Stream.of(recipientsAndSelf).allMatch(r -> r.getGroupsV2Capability() == Recipient.Capability.SUPPORTED);
        if (!gv2 && Stream.of(resolved).anyMatch(r -> !r.hasE164())) {
            Log.w(TAG, "Invalid GV1 group...");
            ids = Collections.emptyList();
            result = Pair.create(false, ids);
        } else {
            result = Pair.create(true, ids);
        }
        stopwatch.split("gv1-check");
        return result;
    }, result -> {
        dismissibleDialog.dismiss();
        stopwatch.stop(TAG);
        if (result.first) {
            startActivityForResult(AddGroupDetailsActivity.newIntent(this, result.second), REQUEST_CODE_ADD_DETAILS);
        } else {
            new AlertDialog.Builder(this).setMessage(R.string.CreateGroupActivity_some_contacts_cannot_be_in_legacy_groups).setPositiveButton(android.R.string.ok, (d, w) -> d.dismiss()).show();
        }
    });
}
Also used : SignalStore(org.thoughtcrime.securesms.keyvalue.SignalStore) Context(android.content.Context) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) Stream(com.annimon.stream.Stream) ContactsCursorLoader(org.thoughtcrime.securesms.contacts.ContactsCursorLoader) DirectoryHelper(org.thoughtcrime.securesms.contacts.sync.DirectoryHelper) Util(org.thoughtcrime.securesms.util.Util) NonNull(androidx.annotation.NonNull) ContactSelectionListFragment(org.thoughtcrime.securesms.ContactSelectionListFragment) SimpleProgressDialog(org.thoughtcrime.securesms.util.views.SimpleProgressDialog) Pair(android.util.Pair) Intent(android.content.Intent) ViewUtil(org.thoughtcrime.securesms.util.ViewUtil) R(org.thoughtcrime.securesms.R) RecipientDatabase(org.thoughtcrime.securesms.database.RecipientDatabase) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) MaterialButton(com.google.android.material.button.MaterialButton) Recipient(org.thoughtcrime.securesms.recipients.Recipient) GroupsV2CapabilityChecker(org.thoughtcrime.securesms.groups.GroupsV2CapabilityChecker) ExtendedFloatingActionButton(com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton) SimpleTask(org.thoughtcrime.securesms.util.concurrent.SimpleTask) ContactSelectionActivity(org.thoughtcrime.securesms.ContactSelectionActivity) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) AddGroupDetailsActivity(org.thoughtcrime.securesms.groups.ui.creategroup.details.AddGroupDetailsActivity) Optional(org.whispersystems.libsignal.util.guava.Optional) Consumer(java.util.function.Consumer) Log(org.signal.core.util.logging.Log) FeatureFlags(org.thoughtcrime.securesms.util.FeatureFlags) List(java.util.List) Nullable(androidx.annotation.Nullable) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) Collections(java.util.Collections) ValueAnimator(android.animation.ValueAnimator) AlertDialog(androidx.appcompat.app.AlertDialog) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) ArrayList(java.util.ArrayList) Recipient(org.thoughtcrime.securesms.recipients.Recipient) IOException(java.io.IOException) ArrayList(java.util.ArrayList) List(java.util.List) SimpleProgressDialog(org.thoughtcrime.securesms.util.views.SimpleProgressDialog)

Example 33 with Stopwatch

use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by signalapp.

the class CameraXUtil method transformByteArray.

private static byte[] transformByteArray(@NonNull byte[] data, @Nullable Rect cropRect, int rotation, boolean flip) throws IOException {
    Stopwatch stopwatch = new Stopwatch("transform");
    Bitmap in;
    if (cropRect != null) {
        BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(data, 0, data.length, false);
        in = decoder.decodeRegion(cropRect, new BitmapFactory.Options());
        decoder.recycle();
        stopwatch.split("crop");
    } else {
        in = BitmapFactory.decodeByteArray(data, 0, data.length);
    }
    Bitmap out = in;
    if (rotation != 0 || flip) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        if (flip) {
            matrix.postScale(-1, 1);
            matrix.postTranslate(in.getWidth(), 0);
        }
        out = Bitmap.createBitmap(in, 0, 0, in.getWidth(), in.getHeight(), matrix, true);
    }
    byte[] transformedData = toJpegBytes(out);
    stopwatch.split("transcode");
    in.recycle();
    out.recycle();
    stopwatch.stop(TAG);
    return transformedData;
}
Also used : Bitmap(android.graphics.Bitmap) Matrix(android.graphics.Matrix) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) BitmapRegionDecoder(android.graphics.BitmapRegionDecoder)

Example 34 with Stopwatch

use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by signalapp.

the class Camera1Fragment method onCaptureClicked.

private void onCaptureClicked() {
    orderEnforcer.reset();
    Stopwatch fastCaptureTimer = new Stopwatch("Capture");
    camera.capture((jpegData, frontFacing) -> {
        fastCaptureTimer.split("captured");
        Transformation<Bitmap> transformation = frontFacing ? new MultiTransformation<>(new CenterCrop(), new FlipTransformation()) : new CenterCrop();
        GlideApp.with(this).asBitmap().load(jpegData).transform(transformation).override(cameraPreview.getWidth(), cameraPreview.getHeight()).into(new SimpleTarget<Bitmap>() {

            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                fastCaptureTimer.split("transform");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                resource.compress(Bitmap.CompressFormat.JPEG, 80, stream);
                fastCaptureTimer.split("compressed");
                byte[] data = stream.toByteArray();
                fastCaptureTimer.split("bytes");
                fastCaptureTimer.stop(TAG);
                controller.onImageCaptured(data, resource.getWidth(), resource.getHeight());
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                controller.onCameraError();
            }
        });
    });
}
Also used : Bitmap(android.graphics.Bitmap) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) Drawable(android.graphics.drawable.Drawable) CenterCrop(com.bumptech.glide.load.resource.bitmap.CenterCrop) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 35 with Stopwatch

use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by signalapp.

the class SubmitDebugLogRepository method submitLogInternal.

@WorkerThread
@NonNull
private Optional<String> submitLogInternal(long untilTime, @NonNull List<LogLine> prefixLines, @Nullable byte[] trace) {
    String traceUrl = null;
    if (trace != null) {
        try {
            traceUrl = uploadContent("application/octet-stream", RequestBody.create(MediaType.get("application/octet-stream"), trace));
        } catch (IOException e) {
            Log.w(TAG, "Error during trace upload.", e);
            return Optional.absent();
        }
    }
    StringBuilder prefixStringBuilder = new StringBuilder();
    for (LogLine line : prefixLines) {
        switch(line.getPlaceholderType()) {
            case NONE:
                prefixStringBuilder.append(line.getText()).append('\n');
                break;
            case TRACE:
                prefixStringBuilder.append(traceUrl).append('\n');
                break;
        }
    }
    try {
        Stopwatch stopwatch = new Stopwatch("log-upload");
        ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
        Uri gzipUri = BlobProvider.getInstance().forData(new ParcelFileDescriptor.AutoCloseInputStream(fds[0]), 0).withMimeType("application/gzip").createForSingleSessionOnDiskAsync(context, null, null);
        OutputStream gzipOutput = new GZIPOutputStream(new ParcelFileDescriptor.AutoCloseOutputStream(fds[1]));
        gzipOutput.write(prefixStringBuilder.toString().getBytes());
        stopwatch.split("front-matter");
        try (LogDatabase.Reader reader = LogDatabase.getInstance(context).getAllBeforeTime(untilTime)) {
            while (reader.hasNext()) {
                gzipOutput.write(reader.next().getBytes());
                gzipOutput.write("\n".getBytes());
            }
        } catch (IllegalStateException e) {
            Log.e(TAG, "Failed to read row!", e);
            return Optional.absent();
        }
        StreamUtil.close(gzipOutput);
        stopwatch.split("body");
        String logUrl = uploadContent("application/gzip", new RequestBody() {

            @Override
            @NonNull
            public MediaType contentType() {
                return MediaType.get("application/gzip");
            }

            @Override
            public long contentLength() {
                return BlobProvider.getInstance().calculateFileSize(context, gzipUri);
            }

            @Override
            public void writeTo(@NonNull BufferedSink sink) throws IOException {
                Source source = Okio.source(BlobProvider.getInstance().getStream(context, gzipUri));
                sink.writeAll(source);
            }
        });
        stopwatch.split("upload");
        stopwatch.stop(TAG);
        BlobProvider.getInstance().delete(context, gzipUri);
        return Optional.of(logUrl);
    } catch (IOException e) {
        Log.w(TAG, "Error during log upload.", e);
        return Optional.absent();
    }
}
Also used : OutputStream(java.io.OutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Uri(android.net.Uri) Source(okio.Source) GZIPOutputStream(java.util.zip.GZIPOutputStream) LogDatabase(org.thoughtcrime.securesms.database.LogDatabase) NonNull(androidx.annotation.NonNull) ParcelFileDescriptor(android.os.ParcelFileDescriptor) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) WorkerThread(androidx.annotation.WorkerThread) NonNull(androidx.annotation.NonNull)

Aggregations

Stopwatch (org.thoughtcrime.securesms.util.Stopwatch)42 NonNull (androidx.annotation.NonNull)20 IOException (java.io.IOException)16 Nullable (androidx.annotation.Nullable)14 Context (android.content.Context)12 ArrayList (java.util.ArrayList)12 Log (org.signal.core.util.logging.Log)12 WorkerThread (androidx.annotation.WorkerThread)10 List (java.util.List)10 Recipient (org.thoughtcrime.securesms.recipients.Recipient)10 RecipientId (org.thoughtcrime.securesms.recipients.RecipientId)10 Util (org.thoughtcrime.securesms.util.Util)10 Stream (com.annimon.stream.Stream)8 Collections (java.util.Collections)8 LinkedList (java.util.LinkedList)8 Set (java.util.Set)8 ApplicationDependencies (org.thoughtcrime.securesms.dependencies.ApplicationDependencies)8 SignalStore (org.thoughtcrime.securesms.keyvalue.SignalStore)8 Optional (org.whispersystems.libsignal.util.guava.Optional)8 Cursor (android.database.Cursor)6