mirror of
https://github.com/twonlyapp/twonly-app.git
synced 2026-06-02 20:42:12 +00:00
Compare commits
64 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6501590dd7 | |||
| d03c42659c | |||
| 849f748968 | |||
| 9e28bb82a2 | |||
| 9beb8ef9d7 | |||
| a688954d76 | |||
| 358f93979e | |||
| dc0ef25d73 | |||
| 7559434f86 | |||
| 62457f1f48 | |||
| 0602f043d2 | |||
| 0c32b41dd0 | |||
| c10dc19342 | |||
| 872592af21 | |||
| c7826ad6dd | |||
| 25c826bff3 | |||
| 789bcda34f | |||
| 874cf5fecc | |||
| 34607e05d1 | |||
| 3499a08155 | |||
| a50c2ba7d7 | |||
| fae5ca3d25 | |||
| d6432677df | |||
| 00cb615e56 | |||
| 1ad304ec2e | |||
| cd5409d021 | |||
| b7c4832ee2 | |||
| f42a49cadf | |||
| 2d6a2e436f | |||
| c0e45cfe1f | |||
| d9da953f77 | |||
| b788146beb | |||
| 6f8f1efe81 | |||
| 304190387d | |||
| 65d188c4f2 | |||
| d32e319c49 | |||
| 2cb51d668a | |||
| 927589a505 | |||
| fc5c74eaed | |||
| d7e4da0e55 | |||
| bfde01cbc5 | |||
| 7614da00b1 | |||
| dec79f3463 | |||
| 236d94622c | |||
| 5bcb3b3efe | |||
| c77c369212 | |||
| 5fb51b20d7 | |||
| df974cd9f7 | |||
| 0204a41d43 | |||
| 11c0ad908e | |||
| 7283852ba5 | |||
| 805d7a66b3 | |||
| ea41158872 | |||
| 32231d11c2 | |||
| 68c99c271f | |||
| 91eedc76b0 | |||
| d0eee1893e | |||
| fe2dd06213 | |||
| 102d2579ce | |||
| 190be5b694 | |||
| c2ac706239 | |||
| e9b550023f | |||
| 5556532879 | |||
| f3b64646f5 |
223 changed files with 39463 additions and 4266 deletions
4
.github/workflows/dev_github.yml
vendored
4
.github/workflows/dev_github.yml
vendored
|
|
@ -31,5 +31,5 @@ jobs:
|
|||
- name: flutter analyze
|
||||
run: flutter analyze
|
||||
|
||||
- name: flutter test
|
||||
run: flutter test
|
||||
# - name: flutter test
|
||||
# run: flutter test
|
||||
|
|
|
|||
68
.github/workflows/release_github.yml
vendored
68
.github/workflows/release_github.yml
vendored
|
|
@ -1,68 +0,0 @@
|
|||
name: Publish on Github
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- pubspec.yaml
|
||||
|
||||
jobs:
|
||||
build_and_publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Clone repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install requirements
|
||||
run: sudo apt-get install protobuf-compiler
|
||||
|
||||
- name: Cloning sub-repos
|
||||
run: git submodule update --init --recursive
|
||||
|
||||
# - name: Check flutter code
|
||||
# run: |
|
||||
# flutter pub get
|
||||
# flutter analyze
|
||||
# flutter test
|
||||
|
||||
- name: Check flutter code
|
||||
run: flutter pub get
|
||||
|
||||
- name: Create key.properties file
|
||||
run: |
|
||||
echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> ./android/key.properties
|
||||
echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> ./android/key.properties
|
||||
echo "keyAlias=github-releases-signature" >> ./android/key.properties
|
||||
echo "storeFile=./keystore.jks" >> ./android/key.properties
|
||||
|
||||
- name: Create keystore file
|
||||
env:
|
||||
KEYSTORE_FILE: ${{ secrets.KEYSTORE_FILE }}
|
||||
run: echo $KEYSTORE_FILE | base64 --decode > ./android/app/keystore.jks
|
||||
|
||||
- name: Build Android APK
|
||||
run: flutter build apk --release --split-per-abi
|
||||
|
||||
- name: Extract pubspec version
|
||||
run: |
|
||||
echo "PUBSPEC_VERSION=$(grep -oP 'version:\s*\K[^+]+(?=\+)' pubspec.yaml)" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload Release Binaries (stable)
|
||||
uses: ncipollo/release-action@v1.18.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: v${{ env.PUBSPEC_VERSION }}
|
||||
allowUpdates: true
|
||||
artifacts: build/app/outputs/flutter-apk/*.apk
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
|
|
@ -10,8 +10,14 @@
|
|||
.history
|
||||
.svn/
|
||||
.swiftpm/
|
||||
*.sqlite
|
||||
*.sqlite-shm
|
||||
*.sqlite-wal
|
||||
migrate_working_dir/
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/README.md
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
|
|
@ -48,4 +54,5 @@ app.*.map.json
|
|||
android/.kotlin/
|
||||
devtools_options.yaml
|
||||
rust/target
|
||||
rust_dependencies/target
|
||||
rust_dependencies/target
|
||||
fastlane/repo/status/running.json
|
||||
|
|
|
|||
42
CHANGELOG.md
42
CHANGELOG.md
|
|
@ -1,5 +1,47 @@
|
|||
# Changelog
|
||||
|
||||
## 0.2.26
|
||||
|
||||
- New: Import images from the gallery
|
||||
- Improved: Media files are now stored in the dedicated "twonly" album
|
||||
- Improved: UI components adapt to native styling (iOS/Android)
|
||||
- Fix: Migration issue that resulted in a corrupted backup mechanism
|
||||
- Fix: Database issues causing messages to be lost or the database to be corrupted
|
||||
- Fix: Permission view did not disappear after they were granted
|
||||
|
||||
## 0.2.23
|
||||
|
||||
- Improved: Smaller UI changes
|
||||
- Fix: Some messages were not marked as opened.
|
||||
|
||||
## 0.2.20
|
||||
|
||||
- New: Adds an "Ask a Friend" button to new contact suggestions.
|
||||
- New: Adds security profiles.
|
||||
- Improved: Onboarding flow for new users.
|
||||
- Improved: Flame restore experience.
|
||||
- Improved: The blue verification checkmark now displays the total number of verifications.
|
||||
- Fix: Issue with receiving messages when user closed app while decrypting
|
||||
- Fix: Background message fetching reliability.
|
||||
- Fix: Issue with focus changing when taking a picture
|
||||
- Fix: Issues with the camera initialization
|
||||
|
||||
## 0.2.16
|
||||
|
||||
- Fix: Images not shown after opening due to cleanup
|
||||
|
||||
## 0.2.15
|
||||
|
||||
- Fix: Issue with opening directly in chats
|
||||
- Fix: Multiple smaller issues
|
||||
|
||||
## 0.2.13
|
||||
|
||||
- New: Tutorial on how to use zoom.
|
||||
- New: Manage storage view.
|
||||
- Improved: Media thumbnails for faster loading.
|
||||
- Fix: Some messages were not marked as opened.
|
||||
|
||||
## 0.2.12
|
||||
|
||||
- New: Automatically mark identical media as opened across all chats (Settings > Chats).
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# twonly
|
||||
|
||||
<a href="https://twonly.eu" rel="some text"><img src="docs/header.png" alt="twonly, a privacy-friendly way to connect with friends through secure, spontaneous image sharing." /></a>
|
||||
<a href="https://twonly.eu" rel="some text"><img src="metadata/en-US/images/featureGraphic.png" alt="twonly, a privacy-friendly way to connect with friends through secure, spontaneous image sharing." /></a>
|
||||
|
||||
This repository contains the complete source code of the [twonly](https://twonly.eu) app. twonly is a replacement for Snapchat, but its purpose is not to replace instant messaging apps, as there are already [many fantastic alternatives](https://www.messenger-matrix.de/messenger-matrix-en.html) out there. It was started because I liked the basic features of Snapchat, such as opening with the camera, the easy-to-use image editor, and the focus on sending fun pictures to friends. But I was annoyed by Snapchat's forced AI chat, receiving random messages to follow strangers, and not knowing how my sent images/text messages were encrypted, if at all. I am also very critical of the direction in which the US is currently moving and therefore try to avoid US providers wherever possible.
|
||||
|
||||
|
|
|
|||
2
android/.gitignore
vendored
2
android/.gitignore
vendored
|
|
@ -9,5 +9,7 @@ GeneratedPluginRegistrant.java
|
|||
# Remember to never publicly share your keystore.
|
||||
# See https://flutter.dev/to/reference-keystore
|
||||
key.properties
|
||||
key.github.properties
|
||||
key.properties.backup
|
||||
**/*.keystore
|
||||
**/*.jks
|
||||
|
|
|
|||
|
|
@ -10,11 +10,32 @@ import android.content.Context
|
|||
import io.crates.keyring.Keyring
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import android.os.Bundle
|
||||
import android.net.Uri
|
||||
import java.io.InputStream
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
class MainActivity : FlutterFragmentActivity() {
|
||||
private val CHANNEL = "eu.twonly/photo_picker"
|
||||
private var pendingResult: MethodChannel.Result? = null
|
||||
|
||||
private lateinit var pickMultipleMedia: ActivityResultLauncher<PickVisualMediaRequest>
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
installSplashScreen()
|
||||
|
||||
pickMultipleMedia = registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { uris ->
|
||||
if (uris.isNotEmpty()) {
|
||||
val uriStrings = uris.map { it.toString() }
|
||||
pendingResult?.success(uriStrings)
|
||||
} else {
|
||||
pendingResult?.success(emptyList<String>())
|
||||
}
|
||||
pendingResult = null
|
||||
}
|
||||
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
|
|
@ -35,7 +56,36 @@ class MainActivity : FlutterFragmentActivity() {
|
|||
|
||||
Keyring.initializeNdkContext(applicationContext)
|
||||
|
||||
MediaStoreChannel.configure(flutterEngine, applicationContext)
|
||||
VideoCompressionChannel.configure(flutterEngine, applicationContext)
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"pickImages" -> {
|
||||
pendingResult = result
|
||||
pickMultipleMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
|
||||
}
|
||||
"getUriBytes" -> {
|
||||
val uriString = call.argument<String>("uri")
|
||||
if (uriString != null) {
|
||||
try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val inputStream: InputStream? = contentResolver.openInputStream(uri)
|
||||
if (inputStream != null) {
|
||||
val bytes = inputStream.readBytes()
|
||||
inputStream.close()
|
||||
result.success(bytes)
|
||||
} else {
|
||||
result.error("UNAVAILABLE", "Could not open InputStream", null)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
result.error("ERROR", e.message, null)
|
||||
}
|
||||
} else {
|
||||
result.error("INVALID_ARGUMENT", "URI string is null", null)
|
||||
}
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,92 +0,0 @@
|
|||
package eu.twonly
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
object MediaStoreChannel {
|
||||
private const val CHANNEL = "eu.twonly/mediaStore"
|
||||
|
||||
fun configure(flutterEngine: FlutterEngine, context: Context) {
|
||||
val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
|
||||
|
||||
channel.setMethodCallHandler { call, result ->
|
||||
try {
|
||||
if (call.method == "safeFileToDownload") {
|
||||
val arguments = call.arguments<Map<String, String>>() as Map<String, String>
|
||||
val sourceFile = arguments["sourceFile"]
|
||||
if (sourceFile == null) {
|
||||
result.success(false)
|
||||
} else {
|
||||
val inputStream = FileInputStream(File(sourceFile))
|
||||
val outputName = File(sourceFile).name.takeIf { it.isNotEmpty() } ?: "memories.zip"
|
||||
|
||||
val savedUri = saveZipToDownloads(context, outputName, inputStream)
|
||||
if (savedUri != null) {
|
||||
result.success(savedUri.toString())
|
||||
} else {
|
||||
result.error("SAVE_FAILED", "Could not save ZIP", null)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result.notImplemented()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
result.error("EXCEPTION", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveZipToDownloads(
|
||||
context: Context,
|
||||
fileName: String = "archive.zip",
|
||||
sourceStream: InputStream
|
||||
): android.net.Uri? {
|
||||
val resolver = context.contentResolver
|
||||
|
||||
val contentValues = ContentValues().apply {
|
||||
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
|
||||
put(MediaStore.MediaColumns.MIME_TYPE, "application/zip")
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
put(MediaStore.MediaColumns.IS_PENDING, 1)
|
||||
}
|
||||
}
|
||||
|
||||
val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
|
||||
} else {
|
||||
MediaStore.Files.getContentUri("external")
|
||||
}
|
||||
|
||||
val uri = resolver.insert(collection, contentValues) ?: return null
|
||||
|
||||
try {
|
||||
resolver.openOutputStream(uri).use { out: OutputStream? ->
|
||||
requireNotNull(out) { "Unable to open output stream" }
|
||||
sourceStream.use { input ->
|
||||
input.copyTo(out)
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val done = ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) }
|
||||
resolver.update(uri, done, null, null)
|
||||
}
|
||||
|
||||
return uri
|
||||
} catch (e: Exception) {
|
||||
try { resolver.delete(uri, null, null) } catch (_: Exception) {}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
8
android/key.github.properties.example
Normal file
8
android/key.github.properties.example
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
# Example signing credentials configuration for GitHub Releases.
|
||||
# Copy this file to 'key.github.properties' and fill in your actual credentials.
|
||||
# Do not commit the actual 'key.github.properties' file to version control.
|
||||
|
||||
storePassword=YOUR_GITHUB_RELEASE_STORE_PASSWORD
|
||||
keyPassword=YOUR_GITHUB_RELEASE_KEY_PASSWORD
|
||||
keyAlias=github-releases-signature
|
||||
storeFile=/absolute/path/to/your/github-release-keystore.jks
|
||||
BIN
assets/fonts/NotoColorEmoji.ttf
Normal file
BIN
assets/fonts/NotoColorEmoji.ttf
Normal file
Binary file not shown.
|
|
@ -0,0 +1,3 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#57CC99" class="bi bi-patch-check-fill" viewBox="0 0 16 16">
|
||||
<path d="M10.067.87a2.89 2.89 0 0 0-4.134 0l-.622.638-.89-.011a2.89 2.89 0 0 0-2.924 2.924l.01.89-.636.622a2.89 2.89 0 0 0 0 4.134l.637.622-.011.89a2.89 2.89 0 0 0 2.924 2.924l.89-.01.622.636a2.89 2.89 0 0 0 4.134 0l.622-.637.89.011a2.89 2.89 0 0 0 2.924-2.924l-.01-.89.636-.622a2.89 2.89 0 0 0 0-4.134l-.637-.622.011-.89a2.89 2.89 0 0 0-2.924-2.924l-.89.01zM8.107 4.000L9.339 4.000L9.339 12.000L7.832 12.000L7.832 6.246L7.817 6.232L7.339 6.638L6.948 6.899L6.455 7.159L5.861 7.391L5.861 6.014L6.165 5.899L6.499 5.725L6.861 5.493L7.296 5.159L7.643 4.812L7.832 4.565L8.049 4.174L8.107 4.000Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 732 B |
|
|
@ -0,0 +1,3 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#57CC99" class="bi bi-patch-check-fill" viewBox="0 0 16 16">
|
||||
<path d="M10.067.87a2.89 2.89 0 0 0-4.134 0l-.622.638-.89-.011a2.89 2.89 0 0 0-2.924 2.924l.01.89-.636.622a2.89 2.89 0 0 0 0 4.134l.637.622-.011.89a2.89 2.89 0 0 0 2.924 2.924l.89-.01.622.636a2.89 2.89 0 0 0 4.134 0l.622-.637.89.011a2.89 2.89 0 0 0 2.924-2.924l-.01-.89.636-.622a2.89 2.89 0 0 0 0-4.134l-.637-.622.011-.89a2.89 2.89 0 0 0-2.924-2.924l-.89.01zM7.899 4.000L8.391 4.000L8.768 4.043L9.029 4.101L9.362 4.217L9.623 4.348L9.942 4.580L10.145 4.783L10.304 4.986L10.406 5.145L10.551 5.464L10.652 5.899L10.667 6.406L10.594 6.884L10.478 7.246L10.290 7.638L10.043 8.029L9.812 8.333L9.507 8.667L8.406 9.696L7.928 10.174L7.754 10.391L7.638 10.580L10.667 10.594L10.667 12.000L5.333 12.000L5.391 11.609L5.522 11.159L5.710 10.725L6.000 10.246L6.232 9.942L6.638 9.478L7.464 8.652L8.072 8.087L8.594 7.551L8.870 7.203L9.029 6.899L9.087 6.739L9.145 6.449L9.145 6.174L9.101 5.928L8.986 5.667L8.768 5.435L8.652 5.362L8.522 5.304L8.246 5.246L7.971 5.246L7.783 5.275L7.652 5.319L7.406 5.464L7.232 5.652L7.101 5.913L7.029 6.203L7.000 6.493L5.493 6.348L5.565 5.870L5.725 5.362L5.957 4.942L6.275 4.594L6.638 4.348L6.942 4.203L7.377 4.072L7.899 4.000Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +1,3 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#57CC99" class="bi bi-patch-check-fill" viewBox="0 0 16 16">
|
||||
<path d="M10.067.87a2.89 2.89 0 0 0-4.134 0l-.622.638-.89-.011a2.89 2.89 0 0 0-2.924 2.924l.01.89-.636.622a2.89 2.89 0 0 0 0 4.134l.637.622-.011.89a2.89 2.89 0 0 0 2.924 2.924l.89-.01.622.636a2.89 2.89 0 0 0 4.134 0l.622-.637.89.011a2.89 2.89 0 0 0 2.924-2.924l-.01-.89.636-.622a2.89 2.89 0 0 0 0-4.134l-.637-.622.011-.89a2.89 2.89 0 0 0-2.924-2.924l-.89.01zM7.730 4.000L8.142 4.000L8.555 4.057L8.854 4.142L9.224 4.313L9.523 4.527L9.794 4.797L10.064 5.196L10.206 5.580L10.249 5.851L10.235 6.263L10.149 6.591L10.007 6.875L9.836 7.103L9.566 7.359L9.125 7.644L9.409 7.730L9.708 7.872L9.950 8.043L10.164 8.256L10.335 8.498L10.477 8.797L10.548 9.039L10.591 9.338L10.577 9.836L10.448 10.377L10.249 10.776L10.093 11.004L9.893 11.231L9.523 11.544L9.125 11.772L8.911 11.858L8.598 11.943L8.171 12.000L7.587 11.986L7.146 11.900L6.733 11.744L6.320 11.488L5.950 11.132L5.680 10.733L5.509 10.320L5.409 9.865L5.409 9.808L6.847 9.637L6.861 9.765L6.947 10.064L7.004 10.192L7.160 10.420L7.416 10.633L7.630 10.733L7.843 10.776L8.171 10.762L8.327 10.719L8.498 10.633L8.797 10.363L8.968 10.064L9.039 9.822L9.068 9.609L9.053 9.167L8.954 8.826L8.769 8.541L8.512 8.327L8.214 8.214L7.872 8.199L7.331 8.299L7.488 7.132L7.929 7.089L8.256 6.975L8.384 6.890L8.569 6.705L8.683 6.505L8.754 6.221L8.754 5.979L8.698 5.737L8.598 5.552L8.427 5.381L8.242 5.281L8.000 5.224L7.772 5.224L7.445 5.324L7.317 5.409L7.132 5.594L7.032 5.751L6.947 5.964L6.890 6.278L5.523 6.036L5.623 5.623L5.794 5.181L5.950 4.911L6.235 4.584L6.591 4.327L6.961 4.157L7.302 4.057L7.730 4.000Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
|
|
@ -1 +1 @@
|
|||
Subproject commit e0c6a9617a20a8d6bc1ad4c6b9c2e229feb5f37a
|
||||
Subproject commit 72d9bd6320bca1f1d29c6e61c3821fed326c0abe
|
||||
BIN
docs/header.png
BIN
docs/header.png
Binary file not shown.
|
Before Width: | Height: | Size: 800 KiB |
2
fastlane/Appfile
Normal file
2
fastlane/Appfile
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
json_key_file(ENV["GOOGLE_PLAY_JSON_KEY_PATH"] || "../../local_data/accesskeys/upload_track_releases_google_play.json")
|
||||
package_name("eu.twonly") # Your application ID
|
||||
144
fastlane/Fastfile
Normal file
144
fastlane/Fastfile
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
default_platform(:android)
|
||||
|
||||
platform :android do
|
||||
desc "Submit a new App Bundle to the Google Play Internal Track"
|
||||
lane :internal do
|
||||
# This lane assumes that `flutter build appbundle` has already been run from the flutter root.
|
||||
upload_to_play_store(
|
||||
track: 'internal',
|
||||
aab: 'build/app/outputs/bundle/release/app-release.aab',
|
||||
skip_upload_metadata: true,
|
||||
skip_upload_images: true,
|
||||
skip_upload_screenshots: true
|
||||
)
|
||||
end
|
||||
|
||||
desc "Build the application locally and upload it as a new GitHub release"
|
||||
lane :release_github do
|
||||
# Read pubspec.yaml to get the version
|
||||
pubspec_path = File.expand_path("../pubspec.yaml", __dir__)
|
||||
unless File.exist?(pubspec_path)
|
||||
UI.user_error!("Could not find pubspec.yaml at #{pubspec_path}")
|
||||
end
|
||||
|
||||
pubspec_content = File.read(pubspec_path)
|
||||
version_match = pubspec_content.match(/^version:\s*([^+]+)/)
|
||||
unless version_match
|
||||
UI.user_error!("Could not extract version from pubspec.yaml")
|
||||
end
|
||||
|
||||
version = version_match[1].strip
|
||||
tag_name = "v#{version}"
|
||||
UI.message("Extracted version: #{version} (tag: #{tag_name})")
|
||||
|
||||
# Load release notes from CHANGELOG.md
|
||||
changelog_path = File.expand_path("../CHANGELOG.md", __dir__)
|
||||
release_notes = "Automated local release via Fastlane"
|
||||
if File.exist?(changelog_path)
|
||||
changelog_content = File.read(changelog_path)
|
||||
escaped_version = Regexp.escape(version)
|
||||
pattern = /##\s*\[?#{escaped_version}\]?(.*?)(?=##\s*|\z)/m
|
||||
match = changelog_content.match(pattern)
|
||||
if match
|
||||
release_notes = match[1].strip
|
||||
UI.message("Loaded release notes from CHANGELOG.md:\n#{release_notes}")
|
||||
else
|
||||
UI.important("Could not find release notes for version #{version} in CHANGELOG.md. Using default description.")
|
||||
end
|
||||
else
|
||||
UI.important("CHANGELOG.md not found at #{changelog_path}. Using default description.")
|
||||
end
|
||||
|
||||
# Handle key.properties swapping if key.github.properties exists
|
||||
key_properties_path = File.expand_path("../android/key.properties", __dir__)
|
||||
github_properties_path = File.expand_path("../android/key.github.properties", __dir__)
|
||||
backup_properties_path = File.expand_path("../android/key.properties.backup", __dir__)
|
||||
|
||||
swapped_properties = false
|
||||
if File.exist?(github_properties_path)
|
||||
UI.message("Found key.github.properties. Swapping in for the build...")
|
||||
if File.exist?(key_properties_path)
|
||||
FileUtils.cp(key_properties_path, backup_properties_path)
|
||||
end
|
||||
FileUtils.cp(github_properties_path, key_properties_path)
|
||||
swapped_properties = true
|
||||
else
|
||||
UI.message("No key.github.properties found. Building with default key.properties...")
|
||||
end
|
||||
|
||||
begin
|
||||
# Build the Android application
|
||||
UI.message("Building Android APK...")
|
||||
Dir.chdir(File.expand_path("..", __dir__)) do
|
||||
sh("flutter build apk --release --split-per-abi")
|
||||
end
|
||||
ensure
|
||||
# Restore original key.properties if swapped
|
||||
if swapped_properties
|
||||
UI.message("Restoring original key.properties...")
|
||||
if File.exist?(backup_properties_path)
|
||||
FileUtils.cp(backup_properties_path, key_properties_path)
|
||||
FileUtils.rm(backup_properties_path)
|
||||
else
|
||||
FileUtils.rm_f(key_properties_path)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Find built APKs
|
||||
apk_glob = File.expand_path("../build/app/outputs/flutter-apk/*-release.apk", __dir__)
|
||||
apks = Dir.glob(apk_glob)
|
||||
|
||||
if apks.empty?
|
||||
UI.user_error!("No release APKs found matching #{apk_glob}")
|
||||
end
|
||||
|
||||
UI.message("Found APKs to upload: #{apks.join(', ')}")
|
||||
|
||||
# Retrieve GitHub Token (fall back to gh auth token)
|
||||
github_token = ENV["GITHUB_TOKEN"]
|
||||
if github_token.nil? || github_token.empty?
|
||||
UI.message("GITHUB_TOKEN env variable not set. Retrieving token via GitHub CLI (gh auth token)...")
|
||||
begin
|
||||
github_token = sh("gh auth token").strip
|
||||
rescue => e
|
||||
UI.user_error!("Failed to retrieve token from gh CLI. Make sure gh is installed and authenticated, or GITHUB_TOKEN environment variable is set. Error: #{e}")
|
||||
end
|
||||
end
|
||||
|
||||
UI.message("Creating GitHub Release #{tag_name}...")
|
||||
set_github_release(
|
||||
repository_name: "twonlyapp/twonly-app",
|
||||
api_token: github_token,
|
||||
tag_name: tag_name,
|
||||
name: "Release #{tag_name}",
|
||||
description: release_notes,
|
||||
upload_assets: apks
|
||||
)
|
||||
UI.success("Successfully uploaded release #{tag_name} to GitHub!")
|
||||
|
||||
# F-Droid deployment
|
||||
fdroid_repo_dir = "/Users/tobi/Documents/drive/twonly/F-Droid/repo"
|
||||
UI.message("Starting F-Droid deployment...")
|
||||
FileUtils.mkdir_p(fdroid_repo_dir)
|
||||
|
||||
apks.each do |apk_path|
|
||||
basename = File.basename(apk_path)
|
||||
new_name = "eu.twonly_v#{version}-#{basename}"
|
||||
dest_path = File.join(fdroid_repo_dir, new_name)
|
||||
UI.message("Copying APK to F-Droid repo: #{dest_path}")
|
||||
FileUtils.cp(apk_path, dest_path)
|
||||
end
|
||||
|
||||
fdroid_dir = "/Users/tobi/Documents/drive/twonly/F-Droid"
|
||||
update_script = File.join(fdroid_dir, "update.sh")
|
||||
if File.exist?(update_script)
|
||||
UI.message("Executing F-Droid update script...")
|
||||
Dir.chdir(fdroid_dir) do
|
||||
sh("chmod +x ./update.sh && ./update.sh")
|
||||
end
|
||||
else
|
||||
UI.important("F-Droid update script not found at #{update_script}")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
@ -280,6 +280,9 @@ PODS:
|
|||
- Flutter
|
||||
- permission_handler_apple (9.3.0):
|
||||
- Flutter
|
||||
- photo_manager (3.9.0):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- pro_video_editor (0.0.1):
|
||||
- Flutter
|
||||
- PromisesObjC (2.4.0)
|
||||
|
|
@ -355,6 +358,7 @@ DEPENDENCIES:
|
|||
- local_auth_darwin (from `.symlinks/plugins/local_auth_darwin/darwin`)
|
||||
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
|
||||
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
|
||||
- photo_manager (from `.symlinks/plugins/photo_manager/darwin`)
|
||||
- pro_video_editor (from `.symlinks/plugins/pro_video_editor/ios`)
|
||||
- restart_app (from `.symlinks/plugins/restart_app/ios`)
|
||||
- rust_lib_twonly (from `.symlinks/plugins/rust_lib_twonly/ios`)
|
||||
|
|
@ -460,6 +464,8 @@ EXTERNAL SOURCES:
|
|||
:path: ".symlinks/plugins/package_info_plus/ios"
|
||||
permission_handler_apple:
|
||||
:path: ".symlinks/plugins/permission_handler_apple/ios"
|
||||
photo_manager:
|
||||
:path: ".symlinks/plugins/photo_manager/darwin"
|
||||
pro_video_editor:
|
||||
:path: ".symlinks/plugins/pro_video_editor/ios"
|
||||
restart_app:
|
||||
|
|
@ -536,6 +542,7 @@ SPEC CHECKSUMS:
|
|||
nanopb: fad817b59e0457d11a5dfbde799381cd727c1275
|
||||
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
|
||||
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
|
||||
photo_manager: 25fd77df14f4f0ba5ef99e2c61814dde77e2bceb
|
||||
pro_video_editor: 44ef9a6d48dbd757ed428cf35396dd05f35c7830
|
||||
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
|
||||
restart_app: 0714144901e260eae68f7afc2fc4aacc1a323ad2
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import workmanager_apple
|
|||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
|
||||
) -> Bool {
|
||||
UNUserNotificationCenter.current().delegate = self
|
||||
|
||||
|
||||
if let registrar = self.registrar(forPlugin: "VideoCompressionChannel") {
|
||||
VideoCompressionChannel.register(with: registrar.messenger())
|
||||
}
|
||||
|
|
@ -32,20 +32,22 @@ import workmanager_apple
|
|||
WorkmanagerPlugin.registerBGProcessingTask(
|
||||
withIdentifier: "eu.twonly.processing_task"
|
||||
)
|
||||
|
||||
|
||||
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
||||
}
|
||||
|
||||
override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
|
||||
override func application(
|
||||
_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]
|
||||
) -> Bool {
|
||||
|
||||
let sharingIntent = SwiftFlutterSharingIntentPlugin.instance
|
||||
if sharingIntent.hasSameSchemePrefix(url: url) {
|
||||
return sharingIntent.application(app, open: url, options: options)
|
||||
}
|
||||
let sharingIntent = SwiftFlutterSharingIntentPlugin.instance
|
||||
if sharingIntent.hasSameSchemePrefix(url: url) {
|
||||
return sharingIntent.application(app, open: url, options: options)
|
||||
}
|
||||
|
||||
// Proceed url handling for other Flutter libraries like app_links
|
||||
return super.application(app, open: url, options:options)
|
||||
}
|
||||
// Proceed url handling for other Flutter libraries like app_links
|
||||
return super.application(app, open: url, options: options)
|
||||
}
|
||||
|
||||
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
||||
|
|
@ -58,7 +60,8 @@ import workmanager_apple
|
|||
NSLog(
|
||||
"Application delegate method userNotificationCenter:didReceive:withCompletionHandler: is called with user info: %@",
|
||||
response.notification.request.content.userInfo)
|
||||
//...
|
||||
super.userNotificationCenter(
|
||||
center, didReceive: response, withCompletionHandler: completionHandler)
|
||||
}
|
||||
|
||||
override func userNotificationCenter(
|
||||
|
|
@ -86,4 +89,4 @@ import workmanager_apple
|
|||
completionHandler([.alert, .sound])
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
13
lib/app.dart
13
lib/app.dart
|
|
@ -137,12 +137,14 @@ class _AppMainWidgetState extends State<AppMainWidget> {
|
|||
bool _isLoaded = false;
|
||||
bool _isTwonlyLocked = true;
|
||||
bool _wasLogged = true;
|
||||
late int _initialPage;
|
||||
|
||||
(Future<int>?, bool) _proofOfWork = (null, false);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initialPage = widget.initialPage;
|
||||
Log.info('AppWidgetState: initState started');
|
||||
initAsync();
|
||||
}
|
||||
|
|
@ -150,6 +152,12 @@ class _AppMainWidgetState extends State<AppMainWidget> {
|
|||
Future<void> initAsync() async {
|
||||
Log.info('AppWidgetState: initAsync started');
|
||||
if (userService.isUserCreated) {
|
||||
if (_initialPage != 0) {
|
||||
final count = await twonlyDB.contactsDao.getContactsCount();
|
||||
if (count == 0) {
|
||||
_initialPage = 0;
|
||||
}
|
||||
}
|
||||
try {
|
||||
unawaited(FirebaseMessaging.instance.requestPermission());
|
||||
} catch (e) {
|
||||
|
|
@ -200,8 +208,7 @@ class _AppMainWidgetState extends State<AppMainWidget> {
|
|||
_isTwonlyLocked = false;
|
||||
}),
|
||||
);
|
||||
} else if (!userService.currentUser.skipSetupPages &&
|
||||
userService.currentUser.currentSetupPage != null) {
|
||||
} else if (!userService.currentUser.skipSetupPages && userService.currentUser.currentSetupPage != null) {
|
||||
// This will only be shown in case the user have not skipped
|
||||
child = SetupView(
|
||||
onUpdate: () => setState(() {
|
||||
|
|
@ -210,7 +217,7 @@ class _AppMainWidgetState extends State<AppMainWidget> {
|
|||
);
|
||||
} else {
|
||||
child = HomeView(
|
||||
initialPage: widget.initialPage,
|
||||
initialPage: _initialPage,
|
||||
);
|
||||
}
|
||||
} else if (_showOnboarding) {
|
||||
|
|
|
|||
|
|
@ -32,6 +32,6 @@ class AppState {
|
|||
static bool isInBackgroundTask = false;
|
||||
static bool allowErrorTrackingViaSentry = false;
|
||||
static bool gotMessageFromServer = false;
|
||||
static int latestAppVersionId = 115;
|
||||
|
||||
static int latestAppVersionId = 116;
|
||||
static bool hasCameraPermissions = false;
|
||||
}
|
||||
|
|
|
|||
154
lib/main.dart
154
lib/main.dart
|
|
@ -1,10 +1,6 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:mutex/mutex.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
|
@ -15,34 +11,24 @@ import 'package:twonly/core/frb_generated.dart';
|
|||
import 'package:twonly/globals.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/callbacks/callbacks.dart';
|
||||
import 'package:twonly/src/constants/secure_storage.keys.dart';
|
||||
import 'package:twonly/src/database/signal/signal_signed_pre_key_store.dart'
|
||||
show getSignalSignedPreKeyStoreOld;
|
||||
import 'package:twonly/src/database/tables/contacts.table.dart';
|
||||
import 'package:twonly/src/database/twonly.db.dart';
|
||||
import 'package:twonly/src/model/json/signal_identity.model.dart';
|
||||
import 'package:twonly/src/providers/connection.provider.dart';
|
||||
import 'package:twonly/src/providers/image_editor.provider.dart';
|
||||
import 'package:twonly/src/providers/purchases.provider.dart';
|
||||
import 'package:twonly/src/providers/settings.provider.dart';
|
||||
import 'package:twonly/src/services/api/mediafiles/download.api.dart';
|
||||
import 'package:twonly/src/services/api/mediafiles/media_background.api.dart';
|
||||
import 'package:twonly/src/services/api/mediafiles/upload.api.dart';
|
||||
import 'package:twonly/src/services/background/callback_dispatcher.background.dart';
|
||||
import 'package:twonly/src/services/backup.service.dart';
|
||||
import 'package:twonly/src/services/mediafiles/mediafile.service.dart';
|
||||
import 'package:twonly/src/services/memories/memories.service.dart';
|
||||
|
||||
import 'package:twonly/src/services/migrations.service.dart';
|
||||
import 'package:twonly/src/services/notifications/fcm.notifications.dart';
|
||||
import 'package:twonly/src/services/notifications/setup.notifications.dart';
|
||||
import 'package:twonly/src/services/user.service.dart';
|
||||
import 'package:twonly/src/services/user_discovery.service.dart';
|
||||
import 'package:twonly/src/utils/avatars.dart';
|
||||
import 'package:twonly/src/utils/exclusive_access.utils.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
import 'package:twonly/src/utils/secure_storage.dart';
|
||||
import 'package:twonly/src/utils/startup_guard.dart';
|
||||
import 'package:twonly/src/visual/views/onboarding/setup.view.dart';
|
||||
|
||||
final _initMutex = Mutex();
|
||||
|
||||
|
|
@ -168,144 +154,6 @@ void main() async {
|
|||
);
|
||||
}
|
||||
|
||||
Future<void> runMigrations() async {
|
||||
if (userService.currentUser.appVersion < 90) {
|
||||
// BUG: Requested media files for reupload where not reuploaded because the wrong state...
|
||||
await twonlyDB.mediaFilesDao.updateAllRetransmissionUploadingState();
|
||||
await UserService.update((u) => u.appVersion = 90);
|
||||
}
|
||||
|
||||
if (userService.currentUser.appVersion < 91) {
|
||||
// BUG: Requested media files for reupload where not reuploaded because the wrong state...
|
||||
await makeMigrationToVersion91();
|
||||
await UserService.update((u) => u.appVersion = 91);
|
||||
}
|
||||
|
||||
if (userService.currentUser.appVersion < 109) {
|
||||
final contacts = await twonlyDB.contactsDao.getAllContacts();
|
||||
for (final contact in contacts) {
|
||||
if (contact.verified) {
|
||||
await twonlyDB.keyVerificationDao.addKeyVerification(
|
||||
contact.userId,
|
||||
VerificationType.migratedFromOldVersion,
|
||||
);
|
||||
}
|
||||
}
|
||||
await UserService.update((u) {
|
||||
u
|
||||
..appVersion = 109
|
||||
..skipSetupPages = true;
|
||||
if (u.avatarSvg == null) {
|
||||
u.currentSetupPage = SetupPages.profile.name;
|
||||
} else {
|
||||
u.currentSetupPage = SetupPages.shareYourFriends.name;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (userService.currentUser.appVersion < 113) {
|
||||
var migrationSuccess = true;
|
||||
final signalIdentity = await SecureStorage.instance.read(
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
key: SecureStorageKeys.signalIdentity,
|
||||
);
|
||||
|
||||
if (signalIdentity != null) {
|
||||
try {
|
||||
final decoded = jsonDecode(signalIdentity);
|
||||
final identity = SignalIdentity.fromJson(
|
||||
decoded as Map<String, dynamic>,
|
||||
);
|
||||
|
||||
await RustKeyManager.importSignalIdentity(
|
||||
identityKeyPairStructure: identity.identityKeyPairU8List,
|
||||
registrationId: identity.registrationId,
|
||||
signedPreKeyStore: await getSignalSignedPreKeyStoreOld(),
|
||||
);
|
||||
Log.info('Importing signal identiy to the rust key manager');
|
||||
|
||||
// Clean up old keys after successful migration
|
||||
await SecureStorage.instance.delete(
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
key: SecureStorageKeys.signalIdentity,
|
||||
);
|
||||
await SecureStorage.instance.delete(
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
key: SecureStorageKeys.signalSignedPreKey,
|
||||
);
|
||||
} catch (e) {
|
||||
Log.error('Failed to migrate signal identity: $e');
|
||||
migrationSuccess = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (migrationSuccess) {
|
||||
await UserService.update((u) {
|
||||
u
|
||||
..appVersion = 113
|
||||
..canUseLoginTokenForAuth = false
|
||||
// As usernames changes where not considered in the old version force users
|
||||
// to reenter there passwords.
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
..twonlySafeBackup?.encryptionKey = []
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
..twonlySafeBackup?.backupId = [];
|
||||
});
|
||||
}
|
||||
}
|
||||
if (userService.currentUser.appVersion < 114) {
|
||||
final allMedia = await twonlyDB.mediaFilesDao
|
||||
.select(twonlyDB.mediaFiles)
|
||||
.get();
|
||||
for (final media in allMedia) {
|
||||
if (media.createdAtMonth == null) {
|
||||
final monthStr = DateFormat('MMMM yyyy').format(media.createdAt);
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
media.mediaId,
|
||||
MediaFilesCompanion(createdAtMonth: Value(monthStr)),
|
||||
);
|
||||
}
|
||||
}
|
||||
await UserService.update((u) => u.appVersion = 114);
|
||||
}
|
||||
|
||||
if (userService.currentUser.appVersion < 115) {
|
||||
var migrationSuccess = true;
|
||||
try {
|
||||
final rustStore = await RustKeyManager.loadSignedPrekeys();
|
||||
for (final entry in rustStore.entries) {
|
||||
final companion = SignalSignedPreKeyStoresCompanion(
|
||||
signedPreKeyId: Value(entry.key),
|
||||
signedPreKey: Value(entry.value),
|
||||
);
|
||||
await twonlyDB
|
||||
.into(twonlyDB.signalSignedPreKeyStores)
|
||||
.insert(
|
||||
companion,
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
await RustKeyManager.removeSignedPrekey(signedPreKeyId: entry.key);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.error('Failed to migrate signed prekeys to Drift: $e');
|
||||
migrationSuccess = false;
|
||||
}
|
||||
if (migrationSuccess) {
|
||||
await UserService.update((u) => u.appVersion = 115);
|
||||
}
|
||||
}
|
||||
|
||||
if (kDebugMode) {
|
||||
assert(
|
||||
AppState.latestAppVersionId == 115,
|
||||
'Forgot to update the target version in runMigrations() after incrementing AppState.latestAppVersionId.',
|
||||
);
|
||||
assert(
|
||||
AppState.latestAppVersionId == userService.currentUser.appVersion,
|
||||
"Migration incomplete: currentUser.appVersion (${userService.currentUser.appVersion}) does not match AppState.latestAppVersionId (${AppState.latestAppVersionId}). Ensure the user's appVersion is updated in the migration block.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> postStartupTasks() async {
|
||||
Log.info('Post startup started.');
|
||||
unawaited(MemoriesService.prewarmCache());
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
|
|
@ -15,7 +16,8 @@ class LoggingCallbacks {
|
|||
Log.info(log.split('INFO ')[1]);
|
||||
} else if (log.contains('DEBUG ')) {
|
||||
Log.info(log.split('DEBUG ')[1]);
|
||||
} else if (kDebugMode) {
|
||||
} else if (kDebugMode && !Platform.environment.containsKey('FLUTTER_TEST')) {
|
||||
// ignore: avoid_print
|
||||
print(log);
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -35,9 +35,14 @@ class Routes {
|
|||
'/settings/privacy/block_users';
|
||||
static const String settingsPrivacyUserDiscovery =
|
||||
'/settings/privacy/user_discovery';
|
||||
static const String settingsPrivacyProfileSelection =
|
||||
'/settings/privacy/profile_selection';
|
||||
static const String settingsNotification = '/settings/notification';
|
||||
static const String settingsStorage = '/settings/storage_data';
|
||||
static const String settingsStorageManage = '/settings/storage_data/manage';
|
||||
static const String settingsStorageImport = '/settings/storage_data/import';
|
||||
static const String settingsStorageImportGallery =
|
||||
'/settings/storage_data/import_gallery';
|
||||
static const String settingsStorageExport = '/settings/storage_data/export';
|
||||
static const String settingsHelp = '/settings/help';
|
||||
static const String settingsHelpFaq = '/settings/help/faq';
|
||||
|
|
|
|||
|
|
@ -103,6 +103,13 @@ class ContactsDao extends DatabaseAccessor<TwonlyDB> with _$ContactsDaoMixin {
|
|||
return select(contacts).get();
|
||||
}
|
||||
|
||||
Future<int> getContactsCount() async {
|
||||
final count = contacts.userId.count();
|
||||
final query = selectOnly(contacts)..addColumns([count]);
|
||||
final result = await query.map((row) => row.read(count)).getSingle();
|
||||
return result ?? 0;
|
||||
}
|
||||
|
||||
Stream<int?> watchContactsBlocked() {
|
||||
final count = contacts.userId.count();
|
||||
final query = selectOnly(contacts)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import 'package:drift/drift.dart';
|
||||
import 'package:hashlib/random.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/database/daos/contacts.dao.dart';
|
||||
import 'package:twonly/src/database/tables/groups.table.dart';
|
||||
import 'package:twonly/src/database/twonly.db.dart';
|
||||
import 'package:twonly/src/services/flame.service.dart';
|
||||
|
|
@ -292,6 +293,27 @@ class GroupsDao extends DatabaseAccessor<TwonlyDB> with _$GroupsDaoMixin {
|
|||
return query.map((row) => row.readTable(groups)).getSingleOrNull();
|
||||
}
|
||||
|
||||
Future<Group?> createOrGetDirectChat(int contactId) async {
|
||||
var directChat = await getDirectChat(contactId);
|
||||
if (directChat == null) {
|
||||
final contact = await attachedDatabase.contactsDao.getContactById(
|
||||
contactId,
|
||||
);
|
||||
if (contact == null) {
|
||||
Log.error('Contact $contactId not found, cannot create direct chat');
|
||||
return null;
|
||||
}
|
||||
await createNewDirectChat(
|
||||
contactId,
|
||||
GroupsCompanion(
|
||||
groupName: Value(getContactDisplayName(contact)),
|
||||
),
|
||||
);
|
||||
directChat = await getDirectChat(contactId);
|
||||
}
|
||||
return directChat;
|
||||
}
|
||||
|
||||
Stream<int> watchSumTotalMediaCounter() {
|
||||
final query = selectOnly(groups)
|
||||
..addColumns([groups.totalMediaCounter.sum()]);
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ class KeyVerificationDao extends DatabaseAccessor<TwonlyDB>
|
|||
KeyVerificationDao(super.db);
|
||||
|
||||
Future<List<VerificationToken>> getRecentVerificationTokens() {
|
||||
final cutoff = DateTime.now().subtract(const Duration(hours: 24));
|
||||
// Tokens are only valid for one hour, so if the users are currently offline, the verification notification will still work later.
|
||||
final cutoff = DateTime.now().subtract(const Duration(hours: 1));
|
||||
return (select(
|
||||
verificationTokens,
|
||||
)..where((t) => t.createdAt.isBiggerOrEqualValue(cutoff))).get();
|
||||
|
|
@ -223,4 +224,38 @@ class KeyVerificationDao extends DatabaseAccessor<TwonlyDB>
|
|||
Log.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteKeyVerification(int contactId) async {
|
||||
try {
|
||||
await (delete(
|
||||
keyVerifications,
|
||||
)..where((kv) => kv.contactId.equals(contactId))).go();
|
||||
if (userService.currentUser.isUserDiscoveryEnabled) {
|
||||
await FlutterUserDiscovery.updateVerificationStateForUser(
|
||||
contactId: contactId,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteKeyVerificationById(
|
||||
int verificationId,
|
||||
int contactId,
|
||||
) async {
|
||||
try {
|
||||
await (delete(
|
||||
keyVerifications,
|
||||
)..where((kv) => kv.verificationId.equals(verificationId))).go();
|
||||
final remaining = await getContactVerification(contactId);
|
||||
if (remaining.isEmpty && userService.currentUser.isUserDiscoveryEnabled) {
|
||||
await FlutterUserDiscovery.updateVerificationStateForUser(
|
||||
contactId: contactId,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -114,16 +114,15 @@ class MediaFilesDao extends DatabaseAccessor<TwonlyDB>
|
|||
.get();
|
||||
}
|
||||
|
||||
Future<List<MediaFile>> getAllNonHashedStoredMediaFiles() async {
|
||||
Future<List<MediaFile>> getAllMediaFilesPendingMigration() async {
|
||||
return (select(mediaFiles)..where(
|
||||
(t) => t.stored.equals(true) & t.storedFileHash.isNull(),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
||||
Future<List<MediaFile>> getAllUnanalyzedStoredMediaFiles() async {
|
||||
return (select(mediaFiles)..where(
|
||||
(t) => t.stored.equals(true) & t.hasCropAnalyzed.equals(false),
|
||||
(t) =>
|
||||
t.stored.equals(true) &
|
||||
(t.storedFileHash.isNull() |
|
||||
t.hasCropAnalyzed.equals(false) |
|
||||
(t.hasThumbnail.equals(false) &
|
||||
t.type.equals(MediaType.audio.name).not()) |
|
||||
t.sizeInBytes.isNull()),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
|
@ -185,4 +184,23 @@ class MediaFilesDao extends DatabaseAccessor<TwonlyDB>
|
|||
final rows = await query.get();
|
||||
return rows.map((row) => row.readTable(db.messages).messageId).toList();
|
||||
}
|
||||
|
||||
Future<List<MediaFile>> getMediaByHash(Uint8List hash) async {
|
||||
final query = select(db.mediaFiles)
|
||||
..where((t) => t.storedFileHash.equals(hash));
|
||||
return query.get();
|
||||
}
|
||||
|
||||
Future<Map<MediaType, int>> getStorageStats() async {
|
||||
final rows = await select(mediaFiles).get();
|
||||
final stats = <MediaType, int>{};
|
||||
|
||||
for (final row in rows) {
|
||||
final type = row.type;
|
||||
final size = row.sizeInBytes ?? 0;
|
||||
stats[type] = (stats[type] ?? 0) + size;
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,7 +102,7 @@ class MessagesDao extends DatabaseAccessor<TwonlyDB> with _$MessagesDaoMixin {
|
|||
t.openedAt.isNull() |
|
||||
t.mediaStored.equals(true)) &
|
||||
(t.isDeletedFromSender.equals(true) |
|
||||
(t.type.equals(MessageType.text.name).not() |
|
||||
(t.type.equals(MessageType.text.name).not() &
|
||||
t.type.equals(MessageType.media.name).not()) |
|
||||
(t.type.equals(MessageType.text.name) &
|
||||
t.content.isNotNull()) |
|
||||
|
|
@ -153,18 +153,25 @@ class MessagesDao extends DatabaseAccessor<TwonlyDB> with _$MessagesDaoMixin {
|
|||
);
|
||||
final groupIds = entry.value;
|
||||
|
||||
await (delete(messages)..where(
|
||||
(m) =>
|
||||
m.groupId.isIn(groupIds) &
|
||||
(m.mediaStored.equals(true) &
|
||||
m.isDeletedFromSender.equals(true) |
|
||||
m.mediaStored.equals(false)) &
|
||||
// Only remove the message when ALL members have seen it. Otherwise the receipt will also be deleted which could cause issues in case a member opens the image later..
|
||||
(m.openedByAll.isSmallerThanValue(deletionTime) |
|
||||
(m.isDeletedFromSender.equals(true) &
|
||||
m.createdAt.isSmallerThanValue(deletionTime))),
|
||||
))
|
||||
.go();
|
||||
final deletedCount =
|
||||
await (delete(messages)..where(
|
||||
(m) =>
|
||||
m.groupId.isIn(groupIds) &
|
||||
((m.mediaStored.equals(true) &
|
||||
m.isDeletedFromSender.equals(true)) |
|
||||
m.mediaStored.equals(false)) &
|
||||
// Only remove the message when ALL members have seen it. Otherwise the receipt will also be deleted which could cause issues in case a member opens the image later..
|
||||
(m.openedByAll.isSmallerThanValue(deletionTime) |
|
||||
(m.isDeletedFromSender.equals(true) &
|
||||
m.createdAt.isSmallerThanValue(deletionTime))),
|
||||
))
|
||||
.go();
|
||||
|
||||
if (deletedCount > 0) {
|
||||
Log.info(
|
||||
'Deleted $deletedCount messages for groups $groupIds due to retention policy.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -249,41 +256,70 @@ class MessagesDao extends DatabaseAccessor<TwonlyDB> with _$MessagesDaoMixin {
|
|||
}
|
||||
|
||||
Future<void> handleMessagesOpened(
|
||||
int contactId,
|
||||
Value<int> contactId,
|
||||
List<String> messageIds,
|
||||
DateTime timestamp,
|
||||
) async {
|
||||
await batch((batch) async {
|
||||
for (final messageId in messageIds) {
|
||||
batch.insert(
|
||||
messageActions,
|
||||
MessageActionsCompanion(
|
||||
messageId: Value(messageId),
|
||||
contactId: Value(contactId),
|
||||
type: const Value(MessageActionType.openedAt),
|
||||
actionAt: Value(timestamp),
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
}
|
||||
for (final messageId in messageIds) {
|
||||
try {
|
||||
var actionTimestamp = timestamp;
|
||||
final msg = await getMessageById(messageId).getSingleOrNull();
|
||||
if (msg != null && actionTimestamp.isBefore(msg.createdAt)) {
|
||||
Log.warn(
|
||||
'Receiver clock skew detected for message $messageId. '
|
||||
'Action timestamp $actionTimestamp is before message creation ${msg.createdAt}. '
|
||||
'Clamping to creation time.',
|
||||
);
|
||||
actionTimestamp = msg.createdAt;
|
||||
}
|
||||
|
||||
for (final messageId in messageIds) {
|
||||
final isOpenedByAll = await haveAllMembers(
|
||||
messageId,
|
||||
MessageActionType.openedAt,
|
||||
);
|
||||
final now = clock.now();
|
||||
final ts = actionTimestamp;
|
||||
await transaction(() async {
|
||||
await into(messageActions).insertOnConflictUpdate(
|
||||
MessageActionsCompanion(
|
||||
messageId: Value(messageId),
|
||||
contactId: contactId,
|
||||
type: const Value(MessageActionType.openedAt),
|
||||
actionAt: Value(ts),
|
||||
),
|
||||
);
|
||||
|
||||
batch.update(
|
||||
twonlyDB.messages,
|
||||
MessagesCompanion(
|
||||
openedAt: Value(now),
|
||||
openedByAll: Value(isOpenedByAll ? now : null),
|
||||
),
|
||||
where: (tbl) => tbl.messageId.equals(messageId),
|
||||
final isOpenedByAll = await haveAllMembers(
|
||||
messageId,
|
||||
MessageActionType.openedAt,
|
||||
);
|
||||
await (update(
|
||||
messages,
|
||||
)..where((tbl) => tbl.messageId.equals(messageId))).write(
|
||||
MessagesCompanion(
|
||||
openedAt: Value(ts),
|
||||
openedByAll: Value(isOpenedByAll ? ts : null),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// Read-back verification: confirm the write was persisted.
|
||||
final verified = await getMessageById(messageId).getSingleOrNull();
|
||||
if (verified != null && verified.openedAt == null) {
|
||||
Log.warn(
|
||||
'handleMessagesOpened read-back failed for $messageId, retrying',
|
||||
);
|
||||
await (update(
|
||||
messages,
|
||||
)..where((tbl) => tbl.messageId.equals(messageId))).write(
|
||||
MessagesCompanion(
|
||||
openedAt: Value(actionTimestamp),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Log.info(
|
||||
'handleMessagesOpened completed for message $messageId',
|
||||
);
|
||||
} catch (e) {
|
||||
Log.error('handleMessagesOpened failed for $messageId: $e');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> handleMessageAckByServer(
|
||||
|
|
@ -291,57 +327,67 @@ class MessagesDao extends DatabaseAccessor<TwonlyDB> with _$MessagesDaoMixin {
|
|||
String messageId,
|
||||
DateTime timestamp,
|
||||
) async {
|
||||
await into(messageActions).insertOnConflictUpdate(
|
||||
MessageActionsCompanion(
|
||||
messageId: Value(messageId),
|
||||
contactId: Value(contactId),
|
||||
type: const Value(MessageActionType.ackByServerAt),
|
||||
actionAt: Value(timestamp),
|
||||
),
|
||||
);
|
||||
await twonlyDB.messagesDao.updateMessageId(
|
||||
messageId,
|
||||
MessagesCompanion(ackByServer: Value(clock.now())),
|
||||
);
|
||||
await transaction(() async {
|
||||
await into(messageActions).insertOnConflictUpdate(
|
||||
MessageActionsCompanion(
|
||||
messageId: Value(messageId),
|
||||
contactId: Value(contactId),
|
||||
type: const Value(MessageActionType.ackByServerAt),
|
||||
actionAt: Value(timestamp),
|
||||
),
|
||||
);
|
||||
await twonlyDB.messagesDao.updateMessageId(
|
||||
messageId,
|
||||
MessagesCompanion(ackByServer: Value(timestamp)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> haveAllMembers(
|
||||
String messageId,
|
||||
MessageActionType action,
|
||||
) async {
|
||||
final message = await twonlyDB.messagesDao
|
||||
.getMessageById(messageId)
|
||||
.getSingleOrNull();
|
||||
if (message == null) return true;
|
||||
final members = await twonlyDB.groupsDao.getGroupNonLeftMembers(
|
||||
message.groupId,
|
||||
);
|
||||
try {
|
||||
final message = await twonlyDB.messagesDao
|
||||
.getMessageById(messageId)
|
||||
.getSingleOrNull();
|
||||
if (message == null) return true;
|
||||
final members = await twonlyDB.groupsDao.getGroupNonLeftMembers(
|
||||
message.groupId,
|
||||
);
|
||||
|
||||
final actions =
|
||||
await (select(messageActions)..where(
|
||||
(t) => t.type.equals(action.name) & t.messageId.equals(messageId),
|
||||
))
|
||||
.get();
|
||||
final actions =
|
||||
await (select(messageActions)..where(
|
||||
(t) =>
|
||||
t.type.equals(action.name) & t.messageId.equals(messageId),
|
||||
))
|
||||
.get();
|
||||
|
||||
return members.length == actions.length;
|
||||
return members.length == actions.length;
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateMessageId(
|
||||
String messageId,
|
||||
MessagesCompanion updatedValues,
|
||||
) async {
|
||||
await (update(
|
||||
final count = await (update(
|
||||
messages,
|
||||
)..where((c) => c.messageId.equals(messageId))).write(updatedValues);
|
||||
Log.info('Updated $count message(s) with messageId $messageId');
|
||||
}
|
||||
|
||||
Future<void> updateMessagesByMediaId(
|
||||
String mediaId,
|
||||
MessagesCompanion updatedValues,
|
||||
) {
|
||||
return (update(
|
||||
) async {
|
||||
final count = await (update(
|
||||
messages,
|
||||
)..where((c) => c.mediaId.equals(mediaId))).write(updatedValues);
|
||||
Log.info('Updated $count message(s) with mediaId $mediaId');
|
||||
}
|
||||
|
||||
Future<Message?> insertMessage(MessagesCompanion message) async {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,14 @@ class ReactionsDao extends DatabaseAccessor<TwonlyDB> with _$ReactionsDaoMixin {
|
|||
final msg = await twonlyDB.messagesDao
|
||||
.getMessageById(messageId)
|
||||
.getSingleOrNull();
|
||||
if (msg == null || msg.groupId != groupId) return;
|
||||
if (msg == null) {
|
||||
Log.error('updateReaction: Message $messageId not found!');
|
||||
return;
|
||||
}
|
||||
if (msg.groupId != groupId) {
|
||||
Log.error('updateReaction: Message groupId ${msg.groupId} != $groupId');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (remove) {
|
||||
|
|
|
|||
|
|
@ -228,6 +228,12 @@ class UserDiscoveryDao extends DatabaseAccessor<TwonlyDB>
|
|||
);
|
||||
}
|
||||
|
||||
Future<UserDiscoveryAnnouncedUser?> getAnnouncedUserById(int id) async {
|
||||
return (select(
|
||||
userDiscoveryAnnouncedUsers,
|
||||
)..where((tbl) => tbl.announcedUserId.equals(id))).getSingleOrNull();
|
||||
}
|
||||
|
||||
Stream<List<UserDiscoveryAnnouncedUser>> watchAllAnnouncedUsers() =>
|
||||
select(userDiscoveryAnnouncedUsers).watch();
|
||||
|
||||
|
|
|
|||
164
lib/src/database/drift_logging_interceptor.dart
Normal file
164
lib/src/database/drift_logging_interceptor.dart
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
import 'dart:async';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
|
||||
class DriftLoggingInterceptor extends QueryInterceptor {
|
||||
bool get _isEnabled {
|
||||
try {
|
||||
if (!userService.isUserCreated) return false;
|
||||
return userService.currentUser.enableDatabaseLogging;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _findUuids(dynamic value) {
|
||||
if (value == null) return const [];
|
||||
final uuids = <String>[];
|
||||
final uuidRegex = RegExp(
|
||||
'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}',
|
||||
);
|
||||
if (value is String) {
|
||||
for (final match in uuidRegex.allMatches(value)) {
|
||||
uuids.add(match.group(0)!);
|
||||
}
|
||||
} else if (value is Iterable) {
|
||||
for (final element in value) {
|
||||
uuids.addAll(_findUuids(element));
|
||||
}
|
||||
} else if (value is Map) {
|
||||
for (final element in value.values) {
|
||||
uuids.addAll(_findUuids(element));
|
||||
}
|
||||
} else {
|
||||
final str = value.toString();
|
||||
for (final match in uuidRegex.allMatches(str)) {
|
||||
uuids.add(match.group(0)!);
|
||||
}
|
||||
}
|
||||
return uuids.toSet().toList();
|
||||
}
|
||||
|
||||
Future<T> _run<T>(
|
||||
String operation,
|
||||
String statement,
|
||||
List<Object?> args,
|
||||
Future<T> Function() query,
|
||||
) async {
|
||||
if (!_isEnabled) {
|
||||
return query();
|
||||
}
|
||||
final stopwatch = Stopwatch()..start();
|
||||
try {
|
||||
final result = await query();
|
||||
final elapsed = stopwatch.elapsedMilliseconds;
|
||||
final uuids = _findUuids(args);
|
||||
if (uuids.isNotEmpty) {
|
||||
Log.info(
|
||||
'[DriftDB] $operation succeeded in ${elapsed}ms: "$statement" | UUIDs: $uuids',
|
||||
);
|
||||
} else {
|
||||
Log.info(
|
||||
'[DriftDB] $operation succeeded in ${elapsed}ms: "$statement"',
|
||||
);
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
final elapsed = stopwatch.elapsedMilliseconds;
|
||||
final uuids = _findUuids(args);
|
||||
if (uuids.isNotEmpty) {
|
||||
Log.info(
|
||||
'[DriftDB] $operation failed after ${elapsed}ms ($e): "$statement" | UUIDs: $uuids',
|
||||
);
|
||||
} else {
|
||||
Log.info(
|
||||
'[DriftDB] $operation failed after ${elapsed}ms ($e): "$statement"',
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> runInsert(
|
||||
QueryExecutor executor,
|
||||
String statement,
|
||||
List<Object?> args,
|
||||
) {
|
||||
return _run('INSERT', statement, args, () => executor.runInsert(statement, args));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> runUpdate(
|
||||
QueryExecutor executor,
|
||||
String statement,
|
||||
List<Object?> args,
|
||||
) {
|
||||
return _run('UPDATE', statement, args, () => executor.runUpdate(statement, args));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> runDelete(
|
||||
QueryExecutor executor,
|
||||
String statement,
|
||||
List<Object?> args,
|
||||
) {
|
||||
return _run('DELETE', statement, args, () => executor.runDelete(statement, args));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> runCustom(
|
||||
QueryExecutor executor,
|
||||
String statement,
|
||||
List<Object?> args,
|
||||
) {
|
||||
return _run('CUSTOM', statement, args, () => executor.runCustom(statement, args));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> runBatched(
|
||||
QueryExecutor executor,
|
||||
BatchedStatements statements,
|
||||
) async {
|
||||
if (!_isEnabled) {
|
||||
return executor.runBatched(statements);
|
||||
}
|
||||
final stopwatch = Stopwatch()..start();
|
||||
try {
|
||||
await executor.runBatched(statements);
|
||||
final elapsed = stopwatch.elapsedMilliseconds;
|
||||
final uuids = <String>[];
|
||||
for (final batchArg in statements.arguments) {
|
||||
uuids.addAll(_findUuids(batchArg.arguments));
|
||||
}
|
||||
final statementsStr = statements.statements.join('; ');
|
||||
if (uuids.isNotEmpty) {
|
||||
Log.info(
|
||||
'[DriftDB] BATCH succeeded in ${elapsed}ms: "$statementsStr" | UUIDs: $uuids',
|
||||
);
|
||||
} else {
|
||||
Log.info(
|
||||
'[DriftDB] BATCH succeeded in ${elapsed}ms: "$statementsStr"',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
final elapsed = stopwatch.elapsedMilliseconds;
|
||||
final uuids = <String>[];
|
||||
for (final batchArg in statements.arguments) {
|
||||
uuids.addAll(_findUuids(batchArg.arguments));
|
||||
}
|
||||
final statementsStr = statements.statements.join('; ');
|
||||
if (uuids.isNotEmpty) {
|
||||
Log.info(
|
||||
'[DriftDB] BATCH failed after ${elapsed}ms ($e): "$statementsStr" | UUIDs: $uuids',
|
||||
);
|
||||
} else {
|
||||
Log.info(
|
||||
'[DriftDB] BATCH failed after ${elapsed}ms ($e): "$statementsStr"',
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
3019
lib/src/database/schemas/twonly_db/drift_schema_v16.json
Normal file
3019
lib/src/database/schemas/twonly_db/drift_schema_v16.json
Normal file
File diff suppressed because it is too large
Load diff
3033
lib/src/database/schemas/twonly_db/drift_schema_v17.json
Normal file
3033
lib/src/database/schemas/twonly_db/drift_schema_v17.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -3,14 +3,13 @@ import 'dart:convert';
|
|||
import 'package:drift/drift.dart';
|
||||
import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/constants/secure_storage.keys.dart';
|
||||
import 'package:twonly/src/database/twonly.db.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
import 'package:twonly/src/utils/secure_storage.dart';
|
||||
|
||||
Future<HashMap<int, Uint8List>> getSignalSignedPreKeyStoreOld() async {
|
||||
final storeSerialized = await SecureStorage.instance.read(
|
||||
key: SecureStorageKeys.signalSignedPreKey,
|
||||
key: 'signed_pre_key_store',
|
||||
);
|
||||
final store = HashMap<int, Uint8List>();
|
||||
if (storeSerialized == null) {
|
||||
|
|
|
|||
|
|
@ -69,6 +69,11 @@ class MediaFiles extends Table {
|
|||
|
||||
BlobColumn get storedFileHash => blob().nullable()();
|
||||
|
||||
BoolColumn get hasThumbnail =>
|
||||
boolean().withDefault(const Constant(false))();
|
||||
|
||||
IntColumn get sizeInBytes => integer().nullable()();
|
||||
|
||||
DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
|
||||
TextColumn get createdAtMonth => text().nullable()();
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import 'package:twonly/src/database/tables/contacts.table.dart';
|
|||
import 'package:twonly/src/database/tables/groups.table.dart';
|
||||
import 'package:twonly/src/database/tables/mediafiles.table.dart';
|
||||
|
||||
enum MessageType { media, text, contacts, restoreFlameCounter }
|
||||
enum MessageType { media, text, contacts, restoreFlameCounter, askAboutUser }
|
||||
|
||||
@DataClassName('Message')
|
||||
class Messages extends Table {
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ class UserDiscoveryAnnouncedUsers extends Table {
|
|||
BoolColumn get wasShownToTheUser =>
|
||||
boolean().withDefault(const Constant(false))();
|
||||
BoolColumn get isHidden => boolean().withDefault(const Constant(false))();
|
||||
BoolColumn get wasAskedFriends =>
|
||||
boolean().withDefault(const Constant(false))();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {announcedUserId};
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import 'package:clock/clock.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:drift_flutter/drift_flutter.dart'
|
||||
show DriftNativeOptions, driftDatabase;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/database/daos/contacts.dao.dart';
|
||||
import 'package:twonly/src/database/daos/groups.dao.dart';
|
||||
import 'package:twonly/src/database/daos/key_verification.dao.dart';
|
||||
|
|
@ -12,6 +12,7 @@ import 'package:twonly/src/database/daos/reactions.dao.dart';
|
|||
import 'package:twonly/src/database/daos/receipts.dao.dart';
|
||||
import 'package:twonly/src/database/daos/shortcuts.dao.dart';
|
||||
import 'package:twonly/src/database/daos/user_discovery.dao.dart';
|
||||
import 'package:twonly/src/database/drift_logging_interceptor.dart';
|
||||
import 'package:twonly/src/database/tables/contacts.table.dart';
|
||||
import 'package:twonly/src/database/tables/groups.table.dart';
|
||||
import 'package:twonly/src/database/tables/mediafiles.table.dart';
|
||||
|
|
@ -81,21 +82,29 @@ class TwonlyDB extends _$TwonlyDB {
|
|||
TwonlyDB.forTesting(DatabaseConnection super.connection);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 15;
|
||||
int get schemaVersion => 17;
|
||||
|
||||
static QueryExecutor _openConnection() {
|
||||
return driftDatabase(
|
||||
final connection = driftDatabase(
|
||||
name: 'twonly',
|
||||
native: DriftNativeOptions(
|
||||
databaseDirectory: getApplicationSupportDirectory,
|
||||
shareAcrossIsolates: true,
|
||||
setup: (rawDb) {
|
||||
rawDb
|
||||
..execute('PRAGMA journal_mode=WAL;')
|
||||
..execute('PRAGMA journal_mode=DELETE;')
|
||||
..execute('PRAGMA synchronous=FULL;')
|
||||
..execute('PRAGMA busy_timeout=5000;');
|
||||
},
|
||||
),
|
||||
);
|
||||
try {
|
||||
if (userService.isUserCreated &&
|
||||
userService.currentUser.enableDatabaseLogging) {
|
||||
return connection.interceptWith(DriftLoggingInterceptor());
|
||||
}
|
||||
} catch (_) {}
|
||||
return connection;
|
||||
}
|
||||
|
||||
@override
|
||||
|
|
@ -211,6 +220,19 @@ class TwonlyDB extends _$TwonlyDB {
|
|||
from14To15: (m, schema) async {
|
||||
await m.createTable(schema.signalSignedPreKeyStores);
|
||||
},
|
||||
from15To16: (m, schema) async {
|
||||
await m.addColumn(
|
||||
schema.mediaFiles,
|
||||
schema.mediaFiles.hasThumbnail,
|
||||
);
|
||||
await m.addColumn(schema.mediaFiles, schema.mediaFiles.sizeInBytes);
|
||||
},
|
||||
from16To17: (m, schema) async {
|
||||
await m.addColumn(
|
||||
schema.userDiscoveryAnnouncedUsers,
|
||||
schema.userDiscoveryAnnouncedUsers.wasAskedFriends,
|
||||
);
|
||||
},
|
||||
)(m, from, to);
|
||||
},
|
||||
);
|
||||
|
|
@ -232,38 +254,4 @@ class TwonlyDB extends _$TwonlyDB {
|
|||
Log.info('Table: $tableName, Size: $tableSize bytes');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteDataForTwonlySafe() async {
|
||||
await (delete(messages)..where(
|
||||
(t) =>
|
||||
(t.mediaStored.equals(false) &
|
||||
t.isDeletedFromSender.equals(false)),
|
||||
))
|
||||
.go();
|
||||
await update(messages).write(
|
||||
const MessagesCompanion(
|
||||
downloadToken: Value(null),
|
||||
),
|
||||
);
|
||||
await (delete(mediaFiles)..where(
|
||||
(t) => (t.stored.equals(false)),
|
||||
))
|
||||
.go();
|
||||
await delete(receipts).go();
|
||||
await delete(receivedReceipts).go();
|
||||
await update(contacts).write(
|
||||
const ContactsCompanion(
|
||||
avatarSvgCompressed: Value(null),
|
||||
senderProfileCounter: Value(0),
|
||||
),
|
||||
);
|
||||
await (delete(signalPreKeyStores)..where(
|
||||
(t) => (t.createdAt.isSmallerThanValue(
|
||||
clock.now().subtract(
|
||||
const Duration(days: 25),
|
||||
),
|
||||
)),
|
||||
))
|
||||
.go();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2810,6 +2810,32 @@ class $MediaFilesTable extends MediaFiles
|
|||
type: DriftSqlType.blob,
|
||||
requiredDuringInsert: false,
|
||||
);
|
||||
static const VerificationMeta _hasThumbnailMeta = const VerificationMeta(
|
||||
'hasThumbnail',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<bool> hasThumbnail = GeneratedColumn<bool>(
|
||||
'has_thumbnail',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.bool,
|
||||
requiredDuringInsert: false,
|
||||
defaultConstraints: GeneratedColumn.constraintIsAlways(
|
||||
'CHECK ("has_thumbnail" IN (0, 1))',
|
||||
),
|
||||
defaultValue: const Constant(false),
|
||||
);
|
||||
static const VerificationMeta _sizeInBytesMeta = const VerificationMeta(
|
||||
'sizeInBytes',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<int> sizeInBytes = GeneratedColumn<int>(
|
||||
'size_in_bytes',
|
||||
aliasedName,
|
||||
true,
|
||||
type: DriftSqlType.int,
|
||||
requiredDuringInsert: false,
|
||||
);
|
||||
static const VerificationMeta _createdAtMeta = const VerificationMeta(
|
||||
'createdAt',
|
||||
);
|
||||
|
|
@ -2853,6 +2879,8 @@ class $MediaFilesTable extends MediaFiles
|
|||
encryptionMac,
|
||||
encryptionNonce,
|
||||
storedFileHash,
|
||||
hasThumbnail,
|
||||
sizeInBytes,
|
||||
createdAt,
|
||||
createdAtMonth,
|
||||
];
|
||||
|
|
@ -2987,6 +3015,24 @@ class $MediaFilesTable extends MediaFiles
|
|||
),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('has_thumbnail')) {
|
||||
context.handle(
|
||||
_hasThumbnailMeta,
|
||||
hasThumbnail.isAcceptableOrUnknown(
|
||||
data['has_thumbnail']!,
|
||||
_hasThumbnailMeta,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('size_in_bytes')) {
|
||||
context.handle(
|
||||
_sizeInBytesMeta,
|
||||
sizeInBytes.isAcceptableOrUnknown(
|
||||
data['size_in_bytes']!,
|
||||
_sizeInBytesMeta,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('created_at')) {
|
||||
context.handle(
|
||||
_createdAtMeta,
|
||||
|
|
@ -3092,6 +3138,14 @@ class $MediaFilesTable extends MediaFiles
|
|||
DriftSqlType.blob,
|
||||
data['${effectivePrefix}stored_file_hash'],
|
||||
),
|
||||
hasThumbnail: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}has_thumbnail'],
|
||||
)!,
|
||||
sizeInBytes: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.int,
|
||||
data['${effectivePrefix}size_in_bytes'],
|
||||
),
|
||||
createdAt: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.dateTime,
|
||||
data['${effectivePrefix}created_at'],
|
||||
|
|
@ -3147,6 +3201,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
final Uint8List? encryptionMac;
|
||||
final Uint8List? encryptionNonce;
|
||||
final Uint8List? storedFileHash;
|
||||
final bool hasThumbnail;
|
||||
final int? sizeInBytes;
|
||||
final DateTime createdAt;
|
||||
final String? createdAtMonth;
|
||||
const MediaFile({
|
||||
|
|
@ -3168,6 +3224,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
this.encryptionMac,
|
||||
this.encryptionNonce,
|
||||
this.storedFileHash,
|
||||
required this.hasThumbnail,
|
||||
this.sizeInBytes,
|
||||
required this.createdAt,
|
||||
this.createdAtMonth,
|
||||
});
|
||||
|
|
@ -3228,6 +3286,10 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
if (!nullToAbsent || storedFileHash != null) {
|
||||
map['stored_file_hash'] = Variable<Uint8List>(storedFileHash);
|
||||
}
|
||||
map['has_thumbnail'] = Variable<bool>(hasThumbnail);
|
||||
if (!nullToAbsent || sizeInBytes != null) {
|
||||
map['size_in_bytes'] = Variable<int>(sizeInBytes);
|
||||
}
|
||||
map['created_at'] = Variable<DateTime>(createdAt);
|
||||
if (!nullToAbsent || createdAtMonth != null) {
|
||||
map['created_at_month'] = Variable<String>(createdAtMonth);
|
||||
|
|
@ -3278,6 +3340,10 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
storedFileHash: storedFileHash == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
: Value(storedFileHash),
|
||||
hasThumbnail: Value(hasThumbnail),
|
||||
sizeInBytes: sizeInBytes == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
: Value(sizeInBytes),
|
||||
createdAt: Value(createdAt),
|
||||
createdAtMonth: createdAtMonth == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
|
|
@ -3323,6 +3389,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
encryptionMac: serializer.fromJson<Uint8List?>(json['encryptionMac']),
|
||||
encryptionNonce: serializer.fromJson<Uint8List?>(json['encryptionNonce']),
|
||||
storedFileHash: serializer.fromJson<Uint8List?>(json['storedFileHash']),
|
||||
hasThumbnail: serializer.fromJson<bool>(json['hasThumbnail']),
|
||||
sizeInBytes: serializer.fromJson<int?>(json['sizeInBytes']),
|
||||
createdAt: serializer.fromJson<DateTime>(json['createdAt']),
|
||||
createdAtMonth: serializer.fromJson<String?>(json['createdAtMonth']),
|
||||
);
|
||||
|
|
@ -3357,6 +3425,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
'encryptionMac': serializer.toJson<Uint8List?>(encryptionMac),
|
||||
'encryptionNonce': serializer.toJson<Uint8List?>(encryptionNonce),
|
||||
'storedFileHash': serializer.toJson<Uint8List?>(storedFileHash),
|
||||
'hasThumbnail': serializer.toJson<bool>(hasThumbnail),
|
||||
'sizeInBytes': serializer.toJson<int?>(sizeInBytes),
|
||||
'createdAt': serializer.toJson<DateTime>(createdAt),
|
||||
'createdAtMonth': serializer.toJson<String?>(createdAtMonth),
|
||||
};
|
||||
|
|
@ -3381,6 +3451,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
Value<Uint8List?> encryptionMac = const Value.absent(),
|
||||
Value<Uint8List?> encryptionNonce = const Value.absent(),
|
||||
Value<Uint8List?> storedFileHash = const Value.absent(),
|
||||
bool? hasThumbnail,
|
||||
Value<int?> sizeInBytes = const Value.absent(),
|
||||
DateTime? createdAt,
|
||||
Value<String?> createdAtMonth = const Value.absent(),
|
||||
}) => MediaFile(
|
||||
|
|
@ -3421,6 +3493,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
storedFileHash: storedFileHash.present
|
||||
? storedFileHash.value
|
||||
: this.storedFileHash,
|
||||
hasThumbnail: hasThumbnail ?? this.hasThumbnail,
|
||||
sizeInBytes: sizeInBytes.present ? sizeInBytes.value : this.sizeInBytes,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
createdAtMonth: createdAtMonth.present
|
||||
? createdAtMonth.value
|
||||
|
|
@ -3476,6 +3550,12 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
storedFileHash: data.storedFileHash.present
|
||||
? data.storedFileHash.value
|
||||
: this.storedFileHash,
|
||||
hasThumbnail: data.hasThumbnail.present
|
||||
? data.hasThumbnail.value
|
||||
: this.hasThumbnail,
|
||||
sizeInBytes: data.sizeInBytes.present
|
||||
? data.sizeInBytes.value
|
||||
: this.sizeInBytes,
|
||||
createdAt: data.createdAt.present ? data.createdAt.value : this.createdAt,
|
||||
createdAtMonth: data.createdAtMonth.present
|
||||
? data.createdAtMonth.value
|
||||
|
|
@ -3504,6 +3584,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
..write('encryptionMac: $encryptionMac, ')
|
||||
..write('encryptionNonce: $encryptionNonce, ')
|
||||
..write('storedFileHash: $storedFileHash, ')
|
||||
..write('hasThumbnail: $hasThumbnail, ')
|
||||
..write('sizeInBytes: $sizeInBytes, ')
|
||||
..write('createdAt: $createdAt, ')
|
||||
..write('createdAtMonth: $createdAtMonth')
|
||||
..write(')'))
|
||||
|
|
@ -3511,7 +3593,7 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
int get hashCode => Object.hashAll([
|
||||
mediaId,
|
||||
type,
|
||||
uploadState,
|
||||
|
|
@ -3530,9 +3612,11 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
$driftBlobEquality.hash(encryptionMac),
|
||||
$driftBlobEquality.hash(encryptionNonce),
|
||||
$driftBlobEquality.hash(storedFileHash),
|
||||
hasThumbnail,
|
||||
sizeInBytes,
|
||||
createdAt,
|
||||
createdAtMonth,
|
||||
);
|
||||
]);
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
|
|
@ -3561,6 +3645,8 @@ class MediaFile extends DataClass implements Insertable<MediaFile> {
|
|||
other.storedFileHash,
|
||||
this.storedFileHash,
|
||||
) &&
|
||||
other.hasThumbnail == this.hasThumbnail &&
|
||||
other.sizeInBytes == this.sizeInBytes &&
|
||||
other.createdAt == this.createdAt &&
|
||||
other.createdAtMonth == this.createdAtMonth);
|
||||
}
|
||||
|
|
@ -3584,6 +3670,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
final Value<Uint8List?> encryptionMac;
|
||||
final Value<Uint8List?> encryptionNonce;
|
||||
final Value<Uint8List?> storedFileHash;
|
||||
final Value<bool> hasThumbnail;
|
||||
final Value<int?> sizeInBytes;
|
||||
final Value<DateTime> createdAt;
|
||||
final Value<String?> createdAtMonth;
|
||||
final Value<int> rowid;
|
||||
|
|
@ -3606,6 +3694,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
this.encryptionMac = const Value.absent(),
|
||||
this.encryptionNonce = const Value.absent(),
|
||||
this.storedFileHash = const Value.absent(),
|
||||
this.hasThumbnail = const Value.absent(),
|
||||
this.sizeInBytes = const Value.absent(),
|
||||
this.createdAt = const Value.absent(),
|
||||
this.createdAtMonth = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
|
|
@ -3629,6 +3719,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
this.encryptionMac = const Value.absent(),
|
||||
this.encryptionNonce = const Value.absent(),
|
||||
this.storedFileHash = const Value.absent(),
|
||||
this.hasThumbnail = const Value.absent(),
|
||||
this.sizeInBytes = const Value.absent(),
|
||||
this.createdAt = const Value.absent(),
|
||||
this.createdAtMonth = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
|
|
@ -3653,6 +3745,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
Expression<Uint8List>? encryptionMac,
|
||||
Expression<Uint8List>? encryptionNonce,
|
||||
Expression<Uint8List>? storedFileHash,
|
||||
Expression<bool>? hasThumbnail,
|
||||
Expression<int>? sizeInBytes,
|
||||
Expression<DateTime>? createdAt,
|
||||
Expression<String>? createdAtMonth,
|
||||
Expression<int>? rowid,
|
||||
|
|
@ -3680,6 +3774,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
if (encryptionMac != null) 'encryption_mac': encryptionMac,
|
||||
if (encryptionNonce != null) 'encryption_nonce': encryptionNonce,
|
||||
if (storedFileHash != null) 'stored_file_hash': storedFileHash,
|
||||
if (hasThumbnail != null) 'has_thumbnail': hasThumbnail,
|
||||
if (sizeInBytes != null) 'size_in_bytes': sizeInBytes,
|
||||
if (createdAt != null) 'created_at': createdAt,
|
||||
if (createdAtMonth != null) 'created_at_month': createdAtMonth,
|
||||
if (rowid != null) 'rowid': rowid,
|
||||
|
|
@ -3705,6 +3801,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
Value<Uint8List?>? encryptionMac,
|
||||
Value<Uint8List?>? encryptionNonce,
|
||||
Value<Uint8List?>? storedFileHash,
|
||||
Value<bool>? hasThumbnail,
|
||||
Value<int?>? sizeInBytes,
|
||||
Value<DateTime>? createdAt,
|
||||
Value<String?>? createdAtMonth,
|
||||
Value<int>? rowid,
|
||||
|
|
@ -3731,6 +3829,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
encryptionMac: encryptionMac ?? this.encryptionMac,
|
||||
encryptionNonce: encryptionNonce ?? this.encryptionNonce,
|
||||
storedFileHash: storedFileHash ?? this.storedFileHash,
|
||||
hasThumbnail: hasThumbnail ?? this.hasThumbnail,
|
||||
sizeInBytes: sizeInBytes ?? this.sizeInBytes,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
createdAtMonth: createdAtMonth ?? this.createdAtMonth,
|
||||
rowid: rowid ?? this.rowid,
|
||||
|
|
@ -3810,6 +3910,12 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
if (storedFileHash.present) {
|
||||
map['stored_file_hash'] = Variable<Uint8List>(storedFileHash.value);
|
||||
}
|
||||
if (hasThumbnail.present) {
|
||||
map['has_thumbnail'] = Variable<bool>(hasThumbnail.value);
|
||||
}
|
||||
if (sizeInBytes.present) {
|
||||
map['size_in_bytes'] = Variable<int>(sizeInBytes.value);
|
||||
}
|
||||
if (createdAt.present) {
|
||||
map['created_at'] = Variable<DateTime>(createdAt.value);
|
||||
}
|
||||
|
|
@ -3843,6 +3949,8 @@ class MediaFilesCompanion extends UpdateCompanion<MediaFile> {
|
|||
..write('encryptionMac: $encryptionMac, ')
|
||||
..write('encryptionNonce: $encryptionNonce, ')
|
||||
..write('storedFileHash: $storedFileHash, ')
|
||||
..write('hasThumbnail: $hasThumbnail, ')
|
||||
..write('sizeInBytes: $sizeInBytes, ')
|
||||
..write('createdAt: $createdAt, ')
|
||||
..write('createdAtMonth: $createdAtMonth, ')
|
||||
..write('rowid: $rowid')
|
||||
|
|
@ -10210,6 +10318,21 @@ class $UserDiscoveryAnnouncedUsersTable extends UserDiscoveryAnnouncedUsers
|
|||
),
|
||||
defaultValue: const Constant(false),
|
||||
);
|
||||
static const VerificationMeta _wasAskedFriendsMeta = const VerificationMeta(
|
||||
'wasAskedFriends',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<bool> wasAskedFriends = GeneratedColumn<bool>(
|
||||
'was_asked_friends',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.bool,
|
||||
requiredDuringInsert: false,
|
||||
defaultConstraints: GeneratedColumn.constraintIsAlways(
|
||||
'CHECK ("was_asked_friends" IN (0, 1))',
|
||||
),
|
||||
defaultValue: const Constant(false),
|
||||
);
|
||||
@override
|
||||
List<GeneratedColumn> get $columns => [
|
||||
announcedUserId,
|
||||
|
|
@ -10218,6 +10341,7 @@ class $UserDiscoveryAnnouncedUsersTable extends UserDiscoveryAnnouncedUsers
|
|||
username,
|
||||
wasShownToTheUser,
|
||||
isHidden,
|
||||
wasAskedFriends,
|
||||
];
|
||||
@override
|
||||
String get aliasedName => _alias ?? actualTableName;
|
||||
|
|
@ -10280,6 +10404,15 @@ class $UserDiscoveryAnnouncedUsersTable extends UserDiscoveryAnnouncedUsers
|
|||
isHidden.isAcceptableOrUnknown(data['is_hidden']!, _isHiddenMeta),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('was_asked_friends')) {
|
||||
context.handle(
|
||||
_wasAskedFriendsMeta,
|
||||
wasAskedFriends.isAcceptableOrUnknown(
|
||||
data['was_asked_friends']!,
|
||||
_wasAskedFriendsMeta,
|
||||
),
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
|
|
@ -10316,6 +10449,10 @@ class $UserDiscoveryAnnouncedUsersTable extends UserDiscoveryAnnouncedUsers
|
|||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}is_hidden'],
|
||||
)!,
|
||||
wasAskedFriends: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}was_asked_friends'],
|
||||
)!,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -10333,6 +10470,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
final String? username;
|
||||
final bool wasShownToTheUser;
|
||||
final bool isHidden;
|
||||
final bool wasAskedFriends;
|
||||
const UserDiscoveryAnnouncedUser({
|
||||
required this.announcedUserId,
|
||||
required this.announcedPublicKey,
|
||||
|
|
@ -10340,6 +10478,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
this.username,
|
||||
required this.wasShownToTheUser,
|
||||
required this.isHidden,
|
||||
required this.wasAskedFriends,
|
||||
});
|
||||
@override
|
||||
Map<String, Expression> toColumns(bool nullToAbsent) {
|
||||
|
|
@ -10352,6 +10491,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
}
|
||||
map['was_shown_to_the_user'] = Variable<bool>(wasShownToTheUser);
|
||||
map['is_hidden'] = Variable<bool>(isHidden);
|
||||
map['was_asked_friends'] = Variable<bool>(wasAskedFriends);
|
||||
return map;
|
||||
}
|
||||
|
||||
|
|
@ -10365,6 +10505,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
: Value(username),
|
||||
wasShownToTheUser: Value(wasShownToTheUser),
|
||||
isHidden: Value(isHidden),
|
||||
wasAskedFriends: Value(wasAskedFriends),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -10382,6 +10523,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
username: serializer.fromJson<String?>(json['username']),
|
||||
wasShownToTheUser: serializer.fromJson<bool>(json['wasShownToTheUser']),
|
||||
isHidden: serializer.fromJson<bool>(json['isHidden']),
|
||||
wasAskedFriends: serializer.fromJson<bool>(json['wasAskedFriends']),
|
||||
);
|
||||
}
|
||||
@override
|
||||
|
|
@ -10394,6 +10536,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
'username': serializer.toJson<String?>(username),
|
||||
'wasShownToTheUser': serializer.toJson<bool>(wasShownToTheUser),
|
||||
'isHidden': serializer.toJson<bool>(isHidden),
|
||||
'wasAskedFriends': serializer.toJson<bool>(wasAskedFriends),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -10404,6 +10547,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
Value<String?> username = const Value.absent(),
|
||||
bool? wasShownToTheUser,
|
||||
bool? isHidden,
|
||||
bool? wasAskedFriends,
|
||||
}) => UserDiscoveryAnnouncedUser(
|
||||
announcedUserId: announcedUserId ?? this.announcedUserId,
|
||||
announcedPublicKey: announcedPublicKey ?? this.announcedPublicKey,
|
||||
|
|
@ -10411,6 +10555,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
username: username.present ? username.value : this.username,
|
||||
wasShownToTheUser: wasShownToTheUser ?? this.wasShownToTheUser,
|
||||
isHidden: isHidden ?? this.isHidden,
|
||||
wasAskedFriends: wasAskedFriends ?? this.wasAskedFriends,
|
||||
);
|
||||
UserDiscoveryAnnouncedUser copyWithCompanion(
|
||||
UserDiscoveryAnnouncedUsersCompanion data,
|
||||
|
|
@ -10428,6 +10573,9 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
? data.wasShownToTheUser.value
|
||||
: this.wasShownToTheUser,
|
||||
isHidden: data.isHidden.present ? data.isHidden.value : this.isHidden,
|
||||
wasAskedFriends: data.wasAskedFriends.present
|
||||
? data.wasAskedFriends.value
|
||||
: this.wasAskedFriends,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -10439,7 +10587,8 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
..write('publicId: $publicId, ')
|
||||
..write('username: $username, ')
|
||||
..write('wasShownToTheUser: $wasShownToTheUser, ')
|
||||
..write('isHidden: $isHidden')
|
||||
..write('isHidden: $isHidden, ')
|
||||
..write('wasAskedFriends: $wasAskedFriends')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
|
|
@ -10452,6 +10601,7 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
username,
|
||||
wasShownToTheUser,
|
||||
isHidden,
|
||||
wasAskedFriends,
|
||||
);
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
|
|
@ -10465,7 +10615,8 @@ class UserDiscoveryAnnouncedUser extends DataClass
|
|||
other.publicId == this.publicId &&
|
||||
other.username == this.username &&
|
||||
other.wasShownToTheUser == this.wasShownToTheUser &&
|
||||
other.isHidden == this.isHidden);
|
||||
other.isHidden == this.isHidden &&
|
||||
other.wasAskedFriends == this.wasAskedFriends);
|
||||
}
|
||||
|
||||
class UserDiscoveryAnnouncedUsersCompanion
|
||||
|
|
@ -10476,6 +10627,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
final Value<String?> username;
|
||||
final Value<bool> wasShownToTheUser;
|
||||
final Value<bool> isHidden;
|
||||
final Value<bool> wasAskedFriends;
|
||||
const UserDiscoveryAnnouncedUsersCompanion({
|
||||
this.announcedUserId = const Value.absent(),
|
||||
this.announcedPublicKey = const Value.absent(),
|
||||
|
|
@ -10483,6 +10635,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
this.username = const Value.absent(),
|
||||
this.wasShownToTheUser = const Value.absent(),
|
||||
this.isHidden = const Value.absent(),
|
||||
this.wasAskedFriends = const Value.absent(),
|
||||
});
|
||||
UserDiscoveryAnnouncedUsersCompanion.insert({
|
||||
this.announcedUserId = const Value.absent(),
|
||||
|
|
@ -10491,6 +10644,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
this.username = const Value.absent(),
|
||||
this.wasShownToTheUser = const Value.absent(),
|
||||
this.isHidden = const Value.absent(),
|
||||
this.wasAskedFriends = const Value.absent(),
|
||||
}) : announcedPublicKey = Value(announcedPublicKey),
|
||||
publicId = Value(publicId);
|
||||
static Insertable<UserDiscoveryAnnouncedUser> custom({
|
||||
|
|
@ -10500,6 +10654,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
Expression<String>? username,
|
||||
Expression<bool>? wasShownToTheUser,
|
||||
Expression<bool>? isHidden,
|
||||
Expression<bool>? wasAskedFriends,
|
||||
}) {
|
||||
return RawValuesInsertable({
|
||||
if (announcedUserId != null) 'announced_user_id': announcedUserId,
|
||||
|
|
@ -10509,6 +10664,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
if (username != null) 'username': username,
|
||||
if (wasShownToTheUser != null) 'was_shown_to_the_user': wasShownToTheUser,
|
||||
if (isHidden != null) 'is_hidden': isHidden,
|
||||
if (wasAskedFriends != null) 'was_asked_friends': wasAskedFriends,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -10519,6 +10675,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
Value<String?>? username,
|
||||
Value<bool>? wasShownToTheUser,
|
||||
Value<bool>? isHidden,
|
||||
Value<bool>? wasAskedFriends,
|
||||
}) {
|
||||
return UserDiscoveryAnnouncedUsersCompanion(
|
||||
announcedUserId: announcedUserId ?? this.announcedUserId,
|
||||
|
|
@ -10527,6 +10684,7 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
username: username ?? this.username,
|
||||
wasShownToTheUser: wasShownToTheUser ?? this.wasShownToTheUser,
|
||||
isHidden: isHidden ?? this.isHidden,
|
||||
wasAskedFriends: wasAskedFriends ?? this.wasAskedFriends,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -10553,6 +10711,9 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
if (isHidden.present) {
|
||||
map['is_hidden'] = Variable<bool>(isHidden.value);
|
||||
}
|
||||
if (wasAskedFriends.present) {
|
||||
map['was_asked_friends'] = Variable<bool>(wasAskedFriends.value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
|
|
@ -10564,7 +10725,8 @@ class UserDiscoveryAnnouncedUsersCompanion
|
|||
..write('publicId: $publicId, ')
|
||||
..write('username: $username, ')
|
||||
..write('wasShownToTheUser: $wasShownToTheUser, ')
|
||||
..write('isHidden: $isHidden')
|
||||
..write('isHidden: $isHidden, ')
|
||||
..write('wasAskedFriends: $wasAskedFriends')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
|
|
@ -15344,6 +15506,8 @@ typedef $$MediaFilesTableCreateCompanionBuilder =
|
|||
Value<Uint8List?> encryptionMac,
|
||||
Value<Uint8List?> encryptionNonce,
|
||||
Value<Uint8List?> storedFileHash,
|
||||
Value<bool> hasThumbnail,
|
||||
Value<int?> sizeInBytes,
|
||||
Value<DateTime> createdAt,
|
||||
Value<String?> createdAtMonth,
|
||||
Value<int> rowid,
|
||||
|
|
@ -15368,6 +15532,8 @@ typedef $$MediaFilesTableUpdateCompanionBuilder =
|
|||
Value<Uint8List?> encryptionMac,
|
||||
Value<Uint8List?> encryptionNonce,
|
||||
Value<Uint8List?> storedFileHash,
|
||||
Value<bool> hasThumbnail,
|
||||
Value<int?> sizeInBytes,
|
||||
Value<DateTime> createdAt,
|
||||
Value<String?> createdAtMonth,
|
||||
Value<int> rowid,
|
||||
|
|
@ -15499,6 +15665,16 @@ class $$MediaFilesTableFilterComposer
|
|||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<bool> get hasThumbnail => $composableBuilder(
|
||||
column: $table.hasThumbnail,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<int> get sizeInBytes => $composableBuilder(
|
||||
column: $table.sizeInBytes,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<DateTime> get createdAt => $composableBuilder(
|
||||
column: $table.createdAt,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
|
|
@ -15634,6 +15810,16 @@ class $$MediaFilesTableOrderingComposer
|
|||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<bool> get hasThumbnail => $composableBuilder(
|
||||
column: $table.hasThumbnail,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<int> get sizeInBytes => $composableBuilder(
|
||||
column: $table.sizeInBytes,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<DateTime> get createdAt => $composableBuilder(
|
||||
column: $table.createdAt,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
|
|
@ -15741,6 +15927,16 @@ class $$MediaFilesTableAnnotationComposer
|
|||
builder: (column) => column,
|
||||
);
|
||||
|
||||
GeneratedColumn<bool> get hasThumbnail => $composableBuilder(
|
||||
column: $table.hasThumbnail,
|
||||
builder: (column) => column,
|
||||
);
|
||||
|
||||
GeneratedColumn<int> get sizeInBytes => $composableBuilder(
|
||||
column: $table.sizeInBytes,
|
||||
builder: (column) => column,
|
||||
);
|
||||
|
||||
GeneratedColumn<DateTime> get createdAt =>
|
||||
$composableBuilder(column: $table.createdAt, builder: (column) => column);
|
||||
|
||||
|
|
@ -15821,6 +16017,8 @@ class $$MediaFilesTableTableManager
|
|||
Value<Uint8List?> encryptionMac = const Value.absent(),
|
||||
Value<Uint8List?> encryptionNonce = const Value.absent(),
|
||||
Value<Uint8List?> storedFileHash = const Value.absent(),
|
||||
Value<bool> hasThumbnail = const Value.absent(),
|
||||
Value<int?> sizeInBytes = const Value.absent(),
|
||||
Value<DateTime> createdAt = const Value.absent(),
|
||||
Value<String?> createdAtMonth = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
|
|
@ -15843,6 +16041,8 @@ class $$MediaFilesTableTableManager
|
|||
encryptionMac: encryptionMac,
|
||||
encryptionNonce: encryptionNonce,
|
||||
storedFileHash: storedFileHash,
|
||||
hasThumbnail: hasThumbnail,
|
||||
sizeInBytes: sizeInBytes,
|
||||
createdAt: createdAt,
|
||||
createdAtMonth: createdAtMonth,
|
||||
rowid: rowid,
|
||||
|
|
@ -15867,6 +16067,8 @@ class $$MediaFilesTableTableManager
|
|||
Value<Uint8List?> encryptionMac = const Value.absent(),
|
||||
Value<Uint8List?> encryptionNonce = const Value.absent(),
|
||||
Value<Uint8List?> storedFileHash = const Value.absent(),
|
||||
Value<bool> hasThumbnail = const Value.absent(),
|
||||
Value<int?> sizeInBytes = const Value.absent(),
|
||||
Value<DateTime> createdAt = const Value.absent(),
|
||||
Value<String?> createdAtMonth = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
|
|
@ -15889,6 +16091,8 @@ class $$MediaFilesTableTableManager
|
|||
encryptionMac: encryptionMac,
|
||||
encryptionNonce: encryptionNonce,
|
||||
storedFileHash: storedFileHash,
|
||||
hasThumbnail: hasThumbnail,
|
||||
sizeInBytes: sizeInBytes,
|
||||
createdAt: createdAt,
|
||||
createdAtMonth: createdAtMonth,
|
||||
rowid: rowid,
|
||||
|
|
@ -21384,6 +21588,7 @@ typedef $$UserDiscoveryAnnouncedUsersTableCreateCompanionBuilder =
|
|||
Value<String?> username,
|
||||
Value<bool> wasShownToTheUser,
|
||||
Value<bool> isHidden,
|
||||
Value<bool> wasAskedFriends,
|
||||
});
|
||||
typedef $$UserDiscoveryAnnouncedUsersTableUpdateCompanionBuilder =
|
||||
UserDiscoveryAnnouncedUsersCompanion Function({
|
||||
|
|
@ -21393,6 +21598,7 @@ typedef $$UserDiscoveryAnnouncedUsersTableUpdateCompanionBuilder =
|
|||
Value<String?> username,
|
||||
Value<bool> wasShownToTheUser,
|
||||
Value<bool> isHidden,
|
||||
Value<bool> wasAskedFriends,
|
||||
});
|
||||
|
||||
final class $$UserDiscoveryAnnouncedUsersTableReferences
|
||||
|
|
@ -21481,6 +21687,11 @@ class $$UserDiscoveryAnnouncedUsersTableFilterComposer
|
|||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<bool> get wasAskedFriends => $composableBuilder(
|
||||
column: $table.wasAskedFriends,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
Expression<bool> userDiscoveryUserRelationsRefs(
|
||||
Expression<bool> Function($$UserDiscoveryUserRelationsTableFilterComposer f)
|
||||
f,
|
||||
|
|
@ -21547,6 +21758,11 @@ class $$UserDiscoveryAnnouncedUsersTableOrderingComposer
|
|||
column: $table.isHidden,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<bool> get wasAskedFriends => $composableBuilder(
|
||||
column: $table.wasAskedFriends,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$UserDiscoveryAnnouncedUsersTableAnnotationComposer
|
||||
|
|
@ -21582,6 +21798,11 @@ class $$UserDiscoveryAnnouncedUsersTableAnnotationComposer
|
|||
GeneratedColumn<bool> get isHidden =>
|
||||
$composableBuilder(column: $table.isHidden, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<bool> get wasAskedFriends => $composableBuilder(
|
||||
column: $table.wasAskedFriends,
|
||||
builder: (column) => column,
|
||||
);
|
||||
|
||||
Expression<T> userDiscoveryUserRelationsRefs<T extends Object>(
|
||||
Expression<T> Function(
|
||||
$$UserDiscoveryUserRelationsTableAnnotationComposer a,
|
||||
|
|
@ -21660,6 +21881,7 @@ class $$UserDiscoveryAnnouncedUsersTableTableManager
|
|||
Value<String?> username = const Value.absent(),
|
||||
Value<bool> wasShownToTheUser = const Value.absent(),
|
||||
Value<bool> isHidden = const Value.absent(),
|
||||
Value<bool> wasAskedFriends = const Value.absent(),
|
||||
}) => UserDiscoveryAnnouncedUsersCompanion(
|
||||
announcedUserId: announcedUserId,
|
||||
announcedPublicKey: announcedPublicKey,
|
||||
|
|
@ -21667,6 +21889,7 @@ class $$UserDiscoveryAnnouncedUsersTableTableManager
|
|||
username: username,
|
||||
wasShownToTheUser: wasShownToTheUser,
|
||||
isHidden: isHidden,
|
||||
wasAskedFriends: wasAskedFriends,
|
||||
),
|
||||
createCompanionCallback:
|
||||
({
|
||||
|
|
@ -21676,6 +21899,7 @@ class $$UserDiscoveryAnnouncedUsersTableTableManager
|
|||
Value<String?> username = const Value.absent(),
|
||||
Value<bool> wasShownToTheUser = const Value.absent(),
|
||||
Value<bool> isHidden = const Value.absent(),
|
||||
Value<bool> wasAskedFriends = const Value.absent(),
|
||||
}) => UserDiscoveryAnnouncedUsersCompanion.insert(
|
||||
announcedUserId: announcedUserId,
|
||||
announcedPublicKey: announcedPublicKey,
|
||||
|
|
@ -21683,6 +21907,7 @@ class $$UserDiscoveryAnnouncedUsersTableTableManager
|
|||
username: username,
|
||||
wasShownToTheUser: wasShownToTheUser,
|
||||
isHidden: isHidden,
|
||||
wasAskedFriends: wasAskedFriends,
|
||||
),
|
||||
withReferenceMapper: (p0) => p0
|
||||
.map(
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -98,16 +98,10 @@ abstract class AppLocalizations {
|
|||
Locale('en'),
|
||||
];
|
||||
|
||||
/// No description provided for @registerTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Welcome to twonly!'**
|
||||
String get registerTitle;
|
||||
|
||||
/// No description provided for @registerSlogan.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'twonly, a privacy friendly way to connect with friends through secure, spontaneous image sharing'**
|
||||
/// **'Stay in touch with friends privately and securely.'**
|
||||
String get registerSlogan;
|
||||
|
||||
/// No description provided for @onboardingWelcomeTitle.
|
||||
|
|
@ -179,7 +173,7 @@ abstract class AppLocalizations {
|
|||
/// No description provided for @registerUsernameSlogan.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Please select a username so others can find you!'**
|
||||
/// **'Your public username'**
|
||||
String get registerUsernameSlogan;
|
||||
|
||||
/// No description provided for @registerUsernameDecoration.
|
||||
|
|
@ -191,7 +185,7 @@ abstract class AppLocalizations {
|
|||
/// No description provided for @registerUsernameLimits.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Your username must be at least 3 characters long.'**
|
||||
/// **'At least 3 characters.'**
|
||||
String get registerUsernameLimits;
|
||||
|
||||
/// No description provided for @registerProofOfWorkFailed.
|
||||
|
|
@ -542,6 +536,36 @@ abstract class AppLocalizations {
|
|||
/// **'When using WI-FI'**
|
||||
String get settingsStorageDataAutoDownWifi;
|
||||
|
||||
/// No description provided for @settingsStorageManageTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Manage storage'**
|
||||
String get settingsStorageManageTitle;
|
||||
|
||||
/// No description provided for @settingsStorageUsed.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Storage used'**
|
||||
String get settingsStorageUsed;
|
||||
|
||||
/// No description provided for @settingsStorageImages.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Images'**
|
||||
String get settingsStorageImages;
|
||||
|
||||
/// No description provided for @settingsStorageVideos.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Videos'**
|
||||
String get settingsStorageVideos;
|
||||
|
||||
/// No description provided for @settingsStorageGifs.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'GIFs'**
|
||||
String get settingsStorageGifs;
|
||||
|
||||
/// No description provided for @settingsProfileCustomizeAvatar.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -602,6 +626,54 @@ abstract class AppLocalizations {
|
|||
/// **'{len} contact(s)'**
|
||||
String settingsPrivacyBlockUsersCount(Object len);
|
||||
|
||||
/// No description provided for @settingsPrivacyProfileSelectionTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Security Profile'**
|
||||
String get settingsPrivacyProfileSelectionTitle;
|
||||
|
||||
/// No description provided for @settingsPrivacyProfileSelectionDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Choose your setup path and security configuration'**
|
||||
String get settingsPrivacyProfileSelectionDesc;
|
||||
|
||||
/// No description provided for @securityProfileTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Security Profile'**
|
||||
String get securityProfileTitle;
|
||||
|
||||
/// No description provided for @securityProfileSubtitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Choose the level of protection that fits your daily use. This can be changed at any time in your settings.'**
|
||||
String get securityProfileSubtitle;
|
||||
|
||||
/// No description provided for @securityProfileNormalTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Normal Protection'**
|
||||
String get securityProfileNormalTitle;
|
||||
|
||||
/// No description provided for @securityProfileNormalDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Good balance between a convenient mode without bothering you too much.'**
|
||||
String get securityProfileNormalDesc;
|
||||
|
||||
/// No description provided for @securityProfileStrictTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Strict Protection'**
|
||||
String get securityProfileStrictTitle;
|
||||
|
||||
/// No description provided for @securityProfileStrictDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Maximum anti-phishing protection but may be inconvenient.'**
|
||||
String get securityProfileStrictDesc;
|
||||
|
||||
/// No description provided for @settingsNotification.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -887,8 +959,8 @@ abstract class AppLocalizations {
|
|||
/// No description provided for @verificationTypeSecretQrToken.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'The other person scanned your QR code.'**
|
||||
String get verificationTypeSecretQrToken;
|
||||
/// **'{username} has scanned your QR code.'**
|
||||
String verificationTypeSecretQrToken(Object username);
|
||||
|
||||
/// No description provided for @verificationTypeLink.
|
||||
///
|
||||
|
|
@ -1388,6 +1460,12 @@ abstract class AppLocalizations {
|
|||
/// **'Delete for all'**
|
||||
String get deleteOkBtnForAll;
|
||||
|
||||
/// No description provided for @memoriesDeleteSnackbarSuccess.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{count, plural, =1 {Deleted 1 item successfully} other {Deleted {count} items successfully}}'**
|
||||
String memoriesDeleteSnackbarSuccess(num count);
|
||||
|
||||
/// No description provided for @deleteOkBtnForMe.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -1406,6 +1484,12 @@ abstract class AppLocalizations {
|
|||
/// **'The image will be irrevocably deleted.'**
|
||||
String get deleteImageBody;
|
||||
|
||||
/// No description provided for @deleteMemoriesBody.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{count, plural, =1 {The image will be irrevocably deleted.} other {The {count} images will be irrevocably deleted.}}'**
|
||||
String deleteMemoriesBody(num count);
|
||||
|
||||
/// No description provided for @settingsBackup.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -1553,15 +1637,9 @@ abstract class AppLocalizations {
|
|||
/// No description provided for @twonlySafeRecoverTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Recovery'**
|
||||
/// **'Restore backup'**
|
||||
String get twonlySafeRecoverTitle;
|
||||
|
||||
/// No description provided for @twonlySafeRecoverDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'If you have created a backup with twonly Backup, you can restore it here.'**
|
||||
String get twonlySafeRecoverDesc;
|
||||
|
||||
/// No description provided for @twonlySafeRecoverBtn.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -2324,6 +2402,12 @@ abstract class AppLocalizations {
|
|||
/// **'Open your own QR code'**
|
||||
String get openYourOwnQRcode;
|
||||
|
||||
/// No description provided for @addContactQrSheetSubtext.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Let a friend scan this QR code to add you'**
|
||||
String get addContactQrSheetSubtext;
|
||||
|
||||
/// No description provided for @finishSetupCardTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -2417,13 +2501,13 @@ abstract class AppLocalizations {
|
|||
/// No description provided for @userDiscoverySettingsManualApproval.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Manual approval'**
|
||||
/// **'Ask every time before sharing'**
|
||||
String get userDiscoverySettingsManualApproval;
|
||||
|
||||
/// No description provided for @userDiscoverySettingsManualApprovalDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Before someone is shared, you\'ll be asked first.'**
|
||||
/// **'Before one of your friends is shared, you will be asked every time.'**
|
||||
String get userDiscoverySettingsManualApprovalDesc;
|
||||
|
||||
/// No description provided for @onboardingUserDiscoveryLetFriendsFindYou.
|
||||
|
|
@ -2681,7 +2765,7 @@ abstract class AppLocalizations {
|
|||
/// No description provided for @verificationBadgeGeneralDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'The checkmark gives you the certainty that you are messaging the right person. Scan the contact\'s QR code to verify it.'**
|
||||
/// **'The checkmark gives you the certainty that you are messaging the right person. You can verify contacts at any time by scanning their QR code.'**
|
||||
String get verificationBadgeGeneralDesc;
|
||||
|
||||
/// No description provided for @verificationBadgeGreenDesc.
|
||||
|
|
@ -2702,6 +2786,36 @@ abstract class AppLocalizations {
|
|||
/// **'A contact whose identity has *not* yet been verified.'**
|
||||
String get verificationBadgeRedDesc;
|
||||
|
||||
/// No description provided for @deleteVerificationTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Delete verification?'**
|
||||
String get deleteVerificationTitle;
|
||||
|
||||
/// No description provided for @deleteVerificationBody.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Are you sure you want to delete this verification?'**
|
||||
String get deleteVerificationBody;
|
||||
|
||||
/// No description provided for @secretQrTokenVerifiedSnackbar.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{username} has scanned your QR code and is now verified.'**
|
||||
String secretQrTokenVerifiedSnackbar(Object username);
|
||||
|
||||
/// No description provided for @mutualGroupsTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{count, plural, =1{1 mutual group} other{{count} mutual groups}}'**
|
||||
String mutualGroupsTitle(num count);
|
||||
|
||||
/// No description provided for @mutualGroupsSentMessages.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{count, plural, =1{1 message sent} other{{count} messages sent}}'**
|
||||
String mutualGroupsSentMessages(num count);
|
||||
|
||||
/// No description provided for @chatEntryFlameRestored.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -2834,6 +2948,18 @@ abstract class AppLocalizations {
|
|||
/// **'Mutual Friends'**
|
||||
String get userDiscoverySettingsTitle;
|
||||
|
||||
/// No description provided for @userDiscoveryWhyThisIsUsed.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Why this is used'**
|
||||
String get userDiscoveryWhyThisIsUsed;
|
||||
|
||||
/// No description provided for @userDiscoveryFeatureOffers.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Your benefits at a glance'**
|
||||
String get userDiscoveryFeatureOffers;
|
||||
|
||||
/// No description provided for @userDiscoveryDisabledLearnMore.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -2906,6 +3032,66 @@ abstract class AppLocalizations {
|
|||
/// **'Request'**
|
||||
String get friendSuggestionsRequest;
|
||||
|
||||
/// No description provided for @friendSuggestionsAskFriend.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Ask your friends'**
|
||||
String get friendSuggestionsAskFriend;
|
||||
|
||||
/// No description provided for @askFriendsDialogTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Ask about {username}'**
|
||||
String askFriendsDialogTitle(Object username);
|
||||
|
||||
/// No description provided for @askFriendsDialogDescription.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Select the friends you want to ask about this user:'**
|
||||
String get askFriendsDialogDescription;
|
||||
|
||||
/// No description provided for @askFriendsDialogConfirm.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Ask'**
|
||||
String get askFriendsDialogConfirm;
|
||||
|
||||
/// No description provided for @askFriendsDialogCancel.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Cancel'**
|
||||
String get askFriendsDialogCancel;
|
||||
|
||||
/// No description provided for @chatAskAFriendReceivedDescription.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Your friend just got this as a suggestion and wants to know if he knows this person.'**
|
||||
String get chatAskAFriendReceivedDescription;
|
||||
|
||||
/// No description provided for @chatAskAFriendAddedDescription.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'You have added this user to your contacts.'**
|
||||
String get chatAskAFriendAddedDescription;
|
||||
|
||||
/// No description provided for @chatAskAFriendHide.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Hide'**
|
||||
String get chatAskAFriendHide;
|
||||
|
||||
/// No description provided for @chatAskAFriendRequest.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Request'**
|
||||
String get chatAskAFriendRequest;
|
||||
|
||||
/// No description provided for @chatAskAFriendUnknownUser.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'User {userId}'**
|
||||
String chatAskAFriendUnknownUser(Object userId);
|
||||
|
||||
/// No description provided for @contactUserDiscoveryImagesLeft.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -3188,12 +3374,6 @@ abstract class AppLocalizations {
|
|||
/// **'Emoji already used or invalid'**
|
||||
String get errorEmojiUsedOrInvalid;
|
||||
|
||||
/// No description provided for @subscriptionPledgeTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Support independent privacy.'**
|
||||
String get subscriptionPledgeTitle;
|
||||
|
||||
/// No description provided for @subscriptionPledgeSecureTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
|
@ -3218,17 +3398,297 @@ abstract class AppLocalizations {
|
|||
/// **'twonly will never show advertisements or sell your private data.'**
|
||||
String get subscriptionPledgeNoAdsDesc;
|
||||
|
||||
/// No description provided for @subscriptionPledgeFundedTitle.
|
||||
/// No description provided for @subscriptionPledgeSubtitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Independent and funded by Users'**
|
||||
String get subscriptionPledgeFundedTitle;
|
||||
/// **'Zero ads. Total privacy.'**
|
||||
String get subscriptionPledgeSubtitle;
|
||||
|
||||
/// No description provided for @subscriptionPledgeFundedDesc.
|
||||
/// No description provided for @dragToZoom.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'twonly is funded purely by user subscriptions to secure our independence and support the future of twonly.'**
|
||||
String get subscriptionPledgeFundedDesc;
|
||||
/// **'Drag to Zoom'**
|
||||
String get dragToZoom;
|
||||
|
||||
/// No description provided for @showUsername.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Show username'**
|
||||
String get showUsername;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Choose your setup path'**
|
||||
String get onboardingProfileSelectionTitle;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionSubtitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Choose how you want to configure your security and privacy settings.'**
|
||||
String get onboardingProfileSelectionSubtitle;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionDefaultTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Default'**
|
||||
String get onboardingProfileSelectionDefaultTitle;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionDefaultDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Instantly applies recommended settings so you can start using the app.'**
|
||||
String get onboardingProfileSelectionDefaultDesc;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionDefaultBadge.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Fast Setup'**
|
||||
String get onboardingProfileSelectionDefaultBadge;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionCustomizeTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Customize'**
|
||||
String get onboardingProfileSelectionCustomizeTitle;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionCustomizeDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Step-by-step setup so you can decide for yourself.'**
|
||||
String get onboardingProfileSelectionCustomizeDesc;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionStrictTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Enhanced Protection'**
|
||||
String get onboardingProfileSelectionStrictTitle;
|
||||
|
||||
/// No description provided for @onboardingProfileSelectionStrictDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Maximum anti-phishing defense. Recommended for *journalists & public figures*.'**
|
||||
String get onboardingProfileSelectionStrictDesc;
|
||||
|
||||
/// No description provided for @replyFlameRestored.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Flames restored'**
|
||||
String get replyFlameRestored;
|
||||
|
||||
/// No description provided for @replyAskAFriend.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Ask a friend'**
|
||||
String get replyAskAFriend;
|
||||
|
||||
/// No description provided for @unverifiedWarningDirectTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Identity not verified in person'**
|
||||
String get unverifiedWarningDirectTitle;
|
||||
|
||||
/// No description provided for @unverifiedWarningGroupTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Not all members are verified in person'**
|
||||
String get unverifiedWarningGroupTitle;
|
||||
|
||||
/// No description provided for @unverifiedWarningBody.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'*Avoid sharing sensitive data*. Risk of *impersonation* without manual verification.'**
|
||||
String get unverifiedWarningBody;
|
||||
|
||||
/// No description provided for @unverifiedWarningButton.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Verify now'**
|
||||
String get unverifiedWarningButton;
|
||||
|
||||
/// No description provided for @today.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Today'**
|
||||
String get today;
|
||||
|
||||
/// No description provided for @yesterday.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Yesterday'**
|
||||
String get yesterday;
|
||||
|
||||
/// No description provided for @galleryDisableWarningTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Disable gallery saving?'**
|
||||
String get galleryDisableWarningTitle;
|
||||
|
||||
/// No description provided for @galleryDisableWarningBody.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'If you disable this, your media files will not be saved to your gallery and could be permanently lost if twonly is removed or has an issue, as media files are not yet backed up.'**
|
||||
String get galleryDisableWarningBody;
|
||||
|
||||
/// No description provided for @galleryDisableWarningConfirm.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Disable'**
|
||||
String get galleryDisableWarningConfirm;
|
||||
|
||||
/// No description provided for @settingsStorageScanGalleryTitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Import from Gallery'**
|
||||
String get settingsStorageScanGalleryTitle;
|
||||
|
||||
/// No description provided for @importGalleryDeselectAll.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Deselect all'**
|
||||
String get importGalleryDeselectAll;
|
||||
|
||||
/// No description provided for @importGallerySelectAll.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Select all'**
|
||||
String get importGallerySelectAll;
|
||||
|
||||
/// No description provided for @importGalleryPermissionRequired.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Permission to access your gallery is required to import previous twonly media files.'**
|
||||
String get importGalleryPermissionRequired;
|
||||
|
||||
/// No description provided for @importGalleryPermissionError.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'An error occurred while requesting permission: {error}'**
|
||||
String importGalleryPermissionError(Object error);
|
||||
|
||||
/// No description provided for @importGalleryLoadError.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Failed to load assets: {error}'**
|
||||
String importGalleryLoadError(Object error);
|
||||
|
||||
/// No description provided for @importGalleryImportingOf.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Importing {current} of {total}...'**
|
||||
String importGalleryImportingOf(Object current, Object total);
|
||||
|
||||
/// No description provided for @importGalleryStarting.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Starting import...'**
|
||||
String get importGalleryStarting;
|
||||
|
||||
/// No description provided for @importGalleryComplete.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Import complete: {imported} successfully imported, {duplicated} duplicated and {failed} failed.'**
|
||||
String importGalleryComplete(
|
||||
Object imported,
|
||||
Object duplicated,
|
||||
Object failed,
|
||||
);
|
||||
|
||||
/// No description provided for @importGalleryGrantAccess.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Grant Access'**
|
||||
String get importGalleryGrantAccess;
|
||||
|
||||
/// No description provided for @importGalleryOpenSettings.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Open Settings'**
|
||||
String get importGalleryOpenSettings;
|
||||
|
||||
/// No description provided for @importGalleryPermissionDenied.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Permission to access gallery denied.'**
|
||||
String get importGalleryPermissionDenied;
|
||||
|
||||
/// No description provided for @importGalleryTryAgain.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Try Again'**
|
||||
String get importGalleryTryAgain;
|
||||
|
||||
/// No description provided for @importGalleryAlbumNotFound.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'\"twonly\" album not found'**
|
||||
String get importGalleryAlbumNotFound;
|
||||
|
||||
/// No description provided for @importGalleryAlbumNotFoundDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'If you don\'t have this album yet, you can also create it to import photos into twonly.'**
|
||||
String get importGalleryAlbumNotFoundDesc;
|
||||
|
||||
/// No description provided for @importGalleryNoImagesFound.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'No images found'**
|
||||
String get importGalleryNoImagesFound;
|
||||
|
||||
/// No description provided for @importGalleryNoImagesFoundDesc.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'There are no images on your device.'**
|
||||
String get importGalleryNoImagesFoundDesc;
|
||||
|
||||
/// No description provided for @importGalleryShowAllImages.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Show all images'**
|
||||
String get importGalleryShowAllImages;
|
||||
|
||||
/// No description provided for @importGalleryShowTwonlyAlbum.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Show twonly album'**
|
||||
String get importGalleryShowTwonlyAlbum;
|
||||
|
||||
/// No description provided for @importGalleryToggleDescAll.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Viewing all images on your device.'**
|
||||
String get importGalleryToggleDescAll;
|
||||
|
||||
/// No description provided for @importGalleryToggleDescTwonly.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Viewing the \"twonly\" album.'**
|
||||
String get importGalleryToggleDescTwonly;
|
||||
|
||||
/// No description provided for @importGalleryFilterTwonly.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Only show the twonly-Album'**
|
||||
String get importGalleryFilterTwonly;
|
||||
|
||||
/// No description provided for @importGalleryRefresh.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Refresh'**
|
||||
String get importGalleryRefresh;
|
||||
|
||||
/// No description provided for @importGallerySelectToImport.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Select items to import'**
|
||||
String get importGallerySelectToImport;
|
||||
|
||||
/// No description provided for @importGalleryImportCount.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{count, plural, =1{Import 1 item} other{Import {count} items}}'**
|
||||
String importGalleryImportCount(num count);
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate
|
||||
|
|
|
|||
|
|
@ -8,12 +8,9 @@ import 'app_localizations.dart';
|
|||
class AppLocalizationsDe extends AppLocalizations {
|
||||
AppLocalizationsDe([String locale = 'de']) : super(locale);
|
||||
|
||||
@override
|
||||
String get registerTitle => 'Willkommen bei twonly!';
|
||||
|
||||
@override
|
||||
String get registerSlogan =>
|
||||
'twonly, eine private und sichere Möglichkeit um mit Freunden in Kontakt zu bleiben.';
|
||||
'Privat und sicher mit Freunden in Kontakt bleiben.';
|
||||
|
||||
@override
|
||||
String get onboardingWelcomeTitle => 'Willkommen bei twonly!';
|
||||
|
|
@ -55,15 +52,13 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
String get onboardingGetStartedTitle => 'Auf geht\'s';
|
||||
|
||||
@override
|
||||
String get registerUsernameSlogan =>
|
||||
'Bitte wähle einen Benutzernamen, damit dich andere finden können!';
|
||||
String get registerUsernameSlogan => 'Dein öffentlicher Benutzername';
|
||||
|
||||
@override
|
||||
String get registerUsernameDecoration => 'Benutzername';
|
||||
|
||||
@override
|
||||
String get registerUsernameLimits =>
|
||||
'Der Benutzername muss mindestens 3 Zeichen lang sein.';
|
||||
String get registerUsernameLimits => 'Mindestens 3 Zeichen.';
|
||||
|
||||
@override
|
||||
String get registerProofOfWorkFailed =>
|
||||
|
|
@ -249,6 +244,21 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
@override
|
||||
String get settingsStorageDataAutoDownWifi => 'Bei Nutzung von WLAN';
|
||||
|
||||
@override
|
||||
String get settingsStorageManageTitle => 'Speicher verwalten';
|
||||
|
||||
@override
|
||||
String get settingsStorageUsed => 'Speicherplatz belegt';
|
||||
|
||||
@override
|
||||
String get settingsStorageImages => 'Bilder';
|
||||
|
||||
@override
|
||||
String get settingsStorageVideos => 'Videos';
|
||||
|
||||
@override
|
||||
String get settingsStorageGifs => 'GIFs';
|
||||
|
||||
@override
|
||||
String get settingsProfileCustomizeAvatar => 'Avatar anpassen';
|
||||
|
||||
|
|
@ -282,6 +292,34 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
return '$len Kontakt(e)';
|
||||
}
|
||||
|
||||
@override
|
||||
String get settingsPrivacyProfileSelectionTitle => 'Sicherheitsprofil';
|
||||
|
||||
@override
|
||||
String get settingsPrivacyProfileSelectionDesc =>
|
||||
'Wähle deinen Setup-Pfad und deine Sicherheitskonfiguration';
|
||||
|
||||
@override
|
||||
String get securityProfileTitle => 'Sicherheitsprofil';
|
||||
|
||||
@override
|
||||
String get securityProfileSubtitle =>
|
||||
'Wähle das Schutzniveau, das zu deiner täglichen Nutzung passt. Dies kann jederzeit in den Einstellungen geändert werden.';
|
||||
|
||||
@override
|
||||
String get securityProfileNormalTitle => 'Normaler Schutz';
|
||||
|
||||
@override
|
||||
String get securityProfileNormalDesc =>
|
||||
'Gute Balance zwischen Komfort und Sicherheit, ohne dich zu sehr einzuschränken.';
|
||||
|
||||
@override
|
||||
String get securityProfileStrictTitle => 'Strikter Schutz';
|
||||
|
||||
@override
|
||||
String get securityProfileStrictDesc =>
|
||||
'Maximaler Schutz vor Phishing, kann aber unkomfortabel sein.';
|
||||
|
||||
@override
|
||||
String get settingsNotification => 'Benachrichtigung';
|
||||
|
||||
|
|
@ -437,8 +475,9 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
String get verificationTypeQrScanned => 'Du hast den QR-Code gescannt.';
|
||||
|
||||
@override
|
||||
String get verificationTypeSecretQrToken =>
|
||||
'Die andere Person hat deinen QR-Code gescannt.';
|
||||
String verificationTypeSecretQrToken(Object username) {
|
||||
return '$username hat deinen QR-Code gescannt.';
|
||||
}
|
||||
|
||||
@override
|
||||
String get verificationTypeLink => 'Per Link verifiziert.';
|
||||
|
|
@ -713,6 +752,17 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
@override
|
||||
String get deleteOkBtnForAll => 'Für alle löschen';
|
||||
|
||||
@override
|
||||
String memoriesDeleteSnackbarSuccess(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: '$count Elemente erfolgreich gelöscht',
|
||||
one: '1 Element erfolgreich gelöscht',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String get deleteOkBtnForMe => 'Für mich löschen';
|
||||
|
||||
|
|
@ -722,6 +772,17 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
@override
|
||||
String get deleteImageBody => 'Das Bild wird unwiderruflich gelöscht.';
|
||||
|
||||
@override
|
||||
String deleteMemoriesBody(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: 'Die $count Bilder werden unwiderruflich gelöscht.',
|
||||
one: 'Das Bild wird unwiderruflich gelöscht.',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String get settingsBackup => 'Backup';
|
||||
|
||||
|
|
@ -801,11 +862,7 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
String get backupChangePassword => 'Password ändern';
|
||||
|
||||
@override
|
||||
String get twonlySafeRecoverTitle => 'Recovery';
|
||||
|
||||
@override
|
||||
String get twonlySafeRecoverDesc =>
|
||||
'Wenn du ein Backup mit twonly Backup erstellt hast, kannst du es hier wiederherstellen.';
|
||||
String get twonlySafeRecoverTitle => 'Backup wiederherstellen';
|
||||
|
||||
@override
|
||||
String get twonlySafeRecoverBtn => 'Backup wiederherstellen';
|
||||
|
|
@ -1270,6 +1327,10 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
@override
|
||||
String get openYourOwnQRcode => 'Eigenen QR-Code öffnen';
|
||||
|
||||
@override
|
||||
String get addContactQrSheetSubtext =>
|
||||
'Lass einen Freund diesen QR-Code scannen, um dich hinzuzufügen';
|
||||
|
||||
@override
|
||||
String get finishSetupCardTitle => 'Profil vervollständigen';
|
||||
|
||||
|
|
@ -1323,11 +1384,11 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
'Erfahre, wer dich anfragt';
|
||||
|
||||
@override
|
||||
String get userDiscoverySettingsManualApproval => 'Manuelle Zustimmung';
|
||||
String get userDiscoverySettingsManualApproval => 'Vor jedem Teilen fragen';
|
||||
|
||||
@override
|
||||
String get userDiscoverySettingsManualApprovalDesc =>
|
||||
'Bevor jemand geteilt wird, wirst du zuerst gefragt.';
|
||||
'Bevor einer deiner Freunde geteilt wird, wirst du jedes Mal gefragt.';
|
||||
|
||||
@override
|
||||
String get onboardingUserDiscoveryLetFriendsFindYou =>
|
||||
|
|
@ -1495,7 +1556,7 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
|
||||
@override
|
||||
String get verificationBadgeGeneralDesc =>
|
||||
'Der Haken gibt dir die Sicherheit, dass du mit der richtigen Person schreibst. Scanne einen Kontakt, um diesen zu verifizieren.';
|
||||
'Der Haken gibt dir die Sicherheit, dass du mit der richtigen Person schreibst. Du kannst Kontakte jederzeit verifizieren, indem du deren QR-Code scannst.';
|
||||
|
||||
@override
|
||||
String get verificationBadgeGreenDesc =>
|
||||
|
|
@ -1509,6 +1570,40 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
String get verificationBadgeRedDesc =>
|
||||
'Ein Kontakt, dessen Identität noch *nicht überprüft* wurde.';
|
||||
|
||||
@override
|
||||
String get deleteVerificationTitle => 'Verifizierung löschen?';
|
||||
|
||||
@override
|
||||
String get deleteVerificationBody =>
|
||||
'Möchtest du diese Verifizierung wirklich löschen?';
|
||||
|
||||
@override
|
||||
String secretQrTokenVerifiedSnackbar(Object username) {
|
||||
return '$username hat deinen QR-Code gescannt und ist nun verifiziert.';
|
||||
}
|
||||
|
||||
@override
|
||||
String mutualGroupsTitle(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: '$count gemeinsame Gruppen',
|
||||
one: '1 gemeinsame Gruppe',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String mutualGroupsSentMessages(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: '$count Nachrichten gesendet',
|
||||
one: '1 Nachricht gesendet',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String chatEntryFlameRestored(Object count) {
|
||||
return '$count Flammen wiederhergestellt';
|
||||
|
|
@ -1588,6 +1683,12 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
@override
|
||||
String get userDiscoverySettingsTitle => 'Gemeinsame Freunde';
|
||||
|
||||
@override
|
||||
String get userDiscoveryWhyThisIsUsed => 'Warum dies verwendet wird';
|
||||
|
||||
@override
|
||||
String get userDiscoveryFeatureOffers => 'Dein Nutzen auf einen Blick';
|
||||
|
||||
@override
|
||||
String get userDiscoveryDisabledLearnMore => 'Mehr erfahren';
|
||||
|
||||
|
|
@ -1631,6 +1732,43 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
@override
|
||||
String get friendSuggestionsRequest => 'Anfragen';
|
||||
|
||||
@override
|
||||
String get friendSuggestionsAskFriend => 'Deine Freunde fragen';
|
||||
|
||||
@override
|
||||
String askFriendsDialogTitle(Object username) {
|
||||
return 'Nach $username fragen';
|
||||
}
|
||||
|
||||
@override
|
||||
String get askFriendsDialogDescription =>
|
||||
'Wähle die Freunde aus, die du zu diesem Nutzer fragen möchtest:';
|
||||
|
||||
@override
|
||||
String get askFriendsDialogConfirm => 'Fragen';
|
||||
|
||||
@override
|
||||
String get askFriendsDialogCancel => 'Abbrechen';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendReceivedDescription =>
|
||||
'Dein Freund hat diesen Nutzer als Vorschlag erhalten und möchte wissen, ob er diese Person kennt.';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendAddedDescription =>
|
||||
'Du hast diesen Nutzer zu deinen Kontakten hinzugefügt.';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendHide => 'Ausblenden';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendRequest => 'Anfragen';
|
||||
|
||||
@override
|
||||
String chatAskAFriendUnknownUser(Object userId) {
|
||||
return 'Nutzer $userId';
|
||||
}
|
||||
|
||||
@override
|
||||
String contactUserDiscoveryImagesLeft(Object imagesLeft, Object username) {
|
||||
return 'Es fehlen noch $imagesLeft Bilder bis deine Freunde mit $username geteilt werden.';
|
||||
|
|
@ -1798,9 +1936,6 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
String get errorEmojiUsedOrInvalid =>
|
||||
'Emoji wird bereits verwendet oder ist ungültig';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeTitle => 'Unterstütze unabhängigen Datenschutz.';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeSecureTitle => 'Secure by Design';
|
||||
|
||||
|
|
@ -1816,10 +1951,180 @@ class AppLocalizationsDe extends AppLocalizations {
|
|||
'twonly wird niemals Werbung anzeigen oder deine privaten Daten verkaufen.';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeFundedTitle =>
|
||||
'Unabhängig und durch Nutzer finanziert';
|
||||
String get subscriptionPledgeSubtitle => 'Keine Werbung. Volle Privatsphäre.';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeFundedDesc =>
|
||||
'twonly wird rein durch Nutzer-Abonnements finanziert, um unsere Unabhängigkeit und die Zukunft von twonly zu sichern.';
|
||||
String get dragToZoom => 'Zum Zoomen ziehen';
|
||||
|
||||
@override
|
||||
String get showUsername => 'Benutzernamen anzeigen';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionTitle => 'Wähle deinen Setup-Weg';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionSubtitle =>
|
||||
'Wähle aus, wie du deine Sicherheits- und Privatsphäre-Einstellungen konfigurieren möchtest.';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionDefaultTitle => 'Standard';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionDefaultDesc =>
|
||||
'Wendet sofort die empfohlenen Einstellungen an, damit du die App direkt nutzen kannst.';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionDefaultBadge => 'Schnelles Setup';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionCustomizeTitle => 'Anpassen';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionCustomizeDesc =>
|
||||
'Schritt-für-Schritt-Einrichtung, damit du selbst entscheiden kannst.';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionStrictTitle => 'Erhöhter Schutz';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionStrictDesc =>
|
||||
'Maximaler Schutz vor Phishing. Empfohlen für *Journalisten & Personen des öffentlichen Lebens*.';
|
||||
|
||||
@override
|
||||
String get replyFlameRestored => 'Flammen wiederhergestellt';
|
||||
|
||||
@override
|
||||
String get replyAskAFriend => 'Einen Freund fragen';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningDirectTitle =>
|
||||
'Identität nicht persönlich verifiziert';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningGroupTitle =>
|
||||
'Nicht alle Mitglieder sind persönlich verifiziert';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningBody =>
|
||||
'*Teile keine geheimen Daten*. Jemand könnte sich *als dein Freund ausgeben*.';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningButton => 'Jetzt verifizieren';
|
||||
|
||||
@override
|
||||
String get today => 'Heute';
|
||||
|
||||
@override
|
||||
String get yesterday => 'Gestern';
|
||||
|
||||
@override
|
||||
String get galleryDisableWarningTitle => 'Galeriespeicherung deaktivieren?';
|
||||
|
||||
@override
|
||||
String get galleryDisableWarningBody =>
|
||||
'Wenn du dies deaktivierst, werden deine Mediendateien nicht in deiner Galerie gespeichert und könnten dauerhaft verloren gehen, wenn twonly deinstalliert wird oder ein Problem auftritt, da Mediendateien noch nicht in Backups enthalten sind.';
|
||||
|
||||
@override
|
||||
String get galleryDisableWarningConfirm => 'Deaktivieren';
|
||||
|
||||
@override
|
||||
String get settingsStorageScanGalleryTitle => 'Aus Galerie importieren';
|
||||
|
||||
@override
|
||||
String get importGalleryDeselectAll => 'Alle abwählen';
|
||||
|
||||
@override
|
||||
String get importGallerySelectAll => 'Alle auswählen';
|
||||
|
||||
@override
|
||||
String get importGalleryPermissionRequired =>
|
||||
'Zugriff auf deine Galerie ist erforderlich, um frühere twonly-Mediendateien zu importieren.';
|
||||
|
||||
@override
|
||||
String importGalleryPermissionError(Object error) {
|
||||
return 'Beim Anfordern der Berechtigung ist ein Fehler aufgetreten: $error';
|
||||
}
|
||||
|
||||
@override
|
||||
String importGalleryLoadError(Object error) {
|
||||
return 'Laden der Medien fehlgeschlagen: $error';
|
||||
}
|
||||
|
||||
@override
|
||||
String importGalleryImportingOf(Object current, Object total) {
|
||||
return '$current von $total wird importiert...';
|
||||
}
|
||||
|
||||
@override
|
||||
String get importGalleryStarting => 'Import wird gestartet...';
|
||||
|
||||
@override
|
||||
String importGalleryComplete(
|
||||
Object imported,
|
||||
Object duplicated,
|
||||
Object failed,
|
||||
) {
|
||||
return 'Import abgeschlossen: $imported erfolgreich importiert, $duplicated Duplikate und $failed fehlgeschlagen.';
|
||||
}
|
||||
|
||||
@override
|
||||
String get importGalleryGrantAccess => 'Zugriff erlauben';
|
||||
|
||||
@override
|
||||
String get importGalleryOpenSettings => 'Einstellungen öffnen';
|
||||
|
||||
@override
|
||||
String get importGalleryPermissionDenied => 'Zugriff auf Galerie verweigert.';
|
||||
|
||||
@override
|
||||
String get importGalleryTryAgain => 'Erneut versuchen';
|
||||
|
||||
@override
|
||||
String get importGalleryAlbumNotFound => '\"twonly\"-Album nicht gefunden';
|
||||
|
||||
@override
|
||||
String get importGalleryAlbumNotFoundDesc =>
|
||||
'Falls du dieses Album noch nicht hast, kannst du es auch erstellen, um Fotos in twonly zu importieren.';
|
||||
|
||||
@override
|
||||
String get importGalleryNoImagesFound => 'Keine Bilder gefunden';
|
||||
|
||||
@override
|
||||
String get importGalleryNoImagesFoundDesc =>
|
||||
'Es befinden sich keine Bilder auf deinem Gerät.';
|
||||
|
||||
@override
|
||||
String get importGalleryShowAllImages => 'Alle Bilder anzeigen';
|
||||
|
||||
@override
|
||||
String get importGalleryShowTwonlyAlbum => 'twonly-Album anzeigen';
|
||||
|
||||
@override
|
||||
String get importGalleryToggleDescAll =>
|
||||
'Es werden alle Bilder auf deinem Gerät angezeigt.';
|
||||
|
||||
@override
|
||||
String get importGalleryToggleDescTwonly =>
|
||||
'Es wird das \"twonly\"-Album angezeigt.';
|
||||
|
||||
@override
|
||||
String get importGalleryFilterTwonly => 'Nur das twonly-Album anzeigen';
|
||||
|
||||
@override
|
||||
String get importGalleryRefresh => 'Aktualisieren';
|
||||
|
||||
@override
|
||||
String get importGallerySelectToImport =>
|
||||
'Elemente zum Importieren auswählen';
|
||||
|
||||
@override
|
||||
String importGalleryImportCount(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: '$count Elemente importieren',
|
||||
one: '1 Element importieren',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,9 @@ import 'app_localizations.dart';
|
|||
class AppLocalizationsEn extends AppLocalizations {
|
||||
AppLocalizationsEn([String locale = 'en']) : super(locale);
|
||||
|
||||
@override
|
||||
String get registerTitle => 'Welcome to twonly!';
|
||||
|
||||
@override
|
||||
String get registerSlogan =>
|
||||
'twonly, a privacy friendly way to connect with friends through secure, spontaneous image sharing';
|
||||
'Stay in touch with friends privately and securely.';
|
||||
|
||||
@override
|
||||
String get onboardingWelcomeTitle => 'Welcome to twonly!';
|
||||
|
|
@ -54,15 +51,13 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
String get onboardingGetStartedTitle => 'Let\'s go!';
|
||||
|
||||
@override
|
||||
String get registerUsernameSlogan =>
|
||||
'Please select a username so others can find you!';
|
||||
String get registerUsernameSlogan => 'Your public username';
|
||||
|
||||
@override
|
||||
String get registerUsernameDecoration => 'Username';
|
||||
|
||||
@override
|
||||
String get registerUsernameLimits =>
|
||||
'Your username must be at least 3 characters long.';
|
||||
String get registerUsernameLimits => 'At least 3 characters.';
|
||||
|
||||
@override
|
||||
String get registerProofOfWorkFailed =>
|
||||
|
|
@ -245,6 +240,21 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get settingsStorageDataAutoDownWifi => 'When using WI-FI';
|
||||
|
||||
@override
|
||||
String get settingsStorageManageTitle => 'Manage storage';
|
||||
|
||||
@override
|
||||
String get settingsStorageUsed => 'Storage used';
|
||||
|
||||
@override
|
||||
String get settingsStorageImages => 'Images';
|
||||
|
||||
@override
|
||||
String get settingsStorageVideos => 'Videos';
|
||||
|
||||
@override
|
||||
String get settingsStorageGifs => 'GIFs';
|
||||
|
||||
@override
|
||||
String get settingsProfileCustomizeAvatar => 'Customize your avatar';
|
||||
|
||||
|
|
@ -278,6 +288,34 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
return '$len contact(s)';
|
||||
}
|
||||
|
||||
@override
|
||||
String get settingsPrivacyProfileSelectionTitle => 'Security Profile';
|
||||
|
||||
@override
|
||||
String get settingsPrivacyProfileSelectionDesc =>
|
||||
'Choose your setup path and security configuration';
|
||||
|
||||
@override
|
||||
String get securityProfileTitle => 'Security Profile';
|
||||
|
||||
@override
|
||||
String get securityProfileSubtitle =>
|
||||
'Choose the level of protection that fits your daily use. This can be changed at any time in your settings.';
|
||||
|
||||
@override
|
||||
String get securityProfileNormalTitle => 'Normal Protection';
|
||||
|
||||
@override
|
||||
String get securityProfileNormalDesc =>
|
||||
'Good balance between a convenient mode without bothering you too much.';
|
||||
|
||||
@override
|
||||
String get securityProfileStrictTitle => 'Strict Protection';
|
||||
|
||||
@override
|
||||
String get securityProfileStrictDesc =>
|
||||
'Maximum anti-phishing protection but may be inconvenient.';
|
||||
|
||||
@override
|
||||
String get settingsNotification => 'Notification';
|
||||
|
||||
|
|
@ -432,8 +470,9 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
String get verificationTypeQrScanned => 'You scanned their QR code.';
|
||||
|
||||
@override
|
||||
String get verificationTypeSecretQrToken =>
|
||||
'The other person scanned your QR code.';
|
||||
String verificationTypeSecretQrToken(Object username) {
|
||||
return '$username has scanned your QR code.';
|
||||
}
|
||||
|
||||
@override
|
||||
String get verificationTypeLink => 'Verified via link.';
|
||||
|
|
@ -707,6 +746,17 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get deleteOkBtnForAll => 'Delete for all';
|
||||
|
||||
@override
|
||||
String memoriesDeleteSnackbarSuccess(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: 'Deleted $count items successfully',
|
||||
one: 'Deleted 1 item successfully',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String get deleteOkBtnForMe => 'Delete for me';
|
||||
|
||||
|
|
@ -716,6 +766,17 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get deleteImageBody => 'The image will be irrevocably deleted.';
|
||||
|
||||
@override
|
||||
String deleteMemoriesBody(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: 'The $count images will be irrevocably deleted.',
|
||||
one: 'The image will be irrevocably deleted.',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String get settingsBackup => 'Backup';
|
||||
|
||||
|
|
@ -795,11 +856,7 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
String get backupChangePassword => 'Change password';
|
||||
|
||||
@override
|
||||
String get twonlySafeRecoverTitle => 'Recovery';
|
||||
|
||||
@override
|
||||
String get twonlySafeRecoverDesc =>
|
||||
'If you have created a backup with twonly Backup, you can restore it here.';
|
||||
String get twonlySafeRecoverTitle => 'Restore backup';
|
||||
|
||||
@override
|
||||
String get twonlySafeRecoverBtn => 'Restore backup';
|
||||
|
|
@ -1261,6 +1318,10 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get openYourOwnQRcode => 'Open your own QR code';
|
||||
|
||||
@override
|
||||
String get addContactQrSheetSubtext =>
|
||||
'Let a friend scan this QR code to add you';
|
||||
|
||||
@override
|
||||
String get finishSetupCardTitle => 'Complete your profile';
|
||||
|
||||
|
|
@ -1314,11 +1375,12 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
'Be informed about who is requesting';
|
||||
|
||||
@override
|
||||
String get userDiscoverySettingsManualApproval => 'Manual approval';
|
||||
String get userDiscoverySettingsManualApproval =>
|
||||
'Ask every time before sharing';
|
||||
|
||||
@override
|
||||
String get userDiscoverySettingsManualApprovalDesc =>
|
||||
'Before someone is shared, you\'ll be asked first.';
|
||||
'Before one of your friends is shared, you will be asked every time.';
|
||||
|
||||
@override
|
||||
String get onboardingUserDiscoveryLetFriendsFindYou =>
|
||||
|
|
@ -1480,7 +1542,7 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
|
||||
@override
|
||||
String get verificationBadgeGeneralDesc =>
|
||||
'The checkmark gives you the certainty that you are messaging the right person. Scan the contact\'s QR code to verify it.';
|
||||
'The checkmark gives you the certainty that you are messaging the right person. You can verify contacts at any time by scanning their QR code.';
|
||||
|
||||
@override
|
||||
String get verificationBadgeGreenDesc =>
|
||||
|
|
@ -1494,6 +1556,40 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
String get verificationBadgeRedDesc =>
|
||||
'A contact whose identity has *not* yet been verified.';
|
||||
|
||||
@override
|
||||
String get deleteVerificationTitle => 'Delete verification?';
|
||||
|
||||
@override
|
||||
String get deleteVerificationBody =>
|
||||
'Are you sure you want to delete this verification?';
|
||||
|
||||
@override
|
||||
String secretQrTokenVerifiedSnackbar(Object username) {
|
||||
return '$username has scanned your QR code and is now verified.';
|
||||
}
|
||||
|
||||
@override
|
||||
String mutualGroupsTitle(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: '$count mutual groups',
|
||||
one: '1 mutual group',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String mutualGroupsSentMessages(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: '$count messages sent',
|
||||
one: '1 message sent',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
|
||||
@override
|
||||
String chatEntryFlameRestored(Object count) {
|
||||
return '$count flames restored';
|
||||
|
|
@ -1573,6 +1669,12 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get userDiscoverySettingsTitle => 'Mutual Friends';
|
||||
|
||||
@override
|
||||
String get userDiscoveryWhyThisIsUsed => 'Why this is used';
|
||||
|
||||
@override
|
||||
String get userDiscoveryFeatureOffers => 'Your benefits at a glance';
|
||||
|
||||
@override
|
||||
String get userDiscoveryDisabledLearnMore => 'Learn more';
|
||||
|
||||
|
|
@ -1616,6 +1718,43 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get friendSuggestionsRequest => 'Request';
|
||||
|
||||
@override
|
||||
String get friendSuggestionsAskFriend => 'Ask your friends';
|
||||
|
||||
@override
|
||||
String askFriendsDialogTitle(Object username) {
|
||||
return 'Ask about $username';
|
||||
}
|
||||
|
||||
@override
|
||||
String get askFriendsDialogDescription =>
|
||||
'Select the friends you want to ask about this user:';
|
||||
|
||||
@override
|
||||
String get askFriendsDialogConfirm => 'Ask';
|
||||
|
||||
@override
|
||||
String get askFriendsDialogCancel => 'Cancel';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendReceivedDescription =>
|
||||
'Your friend just got this as a suggestion and wants to know if he knows this person.';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendAddedDescription =>
|
||||
'You have added this user to your contacts.';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendHide => 'Hide';
|
||||
|
||||
@override
|
||||
String get chatAskAFriendRequest => 'Request';
|
||||
|
||||
@override
|
||||
String chatAskAFriendUnknownUser(Object userId) {
|
||||
return 'User $userId';
|
||||
}
|
||||
|
||||
@override
|
||||
String contactUserDiscoveryImagesLeft(Object imagesLeft, Object username) {
|
||||
return '$imagesLeft more images are needed until your friends are shared with $username.';
|
||||
|
|
@ -1782,9 +1921,6 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
@override
|
||||
String get errorEmojiUsedOrInvalid => 'Emoji already used or invalid';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeTitle => 'Support independent privacy.';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeSecureTitle => 'Secure by Design';
|
||||
|
||||
|
|
@ -1800,9 +1936,177 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||
'twonly will never show advertisements or sell your private data.';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeFundedTitle => 'Independent and funded by Users';
|
||||
String get subscriptionPledgeSubtitle => 'Zero ads. Total privacy.';
|
||||
|
||||
@override
|
||||
String get subscriptionPledgeFundedDesc =>
|
||||
'twonly is funded purely by user subscriptions to secure our independence and support the future of twonly.';
|
||||
String get dragToZoom => 'Drag to Zoom';
|
||||
|
||||
@override
|
||||
String get showUsername => 'Show username';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionTitle => 'Choose your setup path';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionSubtitle =>
|
||||
'Choose how you want to configure your security and privacy settings.';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionDefaultTitle => 'Default';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionDefaultDesc =>
|
||||
'Instantly applies recommended settings so you can start using the app.';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionDefaultBadge => 'Fast Setup';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionCustomizeTitle => 'Customize';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionCustomizeDesc =>
|
||||
'Step-by-step setup so you can decide for yourself.';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionStrictTitle => 'Enhanced Protection';
|
||||
|
||||
@override
|
||||
String get onboardingProfileSelectionStrictDesc =>
|
||||
'Maximum anti-phishing defense. Recommended for *journalists & public figures*.';
|
||||
|
||||
@override
|
||||
String get replyFlameRestored => 'Flames restored';
|
||||
|
||||
@override
|
||||
String get replyAskAFriend => 'Ask a friend';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningDirectTitle => 'Identity not verified in person';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningGroupTitle =>
|
||||
'Not all members are verified in person';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningBody =>
|
||||
'*Avoid sharing sensitive data*. Risk of *impersonation* without manual verification.';
|
||||
|
||||
@override
|
||||
String get unverifiedWarningButton => 'Verify now';
|
||||
|
||||
@override
|
||||
String get today => 'Today';
|
||||
|
||||
@override
|
||||
String get yesterday => 'Yesterday';
|
||||
|
||||
@override
|
||||
String get galleryDisableWarningTitle => 'Disable gallery saving?';
|
||||
|
||||
@override
|
||||
String get galleryDisableWarningBody =>
|
||||
'If you disable this, your media files will not be saved to your gallery and could be permanently lost if twonly is removed or has an issue, as media files are not yet backed up.';
|
||||
|
||||
@override
|
||||
String get galleryDisableWarningConfirm => 'Disable';
|
||||
|
||||
@override
|
||||
String get settingsStorageScanGalleryTitle => 'Import from Gallery';
|
||||
|
||||
@override
|
||||
String get importGalleryDeselectAll => 'Deselect all';
|
||||
|
||||
@override
|
||||
String get importGallerySelectAll => 'Select all';
|
||||
|
||||
@override
|
||||
String get importGalleryPermissionRequired =>
|
||||
'Permission to access your gallery is required to import previous twonly media files.';
|
||||
|
||||
@override
|
||||
String importGalleryPermissionError(Object error) {
|
||||
return 'An error occurred while requesting permission: $error';
|
||||
}
|
||||
|
||||
@override
|
||||
String importGalleryLoadError(Object error) {
|
||||
return 'Failed to load assets: $error';
|
||||
}
|
||||
|
||||
@override
|
||||
String importGalleryImportingOf(Object current, Object total) {
|
||||
return 'Importing $current of $total...';
|
||||
}
|
||||
|
||||
@override
|
||||
String get importGalleryStarting => 'Starting import...';
|
||||
|
||||
@override
|
||||
String importGalleryComplete(
|
||||
Object imported,
|
||||
Object duplicated,
|
||||
Object failed,
|
||||
) {
|
||||
return 'Import complete: $imported successfully imported, $duplicated duplicated and $failed failed.';
|
||||
}
|
||||
|
||||
@override
|
||||
String get importGalleryGrantAccess => 'Grant Access';
|
||||
|
||||
@override
|
||||
String get importGalleryOpenSettings => 'Open Settings';
|
||||
|
||||
@override
|
||||
String get importGalleryPermissionDenied =>
|
||||
'Permission to access gallery denied.';
|
||||
|
||||
@override
|
||||
String get importGalleryTryAgain => 'Try Again';
|
||||
|
||||
@override
|
||||
String get importGalleryAlbumNotFound => '\"twonly\" album not found';
|
||||
|
||||
@override
|
||||
String get importGalleryAlbumNotFoundDesc =>
|
||||
'If you don\'t have this album yet, you can also create it to import photos into twonly.';
|
||||
|
||||
@override
|
||||
String get importGalleryNoImagesFound => 'No images found';
|
||||
|
||||
@override
|
||||
String get importGalleryNoImagesFoundDesc =>
|
||||
'There are no images on your device.';
|
||||
|
||||
@override
|
||||
String get importGalleryShowAllImages => 'Show all images';
|
||||
|
||||
@override
|
||||
String get importGalleryShowTwonlyAlbum => 'Show twonly album';
|
||||
|
||||
@override
|
||||
String get importGalleryToggleDescAll => 'Viewing all images on your device.';
|
||||
|
||||
@override
|
||||
String get importGalleryToggleDescTwonly => 'Viewing the \"twonly\" album.';
|
||||
|
||||
@override
|
||||
String get importGalleryFilterTwonly => 'Only show the twonly-Album';
|
||||
|
||||
@override
|
||||
String get importGalleryRefresh => 'Refresh';
|
||||
|
||||
@override
|
||||
String get importGallerySelectToImport => 'Select items to import';
|
||||
|
||||
@override
|
||||
String importGalleryImportCount(num count) {
|
||||
String _temp0 = intl.Intl.pluralLogic(
|
||||
count,
|
||||
locale: localeName,
|
||||
other: 'Import $count items',
|
||||
one: 'Import 1 item',
|
||||
);
|
||||
return '$_temp0';
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Subproject commit f649128fd875a12f23518ff2641190cc129a9339
|
||||
Subproject commit 189bf8f4dbe2bee4f19a15b9640b8826e4f2e235
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
import 'package:twonly/src/services/profile.service.dart';
|
||||
part 'userdata.model.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
|
|
@ -10,6 +11,7 @@ class UserData {
|
|||
required this.displayName,
|
||||
required this.subscriptionPlan,
|
||||
required this.currentSetupPage,
|
||||
required this.appVersion,
|
||||
});
|
||||
factory UserData.fromJson(Map<String, dynamic> json) =>
|
||||
_$UserDataFromJson(json);
|
||||
|
|
@ -35,6 +37,12 @@ class UserData {
|
|||
@JsonKey(defaultValue: 0)
|
||||
int deviceId = 0;
|
||||
|
||||
@JsonKey(defaultValue: SetupProfile.standard)
|
||||
SetupProfile setupProfile = SetupProfile.standard;
|
||||
|
||||
@JsonKey(defaultValue: SecurityProfile.normal)
|
||||
SecurityProfile securityProfile = SecurityProfile.normal;
|
||||
|
||||
// --- SUBSCRIPTION DTA ---
|
||||
|
||||
@JsonKey(defaultValue: 'Free')
|
||||
|
|
@ -57,6 +65,9 @@ class UserData {
|
|||
@JsonKey(defaultValue: false)
|
||||
bool requestedAudioPermission = false;
|
||||
|
||||
@JsonKey(defaultValue: false)
|
||||
bool enableDatabaseLogging = false;
|
||||
|
||||
@JsonKey(defaultValue: false)
|
||||
bool automaticallyMarkEqualMediaFilesAsOpened = false;
|
||||
|
||||
|
|
@ -76,8 +87,8 @@ class UserData {
|
|||
|
||||
Map<String, List<String>>? autoDownloadOptions;
|
||||
|
||||
@JsonKey(defaultValue: false)
|
||||
bool storeMediaFilesInGallery = false;
|
||||
@JsonKey(defaultValue: true)
|
||||
bool storeMediaFilesInGallery = true;
|
||||
|
||||
@JsonKey(defaultValue: false)
|
||||
bool autoStoreAllSendUnlimitedMediaFiles = false;
|
||||
|
|
@ -165,6 +176,9 @@ class UserData {
|
|||
@JsonKey(defaultValue: false)
|
||||
bool skipSetupPages = false;
|
||||
|
||||
@JsonKey(defaultValue: false)
|
||||
bool hasZoomed = false;
|
||||
|
||||
Map<String, dynamic> toJson() => _$UserDataToJson(this);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,13 +13,22 @@ UserData _$UserDataFromJson(Map<String, dynamic> json) =>
|
|||
displayName: json['displayName'] as String,
|
||||
subscriptionPlan: json['subscriptionPlan'] as String? ?? 'Free',
|
||||
currentSetupPage: json['currentSetupPage'] as String?,
|
||||
appVersion: (json['appVersion'] as num?)?.toInt() ?? 0,
|
||||
)
|
||||
..avatarSvg = json['avatarSvg'] as String?
|
||||
..avatarJson = json['avatarJson'] as String?
|
||||
..appVersion = (json['appVersion'] as num?)?.toInt() ?? 0
|
||||
..avatarCounter = (json['avatarCounter'] as num?)?.toInt() ?? 0
|
||||
..isDeveloper = json['isDeveloper'] as bool? ?? false
|
||||
..deviceId = (json['deviceId'] as num?)?.toInt() ?? 0
|
||||
..setupProfile =
|
||||
$enumDecodeNullable(_$SetupProfileEnumMap, json['setupProfile']) ??
|
||||
SetupProfile.standard
|
||||
..securityProfile =
|
||||
$enumDecodeNullable(
|
||||
_$SecurityProfileEnumMap,
|
||||
json['securityProfile'],
|
||||
) ??
|
||||
SecurityProfile.normal
|
||||
..subscriptionPlanIdStore = json['subscriptionPlanIdStore'] as String?
|
||||
..lastImageSend = json['lastImageSend'] == null
|
||||
? null
|
||||
|
|
@ -33,6 +42,9 @@ UserData _$UserDataFromJson(Map<String, dynamic> json) =>
|
|||
..defaultShowTime = (json['defaultShowTime'] as num?)?.toInt()
|
||||
..requestedAudioPermission =
|
||||
json['requestedAudioPermission'] as bool? ?? false
|
||||
..enableDatabaseLogging = json['enableDatabaseLogging'] as bool? ?? false
|
||||
..automaticallyMarkEqualMediaFilesAsOpened =
|
||||
json['automaticallyMarkEqualMediaFilesAsOpened'] as bool? ?? false
|
||||
..videoStabilizationEnabled =
|
||||
json['videoStabilizationEnabled'] as bool? ?? true
|
||||
..showFeedbackShortcut = json['showFeedbackShortcut'] as bool? ?? true
|
||||
|
|
@ -100,7 +112,8 @@ UserData _$UserDataFromJson(Map<String, dynamic> json) =>
|
|||
..lastUserStudyDataUpload = json['lastUserStudyDataUpload'] == null
|
||||
? null
|
||||
: DateTime.parse(json['lastUserStudyDataUpload'] as String)
|
||||
..skipSetupPages = json['skipSetupPages'] as bool? ?? false;
|
||||
..skipSetupPages = json['skipSetupPages'] as bool? ?? false
|
||||
..hasZoomed = json['hasZoomed'] as bool? ?? false;
|
||||
|
||||
Map<String, dynamic> _$UserDataToJson(UserData instance) => <String, dynamic>{
|
||||
'userId': instance.userId,
|
||||
|
|
@ -112,6 +125,8 @@ Map<String, dynamic> _$UserDataToJson(UserData instance) => <String, dynamic>{
|
|||
'avatarCounter': instance.avatarCounter,
|
||||
'isDeveloper': instance.isDeveloper,
|
||||
'deviceId': instance.deviceId,
|
||||
'setupProfile': _$SetupProfileEnumMap[instance.setupProfile]!,
|
||||
'securityProfile': _$SecurityProfileEnumMap[instance.securityProfile]!,
|
||||
'subscriptionPlan': instance.subscriptionPlan,
|
||||
'subscriptionPlanIdStore': instance.subscriptionPlanIdStore,
|
||||
'lastImageSend': instance.lastImageSend?.toIso8601String(),
|
||||
|
|
@ -121,6 +136,9 @@ Map<String, dynamic> _$UserDataToJson(UserData instance) => <String, dynamic>{
|
|||
'themeMode': _$ThemeModeEnumMap[instance.themeMode]!,
|
||||
'defaultShowTime': instance.defaultShowTime,
|
||||
'requestedAudioPermission': instance.requestedAudioPermission,
|
||||
'enableDatabaseLogging': instance.enableDatabaseLogging,
|
||||
'automaticallyMarkEqualMediaFilesAsOpened':
|
||||
instance.automaticallyMarkEqualMediaFilesAsOpened,
|
||||
'videoStabilizationEnabled': instance.videoStabilizationEnabled,
|
||||
'showFeedbackShortcut': instance.showFeedbackShortcut,
|
||||
'showShowImagePreviewWhenSending': instance.showShowImagePreviewWhenSending,
|
||||
|
|
@ -160,6 +178,18 @@ Map<String, dynamic> _$UserDataToJson(UserData instance) => <String, dynamic>{
|
|||
?.toIso8601String(),
|
||||
'currentSetupPage': instance.currentSetupPage,
|
||||
'skipSetupPages': instance.skipSetupPages,
|
||||
'hasZoomed': instance.hasZoomed,
|
||||
};
|
||||
|
||||
const _$SetupProfileEnumMap = {
|
||||
SetupProfile.standard: 'standard',
|
||||
SetupProfile.customized: 'customized',
|
||||
SetupProfile.maximum: 'maximum',
|
||||
};
|
||||
|
||||
const _$SecurityProfileEnumMap = {
|
||||
SecurityProfile.normal: 'normal',
|
||||
SecurityProfile.strict: 'strict',
|
||||
};
|
||||
|
||||
const _$ThemeModeEnumMap = {
|
||||
|
|
|
|||
|
|
@ -11,10 +11,12 @@ message AdditionalMessageData {
|
|||
LINK = 0;
|
||||
CONTACTS = 1;
|
||||
RESTORED_FLAME_COUNTER = 2;
|
||||
ASK_ABOUT_USER = 3;
|
||||
}
|
||||
Type type = 1;
|
||||
|
||||
optional string link = 2;
|
||||
repeated SharedContact contacts = 3;
|
||||
optional int64 restored_flame_counter = 4;
|
||||
optional int64 ask_about_user_id = 5;
|
||||
}
|
||||
|
|
@ -105,6 +105,7 @@ class AdditionalMessageData extends $pb.GeneratedMessage {
|
|||
$core.String? link,
|
||||
$core.Iterable<SharedContact>? contacts,
|
||||
$fixnum.Int64? restoredFlameCounter,
|
||||
$fixnum.Int64? askAboutUserId,
|
||||
}) {
|
||||
final result = create();
|
||||
if (type != null) result.type = type;
|
||||
|
|
@ -112,6 +113,7 @@ class AdditionalMessageData extends $pb.GeneratedMessage {
|
|||
if (contacts != null) result.contacts.addAll(contacts);
|
||||
if (restoredFlameCounter != null)
|
||||
result.restoredFlameCounter = restoredFlameCounter;
|
||||
if (askAboutUserId != null) result.askAboutUserId = askAboutUserId;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -133,6 +135,7 @@ class AdditionalMessageData extends $pb.GeneratedMessage {
|
|||
..pPM<SharedContact>(3, _omitFieldNames ? '' : 'contacts',
|
||||
subBuilder: SharedContact.create)
|
||||
..aInt64(4, _omitFieldNames ? '' : 'restoredFlameCounter')
|
||||
..aInt64(5, _omitFieldNames ? '' : 'askAboutUserId')
|
||||
..hasRequiredFields = false;
|
||||
|
||||
@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
|
||||
|
|
@ -184,6 +187,15 @@ class AdditionalMessageData extends $pb.GeneratedMessage {
|
|||
$core.bool hasRestoredFlameCounter() => $_has(3);
|
||||
@$pb.TagNumber(4)
|
||||
void clearRestoredFlameCounter() => $_clearField(4);
|
||||
|
||||
@$pb.TagNumber(5)
|
||||
$fixnum.Int64 get askAboutUserId => $_getI64(4);
|
||||
@$pb.TagNumber(5)
|
||||
set askAboutUserId($fixnum.Int64 value) => $_setInt64(4, value);
|
||||
@$pb.TagNumber(5)
|
||||
$core.bool hasAskAboutUserId() => $_has(4);
|
||||
@$pb.TagNumber(5)
|
||||
void clearAskAboutUserId() => $_clearField(5);
|
||||
}
|
||||
|
||||
const $core.bool _omitFieldNames =
|
||||
|
|
|
|||
|
|
@ -22,16 +22,19 @@ class AdditionalMessageData_Type extends $pb.ProtobufEnum {
|
|||
static const AdditionalMessageData_Type RESTORED_FLAME_COUNTER =
|
||||
AdditionalMessageData_Type._(
|
||||
2, _omitEnumNames ? '' : 'RESTORED_FLAME_COUNTER');
|
||||
static const AdditionalMessageData_Type ASK_ABOUT_USER =
|
||||
AdditionalMessageData_Type._(3, _omitEnumNames ? '' : 'ASK_ABOUT_USER');
|
||||
|
||||
static const $core.List<AdditionalMessageData_Type> values =
|
||||
<AdditionalMessageData_Type>[
|
||||
LINK,
|
||||
CONTACTS,
|
||||
RESTORED_FLAME_COUNTER,
|
||||
ASK_ABOUT_USER,
|
||||
];
|
||||
|
||||
static final $core.List<AdditionalMessageData_Type?> _byValue =
|
||||
$pb.ProtobufEnum.$_initByValueList(values, 2);
|
||||
$pb.ProtobufEnum.$_initByValueList(values, 3);
|
||||
static AdditionalMessageData_Type? valueOf($core.int value) =>
|
||||
value < 0 || value >= _byValue.length ? null : _byValue[value];
|
||||
|
||||
|
|
|
|||
|
|
@ -67,11 +67,21 @@ const AdditionalMessageData$json = {
|
|||
'10': 'restoredFlameCounter',
|
||||
'17': true
|
||||
},
|
||||
{
|
||||
'1': 'ask_about_user_id',
|
||||
'3': 5,
|
||||
'4': 1,
|
||||
'5': 3,
|
||||
'9': 2,
|
||||
'10': 'askAboutUserId',
|
||||
'17': true
|
||||
},
|
||||
],
|
||||
'4': [AdditionalMessageData_Type$json],
|
||||
'8': [
|
||||
{'1': '_link'},
|
||||
{'1': '_restored_flame_counter'},
|
||||
{'1': '_ask_about_user_id'},
|
||||
],
|
||||
};
|
||||
|
||||
|
|
@ -82,6 +92,7 @@ const AdditionalMessageData_Type$json = {
|
|||
{'1': 'LINK', '2': 0},
|
||||
{'1': 'CONTACTS', '2': 1},
|
||||
{'1': 'RESTORED_FLAME_COUNTER', '2': 2},
|
||||
{'1': 'ASK_ABOUT_USER', '2': 3},
|
||||
],
|
||||
};
|
||||
|
||||
|
|
@ -90,6 +101,7 @@ final $typed_data.Uint8List additionalMessageDataDescriptor = $convert.base64Dec
|
|||
'ChVBZGRpdGlvbmFsTWVzc2FnZURhdGESLwoEdHlwZRgBIAEoDjIbLkFkZGl0aW9uYWxNZXNzYW'
|
||||
'dlRGF0YS5UeXBlUgR0eXBlEhcKBGxpbmsYAiABKAlIAFIEbGlua4gBARIqCghjb250YWN0cxgD'
|
||||
'IAMoCzIOLlNoYXJlZENvbnRhY3RSCGNvbnRhY3RzEjkKFnJlc3RvcmVkX2ZsYW1lX2NvdW50ZX'
|
||||
'IYBCABKANIAVIUcmVzdG9yZWRGbGFtZUNvdW50ZXKIAQEiOgoEVHlwZRIICgRMSU5LEAASDAoI'
|
||||
'Q09OVEFDVFMQARIaChZSRVNUT1JFRF9GTEFNRV9DT1VOVEVSEAJCBwoFX2xpbmtCGQoXX3Jlc3'
|
||||
'RvcmVkX2ZsYW1lX2NvdW50ZXI=');
|
||||
'IYBCABKANIAVIUcmVzdG9yZWRGbGFtZUNvdW50ZXKIAQESLgoRYXNrX2Fib3V0X3VzZXJfaWQY'
|
||||
'BSABKANIAlIOYXNrQWJvdXRVc2VySWSIAQEiTgoEVHlwZRIICgRMSU5LEAASDAoIQ09OVEFDVF'
|
||||
'MQARIaChZSRVNUT1JFRF9GTEFNRV9DT1VOVEVSEAISEgoOQVNLX0FCT1VUX1VTRVIQA0IHCgVf'
|
||||
'bGlua0IZChdfcmVzdG9yZWRfZmxhbWVfY291bnRlckIUChJfYXNrX2Fib3V0X3VzZXJfaWQ=');
|
||||
|
|
|
|||
|
|
@ -97,6 +97,7 @@ class PublicProfile extends $pb.GeneratedMessage {
|
|||
$core.List<$core.int>? signedPrekeySignature,
|
||||
$fixnum.Int64? signedPrekeyId,
|
||||
$core.List<$core.int>? secretVerificationToken,
|
||||
$fixnum.Int64? timestamp,
|
||||
}) {
|
||||
final result = create();
|
||||
if (userId != null) result.userId = userId;
|
||||
|
|
@ -109,6 +110,7 @@ class PublicProfile extends $pb.GeneratedMessage {
|
|||
if (signedPrekeyId != null) result.signedPrekeyId = signedPrekeyId;
|
||||
if (secretVerificationToken != null)
|
||||
result.secretVerificationToken = secretVerificationToken;
|
||||
if (timestamp != null) result.timestamp = timestamp;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -136,6 +138,7 @@ class PublicProfile extends $pb.GeneratedMessage {
|
|||
..aInt64(7, _omitFieldNames ? '' : 'signedPrekeyId')
|
||||
..a<$core.List<$core.int>>(
|
||||
8, _omitFieldNames ? '' : 'secretVerificationToken', $pb.PbFieldType.OY)
|
||||
..aInt64(9, _omitFieldNames ? '' : 'timestamp')
|
||||
..hasRequiredFields = false;
|
||||
|
||||
@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
|
||||
|
|
@ -230,6 +233,15 @@ class PublicProfile extends $pb.GeneratedMessage {
|
|||
$core.bool hasSecretVerificationToken() => $_has(7);
|
||||
@$pb.TagNumber(8)
|
||||
void clearSecretVerificationToken() => $_clearField(8);
|
||||
|
||||
@$pb.TagNumber(9)
|
||||
$fixnum.Int64 get timestamp => $_getI64(8);
|
||||
@$pb.TagNumber(9)
|
||||
set timestamp($fixnum.Int64 value) => $_setInt64(8, value);
|
||||
@$pb.TagNumber(9)
|
||||
$core.bool hasTimestamp() => $_has(8);
|
||||
@$pb.TagNumber(9)
|
||||
void clearTimestamp() => $_clearField(9);
|
||||
}
|
||||
|
||||
const $core.bool _omitFieldNames =
|
||||
|
|
|
|||
|
|
@ -77,9 +77,19 @@ const PublicProfile$json = {
|
|||
'10': 'secretVerificationToken',
|
||||
'17': true
|
||||
},
|
||||
{
|
||||
'1': 'timestamp',
|
||||
'3': 9,
|
||||
'4': 1,
|
||||
'5': 3,
|
||||
'9': 1,
|
||||
'10': 'timestamp',
|
||||
'17': true
|
||||
},
|
||||
],
|
||||
'8': [
|
||||
{'1': '_secret_verification_token'},
|
||||
{'1': '_timestamp'},
|
||||
],
|
||||
};
|
||||
|
||||
|
|
@ -91,4 +101,5 @@ final $typed_data.Uint8List publicProfileDescriptor = $convert.base64Decode(
|
|||
'lvbl9pZBgFIAEoA1IOcmVnaXN0cmF0aW9uSWQSNgoXc2lnbmVkX3ByZWtleV9zaWduYXR1cmUY'
|
||||
'BiABKAxSFXNpZ25lZFByZWtleVNpZ25hdHVyZRIoChBzaWduZWRfcHJla2V5X2lkGAcgASgDUg'
|
||||
'5zaWduZWRQcmVrZXlJZBI/ChlzZWNyZXRfdmVyaWZpY2F0aW9uX3Rva2VuGAggASgMSABSF3Nl'
|
||||
'Y3JldFZlcmlmaWNhdGlvblRva2VuiAEBQhwKGl9zZWNyZXRfdmVyaWZpY2F0aW9uX3Rva2Vu');
|
||||
'Y3JldFZlcmlmaWNhdGlvblRva2VuiAEBEiEKCXRpbWVzdGFtcBgJIAEoA0gBUgl0aW1lc3RhbX'
|
||||
'CIAQFCHAoaX3NlY3JldF92ZXJpZmljYXRpb25fdG9rZW5CDAoKX3RpbWVzdGFtcA==');
|
||||
|
|
|
|||
|
|
@ -17,4 +17,5 @@ message PublicProfile {
|
|||
bytes signed_prekey_signature = 6;
|
||||
int64 signed_prekey_id = 7;
|
||||
optional bytes secret_verification_token = 8;
|
||||
optional int64 timestamp = 9;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:twonly/app.dart';
|
||||
import 'package:twonly/src/constants/routes.keys.dart';
|
||||
|
|
@ -21,8 +22,8 @@ import 'package:twonly/src/visual/views/settings/backup/backup_setup.view.dart';
|
|||
import 'package:twonly/src/visual/views/settings/chat/chat_reactions.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/chat/chat_settings.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/data_and_storage.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/data_and_storage/export_media.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/data_and_storage/import_media.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/data_and_storage/import_from_gallery.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/data_and_storage/manage_storage.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/developer/automated_testing.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/developer/developer.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/developer/reduce_flames.view.dart';
|
||||
|
|
@ -37,6 +38,7 @@ import 'package:twonly/src/visual/views/settings/help/help.view.dart';
|
|||
import 'package:twonly/src/visual/views/settings/notification.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/privacy.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/privacy/block_users.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/privacy/profile_selection.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/privacy/user_discovery.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/profile/modify_avatar.view.dart';
|
||||
import 'package:twonly/src/visual/views/settings/profile/profile.view.dart';
|
||||
|
|
@ -46,7 +48,10 @@ import 'package:twonly/src/visual/views/settings/subscription/subscription.view.
|
|||
import 'package:twonly/src/visual/views/user_study/user_study_questionnaire.view.dart';
|
||||
import 'package:twonly/src/visual/views/user_study/user_study_welcome.view.dart';
|
||||
|
||||
final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
final routerProvider = GoRouter(
|
||||
navigatorKey: rootNavigatorKey,
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: Routes.home,
|
||||
|
|
@ -200,6 +205,10 @@ final routerProvider = GoRouter(
|
|||
path: 'user_discovery',
|
||||
builder: (context, state) => const UserDiscoverySettingsView(),
|
||||
),
|
||||
GoRoute(
|
||||
path: 'profile_selection',
|
||||
builder: (context, state) => const ProfileSelectionSettingsView(),
|
||||
),
|
||||
],
|
||||
),
|
||||
GoRoute(
|
||||
|
|
@ -211,12 +220,12 @@ final routerProvider = GoRouter(
|
|||
builder: (context, state) => const DataAndStorageView(),
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: 'import',
|
||||
builder: (context, state) => const ImportMediaView(),
|
||||
path: 'manage',
|
||||
builder: (context, state) => const ManageStorageView(),
|
||||
),
|
||||
GoRoute(
|
||||
path: 'export',
|
||||
builder: (context, state) => const ExportMediaView(),
|
||||
path: 'import_gallery',
|
||||
builder: (context, state) => const ImportFromGalleryView(),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
|
|
|||
25
lib/src/services/android_photo_picker.service.dart
Normal file
25
lib/src/services/android_photo_picker.service.dart
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import 'package:flutter/services.dart';
|
||||
|
||||
class AndroidPhotoPickerService {
|
||||
static const MethodChannel _channel = MethodChannel('eu.twonly/photo_picker');
|
||||
|
||||
/// Launches the native Android Photo Picker and returns a list of URIs.
|
||||
static Future<List<String>> pickImages() async {
|
||||
try {
|
||||
final result = await _channel.invokeListMethod<String>('pickImages');
|
||||
return result ?? [];
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the raw bytes from a content URI using the Android ContentResolver.
|
||||
static Future<Uint8List?> getUriBytes(String uri) async {
|
||||
try {
|
||||
final bytes = await _channel.invokeMethod<Uint8List>('getUriBytes', {'uri': uri});
|
||||
return bytes;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -18,12 +18,10 @@ import 'package:package_info_plus/package_info_plus.dart';
|
|||
import 'package:twonly/core/bridge/wrapper/key_manager.dart';
|
||||
import 'package:twonly/globals.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/constants/secure_storage.keys.dart';
|
||||
import 'package:twonly/src/database/twonly.db.dart';
|
||||
import 'package:twonly/src/model/protobuf/api/websocket/client_to_server.pbserver.dart';
|
||||
import 'package:twonly/src/model/protobuf/api/websocket/error.pb.dart';
|
||||
import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart'
|
||||
as server;
|
||||
import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart' as server;
|
||||
import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pbserver.dart';
|
||||
import 'package:twonly/src/services/api/client2client/user_discovery.c2c.dart';
|
||||
import 'package:twonly/src/services/api/mediafiles/download.api.dart';
|
||||
|
|
@ -67,15 +65,13 @@ class ApiService {
|
|||
Stream<SubscriptionPlan> get onPlanUpdated => _planUpdateController.stream;
|
||||
|
||||
final _connectionStateController = StreamController<bool>.broadcast();
|
||||
Stream<bool> get onConnectionStateUpdated =>
|
||||
_connectionStateController.stream;
|
||||
Stream<bool> get onConnectionStateUpdated => _connectionStateController.stream;
|
||||
|
||||
final _appOutdatedController = StreamController<void>.broadcast();
|
||||
Stream<void> get onAppOutdated => _appOutdatedController.stream;
|
||||
|
||||
final _newDeviceRegisteredController = StreamController<void>.broadcast();
|
||||
Stream<void> get onNewDeviceRegistered =>
|
||||
_newDeviceRegisteredController.stream;
|
||||
Stream<void> get onNewDeviceRegistered => _newDeviceRegisteredController.stream;
|
||||
|
||||
bool appIsOutdated = false;
|
||||
bool isAuthenticated = false;
|
||||
|
|
@ -84,8 +80,7 @@ class ApiService {
|
|||
Timer? reconnectionTimer;
|
||||
int _reconnectionDelay = 5;
|
||||
|
||||
final HashMap<Int64, Completer<server.ServerToClient?>> _pendingRequests =
|
||||
HashMap();
|
||||
final HashMap<Int64, Completer<server.ServerToClient?>> _pendingRequests = HashMap();
|
||||
IOWebSocketChannel? _channel;
|
||||
// ignore: cancel_subscriptions
|
||||
StreamSubscription<List<ConnectivityResult>>? _connectivitySubscription;
|
||||
|
|
@ -97,12 +92,20 @@ class ApiService {
|
|||
Uri.parse(apiUrl),
|
||||
pingInterval: const Duration(seconds: 30),
|
||||
);
|
||||
|
||||
try {
|
||||
await channel.ready.timeout(const Duration(seconds: 10));
|
||||
} catch (e) {
|
||||
channel.sink.close().ignore();
|
||||
rethrow;
|
||||
}
|
||||
|
||||
_channel = channel;
|
||||
_channel!.stream.listen(_onData, onDone: _onDone, onError: _onError);
|
||||
await _channel!.ready;
|
||||
Log.info('websocket connected to $apiUrl');
|
||||
return true;
|
||||
} catch (_) {
|
||||
} catch (e) {
|
||||
_channel = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -149,6 +152,7 @@ class ApiService {
|
|||
}
|
||||
|
||||
Future<void> onClosed() async {
|
||||
if (_channel == null) return;
|
||||
Log.info('websocket connection closed');
|
||||
_channel = null;
|
||||
isAuthenticated = false;
|
||||
|
|
@ -180,15 +184,19 @@ class ApiService {
|
|||
_reconnectionDelay = 3;
|
||||
}
|
||||
|
||||
Future<void> close(Function callback) async {
|
||||
Future<void> close(Function? callback) async {
|
||||
Log.info('closing websocket connection');
|
||||
if (_channel != null) {
|
||||
await _channel!.sink.close();
|
||||
try {
|
||||
await _channel!.sink.close().timeout(const Duration(seconds: 2));
|
||||
} catch (e) {
|
||||
Log.warn('Timeout or error closing websocket: $e');
|
||||
}
|
||||
await onClosed();
|
||||
callback();
|
||||
callback?.call();
|
||||
return;
|
||||
}
|
||||
callback();
|
||||
callback?.call();
|
||||
}
|
||||
|
||||
Future<void> listenToNetworkChanges() async {
|
||||
|
|
@ -246,7 +254,10 @@ class ApiService {
|
|||
|
||||
Future<void> _onData(dynamic msgBuffer) async {
|
||||
try {
|
||||
final msg = server.ServerToClient.fromBuffer(msgBuffer as Uint8List);
|
||||
if (msgBuffer is! Uint8List) {
|
||||
msgBuffer = Uint8List.fromList(msgBuffer as List<int>);
|
||||
}
|
||||
final msg = server.ServerToClient.fromBuffer(msgBuffer);
|
||||
if (msg.v0.hasResponse()) {
|
||||
final completer = _pendingRequests.remove(msg.v0.seq);
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
|
|
@ -407,9 +418,7 @@ class ApiService {
|
|||
}
|
||||
if (res.error == ErrorCode.UserIdNotFound && contactId != null) {
|
||||
Log.warn('Contact deleted their account $contactId.');
|
||||
final contact = await twonlyDB.contactsDao
|
||||
.getContactByUserId(contactId)
|
||||
.getSingleOrNull();
|
||||
final contact = await twonlyDB.contactsDao.getContactByUserId(contactId).getSingleOrNull();
|
||||
if (contact != null) {
|
||||
await twonlyDB.contactsDao.updateContact(
|
||||
contactId,
|
||||
|
|
@ -426,7 +435,7 @@ class ApiService {
|
|||
|
||||
Future<bool> tryAuthenticateWithToken() async {
|
||||
final apiAuthToken = await SecureStorage.instance.read(
|
||||
key: SecureStorageKeys.apiAuthToken,
|
||||
key: 'api_auth_token',
|
||||
);
|
||||
|
||||
if (apiAuthToken != null) {
|
||||
|
|
@ -464,7 +473,7 @@ class ApiService {
|
|||
Log.info('Switch was successfully.');
|
||||
await UserService.update((u) => u.canUseLoginTokenForAuth = true);
|
||||
await SecureStorage.instance.delete(
|
||||
key: SecureStorageKeys.apiAuthToken,
|
||||
key: 'api_auth_token',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -474,8 +483,7 @@ class ApiService {
|
|||
return true;
|
||||
}
|
||||
if (result.isError) {
|
||||
if (result.error != ErrorCode.AuthTokenNotValid &&
|
||||
result.error != ErrorCode.ForegroundSessionConnected) {
|
||||
if (result.error != ErrorCode.AuthTokenNotValid && result.error != ErrorCode.ForegroundSessionConnected) {
|
||||
Log.error(
|
||||
'got error while authenticating to the server: ${result.error}',
|
||||
);
|
||||
|
|
@ -513,8 +521,7 @@ class ApiService {
|
|||
return true;
|
||||
}
|
||||
if (result.isError) {
|
||||
if (result.error != ErrorCode.AuthTokenNotValid &&
|
||||
result.error != ErrorCode.ForegroundSessionConnected) {
|
||||
if (result.error != ErrorCode.AuthTokenNotValid && result.error != ErrorCode.ForegroundSessionConnected) {
|
||||
Log.error(
|
||||
'got error while authenticating to the server: ${result.error}',
|
||||
);
|
||||
|
|
@ -546,8 +553,7 @@ class ApiService {
|
|||
return;
|
||||
}
|
||||
|
||||
final handshake = Handshake()
|
||||
..getAuthChallenge = Handshake_GetAuthChallenge();
|
||||
final handshake = Handshake()..getAuthChallenge = Handshake_GetAuthChallenge();
|
||||
final req = createClientToServerFromHandshake(handshake);
|
||||
|
||||
final result = await sendRequestSync(req, authenticated: false);
|
||||
|
|
@ -586,7 +592,7 @@ class ApiService {
|
|||
final apiAuthTokenB64 = base64Encode(apiAuthToken);
|
||||
|
||||
await SecureStorage.instance.write(
|
||||
key: SecureStorageKeys.apiAuthToken,
|
||||
key: 'api_auth_token',
|
||||
value: apiAuthTokenB64,
|
||||
);
|
||||
|
||||
|
|
@ -612,9 +618,7 @@ class ApiService {
|
|||
|
||||
final register = Handshake_Register()
|
||||
..username = username
|
||||
..publicIdentityKey = (await signalStore.getIdentityKeyPair())
|
||||
.getPublicKey()
|
||||
.serialize()
|
||||
..publicIdentityKey = (await signalStore.getIdentityKeyPair()).getPublicKey().serialize()
|
||||
..registrationId = Int64(signalIdentity.registrationId)
|
||||
..signedPrekey = signedPreKey.getKeyPair().publicKey.serialize()
|
||||
..signedPrekeySignature = signedPreKey.signature
|
||||
|
|
|
|||
|
|
@ -10,9 +10,10 @@ Future<void> handleAdditionalDataMessage(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_AdditionalDataMessage message,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info(
|
||||
'Got a additional data message: ${message.senderMessageId} from $groupId',
|
||||
'[$receiptId] Got a additional data message: ${message.senderMessageId} from $groupId',
|
||||
);
|
||||
|
||||
// Prevent message overwrite: reject if a message with this ID already
|
||||
|
|
@ -22,7 +23,7 @@ Future<void> handleAdditionalDataMessage(
|
|||
.getSingleOrNull();
|
||||
if (existing != null && existing.senderId != fromUserId) {
|
||||
Log.warn(
|
||||
'$fromUserId tried to overwrite message from ${existing.senderId}. Dropping.',
|
||||
'[$receiptId] $fromUserId tried to overwrite message from ${existing.senderId}. Dropping.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -45,6 +46,6 @@ Future<void> handleAdditionalDataMessage(
|
|||
fromTimestamp(message.timestamp),
|
||||
);
|
||||
if (msg != null) {
|
||||
Log.info('Inserted a new text message with ID: ${msg.messageId}');
|
||||
Log.info('[$receiptId] Inserted a new text message with ID: ${msg.messageId}');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,6 @@ Future<bool> handleNewContactRequest(int fromUserId) async {
|
|||
await handleContactAccept(fromUserId);
|
||||
}
|
||||
|
||||
// contact was already accepted, so just accept the request in the background.
|
||||
await sendCipherText(
|
||||
contact.userId,
|
||||
EncryptedContent(
|
||||
|
|
@ -36,6 +35,7 @@ Future<bool> handleNewContactRequest(int fromUserId) async {
|
|||
type: EncryptedContent_ContactRequest_Type.ACCEPT,
|
||||
),
|
||||
),
|
||||
blocking: false,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -88,16 +88,17 @@ Future<void> handleContactAccept(int fromUserId) async {
|
|||
Future<bool> handleContactRequest(
|
||||
int fromUserId,
|
||||
EncryptedContent_ContactRequest contactRequest,
|
||||
String receiptId,
|
||||
) async {
|
||||
switch (contactRequest.type) {
|
||||
case EncryptedContent_ContactRequest_Type.REQUEST:
|
||||
Log.info('Got a contact request from $fromUserId');
|
||||
Log.info('[$receiptId] Got a contact request from $fromUserId');
|
||||
return handleNewContactRequest(fromUserId);
|
||||
case EncryptedContent_ContactRequest_Type.ACCEPT:
|
||||
Log.info('Got a contact accept from $fromUserId');
|
||||
Log.info('[$receiptId] Got a contact accept from $fromUserId');
|
||||
await handleContactAccept(fromUserId);
|
||||
case EncryptedContent_ContactRequest_Type.REJECT:
|
||||
Log.info('Got a contact reject from $fromUserId');
|
||||
Log.info('[$receiptId] Got a contact reject from $fromUserId');
|
||||
await twonlyDB.contactsDao.updateContact(
|
||||
fromUserId,
|
||||
const ContactsCompanion(
|
||||
|
|
@ -114,14 +115,15 @@ Future<void> handleContactUpdate(
|
|||
int fromUserId,
|
||||
EncryptedContent_ContactUpdate contactUpdate,
|
||||
int? senderProfileCounter,
|
||||
String receiptId,
|
||||
) async {
|
||||
switch (contactUpdate.type) {
|
||||
case EncryptedContent_ContactUpdate_Type.REQUEST:
|
||||
Log.info('Got a contact update request from $fromUserId');
|
||||
Log.info('[$receiptId] Got a contact update request from $fromUserId');
|
||||
await sendContactMyProfileData(fromUserId);
|
||||
|
||||
case EncryptedContent_ContactUpdate_Type.UPDATE:
|
||||
Log.info('Got a contact update $fromUserId');
|
||||
Log.info('[$receiptId] Got a contact update $fromUserId');
|
||||
Uint8List? avatarSvgCompressed;
|
||||
if (contactUpdate.hasAvatarSvgCompressed()) {
|
||||
avatarSvgCompressed = Uint8List.fromList(
|
||||
|
|
@ -188,8 +190,9 @@ Future<void> handleContactUpdate(
|
|||
Future<void> handleFlameSync(
|
||||
String groupId,
|
||||
EncryptedContent_FlameSync flameSync,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info('Got a flameSync for group $groupId');
|
||||
Log.info('[$receiptId] Got a flameSync for group $groupId');
|
||||
|
||||
final group = await twonlyDB.groupsDao.getGroup(groupId);
|
||||
if (group == null || group.lastFlameCounterChange == null) return;
|
||||
|
|
@ -235,6 +238,7 @@ Future<int?> checkForProfileUpdate(
|
|||
type: EncryptedContent_ContactUpdate_Type.REQUEST,
|
||||
),
|
||||
),
|
||||
blocking: false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,9 @@ import 'package:twonly/src/utils/log.dart';
|
|||
Future<void> handleErrorMessage(
|
||||
int fromUserId,
|
||||
EncryptedContent_ErrorMessages error,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.error('Got error from $fromUserId: $error');
|
||||
Log.error('[$receiptId] Got error from $fromUserId: $error');
|
||||
|
||||
switch (error.type) {
|
||||
case EncryptedContent_ErrorMessages_Type
|
||||
|
|
|
|||
|
|
@ -15,14 +15,13 @@ Future<void> handleGroupCreate(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_GroupCreate newGroup,
|
||||
String receiptId,
|
||||
) async {
|
||||
final user = await twonlyDB.contactsDao
|
||||
.getContactByUserId(fromUserId)
|
||||
.getSingleOrNull();
|
||||
final user = await twonlyDB.contactsDao.getContactByUserId(fromUserId).getSingleOrNull();
|
||||
if (user == null) {
|
||||
// Only contacts can invite other contacts, so this can (via the UI) not happen.
|
||||
Log.error(
|
||||
'User is not a contact. Aborting.',
|
||||
'[$receiptId] User is not a contact. Aborting.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -66,7 +65,7 @@ Future<void> handleGroupCreate(
|
|||
|
||||
if (group == null) {
|
||||
Log.error(
|
||||
'Could not create new group. Probably because the group already existed.',
|
||||
'[$receiptId] Could not create new group. Probably because the group already existed.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -108,12 +107,13 @@ Future<void> handleGroupUpdate(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_GroupUpdate update,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info('Got group update for $groupId from $fromUserId');
|
||||
Log.info('[$receiptId] Got group update for $groupId from $fromUserId');
|
||||
|
||||
final actionType = groupActionTypeFromString(update.groupActionType);
|
||||
if (actionType == null) {
|
||||
Log.error('Group action ${update.groupActionType} is unknown ignoring.');
|
||||
Log.error('[$receiptId] Group action ${update.groupActionType} is unknown ignoring.');
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -189,10 +189,11 @@ Future<bool> handleGroupJoin(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_GroupJoin join,
|
||||
String receiptId,
|
||||
) async {
|
||||
if (await twonlyDB.contactsDao.getContactById(fromUserId) == null) {
|
||||
if (!await addNewHiddenContact(fromUserId)) {
|
||||
Log.error('Got group join, but could not load contact.');
|
||||
Log.error('[$receiptId] Got group join, but could not load contact.');
|
||||
// This can happen in case the group join was received before the group create.
|
||||
// In this case return false, which will cause the receipt to fail and the user
|
||||
// will resend this message.
|
||||
|
|
@ -213,6 +214,7 @@ Future<void> handleResendGroupPublicKey(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_GroupJoin join,
|
||||
String receiptId,
|
||||
) async {
|
||||
final group = await twonlyDB.groupsDao.getGroup(groupId);
|
||||
if (group == null || group.myGroupPrivateKey == null) return;
|
||||
|
|
@ -225,6 +227,7 @@ Future<void> handleResendGroupPublicKey(
|
|||
groupPublicKey: keyPair.getPublicKey().serialize(),
|
||||
),
|
||||
),
|
||||
blocking: false,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -232,6 +235,7 @@ Future<void> handleTypingIndicator(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_TypingIndicator indicator,
|
||||
String receiptId,
|
||||
) async {
|
||||
var lastTypeIndicator = const Value<DateTime?>.absent();
|
||||
|
||||
|
|
|
|||
|
|
@ -18,9 +18,10 @@ Future<void> handleMedia(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_Media media,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info(
|
||||
'Got a media message: ${media.senderMessageId} from $groupId with type ${media.type}',
|
||||
'[$receiptId] Got a media message: ${media.senderMessageId} from $groupId with type ${media.type}',
|
||||
);
|
||||
|
||||
late MediaType mediaType;
|
||||
|
|
@ -33,7 +34,7 @@ Future<void> handleMedia(
|
|||
message.senderId != fromUserId ||
|
||||
message.mediaId == null) {
|
||||
Log.warn(
|
||||
'Got reupload from $fromUserId for a message that either does not exists (${message == null}) or senderId = ${message?.senderId}',
|
||||
'[$receiptId] Got reupload for a message that either does not exists (${message == null}) or senderId = ${message?.senderId}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -82,13 +83,13 @@ Future<void> handleMedia(
|
|||
if (messageTmp != null) {
|
||||
if (messageTmp.senderId != fromUserId) {
|
||||
Log.warn(
|
||||
'$fromUserId tried to modify the message from ${messageTmp.senderId}.',
|
||||
'[$receiptId] $fromUserId tried to modify the message from ${messageTmp.senderId}.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (messageTmp.mediaId == null) {
|
||||
Log.warn(
|
||||
'This message already exit without a mediaId. Message is dropped.',
|
||||
'[$receiptId] This message already exit without a mediaId. Message is dropped.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -97,7 +98,7 @@ Future<void> handleMedia(
|
|||
);
|
||||
if (mediaFile?.downloadState != DownloadState.reuploadRequested) {
|
||||
Log.warn(
|
||||
'This message and media file already exit and was not requested again. Dropping it.',
|
||||
'[$receiptId] This message and media file already exit and was not requested again. Dropping it.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -121,7 +122,9 @@ Future<void> handleMedia(
|
|||
MediaFile? mediaFile;
|
||||
Message? message;
|
||||
|
||||
Log.info('Starting transaction for media message ${media.senderMessageId}');
|
||||
Log.info(
|
||||
'[$receiptId] Starting transaction for media message ${media.senderMessageId}',
|
||||
);
|
||||
await twonlyDB.transaction(() async {
|
||||
mediaFile = await twonlyDB.mediaFilesDao.insertOrUpdateMedia(
|
||||
MediaFilesCompanion(
|
||||
|
|
@ -141,7 +144,7 @@ Future<void> handleMedia(
|
|||
);
|
||||
|
||||
if (mediaFile == null) {
|
||||
Log.error('Could not insert media file into database');
|
||||
Log.error('[$receiptId] Could not insert media file into database');
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -165,7 +168,7 @@ Future<void> handleMedia(
|
|||
);
|
||||
});
|
||||
Log.info(
|
||||
'Finished transaction for media message ${media.senderMessageId}. Success: ${message != null}',
|
||||
'[$receiptId] Finished transaction for media message ${media.senderMessageId}. Success: ${message != null}',
|
||||
);
|
||||
|
||||
if (message != null && mediaFile != null) {
|
||||
|
|
@ -173,7 +176,9 @@ Future<void> handleMedia(
|
|||
groupId,
|
||||
fromTimestamp(media.timestamp),
|
||||
);
|
||||
Log.info('Inserted a new media message with ID: ${message!.messageId}');
|
||||
Log.info(
|
||||
'[$receiptId] Inserted a new media message with ID: ${message!.messageId}',
|
||||
);
|
||||
await incFlameCounter(
|
||||
message!.groupId,
|
||||
true,
|
||||
|
|
@ -184,12 +189,16 @@ Future<void> handleMedia(
|
|||
} else {
|
||||
if (mediaFile == null && message == null) {
|
||||
Log.error(
|
||||
'Could not insert new message as both the message and mediaFile are empty.',
|
||||
'[$receiptId] Could not insert new message as both the message and mediaFile are empty.',
|
||||
);
|
||||
} else if (mediaFile == null) {
|
||||
Log.error('Could not insert new message as the mediaFile is empty.');
|
||||
Log.error(
|
||||
'[$receiptId] Could not insert new message as the mediaFile is empty.',
|
||||
);
|
||||
} else {
|
||||
Log.error('Could not insert new message as the message is empty.');
|
||||
Log.error(
|
||||
'[$receiptId] Could not insert new message as the message is empty.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -197,6 +206,7 @@ Future<void> handleMedia(
|
|||
Future<void> handleMediaUpdate(
|
||||
int fromUserId,
|
||||
EncryptedContent_MediaUpdate mediaUpdate,
|
||||
String receiptId,
|
||||
) async {
|
||||
final message = await twonlyDB.messagesDao
|
||||
.getMessageById(mediaUpdate.targetMessageId)
|
||||
|
|
@ -204,14 +214,14 @@ Future<void> handleMediaUpdate(
|
|||
if (message == null) {
|
||||
// this can happen, in case the message was already deleted.
|
||||
Log.info(
|
||||
'Got media update to message ${mediaUpdate.targetMessageId} but message not found.',
|
||||
'[$receiptId] Got media update to message ${mediaUpdate.targetMessageId} but message not found.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message.mediaId == null) {
|
||||
// this can happen, in case the message was already deleted.
|
||||
Log.warn(
|
||||
'Got media update for message ${mediaUpdate.targetMessageId} which does not have a mediaId defined.',
|
||||
'[$receiptId] Got media update for message ${mediaUpdate.targetMessageId} which does not have a mediaId defined.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -220,14 +230,14 @@ Future<void> handleMediaUpdate(
|
|||
);
|
||||
if (mediaFile == null) {
|
||||
Log.info(
|
||||
'Got media file update, but media file was not found ${message.mediaId}',
|
||||
'[$receiptId] Got media file update, but media file was not found ${message.mediaId}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (mediaUpdate.type) {
|
||||
case EncryptedContent_MediaUpdate_Type.REOPENED:
|
||||
Log.info('Got media file reopened ${mediaFile.mediaId}');
|
||||
Log.info('[$receiptId] Got media file reopened ${mediaFile.mediaId}');
|
||||
await twonlyDB.messagesDao.updateMessageId(
|
||||
message.messageId,
|
||||
const MessagesCompanion(
|
||||
|
|
@ -235,7 +245,7 @@ Future<void> handleMediaUpdate(
|
|||
),
|
||||
);
|
||||
case EncryptedContent_MediaUpdate_Type.STORED:
|
||||
Log.info('Got media file stored ${mediaFile.mediaId}');
|
||||
Log.info('[$receiptId] Got media file stored ${mediaFile.mediaId}');
|
||||
final mediaService = MediaFileService(mediaFile);
|
||||
await mediaService.storeMediaFile();
|
||||
await twonlyDB.messagesDao.updateMessageId(
|
||||
|
|
@ -246,7 +256,9 @@ Future<void> handleMediaUpdate(
|
|||
);
|
||||
|
||||
case EncryptedContent_MediaUpdate_Type.DECRYPTION_ERROR:
|
||||
Log.info('Got media file decryption error ${mediaFile.mediaId}');
|
||||
Log.info(
|
||||
'[$receiptId] Got media file decryption error ${mediaFile.mediaId}',
|
||||
);
|
||||
await reuploadMediaFile(fromUserId, mediaFile, message.messageId);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import 'package:drift/drift.dart' show Value;
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/model/protobuf/client/generated/messages.pb.dart';
|
||||
import 'package:twonly/src/services/api/utils.api.dart';
|
||||
|
|
@ -6,26 +7,27 @@ import 'package:twonly/src/utils/log.dart';
|
|||
Future<void> handleMessageUpdate(
|
||||
int contactId,
|
||||
EncryptedContent_MessageUpdate messageUpdate,
|
||||
String receiptId,
|
||||
) async {
|
||||
switch (messageUpdate.type) {
|
||||
case EncryptedContent_MessageUpdate_Type.OPENED:
|
||||
Log.info(
|
||||
'Opened message ${messageUpdate.multipleTargetMessageIds}',
|
||||
'[$receiptId] Opened message ${messageUpdate.multipleTargetMessageIds}',
|
||||
);
|
||||
try {
|
||||
await twonlyDB.messagesDao.handleMessagesOpened(
|
||||
contactId,
|
||||
Value(contactId),
|
||||
messageUpdate.multipleTargetMessageIds,
|
||||
fromTimestamp(messageUpdate.timestamp),
|
||||
);
|
||||
} catch (e) {
|
||||
Log.warn(e);
|
||||
Log.warn('[$receiptId] Error handling messages opened: $e');
|
||||
}
|
||||
case EncryptedContent_MessageUpdate_Type.DELETE:
|
||||
if (!await isSender(contactId, messageUpdate.senderMessageId)) {
|
||||
if (!await isSender(contactId, messageUpdate.senderMessageId, receiptId)) {
|
||||
return;
|
||||
}
|
||||
Log.info('Delete message ${messageUpdate.senderMessageId}');
|
||||
Log.info('[$receiptId] Delete message ${messageUpdate.senderMessageId}');
|
||||
try {
|
||||
await twonlyDB.messagesDao.handleMessageDeletion(
|
||||
contactId,
|
||||
|
|
@ -33,13 +35,13 @@ Future<void> handleMessageUpdate(
|
|||
fromTimestamp(messageUpdate.timestamp),
|
||||
);
|
||||
} catch (e) {
|
||||
Log.warn(e);
|
||||
Log.warn('[$receiptId] Error handling message deletion: $e');
|
||||
}
|
||||
case EncryptedContent_MessageUpdate_Type.EDIT_TEXT:
|
||||
if (!await isSender(contactId, messageUpdate.senderMessageId)) {
|
||||
if (!await isSender(contactId, messageUpdate.senderMessageId, receiptId)) {
|
||||
return;
|
||||
}
|
||||
Log.info('Edit message ${messageUpdate.senderMessageId}');
|
||||
Log.info('[$receiptId] Edit message ${messageUpdate.senderMessageId}');
|
||||
try {
|
||||
await twonlyDB.messagesDao.handleTextEdit(
|
||||
contactId,
|
||||
|
|
@ -48,12 +50,12 @@ Future<void> handleMessageUpdate(
|
|||
fromTimestamp(messageUpdate.timestamp),
|
||||
);
|
||||
} catch (e) {
|
||||
Log.warn(e);
|
||||
Log.warn('[$receiptId] Error handling text edit: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> isSender(int fromUserId, String messageId) async {
|
||||
Future<bool> isSender(int fromUserId, String messageId, String receiptId) async {
|
||||
final message = await twonlyDB.messagesDao
|
||||
.getMessageById(messageId)
|
||||
.getSingleOrNull();
|
||||
|
|
@ -61,6 +63,6 @@ Future<bool> isSender(int fromUserId, String messageId) async {
|
|||
if (message.senderId == fromUserId) {
|
||||
return true;
|
||||
}
|
||||
Log.error('Contact $fromUserId tried to modify the message $messageId');
|
||||
Log.error('[$receiptId] Contact $fromUserId tried to modify the message $messageId');
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,10 +10,11 @@ DateTime lastPushKeyRequest = clock.now().subtract(const Duration(hours: 1));
|
|||
Future<void> handlePushKey(
|
||||
int contactId,
|
||||
EncryptedContent_PushKeys pushKeys,
|
||||
String receiptId,
|
||||
) async {
|
||||
switch (pushKeys.type) {
|
||||
case EncryptedContent_PushKeys_Type.REQUEST:
|
||||
Log.info('Got a pushkey request from $contactId');
|
||||
Log.info('[$receiptId] Got a pushkey request from $contactId');
|
||||
if (lastPushKeyRequest.isBefore(
|
||||
clock.now().subtract(const Duration(seconds: 60)),
|
||||
)) {
|
||||
|
|
@ -22,7 +23,7 @@ Future<void> handlePushKey(
|
|||
}
|
||||
|
||||
case EncryptedContent_PushKeys_Type.UPDATE:
|
||||
Log.info('Got a pushkey update from $contactId');
|
||||
Log.info('[$receiptId] Got a pushkey update from $contactId');
|
||||
await handleNewPushKey(contactId, pushKeys.keyId.toInt(), pushKeys.key);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,12 @@ Future<void> handleReaction(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_Reaction reaction,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info('Got a reaction from $fromUserId (remove=${reaction.remove})');
|
||||
Log.info(
|
||||
'[$receiptId] Got a reaction from for ${reaction.targetMessageId} (remove=${reaction.remove})',
|
||||
);
|
||||
|
||||
await twonlyDB.reactionsDao.updateReaction(
|
||||
fromUserId,
|
||||
reaction.targetMessageId,
|
||||
|
|
|
|||
|
|
@ -11,9 +11,10 @@ Future<void> handleTextMessage(
|
|||
int fromUserId,
|
||||
String groupId,
|
||||
EncryptedContent_TextMessage textMessage,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info(
|
||||
'Got a text message: ${textMessage.senderMessageId} from $groupId',
|
||||
'[$receiptId] Got a text message: ${textMessage.senderMessageId} from $groupId',
|
||||
);
|
||||
|
||||
// Prevent message overwrite: reject if a message with this ID already
|
||||
|
|
@ -23,7 +24,7 @@ Future<void> handleTextMessage(
|
|||
.getSingleOrNull();
|
||||
if (existing != null && existing.senderId != fromUserId) {
|
||||
Log.warn(
|
||||
'$fromUserId tried to overwrite message from ${existing.senderId}. Dropping.',
|
||||
'[$receiptId] $fromUserId tried to overwrite message from ${existing.senderId}. Dropping.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -47,6 +48,6 @@ Future<void> handleTextMessage(
|
|||
fromTimestamp(textMessage.timestamp),
|
||||
);
|
||||
if (message != null) {
|
||||
Log.info('Inserted a new text message with ID: ${message.messageId}');
|
||||
Log.info('[$receiptId] Inserted a new text message with ID: ${message.messageId}');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,9 @@ void resetUserDiscoveryRequestUpdates() {
|
|||
Future<void> checkForUserDiscoveryChanges(
|
||||
int fromUserId,
|
||||
List<int> receivedVersion,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info('[$receiptId] Checking for a new user discovery version.');
|
||||
final currentVersion = await UserDiscoveryService.shouldRequestNewMessages(
|
||||
fromUserId,
|
||||
receivedVersion,
|
||||
|
|
@ -26,7 +28,7 @@ Future<void> checkForUserDiscoveryChanges(
|
|||
// Only request a new version once per app session
|
||||
return;
|
||||
}
|
||||
Log.info('Having old version from contact. Requesting new version.');
|
||||
Log.info('[$receiptId] Having old version from contact. Requesting new version.');
|
||||
_requestedUpdates.add(fromUserId);
|
||||
await sendCipherText(
|
||||
fromUserId,
|
||||
|
|
@ -35,6 +37,7 @@ Future<void> checkForUserDiscoveryChanges(
|
|||
currentVersion: currentVersion.toList(),
|
||||
),
|
||||
),
|
||||
blocking: false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -42,18 +45,19 @@ Future<void> checkForUserDiscoveryChanges(
|
|||
Future<void> handleUserDiscoveryRequest(
|
||||
int fromUserId,
|
||||
EncryptedContent_UserDiscoveryRequest request,
|
||||
String receiptId,
|
||||
) async {
|
||||
Log.info('Got a user discovery request');
|
||||
Log.info('[$receiptId] Got a user discovery request');
|
||||
|
||||
if (!userService.currentUser.isUserDiscoveryEnabled) {
|
||||
Log.warn('Got a user discovery request while it is disabled');
|
||||
Log.warn('[$receiptId] Got a user discovery request while it is disabled');
|
||||
return;
|
||||
}
|
||||
final contact = await twonlyDB.contactsDao.getContactById(fromUserId);
|
||||
|
||||
if (!UserDiscoveryService.isContactAllowed(contact)) {
|
||||
Log.warn(
|
||||
'Got a request to update user discovery, but mediaSendCounter (${contact?.mediaSendCounter}) < ${userService.currentUser.requiredSendImages} or user is excluded ${contact?.userDiscoveryExcluded}',
|
||||
'[$receiptId] Got a request to update user discovery, but mediaSendCounter (${contact?.mediaSendCounter}) < ${userService.currentUser.requiredSendImages} or user is excluded ${contact?.userDiscoveryExcluded}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -63,7 +67,7 @@ Future<void> handleUserDiscoveryRequest(
|
|||
request.currentVersion,
|
||||
);
|
||||
if (newMessages != null && newMessages.isNotEmpty) {
|
||||
Log.info('Sending ${newMessages.length} user discovery messages');
|
||||
Log.info('[$receiptId] Sending ${newMessages.length} user discovery messages');
|
||||
await sendCipherText(
|
||||
fromUserId,
|
||||
EncryptedContent(
|
||||
|
|
@ -71,21 +75,23 @@ Future<void> handleUserDiscoveryRequest(
|
|||
messages: newMessages,
|
||||
),
|
||||
),
|
||||
blocking: false,
|
||||
);
|
||||
} else {
|
||||
Log.info('Got update request, but there are no new updates for the user');
|
||||
Log.info('[$receiptId] Got update request, but there are no new updates for the user');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> handleUserDiscoveryUpdate(
|
||||
int fromUserId,
|
||||
EncryptedContent_UserDiscoveryUpdate update,
|
||||
String receiptId,
|
||||
) async {
|
||||
if (!userService.currentUser.isUserDiscoveryEnabled) {
|
||||
Log.warn('Got a user discovery update while it is disabled');
|
||||
Log.warn('[$receiptId] Got a user discovery update while it is disabled');
|
||||
return;
|
||||
}
|
||||
Log.info('Got ${update.messages.length} user discovery messages');
|
||||
Log.info('[$receiptId] Got ${update.messages.length} user discovery messages');
|
||||
await UserDiscoveryService.handleNewMessages(
|
||||
fromUserId,
|
||||
update.messages.map(Uint8List.fromList).toList(),
|
||||
|
|
|
|||
|
|
@ -35,7 +35,6 @@ Future<void> _protectMediaUpload(
|
|||
) async {
|
||||
final mutex = _uploadMutexes.putIfAbsent(mediaId, Mutex.new);
|
||||
await mutex.protect(action);
|
||||
_uploadMutexes.remove(mediaId);
|
||||
}
|
||||
|
||||
Future<void> reuploadMediaFiles() async {
|
||||
|
|
@ -52,7 +51,7 @@ Future<void> reuploadMediaFiles() async {
|
|||
|
||||
final contacts = <int, Contact>{};
|
||||
|
||||
for (var receipt in receipts) {
|
||||
for (final receipt in receipts) {
|
||||
if (receipt.retryCount > 1 && receipt.lastRetry != null) {
|
||||
final twentyFourHoursAgo = DateTime.now().subtract(
|
||||
const Duration(hours: 6),
|
||||
|
|
@ -65,20 +64,6 @@ Future<void> reuploadMediaFiles() async {
|
|||
}
|
||||
}
|
||||
|
||||
if (receipt.retryCount >= 2) {
|
||||
// After two retries, change the receiptId. This addresses a bug where the receiver received the message and marked it as received, but the app was closed before the message was fully processed. Because the receipt was already stored, subsequent retries were detected as duplicates and rejected.
|
||||
final oldReceiptId = receipt.receiptId;
|
||||
final updatedReceipt = await twonlyDB.receiptsDao.rotateReceiptId(
|
||||
oldReceiptId,
|
||||
);
|
||||
if (updatedReceipt == null) continue;
|
||||
|
||||
Log.info(
|
||||
'Changed receiptId $oldReceiptId to ${updatedReceipt.receiptId} as retryCount is ${receipt.retryCount}',
|
||||
);
|
||||
receipt = updatedReceipt;
|
||||
}
|
||||
|
||||
var messageId = receipt.messageId;
|
||||
if (receipt.messageId == null) {
|
||||
Log.info('Message not in receipt. Loading it from the content.');
|
||||
|
|
@ -414,6 +399,9 @@ Future<void> insertMediaFileInMessagesTable(
|
|||
);
|
||||
await twonlyDB.groupsDao.increaseLastMessageExchange(groupId, clock.now());
|
||||
if (message != null) {
|
||||
Log.info(
|
||||
'Created message ${message.messageId} for media ${message.mediaId}',
|
||||
);
|
||||
// de-archive contact when sending a new message
|
||||
await twonlyDB.groupsDao.updateGroup(
|
||||
message.groupId,
|
||||
|
|
@ -445,6 +433,10 @@ Future<void> _startBackgroundMediaUploadInternal(
|
|||
|
||||
if (mediaService.mediaFile.uploadState == UploadState.initialized ||
|
||||
mediaService.mediaFile.uploadState == UploadState.preprocessing) {
|
||||
Log.info(
|
||||
'Hanlding media file ${mediaService.mediaFile.mediaId} in ${mediaService.mediaFile.uploadState}',
|
||||
);
|
||||
|
||||
await mediaService.setUploadState(UploadState.preprocessing);
|
||||
|
||||
if (!mediaService.tempPath.existsSync()) {
|
||||
|
|
|
|||
|
|
@ -61,6 +61,8 @@ Future<void> retransmitAllMessages() async {
|
|||
});
|
||||
}
|
||||
|
||||
final Map<String, Mutex> _tryToSendLocks = {};
|
||||
|
||||
// When the ackByServerAt is set this value is written in the receipted
|
||||
Future<(Uint8List, Uint8List?)?> tryToSendCompleteMessage({
|
||||
String? receiptId,
|
||||
|
|
@ -68,15 +70,41 @@ Future<(Uint8List, Uint8List?)?> tryToSendCompleteMessage({
|
|||
bool onlyReturnEncryptedData = false,
|
||||
bool blocking = true,
|
||||
}) async {
|
||||
final rId = receiptId ?? receipt?.receiptId;
|
||||
if (rId == null) {
|
||||
Log.error(
|
||||
'Cannot try to send complete message as both receiptId and receipt are null.',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
final mutex = _tryToSendLocks.putIfAbsent(rId, Mutex.new);
|
||||
return mutex.protect(() async {
|
||||
return _tryToSendCompleteMessageInternal(
|
||||
receiptId: receiptId,
|
||||
receipt: receipt,
|
||||
onlyReturnEncryptedData: onlyReturnEncryptedData,
|
||||
blocking: blocking,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<(Uint8List, Uint8List?)?> _tryToSendCompleteMessageInternal({
|
||||
String? receiptId,
|
||||
Receipt? receipt,
|
||||
bool onlyReturnEncryptedData = false,
|
||||
bool blocking = true,
|
||||
}) async {
|
||||
// this should have a lock for every receiptID, split the function into a _internal withou the lock and a normal with the lock
|
||||
if (apiService.appIsOutdated) return null;
|
||||
if (receiptId == null && receipt == null) return null;
|
||||
|
||||
try {
|
||||
if (receiptId == null && receipt == null) return null;
|
||||
if (receipt == null) {
|
||||
// ignore: parameter_assignments
|
||||
receipt = await twonlyDB.receiptsDao.getReceiptById(receiptId!);
|
||||
if (receipt == null) {
|
||||
Log.warn('Receipt not found.');
|
||||
Log.warn('[$receiptId] Receipt not found.');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -120,8 +148,6 @@ Future<(Uint8List, Uint8List?)?> tryToSendCompleteMessage({
|
|||
message.encryptedContent,
|
||||
);
|
||||
|
||||
Log.info('Uploading ${receipt.receiptId}.');
|
||||
|
||||
Uint8List? pushData;
|
||||
if (receipt.retryCount == 0) {
|
||||
final pushNotification = await getPushNotificationFromEncryptedContent(
|
||||
|
|
@ -166,9 +192,12 @@ Future<(Uint8List, Uint8List?)?> tryToSendCompleteMessage({
|
|||
}
|
||||
|
||||
if (onlyReturnEncryptedData) {
|
||||
Log.info('Returning message with receiptID ${receipt.receiptId}.');
|
||||
return (message.writeToBuffer(), pushData);
|
||||
}
|
||||
|
||||
Log.info('Uploading message with receiptID ${receipt.receiptId}.');
|
||||
|
||||
final resp = await apiService.sendTextMessage(
|
||||
receipt.contactId,
|
||||
message.writeToBuffer(),
|
||||
|
|
@ -176,7 +205,7 @@ Future<(Uint8List, Uint8List?)?> tryToSendCompleteMessage({
|
|||
);
|
||||
|
||||
if (resp.isError) {
|
||||
Log.warn('Could not transmit message got ${resp.error}.');
|
||||
Log.warn('Could not transmit ${receipt.receiptId} got ${resp.error}.');
|
||||
if (resp.error == ErrorCode.UserIdNotFound) {
|
||||
await twonlyDB.receiptsDao.deleteReceipt(receipt.receiptId);
|
||||
await twonlyDB.contactsDao.updateContact(
|
||||
|
|
@ -210,7 +239,7 @@ Future<(Uint8List, Uint8List?)?> tryToSendCompleteMessage({
|
|||
}
|
||||
}
|
||||
} catch (e) {
|
||||
Log.error('Unknown Error when sending message: $e');
|
||||
Log.error('[$receiptId] unknown error when sending message: $e');
|
||||
if (receipt != null) {
|
||||
await twonlyDB.receiptsDao.deleteReceipt(receipt.receiptId);
|
||||
}
|
||||
|
|
@ -316,6 +345,54 @@ Future<void> insertAndSendContactShareMessage(
|
|||
);
|
||||
}
|
||||
|
||||
Future<void> insertAndSendAskAboutUserMessage(
|
||||
int contactId,
|
||||
int askAboutUserId,
|
||||
) async {
|
||||
final directChat = await twonlyDB.groupsDao.createOrGetDirectChat(contactId);
|
||||
if (directChat == null) {
|
||||
Log.error(
|
||||
'Failed to get or create direct chat group for contact $contactId',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final groupId = directChat.groupId;
|
||||
|
||||
final additionalMessageData = AdditionalMessageData(
|
||||
type: AdditionalMessageData_Type.ASK_ABOUT_USER,
|
||||
askAboutUserId: Int64(askAboutUserId),
|
||||
);
|
||||
|
||||
final message = await twonlyDB.messagesDao.insertMessage(
|
||||
MessagesCompanion(
|
||||
groupId: Value(groupId),
|
||||
type: Value(MessageType.askAboutUser.name),
|
||||
additionalMessageData: Value(additionalMessageData.writeToBuffer()),
|
||||
),
|
||||
);
|
||||
|
||||
if (message == null) {
|
||||
Log.error('Could not insert message into database');
|
||||
return;
|
||||
}
|
||||
|
||||
final encryptedContent = pb.EncryptedContent(
|
||||
additionalDataMessage: pb.EncryptedContent_AdditionalDataMessage(
|
||||
senderMessageId: message.messageId,
|
||||
additionalMessageData: additionalMessageData.writeToBuffer(),
|
||||
timestamp: Int64(message.createdAt.millisecondsSinceEpoch),
|
||||
type: MessageType.askAboutUser.name,
|
||||
),
|
||||
);
|
||||
|
||||
await sendCipherTextToGroup(
|
||||
groupId,
|
||||
encryptedContent,
|
||||
messageId: message.messageId,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> sendCipherTextToGroup(
|
||||
String groupId,
|
||||
pb.EncryptedContent encryptedContent, {
|
||||
|
|
@ -409,6 +486,17 @@ Future<(Uint8List, Uint8List?)?> sendCipherText(
|
|||
);
|
||||
|
||||
if (receipt != null) {
|
||||
try {
|
||||
final typeKeys = _getEncryptedContentTypes(encryptedContent);
|
||||
Log.info(
|
||||
'sendCipherText: type=[$typeKeys] messageId=$messageId receiptId=${receipt.receiptId}',
|
||||
);
|
||||
} catch (_) {
|
||||
Log.info(
|
||||
'sendCipherText: messageId=$messageId receiptId=${receipt.receiptId}',
|
||||
);
|
||||
}
|
||||
|
||||
final tmp = tryToSendCompleteMessage(
|
||||
receipt: receipt,
|
||||
onlyReturnEncryptedData: onlyReturnEncryptedData,
|
||||
|
|
@ -492,5 +580,23 @@ Future<void> sendContactMyProfileData(int contactId) async {
|
|||
username: userService.currentUser.username,
|
||||
),
|
||||
);
|
||||
await sendCipherText(contactId, encryptedContent);
|
||||
await sendCipherText(contactId, encryptedContent, blocking: false);
|
||||
}
|
||||
|
||||
String _getEncryptedContentTypes(pb.EncryptedContent content) {
|
||||
final ignoredFields = {
|
||||
'groupId',
|
||||
'isDirectChat',
|
||||
'senderProfileCounter',
|
||||
'senderUserDiscoveryVersion',
|
||||
};
|
||||
|
||||
final types = <String>[];
|
||||
for (final field in content.info_.byName.values) {
|
||||
if (content.hasField(field.tagNumber) &&
|
||||
!ignoredFields.contains(field.name)) {
|
||||
types.add(field.name);
|
||||
}
|
||||
}
|
||||
return types.join(', ');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ Future<void> handleServerMessage(server.ServerToClient msg) async {
|
|||
|
||||
await apiService.sendResponse(ClientToServer()..v0 = v0);
|
||||
AppState.gotMessageFromServer = true;
|
||||
Log.info('Message from server proccessed.');
|
||||
Log.info('All messages from the server proccessed.');
|
||||
}
|
||||
|
||||
DateTime lastPushKeyRequest = clock.now().subtract(const Duration(hours: 1));
|
||||
|
|
@ -86,10 +86,19 @@ Future<void> handleClient2ClientMessage(NewMessage newMessage) async {
|
|||
final receiptId = message.receiptId;
|
||||
|
||||
final mutex = _messageLocks.putIfAbsent(receiptId, Mutex.new);
|
||||
if (mutex.isLocked) {
|
||||
Log.info(
|
||||
'[$receiptId] Skipping — already being processed by another handler',
|
||||
);
|
||||
return;
|
||||
}
|
||||
await mutex.protect(() async {
|
||||
await _handleClient2ClientMessage(newMessage, message);
|
||||
try {
|
||||
await _handleClient2ClientMessage(newMessage, message);
|
||||
} finally {
|
||||
_messageLocks.remove(receiptId);
|
||||
}
|
||||
});
|
||||
_messageLocks.remove(receiptId);
|
||||
}
|
||||
|
||||
Future<void> _handleClient2ClientMessage(
|
||||
|
|
@ -103,11 +112,11 @@ Future<void> _handleClient2ClientMessage(
|
|||
return;
|
||||
}
|
||||
|
||||
Log.info('Started processing message with receiptId $receiptId');
|
||||
Log.info('[$receiptId] Started processing message');
|
||||
|
||||
switch (message.type) {
|
||||
case Message_Type.SENDER_DELIVERY_RECEIPT:
|
||||
Log.info('Got delivery receipt for $receiptId!');
|
||||
Log.info('[$receiptId] Got delivery receipt!');
|
||||
await twonlyDB.receiptsDao.confirmReceipt(receiptId, fromUserId);
|
||||
|
||||
case Message_Type.PLAINTEXT_CONTENT:
|
||||
|
|
@ -120,13 +129,13 @@ Future<void> _handleClient2ClientMessage(
|
|||
await handleSessionResync(fromUserId);
|
||||
}
|
||||
Log.info(
|
||||
'Got decryption error: ${message.plaintextContent.decryptionErrorMessage.type} for $receiptId',
|
||||
'[$receiptId] Got decryption error: ${message.plaintextContent.decryptionErrorMessage.type}',
|
||||
);
|
||||
retry = true;
|
||||
}
|
||||
if (message.plaintextContent.hasRetryControlError()) {
|
||||
Log.info(
|
||||
'Got access control error for $receiptId. Resending message.',
|
||||
'[$receiptId] Got access control error. Resending message.',
|
||||
);
|
||||
retry = true;
|
||||
}
|
||||
|
|
@ -141,7 +150,10 @@ Future<void> _handleClient2ClientMessage(
|
|||
ackByServerAt: const Value(null),
|
||||
),
|
||||
);
|
||||
await tryToSendCompleteMessage(receiptId: newReceiptId);
|
||||
Log.info(
|
||||
'[$receiptId] Sending error message to the original sender with receiptId $newReceiptId.',
|
||||
);
|
||||
await tryToSendCompleteMessage(receiptId: newReceiptId, blocking: false);
|
||||
}
|
||||
|
||||
case Message_Type.CIPHERTEXT:
|
||||
|
|
@ -197,7 +209,6 @@ Future<void> _handleClient2ClientMessage(
|
|||
receiptIdDB = const Value.absent();
|
||||
} else {
|
||||
// Message was successful processed
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -213,9 +224,9 @@ Future<void> _handleClient2ClientMessage(
|
|||
),
|
||||
);
|
||||
} catch (e) {
|
||||
Log.warn(e);
|
||||
Log.warn('[$receiptId] Error inserting receipt: $e');
|
||||
}
|
||||
await tryToSendCompleteMessage(receiptId: receiptId);
|
||||
await tryToSendCompleteMessage(receiptId: receiptId, blocking: false);
|
||||
}
|
||||
case Message_Type.TEST_NOTIFICATION:
|
||||
break;
|
||||
|
|
@ -223,9 +234,9 @@ Future<void> _handleClient2ClientMessage(
|
|||
|
||||
try {
|
||||
await twonlyDB.receiptsDao.gotReceipt(receiptId);
|
||||
Log.info('Got a message with receiptId $receiptId');
|
||||
Log.info('[$receiptId] Finished processing');
|
||||
} catch (e) {
|
||||
Log.error('Error marking message as received $receiptId: $e');
|
||||
Log.error('[$receiptId] Error marking message as received: $e');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -235,26 +246,26 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessageRaw(
|
|||
Message_Type messageType,
|
||||
String receiptId,
|
||||
) async {
|
||||
final (encryptedContent, decryptionErrorType) = await signalDecryptMessage(
|
||||
Log.info('[$receiptId] calling signalDecryptMessage');
|
||||
var (encryptedContent, decryptionErrorType) = await signalDecryptMessage(
|
||||
fromUserId,
|
||||
encryptedContentRaw,
|
||||
messageType.value,
|
||||
);
|
||||
|
||||
if (encryptedContent == null) {
|
||||
if (decryptionErrorType == null) {
|
||||
// Duplicate message
|
||||
return (null, null);
|
||||
}
|
||||
return (
|
||||
null,
|
||||
PlaintextContent()
|
||||
..decryptionErrorMessage = (PlaintextContent_DecryptionErrorMessage()
|
||||
..type = decryptionErrorType),
|
||||
PlaintextContent(
|
||||
decryptionErrorMessage: PlaintextContent_DecryptionErrorMessage(
|
||||
type: decryptionErrorType ??=
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Log.info('Calling handleEncryptedMessage for $receiptId');
|
||||
Log.info('[$receiptId] Calling handleEncryptedMessage');
|
||||
|
||||
final (a, b) = await handleEncryptedMessage(
|
||||
fromUserId,
|
||||
|
|
@ -263,7 +274,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessageRaw(
|
|||
receiptId,
|
||||
);
|
||||
|
||||
Log.info('Finished handleEncryptedMessage for $receiptId');
|
||||
Log.info('[$receiptId] Finished handleEncryptedMessage');
|
||||
|
||||
if (Platform.isAndroid && a == null && b == null) {
|
||||
// Message was handled without any error -> Show push notification to the user.
|
||||
|
|
@ -294,11 +305,16 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
await checkForUserDiscoveryChanges(
|
||||
fromUserId,
|
||||
content.senderUserDiscoveryVersion,
|
||||
receiptId,
|
||||
);
|
||||
}
|
||||
|
||||
if (content.hasContactRequest()) {
|
||||
if (!await handleContactRequest(fromUserId, content.contactRequest)) {
|
||||
if (!await handleContactRequest(
|
||||
fromUserId,
|
||||
content.contactRequest,
|
||||
receiptId,
|
||||
)) {
|
||||
return (
|
||||
null,
|
||||
PlaintextContent()
|
||||
|
|
@ -312,6 +328,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
await handleErrorMessage(
|
||||
fromUserId,
|
||||
content.errorMessages,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -321,6 +338,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.contactUpdate,
|
||||
senderProfileCounter,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -329,6 +347,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
await handleUserDiscoveryRequest(
|
||||
fromUserId,
|
||||
content.userDiscoveryRequest,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -337,12 +356,13 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
await handleUserDiscoveryUpdate(
|
||||
fromUserId,
|
||||
content.userDiscoveryUpdate,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
if (content.hasPushKeys()) {
|
||||
await handlePushKey(fromUserId, content.pushKeys);
|
||||
await handlePushKey(fromUserId, content.pushKeys, receiptId);
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
|
|
@ -350,6 +370,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
await handleMessageUpdate(
|
||||
fromUserId,
|
||||
content.messageUpdate,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -366,12 +387,13 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
await handleMediaUpdate(
|
||||
fromUserId,
|
||||
content.mediaUpdate,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
if (!content.hasGroupId()) {
|
||||
Log.error('Messages should have a groupId $fromUserId.');
|
||||
Log.error('[$receiptId] Messages should have a groupId $fromUserId.');
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
|
|
@ -380,6 +402,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.groupCreate,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -392,12 +415,12 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
.getContactByUserId(fromUserId)
|
||||
.getSingleOrNull();
|
||||
Log.info(
|
||||
'Contact exists?: ${contact != null} Is deleted? ${contact?.deletedByUser} Accepted? (${contact?.accepted})',
|
||||
'[$receiptId] Contact exists?: ${contact != null} Is deleted? ${contact?.deletedByUser} Accepted? (${contact?.accepted})',
|
||||
);
|
||||
if (contact == null || !contact.accepted || contact.deletedByUser) {
|
||||
await handleNewContactRequest(fromUserId);
|
||||
Log.error(
|
||||
'User tries to send message to direct chat while the user does not exists !',
|
||||
'[$receiptId] User tries to send message to direct chat while the user does not exist!',
|
||||
);
|
||||
return (
|
||||
EncryptedContent(
|
||||
|
|
@ -411,7 +434,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
);
|
||||
}
|
||||
Log.info(
|
||||
'Creating new DirectChat between two users',
|
||||
'[$receiptId] Creating new DirectChat between two users',
|
||||
);
|
||||
await twonlyDB.groupsDao.createNewDirectChat(
|
||||
fromUserId,
|
||||
|
|
@ -422,7 +445,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
} else {
|
||||
if (content.hasGroupJoin()) {
|
||||
Log.error(
|
||||
'Got group join message, but group does not exists yet, retry later. As probably the GroupCreate was not yet received.',
|
||||
'[$receiptId] Got group join message, but group does not exist yet, retry later. As probably the GroupCreate was not yet received.',
|
||||
);
|
||||
// In case the group join was received before the GroupCreate the sender should send it later again.
|
||||
return (
|
||||
|
|
@ -432,13 +455,15 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
);
|
||||
}
|
||||
|
||||
Log.error('User $fromUserId tried to access group ${content.groupId}.');
|
||||
Log.error(
|
||||
'[$receiptId] User $fromUserId tried to access group ${content.groupId}.',
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
if (content.hasFlameSync()) {
|
||||
await handleFlameSync(content.groupId, content.flameSync);
|
||||
await handleFlameSync(content.groupId, content.flameSync, receiptId);
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
|
|
@ -447,6 +472,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.groupUpdate,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -456,6 +482,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.groupJoin,
|
||||
receiptId,
|
||||
)) {
|
||||
return (
|
||||
null,
|
||||
|
|
@ -471,6 +498,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.groupJoin,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -480,6 +508,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.additionalDataMessage,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -489,6 +518,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.textMessage,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -498,6 +528,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.reaction,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -507,6 +538,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.media,
|
||||
receiptId,
|
||||
);
|
||||
return (null, null);
|
||||
}
|
||||
|
|
@ -516,6 +548,7 @@ Future<(EncryptedContent?, PlaintextContent?)> handleEncryptedMessage(
|
|||
fromUserId,
|
||||
content.groupId,
|
||||
content.typingIndicator,
|
||||
receiptId,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import 'package:drift/drift.dart';
|
|||
import 'package:fixnum/fixnum.dart';
|
||||
import 'package:twonly/core/bridge/wrapper/key_manager.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/constants/secure_storage.keys.dart';
|
||||
import 'package:twonly/src/database/tables/mediafiles.table.dart';
|
||||
import 'package:twonly/src/database/twonly.db.dart';
|
||||
import 'package:twonly/src/model/protobuf/api/websocket/client_to_server.pb.dart'
|
||||
|
|
@ -129,7 +128,7 @@ Future<Map<String, String>?> getAuthenticationHeader() async {
|
|||
};
|
||||
} else {
|
||||
final apiAuthTokenRaw = await SecureStorage.instance.read(
|
||||
key: SecureStorageKeys.apiAuthToken,
|
||||
key: 'api_auth_token',
|
||||
);
|
||||
|
||||
if (apiAuthTokenRaw == null) {
|
||||
|
|
|
|||
|
|
@ -119,9 +119,15 @@ Future<void> handlePeriodicTask({int lastExecutionInSecondsLimit = 120}) async {
|
|||
if (!shouldBeExecuted) return;
|
||||
|
||||
Log.info('eu.twonly.periodic_task was called.');
|
||||
AppState.gotMessageFromServer = false;
|
||||
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
// Issue: Because the background isolate can be reused across multiple periodic tasks,
|
||||
// the API connection state might be stale or disconnected from a previous run.
|
||||
// Explicitly close it here to ensure a clean slate before connecting.
|
||||
await apiService.close(null);
|
||||
|
||||
if (!await apiService.connect()) {
|
||||
Log.info('Could not connect to the api. Returning early.');
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -65,23 +65,18 @@ Future<void> syncFlameCounters({String? forceForGroup}) async {
|
|||
({int counter, bool isExpiring}) getFlameCounterFromGroup(Group? group) {
|
||||
const zero = (counter: 0, isExpiring: false);
|
||||
if (group == null) return zero;
|
||||
if (group.lastMessageSend == null ||
|
||||
group.lastMessageReceived == null ||
|
||||
group.lastFlameCounterChange == null) {
|
||||
if (group.lastMessageSend == null || group.lastMessageReceived == null || group.lastFlameCounterChange == null) {
|
||||
return zero;
|
||||
}
|
||||
final now = clock.now();
|
||||
final startOfToday = DateTime(now.year, now.month, now.day);
|
||||
final twoDaysAgo = startOfToday.subtract(const Duration(days: 2));
|
||||
final oneDayAgo = startOfToday.subtract(const Duration(days: 1));
|
||||
if (group.lastMessageSend!.isAfter(twoDaysAgo) &&
|
||||
group.lastMessageReceived!.isAfter(twoDaysAgo) ||
|
||||
if (group.lastMessageSend!.isAfter(twoDaysAgo) && group.lastMessageReceived!.isAfter(twoDaysAgo) ||
|
||||
group.lastFlameCounterChange!.isAfter(oneDayAgo)) {
|
||||
// Flame is expiring when today no exchange has happened yet:
|
||||
// both lastMessageSend and lastMessageReceived are before startOfToday.
|
||||
final isExpiring =
|
||||
group.lastMessageSend!.isBefore(oneDayAgo) ||
|
||||
group.lastMessageReceived!.isBefore(oneDayAgo);
|
||||
final isExpiring = group.lastMessageSend!.isBefore(oneDayAgo) || group.lastMessageReceived!.isBefore(oneDayAgo);
|
||||
return (counter: group.flameCounter, isExpiring: isExpiring);
|
||||
} else {
|
||||
return zero;
|
||||
|
|
@ -122,8 +117,7 @@ Future<void> incFlameCounter(
|
|||
final now = clock.now();
|
||||
final startOfToday = DateTime(now.year, now.month, now.day);
|
||||
final twoDaysAgo = startOfToday.subtract(const Duration(days: 2));
|
||||
if (group.lastMessageSend!.isBefore(twoDaysAgo) ||
|
||||
group.lastMessageReceived!.isBefore(twoDaysAgo)) {
|
||||
if (group.lastMessageSend!.isBefore(twoDaysAgo) || group.lastMessageReceived!.isBefore(twoDaysAgo)) {
|
||||
flameCounter = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -135,25 +129,21 @@ Future<void> incFlameCounter(
|
|||
final now = clock.now();
|
||||
final startOfToday = DateTime(now.year, now.month, now.day);
|
||||
|
||||
if (group.lastFlameCounterChange == null ||
|
||||
group.lastFlameCounterChange!.isBefore(startOfToday)) {
|
||||
if (group.lastFlameCounterChange == null || group.lastFlameCounterChange!.isBefore(startOfToday)) {
|
||||
// last flame update was yesterday. check if it can be updated.
|
||||
var updateFlame = false;
|
||||
if (received) {
|
||||
if (group.lastMessageSend != null &&
|
||||
group.lastMessageSend!.isAfter(startOfToday)) {
|
||||
if (group.lastMessageSend != null && group.lastMessageSend!.isAfter(startOfToday)) {
|
||||
// today a message was already send -> update flame
|
||||
updateFlame = true;
|
||||
}
|
||||
} else if (group.lastMessageReceived != null &&
|
||||
group.lastMessageReceived!.isAfter(startOfToday)) {
|
||||
} else if (group.lastMessageReceived != null && group.lastMessageReceived!.isAfter(startOfToday)) {
|
||||
// today a message was already received -> update flame
|
||||
updateFlame = true;
|
||||
}
|
||||
if (updateFlame) {
|
||||
flameCounter += 1;
|
||||
if (group.lastFlameCounterChange == null ||
|
||||
group.lastFlameCounterChange!.isBefore(timestamp)) {
|
||||
if (group.lastFlameCounterChange == null || group.lastFlameCounterChange!.isBefore(timestamp)) {
|
||||
// only update if the timestamp is newer
|
||||
lastFlameCounterChange = Value(timestamp);
|
||||
}
|
||||
|
|
@ -170,13 +160,11 @@ Future<void> incFlameCounter(
|
|||
}
|
||||
|
||||
if (received) {
|
||||
if (group.lastMessageReceived == null ||
|
||||
group.lastMessageReceived!.isBefore(timestamp)) {
|
||||
if (group.lastMessageReceived == null || group.lastMessageReceived!.isBefore(timestamp)) {
|
||||
lastMessageReceived = Value(timestamp);
|
||||
}
|
||||
} else {
|
||||
if (group.lastMessageSend == null ||
|
||||
group.lastMessageSend!.isBefore(timestamp)) {
|
||||
if (group.lastMessageSend == null || group.lastMessageSend!.isBefore(timestamp)) {
|
||||
lastMessageSend = Value(timestamp);
|
||||
}
|
||||
}
|
||||
|
|
@ -203,3 +191,18 @@ bool isItPossibleToRestoreFlames(Group group) {
|
|||
clock.now().subtract(const Duration(days: 7)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> restoreFlames(String groupId) async {
|
||||
final group = await twonlyDB.groupsDao.getGroup(groupId);
|
||||
if (group == null) return;
|
||||
final now = clock.now();
|
||||
await twonlyDB.groupsDao.updateGroup(
|
||||
groupId,
|
||||
GroupsCompanion(
|
||||
flameCounter: Value(group.maxFlameCounter),
|
||||
lastFlameCounterChange: Value(now),
|
||||
lastMessageSend: Value(now),
|
||||
lastMessageReceived: Value(now),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,14 +3,17 @@ import 'dart:typed_data';
|
|||
import 'package:collection/collection.dart';
|
||||
import 'package:cryptography_plus/cryptography_plus.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/database/daos/contacts.dao.dart';
|
||||
import 'package:twonly/src/database/tables/contacts.table.dart';
|
||||
import 'package:twonly/src/model/protobuf/client/generated/messages.pb.dart'
|
||||
as pb;
|
||||
import 'package:twonly/src/providers/routing.provider.dart';
|
||||
import 'package:twonly/src/services/api/messages.api.dart';
|
||||
import 'package:twonly/src/services/signal/identity.signal.dart';
|
||||
import 'package:twonly/src/services/signal/session.signal.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
import 'package:twonly/src/utils/misc.dart';
|
||||
import 'package:twonly/src/visual/components/snackbar.dart';
|
||||
|
||||
class KeyVerificationService {
|
||||
static Future<List<int>> getNewSecretVerificationToken() async {
|
||||
|
|
@ -70,6 +73,18 @@ class KeyVerificationService {
|
|||
VerificationType.secretQrToken,
|
||||
);
|
||||
Log.info('Contact was verified via secretQrToken');
|
||||
|
||||
final contact = await twonlyDB.contactsDao.getContactById(fromUserId);
|
||||
final context = rootNavigatorKey.currentContext;
|
||||
if (context != null && context.mounted && contact != null) {
|
||||
showSnackbar(
|
||||
context,
|
||||
context.lang.secretQrTokenVerifiedSnackbar(
|
||||
getContactDisplayName(contact),
|
||||
),
|
||||
level: SnackbarLevel.success,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import 'dart:io';
|
|||
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_image_compress/flutter_image_compress.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:path/path.dart';
|
||||
|
|
@ -72,6 +73,13 @@ class MediaFileService {
|
|||
delete = false;
|
||||
}
|
||||
|
||||
// Never purge temp files while an upload is still in progress.
|
||||
// The temp file is actively needed for encryption/upload.
|
||||
if (mediaFile.uploadState != UploadState.uploaded &&
|
||||
mediaFile.uploadState != UploadState.fileLimitReached) {
|
||||
delete = false;
|
||||
}
|
||||
|
||||
final messages = messageMap[mediaId] ?? [];
|
||||
|
||||
// in case messages in empty the file will be deleted, as delete is true by default
|
||||
|
|
@ -84,6 +92,15 @@ class MediaFileService {
|
|||
if (message.openedAt == null) {
|
||||
// Message was not yet opened from all persons, so wait...
|
||||
delete = false;
|
||||
} else if (message.openedAt!.isAfter(
|
||||
clock.now().subtract(const Duration(minutes: 3)),
|
||||
)) {
|
||||
// When the message was opened in the last two minutes, do not purge.
|
||||
// Bug: When the user opens an image immediately after starting the app, there is a race condition:
|
||||
// The message is marked as opened, but then purgeTempFolder is run
|
||||
// (it is unawaited) and deletes the file. Thi gives a grace period:
|
||||
// The image must have been opened within the last two minutes, otherwise do not delete it.
|
||||
delete = false;
|
||||
} else if (mediaFile.requiresAuthentication ||
|
||||
mediaFile.displayLimitInMilliseconds != null) {
|
||||
// Message was opened by all persons, and they can not reopen the image.
|
||||
|
|
@ -197,17 +214,34 @@ class MediaFileService {
|
|||
|
||||
Future<void> createThumbnail() async {
|
||||
if (!storedPath.existsSync()) {
|
||||
Log.error('Could not create Thumbnail as stored media does not exists.');
|
||||
if (mediaFile.stored &&
|
||||
mediaFile.createdAt.isBefore(
|
||||
clock.now().subtract(const Duration(days: 30)),
|
||||
)) {
|
||||
// media files does not exists any more so also delete the database entry
|
||||
await twonlyDB.mediaFilesDao.deleteMediaFile(mediaFile.mediaId);
|
||||
fullMediaRemoval();
|
||||
}
|
||||
return;
|
||||
}
|
||||
var success = false;
|
||||
switch (mediaFile.type) {
|
||||
case MediaType.gif:
|
||||
case MediaType.audio:
|
||||
success = await createThumbnailsForGif(storedPath, thumbnailPath);
|
||||
case MediaType.image:
|
||||
// all images are already compress..
|
||||
break;
|
||||
success = await createThumbnailsForImage(storedPath, thumbnailPath);
|
||||
case MediaType.video:
|
||||
await createThumbnailsForVideo(storedPath, thumbnailPath);
|
||||
success = await createThumbnailsForVideo(storedPath, thumbnailPath);
|
||||
case MediaType.audio:
|
||||
break;
|
||||
}
|
||||
|
||||
if (success) {
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
mediaFile.mediaId,
|
||||
const MediaFilesCompanion(hasThumbnail: Value(true)),
|
||||
);
|
||||
await updateFromDB();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -253,7 +287,9 @@ class MediaFileService {
|
|||
tempPath.existsSync();
|
||||
|
||||
bool get imagePreviewAvailable =>
|
||||
thumbnailPath.existsSync() || storedPath.existsSync();
|
||||
mediaFile.hasThumbnail ||
|
||||
thumbnailPath.existsSync() ||
|
||||
storedPath.existsSync();
|
||||
|
||||
Future<void> storeMediaFile() async {
|
||||
Log.info('Storing media file ${mediaFile.mediaId}');
|
||||
|
|
@ -275,6 +311,7 @@ class MediaFileService {
|
|||
} else {
|
||||
await saveImageToGallery(
|
||||
storedPath.readAsBytesSync(),
|
||||
createdAt: mediaFile.createdAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -284,10 +321,24 @@ class MediaFileService {
|
|||
);
|
||||
}
|
||||
unawaited(createThumbnail());
|
||||
await calculateAndSaveSize();
|
||||
await hashMediaFile();
|
||||
// updateFromDb is done in hashStoredMedia()
|
||||
}
|
||||
|
||||
Future<void> calculateAndSaveSize() async {
|
||||
if (storedPath.existsSync()) {
|
||||
final size = storedPath.lengthSync();
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
mediaFile.mediaId,
|
||||
MediaFilesCompanion(
|
||||
sizeInBytes: Value(size),
|
||||
),
|
||||
);
|
||||
await updateFromDB();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> hashMediaFile() async {
|
||||
late final List<int> checksum;
|
||||
if (storedPath.existsSync()) {
|
||||
|
|
@ -398,106 +449,41 @@ class MediaFileService {
|
|||
|
||||
try {
|
||||
final bytes = storedPath.readAsBytesSync();
|
||||
final image = img.decodeImage(bytes);
|
||||
if (image == null) {
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
mediaFile.mediaId,
|
||||
const MediaFilesCompanion(hasCropAnalyzed: Value(true)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final result = await compute(_processImageCrop, bytes);
|
||||
|
||||
var minY = 0;
|
||||
var maxY = image.height - 1;
|
||||
var minX = 0;
|
||||
var maxX = image.width - 1;
|
||||
|
||||
var found = false;
|
||||
for (var y = 0; y < image.height; y++) {
|
||||
for (var x = 0; x < image.width; x++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
minY = y;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
found = false;
|
||||
for (var y = image.height - 1; y >= minY; y--) {
|
||||
for (var x = 0; x < image.width; x++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
maxY = y;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
found = false;
|
||||
for (var x = 0; x < image.width; x++) {
|
||||
for (var y = minY; y <= maxY; y++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
minX = x;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
found = false;
|
||||
for (var x = image.width - 1; x >= minX; x--) {
|
||||
for (var y = minY; y <= maxY; y++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
maxX = x;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
final newWidth = maxX - minX + 1;
|
||||
final newHeight = maxY - minY + 1;
|
||||
|
||||
if (minY > 0 ||
|
||||
maxY < image.height - 1 ||
|
||||
minX > 0 ||
|
||||
maxX < image.width - 1) {
|
||||
if (newWidth > 10 && newHeight > 10) {
|
||||
final cropped = img.copyCrop(
|
||||
image,
|
||||
x: minX,
|
||||
y: minY,
|
||||
width: newWidth,
|
||||
height: newHeight,
|
||||
);
|
||||
final pngBytes = img.encodePng(cropped);
|
||||
if (result.isCropped && result.pngBytes != null) {
|
||||
try {
|
||||
final webpBytes = await FlutterImageCompress.compressWithList(
|
||||
pngBytes,
|
||||
result.pngBytes!,
|
||||
format: CompressFormat.webp,
|
||||
quality: 90,
|
||||
);
|
||||
storedPath.writeAsBytesSync(webpBytes);
|
||||
|
||||
if (thumbnailPath.existsSync()) {
|
||||
thumbnailPath.deleteSync();
|
||||
|
||||
if (webpBytes.isNotEmpty) {
|
||||
storedPath.writeAsBytesSync(webpBytes);
|
||||
} else {
|
||||
Log.warn('WebP compression returned empty, falling back to PNG');
|
||||
storedPath.writeAsBytesSync(result.pngBytes!);
|
||||
}
|
||||
await createThumbnail();
|
||||
final checksum = await sha256File(storedPath);
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
mediaFile.mediaId,
|
||||
MediaFilesCompanion(
|
||||
hasCropAnalyzed: const Value(true),
|
||||
storedFileHash: Value(Uint8List.fromList(checksum)),
|
||||
),
|
||||
);
|
||||
await updateFromDB();
|
||||
return;
|
||||
} catch (e) {
|
||||
Log.error('Error compressing to WebP, falling back to PNG: $e');
|
||||
storedPath.writeAsBytesSync(result.pngBytes!);
|
||||
}
|
||||
|
||||
if (thumbnailPath.existsSync()) {
|
||||
thumbnailPath.deleteSync();
|
||||
}
|
||||
await createThumbnail();
|
||||
final checksum = await sha256File(storedPath);
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
mediaFile.mediaId,
|
||||
MediaFilesCompanion(
|
||||
hasCropAnalyzed: const Value(true),
|
||||
storedFileHash: Value(Uint8List.fromList(checksum)),
|
||||
),
|
||||
);
|
||||
await updateFromDB();
|
||||
return;
|
||||
}
|
||||
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
|
|
@ -517,3 +503,89 @@ class MediaFileService {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _CropResult {
|
||||
const _CropResult(this.pngBytes, this.isCropped);
|
||||
final Uint8List? pngBytes;
|
||||
final bool isCropped;
|
||||
}
|
||||
|
||||
_CropResult _processImageCrop(Uint8List bytes) {
|
||||
final image = img.decodeImage(bytes);
|
||||
if (image == null) return const _CropResult(null, false);
|
||||
|
||||
var minY = 0;
|
||||
var maxY = image.height - 1;
|
||||
var minX = 0;
|
||||
var maxX = image.width - 1;
|
||||
|
||||
var found = false;
|
||||
for (var y = 0; y < image.height; y++) {
|
||||
for (var x = 0; x < image.width; x++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
minY = y;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
found = false;
|
||||
for (var y = image.height - 1; y >= minY; y--) {
|
||||
for (var x = 0; x < image.width; x++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
maxY = y;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
found = false;
|
||||
for (var x = 0; x < image.width; x++) {
|
||||
for (var y = minY; y <= maxY; y++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
minX = x;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
found = false;
|
||||
for (var x = image.width - 1; x >= minX; x--) {
|
||||
for (var y = minY; y <= maxY; y++) {
|
||||
if (image.getPixel(x, y).a > 10) {
|
||||
maxX = x;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
final newWidth = maxX - minX + 1;
|
||||
final newHeight = maxY - minY + 1;
|
||||
|
||||
if (minY > 0 ||
|
||||
maxY < image.height - 1 ||
|
||||
minX > 0 ||
|
||||
maxX < image.width - 1) {
|
||||
if (newWidth > 10 && newHeight > 10) {
|
||||
final cropped = img.copyCrop(
|
||||
image,
|
||||
x: minX,
|
||||
y: minY,
|
||||
width: newWidth,
|
||||
height: newHeight,
|
||||
);
|
||||
final pngBytes = img.encodePng(cropped);
|
||||
return _CropResult(pngBytes, true);
|
||||
}
|
||||
}
|
||||
|
||||
return const _CropResult(null, false);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,18 @@
|
|||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
import 'package:flutter_image_compress/flutter_image_compress.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:pro_video_editor/pro_video_editor.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
|
||||
Future<void> createThumbnailsForVideo(
|
||||
Future<bool> createThumbnailsForVideo(
|
||||
File sourceFile,
|
||||
File destinationFile,
|
||||
) async {
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
if (destinationFile.existsSync()) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
final images = await ProVideoEditor.instance.getThumbnails(
|
||||
|
|
@ -28,11 +30,83 @@ Future<void> createThumbnailsForVideo(
|
|||
stopwatch.stop();
|
||||
destinationFile.writeAsBytesSync(images.first);
|
||||
Log.info(
|
||||
'It took ${stopwatch.elapsedMilliseconds}ms to create the thumbnail.',
|
||||
'It took ${stopwatch.elapsedMilliseconds}ms to create the video thumbnail.',
|
||||
);
|
||||
return true;
|
||||
} else {
|
||||
Log.warn(
|
||||
'Thumbnail creation failed for the video with exit code.',
|
||||
'Thumbnail creation failed for the video.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> createThumbnailsForImage(
|
||||
File sourceFile,
|
||||
File destinationFile,
|
||||
) async {
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
try {
|
||||
await FlutterImageCompress.compressAndGetFile(
|
||||
sourceFile.absolute.path,
|
||||
destinationFile.absolute.path,
|
||||
minWidth: 300,
|
||||
minHeight: 300,
|
||||
quality: 100,
|
||||
format: CompressFormat.webp,
|
||||
);
|
||||
stopwatch.stop();
|
||||
Log.info(
|
||||
'It took ${stopwatch.elapsedMilliseconds}ms to create the image thumbnail.',
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
Log.error('Error creating image thumbnail: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> createThumbnailsForGif(
|
||||
File sourceFile,
|
||||
File destinationFile,
|
||||
) async {
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
if (destinationFile.existsSync()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
// For GIFs, we decode the first frame and save it as WebP
|
||||
final bytes = sourceFile.readAsBytesSync();
|
||||
final image = img.decodeGif(bytes);
|
||||
if (image == null) {
|
||||
Log.error('Could not decode GIF for thumbnail.');
|
||||
return false;
|
||||
}
|
||||
|
||||
final thumbnail = img.copyResize(
|
||||
image,
|
||||
width: image.width > image.height ? 400 : null,
|
||||
height: image.height >= image.width ? 400 : null,
|
||||
);
|
||||
|
||||
final pngBytes = img.encodePng(thumbnail);
|
||||
final webp = await FlutterImageCompress.compressWithList(
|
||||
pngBytes,
|
||||
format: CompressFormat.webp,
|
||||
quality: 85,
|
||||
);
|
||||
destinationFile.writeAsBytesSync(webp);
|
||||
|
||||
stopwatch.stop();
|
||||
Log.info(
|
||||
'It took ${stopwatch.elapsedMilliseconds}ms to create the GIF thumbnail.',
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
Log.error('Error creating GIF thumbnail: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import 'dart:async';
|
|||
import 'dart:collection';
|
||||
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:drift/drift.dart' show Value;
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/database/tables/mediafiles.table.dart';
|
||||
|
|
@ -14,6 +15,7 @@ import 'package:twonly/src/utils/log.dart';
|
|||
class MemoriesState {
|
||||
const MemoriesState({
|
||||
required this.filesToMigrate,
|
||||
required this.totalFilesToMigrate,
|
||||
required this.galleryItems,
|
||||
required this.months,
|
||||
required this.orderedByMonth,
|
||||
|
|
@ -21,16 +23,21 @@ class MemoriesState {
|
|||
});
|
||||
|
||||
final int filesToMigrate;
|
||||
final int totalFilesToMigrate;
|
||||
final List<MemoryItem> galleryItems;
|
||||
final List<String> months;
|
||||
final Map<String, List<int>> orderedByMonth;
|
||||
final Map<int, List<MemoryItem>> galleryItemsLastYears;
|
||||
|
||||
bool get isLoading => filesToMigrate > 0;
|
||||
double get migrationProgress => totalFilesToMigrate > 0
|
||||
? (totalFilesToMigrate - filesToMigrate) / totalFilesToMigrate
|
||||
: 0;
|
||||
bool get isEmpty => galleryItems.isEmpty && filesToMigrate == 0;
|
||||
|
||||
MemoriesState copyWith({
|
||||
int? filesToMigrate,
|
||||
int? totalFilesToMigrate,
|
||||
List<MemoryItem>? galleryItems,
|
||||
List<String>? months,
|
||||
Map<String, List<int>>? orderedByMonth,
|
||||
|
|
@ -38,6 +45,7 @@ class MemoriesState {
|
|||
}) {
|
||||
return MemoriesState(
|
||||
filesToMigrate: filesToMigrate ?? this.filesToMigrate,
|
||||
totalFilesToMigrate: totalFilesToMigrate ?? this.totalFilesToMigrate,
|
||||
galleryItems: galleryItems ?? this.galleryItems,
|
||||
months: months ?? this.months,
|
||||
orderedByMonth: orderedByMonth ?? this.orderedByMonth,
|
||||
|
|
@ -62,6 +70,7 @@ class MemoriesService {
|
|||
|
||||
MemoriesState _currentState = const MemoriesState(
|
||||
filesToMigrate: 0,
|
||||
totalFilesToMigrate: 0,
|
||||
galleryItems: [],
|
||||
months: [],
|
||||
orderedByMonth: {},
|
||||
|
|
@ -88,14 +97,10 @@ class MemoriesService {
|
|||
final mediaFiles = await twonlyDB.mediaFilesDao.getMediaFilesByIds(
|
||||
mediaIds,
|
||||
);
|
||||
final mediaFileMap = {for (final m in mediaFiles) m.mediaId: m};
|
||||
|
||||
final allContacts = await twonlyDB.contactsDao.getAllContacts();
|
||||
final contactMap = {for (final c in allContacts) c.userId: c};
|
||||
|
||||
final now = clock.now();
|
||||
final tempGalleryItems = <MemoryItem>[];
|
||||
final tempGalleryItemsLastYears = <int, List<MemoryItem>>{};
|
||||
final mediaIdToSender = <String, Contact?>{};
|
||||
|
||||
for (final itemJson in itemList) {
|
||||
final map = itemJson as Map<String, dynamic>;
|
||||
|
|
@ -103,64 +108,14 @@ class MemoriesService {
|
|||
final senderUserId = map['senderUserId'] as int?;
|
||||
if (mediaId == null) continue;
|
||||
|
||||
final mediaFile = mediaFileMap[mediaId];
|
||||
if (mediaFile == null) continue;
|
||||
|
||||
final mediaService = MediaFileService(mediaFile);
|
||||
if (!mediaService.imagePreviewAvailable) continue;
|
||||
|
||||
final contact = senderUserId != null
|
||||
mediaIdToSender[mediaId] = senderUserId != null
|
||||
? contactMap[senderUserId]
|
||||
: null;
|
||||
final item = MemoryItem(
|
||||
mediaService: mediaService,
|
||||
messages: [],
|
||||
sender: contact,
|
||||
);
|
||||
tempGalleryItems.add(item);
|
||||
|
||||
if (mediaFile.createdAt.month == now.month &&
|
||||
mediaFile.createdAt.day == now.day) {
|
||||
final diff = now.year - mediaFile.createdAt.year;
|
||||
if (diff > 0) {
|
||||
tempGalleryItemsLastYears.putIfAbsent(diff, () => []).add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final tempOrderedByMonth = <String, List<int>>{};
|
||||
final tempMonths = <String>[];
|
||||
var lastMonth = '';
|
||||
|
||||
for (var i = 0; i < tempGalleryItems.length; i++) {
|
||||
final mFile = tempGalleryItems[i].mediaService.mediaFile;
|
||||
final month =
|
||||
mFile.createdAtMonth ??
|
||||
DateFormat('MMMM yyyy').format(mFile.createdAt);
|
||||
if (lastMonth != month) {
|
||||
lastMonth = month;
|
||||
tempMonths.add(month);
|
||||
}
|
||||
tempOrderedByMonth.putIfAbsent(month, () => []).add(i);
|
||||
}
|
||||
|
||||
for (final list in tempGalleryItemsLastYears.values) {
|
||||
list.sort(
|
||||
(a, b) => b.mediaService.mediaFile.createdAt.compareTo(
|
||||
a.mediaService.mediaFile.createdAt,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final sortedGalleryItemsLastYears =
|
||||
SplayTreeMap<int, List<MemoryItem>>.from(tempGalleryItemsLastYears);
|
||||
|
||||
_cachedState = MemoriesState(
|
||||
filesToMigrate: 0,
|
||||
galleryItems: tempGalleryItems,
|
||||
months: tempMonths,
|
||||
orderedByMonth: tempOrderedByMonth,
|
||||
galleryItemsLastYears: sortedGalleryItemsLastYears,
|
||||
_cachedState = _computeState(
|
||||
mediaFiles: mediaFiles,
|
||||
mediaIdToSender: mediaIdToSender,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -168,34 +123,124 @@ class MemoriesService {
|
|||
}
|
||||
}
|
||||
|
||||
static MemoriesState _computeState({
|
||||
required List<MediaFile> mediaFiles,
|
||||
required Map<String, Contact?> mediaIdToSender,
|
||||
int filesToMigrate = 0,
|
||||
}) {
|
||||
final now = clock.now();
|
||||
final tempGalleryItems = <MemoryItem>[];
|
||||
final tempGalleryItemsLastYears = <int, List<MemoryItem>>{};
|
||||
|
||||
for (final mediaFile in mediaFiles) {
|
||||
final mediaService = MediaFileService(mediaFile);
|
||||
if (!mediaService.imagePreviewAvailable) continue;
|
||||
|
||||
final senderContact = mediaIdToSender[mediaFile.mediaId];
|
||||
final item = MemoryItem(
|
||||
mediaService: mediaService,
|
||||
messages: [],
|
||||
sender: senderContact,
|
||||
);
|
||||
|
||||
tempGalleryItems.add(item);
|
||||
|
||||
if (mediaFile.createdAt.month == now.month &&
|
||||
mediaFile.createdAt.day == now.day) {
|
||||
final diff = now.year - mediaFile.createdAt.year;
|
||||
if (diff > 0) {
|
||||
tempGalleryItemsLastYears.putIfAbsent(diff, () => []).add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort descending by creation date
|
||||
tempGalleryItems.sort(
|
||||
(a, b) => b.mediaService.mediaFile.createdAt.compareTo(
|
||||
a.mediaService.mediaFile.createdAt,
|
||||
),
|
||||
);
|
||||
|
||||
final tempOrderedByMonth = <String, List<int>>{};
|
||||
final tempMonths = <String>[];
|
||||
var lastMonth = '';
|
||||
|
||||
for (var i = 0; i < tempGalleryItems.length; i++) {
|
||||
final mFile = tempGalleryItems[i].mediaService.mediaFile;
|
||||
final month =
|
||||
mFile.createdAtMonth ??
|
||||
DateFormat('MMMM yyyy').format(mFile.createdAt);
|
||||
if (lastMonth != month) {
|
||||
lastMonth = month;
|
||||
tempMonths.add(month);
|
||||
}
|
||||
tempOrderedByMonth.putIfAbsent(month, () => []).add(i);
|
||||
}
|
||||
|
||||
for (final list in tempGalleryItemsLastYears.values) {
|
||||
list.sort(
|
||||
(a, b) => b.mediaService.mediaFile.createdAt.compareTo(
|
||||
a.mediaService.mediaFile.createdAt,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final sortedGalleryItemsLastYears =
|
||||
SplayTreeMap<int, List<MemoryItem>>.from(tempGalleryItemsLastYears);
|
||||
|
||||
return MemoriesState(
|
||||
filesToMigrate: filesToMigrate,
|
||||
totalFilesToMigrate: filesToMigrate, // Reset total when computing new state? No, keep existing total if migrating.
|
||||
galleryItems: tempGalleryItems,
|
||||
months: tempMonths,
|
||||
orderedByMonth: tempOrderedByMonth,
|
||||
galleryItemsLastYears: sortedGalleryItemsLastYears,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _initAsync() async {
|
||||
try {
|
||||
// 1. Perform Inventory / Migration of non-hashed stored files
|
||||
final nonHashedFiles = await twonlyDB.mediaFilesDao
|
||||
.getAllNonHashedStoredMediaFiles();
|
||||
final unanalyzedFiles = await twonlyDB.mediaFilesDao
|
||||
.getAllUnanalyzedStoredMediaFiles();
|
||||
final pendingFiles = await twonlyDB.mediaFilesDao
|
||||
.getAllMediaFilesPendingMigration();
|
||||
|
||||
final totalToMigrate = nonHashedFiles.length + unanalyzedFiles.length;
|
||||
if (totalToMigrate > 0) {
|
||||
_updateState(filesToMigrate: totalToMigrate);
|
||||
if (pendingFiles.isNotEmpty) {
|
||||
_currentState = _currentState.copyWith(
|
||||
filesToMigrate: pendingFiles.length,
|
||||
totalFilesToMigrate: pendingFiles.length,
|
||||
);
|
||||
_notifyState();
|
||||
|
||||
for (final mediaFile in nonHashedFiles) {
|
||||
for (final mediaFile in pendingFiles) {
|
||||
final mediaService = MediaFileService(mediaFile);
|
||||
await mediaService.hashMediaFile();
|
||||
_updateState(filesToMigrate: _currentState.filesToMigrate - 1);
|
||||
|
||||
if (mediaService.mediaFile.storedFileHash == null) {
|
||||
await mediaService.hashMediaFile();
|
||||
}
|
||||
|
||||
if (!mediaService.mediaFile.hasCropAnalyzed) {
|
||||
await mediaService.cropTransparentBorders();
|
||||
}
|
||||
|
||||
if (mediaService.mediaFile.sizeInBytes == null) {
|
||||
await mediaService.calculateAndSaveSize();
|
||||
}
|
||||
|
||||
if (!mediaService.mediaFile.hasThumbnail) {
|
||||
if (mediaService.thumbnailPath.existsSync()) {
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
mediaFile.mediaId,
|
||||
const MediaFilesCompanion(hasThumbnail: Value(true)),
|
||||
);
|
||||
} else if (mediaFile.type != MediaType.audio) {
|
||||
await mediaService.createThumbnail();
|
||||
}
|
||||
}
|
||||
_updateMigrationCount(_currentState.filesToMigrate - 1);
|
||||
}
|
||||
|
||||
for (final mediaFile in unanalyzedFiles) {
|
||||
final mediaService = MediaFileService(mediaFile);
|
||||
await mediaService.cropTransparentBorders();
|
||||
_updateState(filesToMigrate: _currentState.filesToMigrate - 1);
|
||||
}
|
||||
|
||||
_updateState(filesToMigrate: 0);
|
||||
_updateMigrationCount(0);
|
||||
}
|
||||
|
||||
// 2. Subscribe to stored media files stream
|
||||
await _dbSubscription?.cancel();
|
||||
_dbSubscription = twonlyDB.mediaFilesDao
|
||||
.watchAllStoredMediaFiles()
|
||||
|
|
@ -207,11 +252,6 @@ class MemoriesService {
|
|||
|
||||
Future<void> _processMediaFilesStream(List<MediaFile> mediaFiles) async {
|
||||
try {
|
||||
final now = clock.now();
|
||||
final tempGalleryItems = <MemoryItem>[];
|
||||
final tempGalleryItemsLastYears = <int, List<MemoryItem>>{};
|
||||
|
||||
// High-performance batch DB fetch for sender attribution via Messages table mapping
|
||||
final mediaIds = mediaFiles.map((m) => m.mediaId).toList();
|
||||
final allMessages = await twonlyDB.messagesDao.getMessagesByMediaIds(
|
||||
mediaIds,
|
||||
|
|
@ -230,82 +270,24 @@ class MemoriesService {
|
|||
}
|
||||
}
|
||||
|
||||
for (final mediaFile in mediaFiles) {
|
||||
final mediaService = MediaFileService(mediaFile);
|
||||
if (!mediaService.imagePreviewAvailable) continue;
|
||||
|
||||
if (mediaService.mediaFile.type == MediaType.video) {
|
||||
if (!mediaService.thumbnailPath.existsSync()) {
|
||||
unawaited(mediaService.createThumbnail());
|
||||
}
|
||||
}
|
||||
|
||||
final senderContact = mediaIdToSenderContact[mediaFile.mediaId];
|
||||
final item = MemoryItem(
|
||||
mediaService: mediaService,
|
||||
messages: [],
|
||||
sender: senderContact,
|
||||
);
|
||||
|
||||
tempGalleryItems.add(item);
|
||||
|
||||
if (mediaFile.createdAt.month == now.month &&
|
||||
mediaFile.createdAt.day == now.day) {
|
||||
final diff = now.year - mediaFile.createdAt.year;
|
||||
if (diff > 0) {
|
||||
tempGalleryItemsLastYears.putIfAbsent(diff, () => []).add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort descending by creation date
|
||||
tempGalleryItems.sort(
|
||||
(a, b) => b.mediaService.mediaFile.createdAt.compareTo(
|
||||
a.mediaService.mediaFile.createdAt,
|
||||
),
|
||||
);
|
||||
|
||||
final tempOrderedByMonth = <String, List<int>>{};
|
||||
final tempMonths = <String>[];
|
||||
var lastMonth = '';
|
||||
|
||||
// High performance grouping leveraging pre-computed createdAtMonth column
|
||||
for (var i = 0; i < tempGalleryItems.length; i++) {
|
||||
final mFile = tempGalleryItems[i].mediaService.mediaFile;
|
||||
final month =
|
||||
mFile.createdAtMonth ??
|
||||
DateFormat('MMMM yyyy').format(mFile.createdAt);
|
||||
if (lastMonth != month) {
|
||||
lastMonth = month;
|
||||
tempMonths.add(month);
|
||||
}
|
||||
tempOrderedByMonth.putIfAbsent(month, () => []).add(i);
|
||||
}
|
||||
|
||||
for (final list in tempGalleryItemsLastYears.values) {
|
||||
list.sort(
|
||||
(a, b) => b.mediaService.mediaFile.createdAt.compareTo(
|
||||
a.mediaService.mediaFile.createdAt,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final sortedGalleryItemsLastYears =
|
||||
SplayTreeMap<int, List<MemoryItem>>.from(tempGalleryItemsLastYears);
|
||||
|
||||
final newState = MemoriesState(
|
||||
final newState = _computeState(
|
||||
mediaFiles: mediaFiles,
|
||||
mediaIdToSender: mediaIdToSenderContact,
|
||||
filesToMigrate: _currentState.filesToMigrate,
|
||||
galleryItems: tempGalleryItems,
|
||||
months: tempMonths,
|
||||
orderedByMonth: tempOrderedByMonth,
|
||||
galleryItemsLastYears: sortedGalleryItemsLastYears,
|
||||
);
|
||||
).copyWith(totalFilesToMigrate: _currentState.totalFilesToMigrate);
|
||||
|
||||
for (final item in newState.galleryItems) {
|
||||
if (!item.mediaService.mediaFile.hasThumbnail &&
|
||||
item.mediaService.mediaFile.type != MediaType.audio) {
|
||||
unawaited(item.mediaService.createThumbnail());
|
||||
}
|
||||
}
|
||||
|
||||
_cachedState = newState;
|
||||
_updateStateWithObject(newState);
|
||||
_updateState(newState);
|
||||
|
||||
// Persist to KeyValueStore cache asynchronously
|
||||
final cacheList = tempGalleryItems
|
||||
final cacheList = newState.galleryItems
|
||||
.map(
|
||||
(item) => {
|
||||
'mediaId': item.mediaService.mediaFile.mediaId,
|
||||
|
|
@ -319,15 +301,17 @@ class MemoriesService {
|
|||
}
|
||||
}
|
||||
|
||||
void _updateStateWithObject(MemoriesState newState) {
|
||||
void _updateState(MemoriesState newState) {
|
||||
_currentState = newState;
|
||||
if (!_stateController.isClosed) {
|
||||
_stateController.add(_currentState);
|
||||
}
|
||||
_notifyState();
|
||||
}
|
||||
|
||||
void _updateState({int? filesToMigrate}) {
|
||||
void _updateMigrationCount(int filesToMigrate) {
|
||||
_currentState = _currentState.copyWith(filesToMigrate: filesToMigrate);
|
||||
_notifyState();
|
||||
}
|
||||
|
||||
void _notifyState() {
|
||||
if (!_stateController.isClosed) {
|
||||
_stateController.add(_currentState);
|
||||
}
|
||||
|
|
|
|||
157
lib/src/services/migrations.service.dart
Normal file
157
lib/src/services/migrations.service.dart
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:twonly/core/bridge/wrapper/key_manager.dart';
|
||||
import 'package:twonly/globals.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/constants/secure_storage.keys.dart';
|
||||
import 'package:twonly/src/database/signal/signal_signed_pre_key_store.dart'
|
||||
show getSignalSignedPreKeyStoreOld;
|
||||
import 'package:twonly/src/database/tables/contacts.table.dart';
|
||||
import 'package:twonly/src/database/twonly.db.dart';
|
||||
import 'package:twonly/src/model/json/signal_identity.model.dart';
|
||||
import 'package:twonly/src/services/api/mediafiles/download.api.dart';
|
||||
import 'package:twonly/src/services/user.service.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
import 'package:twonly/src/utils/secure_storage.dart';
|
||||
import 'package:twonly/src/visual/views/onboarding/setup.view.dart';
|
||||
|
||||
Future<void> runMigrations() async {
|
||||
if (userService.currentUser.appVersion < 90) {
|
||||
// BUG: Requested media files for reupload where not reuploaded because the wrong state...
|
||||
await twonlyDB.mediaFilesDao.updateAllRetransmissionUploadingState();
|
||||
await UserService.update((u) => u.appVersion = 90);
|
||||
}
|
||||
|
||||
if (userService.currentUser.appVersion < 91) {
|
||||
// BUG: Requested media files for reupload where not reuploaded because the wrong state...
|
||||
await makeMigrationToVersion91();
|
||||
await UserService.update((u) => u.appVersion = 91);
|
||||
}
|
||||
|
||||
if (userService.currentUser.appVersion < 109) {
|
||||
final contacts = await twonlyDB.contactsDao.getAllContacts();
|
||||
for (final contact in contacts) {
|
||||
if (contact.verified) {
|
||||
await twonlyDB.keyVerificationDao.addKeyVerification(
|
||||
contact.userId,
|
||||
VerificationType.migratedFromOldVersion,
|
||||
);
|
||||
}
|
||||
}
|
||||
await UserService.update((u) {
|
||||
u
|
||||
..appVersion = 109
|
||||
..skipSetupPages = true;
|
||||
if (u.avatarSvg == null) {
|
||||
u.currentSetupPage = SetupPages.profile.name;
|
||||
} else {
|
||||
u.currentSetupPage = SetupPages.shareYourFriends.name;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (userService.currentUser.appVersion < 113) {
|
||||
var migrationSuccess = true;
|
||||
final signalIdentity = await SecureStorage.instance.read(
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
key: SecureStorageKeys.signalIdentity,
|
||||
);
|
||||
|
||||
if (signalIdentity != null) {
|
||||
try {
|
||||
final decoded = jsonDecode(signalIdentity);
|
||||
final identity = SignalIdentity.fromJson(
|
||||
decoded as Map<String, dynamic>,
|
||||
);
|
||||
|
||||
await RustKeyManager.importSignalIdentity(
|
||||
identityKeyPairStructure: identity.identityKeyPairU8List,
|
||||
registrationId: identity.registrationId,
|
||||
signedPreKeyStore: await getSignalSignedPreKeyStoreOld(),
|
||||
);
|
||||
Log.info('Importing signal identify to the rust key manager');
|
||||
|
||||
// Clean up old keys after successful migration
|
||||
await SecureStorage.instance.delete(
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
key: SecureStorageKeys.signalIdentity,
|
||||
);
|
||||
await SecureStorage.instance.delete(
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
key: SecureStorageKeys.signalSignedPreKey,
|
||||
);
|
||||
} catch (e) {
|
||||
Log.error('Failed to migrate signal identity: $e');
|
||||
migrationSuccess = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (migrationSuccess) {
|
||||
await UserService.update((u) {
|
||||
u
|
||||
..appVersion = 113
|
||||
..canUseLoginTokenForAuth = false
|
||||
// As usernames changes where not considered in the old version force users
|
||||
// to reenter there passwords.
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
..twonlySafeBackup?.encryptionKey = []
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
..twonlySafeBackup?.backupId = [];
|
||||
});
|
||||
}
|
||||
}
|
||||
if (userService.currentUser.appVersion < 114) {
|
||||
final allMedia = await twonlyDB.mediaFilesDao
|
||||
.select(twonlyDB.mediaFiles)
|
||||
.get();
|
||||
for (final media in allMedia) {
|
||||
if (media.createdAtMonth == null) {
|
||||
final monthStr = DateFormat('MMMM yyyy').format(media.createdAt);
|
||||
await twonlyDB.mediaFilesDao.updateMedia(
|
||||
media.mediaId,
|
||||
MediaFilesCompanion(createdAtMonth: Value(monthStr)),
|
||||
);
|
||||
}
|
||||
}
|
||||
await UserService.update((u) => u.appVersion = 114);
|
||||
}
|
||||
|
||||
if (userService.currentUser.appVersion < 115) {
|
||||
var migrationSuccess = true;
|
||||
try {
|
||||
final rustStore = await RustKeyManager.loadSignedPrekeys();
|
||||
for (final entry in rustStore.entries) {
|
||||
final companion = SignalSignedPreKeyStoresCompanion(
|
||||
signedPreKeyId: Value(entry.key),
|
||||
signedPreKey: Value(entry.value),
|
||||
);
|
||||
await twonlyDB
|
||||
.into(twonlyDB.signalSignedPreKeyStores)
|
||||
.insert(
|
||||
companion,
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
await RustKeyManager.removeSignedPrekey(signedPreKeyId: entry.key);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.error('Failed to migrate signed prekeys to Drift: $e');
|
||||
migrationSuccess = false;
|
||||
}
|
||||
if (migrationSuccess) {
|
||||
await UserService.update((u) => u.appVersion = 115);
|
||||
}
|
||||
}
|
||||
|
||||
if (kDebugMode) {
|
||||
assert(
|
||||
AppState.latestAppVersionId == 116,
|
||||
'Forgot to update the target version in runMigrations() after incrementing AppState.latestAppVersionId.',
|
||||
);
|
||||
assert(
|
||||
AppState.latestAppVersionId == userService.currentUser.appVersion,
|
||||
"Migration incomplete: currentUser.appVersion (${userService.currentUser.appVersion}) does not match AppState.latestAppVersionId (${AppState.latestAppVersionId}). Ensure the user's appVersion is updated in the migration block.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ Future<void> setupNotificationWithUsers({
|
|||
|
||||
// HotFIX: Search for user with id 0 if not there remove all
|
||||
// and create new push keys with all users.
|
||||
final pushUser = pushUsers.firstWhereOrNull((x) => x.userId == 0);
|
||||
final pushUser = pushUsers.firstWhereOrNull((x) => x.userId.toInt() == 0);
|
||||
if (pushUser == null) {
|
||||
Log.info('Clearing push keys');
|
||||
await setPushKeys(SecureStorageKeys.receivingPushKeys, []);
|
||||
|
|
@ -51,7 +51,7 @@ Future<void> setupNotificationWithUsers({
|
|||
final contacts = await twonlyDB.contactsDao.getAllContacts();
|
||||
for (final contact in contacts) {
|
||||
final pushUser = pushUsers.firstWhereOrNull(
|
||||
(x) => x.userId == contact.userId,
|
||||
(x) => x.userId.toInt() == contact.userId,
|
||||
);
|
||||
|
||||
if (pushUser != null && pushUser.pushKeys.isNotEmpty) {
|
||||
|
|
@ -124,7 +124,9 @@ Future<void> sendNewPushKey(int userId, PushKey pushKey) async {
|
|||
Future<void> updatePushUser(Contact contact) async {
|
||||
final pushKeys = await getPushKeys(SecureStorageKeys.receivingPushKeys);
|
||||
|
||||
final pushUser = pushKeys.firstWhereOrNull((x) => x.userId == contact.userId);
|
||||
final pushUser = pushKeys.firstWhereOrNull(
|
||||
(x) => x.userId.toInt() == contact.userId,
|
||||
);
|
||||
|
||||
if (pushUser == null) {
|
||||
pushKeys.add(
|
||||
|
|
@ -148,7 +150,9 @@ Future<void> updatePushUser(Contact contact) async {
|
|||
Future<void> handleNewPushKey(int fromUserId, int keyId, List<int> key) async {
|
||||
final pushKeys = await getPushKeys(SecureStorageKeys.sendingPushKeys);
|
||||
|
||||
var pushUser = pushKeys.firstWhereOrNull((x) => x.userId == fromUserId);
|
||||
var pushUser = pushKeys.firstWhereOrNull(
|
||||
(x) => x.userId.toInt() == fromUserId,
|
||||
);
|
||||
|
||||
if (pushUser == null) {
|
||||
final contact = await twonlyDB.contactsDao
|
||||
|
|
@ -164,7 +168,7 @@ Future<void> handleNewPushKey(int fromUserId, int keyId, List<int> key) async {
|
|||
lastMessageId: uuid.v7(),
|
||||
),
|
||||
);
|
||||
pushUser = pushKeys.firstWhereOrNull((x) => x.userId == fromUserId);
|
||||
pushUser = pushKeys.firstWhereOrNull((x) => x.userId.toInt() == fromUserId);
|
||||
}
|
||||
|
||||
if (pushUser == null) {
|
||||
|
|
@ -187,7 +191,9 @@ Future<void> handleNewPushKey(int fromUserId, int keyId, List<int> key) async {
|
|||
Future<void> updateLastMessageId(int fromUserId, String messageId) async {
|
||||
final pushUsers = await getPushKeys(SecureStorageKeys.receivingPushKeys);
|
||||
|
||||
final pushUser = pushUsers.firstWhereOrNull((x) => x.userId == fromUserId);
|
||||
final pushUser = pushUsers.firstWhereOrNull(
|
||||
(x) => x.userId.toInt() == fromUserId,
|
||||
);
|
||||
if (pushUser == null) {
|
||||
unawaited(setupNotificationWithUsers());
|
||||
return;
|
||||
|
|
@ -285,7 +291,7 @@ Future<PushNotification?> getPushNotificationFromEncryptedContent(
|
|||
|
||||
if (content.hasMediaUpdate()) {
|
||||
final msg = await twonlyDB.messagesDao
|
||||
.getMessageById(content.reaction.targetMessageId)
|
||||
.getMessageById(content.mediaUpdate.targetMessageId)
|
||||
.getSingleOrNull();
|
||||
// These notifications should only be send to the original sender.
|
||||
if (msg == null || msg.senderId != toUserId) {
|
||||
|
|
@ -304,7 +310,9 @@ Future<PushNotification?> getPushNotificationFromEncryptedContent(
|
|||
if (content.hasGroupCreate()) {
|
||||
kind = PushKind.ADDED_TO_GROUP;
|
||||
final group = await twonlyDB.groupsDao.getGroup(content.groupId);
|
||||
additionalContent = group!.groupName;
|
||||
if (group != null) {
|
||||
additionalContent = group.groupName;
|
||||
}
|
||||
}
|
||||
|
||||
if (kind == null) return null;
|
||||
|
|
@ -339,7 +347,9 @@ Future<Uint8List?> encryptPushNotification(
|
|||
var key = 'InsecureOnlyUsedForAddingContact'.codeUnits;
|
||||
var keyId = 0;
|
||||
|
||||
final pushUser = pushKeys.firstWhereOrNull((x) => x.userId == toUserId);
|
||||
final pushUser = pushKeys.firstWhereOrNull(
|
||||
(x) => x.userId.toInt() == toUserId,
|
||||
);
|
||||
|
||||
if (pushUser == null) {
|
||||
// user does not have send any push keys
|
||||
|
|
|
|||
8
lib/src/services/profile.service.dart
Normal file
8
lib/src/services/profile.service.dart
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
enum SetupProfile { standard, customized, maximum }
|
||||
|
||||
enum SecurityProfile { normal, strict }
|
||||
|
||||
extension SecurityProfileExtension on SecurityProfile {
|
||||
bool get showWarningForNonVerifiedContacts => this == SecurityProfile.strict;
|
||||
bool get showOnlyVerifiedInChatViewList => this == SecurityProfile.normal;
|
||||
}
|
||||
|
|
@ -42,62 +42,72 @@ signalDecryptMessage(
|
|||
) async {
|
||||
// Hold the lock only for the cryptographic operation, not for network I/O
|
||||
Log.info('Acquiring lockingSignalProtocol for $fromUserId');
|
||||
final (decryptedContent, errorType, needsResync) = await lockingSignalProtocol
|
||||
.protect(() async {
|
||||
Log.info('Lock acquired for $fromUserId');
|
||||
try {
|
||||
final session = SessionCipher.fromStore(
|
||||
(await getSignalStore())!,
|
||||
getSignalAddress(fromUserId),
|
||||
);
|
||||
final (
|
||||
decryptedContent,
|
||||
errorType,
|
||||
needsResync,
|
||||
) = await lockingSignalProtocol.protect(() async {
|
||||
Log.info('Lock acquired for $fromUserId');
|
||||
try {
|
||||
final session = SessionCipher.fromStore(
|
||||
(await getSignalStore())!,
|
||||
getSignalAddress(fromUserId),
|
||||
);
|
||||
|
||||
Uint8List plaintext;
|
||||
Uint8List plaintext;
|
||||
|
||||
switch (type) {
|
||||
case CiphertextMessage.prekeyType:
|
||||
plaintext = await session.decrypt(
|
||||
PreKeySignalMessage(encryptedContentRaw),
|
||||
);
|
||||
case CiphertextMessage.whisperType:
|
||||
plaintext = await session.decryptFromSignal(
|
||||
SignalMessage.fromSerialized(encryptedContentRaw),
|
||||
);
|
||||
default:
|
||||
Log.error('Unknown Message Decryption Type: $type');
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
return (EncryptedContent.fromBuffer(plaintext), null, false);
|
||||
} on InvalidKeyIdException catch (e) {
|
||||
Log.warn(e);
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.PREKEY_UNKNOWN,
|
||||
false,
|
||||
switch (type) {
|
||||
case CiphertextMessage.prekeyType:
|
||||
plaintext = await session.decrypt(
|
||||
PreKeySignalMessage(encryptedContentRaw),
|
||||
);
|
||||
} on DuplicateMessageException catch (e) {
|
||||
Log.info(e.toString());
|
||||
return (null, null, false);
|
||||
} on InvalidMessageException catch (e) {
|
||||
Log.warn(e);
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
true,
|
||||
case CiphertextMessage.whisperType:
|
||||
plaintext = await session.decryptFromSignal(
|
||||
SignalMessage.fromSerialized(encryptedContentRaw),
|
||||
);
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
default:
|
||||
Log.error('Unknown Message Decryption Type: $type');
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (EncryptedContent.fromBuffer(plaintext), null, false);
|
||||
} on InvalidKeyIdException catch (e) {
|
||||
Log.warn(e);
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.PREKEY_UNKNOWN,
|
||||
false,
|
||||
);
|
||||
} on DuplicateMessageException catch (e) {
|
||||
// This is normal behavior: This can happen in case a message was decrypted, but before further processing
|
||||
// the user killed the app. This results in a new transmission from the server, but as the message was already
|
||||
// decrypted, this error happens. In this case, request the message again.
|
||||
Log.info(e);
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
false,
|
||||
);
|
||||
} on InvalidMessageException catch (e) {
|
||||
Log.warn(e);
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
true,
|
||||
);
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
return (
|
||||
null,
|
||||
PlaintextContent_DecryptionErrorMessage_Type.UNKNOWN,
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Log.info('Released lockingSignalProtocol for $fromUserId');
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import 'dart:convert';
|
|||
import 'package:mutex/mutex.dart';
|
||||
import 'package:twonly/core/bridge/wrapper/key_manager.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/constants/secure_storage.keys.dart';
|
||||
import 'package:twonly/src/model/json/userdata.model.dart';
|
||||
import 'package:twonly/src/utils/keyvalue.dart';
|
||||
import 'package:twonly/src/utils/log.dart';
|
||||
|
|
@ -33,12 +32,19 @@ class UserService {
|
|||
if (userDataMap != null) {
|
||||
final userData = UserData.fromJson(userDataMap);
|
||||
await RustKeyManager.setUserId(userId: userData.userId);
|
||||
try {
|
||||
// Ensure that the old userData is removed as it breaks the backup mechanism.
|
||||
// This code can be removed when all users have updated to the latest version...
|
||||
await SecureStorage.instance.delete(key: 'userData');
|
||||
} catch (e) {
|
||||
Log.error('Could not delete user data from SecureStorage: $e');
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
|
||||
// 2. If not found, try to load from SecureStorage (Migration path)
|
||||
final userDataJson = await SecureStorage.instance.read(
|
||||
key: SecureStorageKeys.userData,
|
||||
key: 'userData',
|
||||
);
|
||||
|
||||
if (userDataJson != null) {
|
||||
|
|
@ -59,15 +65,20 @@ class UserService {
|
|||
}
|
||||
|
||||
static Future<void> _migrateFromSecureStorage(UserData userData) async {
|
||||
// Currently empty migration logic as requested, but we MUST store the data
|
||||
await KeyValueStore.put('user', userData.toJson());
|
||||
|
||||
try {
|
||||
await RustKeyManager.setUserId(userId: userData.userId);
|
||||
} catch (e) {
|
||||
Log.error('Could not set userId in RustKeyManager during migration: $e');
|
||||
}
|
||||
|
||||
// Optional: Log migration
|
||||
try {
|
||||
await SecureStorage.instance.delete(key: 'userData');
|
||||
} catch (e) {
|
||||
Log.error('Could not delete user data from SecureStorage: $e');
|
||||
}
|
||||
|
||||
Log.info('Migrated user data from SecureStorage to KeyValueStore');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -104,7 +104,8 @@ class UserDiscoveryService {
|
|||
|
||||
static Future<Uint8List?> getCurrentVersion() async {
|
||||
try {
|
||||
return await FlutterUserDiscovery.getCurrentVersion();
|
||||
return await FlutterUserDiscovery.getCurrentVersion()
|
||||
.timeout(const Duration(seconds: 5));
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
return null;
|
||||
|
|
@ -140,7 +141,7 @@ class UserDiscoveryService {
|
|||
return await FlutterUserDiscovery.shouldRequestNewMessages(
|
||||
contactId: fromUserId,
|
||||
version: receivedVersion,
|
||||
);
|
||||
).timeout(const Duration(seconds: 5));
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
return null;
|
||||
|
|
@ -155,7 +156,7 @@ class UserDiscoveryService {
|
|||
return await FlutterUserDiscovery.getNewMessages(
|
||||
contactId: fromUserId,
|
||||
receivedVersion: receivedVersion,
|
||||
);
|
||||
).timeout(const Duration(seconds: 5));
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
return null;
|
||||
|
|
@ -175,7 +176,7 @@ class UserDiscoveryService {
|
|||
messages: messages,
|
||||
publicKeyVerifiedTimestamp:
|
||||
verifications.lastOrNull?.createdAt.millisecondsSinceEpoch,
|
||||
);
|
||||
).timeout(const Duration(seconds: 5));
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,10 +18,13 @@ class Log {
|
|||
Logger.root.onRecord.listen((record) async {
|
||||
unawaited(_writeLogToFile(record));
|
||||
if (!kReleaseMode) {
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'${record.level.name} [${AppState.isInBackgroundTask ? 'b' : 'f'}] [twonly] ${record.loggerName} > ${record.message}',
|
||||
);
|
||||
if (!Platform.environment.containsKey('FLUTTER_TEST') ||
|
||||
record.level >= Level.WARNING) {
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'${record.level.name} [${AppState.isInBackgroundTask ? 'b' : 'f'}] [twonly] ${record.loggerName} > ${record.message}',
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -136,7 +139,7 @@ Future<void> cleanLogFile() async {
|
|||
}
|
||||
final lines = await logFile.readAsLines();
|
||||
|
||||
final twoWeekAgo = clock.now().subtract(const Duration(days: 14));
|
||||
final twoWeekAgo = clock.now().subtract(const Duration(days: 3));
|
||||
var keepStartIndex = -1;
|
||||
|
||||
for (var i = 0; i < lines.length; i += 100) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:convert/convert.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
|
@ -7,6 +8,7 @@ import 'package:flutter/material.dart';
|
|||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_image_compress/flutter_image_compress.dart';
|
||||
import 'package:gal/gal.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:local_auth/local_auth.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
|
@ -31,19 +33,49 @@ extension ShortCutsExtension on BuildContext {
|
|||
}
|
||||
}
|
||||
|
||||
Future<String?> saveImageToGallery(Uint8List imageBytes) async {
|
||||
Future<String?> saveImageToGallery(
|
||||
Uint8List imageBytes, {
|
||||
DateTime? createdAt,
|
||||
}) async {
|
||||
var bytesToProcess = imageBytes;
|
||||
|
||||
if (createdAt != null) {
|
||||
try {
|
||||
final image = img.decodeImage(imageBytes);
|
||||
if (image != null) {
|
||||
final formattedDate = DateFormat(
|
||||
'yyyy:MM:dd HH:mm:ss',
|
||||
).format(createdAt);
|
||||
image.exif.imageIfd[0x0132] = img.IfdValueAscii(
|
||||
formattedDate,
|
||||
); // DateTime
|
||||
image.exif.exifIfd[0x9003] = img.IfdValueAscii(
|
||||
formattedDate,
|
||||
); // DateTimeOriginal
|
||||
image.exif.exifIfd[0x9004] = img.IfdValueAscii(
|
||||
formattedDate,
|
||||
); // DateTimeDigitized
|
||||
|
||||
bytesToProcess = img.encodeJpg(image);
|
||||
}
|
||||
} catch (e) {
|
||||
Log.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
final jpgImages = await FlutterImageCompress.compressWithList(
|
||||
// ignore: avoid_redundant_argument_values
|
||||
format: CompressFormat.jpeg,
|
||||
imageBytes,
|
||||
bytesToProcess,
|
||||
quality: 100,
|
||||
keepExif: true,
|
||||
);
|
||||
final hasAccess = await Gal.hasAccess();
|
||||
final hasAccess = await Gal.hasAccess(toAlbum: true);
|
||||
if (!hasAccess) {
|
||||
await Gal.requestAccess();
|
||||
await Gal.requestAccess(toAlbum: true);
|
||||
}
|
||||
try {
|
||||
await Gal.putImageBytes(jpgImages);
|
||||
await Gal.putImageBytes(jpgImages, album: 'twonly');
|
||||
return null;
|
||||
} on GalException catch (e) {
|
||||
Log.error(e);
|
||||
|
|
@ -52,12 +84,12 @@ Future<String?> saveImageToGallery(Uint8List imageBytes) async {
|
|||
}
|
||||
|
||||
Future<String?> saveVideoToGallery(String videoPath) async {
|
||||
final hasAccess = await Gal.hasAccess();
|
||||
final hasAccess = await Gal.hasAccess(toAlbum: true);
|
||||
if (!hasAccess) {
|
||||
await Gal.requestAccess();
|
||||
await Gal.requestAccess(toAlbum: true);
|
||||
}
|
||||
try {
|
||||
await Gal.putVideo(videoPath);
|
||||
await Gal.putVideo(videoPath, album: 'twonly');
|
||||
return null;
|
||||
} on GalException catch (e) {
|
||||
Log.error(e);
|
||||
|
|
@ -293,9 +325,10 @@ Future<List<int>> sha256File(File file) async {
|
|||
List<TextSpan> formattedText(
|
||||
BuildContext context,
|
||||
String input, {
|
||||
Color? textColor,
|
||||
Color? boldTextColor,
|
||||
}) {
|
||||
final defaultColor = Theme.of(context).colorScheme.onSurface;
|
||||
final defaultColor = textColor ?? Theme.of(context).colorScheme.onSurface;
|
||||
|
||||
final regex = RegExp(r'\*(.*?)\*');
|
||||
final spans = <TextSpan>[];
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:collection/collection.dart' show ListExtensions;
|
||||
import 'package:drift/drift.dart' show Value;
|
||||
import 'package:fixnum/fixnum.dart';
|
||||
|
|
@ -41,6 +42,7 @@ class QrCodeUtils {
|
|||
signedPrekeySignature: signedPreKey.signature,
|
||||
signedPrekeyId: Int64(signedPreKey.id),
|
||||
secretVerificationToken: secretVerificationToken,
|
||||
timestamp: Int64(clock.now().millisecondsSinceEpoch),
|
||||
);
|
||||
|
||||
final data = publicProfile.writeToBuffer();
|
||||
|
|
@ -94,7 +96,18 @@ class QrCodeUtils {
|
|||
);
|
||||
|
||||
if (verificationOk) {
|
||||
if (profile.hasSecretVerificationToken()) {
|
||||
var useSecretVerificationToken = profile.hasSecretVerificationToken();
|
||||
if (profile.hasTimestamp()) {
|
||||
// Only notify the scanned user if the QR code was generated within the last 10 minutes.
|
||||
final timestamp = DateTime.fromMillisecondsSinceEpoch(
|
||||
profile.timestamp.toInt(),
|
||||
);
|
||||
final tenMinutesAgo = clock.now().subtract(const Duration(minutes: 10));
|
||||
if (timestamp.isBefore(tenMinutesAgo)) {
|
||||
useSecretVerificationToken = false;
|
||||
}
|
||||
}
|
||||
if (useSecretVerificationToken) {
|
||||
unawaited(
|
||||
KeyVerificationService.handleScannedVerificationToken(
|
||||
contact.userId,
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ class StartupGuard {
|
|||
final stat = file.statSync();
|
||||
final diff = DateTime.now().difference(stat.modified);
|
||||
|
||||
final starting = diff.inSeconds < 30;
|
||||
final starting = diff.inSeconds < 5;
|
||||
if (starting) {
|
||||
Log.info(
|
||||
'Startup guard: App is currently starting (${diff.inSeconds}s ago).',
|
||||
|
|
|
|||
56
lib/src/visual/components/contact_request_badge.comp.dart
Normal file
56
lib/src/visual/components/contact_request_badge.comp.dart
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/constants/routes.keys.dart';
|
||||
import 'package:twonly/src/utils/misc.dart';
|
||||
import 'package:twonly/src/visual/components/notification_badge.comp.dart';
|
||||
import 'package:twonly/src/visual/themes/light.dart';
|
||||
|
||||
class ContactRequestBadgeComp extends StatelessWidget {
|
||||
const ContactRequestBadgeComp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return StreamBuilder<int?>(
|
||||
stream: twonlyDB.contactsDao.watchContactsRequestedCount(),
|
||||
builder: (context, snapshot) {
|
||||
final count = snapshot.data ?? 0;
|
||||
if (count == 0) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: const BoxDecoration(
|
||||
color: primaryColor,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: NotificationBadgeComp(
|
||||
backgroundColor: isDarkMode(context) ? Colors.white : Colors.black,
|
||||
textColor: isDarkMode(context) ? Colors.black : Colors.white,
|
||||
count: count.toString(),
|
||||
child: IconButton(
|
||||
color: Colors.black,
|
||||
icon: const FaIcon(
|
||||
FontAwesomeIcons.userPlus,
|
||||
size: 18,
|
||||
),
|
||||
onPressed: () => context.push(Routes.chatsAddNewUser),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
342
lib/src/visual/components/draggable_scrollbar.comp.dart
Normal file
342
lib/src/visual/components/draggable_scrollbar.comp.dart
Normal file
|
|
@ -0,0 +1,342 @@
|
|||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
|
||||
|
||||
typedef TextLabelBuilder = Widget Function(String label);
|
||||
|
||||
class DraggableScrollbar extends StatefulWidget {
|
||||
const DraggableScrollbar({
|
||||
required this.controller,
|
||||
required this.child,
|
||||
this.labelBuilder,
|
||||
super.key,
|
||||
});
|
||||
final ScrollController controller;
|
||||
final Widget child;
|
||||
final String? Function(double scrollOffset)? labelBuilder;
|
||||
|
||||
@override
|
||||
State<DraggableScrollbar> createState() => _DraggableScrollbarState();
|
||||
|
||||
static const double labelThumbPadding = 16;
|
||||
}
|
||||
|
||||
class _DraggableScrollbarState extends State<DraggableScrollbar>
|
||||
with TickerProviderStateMixin {
|
||||
final ValueNotifier<double> _thumbOffsetNotifier = ValueNotifier(0);
|
||||
final ValueNotifier<double> _viewOffsetNotifier = ValueNotifier(0);
|
||||
bool _isDragInProcess = false;
|
||||
double _boundlessThumbOffset = 0;
|
||||
|
||||
late AnimationController _thumbAnimationController;
|
||||
late CurvedAnimation _thumbAnimation;
|
||||
late AnimationController _labelAnimationController;
|
||||
late CurvedAnimation _labelAnimation;
|
||||
Timer? _fadeoutTimer;
|
||||
|
||||
static const double thumbHeight = 60;
|
||||
static const double thumbWidth = 20;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_thumbAnimationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
);
|
||||
|
||||
_thumbAnimation = CurvedAnimation(
|
||||
parent: _thumbAnimationController,
|
||||
curve: Curves.fastOutSlowIn,
|
||||
);
|
||||
|
||||
_labelAnimationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
);
|
||||
|
||||
_labelAnimation = CurvedAnimation(
|
||||
parent: _labelAnimationController,
|
||||
curve: Curves.fastOutSlowIn,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_thumbOffsetNotifier.dispose();
|
||||
_viewOffsetNotifier.dispose();
|
||||
_thumbAnimation.dispose();
|
||||
_thumbAnimationController.dispose();
|
||||
_labelAnimation.dispose();
|
||||
_labelAnimationController.dispose();
|
||||
_fadeoutTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
ScrollController get controller => widget.controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return NotificationListener<ScrollNotification>(
|
||||
onNotification: (notification) {
|
||||
_onScrollNotification(notification);
|
||||
return false;
|
||||
},
|
||||
child: Stack(
|
||||
children: [
|
||||
RepaintBoundary(
|
||||
child: widget.child,
|
||||
),
|
||||
// Scrollbar layer restricted to SafeArea
|
||||
SafeArea(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final maxThumbOffset = constraints.maxHeight - thumbHeight;
|
||||
|
||||
return ExcludeSemantics(
|
||||
child: RepaintBoundary(
|
||||
child: ValueListenableBuilder<double>(
|
||||
valueListenable: _thumbOffsetNotifier,
|
||||
builder: (context, thumbOffset, child) {
|
||||
final isDark =
|
||||
Theme.of(context).brightness == Brightness.dark;
|
||||
final handleColor = isDark
|
||||
? Colors.grey.shade900
|
||||
: Colors.white;
|
||||
final iconColor = isDark
|
||||
? Colors.white70
|
||||
: Colors.black54;
|
||||
|
||||
final label = widget.labelBuilder?.call(
|
||||
_viewOffsetNotifier.value,
|
||||
);
|
||||
|
||||
return Container(
|
||||
alignment: AlignmentDirectional.topEnd,
|
||||
padding: EdgeInsets.only(top: thumbOffset),
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onVerticalDragStart: (_) => _onVerticalDragStart(),
|
||||
onVerticalDragUpdate: (details) =>
|
||||
_onVerticalDragUpdate(
|
||||
details.delta.dy,
|
||||
maxThumbOffset,
|
||||
),
|
||||
onVerticalDragEnd: (_) => _onVerticalDragEnd(),
|
||||
child: SlideFadeTransition(
|
||||
animation: _thumbAnimation,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
if (label != null && _isDragInProcess)
|
||||
FadeTransition(
|
||||
opacity: _labelAnimation,
|
||||
child: ScaleTransition(
|
||||
scale: _labelAnimation,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(
|
||||
right: DraggableScrollbar
|
||||
.labelThumbPadding,
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 6,
|
||||
horizontal: 12,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
(isDark
|
||||
? Colors.grey.shade900
|
||||
: Colors.grey.shade200)
|
||||
.withValues(alpha: 0.95),
|
||||
borderRadius: BorderRadius.circular(
|
||||
8,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(
|
||||
alpha: 0.2,
|
||||
),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: isDark
|
||||
? Colors.white
|
||||
: Colors.black,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
width: thumbWidth,
|
||||
height: thumbHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: handleColor,
|
||||
border: Border.all(
|
||||
color: isDark
|
||||
? Colors.white10
|
||||
: Colors.black12,
|
||||
width: 0.5,
|
||||
),
|
||||
borderRadius: const BorderRadius.only(
|
||||
topLeft: Radius.circular(8),
|
||||
bottomLeft: Radius.circular(8),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment:
|
||||
MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
top: 4,
|
||||
),
|
||||
child: FaIcon(
|
||||
FontAwesomeIcons.angleUp,
|
||||
size: 14,
|
||||
color: iconColor,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
bottom: 4,
|
||||
),
|
||||
child: FaIcon(
|
||||
FontAwesomeIcons.angleDown,
|
||||
size: 14,
|
||||
color: iconColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _onScrollNotification(ScrollNotification notification) {
|
||||
final scrollMetrics = notification.metrics;
|
||||
if (scrollMetrics.minScrollExtent >= scrollMetrics.maxScrollExtent) return;
|
||||
|
||||
_viewOffsetNotifier.value = scrollMetrics.pixels;
|
||||
|
||||
if (!_isDragInProcess) {
|
||||
if (notification is ScrollUpdateNotification) {
|
||||
// Find constraints and update thumb offset
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
final renderBox = context.findRenderObject() as RenderBox?;
|
||||
if (renderBox == null) return;
|
||||
|
||||
// Subtract SafeArea top/bottom
|
||||
final padding = MediaQuery.paddingOf(context);
|
||||
final availableHeight = renderBox.size.height - padding.vertical;
|
||||
final maxThumbOffset = availableHeight - thumbHeight;
|
||||
|
||||
final scrollExtent =
|
||||
scrollMetrics.pixels /
|
||||
scrollMetrics.maxScrollExtent *
|
||||
maxThumbOffset;
|
||||
_thumbOffsetNotifier.value = scrollExtent.clamp(0.0, maxThumbOffset);
|
||||
});
|
||||
}
|
||||
|
||||
if (notification is ScrollUpdateNotification ||
|
||||
notification is OverscrollNotification) {
|
||||
_showThumb();
|
||||
_scheduleFadeout();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _onVerticalDragStart() {
|
||||
_boundlessThumbOffset = _thumbOffsetNotifier.value;
|
||||
_labelAnimationController.forward();
|
||||
_fadeoutTimer?.cancel();
|
||||
_showThumb();
|
||||
setState(() => _isDragInProcess = true);
|
||||
}
|
||||
|
||||
void _onVerticalDragUpdate(double deltaY, double maxThumbOffset) {
|
||||
_showThumb();
|
||||
if (_isDragInProcess && maxThumbOffset > 0) {
|
||||
_boundlessThumbOffset += deltaY;
|
||||
_thumbOffsetNotifier.value = _boundlessThumbOffset.clamp(
|
||||
0.0,
|
||||
maxThumbOffset,
|
||||
);
|
||||
|
||||
final max = controller.position.maxScrollExtent;
|
||||
final scrollOffset = (_thumbOffsetNotifier.value / maxThumbOffset) * max;
|
||||
controller.jumpTo(
|
||||
scrollOffset.clamp(0.0, controller.position.maxScrollExtent),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _onVerticalDragEnd() {
|
||||
_scheduleFadeout();
|
||||
setState(() => _isDragInProcess = false);
|
||||
}
|
||||
|
||||
void _showThumb() {
|
||||
if (_thumbAnimationController.status != AnimationStatus.forward) {
|
||||
_thumbAnimationController.forward();
|
||||
}
|
||||
}
|
||||
|
||||
void _scheduleFadeout() {
|
||||
_fadeoutTimer?.cancel();
|
||||
_fadeoutTimer = Timer(const Duration(milliseconds: 1500), () {
|
||||
_thumbAnimationController.reverse();
|
||||
_labelAnimationController.reverse();
|
||||
_fadeoutTimer = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class SlideFadeTransition extends StatelessWidget {
|
||||
const SlideFadeTransition({
|
||||
required this.animation,
|
||||
required this.child,
|
||||
super.key,
|
||||
});
|
||||
final Animation<double> animation;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: animation,
|
||||
builder: (context, child) {
|
||||
return Opacity(
|
||||
opacity: animation.value,
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -53,8 +53,12 @@ class EmojiPickerBottom extends StatelessWidget {
|
|||
config: Config(
|
||||
height: 400,
|
||||
locale: Localizations.localeOf(context),
|
||||
checkPlatformCompatibility: false,
|
||||
emojiTextStyle: TextStyle(
|
||||
fontSize: 24 * (Platform.isIOS ? 1.2 : 1),
|
||||
fontFamilyFallback: Platform.isAndroid
|
||||
? const ['NotoColorEmoji']
|
||||
: null,
|
||||
),
|
||||
emojiViewConfig: EmojiViewConfig(
|
||||
backgroundColor: context.color.surfaceContainer,
|
||||
|
|
|
|||
96
lib/src/visual/components/profile_qr_code.comp.dart
Normal file
96
lib/src/visual/components/profile_qr_code.comp.dart
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
import 'package:twonly/src/utils/avatars.dart';
|
||||
import 'package:twonly/src/utils/misc.dart';
|
||||
import 'package:twonly/src/utils/qr.utils.dart';
|
||||
|
||||
class ProfileQrCodeComp extends StatefulWidget {
|
||||
const ProfileQrCodeComp({
|
||||
this.size = 250,
|
||||
this.showAvatar = true,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final double size;
|
||||
final bool showAvatar;
|
||||
|
||||
@override
|
||||
State<ProfileQrCodeComp> createState() => _ProfileQrCodeCompState();
|
||||
}
|
||||
|
||||
class _ProfileQrCodeCompState extends State<ProfileQrCodeComp> {
|
||||
String? _qrCode;
|
||||
Uint8List? _userAvatar;
|
||||
bool _isLoading = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadData();
|
||||
}
|
||||
|
||||
Future<void> _loadData() async {
|
||||
final qr = await QrCodeUtils.publicProfileLink();
|
||||
final avatar = widget.showAvatar ? await getUserAvatar() : null;
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_qrCode = qr;
|
||||
_userAvatar = avatar;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final loaded = !_isLoading && _qrCode != null;
|
||||
return SizedBox(
|
||||
width: widget.size,
|
||||
height: widget.size,
|
||||
child: AnimatedSwitcher(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
child: loaded
|
||||
? Container(
|
||||
key: const ValueKey('qr_code_container'),
|
||||
// padding: const EdgeInsets.all(3),
|
||||
decoration: BoxDecoration(
|
||||
color: context.color.primary,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black26,
|
||||
blurRadius: 3,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: QrImageView.withQr(
|
||||
qr: QrCode.fromData(
|
||||
data: _qrCode!,
|
||||
errorCorrectLevel: QrErrorCorrectLevel.M,
|
||||
),
|
||||
eyeStyle: QrEyeStyle(
|
||||
color: isDarkMode(context) ? Colors.black : Colors.white,
|
||||
borderRadius: 2,
|
||||
),
|
||||
dataModuleStyle: QrDataModuleStyle(
|
||||
color: isDarkMode(context) ? Colors.black : Colors.white,
|
||||
borderRadius: 2,
|
||||
),
|
||||
gapless: false,
|
||||
embeddedImage: (widget.showAvatar && _userAvatar != null) ? MemoryImage(_userAvatar!) : null,
|
||||
embeddedImageStyle: QrEmbeddedImageStyle(
|
||||
size: const Size(60, 66),
|
||||
embeddedImageShape: EmbeddedImageShape.square,
|
||||
shapeColor: context.color.primary,
|
||||
safeArea: true,
|
||||
),
|
||||
size: widget.size,
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(key: ValueKey('qr_code_placeholder')),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
77
lib/src/visual/components/selectable_thumbnail.comp.dart
Normal file
77
lib/src/visual/components/selectable_thumbnail.comp.dart
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:twonly/src/utils/misc.dart';
|
||||
|
||||
class SelectableThumbnailComp extends StatelessWidget {
|
||||
const SelectableThumbnailComp({
|
||||
required this.child,
|
||||
required this.isSelected,
|
||||
this.selectionMode = true,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final bool isSelected;
|
||||
final bool selectionMode;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeInOut,
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected ? context.color.primary : Colors.transparent,
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black12,
|
||||
blurRadius: 4,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeInOut,
|
||||
margin: EdgeInsets.all(isSelected ? 4 : 0),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(
|
||||
isSelected ? 12 : 0,
|
||||
),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
child,
|
||||
if (selectionMode)
|
||||
Positioned(
|
||||
top: 6,
|
||||
right: 6,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(2),
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? context.color.primary
|
||||
: Colors.black38,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.white
|
||||
: Colors.black,
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
child: isSelected
|
||||
? const Icon(
|
||||
Icons.check,
|
||||
size: 14,
|
||||
color: Colors.white,
|
||||
)
|
||||
: const SizedBox(width: 14, height: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -62,7 +62,12 @@ void _showOverlay({
|
|||
required Duration displayDuration,
|
||||
required void Function(AnimationController) onAnimationControllerInit,
|
||||
}) {
|
||||
final overlayState = Overlay.maybeOf(context);
|
||||
var overlayState = Overlay.maybeOf(context);
|
||||
if (overlayState == null) {
|
||||
if (context is StatefulElement && context.state is NavigatorState) {
|
||||
overlayState = (context.state as NavigatorState).overlay;
|
||||
}
|
||||
}
|
||||
if (overlayState == null) return;
|
||||
|
||||
late OverlayEntry overlayEntry;
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ class VerificationBadgeComp extends StatefulWidget {
|
|||
|
||||
class _VerificationBadgeCompState extends State<VerificationBadgeComp> {
|
||||
bool _isVerified = false;
|
||||
bool _isVerifiedByTransferredTrust = false;
|
||||
int _verifiedByTransferredTrustCount = 0;
|
||||
|
||||
StreamSubscription<VerificationStatus>? _streamAllVerified;
|
||||
StreamSubscription<List<KeyVerification>>? _streamContactVerification;
|
||||
|
|
@ -42,25 +42,40 @@ class _VerificationBadgeCompState extends State<VerificationBadgeComp> {
|
|||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.group != null) {
|
||||
initAsync();
|
||||
}
|
||||
|
||||
Future<void> initAsync() async {
|
||||
var group = widget.group;
|
||||
var contact = widget.contact;
|
||||
|
||||
if (group?.isDirectChat == true) {
|
||||
final members = await twonlyDB.groupsDao.getGroupContact(group!.groupId);
|
||||
if (members.isNotEmpty) {
|
||||
contact = members.first;
|
||||
group = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (group != null) {
|
||||
_streamAllVerified = twonlyDB.keyVerificationDao
|
||||
.watchAllGroupMembersVerified(widget.group!.groupId)
|
||||
.watchAllGroupMembersVerified(group.groupId)
|
||||
.listen((update) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isVerified = false;
|
||||
_isVerifiedByTransferredTrust = false;
|
||||
_verifiedByTransferredTrustCount = 0;
|
||||
if (update == VerificationStatus.trusted) {
|
||||
_isVerified = true;
|
||||
}
|
||||
if (update == VerificationStatus.partialTrusted) {
|
||||
_isVerifiedByTransferredTrust = true;
|
||||
_verifiedByTransferredTrustCount = 10;
|
||||
}
|
||||
});
|
||||
});
|
||||
} else if (widget.contact != null) {
|
||||
} else if (contact != null) {
|
||||
_streamContactVerification = twonlyDB.keyVerificationDao
|
||||
.watchContactVerification(widget.contact!.userId)
|
||||
.watchContactVerification(contact.userId)
|
||||
.listen((update) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
|
|
@ -69,16 +84,16 @@ class _VerificationBadgeCompState extends State<VerificationBadgeComp> {
|
|||
});
|
||||
|
||||
_streamTransferredTrust = twonlyDB.keyVerificationDao
|
||||
.watchTransferredTrustVerifications(widget.contact!.userId)
|
||||
.watchTransferredTrustVerifications(contact.userId)
|
||||
.listen((update) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isVerifiedByTransferredTrust = update.isNotEmpty;
|
||||
_verifiedByTransferredTrustCount = update.length;
|
||||
});
|
||||
});
|
||||
} else if (widget.isVerifiedByTransferredTrust != null) {
|
||||
setState(() {
|
||||
_isVerifiedByTransferredTrust = widget.isVerifiedByTransferredTrust!;
|
||||
_verifiedByTransferredTrustCount = 10;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -94,7 +109,7 @@ class _VerificationBadgeCompState extends State<VerificationBadgeComp> {
|
|||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!_isVerified &&
|
||||
!_isVerifiedByTransferredTrust &&
|
||||
_verifiedByTransferredTrustCount == 0 &&
|
||||
widget.showOnlyIfVerified) {
|
||||
return Container();
|
||||
}
|
||||
|
|
@ -112,10 +127,12 @@ class _VerificationBadgeCompState extends State<VerificationBadgeComp> {
|
|||
bottom: 3,
|
||||
),
|
||||
child: SvgIcon(
|
||||
assetPath: (_isVerified || _isVerifiedByTransferredTrust)
|
||||
assetPath: _isVerified
|
||||
? SvgIcons.verifiedGreen
|
||||
: _verifiedByTransferredTrustCount > 0
|
||||
? SvgIcons.verifiedNumeric(_verifiedByTransferredTrustCount)
|
||||
: SvgIcons.verifiedRed,
|
||||
color: (_isVerifiedByTransferredTrust && !_isVerified)
|
||||
color: (_verifiedByTransferredTrustCount > 0 && !_isVerified)
|
||||
? colorVerificationBadgeYellow
|
||||
: null,
|
||||
size: widget.size,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:twonly/locator.dart';
|
||||
import 'package:twonly/src/services/profile.service.dart';
|
||||
import 'package:twonly/src/utils/misc.dart';
|
||||
import 'package:twonly/src/visual/elements/svg_icon.element.dart';
|
||||
import 'package:twonly/src/visual/themes/light.dart';
|
||||
|
|
@ -23,16 +25,18 @@ class VerificationBadgeInfo extends StatelessWidget {
|
|||
description: context.lang.verificationBadgeGreenDesc,
|
||||
boldTextColor: primaryColor,
|
||||
),
|
||||
_buildItem(
|
||||
context,
|
||||
icon: const SvgIcon(
|
||||
assetPath: SvgIcons.verifiedGreen,
|
||||
size: 40,
|
||||
color: colorVerificationBadgeYellow,
|
||||
if (userService.currentUser.securityProfile != SecurityProfile.strict ||
|
||||
userService.currentUser.isUserDiscoveryEnabled)
|
||||
_buildItem(
|
||||
context,
|
||||
icon: const SvgIcon(
|
||||
assetPath: SvgIcons.verifiedGreen,
|
||||
size: 40,
|
||||
color: colorVerificationBadgeYellow,
|
||||
),
|
||||
description: context.lang.verificationBadgeYellowDesc,
|
||||
boldTextColor: colorVerificationBadgeYellow,
|
||||
),
|
||||
description: context.lang.verificationBadgeYellowDesc,
|
||||
boldTextColor: colorVerificationBadgeYellow,
|
||||
),
|
||||
_buildItem(
|
||||
context,
|
||||
icon: const SvgIcon(assetPath: SvgIcons.verifiedRed, size: 40),
|
||||
|
|
|
|||
|
|
@ -21,13 +21,18 @@ class ContextMenu extends StatefulWidget {
|
|||
class _ContextMenuState extends State<ContextMenu> {
|
||||
Offset? _tapPosition;
|
||||
|
||||
Widget _getIcon(IconData icon) {
|
||||
Widget _getIcon(dynamic icon) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(left: 12),
|
||||
child: FaIcon(
|
||||
icon,
|
||||
size: 20,
|
||||
),
|
||||
child: icon is IconData
|
||||
? Icon(
|
||||
icon,
|
||||
size: 20,
|
||||
)
|
||||
: FaIcon(
|
||||
icon as FaIconData?,
|
||||
size: 20,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -95,5 +100,5 @@ class ContextMenuItem {
|
|||
});
|
||||
final String title;
|
||||
final Future<void> Function() onTap;
|
||||
final IconData icon;
|
||||
final dynamic icon;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class BetterListTile extends StatelessWidget {
|
|||
this.iconSize = 20,
|
||||
this.padding,
|
||||
});
|
||||
final IconData? icon;
|
||||
final dynamic icon;
|
||||
final Widget? leading;
|
||||
final Widget? trailing;
|
||||
final String? text;
|
||||
|
|
@ -34,11 +34,17 @@ class BetterListTile extends StatelessWidget {
|
|||
child: Center(
|
||||
child: (leading != null)
|
||||
? leading
|
||||
: FaIcon(
|
||||
icon,
|
||||
size: iconSize,
|
||||
color: color,
|
||||
),
|
||||
: (icon is IconData)
|
||||
? Icon(
|
||||
icon as IconData,
|
||||
size: iconSize,
|
||||
color: color,
|
||||
)
|
||||
: FaIcon(
|
||||
icon as FaIconData?,
|
||||
size: iconSize,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
),
|
||||
trailing: trailing,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,13 @@ import 'package:flutter_svg/flutter_svg.dart';
|
|||
class SvgIcons {
|
||||
static const String verifiedGreen = 'assets/icons/verified_badge_green.svg';
|
||||
static const String verifiedRed = 'assets/icons/verified_badge_red.svg';
|
||||
|
||||
static String verifiedNumeric(int value) {
|
||||
if (value >= 4) {
|
||||
return verifiedGreen;
|
||||
}
|
||||
return 'assets/icons/verification_badge_numeric/verified_badge_$value.svg';
|
||||
}
|
||||
}
|
||||
|
||||
class SvgIcon extends StatelessWidget {
|
||||
|
|
|
|||
|
|
@ -46,24 +46,43 @@ class ScreenshotController {
|
|||
}
|
||||
late GlobalKey _containerKey;
|
||||
|
||||
Future<ScreenshotImageHelper?> capture({double? pixelRatio}) async {
|
||||
Future<ScreenshotImageHelper?> capture({
|
||||
double? pixelRatio,
|
||||
int retries = 20,
|
||||
}) async {
|
||||
try {
|
||||
final findRenderObject = _containerKey.currentContext?.findRenderObject();
|
||||
if (findRenderObject == null) {
|
||||
return null;
|
||||
}
|
||||
final boundary = findRenderObject as RenderRepaintBoundary;
|
||||
|
||||
final context = _containerKey.currentContext;
|
||||
var tmpPixelRatio = pixelRatio;
|
||||
if (tmpPixelRatio == null) {
|
||||
if (context != null && context.mounted) {
|
||||
tmpPixelRatio =
|
||||
tmpPixelRatio ?? MediaQuery.of(context).devicePixelRatio;
|
||||
tmpPixelRatio = tmpPixelRatio ?? MediaQuery.of(context).devicePixelRatio;
|
||||
}
|
||||
}
|
||||
final image = await boundary.toImage(pixelRatio: tmpPixelRatio ?? 1);
|
||||
return ScreenshotImageHelper(image: image);
|
||||
} catch (e) {
|
||||
if (retries > 0) {
|
||||
final completer = Completer<ScreenshotImageHelper?>();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
final result = await capture(
|
||||
pixelRatio: pixelRatio,
|
||||
retries: retries - 1,
|
||||
);
|
||||
completer.complete(result);
|
||||
});
|
||||
Timer(const Duration(milliseconds: 50), () {
|
||||
if (!completer.isCompleted) {
|
||||
WidgetsBinding.instance.scheduleFrame();
|
||||
}
|
||||
});
|
||||
return completer.future;
|
||||
}
|
||||
Log.error(e);
|
||||
}
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ class _VideoPlayerFileHelperState extends State<VideoPlayerFileHelper> {
|
|||
aspectRatio: _controller.value.aspectRatio,
|
||||
child: VideoPlayerHelper(controller: _controller),
|
||||
)
|
||||
: const CircularProgressIndicator(),
|
||||
: const CircularProgressIndicator.adaptive(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue