use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.
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();
}
}
use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.
the class CameraXFragment method onCaptureClicked.
private void onCaptureClicked() {
Stopwatch stopwatch = new Stopwatch("Capture");
CameraXSelfieFlashHelper flashHelper = new CameraXSelfieFlashHelper(requireActivity().getWindow(), camera, selfieFlash);
camera.takePicture(Executors.mainThreadExecutor(), new ImageCapture.OnImageCapturedCallback() {
@Override
public void onCaptureSuccess(@NonNull ImageProxy image) {
flashHelper.endFlash();
SimpleTask.run(CameraXFragment.this.getViewLifecycleOwner().getLifecycle(), () -> {
stopwatch.split("captured");
try {
return CameraXUtil.toJpeg(image, camera.getCameraLensFacing() == CameraSelector.LENS_FACING_FRONT);
} catch (IOException e) {
Log.w(TAG, "Failed to encode captured image.", e);
return null;
} finally {
image.close();
}
}, result -> {
stopwatch.split("transformed");
stopwatch.stop(TAG);
if (result != null) {
controller.onImageCaptured(result.getData(), result.getWidth(), result.getHeight());
} else {
controller.onCameraError();
}
});
}
@Override
public void onError(ImageCaptureException exception) {
Log.w(TAG, "Failed to capture image", exception);
flashHelper.endFlash();
controller.onCameraError();
}
});
flashHelper.startFlash();
}
use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.
the class PinRestoreRepository method submitPin.
void submitPin(@NonNull String pin, @NonNull TokenData tokenData, @NonNull Callback<PinResultData> callback) {
executor.execute(() -> {
try {
Stopwatch stopwatch = new Stopwatch("PinSubmission");
KbsPinData kbsData = KbsRepository.restoreMasterKey(pin, tokenData.getEnclave(), tokenData.getBasicAuth(), tokenData.getTokenResponse());
PinState.onSignalPinRestore(ApplicationDependencies.getApplication(), Objects.requireNonNull(kbsData), pin);
stopwatch.split("MasterKey");
ApplicationDependencies.getJobManager().runSynchronously(new StorageAccountRestoreJob(), StorageAccountRestoreJob.LIFESPAN);
stopwatch.split("AccountRestore");
ApplicationDependencies.getJobManager().runSynchronously(new StorageSyncJob(), TimeUnit.SECONDS.toMillis(10));
stopwatch.split("ContactRestore");
stopwatch.stop(TAG);
callback.onComplete(new PinResultData(PinResult.SUCCESS, tokenData));
} catch (IOException e) {
callback.onComplete(new PinResultData(PinResult.NETWORK_ERROR, tokenData));
} catch (KeyBackupSystemNoDataException e) {
callback.onComplete(new PinResultData(PinResult.LOCKED, tokenData));
} catch (KeyBackupSystemWrongPinException e) {
callback.onComplete(new PinResultData(PinResult.INCORRECT, TokenData.withResponse(tokenData, e.getTokenResponse())));
}
});
}
use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.
the class FullBackupExporter method internalExport.
private static void internalExport(@NonNull Context context, @NonNull AttachmentSecret attachmentSecret, @NonNull SQLiteDatabase input, @NonNull OutputStream fileOutputStream, @NonNull String passphrase, boolean closeOutputStream, @NonNull BackupCancellationSignal cancellationSignal) throws IOException {
BackupFrameOutputStream outputStream = new BackupFrameOutputStream(fileOutputStream, passphrase);
int count = 0;
long estimatedCountOutside = 0L;
try {
outputStream.writeDatabaseVersion(input.getVersion());
count++;
List<String> tables = exportSchema(input, outputStream);
count += tables.size() * TABLE_RECORD_COUNT_MULTIPLIER;
final long estimatedCount = calculateCount(context, input, tables);
estimatedCountOutside = estimatedCount;
Stopwatch stopwatch = new Stopwatch("Backup");
for (String table : tables) {
throwIfCanceled(cancellationSignal);
if (table.equals(MmsDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> isNonExpiringMmsMessage(cursor) && isNotReleaseChannel(cursor), null, count, estimatedCount, cancellationSignal);
} else if (table.equals(SmsDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> isNonExpiringSmsMessage(cursor) && isNotReleaseChannel(cursor), null, count, estimatedCount, cancellationSignal);
} else if (table.equals(ReactionDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> isForNonExpiringMessage(input, new MessageId(CursorUtil.requireLong(cursor, ReactionDatabase.MESSAGE_ID), CursorUtil.requireBoolean(cursor, ReactionDatabase.IS_MMS))), null, count, estimatedCount, cancellationSignal);
} else if (table.equals(MentionDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> isForNonExpiringMmsMessageAndNotReleaseChannel(input, CursorUtil.requireLong(cursor, MentionDatabase.MESSAGE_ID)), null, count, estimatedCount, cancellationSignal);
} else if (table.equals(GroupReceiptDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> isForNonExpiringMmsMessageAndNotReleaseChannel(input, cursor.getLong(cursor.getColumnIndexOrThrow(GroupReceiptDatabase.MMS_ID))), null, count, estimatedCount, cancellationSignal);
} else if (table.equals(AttachmentDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> isForNonExpiringMmsMessageAndNotReleaseChannel(input, cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.MMS_ID))), (cursor, innerCount) -> exportAttachment(attachmentSecret, cursor, outputStream, innerCount, estimatedCount), count, estimatedCount, cancellationSignal);
} else if (table.equals(StickerDatabase.TABLE_NAME)) {
count = exportTable(table, input, outputStream, cursor -> true, (cursor, innerCount) -> exportSticker(attachmentSecret, cursor, outputStream, innerCount, estimatedCount), count, estimatedCount, cancellationSignal);
} else if (!BLACKLISTED_TABLES.contains(table) && !table.startsWith("sqlite_")) {
count = exportTable(table, input, outputStream, null, null, count, estimatedCount, cancellationSignal);
}
stopwatch.split("table::" + table);
}
for (BackupProtos.SharedPreference preference : TextSecurePreferences.getPreferencesToSaveToBackup(context)) {
throwIfCanceled(cancellationSignal);
EventBus.getDefault().post(new BackupEvent(BackupEvent.Type.PROGRESS, ++count, estimatedCount));
outputStream.write(preference);
}
stopwatch.split("prefs");
count = exportKeyValues(outputStream, SignalStore.getKeysToIncludeInBackup(), count, estimatedCount, cancellationSignal);
stopwatch.split("key_values");
for (AvatarHelper.Avatar avatar : AvatarHelper.getAvatars(context)) {
throwIfCanceled(cancellationSignal);
if (avatar != null) {
EventBus.getDefault().post(new BackupEvent(BackupEvent.Type.PROGRESS, ++count, estimatedCount));
outputStream.write(avatar.getFilename(), avatar.getInputStream(), avatar.getLength());
}
}
stopwatch.split("avatars");
stopwatch.stop(TAG);
outputStream.writeEnd();
} finally {
if (closeOutputStream) {
outputStream.close();
}
EventBus.getDefault().post(new BackupEvent(BackupEvent.Type.FINISHED, ++count, estimatedCountOutside));
}
}
use of org.thoughtcrime.securesms.util.Stopwatch in project Signal-Android by WhisperSystems.
the class PaymentSendJob method onRun.
@Override
protected void onRun() throws Exception {
if (!Recipient.self().isRegistered()) {
throw new NotPushRegisteredException();
}
if (!SignalStore.paymentsValues().mobileCoinPaymentsEnabled()) {
Log.w(TAG, "Payments are not enabled");
return;
}
Stopwatch stopwatch = new Stopwatch("Payment submission");
Wallet wallet = ApplicationDependencies.getPayments().getWallet();
PaymentDatabase paymentDatabase = SignalDatabase.payments();
paymentDatabase.createOutgoingPayment(uuid, recipientId, publicAddress, timestamp, note, amount);
Log.i(TAG, "Payment record created " + uuid);
stopwatch.split("Record created");
try {
PaymentSubmissionResult paymentSubmissionResult = wallet.sendPayment(publicAddress, amount.requireMobileCoin(), totalFee.requireMobileCoin());
stopwatch.split("Payment submitted");
if (paymentSubmissionResult.containsDefrags()) {
Log.i(TAG, "Payment contains " + paymentSubmissionResult.defrags().size() + " defrags, main payment" + uuid);
RecipientId self = Recipient.self().getId();
MobileCoinPublicAddress selfAddress = wallet.getMobileCoinPublicAddress();
for (TransactionSubmissionResult defrag : paymentSubmissionResult.defrags()) {
UUID defragUuid = UUID.randomUUID();
PaymentTransactionId.MobileCoin mobileCoinTransaction = (PaymentTransactionId.MobileCoin) defrag.getTransactionId();
paymentDatabase.createDefrag(defragUuid, self, selfAddress, timestamp - 1, mobileCoinTransaction.getFee(), mobileCoinTransaction.getTransaction(), mobileCoinTransaction.getReceipt());
Log.i(TAG, "Defrag entered with id " + defragUuid);
ApplicationDependencies.getJobManager().startChain(new PaymentTransactionCheckJob(defragUuid, QUEUE)).then(new MultiDeviceOutgoingPaymentSyncJob(defragUuid)).enqueue();
}
stopwatch.split("Defrag");
}
TransactionSubmissionResult.ErrorCode errorCode = paymentSubmissionResult.getErrorCode();
switch(errorCode) {
case INSUFFICIENT_FUNDS:
paymentDatabase.markPaymentFailed(uuid, FailureReason.INSUFFICIENT_FUNDS);
throw new PaymentException("Payment failed due to " + errorCode);
case GENERIC_FAILURE:
paymentDatabase.markPaymentFailed(uuid, FailureReason.UNKNOWN);
throw new PaymentException("Payment failed due to " + errorCode);
case NETWORK_FAILURE:
paymentDatabase.markPaymentFailed(uuid, FailureReason.NETWORK);
throw new PaymentException("Payment failed due to " + errorCode);
case NONE:
Log.i(TAG, "Payment submission complete");
TransactionSubmissionResult transactionSubmissionResult = Objects.requireNonNull(paymentSubmissionResult.getNonDefrag());
PaymentTransactionId.MobileCoin mobileCoinTransaction = (PaymentTransactionId.MobileCoin) transactionSubmissionResult.getTransactionId();
paymentDatabase.markPaymentSubmitted(uuid, mobileCoinTransaction.getTransaction(), mobileCoinTransaction.getReceipt(), mobileCoinTransaction.getFee());
Log.i(TAG, "Payment record updated " + uuid);
break;
}
} catch (Exception e) {
Log.w(TAG, "Unknown payment failure", e);
paymentDatabase.markPaymentFailed(uuid, FailureReason.UNKNOWN);
throw e;
}
stopwatch.split("Update database record");
stopwatch.stop(TAG);
}
Aggregations