From a3d9bcf98b69ffb7a99f7a6466c909afaf23fb6d Mon Sep 17 00:00:00 2001 From: otsmr Date: Tue, 15 Jul 2025 00:38:23 +0200 Subject: [PATCH] enabling linter --- .vscode/launch.json | 271 -- .vscode/settings.json | 5 - README.md | 11 +- analysis_options.yaml | 44 +- assets/animated_icons/delete.py | 175 -- .../twonly_database/drift_schema_v1.json | 1 - .../twonly_database/drift_schema_v10.json | 1 - .../twonly_database/drift_schema_v11.json | 1 - .../twonly_database/drift_schema_v12.json | 1 - .../twonly_database/drift_schema_v13.json | 1 - .../twonly_database/drift_schema_v14.json | 1 - .../twonly_database/drift_schema_v15.json | 1 - .../twonly_database/drift_schema_v2.json | 1 - .../twonly_database/drift_schema_v3.json | 1 - .../twonly_database/drift_schema_v4.json | 1 - .../twonly_database/drift_schema_v5.json | 1 - .../twonly_database/drift_schema_v6.json | 1 - .../twonly_database/drift_schema_v7.json | 1 - .../twonly_database/drift_schema_v8.json | 1 - .../twonly_database/drift_schema_v9.json | 1 - lib/app.dart | 141 +- lib/globals.dart | 6 +- lib/main.dart | 27 +- lib/src/constants/secure_storage_keys.dart | 16 +- lib/src/database/daos/contacts_dao.dart | 30 +- .../database/daos/media_downloads_dao.dart | 4 +- lib/src/database/daos/media_uploads_dao.dart | 2 +- .../daos/message_retransmissions.dao.dart | 10 +- lib/src/database/daos/messages_dao.dart | 24 +- lib/src/database/daos/signal_dao.dart | 4 +- .../signal/connect_identitiy_key_store.dart | 17 +- .../signal/connect_pre_key_store.dart | 6 +- .../signal/connect_signed_pre_key_store.dart | 14 +- .../database/tables/media_uploads_table.dart | 56 +- lib/src/database/twonly_database.dart | 52 +- lib/src/localization/app_de.arb | 4 +- lib/src/localization/app_en.arb | 6 +- .../generated/app_localizations.dart | 8 +- .../generated/app_localizations_de.dart | 4 +- .../generated/app_localizations_en.dart | 4 +- lib/src/model/json/message.dart | 119 +- lib/src/model/memory_item.model.dart | 35 +- .../api/websocket/client_to_server.pb.dart | 2195 +++++++++++------ lib/src/services/api.service.dart | 330 +-- lib/src/services/api/media_download.dart | 213 +- lib/src/services/api/media_upload.dart | 328 ++- lib/src/services/api/messages.dart | 93 +- lib/src/services/api/server_messages.dart | 129 +- lib/src/services/api/utils.dart | 19 +- lib/src/services/fcm.service.dart | 46 +- lib/src/services/flame.service.dart | 2 +- .../background.notifications.dart | 178 +- .../notifications/pushkeys.notifications.dart | 101 +- .../notifications/setup.notifications.dart | 2 +- .../services/signal/encryption.signal.dart | 56 +- lib/src/services/signal/identity.signal.dart | 42 +- lib/src/services/signal/prekeys.signal.dart | 4 +- lib/src/services/signal/session.signal.dart | 2 +- lib/src/services/thumbnail.service.dart | 55 +- .../twonly_safe/common.twonly_safe.dart | 4 +- .../create_backup.twonly_safe.dart | 83 +- .../twonly_safe/restore.twonly_safe.dart | 43 +- lib/src/utils/keyvalue.dart | 4 +- lib/src/utils/log.dart | 7 - lib/src/utils/misc.dart | 219 +- lib/src/utils/storage.dart | 23 +- .../zoom_selector.dart | 2 +- .../camera_preview_controller_view.dart | 95 +- lib/src/views/camera/camera_send_to_view.dart | 4 +- .../camera/image_editor/data/image_item.dart | 2 +- .../image_editor/layers/emoji_layer.dart | 31 +- .../image_editor/layers/filter_layer.dart | 36 +- .../layers/filters/location_filter.dart | 70 +- .../image_editor/layers/text_layer.dart | 4 +- .../camera/image_editor/layers_viewer.dart | 7 +- .../image_editor/modules/all_emojis.dart | 4 +- .../best_friends_selector.dart | 87 +- .../views/camera/share_image_editor_view.dart | 104 +- lib/src/views/camera/share_image_view.dart | 84 +- lib/src/views/chats/add_new_user.view.dart | 99 +- lib/src/views/chats/chat_list.view.dart | 92 +- .../backup_notice.card.dart | 6 +- .../chat_list_components/demo_user.card.dart | 6 +- lib/src/views/chats/chat_messages.view.dart | 153 +- .../chat_media_entry.dart | 2 +- .../chat_message_entry.dart | 48 +- .../chat_reaction_row.dart | 21 +- .../chat_text_response_columns.dart | 26 +- .../in_chat_media_viewer.dart | 28 +- .../message_actions.dart | 32 +- lib/src/views/chats/media_viewer.view.dart | 203 +- lib/src/views/chats/start_new_chat.view.dart | 39 +- lib/src/views/components/alert_dialog.dart | 11 +- lib/src/views/components/animate_icon.dart | 342 ++- lib/src/views/components/app_outdated.dart | 86 + .../views/components/better_list_title.dart | 17 +- lib/src/views/components/better_text.dart | 22 +- ...long_string.dart => fingerprint_text.dart} | 15 +- lib/src/views/components/flame.dart | 13 +- lib/src/views/components/headline.dart | 7 +- lib/src/views/components/initialsavatar.dart | 99 +- .../views/components/media_view_sizing.dart | 11 +- .../components/message_send_state_icon.dart | 60 +- .../views/components/notification_badge.dart | 13 +- lib/src/views/components/radio_button.dart | 11 +- .../views/components/user_context_menu.dart | 34 +- lib/src/views/components/verified_shield.dart | 7 +- .../components/video_player_wrapper.dart | 12 +- lib/src/views/contact/contact.view.dart | 47 +- .../views/contact/contact_verify.view.dart | 93 +- .../contact/contact_verify_qr_scan.view.dart | 9 +- lib/src/views/home.view.dart | 49 +- lib/src/views/memories/memories.view.dart | 58 +- .../memories/memories_item_thumbnail.dart | 10 +- .../memories/memories_photo_slider.view.dart | 32 +- lib/src/views/onboarding/onboarding.view.dart | 33 +- lib/src/views/onboarding/recover.view.dart | 6 +- lib/src/views/onboarding/register.view.dart | 76 +- lib/src/views/settings/account.view.dart | 58 +- lib/src/views/settings/appearance.view.dart | 24 +- .../views/settings/backup/backup.view.dart | 68 +- .../backup/twonly_safe_backup.view.dart | 49 +- .../backup/twonly_safe_server.view.dart | 66 +- .../settings/chat/chat_reactions.view.dart | 22 +- .../settings/chat/chat_settings.view.dart | 2 +- .../views/settings/data_and_storage.view.dart | 36 +- .../views/settings/help/contact_us.view.dart | 128 +- lib/src/views/settings/help/credits.view.dart | 6 +- lib/src/views/settings/help/faq.view.dart | 40 +- lib/src/views/settings/help/help.view.dart | 28 +- lib/src/views/settings/notification.view.dart | 15 +- .../settings/privacy_view_block.users.dart | 4 +- .../settings/profile/modify_avatar.view.dart | 2 +- .../views/settings/profile/profile.view.dart | 4 +- .../views/settings/settings_main.view.dart | 109 +- .../settings/share_with_friends.view.dart | 2 +- .../subscription/additional_users.view.dart | 90 +- .../settings/subscription/checkout.view.dart | 51 +- .../manage_subscription.view.dart | 32 +- .../subscription/select_payment.view.dart | 76 +- .../subscription/subscription.view.dart | 229 +- .../subscription/transaction.view.dart | 13 +- .../settings/subscription/voucher.view.dart | 83 +- lib/src/views/tutorial/show_tutorial.dart | 36 +- lib/src/views/tutorial/tutorials.dart | 8 +- pubspec.lock | 8 + pubspec.yaml | 1 + .../generate_proto.sh | 13 +- 148 files changed, 4643 insertions(+), 4406 deletions(-) delete mode 100644 .vscode/launch.json delete mode 100644 .vscode/settings.json delete mode 100644 assets/animated_icons/delete.py delete mode 100644 drift_schemas/twonly_database/drift_schema_v1.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v10.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v11.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v12.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v13.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v14.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v15.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v2.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v3.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v4.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v5.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v6.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v7.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v8.json delete mode 100644 drift_schemas/twonly_database/drift_schema_v9.json create mode 100644 lib/src/views/components/app_outdated.dart rename lib/src/views/components/{format_long_string.dart => fingerprint_text.dart} (65%) rename generate_proto.sh => scripts/generate_proto.sh (83%) diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 5e60659..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,271 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "twonly-app", - "request": "launch", - "type": "dart" - }, - { - "name": "twonly-app (profile mode)", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "twonly-app (release mode)", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage", - "cwd": "dependencies/flutter_secure_storage", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_zxing", - "cwd": "dependencies/flutter_zxing", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_zxing (profile mode)", - "cwd": "dependencies/flutter_zxing", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_zxing (release mode)", - "cwd": "dependencies/flutter_zxing", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage_darwin", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_darwin", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage_darwin (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_darwin", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage_darwin (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_darwin", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage_linux", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_linux", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage_linux (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_linux", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage_linux (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_linux", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage_platform_interface", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_platform_interface", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage_platform_interface (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_platform_interface", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage_platform_interface (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_platform_interface", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage_web", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_web", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage_web (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_web", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage_web (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_web", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage_windows", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_windows", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage_windows (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_windows", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage_windows (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_windows", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "example", - "cwd": "dependencies/flutter_zxing/example", - "request": "launch", - "type": "dart" - }, - { - "name": "example (profile mode)", - "cwd": "dependencies/flutter_zxing/example", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "example (release mode)", - "cwd": "dependencies/flutter_zxing/example", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "zxscanner", - "cwd": "dependencies/flutter_zxing/zxscanner", - "request": "launch", - "type": "dart" - }, - { - "name": "zxscanner (profile mode)", - "cwd": "dependencies/flutter_zxing/zxscanner", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "zxscanner (release mode)", - "cwd": "dependencies/flutter_zxing/zxscanner", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "flutter_secure_storage_macos", - "cwd": "dependencies/flutter_secure_storage/archived_packages/flutter_secure_storage_macos", - "request": "launch", - "type": "dart" - }, - { - "name": "flutter_secure_storage_macos (profile mode)", - "cwd": "dependencies/flutter_secure_storage/archived_packages/flutter_secure_storage_macos", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "flutter_secure_storage_macos (release mode)", - "cwd": "dependencies/flutter_secure_storage/archived_packages/flutter_secure_storage_macos", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "example", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage/example", - "request": "launch", - "type": "dart" - }, - { - "name": "example (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage/example", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "example (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage/example", - "request": "launch", - "type": "dart", - "flutterMode": "release" - }, - { - "name": "example", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_windows/example", - "request": "launch", - "type": "dart" - }, - { - "name": "example (profile mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_windows/example", - "request": "launch", - "type": "dart", - "flutterMode": "profile" - }, - { - "name": "example (release mode)", - "cwd": "dependencies/flutter_secure_storage/flutter_secure_storage_windows/example", - "request": "launch", - "type": "dart", - "flutterMode": "release" - } - ] -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 41c6f8e..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "files.exclude": { - "dependencies": false - } -} \ No newline at end of file diff --git a/README.md b/README.md index f4309c3..1665e69 100644 --- a/README.md +++ b/README.md @@ -13,12 +13,15 @@ This repository contains the complete source code of the [twonly](https://twonly ## In work -- We plan to implement a Sealed Sender feature to minimize metadata -- We currently evaluating to switch from the Signal Protocol to [MLS](https://openmls.tech/). - +- For Android: Using [UnifiedPush](https://unifiedpush.org/) instead of FCM +- For Android: Reproducible Builds + Publishing on Github/F-Droid +- Implementing [Sealed Sender](https://signal.org/blog/sealed-sender/) to minimize metadata +- Maybe: Switching from the Signal Protocol to [MLS](https://openmls.tech/). ## Security Issues -If you discover a security issue in twonly, please adhere to the coordinated vulnerability disclosure model. Please send us your report to security@twonly.eu. We also offer for critical security issues a small bug bounties, but we can not guarantee a bounty currently :/ +If you discover a security issue in twonly, please adhere to the coordinated vulnerability disclosure model. Please send +us your report to security@twonly.eu. We also offer for critical security issues a small bug bounties, but we can not +guarantee a bounty currently :/ ## Development diff --git a/analysis_options.yaml b/analysis_options.yaml index 0d29021..1b09755 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,28 +1,24 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. +include: package:very_good_analysis/analysis_options.yaml -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml +analyzer: + errors: + always_use_package_imports: ignore + public_member_api_docs: ignore + lines_longer_than_80_chars: ignore + avoid_function_literals_in_foreach_calls: ignore + avoid_setters_without_getters: ignore + inference_failure_on_instance_creation: ignore + avoid_positional_boolean_parameters: ignore + inference_failure_on_collection_literal: ignore + exclude: + - "lib/src/model/protobuf/**" + - "lib/src/model/protobuf/api/websocket/**" + - "lib/generated/**" + - "test/drift/**" + - "**.g.dart" linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at https://dart.dev/lints. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options + public_member_api_docs: false + avoid_catches_without_on_clauses: false + document_ignores: false diff --git a/assets/animated_icons/delete.py b/assets/animated_icons/delete.py deleted file mode 100644 index dae69e6..0000000 --- a/assets/animated_icons/delete.py +++ /dev/null @@ -1,175 +0,0 @@ - - - -emojies = { - "โค": "red_heart.json", - "๐Ÿ˜‚": "joy.json", - "๐Ÿ”ฅ": "fire.json", - "๐Ÿ’ช": "muscle.json", - "๐Ÿ˜ญ": "loudly-crying.json", - "๐Ÿคฏ": "mind-blown.json", - "โค๏ธโ€๐Ÿ”ฅ": "red_heart_fire.json", - "๐Ÿ˜": "grinning.json", - "๐Ÿ˜†": "laughing.json", - "๐Ÿ˜…": "grin-sweat.json", - "๐Ÿคฃ": "rofl.json", - "๐Ÿ˜‰": "wink.json", - "๐Ÿ˜˜": "kissing-heart.json", - "๐Ÿฅฐ": "heart-face.json", - "๐Ÿ˜": "heart-eyes.json", - "๐Ÿคฉ": "star-struck.json", - "๐Ÿฅณ": "partying-face.json", - "๐Ÿ™ƒ": "upside-down-face.json", - "๐Ÿฅฒ": "happy-cry.json", - "๐Ÿ˜Š": "blush.json", - "๐Ÿ˜": "smirk.json", - "๐Ÿคค": "drool.json", - "๐Ÿ˜‹": "yum.json", - "๐Ÿ˜›": "stuck-out-tongue.json", - "๐Ÿคช": "zany-face.json", - "๐Ÿฅด": "woozy.json", - "๐Ÿ˜”": "pensive.json", - "๐Ÿฅบ": "pleading.json", - "๐Ÿ˜ฌ": "grimacing.json", - "๐Ÿ˜‘": "expressionless.json", - "๐Ÿค": "zipper-face.json", - "๐Ÿค”": "thinking-face.json", - "๐Ÿฅฑ": "yawn.json", - "๐Ÿค—": "hug-face.json", - "๐Ÿ˜ฑ": "screaming.json", - "๐Ÿคจ": "raised-eyebrow.json", - "๐Ÿง": "monocle.json", - "๐Ÿ˜’": "unamused.json", - "๐Ÿ™„": "rolling-eyes.json", - "๐Ÿ˜ค": "triumph.json", - "๐Ÿคฌ": "cursing.json", - "๐Ÿ˜ž": "sad.json", - "๐Ÿ˜ข": "cry.json", - "๐Ÿ™": "frown.json", - "๐Ÿ˜จ": "scared.json", - "๐Ÿ˜ณ": "flushed.json", - "๐Ÿ˜–": "scrunched-mouth.json", - "๐Ÿ˜ต": "x-eyes.json", - "๐Ÿฅถ": "cold-face.json", - "๐Ÿฅต": "hot-face.json", - "๐Ÿคฎ": "vomit.json", - "๐Ÿ˜ด": "sleep.json", - "๐Ÿค’": "thermometer-face.json", - "๐Ÿค•": "bandage-face.json", - "๐Ÿคฅ": "liar.json", - "๐Ÿ˜‡": "halo.json", - "๐Ÿค ": "cowboy.json", - "๐Ÿค‘": "money-face.json", - "๐Ÿค“": "nerd-face.json", - "๐Ÿ˜Ž": "sunglasses-face.json", - "๐Ÿฅธ": "disguise.json", - "๐Ÿคก": "clown.json", - "๐Ÿ’ฉ": "poop.json", - "๐Ÿ˜ˆ": "imp-smile.json", - "๐Ÿ‘ป": "ghost.json", - "๐Ÿ’€": "skull.json", - "โ›„": "snowman.json", - "๐ŸŽƒ": "jack-o-lantern.json", - "๐Ÿค–": "robot.json", - "๐Ÿ‘ฝ": "alien.json", - "๐Ÿ™ˆ": "see-no-evil-monkey.json", - "๐Ÿ™‰": "hear-no-evil-monkey.json", - "๐Ÿ™Š": "speak-no-evil-monkey.json", - "๐ŸŒŸ": "glowing-star.json", - "โœจ": "sparkles.json", - "โšก": "electricity.json", - "๐Ÿ’ฅ": "collision.json", - "๐Ÿ’ฏ": "100.json", - "๐ŸŽ‰": "party-popper.json", - "๐ŸŽŠ": "confetti-ball.json", - "๐Ÿงก": "orange-heart.json", - "๐Ÿ’›": "yellow-heart.json", - "๐Ÿ’š": "green-heart.json", - "๐Ÿ’™": "blue-heart.json", - "๐Ÿ’œ": "purple-heart.json", - "๐Ÿ’˜": "cupid.json", - "๐Ÿ’": "gift-heart.json", - "๐Ÿ’–": "sparkling-heart.json", - "๐Ÿ’•": "two-hearts.json", - "๐Ÿ’”": "broken-heart.json", - "๐Ÿ’‹": "kiss.json", - "๐Ÿ‘€": "eyes.json", - "๐Ÿฆป": "hearing-aid.json", - "๐Ÿฆถ": "foot.json", - "๐Ÿฆพ": "arm-mechanical.json", - "๐Ÿ‘": "clap.json", - "๐Ÿ‘": "thumbs-up.json", - "๐Ÿ‘Ž": "thumbs-down.json", - "๐Ÿ™Œ": "raising-hands.json", - "โœŠ": "raised-fist.json", - "๐Ÿ‘Š": "fist.json", - "๐Ÿ‘‹": "wave.json", - "๐Ÿค˜": "metal.json", - "๐Ÿคž": "crossed-fingers.json", - "๐Ÿค™": "call-me-hand.json", - "๐Ÿ‘Œ": "ok.json", - "๐Ÿ–•": "middle-finger.json", - "๐Ÿค": "handshake.json", - "๐Ÿ’ƒ": "dancer-woman.json", - "๐ŸŒฑ": "plant.json", - "๐Ÿƒ": "leaves.json", - "๐Ÿ€": "luck.json", - "๐ŸŒŠ": "ocean.json", - "๐Ÿ’ง": "droplet.json", - "๐Ÿฆ„": "unicorn.json", - "๐Ÿฆ–": "t-rex.json", - "๐Ÿฆ•": "dinosaur.json", - "๐Ÿข": "turtle.json", - "๐Ÿ": "snake.json", - "๐Ÿฉ": "poodle.json", - "๐Ÿ•": "dog.json", - "๐Ÿ–": "pig.json", - "๐Ÿฆ˜": "kangaroo.json", - "๐Ÿฆ": "gorilla.json", - "๐Ÿฆง": "orangutan.json", - "๐Ÿฆฆ": "otter.json", - "๐Ÿ“": "rooster.json", - "๐Ÿฆ…": "eagle.json", - "๐Ÿฆ‰": "owl.json", - "๐Ÿฌ": "dolphin.json", - "๐Ÿณ": "whale.json", - "๐ŸŸ": "fish.json", - "๐Ÿก": "blowfish.json", - "๐Ÿฆ€": "crab.json", - "๐Ÿ™": "octopus.json", - "๐ŸŒ": "snail.json", - "๐Ÿป": "clinking-beer-mugs.json", - "๐Ÿพ": "bottle-with-popping-cork.json", - "๐Ÿšจ": "police-car-light.json", - "๐Ÿ›ธ": "flying-saucer.json", - "๐Ÿš€": "rocket.json", - "๐Ÿ›ซ": "airplane-departure.json", - "๐ŸŽข": "roller-coaster.json", - "๐ŸŽก": "ferris-wheel.json", - "๐ŸŽˆ": "balloon.json", - "๐ŸŽ": "wrapped-gift.json", - "๐ŸŽ†": "fireworks.json", - "๐Ÿ’ธ": "money-with-wings.json", - "๐Ÿ’Ž": "gem-stone.json", - "๐ŸŽ“": "graduation-cap.json", - "๐Ÿ””": "bell.json", - "๐Ÿ’ฃ": "bomb.json", - "โ—": "exclamation.json", - "โ“": "question.json", - "โŒ": "cross-mark.json", - "๐Ÿ": "chequered-flag.json", - "๐Ÿšฉ": "triangular-flag.json", - "๐Ÿด": "black-flag.json", -} - -import os -files = [f for f in os.listdir(".") if os.path.isfile(os.path.join(".", f))] -for file in files: - if ".json" in file: - found = False - for name in emojies.values(): - if name == file: - found = True - if not found: - print("DELETE", file) - os.remove(file) \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v1.json b/drift_schemas/twonly_database/drift_schema_v1.json deleted file mode 100644 index 75469cc..0000000 --- a/drift_schemas/twonly_database/drift_schema_v1.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":3,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v10.json b/drift_schemas/twonly_database/drift_schema_v10.json deleted file mode 100644 index 17071c0..0000000 --- a/drift_schemas/twonly_database/drift_schema_v10.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"deleted","getter_name":"deleted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"deleted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"deleted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":8,"references":[],"type":"table","data":{"name":"signal_contact_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id","pre_key_id"]}},{"id":9,"references":[],"type":"table","data":{"name":"signal_contact_signed_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_id","getter_name":"signedPreKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key","getter_name":"signedPreKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_signature","getter_name":"signedPreKeySignature","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v11.json b/drift_schemas/twonly_database/drift_schema_v11.json deleted file mode 100644 index 8803126..0000000 --- a/drift_schemas/twonly_database/drift_schema_v11.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"deleted","getter_name":"deleted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"deleted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"deleted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":8,"references":[],"type":"table","data":{"name":"signal_contact_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id","pre_key_id"]}},{"id":9,"references":[],"type":"table","data":{"name":"signal_contact_signed_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_id","getter_name":"signedPreKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key","getter_name":"signedPreKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_signature","getter_name":"signedPreKeySignature","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id"]}},{"id":10,"references":[0,1],"type":"table","data":{"name":"message_retransmissions","was_declared_in_moor":false,"columns":[{"name":"retransmission_id","getter_name":"retransmissionId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":true,"customConstraints":null,"defaultConstraints":"REFERENCES messages (message_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES messages (message_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"messages","column":"message_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"plaintext_content","getter_name":"plaintextContent","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"push_data","getter_name":"pushData","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_server_at","getter_name":"acknowledgeByServerAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v12.json b/drift_schemas/twonly_database/drift_schema_v12.json deleted file mode 100644 index 751185a..0000000 --- a/drift_schemas/twonly_database/drift_schema_v12.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"deleted","getter_name":"deleted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"deleted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"deleted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":8,"references":[],"type":"table","data":{"name":"signal_contact_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id","pre_key_id"]}},{"id":9,"references":[],"type":"table","data":{"name":"signal_contact_signed_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_id","getter_name":"signedPreKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key","getter_name":"signedPreKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_signature","getter_name":"signedPreKeySignature","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id"]}},{"id":10,"references":[0,1],"type":"table","data":{"name":"message_retransmissions","was_declared_in_moor":false,"columns":[{"name":"retransmission_id","getter_name":"retransmissionId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":true,"customConstraints":null,"defaultConstraints":"REFERENCES messages (message_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES messages (message_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"messages","column":"message_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"plaintext_content","getter_name":"plaintextContent","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"push_data","getter_name":"pushData","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"will_not_get_a_c_k_by_user","getter_name":"willNotGetACKByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"will_not_get_a_c_k_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"will_not_get_a_c_k_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_server_at","getter_name":"acknowledgeByServerAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v13.json b/drift_schemas/twonly_database/drift_schema_v13.json deleted file mode 100644 index 8803126..0000000 --- a/drift_schemas/twonly_database/drift_schema_v13.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"deleted","getter_name":"deleted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"deleted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"deleted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":8,"references":[],"type":"table","data":{"name":"signal_contact_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id","pre_key_id"]}},{"id":9,"references":[],"type":"table","data":{"name":"signal_contact_signed_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_id","getter_name":"signedPreKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key","getter_name":"signedPreKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_signature","getter_name":"signedPreKeySignature","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id"]}},{"id":10,"references":[0,1],"type":"table","data":{"name":"message_retransmissions","was_declared_in_moor":false,"columns":[{"name":"retransmission_id","getter_name":"retransmissionId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":true,"customConstraints":null,"defaultConstraints":"REFERENCES messages (message_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES messages (message_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"messages","column":"message_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"plaintext_content","getter_name":"plaintextContent","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"push_data","getter_name":"pushData","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_server_at","getter_name":"acknowledgeByServerAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v14.json b/drift_schemas/twonly_database/drift_schema_v14.json deleted file mode 100644 index 3653e7b..0000000 --- a/drift_schemas/twonly_database/drift_schema_v14.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"deleted","getter_name":"deleted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"deleted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"deleted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":8,"references":[],"type":"table","data":{"name":"signal_contact_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id","pre_key_id"]}},{"id":9,"references":[],"type":"table","data":{"name":"signal_contact_signed_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_id","getter_name":"signedPreKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key","getter_name":"signedPreKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_signature","getter_name":"signedPreKeySignature","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id"]}},{"id":10,"references":[0,1],"type":"table","data":{"name":"message_retransmissions","was_declared_in_moor":false,"columns":[{"name":"retransmission_id","getter_name":"retransmissionId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":true,"customConstraints":null,"defaultConstraints":"REFERENCES messages (message_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES messages (message_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"messages","column":"message_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"plaintext_content","getter_name":"plaintextContent","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"push_data","getter_name":"pushData","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"encrypted_hash","getter_name":"encryptedHash","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_server_at","getter_name":"acknowledgeByServerAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v15.json b/drift_schemas/twonly_database/drift_schema_v15.json deleted file mode 100644 index f76a649..0000000 --- a/drift_schemas/twonly_database/drift_schema_v15.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"deleted","getter_name":"deleted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"deleted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"deleted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_retransmission_state","getter_name":"mediaRetransmissionState","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'none\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MediaRetransmitting.values)","dart_type_name":"MediaRetransmitting"}},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":8,"references":[],"type":"table","data":{"name":"signal_contact_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id","pre_key_id"]}},{"id":9,"references":[],"type":"table","data":{"name":"signal_contact_signed_pre_keys","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_id","getter_name":"signedPreKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key","getter_name":"signedPreKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"signed_pre_key_signature","getter_name":"signedPreKeySignature","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["contact_id"]}},{"id":10,"references":[0,1],"type":"table","data":{"name":"message_retransmissions","was_declared_in_moor":false,"columns":[{"name":"retransmission_id","getter_name":"retransmissionId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":true,"customConstraints":null,"defaultConstraints":"REFERENCES messages (message_id) ON DELETE CASCADE","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES messages (message_id) ON DELETE CASCADE"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"messages","column":"message_id"},"initially_deferred":false,"on_update":null,"on_delete":"cascade"}}]},{"name":"plaintext_content","getter_name":"plaintextContent","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"push_data","getter_name":"pushData","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"encrypted_hash","getter_name":"encryptedHash","moor_type":"blob","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_server_at","getter_name":"acknowledgeByServerAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v2.json b/drift_schemas/twonly_database/drift_schema_v2.json deleted file mode 100644 index 3c36fa4..0000000 --- a/drift_schemas/twonly_database/drift_schema_v2.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":3,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v3.json b/drift_schemas/twonly_database/drift_schema_v3.json deleted file mode 100644 index e6f7140..0000000 --- a/drift_schemas/twonly_database/drift_schema_v3.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":3,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v4.json b/drift_schemas/twonly_database/drift_schema_v4.json deleted file mode 100644 index 846a93c..0000000 --- a/drift_schemas/twonly_database/drift_schema_v4.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v5.json b/drift_schemas/twonly_database/drift_schema_v5.json deleted file mode 100644 index d62b84e..0000000 --- a/drift_schemas/twonly_database/drift_schema_v5.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v6.json b/drift_schemas/twonly_database/drift_schema_v6.json deleted file mode 100644 index 645e0b7..0000000 --- a/drift_schemas/twonly_database/drift_schema_v6.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v7.json b/drift_schemas/twonly_database/drift_schema_v7.json deleted file mode 100644 index 079a16f..0000000 --- a/drift_schemas/twonly_database/drift_schema_v7.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v8.json b/drift_schemas/twonly_database/drift_schema_v8.json deleted file mode 100644 index 333610e..0000000 --- a/drift_schemas/twonly_database/drift_schema_v8.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":["unknown"]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/drift_schemas/twonly_database/drift_schema_v9.json b/drift_schemas/twonly_database/drift_schema_v9.json deleted file mode 100644 index 98ecfc6..0000000 --- a/drift_schemas/twonly_database/drift_schema_v9.json +++ /dev/null @@ -1 +0,0 @@ -{"_meta":{"description":"This file contains a serialized version of schema entities for drift.","version":"1.2.0"},"options":{"store_date_time_values_as_text":false},"entities":[{"id":0,"references":[],"type":"table","data":{"name":"contacts","was_declared_in_moor":false,"columns":[{"name":"user_id","getter_name":"userId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"username","getter_name":"username","moor_type":"string","nullable":false,"customConstraints":null,"defaultConstraints":"UNIQUE","dialectAwareDefaultConstraints":{"sqlite":"UNIQUE"},"default_dart":null,"default_client_dart":null,"dsl_features":["unique"]},{"name":"display_name","getter_name":"displayName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"nick_name","getter_name":"nickName","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"avatar_svg","getter_name":"avatarSvg","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"my_avatar_counter","getter_name":"myAvatarCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"accepted","getter_name":"accepted","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"accepted\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"accepted\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"requested","getter_name":"requested","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"requested\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"requested\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"blocked","getter_name":"blocked","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"blocked\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"blocked\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"verified","getter_name":"verified","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"verified\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"verified\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"archived","getter_name":"archived","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"archived\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"archived\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"pinned","getter_name":"pinned","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"pinned\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"pinned\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"also_best_friend","getter_name":"alsoBestFriend","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"also_best_friend\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"also_best_friend\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"delete_messages_after_x_minutes","getter_name":"deleteMessagesAfterXMinutes","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('1440')","default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"total_media_counter","getter_name":"totalMediaCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"last_message_send","getter_name":"lastMessageSend","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_received","getter_name":"lastMessageReceived","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_counter_change","getter_name":"lastFlameCounterChange","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_flame_sync","getter_name":"lastFlameSync","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"last_message_exchange","getter_name":"lastMessageExchange","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"flame_counter","getter_name":"flameCounter","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["user_id"]}},{"id":1,"references":[0],"type":"table","data":{"name":"messages","was_declared_in_moor":false,"columns":[{"name":"contact_id","getter_name":"contactId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"REFERENCES contacts (user_id)","dialectAwareDefaultConstraints":{"sqlite":"REFERENCES contacts (user_id)"},"default_dart":null,"default_client_dart":null,"dsl_features":[{"foreign_key":{"to":{"table":"contacts","column":"user_id"},"initially_deferred":false,"on_update":null,"on_delete":null}}]},{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"message_other_id","getter_name":"messageOtherId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"media_download_id","getter_name":"mediaDownloadId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_message_id","getter_name":"responseToMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"response_to_other_message_id","getter_name":"responseToOtherMessageId","moor_type":"int","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"acknowledge_by_user","getter_name":"acknowledgeByUser","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_user\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_user\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"media_stored","getter_name":"mediaStored","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"media_stored\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"media_stored\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"download_state","getter_name":"downloadState","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('2')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumIndexConverter(DownloadState.values)","dart_type_name":"DownloadState"}},{"name":"acknowledge_by_server","getter_name":"acknowledgeByServer","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"acknowledge_by_server\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"acknowledge_by_server\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"error_while_sending","getter_name":"errorWhileSending","moor_type":"bool","nullable":false,"customConstraints":null,"defaultConstraints":"CHECK (\"error_while_sending\" IN (0, 1))","dialectAwareDefaultConstraints":{"sqlite":"CHECK (\"error_while_sending\" IN (0, 1))"},"default_dart":"const CustomExpression('0')","default_client_dart":null,"dsl_features":[]},{"name":"kind","getter_name":"kind","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(MessageKind.values)","dart_type_name":"MessageKind"}},{"name":"content_json","getter_name":"contentJson","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"opened_at","getter_name":"openedAt","moor_type":"dateTime","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"send_at","getter_name":"sendAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]},{"name":"updated_at","getter_name":"updatedAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":2,"references":[],"type":"table","data":{"name":"media_uploads","was_declared_in_moor":false,"columns":[{"name":"media_upload_id","getter_name":"mediaUploadId","moor_type":"int","nullable":false,"customConstraints":null,"defaultConstraints":"PRIMARY KEY AUTOINCREMENT","dialectAwareDefaultConstraints":{"sqlite":"PRIMARY KEY AUTOINCREMENT"},"default_dart":null,"default_client_dart":null,"dsl_features":["auto-increment"]},{"name":"state","getter_name":"state","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'pending\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"const EnumNameConverter(UploadState.values)","dart_type_name":"UploadState"}},{"name":"metadata","getter_name":"metadata","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadMetadataConverter()","dart_type_name":"MediaUploadMetadata"}},{"name":"message_ids","getter_name":"messageIds","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}},{"name":"encryption_data","getter_name":"encryptionData","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaEncryptionDataConverter()","dart_type_name":"MediaEncryptionData"}},{"name":"upload_tokens","getter_name":"uploadTokens","moor_type":"string","nullable":true,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"MediaUploadTokensConverter()","dart_type_name":"MediaUploadTokens"}},{"name":"already_notified","getter_name":"alreadyNotified","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('\\'[]\\'')","default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":3,"references":[],"type":"table","data":{"name":"media_downloads","was_declared_in_moor":false,"columns":[{"name":"message_id","getter_name":"messageId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"download_token","getter_name":"downloadToken","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[],"type_converter":{"dart_expr":"IntListTypeConverter()","dart_type_name":"List"}}],"is_virtual":false,"without_rowid":false,"constraints":[]}},{"id":4,"references":[],"type":"table","data":{"name":"signal_identity_key_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"identity_key","getter_name":"identityKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}},{"id":5,"references":[],"type":"table","data":{"name":"signal_pre_key_stores","was_declared_in_moor":false,"columns":[{"name":"pre_key_id","getter_name":"preKeyId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"pre_key","getter_name":"preKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["pre_key_id"]}},{"id":6,"references":[],"type":"table","data":{"name":"signal_sender_key_stores","was_declared_in_moor":false,"columns":[{"name":"sender_key_name","getter_name":"senderKeyName","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"sender_key","getter_name":"senderKey","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["sender_key_name"]}},{"id":7,"references":[],"type":"table","data":{"name":"signal_session_stores","was_declared_in_moor":false,"columns":[{"name":"device_id","getter_name":"deviceId","moor_type":"int","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"name","getter_name":"name","moor_type":"string","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"session_record","getter_name":"sessionRecord","moor_type":"blob","nullable":false,"customConstraints":null,"default_dart":null,"default_client_dart":null,"dsl_features":[]},{"name":"created_at","getter_name":"createdAt","moor_type":"dateTime","nullable":false,"customConstraints":null,"default_dart":"const CustomExpression('CAST(strftime(\\'%s\\', CURRENT_TIMESTAMP) AS INTEGER)')","default_client_dart":null,"dsl_features":[]}],"is_virtual":false,"without_rowid":false,"constraints":[],"explicit_pk":["device_id","name"]}}]} \ No newline at end of file diff --git a/lib/app.dart b/lib/app.dart index 2e1e771..2cb2768 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -1,24 +1,18 @@ -import 'dart:io'; -import 'package:flutter/foundation.dart'; +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:provider/provider.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/localization/generated/app_localizations.dart'; import 'package:twonly/src/providers/connection.provider.dart'; import 'package:twonly/src/providers/settings.provider.dart'; import 'package:twonly/src/services/api/media_upload.dart'; -import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; -import 'package:twonly/src/views/onboarding/onboarding.view.dart'; +import 'package:twonly/src/views/components/app_outdated.dart'; import 'package:twonly/src/views/home.view.dart'; +import 'package:twonly/src/views/onboarding/onboarding.view.dart'; import 'package:twonly/src/views/onboarding/register.view.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'dart:async'; -import 'package:url_launcher/url_launcher.dart'; -// these two callbacks are called on updated to the corresponding database - -/// The Widget that configures your application. class App extends StatefulWidget { const App({super.key}); @override @@ -27,7 +21,6 @@ class App extends StatefulWidget { class _AppState extends State with WidgetsBindingObserver { bool wasPaused = false; - bool appIsOutdated = false; @override void initState() { @@ -35,16 +28,15 @@ class _AppState extends State with WidgetsBindingObserver { globalIsAppInBackground = false; WidgetsBinding.instance.addObserver(this); - // register global callbacks to the widget tree - globalCallbackConnectionState = (update) { - context.read().updateConnectionState(update); + globalCallbackConnectionState = ({required bool isConnected}) { + context.read().updateConnectionState(isConnected); setUserPlan(); }; initAsync(); } - Future setUserPlan() async { + Future setUserPlan() async { final user = await getUser(); globalBestFriendUserId = -1; if (user != null && mounted) { @@ -59,23 +51,19 @@ class _AppState extends State with WidgetsBindingObserver { } } if (mounted) { - context.read().updatePlan(user.subscriptionPlan); + await context + .read() + .updatePlan(user.subscriptionPlan); } } } - Future initAsync() async { - setUserPlan(); - globalCallbackAppIsOutdated = () async { - context.read().updateConnectionState(false); - setState(() { - appIsOutdated = true; - }); - }; + Future initAsync() async { + await setUserPlan(); await apiService.connect(force: true); - apiService.listenToNetworkChanges(); + await apiService.listenToNetworkChanges(); // call this function so invalid media files are get purged - retryMediaUpload(true); + await retryMediaUpload(true); } @override @@ -97,8 +85,7 @@ class _AppState extends State with WidgetsBindingObserver { @override void dispose() { WidgetsBinding.instance.removeObserver(this); - globalCallbackConnectionState = (a) {}; - globalCallbackAppIsOutdated = () {}; + globalCallbackConnectionState = ({required bool isConnected}) {}; super.dispose(); } @@ -145,10 +132,8 @@ class _AppState extends State with WidgetsBindingObserver { themeMode: context.watch().themeMode, initialRoute: '/', routes: { - "/": (context) => - AppMainWidget(initialPage: 1, appIsOutdated: appIsOutdated), - "/chats": (context) => - AppMainWidget(initialPage: 0, appIsOutdated: appIsOutdated) + "/": (context) => AppMainWidget(initialPage: 1), + "/chats": (context) => AppMainWidget(initialPage: 0) }, ); }, @@ -157,17 +142,18 @@ class _AppState extends State with WidgetsBindingObserver { } class AppMainWidget extends StatefulWidget { - const AppMainWidget( - {super.key, required this.initialPage, required this.appIsOutdated}); + const AppMainWidget({ + super.key, + required this.initialPage, + }); final int initialPage; - final bool appIsOutdated; @override State createState() => _AppMainWidgetState(); } class _AppMainWidgetState extends State { Future userCreated = isUserCreated(); - bool showOnboarding = kReleaseMode; + bool showOnboarding = true; @override Widget build(BuildContext context) { @@ -178,80 +164,25 @@ class _AppMainWidgetState extends State { builder: (context, snapshot) { if (!snapshot.hasData) { return Center(child: Container()); - } - - if (snapshot.data!) { + } else if (snapshot.data!) { return HomeView( initialPage: widget.initialPage, ); + } else if (showOnboarding) { + return OnboardingView( + callbackOnSuccess: () => setState(() { + showOnboarding = false; + }), + ); } - - return showOnboarding - ? OnboardingView( - callbackOnSuccess: () { - setState(() { - showOnboarding = false; - }); - }, - ) - : RegisterView( - callbackOnSuccess: () { - setState(() { - userCreated = isUserCreated(); - }); - }, - ); + return RegisterView( + callbackOnSuccess: () => setState(() { + userCreated = isUserCreated(); + }), + ); }, ), - if (widget.appIsOutdated) - Positioned( - top: 60, - left: 30, - right: 30, - child: SafeArea( - child: Container( - padding: EdgeInsets.symmetric(vertical: 10, horizontal: 8), - decoration: BoxDecoration( - color: Colors.red, - borderRadius: BorderRadius.circular(10), - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Text( - context.lang.appOutdated, - textAlign: TextAlign.center, - softWrap: true, - style: Theme.of(context) - .textTheme - .bodyMedium - ?.copyWith(color: Colors.white, fontSize: 16), - ), - if (Platform.isAndroid) SizedBox(height: 5), - if (Platform.isAndroid) - ElevatedButton( - onPressed: () { - launchUrl(Uri.parse( - "https://play.google.com/store/apps/details?id=eu.twonly")); - }, - style: ElevatedButton.styleFrom( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - ), - child: Text( - context.lang.appOutdatedBtn, - style: Theme.of(context) - .textTheme - .bodyMedium - ?.copyWith(color: Colors.white, fontSize: 16), - ), - ), - ], - ), - ), - ), - ), + AppOutdated(), ], ); } diff --git a/lib/globals.dart b/lib/globals.dart index 3800bef..0ac4af8 100644 --- a/lib/globals.dart +++ b/lib/globals.dart @@ -15,8 +15,10 @@ bool gIsDemoUser = false; // App widget. // This callback called by the apiProvider -Function(bool) globalCallbackConnectionState = (a) {}; -Function() globalCallbackAppIsOutdated = () {}; +void Function({required bool isConnected}) globalCallbackConnectionState = ({ + required bool isConnected, +}) {}; +void Function() globalCallbackAppIsOutdated = () {}; bool globalIsAppInBackground = true; int globalBestFriendUserId = -1; diff --git a/lib/main.dart b/lib/main.dart index ad535c5..b742509 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,20 +1,23 @@ +import 'dart:async'; + import 'package:camera/camera.dart'; +import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/providers/connection.provider.dart'; import 'package:twonly/src/providers/image_editor.provider.dart'; +import 'package:twonly/src/providers/settings.provider.dart'; +import 'package:twonly/src/services/api.service.dart'; import 'package:twonly/src/services/api/media_download.dart'; import 'package:twonly/src/services/api/media_upload.dart'; -import 'package:twonly/src/services/api.service.dart'; -import 'package:flutter/material.dart'; -import 'package:twonly/src/providers/connection.provider.dart'; -import 'package:twonly/src/providers/settings.provider.dart'; import 'package:twonly/src/services/fcm.service.dart'; import 'package:twonly/src/services/notifications/setup.notifications.dart'; import 'package:twonly/src/services/twonly_safe/create_backup.twonly_safe.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/storage.dart'; + import 'app.dart'; void main() async { @@ -31,31 +34,29 @@ void main() async { } final settingsController = SettingsChangeProvider(); - // Load the user's preferred theme while the splash screen is displayed. - // This prevents a sudden theme change when the app is first displayed. + await settingsController.loadSettings(); await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); - setupPushNotification(); + unawaited(setupPushNotification()); gCameras = await availableCameras(); apiService = ApiService(); twonlyDB = TwonlyDatabase(); + await twonlyDB.messagesDao.resetPendingDownloadState(); await twonlyDB.messagesDao.handleMediaFilesOlderThan7Days(); await twonlyDB.signalDao.purgeOutDatedPreKeys(); // Purge media files in the background - purgeReceivedMediaFiles(); - purgeSendMediaFiles(); + unawaited(purgeReceivedMediaFiles()); + unawaited(purgeSendMediaFiles()); - performTwonlySafeBackup(); + unawaited(performTwonlySafeBackup()); await initFileDownloader(); - cleanLogFile(); - runApp( MultiProvider( providers: [ @@ -63,7 +64,7 @@ void main() async { ChangeNotifierProvider(create: (_) => CustomChangeProvider()), ChangeNotifierProvider(create: (_) => ImageEditorProvider()), ], - child: App(), + child: const App(), ), ); } diff --git a/lib/src/constants/secure_storage_keys.dart b/lib/src/constants/secure_storage_keys.dart index fb5fd69..8e2eac5 100644 --- a/lib/src/constants/secure_storage_keys.dart +++ b/lib/src/constants/secure_storage_keys.dart @@ -1,11 +1,11 @@ class SecureStorageKeys { - static const String signalIdentity = "signal_identity"; - static const String signalSignedPreKey = "signed_pre_key_store"; - static const String apiAuthToken = "api_auth_token"; - static const String googleFcm = "google_fcm"; - static const String userData = "userData"; - static const String twonlySafeLastBackupHash = "twonly_safe_last_backup_hash"; + static const String signalIdentity = 'signal_identity'; + static const String signalSignedPreKey = 'signed_pre_key_store'; + static const String apiAuthToken = 'api_auth_token'; + static const String googleFcm = 'google_fcm'; + static const String userData = 'userData'; + static const String twonlySafeLastBackupHash = 'twonly_safe_last_backup_hash'; - static const String receivingPushKeys = "receiving_push_keys"; - static const String sendingPushKeys = "sending_push_keys"; + static const String receivingPushKeys = 'receiving_push_keys'; + static const String sendingPushKeys = 'sending_push_keys'; } diff --git a/lib/src/database/daos/contacts_dao.dart b/lib/src/database/daos/contacts_dao.dart index 19f95e5..f6ea804 100644 --- a/lib/src/database/daos/contacts_dao.dart +++ b/lib/src/database/daos/contacts_dao.dart @@ -20,30 +20,33 @@ class ContactsDao extends DatabaseAccessor } } - Future incFlameCounter( - int contactId, bool received, DateTime timestamp) async { - Contact contact = (await (select(contacts) + Future incFlameCounter( + int contactId, + bool received, + DateTime timestamp, + ) async { + final contact = (await (select(contacts) ..where((t) => t.userId.equals(contactId))) .get()) .first; - int totalMediaCounter = contact.totalMediaCounter + 1; - int flameCounter = contact.flameCounter; + final totalMediaCounter = contact.totalMediaCounter + 1; + var flameCounter = contact.flameCounter; if (contact.lastMessageReceived != null && contact.lastMessageSend != null) { final now = DateTime.now(); final startOfToday = DateTime(now.year, now.month, now.day); - final twoDaysAgo = startOfToday.subtract(Duration(days: 2)); + final twoDaysAgo = startOfToday.subtract(const Duration(days: 2)); if (contact.lastMessageSend!.isBefore(twoDaysAgo) || contact.lastMessageReceived!.isBefore(twoDaysAgo)) { flameCounter = 0; } } - Value lastMessageSend = Value.absent(); - Value lastMessageReceived = Value.absent(); - Value lastFlameCounterChange = Value.absent(); + var lastMessageSend = const Value.absent(); + var lastMessageReceived = const Value.absent(); + var lastFlameCounterChange = const Value.absent(); if (contact.lastFlameCounterChange != null) { final now = DateTime.now(); @@ -51,7 +54,7 @@ class ContactsDao extends DatabaseAccessor if (contact.lastFlameCounterChange!.isBefore(startOfToday)) { // last flame update was yesterday. check if it can be updated. - bool updateFlame = false; + var updateFlame = false; if (received) { if (contact.lastMessageSend != null && contact.lastMessageSend!.isAfter(startOfToday)) { @@ -94,11 +97,12 @@ class ContactsDao extends DatabaseAccessor return select(contacts)..where((t) => t.userId.equals(userId)); } - Future deleteContactByUserId(int userId) { + Future deleteContactByUserId(int userId) { return (delete(contacts)..where((t) => t.userId.equals(userId))).go(); } - Future updateContact(int userId, ContactsCompanion updatedValues) async { + Future updateContact( + int userId, ContactsCompanion updatedValues) async { await ((update(contacts)..where((c) => c.userId.equals(userId))) .write(updatedValues)); if (updatedValues.blocked.present || @@ -111,7 +115,7 @@ class ContactsDao extends DatabaseAccessor } } - Future newMessageExchange(int userId) { + Future newMessageExchange(int userId) { return updateContact( userId, ContactsCompanion( diff --git a/lib/src/database/daos/media_downloads_dao.dart b/lib/src/database/daos/media_downloads_dao.dart index defba0c..99e6a14 100644 --- a/lib/src/database/daos/media_downloads_dao.dart +++ b/lib/src/database/daos/media_downloads_dao.dart @@ -11,7 +11,7 @@ class MediaDownloadsDao extends DatabaseAccessor with _$MediaDownloadsDaoMixin { MediaDownloadsDao(super.db); - Future updateMediaDownload( + Future updateMediaDownload( int messageId, MediaDownloadsCompanion updatedValues) { return (update(mediaDownloads)..where((c) => c.messageId.equals(messageId))) .write(updatedValues); @@ -26,7 +26,7 @@ class MediaDownloadsDao extends DatabaseAccessor } } - Future deleteMediaDownload(int messageId) { + Future deleteMediaDownload(int messageId) { return (delete(mediaDownloads)..where((t) => t.messageId.equals(messageId))) .go(); } diff --git a/lib/src/database/daos/media_uploads_dao.dart b/lib/src/database/daos/media_uploads_dao.dart index 3361886..127328c 100644 --- a/lib/src/database/daos/media_uploads_dao.dart +++ b/lib/src/database/daos/media_uploads_dao.dart @@ -33,7 +33,7 @@ class MediaUploadsDao extends DatabaseAccessor } } - Future deleteMediaUpload(int mediaUploadId) { + Future deleteMediaUpload(int mediaUploadId) { return (delete(mediaUploads) ..where((t) => t.mediaUploadId.equals(mediaUploadId))) .go(); diff --git a/lib/src/database/daos/message_retransmissions.dao.dart b/lib/src/database/daos/message_retransmissions.dao.dart index 8db9798..ae26720 100644 --- a/lib/src/database/daos/message_retransmissions.dao.dart +++ b/lib/src/database/daos/message_retransmissions.dao.dart @@ -45,7 +45,7 @@ class MessageRetransmissionDao extends DatabaseAccessor ..where((t) => t.retransmissionId.equals(retransmissionId)); } - Future updateRetransmission( + Future updateRetransmission( int retransmissionId, MessageRetransmissionsCompanion updatedValues, ) { @@ -54,13 +54,13 @@ class MessageRetransmissionDao extends DatabaseAccessor .write(updatedValues); } - Future resetAckStatusFor(int fromUserId, Uint8List encryptedHash) async { + Future resetAckStatusFor(int fromUserId, Uint8List encryptedHash) async { return ((update(messageRetransmissions)) ..where((m) => m.contactId.equals(fromUserId) & m.encryptedHash.equals(encryptedHash))) .write( - MessageRetransmissionsCompanion( + const MessageRetransmissionsCompanion( acknowledgeByServerAt: Value(null), ), ); @@ -75,13 +75,13 @@ class MessageRetransmissionDao extends DatabaseAccessor .getSingleOrNull(); } - Future deleteRetransmissionById(int retransmissionId) { + Future deleteRetransmissionById(int retransmissionId) { return (delete(messageRetransmissions) ..where((t) => t.retransmissionId.equals(retransmissionId))) .go(); } - Future deleteRetransmissionByMessageId(int messageId) { + Future deleteRetransmissionByMessageId(int messageId) { return (delete(messageRetransmissions) ..where((t) => t.messageId.equals(messageId))) .go(); diff --git a/lib/src/database/daos/messages_dao.dart b/lib/src/database/daos/messages_dao.dart index 5ed6372..24c50b3 100644 --- a/lib/src/database/daos/messages_dao.dart +++ b/lib/src/database/daos/messages_dao.dart @@ -56,7 +56,7 @@ class MessagesDao extends DatabaseAccessor .watch(); } - Future removeOldMessages() { + Future removeOldMessages() { return (update(messages) ..where((t) => (t.openedAt.isSmallerThanValue( @@ -69,7 +69,7 @@ class MessagesDao extends DatabaseAccessor .write(MessagesCompanion(contentJson: Value(null))); } - Future handleMediaFilesOlderThan7Days() { + Future handleMediaFilesOlderThan7Days() { /// media files will be deleted by the server after 7 days, so delete them here also return (update(messages) ..where( @@ -130,7 +130,7 @@ class MessagesDao extends DatabaseAccessor .get(); } - Future openedAllNonMediaMessages(int contactId) { + Future openedAllNonMediaMessages(int contactId) { final updates = MessagesCompanion(openedAt: Value(DateTime.now())); return (update(messages) ..where((t) => @@ -141,7 +141,7 @@ class MessagesDao extends DatabaseAccessor .write(updates); } - Future resetPendingDownloadState() { + Future resetPendingDownloadState() { // All media files in the downloading state are reseteded to the pending state // When the app is used in mobile network, they will not be downloaded at the start // if they are not yet downloaded... @@ -155,7 +155,7 @@ class MessagesDao extends DatabaseAccessor .write(updates); } - Future openedAllNonMediaMessagesFromOtherUser(int contactId) { + Future openedAllNonMediaMessagesFromOtherUser(int contactId) { final updates = MessagesCompanion(openedAt: Value(DateTime.now())); return (update(messages) ..where((t) => @@ -167,7 +167,7 @@ class MessagesDao extends DatabaseAccessor .write(updates); } - Future updateMessageByOtherUser( + Future updateMessageByOtherUser( int userId, int messageId, MessagesCompanion updatedValues) { return (update(messages) ..where((c) => @@ -175,7 +175,7 @@ class MessagesDao extends DatabaseAccessor .write(updatedValues); } - Future updateMessageByOtherMessageId( + Future updateMessageByOtherMessageId( int userId, int messageOtherId, MessagesCompanion updatedValues) { return (update(messages) ..where((c) => @@ -184,7 +184,7 @@ class MessagesDao extends DatabaseAccessor .write(updatedValues); } - Future updateMessageByMessageId( + Future updateMessageByMessageId( int messageId, MessagesCompanion updatedValues) { return (update(messages)..where((c) => c.messageId.equals(messageId))) .write(updatedValues); @@ -203,14 +203,14 @@ class MessagesDao extends DatabaseAccessor } } - Future deleteMessagesByContactId(int contactId) { + Future deleteMessagesByContactId(int contactId) { return (delete(messages) ..where((t) => t.contactId.equals(contactId) & t.mediaStored.equals(false))) .go(); } - Future deleteMessagesByContactIdAndOtherMessageId( + Future deleteMessagesByContactIdAndOtherMessageId( int contactId, int messageOtherId) { return (delete(messages) ..where((t) => @@ -219,11 +219,11 @@ class MessagesDao extends DatabaseAccessor .go(); } - Future deleteMessagesByMessageId(int messageId) { + Future deleteMessagesByMessageId(int messageId) { return (delete(messages)..where((t) => t.messageId.equals(messageId))).go(); } - Future deleteAllMessagesByContactId(int contactId) { + Future deleteAllMessagesByContactId(int contactId) { return (delete(messages)..where((t) => t.contactId.equals(contactId))).go(); } diff --git a/lib/src/database/daos/signal_dao.dart b/lib/src/database/daos/signal_dao.dart index e088e7c..46e7cae 100644 --- a/lib/src/database/daos/signal_dao.dart +++ b/lib/src/database/daos/signal_dao.dart @@ -15,7 +15,7 @@ class SignalDao extends DatabaseAccessor with _$SignalDaoMixin { // this constructor is required so that the main database can create an instance // of this object. SignalDao(super.db); - Future deleteAllByContactId(int contactId) async { + Future deleteAllByContactId(int contactId) async { await (delete(signalContactPreKeys) ..where((t) => t.contactId.equals(contactId))) .go(); @@ -24,7 +24,7 @@ class SignalDao extends DatabaseAccessor with _$SignalDaoMixin { .go(); } - Future deleteAllPreKeysByContactId(int contactId) async { + Future deleteAllPreKeysByContactId(int contactId) async { await (delete(signalContactPreKeys) ..where((t) => t.contactId.equals(contactId))) .go(); diff --git a/lib/src/database/signal/connect_identitiy_key_store.dart b/lib/src/database/signal/connect_identitiy_key_store.dart index 0b0f9b0..aa2fe55 100644 --- a/lib/src/database/signal/connect_identitiy_key_store.dart +++ b/lib/src/database/signal/connect_identitiy_key_store.dart @@ -1,7 +1,7 @@ import 'package:collection/collection.dart'; import 'package:drift/drift.dart'; -import 'package:twonly/globals.dart'; import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; +import 'package:twonly/globals.dart'; import 'package:twonly/src/database/twonly_database.dart'; class ConnectIdentityKeyStore extends IdentityKeyStore { @@ -12,13 +12,11 @@ class ConnectIdentityKeyStore extends IdentityKeyStore { @override Future getIdentity(SignalProtocolAddress address) async { - SignalIdentityKeyStore? identity = - await (twonlyDB.select(twonlyDB.signalIdentityKeyStores) - ..where((t) => - t.deviceId.equals(address.getDeviceId()) & - t.name.equals(address.getName()))) - .getSingleOrNull(); - + final identity = await (twonlyDB.select(twonlyDB.signalIdentityKeyStores) + ..where((t) => + t.deviceId.equals(address.getDeviceId()) & + t.name.equals(address.getName()))) + .getSingleOrNull(); if (identity == null) return null; return IdentityKey.fromBytes(identity.identityKey, 0); } @@ -37,7 +35,8 @@ class ConnectIdentityKeyStore extends IdentityKeyStore { return false; } return trusted == null || - ListEquality().equals(trusted.serialize(), identityKey.serialize()); + const ListEquality() + .equals(trusted.serialize(), identityKey.serialize()); } @override diff --git a/lib/src/database/signal/connect_pre_key_store.dart b/lib/src/database/signal/connect_pre_key_store.dart index 1ecdc82..934b4f2 100644 --- a/lib/src/database/signal/connect_pre_key_store.dart +++ b/lib/src/database/signal/connect_pre_key_store.dart @@ -1,6 +1,6 @@ import 'package:drift/drift.dart'; -import 'package:twonly/globals.dart'; import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; +import 'package:twonly/globals.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/utils/log.dart'; @@ -21,7 +21,7 @@ class ConnectPreKeyStore extends PreKeyStore { if (preKeyRecord.isEmpty) { throw InvalidKeyIdException('No such preKey record! - $preKeyId'); } - Uint8List preKey = preKeyRecord.first.preKey; + final preKey = preKeyRecord.first.preKey; return PreKeyRecord.fromBuffer(preKey); } @@ -42,7 +42,7 @@ class ConnectPreKeyStore extends PreKeyStore { try { await twonlyDB.into(twonlyDB.signalPreKeyStores).insert(preKeyCompanion); } catch (e) { - Log.error("$e"); + Log.error('$e'); } } } diff --git a/lib/src/database/signal/connect_signed_pre_key_store.dart b/lib/src/database/signal/connect_signed_pre_key_store.dart index faf1bf5..88ca170 100644 --- a/lib/src/database/signal/connect_signed_pre_key_store.dart +++ b/lib/src/database/signal/connect_signed_pre_key_store.dart @@ -7,24 +7,24 @@ import 'package:twonly/src/constants/secure_storage_keys.dart'; class ConnectSignedPreKeyStore extends SignedPreKeyStore { Future> getStore() async { - final storage = FlutterSecureStorage(); + const storage = FlutterSecureStorage(); final storeSerialized = await storage.read( key: SecureStorageKeys.signalSignedPreKey, ); - var store = HashMap(); + final store = HashMap(); if (storeSerialized == null) { return store; } - final storeHashMap = json.decode(storeSerialized); + final storeHashMap = json.decode(storeSerialized) as List>; for (final item in storeHashMap) { - store[item[0]] = base64Decode(item[1]); + store[item[0] as int] = base64Decode(item[1] as String); } return store; } - Future safeStore(HashMap store) async { - final storage = FlutterSecureStorage(); - var storeHashMap = []; + Future safeStore(HashMap store) async { + const storage = FlutterSecureStorage(); + final storeHashMap = >[]; for (final item in store.entries) { storeHashMap.add([item.key, base64Encode(item.value)]); } diff --git a/lib/src/database/tables/media_uploads_table.dart b/lib/src/database/tables/media_uploads_table.dart index 5e13ef5..f2132b2 100644 --- a/lib/src/database/tables/media_uploads_table.dart +++ b/lib/src/database/tables/media_uploads_table.dart @@ -6,7 +6,6 @@ enum UploadState { readyToUpload, uploadTaskStarted, receiverNotified, - // after all users notified all media files that are not storable by the other person will be deleted } @DataClassName('MediaUpload') @@ -16,18 +15,30 @@ class MediaUploads extends Table { textEnum().withDefault(Constant(UploadState.pending.name))(); TextColumn get metadata => - text().map(MediaUploadMetadataConverter()).nullable()(); + text().map(const MediaUploadMetadataConverter()).nullable()(); /// exists in UploadState.addedToMessagesDb TextColumn get messageIds => text().map(IntListTypeConverter()).nullable()(); TextColumn get encryptionData => - text().map(MediaEncryptionDataConverter()).nullable()(); + text().map(const MediaEncryptionDataConverter()).nullable()(); } // --- state ---- class MediaUploadMetadata { + MediaUploadMetadata(); + factory MediaUploadMetadata.fromJson(Map json) { + return MediaUploadMetadata() + ..contactIds = List.from(json['contactIds'] as Iterable) + ..isRealTwonly = json['isRealTwonly'] as bool + ..isVideo = json['isVideo'] as bool + ..mirrorVideo = json['mirrorVideo'] as bool + ..maxShowTime = json['maxShowTime'] as int + ..maxShowTime = json['maxShowTime'] as int + ..messageSendAt = DateTime.parse(json['messageSendAt'] as String); + } + late List contactIds; late bool isRealTwonly; late int maxShowTime; @@ -35,8 +46,6 @@ class MediaUploadMetadata { late bool isVideo; late bool mirrorVideo; - MediaUploadMetadata(); - Map toJson() { return { 'contactIds': contactIds, @@ -47,28 +56,26 @@ class MediaUploadMetadata { 'messageSendAt': messageSendAt.toIso8601String(), }; } - - factory MediaUploadMetadata.fromJson(Map json) { - MediaUploadMetadata state = MediaUploadMetadata(); - state.contactIds = List.from(json['contactIds']); - state.isRealTwonly = json['isRealTwonly']; - state.isVideo = json['isVideo']; - state.mirrorVideo = json['mirrorVideo']; - state.maxShowTime = json['maxShowTime']; - state.maxShowTime = json['maxShowTime']; - state.messageSendAt = DateTime.parse(json['messageSendAt']); - return state; - } } class MediaEncryptionData { + MediaEncryptionData(); + + factory MediaEncryptionData.fromJson(Map json) { + return MediaEncryptionData() + ..sha2Hash = List.from(json['sha2Hash'] as Iterable) + ..encryptionKey = + List.from(json['encryptionKey'] as Iterable) + ..encryptionMac = + List.from(json['encryptionMac'] as Iterable) + ..encryptionNonce = + List.from(json['encryptionNonce'] as Iterable); + } late List sha2Hash; late List encryptionKey; late List encryptionMac; late List encryptionNonce; - MediaEncryptionData(); - Map toJson() { return { 'sha2Hash': sha2Hash, @@ -77,15 +84,6 @@ class MediaEncryptionData { 'encryptionNonce': encryptionNonce, }; } - - factory MediaEncryptionData.fromJson(Map json) { - MediaEncryptionData state = MediaEncryptionData(); - state.sha2Hash = List.from(json['sha2Hash']); - state.encryptionKey = List.from(json['encryptionKey']); - state.encryptionMac = List.from(json['encryptionMac']); - state.encryptionNonce = List.from(json['encryptionNonce']); - return state; - } } // --- converters ---- @@ -93,7 +91,7 @@ class MediaEncryptionData { class IntListTypeConverter extends TypeConverter, String> { @override List fromSql(String fromDb) { - return List.from(jsonDecode(fromDb)); + return List.from(jsonDecode(fromDb) as Iterable); } @override diff --git a/lib/src/database/twonly_database.dart b/lib/src/database/twonly_database.dart index 266d0f9..2d734b0 100644 --- a/lib/src/database/twonly_database.dart +++ b/lib/src/database/twonly_database.dart @@ -1,6 +1,6 @@ import 'package:drift/drift.dart'; import 'package:drift_flutter/drift_flutter.dart' - show driftDatabase, DriftNativeOptions; + show DriftNativeOptions, driftDatabase; import 'package:path_provider/path_provider.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; import 'package:twonly/src/database/daos/media_downloads_dao.dart'; @@ -73,15 +73,15 @@ class TwonlyDatabase extends _$TwonlyDatabase { }, onUpgrade: stepByStep( from1To2: (m, schema) async { - m.addColumn(schema.messages, schema.messages.errorWhileSending); + await m.addColumn(schema.messages, schema.messages.errorWhileSending); }, from2To3: (m, schema) async { - m.addColumn(schema.contacts, schema.contacts.archived); - m.addColumn( + await m.addColumn(schema.contacts, schema.contacts.archived); + await m.addColumn( schema.contacts, schema.contacts.deleteMessagesAfterXMinutes); }, from3To4: (m, schema) async { - m.createTable(schema.mediaUploads); + await m.createTable(schema.mediaUploads); await m.alterTable(TableMigration( schema.mediaUploads, columnTransformer: { @@ -91,19 +91,19 @@ class TwonlyDatabase extends _$TwonlyDatabase { )); }, from4To5: (m, schema) async { - m.createTable(mediaDownloads); - m.addColumn(schema.messages, schema.messages.mediaDownloadId); - m.addColumn(schema.messages, schema.messages.mediaUploadId); + await m.createTable(mediaDownloads); + await m.addColumn(schema.messages, schema.messages.mediaDownloadId); + await m.addColumn(schema.messages, schema.messages.mediaUploadId); }, from5To6: (m, schema) async { - m.addColumn(schema.messages, schema.messages.mediaStored); + await m.addColumn(schema.messages, schema.messages.mediaStored); }, from6To7: (m, schema) async { - m.addColumn(schema.contacts, schema.contacts.pinned); + await m.addColumn(schema.contacts, schema.contacts.pinned); }, from7To8: (m, schema) async { - m.addColumn(schema.contacts, schema.contacts.alsoBestFriend); - m.addColumn(schema.contacts, schema.contacts.lastFlameSync); + await m.addColumn(schema.contacts, schema.contacts.alsoBestFriend); + await m.addColumn(schema.contacts, schema.contacts.lastFlameSync); }, from8To9: (m, schema) async { await m.alterTable(TableMigration( @@ -115,29 +115,29 @@ class TwonlyDatabase extends _$TwonlyDatabase { )); }, from9To10: (m, schema) async { - m.createTable(schema.signalContactPreKeys); - m.createTable(schema.signalContactSignedPreKeys); - m.addColumn(schema.contacts, schema.contacts.deleted); + await m.createTable(schema.signalContactPreKeys); + await m.createTable(schema.signalContactSignedPreKeys); + await m.addColumn(schema.contacts, schema.contacts.deleted); }, from10To11: (m, schema) async { - m.createTable(schema.messageRetransmissions); + await m.createTable(schema.messageRetransmissions); }, from11To12: (m, schema) async { - m.addColumn(schema.messageRetransmissions, + await m.addColumn(schema.messageRetransmissions, schema.messageRetransmissions.willNotGetACKByUser); }, from12To13: (m, schema) async { - m.dropColumn( - schema.messageRetransmissions, "will_not_get_a_c_k_by_user"); + await m.dropColumn( + schema.messageRetransmissions, 'will_not_get_a_c_k_by_user'); }, from13To14: (m, schema) async { - m.addColumn(schema.messageRetransmissions, + await m.addColumn(schema.messageRetransmissions, schema.messageRetransmissions.encryptedHash); }, from14To15: (m, schema) async { - m.dropColumn(schema.mediaUploads, "upload_tokens"); - m.dropColumn(schema.mediaUploads, "already_notified"); - m.addColumn( + await m.dropColumn(schema.mediaUploads, 'upload_tokens'); + await m.dropColumn(schema.mediaUploads, 'already_notified'); + await m.addColumn( schema.messages, schema.messages.mediaRetransmissionState); }, ), @@ -161,13 +161,13 @@ class TwonlyDatabase extends _$TwonlyDatabase { } } - Future deleteDataForTwonlySafe() async { + Future deleteDataForTwonlySafe() async { await delete(messages).go(); await delete(messageRetransmissions).go(); await delete(mediaDownloads).go(); await delete(mediaUploads).go(); await update(contacts).write( - ContactsCompanion( + const ContactsCompanion( avatarSvg: Value(null), myAvatarCounter: Value(0), ), @@ -177,7 +177,7 @@ class TwonlyDatabase extends _$TwonlyDatabase { await (delete(signalPreKeyStores) ..where((t) => (t.createdAt.isSmallerThanValue( DateTime.now().subtract( - Duration(days: 25), + const Duration(days: 25), ), )))) .go(); diff --git a/lib/src/localization/app_de.arb b/lib/src/localization/app_de.arb index 4d30728..1be3599 100644 --- a/lib/src/localization/app_de.arb +++ b/lib/src/localization/app_de.arb @@ -89,7 +89,7 @@ "messageSendState_Sending": "Wird gesendet", "messageSendState_TapToLoad": "Tippe zum Laden", "messageSendState_Loading": "Herunterladen", - "messageStoredInGalery": "Gespeichert", + "messageStoredInGallery": "Gespeichert", "messageReopened": "Erneut geรถffnet", "@messageReopened": {}, "imageEditorDrawOk": "Zeichnung machen", @@ -329,7 +329,7 @@ "appOutdatedBtn": "Jetzt aktualisieren.", "doubleClickToReopen": "Doppelklicken zum\nerneuten ร–ffnen.", "retransmissionRequested": "Wird erneut versucht.", - "testPaymentMethode": "twonly befindet sich derzeit in einer Testphase und kann nur mit einem Einladungscode vollstรคndig genutzt werden. Es gibt derzeit keine Zahlungsmethode, um Ihr twonly-Guthaben aufzuladen!", + "testPaymentMethod": "twonly befindet sich derzeit in einer Testphase und kann nur mit einem Einladungscode vollstรคndig genutzt werden. Es gibt derzeit keine Zahlungsmethode, um Ihr twonly-Guthaben aufzuladen!", "testingAccountTitle": "Tester-Zugang", "testingAccountBody": "Danke fรผr dein Interesse! Wir werden deine Anfrage prรผfen und den Plan so schnell wie mรถglich aktivieren. Da wir uns jedoch noch in einer Testphase befinden, ist die Anzahl der Tester-Konten begrenzt. Wir werden dich jedoch benachrichtigen, sobald dir ein Platz zugewiesen wurde." } \ No newline at end of file diff --git a/lib/src/localization/app_en.arb b/lib/src/localization/app_en.arb index fd2e44e..60f4268 100644 --- a/lib/src/localization/app_en.arb +++ b/lib/src/localization/app_en.arb @@ -145,8 +145,8 @@ "@messageSendState_TapToLoad": {}, "messageSendState_Loading": "Downloading", "@messageSendState_Loading": {}, - "messageStoredInGalery": "Stored in gallery", - "@messageStoredInGalery": {}, + "messageStoredInGallery": "Stored in gallery", + "@messageStoredInGallery": {}, "messageReopened": "Re-opened", "@messageReopened": {}, "imageEditorDrawOk": "Take drawing", @@ -486,7 +486,7 @@ "appOutdatedBtn": "Update Now", "doubleClickToReopen": "Double-click\nto open again", "retransmissionRequested": "Retransmission requested", - "testPaymentMethode": "twonly is currently in a test phase and can only be used in full with an invitation code. There is currently no payment method to top up your twonly credit!", + "testPaymentMethod": "twonly is currently in a test phase and can only be used in full with an invitation code. There is currently no payment method to top up your twonly credit!", "testingAccountTitle": "Tester account activation", "testingAccountBody": "Thank you for your interest! We will check your request and activate the plan as soon as possible. However, as we are currently still in a test phase, the number of tester accounts is limited. However, we will notify you as soon as you have been allocated a place." } \ No newline at end of file diff --git a/lib/src/localization/generated/app_localizations.dart b/lib/src/localization/generated/app_localizations.dart index 7719bdf..aed1289 100644 --- a/lib/src/localization/generated/app_localizations.dart +++ b/lib/src/localization/generated/app_localizations.dart @@ -542,11 +542,11 @@ abstract class AppLocalizations { /// **'Downloading'** String get messageSendState_Loading; - /// No description provided for @messageStoredInGalery. + /// No description provided for @messageStoredInGallery. /// /// In en, this message translates to: /// **'Stored in gallery'** - String get messageStoredInGalery; + String get messageStoredInGallery; /// No description provided for @messageReopened. /// @@ -2012,11 +2012,11 @@ abstract class AppLocalizations { /// **'Retransmission requested'** String get retransmissionRequested; - /// No description provided for @testPaymentMethode. + /// No description provided for @testPaymentMethod. /// /// In en, this message translates to: /// **'twonly is currently in a test phase and can only be used in full with an invitation code. There is currently no payment method to top up your twonly credit!'** - String get testPaymentMethode; + String get testPaymentMethod; /// No description provided for @testingAccountTitle. /// diff --git a/lib/src/localization/generated/app_localizations_de.dart b/lib/src/localization/generated/app_localizations_de.dart index 777c39d..bc16c83 100644 --- a/lib/src/localization/generated/app_localizations_de.dart +++ b/lib/src/localization/generated/app_localizations_de.dart @@ -253,7 +253,7 @@ class AppLocalizationsDe extends AppLocalizations { String get messageSendState_Loading => 'Herunterladen'; @override - String get messageStoredInGalery => 'Gespeichert'; + String get messageStoredInGallery => 'Gespeichert'; @override String get messageReopened => 'Erneut geรถffnet'; @@ -1068,7 +1068,7 @@ class AppLocalizationsDe extends AppLocalizations { String get retransmissionRequested => 'Wird erneut versucht.'; @override - String get testPaymentMethode => + String get testPaymentMethod => 'twonly befindet sich derzeit in einer Testphase und kann nur mit einem Einladungscode vollstรคndig genutzt werden. Es gibt derzeit keine Zahlungsmethode, um Ihr twonly-Guthaben aufzuladen!'; @override diff --git a/lib/src/localization/generated/app_localizations_en.dart b/lib/src/localization/generated/app_localizations_en.dart index 382dfc3..22f94b3 100644 --- a/lib/src/localization/generated/app_localizations_en.dart +++ b/lib/src/localization/generated/app_localizations_en.dart @@ -250,7 +250,7 @@ class AppLocalizationsEn extends AppLocalizations { String get messageSendState_Loading => 'Downloading'; @override - String get messageStoredInGalery => 'Stored in gallery'; + String get messageStoredInGallery => 'Stored in gallery'; @override String get messageReopened => 'Re-opened'; @@ -1062,7 +1062,7 @@ class AppLocalizationsEn extends AppLocalizations { String get retransmissionRequested => 'Retransmission requested'; @override - String get testPaymentMethode => + String get testPaymentMethod => 'twonly is currently in a test phase and can only be used in full with an invitation code. There is currently no payment method to top up your twonly credit!'; @override diff --git a/lib/src/model/json/message.dart b/lib/src/model/json/message.dart index b620b48..89cd875 100644 --- a/lib/src/model/json/message.dart +++ b/lib/src/model/json/message.dart @@ -1,3 +1,5 @@ +// ignore_for_file: strict_raw_type, prefer_constructors_over_static_methods + import 'package:flutter/material.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; import 'package:twonly/src/utils/misc.dart'; @@ -34,6 +36,14 @@ extension MessageKindExtension on MessageKind { } class MessageJson { + MessageJson({ + required this.kind, + required this.content, + required this.timestamp, + this.messageReceiverId, + this.messageSenderId, + this.retransId, + }); final MessageKind kind; final MessageContent? content; final int? messageReceiverId; @@ -41,22 +51,13 @@ class MessageJson { int? retransId; DateTime timestamp; - MessageJson({ - required this.kind, - this.messageReceiverId, - this.messageSenderId, - this.retransId, - required this.content, - required this.timestamp, - }); - @override String toString() { return 'Message(kind: $kind, content: $content, timestamp: $timestamp)'; } static MessageJson fromJson(Map json) { - final kind = MessageKindExtension.fromString(json["kind"]); + final kind = MessageKindExtension.fromString(json['kind'] as String); return MessageJson( kind: kind, @@ -65,7 +66,7 @@ class MessageJson { retransId: (json['retransId'] as num?)?.toInt(), content: MessageContent.fromJson( kind, json['content'] as Map), - timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp']), + timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int), ); } @@ -100,9 +101,15 @@ class MessageContent { return AckContent.fromJson(json); case MessageKind.signalDecryptError: return SignalDecryptErrorContent.fromJson(json); - default: - return null; + case MessageKind.storedMediaFile: + case MessageKind.contactRequest: + case MessageKind.rejectRequest: + case MessageKind.acceptRequest: + case MessageKind.opened: + case MessageKind.requestPushKey: + case MessageKind.receiveMediaError: } + return null; } Map toJson() { @@ -111,15 +118,6 @@ class MessageContent { } class MediaMessageContent extends MessageContent { - final int maxShowTime; - final bool isRealTwonly; - final bool isVideo; - final bool mirrorVideo; - final List? downloadToken; - final List? encryptionKey; - final List? encryptionMac; - final List? encryptionNonce; - MediaMessageContent({ required this.maxShowTime, required this.isRealTwonly, @@ -130,25 +128,33 @@ class MediaMessageContent extends MessageContent { this.encryptionMac, this.encryptionNonce, }); + final int maxShowTime; + final bool isRealTwonly; + final bool isVideo; + final bool mirrorVideo; + final List? downloadToken; + final List? encryptionKey; + final List? encryptionMac; + final List? encryptionNonce; static MediaMessageContent fromJson(Map json) { return MediaMessageContent( downloadToken: json['downloadToken'] == null ? null - : List.from(json['downloadToken']), + : List.from(json['downloadToken'] as List), encryptionKey: json['encryptionKey'] == null ? null - : List.from(json['encryptionKey']), + : List.from(json['encryptionKey'] as List), encryptionMac: json['encryptionMac'] == null ? null - : List.from(json['encryptionMac']), + : List.from(json['encryptionMac'] as List), encryptionNonce: json['encryptionNonce'] == null ? null - : List.from(json['encryptionNonce']), - maxShowTime: json['maxShowTime'], - isRealTwonly: json['isRealTwonly'], - isVideo: json['isVideo'] ?? false, - mirrorVideo: json['mirrorVideo'] ?? false, + : List.from(json['encryptionNonce'] as List), + maxShowTime: json['maxShowTime'] as int, + isRealTwonly: json['isRealTwonly'] as bool, + isVideo: json['isVideo'] as bool? ?? false, + mirrorVideo: json['mirrorVideo'] as bool? ?? false, ); } @@ -168,23 +174,23 @@ class MediaMessageContent extends MessageContent { } class TextMessageContent extends MessageContent { - String text; - int? responseToMessageId; - int? responseToOtherMessageId; TextMessageContent({ required this.text, this.responseToMessageId, this.responseToOtherMessageId, }); + String text; + int? responseToMessageId; + int? responseToOtherMessageId; static TextMessageContent fromJson(Map json) { return TextMessageContent( - text: json['text'], + text: json['text'] as String, responseToOtherMessageId: json.containsKey('responseToOtherMessageId') - ? json['responseToOtherMessageId'] + ? json['responseToOtherMessageId'] as int? : null, responseToMessageId: json.containsKey('responseToMessageId') - ? json['responseToMessageId'] + ? json['responseToMessageId'] as int? : null); } @@ -199,11 +205,11 @@ class TextMessageContent extends MessageContent { } class ReopenedMediaFileContent extends MessageContent { - int messageId; ReopenedMediaFileContent({required this.messageId}); + int messageId; static ReopenedMediaFileContent fromJson(Map json) { - return ReopenedMediaFileContent(messageId: json['messageId']); + return ReopenedMediaFileContent(messageId: json['messageId'] as int); } @override @@ -213,12 +219,12 @@ class ReopenedMediaFileContent extends MessageContent { } class SignalDecryptErrorContent extends MessageContent { - List encryptedHash; SignalDecryptErrorContent({required this.encryptedHash}); + List encryptedHash; static SignalDecryptErrorContent fromJson(Map json) { return SignalDecryptErrorContent( - encryptedHash: List.from(json['encryptedHash']), + encryptedHash: List.from(json['encryptedHash'] as List), ); } @@ -231,14 +237,14 @@ class SignalDecryptErrorContent extends MessageContent { } class AckContent extends MessageContent { + AckContent({required this.messageIdToAck, required this.retransIdToAck}); int? messageIdToAck; int retransIdToAck; - AckContent({required this.messageIdToAck, required this.retransIdToAck}); static AckContent fromJson(Map json) { return AckContent( - messageIdToAck: json['messageIdToAck'], - retransIdToAck: json['retransIdToAck'], + messageIdToAck: json['messageIdToAck'] as int, + retransIdToAck: json['retransIdToAck'] as int, ); } @@ -252,14 +258,14 @@ class AckContent extends MessageContent { } class ProfileContent extends MessageContent { + ProfileContent({required this.avatarSvg, required this.displayName}); String avatarSvg; String displayName; - ProfileContent({required this.avatarSvg, required this.displayName}); static ProfileContent fromJson(Map json) { return ProfileContent( - avatarSvg: json['avatarSvg'], - displayName: json['displayName'], + avatarSvg: json['avatarSvg'] as String, + displayName: json['displayName'] as String, ); } @@ -270,14 +276,14 @@ class ProfileContent extends MessageContent { } class PushKeyContent extends MessageContent { + PushKeyContent({required this.keyId, required this.key}); int keyId; List key; - PushKeyContent({required this.keyId, required this.key}); static PushKeyContent fromJson(Map json) { return PushKeyContent( - keyId: json['keyId'], - key: List.from(json['key']), + keyId: json['keyId'] as int, + key: List.from(json['key'] as List), ); } @@ -291,21 +297,20 @@ class PushKeyContent extends MessageContent { } class FlameSyncContent extends MessageContent { - int flameCounter; - DateTime lastFlameCounterChange; - bool bestFriend; - FlameSyncContent( {required this.flameCounter, required this.bestFriend, required this.lastFlameCounterChange}); + int flameCounter; + DateTime lastFlameCounterChange; + bool bestFriend; static FlameSyncContent fromJson(Map json) { return FlameSyncContent( - flameCounter: json['flameCounter'], - bestFriend: json['bestFriend'], - lastFlameCounterChange: - DateTime.fromMillisecondsSinceEpoch(json['lastFlameCounterChange']), + flameCounter: json['flameCounter'] as int, + bestFriend: json['bestFriend'] as bool, + lastFlameCounterChange: DateTime.fromMillisecondsSinceEpoch( + json['lastFlameCounterChange'] as int), ); } diff --git a/lib/src/model/memory_item.model.dart b/lib/src/model/memory_item.model.dart index e05f78b..1dffd06 100644 --- a/lib/src/model/memory_item.model.dart +++ b/lib/src/model/memory_item.model.dart @@ -1,10 +1,11 @@ import 'dart:convert'; import 'dart:io'; + import 'package:drift/drift.dart'; -import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/services/api/media_upload.dart' as send; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/model/json/message.dart'; +import 'package:twonly/src/services/api/media_upload.dart' as send; import 'package:twonly/src/services/thumbnail.service.dart'; class MemoryItem { @@ -28,45 +29,45 @@ class MemoryItem { static Future> convertFromMessages( List messages, ) async { - Map items = {}; + final items = {}; for (final message in messages) { - bool isSend = message.messageOtherId == null; - int id = message.mediaUploadId ?? message.messageId; + final isSend = message.messageOtherId == null; + final id = message.mediaUploadId ?? message.messageId; final basePath = await send.getMediaFilePath( isSend ? message.mediaUploadId! : message.messageId, - isSend ? "send" : "received", + isSend ? 'send' : 'received', ); File? imagePath; late File thumbnailFile; File? videoPath; - if (await File("$basePath.mp4").exists()) { - videoPath = File("$basePath.mp4"); + if (File('$basePath.mp4').existsSync()) { + videoPath = File('$basePath.mp4'); thumbnailFile = getThumbnailPath(videoPath); - if (!await thumbnailFile.exists()) { + if (!thumbnailFile.existsSync()) { await createThumbnailsForVideo(videoPath); } - } else if (await File("$basePath.png").exists()) { - imagePath = File("$basePath.png"); + } else if (File('$basePath.png').existsSync()) { + imagePath = File('$basePath.png'); thumbnailFile = getThumbnailPath(imagePath); - if (!await thumbnailFile.exists()) { + if (!thumbnailFile.existsSync()) { await createThumbnailsForImage(imagePath); } } else { if (message.mediaStored) { /// media file was deleted, ... remove the file - twonlyDB.messagesDao.updateMessageByMessageId( + await twonlyDB.messagesDao.updateMessageByMessageId( message.messageId, - MessagesCompanion( + const MessagesCompanion( mediaStored: Value(false), ), ); } continue; } - bool mirrorVideo = false; + var mirrorVideo = false; if (videoPath != null) { - MediaMessageContent content = - MediaMessageContent.fromJson(jsonDecode(message.contentJson!)); + final content = MediaMessageContent.fromJson( + jsonDecode(message.contentJson!) as Map); mirrorVideo = content.mirrorVideo; } diff --git a/lib/src/model/protobuf/api/websocket/client_to_server.pb.dart b/lib/src/model/protobuf/api/websocket/client_to_server.pb.dart index 41519e9..f8c2a45 100644 --- a/lib/src/model/protobuf/api/websocket/client_to_server.pb.dart +++ b/lib/src/model/protobuf/api/websocket/client_to_server.pb.dart @@ -16,10 +16,7 @@ import 'package:protobuf/protobuf.dart' as $pb; import 'error.pbenum.dart' as $0; -enum ClientToServer_V { - v0, - notSet -} +enum ClientToServer_V { v0, notSet } class ClientToServer extends $pb.GeneratedMessage { factory ClientToServer({ @@ -32,38 +29,48 @@ class ClientToServer extends $pb.GeneratedMessage { return $result; } ClientToServer._() : super(); - factory ClientToServer.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ClientToServer.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ClientToServer.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ClientToServer.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); static const $core.Map<$core.int, ClientToServer_V> _ClientToServer_VByTag = { - 1 : ClientToServer_V.v0, - 0 : ClientToServer_V.notSet + 1: ClientToServer_V.v0, + 0: ClientToServer_V.notSet }; - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ClientToServer', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ClientToServer', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..oo(0, [1]) - ..aOM(1, _omitFieldNames ? '' : 'V0', protoName: 'V0', subBuilder: V0.create) - ..hasRequiredFields = false - ; + ..aOM(1, _omitFieldNames ? '' : 'V0', + protoName: 'V0', subBuilder: V0.create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') ClientToServer clone() => ClientToServer()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ClientToServer copyWith(void Function(ClientToServer) updates) => super.copyWith((message) => updates(message as ClientToServer)) as ClientToServer; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ClientToServer copyWith(void Function(ClientToServer) updates) => + super.copyWith((message) => updates(message as ClientToServer)) + as ClientToServer; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ClientToServer create() => ClientToServer._(); ClientToServer createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ClientToServer getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ClientToServer getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ClientToServer? _defaultInstance; ClientToServer_V whichV() => _ClientToServer_VByTag[$_whichOneof(0)]!; @@ -72,7 +79,10 @@ class ClientToServer extends $pb.GeneratedMessage { @$pb.TagNumber(1) V0 get v0 => $_getN(0); @$pb.TagNumber(1) - set v0(V0 v) { setField(1, v); } + set v0(V0 v) { + setField(1, v); + } + @$pb.TagNumber(1) $core.bool hasV0() => $_has(0); @$pb.TagNumber(1) @@ -81,12 +91,7 @@ class ClientToServer extends $pb.GeneratedMessage { V0 ensureV0() => $_ensure(0); } -enum V0_Kind { - handshake, - applicationdata, - response, - notSet -} +enum V0_Kind { handshake, applicationdata, response, notSet } class V0 extends $pb.GeneratedMessage { factory V0({ @@ -111,34 +116,44 @@ class V0 extends $pb.GeneratedMessage { return $result; } V0._() : super(); - factory V0.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory V0.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory V0.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory V0.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); static const $core.Map<$core.int, V0_Kind> _V0_KindByTag = { - 2 : V0_Kind.handshake, - 3 : V0_Kind.applicationdata, - 4 : V0_Kind.response, - 0 : V0_Kind.notSet + 2: V0_Kind.handshake, + 3: V0_Kind.applicationdata, + 4: V0_Kind.response, + 0: V0_Kind.notSet }; - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'V0', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'V0', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..oo(0, [2, 3, 4]) - ..a<$fixnum.Int64>(1, _omitFieldNames ? '' : 'seq', $pb.PbFieldType.OU6, defaultOrMaker: $fixnum.Int64.ZERO) - ..aOM(2, _omitFieldNames ? '' : 'handshake', subBuilder: Handshake.create) - ..aOM(3, _omitFieldNames ? '' : 'applicationdata', subBuilder: ApplicationData.create) - ..aOM(4, _omitFieldNames ? '' : 'response', subBuilder: Response.create) - ..hasRequiredFields = false - ; + ..a<$fixnum.Int64>(1, _omitFieldNames ? '' : 'seq', $pb.PbFieldType.OU6, + defaultOrMaker: $fixnum.Int64.ZERO) + ..aOM(2, _omitFieldNames ? '' : 'handshake', + subBuilder: Handshake.create) + ..aOM(3, _omitFieldNames ? '' : 'applicationdata', + subBuilder: ApplicationData.create) + ..aOM(4, _omitFieldNames ? '' : 'response', + subBuilder: Response.create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') V0 clone() => V0()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - V0 copyWith(void Function(V0) updates) => super.copyWith((message) => updates(message as V0)) as V0; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + V0 copyWith(void Function(V0) updates) => + super.copyWith((message) => updates(message as V0)) as V0; $pb.BuilderInfo get info_ => _i; @@ -147,7 +162,8 @@ class V0 extends $pb.GeneratedMessage { V0 createEmptyInstance() => create(); static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static V0 getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static V0 getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static V0? _defaultInstance; V0_Kind whichKind() => _V0_KindByTag[$_whichOneof(0)]!; @@ -156,7 +172,10 @@ class V0 extends $pb.GeneratedMessage { @$pb.TagNumber(1) $fixnum.Int64 get seq => $_getI64(0); @$pb.TagNumber(1) - set seq($fixnum.Int64 v) { $_setInt64(0, v); } + set seq($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasSeq() => $_has(0); @$pb.TagNumber(1) @@ -165,7 +184,10 @@ class V0 extends $pb.GeneratedMessage { @$pb.TagNumber(2) Handshake get handshake => $_getN(1); @$pb.TagNumber(2) - set handshake(Handshake v) { setField(2, v); } + set handshake(Handshake v) { + setField(2, v); + } + @$pb.TagNumber(2) $core.bool hasHandshake() => $_has(1); @$pb.TagNumber(2) @@ -176,7 +198,10 @@ class V0 extends $pb.GeneratedMessage { @$pb.TagNumber(3) ApplicationData get applicationdata => $_getN(2); @$pb.TagNumber(3) - set applicationdata(ApplicationData v) { setField(3, v); } + set applicationdata(ApplicationData v) { + setField(3, v); + } + @$pb.TagNumber(3) $core.bool hasApplicationdata() => $_has(2); @$pb.TagNumber(3) @@ -187,7 +212,10 @@ class V0 extends $pb.GeneratedMessage { @$pb.TagNumber(4) Response get response => $_getN(3); @$pb.TagNumber(4) - set response(Response v) { setField(4, v); } + set response(Response v) { + setField(4, v); + } + @$pb.TagNumber(4) $core.bool hasResponse() => $_has(3); @$pb.TagNumber(4) @@ -235,46 +263,61 @@ class Handshake_Register extends $pb.GeneratedMessage { return $result; } Handshake_Register._() : super(); - factory Handshake_Register.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Handshake_Register.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Handshake_Register.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Handshake_Register.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Handshake.Register', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Handshake.Register', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'username') ..aOS(2, _omitFieldNames ? '' : 'inviteCode') - ..a<$core.List<$core.int>>(3, _omitFieldNames ? '' : 'publicIdentityKey', $pb.PbFieldType.OY) - ..a<$core.List<$core.int>>(4, _omitFieldNames ? '' : 'signedPrekey', $pb.PbFieldType.OY) - ..a<$core.List<$core.int>>(5, _omitFieldNames ? '' : 'signedPrekeySignature', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>( + 3, _omitFieldNames ? '' : 'publicIdentityKey', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>( + 4, _omitFieldNames ? '' : 'signedPrekey', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>( + 5, _omitFieldNames ? '' : 'signedPrekeySignature', $pb.PbFieldType.OY) ..aInt64(6, _omitFieldNames ? '' : 'signedPrekeyId') ..aInt64(7, _omitFieldNames ? '' : 'registrationId') ..aOB(8, _omitFieldNames ? '' : 'isIos') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') Handshake_Register clone() => Handshake_Register()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Handshake_Register copyWith(void Function(Handshake_Register) updates) => super.copyWith((message) => updates(message as Handshake_Register)) as Handshake_Register; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Handshake_Register copyWith(void Function(Handshake_Register) updates) => + super.copyWith((message) => updates(message as Handshake_Register)) + as Handshake_Register; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Handshake_Register create() => Handshake_Register._(); Handshake_Register createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static Handshake_Register getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Handshake_Register getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Handshake_Register? _defaultInstance; @$pb.TagNumber(1) $core.String get username => $_getSZ(0); @$pb.TagNumber(1) - set username($core.String v) { $_setString(0, v); } + set username($core.String v) { + $_setString(0, v); + } + @$pb.TagNumber(1) $core.bool hasUsername() => $_has(0); @$pb.TagNumber(1) @@ -283,7 +326,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(2) $core.String get inviteCode => $_getSZ(1); @$pb.TagNumber(2) - set inviteCode($core.String v) { $_setString(1, v); } + set inviteCode($core.String v) { + $_setString(1, v); + } + @$pb.TagNumber(2) $core.bool hasInviteCode() => $_has(1); @$pb.TagNumber(2) @@ -292,7 +338,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(3) $core.List<$core.int> get publicIdentityKey => $_getN(2); @$pb.TagNumber(3) - set publicIdentityKey($core.List<$core.int> v) { $_setBytes(2, v); } + set publicIdentityKey($core.List<$core.int> v) { + $_setBytes(2, v); + } + @$pb.TagNumber(3) $core.bool hasPublicIdentityKey() => $_has(2); @$pb.TagNumber(3) @@ -301,7 +350,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(4) $core.List<$core.int> get signedPrekey => $_getN(3); @$pb.TagNumber(4) - set signedPrekey($core.List<$core.int> v) { $_setBytes(3, v); } + set signedPrekey($core.List<$core.int> v) { + $_setBytes(3, v); + } + @$pb.TagNumber(4) $core.bool hasSignedPrekey() => $_has(3); @$pb.TagNumber(4) @@ -310,7 +362,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(5) $core.List<$core.int> get signedPrekeySignature => $_getN(4); @$pb.TagNumber(5) - set signedPrekeySignature($core.List<$core.int> v) { $_setBytes(4, v); } + set signedPrekeySignature($core.List<$core.int> v) { + $_setBytes(4, v); + } + @$pb.TagNumber(5) $core.bool hasSignedPrekeySignature() => $_has(4); @$pb.TagNumber(5) @@ -319,7 +374,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(6) $fixnum.Int64 get signedPrekeyId => $_getI64(5); @$pb.TagNumber(6) - set signedPrekeyId($fixnum.Int64 v) { $_setInt64(5, v); } + set signedPrekeyId($fixnum.Int64 v) { + $_setInt64(5, v); + } + @$pb.TagNumber(6) $core.bool hasSignedPrekeyId() => $_has(5); @$pb.TagNumber(6) @@ -328,7 +386,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(7) $fixnum.Int64 get registrationId => $_getI64(6); @$pb.TagNumber(7) - set registrationId($fixnum.Int64 v) { $_setInt64(6, v); } + set registrationId($fixnum.Int64 v) { + $_setInt64(6, v); + } + @$pb.TagNumber(7) $core.bool hasRegistrationId() => $_has(6); @$pb.TagNumber(7) @@ -337,7 +398,10 @@ class Handshake_Register extends $pb.GeneratedMessage { @$pb.TagNumber(8) $core.bool get isIos => $_getBF(7); @$pb.TagNumber(8) - set isIos($core.bool v) { $_setBool(7, v); } + set isIos($core.bool v) { + $_setBool(7, v); + } + @$pb.TagNumber(8) $core.bool hasIsIos() => $_has(7); @$pb.TagNumber(8) @@ -347,32 +411,44 @@ class Handshake_Register extends $pb.GeneratedMessage { class Handshake_GetAuthChallenge extends $pb.GeneratedMessage { factory Handshake_GetAuthChallenge() => create(); Handshake_GetAuthChallenge._() : super(); - factory Handshake_GetAuthChallenge.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Handshake_GetAuthChallenge.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Handshake_GetAuthChallenge.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Handshake_GetAuthChallenge.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Handshake.GetAuthChallenge', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Handshake.GetAuthChallenge', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - Handshake_GetAuthChallenge clone() => Handshake_GetAuthChallenge()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Handshake_GetAuthChallenge copyWith(void Function(Handshake_GetAuthChallenge) updates) => super.copyWith((message) => updates(message as Handshake_GetAuthChallenge)) as Handshake_GetAuthChallenge; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + Handshake_GetAuthChallenge clone() => + Handshake_GetAuthChallenge()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Handshake_GetAuthChallenge copyWith( + void Function(Handshake_GetAuthChallenge) updates) => + super.copyWith( + (message) => updates(message as Handshake_GetAuthChallenge)) + as Handshake_GetAuthChallenge; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Handshake_GetAuthChallenge create() => Handshake_GetAuthChallenge._(); Handshake_GetAuthChallenge createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static Handshake_GetAuthChallenge getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Handshake_GetAuthChallenge getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Handshake_GetAuthChallenge? _defaultInstance; } @@ -391,40 +467,55 @@ class Handshake_GetAuthToken extends $pb.GeneratedMessage { return $result; } Handshake_GetAuthToken._() : super(); - factory Handshake_GetAuthToken.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Handshake_GetAuthToken.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Handshake_GetAuthToken.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Handshake_GetAuthToken.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Handshake.GetAuthToken', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Handshake.GetAuthToken', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..a<$core.List<$core.int>>(2, _omitFieldNames ? '' : 'response', $pb.PbFieldType.OY) - ..hasRequiredFields = false - ; + ..a<$core.List<$core.int>>( + 2, _omitFieldNames ? '' : 'response', $pb.PbFieldType.OY) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - Handshake_GetAuthToken clone() => Handshake_GetAuthToken()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Handshake_GetAuthToken copyWith(void Function(Handshake_GetAuthToken) updates) => super.copyWith((message) => updates(message as Handshake_GetAuthToken)) as Handshake_GetAuthToken; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + Handshake_GetAuthToken clone() => + Handshake_GetAuthToken()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Handshake_GetAuthToken copyWith( + void Function(Handshake_GetAuthToken) updates) => + super.copyWith((message) => updates(message as Handshake_GetAuthToken)) + as Handshake_GetAuthToken; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Handshake_GetAuthToken create() => Handshake_GetAuthToken._(); Handshake_GetAuthToken createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static Handshake_GetAuthToken getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Handshake_GetAuthToken getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Handshake_GetAuthToken? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -433,7 +524,10 @@ class Handshake_GetAuthToken extends $pb.GeneratedMessage { @$pb.TagNumber(2) $core.List<$core.int> get response => $_getN(1); @$pb.TagNumber(2) - set response($core.List<$core.int> v) { $_setBytes(1, v); } + set response($core.List<$core.int> v) { + $_setBytes(1, v); + } + @$pb.TagNumber(2) $core.bool hasResponse() => $_has(1); @$pb.TagNumber(2) @@ -459,41 +553,56 @@ class Handshake_Authenticate extends $pb.GeneratedMessage { return $result; } Handshake_Authenticate._() : super(); - factory Handshake_Authenticate.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Handshake_Authenticate.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Handshake_Authenticate.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Handshake_Authenticate.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Handshake.Authenticate', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Handshake.Authenticate', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..a<$core.List<$core.int>>(2, _omitFieldNames ? '' : 'authToken', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>( + 2, _omitFieldNames ? '' : 'authToken', $pb.PbFieldType.OY) ..aOS(3, _omitFieldNames ? '' : 'appVersion') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - Handshake_Authenticate clone() => Handshake_Authenticate()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Handshake_Authenticate copyWith(void Function(Handshake_Authenticate) updates) => super.copyWith((message) => updates(message as Handshake_Authenticate)) as Handshake_Authenticate; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + Handshake_Authenticate clone() => + Handshake_Authenticate()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Handshake_Authenticate copyWith( + void Function(Handshake_Authenticate) updates) => + super.copyWith((message) => updates(message as Handshake_Authenticate)) + as Handshake_Authenticate; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Handshake_Authenticate create() => Handshake_Authenticate._(); Handshake_Authenticate createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static Handshake_Authenticate getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Handshake_Authenticate getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Handshake_Authenticate? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -502,7 +611,10 @@ class Handshake_Authenticate extends $pb.GeneratedMessage { @$pb.TagNumber(2) $core.List<$core.int> get authToken => $_getN(1); @$pb.TagNumber(2) - set authToken($core.List<$core.int> v) { $_setBytes(1, v); } + set authToken($core.List<$core.int> v) { + $_setBytes(1, v); + } + @$pb.TagNumber(2) $core.bool hasAuthToken() => $_has(1); @$pb.TagNumber(2) @@ -511,7 +623,10 @@ class Handshake_Authenticate extends $pb.GeneratedMessage { @$pb.TagNumber(3) $core.String get appVersion => $_getSZ(2); @$pb.TagNumber(3) - set appVersion($core.String v) { $_setString(2, v); } + set appVersion($core.String v) { + $_setString(2, v); + } + @$pb.TagNumber(3) $core.bool hasAppVersion() => $_has(2); @$pb.TagNumber(3) @@ -519,10 +634,10 @@ class Handshake_Authenticate extends $pb.GeneratedMessage { } enum Handshake_Handshake { - register, - getauthchallenge, - getauthtoken, - authenticate, + register, + getauthchallenge, + getauthtoken, + authenticate, notSet } @@ -549,35 +664,47 @@ class Handshake extends $pb.GeneratedMessage { return $result; } Handshake._() : super(); - factory Handshake.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Handshake.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Handshake.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Handshake.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static const $core.Map<$core.int, Handshake_Handshake> _Handshake_HandshakeByTag = { - 1 : Handshake_Handshake.register, - 2 : Handshake_Handshake.getauthchallenge, - 3 : Handshake_Handshake.getauthtoken, - 4 : Handshake_Handshake.authenticate, - 0 : Handshake_Handshake.notSet + static const $core.Map<$core.int, Handshake_Handshake> + _Handshake_HandshakeByTag = { + 1: Handshake_Handshake.register, + 2: Handshake_Handshake.getauthchallenge, + 3: Handshake_Handshake.getauthtoken, + 4: Handshake_Handshake.authenticate, + 0: Handshake_Handshake.notSet }; - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Handshake', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Handshake', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..oo(0, [1, 2, 3, 4]) - ..aOM(1, _omitFieldNames ? '' : 'register', subBuilder: Handshake_Register.create) - ..aOM(2, _omitFieldNames ? '' : 'getauthchallenge', subBuilder: Handshake_GetAuthChallenge.create) - ..aOM(3, _omitFieldNames ? '' : 'getauthtoken', subBuilder: Handshake_GetAuthToken.create) - ..aOM(4, _omitFieldNames ? '' : 'authenticate', subBuilder: Handshake_Authenticate.create) - ..hasRequiredFields = false - ; + ..aOM(1, _omitFieldNames ? '' : 'register', + subBuilder: Handshake_Register.create) + ..aOM( + 2, _omitFieldNames ? '' : 'getauthchallenge', + subBuilder: Handshake_GetAuthChallenge.create) + ..aOM(3, _omitFieldNames ? '' : 'getauthtoken', + subBuilder: Handshake_GetAuthToken.create) + ..aOM(4, _omitFieldNames ? '' : 'authenticate', + subBuilder: Handshake_Authenticate.create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') Handshake clone() => Handshake()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Handshake copyWith(void Function(Handshake) updates) => super.copyWith((message) => updates(message as Handshake)) as Handshake; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Handshake copyWith(void Function(Handshake) updates) => + super.copyWith((message) => updates(message as Handshake)) as Handshake; $pb.BuilderInfo get info_ => _i; @@ -586,16 +713,21 @@ class Handshake extends $pb.GeneratedMessage { Handshake createEmptyInstance() => create(); static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static Handshake getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Handshake getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Handshake? _defaultInstance; - Handshake_Handshake whichHandshake() => _Handshake_HandshakeByTag[$_whichOneof(0)]!; + Handshake_Handshake whichHandshake() => + _Handshake_HandshakeByTag[$_whichOneof(0)]!; void clearHandshake() => clearField($_whichOneof(0)); @$pb.TagNumber(1) Handshake_Register get register => $_getN(0); @$pb.TagNumber(1) - set register(Handshake_Register v) { setField(1, v); } + set register(Handshake_Register v) { + setField(1, v); + } + @$pb.TagNumber(1) $core.bool hasRegister() => $_has(0); @$pb.TagNumber(1) @@ -606,7 +738,10 @@ class Handshake extends $pb.GeneratedMessage { @$pb.TagNumber(2) Handshake_GetAuthChallenge get getauthchallenge => $_getN(1); @$pb.TagNumber(2) - set getauthchallenge(Handshake_GetAuthChallenge v) { setField(2, v); } + set getauthchallenge(Handshake_GetAuthChallenge v) { + setField(2, v); + } + @$pb.TagNumber(2) $core.bool hasGetauthchallenge() => $_has(1); @$pb.TagNumber(2) @@ -617,7 +752,10 @@ class Handshake extends $pb.GeneratedMessage { @$pb.TagNumber(3) Handshake_GetAuthToken get getauthtoken => $_getN(2); @$pb.TagNumber(3) - set getauthtoken(Handshake_GetAuthToken v) { setField(3, v); } + set getauthtoken(Handshake_GetAuthToken v) { + setField(3, v); + } + @$pb.TagNumber(3) $core.bool hasGetauthtoken() => $_has(2); @$pb.TagNumber(3) @@ -628,7 +766,10 @@ class Handshake extends $pb.GeneratedMessage { @$pb.TagNumber(4) Handshake_Authenticate get authenticate => $_getN(3); @$pb.TagNumber(4) - set authenticate(Handshake_Authenticate v) { setField(4, v); } + set authenticate(Handshake_Authenticate v) { + setField(4, v); + } + @$pb.TagNumber(4) $core.bool hasAuthenticate() => $_has(3); @$pb.TagNumber(4) @@ -656,41 +797,59 @@ class ApplicationData_TextMessage extends $pb.GeneratedMessage { return $result; } ApplicationData_TextMessage._() : super(); - factory ApplicationData_TextMessage.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_TextMessage.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_TextMessage.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_TextMessage.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.TextMessage', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.TextMessage', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..a<$core.List<$core.int>>(3, _omitFieldNames ? '' : 'body', $pb.PbFieldType.OY) - ..a<$core.List<$core.int>>(4, _omitFieldNames ? '' : 'pushData', $pb.PbFieldType.OY) - ..hasRequiredFields = false - ; + ..a<$core.List<$core.int>>( + 3, _omitFieldNames ? '' : 'body', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>( + 4, _omitFieldNames ? '' : 'pushData', $pb.PbFieldType.OY) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_TextMessage clone() => ApplicationData_TextMessage()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_TextMessage copyWith(void Function(ApplicationData_TextMessage) updates) => super.copyWith((message) => updates(message as ApplicationData_TextMessage)) as ApplicationData_TextMessage; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_TextMessage clone() => + ApplicationData_TextMessage()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_TextMessage copyWith( + void Function(ApplicationData_TextMessage) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_TextMessage)) + as ApplicationData_TextMessage; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_TextMessage create() => ApplicationData_TextMessage._(); + static ApplicationData_TextMessage create() => + ApplicationData_TextMessage._(); ApplicationData_TextMessage createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_TextMessage getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_TextMessage getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_TextMessage? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -699,7 +858,10 @@ class ApplicationData_TextMessage extends $pb.GeneratedMessage { @$pb.TagNumber(3) $core.List<$core.int> get body => $_getN(1); @$pb.TagNumber(3) - set body($core.List<$core.int> v) { $_setBytes(1, v); } + set body($core.List<$core.int> v) { + $_setBytes(1, v); + } + @$pb.TagNumber(3) $core.bool hasBody() => $_has(1); @$pb.TagNumber(3) @@ -708,7 +870,10 @@ class ApplicationData_TextMessage extends $pb.GeneratedMessage { @$pb.TagNumber(4) $core.List<$core.int> get pushData => $_getN(2); @$pb.TagNumber(4) - set pushData($core.List<$core.int> v) { $_setBytes(2, v); } + set pushData($core.List<$core.int> v) { + $_setBytes(2, v); + } + @$pb.TagNumber(4) $core.bool hasPushData() => $_has(2); @$pb.TagNumber(4) @@ -726,39 +891,56 @@ class ApplicationData_GetUserByUsername extends $pb.GeneratedMessage { return $result; } ApplicationData_GetUserByUsername._() : super(); - factory ApplicationData_GetUserByUsername.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetUserByUsername.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetUserByUsername.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetUserByUsername.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetUserByUsername', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetUserByUsername', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'username') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetUserByUsername clone() => ApplicationData_GetUserByUsername()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetUserByUsername copyWith(void Function(ApplicationData_GetUserByUsername) updates) => super.copyWith((message) => updates(message as ApplicationData_GetUserByUsername)) as ApplicationData_GetUserByUsername; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetUserByUsername clone() => + ApplicationData_GetUserByUsername()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetUserByUsername copyWith( + void Function(ApplicationData_GetUserByUsername) updates) => + super.copyWith((message) => + updates(message as ApplicationData_GetUserByUsername)) + as ApplicationData_GetUserByUsername; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetUserByUsername create() => ApplicationData_GetUserByUsername._(); + static ApplicationData_GetUserByUsername create() => + ApplicationData_GetUserByUsername._(); ApplicationData_GetUserByUsername createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetUserByUsername getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetUserByUsername getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor( + create); static ApplicationData_GetUserByUsername? _defaultInstance; @$pb.TagNumber(1) $core.String get username => $_getSZ(0); @$pb.TagNumber(1) - set username($core.String v) { $_setString(0, v); } + set username($core.String v) { + $_setString(0, v); + } + @$pb.TagNumber(1) $core.bool hasUsername() => $_has(0); @$pb.TagNumber(1) @@ -776,39 +958,57 @@ class ApplicationData_UpdateGoogleFcmToken extends $pb.GeneratedMessage { return $result; } ApplicationData_UpdateGoogleFcmToken._() : super(); - factory ApplicationData_UpdateGoogleFcmToken.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_UpdateGoogleFcmToken.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_UpdateGoogleFcmToken.fromBuffer( + $core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_UpdateGoogleFcmToken.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.UpdateGoogleFcmToken', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.UpdateGoogleFcmToken', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'googleFcm') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_UpdateGoogleFcmToken clone() => ApplicationData_UpdateGoogleFcmToken()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_UpdateGoogleFcmToken copyWith(void Function(ApplicationData_UpdateGoogleFcmToken) updates) => super.copyWith((message) => updates(message as ApplicationData_UpdateGoogleFcmToken)) as ApplicationData_UpdateGoogleFcmToken; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_UpdateGoogleFcmToken clone() => + ApplicationData_UpdateGoogleFcmToken()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_UpdateGoogleFcmToken copyWith( + void Function(ApplicationData_UpdateGoogleFcmToken) updates) => + super.copyWith((message) => + updates(message as ApplicationData_UpdateGoogleFcmToken)) + as ApplicationData_UpdateGoogleFcmToken; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_UpdateGoogleFcmToken create() => ApplicationData_UpdateGoogleFcmToken._(); + static ApplicationData_UpdateGoogleFcmToken create() => + ApplicationData_UpdateGoogleFcmToken._(); ApplicationData_UpdateGoogleFcmToken createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_UpdateGoogleFcmToken getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_UpdateGoogleFcmToken getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< + ApplicationData_UpdateGoogleFcmToken>(create); static ApplicationData_UpdateGoogleFcmToken? _defaultInstance; @$pb.TagNumber(1) $core.String get googleFcm => $_getSZ(0); @$pb.TagNumber(1) - set googleFcm($core.String v) { $_setString(0, v); } + set googleFcm($core.String v) { + $_setString(0, v); + } + @$pb.TagNumber(1) $core.bool hasGoogleFcm() => $_has(0); @$pb.TagNumber(1) @@ -826,39 +1026,55 @@ class ApplicationData_GetUserById extends $pb.GeneratedMessage { return $result; } ApplicationData_GetUserById._() : super(); - factory ApplicationData_GetUserById.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetUserById.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetUserById.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetUserById.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetUserById', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetUserById', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetUserById clone() => ApplicationData_GetUserById()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetUserById copyWith(void Function(ApplicationData_GetUserById) updates) => super.copyWith((message) => updates(message as ApplicationData_GetUserById)) as ApplicationData_GetUserById; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetUserById clone() => + ApplicationData_GetUserById()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetUserById copyWith( + void Function(ApplicationData_GetUserById) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_GetUserById)) + as ApplicationData_GetUserById; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetUserById create() => ApplicationData_GetUserById._(); + static ApplicationData_GetUserById create() => + ApplicationData_GetUserById._(); ApplicationData_GetUserById createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetUserById getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetUserById getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_GetUserById? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -876,39 +1092,55 @@ class ApplicationData_RedeemVoucher extends $pb.GeneratedMessage { return $result; } ApplicationData_RedeemVoucher._() : super(); - factory ApplicationData_RedeemVoucher.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_RedeemVoucher.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_RedeemVoucher.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_RedeemVoucher.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.RedeemVoucher', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.RedeemVoucher', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'voucher') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_RedeemVoucher clone() => ApplicationData_RedeemVoucher()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_RedeemVoucher copyWith(void Function(ApplicationData_RedeemVoucher) updates) => super.copyWith((message) => updates(message as ApplicationData_RedeemVoucher)) as ApplicationData_RedeemVoucher; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_RedeemVoucher clone() => + ApplicationData_RedeemVoucher()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_RedeemVoucher copyWith( + void Function(ApplicationData_RedeemVoucher) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_RedeemVoucher)) + as ApplicationData_RedeemVoucher; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_RedeemVoucher create() => ApplicationData_RedeemVoucher._(); + static ApplicationData_RedeemVoucher create() => + ApplicationData_RedeemVoucher._(); ApplicationData_RedeemVoucher createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_RedeemVoucher getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_RedeemVoucher getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_RedeemVoucher? _defaultInstance; @$pb.TagNumber(1) $core.String get voucher => $_getSZ(0); @$pb.TagNumber(1) - set voucher($core.String v) { $_setString(0, v); } + set voucher($core.String v) { + $_setString(0, v); + } + @$pb.TagNumber(1) $core.bool hasVoucher() => $_has(0); @$pb.TagNumber(1) @@ -934,41 +1166,58 @@ class ApplicationData_SwitchToPayedPlan extends $pb.GeneratedMessage { return $result; } ApplicationData_SwitchToPayedPlan._() : super(); - factory ApplicationData_SwitchToPayedPlan.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_SwitchToPayedPlan.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_SwitchToPayedPlan.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_SwitchToPayedPlan.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.SwitchToPayedPlan', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.SwitchToPayedPlan', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'planId') ..aOB(2, _omitFieldNames ? '' : 'payMonthly') ..aOB(3, _omitFieldNames ? '' : 'autoRenewal') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_SwitchToPayedPlan clone() => ApplicationData_SwitchToPayedPlan()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_SwitchToPayedPlan copyWith(void Function(ApplicationData_SwitchToPayedPlan) updates) => super.copyWith((message) => updates(message as ApplicationData_SwitchToPayedPlan)) as ApplicationData_SwitchToPayedPlan; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_SwitchToPayedPlan clone() => + ApplicationData_SwitchToPayedPlan()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_SwitchToPayedPlan copyWith( + void Function(ApplicationData_SwitchToPayedPlan) updates) => + super.copyWith((message) => + updates(message as ApplicationData_SwitchToPayedPlan)) + as ApplicationData_SwitchToPayedPlan; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_SwitchToPayedPlan create() => ApplicationData_SwitchToPayedPlan._(); + static ApplicationData_SwitchToPayedPlan create() => + ApplicationData_SwitchToPayedPlan._(); ApplicationData_SwitchToPayedPlan createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_SwitchToPayedPlan getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_SwitchToPayedPlan getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor( + create); static ApplicationData_SwitchToPayedPlan? _defaultInstance; @$pb.TagNumber(1) $core.String get planId => $_getSZ(0); @$pb.TagNumber(1) - set planId($core.String v) { $_setString(0, v); } + set planId($core.String v) { + $_setString(0, v); + } + @$pb.TagNumber(1) $core.bool hasPlanId() => $_has(0); @$pb.TagNumber(1) @@ -977,7 +1226,10 @@ class ApplicationData_SwitchToPayedPlan extends $pb.GeneratedMessage { @$pb.TagNumber(2) $core.bool get payMonthly => $_getBF(1); @$pb.TagNumber(2) - set payMonthly($core.bool v) { $_setBool(1, v); } + set payMonthly($core.bool v) { + $_setBool(1, v); + } + @$pb.TagNumber(2) $core.bool hasPayMonthly() => $_has(1); @$pb.TagNumber(2) @@ -986,7 +1238,10 @@ class ApplicationData_SwitchToPayedPlan extends $pb.GeneratedMessage { @$pb.TagNumber(3) $core.bool get autoRenewal => $_getBF(2); @$pb.TagNumber(3) - set autoRenewal($core.bool v) { $_setBool(2, v); } + set autoRenewal($core.bool v) { + $_setBool(2, v); + } + @$pb.TagNumber(3) $core.bool hasAutoRenewal() => $_has(2); @$pb.TagNumber(3) @@ -1004,39 +1259,56 @@ class ApplicationData_UpdatePlanOptions extends $pb.GeneratedMessage { return $result; } ApplicationData_UpdatePlanOptions._() : super(); - factory ApplicationData_UpdatePlanOptions.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_UpdatePlanOptions.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_UpdatePlanOptions.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_UpdatePlanOptions.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.UpdatePlanOptions', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.UpdatePlanOptions', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOB(1, _omitFieldNames ? '' : 'autoRenewal') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_UpdatePlanOptions clone() => ApplicationData_UpdatePlanOptions()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_UpdatePlanOptions copyWith(void Function(ApplicationData_UpdatePlanOptions) updates) => super.copyWith((message) => updates(message as ApplicationData_UpdatePlanOptions)) as ApplicationData_UpdatePlanOptions; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_UpdatePlanOptions clone() => + ApplicationData_UpdatePlanOptions()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_UpdatePlanOptions copyWith( + void Function(ApplicationData_UpdatePlanOptions) updates) => + super.copyWith((message) => + updates(message as ApplicationData_UpdatePlanOptions)) + as ApplicationData_UpdatePlanOptions; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_UpdatePlanOptions create() => ApplicationData_UpdatePlanOptions._(); + static ApplicationData_UpdatePlanOptions create() => + ApplicationData_UpdatePlanOptions._(); ApplicationData_UpdatePlanOptions createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_UpdatePlanOptions getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_UpdatePlanOptions getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor( + create); static ApplicationData_UpdatePlanOptions? _defaultInstance; @$pb.TagNumber(1) $core.bool get autoRenewal => $_getBF(0); @$pb.TagNumber(1) - set autoRenewal($core.bool v) { $_setBool(0, v); } + set autoRenewal($core.bool v) { + $_setBool(0, v); + } + @$pb.TagNumber(1) $core.bool hasAutoRenewal() => $_has(0); @$pb.TagNumber(1) @@ -1054,39 +1326,55 @@ class ApplicationData_CreateVoucher extends $pb.GeneratedMessage { return $result; } ApplicationData_CreateVoucher._() : super(); - factory ApplicationData_CreateVoucher.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_CreateVoucher.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_CreateVoucher.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_CreateVoucher.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.CreateVoucher', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.CreateVoucher', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..a<$core.int>(1, _omitFieldNames ? '' : 'valueCents', $pb.PbFieldType.OU3) - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_CreateVoucher clone() => ApplicationData_CreateVoucher()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_CreateVoucher copyWith(void Function(ApplicationData_CreateVoucher) updates) => super.copyWith((message) => updates(message as ApplicationData_CreateVoucher)) as ApplicationData_CreateVoucher; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_CreateVoucher clone() => + ApplicationData_CreateVoucher()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_CreateVoucher copyWith( + void Function(ApplicationData_CreateVoucher) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_CreateVoucher)) + as ApplicationData_CreateVoucher; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_CreateVoucher create() => ApplicationData_CreateVoucher._(); + static ApplicationData_CreateVoucher create() => + ApplicationData_CreateVoucher._(); ApplicationData_CreateVoucher createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_CreateVoucher getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_CreateVoucher getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_CreateVoucher? _defaultInstance; @$pb.TagNumber(1) $core.int get valueCents => $_getIZ(0); @$pb.TagNumber(1) - set valueCents($core.int v) { $_setUnsignedInt32(0, v); } + set valueCents($core.int v) { + $_setUnsignedInt32(0, v); + } + @$pb.TagNumber(1) $core.bool hasValueCents() => $_has(0); @$pb.TagNumber(1) @@ -1096,160 +1384,230 @@ class ApplicationData_CreateVoucher extends $pb.GeneratedMessage { class ApplicationData_GetLocation extends $pb.GeneratedMessage { factory ApplicationData_GetLocation() => create(); ApplicationData_GetLocation._() : super(); - factory ApplicationData_GetLocation.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetLocation.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetLocation.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetLocation.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetLocation', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetLocation', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetLocation clone() => ApplicationData_GetLocation()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetLocation copyWith(void Function(ApplicationData_GetLocation) updates) => super.copyWith((message) => updates(message as ApplicationData_GetLocation)) as ApplicationData_GetLocation; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetLocation clone() => + ApplicationData_GetLocation()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetLocation copyWith( + void Function(ApplicationData_GetLocation) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_GetLocation)) + as ApplicationData_GetLocation; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetLocation create() => ApplicationData_GetLocation._(); + static ApplicationData_GetLocation create() => + ApplicationData_GetLocation._(); ApplicationData_GetLocation createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetLocation getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetLocation getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_GetLocation? _defaultInstance; } class ApplicationData_GetVouchers extends $pb.GeneratedMessage { factory ApplicationData_GetVouchers() => create(); ApplicationData_GetVouchers._() : super(); - factory ApplicationData_GetVouchers.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetVouchers.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetVouchers.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetVouchers.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetVouchers', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetVouchers', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetVouchers clone() => ApplicationData_GetVouchers()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetVouchers copyWith(void Function(ApplicationData_GetVouchers) updates) => super.copyWith((message) => updates(message as ApplicationData_GetVouchers)) as ApplicationData_GetVouchers; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetVouchers clone() => + ApplicationData_GetVouchers()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetVouchers copyWith( + void Function(ApplicationData_GetVouchers) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_GetVouchers)) + as ApplicationData_GetVouchers; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetVouchers create() => ApplicationData_GetVouchers._(); + static ApplicationData_GetVouchers create() => + ApplicationData_GetVouchers._(); ApplicationData_GetVouchers createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetVouchers getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetVouchers getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_GetVouchers? _defaultInstance; } class ApplicationData_GetAvailablePlans extends $pb.GeneratedMessage { factory ApplicationData_GetAvailablePlans() => create(); ApplicationData_GetAvailablePlans._() : super(); - factory ApplicationData_GetAvailablePlans.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetAvailablePlans.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetAvailablePlans.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetAvailablePlans.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetAvailablePlans', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetAvailablePlans', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetAvailablePlans clone() => ApplicationData_GetAvailablePlans()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetAvailablePlans copyWith(void Function(ApplicationData_GetAvailablePlans) updates) => super.copyWith((message) => updates(message as ApplicationData_GetAvailablePlans)) as ApplicationData_GetAvailablePlans; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetAvailablePlans clone() => + ApplicationData_GetAvailablePlans()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetAvailablePlans copyWith( + void Function(ApplicationData_GetAvailablePlans) updates) => + super.copyWith((message) => + updates(message as ApplicationData_GetAvailablePlans)) + as ApplicationData_GetAvailablePlans; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetAvailablePlans create() => ApplicationData_GetAvailablePlans._(); + static ApplicationData_GetAvailablePlans create() => + ApplicationData_GetAvailablePlans._(); ApplicationData_GetAvailablePlans createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetAvailablePlans getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetAvailablePlans getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor( + create); static ApplicationData_GetAvailablePlans? _defaultInstance; } class ApplicationData_GetAddAccountsInvites extends $pb.GeneratedMessage { factory ApplicationData_GetAddAccountsInvites() => create(); ApplicationData_GetAddAccountsInvites._() : super(); - factory ApplicationData_GetAddAccountsInvites.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetAddAccountsInvites.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetAddAccountsInvites.fromBuffer( + $core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetAddAccountsInvites.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetAddAccountsInvites', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetAddAccountsInvites', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetAddAccountsInvites clone() => ApplicationData_GetAddAccountsInvites()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetAddAccountsInvites copyWith(void Function(ApplicationData_GetAddAccountsInvites) updates) => super.copyWith((message) => updates(message as ApplicationData_GetAddAccountsInvites)) as ApplicationData_GetAddAccountsInvites; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetAddAccountsInvites clone() => + ApplicationData_GetAddAccountsInvites()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetAddAccountsInvites copyWith( + void Function(ApplicationData_GetAddAccountsInvites) updates) => + super.copyWith((message) => + updates(message as ApplicationData_GetAddAccountsInvites)) + as ApplicationData_GetAddAccountsInvites; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetAddAccountsInvites create() => ApplicationData_GetAddAccountsInvites._(); + static ApplicationData_GetAddAccountsInvites create() => + ApplicationData_GetAddAccountsInvites._(); ApplicationData_GetAddAccountsInvites createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetAddAccountsInvites getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetAddAccountsInvites getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< + ApplicationData_GetAddAccountsInvites>(create); static ApplicationData_GetAddAccountsInvites? _defaultInstance; } class ApplicationData_GetCurrentPlanInfos extends $pb.GeneratedMessage { factory ApplicationData_GetCurrentPlanInfos() => create(); ApplicationData_GetCurrentPlanInfos._() : super(); - factory ApplicationData_GetCurrentPlanInfos.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetCurrentPlanInfos.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetCurrentPlanInfos.fromBuffer( + $core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetCurrentPlanInfos.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetCurrentPlanInfos', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetCurrentPlanInfos', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetCurrentPlanInfos clone() => ApplicationData_GetCurrentPlanInfos()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetCurrentPlanInfos copyWith(void Function(ApplicationData_GetCurrentPlanInfos) updates) => super.copyWith((message) => updates(message as ApplicationData_GetCurrentPlanInfos)) as ApplicationData_GetCurrentPlanInfos; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetCurrentPlanInfos clone() => + ApplicationData_GetCurrentPlanInfos()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetCurrentPlanInfos copyWith( + void Function(ApplicationData_GetCurrentPlanInfos) updates) => + super.copyWith((message) => + updates(message as ApplicationData_GetCurrentPlanInfos)) + as ApplicationData_GetCurrentPlanInfos; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetCurrentPlanInfos create() => ApplicationData_GetCurrentPlanInfos._(); + static ApplicationData_GetCurrentPlanInfos create() => + ApplicationData_GetCurrentPlanInfos._(); ApplicationData_GetCurrentPlanInfos createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetCurrentPlanInfos getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetCurrentPlanInfos getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< + ApplicationData_GetCurrentPlanInfos>(create); static ApplicationData_GetCurrentPlanInfos? _defaultInstance; } @@ -1264,39 +1622,57 @@ class ApplicationData_RedeemAdditionalCode extends $pb.GeneratedMessage { return $result; } ApplicationData_RedeemAdditionalCode._() : super(); - factory ApplicationData_RedeemAdditionalCode.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_RedeemAdditionalCode.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_RedeemAdditionalCode.fromBuffer( + $core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_RedeemAdditionalCode.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.RedeemAdditionalCode', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.RedeemAdditionalCode', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aOS(2, _omitFieldNames ? '' : 'inviteCode') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_RedeemAdditionalCode clone() => ApplicationData_RedeemAdditionalCode()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_RedeemAdditionalCode copyWith(void Function(ApplicationData_RedeemAdditionalCode) updates) => super.copyWith((message) => updates(message as ApplicationData_RedeemAdditionalCode)) as ApplicationData_RedeemAdditionalCode; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_RedeemAdditionalCode clone() => + ApplicationData_RedeemAdditionalCode()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_RedeemAdditionalCode copyWith( + void Function(ApplicationData_RedeemAdditionalCode) updates) => + super.copyWith((message) => + updates(message as ApplicationData_RedeemAdditionalCode)) + as ApplicationData_RedeemAdditionalCode; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_RedeemAdditionalCode create() => ApplicationData_RedeemAdditionalCode._(); + static ApplicationData_RedeemAdditionalCode create() => + ApplicationData_RedeemAdditionalCode._(); ApplicationData_RedeemAdditionalCode createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_RedeemAdditionalCode getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_RedeemAdditionalCode getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< + ApplicationData_RedeemAdditionalCode>(create); static ApplicationData_RedeemAdditionalCode? _defaultInstance; @$pb.TagNumber(2) $core.String get inviteCode => $_getSZ(0); @$pb.TagNumber(2) - set inviteCode($core.String v) { $_setString(0, v); } + set inviteCode($core.String v) { + $_setString(0, v); + } + @$pb.TagNumber(2) $core.bool hasInviteCode() => $_has(0); @$pb.TagNumber(2) @@ -1314,39 +1690,57 @@ class ApplicationData_RemoveAdditionalUser extends $pb.GeneratedMessage { return $result; } ApplicationData_RemoveAdditionalUser._() : super(); - factory ApplicationData_RemoveAdditionalUser.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_RemoveAdditionalUser.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_RemoveAdditionalUser.fromBuffer( + $core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_RemoveAdditionalUser.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.RemoveAdditionalUser', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.RemoveAdditionalUser', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_RemoveAdditionalUser clone() => ApplicationData_RemoveAdditionalUser()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_RemoveAdditionalUser copyWith(void Function(ApplicationData_RemoveAdditionalUser) updates) => super.copyWith((message) => updates(message as ApplicationData_RemoveAdditionalUser)) as ApplicationData_RemoveAdditionalUser; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_RemoveAdditionalUser clone() => + ApplicationData_RemoveAdditionalUser()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_RemoveAdditionalUser copyWith( + void Function(ApplicationData_RemoveAdditionalUser) updates) => + super.copyWith((message) => + updates(message as ApplicationData_RemoveAdditionalUser)) + as ApplicationData_RemoveAdditionalUser; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_RemoveAdditionalUser create() => ApplicationData_RemoveAdditionalUser._(); + static ApplicationData_RemoveAdditionalUser create() => + ApplicationData_RemoveAdditionalUser._(); ApplicationData_RemoveAdditionalUser createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_RemoveAdditionalUser getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_RemoveAdditionalUser getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< + ApplicationData_RemoveAdditionalUser>(create); static ApplicationData_RemoveAdditionalUser? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -1364,39 +1758,56 @@ class ApplicationData_GetPrekeysByUserId extends $pb.GeneratedMessage { return $result; } ApplicationData_GetPrekeysByUserId._() : super(); - factory ApplicationData_GetPrekeysByUserId.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetPrekeysByUserId.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetPrekeysByUserId.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetPrekeysByUserId.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetPrekeysByUserId', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetPrekeysByUserId', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetPrekeysByUserId clone() => ApplicationData_GetPrekeysByUserId()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetPrekeysByUserId copyWith(void Function(ApplicationData_GetPrekeysByUserId) updates) => super.copyWith((message) => updates(message as ApplicationData_GetPrekeysByUserId)) as ApplicationData_GetPrekeysByUserId; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetPrekeysByUserId clone() => + ApplicationData_GetPrekeysByUserId()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetPrekeysByUserId copyWith( + void Function(ApplicationData_GetPrekeysByUserId) updates) => + super.copyWith((message) => + updates(message as ApplicationData_GetPrekeysByUserId)) + as ApplicationData_GetPrekeysByUserId; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetPrekeysByUserId create() => ApplicationData_GetPrekeysByUserId._(); + static ApplicationData_GetPrekeysByUserId create() => + ApplicationData_GetPrekeysByUserId._(); ApplicationData_GetPrekeysByUserId createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetPrekeysByUserId getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetPrekeysByUserId getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor( + create); static ApplicationData_GetPrekeysByUserId? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -1414,39 +1825,57 @@ class ApplicationData_GetSignedPreKeyByUserId extends $pb.GeneratedMessage { return $result; } ApplicationData_GetSignedPreKeyByUserId._() : super(); - factory ApplicationData_GetSignedPreKeyByUserId.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_GetSignedPreKeyByUserId.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_GetSignedPreKeyByUserId.fromBuffer( + $core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_GetSignedPreKeyByUserId.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.GetSignedPreKeyByUserId', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.GetSignedPreKeyByUserId', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'userId') - ..hasRequiredFields = false - ; + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_GetSignedPreKeyByUserId clone() => ApplicationData_GetSignedPreKeyByUserId()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_GetSignedPreKeyByUserId copyWith(void Function(ApplicationData_GetSignedPreKeyByUserId) updates) => super.copyWith((message) => updates(message as ApplicationData_GetSignedPreKeyByUserId)) as ApplicationData_GetSignedPreKeyByUserId; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_GetSignedPreKeyByUserId clone() => + ApplicationData_GetSignedPreKeyByUserId()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_GetSignedPreKeyByUserId copyWith( + void Function(ApplicationData_GetSignedPreKeyByUserId) updates) => + super.copyWith((message) => + updates(message as ApplicationData_GetSignedPreKeyByUserId)) + as ApplicationData_GetSignedPreKeyByUserId; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_GetSignedPreKeyByUserId create() => ApplicationData_GetSignedPreKeyByUserId._(); + static ApplicationData_GetSignedPreKeyByUserId create() => + ApplicationData_GetSignedPreKeyByUserId._(); ApplicationData_GetSignedPreKeyByUserId createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_GetSignedPreKeyByUserId getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_GetSignedPreKeyByUserId getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor< + ApplicationData_GetSignedPreKeyByUserId>(create); static ApplicationData_GetSignedPreKeyByUserId? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get userId => $_getI64(0); @$pb.TagNumber(1) - set userId($fixnum.Int64 v) { $_setInt64(0, v); } + set userId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasUserId() => $_has(0); @$pb.TagNumber(1) @@ -1472,41 +1901,60 @@ class ApplicationData_UpdateSignedPreKey extends $pb.GeneratedMessage { return $result; } ApplicationData_UpdateSignedPreKey._() : super(); - factory ApplicationData_UpdateSignedPreKey.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_UpdateSignedPreKey.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_UpdateSignedPreKey.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_UpdateSignedPreKey.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.UpdateSignedPreKey', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.UpdateSignedPreKey', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'signedPrekeyId') - ..a<$core.List<$core.int>>(2, _omitFieldNames ? '' : 'signedPrekey', $pb.PbFieldType.OY) - ..a<$core.List<$core.int>>(3, _omitFieldNames ? '' : 'signedPrekeySignature', $pb.PbFieldType.OY) - ..hasRequiredFields = false - ; + ..a<$core.List<$core.int>>( + 2, _omitFieldNames ? '' : 'signedPrekey', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>( + 3, _omitFieldNames ? '' : 'signedPrekeySignature', $pb.PbFieldType.OY) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_UpdateSignedPreKey clone() => ApplicationData_UpdateSignedPreKey()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_UpdateSignedPreKey copyWith(void Function(ApplicationData_UpdateSignedPreKey) updates) => super.copyWith((message) => updates(message as ApplicationData_UpdateSignedPreKey)) as ApplicationData_UpdateSignedPreKey; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_UpdateSignedPreKey clone() => + ApplicationData_UpdateSignedPreKey()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_UpdateSignedPreKey copyWith( + void Function(ApplicationData_UpdateSignedPreKey) updates) => + super.copyWith((message) => + updates(message as ApplicationData_UpdateSignedPreKey)) + as ApplicationData_UpdateSignedPreKey; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_UpdateSignedPreKey create() => ApplicationData_UpdateSignedPreKey._(); + static ApplicationData_UpdateSignedPreKey create() => + ApplicationData_UpdateSignedPreKey._(); ApplicationData_UpdateSignedPreKey createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_UpdateSignedPreKey getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_UpdateSignedPreKey getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor( + create); static ApplicationData_UpdateSignedPreKey? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get signedPrekeyId => $_getI64(0); @$pb.TagNumber(1) - set signedPrekeyId($fixnum.Int64 v) { $_setInt64(0, v); } + set signedPrekeyId($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasSignedPrekeyId() => $_has(0); @$pb.TagNumber(1) @@ -1515,7 +1963,10 @@ class ApplicationData_UpdateSignedPreKey extends $pb.GeneratedMessage { @$pb.TagNumber(2) $core.List<$core.int> get signedPrekey => $_getN(1); @$pb.TagNumber(2) - set signedPrekey($core.List<$core.int> v) { $_setBytes(1, v); } + set signedPrekey($core.List<$core.int> v) { + $_setBytes(1, v); + } + @$pb.TagNumber(2) $core.bool hasSignedPrekey() => $_has(1); @$pb.TagNumber(2) @@ -1524,7 +1975,10 @@ class ApplicationData_UpdateSignedPreKey extends $pb.GeneratedMessage { @$pb.TagNumber(3) $core.List<$core.int> get signedPrekeySignature => $_getN(2); @$pb.TagNumber(3) - set signedPrekeySignature($core.List<$core.int> v) { $_setBytes(2, v); } + set signedPrekeySignature($core.List<$core.int> v) { + $_setBytes(2, v); + } + @$pb.TagNumber(3) $core.bool hasSignedPrekeySignature() => $_has(2); @$pb.TagNumber(3) @@ -1542,39 +1996,56 @@ class ApplicationData_DownloadDone extends $pb.GeneratedMessage { return $result; } ApplicationData_DownloadDone._() : super(); - factory ApplicationData_DownloadDone.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_DownloadDone.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_DownloadDone.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_DownloadDone.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.DownloadDone', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..a<$core.List<$core.int>>(1, _omitFieldNames ? '' : 'downloadToken', $pb.PbFieldType.OY) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.DownloadDone', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..a<$core.List<$core.int>>( + 1, _omitFieldNames ? '' : 'downloadToken', $pb.PbFieldType.OY) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_DownloadDone clone() => ApplicationData_DownloadDone()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_DownloadDone copyWith(void Function(ApplicationData_DownloadDone) updates) => super.copyWith((message) => updates(message as ApplicationData_DownloadDone)) as ApplicationData_DownloadDone; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_DownloadDone clone() => + ApplicationData_DownloadDone()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_DownloadDone copyWith( + void Function(ApplicationData_DownloadDone) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_DownloadDone)) + as ApplicationData_DownloadDone; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_DownloadDone create() => ApplicationData_DownloadDone._(); + static ApplicationData_DownloadDone create() => + ApplicationData_DownloadDone._(); ApplicationData_DownloadDone createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_DownloadDone getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_DownloadDone getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_DownloadDone? _defaultInstance; @$pb.TagNumber(1) $core.List<$core.int> get downloadToken => $_getN(0); @$pb.TagNumber(1) - set downloadToken($core.List<$core.int> v) { $_setBytes(0, v); } + set downloadToken($core.List<$core.int> v) { + $_setBytes(0, v); + } + @$pb.TagNumber(1) $core.bool hasDownloadToken() => $_has(0); @$pb.TagNumber(1) @@ -1584,56 +2055,69 @@ class ApplicationData_DownloadDone extends $pb.GeneratedMessage { class ApplicationData_DeleteAccount extends $pb.GeneratedMessage { factory ApplicationData_DeleteAccount() => create(); ApplicationData_DeleteAccount._() : super(); - factory ApplicationData_DeleteAccount.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData_DeleteAccount.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData_DeleteAccount.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData_DeleteAccount.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData.DeleteAccount', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData.DeleteAccount', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') - ApplicationData_DeleteAccount clone() => ApplicationData_DeleteAccount()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData_DeleteAccount copyWith(void Function(ApplicationData_DeleteAccount) updates) => super.copyWith((message) => updates(message as ApplicationData_DeleteAccount)) as ApplicationData_DeleteAccount; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') + ApplicationData_DeleteAccount clone() => + ApplicationData_DeleteAccount()..mergeFromMessage(this); + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData_DeleteAccount copyWith( + void Function(ApplicationData_DeleteAccount) updates) => + super.copyWith( + (message) => updates(message as ApplicationData_DeleteAccount)) + as ApplicationData_DeleteAccount; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') - static ApplicationData_DeleteAccount create() => ApplicationData_DeleteAccount._(); + static ApplicationData_DeleteAccount create() => + ApplicationData_DeleteAccount._(); ApplicationData_DeleteAccount createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData_DeleteAccount getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData_DeleteAccount getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData_DeleteAccount? _defaultInstance; } enum ApplicationData_ApplicationData { - textmessage, - getuserbyusername, - getprekeysbyuserid, - getuserbyid, - updategooglefcmtoken, - getlocation, - getcurrentplaninfos, - redeemvoucher, - getavailableplans, - createvoucher, - getvouchers, - switchtopayedplan, - getaddaccountsinvites, - redeemadditionalcode, - removeadditionaluser, - updateplanoptions, - downloaddone, - getsignedprekeybyuserid, - updatesignedprekey, - deleteaccount, + textmessage, + getuserbyusername, + getprekeysbyuserid, + getuserbyid, + updategooglefcmtoken, + getlocation, + getcurrentplaninfos, + redeemvoucher, + getavailableplans, + createvoucher, + getvouchers, + switchtopayedplan, + getaddaccountsinvites, + redeemadditionalcode, + removeadditionaluser, + updateplanoptions, + downloaddone, + getsignedprekeybyuserid, + updatesignedprekey, + deleteaccount, notSet } @@ -1724,85 +2208,157 @@ class ApplicationData extends $pb.GeneratedMessage { return $result; } ApplicationData._() : super(); - factory ApplicationData.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory ApplicationData.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory ApplicationData.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory ApplicationData.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static const $core.Map<$core.int, ApplicationData_ApplicationData> _ApplicationData_ApplicationDataByTag = { - 1 : ApplicationData_ApplicationData.textmessage, - 2 : ApplicationData_ApplicationData.getuserbyusername, - 3 : ApplicationData_ApplicationData.getprekeysbyuserid, - 6 : ApplicationData_ApplicationData.getuserbyid, - 8 : ApplicationData_ApplicationData.updategooglefcmtoken, - 9 : ApplicationData_ApplicationData.getlocation, - 10 : ApplicationData_ApplicationData.getcurrentplaninfos, - 11 : ApplicationData_ApplicationData.redeemvoucher, - 12 : ApplicationData_ApplicationData.getavailableplans, - 13 : ApplicationData_ApplicationData.createvoucher, - 14 : ApplicationData_ApplicationData.getvouchers, - 15 : ApplicationData_ApplicationData.switchtopayedplan, - 16 : ApplicationData_ApplicationData.getaddaccountsinvites, - 17 : ApplicationData_ApplicationData.redeemadditionalcode, - 18 : ApplicationData_ApplicationData.removeadditionaluser, - 19 : ApplicationData_ApplicationData.updateplanoptions, - 20 : ApplicationData_ApplicationData.downloaddone, - 22 : ApplicationData_ApplicationData.getsignedprekeybyuserid, - 23 : ApplicationData_ApplicationData.updatesignedprekey, - 24 : ApplicationData_ApplicationData.deleteaccount, - 0 : ApplicationData_ApplicationData.notSet + static const $core.Map<$core.int, ApplicationData_ApplicationData> + _ApplicationData_ApplicationDataByTag = { + 1: ApplicationData_ApplicationData.textmessage, + 2: ApplicationData_ApplicationData.getuserbyusername, + 3: ApplicationData_ApplicationData.getprekeysbyuserid, + 6: ApplicationData_ApplicationData.getuserbyid, + 8: ApplicationData_ApplicationData.updategooglefcmtoken, + 9: ApplicationData_ApplicationData.getlocation, + 10: ApplicationData_ApplicationData.getcurrentplaninfos, + 11: ApplicationData_ApplicationData.redeemvoucher, + 12: ApplicationData_ApplicationData.getavailableplans, + 13: ApplicationData_ApplicationData.createvoucher, + 14: ApplicationData_ApplicationData.getvouchers, + 15: ApplicationData_ApplicationData.switchtopayedplan, + 16: ApplicationData_ApplicationData.getaddaccountsinvites, + 17: ApplicationData_ApplicationData.redeemadditionalcode, + 18: ApplicationData_ApplicationData.removeadditionaluser, + 19: ApplicationData_ApplicationData.updateplanoptions, + 20: ApplicationData_ApplicationData.downloaddone, + 22: ApplicationData_ApplicationData.getsignedprekeybyuserid, + 23: ApplicationData_ApplicationData.updatesignedprekey, + 24: ApplicationData_ApplicationData.deleteaccount, + 0: ApplicationData_ApplicationData.notSet }; - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'ApplicationData', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..oo(0, [1, 2, 3, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24]) - ..aOM(1, _omitFieldNames ? '' : 'textmessage', subBuilder: ApplicationData_TextMessage.create) - ..aOM(2, _omitFieldNames ? '' : 'getuserbyusername', subBuilder: ApplicationData_GetUserByUsername.create) - ..aOM(3, _omitFieldNames ? '' : 'getprekeysbyuserid', subBuilder: ApplicationData_GetPrekeysByUserId.create) - ..aOM(6, _omitFieldNames ? '' : 'getuserbyid', subBuilder: ApplicationData_GetUserById.create) - ..aOM(8, _omitFieldNames ? '' : 'updategooglefcmtoken', subBuilder: ApplicationData_UpdateGoogleFcmToken.create) - ..aOM(9, _omitFieldNames ? '' : 'getlocation', subBuilder: ApplicationData_GetLocation.create) - ..aOM(10, _omitFieldNames ? '' : 'getcurrentplaninfos', subBuilder: ApplicationData_GetCurrentPlanInfos.create) - ..aOM(11, _omitFieldNames ? '' : 'redeemvoucher', subBuilder: ApplicationData_RedeemVoucher.create) - ..aOM(12, _omitFieldNames ? '' : 'getavailableplans', subBuilder: ApplicationData_GetAvailablePlans.create) - ..aOM(13, _omitFieldNames ? '' : 'createvoucher', subBuilder: ApplicationData_CreateVoucher.create) - ..aOM(14, _omitFieldNames ? '' : 'getvouchers', subBuilder: ApplicationData_GetVouchers.create) - ..aOM(15, _omitFieldNames ? '' : 'Switchtopayedplan', protoName: 'Switchtopayedplan', subBuilder: ApplicationData_SwitchToPayedPlan.create) - ..aOM(16, _omitFieldNames ? '' : 'getaddaccountsinvites', subBuilder: ApplicationData_GetAddAccountsInvites.create) - ..aOM(17, _omitFieldNames ? '' : 'redeemadditionalcode', subBuilder: ApplicationData_RedeemAdditionalCode.create) - ..aOM(18, _omitFieldNames ? '' : 'removeadditionaluser', subBuilder: ApplicationData_RemoveAdditionalUser.create) - ..aOM(19, _omitFieldNames ? '' : 'updateplanoptions', subBuilder: ApplicationData_UpdatePlanOptions.create) - ..aOM(20, _omitFieldNames ? '' : 'downloaddone', subBuilder: ApplicationData_DownloadDone.create) - ..aOM(22, _omitFieldNames ? '' : 'getsignedprekeybyuserid', subBuilder: ApplicationData_GetSignedPreKeyByUserId.create) - ..aOM(23, _omitFieldNames ? '' : 'updatesignedprekey', subBuilder: ApplicationData_UpdateSignedPreKey.create) - ..aOM(24, _omitFieldNames ? '' : 'deleteaccount', subBuilder: ApplicationData_DeleteAccount.create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'ApplicationData', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..oo(0, [ + 1, + 2, + 3, + 6, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 22, + 23, + 24 + ]) + ..aOM(1, _omitFieldNames ? '' : 'textmessage', + subBuilder: ApplicationData_TextMessage.create) + ..aOM( + 2, _omitFieldNames ? '' : 'getuserbyusername', + subBuilder: ApplicationData_GetUserByUsername.create) + ..aOM( + 3, _omitFieldNames ? '' : 'getprekeysbyuserid', + subBuilder: ApplicationData_GetPrekeysByUserId.create) + ..aOM(6, _omitFieldNames ? '' : 'getuserbyid', + subBuilder: ApplicationData_GetUserById.create) + ..aOM( + 8, _omitFieldNames ? '' : 'updategooglefcmtoken', + subBuilder: ApplicationData_UpdateGoogleFcmToken.create) + ..aOM(9, _omitFieldNames ? '' : 'getlocation', + subBuilder: ApplicationData_GetLocation.create) + ..aOM( + 10, _omitFieldNames ? '' : 'getcurrentplaninfos', + subBuilder: ApplicationData_GetCurrentPlanInfos.create) + ..aOM( + 11, _omitFieldNames ? '' : 'redeemvoucher', + subBuilder: ApplicationData_RedeemVoucher.create) + ..aOM( + 12, _omitFieldNames ? '' : 'getavailableplans', + subBuilder: ApplicationData_GetAvailablePlans.create) + ..aOM( + 13, _omitFieldNames ? '' : 'createvoucher', + subBuilder: ApplicationData_CreateVoucher.create) + ..aOM(14, _omitFieldNames ? '' : 'getvouchers', + subBuilder: ApplicationData_GetVouchers.create) + ..aOM( + 15, _omitFieldNames ? '' : 'Switchtopayedplan', + protoName: 'Switchtopayedplan', + subBuilder: ApplicationData_SwitchToPayedPlan.create) + ..aOM( + 16, _omitFieldNames ? '' : 'getaddaccountsinvites', + subBuilder: ApplicationData_GetAddAccountsInvites.create) + ..aOM( + 17, _omitFieldNames ? '' : 'redeemadditionalcode', + subBuilder: ApplicationData_RedeemAdditionalCode.create) + ..aOM( + 18, _omitFieldNames ? '' : 'removeadditionaluser', + subBuilder: ApplicationData_RemoveAdditionalUser.create) + ..aOM( + 19, _omitFieldNames ? '' : 'updateplanoptions', + subBuilder: ApplicationData_UpdatePlanOptions.create) + ..aOM( + 20, _omitFieldNames ? '' : 'downloaddone', + subBuilder: ApplicationData_DownloadDone.create) + ..aOM( + 22, _omitFieldNames ? '' : 'getsignedprekeybyuserid', + subBuilder: ApplicationData_GetSignedPreKeyByUserId.create) + ..aOM( + 23, _omitFieldNames ? '' : 'updatesignedprekey', + subBuilder: ApplicationData_UpdateSignedPreKey.create) + ..aOM( + 24, _omitFieldNames ? '' : 'deleteaccount', + subBuilder: ApplicationData_DeleteAccount.create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') ApplicationData clone() => ApplicationData()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - ApplicationData copyWith(void Function(ApplicationData) updates) => super.copyWith((message) => updates(message as ApplicationData)) as ApplicationData; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + ApplicationData copyWith(void Function(ApplicationData) updates) => + super.copyWith((message) => updates(message as ApplicationData)) + as ApplicationData; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ApplicationData create() => ApplicationData._(); ApplicationData createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static ApplicationData getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static ApplicationData getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static ApplicationData? _defaultInstance; - ApplicationData_ApplicationData whichApplicationData() => _ApplicationData_ApplicationDataByTag[$_whichOneof(0)]!; + ApplicationData_ApplicationData whichApplicationData() => + _ApplicationData_ApplicationDataByTag[$_whichOneof(0)]!; void clearApplicationData() => clearField($_whichOneof(0)); @$pb.TagNumber(1) ApplicationData_TextMessage get textmessage => $_getN(0); @$pb.TagNumber(1) - set textmessage(ApplicationData_TextMessage v) { setField(1, v); } + set textmessage(ApplicationData_TextMessage v) { + setField(1, v); + } + @$pb.TagNumber(1) $core.bool hasTextmessage() => $_has(0); @$pb.TagNumber(1) @@ -1813,7 +2369,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(2) ApplicationData_GetUserByUsername get getuserbyusername => $_getN(1); @$pb.TagNumber(2) - set getuserbyusername(ApplicationData_GetUserByUsername v) { setField(2, v); } + set getuserbyusername(ApplicationData_GetUserByUsername v) { + setField(2, v); + } + @$pb.TagNumber(2) $core.bool hasGetuserbyusername() => $_has(1); @$pb.TagNumber(2) @@ -1824,7 +2383,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(3) ApplicationData_GetPrekeysByUserId get getprekeysbyuserid => $_getN(2); @$pb.TagNumber(3) - set getprekeysbyuserid(ApplicationData_GetPrekeysByUserId v) { setField(3, v); } + set getprekeysbyuserid(ApplicationData_GetPrekeysByUserId v) { + setField(3, v); + } + @$pb.TagNumber(3) $core.bool hasGetprekeysbyuserid() => $_has(2); @$pb.TagNumber(3) @@ -1835,7 +2397,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(6) ApplicationData_GetUserById get getuserbyid => $_getN(3); @$pb.TagNumber(6) - set getuserbyid(ApplicationData_GetUserById v) { setField(6, v); } + set getuserbyid(ApplicationData_GetUserById v) { + setField(6, v); + } + @$pb.TagNumber(6) $core.bool hasGetuserbyid() => $_has(3); @$pb.TagNumber(6) @@ -1846,18 +2411,25 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(8) ApplicationData_UpdateGoogleFcmToken get updategooglefcmtoken => $_getN(4); @$pb.TagNumber(8) - set updategooglefcmtoken(ApplicationData_UpdateGoogleFcmToken v) { setField(8, v); } + set updategooglefcmtoken(ApplicationData_UpdateGoogleFcmToken v) { + setField(8, v); + } + @$pb.TagNumber(8) $core.bool hasUpdategooglefcmtoken() => $_has(4); @$pb.TagNumber(8) void clearUpdategooglefcmtoken() => clearField(8); @$pb.TagNumber(8) - ApplicationData_UpdateGoogleFcmToken ensureUpdategooglefcmtoken() => $_ensure(4); + ApplicationData_UpdateGoogleFcmToken ensureUpdategooglefcmtoken() => + $_ensure(4); @$pb.TagNumber(9) ApplicationData_GetLocation get getlocation => $_getN(5); @$pb.TagNumber(9) - set getlocation(ApplicationData_GetLocation v) { setField(9, v); } + set getlocation(ApplicationData_GetLocation v) { + setField(9, v); + } + @$pb.TagNumber(9) $core.bool hasGetlocation() => $_has(5); @$pb.TagNumber(9) @@ -1868,18 +2440,25 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(10) ApplicationData_GetCurrentPlanInfos get getcurrentplaninfos => $_getN(6); @$pb.TagNumber(10) - set getcurrentplaninfos(ApplicationData_GetCurrentPlanInfos v) { setField(10, v); } + set getcurrentplaninfos(ApplicationData_GetCurrentPlanInfos v) { + setField(10, v); + } + @$pb.TagNumber(10) $core.bool hasGetcurrentplaninfos() => $_has(6); @$pb.TagNumber(10) void clearGetcurrentplaninfos() => clearField(10); @$pb.TagNumber(10) - ApplicationData_GetCurrentPlanInfos ensureGetcurrentplaninfos() => $_ensure(6); + ApplicationData_GetCurrentPlanInfos ensureGetcurrentplaninfos() => + $_ensure(6); @$pb.TagNumber(11) ApplicationData_RedeemVoucher get redeemvoucher => $_getN(7); @$pb.TagNumber(11) - set redeemvoucher(ApplicationData_RedeemVoucher v) { setField(11, v); } + set redeemvoucher(ApplicationData_RedeemVoucher v) { + setField(11, v); + } + @$pb.TagNumber(11) $core.bool hasRedeemvoucher() => $_has(7); @$pb.TagNumber(11) @@ -1890,7 +2469,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(12) ApplicationData_GetAvailablePlans get getavailableplans => $_getN(8); @$pb.TagNumber(12) - set getavailableplans(ApplicationData_GetAvailablePlans v) { setField(12, v); } + set getavailableplans(ApplicationData_GetAvailablePlans v) { + setField(12, v); + } + @$pb.TagNumber(12) $core.bool hasGetavailableplans() => $_has(8); @$pb.TagNumber(12) @@ -1901,7 +2483,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(13) ApplicationData_CreateVoucher get createvoucher => $_getN(9); @$pb.TagNumber(13) - set createvoucher(ApplicationData_CreateVoucher v) { setField(13, v); } + set createvoucher(ApplicationData_CreateVoucher v) { + setField(13, v); + } + @$pb.TagNumber(13) $core.bool hasCreatevoucher() => $_has(9); @$pb.TagNumber(13) @@ -1912,7 +2497,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(14) ApplicationData_GetVouchers get getvouchers => $_getN(10); @$pb.TagNumber(14) - set getvouchers(ApplicationData_GetVouchers v) { setField(14, v); } + set getvouchers(ApplicationData_GetVouchers v) { + setField(14, v); + } + @$pb.TagNumber(14) $core.bool hasGetvouchers() => $_has(10); @$pb.TagNumber(14) @@ -1923,7 +2511,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(15) ApplicationData_SwitchToPayedPlan get switchtopayedplan => $_getN(11); @$pb.TagNumber(15) - set switchtopayedplan(ApplicationData_SwitchToPayedPlan v) { setField(15, v); } + set switchtopayedplan(ApplicationData_SwitchToPayedPlan v) { + setField(15, v); + } + @$pb.TagNumber(15) $core.bool hasSwitchtopayedplan() => $_has(11); @$pb.TagNumber(15) @@ -1934,40 +2525,55 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(16) ApplicationData_GetAddAccountsInvites get getaddaccountsinvites => $_getN(12); @$pb.TagNumber(16) - set getaddaccountsinvites(ApplicationData_GetAddAccountsInvites v) { setField(16, v); } + set getaddaccountsinvites(ApplicationData_GetAddAccountsInvites v) { + setField(16, v); + } + @$pb.TagNumber(16) $core.bool hasGetaddaccountsinvites() => $_has(12); @$pb.TagNumber(16) void clearGetaddaccountsinvites() => clearField(16); @$pb.TagNumber(16) - ApplicationData_GetAddAccountsInvites ensureGetaddaccountsinvites() => $_ensure(12); + ApplicationData_GetAddAccountsInvites ensureGetaddaccountsinvites() => + $_ensure(12); @$pb.TagNumber(17) ApplicationData_RedeemAdditionalCode get redeemadditionalcode => $_getN(13); @$pb.TagNumber(17) - set redeemadditionalcode(ApplicationData_RedeemAdditionalCode v) { setField(17, v); } + set redeemadditionalcode(ApplicationData_RedeemAdditionalCode v) { + setField(17, v); + } + @$pb.TagNumber(17) $core.bool hasRedeemadditionalcode() => $_has(13); @$pb.TagNumber(17) void clearRedeemadditionalcode() => clearField(17); @$pb.TagNumber(17) - ApplicationData_RedeemAdditionalCode ensureRedeemadditionalcode() => $_ensure(13); + ApplicationData_RedeemAdditionalCode ensureRedeemadditionalcode() => + $_ensure(13); @$pb.TagNumber(18) ApplicationData_RemoveAdditionalUser get removeadditionaluser => $_getN(14); @$pb.TagNumber(18) - set removeadditionaluser(ApplicationData_RemoveAdditionalUser v) { setField(18, v); } + set removeadditionaluser(ApplicationData_RemoveAdditionalUser v) { + setField(18, v); + } + @$pb.TagNumber(18) $core.bool hasRemoveadditionaluser() => $_has(14); @$pb.TagNumber(18) void clearRemoveadditionaluser() => clearField(18); @$pb.TagNumber(18) - ApplicationData_RemoveAdditionalUser ensureRemoveadditionaluser() => $_ensure(14); + ApplicationData_RemoveAdditionalUser ensureRemoveadditionaluser() => + $_ensure(14); @$pb.TagNumber(19) ApplicationData_UpdatePlanOptions get updateplanoptions => $_getN(15); @$pb.TagNumber(19) - set updateplanoptions(ApplicationData_UpdatePlanOptions v) { setField(19, v); } + set updateplanoptions(ApplicationData_UpdatePlanOptions v) { + setField(19, v); + } + @$pb.TagNumber(19) $core.bool hasUpdateplanoptions() => $_has(15); @$pb.TagNumber(19) @@ -1978,7 +2584,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(20) ApplicationData_DownloadDone get downloaddone => $_getN(16); @$pb.TagNumber(20) - set downloaddone(ApplicationData_DownloadDone v) { setField(20, v); } + set downloaddone(ApplicationData_DownloadDone v) { + setField(20, v); + } + @$pb.TagNumber(20) $core.bool hasDownloaddone() => $_has(16); @$pb.TagNumber(20) @@ -1987,20 +2596,28 @@ class ApplicationData extends $pb.GeneratedMessage { ApplicationData_DownloadDone ensureDownloaddone() => $_ensure(16); @$pb.TagNumber(22) - ApplicationData_GetSignedPreKeyByUserId get getsignedprekeybyuserid => $_getN(17); + ApplicationData_GetSignedPreKeyByUserId get getsignedprekeybyuserid => + $_getN(17); @$pb.TagNumber(22) - set getsignedprekeybyuserid(ApplicationData_GetSignedPreKeyByUserId v) { setField(22, v); } + set getsignedprekeybyuserid(ApplicationData_GetSignedPreKeyByUserId v) { + setField(22, v); + } + @$pb.TagNumber(22) $core.bool hasGetsignedprekeybyuserid() => $_has(17); @$pb.TagNumber(22) void clearGetsignedprekeybyuserid() => clearField(22); @$pb.TagNumber(22) - ApplicationData_GetSignedPreKeyByUserId ensureGetsignedprekeybyuserid() => $_ensure(17); + ApplicationData_GetSignedPreKeyByUserId ensureGetsignedprekeybyuserid() => + $_ensure(17); @$pb.TagNumber(23) ApplicationData_UpdateSignedPreKey get updatesignedprekey => $_getN(18); @$pb.TagNumber(23) - set updatesignedprekey(ApplicationData_UpdateSignedPreKey v) { setField(23, v); } + set updatesignedprekey(ApplicationData_UpdateSignedPreKey v) { + setField(23, v); + } + @$pb.TagNumber(23) $core.bool hasUpdatesignedprekey() => $_has(18); @$pb.TagNumber(23) @@ -2011,7 +2628,10 @@ class ApplicationData extends $pb.GeneratedMessage { @$pb.TagNumber(24) ApplicationData_DeleteAccount get deleteaccount => $_getN(19); @$pb.TagNumber(24) - set deleteaccount(ApplicationData_DeleteAccount v) { setField(24, v); } + set deleteaccount(ApplicationData_DeleteAccount v) { + setField(24, v); + } + @$pb.TagNumber(24) $core.bool hasDeleteaccount() => $_has(19); @$pb.TagNumber(24) @@ -2035,40 +2655,53 @@ class Response_PreKey extends $pb.GeneratedMessage { return $result; } Response_PreKey._() : super(); - factory Response_PreKey.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Response_PreKey.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Response_PreKey.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Response_PreKey.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Response.PreKey', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Response.PreKey', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..aInt64(1, _omitFieldNames ? '' : 'id') - ..a<$core.List<$core.int>>(2, _omitFieldNames ? '' : 'prekey', $pb.PbFieldType.OY) - ..hasRequiredFields = false - ; + ..a<$core.List<$core.int>>( + 2, _omitFieldNames ? '' : 'prekey', $pb.PbFieldType.OY) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') Response_PreKey clone() => Response_PreKey()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Response_PreKey copyWith(void Function(Response_PreKey) updates) => super.copyWith((message) => updates(message as Response_PreKey)) as Response_PreKey; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Response_PreKey copyWith(void Function(Response_PreKey) updates) => + super.copyWith((message) => updates(message as Response_PreKey)) + as Response_PreKey; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Response_PreKey create() => Response_PreKey._(); Response_PreKey createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static Response_PreKey getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Response_PreKey getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Response_PreKey? _defaultInstance; @$pb.TagNumber(1) $fixnum.Int64 get id => $_getI64(0); @$pb.TagNumber(1) - set id($fixnum.Int64 v) { $_setInt64(0, v); } + set id($fixnum.Int64 v) { + $_setInt64(0, v); + } + @$pb.TagNumber(1) $core.bool hasId() => $_has(0); @$pb.TagNumber(1) @@ -2077,7 +2710,10 @@ class Response_PreKey extends $pb.GeneratedMessage { @$pb.TagNumber(2) $core.List<$core.int> get prekey => $_getN(1); @$pb.TagNumber(2) - set prekey($core.List<$core.int> v) { $_setBytes(1, v); } + set prekey($core.List<$core.int> v) { + $_setBytes(1, v); + } + @$pb.TagNumber(2) $core.bool hasPrekey() => $_has(1); @$pb.TagNumber(2) @@ -2095,44 +2731,51 @@ class Response_Prekeys extends $pb.GeneratedMessage { return $result; } Response_Prekeys._() : super(); - factory Response_Prekeys.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Response_Prekeys.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Response_Prekeys.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Response_Prekeys.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Response.Prekeys', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) - ..pc(1, _omitFieldNames ? '' : 'prekeys', $pb.PbFieldType.PM, subBuilder: Response_PreKey.create) - ..hasRequiredFields = false - ; + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Response.Prekeys', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) + ..pc( + 1, _omitFieldNames ? '' : 'prekeys', $pb.PbFieldType.PM, + subBuilder: Response_PreKey.create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') Response_Prekeys clone() => Response_Prekeys()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Response_Prekeys copyWith(void Function(Response_Prekeys) updates) => super.copyWith((message) => updates(message as Response_Prekeys)) as Response_Prekeys; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Response_Prekeys copyWith(void Function(Response_Prekeys) updates) => + super.copyWith((message) => updates(message as Response_Prekeys)) + as Response_Prekeys; $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Response_Prekeys create() => Response_Prekeys._(); Response_Prekeys createEmptyInstance() => create(); - static $pb.PbList createRepeated() => $pb.PbList(); + static $pb.PbList createRepeated() => + $pb.PbList(); @$core.pragma('dart2js:noInline') - static Response_Prekeys getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Response_Prekeys getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Response_Prekeys? _defaultInstance; @$pb.TagNumber(1) $core.List get prekeys => $_getList(0); } -enum Response_Ok_Ok { - none, - prekeys, - notSet -} +enum Response_Ok_Ok { none, prekeys, notSet } class Response_Ok extends $pb.GeneratedMessage { factory Response_Ok({ @@ -2149,31 +2792,39 @@ class Response_Ok extends $pb.GeneratedMessage { return $result; } Response_Ok._() : super(); - factory Response_Ok.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Response_Ok.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Response_Ok.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Response_Ok.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); static const $core.Map<$core.int, Response_Ok_Ok> _Response_Ok_OkByTag = { - 1 : Response_Ok_Ok.none, - 2 : Response_Ok_Ok.prekeys, - 0 : Response_Ok_Ok.notSet + 1: Response_Ok_Ok.none, + 2: Response_Ok_Ok.prekeys, + 0: Response_Ok_Ok.notSet }; - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Response.Ok', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Response.Ok', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..oo(0, [1, 2]) ..aOB(1, _omitFieldNames ? '' : 'None', protoName: 'None') - ..aOM(2, _omitFieldNames ? '' : 'prekeys', subBuilder: Response_Prekeys.create) - ..hasRequiredFields = false - ; + ..aOM(2, _omitFieldNames ? '' : 'prekeys', + subBuilder: Response_Prekeys.create) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') Response_Ok clone() => Response_Ok()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Response_Ok copyWith(void Function(Response_Ok) updates) => super.copyWith((message) => updates(message as Response_Ok)) as Response_Ok; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Response_Ok copyWith(void Function(Response_Ok) updates) => + super.copyWith((message) => updates(message as Response_Ok)) + as Response_Ok; $pb.BuilderInfo get info_ => _i; @@ -2182,7 +2833,8 @@ class Response_Ok extends $pb.GeneratedMessage { Response_Ok createEmptyInstance() => create(); static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static Response_Ok getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Response_Ok getDefault() => _defaultInstance ??= + $pb.GeneratedMessage.$_defaultFor(create); static Response_Ok? _defaultInstance; Response_Ok_Ok whichOk() => _Response_Ok_OkByTag[$_whichOneof(0)]!; @@ -2191,7 +2843,10 @@ class Response_Ok extends $pb.GeneratedMessage { @$pb.TagNumber(1) $core.bool get none => $_getBF(0); @$pb.TagNumber(1) - set none($core.bool v) { $_setBool(0, v); } + set none($core.bool v) { + $_setBool(0, v); + } + @$pb.TagNumber(1) $core.bool hasNone() => $_has(0); @$pb.TagNumber(1) @@ -2200,7 +2855,10 @@ class Response_Ok extends $pb.GeneratedMessage { @$pb.TagNumber(2) Response_Prekeys get prekeys => $_getN(1); @$pb.TagNumber(2) - set prekeys(Response_Prekeys v) { setField(2, v); } + set prekeys(Response_Prekeys v) { + setField(2, v); + } + @$pb.TagNumber(2) $core.bool hasPrekeys() => $_has(1); @$pb.TagNumber(2) @@ -2209,11 +2867,7 @@ class Response_Ok extends $pb.GeneratedMessage { Response_Prekeys ensurePrekeys() => $_ensure(1); } -enum Response_Response { - ok, - error, - notSet -} +enum Response_Response { ok, error, notSet } class Response extends $pb.GeneratedMessage { factory Response({ @@ -2230,31 +2884,42 @@ class Response extends $pb.GeneratedMessage { return $result; } Response._() : super(); - factory Response.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r); - factory Response.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r); + factory Response.fromBuffer($core.List<$core.int> i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromBuffer(i, r); + factory Response.fromJson($core.String i, + [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => + create()..mergeFromJson(i, r); - static const $core.Map<$core.int, Response_Response> _Response_ResponseByTag = { - 1 : Response_Response.ok, - 2 : Response_Response.error, - 0 : Response_Response.notSet + static const $core.Map<$core.int, Response_Response> _Response_ResponseByTag = + { + 1: Response_Response.ok, + 2: Response_Response.error, + 0: Response_Response.notSet }; - static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Response', package: const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo( + _omitMessageNames ? '' : 'Response', + package: + const $pb.PackageName(_omitMessageNames ? '' : 'client_to_server'), + createEmptyInstance: create) ..oo(0, [1, 2]) - ..aOM(1, _omitFieldNames ? '' : 'ok', subBuilder: Response_Ok.create) - ..e<$0.ErrorCode>(2, _omitFieldNames ? '' : 'error', $pb.PbFieldType.OE, defaultOrMaker: $0.ErrorCode.Unknown, valueOf: $0.ErrorCode.valueOf, enumValues: $0.ErrorCode.values) - ..hasRequiredFields = false - ; + ..aOM(1, _omitFieldNames ? '' : 'ok', + subBuilder: Response_Ok.create) + ..e<$0.ErrorCode>(2, _omitFieldNames ? '' : 'error', $pb.PbFieldType.OE, + defaultOrMaker: $0.ErrorCode.Unknown, + valueOf: $0.ErrorCode.valueOf, + enumValues: $0.ErrorCode.values) + ..hasRequiredFields = false; - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' - 'Will be removed in next major version') + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' + 'Will be removed in next major version') Response clone() => Response()..mergeFromMessage(this); - @$core.Deprecated( - 'Using this can add significant overhead to your binary. ' - 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' - 'Will be removed in next major version') - Response copyWith(void Function(Response) updates) => super.copyWith((message) => updates(message as Response)) as Response; + @$core.Deprecated('Using this can add significant overhead to your binary. ' + 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' + 'Will be removed in next major version') + Response copyWith(void Function(Response) updates) => + super.copyWith((message) => updates(message as Response)) as Response; $pb.BuilderInfo get info_ => _i; @@ -2263,16 +2928,21 @@ class Response extends $pb.GeneratedMessage { Response createEmptyInstance() => create(); static $pb.PbList createRepeated() => $pb.PbList(); @$core.pragma('dart2js:noInline') - static Response getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Response getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Response? _defaultInstance; - Response_Response whichResponse() => _Response_ResponseByTag[$_whichOneof(0)]!; + Response_Response whichResponse() => + _Response_ResponseByTag[$_whichOneof(0)]!; void clearResponse() => clearField($_whichOneof(0)); @$pb.TagNumber(1) Response_Ok get ok => $_getN(0); @$pb.TagNumber(1) - set ok(Response_Ok v) { setField(1, v); } + set ok(Response_Ok v) { + setField(1, v); + } + @$pb.TagNumber(1) $core.bool hasOk() => $_has(0); @$pb.TagNumber(1) @@ -2283,13 +2953,16 @@ class Response extends $pb.GeneratedMessage { @$pb.TagNumber(2) $0.ErrorCode get error => $_getN(1); @$pb.TagNumber(2) - set error($0.ErrorCode v) { setField(2, v); } + set error($0.ErrorCode v) { + setField(2, v); + } + @$pb.TagNumber(2) $core.bool hasError() => $_has(1); @$pb.TagNumber(2) void clearError() => clearField(2); } - const _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); -const _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); +const _omitMessageNames = + $core.bool.fromEnvironment('protobuf.omit_message_names'); diff --git a/lib/src/services/api.service.dart b/lib/src/services/api.service.dart index 9d9c90a..44caad4 100644 --- a/lib/src/services/api.service.dart +++ b/lib/src/services/api.service.dart @@ -1,13 +1,18 @@ +// ignore_for_file: avoid_dynamic_calls, strict_raw_type + import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; + import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:drift/drift.dart'; import 'package:fixnum/fixnum.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +// ignore: implementation_imports +import 'package:libsignal_protocol_dart/src/ecc/ed25519.dart'; import 'package:mutex/mutex.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:twonly/globals.dart'; @@ -18,24 +23,22 @@ 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.pbserver.dart'; -import 'package:twonly/src/services/api/messages.dart'; -import 'package:twonly/src/services/api/utils.dart'; import 'package:twonly/src/services/api/media_download.dart'; import 'package:twonly/src/services/api/media_upload.dart'; +import 'package:twonly/src/services/api/messages.dart'; import 'package:twonly/src/services/api/server_messages.dart'; +import 'package:twonly/src/services/api/utils.dart'; +import 'package:twonly/src/services/fcm.service.dart'; +import 'package:twonly/src/services/flame.service.dart'; import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; import 'package:twonly/src/services/signal/identity.signal.dart'; import 'package:twonly/src/services/signal/prekeys.signal.dart'; import 'package:twonly/src/services/signal/utils.signal.dart'; -import 'package:twonly/src/services/fcm.service.dart'; -import 'package:twonly/src/services/flame.service.dart'; import 'package:twonly/src/utils/keyvalue.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; import 'package:web_socket_channel/io.dart'; -// ignore: implementation_imports -import 'package:libsignal_protocol_dart/src/ecc/ed25519.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; final lockConnecting = Mutex(); @@ -45,12 +48,12 @@ final lockRetransStore = Mutex(); /// It handles errors and does automatically tries to reconnect on /// errors or network changes. class ApiService { - final String apiHost = (kDebugMode) ? "10.99.0.140:3030" : "api.twonly.eu"; - final String apiSecure = (kDebugMode) ? "" : "s"; + ApiService(); + final String apiHost = kDebugMode ? '10.99.0.140:3030' : 'api.twonly.eu'; + final String apiSecure = kDebugMode ? '' : 's'; bool appIsOutdated = false; bool isAuthenticated = false; - ApiService(); // reconnection params Timer? reconnectionTimer; @@ -69,51 +72,51 @@ class ApiService { _channel = channel; _channel!.stream.listen(_onData, onDone: _onDone, onError: _onError); await _channel!.ready; - Log.info("websocket connected to $apiUrl"); + Log.info('websocket connected to $apiUrl'); return true; } on WebSocketChannelException catch (e) { if (!e.message .toString() - .contains("No address associated with hostname")) { - Log.error("could not connect to api got: $e"); + .contains('No address associated with hostname')) { + Log.error('could not connect to api got: $e'); } return false; } } // Function is called after the user is authenticated at the server - Future onAuthenticated() async { + Future onAuthenticated() async { isAuthenticated = true; - initFCMAfterAuthenticated(); - globalCallbackConnectionState(true); + await initFCMAfterAuthenticated(); + globalCallbackConnectionState(isConnected: true); if (!globalIsAppInBackground) { - retransmitRawBytes(); - tryTransmitMessages(); - retryMediaUpload(false); - tryDownloadAllMediaFiles(); - notifyContactsAboutProfileChange(); + unawaited(retransmitRawBytes()); + unawaited(tryTransmitMessages()); + unawaited(retryMediaUpload(false)); + unawaited(tryDownloadAllMediaFiles()); + unawaited(notifyContactsAboutProfileChange()); twonlyDB.markUpdated(); - syncFlameCounters(); - setupNotificationWithUsers(); - signalHandleNewServerConnection(); + unawaited(syncFlameCounters()); + unawaited(setupNotificationWithUsers()); + unawaited(signalHandleNewServerConnection()); } } - Future onConnected() async { + Future onConnected() async { await authenticate(); _reconnectionDelay = 5; - globalCallbackConnectionState(true); + globalCallbackConnectionState(isConnected: true); } - Future onClosed() async { + Future onClosed() async { _channel = null; isAuthenticated = false; - globalCallbackConnectionState(false); + globalCallbackConnectionState(isConnected: false); await twonlyDB.messagesDao.resetPendingDownloadState(); } - Future startReconnectionTimer() async { + Future startReconnectionTimer() async { reconnectionTimer?.cancel(); reconnectionTimer ??= Timer(Duration(seconds: _reconnectionDelay), () { reconnectionTimer = null; @@ -122,18 +125,18 @@ class ApiService { _reconnectionDelay += 5; } - Future close(Function callback) async { - Log.info("closing websocket connection"); + Future close(Function callback) async { + Log.info('closing websocket connection'); if (_channel != null) { await _channel!.sink.close(); - onClosed(); + await onClosed(); callback(); return; } callback(); } - Future listenToNetworkChanges() async { + Future listenToNetworkChanges() async { if (connectivitySubscription != null) { return; } @@ -155,7 +158,7 @@ class ApiService { reconnectionTimer = null; final user = await getUser(); if (user != null && user.isDemoUser) { - globalCallbackConnectionState(true); + globalCallbackConnectionState(isConnected: true); return false; } return lockConnecting.protect(() async { @@ -168,9 +171,9 @@ class ApiService { isAuthenticated = false; - String apiUrl = "ws$apiSecure://$apiHost/api/client"; + final apiUrl = 'ws$apiSecure://$apiHost/api/client'; - Log.info("connecting to $apiUrl"); + Log.info('connecting to $apiUrl'); if (await _connectTo(apiUrl)) { await onConnected(); @@ -183,18 +186,18 @@ class ApiService { bool get isConnected => _channel != null && _channel!.closeCode != null; void _onDone() { - Log.info("websocket closed without error"); + Log.info('websocket closed without error'); onClosed(); } void _onError(dynamic e) { - Log.error("websocket error: $e"); + Log.error('websocket error: $e'); onClosed(); } void _onData(dynamic msgBuffer) async { try { - final msg = server.ServerToClient.fromBuffer(msgBuffer); + final msg = server.ServerToClient.fromBuffer(msgBuffer as Uint8List); if (msg.v0.hasResponse()) { removeFromRetransmissionBuffer(msg.v0.seq); messagesV0[msg.v0.seq] = msg; @@ -202,7 +205,7 @@ class ApiService { await handleServerMessage(msg); } } catch (e) { - Log.error("Error parsing the servers message: $e"); + Log.error('Error parsing the servers message: $e'); } } @@ -218,57 +221,57 @@ class ApiService { return tmp; } if (DateTime.now().difference(startTime) > timeout) { - Log.error("Timeout for message $seq"); + Log.error('Timeout for message $seq'); return null; } - await Future.delayed(Duration(milliseconds: 10)); + await Future.delayed(const Duration(milliseconds: 10)); } } - Future sendResponse(ClientToServer response) async { + Future sendResponse(ClientToServer response) async { if (_channel != null) { _channel!.sink.add(response.writeToBuffer()); } } Future> getRetransmission() async { - return await KeyValueStore.get("rawbytes-to-retransmit") ?? {}; + return (await KeyValueStore.get('rawbytes-to-retransmit')) ?? {}; } - Future retransmitRawBytes() async { + Future retransmitRawBytes() async { await lockRetransStore.protect(() async { - var retransmit = await getRetransmission(); + final retransmit = await getRetransmission(); if (retransmit.keys.isEmpty) return; - Log.info("retransmitting ${retransmit.keys.length} raw bytes messages"); - bool gotError = false; + Log.info('retransmitting ${retransmit.keys.length} raw bytes messages'); + var gotError = false; for (final seq in retransmit.keys) { try { - _channel!.sink.add(base64Decode(retransmit[seq])); + _channel!.sink.add(base64Decode(retransmit[seq] as String)); } catch (e) { gotError = true; - Log.error("$e"); + Log.error('$e'); } } if (!gotError) { - KeyValueStore.put("rawbytes-to-retransmit", {}); + await KeyValueStore.put('rawbytes-to-retransmit', {}); } }); } - Future addToRetransmissionBuffer(Int64 seq, Uint8List bytes) async { + Future addToRetransmissionBuffer(Int64 seq, Uint8List bytes) async { await lockRetransStore.protect(() async { - var retransmit = await getRetransmission(); + final retransmit = await getRetransmission(); retransmit[seq.toString()] = base64Encode(bytes); - KeyValueStore.put("rawbytes-to-retransmit", retransmit); + await KeyValueStore.put('rawbytes-to-retransmit', retransmit); }); } - Future removeFromRetransmissionBuffer(Int64 seq) async { + Future removeFromRetransmissionBuffer(Int64 seq) async { await lockRetransStore.protect(() async { - var retransmit = await getRetransmission(); + final retransmit = await getRetransmission(); if (retransmit.isEmpty) return; retransmit.remove(seq.toString()); - KeyValueStore.put("rawbytes-to-retransmit", retransmit); + await KeyValueStore.put('rawbytes-to-retransmit', retransmit); }); } @@ -287,11 +290,11 @@ class ApiService { final requestBytes = request.writeToBuffer(); if (ensureRetransmission) { - addToRetransmissionBuffer(seq, requestBytes); + await addToRetransmissionBuffer(seq, requestBytes); } if (_channel == null) { - Log.warn("sending request while api is not connected"); + Log.warn('sending request while api is not connected'); if (!await connect()) { return Result.error(ErrorCode.InternalError); } @@ -302,12 +305,12 @@ class ApiService { _channel!.sink.add(requestBytes); - Result res = asResult(await _waitForResponse(seq)); + final res = asResult(await _waitForResponse(seq)); if (res.isError) { - Log.error("got error from server: ${res.error}"); + Log.error('got error from server: ${res.error}'); if (res.error == ErrorCode.AppVersionOutdated) { globalCallbackAppIsOutdated(); - Log.error("App Version is OUTDATED."); + Log.error('App Version is OUTDATED.'); appIsOutdated = true; await close(() {}); return Result.error(ErrorCode.InternalError); @@ -320,16 +323,16 @@ class ApiService { // this will send the request one more time. return sendRequestSync(request, authenticated: false); } else { - Log.error("session is not authenticated"); + Log.error('session is not authenticated'); return Result.error(ErrorCode.InternalError); } } } if (res.error == ErrorCode.UserIdNotFound && contactId != null) { - Log.error("Contact deleted their account $contactId."); + Log.error('Contact deleted their account $contactId.'); await twonlyDB.contactsDao.updateContact( contactId, - ContactsCompanion( + const ContactsCompanion( deleted: Value(true), ), ); @@ -339,8 +342,8 @@ class ApiService { } Future tryAuthenticateWithToken(int userId) async { - final storage = FlutterSecureStorage(); - String? apiAuthToken = + const storage = FlutterSecureStorage(); + final apiAuthToken = await storage.read(key: SecureStorageKeys.apiAuthToken); if (apiAuthToken != null) { @@ -355,21 +358,21 @@ class ApiService { final result = await sendRequestSync(req, authenticated: false); if (result.isSuccess) { - server.Response_Ok ok = result.value; + final ok = result.value as server.Response_Ok; if (ok.hasAuthenticated()) { - server.Response_Authenticated authenticated = ok.authenticated; - updateUserdata((user) { + final authenticated = ok.authenticated; + await updateUserdata((user) { user.subscriptionPlan = authenticated.plan; return user; }); } - Log.info("websocket is authenticated"); - onAuthenticated(); + Log.info('websocket is authenticated'); + unawaited(onAuthenticated()); return true; } if (result.isError) { if (result.error != ErrorCode.AuthTokenNotValid) { - Log.error("got error while authenticating to the server", result); + Log.error('got error while authenticating to the server', result); return false; } } @@ -377,7 +380,7 @@ class ApiService { return false; } - Future authenticate() async { + Future authenticate() async { if (isAuthenticated) return; if (await getSignalIdentity() == null) { return; @@ -392,11 +395,11 @@ class ApiService { var handshake = Handshake() ..getauthchallenge = Handshake_GetAuthChallenge(); - var req = createClientToServerFromHandshake(handshake); + final req = createClientToServerFromHandshake(handshake); final result = await sendRequestSync(req, authenticated: false); if (result.isError) { - Log.error("could not request auth challenge", result); + Log.error('could not request auth challenge', result); return; } @@ -405,7 +408,7 @@ class ApiService { var privKey = (await getSignalIdentityKeyPair())?.getPrivateKey(); if (privKey == null) return; final random = getRandomUint8List(32); - final signature = sign(privKey.serialize(), challenge, random); + final signature = sign(privKey.serialize(), challenge as Uint8List, random); privKey = null; final getAuthToken = Handshake_GetAuthToken() @@ -414,18 +417,18 @@ class ApiService { final getauthtoken = Handshake()..getauthtoken = getAuthToken; - var req2 = createClientToServerFromHandshake(getauthtoken); + final req2 = createClientToServerFromHandshake(getauthtoken); final result2 = await sendRequestSync(req2, authenticated: false); if (result2.isError) { - Log.error("could not send auth response: ${result2.error}"); + Log.error('could not send auth response: ${result2.error}'); return; } - Uint8List apiAuthToken = result2.value.authtoken; - String apiAuthTokenB64 = base64Encode(apiAuthToken); + final apiAuthToken = result2.value.authtoken as Uint8List; + final apiAuthTokenB64 = base64Encode(apiAuthToken); - final storage = FlutterSecureStorage(); + const storage = FlutterSecureStorage(); await storage.write( key: SecureStorageKeys.apiAuthToken, value: apiAuthTokenB64); @@ -452,51 +455,51 @@ class ApiService { ..signedPrekeyId = Int64(signedPreKey.id) ..isIos = Platform.isIOS; - if (inviteCode != null && inviteCode != "") { + if (inviteCode != null && inviteCode != '') { register.inviteCode = inviteCode; } - var handshake = Handshake()..register = register; - var req = createClientToServerFromHandshake(handshake); + final handshake = Handshake()..register = register; + final req = createClientToServerFromHandshake(handshake); - return await sendRequestSync(req); + return sendRequestSync(req); } Future getUsername(int userId) async { - var get = ApplicationData_GetUserById()..userId = Int64(userId); - var appData = ApplicationData()..getuserbyid = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req, contactId: userId); + final get = ApplicationData_GetUserById()..userId = Int64(userId); + final appData = ApplicationData()..getuserbyid = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req, contactId: userId); } Future downloadDone(List token) async { - var get = ApplicationData_DownloadDone()..downloadToken = token; - var appData = ApplicationData()..downloaddone = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req, ensureRetransmission: true); + final get = ApplicationData_DownloadDone()..downloadToken = token; + final appData = ApplicationData()..downloaddone = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req, ensureRetransmission: true); } Future getCurrentLocation() async { - var get = ApplicationData_GetLocation(); - var appData = ApplicationData()..getlocation = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_GetLocation(); + final appData = ApplicationData()..getlocation = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future getUserData(String username) async { - var get = ApplicationData_GetUserByUsername()..username = username; - var appData = ApplicationData()..getuserbyusername = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_GetUserByUsername()..username = username; + final appData = ApplicationData()..getuserbyusername = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future getPlanBallance() async { - var get = ApplicationData_GetCurrentPlanInfos(); - var appData = ApplicationData()..getcurrentplaninfos = get; - var req = createClientToServerFromApplicationData(appData); - Result res = await sendRequestSync(req); + final get = ApplicationData_GetCurrentPlanInfos(); + final appData = ApplicationData()..getcurrentplaninfos = get; + final req = createClientToServerFromApplicationData(appData); + final res = await sendRequestSync(req); if (res.isSuccess) { - server.Response_Ok ok = res.value; + final ok = res.value as server.Response_Ok; if (ok.hasPlanballance()) { return ok.planballance; } @@ -505,12 +508,12 @@ class ApiService { } Future getVoucherList() async { - var get = ApplicationData_GetVouchers(); - var appData = ApplicationData()..getvouchers = get; - var req = createClientToServerFromApplicationData(appData); - Result res = await sendRequestSync(req); + final get = ApplicationData_GetVouchers(); + final appData = ApplicationData()..getvouchers = get; + final req = createClientToServerFromApplicationData(appData); + final res = await sendRequestSync(req); if (res.isSuccess) { - server.Response_Ok ok = res.value; + final ok = res.value as server.Response_Ok; if (ok.hasVouchers()) { return ok.vouchers; } @@ -519,12 +522,12 @@ class ApiService { } Future?> getAdditionalUserInvites() async { - var get = ApplicationData_GetAddAccountsInvites(); - var appData = ApplicationData()..getaddaccountsinvites = get; - var req = createClientToServerFromApplicationData(appData); - Result res = await sendRequestSync(req); + final get = ApplicationData_GetAddAccountsInvites(); + final appData = ApplicationData()..getaddaccountsinvites = get; + final req = createClientToServerFromApplicationData(appData); + final res = await sendRequestSync(req); if (res.isSuccess) { - server.Response_Ok ok = res.value; + final ok = res.value as server.Response_Ok; if (ok.hasAddaccountsinvites()) { return ok.addaccountsinvites.invites; } @@ -533,63 +536,63 @@ class ApiService { } Future updatePlanOptions(bool autoRenewal) async { - var get = ApplicationData_UpdatePlanOptions()..autoRenewal = autoRenewal; - var appData = ApplicationData()..updateplanoptions = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_UpdatePlanOptions()..autoRenewal = autoRenewal; + final appData = ApplicationData()..updateplanoptions = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future removeAdditionalUser(Int64 userId) async { - var get = ApplicationData_RemoveAdditionalUser()..userId = userId; - var appData = ApplicationData()..removeadditionaluser = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req, contactId: userId.toInt()); + final get = ApplicationData_RemoveAdditionalUser()..userId = userId; + final appData = ApplicationData()..removeadditionaluser = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req, contactId: userId.toInt()); } Future buyVoucher(int valueInCents) async { - var get = ApplicationData_CreateVoucher()..valueCents = valueInCents; - var appData = ApplicationData()..createvoucher = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_CreateVoucher()..valueCents = valueInCents; + final appData = ApplicationData()..createvoucher = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future switchToPayedPlan( String planId, bool payMonthly, bool autoRenewal) async { - var get = ApplicationData_SwitchToPayedPlan() + final get = ApplicationData_SwitchToPayedPlan() ..planId = planId ..payMonthly = payMonthly ..autoRenewal = autoRenewal; - var appData = ApplicationData()..switchtopayedplan = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final appData = ApplicationData()..switchtopayedplan = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future redeemVoucher(String voucher) async { - var get = ApplicationData_RedeemVoucher()..voucher = voucher; - var appData = ApplicationData()..redeemvoucher = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_RedeemVoucher()..voucher = voucher; + final appData = ApplicationData()..redeemvoucher = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future deleteAccount() async { - var get = ApplicationData_DeleteAccount(); - var appData = ApplicationData()..deleteaccount = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_DeleteAccount(); + final appData = ApplicationData()..deleteaccount = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future redeemUserInviteCode(String inviteCode) async { - var get = ApplicationData_RedeemAdditionalCode()..inviteCode = inviteCode; - var appData = ApplicationData()..redeemadditionalcode = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_RedeemAdditionalCode()..inviteCode = inviteCode; + final appData = ApplicationData()..redeemadditionalcode = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future updateFCMToken(String googleFcm) async { - var get = ApplicationData_UpdateGoogleFcmToken()..googleFcm = googleFcm; - var appData = ApplicationData()..updategooglefcmtoken = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final get = ApplicationData_UpdateGoogleFcmToken()..googleFcm = googleFcm; + final appData = ApplicationData()..updategooglefcmtoken = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future updateSignedPreKey( @@ -597,22 +600,23 @@ class ApiService { Uint8List signedPreKey, Uint8List signedPreKeySignature, ) async { - var get = ApplicationData_UpdateSignedPreKey() + final get = ApplicationData_UpdateSignedPreKey() ..signedPrekeyId = Int64(signedPreKeyId) ..signedPrekey = signedPreKey ..signedPrekeySignature = signedPreKeySignature; - var appData = ApplicationData()..updatesignedprekey = get; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req); + final appData = ApplicationData()..updatesignedprekey = get; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req); } Future getSignedKeyByUserId(int userId) async { - var get = ApplicationData_GetSignedPreKeyByUserId()..userId = Int64(userId); - var appData = ApplicationData()..getsignedprekeybyuserid = get; - var req = createClientToServerFromApplicationData(appData); + final get = ApplicationData_GetSignedPreKeyByUserId() + ..userId = Int64(userId); + final appData = ApplicationData()..getsignedprekeybyuserid = get; + final req = createClientToServerFromApplicationData(appData); Result res = await sendRequestSync(req, contactId: userId); if (res.isSuccess) { - server.Response_Ok ok = res.value; + final ok = res.value as server.Response_Ok; if (ok.hasSignedprekey()) { return ok.signedprekey; } @@ -621,12 +625,12 @@ class ApiService { } Future getPreKeysByUserId(int userId) async { - var get = ApplicationData_GetPrekeysByUserId()..userId = Int64(userId); - var appData = ApplicationData()..getprekeysbyuserid = get; - var req = createClientToServerFromApplicationData(appData); + final get = ApplicationData_GetPrekeysByUserId()..userId = Int64(userId); + final appData = ApplicationData()..getprekeysbyuserid = get; + final req = createClientToServerFromApplicationData(appData); Result res = await sendRequestSync(req, contactId: userId); if (res.isSuccess) { - server.Response_Ok ok = res.value; + final ok = res.value as server.Response_Ok; if (ok.hasUserdata()) { server.Response_UserData data = ok.userdata; if (data.hasSignedPrekey() && @@ -654,8 +658,8 @@ class ApiService { testMessage.pushData = pushData; } - var appData = ApplicationData()..textmessage = testMessage; - var req = createClientToServerFromApplicationData(appData); - return await sendRequestSync(req, contactId: target); + final appData = ApplicationData()..textmessage = testMessage; + final req = createClientToServerFromApplicationData(appData); + return sendRequestSync(req, contactId: target); } } diff --git a/lib/src/services/api/media_download.dart b/lib/src/services/api/media_download.dart index 381be5c..66d8658 100644 --- a/lib/src/services/api/media_download.dart +++ b/lib/src/services/api/media_download.dart @@ -1,18 +1,20 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; + import 'package:background_downloader/background_downloader.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:cryptography_flutter_plus/cryptography_flutter_plus.dart'; +import 'package:cryptography_plus/cryptography_plus.dart'; import 'package:drift/drift.dart'; import 'package:http/http.dart' as http; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; import 'package:twonly/src/services/api/media_upload.dart'; -import 'package:cryptography_plus/cryptography_plus.dart'; import 'package:twonly/src/services/api/utils.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/storage.dart'; @@ -20,13 +22,13 @@ import 'package:twonly/src/views/camera/share_image_editor_view.dart'; Map downloadStartedForMediaReceived = {}; -Future tryDownloadAllMediaFiles({bool force = false}) async { +Future tryDownloadAllMediaFiles({bool force = false}) async { // This is called when WebSocket is newly connected, so allow all downloads to be restarted. downloadStartedForMediaReceived = {}; - List messages = + final messages = await twonlyDB.messagesDao.getAllMessagesPendingDownloading(); - for (Message message in messages) { + for (final message in messages) { await startDownloadMedia(message, force); } } @@ -45,8 +47,7 @@ Map> defaultAutoDownloadOptions = { }; Future isAllowedToDownload(bool isVideo) async { - final List connectivityResult = - await (Connectivity().checkConnectivity()); + final connectivityResult = await Connectivity().checkConnectivity(); final user = await getUser(); final options = user!.autoDownloadOptions ?? defaultAutoDownloadOptions; @@ -76,9 +77,9 @@ Future isAllowedToDownload(bool isVideo) async { return false; } -Future handleDownloadStatusUpdate(TaskStatusUpdate update) async { - int messageId = int.parse(update.task.taskId.replaceAll("download_", "")); - bool failed = false; +Future handleDownloadStatusUpdate(TaskStatusUpdate update) async { + final messageId = int.parse(update.task.taskId.replaceAll('download_', '')); + var failed = false; if (update.status == TaskStatus.failed || update.status == TaskStatus.canceled || @@ -90,46 +91,47 @@ Future handleDownloadStatusUpdate(TaskStatusUpdate update) async { } else { failed = true; Log.error( - "Got invalid response status code: ${update.responseStatusCode}", + 'Got invalid response status code: ${update.responseStatusCode}', ); } } else { - Log.info("Got ${update.status} for $messageId"); + Log.info('Got ${update.status} for $messageId'); return; } await handleDownloadStatusUpdateInternal(messageId, failed); } -Future handleDownloadStatusUpdateInternal(int messageId, bool failed) async { +Future handleDownloadStatusUpdateInternal( + int messageId, bool failed) async { if (failed) { - Log.error("Download failed for $messageId"); - Message? message = await twonlyDB.messagesDao + Log.error('Download failed for $messageId'); + final message = await twonlyDB.messagesDao .getMessageByMessageId(messageId) .getSingleOrNull(); if (message != null) { await handleMediaError(message); } } else { - Log.info("Download was successfully for $messageId"); + Log.info('Download was successfully for $messageId'); await handleEncryptedFile(messageId); } } -Future startDownloadMedia(Message message, bool force, +Future startDownloadMedia(Message message, bool force, {int retryCounter = 0}) async { if (message.contentJson == null) return; if (downloadStartedForMediaReceived[message.messageId] != null && retryCounter == 0) { - DateTime started = downloadStartedForMediaReceived[message.messageId]!; - Duration elapsed = DateTime.now().difference(started); - if (elapsed <= Duration(seconds: 60)) { - Log.error("Download already started..."); + final started = downloadStartedForMediaReceived[message.messageId]!; + final elapsed = DateTime.now().difference(started); + if (elapsed <= const Duration(seconds: 60)) { + Log.error('Download already started...'); return; } } - final content = - MessageContent.fromJson(message.kind, jsonDecode(message.contentJson!)); + final content = MessageContent.fromJson( + message.kind, jsonDecode(message.contentJson!) as Map); if (content is! MediaMessageContent) return; if (content.downloadToken == null) return; @@ -158,7 +160,7 @@ Future startDownloadMedia(Message message, bool force, if (message.downloadState != DownloadState.downloaded) { await twonlyDB.messagesDao.updateMessageByMessageId( message.messageId, - MessagesCompanion( + const MessagesCompanion( downloadState: Value(DownloadState.downloading), ), ); @@ -166,36 +168,34 @@ Future startDownloadMedia(Message message, bool force, downloadStartedForMediaReceived[message.messageId] = DateTime.now(); - String downloadToken = uint8ListToHex(content.downloadToken!); + final downloadToken = uint8ListToHex(content.downloadToken!); - String apiUrl = - "http${apiService.apiSecure}://${apiService.apiHost}/api/download/$downloadToken"; + final apiUrl = + 'http${apiService.apiSecure}://${apiService.apiHost}/api/download/$downloadToken'; try { final task = DownloadTask( url: apiUrl, - taskId: "download_${media.messageId}", - directory: "media/received/", + taskId: 'download_${media.messageId}', + directory: 'media/received/', baseDirectory: BaseDirectory.applicationSupport, - filename: "${media.messageId}.encrypted", + filename: '${media.messageId}.encrypted', priority: 0, retries: 10, ); Log.info( - "Got media file. Starting download: ${downloadToken.substring(0, 10)}", + 'Got media file. Starting download: ${downloadToken.substring(0, 10)}', ); try { await downloadFileFast(media.messageId, apiUrl); - return; } catch (e) { - Log.error("Fast download failed: $e"); - final result = await FileDownloader().enqueue(task); - return result; + Log.error('Fast download failed: $e'); + await FileDownloader().enqueue(task); } } catch (e) { - Log.error("Exception during download: $e"); + Log.error('Exception during download: $e'); } } @@ -203,19 +203,19 @@ Future downloadFileFast( int messageId, String apiUrl, ) async { - final String directoryPath = - "${(await getApplicationSupportDirectory()).path}/media/received/"; - final String filename = "$messageId.encrypted"; + final directoryPath = + '${(await getApplicationSupportDirectory()).path}/media/received/'; + final filename = '$messageId.encrypted'; - final Directory directory = Directory(directoryPath); - if (!await directory.exists()) { + final directory = Directory(directoryPath); + if (!directory.existsSync()) { await directory.create(recursive: true); } - final String filePath = "${directory.path}/$filename"; + final filePath = '${directory.path}/$filename'; final response = - await http.get(Uri.parse(apiUrl)).timeout(Duration(seconds: 10)); + await http.get(Uri.parse(apiUrl)).timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { await File(filePath).writeAsBytes(response.bodyBytes); @@ -228,34 +228,34 @@ Future downloadFileFast( return; } // can be tried again - throw Exception("Fast download failed with status: ${response.statusCode}"); + throw Exception('Fast download failed with status: ${response.statusCode}'); } } -Future handleEncryptedFile(int messageId) async { - Message? msg = await twonlyDB.messagesDao +Future handleEncryptedFile(int messageId) async { + final msg = await twonlyDB.messagesDao .getMessageByMessageId(messageId) .getSingleOrNull(); if (msg == null) { - Log.error("Not message for downloaded file found: $messageId"); + Log.error('Not message for downloaded file found: $messageId'); return; } - Uint8List? encryptedBytes = await readMediaFile(msg.messageId, "encrypted"); + final encryptedBytes = await readMediaFile(msg.messageId, 'encrypted'); if (encryptedBytes == null) { - Log.error("encrypted bytes are not found for ${msg.messageId}"); + Log.error('encrypted bytes are not found for ${msg.messageId}'); return; } - MediaMessageContent content = - MediaMessageContent.fromJson(jsonDecode(msg.contentJson!)); + final content = + MediaMessageContent.fromJson(jsonDecode(msg.contentJson!) as Map); try { final chacha20 = FlutterChacha20.poly1305Aead(); - SecretKeyData secretKeyData = SecretKeyData(content.encryptionKey!); + final secretKeyData = SecretKeyData(content.encryptionKey!); - SecretBox secretBox = SecretBox( + final secretBox = SecretBox( encryptedBytes, nonce: content.encryptionNonce!, mac: Mac(content.encryptionMac!), @@ -269,10 +269,10 @@ Future handleEncryptedFile(int messageId) async { if (content.isVideo) { final extractedBytes = extractUint8Lists(imageBytes); imageBytes = extractedBytes[0]; - await writeMediaFile(msg.messageId, "mp4", extractedBytes[1]); + await writeMediaFile(msg.messageId, 'mp4', extractedBytes[1]); } - await writeMediaFile(msg.messageId, "png", imageBytes); + await writeMediaFile(msg.messageId, 'png', imageBytes); // } catch (e) { // Log.error( // "could not decrypt the media file in the second try. reporting error to user: $e"); @@ -280,13 +280,13 @@ Future handleEncryptedFile(int messageId) async { // return; // } } catch (e) { - Log.error("$e"); + Log.error('$e'); /// legacy support final chacha20 = Xchacha20.poly1305Aead(); - SecretKeyData secretKeyData = SecretKeyData(content.encryptionKey!); + final secretKeyData = SecretKeyData(content.encryptionKey!); - SecretBox secretBox = SecretBox( + final secretBox = SecretBox( encryptedBytes, nonce: content.encryptionNonce!, mac: Mac(content.encryptionMac!), @@ -300,121 +300,122 @@ Future handleEncryptedFile(int messageId) async { if (content.isVideo) { final extractedBytes = extractUint8Lists(imageBytes); imageBytes = extractedBytes[0]; - await writeMediaFile(msg.messageId, "mp4", extractedBytes[1]); + await writeMediaFile(msg.messageId, 'mp4', extractedBytes[1]); } - await writeMediaFile(msg.messageId, "png", imageBytes); + await writeMediaFile(msg.messageId, 'png', imageBytes); } catch (e) { Log.error( - "could not decrypt the media file in the second try. reporting error to user: $e"); - handleMediaError(msg); + 'could not decrypt the media file in the second try. reporting error to user: $e'); + await handleMediaError(msg); return; } } await twonlyDB.messagesDao.updateMessageByMessageId( msg.messageId, - MessagesCompanion(downloadState: Value(DownloadState.downloaded)), + const MessagesCompanion(downloadState: Value(DownloadState.downloaded)), ); - Log.info("Download and decryption of ${msg.messageId} was successful"); + Log.info('Download and decryption of ${msg.messageId} was successful'); - await deleteMediaFile(msg.messageId, "encrypted"); + await deleteMediaFile(msg.messageId, 'encrypted'); - apiService.downloadDone(content.downloadToken!); + unawaited(apiService.downloadDone(content.downloadToken!)); } Future getImageBytes(int mediaId) async { - return await readMediaFile(mediaId, "png"); + return readMediaFile(mediaId, 'png'); } Future getVideoPath(int mediaId) async { - String basePath = await getMediaFilePath(mediaId, "received"); - return File("$basePath.mp4"); + final basePath = await getMediaFilePath(mediaId, 'received'); + return File('$basePath.mp4'); } /// --- helper functions --- Future readMediaFile(int mediaId, String type) async { - String basePath = await getMediaFilePath(mediaId, "received"); - File file = File("$basePath.$type"); - Log.info("Reading: $file"); - if (!await file.exists()) { + final basePath = await getMediaFilePath(mediaId, 'received'); + final file = File('$basePath.$type'); + Log.info('Reading: $file'); + if (!file.existsSync()) { return null; } - return await file.readAsBytes(); + return file.readAsBytes(); } Future existsMediaFile(int mediaId, String type) async { - String basePath = await getMediaFilePath(mediaId, "received"); - File file = File("$basePath.$type"); - return await file.exists(); + final basePath = await getMediaFilePath(mediaId, 'received'); + final file = File('$basePath.$type'); + return file.existsSync(); } Future writeMediaFile(int mediaId, String type, Uint8List data) async { - String basePath = await getMediaFilePath(mediaId, "received"); - File file = File("$basePath.$type"); + final basePath = await getMediaFilePath(mediaId, 'received'); + final file = File('$basePath.$type'); await file.writeAsBytes(data); } Future deleteMediaFile(int mediaId, String type) async { - String basePath = await getMediaFilePath(mediaId, "received"); - File file = File("$basePath.$type"); + final basePath = await getMediaFilePath(mediaId, 'received'); + final file = File('$basePath.$type'); try { - if (await file.exists()) { + if (file.existsSync()) { await file.delete(); } } catch (e) { - Log.error("Error deleting: $e"); + Log.error('Error deleting: $e'); } } Future purgeReceivedMediaFiles() async { final basedir = await getApplicationSupportDirectory(); - final directory = Directory(join(basedir.path, 'media', "received")); + final directory = Directory(join(basedir.path, 'media', 'received')); await purgeMediaFiles(directory); } Future purgeMediaFiles(Directory directory) async { // Check if the directory exists - if (await directory.exists()) { + if (directory.existsSync()) { // List all files in the directory - List files = directory.listSync(); + final files = directory.listSync(); // Iterate over each file - for (var file in files) { + for (final file in files) { // Get the filename - String filename = file.uri.pathSegments.last; + final filename = file.uri.pathSegments.last; // Use a regular expression to extract the integer part final match = RegExp(r'(\d+)').firstMatch(filename); if (match != null) { // Parse the integer and add it to the list - int fileId = int.parse(match.group(0)!); + final fileId = int.parse(match.group(0)!); try { - if (directory.path.endsWith("send")) { - List messages = + if (directory.path.endsWith('send')) { + final messages = await twonlyDB.messagesDao.getMessagesByMediaUploadId(fileId); - bool canBeDeleted = true; + var canBeDeleted = true; for (final message in messages) { try { - MediaMessageContent content = MediaMessageContent.fromJson( - jsonDecode(message.contentJson!), + final content = MediaMessageContent.fromJson( + jsonDecode(message.contentJson!) as Map, ); - DateTime oneDayAgo = DateTime.now().subtract(Duration(days: 1)); - DateTime twoDaysAgo = - DateTime.now().subtract(Duration(days: 1)); + final oneDayAgo = + DateTime.now().subtract(const Duration(days: 1)); + final twoDaysAgo = + DateTime.now().subtract(const Duration(days: 1)); - if (((message.openedAt == null || + if ((message.openedAt == null || oneDayAgo.isBefore(message.openedAt!)) && - !message.errorWhileSending)) { + !message.errorWhileSending) { canBeDeleted = false; } else if (message.mediaStored) { - if (!file.path.contains(".original.") && - !file.path.contains(".encrypted")) { + if (!file.path.contains('.original.') && + !file.path.contains('.encrypted')) { canBeDeleted = false; } } @@ -429,8 +430,8 @@ Future purgeMediaFiles(Directory directory) async { canBeDeleted = true; } // Encrypted or upload data can be removed when acknowledgeByServer - if (file.path.contains(".upload") || - file.path.contains(".encrypted")) { + if (file.path.contains('.upload') || + file.path.contains('.encrypted')) { canBeDeleted = true; } } @@ -439,11 +440,11 @@ Future purgeMediaFiles(Directory directory) async { } } if (canBeDeleted) { - Log.info("purged media file ${file.path} "); + Log.info('purged media file ${file.path} '); file.deleteSync(); } } else { - Message? message = await twonlyDB.messagesDao + final message = await twonlyDB.messagesDao .getMessageByMessageId(fileId) .getSingleOrNull(); if ((message == null) || @@ -455,7 +456,7 @@ Future purgeMediaFiles(Directory directory) async { } } } catch (e) { - Log.error("$e"); + Log.error('$e'); } } } diff --git a/lib/src/services/api/media_upload.dart b/lib/src/services/api/media_upload.dart index 4e6b60e..e69f9b6 100644 --- a/lib/src/services/api/media_upload.dart +++ b/lib/src/services/api/media_upload.dart @@ -1,15 +1,16 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:io'; import 'dart:math'; + import 'package:background_downloader/background_downloader.dart'; import 'package:cryptography_flutter_plus/cryptography_flutter_plus.dart'; -import 'package:fixnum/fixnum.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter_secure_storage/flutter_secure_storage.dart'; -import 'dart:io'; import 'package:cryptography_plus/cryptography_plus.dart'; import 'package:drift/drift.dart'; +import 'package:fixnum/fixnum.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:http/http.dart' as http; import 'package:mutex/mutex.dart'; import 'package:path/path.dart'; @@ -35,11 +36,11 @@ import 'package:video_compress/video_compress.dart'; Future isAllowedToSend() async { final user = await getUser(); if (user == null) return null; - if (user.subscriptionPlan == "Preview") { + if (user.subscriptionPlan == 'Preview') { return ErrorCode.PlanNotAllowed; } - if (user.subscriptionPlan == "Free") { - int? todaysImageCounter = user.todaysImageCounter; + if (user.subscriptionPlan == 'Free') { + var todaysImageCounter = user.todaysImageCounter; if (user.lastImageSend != null && user.todaysImageCounter != null) { if (isToday(user.lastImageSend!)) { if (user.todaysImageCounter == 3) { @@ -53,25 +54,26 @@ Future isAllowedToSend() async { todaysImageCounter = 1; } await updateUserdata((user) { - user.lastImageSend = DateTime.now(); - user.todaysImageCounter = todaysImageCounter; + user + ..lastImageSend = DateTime.now() + ..todaysImageCounter = todaysImageCounter; return user; }); } return null; } -Future initFileDownloader() async { +Future initFileDownloader() async { FileDownloader().updates.listen((update) async { switch (update) { case TaskStatusUpdate(): - if (update.task.taskId.contains("upload_")) { + if (update.task.taskId.contains('upload_')) { await handleUploadStatusUpdate(update); } - if (update.task.taskId.contains("download_")) { + if (update.task.taskId.contains('download_')) { await handleDownloadStatusUpdate(update); } - if (update.task.taskId.contains("backup")) { + if (update.task.taskId.contains('backup')) { await handleBackupStatusUpdate(update); } case TaskProgressUpdate(): @@ -82,17 +84,16 @@ Future initFileDownloader() async { await FileDownloader().start(); - FileDownloader().configure(androidConfig: [ + await FileDownloader().configure(androidConfig: [ (Config.bypassTLSCertificateValidation, kDebugMode), ]); if (kDebugMode) { FileDownloader().configureNotification( - running: TaskNotification( + running: const TaskNotification( 'Uploading/Downloading', '{filename} ({progress}).', ), - complete: null, progressBar: true, ); } @@ -112,14 +113,14 @@ Future initFileDownloader() async { Future checkForFailedUploads() async { final messages = await twonlyDB.messagesDao.getAllMessagesPendingUpload(); - List mediaUploadIds = []; - for (Message message in messages) { + final mediaUploadIds = []; + for (var message in messages) { if (mediaUploadIds.contains(message.mediaUploadId)) { continue; } - int affectedRows = await twonlyDB.mediaUploadsDao.updateMediaUpload( + final affectedRows = await twonlyDB.mediaUploadsDao.updateMediaUpload( message.mediaUploadId!, - MediaUploadsCompanion( + const MediaUploadsCompanion( state: Value(UploadState.pending), encryptionData: Value( null, // start from scratch e.q. encrypt the files again if already happen @@ -128,11 +129,11 @@ Future checkForFailedUploads() async { ); if (affectedRows == 0) { Log.error( - "The media from message ${message.messageId} already deleted.", + 'The media from message ${message.messageId} already deleted.', ); await twonlyDB.messagesDao.updateMessageByMessageId( message.messageId, - MessagesCompanion( + const MessagesCompanion( errorWhileSending: Value(true), ), ); @@ -142,24 +143,24 @@ Future checkForFailedUploads() async { } if (messages.isNotEmpty) { Log.error( - "Got ${messages.length} messages (${mediaUploadIds.length} media upload files) that are not correctly uploaded. Trying from scratch again.", + 'Got ${messages.length} messages (${mediaUploadIds.length} media upload files) that are not correctly uploaded. Trying from scratch again.', ); } return mediaUploadIds.isNotEmpty; // return true if there are affected } final lockingHandleMediaFile = Mutex(); -Future retryMediaUpload(bool appRestarted, {int maxRetries = 3}) async { +Future retryMediaUpload(bool appRestarted, {int maxRetries = 3}) async { if (maxRetries == 0) { - Log.error("retried media upload 3 times. abort retrying"); + Log.error('retried media upload 3 times. abort retrying'); return; } - bool retry = await lockingHandleMediaFile.protect(() async { + final retry = await lockingHandleMediaFile.protect(() async { final mediaFiles = await twonlyDB.mediaUploadsDao.getMediaUploadsForRetry(); if (mediaFiles.isEmpty) { return checkForFailedUploads(); } - Log.info("re uploading ${mediaFiles.length} media files."); + Log.info('re uploading ${mediaFiles.length} media files.'); for (final mediaFile in mediaFiles) { if (mediaFile.messageIds == null || mediaFile.metadata == null) { if (appRestarted) { @@ -168,7 +169,7 @@ Future retryMediaUpload(bool appRestarted, {int maxRetries = 3}) async { await twonlyDB.mediaUploadsDao .deleteMediaUpload(mediaFile.mediaUploadId); Log.info( - "upload can be removed, the finalized function was never called...", + 'upload can be removed, the finalized function was never called...', ); } continue; @@ -188,24 +189,23 @@ Future retryMediaUpload(bool appRestarted, {int maxRetries = 3}) async { } Future initMediaUpload() async { - return await twonlyDB.mediaUploadsDao - .insertMediaUpload(MediaUploadsCompanion()); + return twonlyDB.mediaUploadsDao + .insertMediaUpload(const MediaUploadsCompanion()); } Future addVideoToUpload(int mediaUploadId, File videoFilePath) async { - String basePath = await getMediaFilePath(mediaUploadId, "send"); - await videoFilePath.copy("$basePath.original.mp4"); - return await compressVideoIfExists(mediaUploadId); + final basePath = await getMediaFilePath(mediaUploadId, 'send'); + await videoFilePath.copy('$basePath.original.mp4'); + return compressVideoIfExists(mediaUploadId); } Future addOrModifyImageToUpload( int mediaUploadId, Uint8List imageBytes) async { Uint8List imageBytesCompressed; - Stopwatch stopwatch = Stopwatch(); - stopwatch.start(); + final stopwatch = Stopwatch()..start(); - Log.info("Raw images size in bytes: ${imageBytes.length}"); + Log.info('Raw images size in bytes: ${imageBytes.length}'); try { imageBytesCompressed = await FlutterImageCompress.compressWithList( @@ -224,11 +224,11 @@ Future addOrModifyImageToUpload( quality: 60, ); } - await writeSendMediaFile(mediaUploadId, "png", imageBytesCompressed); + await writeSendMediaFile(mediaUploadId, 'png', imageBytesCompressed); } catch (e) { - Log.error("$e"); + Log.error('$e'); // as a fall back use the original image - await writeSendMediaFile(mediaUploadId, "png", imageBytes); + await writeSendMediaFile(mediaUploadId, 'png', imageBytes); imageBytesCompressed = imageBytes; } @@ -236,7 +236,7 @@ Future addOrModifyImageToUpload( Log.info( 'Compression the image took: ${stopwatch.elapsedMilliseconds} milliseconds'); - Log.info("Raw images size in bytes: ${imageBytesCompressed.length}"); + Log.info('Raw images size in bytes: ${imageBytesCompressed.length}'); // stopwatch.reset(); // stopwatch.start(); @@ -256,16 +256,16 @@ Future addOrModifyImageToUpload( /// remove the data so it will be done again. await twonlyDB.mediaUploadsDao.updateMediaUpload( mediaUploadId, - MediaUploadsCompanion( + const MediaUploadsCompanion( encryptionData: Value(null), ), ); return imageBytesCompressed; } -Future handlePreProcessingState(MediaUpload media) async { +Future handlePreProcessingState(MediaUpload media) async { try { - final imageHandler = readSendMediaFile(media.mediaUploadId, "png"); + final imageHandler = readSendMediaFile(media.mediaUploadId, 'png'); final videoHandler = compressVideoIfExists(media.mediaUploadId); await encryptMediaFiles( media.mediaUploadId, @@ -273,34 +273,36 @@ Future handlePreProcessingState(MediaUpload media) async { videoHandler, ); } catch (e) { - Log.error("${media.mediaUploadId} got error in pre processing: $e"); + Log.error('${media.mediaUploadId} got error in pre processing: $e'); await handleUploadError(media); } } -Future encryptMediaFiles( +Future encryptMediaFiles( int mediaUploadId, - Future imageHandler, + Future imageHandler, Future? videoHandler, ) async { - Log.info("$mediaUploadId encrypting files"); - Uint8List dataToEncrypt = await imageHandler; + Log.info('$mediaUploadId encrypting files'); + // ignore: cast_nullable_to_non_nullable + var dataToEncrypt = await imageHandler; /// if there is a video wait until it is finished with compression if (videoHandler != null) { if (await videoHandler) { - Uint8List compressedVideo = await readSendMediaFile(mediaUploadId, "mp4"); + final compressedVideo = await readSendMediaFile(mediaUploadId, 'mp4'); dataToEncrypt = combineUint8Lists(dataToEncrypt, compressedVideo); } } - var state = MediaEncryptionData(); + final state = MediaEncryptionData(); final chacha20 = FlutterChacha20.poly1305Aead(); - SecretKeyData secretKey = await (await chacha20.newSecretKey()).extract(); + final secretKey = await (await chacha20.newSecretKey()).extract(); - state.encryptionKey = secretKey.bytes; - state.encryptionNonce = chacha20.newNonce(); + state + ..encryptionKey = secretKey.bytes + ..encryptionNonce = chacha20.newNonce(); final secretBox = await chacha20.encrypt( dataToEncrypt, @@ -308,46 +310,46 @@ Future encryptMediaFiles( nonce: state.encryptionNonce, ); - state.encryptionMac = secretBox.mac.bytes; - - state.sha2Hash = (await Sha256().hash(secretBox.cipherText)).bytes; + state + ..encryptionMac = secretBox.mac.bytes + ..sha2Hash = (await Sha256().hash(secretBox.cipherText)).bytes; final encryptedBytes = Uint8List.fromList(secretBox.cipherText); await writeSendMediaFile( mediaUploadId, - "encrypted", + 'encrypted', encryptedBytes, ); await twonlyDB.mediaUploadsDao.updateMediaUpload( mediaUploadId, MediaUploadsCompanion( - state: Value(UploadState.readyToUpload), + state: const Value(UploadState.readyToUpload), encryptionData: Value(state), ), ); - handleNextMediaUploadSteps(mediaUploadId); + unawaited(handleNextMediaUploadSteps(mediaUploadId)); } -Future finalizeUpload(int mediaUploadId, List contactIds, +Future finalizeUpload(int mediaUploadId, List contactIds, bool isRealTwonly, bool isVideo, bool mirrorVideo, int maxShowTime) async { - MediaUploadMetadata metadata = MediaUploadMetadata(); - metadata.contactIds = contactIds; - metadata.isRealTwonly = isRealTwonly; - metadata.messageSendAt = DateTime.now(); - metadata.isVideo = isVideo; - metadata.maxShowTime = maxShowTime; - metadata.mirrorVideo = mirrorVideo; + final metadata = MediaUploadMetadata() + ..contactIds = contactIds + ..isRealTwonly = isRealTwonly + ..messageSendAt = DateTime.now() + ..isVideo = isVideo + ..maxShowTime = maxShowTime + ..mirrorVideo = mirrorVideo; - List messageIds = []; + final messageIds = []; for (final contactId in contactIds) { - int? messageId = await twonlyDB.messagesDao.insertMessage( + final messageId = await twonlyDB.messagesDao.insertMessage( MessagesCompanion( contactId: Value(contactId), - kind: Value(MessageKind.media), + kind: const Value(MessageKind.media), sendAt: Value(metadata.messageSendAt), - downloadState: Value(DownloadState.pending), + downloadState: const Value(DownloadState.pending), mediaUploadId: Value(mediaUploadId), contentJson: Value( jsonEncode( @@ -364,14 +366,14 @@ Future finalizeUpload(int mediaUploadId, List contactIds, // de-archive contact when sending a new message await twonlyDB.contactsDao.updateContact( contactId, - ContactsCompanion( + const ContactsCompanion( archived: Value(false), ), ); if (messageId != null) { messageIds.add(messageId); } else { - Log.error("Error inserting media upload message in database."); + Log.error('Error inserting media upload message in database.'); } } @@ -383,13 +385,13 @@ Future finalizeUpload(int mediaUploadId, List contactIds, ), ); - handleNextMediaUploadSteps(mediaUploadId); + unawaited(handleNextMediaUploadSteps(mediaUploadId)); } final lockingHandleNextMediaUploadStep = Mutex(); -Future handleNextMediaUploadSteps(int mediaUploadId) async { +Future handleNextMediaUploadSteps(int mediaUploadId) async { await lockingHandleNextMediaUploadStep.protect(() async { - var mediaUpload = await twonlyDB.mediaUploadsDao + final mediaUpload = await twonlyDB.mediaUploadsDao .getMediaUploadById(mediaUploadId) .getSingleOrNull(); @@ -397,7 +399,7 @@ Future handleNextMediaUploadSteps(int mediaUploadId) async { if (mediaUpload.state == UploadState.receiverNotified || mediaUpload.state == UploadState.uploadTaskStarted) { /// Upload done and all users are notified :) - Log.info("$mediaUploadId is already done"); + Log.info('$mediaUploadId is already done'); return false; } try { @@ -414,7 +416,7 @@ Future handleNextMediaUploadSteps(int mediaUploadId) async { await handleMediaUpload(mediaUpload); } catch (e) { - Log.error("Non recoverable error while sending media file: $e"); + Log.error('Non recoverable error while sending media file: $e'); await handleUploadError(mediaUpload); } return false; @@ -427,22 +429,22 @@ Future handleNextMediaUploadSteps(int mediaUploadId) async { /// /// -Future handleUploadStatusUpdate(TaskStatusUpdate update) async { - bool failed = false; - int mediaUploadId = int.parse(update.task.taskId.replaceAll("upload_", "")); +Future handleUploadStatusUpdate(TaskStatusUpdate update) async { + var failed = false; + final mediaUploadId = int.parse(update.task.taskId.replaceAll('upload_', '')); - MediaUpload? media = await twonlyDB.mediaUploadsDao + final media = await twonlyDB.mediaUploadsDao .getMediaUploadById(mediaUploadId) .getSingleOrNull(); if (media == null) { Log.error( - "Got an upload task but no upload media in the media upload database", + 'Got an upload task but no upload media in the media upload database', ); return; } if (update.status == TaskStatus.failed || update.status == TaskStatus.canceled) { - Log.error("Upload failed: ${update.status}"); + Log.error('Upload failed: ${update.status}'); failed = true; } else if (update.status == TaskStatus.complete) { if (update.responseStatusCode == 200) { @@ -454,7 +456,7 @@ Future handleUploadStatusUpdate(TaskStatusUpdate update) async { failed = true; } Log.error( - "Got error while uploading: ${update.responseStatusCode}", + 'Got error while uploading: ${update.responseStatusCode}', ); } } @@ -463,7 +465,7 @@ Future handleUploadStatusUpdate(TaskStatusUpdate update) async { for (final messageId in media.messageIds!) { await twonlyDB.messagesDao.updateMessageByMessageId( messageId, - MessagesCompanion( + const MessagesCompanion( acknowledgeByServer: Value(true), errorWhileSending: Value(true), ), @@ -474,13 +476,13 @@ Future handleUploadStatusUpdate(TaskStatusUpdate update) async { 'Status update for ${update.task.taskId} with status ${update.status}'); } -Future handleUploadSuccess(MediaUpload media) async { - Log.info("Upload of ${media.mediaUploadId} success!"); +Future handleUploadSuccess(MediaUpload media) async { + Log.info('Upload of ${media.mediaUploadId} success!'); currentUploadTasks.remove(media.mediaUploadId); await twonlyDB.mediaUploadsDao.updateMediaUpload( media.mediaUploadId, - MediaUploadsCompanion( + const MediaUploadsCompanion( state: Value(UploadState.receiverNotified), ), ); @@ -488,7 +490,7 @@ Future handleUploadSuccess(MediaUpload media) async { for (final messageId in media.messageIds!) { await twonlyDB.messagesDao.updateMessageByMessageId( messageId, - MessagesCompanion( + const MessagesCompanion( acknowledgeByServer: Value(true), errorWhileSending: Value(false), ), @@ -496,13 +498,13 @@ Future handleUploadSuccess(MediaUpload media) async { } } -Future handleUploadError(MediaUpload mediaUpload) async { +Future handleUploadError(MediaUpload mediaUpload) async { // if the messageIds are already there notify the user about this error... if (mediaUpload.messageIds != null) { - for (int messageId in mediaUpload.messageIds!) { + for (final messageId in mediaUpload.messageIds!) { await twonlyDB.messagesDao.updateMessageByMessageId( messageId, - MessagesCompanion( + const MessagesCompanion( errorWhileSending: Value(true), ), ); @@ -511,20 +513,20 @@ Future handleUploadError(MediaUpload mediaUpload) async { await twonlyDB.mediaUploadsDao.deleteMediaUpload(mediaUpload.mediaUploadId); } -Future handleMediaUpload(MediaUpload media) async { - Uint8List bytesToUpload = - await readSendMediaFile(media.mediaUploadId, "encrypted"); +Future handleMediaUpload(MediaUpload media) async { + final bytesToUpload = + await readSendMediaFile(media.mediaUploadId, 'encrypted'); if (media.messageIds == null) return; - List messageIds = media.messageIds!; + final messageIds = media.messageIds!; - List downloadTokens = []; + final downloadTokens = []; - List messagesOnSuccess = []; + final messagesOnSuccess = []; for (var i = 0; i < messageIds.length; i++) { - Message? message = await twonlyDB.messagesDao + final message = await twonlyDB.messagesDao .getMessageByMessageId(messageIds[i]) .getSingleOrNull(); if (message == null) continue; @@ -536,7 +538,7 @@ Future handleMediaUpload(MediaUpload media) async { final downloadToken = createDownloadToken(); - MessageJson msg = MessageJson( + final msg = MessageJson( kind: MessageKind.media, messageSenderId: messageIds[i], content: MediaMessageContent( @@ -552,19 +554,19 @@ Future handleMediaUpload(MediaUpload media) async { timestamp: media.metadata!.messageSendAt, ); - Uint8List plaintextContent = + final plaintextContent = Uint8List.fromList(gzip.encode(utf8.encode(jsonEncode(msg.toJson())))); - Contact? contact = await twonlyDB.contactsDao + final contact = await twonlyDB.contactsDao .getContactByUserId(message.contactId) .getSingleOrNull(); if (contact == null || contact.deleted) { Log.warn( - "Contact deleted ${message.contactId} or not found in database."); + 'Contact deleted ${message.contactId} or not found in database.'); await twonlyDB.messagesDao.updateMessageByMessageId( message.messageId, - MessagesCompanion(errorWhileSending: Value(true)), + const MessagesCompanion(errorWhileSending: Value(true)), ); continue; } @@ -575,14 +577,14 @@ Future handleMediaUpload(MediaUpload media) async { message.sendAt, ); - Uint8List? encryptedBytes = await signalEncryptMessage( + final encryptedBytes = await signalEncryptMessage( message.contactId, plaintextContent, ); if (encryptedBytes == null) continue; - var messageOnSuccess = TextMessage() + final messageOnSuccess = TextMessage() ..body = encryptedBytes ..userId = Int64(message.contactId); @@ -615,29 +617,29 @@ Future handleMediaUpload(MediaUpload media) async { final uploadRequestBytes = uploadRequest.writeToBuffer(); - String? apiAuthTokenRaw = - await FlutterSecureStorage().read(key: SecureStorageKeys.apiAuthToken); + final apiAuthTokenRaw = await const FlutterSecureStorage() + .read(key: SecureStorageKeys.apiAuthToken); if (apiAuthTokenRaw == null) { - Log.error("api auth token not defined."); + Log.error('api auth token not defined.'); return; } - String apiAuthToken = uint8ListToHex(base64Decode(apiAuthTokenRaw)); + final apiAuthToken = uint8ListToHex(base64Decode(apiAuthTokenRaw)); - File uploadRequestFile = await writeSendMediaFile( + final uploadRequestFile = await writeSendMediaFile( media.mediaUploadId, - "upload", + 'upload', uploadRequestBytes, ); - String apiUrl = - "http${apiService.apiSecure}://${apiService.apiHost}/api/upload"; + final apiUrl = + 'http${apiService.apiSecure}://${apiService.apiHost}/api/upload'; try { - Log.info("Starting upload from ${media.mediaUploadId}"); + Log.info('Starting upload from ${media.mediaUploadId}'); final task = UploadTask.fromFile( - taskId: "upload_${media.mediaUploadId}", - displayName: (media.metadata?.isVideo ?? false) ? "image" : "video", + taskId: 'upload_${media.mediaUploadId}', + displayName: (media.metadata?.isVideo ?? false) ? 'image' : 'video', file: uploadRequestFile, url: apiUrl, priority: 0, @@ -652,62 +654,62 @@ Future handleMediaUpload(MediaUpload media) async { try { await uploadFileFast(media, uploadRequestBytes, apiUrl, apiAuthToken); } catch (e) { - Log.error("Fast upload failed: $e. Using slow method directly."); - enqueueUploadTask(media.mediaUploadId); + Log.error('Fast upload failed: $e. Using slow method directly.'); + await enqueueUploadTask(media.mediaUploadId); } } catch (e) { - Log.error("Exception during upload: $e"); + Log.error('Exception during upload: $e'); } } Map currentUploadTasks = {}; -Future enqueueUploadTask(int mediaUploadId) async { +Future enqueueUploadTask(int mediaUploadId) async { if (currentUploadTasks[mediaUploadId] == null) { - Log.info("could not enqueue upload task: $mediaUploadId"); + Log.info('could not enqueue upload task: $mediaUploadId'); return; } - Log.info("Enqueue upload task: $mediaUploadId"); + Log.info('Enqueue upload task: $mediaUploadId'); await FileDownloader().enqueue(currentUploadTasks[mediaUploadId]!); currentUploadTasks.remove(mediaUploadId); await twonlyDB.mediaUploadsDao.updateMediaUpload( mediaUploadId, - MediaUploadsCompanion( + const MediaUploadsCompanion( state: Value(UploadState.uploadTaskStarted), ), ); } -Future handleUploadWhenAppGoesBackground() async { +Future handleUploadWhenAppGoesBackground() async { if (currentUploadTasks.keys.isEmpty) { return; } - Log.info("App goes into background. Enqueue uploads to the background."); + Log.info('App goes into background. Enqueue uploads to the background.'); final keys = currentUploadTasks.keys.toList(); for (final key in keys) { enqueueUploadTask(key); } } -Future uploadFileFast( +Future uploadFileFast( MediaUpload media, Uint8List uploadRequestFile, String apiUrl, String apiAuthToken, ) async { - var requestMultipart = http.MultipartRequest( - "POST", + final requestMultipart = http.MultipartRequest( + 'POST', Uri.parse(apiUrl), ); requestMultipart.headers['x-twonly-auth-token'] = apiAuthToken; requestMultipart.files.add(http.MultipartFile.fromBytes( - "file", + 'file', uploadRequestFile, - filename: "upload", + filename: 'upload', )); final response = await requestMultipart.send(); @@ -721,9 +723,9 @@ Future uploadFileFast( } Future compressVideoIfExists(int mediaUploadId) async { - String basePath = await getMediaFilePath(mediaUploadId, "send"); - File videoOriginalFile = File("$basePath.original.mp4"); - File videoCompressedFile = File("$basePath.mp4"); + final basePath = await getMediaFilePath(mediaUploadId, 'send'); + final videoOriginalFile = File('$basePath.original.mp4'); + final videoCompressedFile = File('$basePath.mp4'); if (videoCompressedFile.existsSync()) { // file is already compressed and exists @@ -735,38 +737,35 @@ Future compressVideoIfExists(int mediaUploadId) async { return false; } - Stopwatch stopwatch = Stopwatch(); - stopwatch.start(); + final stopwatch = Stopwatch()..start(); MediaInfo? mediaInfo; try { mediaInfo = await VideoCompress.compressVideo( videoOriginalFile.path, quality: VideoQuality.Res1280x720Quality, - deleteOrigin: false, includeAudio: true, // https://github.com/jonataslaw/VideoCompress/issues/184 ); - Log.info("Video has now size of ${mediaInfo!.filesize} bytes."); + Log.info('Video has now size of ${mediaInfo!.filesize} bytes.'); if (mediaInfo.filesize! >= 30 * 1000 * 1000) { // if the media file is over 20MB compress it with low quality mediaInfo = await VideoCompress.compressVideo( videoOriginalFile.path, quality: VideoQuality.Res960x540Quality, - deleteOrigin: false, includeAudio: true, ); } } catch (e) { - Log.error("during video compression: $e"); + Log.error('during video compression: $e'); } stopwatch.stop(); - Log.info("It took ${stopwatch.elapsedMilliseconds}ms to compress the video"); + Log.info('It took ${stopwatch.elapsedMilliseconds}ms to compress the video'); if (mediaInfo == null) { - Log.error("could not compress video."); + Log.error('could not compress video.'); // as a fall back use the non compressed version await videoOriginalFile.copy(videoCompressedFile.path); await videoOriginalFile.delete(); @@ -780,26 +779,26 @@ Future compressVideoIfExists(int mediaUploadId) async { /// --- helper functions --- Future readSendMediaFile(int mediaUploadId, String type) async { - String basePath = await getMediaFilePath(mediaUploadId, "send"); - File file = File("$basePath.$type"); - if (!await file.exists()) { - throw Exception("$file not found"); + final basePath = await getMediaFilePath(mediaUploadId, 'send'); + final file = File('$basePath.$type'); + if (!file.existsSync()) { + throw Exception('$file not found'); } - return await file.readAsBytes(); + return file.readAsBytes(); } Future writeSendMediaFile( int mediaUploadId, String type, Uint8List data) async { - String basePath = await getMediaFilePath(mediaUploadId, "send"); - File file = File("$basePath.$type"); + final basePath = await getMediaFilePath(mediaUploadId, 'send'); + final file = File('$basePath.$type'); await file.writeAsBytes(data); return file; } Future deleteSendMediaFile(int mediaUploadId, String type) async { - String basePath = await getMediaFilePath(mediaUploadId, "send"); - File file = File("$basePath.$type"); - if (await file.exists()) { + final basePath = await getMediaFilePath(mediaUploadId, 'send'); + final file = File('$basePath.$type'); + if (file.existsSync()) { await file.delete(); } } @@ -807,7 +806,7 @@ Future deleteSendMediaFile(int mediaUploadId, String type) async { Future getMediaFilePath(dynamic mediaId, String type) async { final basedir = await getApplicationSupportDirectory(); final mediaSendDir = Directory(join(basedir.path, 'media', type)); - if (!await mediaSendDir.exists()) { + if (!mediaSendDir.existsSync()) { await mediaSendDir.create(recursive: true); } return join(mediaSendDir.path, '$mediaId'); @@ -816,7 +815,7 @@ Future getMediaFilePath(dynamic mediaId, String type) async { Future getMediaBaseFilePath(String type) async { final basedir = await getApplicationSupportDirectory(); final mediaSendDir = Directory(join(basedir.path, 'media', type)); - if (!await mediaSendDir.exists()) { + if (!mediaSendDir.existsSync()) { await mediaSendDir.create(recursive: true); } return mediaSendDir.path; @@ -825,18 +824,15 @@ Future getMediaBaseFilePath(String type) async { /// combines two utf8 list Uint8List combineUint8Lists(Uint8List list1, Uint8List list2) { final combinedLength = 4 + list1.length + list2.length; - final combinedList = Uint8List(combinedLength); - final byteData = ByteData.sublistView(combinedList); - byteData.setInt32( - 0, list1.length, Endian.big); // Store size in big-endian format - combinedList.setRange(4, 4 + list1.length, list1); - combinedList.setRange(4 + list1.length, combinedLength, list2); + final combinedList = Uint8List(combinedLength) + ..setRange(4, 4 + list1.length, list1) + ..setRange(4 + list1.length, combinedLength, list2); return combinedList; } List extractUint8Lists(Uint8List combinedList) { final byteData = ByteData.sublistView(combinedList); - final sizeOfList1 = byteData.getInt32(0, Endian.big); + final sizeOfList1 = byteData.getInt32(0); final list1 = Uint8List.view(combinedList.buffer, 4, sizeOfList1); final list2 = Uint8List.view(combinedList.buffer, 4 + sizeOfList1, combinedList.lengthInBytes - 4 - sizeOfList1); @@ -845,7 +841,7 @@ List extractUint8Lists(Uint8List combinedList) { Future purgeSendMediaFiles() async { final basedir = await getApplicationSupportDirectory(); - final directory = Directory(join(basedir.path, 'media', "send")); + final directory = Directory(join(basedir.path, 'media', 'send')); await purgeMediaFiles(directory); } @@ -858,10 +854,10 @@ Uint8List hexToUint8List(String hex) => Uint8List.fromList(List.generate( (i) => int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16))); Uint8List createDownloadToken() { - final Random random = Random(); + final random = Random(); - Uint8List token = Uint8List(32); - for (int j = 0; j < 32; j++) { + final token = Uint8List(32); + for (var j = 0; j < 32; j++) { token[j] = random.nextInt(256); // Generate a random byte (0-255) } return token; diff --git a/lib/src/services/api/messages.dart b/lib/src/services/api/messages.dart index 7c986ed..34eeede 100644 --- a/lib/src/services/api/messages.dart +++ b/lib/src/services/api/messages.dart @@ -1,20 +1,19 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; + import 'package:cryptography_plus/cryptography_plus.dart'; import 'package:drift/drift.dart'; import 'package:fixnum/fixnum.dart'; import 'package:mutex/mutex.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/model/json/userdata.dart'; import 'package:twonly/src/model/protobuf/api/websocket/error.pb.dart'; import 'package:twonly/src/model/protobuf/push_notification/push_notification.pb.dart'; import 'package:twonly/src/services/api/server_messages.dart' show messageGetsAck; -import 'package:twonly/src/services/api/utils.dart'; import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; import 'package:twonly/src/services/signal/encryption.signal.dart'; import 'package:twonly/src/utils/log.dart'; @@ -22,12 +21,12 @@ import 'package:twonly/src/utils/storage.dart'; final lockRetransmission = Mutex(); -Future tryTransmitMessages() async { - return await lockRetransmission.protect(() async { +Future tryTransmitMessages() async { + return lockRetransmission.protect(() async { final retransIds = await twonlyDB.messageRetransmissionDao.getRetransmitAbleMessages(); - Log.info("Retransmitting ${retransIds.length} text messages"); + Log.info('Retransmitting ${retransIds.length} text messages'); if (retransIds.isEmpty) return; @@ -37,53 +36,51 @@ Future tryTransmitMessages() async { }); } -Future sendRetransmitMessage(int retransId) async { +Future sendRetransmitMessage(int retransId) async { try { - MessageRetransmission? retrans = await twonlyDB.messageRetransmissionDao + final retrans = await twonlyDB.messageRetransmissionDao .getRetransmissionById(retransId) .getSingleOrNull(); if (retrans == null) { - Log.error("$retransId not found in database"); + Log.error('$retransId not found in database'); return; } if (retrans.acknowledgeByServerAt != null) { - Log.error("$retransId message already retransmitted"); + Log.error('$retransId message already retransmitted'); return; } - MessageJson json = MessageJson.fromJson( - jsonDecode( - utf8.decode( - gzip.decode(retrans.plaintextContent), - ), + final json = MessageJson.fromJson(jsonDecode( + utf8.decode( + gzip.decode(retrans.plaintextContent), ), - ); + ) as Map); - Log.info("Retransmitting $retransId: ${json.kind} to ${retrans.contactId}"); + Log.info('Retransmitting $retransId: ${json.kind} to ${retrans.contactId}'); - Contact? contact = await twonlyDB.contactsDao + final contact = await twonlyDB.contactsDao .getContactByUserId(retrans.contactId) .getSingleOrNull(); if (contact == null || contact.deleted) { - Log.warn("Contact deleted $retransId or not found in database."); + Log.warn('Contact deleted $retransId or not found in database.'); if (retrans.messageId != null) { await twonlyDB.messagesDao.updateMessageByMessageId( retrans.messageId!, - MessagesCompanion(errorWhileSending: Value(true)), + const MessagesCompanion(errorWhileSending: Value(true)), ); } return; } - Uint8List? encryptedBytes = await signalEncryptMessage( + final encryptedBytes = await signalEncryptMessage( retrans.contactId, retrans.plaintextContent, ); if (encryptedBytes == null) { - Log.error("Could not encrypt the message. Aborting and trying again."); + Log.error('Could not encrypt the message. Aborting and trying again.'); return; } @@ -96,27 +93,27 @@ Future sendRetransmitMessage(int retransId) async { ), ); - Result resp = await apiService.sendTextMessage( + final resp = await apiService.sendTextMessage( retrans.contactId, encryptedBytes, retrans.pushData, ); - bool retry = true; + var retry = true; if (resp.isError) { - Log.error("Could not retransmit message."); + Log.error('Could not retransmit message.'); if (resp.error == ErrorCode.UserIdNotFound) { retry = false; if (retrans.messageId != null) { await twonlyDB.messagesDao.updateMessageByMessageId( retrans.messageId!, - MessagesCompanion(errorWhileSending: Value(true)), + const MessagesCompanion(errorWhileSending: Value(true)), ); } await twonlyDB.contactsDao.updateContact( retrans.contactId, - ContactsCompanion(deleted: Value(true)), + const ContactsCompanion(deleted: Value(true)), ); } } @@ -126,7 +123,7 @@ Future sendRetransmitMessage(int retransId) async { if (retrans.messageId != null) { await twonlyDB.messagesDao.updateMessageByMessageId( retrans.messageId!, - MessagesCompanion( + const MessagesCompanion( acknowledgeByServer: Value(true), errorWhileSending: Value(false), ), @@ -148,13 +145,13 @@ Future sendRetransmitMessage(int retransId) async { } } } catch (e) { - Log.error("error resending message: $e"); + Log.error('error resending message: $e'); await twonlyDB.messageRetransmissionDao.deleteRetransmissionById(retransId); } } // encrypts and stores the message and then sends it in the background -Future encryptAndSendMessageAsync( +Future encryptAndSendMessageAsync( int? messageId, int userId, MessageJson msg, { @@ -169,7 +166,8 @@ Future encryptAndSendMessageAsync( pushData = await getPushData(userId, pushNotification); } - int? retransId = await twonlyDB.messageRetransmissionDao.insertRetransmission( + final retransId = + await twonlyDB.messageRetransmissionDao.insertRetransmission( MessageRetransmissionsCompanion( contactId: Value(userId), messageId: Value(messageId), @@ -179,13 +177,13 @@ Future encryptAndSendMessageAsync( ); if (retransId == null) { - Log.error("Could not insert the message into the retransmission database"); + Log.error('Could not insert the message into the retransmission database'); return; } msg.retransId = retransId; - Uint8List plaintextContent = + final plaintextContent = Uint8List.fromList(gzip.encode(utf8.encode(jsonEncode(msg.toJson())))); await twonlyDB.messageRetransmissionDao.updateRetransmission( @@ -194,29 +192,29 @@ Future encryptAndSendMessageAsync( plaintextContent: Value(plaintextContent))); // this can now be done in the background... - sendRetransmitMessage(retransId); + unawaited(sendRetransmitMessage(retransId)); } -Future sendTextMessage( +Future sendTextMessage( int target, TextMessageContent content, PushNotification? pushNotification, ) async { - DateTime messageSendAt = DateTime.now(); + final messageSendAt = DateTime.now(); DateTime? openedAt; if (pushNotification != null && pushNotification.hasReactionContent()) { openedAt = DateTime.now(); } - int? messageId = await twonlyDB.messagesDao.insertMessage( + final messageId = await twonlyDB.messagesDao.insertMessage( MessagesCompanion( contactId: Value(target), - kind: Value(MessageKind.textMessage), + kind: const Value(MessageKind.textMessage), sendAt: Value(messageSendAt), responseToOtherMessageId: Value(content.responseToMessageId), responseToMessageId: Value(content.responseToOtherMessageId), - downloadState: Value(DownloadState.downloaded), + downloadState: const Value(DownloadState.downloaded), openedAt: Value(openedAt), contentJson: Value( jsonEncode(content.toJson()), @@ -230,7 +228,7 @@ Future sendTextMessage( pushNotification.messageId = Int64(messageId); } - MessageJson msg = MessageJson( + final msg = MessageJson( kind: MessageKind.textMessage, messageSenderId: messageId, content: content, @@ -245,11 +243,11 @@ Future sendTextMessage( ); } -Future notifyContactAboutOpeningMessage( +Future notifyContactAboutOpeningMessage( int fromUserId, List messageOtherIds, ) async { - int biggestMessageId = messageOtherIds.first; + var biggestMessageId = messageOtherIds.first; for (final messageOtherId in messageOtherIds) { if (messageOtherId > biggestMessageId) biggestMessageId = messageOtherId; @@ -267,17 +265,16 @@ Future notifyContactAboutOpeningMessage( await updateLastMessageId(fromUserId, biggestMessageId); } -Future notifyContactsAboutProfileChange() async { - List contacts = - await twonlyDB.contactsDao.getAllNotBlockedContacts(); +Future notifyContactsAboutProfileChange() async { + final contacts = await twonlyDB.contactsDao.getAllNotBlockedContacts(); - UserData? user = await getUser(); + final user = await getUser(); if (user == null) return; if (user.avatarSvg == null) return; - for (Contact contact in contacts) { + for (final contact in contacts) { if (contact.myAvatarCounter < user.avatarCounter) { - twonlyDB.contactsDao.updateContact( + await twonlyDB.contactsDao.updateContact( contact.userId, ContactsCompanion( myAvatarCounter: Value(user.avatarCounter), diff --git a/lib/src/services/api/server_messages.dart b/lib/src/services/api/server_messages.dart index fde09b3..44f135f 100644 --- a/lib/src/services/api/server_messages.dart +++ b/lib/src/services/api/server_messages.dart @@ -1,14 +1,15 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; + import 'package:cryptography_plus/cryptography_plus.dart'; import 'package:drift/drift.dart'; import 'package:fixnum/fixnum.dart'; -import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; import 'package:mutex/mutex.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/tables/media_uploads_table.dart'; -import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; import 'package:twonly/src/model/protobuf/api/websocket/client_to_server.pb.dart' as client; @@ -16,10 +17,10 @@ import 'package:twonly/src/model/protobuf/api/websocket/client_to_server.pb.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/services/api/media_download.dart'; import 'package:twonly/src/services/api/media_upload.dart'; import 'package:twonly/src/services/api/messages.dart'; import 'package:twonly/src/services/api/utils.dart'; -import 'package:twonly/src/services/api/media_download.dart'; import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; import 'package:twonly/src/services/notifications/setup.notifications.dart'; import 'package:twonly/src/services/signal/encryption.signal.dart'; @@ -31,7 +32,7 @@ import 'package:twonly/src/views/components/animate_icon.dart'; final lockHandleServerMessage = Mutex(); -Future handleServerMessage(server.ServerToClient msg) async { +Future handleServerMessage(server.ServerToClient msg) async { return lockHandleServerMessage.protect(() async { client.Response? response; @@ -39,34 +40,35 @@ Future handleServerMessage(server.ServerToClient msg) async { if (msg.v0.hasRequestNewPreKeys()) { response = await handleRequestNewPreKey(); } else if (msg.v0.hasNewMessage()) { - Uint8List body = Uint8List.fromList(msg.v0.newMessage.body); - int fromUserId = msg.v0.newMessage.fromUserId.toInt(); + final body = Uint8List.fromList(msg.v0.newMessage.body); + final fromUserId = msg.v0.newMessage.fromUserId.toInt(); response = await handleNewMessage(fromUserId, body); } else { - Log.error("Got a new message from the server: $msg"); + Log.error('Got a new message from the server: $msg'); response = client.Response()..error = ErrorCode.InternalError; } } catch (e) { response = client.Response()..error = ErrorCode.InternalError; } - var v0 = client.V0() + final v0 = client.V0() ..seq = msg.v0.seq ..response = response; - apiService.sendResponse(ClientToServer()..v0 = v0); + await apiService.sendResponse(ClientToServer()..v0 = v0); }); } -DateTime lastSignalDecryptMessage = DateTime.now().subtract(Duration(hours: 1)); -DateTime lastPushKeyRequest = DateTime.now().subtract(Duration(hours: 1)); +DateTime lastSignalDecryptMessage = + DateTime.now().subtract(const Duration(hours: 1)); +DateTime lastPushKeyRequest = DateTime.now().subtract(const Duration(hours: 1)); bool messageGetsAck(MessageKind kind) { return kind != MessageKind.pushKey && kind != MessageKind.ack; } Future handleNewMessage(int fromUserId, Uint8List body) async { - MessageJson? message = await signalDecryptMessage(fromUserId, body); + final message = await signalDecryptMessage(fromUserId, body); if (message == null) { final encryptedHash = (await Sha256().hash(body)).bytes; await encryptAndSendMessageAsync( @@ -79,17 +81,17 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { ), ); - Log.error("Could not decrypt others message!"); + Log.error('Could not decrypt others message!'); // Message is not valid, so server can delete it - var ok = client.Response_Ok()..none = true; + final ok = client.Response_Ok()..none = true; return client.Response()..ok = ok; } - Log.info("Got: ${message.kind} from $fromUserId"); + Log.info('Got: ${message.kind} from $fromUserId'); if (messageGetsAck(message.kind) && message.retransId != null) { - Log.info("Sending ACK for ${message.kind}"); + Log.info('Sending ACK for ${message.kind}'); /// ACK every message await encryptAndSendMessageAsync( @@ -111,7 +113,7 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { final content = message.content; if (content is AckContent) { if (content.messageIdToAck != null) { - final update = MessagesCompanion( + const update = MessagesCompanion( acknowledgeByUser: Value(true), errorWhileSending: Value(false), ); @@ -125,10 +127,9 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { await twonlyDB.messageRetransmissionDao .deleteRetransmissionById(content.retransIdToAck); } - break; case MessageKind.signalDecryptError: Log.error( - "Got signal decrypt error from other user! Sending all non ACK messages again."); + 'Got signal decrypt error from other user! Sending all non ACK messages again.'); final content = message.content; if (content is SignalDecryptErrorContent) { @@ -140,16 +141,15 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { final message = await twonlyDB.messageRetransmissionDao .getRetransmissionFromHash(fromUserId, hash); if (message != null) { - sendRetransmitMessage(message.retransmissionId); + unawaited(sendRetransmitMessage(message.retransmissionId)); } } - break; case MessageKind.contactRequest: return handleContactRequest(fromUserId, message); case MessageKind.flameSync: - Contact? contact = await twonlyDB.contactsDao + final contact = await twonlyDB.contactsDao .getContactByUserId(fromUserId) .getSingleOrNull(); if (contact != null && contact.lastFlameCounterChange != null) { @@ -188,12 +188,12 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { openedMessage.mediaRetransmissionState == MediaRetransmitting.none && openedMessage.sendAt - .isAfter(DateTime.now().subtract(Duration(days: 2)))) { + .isAfter(DateTime.now().subtract(const Duration(days: 2)))) { // reset the media upload state to pending, // this will cause the media to be re-encrypted again - twonlyDB.mediaUploadsDao.updateMediaUpload( + await twonlyDB.mediaUploadsDao.updateMediaUpload( openedMessage.mediaUploadId!, - MediaUploadsCompanion( + const MediaUploadsCompanion( state: Value( UploadState.pending, ), @@ -203,18 +203,18 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { await twonlyDB.messagesDao.updateMessageByOtherUser( fromUserId, message.messageReceiverId!, - MessagesCompanion( + const MessagesCompanion( downloadState: Value(DownloadState.pending), mediaRetransmissionState: Value(MediaRetransmitting.retransmitted), ), ); - retryMediaUpload(false); + unawaited(retryMediaUpload(false)); } else { await twonlyDB.messagesDao.updateMessageByOtherUser( fromUserId, message.messageReceiverId!, - MessagesCompanion( + const MessagesCompanion( errorWhileSending: Value(true), ), ); @@ -226,7 +226,7 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { if (message.messageReceiverId != null) { final update = MessagesCompanion( openedAt: Value(message.timestamp), - errorWhileSending: Value(false), + errorWhileSending: const Value(false), ); await twonlyDB.messagesDao.updateMessageByOtherUser( fromUserId, @@ -243,20 +243,17 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { ); } } - break; case MessageKind.rejectRequest: await deleteContact(fromUserId); - break; case MessageKind.acceptRequest: - final update = ContactsCompanion(accepted: Value(true)); + const update = ContactsCompanion(accepted: Value(true)); await twonlyDB.contactsDao.updateContact(fromUserId, update); - notifyContactsAboutProfileChange(); - break; + unawaited(notifyContactsAboutProfileChange()); case MessageKind.profileChange: - var content = message.content; + final content = message.content; if (content is ProfileContent) { final update = ContactsCompanion( avatarSvg: Value(content.avatarSvg), @@ -264,14 +261,13 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { ); await twonlyDB.contactsDao.updateContact(fromUserId, update); } - createPushAvatars(); - break; + unawaited(createPushAvatars()); case MessageKind.requestPushKey: if (lastPushKeyRequest - .isBefore(DateTime.now().subtract(Duration(seconds: 60)))) { + .isBefore(DateTime.now().subtract(const Duration(seconds: 60)))) { lastPushKeyRequest = DateTime.now(); - setupNotificationWithUsers(forceContact: fromUserId); + unawaited(setupNotificationWithUsers(forceContact: fromUserId)); } case MessageKind.pushKey: @@ -282,14 +278,15 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { } } + // ignore: no_default_cases default: if (message.kind != MessageKind.textMessage && message.kind != MessageKind.media && message.kind != MessageKind.storedMediaFile && message.kind != MessageKind.reopenedMedia) { - Log.error("Got unknown MessageKind $message"); + Log.error('Got unknown MessageKind $message'); } else if (message.messageSenderId == null) { - Log.error("Messageid not defined $message"); + Log.error('Messageid not defined $message'); } else { if (message.kind == MessageKind.storedMediaFile) { if (message.messageReceiverId != null) { @@ -297,7 +294,7 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { await twonlyDB.messagesDao.updateMessageByOtherUser( fromUserId, message.messageReceiverId!, - MessagesCompanion( + const MessagesCompanion( mediaStored: Value(true), errorWhileSending: Value(false), ), @@ -308,11 +305,11 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { .getSingleOrNull(); if (msg != null && msg.mediaUploadId != null) { final filePath = - await getMediaFilePath(msg.mediaUploadId, "send"); - if (filePath.contains("mp4")) { - createThumbnailsForVideo(File(filePath)); + await getMediaFilePath(msg.mediaUploadId, 'send'); + if (filePath.contains('mp4')) { + unawaited(createThumbnailsForVideo(File(filePath))); } else { - createThumbnailsForImage(File(filePath)); + unawaited(createThumbnailsForImage(File(filePath))); } } } @@ -330,8 +327,8 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { .deleteMessagesByMessageId(openedMessage.messageId); } else { Log.error( - "Got a duplicated message from other user: ${message.messageSenderId!}"); - var ok = client.Response_Ok()..none = true; + 'Got a duplicated message from other user: ${message.messageSenderId!}'); + final ok = client.Response_Ok()..none = true; return client.Response()..ok = ok; } } @@ -340,7 +337,7 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { int? responseToOtherMessageId; int? messageId; - bool acknowledgeByUser = false; + var acknowledgeByUser = false; DateTime? openedAt; if (message.kind == MessageKind.reopenedMedia) { @@ -369,7 +366,7 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { fromUserId, responseToMessageId, MessagesCompanion( - errorWhileSending: Value(false), + errorWhileSending: const Value(false), openedAt: Value( DateTime.now(), ), // when a user reacted to the media file, it should be marked as opened @@ -377,13 +374,13 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { ); } - String contentJson = jsonEncode(content.toJson()); + final contentJson = jsonEncode(content.toJson()); final update = MessagesCompanion( contactId: Value(fromUserId), kind: Value(message.kind), messageOtherId: Value(message.messageSenderId), contentJson: Value(contentJson), - acknowledgeByServer: Value(true), + acknowledgeByServer: const Value(true), acknowledgeByUser: Value(acknowledgeByUser), responseToMessageId: Value(responseToMessageId), responseToOtherMessageId: Value(responseToOtherMessageId), @@ -403,7 +400,7 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { } if (message.kind == MessageKind.media) { - twonlyDB.contactsDao.incFlameCounter( + await twonlyDB.contactsDao.incFlameCounter( fromUserId, true, message.timestamp, @@ -413,37 +410,37 @@ Future handleNewMessage(int fromUserId, Uint8List body) async { .getMessageByMessageId(messageId) .getSingleOrNull(); if (msg != null) { - startDownloadMedia(msg, false); + unawaited(startDownloadMedia(msg, false)); } } } else { - Log.error("Content is not defined $message"); + Log.error('Content is not defined $message'); } // unarchive contact when receiving a new message await twonlyDB.contactsDao.updateContact( fromUserId, - ContactsCompanion( + const ContactsCompanion( archived: Value(false), ), ); } } - var ok = client.Response_Ok()..none = true; + final ok = client.Response_Ok()..none = true; return client.Response()..ok = ok; } Future handleRequestNewPreKey() async { - List localPreKeys = await signalGetPreKeys(); + final localPreKeys = await signalGetPreKeys(); - List prekeysList = []; - for (int i = 0; i < localPreKeys.length; i++) { + final prekeysList = []; + for (var i = 0; i < localPreKeys.length; i++) { prekeysList.add(client.Response_PreKey() ..id = Int64(localPreKeys[i].id) ..prekey = localPreKeys[i].getKeyPair().publicKey.serialize()); } - var prekeys = client.Response_Prekeys(prekeys: prekeysList); - var ok = client.Response_Ok()..prekeys = prekeys; + final prekeys = client.Response_Prekeys(prekeys: prekeysList); + final ok = client.Response_Ok()..prekeys = prekeys; return client.Response()..ok = ok; } @@ -451,18 +448,18 @@ Future handleContactRequest( int fromUserId, MessageJson message) async { // request the username by the server so an attacker can not // forge the displayed username in the contact request - Result username = await apiService.getUsername(fromUserId); + final username = await apiService.getUsername(fromUserId); if (username.isSuccess) { - Uint8List name = username.value.userdata.username; + final name = username.value.userdata.username as Uint8List; await twonlyDB.contactsDao.insertContact( ContactsCompanion( username: Value(utf8.decode(name)), userId: Value(fromUserId), - requested: Value(true), + requested: const Value(true), ), ); } await setupNotificationWithUsers(); - var ok = client.Response_Ok()..none = true; + final ok = client.Response_Ok()..none = true; return client.Response()..ok = ok; } diff --git a/lib/src/services/api/utils.dart b/lib/src/services/api/utils.dart index 8879114..ec74964 100644 --- a/lib/src/services/api/utils.dart +++ b/lib/src/services/api/utils.dart @@ -14,16 +14,17 @@ import 'package:twonly/src/services/api/messages.dart'; import 'package:twonly/src/services/signal/session.signal.dart'; class Result { + Result.error(this.error) : value = null; + Result.success(this.value) : error = null; + final T? value; final E? error; bool get isSuccess => value != null; bool get isError => error != null; - - Result.success(this.value) : error = null; - Result.error(this.error) : value = null; } +// ignore: strict_raw_type Result asResult(server.ServerToClient? msg) { if (msg == null) { return Result.error(ErrorCode.InternalError); @@ -44,20 +45,20 @@ ClientToServer createClientToServerFromHandshake(Handshake handshake) { ClientToServer createClientToServerFromApplicationData( ApplicationData applicationData) { - var v0 = client.V0() + final v0 = client.V0() ..seq = Int64(0) ..applicationdata = applicationData; return ClientToServer()..v0 = v0; } -Future deleteContact(int contactId) async { +Future deleteContact(int contactId) async { await twonlyDB.messagesDao.deleteAllMessagesByContactId(contactId); await twonlyDB.signalDao.deleteAllByContactId(contactId); await deleteSessionWithTarget(contactId); await twonlyDB.contactsDao.deleteContactByUserId(contactId); } -Future rejectUser(int contactId) async { +Future rejectUser(int contactId) async { await encryptAndSendMessageAsync( null, contactId, @@ -69,10 +70,10 @@ Future rejectUser(int contactId) async { ); } -Future handleMediaError(Message message) async { +Future handleMediaError(Message message) async { await twonlyDB.messagesDao.updateMessageByMessageId( message.messageId, - MessagesCompanion( + const MessagesCompanion( errorWhileSending: Value(true), mediaRetransmissionState: Value( MediaRetransmitting.requested, @@ -80,7 +81,7 @@ Future handleMediaError(Message message) async { ), ); if (message.messageOtherId != null) { - encryptAndSendMessageAsync( + await encryptAndSendMessageAsync( null, message.contactId, MessageJson( diff --git a/lib/src/services/fcm.service.dart b/lib/src/services/fcm.service.dart index 4b2a1b4..303fc68 100644 --- a/lib/src/services/fcm.service.dart +++ b/lib/src/services/fcm.service.dart @@ -1,3 +1,5 @@ +import 'dart:io' show Platform; + import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; @@ -5,22 +7,22 @@ import 'package:twonly/globals.dart'; import 'package:twonly/src/constants/secure_storage_keys.dart'; import 'package:twonly/src/services/notifications/background.notifications.dart'; import 'package:twonly/src/utils/log.dart'; -import 'dart:io' show Platform; + import '../../firebase_options.dart'; // see more here: https://firebase.google.com/docs/cloud-messaging/flutter/receive?hl=de -Future initFCMAfterAuthenticated() async { +Future initFCMAfterAuthenticated() async { if (globalIsAppInBackground) return; - final storage = FlutterSecureStorage(); + const storage = FlutterSecureStorage(); - String? storedToken = await storage.read(key: SecureStorageKeys.googleFcm); + final storedToken = await storage.read(key: SecureStorageKeys.googleFcm); try { final fcmToken = await FirebaseMessaging.instance.getToken(); if (fcmToken == null) { - Log.error("Error getting fcmToken"); + Log.error('Error getting fcmToken'); return; } @@ -33,14 +35,14 @@ Future initFCMAfterAuthenticated() async { await apiService.updateFCMToken(fcmToken); await storage.write(key: SecureStorageKeys.googleFcm, value: fcmToken); }).onError((err) { - Log.error("could not listen on token refresh"); + Log.error('could not listen on token refresh'); }); } catch (e) { - Log.error("could not load fcm token: $e"); + Log.error('could not load fcm token: $e'); } } -Future initFCMService() async { +Future initFCMService() async { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); @@ -51,15 +53,7 @@ Future initFCMService() async { // of notifications they would like to receive once the user receives a notification. // final notificationSettings = // await FirebaseMessaging.instance.requestPermission(provisional: true); - await FirebaseMessaging.instance.requestPermission( - alert: true, - announcement: false, - badge: true, - carPlay: false, - criticalAlert: false, - provisional: false, - sound: true, - ); + await FirebaseMessaging.instance.requestPermission(); // For apple platforms, ensure the APNS token is available before making any FCM plugin API calls if (Platform.isIOS) { @@ -69,9 +63,7 @@ Future initFCMService() async { } } - FirebaseMessaging.onMessage.listen((RemoteMessage message) { - handleRemoteMessage(message); - }); + FirebaseMessaging.onMessage.listen(handleRemoteMessage); } @pragma('vm:entry-point') @@ -80,19 +72,19 @@ Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { Log.info('Handling a background message: ${message.messageId}'); await handleRemoteMessage(message); // make sure every thing run... - await Future.delayed(Duration(milliseconds: 2000)); + await Future.delayed(const Duration(milliseconds: 2000)); } -Future handleRemoteMessage(RemoteMessage message) async { +Future handleRemoteMessage(RemoteMessage message) async { if (!Platform.isAndroid) { - Log.error("Got message in Dart while on iOS"); + Log.error('Got message in Dart while on iOS'); } if (message.notification != null) { - String title = message.notification!.title ?? ""; - String body = message.notification!.body ?? ""; + final title = message.notification!.title ?? ''; + final body = message.notification!.body ?? ''; await customLocalPushNotification(title, body); - } else if (message.data["push_data"] != null) { - await handlePushData(message.data["push_data"]); + } else if (message.data['push_data'] != null) { + await handlePushData(message.data['push_data'] as String); } } diff --git a/lib/src/services/flame.service.dart b/lib/src/services/flame.service.dart index 6ad7863..55346c2 100644 --- a/lib/src/services/flame.service.dart +++ b/lib/src/services/flame.service.dart @@ -9,7 +9,7 @@ import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/model/json/message.dart' as my; -Future syncFlameCounters() async { +Future syncFlameCounters() async { var user = await getUser(); if (user == null) return; diff --git a/lib/src/services/notifications/background.notifications.dart b/lib/src/services/notifications/background.notifications.dart index 074946b..1f7e6da 100644 --- a/lib/src/services/notifications/background.notifications.dart +++ b/lib/src/services/notifications/background.notifications.dart @@ -14,9 +14,8 @@ import 'package:twonly/src/utils/log.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); -Future customLocalPushNotification(String title, String msg) async { - const AndroidNotificationDetails androidNotificationDetails = - AndroidNotificationDetails( +Future customLocalPushNotification(String title, String msg) async { + const androidNotificationDetails = AndroidNotificationDetails( '1', 'System', channelDescription: 'System messages.', @@ -24,9 +23,8 @@ Future customLocalPushNotification(String title, String msg) async { priority: Priority.max, ); - const DarwinNotificationDetails darwinNotificationDetails = - DarwinNotificationDetails(); - const NotificationDetails notificationDetails = NotificationDetails( + const darwinNotificationDetails = DarwinNotificationDetails(); + const notificationDetails = NotificationDetails( android: androidNotificationDetails, iOS: darwinNotificationDetails, ); @@ -39,7 +37,7 @@ Future customLocalPushNotification(String title, String msg) async { ); } -Future handlePushData(String pushDataB64) async { +Future handlePushData(String pushDataB64) async { try { final pushData = EncryptedPushNotification.fromBuffer(base64.decode(pushDataB64)); @@ -48,7 +46,7 @@ Future handlePushData(String pushDataB64) async { PushUser? foundPushUser; if (pushData.keyId == 0) { - List key = "InsecureOnlyUsedForAddingContact".codeUnits; + final key = 'InsecureOnlyUsedForAddingContact'.codeUnits; pushNotification = await tryDecryptMessage(key, pushData); } else { final pushUsers = await getPushKeys(SecureStorageKeys.receivingPushKeys); @@ -70,14 +68,14 @@ Future handlePushData(String pushDataB64) async { if (pushNotification != null) { if (pushNotification.kind == PushKind.testNotification) { await customLocalPushNotification( - "Test notification", - "This is a test notification.", + 'Test notification', + 'This is a test notification.', ); } else if (foundPushUser != null) { if (pushNotification.hasMessageId()) { if (pushNotification.messageId <= foundPushUser.lastMessageId) { Log.info( - "Got a push notification for a message which was already opened.", + 'Got a push notification for a message which was already opened.', ); return; } @@ -90,8 +88,8 @@ Future handlePushData(String pushDataB64) async { } } catch (e) { await customLocalPushNotification( - "Du hast eine neue Nachricht.", - "ร–ffne twonly um mehr zu erfahren.", + 'Du hast eine neue Nachricht.', + 'ร–ffne twonly um mehr zu erfahren.', ); Log.error(e); } @@ -101,9 +99,9 @@ Future tryDecryptMessage( List key, EncryptedPushNotification push) async { try { final chacha20 = FlutterChacha20.poly1305Aead(); - SecretKeyData secretKeyData = SecretKeyData(key); + final secretKeyData = SecretKeyData(key); - SecretBox secretBox = SecretBox( + final secretBox = SecretBox( push.ciphertext, nonce: push.nonce, mac: Mac(push.mac), @@ -118,7 +116,7 @@ Future tryDecryptMessage( } } -Future showLocalPushNotification( +Future showLocalPushNotification( PushUser pushUser, PushNotification pushNotification, ) async { @@ -127,24 +125,23 @@ Future showLocalPushNotification( // do not show notification for blocked users... if (pushUser.blocked) { - Log.info("Blocked a message from a blocked user!"); + Log.info('Blocked a message from a blocked user!'); return; } title = pushUser.displayName; body = getPushNotificationText(pushNotification); - if (body == "") { - Log.error("No push notification type defined!"); + if (body == '') { + Log.error('No push notification type defined!'); } FilePathAndroidBitmap? styleInformation; - String? avatarPath = await getAvatarIcon(pushUser.userId.toInt()); + final avatarPath = await getAvatarIcon(pushUser.userId.toInt()); if (avatarPath != null) { styleInformation = FilePathAndroidBitmap(avatarPath); } - AndroidNotificationDetails androidNotificationDetails = - AndroidNotificationDetails( + final androidNotificationDetails = AndroidNotificationDetails( '0', 'Messages', channelDescription: 'Messages from other users.', @@ -154,9 +151,8 @@ Future showLocalPushNotification( largeIcon: styleInformation, ); - const DarwinNotificationDetails darwinNotificationDetails = - DarwinNotificationDetails(); - NotificationDetails notificationDetails = NotificationDetails( + const darwinNotificationDetails = DarwinNotificationDetails(); + final notificationDetails = NotificationDetails( android: androidNotificationDetails, iOS: darwinNotificationDetails, ); @@ -170,19 +166,18 @@ Future showLocalPushNotification( ); } -Future showLocalPushNotificationWithoutUserId( +Future showLocalPushNotificationWithoutUserId( PushNotification pushNotification, ) async { String? title; String? body; body = getPushNotificationTextWithoutUserId(pushNotification.kind); - if (body == "") { - Log.error("No push notification type defined!"); + if (body == '') { + Log.error('No push notification type defined!'); } - AndroidNotificationDetails androidNotificationDetails = - AndroidNotificationDetails( + const androidNotificationDetails = AndroidNotificationDetails( '0', 'Messages', channelDescription: 'Messages from other users.', @@ -191,9 +186,8 @@ Future showLocalPushNotificationWithoutUserId( ticker: 'You got a new message.', ); - const DarwinNotificationDetails darwinNotificationDetails = - DarwinNotificationDetails(); - NotificationDetails notificationDetails = NotificationDetails( + const darwinNotificationDetails = DarwinNotificationDetails(); + const notificationDetails = NotificationDetails( android: androidNotificationDetails, iOS: darwinNotificationDetails); await flutterLocalNotificationsPlugin.show( @@ -219,99 +213,99 @@ Future getAvatarIcon(int contactId) async { String getPushNotificationTextWithoutUserId(PushKind pushKind) { Map pushNotificationText; - String systemLanguage = Platform.localeName; + final systemLanguage = Platform.localeName; - if (systemLanguage.contains("de")) { + if (systemLanguage.contains('de')) { pushNotificationText = { - PushKind.text.name: "Du hast eine neue Nachricht erhalten.", - PushKind.twonly.name: "Du hast ein neues twonly erhalten.", - PushKind.video.name: "Du hast ein neues Video erhalten.", - PushKind.image.name: "Du hast ein neues Bild erhalten.", + PushKind.text.name: 'Du hast eine neue Nachricht erhalten.', + PushKind.twonly.name: 'Du hast ein neues twonly erhalten.', + PushKind.video.name: 'Du hast ein neues Video erhalten.', + PushKind.image.name: 'Du hast ein neues Bild erhalten.', PushKind.contactRequest.name: - "Du hast eine neue Kontaktanfrage erhalten.", - PushKind.acceptRequest.name: "Deine Kontaktanfrage wurde angenommen.", - PushKind.storedMediaFile.name: "Dein Bild wurde gespeichert.", - PushKind.reaction.name: "Du hast eine Reaktion auf dein Bild erhalten.", - PushKind.reopenedMedia.name: "Dein Bild wurde erneut geรถffnet.", + 'Du hast eine neue Kontaktanfrage erhalten.', + PushKind.acceptRequest.name: 'Deine Kontaktanfrage wurde angenommen.', + PushKind.storedMediaFile.name: 'Dein Bild wurde gespeichert.', + PushKind.reaction.name: 'Du hast eine Reaktion auf dein Bild erhalten.', + PushKind.reopenedMedia.name: 'Dein Bild wurde erneut geรถffnet.', PushKind.reactionToVideo.name: - "Du hast eine Reaktion auf dein Video erhalten.", + 'Du hast eine Reaktion auf dein Video erhalten.', PushKind.reactionToText.name: - "Du hast eine Reaktion auf deinen Text erhalten.", + 'Du hast eine Reaktion auf deinen Text erhalten.', PushKind.reactionToImage.name: - "Du hast eine Reaktion auf dein Bild erhalten.", - PushKind.response.name: "Du hast eine Antwort erhalten.", + 'Du hast eine Reaktion auf dein Bild erhalten.', + PushKind.response.name: 'Du hast eine Antwort erhalten.', }; } else { pushNotificationText = { - PushKind.text.name: "You have received a new message.", - PushKind.twonly.name: "You have received a new twonly.", - PushKind.video.name: "You have received a new video.", - PushKind.image.name: "You have received a new image.", - PushKind.contactRequest.name: "You have received a new contact request.", - PushKind.acceptRequest.name: "Your contact request has been accepted.", - PushKind.storedMediaFile.name: "Your image has been saved.", - PushKind.reaction.name: "You have received a reaction to your image.", - PushKind.reopenedMedia.name: "Your image has been reopened.", + PushKind.text.name: 'You have received a new message.', + PushKind.twonly.name: 'You have received a new twonly.', + PushKind.video.name: 'You have received a new video.', + PushKind.image.name: 'You have received a new image.', + PushKind.contactRequest.name: 'You have received a new contact request.', + PushKind.acceptRequest.name: 'Your contact request has been accepted.', + PushKind.storedMediaFile.name: 'Your image has been saved.', + PushKind.reaction.name: 'You have received a reaction to your image.', + PushKind.reopenedMedia.name: 'Your image has been reopened.', PushKind.reactionToVideo.name: - "You have received a reaction to your video.", + 'You have received a reaction to your video.', PushKind.reactionToText.name: - "You have received a reaction to your text.", + 'You have received a reaction to your text.', PushKind.reactionToImage.name: - "You have received a reaction to your image.", - PushKind.response.name: "You have received a response.", + 'You have received a reaction to your image.', + PushKind.response.name: 'You have received a response.', }; } - return pushNotificationText[pushKind.name] ?? ""; + return pushNotificationText[pushKind.name] ?? ''; } String getPushNotificationText(PushNotification pushNotification) { - String systemLanguage = Platform.localeName; + final systemLanguage = Platform.localeName; Map pushNotificationText; - if (systemLanguage.contains("de")) { + if (systemLanguage.contains('de')) { pushNotificationText = { - PushKind.text.name: "hat dir eine Nachricht gesendet.", - PushKind.twonly.name: "hat dir ein twonly gesendet.", - PushKind.video.name: "hat dir ein Video gesendet.", - PushKind.image.name: "hat dir ein Bild gesendet.", - PushKind.contactRequest.name: "mรถchte sich mit dir vernetzen.", - PushKind.acceptRequest.name: "ist jetzt mit dir vernetzt.", - PushKind.storedMediaFile.name: "hat dein Bild gespeichert.", - PushKind.reaction.name: "hat auf dein Bild reagiert.", - PushKind.reopenedMedia.name: "hat dein Bild erneut geรถffnet.", + PushKind.text.name: 'hat dir eine Nachricht gesendet.', + PushKind.twonly.name: 'hat dir ein twonly gesendet.', + PushKind.video.name: 'hat dir ein Video gesendet.', + PushKind.image.name: 'hat dir ein Bild gesendet.', + PushKind.contactRequest.name: 'mรถchte sich mit dir vernetzen.', + PushKind.acceptRequest.name: 'ist jetzt mit dir vernetzt.', + PushKind.storedMediaFile.name: 'hat dein Bild gespeichert.', + PushKind.reaction.name: 'hat auf dein Bild reagiert.', + PushKind.reopenedMedia.name: 'hat dein Bild erneut geรถffnet.', PushKind.reactionToVideo.name: - "hat mit {{reaction}} auf dein Video reagiert.", + 'hat mit {{reaction}} auf dein Video reagiert.', PushKind.reactionToText.name: - "hat mit {{reaction}} auf deine Nachricht reagiert.", + 'hat mit {{reaction}} auf deine Nachricht reagiert.', PushKind.reactionToImage.name: - "hat mit {{reaction}} auf dein Bild reagiert.", - PushKind.response.name: "hat dir geantwortet.", + 'hat mit {{reaction}} auf dein Bild reagiert.', + PushKind.response.name: 'hat dir geantwortet.', }; } else { pushNotificationText = { - PushKind.text.name: "has sent you a message.", - PushKind.twonly.name: "has sent you a twonly.", - PushKind.video.name: "has sent you a video.", - PushKind.image.name: "has sent you an image.", - PushKind.contactRequest.name: "wants to connect with you.", - PushKind.acceptRequest.name: "is now connected with you.", - PushKind.storedMediaFile.name: "has stored your image.", - PushKind.reaction.name: "has reacted to your image.", - PushKind.reopenedMedia.name: "has reopened your image.", + PushKind.text.name: 'has sent you a message.', + PushKind.twonly.name: 'has sent you a twonly.', + PushKind.video.name: 'has sent you a video.', + PushKind.image.name: 'has sent you an image.', + PushKind.contactRequest.name: 'wants to connect with you.', + PushKind.acceptRequest.name: 'is now connected with you.', + PushKind.storedMediaFile.name: 'has stored your image.', + PushKind.reaction.name: 'has reacted to your image.', + PushKind.reopenedMedia.name: 'has reopened your image.', PushKind.reactionToVideo.name: - "has reacted with {{reaction}} to your video.", + 'has reacted with {{reaction}} to your video.', PushKind.reactionToText.name: - "has reacted with {{reaction}} to your message.", + 'has reacted with {{reaction}} to your message.', PushKind.reactionToImage.name: - "has reacted with {{reaction}} to your image.", - PushKind.response.name: "has responded.", + 'has reacted with {{reaction}} to your image.', + PushKind.response.name: 'has responded.', }; } - var contentText = pushNotificationText[pushNotification.kind.name] ?? ""; + var contentText = pushNotificationText[pushNotification.kind.name] ?? ''; if (pushNotification.hasReactionContent()) { contentText = contentText.replaceAll( - "{{reaction}}", pushNotification.reactionContent); + '{{reaction}}', pushNotification.reactionContent); } return contentText; } diff --git a/lib/src/services/notifications/pushkeys.notifications.dart b/lib/src/services/notifications/pushkeys.notifications.dart index c2a1a1d..258297a 100644 --- a/lib/src/services/notifications/pushkeys.notifications.dart +++ b/lib/src/services/notifications/pushkeys.notifications.dart @@ -18,22 +18,22 @@ import 'package:twonly/src/services/api/messages.dart'; import 'package:twonly/src/utils/log.dart'; /// This function must be called after the database is setup -Future setupNotificationWithUsers( +Future setupNotificationWithUsers( {bool force = false, int? forceContact}) async { var pushUsers = await getPushKeys(SecureStorageKeys.receivingPushKeys); // HotFIX: Search for user with id 0 if not there remove all // and create new push keys with all users. - PushUser? pushUser = pushUsers.firstWhereOrNull((x) => x.userId == 0); + final pushUser = pushUsers.firstWhereOrNull((x) => x.userId == 0); if (pushUser == null) { - Log.info("Clearing push keys"); + Log.info('Clearing push keys'); await setPushKeys(SecureStorageKeys.receivingPushKeys, []); - pushUsers = await getPushKeys(SecureStorageKeys.receivingPushKeys); - pushUsers.add(PushUser( - userId: Int64(0), - displayName: "NoUser", - pushKeys: [], - )); + pushUsers = await getPushKeys(SecureStorageKeys.receivingPushKeys) + ..add(PushUser( + userId: Int64(), + displayName: 'NoUser', + pushKeys: [], + )); } var wasChanged = false; @@ -42,7 +42,7 @@ Future setupNotificationWithUsers( final contacts = await twonlyDB.contactsDao.getAllNotBlockedContacts(); for (final contact in contacts) { - PushUser? pushUser = + final pushUser = pushUsers.firstWhereOrNull((x) => x.userId == contact.userId); if (pushUser != null) { @@ -67,11 +67,11 @@ Future setupNotificationWithUsers( pushUser.pushKeys.add(lastKey); pushUser.pushKeys.add(pushKey); wasChanged = true; - Log.info("Creating new pushkey for ${contact.userId}"); + Log.info('Creating new pushkey for ${contact.userId}'); } } else { Log.info( - "User ${contact.userId} not yet in pushkeys. Creating a new user.", + 'User ${contact.userId} not yet in pushkeys. Creating a new user.', ); wasChanged = true; @@ -87,7 +87,6 @@ Future setupNotificationWithUsers( displayName: getContactDisplayName(contact), blocked: contact.blocked, pushKeys: [pushKey], - lastMessageId: null, )); } } @@ -97,7 +96,7 @@ Future setupNotificationWithUsers( } } -Future sendNewPushKey(int userId, PushKey pushKey) async { +Future sendNewPushKey(int userId, PushKey pushKey) async { await encryptAndSendMessageAsync( null, userId, @@ -114,11 +113,10 @@ Future sendNewPushKey(int userId, PushKey pushKey) async { ); } -Future updatePushUser(Contact contact) async { - var pushKeys = await getPushKeys(SecureStorageKeys.receivingPushKeys); +Future updatePushUser(Contact contact) async { + final pushKeys = await getPushKeys(SecureStorageKeys.receivingPushKeys); - PushUser? pushUser = - pushKeys.firstWhereOrNull((x) => x.userId == contact.userId); + final pushUser = pushKeys.firstWhereOrNull((x) => x.userId == contact.userId); if (pushUser == null) { pushKeys.add(PushUser( @@ -126,20 +124,21 @@ Future updatePushUser(Contact contact) async { displayName: getContactDisplayName(contact), pushKeys: [], blocked: contact.blocked, - lastMessageId: Int64(0), + lastMessageId: Int64(), )); } else { - pushUser.displayName = getContactDisplayName(contact); - pushUser.blocked = contact.blocked; + pushUser + ..displayName = getContactDisplayName(contact) + ..blocked = contact.blocked; } await setPushKeys(SecureStorageKeys.receivingPushKeys, pushKeys); } -Future handleNewPushKey(int fromUserId, my.PushKeyContent pushKey) async { - var pushKeys = await getPushKeys(SecureStorageKeys.sendingPushKeys); +Future handleNewPushKey(int fromUserId, my.PushKeyContent pushKey) async { + final pushKeys = await getPushKeys(SecureStorageKeys.sendingPushKeys); - PushUser? pushUser = pushKeys.firstWhereOrNull((x) => x.userId == fromUserId); + var pushUser = pushKeys.firstWhereOrNull((x) => x.userId == fromUserId); if (pushUser == null) { final contact = await twonlyDB.contactsDao @@ -151,13 +150,13 @@ Future handleNewPushKey(int fromUserId, my.PushKeyContent pushKey) async { displayName: getContactDisplayName(contact), pushKeys: [], blocked: contact.blocked, - lastMessageId: Int64(0), + lastMessageId: Int64(), )); pushUser = pushKeys.firstWhereOrNull((x) => x.userId == fromUserId); } if (pushUser == null) { - Log.error("could not store new push key as no user was found"); + Log.error('could not store new push key as no user was found'); } // only store the newest key... @@ -173,14 +172,12 @@ Future handleNewPushKey(int fromUserId, my.PushKeyContent pushKey) async { await setPushKeys(SecureStorageKeys.sendingPushKeys, pushKeys); } -Future updateLastMessageId(int fromUserId, int messageId) async { - List pushUsers = - await getPushKeys(SecureStorageKeys.receivingPushKeys); +Future updateLastMessageId(int fromUserId, int messageId) async { + final pushUsers = await getPushKeys(SecureStorageKeys.receivingPushKeys); - PushUser? pushUser = - pushUsers.firstWhereOrNull((x) => x.userId == fromUserId); + final pushUser = pushUsers.firstWhereOrNull((x) => x.userId == fromUserId); if (pushUser == null) { - setupNotificationWithUsers(); + unawaited(setupNotificationWithUsers()); return; } @@ -193,13 +190,12 @@ Future updateLastMessageId(int fromUserId, int messageId) async { /// this will trigger a push notification /// push notification only containing the message kind and username Future getPushData(int toUserId, PushNotification content) async { - final List pushKeys = - await getPushKeys(SecureStorageKeys.sendingPushKeys); + final pushKeys = await getPushKeys(SecureStorageKeys.sendingPushKeys); - List key = "InsecureOnlyUsedForAddingContact".codeUnits; - int keyId = 0; + var key = 'InsecureOnlyUsedForAddingContact'.codeUnits; + var keyId = 0; - PushUser? pushUser = pushKeys.firstWhereOrNull((x) => x.userId == toUserId); + final pushUser = pushKeys.firstWhereOrNull((x) => x.userId == toUserId); if (pushUser == null) { // user does not have send any push keys @@ -210,7 +206,7 @@ Future getPushData(int toUserId, PushNotification content) async { content.kind != PushKind.testNotification) { // this will be enforced after every app uses this system... :/ // return null; - Log.error("Using insecure key as the receiver does not send a push key!"); + Log.error('Using insecure key as the receiver does not send a push key!'); await encryptAndSendMessageAsync( null, toUserId, @@ -226,7 +222,7 @@ Future getPushData(int toUserId, PushNotification content) async { key = pushUser.pushKeys.last.key; keyId = pushUser.pushKeys.last.id.toInt(); } catch (e) { - Log.error("No push notification key found for user $toUserId"); + Log.error('No push notification key found for user $toUserId'); return null; } } @@ -248,39 +244,36 @@ Future getPushData(int toUserId, PushNotification content) async { } Future> getPushKeys(String storageKey) async { - var storage = FlutterSecureStorage(); - String? pushKeysProto = await storage.read( + const storage = FlutterSecureStorage(); + final pushKeysProto = await storage.read( key: storageKey, - iOptions: IOSOptions( - groupId: "CN332ZUGRP.eu.twonly.shared", - synchronizable: false, + iOptions: const IOSOptions( + groupId: 'CN332ZUGRP.eu.twonly.shared', accessibility: KeychainAccessibility.first_unlock, ), ); if (pushKeysProto == null) return []; - Uint8List pushKeysRaw = base64Decode(pushKeysProto); + final pushKeysRaw = base64Decode(pushKeysProto); return PushUsers.fromBuffer(pushKeysRaw).users; } -Future setPushKeys(String storageKey, List pushKeys) async { - var storage = FlutterSecureStorage(); +Future setPushKeys(String storageKey, List pushKeys) async { + const storage = FlutterSecureStorage(); await storage.delete( key: storageKey, - iOptions: IOSOptions( - groupId: "CN332ZUGRP.eu.twonly.shared", - synchronizable: false, + iOptions: const IOSOptions( + groupId: 'CN332ZUGRP.eu.twonly.shared', accessibility: KeychainAccessibility.first_unlock, ), ); - String jsonString = base64Encode(PushUsers(users: pushKeys).writeToBuffer()); + final jsonString = base64Encode(PushUsers(users: pushKeys).writeToBuffer()); await storage.write( key: storageKey, value: jsonString, - iOptions: IOSOptions( - groupId: "CN332ZUGRP.eu.twonly.shared", - synchronizable: false, + iOptions: const IOSOptions( + groupId: 'CN332ZUGRP.eu.twonly.shared', accessibility: KeychainAccessibility.first_unlock, ), ); diff --git a/lib/src/services/notifications/setup.notifications.dart b/lib/src/services/notifications/setup.notifications.dart index 9a0d73b..3dcd399 100644 --- a/lib/src/services/notifications/setup.notifications.dart +++ b/lib/src/services/notifications/setup.notifications.dart @@ -58,7 +58,7 @@ Future setupPushNotification() async { ); } -Future createPushAvatars() async { +Future createPushAvatars() async { if (!Platform.isAndroid) { return; // avatars currently only shown in Android... } diff --git a/lib/src/services/signal/encryption.signal.dart b/lib/src/services/signal/encryption.signal.dart index dada972..832c778 100644 --- a/lib/src/services/signal/encryption.signal.dart +++ b/lib/src/services/signal/encryption.signal.dart @@ -1,11 +1,10 @@ import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; + import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; import 'package:mutex/mutex.dart'; -import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/database/signal/connect_signal_protocol_store.dart'; import 'package:twonly/src/services/signal/consts.signal.dart'; import 'package:twonly/src/services/signal/prekeys.signal.dart'; import 'package:twonly/src/services/signal/utils.signal.dart'; @@ -17,19 +16,18 @@ final lockingSignalEncryption = Mutex(); Future signalEncryptMessage( int target, Uint8List plaintextContent) async { - return await lockingSignalEncryption.protect(() async { + return lockingSignalEncryption.protect(() async { try { - ConnectSignalProtocolStore signalStore = (await getSignalStore())!; + final signalStore = (await getSignalStore())!; final address = SignalProtocolAddress(target.toString(), defaultDeviceId); - SessionCipher session = SessionCipher.fromStore(signalStore, address); + final session = SessionCipher.fromStore(signalStore, address); - SignalContactPreKey? preKey = await getPreKeyByContactId(target); - SignalContactSignedPreKey? signedPreKey = - await getSignedPreKeyByContactId(target); + final preKey = await getPreKeyByContactId(target); + final signedPreKey = await getSignedPreKeyByContactId(target); if (signedPreKey != null) { - SessionBuilder sessionBuilder = SessionBuilder.fromSignalStore( + final sessionBuilder = SessionBuilder.fromSignalStore( signalStore, address, ); @@ -45,20 +43,20 @@ Future signalEncryptMessage( ); } - ECPublicKey? tempSignedPreKeyPublic = Curve.decodePoint( + final ECPublicKey? tempSignedPreKeyPublic = Curve.decodePoint( DjbECPublicKey(Uint8List.fromList(signedPreKey.signedPreKey)) .serialize(), 1, ); - Uint8List? tempSignedPreKeySignature = Uint8List.fromList( + final Uint8List? tempSignedPreKeySignature = Uint8List.fromList( signedPreKey.signedPreKeySignature, ); final IdentityKey? tempIdentityKey = await signalStore.getIdentity(address); if (tempIdentityKey != null) { - PreKeyBundle preKeyBundle = PreKeyBundle( + final preKeyBundle = PreKeyBundle( target, defaultDeviceId, preKey?.preKeyId, @@ -72,16 +70,16 @@ Future signalEncryptMessage( try { await sessionBuilder.processPreKeyBundle(preKeyBundle); } catch (e) { - Log.error("could not process pre key bundle: $e"); + Log.error('could not process pre key bundle: $e'); } } else { - Log.error("did not get the identity of the remote address"); + Log.error('did not get the identity of the remote address'); } } final ciphertext = await session.encrypt(plaintextContent); - var b = BytesBuilder(); + final b = BytesBuilder(); b.add(ciphertext.serialize()); b.add(intToBytes(ciphertext.getType())); @@ -95,36 +93,34 @@ Future signalEncryptMessage( Future signalDecryptMessage(int source, Uint8List msg) async { try { - ConnectSignalProtocolStore signalStore = (await getSignalStore())!; + final signalStore = (await getSignalStore())!; - SessionCipher session = SessionCipher.fromStore( + final session = SessionCipher.fromStore( signalStore, SignalProtocolAddress(source.toString(), defaultDeviceId)); - List? msgs = removeLastXBytes(msg, 4); + final msgs = removeLastXBytes(msg, 4); if (msgs == null) { - Log.error("Message requires at least 4 bytes."); + Log.error('Message requires at least 4 bytes.'); return null; } - Uint8List body = msgs[0]; - int type = bytesToInt(msgs[1]); + final body = msgs[0]; + final type = bytesToInt(msgs[1]); Uint8List plaintext; if (type == CiphertextMessage.prekeyType) { - PreKeySignalMessage pre = PreKeySignalMessage(body); + final pre = PreKeySignalMessage(body); plaintext = await session.decrypt(pre); } else if (type == CiphertextMessage.whisperType) { - SignalMessage signalMsg = SignalMessage.fromSerialized(body); + final signalMsg = SignalMessage.fromSerialized(body); plaintext = await session.decryptFromSignal(signalMsg); } else { - Log.error("Type not known: $type"); + Log.error('Type not known: $type'); return null; } - return MessageJson.fromJson( - jsonDecode( - utf8.decode( - gzip.decode(plaintext), - ), + return MessageJson.fromJson(jsonDecode( + utf8.decode( + gzip.decode(plaintext), ), - ); + ) as Map); } catch (e) { Log.error(e.toString()); return null; diff --git a/lib/src/services/signal/identity.signal.dart b/lib/src/services/signal/identity.signal.dart index 009025b..866b66c 100644 --- a/lib/src/services/signal/identity.signal.dart +++ b/lib/src/services/signal/identity.signal.dart @@ -1,12 +1,11 @@ import 'dart:convert'; + import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/constants/secure_storage_keys.dart'; -import 'package:twonly/src/model/json/signal_identity.dart'; import 'package:twonly/src/database/signal/connect_signal_protocol_store.dart'; -import 'package:twonly/src/model/json/userdata.dart'; -import 'package:twonly/src/services/api/utils.dart'; +import 'package:twonly/src/model/json/signal_identity.dart'; import 'package:twonly/src/services/signal/consts.signal.dart'; import 'package:twonly/src/services/signal/utils.signal.dart'; import 'package:twonly/src/utils/log.dart'; @@ -20,40 +19,41 @@ Future getSignalIdentityKeyPair() async { // This function runs after the clients authenticated with the server. // It then checks if it should update a new session key -Future signalHandleNewServerConnection() async { - final UserData? user = await getUser(); +Future signalHandleNewServerConnection() async { + final user = await getUser(); if (user == null) return; if (user.signalLastSignedPreKeyUpdated != null) { - DateTime fortyEightHoursAgo = DateTime.now().subtract(Duration(hours: 48)); - bool isYoungerThan48Hours = + final fortyEightHoursAgo = + DateTime.now().subtract(const Duration(hours: 48)); + final isYoungerThan48Hours = (user.signalLastSignedPreKeyUpdated!).isAfter(fortyEightHoursAgo); if (isYoungerThan48Hours) { // The key does live for 48 hours then it expires and a new key is generated. return; } } - SignedPreKeyRecord? signedPreKey = await _getNewSignalSignedPreKey(); + final signedPreKey = await _getNewSignalSignedPreKey(); if (signedPreKey == null) { - Log.error("could not generate a new signed pre key!"); + Log.error('could not generate a new signed pre key!'); return; } await updateUserdata((user) { user.signalLastSignedPreKeyUpdated = DateTime.now(); return user; }); - Result res = await apiService.updateSignedPreKey( + final res = await apiService.updateSignedPreKey( signedPreKey.id, signedPreKey.getKeyPair().publicKey.serialize(), signedPreKey.signature, ); if (res.isError) { - Log.error("could not update the signed pre key: ${res.error}"); + Log.error('could not update the signed pre key: ${res.error}'); await updateUserdata((user) { user.signalLastSignedPreKeyUpdated = null; return user; }); } else { - Log.info("updated signed pre key"); + Log.info('updated signed pre key'); } } @@ -61,7 +61,7 @@ Future> signalGetPreKeys() async { final user = await getUser(); if (user == null) return []; - int start = user.currentPreKeyIndexStart; + final start = user.currentPreKeyIndexStart; await updateUserdata((user) { user.currentPreKeyIndexStart += 200; return user; @@ -77,7 +77,7 @@ Future> signalGetPreKeys() async { Future getSignalIdentity() async { try { - final storage = FlutterSecureStorage(); + const storage = FlutterSecureStorage(); var signalIdentityJson = await storage.read(key: SecureStorageKeys.signalIdentity); if (signalIdentityJson == null) { @@ -85,15 +85,15 @@ Future getSignalIdentity() async { } final decoded = jsonDecode(signalIdentityJson); signalIdentityJson = null; - return SignalIdentity.fromJson(decoded); + return SignalIdentity.fromJson(decoded as Map); } catch (e) { - Log.error("could not load signal identity: $e"); + Log.error('could not load signal identity: $e'); return null; } } -Future createIfNotExistsSignalIdentity() async { - final storage = FlutterSecureStorage(); +Future createIfNotExistsSignalIdentity() async { + const storage = FlutterSecureStorage(); final signalIdentity = await storage.read( key: SecureStorageKeys.signalIdentity, @@ -106,7 +106,7 @@ Future createIfNotExistsSignalIdentity() async { final identityKeyPair = generateIdentityKeyPair(); final registrationId = generateRegistrationId(true); - ConnectSignalProtocolStore signalStore = + final signalStore = ConnectSignalProtocolStore(identityKeyPair, registrationId); final signedPreKey = generateSignedPreKey(identityKeyPair, defaultDeviceId); @@ -133,13 +133,13 @@ Future _getNewSignalSignedPreKey() async { return null; } - int signedPreKeyId = user.currentSignedPreKeyIndexStart; + final signedPreKeyId = user.currentSignedPreKeyIndexStart; await updateUserdata((user) { user.currentSignedPreKeyIndexStart += 1; return user; }); - final SignedPreKeyRecord signedPreKey = generateSignedPreKey( + final signedPreKey = generateSignedPreKey( identityKeyPair, signedPreKeyId, ); diff --git a/lib/src/services/signal/prekeys.signal.dart b/lib/src/services/signal/prekeys.signal.dart index 7bfdaec..cbdd517 100644 --- a/lib/src/services/signal/prekeys.signal.dart +++ b/lib/src/services/signal/prekeys.signal.dart @@ -23,7 +23,7 @@ Mutex requestNewKeys = Mutex(); DateTime lastPreKeyRequest = DateTime.now().subtract(Duration(hours: 1)); DateTime lastSignedPreKeyRequest = DateTime.now().subtract(Duration(hours: 1)); -Future requestNewPrekeysForContact(int contactId) async { +Future requestNewPrekeysForContact(int contactId) async { if (lastPreKeyRequest .isAfter(DateTime.now().subtract(Duration(seconds: 60)))) { return; @@ -59,7 +59,7 @@ Future getPreKeyByContactId(int contactId) async { return twonlyDB.signalDao.popPreKeyByContactId(contactId); } -Future requestNewSignedPreKeyForContact(int contactId) async { +Future requestNewSignedPreKeyForContact(int contactId) async { if (lastSignedPreKeyRequest .isAfter(DateTime.now().subtract(Duration(seconds: 60)))) { Log.info("last signed pre request was 60s before"); diff --git a/lib/src/services/signal/session.signal.dart b/lib/src/services/signal/session.signal.dart index 020c1a3..fb678da 100644 --- a/lib/src/services/signal/session.signal.dart +++ b/lib/src/services/signal/session.signal.dart @@ -77,7 +77,7 @@ Future createNewSignalSession(Response_UserData userData) async { } } -Future deleteSessionWithTarget(int target) async { +Future deleteSessionWithTarget(int target) async { ConnectSignalProtocolStore? signalStore = await getSignalStore(); if (signalStore == null) return; final address = SignalProtocolAddress(target.toString(), defaultDeviceId); diff --git a/lib/src/services/thumbnail.service.dart b/lib/src/services/thumbnail.service.dart index 4b989b1..0be7362 100644 --- a/lib/src/services/thumbnail.service.dart +++ b/lib/src/services/thumbnail.service.dart @@ -1,23 +1,24 @@ import 'dart:io'; import 'dart:ui'; + import 'package:flutter/material.dart'; import 'package:flutter_image_compress/flutter_image_compress.dart'; import 'package:path/path.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:video_thumbnail/video_thumbnail.dart'; -import 'package:path_provider/path_provider.dart'; Future createThumbnails(String directoryPath) async { final directory = Directory(directoryPath); final outputDirectory = await getTemporaryDirectory(); - if (await directory.exists()) { - final List files = directory.listSync(); + if (directory.existsSync()) { + final files = directory.listSync(); - for (var file in files) { + for (final file in files) { if (file is File) { - final String filePath = file.path; - final String fileExtension = filePath.split('.').last.toLowerCase(); + final filePath = file.path; + final fileExtension = filePath.split('.').last.toLowerCase(); if (['jpg', 'jpeg', 'png'].contains(fileExtension)) { // Create thumbnail for images @@ -26,23 +27,18 @@ Future createThumbnails(String directoryPath) async { final thumbnailFile = File('${outputDirectory.path}/${file.uri.pathSegments.last}'); await thumbnailFile.writeAsBytes(thumbnail!.buffer.asUint8List()); - print('Thumbnail created for image: ${file.uri.pathSegments.last}'); } else if (['mp4', 'mov', 'avi'].contains(fileExtension)) { // Create thumbnail for videos - - print('Thumbnail created for video: ${file.uri.pathSegments.last}'); } } } - } else { - print('Directory does not exist: $directoryPath'); } } -Future createThumbnailsForImage(File file) async { - final String fileExtension = file.path.split('.').last.toLowerCase(); - if (fileExtension != "png") { - Log.error("Could not create thumbnail for image. $fileExtension != .png"); +Future createThumbnailsForImage(File file) async { + final fileExtension = file.path.split('.').last.toLowerCase(); + if (fileExtension != 'png') { + Log.error('Could not create thumbnail for image. $fileExtension != .png'); return; } @@ -56,45 +52,44 @@ Future createThumbnailsForImage(File file) async { ); if (imageBytesCompressed == null) { - Log.error("Could not compress the image"); + Log.error('Could not compress the image'); return; } - File thumbnailFile = getThumbnailPath(file); + final thumbnailFile = getThumbnailPath(file); await thumbnailFile.writeAsBytes(imageBytesCompressed); } catch (e) { - Log.error("Could not compress the image got :$e"); + Log.error('Could not compress the image got :$e'); } } -Future createThumbnailsForVideo(File file) async { - final String fileExtension = file.path.split('.').last.toLowerCase(); - if (fileExtension != "mp4") { - Log.error("Could not create thumbnail for video. $fileExtension != .mp4"); +Future createThumbnailsForVideo(File file) async { + final fileExtension = file.path.split('.').last.toLowerCase(); + if (fileExtension != 'mp4') { + Log.error('Could not create thumbnail for video. $fileExtension != .mp4'); return; } try { await VideoThumbnail.thumbnailFile( video: file.path, - imageFormat: ImageFormat.PNG, thumbnailPath: getThumbnailPath(file).path, maxWidth: 450, quality: 75, ); } catch (e) { - Log.error("Could not create the video thumbnail: $e"); + Log.error('Could not create the video thumbnail: $e'); } } File getThumbnailPath(File file) { - String originalFileName = file.uri.pathSegments.last; - String fileNameWithoutExtension = originalFileName.split('.').first; - String fileExtension = originalFileName.split('.').last; - if (fileExtension == "mp4") { - fileExtension = "png"; + final originalFileName = file.uri.pathSegments.last; + final fileNameWithoutExtension = originalFileName.split('.').first; + var fileExtension = originalFileName.split('.').last; + if (fileExtension == 'mp4') { + fileExtension = 'png'; } - String newFileName = '$fileNameWithoutExtension.thumbnail.$fileExtension'; + final newFileName = '$fileNameWithoutExtension.thumbnail.$fileExtension'; Directory(file.parent.path).createSync(); return File(join(file.parent.path, newFileName)); } diff --git a/lib/src/services/twonly_safe/common.twonly_safe.dart b/lib/src/services/twonly_safe/common.twonly_safe.dart index 169e2b9..bafddd2 100644 --- a/lib/src/services/twonly_safe/common.twonly_safe.dart +++ b/lib/src/services/twonly_safe/common.twonly_safe.dart @@ -8,7 +8,7 @@ import 'package:twonly/src/services/twonly_safe/create_backup.twonly_safe.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/storage.dart'; -Future enableTwonlySafe(String password) async { +Future enableTwonlySafe(String password) async { final user = await getUser(); if (user == null) return; @@ -24,7 +24,7 @@ Future enableTwonlySafe(String password) async { performTwonlySafeBackup(force: true); } -Future disableTwonlySafe() async { +Future disableTwonlySafe() async { final serverUrl = await getTwonlySafeBackupUrl(); if (serverUrl != null) { try { diff --git a/lib/src/services/twonly_safe/create_backup.twonly_safe.dart b/lib/src/services/twonly_safe/create_backup.twonly_safe.dart index 4d77a0a..0c48785 100644 --- a/lib/src/services/twonly_safe/create_backup.twonly_safe.dart +++ b/lib/src/services/twonly_safe/create_backup.twonly_safe.dart @@ -18,7 +18,7 @@ import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/views/settings/backup/backup.view.dart'; -Future performTwonlySafeBackup({bool force = false}) async { +Future performTwonlySafeBackup({bool force = false}) async { final user = await getUser(); if (user == null || user.twonlySafeBackup == null || user.isDemoUser) { @@ -27,38 +27,39 @@ Future performTwonlySafeBackup({bool force = false}) async { if (user.twonlySafeBackup!.backupUploadState == LastBackupUploadState.pending) { - Log.warn("Backup upload is already pending."); + Log.warn('Backup upload is already pending.'); return; } - DateTime? lastUpdateTime = user.twonlySafeBackup!.lastBackupDone; + final DateTime? lastUpdateTime = user.twonlySafeBackup!.lastBackupDone; if (!force && lastUpdateTime != null) { - if (lastUpdateTime.isAfter(DateTime.now().subtract(Duration(days: 1)))) { + if (lastUpdateTime + .isAfter(DateTime.now().subtract(const Duration(days: 1)))) { return; } } - Log.info("Starting new twonly Safe-Backup!"); + Log.info('Starting new twonly Safe-Backup!'); final baseDir = (await getApplicationSupportDirectory()).path; - final backupDir = Directory(join(baseDir, "backup_twonly_safe/")); + final backupDir = Directory(join(baseDir, 'backup_twonly_safe/')); await backupDir.create(recursive: true); final backupDatabaseFile = - File(join(backupDir.path, "twonly_database.backup.sqlite")); + File(join(backupDir.path, 'twonly_database.backup.sqlite')); final backupDatabaseFileCleaned = - File(join(backupDir.path, "twonly_database.backup.cleaned.sqlite")); + File(join(backupDir.path, 'twonly_database.backup.cleaned.sqlite')); // copy database - final originalDatabase = File(join(baseDir, "twonly_database.sqlite")); + final originalDatabase = File(join(baseDir, 'twonly_database.sqlite')); await originalDatabase.copy(backupDatabaseFile.path); driftRuntimeOptions.dontWarnAboutMultipleDatabases = true; final backupDB = TwonlyDatabase( driftDatabase( - name: "twonly_database.backup", + name: 'twonly_database.backup', native: DriftNativeOptions( databaseDirectory: () async { return backupDir; @@ -74,24 +75,26 @@ Future performTwonlySafeBackup({bool force = false}) async { await backupDB.printTableSizes(); - backupDB.close(); + await backupDB.close(); - var secureStorageBackup = {}; - final storage = FlutterSecureStorage(); + // ignore: inference_failure_on_collection_literal + final secureStorageBackup = {}; + const storage = FlutterSecureStorage(); secureStorageBackup[SecureStorageKeys.signalIdentity] = await storage.read(key: SecureStorageKeys.signalIdentity); secureStorageBackup[SecureStorageKeys.signalSignedPreKey] = await storage.read(key: SecureStorageKeys.signalSignedPreKey); - var userBackup = await getUser(); + final userBackup = await getUser(); if (userBackup == null) return; // FILTER settings which should not be in the backup - userBackup.twonlySafeBackup = null; - userBackup.lastImageSend = null; - userBackup.todaysImageCounter = null; - userBackup.lastPlanBallance = ""; - userBackup.additionalUserInvites = ""; - userBackup.signalLastSignedPreKeyUpdated = null; + userBackup + ..twonlySafeBackup = null + ..lastImageSend = null + ..todaysImageCounter = null + ..lastPlanBallance = '' + ..additionalUserInvites = '' + ..signalLastSignedPreKeyUpdated = null; secureStorageBackup[SecureStorageKeys.userData] = jsonEncode(userBackup); @@ -101,8 +104,8 @@ Future performTwonlySafeBackup({bool force = false}) async { await backupDatabaseFile.delete(); await backupDatabaseFileCleaned.delete(); - Log.info("twonlyDatabaseLength = ${twonlyDatabaseBytes.lengthInBytes}"); - Log.info("secureStorageLength = ${jsonEncode(secureStorageBackup).length}"); + Log.info('twonlyDatabaseLength = ${twonlyDatabaseBytes.lengthInBytes}'); + Log.info('secureStorageLength = ${jsonEncode(secureStorageBackup).length}'); final backupProto = TwonlySafeBackupContent( secureStorageJson: jsonEncode(secureStorageBackup), @@ -115,7 +118,7 @@ Future performTwonlySafeBackup({bool force = false}) async { if (user.twonlySafeBackup!.lastBackupDone == null || user.twonlySafeBackup!.lastBackupDone! - .isAfter(DateTime.now().subtract(Duration(days: 90)))) { + .isAfter(DateTime.now().subtract(const Duration(days: 90)))) { force = true; } @@ -124,7 +127,7 @@ Future performTwonlySafeBackup({bool force = false}) async { if (lastHash != null && !force) { if (backupHash == lastHash) { - Log.info("Since last backup nothing has changed."); + Log.info('Since last backup nothing has changed.'); return; } } @@ -144,25 +147,25 @@ Future performTwonlySafeBackup({bool force = false}) async { nonce: nonce, ); - final encryptedBackupBytes = (TwonlySafeBackupEncrypted( + final encryptedBackupBytes = TwonlySafeBackupEncrypted( mac: secretBox.mac.bytes, nonce: nonce, cipherText: secretBox.cipherText, - )).writeToBuffer(); + ).writeToBuffer(); - Log.info("Backup files created."); + Log.info('Backup files created.'); - var encryptedBackupBytesFile = - File(join(backupDir.path, "twonly_safe.backup")); + final encryptedBackupBytesFile = + File(join(backupDir.path, 'twonly_safe.backup')); await encryptedBackupBytesFile.writeAsBytes(encryptedBackupBytes); Log.info( - "Create twonly Safe backup with a size of ${encryptedBackupBytes.length} bytes."); + 'Create twonly Safe backup with a size of ${encryptedBackupBytes.length} bytes.'); if (user.backupServer != null) { if (encryptedBackupBytes.length > user.backupServer!.maxBackupBytes) { - Log.error("Backup is to big for the alternative backup server."); + Log.error('Backup is to big for the alternative backup server.'); await updateUserdata((user) { user.twonlySafeBackup!.backupUploadState = LastBackupUploadState.failed; return user; @@ -172,20 +175,20 @@ Future performTwonlySafeBackup({bool force = false}) async { } final task = UploadTask.fromFile( - taskId: "backup", + taskId: 'backup', file: encryptedBackupBytesFile, - httpRequestMethod: "PUT", + httpRequestMethod: 'PUT', url: (await getTwonlySafeBackupUrl())!, // requiresWiFi: true, priority: 5, post: 'binary', retries: 2, headers: { - "Content-Type": "application/octet-stream", + 'Content-Type': 'application/octet-stream', }, ); if (await FileDownloader().enqueue(task)) { - Log.info("Starting upload from twonly Safe backup."); + Log.info('Starting upload from twonly Safe backup.'); await updateUserdata((user) { user.twonlySafeBackup!.backupUploadState = LastBackupUploadState.pending; user.twonlySafeBackup!.lastBackupDone = DateTime.now(); @@ -194,15 +197,15 @@ Future performTwonlySafeBackup({bool force = false}) async { }); gUpdateBackupView(); } else { - Log.error("Error starting UploadTask for twonly Safe."); + Log.error('Error starting UploadTask for twonly Safe.'); } } -Future handleBackupStatusUpdate(TaskStatusUpdate update) async { +Future handleBackupStatusUpdate(TaskStatusUpdate update) async { if (update.status == TaskStatus.failed || update.status == TaskStatus.canceled) { Log.error( - "twonly Safe upload failed. ${update.responseStatusCode} ${update.responseBody} ${update.responseHeaders} ${update.exception}"); + 'twonly Safe upload failed. ${update.responseStatusCode} ${update.responseBody} ${update.responseHeaders} ${update.exception}'); await updateUserdata((user) { if (user.twonlySafeBackup != null) { user.twonlySafeBackup!.backupUploadState = LastBackupUploadState.failed; @@ -211,7 +214,7 @@ Future handleBackupStatusUpdate(TaskStatusUpdate update) async { }); } else if (update.status == TaskStatus.complete) { Log.error( - "twonly Safe uploaded with status code ${update.responseStatusCode}"); + 'twonly Safe uploaded with status code ${update.responseStatusCode}'); await updateUserdata((user) { if (user.twonlySafeBackup != null) { user.twonlySafeBackup!.backupUploadState = @@ -220,7 +223,7 @@ Future handleBackupStatusUpdate(TaskStatusUpdate update) async { return user; }); } else { - Log.info("Backup is in state: ${update.status}"); + Log.info('Backup is in state: ${update.status}'); return; } gUpdateBackupView(); diff --git a/lib/src/services/twonly_safe/restore.twonly_safe.dart b/lib/src/services/twonly_safe/restore.twonly_safe.dart index 64fbf30..e6d4eaf 100644 --- a/lib/src/services/twonly_safe/restore.twonly_safe.dart +++ b/lib/src/services/twonly_safe/restore.twonly_safe.dart @@ -1,3 +1,5 @@ +// ignore_for_file: avoid_dynamic_calls + import 'dart:convert'; import 'dart:io'; import 'package:cryptography_flutter_plus/cryptography_flutter_plus.dart'; @@ -15,19 +17,19 @@ import 'package:twonly/src/model/protobuf/backup/backup.pb.dart'; import 'package:twonly/src/services/twonly_safe/common.twonly_safe.dart'; import 'package:twonly/src/utils/log.dart'; -Future recoverTwonlySafe( +Future recoverTwonlySafe( String username, String password, BackupServer? server, ) async { final (backupId, encryptionKey) = await getMasterKey(password, username); - String? backupServerUrl = + final backupServerUrl = await getTwonlySafeBackupUrlFromServer(backupId, server); if (backupServerUrl == null) { - Log.error("Could not create backup url"); - throw Exception("Could not create backup server url"); + Log.error('Could not create backup url'); + throw Exception('Could not create backup server url'); } late Uint8List backupData; @@ -39,7 +41,7 @@ Future recoverTwonlySafe( }); } catch (e) { Log.error('Error fetching backup: $e'); - throw Exception("Backup server could not be reached. ($e)"); + throw Exception('Backup server could not be reached. ($e)'); } switch (response.statusCode) { @@ -55,19 +57,18 @@ Future recoverTwonlySafe( throw Exception('Unexpected error: ${response.statusCode}'); } - return await handleBackupData(encryptionKey, backupData); + return handleBackupData(encryptionKey, backupData); } -Future handleBackupData( +Future handleBackupData( Uint8List encryptionKey, Uint8List backupData, ) async { - TwonlySafeBackupEncrypted encryptedBackup = - TwonlySafeBackupEncrypted.fromBuffer( + final encryptedBackup = TwonlySafeBackupEncrypted.fromBuffer( backupData, ); - SecretBox secretBox = SecretBox( + final secretBox = SecretBox( encryptedBackup.cipherText, nonce: encryptedBackup.nonce, mac: Mac(encryptedBackup.mac), @@ -80,12 +81,12 @@ Future handleBackupData( final plaintextBytes = gzip.decode(compressedBytes); - TwonlySafeBackupContent backupContent = TwonlySafeBackupContent.fromBuffer( + final backupContent = TwonlySafeBackupContent.fromBuffer( plaintextBytes, ); final baseDir = (await getApplicationSupportDirectory()).path; - final originalDatabase = File(join(baseDir, "twonly_database.sqlite")); + final originalDatabase = File(join(baseDir, 'twonly_database.sqlite')); await originalDatabase.writeAsBytes(backupContent.twonlyDatabase); /// When restoring the last message ID must be increased otherwise @@ -106,33 +107,33 @@ Future handleBackupData( if (randomUserId != null) { // for each day add 400 message ids - var dummyMessagesCounter = (lastMessageSend + 1) * 400; + final dummyMessagesCounter = (lastMessageSend + 1) * 400; Log.info( - "Creating $dummyMessagesCounter dummy messages to increase message counter as last message was $lastMessageSend days ago."); + 'Creating $dummyMessagesCounter dummy messages to increase message counter as last message was $lastMessageSend days ago.'); for (var i = 0; i < dummyMessagesCounter; i++) { await database.messagesDao.insertMessage( MessagesCompanion( contactId: Value(randomUserId), - kind: Value(MessageKind.ack), - acknowledgeByServer: Value(true), - errorWhileSending: Value(true), + kind: const Value(MessageKind.ack), + acknowledgeByServer: const Value(true), + errorWhileSending: const Value(true), ), ); } await database.messagesDao.deleteAllMessagesByContactId(randomUserId); } - final storage = FlutterSecureStorage(); + const storage = FlutterSecureStorage(); final secureStorage = jsonDecode(backupContent.secureStorageJson); await storage.write( key: SecureStorageKeys.signalIdentity, - value: secureStorage[SecureStorageKeys.signalIdentity]); + value: secureStorage[SecureStorageKeys.signalIdentity] as String); await storage.write( key: SecureStorageKeys.signalSignedPreKey, - value: secureStorage[SecureStorageKeys.signalSignedPreKey]); + value: secureStorage[SecureStorageKeys.signalSignedPreKey] as String); await storage.write( key: SecureStorageKeys.userData, - value: secureStorage[SecureStorageKeys.userData]); + value: secureStorage[SecureStorageKeys.userData] as String); } diff --git a/lib/src/utils/keyvalue.dart b/lib/src/utils/keyvalue.dart index 916ed0e..05e5639 100644 --- a/lib/src/utils/keyvalue.dart +++ b/lib/src/utils/keyvalue.dart @@ -15,9 +15,9 @@ class KeyValueStore { final file = File(filePath); // Check if the file exists - if (await file.exists()) { + if (file.existsSync()) { final contents = await file.readAsString(); - return jsonDecode(contents); + return jsonDecode(contents) as Map; } else { return null; // File does not exist } diff --git a/lib/src/utils/log.dart b/lib/src/utils/log.dart index f18f4ec..39391e0 100644 --- a/lib/src/utils/log.dart +++ b/lib/src/utils/log.dart @@ -43,13 +43,6 @@ Future loadLogFile() async { } } -Future cleanLogFile() async { - final str = await loadLogFile(); - if (str.contains("secureStorageBytes")) { - deleteLogFile(); - } -} - Future _writeLogToFile(LogRecord record) async { final directory = await getApplicationSupportDirectory(); final logFile = File('${directory.path}/app.log'); diff --git a/lib/src/utils/misc.dart b/lib/src/utils/misc.dart index cbd592e..f02321c 100644 --- a/lib/src/utils/misc.dart +++ b/lib/src/utils/misc.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:math'; + import 'package:drift/drift.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -12,9 +13,9 @@ import 'package:provider/provider.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/localization/generated/app_localizations.dart'; import 'package:twonly/src/model/json/message.dart'; import 'package:twonly/src/model/protobuf/api/websocket/error.pb.dart'; -import 'package:twonly/src/localization/generated/app_localizations.dart'; import 'package:twonly/src/providers/settings.provider.dart'; import 'package:twonly/src/utils/log.dart'; @@ -51,10 +52,10 @@ Future saveVideoToGallery(String videoPath) async { } Uint8List getRandomUint8List(int length) { - final Random random = Random.secure(); - final Uint8List randomBytes = Uint8List(length); + final random = Random.secure(); + final randomBytes = Uint8List(length); - for (int i = 0; i < length; i++) { + for (var i = 0; i < length; i++) { randomBytes[i] = random.nextInt(256); // Generate a random byte (0-255) } @@ -62,6 +63,7 @@ Uint8List getRandomUint8List(int length) { } String errorCodeToText(BuildContext context, ErrorCode code) { + // ignore: exhaustive_cases switch (code) { case ErrorCode.InternalError: return context.lang.errorInternalError; @@ -81,22 +83,21 @@ String errorCodeToText(BuildContext context, ErrorCode code) { return context.lang.errorVoucherInvalid; case ErrorCode.PlanUpgradeNotYearly: return context.lang.errorPlanUpgradeNotYearly; - default: - return code.toString(); // Fallback for unrecognized keys } + return code.toString(); // Fallback for unrecognized keys } String formatDuration(int seconds) { if (seconds < 60) { return '$seconds Sec.'; } else if (seconds < 3600) { - int minutes = seconds ~/ 60; + final minutes = seconds ~/ 60; return '$minutes Min.'; } else if (seconds < 86400) { - int hours = seconds ~/ 3600; + final hours = seconds ~/ 3600; return '$hours Hrs.'; // Assuming "Stu." is for hours } else { - int days = seconds ~/ 86400; + final days = seconds ~/ 86400; return '$days Days'; } } @@ -107,20 +108,19 @@ InputDecoration getInputDecoration(BuildContext context, String hintText) { return InputDecoration( hintText: hintText, focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(9.0), - borderSide: BorderSide(color: primaryColor, width: 1.0), + borderRadius: BorderRadius.circular(9), + borderSide: BorderSide(color: primaryColor), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(8.0), - borderSide: - BorderSide(color: Theme.of(context).colorScheme.outline, width: 1.0), + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline), ), - contentPadding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0), + contentPadding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20), ); } Future getCompressedImage(Uint8List imageBytes) async { - var result = await FlutterImageCompress.compressWithList( + final result = await FlutterImageCompress.compressWithList( imageBytes, quality: 90, ); @@ -130,8 +130,8 @@ Future getCompressedImage(Uint8List imageBytes) async { Future authenticateUser(String localizedReason, {bool force = true}) async { try { - final LocalAuthentication auth = LocalAuthentication(); - bool didAuthenticate = await auth.authenticate( + final auth = LocalAuthentication(); + final didAuthenticate = await auth.authenticate( localizedReason: localizedReason, options: const AuthenticationOptions(useErrorDialogs: false)); if (didAuthenticate) { @@ -147,31 +147,30 @@ Future authenticateUser(String localizedReason, } Uint8List intToBytes(int value) { - final byteData = ByteData(4); - byteData.setInt32(0, value, Endian.big); + final byteData = ByteData(4)..setInt32(0, value); return byteData.buffer.asUint8List(); } int bytesToInt(Uint8List bytes) { final byteData = ByteData.sublistView(bytes); - return byteData.getInt32(0, Endian.big); + return byteData.getInt32(0); } List? removeLastXBytes(Uint8List original, int count) { if (original.length < count) { return null; } - final newList = Uint8List(original.length - count); - newList.setAll(0, original.sublist(0, original.length - count)); + final newList = Uint8List(original.length - count) + ..setAll(0, original.sublist(0, original.length - count)); final lastXBytes = original.sublist(original.length - count); return [newList, lastXBytes]; } bool isDarkMode(BuildContext context) { - ThemeMode? selectedTheme = context.read().themeMode; + final selectedTheme = context.read().themeMode; - bool isDarkMode = + final isDarkMode = MediaQuery.of(context).platformBrightness == Brightness.dark; return selectedTheme == ThemeMode.dark || @@ -188,20 +187,20 @@ bool isToday(DateTime lastImageSend) { InputDecoration inputTextMessageDeco(BuildContext context) { return InputDecoration( hintText: context.lang.chatListDetailInput, - contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), + contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: - BorderSide(color: Theme.of(context).colorScheme.primary, width: 2.0), + BorderSide(color: Theme.of(context).colorScheme.primary, width: 2), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(20.0), + borderRadius: BorderRadius.circular(20), borderSide: - BorderSide(color: Theme.of(context).colorScheme.primary, width: 2.0), + BorderSide(color: Theme.of(context).colorScheme.primary, width: 2), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(20.0), - borderSide: BorderSide(color: Colors.grey, width: 2.0), + borderRadius: BorderRadius.circular(20), + borderSide: const BorderSide(color: Colors.grey, width: 2), ), ); } @@ -213,8 +212,8 @@ String truncateString(String input, {int maxLength = 20}) { return input; } -Future insertDemoContacts() async { - List commonUsernames = [ +Future insertDemoContacts() async { + final commonUsernames = [ 'James', 'Mary', 'John', @@ -236,7 +235,7 @@ Future insertDemoContacts() async { 'Thomas', 'Karen', ]; - final List> contactConfigs = [ + final contactConfigs = >[ {'count': 3, 'requested': true}, {'count': 4, 'requested': false, 'accepted': true}, {'count': 1, 'accepted': true, 'blocked': true}, @@ -245,43 +244,44 @@ Future insertDemoContacts() async { {'count': 1, 'requested': false}, ]; - int counter = 0; + var counter = 0; - for (var config in contactConfigs) { - for (int i = 0; i < config['count']; i++) { + for (final config in contactConfigs) { + for (var i = 0; i < (config['count'] as int); i++) { if (counter >= commonUsernames.length) { break; } - String username = commonUsernames[counter]; - int userId = Random().nextInt(1000000); + final username = commonUsernames[counter]; + final userId = Random().nextInt(1000000); await twonlyDB.contactsDao.insertContact( ContactsCompanion( username: Value(username), userId: Value(userId), - requested: Value(config['requested'] ?? false), - accepted: Value(config['accepted'] ?? false), - blocked: Value(config['blocked'] ?? false), - archived: Value(config['archived'] ?? false), - pinned: Value(config['pinned'] ?? false), + requested: Value(config['requested'] as bool? ?? false), + accepted: Value(config['accepted'] as bool? ?? false), + blocked: Value(config['blocked'] as bool? ?? false), + archived: Value(config['archived'] as bool? ?? false), + pinned: Value(config['pinned'] as bool? ?? false), ), ); - if (config['accepted'] ?? false) { + if (config['accepted'] as bool? ?? false) { for (var i = 0; i < 20; i++) { - int chatId = Random().nextInt(chatMessages.length); + final chatId = Random().nextInt(chatMessages.length); await twonlyDB.messagesDao.insertMessage( MessagesCompanion( contactId: Value(userId), - kind: Value(MessageKind.textMessage), - sendAt: Value(chatMessages[chatId][1]), - acknowledgeByServer: Value(true), - acknowledgeByUser: Value(true), + kind: const Value(MessageKind.textMessage), + sendAt: Value(chatMessages[chatId][1] as DateTime), + acknowledgeByServer: const Value(true), + acknowledgeByUser: const Value(true), messageOtherId: Value(Random().nextBool() ? Random().nextInt(10000) : null), // responseToOtherMessageId: Value(content.responseToMessageId), // responseToMessageId: Value(content.responseToOtherMessageId), - downloadState: Value(DownloadState.downloaded), + downloadState: const Value(DownloadState.downloaded), contentJson: Value( - jsonEncode(TextMessageContent(text: chatMessages[chatId][0])), + jsonEncode(TextMessageContent( + text: chatMessages[chatId][0] as String)), ), ), ); @@ -292,91 +292,94 @@ Future insertDemoContacts() async { } } -Future createFakeDemoData() async { +Future createFakeDemoData() async { await insertDemoContacts(); } List> chatMessages = [ [ - "Lorem ipsum dolor sit amet.", - DateTime.now().subtract(Duration(minutes: 20)) + 'Lorem ipsum dolor sit amet.', + DateTime.now().subtract(const Duration(minutes: 20)) ], [ - "Consectetur adipiscing elit.", - DateTime.now().subtract(Duration(minutes: 19)) + 'Consectetur adipiscing elit.', + DateTime.now().subtract(const Duration(minutes: 19)) ], [ - "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", - DateTime.now().subtract(Duration(minutes: 18)) - ], - ["Ut enim ad minim veniam.", DateTime.now().subtract(Duration(minutes: 17))], - [ - "Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - DateTime.now().subtract(Duration(minutes: 16)) + 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + DateTime.now().subtract(const Duration(minutes: 18)) ], [ - "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", - DateTime.now().subtract(Duration(minutes: 15)) + 'Ut enim ad minim veniam.', + DateTime.now().subtract(const Duration(minutes: 17)) ], [ - "Excepteur sint occaecat cupidatat non proident.", - DateTime.now().subtract(Duration(minutes: 14)) + 'Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', + DateTime.now().subtract(const Duration(minutes: 16)) ], [ - "Sunt in culpa qui officia deserunt mollit anim id est laborum.", - DateTime.now().subtract(Duration(minutes: 13)) + 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', + DateTime.now().subtract(const Duration(minutes: 15)) ], [ - "Curabitur pretium tincidunt lacus.", - DateTime.now().subtract(Duration(minutes: 12)) - ], - ["Nulla facilisi.", DateTime.now().subtract(Duration(minutes: 11))], - [ - "Aenean lacinia bibendum nulla sed consectetur.", - DateTime.now().subtract(Duration(minutes: 10)) + 'Excepteur sint occaecat cupidatat non proident.', + DateTime.now().subtract(const Duration(minutes: 14)) ], [ - "Sed posuere consectetur est at lobortis.", - DateTime.now().subtract(Duration(minutes: 9)) + 'Sunt in culpa qui officia deserunt mollit anim id est laborum.', + DateTime.now().subtract(const Duration(minutes: 13)) ], [ - "Vestibulum id ligula porta felis euismod semper.", - DateTime.now().subtract(Duration(minutes: 8)) + 'Curabitur pretium tincidunt lacus.', + DateTime.now().subtract(const Duration(minutes: 12)) + ], + ['Nulla facilisi.', DateTime.now().subtract(const Duration(minutes: 11))], + [ + 'Aenean lacinia bibendum nulla sed consectetur.', + DateTime.now().subtract(const Duration(minutes: 10)) ], [ - "Cras justo odio, dapibus ac facilisis in, egestas eget quam.", - DateTime.now().subtract(Duration(minutes: 7)) + 'Sed posuere consectetur est at lobortis.', + DateTime.now().subtract(const Duration(minutes: 9)) ], [ - "Morbi leo risus, porta ac consectetur ac, vestibulum at eros.", - DateTime.now().subtract(Duration(minutes: 6)) + 'Vestibulum id ligula porta felis euismod semper.', + DateTime.now().subtract(const Duration(minutes: 8)) ], [ - "Praesent commodo cursus magna, vel scelerisque nisl consectetur et.", - DateTime.now().subtract(Duration(minutes: 5)) + 'Cras justo odio, dapibus ac facilisis in, egestas eget quam.', + DateTime.now().subtract(const Duration(minutes: 7)) ], [ - "Donec ullamcorper nulla non metus auctor fringilla.", - DateTime.now().subtract(Duration(minutes: 4)) + 'Morbi leo risus, porta ac consectetur ac, vestibulum at eros.', + DateTime.now().subtract(const Duration(minutes: 6)) ], [ - "Etiam porta sem malesuada magna mollis euismod.", - DateTime.now().subtract(Duration(minutes: 3)) + 'Praesent commodo cursus magna, vel scelerisque nisl consectetur et.', + DateTime.now().subtract(const Duration(minutes: 5)) ], [ - "Aenean lacinia bibendum nulla sed consectetur.", - DateTime.now().subtract(Duration(minutes: 2)) + 'Donec ullamcorper nulla non metus auctor fringilla.', + DateTime.now().subtract(const Duration(minutes: 4)) ], [ - "Nullam quis risus eget urna mollis ornare vel eu leo.", - DateTime.now().subtract(Duration(minutes: 1)) + 'Etiam porta sem malesuada magna mollis euismod.', + DateTime.now().subtract(const Duration(minutes: 3)) ], - ["Curabitur blandit tempus porttitor.", DateTime.now()], + [ + 'Aenean lacinia bibendum nulla sed consectetur.', + DateTime.now().subtract(const Duration(minutes: 2)) + ], + [ + 'Nullam quis risus eget urna mollis ornare vel eu leo.', + DateTime.now().subtract(const Duration(minutes: 1)) + ], + ['Curabitur blandit tempus porttitor.', DateTime.now()], ]; String formatDateTime(BuildContext context, DateTime? dateTime) { if (dateTime == null) { - return "Never"; + return 'Never'; } final now = DateTime.now(); final difference = now.difference(dateTime); @@ -390,32 +393,34 @@ String formatDateTime(BuildContext context, DateTime? dateTime) { if (difference.inDays == 0) { return time; } else { - return "$time $date"; + return '$time $date'; } } String formatBytes(int bytes, {int decimalPlaces = 2}) { - if (bytes <= 0) return "0 Bytes"; - const List units = ["Bytes", "KB", "MB", "GB", "TB"]; - final int unitIndex = (log(bytes) / log(1000)).floor(); - final double formattedSize = bytes / pow(1000, unitIndex); - return "${formattedSize.toStringAsFixed(decimalPlaces)} ${units[unitIndex]}"; + if (bytes <= 0) return '0 Bytes'; + const units = ['Bytes', 'KB', 'MB', 'GB', 'TB']; + final unitIndex = (log(bytes) / log(1000)).floor(); + final formattedSize = bytes / pow(1000, unitIndex); + return '${formattedSize.toStringAsFixed(decimalPlaces)} ${units[unitIndex]}'; } String getMessageText(Message message) { try { - if (message.contentJson == null) return ""; - return TextMessageContent.fromJson(jsonDecode(message.contentJson!)).text; + if (message.contentJson == null) return ''; + return TextMessageContent.fromJson(jsonDecode(message.contentJson!) as Map) + .text; } catch (e) { Log.error(e); - return ""; + return ''; } } MediaMessageContent? getMediaContent(Message message) { try { if (message.contentJson == null) return null; - return MediaMessageContent.fromJson(jsonDecode(message.contentJson!)); + return MediaMessageContent.fromJson( + jsonDecode(message.contentJson!) as Map); } catch (e) { Log.error(e); return null; diff --git a/lib/src/utils/storage.dart b/lib/src/utils/storage.dart index 54cf5cd..052c584 100644 --- a/lib/src/utils/storage.dart +++ b/lib/src/utils/storage.dart @@ -10,7 +10,7 @@ import 'package:twonly/src/providers/connection.provider.dart'; import 'package:twonly/src/utils/log.dart'; Future isUserCreated() async { - UserData? user = await getUser(); + final user = await getUser(); if (user == null) { return false; } @@ -18,8 +18,8 @@ Future isUserCreated() async { } Future getUser() async { - String? userJson = - await FlutterSecureStorage().read(key: SecureStorageKeys.userData); + final userJson = + await const FlutterSecureStorage().read(key: SecureStorageKeys.userData); if (userJson == null) { return null; } @@ -28,12 +28,12 @@ Future getUser() async { final user = UserData.fromJson(userMap); return user; } catch (e) { - Log.error("Error getting user: $e"); + Log.error('Error getting user: $e'); return null; } } -Future updateUsersPlan(BuildContext context, String planId) async { +Future updateUsersPlan(BuildContext context, String planId) async { context.read().plan = planId; await updateUserdata((user) { @@ -42,17 +42,18 @@ Future updateUsersPlan(BuildContext context, String planId) async { }); if (!context.mounted) return; - context.read().updatePlan(planId); + await context.read().updatePlan(planId); } Mutex updateProtection = Mutex(); -Future updateUserdata(Function(UserData userData) updateUser) async { - return await updateProtection.protect(() async { +Future updateUserdata( + UserData Function(UserData userData) updateUser) async { + return updateProtection.protect(() async { final user = await getUser(); if (user == null) return null; - UserData updated = updateUser(user); - FlutterSecureStorage() + final updated = updateUser(user); + await const FlutterSecureStorage() .write(key: SecureStorageKeys.userData, value: jsonEncode(updated)); return user; }); @@ -63,6 +64,6 @@ Future deleteLocalUserData() async { if (appDir.existsSync()) { appDir.deleteSync(recursive: true); } - await FlutterSecureStorage().deleteAll(); + await const FlutterSecureStorage().deleteAll(); return true; } diff --git a/lib/src/views/camera/camera_preview_components/zoom_selector.dart b/lib/src/views/camera/camera_preview_components/zoom_selector.dart index 85cbf35..08c1d5b 100644 --- a/lib/src/views/camera/camera_preview_components/zoom_selector.dart +++ b/lib/src/views/camera/camera_preview_components/zoom_selector.dart @@ -36,7 +36,7 @@ class _CameraZoomButtonsState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { showWideAngleZoom = (await widget.controller.getMinZoomLevel()) < 1; if (_isDisposed) return; setState(() {}); diff --git a/lib/src/views/camera/camera_preview_controller_view.dart b/lib/src/views/camera/camera_preview_controller_view.dart index 447bbd4..612ed5a 100644 --- a/lib/src/views/camera/camera_preview_controller_view.dart +++ b/lib/src/views/camera/camera_preview_controller_view.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:io'; + import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -8,18 +9,18 @@ import 'package:image_picker/image_picker.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:screenshot/screenshot.dart'; import 'package:twonly/globals.dart'; +import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/utils/log.dart'; +import 'package:twonly/src/utils/misc.dart'; +import 'package:twonly/src/views/camera/camera_preview_components/permissions_view.dart'; import 'package:twonly/src/views/camera/camera_preview_components/send_to.dart'; import 'package:twonly/src/views/camera/camera_preview_components/video_recording_time.dart'; import 'package:twonly/src/views/camera/camera_preview_components/zoom_selector.dart'; -import 'package:twonly/src/database/daos/contacts_dao.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/camera/camera_send_to_view.dart'; import 'package:twonly/src/views/camera/image_editor/action_button.dart'; -import 'package:twonly/src/views/components/media_view_sizing.dart'; -import 'package:twonly/src/views/camera/camera_preview_components/permissions_view.dart'; import 'package:twonly/src/views/camera/share_image_editor_view.dart'; +import 'package:twonly/src/views/components/media_view_sizing.dart'; import 'package:twonly/src/views/home.view.dart'; int maxVideoRecordingTime = 15; @@ -43,7 +44,7 @@ Future<(SelectedCameraDetails, CameraController)?> initializeCameraController( details.scaleFactor = 1; } - CameraController cameraController = CameraController( + final cameraController = CameraController( gCameras[sCameraId], ResolutionPreset.high, enableAudio: enableAudio, @@ -52,7 +53,7 @@ Future<(SelectedCameraDetails, CameraController)?> initializeCameraController( await cameraController.initialize().then((_) async { await cameraController.setZoomLevel(details.scaleFactor); await cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp); - cameraController + await cameraController .setFlashMode(details.isFlashOn ? FlashMode.always : FlashMode.off); await cameraController .getMaxZoomLevel() @@ -60,9 +61,10 @@ Future<(SelectedCameraDetails, CameraController)?> initializeCameraController( await cameraController .getMinZoomLevel() .then((double value) => details.minAvailableZoom = value); - details.isZoomAble = details.maxAvailableZoom != details.minAvailableZoom; - details.cameraLoaded = true; - details.cameraId = sCameraId; + details + ..isZoomAble = details.maxAvailableZoom != details.minAvailableZoom + ..cameraLoaded = true + ..cameraId = sCameraId; }).catchError((Object e) { Log.error("$e"); }); @@ -81,13 +83,13 @@ class SelectedCameraDetails { class CameraPreviewControllerView extends StatefulWidget { const CameraPreviewControllerView({ - super.key, required this.selectCamera, required this.isHomeView, + super.key, this.sendTo, }); final Contact? sendTo; - final Function(int sCameraId, bool init, bool enableAudio) selectCamera; + final void Function(int sCameraId, bool init, bool enableAudio) selectCamera; final bool isHomeView; @override @@ -123,13 +125,13 @@ class _CameraPreviewControllerView extends State { class CameraPreviewView extends StatefulWidget { const CameraPreviewView( - {super.key, - this.sendTo, - required this.selectCamera, - required this.isHomeView}); + {required this.selectCamera, + required this.isHomeView, + super.key, + this.sendTo}); final Contact? sendTo; final bool isHomeView; - final Function(int sCameraId, bool init, bool enableAudio) selectCamera; + final void Function(int sCameraId, bool init, bool enableAudio) selectCamera; @override State createState() => _CameraPreviewViewState(); @@ -171,7 +173,7 @@ class _CameraPreviewViewState extends State { ? HomeViewState.screenshotController : CameraSendToViewState.screenshotController; - void initAsync() async { + Future initAsync() async { hasAudioPermission = await Permission.microphone.isGranted; if (!mounted) return; setState(() {}); @@ -183,12 +185,12 @@ class _CameraPreviewViewState extends State { super.dispose(); } - Future requestMicrophonePermission() async { - Map statuses = await [ + Future requestMicrophonePermission() async { + final statuses = await [ Permission.microphone, ].request(); if (statuses[Permission.microphone]!.isPermanentlyDenied) { - openAppSettings(); + await openAppSettings(); } else { hasAudioPermission = await Permission.microphone.isGranted; setState(() {}); @@ -221,7 +223,7 @@ class _CameraPreviewViewState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Error loading picture: $e'), - duration: Duration(seconds: 3), + duration: const Duration(seconds: 3), ), ); } @@ -229,7 +231,7 @@ class _CameraPreviewViewState extends State { } } - Future takePicture() async { + Future takePicture() async { if (sharePreviewIsShown || isVideoRecording) return; late Future imageBytes; @@ -242,16 +244,18 @@ class _CameraPreviewViewState extends State { showSelfieFlash = true; }); } else { - cameraController?.setFlashMode(FlashMode.torch); + await cameraController?.setFlashMode(FlashMode.torch); } - await Future.delayed(Duration(milliseconds: 1000)); + await Future.delayed(const Duration(milliseconds: 1000)); } await cameraController?.pausePreview(); if (!mounted) return; - cameraController?.setFlashMode( + await cameraController?.setFlashMode( selectedCameraDetails.isFlashOn ? FlashMode.always : FlashMode.off); + if (!mounted) return; + imageBytes = screenshotController.capture( pixelRatio: MediaQuery.of(context).devicePixelRatio); @@ -263,7 +267,7 @@ class _CameraPreviewViewState extends State { Future pushMediaEditor( Future? imageBytes, File? videoFilePath, {bool sharedFromGallery = false}) async { - bool? shouldReturn = await Navigator.push( + final shouldReturn = await Navigator.push( context, PageRouteBuilder( opaque: false, @@ -281,7 +285,7 @@ class _CameraPreviewViewState extends State { transitionDuration: Duration.zero, reverseTransitionDuration: Duration.zero, ), - ); + ) as bool?; if (mounted) { setState(() { sharePreviewIsShown = false; @@ -306,15 +310,16 @@ class _CameraPreviewViewState extends State { bool get isFront => cameraController?.description.lensDirection == CameraLensDirection.front; - Future onPanUpdate(details) async { - if (isFront) { + Future onPanUpdate(dynamic details) async { + if (isFront || details == null) { return; } if (cameraController == null) return; if (!cameraController!.value.isInitialized) return; selectedCameraDetails.scaleFactor = - (baseScaleFactor + (basePanY - details.localPosition.dy) / 30) + // ignore: avoid_dynamic_calls + (baseScaleFactor + (basePanY - (details.localPosition.dy as int)) / 30) .clamp(1, selectedCameraDetails.maxAvailableZoom); await cameraController!.setZoomLevel(selectedCameraDetails.scaleFactor); @@ -323,7 +328,7 @@ class _CameraPreviewViewState extends State { } } - Future pickImageFromGallery() async { + Future pickImageFromGallery() async { setState(() { galleryLoadedImageIsShown = true; sharePreviewIsShown = true; @@ -332,7 +337,7 @@ class _CameraPreviewViewState extends State { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { - File imageFile = File(pickedFile.path); + final imageFile = File(pickedFile.path); await pushMediaEditor( imageFile.readAsBytes(), null, @@ -345,12 +350,12 @@ class _CameraPreviewViewState extends State { }); } - Future startVideoRecording() async { + Future startVideoRecording() async { if (cameraController != null && cameraController!.value.isRecordingVideo) { return; } if (hasAudioPermission && videoWithAudio) { - await widget.selectCamera( + widget.selectCamera( selectedCameraDetails.cameraId, false, await Permission.microphone.isGranted && videoWithAudio, @@ -363,7 +368,8 @@ class _CameraPreviewViewState extends State { try { await cameraController?.startVideoRecording(); - videoRecordingTimer = Timer.periodic(Duration(milliseconds: 15), (timer) { + videoRecordingTimer = + Timer.periodic(const Duration(milliseconds: 15), (timer) { setState(() { currentTime = DateTime.now(); }); @@ -388,7 +394,7 @@ class _CameraPreviewViewState extends State { } } - Future stopVideoRecording() async { + Future stopVideoRecording() async { if (videoRecordingTimer != null) { videoRecordingTimer?.cancel(); videoRecordingTimer = null; @@ -404,7 +410,7 @@ class _CameraPreviewViewState extends State { sharePreviewIsShown = true; }); File? videoPathFile; - XFile? videoPath = await cameraController?.stopVideoRecording(); + final videoPath = await cameraController?.stopVideoRecording(); if (videoPath != null) { if (Platform.isAndroid) { // see https://github.com/flutter/flutter/issues/148335 @@ -432,7 +438,7 @@ class _CameraPreviewViewState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Error: $e'), - duration: Duration(seconds: 3), + duration: const Duration(seconds: 3), ), ); } @@ -464,10 +470,9 @@ class _CameraPreviewViewState extends State { baseScaleFactor = selectedCameraDetails.scaleFactor; }); // Get the position of the pointer - RenderBox renderBox = - keyTriggerButton.currentContext?.findRenderObject() as RenderBox; - Offset localPosition = - renderBox.globalToLocal(details.globalPosition); + final renderBox = + keyTriggerButton.currentContext!.findRenderObject()! as RenderBox; + final localPosition = renderBox.globalToLocal(details.globalPosition); final containerRect = Rect.fromLTWH(0, 0, renderBox.size.width, renderBox.size.height); @@ -620,7 +625,7 @@ class _CameraPreviewViewState extends State { height: 50, width: 80, padding: const EdgeInsets.all(2), - child: Center( + child: const Center( child: FaIcon( FontAwesomeIcons.photoFilm, color: Colors.white, @@ -653,7 +658,7 @@ class _CameraPreviewViewState extends State { ), ), ), - if (!isVideoRecording) SizedBox(width: 80) + if (!isVideoRecording) const SizedBox(width: 80) ], ), ], diff --git a/lib/src/views/camera/camera_send_to_view.dart b/lib/src/views/camera/camera_send_to_view.dart index cd73f69..c0d572b 100644 --- a/lib/src/views/camera/camera_send_to_view.dart +++ b/lib/src/views/camera/camera_send_to_view.dart @@ -31,7 +31,7 @@ class CameraSendToViewState extends State { super.dispose(); } - Future selectCamera(int sCameraId, bool init, bool enableAudio) async { + Future selectCamera(int sCameraId, bool init, bool enableAudio) async { final opts = await initializeCameraController( selectedCameraDetails, sCameraId, init, enableAudio); if (opts != null) { @@ -41,7 +41,7 @@ class CameraSendToViewState extends State { setState(() {}); } - Future toggleSelectedCamera() async { + Future toggleSelectedCamera() async { await cameraController?.dispose(); cameraController = null; selectCamera((selectedCameraDetails.cameraId + 1) % 2, false, false); diff --git a/lib/src/views/camera/image_editor/data/image_item.dart b/lib/src/views/camera/image_editor/data/image_item.dart index 96d53e5..a429698 100755 --- a/lib/src/views/camera/image_editor/data/image_item.dart +++ b/lib/src/views/camera/image_editor/data/image_item.dart @@ -12,7 +12,7 @@ class ImageItem { if (image != null) load(image); } - Future load(dynamic image) async { + Future load(dynamic image) async { loader = Completer(); if (image is ImageItem) { diff --git a/lib/src/views/camera/image_editor/layers/emoji_layer.dart b/lib/src/views/camera/image_editor/layers/emoji_layer.dart index 7dace2b..a5ff29a 100755 --- a/lib/src/views/camera/image_editor/layers/emoji_layer.dart +++ b/lib/src/views/camera/image_editor/layers/emoji_layer.dart @@ -6,24 +6,23 @@ import 'package:twonly/src/views/camera/image_editor/data/layer.dart'; /// Emoji layer class EmojiLayer extends StatefulWidget { + const EmojiLayer({ + required this.layerData, + super.key, + this.onUpdate, + }); final EmojiLayerData layerData; final VoidCallback? onUpdate; - const EmojiLayer({ - super.key, - required this.layerData, - this.onUpdate, - }); - @override - createState() => _EmojiLayerState(); + State createState() => _EmojiLayerState(); } class _EmojiLayerState extends State { double initialRotation = 0; Offset initialOffset = Offset.zero; Offset initialFocalPoint = Offset.zero; - double initialScale = 1.0; + double initialScale = 1; bool deleteLayer = false; bool twoPointerWhereDown = false; final GlobalKey outlineKey = GlobalKey(); @@ -94,16 +93,16 @@ class _EmojiLayerState extends State { if (twoPointerWhereDown == true && details.pointerCount != 2) { return; } - final RenderBox outlineBox = - outlineKey.currentContext!.findRenderObject() as RenderBox; + final outlineBox = + outlineKey.currentContext!.findRenderObject()! as RenderBox; - final RenderBox emojiBox = - emojiKey.currentContext!.findRenderObject() as RenderBox; + final emojiBox = + emojiKey.currentContext!.findRenderObject()! as RenderBox; - bool isAtTheBottom = + final isAtTheBottom = (widget.layerData.offset.dy + emojiBox.size.height / 2) > outlineBox.size.height - 80; - bool isInTheCenter = MediaQuery.of(context).size.width / 2 - + final isInTheCenter = MediaQuery.of(context).size.width / 2 - 30 < (widget.layerData.offset.dx + emojiBox.size.width / 2) && @@ -125,9 +124,9 @@ class _EmojiLayerState extends State { initialRotation + details.rotation; // Update the position based on the translation - var dx = (initialOffset.dx) + + final dx = (initialOffset.dx) + (details.focalPoint.dx - initialFocalPoint.dx); - var dy = (initialOffset.dy) + + final dy = (initialOffset.dy) + (details.focalPoint.dy - initialFocalPoint.dy); widget.layerData.offset = Offset(dx, dy); }); diff --git a/lib/src/views/camera/image_editor/layers/filter_layer.dart b/lib/src/views/camera/image_editor/layers/filter_layer.dart index 972b016..0e4b98c 100644 --- a/lib/src/views/camera/image_editor/layers/filter_layer.dart +++ b/lib/src/views/camera/image_editor/layers/filter_layer.dart @@ -7,14 +7,14 @@ import 'package:twonly/src/views/camera/image_editor/layers/filters/location_fil /// Main layer class FilterLayer extends StatefulWidget { - final FilterLayerData layerData; // final VoidCallback? onUpdate; const FilterLayer({ - super.key, required this.layerData, + super.key, // this.onUpdate, }); + final FilterLayerData layerData; @override State createState() => _FilterLayerState(); @@ -26,7 +26,7 @@ class FilterSkeleton extends StatelessWidget { @override Widget build(BuildContext context) { - return Container( + return ColoredBox( color: Colors.transparent, child: Stack( children: [ @@ -39,8 +39,12 @@ class FilterSkeleton extends StatelessWidget { } class FilterText extends StatelessWidget { - const FilterText(this.text, - {super.key, this.fontSize = 24, this.color = Colors.white}); + const FilterText( + this.text, { + super.key, + this.fontSize = 24, + this.color = Colors.white, + }); final String text; final double fontSize; final Color color; @@ -53,9 +57,9 @@ class FilterText extends StatelessWidget { style: TextStyle( fontSize: fontSize, color: color, - shadows: [ + shadows: const [ Shadow( - color: const Color.fromARGB(122, 0, 0, 0), + color: Color.fromARGB(122, 0, 0, 0), blurRadius: 5.0, ) ], @@ -67,10 +71,10 @@ class FilterText extends StatelessWidget { class _FilterLayerState extends State { final PageController pageController = PageController(); List pages = [ - FilterSkeleton(), - DateTimeFilter(), - LocationFilter(), - FilterSkeleton(), + const FilterSkeleton(), + const DateTimeFilter(), + const LocationFilter(), + const FilterSkeleton(), ]; @override @@ -82,11 +86,11 @@ class _FilterLayerState extends State { initAsync(); } - Future initAsync() async { - var stickers = (await getStickerIndex()) - .where((x) => x.imageSrc.contains("/imagefilter/")) - .toList(); - stickers.sortBy((x) => x.imageSrc); + Future initAsync() async { + final stickers = (await getStickerIndex()) + .where((x) => x.imageSrc.contains('/imagefilter/')) + .toList() + ..sortBy((x) => x.imageSrc); for (final sticker in stickers) { pages.insert(pages.length - 1, ImageFilter(imagePath: sticker.imageSrc)); diff --git a/lib/src/views/camera/image_editor/layers/filters/location_filter.dart b/lib/src/views/camera/image_editor/layers/filters/location_filter.dart index 282b539..ad2aa5a 100644 --- a/lib/src/views/camera/image_editor/layers/filters/location_filter.dart +++ b/lib/src/views/camera/image_editor/layers/filters/location_filter.dart @@ -1,15 +1,16 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:path_provider/path_provider.dart'; import 'package:twonly/globals.dart'; +import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/views/camera/image_editor/layers/filter_layer.dart'; import 'package:twonly/src/views/camera/image_editor/layers/filters/datetime_filter.dart'; -import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart'; -import 'dart:convert'; -import 'package:http/http.dart' as http; -import 'package:path_provider/path_provider.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'dart:io'; class LocationFilter extends StatefulWidget { const LocationFilter({super.key}); @@ -28,29 +29,30 @@ class _LocationFilterState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { final res = await apiService.getCurrentLocation(); if (res.isSuccess) { - location = res.value.location; - _searchForImage(); + // ignore: avoid_dynamic_calls + location = res.value.location as Response_Location?; + await _searchForImage(); if (mounted) setState(() {}); } } - void _searchForImage() async { + Future _searchForImage() async { if (location == null) return; - List imageIndex = await getStickerIndex(); + final imageIndex = await getStickerIndex(); // Normalize the city and country for search - String normalizedCity = location!.city.toLowerCase().replaceAll(' ', '_'); - String normalizedCountry = location!.county.toLowerCase(); + final normalizedCity = location!.city.toLowerCase().replaceAll(' ', '_'); + final normalizedCountry = location!.county.toLowerCase(); // Search for the city first - for (var item in imageIndex) { + for (final item in imageIndex) { if (item.imageSrc.contains('/cities/$normalizedCountry/')) { // Check if the item matches the normalized city if (item.imageSrc.endsWith('$normalizedCity.png')) { - if (item.imageSrc.startsWith("/api/")) { - _imageUrl = "https://twonly.eu/${item.imageSrc}"; + if (item.imageSrc.startsWith('/api/')) { + _imageUrl = 'https://twonly.eu/${item.imageSrc}'; if (mounted) setState(() {}); } return; @@ -60,11 +62,11 @@ class _LocationFilterState extends State { // If city not found, search for the country if (_imageUrl == null) { - for (var item in imageIndex) { + for (final item in imageIndex) { if (item.imageSrc.contains('/countries/') && item.imageSrc.contains(normalizedCountry)) { - if (item.imageSrc.startsWith("/api/")) { - _imageUrl = "https://twonly.eu/${item.imageSrc}"; + if (item.imageSrc.startsWith('/api/')) { + _imageUrl = 'https://twonly.eu/${item.imageSrc}'; if (mounted) setState(() {}); } break; @@ -91,7 +93,7 @@ class _LocationFilterState extends State { } if (location != null) { - if (location!.county != "-") { + if (location!.county != '-') { return FilterSkeleton( child: Positioned( bottom: 50, @@ -108,35 +110,35 @@ class _LocationFilterState extends State { } } - return DateTimeFilter(color: Colors.black); + return const DateTimeFilter(color: Colors.black); } } class Sticker { - final String imageSrc; - final String source; - Sticker({required this.imageSrc, required this.source}); - factory Sticker.fromJson(Map json) { return Sticker( - imageSrc: json['imageSrc'], - source: json['source'] ?? '', // Handle null source + imageSrc: json['imageSrc'] as String, + source: json['source'] as String? ?? '', ); } + final String imageSrc; + final String source; } Future> getStickerIndex() async { final directory = await getApplicationCacheDirectory(); final indexFile = File('${directory.path}/stickers.json'); - List res = []; + var res = []; if (await indexFile.exists() && !kDebugMode) { final lastModified = await indexFile.lastModified(); final difference = DateTime.now().difference(lastModified); final content = await indexFile.readAsString(); - List jsonList = json.decode(content); - res = jsonList.map((json) => Sticker.fromJson(json)).toList(); + final jsonList = json.decode(content) as List; + res = jsonList + .map((json) => Sticker.fromJson(json as Map)) + .toList(); if (difference.inHours < 2) { return res; } @@ -146,13 +148,15 @@ Future> getStickerIndex() async { .get(Uri.parse('https://twonly.eu/api/sticker/stickers.json')); if (response.statusCode == 200) { await indexFile.writeAsString(response.body); - List jsonList = json.decode(response.body); - return jsonList.map((json) => Sticker.fromJson(json)).toList(); + final jsonList = json.decode(response.body) as List; + return jsonList + .map((json) => Sticker.fromJson(json as Map)) + .toList(); } else { return res; } } catch (e) { - Log.error("$e"); + Log.error('$e'); return res; } } diff --git a/lib/src/views/camera/image_editor/layers/text_layer.dart b/lib/src/views/camera/image_editor/layers/text_layer.dart index d9c1377..db30d54 100755 --- a/lib/src/views/camera/image_editor/layers/text_layer.dart +++ b/lib/src/views/camera/image_editor/layers/text_layer.dart @@ -111,7 +111,7 @@ class _TextViewState extends State { ), ), textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( color: Colors.white, fontSize: 20, ), @@ -182,7 +182,7 @@ class _TextViewState extends State { child: Text( widget.layerData.text, textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( color: Colors.white, fontSize: 20, ), diff --git a/lib/src/views/camera/image_editor/layers_viewer.dart b/lib/src/views/camera/image_editor/layers_viewer.dart index 3239fb5..f6155f3 100644 --- a/lib/src/views/camera/image_editor/layers_viewer.dart +++ b/lib/src/views/camera/image_editor/layers_viewer.dart @@ -8,14 +8,13 @@ import 'package:twonly/src/views/camera/image_editor/layers/text_layer.dart'; /// View stacked layers (unbounded height, width) class LayersViewer extends StatelessWidget { - final List layers; - final Function()? onUpdate; - const LayersViewer({ - super.key, required this.layers, + super.key, this.onUpdate, }); + final List layers; + final void Function()? onUpdate; @override Widget build(BuildContext context) { diff --git a/lib/src/views/camera/image_editor/modules/all_emojis.dart b/lib/src/views/camera/image_editor/modules/all_emojis.dart index 2c03402..a3e2aed 100755 --- a/lib/src/views/camera/image_editor/modules/all_emojis.dart +++ b/lib/src/views/camera/image_editor/modules/all_emojis.dart @@ -19,7 +19,7 @@ class _EmojisState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { final user = await getUser(); if (user == null) return; setState(() { @@ -28,7 +28,7 @@ class _EmojisState extends State { }); } - Future selectEmojis(String emoji) async { + Future selectEmojis(String emoji) async { await updateUserdata((user) { if (user.lastUsedEditorEmojis == null) { user.lastUsedEditorEmojis = [emoji]; diff --git a/lib/src/views/camera/share_image_components/best_friends_selector.dart b/lib/src/views/camera/share_image_components/best_friends_selector.dart index 06fb5b1..c372b7a 100644 --- a/lib/src/views/camera/share_image_components/best_friends_selector.dart +++ b/lib/src/views/camera/share_image_components/best_friends_selector.dart @@ -1,29 +1,32 @@ +// ignore_for_file: strict_raw_type + import 'dart:collection'; + import 'package:flutter/material.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/views/components/verified_shield.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/components/flame.dart'; import 'package:twonly/src/views/components/headline.dart'; import 'package:twonly/src/views/components/initialsavatar.dart'; +import 'package:twonly/src/views/components/verified_shield.dart'; class BestFriendsSelector extends StatelessWidget { + const BestFriendsSelector({ + required this.users, + required this.isRealTwonly, + required this.updateStatus, + required this.selectedUserIds, + required this.title, + super.key, + }); final List users; - final Function(int, bool) updateStatus; + final void Function(int, bool) updateStatus; final HashSet selectedUserIds; final bool isRealTwonly; final String title; - const BestFriendsSelector( - {super.key, - required this.users, - required this.isRealTwonly, - required this.updateStatus, - required this.selectedUserIds, - required this.title}); - @override Widget build(BuildContext context) { if (users.isEmpty) { @@ -45,10 +48,11 @@ class BestFriendsSelector extends StatelessWidget { } }, child: Container( - padding: EdgeInsets.symmetric(horizontal: 7, vertical: 4), + padding: + const EdgeInsets.symmetric(horizontal: 7, vertical: 4), decoration: BoxDecoration( color: Theme.of(context).colorScheme.outline.withAlpha(50), - boxShadow: [ + boxShadow: const [ BoxShadow( blurRadius: 10.9, color: Color.fromRGBO(0, 0, 0, 0.1), @@ -57,7 +61,7 @@ class BestFriendsSelector extends StatelessWidget { borderRadius: BorderRadius.circular(8.0), ), child: Text(context.lang.shareImagedSelectAll, - style: TextStyle(fontSize: 10)), + style: const TextStyle(fontSize: 10)), ), ), ], @@ -81,19 +85,20 @@ class BestFriendsSelector extends StatelessWidget { isRealTwonly: isRealTwonly, ), ), - (secondUserIndex < users.length) - ? Expanded( - child: UserCheckbox( - isChecked: selectedUserIds - .contains(users[secondUserIndex].userId), - user: users[secondUserIndex], - onChanged: updateStatus, - isRealTwonly: isRealTwonly, - ), - ) - : Expanded( - child: Container(), - ), + if (secondUserIndex < users.length) + Expanded( + child: UserCheckbox( + isChecked: selectedUserIds + .contains(users[secondUserIndex].userId), + user: users[secondUserIndex], + onChanged: updateStatus, + isRealTwonly: isRealTwonly, + ), + ) + else + Expanded( + child: Container(), + ), ], ); }, @@ -105,35 +110,34 @@ class BestFriendsSelector extends StatelessWidget { } class UserCheckbox extends StatelessWidget { - final Contact user; - final Function(int, bool) onChanged; - final bool isChecked; - final bool isRealTwonly; - const UserCheckbox({ - super.key, required this.user, required this.onChanged, required this.isRealTwonly, required this.isChecked, + super.key, }); + final Contact user; + final void Function(int, bool) onChanged; + final bool isChecked; + final bool isRealTwonly; @override Widget build(BuildContext context) { - String displayName = getContactDisplayName(user); + final displayName = getContactDisplayName(user); return Container( - padding: - EdgeInsets.symmetric(horizontal: 3), // Padding inside the container + padding: const EdgeInsets.symmetric( + horizontal: 3), // Padding inside the container child: GestureDetector( onTap: () { onChanged(user.userId, !isChecked); }, child: Container( - padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0), + padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration( color: Theme.of(context).colorScheme.outline.withAlpha(50), - boxShadow: [ + boxShadow: const [ BoxShadow( blurRadius: 10.9, color: Color.fromRGBO(0, 0, 0, 0.1), @@ -147,16 +151,15 @@ class UserCheckbox extends StatelessWidget { contact: user, fontSize: 12, ), - SizedBox(width: 8), + const SizedBox(width: 8), Column( - mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ if (isRealTwonly) Padding( - padding: EdgeInsets.only(right: 2), + padding: const EdgeInsets.only(right: 2), child: VerifiedShield( user, size: 12, @@ -186,10 +189,10 @@ class UserCheckbox extends StatelessWidget { side: WidgetStateBorderSide.resolveWith( (Set states) { if (states.contains(WidgetState.selected)) { - return BorderSide(width: 0); + return const BorderSide(width: 0); } return BorderSide( - width: 1, color: Theme.of(context).colorScheme.outline); + color: Theme.of(context).colorScheme.outline); }, ), onChanged: (bool? value) { diff --git a/lib/src/views/camera/share_image_editor_view.dart b/lib/src/views/camera/share_image_editor_view.dart index 176ff89..7195094 100644 --- a/lib/src/views/camera/share_image_editor_view.dart +++ b/lib/src/views/camera/share_image_editor_view.dart @@ -1,28 +1,29 @@ +// ignore_for_file: inference_failure_on_function_invocation + +import 'dart:async'; import 'dart:collection'; import 'dart:io'; -import 'dart:async'; + import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; -import 'package:twonly/src/model/protobuf/api/websocket/error.pb.dart' - show ErrorCode; -import 'package:twonly/src/services/api/media_upload.dart'; -import 'package:twonly/src/utils/log.dart'; -import 'package:twonly/src/views/camera/camera_preview_components/save_to_gallery.dart'; -import 'package:twonly/src/views/camera/image_editor/action_button.dart'; -import 'package:twonly/src/views/components/alert_dialog.dart'; -import 'package:twonly/src/views/components/media_view_sizing.dart'; -import 'package:twonly/src/views/components/notification_badge.dart'; +import 'package:screenshot/screenshot.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/services/api/media_upload.dart'; +import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; -import 'package:twonly/src/views/camera/share_image_view.dart'; -import 'package:flutter/services.dart'; +import 'package:twonly/src/views/camera/camera_preview_components/save_to_gallery.dart'; +import 'package:twonly/src/views/camera/image_editor/action_button.dart'; import 'package:twonly/src/views/camera/image_editor/data/image_item.dart'; import 'package:twonly/src/views/camera/image_editor/data/layer.dart'; import 'package:twonly/src/views/camera/image_editor/layers_viewer.dart'; import 'package:twonly/src/views/camera/image_editor/modules/all_emojis.dart'; -import 'package:screenshot/screenshot.dart'; +import 'package:twonly/src/views/camera/share_image_view.dart'; +import 'package:twonly/src/views/components/alert_dialog.dart'; +import 'package:twonly/src/views/components/media_view_sizing.dart'; +import 'package:twonly/src/views/components/notification_badge.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; import 'package:video_player/video_player.dart'; @@ -34,13 +35,13 @@ const gMediaShowInfinite = 999999; class ShareImageEditorView extends StatefulWidget { const ShareImageEditorView({ + required this.mirrorVideo, + required this.useHighQuality, + required this.sharedFromGallery, super.key, this.imageBytes, this.sendTo, this.videoFilePath, - required this.mirrorVideo, - required this.useHighQuality, - required this.sharedFromGallery, }); final Future? imageBytes; final File? videoFilePath; @@ -87,9 +88,8 @@ class _ShareImageEditorView extends State { videoController?.initialize().then((_) { videoController!.play(); setState(() {}); - }).catchError((Object error) { - Log.error(error); - }); + // ignore: invalid_return_type_for_catch_error, argument_type_not_assignable_to_error_handler + }).catchError(Log.error); } } @@ -103,7 +103,7 @@ class _ShareImageEditorView extends State { } } - Future initMediaFileUpload() async { + Future initMediaFileUpload() async { // media init was already called... if (mediaUploadId != null) return; @@ -173,13 +173,13 @@ class _ShareImageEditorView extends State { Icons.add_reaction_outlined, tooltipText: context.lang.addEmoji, onPressed: () async { - EmojiLayerData? layer = await showModalBottomSheet( + final layer = await showModalBottomSheet( context: context, backgroundColor: Colors.black, builder: (BuildContext context) { return const Emojis(); }, - ); + ) as Layer?; if (layer == null) return; undoLayers.clear(); removedLayers.clear(); @@ -190,9 +190,9 @@ class _ShareImageEditorView extends State { const SizedBox(height: 8), NotificationBadge( count: (widget.videoFilePath != null) - ? "0" + ? '0' : maxShowTime == 999999 - ? "โˆž" + ? 'โˆž' : maxShowTime.toString(), child: ActionButton( (widget.videoFilePath != null) @@ -239,8 +239,11 @@ class _ShareImageEditorView extends State { onPressed: () async { if (widget.sendTo != null) { if (!widget.sendTo!.verified) { - showAlertDialog(context, context.lang.shareImageUserNotVerified, - context.lang.shareImageUserNotVerifiedDesc); + await showAlertDialog( + context, + context.lang.shareImageUserNotVerified, + context.lang.shareImageUserNotVerifiedDesc, + ); return; } } @@ -277,9 +280,9 @@ class _ShareImageEditorView extends State { disable: layers.where((x) => !x.isDeleted).length <= 2, onPressed: () { if (removedLayers.isNotEmpty) { - var lastLayer = removedLayers.removeLast(); - lastLayer.isDeleted = false; - lastLayer.isEditing = false; + final lastLayer = removedLayers.removeLast() + ..isDeleted = false + ..isEditing = false; layers.add(lastLayer); setState(() {}); return; @@ -308,15 +311,15 @@ class _ShareImageEditorView extends State { ]; } - Future pushShareImageView() async { + Future pushShareImageView() async { if (mediaUploadId == null) { await initMediaFileUpload(); if (mediaUploadId == null) return; } - Future imageBytes = getMergedImage(); - videoController?.pause(); + final imageBytes = getMergedImage(); + await videoController?.pause(); if (isDisposed || !mounted) return; - bool? wasSend = await Navigator.push( + final wasSend = await Navigator.push( context, MaterialPageRoute( builder: (context) => ShareImageView( @@ -330,12 +333,12 @@ class _ShareImageEditorView extends State { mirrorVideo: widget.mirrorVideo, ), ), - ); + ) as bool?; if (wasSend != null && wasSend && mounted) { // ignore: use_build_context_synchronously Navigator.pop(context, true); } else { - videoController?.play(); + await videoController?.play(); } } @@ -343,13 +346,13 @@ class _ShareImageEditorView extends State { Uint8List? image; if (layers.length > 1 || widget.videoFilePath != null) { - for (var x in layers) { + for (final x in layers) { x.showCustomButtons = false; } setState(() {}); image = await screenshotController.capture( pixelRatio: (widget.useHighQuality) ? pixelRatio : 1); - for (var x in layers) { + for (final x in layers) { x.showCustomButtons = true; } setState(() {}); @@ -362,7 +365,7 @@ class _ShareImageEditorView extends State { } Future loadImage(Future imageFile) async { - Uint8List? imageBytes = await imageFile; + final imageBytes = await imageFile; await currentImage.load(imageBytes); if (isDisposed) return; @@ -380,19 +383,19 @@ class _ShareImageEditorView extends State { }); } - Future sendImageToSinglePerson() async { + Future sendImageToSinglePerson() async { if (sendingOrLoadingImage) return; setState(() { sendingOrLoadingImage = true; }); - Uint8List? imageBytes = await getMergedImage(); + final imageBytes = await getMergedImage(); if (!context.mounted) return; if (imageBytes == null) { // ignore: use_build_context_synchronously Navigator.pop(context, true); return; } - ErrorCode? err = await isAllowedToSend(); + final err = await isAllowedToSend(); if (!context.mounted) return; if (err != null) { @@ -407,8 +410,7 @@ class _ShareImageEditorView extends State { })); } } else { - Future imageHandler = - addOrModifyImageToUpload(mediaUploadId!, imageBytes); + final imageHandler = addOrModifyImageToUpload(mediaUploadId!, imageBytes); // first finalize the upload await finalizeUpload( @@ -421,7 +423,7 @@ class _ShareImageEditorView extends State { ); /// then call the upload process in the background - encryptMediaFiles( + await encryptMediaFiles( mediaUploadId!, imageHandler, videoUploadHandler, @@ -526,7 +528,7 @@ class _ShareImageEditorView extends State { ), ], ), - bottomNavigationBar: Container( + bottomNavigationBar: ColoredBox( color: Theme.of(context).colorScheme.surface, child: SafeArea( child: Padding( @@ -541,7 +543,7 @@ class _ShareImageEditorView extends State { displayButtonLabel: widget.sendTo == null, isLoading: loadingImage, ), - if (widget.sendTo != null) SizedBox(width: 10), + if (widget.sendTo != null) const SizedBox(width: 10), if (widget.sendTo != null) OutlinedButton( style: OutlinedButton.styleFrom( @@ -549,7 +551,7 @@ class _ShareImageEditorView extends State { foregroundColor: Theme.of(context).colorScheme.primary, ), onPressed: pushShareImageView, - child: FaIcon(FontAwesomeIcons.userPlus), + child: const FaIcon(FontAwesomeIcons.userPlus), ), SizedBox(width: widget.sendTo == null ? 20 : 10), FilledButton.icon( @@ -562,22 +564,22 @@ class _ShareImageEditorView extends State { color: Theme.of(context).colorScheme.inversePrimary, ), ) - : FaIcon(FontAwesomeIcons.solidPaperPlane), + : const FaIcon(FontAwesomeIcons.solidPaperPlane), onPressed: () async { if (sendingOrLoadingImage) return; if (widget.sendTo == null) return pushShareImageView(); - sendImageToSinglePerson(); + await sendImageToSinglePerson(); }, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 30), + const EdgeInsets.symmetric(vertical: 10, horizontal: 30), ), ), label: Text( (widget.sendTo == null) ? context.lang.shareImagedEditorShareWith : getContactDisplayName(widget.sendTo!), - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), ), ), ], diff --git a/lib/src/views/camera/share_image_view.dart b/lib/src/views/camera/share_image_view.dart index bd65a56..ab1ea44 100644 --- a/lib/src/views/camera/share_image_view.dart +++ b/lib/src/views/camera/share_image_view.dart @@ -1,24 +1,25 @@ +// ignore_for_file: strict_raw_type + import 'dart:async'; import 'dart:collection'; import 'dart:typed_data'; + import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/model/protobuf/api/websocket/error.pb.dart'; +import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/services/api/media_upload.dart'; +import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/camera/share_image_components/best_friends_selector.dart'; import 'package:twonly/src/views/components/flame.dart'; import 'package:twonly/src/views/components/headline.dart'; import 'package:twonly/src/views/components/initialsavatar.dart'; import 'package:twonly/src/views/components/verified_shield.dart'; -import 'package:twonly/src/database/daos/contacts_dao.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; class ShareImageView extends StatefulWidget { const ShareImageView({ - super.key, required this.imageBytesFuture, required this.isRealTwonly, required this.mirrorVideo, @@ -27,6 +28,7 @@ class ShareImageView extends StatefulWidget { required this.updateStatus, required this.videoUploadHandler, required this.mediaUploadId, + super.key, this.enableVideoAudio, }); final Future imageBytesFuture; @@ -36,7 +38,7 @@ class ShareImageView extends StatefulWidget { final HashSet selectedUserIds; final bool? enableVideoAudio; final int mediaUploadId; - final Function(int, bool) updateStatus; + final void Function(int, bool) updateStatus; final Future? videoUploadHandler; @override @@ -60,8 +62,7 @@ class _ShareImageView extends State { void initState() { super.initState(); - Stream> allContacts = - twonlyDB.contactsDao.watchContactsForShareView(); + final allContacts = twonlyDB.contactsDao.watchContactsForShareView(); contactSub = allContacts.listen((allContacts) { setState(() { @@ -73,13 +74,13 @@ class _ShareImageView extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { imageBytes = await widget.imageBytesFuture; if (imageBytes != null) { final imageHandler = addOrModifyImageToUpload(widget.mediaUploadId, imageBytes!); // start with the pre upload of the media file... - encryptMediaFiles( + await encryptMediaFiles( widget.mediaUploadId, imageHandler, widget.videoUploadHandler); } setState(() {}); @@ -91,12 +92,12 @@ class _ShareImageView extends State { contactSub.cancel(); } - Future updateUsers(List users) async { + Future updateUsers(List users) async { // Sort contacts by flameCounter and then by totalMediaCounter users.sort((a, b) { // First, compare by flameCounter - int flameComparison = (getFlameCounterFromContact(b)) - .compareTo((getFlameCounterFromContact(a))); + final flameComparison = getFlameCounterFromContact(b) + .compareTo(getFlameCounterFromContact(a)); if (flameComparison != 0) { return flameComparison; // Sort by flameCounter in descending order } @@ -106,11 +107,11 @@ class _ShareImageView extends State { }); // Separate best friends and other users - List bestFriends = []; - List otherUsers = []; - List pinnedContacts = users.where((c) => c.pinned).toList(); + final bestFriends = []; + final otherUsers = []; + final pinnedContacts = users.where((c) => c.pinned).toList(); - for (var contact in users) { + for (final contact in users) { if (contact.pinned) continue; if (!contact.archived && (getFlameCounterFromContact(contact)) > 0 && @@ -128,10 +129,10 @@ class _ShareImageView extends State { }); } - Future _filterUsers(String query) async { + Future _filterUsers(String query) async { lastQuery = query; if (query.isEmpty) { - updateUsers(contacts + await updateUsers(contacts .where((x) => !x.archived || !hideArchivedUsers || @@ -139,17 +140,17 @@ class _ShareImageView extends State { .toList()); return; } - List usersFiltered = contacts + final usersFiltered = contacts .where((user) => getContactDisplayName(user) .toLowerCase() .contains(query.toLowerCase())) .toList(); - updateUsers(usersFiltered); + await updateUsers(usersFiltered); } void updateStatus(int userId, bool checked) { if (widget.isRealTwonly) { - Contact user = contacts.firstWhere((x) => x.userId == userId); + final user = contacts.firstWhere((x) => x.userId == userId); if (!user.verified) { showRealTwonlyWarning = true; setState(() {}); @@ -169,18 +170,19 @@ class _ShareImageView extends State { ), body: SafeArea( child: Padding( - padding: EdgeInsets.only(bottom: 40, left: 10, top: 20, right: 10), + padding: + const EdgeInsets.only(bottom: 40, left: 10, top: 20, right: 10), child: Column( children: [ if (showRealTwonlyWarning) Text( context.lang.shareImageAllTwonlyWarning, - style: TextStyle(color: Colors.orange, fontSize: 13), + style: const TextStyle(color: Colors.orange, fontSize: 13), textAlign: TextAlign.center, ), if (showRealTwonlyWarning) const SizedBox(height: 10), Padding( - padding: EdgeInsets.symmetric(horizontal: 10), + padding: const EdgeInsets.symmetric(horizontal: 10), child: TextField( onChanged: _filterUsers, decoration: getInputDecoration( @@ -216,7 +218,7 @@ class _ShareImageView extends State { children: [ Text( context.lang.shareImageShowArchived, - style: TextStyle(fontSize: 10), + style: const TextStyle(fontSize: 10), ), Transform.scale( scale: 0.75, @@ -225,10 +227,9 @@ class _ShareImageView extends State { side: WidgetStateBorderSide.resolveWith( (Set states) { if (states.contains(WidgetState.selected)) { - return BorderSide(width: 0); + return const BorderSide(width: 0); } return BorderSide( - width: 1, color: Theme.of(context) .colorScheme .outline); @@ -261,7 +262,7 @@ class _ShareImageView extends State { floatingActionButton: SizedBox( height: 120, child: Padding( - padding: EdgeInsets.symmetric(horizontal: 20), + padding: const EdgeInsets.symmetric(horizontal: 20), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ @@ -275,13 +276,13 @@ class _ShareImageView extends State { color: Theme.of(context).colorScheme.inversePrimary, ), ) - : FaIcon(FontAwesomeIcons.solidPaperPlane), + : const FaIcon(FontAwesomeIcons.solidPaperPlane), onPressed: () async { if (imageBytes == null || widget.selectedUserIds.isEmpty) { return; } - ErrorCode? err = await isAllowedToSend(); + final err = await isAllowedToSend(); if (!context.mounted) return; if (err != null) { @@ -306,7 +307,7 @@ class _ShareImageView extends State { ); /// trigger the upload of the media file. - handleNextMediaUploadSteps(widget.mediaUploadId); + unawaited(handleNextMediaUploadSteps(widget.mediaUploadId)); if (context.mounted) { Navigator.pop(context, true); @@ -321,7 +322,7 @@ class _ShareImageView extends State { }, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 30), + const EdgeInsets.symmetric(vertical: 10, horizontal: 30), ), backgroundColor: WidgetStateProperty.all( imageBytes == null || widget.selectedUserIds.isEmpty @@ -330,7 +331,7 @@ class _ShareImageView extends State { )), label: Text( context.lang.shareImagedEditorSendImage, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), ), ), ], @@ -344,12 +345,12 @@ class _ShareImageView extends State { class UserList extends StatelessWidget { const UserList( this.users, { - super.key, required this.selectedUserIds, required this.updateStatus, required this.isRealTwonly, + super.key, }); - final Function(int, bool) updateStatus; + final void Function(int, bool) updateStatus; final List users; final bool isRealTwonly; final HashSet selectedUserIds; @@ -364,12 +365,10 @@ class UserList extends StatelessWidget { restorationId: 'new_message_users_list', itemCount: users.length, itemBuilder: (BuildContext context, int i) { - Contact user = users[i]; - int flameCounter = getFlameCounterFromContact(user); + final user = users[i]; + final flameCounter = getFlameCounterFromContact(user); return ListTile( title: Row( - mainAxisAlignment: MainAxisAlignment.start, // Center horizontally - crossAxisAlignment: CrossAxisAlignment.center, // Center vertically children: [ if (isRealTwonly) Padding( @@ -394,10 +393,9 @@ class UserList extends StatelessWidget { side: WidgetStateBorderSide.resolveWith( (Set states) { if (states.contains(WidgetState.selected)) { - return BorderSide(width: 0); + return const BorderSide(width: 0); } - return BorderSide( - width: 1, color: Theme.of(context).colorScheme.outline); + return BorderSide(color: Theme.of(context).colorScheme.outline); }, ), onChanged: (bool? value) { diff --git a/lib/src/views/chats/add_new_user.view.dart b/lib/src/views/chats/add_new_user.view.dart index 965878f..262ac2e 100644 --- a/lib/src/views/chats/add_new_user.view.dart +++ b/lib/src/views/chats/add_new_user.view.dart @@ -1,25 +1,29 @@ +// ignore_for_file: avoid_dynamic_calls + import 'dart:async'; + import 'package:drift/drift.dart' hide Column; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:provider/provider.dart'; -import 'package:twonly/src/model/protobuf/push_notification/push_notification.pbserver.dart'; -import 'package:twonly/src/providers/connection.provider.dart'; -import 'package:twonly/src/services/api/utils.dart'; -import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; -import 'package:twonly/src/services/signal/session.signal.dart'; -import 'package:twonly/src/views/components/alert_dialog.dart'; +import 'package:twonly/globals.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/model/json/message.dart'; +import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart'; +import 'package:twonly/src/model/protobuf/push_notification/push_notification.pbserver.dart'; +import 'package:twonly/src/providers/connection.provider.dart'; +import 'package:twonly/src/services/api/messages.dart'; +import 'package:twonly/src/services/api/utils.dart'; +import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; +import 'package:twonly/src/services/signal/session.signal.dart'; import 'package:twonly/src/utils/misc.dart'; -import 'package:twonly/globals.dart'; +import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/views/components/headline.dart'; import 'package:twonly/src/views/components/initialsavatar.dart'; -import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/services/api/messages.dart'; -import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; class AddNewUserView extends StatefulWidget { @@ -58,7 +62,7 @@ class _SearchUsernameView extends State { }); } - Future _addNewUser(BuildContext context) async { + Future _addNewUser(BuildContext context) async { final user = await getUser(); if (user == null || user.username == searchUserName.text) { return; @@ -84,23 +88,24 @@ class _SearchUsernameView extends State { return; } - int added = await twonlyDB.contactsDao.insertContact( + final added = await twonlyDB.contactsDao.insertContact( ContactsCompanion( username: Value(searchUserName.text), - userId: Value(res.value.userdata.userId.toInt()), - requested: Value(false), + userId: Value(res.value.userdata.userId.toInt() as int), + requested: const Value(false), ), ); if (added > 0) { - if (await createNewSignalSession(res.value.userdata)) { + if (await createNewSignalSession( + res.value.userdata as Response_UserData)) { // before notifying the other party, add await setupNotificationWithUsers( - forceContact: res.value.userdata.userId.toInt(), + forceContact: res.value.userdata.userId.toInt() as int, ); await encryptAndSendMessageAsync( null, - res.value.userdata.userId.toInt(), + res.value.userdata.userId.toInt() as int, MessageJson( kind: MessageKind.contactRequest, timestamp: DateTime.now(), @@ -111,7 +116,7 @@ class _SearchUsernameView extends State { } } } else { - showAlertDialog(context, context.lang.searchUsernameNotFound, + await showAlertDialog(context, context.lang.searchUsernameNotFound, context.lang.searchUsernameNotFoundBody(searchUserName.text)); } setState(() { @@ -119,59 +124,59 @@ class _SearchUsernameView extends State { }); } - InputDecoration getInputDecoration(hintText) { + InputDecoration getInputDecoration(String hintText) { final primaryColor = Theme.of(context).colorScheme.primary; // Get the primary color return InputDecoration( hintText: hintText, focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(9.0), - borderSide: BorderSide(color: primaryColor, width: 1.0), + borderRadius: BorderRadius.circular(9), + borderSide: BorderSide(color: primaryColor), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(8.0), - borderSide: BorderSide( - color: Theme.of(context).colorScheme.outline, width: 1.0), + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline), ), - contentPadding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0), + contentPadding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20), ); } @override Widget build(BuildContext context) { - bool isPreview = context.read().plan == "Preview"; + final isPreview = context.read().plan == 'Preview'; return Scaffold( appBar: AppBar( title: Text(context.lang.searchUsernameTitle), ), body: SafeArea( child: Padding( - padding: EdgeInsets.only(bottom: 20, left: 10, top: 20, right: 10), + padding: + const EdgeInsets.only(bottom: 20, left: 10, top: 20, right: 10), child: Column( children: [ if (isPreview) ...[ Padding( - padding: EdgeInsets.all(20), + padding: const EdgeInsets.all(20), child: Text( context.lang.searchUserNamePreview, textAlign: TextAlign.center, ), ), FilledButton.icon( - icon: FaIcon(FontAwesomeIcons.shieldHeart), + icon: const FaIcon(FontAwesomeIcons.shieldHeart), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { - return SubscriptionView(); + return const SubscriptionView(); })); }, label: Text(context.lang.selectSubscription), ), - SizedBox(height: 30), + const SizedBox(height: 30), ], if (!isPreview) ...[ Padding( - padding: EdgeInsets.symmetric(horizontal: 10), + padding: const EdgeInsets.symmetric(horizontal: 10), child: TextField( onSubmitted: (_) { _addNewUser(context); @@ -184,7 +189,7 @@ class _SearchUsernameView extends State { }, inputFormatters: [ LengthLimitingTextInputFormatter(12), - FilteringTextInputFormatter.allow(RegExp(r'[a-z0-9A-Z]')), + FilteringTextInputFormatter.allow(RegExp('[a-z0-9A-Z]')), ], controller: searchUserName, decoration: @@ -204,18 +209,18 @@ class _SearchUsernameView extends State { ), ), ), - floatingActionButton: (isPreview) + floatingActionButton: isPreview ? null : Padding( - padding: const EdgeInsets.only(bottom: 30.0), + padding: const EdgeInsets.only(bottom: 30), child: FloatingActionButton( foregroundColor: Colors.white, onPressed: () { if (!_isLoading) _addNewUser(context); }, - child: (_isLoading) + child: _isLoading ? const Center(child: CircularProgressIndicator()) - : FaIcon(FontAwesomeIcons.magnifyingGlassPlus), + : const FaIcon(FontAwesomeIcons.magnifyingGlassPlus), ), ), ); @@ -237,9 +242,9 @@ class _ContactsListViewState extends State { Tooltip( message: context.lang.searchUserNameArchiveUserTooltip, child: IconButton( - icon: FaIcon(FontAwesomeIcons.boxArchive, size: 15), + icon: const FaIcon(FontAwesomeIcons.boxArchive, size: 15), onPressed: () async { - final update = ContactsCompanion(archived: Value(true)); + const update = ContactsCompanion(archived: Value(true)); await twonlyDB.contactsDao.updateContact(contact.userId, update); }, ), @@ -253,10 +258,10 @@ class _ContactsListViewState extends State { Tooltip( message: context.lang.searchUserNameBlockUserTooltip, child: IconButton( - icon: Icon(Icons.person_off_rounded, - color: const Color.fromARGB(164, 244, 67, 54)), + icon: const Icon(Icons.person_off_rounded, + color: Color.fromARGB(164, 244, 67, 54)), onPressed: () async { - final update = ContactsCompanion(blocked: Value(true)); + const update = ContactsCompanion(blocked: Value(true)); await twonlyDB.contactsDao.updateContact(contact.userId, update); }, ), @@ -264,17 +269,17 @@ class _ContactsListViewState extends State { Tooltip( message: context.lang.searchUserNameRejectUserTooltip, child: IconButton( - icon: Icon(Icons.close, color: Colors.red), + icon: const Icon(Icons.close, color: Colors.red), onPressed: () async { - rejectUser(contact.userId); + await rejectUser(contact.userId); await deleteContact(contact.userId); }, ), ), IconButton( - icon: Icon(Icons.check, color: Colors.green), + icon: const Icon(Icons.check, color: Colors.green), onPressed: () async { - final update = ContactsCompanion(accepted: Value(true)); + const update = ContactsCompanion(accepted: Value(true)); await twonlyDB.contactsDao.updateContact(contact.userId, update); await encryptAndSendMessageAsync( null, @@ -286,7 +291,7 @@ class _ContactsListViewState extends State { ), pushNotification: PushNotification(kind: PushKind.acceptRequest), ); - notifyContactsAboutProfileChange(); + await notifyContactsAboutProfileChange(); }, ), ]; diff --git a/lib/src/views/chats/chat_list.view.dart b/lib/src/views/chats/chat_list.view.dart index 7ec44aa..5d4171a 100644 --- a/lib/src/views/chats/chat_list.view.dart +++ b/lib/src/views/chats/chat_list.view.dart @@ -1,30 +1,31 @@ import 'dart:async'; + +import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:provider/provider.dart'; import 'package:twonly/globals.dart'; +import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/providers/connection.provider.dart'; import 'package:twonly/src/services/api/media_download.dart'; +import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/camera/camera_send_to_view.dart'; +import 'package:twonly/src/views/chats/add_new_user.view.dart'; import 'package:twonly/src/views/chats/chat_list_components/backup_notice.card.dart'; import 'package:twonly/src/views/chats/chat_list_components/connection_info.comp.dart'; import 'package:twonly/src/views/chats/chat_list_components/demo_user.card.dart'; +import 'package:twonly/src/views/chats/chat_messages.view.dart'; +import 'package:twonly/src/views/chats/media_viewer.view.dart'; +import 'package:twonly/src/views/chats/start_new_chat.view.dart'; import 'package:twonly/src/views/components/flame.dart'; import 'package:twonly/src/views/components/initialsavatar.dart'; import 'package:twonly/src/views/components/message_send_state_icon.dart'; import 'package:twonly/src/views/components/notification_badge.dart'; import 'package:twonly/src/views/components/user_context_menu.dart'; -import 'package:twonly/src/database/daos/contacts_dao.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/database/tables/messages_table.dart'; -import 'package:twonly/src/providers/connection.provider.dart'; -import 'package:twonly/src/utils/misc.dart'; -import 'package:twonly/src/views/camera/camera_send_to_view.dart'; -import 'package:twonly/src/views/chats/chat_messages.view.dart'; -import 'package:twonly/src/views/chats/media_viewer.view.dart'; -import 'package:twonly/src/views/chats/start_new_chat.view.dart'; import 'package:twonly/src/views/settings/help/contact_us.view.dart'; import 'package:twonly/src/views/settings/settings_main.view.dart'; -import 'package:twonly/src/views/chats/add_new_user.view.dart'; -import 'package:flutter/material.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; import 'package:twonly/src/views/tutorial/tutorials.dart'; @@ -50,7 +51,7 @@ class _ChatListViewState extends State { super.initState(); } - Future initAsync() async { + Future initAsync() async { final stream = twonlyDB.contactsDao.watchContactsForChatList(); _contactsSub = stream.listen((contacts) { setState(() { @@ -59,7 +60,7 @@ class _ChatListViewState extends State { }); }); - tutorial = Timer(Duration(seconds: 1), () async { + tutorial = Timer(const Duration(seconds: 1), () async { tutorial = null; if (!mounted) return; await showChatListTutorialSearchOtherUsers(context, searchForOtherUsers); @@ -86,15 +87,15 @@ class _ChatListViewState extends State { @override Widget build(BuildContext context) { - bool isConnected = context.watch().isConnected; + final isConnected = context.watch().isConnected; return Scaffold( appBar: AppBar( title: Row(children: [ - Text("twonly "), + const Text('twonly '), GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { - return SubscriptionView(); + return const SubscriptionView(); })); }, child: Container( @@ -102,7 +103,7 @@ class _ChatListViewState extends State { color: context.color.primary, borderRadius: BorderRadius.circular(15), ), - padding: EdgeInsets.symmetric(horizontal: 5, vertical: 3), + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 3), child: Text( context.watch().plan, style: TextStyle( @@ -121,13 +122,13 @@ class _ChatListViewState extends State { Navigator.push( context, MaterialPageRoute( - builder: (context) => ContactUsView(), + builder: (context) => const ContactUsView(), ), ); }, color: Colors.grey, tooltip: context.lang.feedbackTooltip, - icon: FaIcon(FontAwesomeIcons.commentDots, size: 19), + icon: const FaIcon(FontAwesomeIcons.commentDots, size: 19), ), StreamBuilder( stream: twonlyDB.contactsDao.watchContactsRequested(), @@ -140,12 +141,12 @@ class _ChatListViewState extends State { count: count.toString(), child: IconButton( key: searchForOtherUsers, - icon: FaIcon(FontAwesomeIcons.userPlus, size: 18), + icon: const FaIcon(FontAwesomeIcons.userPlus, size: 18), onPressed: () { Navigator.push( context, MaterialPageRoute( - builder: (context) => AddNewUserView(), + builder: (context) => const AddNewUserView(), ), ); }, @@ -158,11 +159,11 @@ class _ChatListViewState extends State { Navigator.push( context, MaterialPageRoute( - builder: (context) => SettingsMainView(), + builder: (context) => const SettingsMainView(), ), ); }, - icon: FaIcon(FontAwesomeIcons.gear, size: 19), + icon: const FaIcon(FontAwesomeIcons.gear, size: 19), ) ], ), @@ -172,7 +173,7 @@ class _ChatListViewState extends State { top: 0, left: 0, right: 0, - child: isConnected ? Container() : ConnectionInfo(), + child: isConnected ? Container() : const ConnectionInfo(), ), Positioned.fill( child: (_contacts.isEmpty && _pinnedContacts.isEmpty) @@ -180,12 +181,12 @@ class _ChatListViewState extends State { child: Padding( padding: const EdgeInsets.all(10), child: OutlinedButton.icon( - icon: Icon(Icons.person_add), + icon: const Icon(Icons.person_add), onPressed: () { Navigator.push( context, MaterialPageRoute( - builder: (context) => AddNewUserView(), + builder: (context) => const AddNewUserView(), ), ); }, @@ -197,7 +198,7 @@ class _ChatListViewState extends State { onRefresh: () async { await apiService.close(() {}); await apiService.connect(force: true); - await Future.delayed(Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); }, child: ListView.builder( itemCount: _pinnedContacts.length + @@ -207,12 +208,12 @@ class _ChatListViewState extends State { 1, itemBuilder: (context, index) { if (index == 0) { - return BackupNoticeCard(); + return const BackupNoticeCard(); } index -= 1; if (gIsDemoUser) { if (index == 0) { - return DemoUserCard(); + return const DemoUserCard(); } index -= 1; } @@ -230,9 +231,9 @@ class _ChatListViewState extends State { } // If there are pinned users, account for the Divider - int adjustedIndex = index - _pinnedContacts.length; + var adjustedIndex = index - _pinnedContacts.length; if (_pinnedContacts.isNotEmpty && adjustedIndex == 0) { - return Divider(); + return const Divider(); } // Adjust the index for the contacts list @@ -255,18 +256,18 @@ class _ChatListViewState extends State { ], ), floatingActionButton: Padding( - padding: const EdgeInsets.only(bottom: 30.0), + padding: const EdgeInsets.only(bottom: 30), child: FloatingActionButton( foregroundColor: Colors.white, onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) { - return StartNewChatView(); + return const StartNewChatView(); }), ); }, - child: FaIcon(FontAwesomeIcons.penToSquare), + child: const FaIcon(FontAwesomeIcons.penToSquare), ), ), ); @@ -274,12 +275,11 @@ class _ChatListViewState extends State { } class UserListItem extends StatefulWidget { + const UserListItem( + {required this.user, required this.firstUserListItemKey, super.key}); final Contact user; final GlobalKey? firstUserListItemKey; - const UserListItem( - {super.key, required this.user, required this.firstUserListItemKey}); - @override State createState() => _UserListItem(); } @@ -363,11 +363,11 @@ class _UserListItem extends State { void lastUpdateTime() { // Change the color every 200 milliseconds - updateTime = Timer.periodic(Duration(milliseconds: 200), (timer) { + updateTime = Timer.periodic(const Duration(milliseconds: 200), (timer) { setState(() { if (currentMessage != null) { lastMessageInSeconds = - (DateTime.now().difference(currentMessage!.sendAt)).inSeconds; + DateTime.now().difference(currentMessage!.sendAt).inSeconds; if (lastMessageInSeconds < 0) { lastMessageInSeconds = 0; } @@ -378,7 +378,7 @@ class _UserListItem extends State { @override Widget build(BuildContext context) { - int flameCounter = getFlameCounterFromContact(widget.user); + final flameCounter = getFlameCounterFromContact(widget.user); return Stack( children: [ @@ -405,11 +405,11 @@ class _UserListItem extends State { : Row( children: [ MessageSendStateIcon(previewMessages), - Text("โ€ข"), + const Text('โ€ข'), const SizedBox(width: 5), Text( formatDuration(lastMessageInSeconds), - style: TextStyle(fontSize: 12), + style: const TextStyle(fontSize: 12), ), if (flameCounter > 0) FlameCounterWidget( @@ -442,7 +442,7 @@ class _UserListItem extends State { )); return; } - List msgs = previewMessages + final msgs = previewMessages .where((x) => x.kind == MessageKind.media) .toList(); if (msgs.isNotEmpty && @@ -452,6 +452,7 @@ class _UserListItem extends State { switch (msgs.first.downloadState) { case DownloadState.pending: startDownloadMedia(msgs.first, true); + return; case DownloadState.downloaded: Navigator.push( context, @@ -459,9 +460,10 @@ class _UserListItem extends State { return MediaViewerView(widget.user); }), ); - default: + return; + case DownloadState.downloading: + return; } - return; } Navigator.push( context, diff --git a/lib/src/views/chats/chat_list_components/backup_notice.card.dart b/lib/src/views/chats/chat_list_components/backup_notice.card.dart index debd8c5..fa0525b 100644 --- a/lib/src/views/chats/chat_list_components/backup_notice.card.dart +++ b/lib/src/views/chats/chat_list_components/backup_notice.card.dart @@ -20,7 +20,7 @@ class _BackupNoticeCardState extends State { super.initState(); } - Future initAsync() async { + Future initAsync() async { final user = await getUser(); showBackupNotice = false; if (user != null && @@ -47,7 +47,7 @@ class _BackupNoticeCardState extends State { children: [ Text( context.lang.backupNoticeTitle, - style: TextStyle( + style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), @@ -55,7 +55,7 @@ class _BackupNoticeCardState extends State { SizedBox(height: 5), Text( context.lang.backupNoticeDesc, - style: TextStyle(fontSize: 14), + style: const TextStyle(fontSize: 14), ), Row( mainAxisAlignment: MainAxisAlignment.end, diff --git a/lib/src/views/chats/chat_list_components/demo_user.card.dart b/lib/src/views/chats/chat_list_components/demo_user.card.dart index 274e2dc..5ebbc50 100644 --- a/lib/src/views/chats/chat_list_components/demo_user.card.dart +++ b/lib/src/views/chats/chat_list_components/demo_user.card.dart @@ -15,7 +15,7 @@ class DemoUserCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( - "This is a Demo-Preview.", + 'This is a Demo-Preview.', textAlign: TextAlign.center, style: TextStyle( color: !isDarkMode(context) ? Colors.white : Colors.black, @@ -25,12 +25,12 @@ class DemoUserCard extends StatelessWidget { FilledButton( onPressed: () async { await deleteLocalUserData(); - Restart.restartApp( + await Restart.restartApp( notificationTitle: 'Demo-Mode exited.', notificationBody: 'Click here to open the app again', ); }, - child: Text("Register"), + child: const Text('Register'), ) ], ), diff --git a/lib/src/views/chats/chat_messages.view.dart b/lib/src/views/chats/chat_messages.view.dart index dace29e..400b3f8 100644 --- a/lib/src/views/chats/chat_messages.view.dart +++ b/lib/src/views/chats/chat_messages.view.dart @@ -2,33 +2,33 @@ import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; + import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:pie_menu/pie_menu.dart'; import 'package:twonly/globals.dart'; +import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/model/json/message.dart'; +import 'package:twonly/src/model/memory_item.model.dart'; import 'package:twonly/src/model/protobuf/push_notification/push_notification.pb.dart'; +import 'package:twonly/src/services/api/messages.dart'; import 'package:twonly/src/services/notifications/background.notifications.dart'; +import 'package:twonly/src/utils/misc.dart'; +import 'package:twonly/src/views/camera/camera_send_to_view.dart'; import 'package:twonly/src/views/chats/chat_messages_components/chat_message_entry.dart'; import 'package:twonly/src/views/components/animate_icon.dart'; import 'package:twonly/src/views/components/initialsavatar.dart'; import 'package:twonly/src/views/components/user_context_menu.dart'; import 'package:twonly/src/views/components/verified_shield.dart'; -import 'package:twonly/src/database/daos/contacts_dao.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/database/tables/messages_table.dart'; -import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/services/api/messages.dart'; - -import 'package:twonly/src/views/camera/camera_send_to_view.dart'; -import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/contact/contact.view.dart'; -import 'package:twonly/src/model/memory_item.model.dart'; import 'package:twonly/src/views/tutorial/tutorials.dart'; Color getMessageColor(Message message) { return (message.messageOtherId == null) - ? Color.fromARGB(255, 58, 136, 102) - : Color.fromARGB(83, 68, 137, 255); + ? const Color.fromARGB(255, 58, 136, 102) + : const Color.fromARGB(83, 68, 137, 255); } /// Displays detailed information about a SampleItem. @@ -45,7 +45,7 @@ class _ChatMessagesViewState extends State { TextEditingController newMessageController = TextEditingController(); HashSet alreadyReportedOpened = HashSet(); late Contact user; - String currentInputText = ""; + String currentInputText = ''; late StreamSubscription userSub; late StreamSubscription> messageSub; List messages = []; @@ -64,7 +64,7 @@ class _ChatMessagesViewState extends State { textFieldFocus = FocusNode(); initStreams(); - tutorial = Timer(Duration(seconds: 1), () async { + tutorial = Timer(const Duration(seconds: 1), () async { tutorial = null; if (!mounted) return; await showVerifyShieldTutorial(context, verifyShieldKey); @@ -80,10 +80,9 @@ class _ChatMessagesViewState extends State { textFieldFocus.dispose(); } - Future initStreams() async { + Future initStreams() async { await twonlyDB.messagesDao.removeOldMessages(); - Stream contact = - twonlyDB.contactsDao.watchContact(widget.contact.userId); + final contact = twonlyDB.contactsDao.watchContact(widget.contact.userId); userSub = contact.listen((contact) { if (contact == null) return; setState(() { @@ -91,46 +90,48 @@ class _ChatMessagesViewState extends State { }); }); - Stream> msgStream = + final msgStream = twonlyDB.messagesDao.watchAllMessagesFrom(widget.contact.userId); messageSub = msgStream.listen((msgs) async { // if (!context.mounted) return; if (Platform.isAndroid) { - flutterLocalNotificationsPlugin.cancel(widget.contact.userId); + await flutterLocalNotificationsPlugin.cancel(widget.contact.userId); } else { - flutterLocalNotificationsPlugin.cancelAll(); + await flutterLocalNotificationsPlugin.cancelAll(); } - List displayedMessages = []; + final displayedMessages = []; // should be cleared - Map> tmpTextReactionsToMessageId = {}; - Map> tmpEmojiReactionsToMessageId = {}; + final tmpTextReactionsToMessageId = >{}; + final tmpEmojiReactionsToMessageId = >{}; - List openedMessageOtherIds = []; + final openedMessageOtherIds = []; - Map messageOtherMessageIdToMyMessageId = {}; + final messageOtherMessageIdToMyMessageId = {}; /// there is probably a better way... - for (Message msg in msgs) { + for (final msg in msgs) { if (msg.messageOtherId != null) { messageOtherMessageIdToMyMessageId[msg.messageOtherId!] = msg.messageId; } } - for (Message msg in msgs) { + for (final msg in msgs) { if (msg.kind == MessageKind.textMessage && msg.messageOtherId != null && msg.openedAt == null) { openedMessageOtherIds.add(msg.messageOtherId!); } - int? responseId = msg.responseToMessageId ?? + final responseId = msg.responseToMessageId ?? messageOtherMessageIdToMyMessageId[msg.responseToOtherMessageId]; if (responseId != null) { - bool added = false; - MessageContent? content = - MessageContent.fromJson(msg.kind, jsonDecode(msg.contentJson!)); + var added = false; + final content = MessageContent.fromJson( + msg.kind, + jsonDecode(msg.contentJson!) as Map, + ); if (content is TextMessageContent) { if (content.text.isNotEmpty && !isEmoji(content.text)) { added = true; @@ -175,8 +176,8 @@ class _ChatMessagesViewState extends State { }); } - Future _sendMessage() async { - if (newMessageController.text == "") return; + Future _sendMessage() async { + if (newMessageController.text == '') return; await sendTextMessage( user.userId, @@ -197,7 +198,7 @@ class _ChatMessagesViewState extends State { ), ); newMessageController.clear(); - currentInputText = ""; + currentInputText = ''; responseToMessage = null; setState(() {}); } @@ -207,45 +208,44 @@ class _ChatMessagesViewState extends State { if (message.kind == MessageKind.textMessage) { if (message.contentJson != null) { - MessageContent? content = MessageContent.fromJson( - MessageKind.textMessage, jsonDecode(message.contentJson!)); + final content = MessageContent.fromJson( + MessageKind.textMessage, jsonDecode(message.contentJson!) as Map); if (content is TextMessageContent) { subtitle = truncateString(content.text); } } } if (message.kind == MessageKind.media) { - MessageContent? content = MessageContent.fromJson( - MessageKind.media, jsonDecode(message.contentJson!)); + final content = MessageContent.fromJson( + MessageKind.media, jsonDecode(message.contentJson!) as Map); if (content is MediaMessageContent) { - subtitle = content.isVideo ? "Video" : "Image"; + subtitle = content.isVideo ? 'Video' : 'Image'; } } - String username = "You"; + var username = 'You'; if (message.messageOtherId != null) { username = getContactDisplayName(widget.contact); } - Color color = getMessageColor(message); + final color = getMessageColor(message); return Container( - padding: EdgeInsets.only(left: 10), + padding: const EdgeInsets.only(left: 10), decoration: BoxDecoration( border: Border( left: BorderSide( color: color, - width: 2.0, + width: 2, ), ), ), child: Column( - mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( username, - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), ), if (subtitle != null) Text(subtitle) ], @@ -269,14 +269,14 @@ class _ChatMessagesViewState extends State { contact: user, fontSize: 19, ), - SizedBox(width: 10), + const SizedBox(width: 10), Expanded( child: Container( color: Colors.transparent, child: Row( children: [ Text(getContactDisplayName(user)), - SizedBox(width: 10), + const SizedBox(width: 10), VerifiedShield(key: verifyShieldKey, user), ], ), @@ -300,8 +300,8 @@ class _ChatMessagesViewState extends State { index -= 1; double size = 44; if (messages[index].kind == MessageKind.textMessage) { - TextMessageContent? content = TextMessageContent.fromJson( - jsonDecode(messages[index].contentJson!)); + final content = TextMessageContent.fromJson( + jsonDecode(messages[index].contentJson!) as Map); if (EmojiAnimation.supported(content.text)) { size = 99; } else { @@ -321,9 +321,8 @@ class _ChatMessagesViewState extends State { if (reactions != null && reactions.isNotEmpty) { for (final reaction in reactions) { if (reaction.kind == MessageKind.textMessage) { - TextMessageContent? content = - TextMessageContent.fromJson( - jsonDecode(reaction.contentJson!)); + final content = TextMessageContent.fromJson( + jsonDecode(reaction.contentJson!) as Map); size += calculateNumberOfLines(content.text, MediaQuery.of(context).size.width * 0.5, 14) * 27; @@ -362,7 +361,6 @@ class _ChatMessagesViewState extends State { if (responseToMessage != null && !user.deleted) Container( padding: const EdgeInsets.only( - bottom: 00, left: 20, right: 20, top: 10, @@ -376,7 +374,7 @@ class _ChatMessagesViewState extends State { responseToMessage = null; }); }, - icon: FaIcon( + icon: const FaIcon( FontAwesomeIcons.xmark, size: 16, ), @@ -412,30 +410,28 @@ class _ChatMessagesViewState extends State { decoration: inputTextMessageDeco(context), ), ), - (currentInputText != "") - ? IconButton( - padding: EdgeInsets.all(15), - icon: - FaIcon(FontAwesomeIcons.solidPaperPlane), - onPressed: () { - _sendMessage(); - }, - ) - : IconButton( - icon: FaIcon(FontAwesomeIcons.camera), - padding: EdgeInsets.all(15), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) { - return CameraSendToView( - widget.contact); - }, - ), - ); - }, - ) + if (currentInputText != '') + IconButton( + padding: const EdgeInsets.all(15), + icon: const FaIcon( + FontAwesomeIcons.solidPaperPlane), + onPressed: _sendMessage, + ) + else + IconButton( + icon: const FaIcon(FontAwesomeIcons.camera), + padding: const EdgeInsets.all(15), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) { + return CameraSendToView(widget.contact); + }, + ), + ); + }, + ) ], ), ), @@ -469,7 +465,6 @@ double calculateNumberOfLines(String text, double width, double fontSize) { style: TextStyle(fontSize: fontSize), ), textDirection: TextDirection.ltr, - ); - textPainter.layout(maxWidth: (width - 32)); + )..layout(maxWidth: width - 32); return textPainter.computeLineMetrics().length.toDouble(); } diff --git a/lib/src/views/chats/chat_messages_components/chat_media_entry.dart b/lib/src/views/chats/chat_messages_components/chat_media_entry.dart index c774d8e..3b2994d 100644 --- a/lib/src/views/chats/chat_messages_components/chat_media_entry.dart +++ b/lib/src/views/chats/chat_messages_components/chat_media_entry.dart @@ -41,7 +41,7 @@ class _ChatMediaEntryState extends State { checkIfTutorialCanBeShown(); } - Future checkIfTutorialCanBeShown() async { + Future checkIfTutorialCanBeShown() async { if (widget.message.openedAt == null && widget.message.messageOtherId != null || widget.message.mediaStored) { diff --git a/lib/src/views/chats/chat_messages_components/chat_message_entry.dart b/lib/src/views/chats/chat_messages_components/chat_message_entry.dart index a28f955..c801335 100644 --- a/lib/src/views/chats/chat_messages_components/chat_message_entry.dart +++ b/lib/src/views/chats/chat_messages_components/chat_message_entry.dart @@ -1,13 +1,14 @@ import 'dart:convert'; + import 'package:flutter/material.dart'; +import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/model/json/message.dart'; +import 'package:twonly/src/model/memory_item.model.dart'; import 'package:twonly/src/views/chats/chat_messages_components/chat_media_entry.dart'; import 'package:twonly/src/views/chats/chat_messages_components/chat_reaction_row.dart'; import 'package:twonly/src/views/chats/chat_messages_components/chat_text_entry.dart'; import 'package:twonly/src/views/chats/chat_messages_components/chat_text_response_columns.dart'; import 'package:twonly/src/views/chats/chat_messages_components/message_actions.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/model/memory_item.model.dart'; class ChatListEntry extends StatefulWidget { const ChatListEntry( @@ -17,8 +18,8 @@ class ChatListEntry extends StatefulWidget { this.lastMessageFromSameUser, this.textReactions, this.otherReactions, { - super.key, required this.onResponseTriggered, + super.key, }); final Message message; final Contact contact; @@ -26,7 +27,7 @@ class ChatListEntry extends StatefulWidget { final List textReactions; final List otherReactions; final List galleryItems; - final Function(Message) onResponseTriggered; + final void Function(Message) onResponseTriggered; @override State createState() => _ChatListEntryState(); @@ -40,7 +41,7 @@ class _ChatListEntryState extends State { void initState() { super.initState(); final msgContent = MessageContent.fromJson( - widget.message.kind, jsonDecode(widget.message.contentJson!)); + widget.message.kind, jsonDecode(widget.message.contentJson!) as Map); if (msgContent is TextMessageContent) { textMessage = msgContent.text; } @@ -50,16 +51,14 @@ class _ChatListEntryState extends State { @override Widget build(BuildContext context) { if (content == null) return Container(); - bool right = widget.message.messageOtherId == null; + final right = widget.message.messageOtherId == null; - return Container( - // tag: "${widget.message.mediaUploadId ?? widget.message.messageId}", - child: Align( + return Align( alignment: right ? Alignment.centerRight : Alignment.centerLeft, child: Padding( padding: widget.lastMessageFromSameUser - ? EdgeInsets.only(top: 5, bottom: 0, right: 10, left: 10) - : EdgeInsets.only(top: 5, bottom: 20, right: 10, left: 10), + ? const EdgeInsets.only(top: 5, right: 10, left: 10) + : const EdgeInsets.only(top: 5, bottom: 20, right: 10, left: 10), child: Column( mainAxisAlignment: right ? MainAxisAlignment.end : MainAxisAlignment.start, @@ -71,17 +70,18 @@ class _ChatListEntryState extends State { child: Stack( alignment: right ? Alignment.centerRight : Alignment.centerLeft, children: [ - (textMessage != null) - ? ChatTextEntry( - message: widget.message, - text: textMessage!, - ) - : ChatMediaEntry( - message: widget.message, - contact: widget.contact, - galleryItems: widget.galleryItems, - content: content!, - ), + if (textMessage != null) + ChatTextEntry( + message: widget.message, + text: textMessage!, + ) + else + ChatMediaEntry( + message: widget.message, + contact: widget.contact, + galleryItems: widget.galleryItems, + content: content!, + ), Positioned( bottom: 5, left: 5, @@ -104,6 +104,6 @@ class _ChatListEntryState extends State { ], ), ), - )); + ); } } diff --git a/lib/src/views/chats/chat_messages_components/chat_reaction_row.dart b/lib/src/views/chats/chat_messages_components/chat_reaction_row.dart index e30f610..7a3aed2 100644 --- a/lib/src/views/chats/chat_messages_components/chat_reaction_row.dart +++ b/lib/src/views/chats/chat_messages_components/chat_reaction_row.dart @@ -1,15 +1,16 @@ import 'dart:convert'; + import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; -import 'package:twonly/src/views/components/animate_icon.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; +import 'package:twonly/src/views/components/animate_icon.dart'; class ReactionRow extends StatefulWidget { const ReactionRow({ - super.key, required this.otherReactions, required this.message, + super.key, }); final List otherReactions; @@ -22,18 +23,18 @@ class ReactionRow extends StatefulWidget { class _ReactionRowState extends State { @override Widget build(BuildContext context) { - List children = []; - bool hasOneTextReaction = false; - bool hasOneReopened = false; + final children = []; + var hasOneTextReaction = false; + var hasOneReopened = false; for (final reaction in widget.otherReactions) { - MessageContent? content = MessageContent.fromJson( - reaction.kind, jsonDecode(reaction.contentJson!)); + final content = MessageContent.fromJson( + reaction.kind, jsonDecode(reaction.contentJson!) as Map); if (content is ReopenedMediaFileContent) { if (hasOneReopened) continue; hasOneReopened = true; children.add( - Expanded( + const Expanded( child: Align( alignment: Alignment.bottomRight, child: Padding( @@ -61,12 +62,12 @@ class _ReactionRowState extends State { child: EmojiAnimation(emoji: content.text), ); } else { - child = Text(content.text, style: TextStyle(fontSize: 14)); + child = Text(content.text, style: const TextStyle(fontSize: 14)); } children.insert( 0, Padding( - padding: EdgeInsets.only(left: 3), + padding: const EdgeInsets.only(left: 3), child: child, ), ); diff --git a/lib/src/views/chats/chat_messages_components/chat_text_response_columns.dart b/lib/src/views/chats/chat_messages_components/chat_text_response_columns.dart index 4d7aec5..b7ffe03 100644 --- a/lib/src/views/chats/chat_messages_components/chat_text_response_columns.dart +++ b/lib/src/views/chats/chat_messages_components/chat_text_response_columns.dart @@ -1,15 +1,16 @@ import 'dart:convert'; + import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; -import 'package:twonly/src/views/chats/chat_messages.view.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; +import 'package:twonly/src/views/chats/chat_messages.view.dart'; class ChatTextResponseColumns extends StatelessWidget { const ChatTextResponseColumns({ - super.key, required this.textReactions, required this.right, + super.key, }); final List textReactions; @@ -17,25 +18,25 @@ class ChatTextResponseColumns extends StatelessWidget { @override Widget build(BuildContext context) { - List children = []; + final children = []; for (final reaction in textReactions) { - MessageContent? content = MessageContent.fromJson( - reaction.kind, jsonDecode(reaction.contentJson!)); + final content = MessageContent.fromJson( + reaction.kind, jsonDecode(reaction.contentJson!) as Map); if (content is TextMessageContent) { var entries = [ - FaIcon( + const FaIcon( FontAwesomeIcons.reply, size: 10, ), - SizedBox(width: 5), + const SizedBox(width: 5), Container( constraints: BoxConstraints( maxWidth: MediaQuery.of(context).size.width * 0.5, ), child: Text( content.text, - style: TextStyle(fontSize: 14), + style: const TextStyle(fontSize: 14), textAlign: right ? TextAlign.right : TextAlign.left, )), ]; @@ -43,20 +44,21 @@ class ChatTextResponseColumns extends StatelessWidget { entries = entries.reversed.toList(); } - Color color = getMessageColor(reaction); + final color = getMessageColor(reaction); children.insert( 0, Container( - padding: EdgeInsets.only(top: 5, bottom: 0, right: 10, left: 10), + padding: + const EdgeInsets.only(top: 5, bottom: 0, right: 10, left: 10), child: Container( constraints: BoxConstraints( maxWidth: MediaQuery.of(context).size.width * 0.8, ), - padding: EdgeInsets.symmetric(vertical: 1, horizontal: 10), + padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 10), decoration: BoxDecoration( color: color, - borderRadius: BorderRadius.circular(12.0), + borderRadius: BorderRadius.circular(12), ), child: Row( mainAxisSize: MainAxisSize.min, diff --git a/lib/src/views/chats/chat_messages_components/in_chat_media_viewer.dart b/lib/src/views/chats/chat_messages_components/in_chat_media_viewer.dart index 6fb6bec..cf09e0e 100644 --- a/lib/src/views/chats/chat_messages_components/in_chat_media_viewer.dart +++ b/lib/src/views/chats/chat_messages_components/in_chat_media_viewer.dart @@ -1,20 +1,21 @@ import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/views/components/message_send_state_icon.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/memory_item.model.dart'; +import 'package:twonly/src/views/components/message_send_state_icon.dart'; import 'package:twonly/src/views/memories/memories_item_thumbnail.dart'; import 'package:twonly/src/views/memories/memories_photo_slider.view.dart'; class InChatMediaViewer extends StatefulWidget { const InChatMediaViewer({ - super.key, required this.message, required this.contact, required this.color, required this.galleryItems, required this.canBeReopened, + super.key, }); final Message message; @@ -40,9 +41,9 @@ class _InChatMediaViewerState extends State { initStream(); } - Future loadIndexAsync() async { + Future loadIndexAsync() async { if (!widget.message.mediaStored) return; - _timer = Timer.periodic(Duration(milliseconds: 10), (timer) { + _timer = Timer.periodic(const Duration(milliseconds: 10), (timer) { /// when the galleryItems are updated this widget is not reloaded /// so using this timer as a workaround if (loadIndex()) { @@ -72,7 +73,7 @@ class _InChatMediaViewerState extends State { // videoController?.dispose(); } - Future initStream() async { + Future initStream() async { /// When the image is opened from the chat and then stored the /// image is not loaded so this will trigger an initAsync when mediaStored is changed @@ -85,22 +86,21 @@ class _InChatMediaViewerState extends State { messageStream = stream.listen((updated) async { if (updated != null) { if (updated.mediaStored) { - messageStream?.cancel(); - loadIndexAsync(); + await messageStream?.cancel(); + await loadIndexAsync(); } } }); } - Future onTap() async { + Future onTap() async { if (galleryItemIndex == null) return; - Navigator.push( + await Navigator.push( context, MaterialPageRoute( builder: (context) => MemoriesPhotoSliderView( galleryItems: widget.galleryItems, initialIndex: galleryItemIndex!, - scrollDirection: Axis.horizontal, ), ), ); @@ -110,15 +110,14 @@ class _InChatMediaViewerState extends State { Widget build(BuildContext context) { if (galleryItemIndex == null) { return Container( - constraints: BoxConstraints( + constraints: const BoxConstraints( minHeight: 39, ), decoration: BoxDecoration( border: Border.all( color: widget.color, - width: 1.0, ), - borderRadius: BorderRadius.circular(12.0), + borderRadius: BorderRadius.circular(12), ), child: Padding( padding: EdgeInsets.symmetric( @@ -135,10 +134,9 @@ class _InChatMediaViewerState extends State { decoration: BoxDecoration( border: Border.all( color: Colors.transparent, - width: 1.0, ), color: Colors.transparent, - borderRadius: BorderRadius.circular(12.0), + borderRadius: BorderRadius.circular(12), ), child: MemoriesItemThumbnail( galleryItem: widget.galleryItems[galleryItemIndex!], diff --git a/lib/src/views/chats/chat_messages_components/message_actions.dart b/lib/src/views/chats/chat_messages_components/message_actions.dart index 1b2a598..aa320f8 100644 --- a/lib/src/views/chats/chat_messages_components/message_actions.dart +++ b/lib/src/views/chats/chat_messages_components/message_actions.dart @@ -1,3 +1,5 @@ +// ignore_for_file: avoid_dynamic_calls, inference_failure_on_function_invocation + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; @@ -15,23 +17,22 @@ import 'package:twonly/src/views/camera/image_editor/modules/all_emojis.dart'; import 'package:twonly/src/views/components/alert_dialog.dart'; class MessageActions extends StatefulWidget { - final Widget child; - final Message message; - final VoidCallback onResponseTriggered; - const MessageActions({ - super.key, required this.child, required this.message, required this.onResponseTriggered, + super.key, }); + final Widget child; + final Message message; + final VoidCallback onResponseTriggered; @override State createState() => _SlidingResponseWidgetState(); } class _SlidingResponseWidgetState extends State { - double _offsetX = 0.0; + double _offsetX = 0; bool gotFeedback = false; void _onHorizontalDragUpdate(DragUpdateDetails details) { @@ -77,7 +78,7 @@ class _SlidingResponseWidgetState extends State { ), ), if (_offsetX >= 40) - Positioned( + const Positioned( left: 20, top: 0, bottom: 0, @@ -98,16 +99,15 @@ class _SlidingResponseWidgetState extends State { } class MessageContextMenu extends StatelessWidget { - final Widget child; - final Message message; - final VoidCallback onResponseTriggered; - const MessageContextMenu({ - super.key, required this.message, required this.child, required this.onResponseTriggered, + super.key, }); + final Widget child; + final Message message; + final VoidCallback onResponseTriggered; @override Widget build(BuildContext context) { @@ -122,17 +122,17 @@ class MessageContextMenu extends StatelessWidget { PieAction( tooltip: Text(context.lang.react), onSelect: () async { - EmojiLayerData? layer = await showModalBottomSheet( + final layer = await showModalBottomSheet( context: context, backgroundColor: Colors.black, builder: (BuildContext context) { return const Emojis(); }, - ); + ) as TextLayerData?; if (layer == null) return; Log.info(layer.text); - sendTextMessage( + await sendTextMessage( message.contactId, TextMessageContent( text: layer.text, @@ -171,7 +171,7 @@ class MessageContextMenu extends StatelessWidget { PieAction( tooltip: Text(context.lang.delete), onSelect: () async { - bool delete = await showAlertDialog( + final delete = await showAlertDialog( context, context.lang.deleteTitle, null, diff --git a/lib/src/views/chats/media_viewer.view.dart b/lib/src/views/chats/media_viewer.view.dart index ac4cef5..8931a18 100644 --- a/lib/src/views/chats/media_viewer.view.dart +++ b/lib/src/views/chats/media_viewer.view.dart @@ -1,6 +1,9 @@ +// ignore_for_file: inference_failure_on_collection_literal, avoid_dynamic_calls + import 'dart:async'; import 'dart:convert'; import 'dart:io'; + import 'package:drift/drift.dart' hide Column; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; @@ -8,28 +11,28 @@ import 'package:lottie/lottie.dart'; import 'package:no_screenshot/no_screenshot.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/model/json/message.dart'; import 'package:twonly/src/model/protobuf/push_notification/push_notification.pb.dart'; +import 'package:twonly/src/services/api/media_download.dart'; +import 'package:twonly/src/services/api/messages.dart'; import 'package:twonly/src/services/api/utils.dart'; import 'package:twonly/src/services/notifications/background.notifications.dart'; import 'package:twonly/src/utils/log.dart'; -import 'package:twonly/src/views/camera/share_image_editor_view.dart'; -import 'package:twonly/src/views/components/animate_icon.dart'; -import 'package:twonly/src/views/components/media_view_sizing.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/database/tables/messages_table.dart'; -import 'package:twonly/src/model/json/message.dart'; -import 'package:twonly/src/services/api/messages.dart'; -import 'package:twonly/src/services/api/media_download.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/views/camera/camera_send_to_view.dart'; +import 'package:twonly/src/views/camera/share_image_editor_view.dart'; +import 'package:twonly/src/views/components/animate_icon.dart'; +import 'package:twonly/src/views/components/media_view_sizing.dart'; import 'package:video_player/video_player.dart'; -final _noScreenshot = NoScreenshot.instance; +final NoScreenshot _noScreenshot = NoScreenshot.instance; class MediaViewerView extends StatefulWidget { - final Contact contact; const MediaViewerView(this.contact, {super.key, this.initialMessage}); + final Contact contact; final Message? initialMessage; @@ -89,17 +92,17 @@ class _MediaViewerViewState extends State { super.dispose(); } - Future asyncLoadNextMedia(bool firstRun) async { - Stream> messages = + Future asyncLoadNextMedia(bool firstRun) async { + final messages = twonlyDB.messagesDao.watchMediaMessageNotOpened(widget.contact.userId); _subscription = messages.listen((messages) { - for (Message msg in messages) { + for (final msg in messages) { // if (!allMediaFiles.any((m) => m.messageId == msg.messageId)) { // allMediaFiles.add(msg); // } // Find the index of the existing message with the same messageId - int index = + final index = allMediaFiles.indexWhere((m) => m.messageId == msg.messageId); if (index >= 1) { @@ -114,24 +117,23 @@ class _MediaViewerViewState extends State { setState(() {}); if (firstRun) { loadCurrentMediaFile(); - firstRun = false; } }); } - Future nextMediaOrExit() async { + Future nextMediaOrExit() async { if (!mounted) return; - videoController?.dispose(); + await videoController?.dispose(); nextMediaTimer?.cancel(); progressTimer?.cancel(); if (allMediaFiles.isNotEmpty) { try { if (!imageSaved && maxShowTime != gMediaShowInfinite) { - await deleteMediaFile(allMediaFiles.first.messageId, "mp4"); - await deleteMediaFile(allMediaFiles.first.messageId, "png"); + await deleteMediaFile(allMediaFiles.first.messageId, 'mp4'); + await deleteMediaFile(allMediaFiles.first.messageId, 'png'); } } catch (e) { - Log.error("$e"); + Log.error('$e'); } } if (allMediaFiles.isEmpty || allMediaFiles.length == 1) { @@ -144,7 +146,7 @@ class _MediaViewerViewState extends State { } } - Future loadCurrentMediaFile({bool showTwonly = false}) async { + Future loadCurrentMediaFile({bool showTwonly = false}) async { if (!mounted) return; if (!context.mounted || allMediaFiles.isEmpty) return nextMediaOrExit(); await _noScreenshot.screenshotOff(); @@ -165,9 +167,10 @@ class _MediaViewerViewState extends State { }); if (Platform.isAndroid) { - flutterLocalNotificationsPlugin.cancel(allMediaFiles.first.contactId); + await flutterLocalNotificationsPlugin + .cancel(allMediaFiles.first.contactId); } else { - flutterLocalNotificationsPlugin.cancelAll(); + await flutterLocalNotificationsPlugin.cancelAll(); } if (allMediaFiles.first.downloadState != DownloadState.downloaded) { @@ -179,14 +182,14 @@ class _MediaViewerViewState extends State { final stream = twonlyDB.messagesDao .getMessageByMessageId(allMediaFiles.first.messageId) .watchSingleOrNull(); - downloadStateListener?.cancel(); + await downloadStateListener?.cancel(); downloadStateListener = stream.listen((updated) async { if (updated != null) { if (updated.downloadState == DownloadState.downloaded) { - downloadStateListener?.cancel(); + await downloadStateListener?.cancel(); await handleNextDownloadedMedia(updated, showTwonly); // start downloading all the other possible missing media files. - tryDownloadAllMediaFiles(force: true); + await tryDownloadAllMediaFiles(force: true); } } }); @@ -195,9 +198,10 @@ class _MediaViewerViewState extends State { } } - Future handleNextDownloadedMedia(Message current, bool showTwonly) async { - final MediaMessageContent content = - MediaMessageContent.fromJson(jsonDecode(current.contentJson!)); + Future handleNextDownloadedMedia( + Message current, bool showTwonly) async { + final content = + MediaMessageContent.fromJson(jsonDecode(current.contentJson!) as Map); if (content.isRealTwonly) { setState(() { @@ -205,12 +209,12 @@ class _MediaViewerViewState extends State { }); if (!showTwonly) return; - bool isAuth = await authenticateUser( + final isAuth = await authenticateUser( context.lang.mediaViewerAuthReason, force: false, ); if (!isAuth) { - nextMediaOrExit(); + await nextMediaOrExit(); return; } } @@ -229,8 +233,9 @@ class _MediaViewerViewState extends State { final videoPathTmp = await getVideoPath(current.messageId); if (videoPathTmp != null) { videoController = VideoPlayerController.file(File(videoPathTmp.path)); - videoController?.setLooping(content.maxShowTime == gMediaShowInfinite); - videoController?.initialize().then((_) { + await videoController + ?.setLooping(content.maxShowTime == gMediaShowInfinite); + await videoController?.initialize().then((_) { videoController!.play(); videoController?.addListener(() { setState(() { @@ -248,9 +253,8 @@ class _MediaViewerViewState extends State { setState(() { videoPath = videoPathTmp.path; }); - }).catchError((Object error) { - Log.error(error); - }); + // ignore: invalid_return_type_for_catch_error, argument_type_not_assignable_to_error_handler + }).catchError(Log.error); } } @@ -258,7 +262,7 @@ class _MediaViewerViewState extends State { if ((imageBytes == null && !content.isVideo) || (content.isVideo && videoController == null)) { - Log.error("media files are not found..."); + Log.error('media files are not found...'); // When the message should be downloaded but imageBytes are null then a error happened await handleMediaError(current); return nextMediaOrExit(); @@ -287,17 +291,17 @@ class _MediaViewerViewState extends State { nextMediaOrExit(); } }); - progressTimer = Timer.periodic(Duration(milliseconds: 10), (timer) { + progressTimer = Timer.periodic(const Duration(milliseconds: 10), (timer) { if (canBeSeenUntil != null) { - Duration difference = canBeSeenUntil!.difference(DateTime.now()); + final difference = canBeSeenUntil!.difference(DateTime.now()); // Calculate the progress as a value between 0.0 and 1.0 - progress = (difference.inMilliseconds / (maxShowTime * 1000)); + progress = difference.inMilliseconds / (maxShowTime * 1000); setState(() {}); } }); } - Future onPressedSaveToGallery() async { + Future onPressedSaveToGallery() async { if (allMediaFiles.first.messageOtherId == null) { return; // should not be possible } @@ -306,7 +310,7 @@ class _MediaViewerViewState extends State { }); await twonlyDB.messagesDao.updateMessageByMessageId( allMediaFiles.first.messageId, - MessagesCompanion(mediaStored: Value(true)), + const MessagesCompanion(mediaStored: Value(true)), ); await encryptAndSendMessageAsync( null, @@ -314,7 +318,7 @@ class _MediaViewerViewState extends State { MessageJson( kind: MessageKind.storedMediaFile, messageSenderId: allMediaFiles.first.messageId, - messageReceiverId: allMediaFiles.first.messageOtherId!, + messageReceiverId: allMediaFiles.first.messageOtherId, content: MessageContent(), timestamp: DateTime.now(), ), @@ -337,8 +341,8 @@ class _MediaViewerViewState extends State { } void displayShortReactions() { - RenderBox renderBox = - mediaWidgetKey.currentContext?.findRenderObject() as RenderBox; + final renderBox = + mediaWidgetKey.currentContext!.findRenderObject()! as RenderBox; setState(() { showShortReactions = true; mediaViewerDistanceFromBottom = renderBox.size.height; @@ -349,7 +353,6 @@ class _MediaViewerViewState extends State { return Row( key: mediaWidgetKey, mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, children: [ if (maxShowTime == gMediaShowInfinite) OutlinedButton( @@ -364,18 +367,19 @@ class _MediaViewerViewState extends State { onPressed: onPressedSaveToGallery, child: Row( children: [ - imageSaving - ? SizedBox( - width: 10, - height: 10, - child: CircularProgressIndicator(strokeWidth: 1)) - : imageSaved - ? Icon(Icons.check) - : FaIcon(FontAwesomeIcons.floppyDisk), + if (imageSaving) + const SizedBox( + width: 10, + height: 10, + child: CircularProgressIndicator(strokeWidth: 1)) + else + imageSaved + ? const Icon(Icons.check) + : const FaIcon(FontAwesomeIcons.floppyDisk), ], ), ), - SizedBox(width: 10), + const SizedBox(width: 10), IconButton( icon: SizedBox( width: 30, @@ -410,13 +414,13 @@ class _MediaViewerViewState extends State { }, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 20), + const EdgeInsets.symmetric(vertical: 10, horizontal: 20), ), ), ), - SizedBox(width: 10), + const SizedBox(width: 10), IconButton.outlined( - icon: FaIcon(FontAwesomeIcons.message), + icon: const FaIcon(FontAwesomeIcons.message), onPressed: () async { displayShortReactions(); setState(() { @@ -425,31 +429,32 @@ class _MediaViewerViewState extends State { }, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 20), + const EdgeInsets.symmetric(vertical: 10, horizontal: 20), ), ), ), - SizedBox(width: 10), + const SizedBox(width: 10), IconButton.outlined( - icon: FaIcon(FontAwesomeIcons.camera), + icon: const FaIcon(FontAwesomeIcons.camera), onPressed: () async { nextMediaTimer?.cancel(); progressTimer?.cancel(); - videoController?.pause(); + await videoController?.pause(); + if (!mounted) return; await Navigator.push(context, MaterialPageRoute( builder: (context) { return CameraSendToView(widget.contact); }, )); if (mounted && maxShowTime != gMediaShowInfinite) { - nextMediaOrExit(); + await nextMediaOrExit(); } else { - videoController?.play(); + await videoController?.play(); } }, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 20), + const EdgeInsets.symmetric(vertical: 10, horizontal: 20), ), ), ), @@ -494,7 +499,7 @@ class _MediaViewerViewState extends State { child: Image.memory( imageBytes!, fit: BoxFit.contain, - frameBuilder: ((context, child, frame, + frameBuilder: (context, child, frame, wasSynchronouslyLoaded) { if (wasSynchronouslyLoaded) return child; return AnimatedSwitcher( @@ -505,12 +510,12 @@ class _MediaViewerViewState extends State { height: 60, color: Colors.transparent, width: 60, - child: CircularProgressIndicator( + child: const CircularProgressIndicator( strokeWidth: 2, ), ), ); - }), + }, ), ), ], @@ -531,7 +536,7 @@ class _MediaViewerViewState extends State { ), ), Container( - padding: EdgeInsets.only(bottom: 200), + padding: const EdgeInsets.only(bottom: 200), child: Text(context.lang.mediaViewerTwonlyTapToOpen), ), ], @@ -544,7 +549,7 @@ class _MediaViewerViewState extends State { child: Row( children: [ IconButton( - icon: Icon(Icons.close, size: 30), + icon: const Icon(Icons.close, size: 30), color: Colors.white, onPressed: () async { Navigator.pop(context); @@ -554,7 +559,7 @@ class _MediaViewerViewState extends State { ), ), if (isDownloading) - Positioned.fill( + const Positioned.fill( child: Center( child: SizedBox( height: 60, @@ -574,7 +579,7 @@ class _MediaViewerViewState extends State { height: 20, child: CircularProgressIndicator( value: progress, - strokeWidth: 2.0, + strokeWidth: 2, ), ), ], @@ -588,13 +593,13 @@ class _MediaViewerViewState extends State { child: Text( getContactDisplayName(widget.contact), textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, shadows: [ Shadow( - color: const Color.fromARGB(122, 0, 0, 0), - blurRadius: 5.0, + color: Color.fromARGB(122, 0, 0, 0), + blurRadius: 5, ) ], ), @@ -612,7 +617,7 @@ class _MediaViewerViewState extends State { child: Row( children: [ IconButton( - icon: FaIcon(FontAwesomeIcons.xmark), + icon: const FaIcon(FontAwesomeIcons.xmark), onPressed: () { setState(() { showShortReactions = false; @@ -634,7 +639,7 @@ class _MediaViewerViewState extends State { ), ), IconButton( - icon: FaIcon(FontAwesomeIcons.solidPaperPlane), + icon: const FaIcon(FontAwesomeIcons.solidPaperPlane), onPressed: () { if (textMessageController.text.isNotEmpty) { sendTextMessage( @@ -684,7 +689,6 @@ class _MediaViewerViewState extends State { class ReactionButtons extends StatefulWidget { const ReactionButtons({ - super.key, required this.show, required this.textInputFocused, required this.userId, @@ -692,6 +696,7 @@ class ReactionButtons extends StatefulWidget { required this.responseToMessageId, required this.isVideo, required this.hide, + super.key, }); final double mediaViewerDistanceFromBottom; @@ -700,7 +705,7 @@ class ReactionButtons extends StatefulWidget { final bool textInputFocused; final int userId; final int responseToMessageId; - final Function() hide; + final void Function() hide; @override State createState() => _ReactionButtonsState(); @@ -718,8 +723,8 @@ class _ReactionButtonsState extends State { initAsync(); } - Future initAsync() async { - var user = await getUser(); + Future initAsync() async { + final user = await getUser(); if (user != null && user.preSelectedEmojies != null) { selectedEmojis = user.preSelectedEmojies!; } @@ -733,7 +738,7 @@ class _ReactionButtonsState extends State { selectedEmojis.length > 6 ? selectedEmojis.skip(6).toList() : []; return AnimatedPositioned( - duration: Duration(milliseconds: 200), // Animation duration + duration: const Duration(milliseconds: 200), // Animation duration bottom: widget.show ? (widget.textInputFocused ? 50 @@ -744,10 +749,11 @@ class _ReactionButtonsState extends State { curve: Curves.linearToEaseOut, child: AnimatedOpacity( opacity: widget.show ? 1.0 : 0.0, // Fade in/out - duration: Duration(milliseconds: 150), + duration: const Duration(milliseconds: 150), child: Container( color: widget.show ? Colors.black.withAlpha(0) : Colors.transparent, - padding: widget.show ? EdgeInsets.symmetric(vertical: 32) : null, + padding: + widget.show ? const EdgeInsets.symmetric(vertical: 32) : null, child: Column( children: [ if (secondRowEmojis.isNotEmpty) @@ -761,11 +767,11 @@ class _ReactionButtonsState extends State { hide: widget.hide, show: widget.show, isVideo: widget.isVideo, - emoji: emoji, + emoji: emoji as String, )) .toList(), ), - if (secondRowEmojis.isNotEmpty) SizedBox(height: 15), + if (secondRowEmojis.isNotEmpty) const SizedBox(height: 15), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.end, @@ -791,22 +797,21 @@ class _ReactionButtonsState extends State { } class EmojiReactionWidget extends StatefulWidget { - final int userId; - final int responseToMessageId; - final Function hide; - final bool show; - final bool isVideo; - final String emoji; - const EmojiReactionWidget({ - super.key, required this.userId, required this.responseToMessageId, required this.hide, required this.isVideo, required this.show, required this.emoji, + super.key, }); + final int userId; + final int responseToMessageId; + final Function hide; + final bool show; + final bool isVideo; + final String emoji; @override State createState() => _EmojiReactionWidgetState(); @@ -818,7 +823,7 @@ class _EmojiReactionWidgetState extends State { @override Widget build(BuildContext context) { return AnimatedSize( - duration: Duration(milliseconds: 200), + duration: const Duration(milliseconds: 200), curve: Curves.linearToEaseOut, child: GestureDetector( onTap: () { @@ -838,7 +843,7 @@ class _EmojiReactionWidgetState extends State { setState(() { selectedShortReaction = 0; // Assuming index is 0 for this example }); - Future.delayed(Duration(milliseconds: 300), () { + Future.delayed(const Duration(milliseconds: 300), () { setState(() { widget.hide(); selectedShortReaction = -1; @@ -849,13 +854,13 @@ class _EmojiReactionWidgetState extends State { 0) // Assuming index is 0 for this example ? EmojiAnimationFlying( emoji: widget.emoji, - duration: Duration(milliseconds: 300), - startPosition: 0.0, + duration: const Duration(milliseconds: 300), + startPosition: 0, size: (widget.show) ? 40 : 10, ) : AnimatedOpacity( opacity: (selectedShortReaction == -1) ? 1 : 0, // Fade in/out - duration: Duration(milliseconds: 150), + duration: const Duration(milliseconds: 150), child: SizedBox( width: widget.show ? 40 : 10, child: Center( diff --git a/lib/src/views/chats/start_new_chat.view.dart b/lib/src/views/chats/start_new_chat.view.dart index d7b113b..a68b823 100644 --- a/lib/src/views/chats/start_new_chat.view.dart +++ b/lib/src/views/chats/start_new_chat.view.dart @@ -1,17 +1,18 @@ import 'dart:async'; + import 'package:drift/drift.dart' hide Column; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:pie_menu/pie_menu.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/views/components/flame.dart'; -import 'package:twonly/src/views/components/initialsavatar.dart'; -import 'package:twonly/src/views/components/user_context_menu.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/utils/misc.dart'; -import 'package:twonly/src/views/chats/chat_messages.view.dart'; import 'package:twonly/src/views/chats/add_new_user.view.dart'; +import 'package:twonly/src/views/chats/chat_messages.view.dart'; +import 'package:twonly/src/views/components/flame.dart'; +import 'package:twonly/src/views/components/initialsavatar.dart'; +import 'package:twonly/src/views/components/user_context_menu.dart'; class StartNewChatView extends StatefulWidget { const StartNewChatView({super.key}); @@ -29,8 +30,7 @@ class _StartNewChatView extends State { void initState() { super.initState(); - Stream> stream = - twonlyDB.contactsDao.watchContactsForStartNewChat(); + final stream = twonlyDB.contactsDao.watchContactsForStartNewChat(); contactSub = stream.listen((update) { update.sort((a, b) => @@ -48,14 +48,14 @@ class _StartNewChatView extends State { contactSub.cancel(); } - Future filterUsers() async { + Future filterUsers() async { if (searchUserName.value.text.isEmpty) { setState(() { contacts = allContacts; }); return; } - List usersFiltered = allContacts + final usersFiltered = allContacts .where((user) => getContactDisplayName(user) .toLowerCase() .contains(searchUserName.value.text.toLowerCase())) @@ -75,11 +75,12 @@ class _StartNewChatView extends State { child: PieCanvas( theme: getPieCanvasTheme(context), child: Padding( - padding: EdgeInsets.only(bottom: 40, left: 10, top: 20, right: 10), + padding: + const EdgeInsets.only(bottom: 40, left: 10, top: 20, right: 10), child: Column( children: [ Padding( - padding: EdgeInsets.symmetric(horizontal: 10), + padding: const EdgeInsets.symmetric(horizontal: 10), child: TextField( onChanged: (_) { filterUsers(); @@ -121,9 +122,9 @@ class UserList extends StatelessWidget { itemBuilder: (BuildContext context, int i) { if (i == 0) { return ListTile( - key: Key("add_new_contact"), + key: const Key('add_new_contact'), title: Text(context.lang.startNewChatNewContact), - leading: CircleAvatar( + leading: const CircleAvatar( child: FaIcon( FontAwesomeIcons.userPlus, size: 13, @@ -133,24 +134,22 @@ class UserList extends StatelessWidget { Navigator.push( context, MaterialPageRoute( - builder: (context) => AddNewUserView(), + builder: (context) => const AddNewUserView(), ), ); }, ); } if (i == 1) { - return Divider(); + return const Divider(); } - Contact user = users[i - 2]; - int flameCounter = getFlameCounterFromContact(user); + final user = users[i - 2]; + final flameCounter = getFlameCounterFromContact(user); return UserContextMenu( key: Key(user.userId.toString()), contact: user, child: ListTile( title: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, children: [ Text(getContactDisplayName(user)), if (flameCounter >= 1) @@ -159,14 +158,14 @@ class UserList extends StatelessWidget { flameCounter, prefix: true, ), - Spacer(), + const Spacer(), IconButton( icon: FaIcon(FontAwesomeIcons.boxOpen, size: 13, color: user.archived ? null : Colors.transparent), onPressed: user.archived ? () async { - final update = + const update = ContactsCompanion(archived: Value(false)); await twonlyDB.contactsDao .updateContact(user.userId, update); diff --git a/lib/src/views/components/alert_dialog.dart b/lib/src/views/components/alert_dialog.dart index d676f31..8393e31 100644 --- a/lib/src/views/components/alert_dialog.dart +++ b/lib/src/views/components/alert_dialog.dart @@ -10,9 +10,9 @@ Future showAlertDialog( String? customOk, String? customCancel, }) async { - Completer completer = Completer(); + final completer = Completer(); - Widget okButton = TextButton( + final Widget okButton = TextButton( child: Text(customOk ?? context.lang.ok), onPressed: () { completer.complete(true); @@ -20,7 +20,7 @@ Future showAlertDialog( }, ); - Widget cancelButton = TextButton( + final Widget cancelButton = TextButton( child: Text(customCancel ?? context.lang.cancel), onPressed: () { completer.complete(false); @@ -29,7 +29,7 @@ Future showAlertDialog( ); // set up the AlertDialog - AlertDialog alert = AlertDialog( + final alert = AlertDialog( title: Text(title), content: (content == null) ? null : Text(content), actions: [ @@ -39,7 +39,8 @@ Future showAlertDialog( ); // show the dialog - showDialog( + // ignore: inference_failure_on_function_invocation + await showDialog( context: context, builder: (BuildContext context) { return alert; diff --git a/lib/src/views/components/animate_icon.dart b/lib/src/views/components/animate_icon.dart index 1246585..c0712db 100644 --- a/lib/src/views/components/animate_icon.dart +++ b/lib/src/views/components/animate_icon.dart @@ -17,171 +17,170 @@ bool isEmoji(String character) { } class EmojiAnimation extends StatelessWidget { + const EmojiAnimation({required this.emoji, super.key, this.repeat = true}); final String emoji; final bool repeat; static final Map animatedIcons = { - "โค": "red_heart.json", - "๐Ÿ˜‚": "joy.json", - "๐Ÿ”ฅ": "fire.json", - "๐Ÿ’ช": "muscle.json", - "๐Ÿ˜ญ": "loudly-crying.json", - "๐Ÿคฏ": "mind-blown.json", - "โค๏ธโ€๐Ÿ”ฅ": "red_heart_fire.json", - "๐Ÿ˜": "grinning.json", - "๐Ÿ˜†": "laughing.json", - "๐Ÿ˜…": "grin-sweat.json", - "๐Ÿคฃ": "rofl.json", - "๐Ÿ˜‰": "wink.json", - "๐Ÿ˜˜": "kissing-heart.json", - "๐Ÿฅฐ": "heart-face.json", - "๐Ÿ˜": "heart-eyes.json", - "๐Ÿคฉ": "star-struck.json", - "๐Ÿฅณ": "partying-face.json", - "๐Ÿ™ƒ": "upside-down-face.json", - "๐Ÿฅฒ": "happy-cry.json", - "๐Ÿ˜Š": "blush.json", - "๐Ÿ˜": "smirk.json", - "๐Ÿคค": "drool.json", - "๐Ÿ˜‹": "yum.json", - "๐Ÿ˜›": "stuck-out-tongue.json", - "๐Ÿคช": "zany-face.json", - "๐Ÿฅด": "woozy.json", - "๐Ÿ˜”": "pensive.json", - "๐Ÿฅบ": "pleading.json", - "๐Ÿ˜ฌ": "grimacing.json", - "๐Ÿ˜‘": "expressionless.json", - "๐Ÿค": "zipper-face.json", - "๐Ÿค”": "thinking-face.json", - "๐Ÿฅฑ": "yawn.json", - "๐Ÿค—": "hug-face.json", - "๐Ÿ˜ฑ": "screaming.json", - "๐Ÿคจ": "raised-eyebrow.json", - "๐Ÿง": "monocle.json", - "๐Ÿ˜’": "unamused.json", - "๐Ÿ™„": "rolling-eyes.json", - "๐Ÿ˜ค": "triumph.json", - "๐Ÿคฌ": "cursing.json", - "๐Ÿ˜ž": "sad.json", - "๐Ÿ˜ข": "cry.json", - "๐Ÿ™": "frown.json", - "๐Ÿ˜จ": "scared.json", - "๐Ÿ˜ณ": "flushed.json", - "๐Ÿ˜–": "scrunched-mouth.json", - "๐Ÿ˜ต": "x-eyes.json", - "๐Ÿฅถ": "cold-face.json", - "๐Ÿฅต": "hot-face.json", - "๐Ÿคฎ": "vomit.json", - "๐Ÿ˜ด": "sleep.json", - "๐Ÿค’": "thermometer-face.json", - "๐Ÿค•": "bandage-face.json", - "๐Ÿคฅ": "liar.json", - "๐Ÿ˜‡": "halo.json", - "๐Ÿค ": "cowboy.json", - "๐Ÿค‘": "money-face.json", - "๐Ÿค“": "nerd-face.json", - "๐Ÿ˜Ž": "sunglasses-face.json", - "๐Ÿฅธ": "disguise.json", - "๐Ÿคก": "clown.json", - "๐Ÿ’ฉ": "poop.json", - "๐Ÿ˜ˆ": "imp-smile.json", - "๐Ÿ‘ป": "ghost.json", - "๐Ÿ’€": "skull.json", - "โ›„": "snowman.json", - "๐ŸŽƒ": "jack-o-lantern.json", - "๐Ÿค–": "robot.json", - "๐Ÿ‘ฝ": "alien.json", - "๐Ÿ™ˆ": "see-no-evil-monkey.json", - "๐Ÿ™‰": "hear-no-evil-monkey.json", - "๐Ÿ™Š": "speak-no-evil-monkey.json", - "๐ŸŒŸ": "glowing-star.json", - "โœจ": "sparkles.json", - "โšก": "electricity.json", - "๐Ÿ’ฅ": "collision.json", - "๐Ÿ’ฏ": "100.json", - "๐ŸŽ‰": "party-popper.json", - "๐ŸŽŠ": "confetti-ball.json", - "๐Ÿงก": "orange-heart.json", - "๐Ÿ’›": "yellow-heart.json", - "๐Ÿ’š": "green-heart.json", - "๐Ÿ’™": "blue-heart.json", - "๐Ÿ’œ": "purple-heart.json", - "๐Ÿ’˜": "cupid.json", - "๐Ÿ’": "gift-heart.json", - "๐Ÿ’–": "sparkling-heart.json", - "๐Ÿ’•": "two-hearts.json", - "๐Ÿ’”": "broken-heart.json", - "๐Ÿ’‹": "kiss.json", - "๐Ÿ‘€": "eyes.json", - "๐Ÿฆป": "hearing-aid.json", - "๐Ÿฆถ": "foot.json", - "๐Ÿฆพ": "arm-mechanical.json", - "๐Ÿ‘": "clap.json", - "๐Ÿ‘": "thumbs-up.json", - "๐Ÿ‘Ž": "thumbs-down.json", - "๐Ÿ™Œ": "raising-hands.json", - "โœŠ": "raised-fist.json", - "๐Ÿ‘Š": "fist.json", - "๐Ÿ‘‹": "wave.json", - "๐Ÿค˜": "metal.json", - "๐Ÿคž": "crossed-fingers.json", - "๐Ÿค™": "call-me-hand.json", - "๐Ÿ‘Œ": "ok.json", - "๐Ÿ–•": "middle-finger.json", - "๐Ÿค": "handshake.json", - "๐Ÿ’ƒ": "dancer-woman.json", - "๐ŸŒฑ": "plant.json", - "๐Ÿƒ": "leaves.json", - "๐Ÿ€": "luck.json", - "๐ŸŒŠ": "ocean.json", - "๐Ÿ’ง": "droplet.json", - "๐Ÿฆ„": "unicorn.json", - "๐Ÿฆ–": "t-rex.json", - "๐Ÿฆ•": "dinosaur.json", - "๐Ÿข": "turtle.json", - "๐Ÿ": "snake.json", - "๐Ÿฉ": "poodle.json", - "๐Ÿ•": "dog.json", - "๐Ÿ–": "pig.json", - "๐Ÿฆ˜": "kangaroo.json", - "๐Ÿฆ": "gorilla.json", - "๐Ÿฆง": "orangutan.json", - "๐Ÿฆฆ": "otter.json", - "๐Ÿ“": "rooster.json", - "๐Ÿฆ…": "eagle.json", - "๐Ÿฆ‰": "owl.json", - "๐Ÿฌ": "dolphin.json", - "๐Ÿณ": "whale.json", - "๐ŸŸ": "fish.json", - "๐Ÿก": "blowfish.json", - "๐Ÿฆ€": "crab.json", - "๐Ÿ™": "octopus.json", - "๐ŸŒ": "snail.json", - "๐Ÿป": "clinking-beer-mugs.json", - "๐Ÿพ": "bottle-with-popping-cork.json", - "๐Ÿšจ": "police-car-light.json", - "๐Ÿ›ธ": "flying-saucer.json", - "๐Ÿš€": "rocket.json", - "๐Ÿ›ซ": "airplane-departure.json", - "๐ŸŽข": "roller-coaster.json", - "๐ŸŽก": "ferris-wheel.json", - "๐ŸŽˆ": "balloon.json", - "๐ŸŽ": "wrapped-gift.json", - "๐ŸŽ†": "fireworks.json", - "๐Ÿ’ธ": "money-with-wings.json", - "๐Ÿ’Ž": "gem-stone.json", - "๐ŸŽ“": "graduation-cap.json", - "๐Ÿ””": "bell.json", - "๐Ÿ’ฃ": "bomb.json", - "โ—": "exclamation.json", - "โ“": "question.json", - "โŒ": "cross-mark.json", - "๐Ÿ": "chequered-flag.json", - "๐Ÿšฉ": "triangular-flag.json", - "๐Ÿด": "black-flag.json", + 'โค': 'red_heart.json', + '๐Ÿ˜‚': 'joy.json', + '๐Ÿ”ฅ': 'fire.json', + '๐Ÿ’ช': 'muscle.json', + '๐Ÿ˜ญ': 'loudly-crying.json', + '๐Ÿคฏ': 'mind-blown.json', + 'โค๏ธโ€๐Ÿ”ฅ': 'red_heart_fire.json', + '๐Ÿ˜': 'grinning.json', + '๐Ÿ˜†': 'laughing.json', + '๐Ÿ˜…': 'grin-sweat.json', + '๐Ÿคฃ': 'rofl.json', + '๐Ÿ˜‰': 'wink.json', + '๐Ÿ˜˜': 'kissing-heart.json', + '๐Ÿฅฐ': 'heart-face.json', + '๐Ÿ˜': 'heart-eyes.json', + '๐Ÿคฉ': 'star-struck.json', + '๐Ÿฅณ': 'partying-face.json', + '๐Ÿ™ƒ': 'upside-down-face.json', + '๐Ÿฅฒ': 'happy-cry.json', + '๐Ÿ˜Š': 'blush.json', + '๐Ÿ˜': 'smirk.json', + '๐Ÿคค': 'drool.json', + '๐Ÿ˜‹': 'yum.json', + '๐Ÿ˜›': 'stuck-out-tongue.json', + '๐Ÿคช': 'zany-face.json', + '๐Ÿฅด': 'woozy.json', + '๐Ÿ˜”': 'pensive.json', + '๐Ÿฅบ': 'pleading.json', + '๐Ÿ˜ฌ': 'grimacing.json', + '๐Ÿ˜‘': 'expressionless.json', + '๐Ÿค': 'zipper-face.json', + '๐Ÿค”': 'thinking-face.json', + '๐Ÿฅฑ': 'yawn.json', + '๐Ÿค—': 'hug-face.json', + '๐Ÿ˜ฑ': 'screaming.json', + '๐Ÿคจ': 'raised-eyebrow.json', + '๐Ÿง': 'monocle.json', + '๐Ÿ˜’': 'unamused.json', + '๐Ÿ™„': 'rolling-eyes.json', + '๐Ÿ˜ค': 'triumph.json', + '๐Ÿคฌ': 'cursing.json', + '๐Ÿ˜ž': 'sad.json', + '๐Ÿ˜ข': 'cry.json', + '๐Ÿ™': 'frown.json', + '๐Ÿ˜จ': 'scared.json', + '๐Ÿ˜ณ': 'flushed.json', + '๐Ÿ˜–': 'scrunched-mouth.json', + '๐Ÿ˜ต': 'x-eyes.json', + '๐Ÿฅถ': 'cold-face.json', + '๐Ÿฅต': 'hot-face.json', + '๐Ÿคฎ': 'vomit.json', + '๐Ÿ˜ด': 'sleep.json', + '๐Ÿค’': 'thermometer-face.json', + '๐Ÿค•': 'bandage-face.json', + '๐Ÿคฅ': 'liar.json', + '๐Ÿ˜‡': 'halo.json', + '๐Ÿค ': 'cowboy.json', + '๐Ÿค‘': 'money-face.json', + '๐Ÿค“': 'nerd-face.json', + '๐Ÿ˜Ž': 'sunglasses-face.json', + '๐Ÿฅธ': 'disguise.json', + '๐Ÿคก': 'clown.json', + '๐Ÿ’ฉ': 'poop.json', + '๐Ÿ˜ˆ': 'imp-smile.json', + '๐Ÿ‘ป': 'ghost.json', + '๐Ÿ’€': 'skull.json', + 'โ›„': 'snowman.json', + '๐ŸŽƒ': 'jack-o-lantern.json', + '๐Ÿค–': 'robot.json', + '๐Ÿ‘ฝ': 'alien.json', + '๐Ÿ™ˆ': 'see-no-evil-monkey.json', + '๐Ÿ™‰': 'hear-no-evil-monkey.json', + '๐Ÿ™Š': 'speak-no-evil-monkey.json', + '๐ŸŒŸ': 'glowing-star.json', + 'โœจ': 'sparkles.json', + 'โšก': 'electricity.json', + '๐Ÿ’ฅ': 'collision.json', + '๐Ÿ’ฏ': '100.json', + '๐ŸŽ‰': 'party-popper.json', + '๐ŸŽŠ': 'confetti-ball.json', + '๐Ÿงก': 'orange-heart.json', + '๐Ÿ’›': 'yellow-heart.json', + '๐Ÿ’š': 'green-heart.json', + '๐Ÿ’™': 'blue-heart.json', + '๐Ÿ’œ': 'purple-heart.json', + '๐Ÿ’˜': 'cupid.json', + '๐Ÿ’': 'gift-heart.json', + '๐Ÿ’–': 'sparkling-heart.json', + '๐Ÿ’•': 'two-hearts.json', + '๐Ÿ’”': 'broken-heart.json', + '๐Ÿ’‹': 'kiss.json', + '๐Ÿ‘€': 'eyes.json', + '๐Ÿฆป': 'hearing-aid.json', + '๐Ÿฆถ': 'foot.json', + '๐Ÿฆพ': 'arm-mechanical.json', + '๐Ÿ‘': 'clap.json', + '๐Ÿ‘': 'thumbs-up.json', + '๐Ÿ‘Ž': 'thumbs-down.json', + '๐Ÿ™Œ': 'raising-hands.json', + 'โœŠ': 'raised-fist.json', + '๐Ÿ‘Š': 'fist.json', + '๐Ÿ‘‹': 'wave.json', + '๐Ÿค˜': 'metal.json', + '๐Ÿคž': 'crossed-fingers.json', + '๐Ÿค™': 'call-me-hand.json', + '๐Ÿ‘Œ': 'ok.json', + '๐Ÿ–•': 'middle-finger.json', + '๐Ÿค': 'handshake.json', + '๐Ÿ’ƒ': 'dancer-woman.json', + '๐ŸŒฑ': 'plant.json', + '๐Ÿƒ': 'leaves.json', + '๐Ÿ€': 'luck.json', + '๐ŸŒŠ': 'ocean.json', + '๐Ÿ’ง': 'droplet.json', + '๐Ÿฆ„': 'unicorn.json', + '๐Ÿฆ–': 't-rex.json', + '๐Ÿฆ•': 'dinosaur.json', + '๐Ÿข': 'turtle.json', + '๐Ÿ': 'snake.json', + '๐Ÿฉ': 'poodle.json', + '๐Ÿ•': 'dog.json', + '๐Ÿ–': 'pig.json', + '๐Ÿฆ˜': 'kangaroo.json', + '๐Ÿฆ': 'gorilla.json', + '๐Ÿฆง': 'orangutan.json', + '๐Ÿฆฆ': 'otter.json', + '๐Ÿ“': 'rooster.json', + '๐Ÿฆ…': 'eagle.json', + '๐Ÿฆ‰': 'owl.json', + '๐Ÿฌ': 'dolphin.json', + '๐Ÿณ': 'whale.json', + '๐ŸŸ': 'fish.json', + '๐Ÿก': 'blowfish.json', + '๐Ÿฆ€': 'crab.json', + '๐Ÿ™': 'octopus.json', + '๐ŸŒ': 'snail.json', + '๐Ÿป': 'clinking-beer-mugs.json', + '๐Ÿพ': 'bottle-with-popping-cork.json', + '๐Ÿšจ': 'police-car-light.json', + '๐Ÿ›ธ': 'flying-saucer.json', + '๐Ÿš€': 'rocket.json', + '๐Ÿ›ซ': 'airplane-departure.json', + '๐ŸŽข': 'roller-coaster.json', + '๐ŸŽก': 'ferris-wheel.json', + '๐ŸŽˆ': 'balloon.json', + '๐ŸŽ': 'wrapped-gift.json', + '๐ŸŽ†': 'fireworks.json', + '๐Ÿ’ธ': 'money-with-wings.json', + '๐Ÿ’Ž': 'gem-stone.json', + '๐ŸŽ“': 'graduation-cap.json', + '๐Ÿ””': 'bell.json', + '๐Ÿ’ฃ': 'bomb.json', + 'โ—': 'exclamation.json', + 'โ“': 'question.json', + 'โŒ': 'cross-mark.json', + '๐Ÿ': 'chequered-flag.json', + '๐Ÿšฉ': 'triangular-flag.json', + '๐Ÿด': 'black-flag.json', }; - const EmojiAnimation({super.key, required this.emoji, this.repeat = true}); - static bool supported(String emoji) { if (emoji.length > 4) return false; return animatedIcons.containsKey(emoji) || isEmoji(emoji); @@ -194,39 +193,38 @@ class EmojiAnimation extends StatelessWidget { // Check if the emoji has a corresponding Lottie animation if (animatedIcons.containsKey(emoji)) { return Lottie.asset( - "assets/animated_icons/${animatedIcons[emoji]}", + 'assets/animated_icons/${animatedIcons[emoji]}', repeat: repeat, ); } else if (isEmoji(emoji)) { return Text( emoji, - style: TextStyle(fontSize: 60), + style: const TextStyle(fontSize: 60), ); } else { return Text( emoji, - style: TextStyle(fontSize: 15), + style: const TextStyle(fontSize: 15), ); } } } class EmojiAnimationFlying extends StatelessWidget { + const EmojiAnimationFlying({ + required this.emoji, + required this.duration, + required this.startPosition, + required this.size, + super.key, + this.repeat = true, + }); final String emoji; final Duration duration; final double startPosition; final int size; final bool repeat; - const EmojiAnimationFlying({ - super.key, - required this.emoji, - required this.duration, - required this.startPosition, - required this.size, - this.repeat = true, - }); - @override Widget build(BuildContext context) { return TweenAnimationBuilder( diff --git a/lib/src/views/components/app_outdated.dart b/lib/src/views/components/app_outdated.dart new file mode 100644 index 0000000..617144b --- /dev/null +++ b/lib/src/views/components/app_outdated.dart @@ -0,0 +1,86 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:twonly/globals.dart'; +import 'package:twonly/src/providers/connection.provider.dart'; +import 'package:twonly/src/utils/misc.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class AppOutdated extends StatefulWidget { + const AppOutdated({super.key}); + + @override + State createState() => _AppOutdatedState(); +} + +class _AppOutdatedState extends State { + bool appIsOutdated = false; + + @override + void dispose() { + globalCallbackAppIsOutdated = () {}; + super.dispose(); + } + + Future initAsync() async { + globalCallbackAppIsOutdated = () async { + await context.read().updateConnectionState(false); + setState(() { + appIsOutdated = true; + }); + }; + } + + @override + Widget build(BuildContext context) { + if (!appIsOutdated) return Container(); + return Positioned( + top: 60, + left: 30, + right: 30, + child: SafeArea( + child: Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(10), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Text( + context.lang.appOutdated, + textAlign: TextAlign.center, + softWrap: true, + style: Theme.of(context) + .textTheme + .bodyMedium + ?.copyWith(color: Colors.white, fontSize: 16), + ), + if (Platform.isAndroid) const SizedBox(height: 5), + if (Platform.isAndroid) + ElevatedButton( + onPressed: () { + launchUrl(Uri.parse( + 'https://play.google.com/store/apps/details?id=eu.twonly')); + }, + style: ElevatedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: Text( + context.lang.appOutdatedBtn, + style: Theme.of(context) + .textTheme + .bodyMedium + ?.copyWith(color: Colors.white, fontSize: 16), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/src/views/components/better_list_title.dart b/lib/src/views/components/better_list_title.dart index 4ebfb27..b120c9e 100644 --- a/lib/src/views/components/better_list_title.dart +++ b/lib/src/views/components/better_list_title.dart @@ -2,6 +2,14 @@ import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; class BetterListTile extends StatelessWidget { + const BetterListTile( + {required this.icon, + required this.text, + required this.onTap, + super.key, + this.color, + this.subtitle, + this.iconSize = 20}); final IconData icon; final String text; final Widget? subtitle; @@ -9,15 +17,6 @@ class BetterListTile extends StatelessWidget { final VoidCallback onTap; final double iconSize; - const BetterListTile( - {super.key, - required this.icon, - required this.text, - this.color, - this.subtitle, - required this.onTap, - this.iconSize = 20}); - @override Widget build(BuildContext context) { return ListTile( diff --git a/lib/src/views/components/better_text.dart b/lib/src/views/components/better_text.dart index 53691fa..d48a45b 100644 --- a/lib/src/views/components/better_text.dart +++ b/lib/src/views/components/better_text.dart @@ -1,36 +1,34 @@ -import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:url_launcher/url_launcher.dart'; class BetterText extends StatelessWidget { + const BetterText({required this.text, super.key}); final String text; - const BetterText({super.key, required this.text}); - @override Widget build(BuildContext context) { // Regular expression to find URLs and domains - final RegExp urlRegExp = RegExp( + final urlRegExp = RegExp( r'(?:(?:https?://|www\.)[^\s]+|(?:[a-zA-Z0-9-]+\.[a-zA-Z]{2,}))', caseSensitive: false, - multiLine: false, ); - final List spans = []; - final Iterable matches = urlRegExp.allMatches(text); + final spans = []; + final matches = urlRegExp.allMatches(text); - int lastMatchEnd = 0; + var lastMatchEnd = 0; for (final match in matches) { if (match.start > lastMatchEnd) { spans.add(TextSpan(text: text.substring(lastMatchEnd, match.start))); } - final String? url = match.group(0); + final url = match.group(0); spans.add(TextSpan( text: url, - style: TextStyle(color: Colors.blue), + style: const TextStyle(color: Colors.blue), recognizer: TapGestureRecognizer() ..onTap = () async { final lUrl = @@ -38,7 +36,7 @@ class BetterText extends StatelessWidget { try { await launchUrl(lUrl); } catch (e) { - Log.error("Could not launch $e"); + Log.error('Could not launch $e'); } }, )); @@ -54,7 +52,7 @@ class BetterText extends StatelessWidget { TextSpan( children: spans, ), - style: TextStyle( + style: const TextStyle( color: Colors.white, fontSize: 17, ), diff --git a/lib/src/views/components/format_long_string.dart b/lib/src/views/components/fingerprint_text.dart similarity index 65% rename from lib/src/views/components/format_long_string.dart rename to lib/src/views/components/fingerprint_text.dart index ca74935..e7cf081 100644 --- a/lib/src/views/components/format_long_string.dart +++ b/lib/src/views/components/fingerprint_text.dart @@ -1,16 +1,15 @@ import 'package:flutter/material.dart'; -class FormattedStringWidget extends StatelessWidget { +class FingerprintText extends StatelessWidget { + const FingerprintText(this.longString, {super.key}); final String longString; - const FormattedStringWidget(this.longString, {super.key}); - String formatString(String input) { - StringBuffer formattedString = StringBuffer(); - int blockCount = 0; + final formattedString = StringBuffer(); + var blockCount = 0; - for (int i = 0; i < input.length; i += 4) { - String block = + for (var i = 0; i < input.length; i += 4) { + final block = input.substring(i, i + 4 > input.length ? input.length : i + 4); formattedString.write(block); blockCount++; @@ -30,7 +29,7 @@ class FormattedStringWidget extends StatelessWidget { Widget build(BuildContext context) { return SelectableText( formatString(longString), - style: TextStyle(fontSize: 16, color: Colors.black), + style: const TextStyle(fontSize: 16, color: Colors.black), textAlign: TextAlign.center, ); } diff --git a/lib/src/views/components/flame.dart b/lib/src/views/components/flame.dart index 19af603..2fc4ccc 100644 --- a/lib/src/views/components/flame.dart +++ b/lib/src/views/components/flame.dart @@ -1,26 +1,25 @@ import 'package:flutter/material.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/views/components/animate_icon.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/views/components/animate_icon.dart'; class FlameCounterWidget extends StatelessWidget { - final Contact user; - final int flameCounter; - final bool prefix; - const FlameCounterWidget( this.user, this.flameCounter, { this.prefix = false, super.key, }); + final Contact user; + final int flameCounter; + final bool prefix; @override Widget build(BuildContext context) { return Row( children: [ if (prefix) const SizedBox(width: 5), - if (prefix) Text("โ€ข"), + if (prefix) const Text('โ€ข'), if (prefix) const SizedBox(width: 5), Text( flameCounter.toString(), @@ -29,7 +28,7 @@ class FlameCounterWidget extends StatelessWidget { SizedBox( height: 15, child: EmojiAnimation( - emoji: (globalBestFriendUserId == user.userId) ? "โค๏ธโ€๐Ÿ”ฅ" : "๐Ÿ”ฅ"), + emoji: (globalBestFriendUserId == user.userId) ? 'โค๏ธโ€๐Ÿ”ฅ' : '๐Ÿ”ฅ'), ), ], ); diff --git a/lib/src/views/components/headline.dart b/lib/src/views/components/headline.dart index cf73589..f21c5ae 100644 --- a/lib/src/views/components/headline.dart +++ b/lib/src/views/components/headline.dart @@ -1,18 +1,17 @@ import 'package:flutter/material.dart'; class HeadLineComponent extends StatelessWidget { - final String text; - const HeadLineComponent(this.text, {super.key}); + final String text; @override Widget build(BuildContext context) { return Container( alignment: Alignment.centerLeft, - padding: EdgeInsets.symmetric(horizontal: 4.0, vertical: 10), + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 10), child: Text( text, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), ), ); } diff --git a/lib/src/views/components/initialsavatar.dart b/lib/src/views/components/initialsavatar.dart index 3fbaf2d..b5fe029 100644 --- a/lib/src/views/components/initialsavatar.dart +++ b/lib/src/views/components/initialsavatar.dart @@ -6,24 +6,23 @@ import 'package:twonly/src/model/json/userdata.dart'; import 'package:twonly/src/utils/log.dart'; class ContactAvatar extends StatelessWidget { - final Contact? contact; - final UserData? userData; - final double? fontSize; - const ContactAvatar({ super.key, this.contact, this.userData, this.fontSize = 20, }); + final Contact? contact; + final UserData? userData; + final double? fontSize; @override Widget build(BuildContext context) { - String displayName = ""; + var displayName = ''; String? avatarSvg; if (contact != null) { - displayName = getContactDisplayName(contact!).replaceAll("\u0336", ""); + displayName = getContactDisplayName(contact!).replaceAll('\u0336', ''); avatarSvg = contact!.avatarSvg; } else if (userData != null) { displayName = userData!.displayName; @@ -32,7 +31,7 @@ class ContactAvatar extends StatelessWidget { return Container(); } - double proSize = (fontSize == null) ? 40 : (fontSize! * 2); + final proSize = (fontSize == null) ? 40 : (fontSize! * 2); if (avatarSvg != null) { return Container( @@ -44,15 +43,15 @@ class ContactAvatar extends StatelessWidget { ), child: Center( child: ClipRRect( - borderRadius: BorderRadius.circular(12.0), + borderRadius: BorderRadius.circular(12), child: SizedBox( - height: proSize, + height: proSize as double, width: proSize, child: Center( child: SvgPicture.string( avatarSvg, errorBuilder: (context, error, stackTrace) { - Log.error("$error"); + Log.error('$error'); return Container(); }, ), @@ -64,8 +63,8 @@ class ContactAvatar extends StatelessWidget { } // Extract initials from the displayName - List nameParts = displayName.split(' '); - String initials = nameParts.map((part) => part[0]).join().toUpperCase(); + final nameParts = displayName.split(' '); + var initials = nameParts.map((part) => part[0]).join().toUpperCase(); if (initials.length > 2) { initials = initials[0] + initials[1]; @@ -76,10 +75,10 @@ class ContactAvatar extends StatelessWidget { initials = initials.toUpperCase(); // Generate a color based on the initials (you can customize this logic) - Color avatarColor = _getColorFromUsername( + final avatarColor = _getColorFromUsername( displayName, Theme.of(context).brightness == Brightness.dark); - Widget child = Text( + final Widget child = Text( initials, style: TextStyle( color: _getTextColor(avatarColor), @@ -88,50 +87,51 @@ class ContactAvatar extends StatelessWidget { ), ); - bool isPro = initials[0] == "T"; + final isPro = initials[0] == 'T'; - return isPro - ? //or 15.0 - Container( - constraints: BoxConstraints( - minHeight: 2 * (fontSize ?? 20), - minWidth: 2 * (fontSize ?? 20), - maxWidth: 2 * (fontSize ?? 20), - maxHeight: 2 * (fontSize ?? 20), + if (isPro) { + return Container( + constraints: BoxConstraints( + minHeight: 2 * (fontSize ?? 20), + minWidth: 2 * (fontSize ?? 20), + maxWidth: 2 * (fontSize ?? 20), + maxHeight: 2 * (fontSize ?? 20), + ), + child: Center( + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Container( + height: proSize as double, + width: proSize, + //padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), + color: avatarColor, + child: Center(child: child), ), - child: Center( - child: ClipRRect( - borderRadius: BorderRadius.circular(12.0), - child: Container( - height: proSize, - width: proSize, - //padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), - color: avatarColor, - child: Center(child: child), - ), - ), - ), - ) - : CircleAvatar( - backgroundColor: avatarColor, - radius: fontSize, - child: child, - ); + ), + ), + ); + } else { + return CircleAvatar( + backgroundColor: avatarColor, + radius: fontSize, + child: child, + ); + } } Color _getTextColor(Color color) { - double value = 100.0; + const value = 100.0; // Ensure the value does not exceed the RGB limits - int newRed = ((color.r * 255) - value).clamp(0, 255).round(); - int newGreen = (color.g * 255 - value).clamp(0, 255).round(); - int newBlue = (color.b * 255 - value).clamp(0, 255).round(); + final newRed = ((color.r * 255) - value).clamp(0, 255).round(); + final newGreen = (color.g * 255 - value).clamp(0, 255).round(); + final newBlue = (color.b * 255 - value).clamp(0, 255).round(); return Color.fromARGB((color.a * 255).round(), newRed, newGreen, newBlue); } Color _getColorFromUsername(String displayName, bool isDarkMode) { // Define color lists for light and dark themes - List lightColors = [ + final lightColors = [ Colors.red, Colors.green, Colors.blue, @@ -147,7 +147,7 @@ class ContactAvatar extends StatelessWidget { Colors.grey, ]; - List darkColors = [ + final darkColors = [ const Color.fromARGB(255, 246, 227, 254), // Light Lavender const Color.fromARGB(255, 246, 216, 215), // Light Pink const Color.fromARGB(255, 226, 236, 235), // Light Teal @@ -168,10 +168,11 @@ class ContactAvatar extends StatelessWidget { ]; // Simple logic to generate a hash from initials - int hash = displayName.codeUnits.fold(0, (prev, element) => prev + element); + final hash = + displayName.codeUnits.fold(0, (prev, element) => prev + element); // Select the appropriate color list based on the current theme brightness - List colors = isDarkMode ? darkColors : lightColors; + final colors = isDarkMode ? darkColors : lightColors; // Use the hash to select a color from the list return colors[hash % colors.length]; diff --git a/lib/src/views/components/media_view_sizing.dart b/lib/src/views/components/media_view_sizing.dart index 8abfa7f..116376d 100644 --- a/lib/src/views/components/media_view_sizing.dart +++ b/lib/src/views/components/media_view_sizing.dart @@ -2,9 +2,9 @@ import 'package:flutter/material.dart'; class MediaViewSizing extends StatefulWidget { const MediaViewSizing( - {super.key, + {required this.child, + super.key, this.requiredHeight, - required this.child, this.bottomNavigation}); final double? requiredHeight; @@ -18,7 +18,7 @@ class MediaViewSizing extends StatefulWidget { class _MediaViewSizingState extends State { @override Widget build(BuildContext context) { - bool needToDownSizeImage = false; + var needToDownSizeImage = false; if (widget.requiredHeight != null) { // Get the screen size and safe area padding @@ -30,8 +30,8 @@ class _MediaViewSizingState extends State { final availableHeight = screenSize.height - safeAreaPadding.top - safeAreaPadding.bottom; - var aspectRatioWidth = availableWidth; - var aspectRatioHeight = (aspectRatioWidth * 16) / 9; + final aspectRatioWidth = availableWidth; + final aspectRatioHeight = (aspectRatioWidth * 16) / 9; if (aspectRatioHeight < availableHeight) { if ((screenSize.height - widget.requiredHeight!) < aspectRatioHeight) { needToDownSizeImage = true; @@ -65,7 +65,6 @@ class _MediaViewSizingState extends State { return SafeArea( child: Column( - mainAxisAlignment: MainAxisAlignment.start, children: [imageChild, bottomNavigation], ), ); diff --git a/lib/src/views/components/message_send_state_icon.dart b/lib/src/views/components/message_send_state_icon.dart index f62e0e1..9d0968e 100644 --- a/lib/src/views/components/message_send_state_icon.dart +++ b/lib/src/views/components/message_send_state_icon.dart @@ -1,9 +1,10 @@ import 'dart:collection'; import 'dart:convert'; + import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; -import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/database/tables/messages_table.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/json/message.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/components/animate_icon.dart'; @@ -47,16 +48,15 @@ MessageSendState messageSendStateFromMessage(Message msg) { } class MessageSendStateIcon extends StatefulWidget { - final List messages; - final MainAxisAlignment mainAxisAlignment; - final bool canBeReopened; - const MessageSendStateIcon( this.messages, { super.key, this.canBeReopened = false, this.mainAxisAlignment = MainAxisAlignment.end, }); + final List messages; + final MainAxisAlignment mainAxisAlignment; + final bool canBeReopened; @override State createState() => _MessageSendStateIconState(); @@ -68,7 +68,7 @@ class _MessageSendStateIconState extends State { super.initState(); } - Widget getLoaderIcon(color) { + Widget getLoaderIcon(Color color) { return Row( children: [ SizedBox( @@ -76,17 +76,17 @@ class _MessageSendStateIconState extends State { height: 10, child: CircularProgressIndicator(strokeWidth: 1, color: color), ), - SizedBox(width: 2), + const SizedBox(width: 2), ], ); } @override Widget build(BuildContext context) { - List icons = []; - String text = ""; + final icons = []; + var text = ''; - HashSet kindsAlreadyShown = HashSet(); + final kindsAlreadyShown = HashSet(); Widget? textWidget; for (final message in widget.messages) { @@ -94,22 +94,22 @@ class _MessageSendStateIconState extends State { if (kindsAlreadyShown.contains(message.kind)) continue; kindsAlreadyShown.add(message.kind); - MessageSendState state = messageSendStateFromMessage(message); + final state = messageSendStateFromMessage(message); late Color color; MessageContent? content; if (message.contentJson == null) { - color = getMessageColorFromType(TextMessageContent(text: ""), context); + color = getMessageColorFromType(TextMessageContent(text: ''), context); } else { content = MessageContent.fromJson( message.kind, - jsonDecode(message.contentJson!), + jsonDecode(message.contentJson!) as Map, ); if (content == null) continue; color = getMessageColorFromType(content, context); } - Widget icon = Placeholder(); + Widget icon = const Placeholder(); textWidget = null; switch (state) { @@ -117,21 +117,19 @@ class _MessageSendStateIconState extends State { icon = Icon(Icons.crop_square, size: 14, color: color); if (content is TextMessageContent) { if (isEmoji(content.text)) { - icon = Text(content.text, style: TextStyle(fontSize: 12)); + icon = Text(content.text, style: const TextStyle(fontSize: 12)); } } text = context.lang.messageSendState_Received; if (widget.canBeReopened) { textWidget = Text( context.lang.doubleClickToReopen, - style: TextStyle(fontSize: 9), + style: const TextStyle(fontSize: 9), ); } - break; case MessageSendState.sendOpened: icon = FaIcon(FontAwesomeIcons.paperPlane, size: 12, color: color); text = context.lang.messageSendState_Opened; - break; case MessageSendState.received: icon = Icon(Icons.square_rounded, size: 14, color: color); text = context.lang.messageSendState_Received; @@ -144,24 +142,21 @@ class _MessageSendStateIconState extends State { icon = getLoaderIcon(color); } } - break; case MessageSendState.send: icon = FaIcon(FontAwesomeIcons.solidPaperPlane, size: 12, color: color); text = context.lang.messageSendState_Send; - break; case MessageSendState.sending: icon = getLoaderIcon(color); text = context.lang.messageSendState_Sending; case MessageSendState.receiving: icon = getLoaderIcon(color); text = context.lang.messageSendState_Received; - break; } if (message.kind == MessageKind.storedMediaFile) { icon = FaIcon(FontAwesomeIcons.floppyDisk, size: 12, color: color); - text = context.lang.messageStoredInGalery; + text = context.lang.messageStoredInGallery; } if (message.kind == MessageKind.reopenedMedia) { @@ -172,14 +167,14 @@ class _MessageSendStateIconState extends State { if (message.errorWhileSending) { icon = FaIcon(FontAwesomeIcons.circleExclamation, size: 12, color: color); - text = "Error"; + text = 'Error'; } if (message.mediaRetransmissionState == MediaRetransmitting.requested) { icon = FaIcon(FontAwesomeIcons.clockRotateLeft, size: 12, color: color); textWidget = Text( context.lang.retransmissionRequested, - style: TextStyle(fontSize: 9), + style: const TextStyle(fontSize: 9), ); } @@ -192,7 +187,7 @@ class _MessageSendStateIconState extends State { if (icons.isEmpty) return Container(); - Widget icon = icons[0]; + var icon = icons[0]; if (icons.length == 2) { icon = Stack( @@ -204,7 +199,7 @@ class _MessageSendStateIconState extends State { Transform( transform: Matrix4.identity() ..scale(0.7) // Scale to half - ..translate(3.0, 5.0), + ..translate(3.0, 5), // Move down by 10 pixels (adjust as needed) alignment: Alignment.center, child: icons[1], @@ -219,12 +214,13 @@ class _MessageSendStateIconState extends State { children: [ icon, const SizedBox(width: 3), - (textWidget != null) - ? textWidget - : Text( - text, - style: TextStyle(fontSize: 12), - ), + if (textWidget != null) + textWidget + else + Text( + text, + style: const TextStyle(fontSize: 12), + ), const SizedBox(width: 5), ], ); diff --git a/lib/src/views/components/notification_badge.dart b/lib/src/views/components/notification_badge.dart index bf79500..47c2645 100644 --- a/lib/src/views/components/notification_badge.dart +++ b/lib/src/views/components/notification_badge.dart @@ -1,16 +1,15 @@ import 'package:flutter/material.dart'; class NotificationBadge extends StatelessWidget { + const NotificationBadge( + {required this.count, required this.child, super.key}); final String count; final Widget child; - const NotificationBadge( - {super.key, required this.count, required this.child}); - @override Widget build(BuildContext context) { - if (count == "0") return child; - bool infinity = count == "โˆž"; + if (count == '0') return child; + final infinity = count == 'โˆž'; return Stack( children: [ child, @@ -26,8 +25,8 @@ class NotificationBadge extends StatelessWidget { child: Transform.rotate( angle: infinity ? 90 * (3.141592653589793 / 180) : 0, child: Text( - infinity ? "8" : count, - style: TextStyle( + infinity ? '8' : count, + style: const TextStyle( color: Colors.white, // Text color fontSize: 10, ), diff --git a/lib/src/views/components/radio_button.dart b/lib/src/views/components/radio_button.dart index d93c4b0..3d71638 100644 --- a/lib/src/views/components/radio_button.dart +++ b/lib/src/views/components/radio_button.dart @@ -1,18 +1,17 @@ import 'package:flutter/material.dart'; class RadioButton extends StatelessWidget { - final T value; - final T? groupValue; - final String label; - final ValueChanged onChanged; - const RadioButton({ - super.key, required this.value, required this.groupValue, required this.label, required this.onChanged, + super.key, }); + final T value; + final T? groupValue; + final String label; + final ValueChanged onChanged; @override Widget build(BuildContext context) { diff --git a/lib/src/views/components/user_context_menu.dart b/lib/src/views/components/user_context_menu.dart index 01f5205..ac2b0a1 100644 --- a/lib/src/views/components/user_context_menu.dart +++ b/lib/src/views/components/user_context_menu.dart @@ -11,14 +11,13 @@ import 'package:twonly/src/views/contact/contact.view.dart'; import 'package:twonly/src/views/contact/contact_verify.view.dart'; class UserContextMenu extends StatefulWidget { - final Widget child; - final Contact contact; - const UserContextMenu({ - super.key, required this.contact, required this.child, + super.key, }); + final Widget child; + final Contact contact; @override State createState() => _UserContextMenuState(); @@ -39,25 +38,25 @@ class _UserContextMenuState extends State { PieAction( tooltip: Text(context.lang.contextMenuArchiveUser), onSelect: () async { - final update = ContactsCompanion(archived: Value(true)); + const update = ContactsCompanion(archived: Value(true)); if (context.mounted) { await twonlyDB.contactsDao .updateContact(widget.contact.userId, update); } }, - child: FaIcon(FontAwesomeIcons.boxArchive), + child: const FaIcon(FontAwesomeIcons.boxArchive), ), if (widget.contact.archived) PieAction( tooltip: Text(context.lang.contextMenuUndoArchiveUser), onSelect: () async { - final update = ContactsCompanion(archived: Value(false)); + const update = ContactsCompanion(archived: Value(false)); if (context.mounted) { await twonlyDB.contactsDao .updateContact(widget.contact.userId, update); } }, - child: FaIcon(FontAwesomeIcons.boxOpen), + child: const FaIcon(FontAwesomeIcons.boxOpen), ), if (!widget.contact.verified) PieAction( @@ -107,14 +106,13 @@ class _UserContextMenuState extends State { } class UserContextMenuBlocked extends StatefulWidget { - final Widget child; - final Contact contact; - const UserContextMenuBlocked({ - super.key, required this.contact, required this.child, + super.key, }); + final Widget child; + final Contact contact; @override State createState() => _UserContextMenuBlocked(); @@ -130,25 +128,25 @@ class _UserContextMenuBlocked extends State { PieAction( tooltip: Text(context.lang.contextMenuArchiveUser), onSelect: () async { - final update = ContactsCompanion(archived: Value(true)); + const update = ContactsCompanion(archived: Value(true)); if (context.mounted) { await twonlyDB.contactsDao .updateContact(widget.contact.userId, update); } }, - child: FaIcon(FontAwesomeIcons.boxArchive), + child: const FaIcon(FontAwesomeIcons.boxArchive), ), if (widget.contact.archived) PieAction( tooltip: Text(context.lang.contextMenuUndoArchiveUser), onSelect: () async { - final update = ContactsCompanion(archived: Value(false)); + const update = ContactsCompanion(archived: Value(false)); if (context.mounted) { await twonlyDB.contactsDao .updateContact(widget.contact.userId, update); } }, - child: FaIcon(FontAwesomeIcons.boxOpen), + child: const FaIcon(FontAwesomeIcons.boxOpen), ), PieAction( tooltip: Text(context.lang.contextMenuUserProfile), @@ -180,10 +178,10 @@ PieTheme getPieCanvasTheme(BuildContext context) { backgroundColor: Theme.of(context).colorScheme.primary, iconColor: Theme.of(context).colorScheme.surfaceBright, ), - tooltipPadding: EdgeInsets.all(20), + tooltipPadding: const EdgeInsets.all(20), overlayColor: const Color.fromARGB(69, 0, 0, 0), // spacing: 0, - tooltipTextStyle: TextStyle( + tooltipTextStyle: const TextStyle( fontSize: 32, fontWeight: FontWeight.w600, ), diff --git a/lib/src/views/components/verified_shield.dart b/lib/src/views/components/verified_shield.dart index 780a196..101a20c 100644 --- a/lib/src/views/components/verified_shield.dart +++ b/lib/src/views/components/verified_shield.dart @@ -4,11 +4,10 @@ import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/views/contact/contact_verify.view.dart'; class VerifiedShield extends StatelessWidget { + const VerifiedShield(this.contact, {super.key, this.size = 18}); final Contact contact; final double size; - const VerifiedShield(this.contact, {super.key, this.size = 18}); - @override Widget build(BuildContext context) { return GestureDetector( @@ -21,8 +20,8 @@ class VerifiedShield extends StatelessWidget { }, child: Tooltip( message: contact.verified - ? "You verified this contact" - : "You have not verifies this contact.", + ? 'You verified this contact' + : 'You have not verifies this contact.', child: FaIcon( contact.verified ? FontAwesomeIcons.shieldHeart diff --git a/lib/src/views/components/video_player_wrapper.dart b/lib/src/views/components/video_player_wrapper.dart index b67a58b..2ed4be2 100644 --- a/lib/src/views/components/video_player_wrapper.dart +++ b/lib/src/views/components/video_player_wrapper.dart @@ -4,12 +4,11 @@ import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; class VideoPlayerWrapper extends StatefulWidget { + const VideoPlayerWrapper( + {required this.videoPath, required this.mirrorVideo, super.key}); final File videoPath; final bool mirrorVideo; - const VideoPlayerWrapper( - {super.key, required this.videoPath, required this.mirrorVideo}); - @override State createState() => _VideoPlayerWrapperState(); } @@ -24,8 +23,9 @@ class _VideoPlayerWrapperState extends State { ..initialize().then((_) { if (context.mounted) { setState(() { - _controller.setLooping(true); - _controller.play(); + _controller + ..setLooping(true) + ..play(); }); } }); @@ -48,7 +48,7 @@ class _VideoPlayerWrapperState extends State { child: VideoPlayer(_controller), ), ) - : CircularProgressIndicator(), // Show loading indicator while initializing + : const CircularProgressIndicator(), // Show loading indicator while initializing ); } } diff --git a/lib/src/views/contact/contact.view.dart b/lib/src/views/contact/contact.view.dart index 16096f9..ea68ed5 100644 --- a/lib/src/views/contact/contact.view.dart +++ b/lib/src/views/contact/contact.view.dart @@ -1,17 +1,17 @@ import 'package:drift/drift.dart'; +import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:twonly/globals.dart'; +import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/services/api/utils.dart'; +import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/views/components/better_list_title.dart'; import 'package:twonly/src/views/components/flame.dart'; import 'package:twonly/src/views/components/initialsavatar.dart'; import 'package:twonly/src/views/components/verified_shield.dart'; -import 'package:flutter/material.dart'; -import 'package:twonly/src/database/twonly_database.dart'; -import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/contact/contact_verify.view.dart'; -import 'package:twonly/src/database/daos/contacts_dao.dart'; class ContactView extends StatefulWidget { const ContactView(this.userId, {super.key}); @@ -23,15 +23,15 @@ class ContactView extends StatefulWidget { } class _ContactViewState extends State { - Future handleUserRemoveRequest(Contact contact) async { - bool remove = await showAlertDialog( + Future handleUserRemoveRequest(Contact contact) async { + final remove = await showAlertDialog( context, context.lang.contactRemoveTitle(getContactDisplayName(contact)), context.lang.contactRemoveBody, ); if (remove) { // trigger deletion for the other user... - rejectUser(contact.userId); + await rejectUser(contact.userId); await deleteContact(contact.userId); if (mounted) { Navigator.popUntil(context, (route) => route.isFirst); @@ -39,18 +39,18 @@ class _ContactViewState extends State { } } - Future handleUserBlockRequest(Contact contact) async { - bool block = await showAlertDialog( + Future handleUserBlockRequest(Contact contact) async { + final block = await showAlertDialog( context, context.lang.contactBlockTitle(getContactDisplayName(contact)), context.lang.contactBlockBody, ); if (block) { - final update = ContactsCompanion(blocked: Value(true)); + const update = ContactsCompanion(blocked: Value(true)); if (context.mounted) { await twonlyDB.contactsDao.updateContact(contact.userId, update); } - if (context.mounted) { + if (mounted) { Navigator.popUntil(context, (route) => route.isFirst); } } @@ -58,13 +58,13 @@ class _ContactViewState extends State { @override Widget build(BuildContext context) { - Stream contact = twonlyDB.contactsDao + final contact = twonlyDB.contactsDao .getContactByUserId(widget.userId) .watchSingleOrNull(); return Scaffold( appBar: AppBar( - title: Text(""), + title: const Text(''), ), body: StreamBuilder( stream: contact, @@ -73,7 +73,7 @@ class _ContactViewState extends State { return Container(); } final contact = snapshot.data!; - int flameCounter = getFlameCounterFromContact(contact); + final flameCounter = getFlameCounterFromContact(contact); return ListView( children: [ Padding( @@ -84,11 +84,11 @@ class _ContactViewState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( - padding: EdgeInsets.only(right: 10), + padding: const EdgeInsets.only(right: 10), child: VerifiedShield(contact)), Text( getContactDisplayName(contact), - style: TextStyle(fontSize: 20), + style: const TextStyle(fontSize: 20), ), if (flameCounter > 0) FlameCounterWidget( @@ -99,18 +99,19 @@ class _ContactViewState extends State { ], ), if (getContactDisplayName(contact) != contact.username) - Center(child: Text("(${contact.username})")), - SizedBox(height: 50), + Center(child: Text('(${contact.username})')), + const SizedBox(height: 50), BetterListTile( icon: FontAwesomeIcons.pencil, text: context.lang.contactNickname, onTap: () async { - String? nickName = + final nickName = await showNicknameChangeDialog(context, contact); - if (context.mounted && nickName != null && nickName != "") { + if (context.mounted && nickName != null && nickName != '') { final update = ContactsCompanion(nickName: Value(nickName)); - twonlyDB.contactsDao.updateContact(contact.userId, update); + await twonlyDB.contactsDao + .updateContact(contact.userId, update); } }, ), @@ -131,7 +132,7 @@ class _ContactViewState extends State { iconSize: 16, text: context.lang.deleteAllContactMessages, onTap: () async { - bool block = await showAlertDialog( + final block = await showAlertDialog( context, context.lang.deleteAllContactMessages, context.lang.deleteAllContactMessagesBody( @@ -168,7 +169,7 @@ class _ContactViewState extends State { Future showNicknameChangeDialog( BuildContext context, Contact contact) { - final TextEditingController controller = + final controller = TextEditingController(text: getContactDisplayName(contact)); return showDialog( diff --git a/lib/src/views/contact/contact_verify.view.dart b/lib/src/views/contact/contact_verify.view.dart index b16da39..cfe9c65 100644 --- a/lib/src/views/contact/contact_verify.view.dart +++ b/lib/src/views/contact/contact_verify.view.dart @@ -1,20 +1,21 @@ import 'dart:async'; import 'dart:convert'; + import 'package:drift/drift.dart' hide Column; +import 'package:flutter/material.dart'; import 'package:flutter_zxing/flutter_zxing.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:image/image.dart' as imglib; import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; import 'package:lottie/lottie.dart'; import 'package:twonly/globals.dart'; -import 'package:twonly/src/services/signal/session.signal.dart'; -import 'package:twonly/src/views/components/format_long_string.dart'; -import 'package:flutter/material.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/services/signal/session.signal.dart'; import 'package:twonly/src/utils/misc.dart'; +import 'package:twonly/src/views/components/fingerprint_text.dart'; import 'package:twonly/src/views/contact/contact_verify_qr_scan.view.dart'; import 'package:url_launcher/url_launcher.dart'; -import 'package:image/image.dart' as imglib; class ContactVerifyView extends StatefulWidget { const ContactVerifyView(this.contact, {super.key}); @@ -24,6 +25,7 @@ class ContactVerifyView extends StatefulWidget { State createState() => _ContactVerifyViewState(); } +// ignore: constant_identifier_names enum ScanResult { None, Success, Failed } class _ContactVerifyViewState extends State { @@ -46,20 +48,17 @@ class _ContactVerifyViewState extends State { super.dispose(); } - Future loadAsync() async { + Future loadAsync() async { _fingerprint = await generateSessionFingerPrint(widget.contact.userId); if (_fingerprint != null) { - final Encode result = zx.encodeBarcode( + final result = zx.encodeBarcode( contents: base64Encode( _fingerprint!.scannableFingerprint.fingerprints, ), params: EncodeParams( - format: Format.qrCode, width: 150, height: 150, - margin: 0, - eccLevel: EccLevel.low, ), ); if (result.isValid && result.data != null) { @@ -73,7 +72,7 @@ class _ContactVerifyViewState extends State { } } - Stream contact = twonlyDB.contactsDao + final contact = twonlyDB.contactsDao .getContactByUserId(widget.contact.userId) .watchSingleOrNull(); _contactSub = contact.listen((contact) { @@ -85,36 +84,36 @@ class _ContactVerifyViewState extends State { setState(() {}); } - Future openQrScanner() async { + Future openQrScanner() async { if (_fingerprint == null) return; - bool? isValid = await Navigator.push(context, MaterialPageRoute( + final isValid = await Navigator.push(context, MaterialPageRoute( builder: (context) { return ContactVerifyQrScanView( widget.contact, fingerprint: _fingerprint!, ); }, - )); + )) as bool?; if (isValid == null) { return; // user just returned... } if (isValid) { _scanResult = ScanResult.Success; - updateUserVerifyState(true); + await updateUserVerifyState(true); } else { _scanResult = ScanResult.Failed; - updateUserVerifyState(false); + await updateUserVerifyState(false); } setState(() {}); } - Future updateUserVerifyState(bool verified) async { + Future updateUserVerifyState(bool verified) async { final update = ContactsCompanion(verified: Value(verified)); await twonlyDB.contactsDao.updateContact(_contact.userId, update); } Widget get qrWidget => (_qrCodeImageBytes == null) - ? SizedBox( + ? const SizedBox( width: 150, height: 150, ) @@ -127,7 +126,7 @@ class _ContactVerifyViewState extends State { : 'assets/animations/failed.json', repeat: false, onLoaded: (p0) { - Future.delayed(Duration(seconds: 3), () { + Future.delayed(const Duration(seconds: 3), () { if (mounted) { setState(() { _scanResult = ScanResult.None; @@ -145,14 +144,14 @@ class _ContactVerifyViewState extends State { title: Text(context.lang.contactVerifyNumberTitle), ), body: (_fingerprint == null) - ? Center(child: CircularProgressIndicator()) + ? const Center(child: CircularProgressIndicator()) : ListView( children: [ Center( child: Padding( - padding: const EdgeInsets.all(20.0), + padding: const EdgeInsets.all(20), child: Container( - padding: EdgeInsets.all(25), + padding: const EdgeInsets.all(25), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Theme.of(context).colorScheme.primary, @@ -166,21 +165,22 @@ class _ContactVerifyViewState extends State { borderRadius: BorderRadius.circular(10), color: Colors.white, ), - padding: EdgeInsets.symmetric(vertical: 20), + padding: const EdgeInsets.symmetric(vertical: 20), child: Column( children: [ - (_scanResult == ScanResult.None) - ? qrWidget - : resultAnimation, - SizedBox(height: 10), + if (_scanResult == ScanResult.None) + qrWidget + else + resultAnimation, + const SizedBox(height: 10), SizedBox( width: 200, child: Text( (_scanResult == ScanResult.None) ? context .lang.contactVerifyNumberTapToScan - : "", - style: TextStyle( + : '', + style: const TextStyle( color: Colors.black, fontSize: 15, ), @@ -190,8 +190,8 @@ class _ContactVerifyViewState extends State { ], ), ), - SizedBox(height: 20), - FormattedStringWidget( + const SizedBox(height: 20), + FingerprintText( _fingerprint!.displayableFingerprint .getDisplayText(), ), @@ -215,10 +215,10 @@ class _ContactVerifyViewState extends State { child: GestureDetector( onTap: () { launchUrl(Uri.parse( - "https://twonly.eu/en/faq/security/verify-security-number.html")); + 'https://twonly.eu/en/faq/security/verify-security-number.html')); }, child: Text( - "Read more.", + 'Read more.', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, @@ -231,23 +231,24 @@ class _ContactVerifyViewState extends State { ), bottomNavigationBar: SafeArea( child: Padding( - padding: EdgeInsets.only(bottom: 60), + padding: const EdgeInsets.only(bottom: 60), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - (_contact.verified) - ? OutlinedButton.icon( - onPressed: () => updateUserVerifyState(false), - label: Text( - context.lang.contactVerifyNumberClearVerification), - ) - : FilledButton.icon( - icon: FaIcon(FontAwesomeIcons.shieldHeart), - onPressed: () => updateUserVerifyState(true), - label: Text( - context.lang.contactVerifyNumberMarkAsVerified, - ), - ) + if (_contact.verified) + OutlinedButton.icon( + onPressed: () => updateUserVerifyState(false), + label: + Text(context.lang.contactVerifyNumberClearVerification), + ) + else + FilledButton.icon( + icon: const FaIcon(FontAwesomeIcons.shieldHeart), + onPressed: () => updateUserVerifyState(true), + label: Text( + context.lang.contactVerifyNumberMarkAsVerified, + ), + ) ], ), ), diff --git a/lib/src/views/contact/contact_verify_qr_scan.view.dart b/lib/src/views/contact/contact_verify_qr_scan.view.dart index e939515..097e594 100644 --- a/lib/src/views/contact/contact_verify_qr_scan.view.dart +++ b/lib/src/views/contact/contact_verify_qr_scan.view.dart @@ -1,7 +1,6 @@ import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_zxing/flutter_zxing.dart'; import 'package:libsignal_protocol_dart/libsignal_protocol_dart.dart'; import 'package:twonly/src/database/twonly_database.dart'; @@ -9,7 +8,7 @@ import 'package:twonly/src/utils/log.dart'; class ContactVerifyQrScanView extends StatefulWidget { const ContactVerifyQrScanView(this.contact, - {super.key, required this.fingerprint}); + {required this.fingerprint, super.key}); final Fingerprint fingerprint; final Contact contact; @@ -24,16 +23,16 @@ class _ContactVerifyQrScanViewState extends State { return Scaffold( body: ReaderWidget( onScan: (result) async { - bool isValid = false; + var isValid = false; try { if (result.text != null) { - Uint8List otherFingerPrint = base64Decode(result.text!); + final otherFingerPrint = base64Decode(result.text!); isValid = widget.fingerprint.scannableFingerprint.compareTo( otherFingerPrint, ); } } catch (e) { - Log.error("$e"); + Log.error('$e'); } return Navigator.pop(context, isValid); }, diff --git a/lib/src/views/home.view.dart b/lib/src/views/home.view.dart index f7af20d..6d58b05 100644 --- a/lib/src/views/home.view.dart +++ b/lib/src/views/home.view.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'package:camera/camera.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:pie_menu/pie_menu.dart'; @@ -7,18 +8,17 @@ import 'package:screenshot/screenshot.dart'; import 'package:twonly/src/services/notifications/setup.notifications.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/camera/camera_preview_components/camera_preview.dart'; +import 'package:twonly/src/views/camera/camera_preview_controller_view.dart'; +import 'package:twonly/src/views/chats/chat_list.view.dart'; import 'package:twonly/src/views/components/user_context_menu.dart'; import 'package:twonly/src/views/memories/memories.view.dart'; -import 'camera/camera_preview_controller_view.dart'; -import 'chats/chat_list.view.dart'; -import 'package:flutter/material.dart'; -Function(int) globalUpdateOfHomeViewPageIndex = (a) {}; +void Function(int) globalUpdateOfHomeViewPageIndex = (a) {}; class HomeView extends StatefulWidget { const HomeView({ - super.key, required this.initialPage, + super.key, }); final int initialPage; @@ -27,7 +27,7 @@ class HomeView extends StatefulWidget { } class Shade extends StatelessWidget { - const Shade({super.key, required this.opacity}); + const Shade({required this.opacity, super.key}); final double opacity; @override @@ -46,12 +46,11 @@ class Shade extends StatelessWidget { class HomeViewState extends State { int activePageIdx = 0; - final PageController homeViewPageController = - PageController(keepPage: true, initialPage: 1); + final PageController homeViewPageController = PageController(initialPage: 1); - double buttonDiameter = 100.0; - double offsetRatio = 0.0; - double offsetFromOne = 0.0; + double buttonDiameter = 100; + double offsetRatio = 0; + double offsetFromOne = 0; Timer? disableCameraTimer; bool initCameraStarted = true; @@ -73,7 +72,7 @@ class HomeViewState extends State { selectCamera(selectedCameraDetails.cameraId, false, false); } if (offsetRatio == 1) { - disableCameraTimer = Timer(Duration(milliseconds: 500), () { + disableCameraTimer = Timer(const Duration(milliseconds: 500), () { cameraController?.dispose(); cameraController = null; selectedCameraDetails = SelectedCameraDetails(); @@ -109,7 +108,7 @@ class HomeViewState extends State { super.dispose(); } - Future selectCamera(int sCameraId, bool init, bool enableAudio) async { + Future selectCamera(int sCameraId, bool init, bool enableAudio) async { final opts = await initializeCameraController( selectedCameraDetails, sCameraId, init, enableAudio); if (opts != null) { @@ -120,14 +119,14 @@ class HomeViewState extends State { setState(() {}); } - Future toggleSelectedCamera() async { + Future toggleSelectedCamera() async { await cameraController?.dispose(); cameraController = null; - selectCamera((selectedCameraDetails.cameraId + 1) % 2, false, false); + await selectCamera((selectedCameraDetails.cameraId + 1) % 2, false, false); } - Future initAsync() async { - var notificationAppLaunchDetails = + Future initAsync() async { + final notificationAppLaunchDetails = await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails(); if (notificationAppLaunchDetails != null) { @@ -146,7 +145,7 @@ class HomeViewState extends State { onDoubleTap: offsetRatio == 0 ? toggleSelectedCamera : null, child: Stack( children: [ - HomeViewCameraPreview(), + const HomeViewCameraPreview(), Shade( opacity: offsetRatio, ), @@ -161,9 +160,9 @@ class HomeViewState extends State { }); }, children: [ - ChatListView(), + const ChatListView(), Container(), - MemoriesView(), + const MemoriesView(), ], ), ), @@ -176,7 +175,7 @@ class HomeViewState extends State { ? MediaQuery.sizeOf(context).height * 2 : 0, child: Opacity( - opacity: (1 - (offsetRatio * 4) % 1), + opacity: 1 - (offsetRatio * 4) % 1, child: CameraPreviewControllerView( selectCamera: selectCamera, isHomeView: true, @@ -193,18 +192,18 @@ class HomeViewState extends State { Theme.of(context).colorScheme.inverseSurface.withAlpha(150)), selectedIconTheme: IconThemeData( color: Theme.of(context).colorScheme.inverseSurface), - items: [ + items: const [ BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.solidComments), - label: "", + label: '', ), BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.camera), - label: "", + label: '', ), BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.photoFilm), - label: "", + label: '', ), ], onTap: (int index) { diff --git a/lib/src/views/memories/memories.view.dart b/lib/src/views/memories/memories.view.dart index 03fe6e3..fcf015a 100644 --- a/lib/src/views/memories/memories.view.dart +++ b/lib/src/views/memories/memories.view.dart @@ -1,11 +1,12 @@ import 'dart:async'; import 'dart:io'; -import 'package:intl/intl.dart'; -import 'package:twonly/src/services/api/media_upload.dart' as send; + import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/twonly_database.dart'; import 'package:twonly/src/model/memory_item.model.dart'; +import 'package:twonly/src/services/api/media_upload.dart' as send; import 'package:twonly/src/services/thumbnail.service.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/memories/memories_item_thumbnail.dart'; @@ -38,40 +39,40 @@ class MemoriesViewState extends State { } Future> loadMemoriesDirectory() async { - final directoryPath = await send.getMediaBaseFilePath("memories"); + final directoryPath = await send.getMediaBaseFilePath('memories'); final directory = Directory(directoryPath); - List items = []; - if (await directory.exists()) { + final items = []; + if (directory.existsSync()) { final files = directory.listSync(); - for (var file in files) { + for (final file in files) { if (file is File) { final fileName = file.uri.pathSegments.last; File? imagePath; File? videoPath; late File thumbnailFile; - if (fileName.contains(".thumbnail.")) { + if (fileName.contains('.thumbnail.')) { continue; } - if (fileName.contains(".png")) { + if (fileName.contains('.png')) { imagePath = file; thumbnailFile = file; // if (!await thumbnailFile.exists()) { // await createThumbnailsForImage(imagePath); // } - } else if (fileName.contains(".mp4")) { + } else if (fileName.contains('.mp4')) { videoPath = file; thumbnailFile = getThumbnailPath(videoPath); - if (!await thumbnailFile.exists()) { + if (!thumbnailFile.existsSync()) { await createThumbnailsForVideo(videoPath); } } else { break; } - final creationDate = await file.lastModified(); + final creationDate = file.lastModifiedSync(); items.add(MemoryItem( - id: int.parse(fileName.split(".")[0]), + id: int.parse(fileName.split('.')[0]), messages: [], date: creationDate, mirrorVideo: false, @@ -85,17 +86,16 @@ class MemoriesViewState extends State { return items; } - Future initAsync() async { - messageSub?.cancel(); - Stream> msgStream = - twonlyDB.messagesDao.getAllStoredMediaFiles(); + Future initAsync() async { + await messageSub?.cancel(); + final msgStream = twonlyDB.messagesDao.getAllStoredMediaFiles(); messageSub = msgStream.listen((msgs) async { - Map items = await MemoryItem.convertFromMessages(msgs); + final items = await MemoryItem.convertFromMessages(msgs); // Group items by month orderedByMonth = {}; months = []; - String lastMonth = ""; + var lastMonth = ''; galleryItems = await loadMemoriesDirectory(); for (final item in galleryItems) { items.remove(item @@ -104,7 +104,7 @@ class MemoriesViewState extends State { galleryItems += items.values.toList(); galleryItems.sort((a, b) => b.date.compareTo(a.date)); for (var i = 0; i < galleryItems.length; i++) { - String month = DateFormat('MMMM yyyy').format(galleryItems[i].date); + final month = DateFormat('MMMM yyyy').format(galleryItems[i].date); if (lastMonth != month) { lastMonth = month; months.add(month); @@ -120,7 +120,7 @@ class MemoriesViewState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: Text('Memories')), + appBar: AppBar(title: const Text('Memories')), body: Scrollbar( child: (galleryItems.isEmpty) ? Center( @@ -129,26 +129,26 @@ class MemoriesViewState extends State { textAlign: TextAlign.center, )) : ListView.builder( - itemCount: (months.length * 2), + itemCount: months.length * 2, itemBuilder: (context, mIndex) { - if (mIndex % 2 == 0) { + if (mIndex.isEven) { return Padding( - padding: const EdgeInsets.all(8.0), + padding: const EdgeInsets.all(8), child: Text(months[(mIndex / 2).toInt()]), ); } - int index = ((mIndex - 1) / 2).toInt(); + final index = ((mIndex - 1) / 2).toInt(); return GridView.builder( shrinkWrap: true, physics: const ClampingScrollPhysics(), - scrollDirection: Axis.vertical, - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, childAspectRatio: 9 / 16, ), itemCount: orderedByMonth[months[index]]!.length, itemBuilder: (context, gIndex) { - int gaIndex = orderedByMonth[months[index]]![gIndex]; + final gaIndex = orderedByMonth[months[index]]![gIndex]; return MemoriesItemThumbnail( galleryItem: galleryItems[gaIndex], onTap: () { @@ -163,7 +163,7 @@ class MemoriesViewState extends State { ); } - void open(BuildContext context, final int index) async { + Future open(BuildContext context, int index) async { await Navigator.push( context, MaterialPageRoute( @@ -174,6 +174,6 @@ class MemoriesViewState extends State { ), ), ); - initAsync(); + await initAsync(); } } diff --git a/lib/src/views/memories/memories_item_thumbnail.dart b/lib/src/views/memories/memories_item_thumbnail.dart index 9c8f0ea..efcd0f6 100644 --- a/lib/src/views/memories/memories_item_thumbnail.dart +++ b/lib/src/views/memories/memories_item_thumbnail.dart @@ -4,9 +4,9 @@ import 'package:twonly/src/model/memory_item.model.dart'; class MemoriesItemThumbnail extends StatefulWidget { const MemoriesItemThumbnail({ - super.key, required this.galleryItem, required this.onTap, + super.key, }); final MemoryItem galleryItem; @@ -29,9 +29,9 @@ class _MemoriesItemThumbnailState extends State { String formatDuration(Duration duration) { String twoDigits(int n) => n.toString().padLeft(2, '0'); - String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); - String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60)); - return "$twoDigitMinutes:$twoDigitSeconds"; + final twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); + final twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60)); + return '$twoDigitMinutes:$twoDigitSeconds'; } @override @@ -44,7 +44,7 @@ class _MemoriesItemThumbnailState extends State { children: [ Image.file(widget.galleryItem.thumbnailPath), if (widget.galleryItem.videoPath != null) - Positioned.fill( + const Positioned.fill( child: Center( child: FaIcon(FontAwesomeIcons.circlePlay), ), diff --git a/lib/src/views/memories/memories_photo_slider.view.dart b/lib/src/views/memories/memories_photo_slider.view.dart index cc2b9c4..f811656 100644 --- a/lib/src/views/memories/memories_photo_slider.view.dart +++ b/lib/src/views/memories/memories_photo_slider.view.dart @@ -1,10 +1,11 @@ import 'package:drift/drift.dart'; -import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view_gallery.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/twonly_database.dart'; +import 'package:twonly/src/model/memory_item.model.dart'; import 'package:twonly/src/services/api/media_download.dart' as received; import 'package:twonly/src/services/api/media_upload.dart' as send; import 'package:twonly/src/utils/misc.dart'; @@ -12,17 +13,16 @@ import 'package:twonly/src/views/camera/share_image_editor_view.dart'; import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/views/components/media_view_sizing.dart'; import 'package:twonly/src/views/components/video_player_wrapper.dart'; -import 'package:twonly/src/model/memory_item.model.dart'; class MemoriesPhotoSliderView extends StatefulWidget { MemoriesPhotoSliderView({ + required this.galleryItems, super.key, this.loadingBuilder, this.backgroundDecoration, this.minScale, this.maxScale, this.initialIndex = 0, - required this.galleryItems, this.scrollDirection = Axis.horizontal, }) : pageController = PageController(initialPage: initialIndex); @@ -50,9 +50,9 @@ class _MemoriesPhotoSliderViewState extends State { }); } - Future deleteFile() async { - List messages = widget.galleryItems[currentIndex].messages; - bool confirmed = await showAlertDialog( + Future deleteFile() async { + final messages = widget.galleryItems[currentIndex].messages; + final confirmed = await showAlertDialog( context, context.lang.deleteImageTitle, context.lang.deleteImageBody, @@ -65,7 +65,7 @@ class _MemoriesPhotoSliderViewState extends State { for (final message in messages) { await twonlyDB.messagesDao.updateMessageByMessageId( message.messageId, - MessagesCompanion(mediaStored: Value(false)), + const MessagesCompanion(mediaStored: Value(false)), ); } @@ -78,7 +78,7 @@ class _MemoriesPhotoSliderViewState extends State { } } - Future exportFile() async { + Future exportFile() async { final item = widget.galleryItems[currentIndex]; try { @@ -113,12 +113,11 @@ class _MemoriesPhotoSliderViewState extends State { children: [ MediaViewSizing( bottomNavigation: Row( - crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ FilledButton.icon( - icon: FaIcon(FontAwesomeIcons.solidPaperPlane), - onPressed: () async { + icon: const FaIcon(FontAwesomeIcons.solidPaperPlane), + onPressed: () { Navigator.push( context, MaterialPageRoute( @@ -137,14 +136,15 @@ class _MemoriesPhotoSliderViewState extends State { }, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 30), + const EdgeInsets.symmetric( + vertical: 10, horizontal: 30), ), backgroundColor: WidgetStateProperty.all( Theme.of(context).colorScheme.primary, )), label: Text( context.lang.shareImagedEditorSendImage, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), ), ), ], @@ -165,10 +165,10 @@ class _MemoriesPhotoSliderViewState extends State { right: 5, child: PopupMenuButton( onSelected: (String result) { - if (result == "delete") { + if (result == 'delete') { deleteFile(); } - if (result == "export") { + if (result == 'export') { exportFile(); } }, @@ -199,7 +199,7 @@ class _MemoriesPhotoSliderViewState extends State { } PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) { - final MemoryItem item = widget.galleryItems[index]; + final item = widget.galleryItems[index]; return item.videoPath != null ? PhotoViewGalleryPageOptions.customChild( child: VideoPlayerWrapper( diff --git a/lib/src/views/onboarding/onboarding.view.dart b/lib/src/views/onboarding/onboarding.view.dart index 889fbfc..154977e 100644 --- a/lib/src/views/onboarding/onboarding.view.dart +++ b/lib/src/views/onboarding/onboarding.view.dart @@ -1,17 +1,17 @@ -import 'package:introduction_screen/introduction_screen.dart'; import 'package:flutter/material.dart'; +import 'package:introduction_screen/introduction_screen.dart'; import 'package:lottie/lottie.dart'; import 'package:twonly/src/utils/misc.dart'; class OnboardingView extends StatelessWidget { - const OnboardingView({super.key, required this.callbackOnSuccess}); - final Function callbackOnSuccess; + const OnboardingView({required this.callbackOnSuccess, super.key}); + final VoidCallback callbackOnSuccess; @override Widget build(BuildContext context) { return Scaffold( body: IntroductionScreen( - bodyPadding: EdgeInsets.only(top: 75, left: 10, right: 10), + bodyPadding: const EdgeInsets.only(top: 75, left: 10, right: 10), pages: [ PageViewModel( title: context.lang.onboardingWelcomeTitle, @@ -81,7 +81,7 @@ class OnboardingView extends StatelessWidget { Text( context.lang.onboardingBuyOneGetTwoBody, textAlign: TextAlign.center, - style: TextStyle(fontSize: 18), + style: const TextStyle(fontSize: 18), ), ], ), @@ -98,15 +98,12 @@ class OnboardingView extends StatelessWidget { Text( context.lang.onboardingGetStartedBody, textAlign: TextAlign.center, - style: TextStyle(fontSize: 18), + style: const TextStyle(fontSize: 18), ), Padding( padding: const EdgeInsets.only(left: 50, right: 50, top: 20), child: FilledButton( - onPressed: () { - callbackOnSuccess(); - // On button pressed - }, + onPressed: callbackOnSuccess, child: Text(context.lang.onboardingTryForFree), ), ), @@ -122,22 +119,18 @@ class OnboardingView extends StatelessWidget { ), ), ], - showNextButton: true, - done: Text(""), + done: const Text(''), next: Text(context.lang.next), // done: RegisterView(callbackOnSuccess: callbackOnSuccess), - onDone: () { - callbackOnSuccess(); - // On button pressed - }, + onDone: callbackOnSuccess, dotsDecorator: DotsDecorator( - size: const Size.square(8.0), - activeSize: const Size(20.0, 10.0), + size: const Size.square(8), + activeSize: const Size(20, 10), activeColor: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.secondary, - spacing: const EdgeInsets.symmetric(horizontal: 3.0), + spacing: const EdgeInsets.symmetric(horizontal: 3), activeShape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)), + RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)), ), ), ); diff --git a/lib/src/views/onboarding/recover.view.dart b/lib/src/views/onboarding/recover.view.dart index 35711cb..782f594 100644 --- a/lib/src/views/onboarding/recover.view.dart +++ b/lib/src/views/onboarding/recover.view.dart @@ -22,7 +22,7 @@ class _BackupRecoveryViewState extends State { final TextEditingController usernameCtrl = TextEditingController(); final TextEditingController passwordCtrl = TextEditingController(); - Future _recoverTwonlySafe() async { + Future _recoverTwonlySafe() async { setState(() { isLoading = true; }); @@ -89,7 +89,7 @@ class _BackupRecoveryViewState extends State { onChanged: (value) { setState(() {}); }, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), decoration: getInputDecoration( context, context.lang.registerUsernameDecoration, @@ -103,7 +103,7 @@ class _BackupRecoveryViewState extends State { onChanged: (value) { setState(() {}); }, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), obscureText: obscureText, decoration: getInputDecoration( context, diff --git a/lib/src/views/onboarding/register.view.dart b/lib/src/views/onboarding/register.view.dart index 97adc30..eb2bdeb 100644 --- a/lib/src/views/onboarding/register.view.dart +++ b/lib/src/views/onboarding/register.view.dart @@ -1,21 +1,24 @@ +// ignore_for_file: avoid_dynamic_calls + import 'dart:async'; import 'dart:convert'; -import 'package:flutter_secure_storage/flutter_secure_storage.dart'; -import 'package:twonly/globals.dart'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:twonly/globals.dart'; import 'package:twonly/src/constants/secure_storage_keys.dart'; +import 'package:twonly/src/model/json/userdata.dart'; import 'package:twonly/src/model/protobuf/api/websocket/error.pb.dart'; import 'package:twonly/src/services/signal/identity.signal.dart'; import 'package:twonly/src/utils/log.dart'; +import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/views/components/alert_dialog.dart'; -import 'package:twonly/src/model/json/userdata.dart'; -import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/onboarding/recover.view.dart'; class RegisterView extends StatefulWidget { - const RegisterView({super.key, required this.callbackOnSuccess}); + const RegisterView({required this.callbackOnSuccess, super.key}); final Function callbackOnSuccess; @override @@ -29,9 +32,9 @@ class _RegisterViewState extends State { bool _isTryingToRegister = false; bool _isValidUserName = false; - Future createNewUser({bool isDemoAccount = false}) async { - String username = (isDemoAccount) ? "" : usernameController.text; - String inviteCode = inviteCodeController.text; + Future createNewUser({bool isDemoAccount = false}) async { + final username = isDemoAccount ? '' : usernameController.text; + final inviteCode = inviteCodeController.text; setState(() { _isTryingToRegister = true; @@ -39,24 +42,24 @@ class _RegisterViewState extends State { await createIfNotExistsSignalIdentity(); - int userId = 0; + var userId = 0; if (!isDemoAccount) { final res = await apiService.register(username, inviteCode); if (res.isSuccess) { - Log.info("Got user_id ${res.value} from server"); - userId = res.value.userid.toInt(); + Log.info('Got user_id ${res.value} from server'); + userId = res.value.userid.toInt() as int; } else { if (res.error == ErrorCode.UserIdAlreadyTaken) { - Log.error("User ID already token. Tying again."); + Log.error('User ID already token. Tying again.'); await deleteLocalUserData(); return createNewUser(); } if (mounted) { - showAlertDialog( + await showAlertDialog( context, - "Oh no!", - errorCodeToText(context, res.error), + 'Oh no!', + errorCodeToText(context, res.error as ErrorCode), ); } return; @@ -71,60 +74,60 @@ class _RegisterViewState extends State { userId: userId, username: username, displayName: username, - subscriptionPlan: "Preview", + subscriptionPlan: 'Preview', isDemoUser: isDemoAccount, ); - FlutterSecureStorage() + await const FlutterSecureStorage() .write(key: SecureStorageKeys.userData, value: jsonEncode(userData)); if (!isDemoAccount) { await apiService.authenticate(); } else { gIsDemoUser = true; - createFakeDemoData(); + await createFakeDemoData(); } widget.callbackOnSuccess(); } @override Widget build(BuildContext context) { - InputDecoration getInputDecoration(hintText) { + InputDecoration getInputDecoration(String hintText) { return InputDecoration(hintText: hintText, fillColor: Colors.grey[400]); } return Scaffold( appBar: AppBar( - title: Text(""), + title: const Text(''), ), body: Padding( - padding: EdgeInsets.all(10), + padding: const EdgeInsets.all(10), child: Padding( - padding: EdgeInsets.only(left: 10, right: 10), + padding: const EdgeInsets.only(left: 10, right: 10), child: ListView( children: [ const SizedBox(height: 50), Text( context.lang.registerTitle, textAlign: TextAlign.center, - style: TextStyle(fontSize: 30), + style: const TextStyle(fontSize: 30), ), Padding( - padding: EdgeInsets.symmetric(horizontal: 30), + padding: const EdgeInsets.symmetric(horizontal: 30), child: Text( context.lang.registerSlogan, textAlign: TextAlign.center, - style: TextStyle(fontSize: 12), + style: const TextStyle(fontSize: 12), ), ), const SizedBox(height: 60), Center( child: Padding( - padding: EdgeInsets.only(left: 10, right: 10), + padding: const EdgeInsets.only(left: 10, right: 10), child: Text( context.lang.registerUsernameSlogan, textAlign: TextAlign.center, - style: TextStyle(fontSize: 15), + style: const TextStyle(fontSize: 15), ), ), ), @@ -142,9 +145,9 @@ class _RegisterViewState extends State { }, inputFormatters: [ LengthLimitingTextInputFormatter(12), - FilteringTextInputFormatter.allow(RegExp(r'[a-z0-9A-Z]')), + FilteringTextInputFormatter.allow(RegExp('[a-z0-9A-Z]')), ], - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), decoration: getInputDecoration( context.lang.registerUsernameDecoration, ), @@ -156,7 +159,7 @@ class _RegisterViewState extends State { // child: Text( // context.lang.registerUsernameLimits, // textAlign: TextAlign.center, - // style: TextStyle(fontSize: 9), + // style: const TextStyle(fontSize: 9), // ), // ), // ), @@ -177,7 +180,7 @@ class _RegisterViewState extends State { Column(children: [ FilledButton.icon( icon: _isTryingToRegister - ? SizedBox( + ? const SizedBox( width: 18, height: 18, child: CircularProgressIndicator( @@ -185,11 +188,12 @@ class _RegisterViewState extends State { strokeWidth: 2, ), ) - : Icon(Icons.group), + : const Icon(Icons.group), onPressed: _isValidUserName ? createNewUser : null, style: ButtonStyle( padding: WidgetStateProperty.all( - EdgeInsets.symmetric(vertical: 10, horizontal: 30), + const EdgeInsets.symmetric( + vertical: 10, horizontal: 30), ), backgroundColor: _isTryingToRegister ? WidgetStateProperty.all( @@ -197,7 +201,7 @@ class _RegisterViewState extends State { : null), label: Text( context.lang.registerSubmitButton, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), ), ), const SizedBox(height: 10), @@ -208,13 +212,13 @@ class _RegisterViewState extends State { onPressed: () { createNewUser(isDemoAccount: true); }, - label: Text("Demo"), + label: const Text('Demo'), ), OutlinedButton.icon( onPressed: () { Navigator.push(context, MaterialPageRoute( builder: (context) { - return BackupRecoveryView(); + return const BackupRecoveryView(); }, )); }, diff --git a/lib/src/views/settings/account.view.dart b/lib/src/views/settings/account.view.dart index 7d95944..085be3d 100644 --- a/lib/src/views/settings/account.view.dart +++ b/lib/src/views/settings/account.view.dart @@ -1,13 +1,15 @@ +import 'dart:async'; + import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:restart_app/restart_app.dart'; -import 'package:flutter/material.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart'; -import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/views/settings/account/refund_credits.view.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; @@ -28,20 +30,20 @@ class _AccountViewState extends State { super.initState(); } - Future initAsync() async { + Future initAsync() async { final ballance = await loadPlanBalance(useCache: false); if (ballance == null || !mounted) return; - int ballanceInCents = ballance.transactions + var ballanceInCents = ballance.transactions .where((x) => - (x.transactionType != Response_TransactionTypes.ThanksForTesting || - kDebugMode)) + x.transactionType != Response_TransactionTypes.ThanksForTesting || + kDebugMode) .map((a) => a.depositCents.toInt()) .sum; if (ballanceInCents < 0) { ballanceInCents = 0; } - hasRemainingBallance = (ballanceInCents > 0); - Locale myLocale = Localizations.localeOf(context); + hasRemainingBallance = ballanceInCents > 0; + final myLocale = Localizations.localeOf(context); formattedBallance = NumberFormat.currency( locale: myLocale.toString(), symbol: 'โ‚ฌ', @@ -59,22 +61,22 @@ class _AccountViewState extends State { body: ListView( children: [ ListTile( - title: Text("Transfer account"), - subtitle: Text("Coming soon"), + title: const Text('Transfer account'), + subtitle: const Text('Coming soon'), onTap: () async { - showAlertDialog( + await showAlertDialog( context, - "Coming soon", - "This feature is not yet implemented!", + 'Coming soon', + 'This feature is not yet implemented!', ); }, ), - Divider(), + const Divider(), Container( alignment: Alignment.center, - padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20), - child: Text( - "Danger Zone", + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), + child: const Text( + 'Danger Zone', textAlign: TextAlign.center, style: TextStyle( fontSize: 20, @@ -86,19 +88,19 @@ class _AccountViewState extends State { ListTile( title: Text( context.lang.settingsAccountDeleteAccount, - style: TextStyle(color: Colors.red), + style: const TextStyle(color: Colors.red), ), subtitle: (formattedBallance == null) ? Text(context.lang.settingsAccountDeleteAccountNoInternet) - : (hasRemainingBallance) + : hasRemainingBallance ? Text(context.lang .settingsAccountDeleteAccountWithBallance( formattedBallance!)) : Text(context.lang.settingsAccountDeleteAccountNoBallance), - onLongPress: (kDebugMode) + onLongPress: kDebugMode ? () async { await deleteLocalUserData(); - Restart.restartApp( + await Restart.restartApp( notificationTitle: 'Account successfully deleted', notificationBody: 'Click here to open the app again', ); @@ -108,17 +110,17 @@ class _AccountViewState extends State { ? null : () async { if (hasRemainingBallance) { - bool? canGoNext = await Navigator.push(context, + final canGoNext = await Navigator.push(context, MaterialPageRoute(builder: (context) { return RefundCreditsView( formattedBalance: formattedBallance!, ); - })); - initAsync(); + })) as bool?; + unawaited(initAsync()); if (canGoNext == null || !canGoNext) return; } if (!context.mounted) return; - bool ok = await showAlertDialog( + final ok = await showAlertDialog( context, context.lang.settingsAccountDeleteModalTitle, context.lang.settingsAccountDeleteModalBody, @@ -128,9 +130,9 @@ class _AccountViewState extends State { if (res.isError) { if (!context.mounted) return; ScaffoldMessenger.of(context).showSnackBar( - SnackBar( + const SnackBar( content: Text( - "Could not delete the account. Please ensure you have a internet connection!", + 'Could not delete the account. Please ensure you have a internet connection!', ), duration: Duration(seconds: 3), ), @@ -138,7 +140,7 @@ class _AccountViewState extends State { return; } await deleteLocalUserData(); - Restart.restartApp( + await Restart.restartApp( notificationTitle: 'Account successfully deleted', notificationBody: 'Click here to open the app again', ); diff --git a/lib/src/views/settings/appearance.view.dart b/lib/src/views/settings/appearance.view.dart index 7c7843c..153b8f5 100644 --- a/lib/src/views/settings/appearance.view.dart +++ b/lib/src/views/settings/appearance.view.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import 'package:twonly/src/utils/storage.dart'; -import 'package:twonly/src/views/components/radio_button.dart'; import 'package:twonly/src/providers/settings.provider.dart'; import 'package:twonly/src/utils/misc.dart'; +import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/components/radio_button.dart'; class AppearanceView extends StatefulWidget { const AppearanceView({super.key}); @@ -21,7 +21,7 @@ class _AppearanceViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { final user = await getUser(); if (user == null) return; setState(() { @@ -29,9 +29,10 @@ class _AppearanceViewState extends State { }); } - void _showSelectThemeMode(BuildContext context) async { + Future _showSelectThemeMode(BuildContext context) async { ThemeMode? selectedValue = context.read().themeMode; + // ignore: inference_failure_on_function_invocation await showDialog( context: context, builder: (BuildContext context) { @@ -73,22 +74,23 @@ class _AppearanceViewState extends State { }, ); if (selectedValue != null && context.mounted) { - context.read().updateThemeMode(selectedValue); + await context + .read() + .updateThemeMode(selectedValue); } } - void toggleShowFeedbackIcon() async { + Future toggleShowFeedbackIcon() async { await updateUserdata((u) { u.showFeedbackShortcut = !u.showFeedbackShortcut; return u; }); - initAsync(); + await initAsync(); } @override Widget build(BuildContext context) { - ThemeMode? selectedTheme = - context.watch().themeMode; + final selectedTheme = context.watch().themeMode; return Scaffold( appBar: AppBar( title: Text(context.lang.settingsAppearance), @@ -97,8 +99,8 @@ class _AppearanceViewState extends State { children: [ ListTile( title: Text(context.lang.settingsAppearanceTheme), - subtitle: - Text(selectedTheme.name, style: TextStyle(color: Colors.grey)), + subtitle: Text(selectedTheme.name, + style: const TextStyle(color: Colors.grey)), onTap: () { _showSelectThemeMode(context); }, diff --git a/lib/src/views/settings/backup/backup.view.dart b/lib/src/views/settings/backup/backup.view.dart index a13c79a..f3d2f5e 100644 --- a/lib/src/views/settings/backup/backup.view.dart +++ b/lib/src/views/settings/backup/backup.view.dart @@ -8,7 +8,7 @@ import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/views/settings/backup/twonly_safe_backup.view.dart'; -Function() gUpdateBackupView = () {}; +void Function() gUpdateBackupView = () {}; class BackupView extends StatefulWidget { const BackupView({super.key}); @@ -18,7 +18,7 @@ class BackupView extends StatefulWidget { } BackupServer defaultBackupServer = BackupServer( - serverUrl: "Default", + serverUrl: 'Default', retentionDays: 180, maxBackupBytes: 2097152, ); @@ -30,8 +30,7 @@ class _BackupViewState extends State { int activePageIdx = 0; - final PageController pageController = - PageController(keepPage: true, initialPage: 0); + final PageController pageController = PageController(); @override void initState() { @@ -46,7 +45,7 @@ class _BackupViewState extends State { super.dispose(); } - Future initAsync() async { + Future initAsync() async { final user = await getUser(); twonlySafeBackup = user?.twonlySafeBackup; backupServer = defaultBackupServer; @@ -98,10 +97,10 @@ class _BackupViewState extends State { ...[ ( context.lang.backupServer, - (backupServer.serverUrl.contains("@")) - ? backupServer.serverUrl.split("@")[1] + (backupServer.serverUrl.contains('@')) + ? backupServer.serverUrl.split('@')[1] : backupServer.serverUrl - .replaceAll("https://", "") + .replaceAll('https://', '') ), ( context.lang.backupMaxBackupSize, @@ -109,7 +108,7 @@ class _BackupViewState extends State { ), ( context.lang.backupStorageRetention, - "${backupServer.retentionDays} Days" + '${backupServer.retentionDays} Days' ), ( context.lang.backupLastBackupDate, @@ -133,7 +132,8 @@ class _BackupViewState extends State { ), TableCell( child: Padding( - padding: EdgeInsets.symmetric(vertical: 4), + padding: + const EdgeInsets.symmetric(vertical: 4), child: Text( pair.$2, textAlign: TextAlign.right, @@ -145,9 +145,9 @@ class _BackupViewState extends State { }), ], ), - SizedBox(height: 10), + const SizedBox(height: 10), FilledButton( - onPressed: (isLoading) + onPressed: isLoading ? null : () async { setState(() { @@ -164,7 +164,7 @@ class _BackupViewState extends State { ), onTap: () async { if (twonlySafeBackup != null) { - bool disable = await showAlertDialog( + final disable = await showAlertDialog( context, context.lang.deleteBackupTitle, context.lang.deleteBackupBody); @@ -177,14 +177,14 @@ class _BackupViewState extends State { }); await Navigator.push(context, MaterialPageRoute(builder: (context) { - return TwonlyIdentityBackupView(); + return const TwonlyIdentityBackupView(); })); } - initAsync(); + await initAsync(); }, ), BackupOption( - title: "${context.lang.backupData} (Coming Soon)", + title: '${context.lang.backupData} (Coming Soon)', description: context.lang.backupDataDesc, autoBackupEnabled: false, onTap: null, @@ -199,12 +199,12 @@ class _BackupViewState extends State { selectedIconTheme: IconThemeData(color: Theme.of(context).colorScheme.inverseSurface), items: [ - BottomNavigationBarItem( + const BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.vault, size: 17), - label: "twonly Safe", + label: 'twonly Safe', ), BottomNavigationBarItem( - icon: FaIcon(FontAwesomeIcons.boxArchive, size: 17), + icon: const FaIcon(FontAwesomeIcons.boxArchive, size: 17), label: context.lang.backupData, ), ], @@ -226,43 +226,43 @@ class _BackupViewState extends State { } class BackupOption extends StatelessWidget { - final String title; - final String description; - final Widget? child; - final bool autoBackupEnabled; - final Function()? onTap; - const BackupOption({ - super.key, required this.title, required this.description, required this.autoBackupEnabled, required this.onTap, + super.key, this.child, }); + final String title; + final String description; + final Widget? child; + final bool autoBackupEnabled; + final void Function()? onTap; @override Widget build(BuildContext context) { return GestureDetector( - onTap: (autoBackupEnabled) ? null : onTap, + onTap: autoBackupEnabled ? null : onTap, child: Card( - margin: EdgeInsets.all(16.0), + margin: const EdgeInsets.all(16), child: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, - style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: + const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), - SizedBox(height: 8.0), + const SizedBox(height: 8), Text(description), - SizedBox(height: 8.0), - (child != null) ? child! : Container(), + const SizedBox(height: 8), + if (child != null) child! else Container(), Expanded(child: Container()), Center( - child: (autoBackupEnabled) + child: autoBackupEnabled ? OutlinedButton( onPressed: onTap, child: Text(context.lang.disable), diff --git a/lib/src/views/settings/backup/twonly_safe_backup.view.dart b/lib/src/views/settings/backup/twonly_safe_backup.view.dart index bdc3603..795d661 100644 --- a/lib/src/views/settings/backup/twonly_safe_backup.view.dart +++ b/lib/src/views/settings/backup/twonly_safe_backup.view.dart @@ -1,6 +1,6 @@ -import 'package:flutter/services.dart' show rootBundle; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart' show rootBundle; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:twonly/src/services/twonly_safe/common.twonly_safe.dart'; import 'package:twonly/src/utils/misc.dart'; @@ -21,13 +21,13 @@ class _TwonlyIdentityBackupViewState extends State { final TextEditingController passwordCtrl = TextEditingController(); final TextEditingController repeatedPasswordCtrl = TextEditingController(); - Future onPressedEnableTwonlySafe() async { + Future onPressedEnableTwonlySafe() async { setState(() { isLoading = true; }); if (!await isSecurePassword(passwordCtrl.text)) { if (!mounted) return; - bool ignore = await showAlertDialog( + final ignore = await showAlertDialog( context, context.lang.backupInsecurePassword, context.lang.backupInsecurePasswordDesc, @@ -48,7 +48,7 @@ class _TwonlyIdentityBackupViewState extends State { isLoading = true; }); - await Future.delayed(Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); await enableTwonlySafe(passwordCtrl.text); if (!mounted) return; @@ -63,23 +63,24 @@ class _TwonlyIdentityBackupViewState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("twonly Safe"), + title: const Text('twonly Safe'), actions: [ IconButton( onPressed: () { showAlertDialog( context, - "twonly Safe", + 'twonly Safe', context.lang.backupTwonlySafeLongDesc, ); }, - icon: FaIcon(FontAwesomeIcons.circleInfo), + icon: const FaIcon(FontAwesomeIcons.circleInfo), iconSize: 18, ) ], ), body: Padding( - padding: EdgeInsetsGeometry.symmetric(vertical: 40, horizontal: 40), + padding: + const EdgeInsetsGeometry.symmetric(vertical: 40, horizontal: 40), child: ListView( children: [ Text( @@ -94,7 +95,7 @@ class _TwonlyIdentityBackupViewState extends State { onChanged: (value) { setState(() {}); }, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), obscureText: obscureText, decoration: getInputDecoration( context, @@ -122,13 +123,13 @@ class _TwonlyIdentityBackupViewState extends State { ], ), Padding( - padding: EdgeInsetsGeometry.all(5), + padding: const EdgeInsetsGeometry.all(5), child: Text( context.lang.backupPasswordRequirement, style: TextStyle( fontSize: 13, - color: ((passwordCtrl.text.length < 8 && - passwordCtrl.text.isNotEmpty)) + color: (passwordCtrl.text.length < 8 && + passwordCtrl.text.isNotEmpty) ? Colors.red : Colors.transparent), ), @@ -139,7 +140,7 @@ class _TwonlyIdentityBackupViewState extends State { onChanged: (value) { setState(() {}); }, - style: TextStyle(fontSize: 17), + style: const TextStyle(fontSize: 17), obscureText: true, decoration: getInputDecoration( context, @@ -147,7 +148,7 @@ class _TwonlyIdentityBackupViewState extends State { ), ), Padding( - padding: EdgeInsetsGeometry.all(5), + padding: const EdgeInsetsGeometry.all(5), child: Text( context.lang.passwordRepeatedNotEqual, style: TextStyle( @@ -158,18 +159,18 @@ class _TwonlyIdentityBackupViewState extends State { : Colors.transparent), ), ), - SizedBox(height: 10), + const SizedBox(height: 10), Center( child: OutlinedButton( onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { - return TwonlySafeServerView(); + return const TwonlySafeServerView(); })); }, child: Text(context.lang.backupExpertSettings), ), ), - SizedBox(height: 10), + const SizedBox(height: 10), Center( child: FilledButton.icon( onPressed: (!isLoading && @@ -179,12 +180,12 @@ class _TwonlyIdentityBackupViewState extends State { ? onPressedEnableTwonlySafe : null, icon: isLoading - ? SizedBox( + ? const SizedBox( height: 12, width: 12, child: CircularProgressIndicator(strokeWidth: 1), ) - : Icon(Icons.lock_clock_rounded), + : const Icon(Icons.lock_clock_rounded), label: Text(context.lang.backupEnableBackup), )) ], @@ -195,14 +196,14 @@ class _TwonlyIdentityBackupViewState extends State { } Future isSecurePassword(String password) async { - String badPasswordsStr = + final badPasswordsStr = await rootBundle.loadString('assets/passwords/bad_passwords.txt'); - List badPasswords = badPasswordsStr.split("\n"); + final badPasswords = badPasswordsStr.split('\n'); if (badPasswords.contains(password)) { return false; } // Check if the password meets all criteria - return RegExp(r'[A-Z]').hasMatch(password) && - RegExp(r'[a-z]').hasMatch(password) && - RegExp(r'[0-9]').hasMatch(password); + return RegExp('[A-Z]').hasMatch(password) && + RegExp('[a-z]').hasMatch(password) && + RegExp('[0-9]').hasMatch(password); } diff --git a/lib/src/views/settings/backup/twonly_safe_server.view.dart b/lib/src/views/settings/backup/twonly_safe_server.view.dart index 2db1522..e2e3aa2 100644 --- a/lib/src/views/settings/backup/twonly_safe_server.view.dart +++ b/lib/src/views/settings/backup/twonly_safe_server.view.dart @@ -1,3 +1,5 @@ +// ignore_for_file: avoid_dynamic_calls + import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; @@ -21,17 +23,17 @@ class _TwonlySafeServerViewState extends State { @override void initState() { - _urlController.text = "https://"; + _urlController.text = 'https://'; super.initState(); initAsync(); } - Future initAsync() async { + Future initAsync() async { final user = await getUser(); if (user?.backupServer != null) { - var uri = Uri.parse(user!.backupServer!.serverUrl); + final uri = Uri.parse(user!.backupServer!.serverUrl); // remove user auth data - Uri serverUrl = Uri( + final serverUrl = Uri( scheme: uri.scheme, host: uri.host, port: uri.port, @@ -39,27 +41,27 @@ class _TwonlySafeServerViewState extends State { query: uri.query, ); _urlController.text = serverUrl.toString(); - _usernameController.text = serverUrl.userInfo.split(":")[0].toString(); + _usernameController.text = serverUrl.userInfo.split(':')[0]; } setState(() {}); } - Future checkAndUpdateBackupServer() async { - String serverUrl = _urlController.text; - if (!serverUrl.endsWith("/")) { - serverUrl += "/"; + Future checkAndUpdateBackupServer() async { + var serverUrl = _urlController.text; + if (!serverUrl.endsWith('/')) { + serverUrl += '/'; } - String username = _usernameController.text; - String password = _passwordController.text; + final username = _usernameController.text; + final password = _passwordController.text; if (username.isNotEmpty || password.isNotEmpty) { - serverUrl = serverUrl.replaceAll("https://", ""); - serverUrl = "https://$username@$password$serverUrl"; + serverUrl = serverUrl.replaceAll('https://', ''); + serverUrl = 'https://$username@$password$serverUrl'; } try { - final uri = Uri.parse("${serverUrl}config"); + final uri = Uri.parse('${serverUrl}config'); final response = await http.get( uri, headers: { @@ -73,8 +75,8 @@ class _TwonlySafeServerViewState extends State { final backupServer = BackupServer( serverUrl: serverUrl, - retentionDays: data["retentionDays"]!, - maxBackupBytes: data["maxBackupBytes"]!, + retentionDays: data['retentionDays']! as int, + maxBackupBytes: data['maxBackupBytes']! as int, ); await updateUserdata((user) { user.backupServer = backupServer; @@ -87,12 +89,12 @@ class _TwonlySafeServerViewState extends State { 'Got invalid status code ${response.statusCode} from server.'); } } catch (e) { - Log.error("$e"); + Log.error('$e'); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('$e'), - duration: Duration(seconds: 3), + duration: const Duration(seconds: 3), ), ); } @@ -103,10 +105,10 @@ class _TwonlySafeServerViewState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('twonly Safe Server'), + title: const Text('twonly Safe Server'), ), body: Padding( - padding: const EdgeInsets.all(40.0), + padding: const EdgeInsets.all(40), child: ListView( children: [ Text( @@ -118,47 +120,47 @@ class _TwonlySafeServerViewState extends State { controller: _urlController, onChanged: (value) { if (value.length < 8) { - value = ""; + value = ''; } - value = value.replaceAll("https://", ""); - value = value.replaceAll("http://", ""); - value = "https://$value"; + value = value.replaceAll('https://', ''); + value = value.replaceAll('http://', ''); + value = 'https://$value'; _urlController.text = value; setState(() {}); }, - decoration: InputDecoration( + decoration: const InputDecoration( labelText: 'Server URL', border: OutlineInputBorder(), ), ), - SizedBox(height: 16.0), + const SizedBox(height: 16), TextField( controller: _usernameController, - decoration: InputDecoration( + decoration: const InputDecoration( labelText: 'Username (optional)', border: OutlineInputBorder(), ), ), - SizedBox(height: 16.0), + const SizedBox(height: 16), TextField( controller: _passwordController, - decoration: InputDecoration( + decoration: const InputDecoration( labelText: 'Password (optional)', border: OutlineInputBorder(), ), obscureText: true, ), - SizedBox(height: 20.0), + const SizedBox(height: 20), Center( child: FilledButton.icon( onPressed: (_urlController.text.length > 8) ? checkAndUpdateBackupServer : null, - icon: FaIcon(FontAwesomeIcons.server), + icon: const FaIcon(FontAwesomeIcons.server), label: Text(context.lang.backupUseOwnServer), ), ), - SizedBox(height: 10.0), + const SizedBox(height: 10), Center( child: OutlinedButton( onPressed: () async { diff --git a/lib/src/views/settings/chat/chat_reactions.view.dart b/lib/src/views/settings/chat/chat_reactions.view.dart index b001e66..ce1acf1 100644 --- a/lib/src/views/settings/chat/chat_reactions.view.dart +++ b/lib/src/views/settings/chat/chat_reactions.view.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:twonly/src/views/components/animate_icon.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/components/animate_icon.dart'; class ChatReactionSelectionView extends StatefulWidget { const ChatReactionSelectionView({super.key}); @@ -20,8 +20,8 @@ class _ChatReactionSelectionView extends State { initAsync(); } - Future initAsync() async { - var user = await getUser(); + Future initAsync() async { + final user = await getUser(); if (user != null && user.preSelectedEmojies != null) { selectedEmojis = user.preSelectedEmojies!; } else { @@ -30,7 +30,7 @@ class _ChatReactionSelectionView extends State { setState(() {}); } - void _onEmojiSelected(String emoji) async { + Future _onEmojiSelected(String emoji) async { if (selectedEmojis.contains(emoji)) { selectedEmojis.remove(emoji); } else { @@ -44,7 +44,7 @@ class _ChatReactionSelectionView extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(context.lang.settingsPreSelectedReactionsError), - duration: Duration(seconds: 3), + duration: const Duration(seconds: 3), ), ); } @@ -56,16 +56,15 @@ class _ChatReactionSelectionView extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('Select Reactions'), + title: const Text('Select Reactions'), ), body: GridView.builder( - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, // Number of columns - childAspectRatio: 1.0, // Aspect ratio of each item ), itemCount: EmojiAnimation.animatedIcons.keys.length, itemBuilder: (context, index) { - String emoji = EmojiAnimation.animatedIcons.keys.elementAt(index); + final emoji = EmojiAnimation.animatedIcons.keys.elementAt(index); return GestureDetector( onTap: () { _onEmojiSelected(emoji); @@ -80,7 +79,6 @@ class _ChatReactionSelectionView extends State { height: 40, child: EmojiAnimation( emoji: emoji, - repeat: true, // repeat: selectedEmojis.contains(emoji), ), ), @@ -90,7 +88,7 @@ class _ChatReactionSelectionView extends State { }, ), floatingActionButton: Padding( - padding: const EdgeInsets.only(bottom: 30.0), + padding: const EdgeInsets.only(bottom: 30), child: FloatingActionButton( foregroundColor: Colors.white, onPressed: () async { @@ -102,7 +100,7 @@ class _ChatReactionSelectionView extends State { return user; }); }, - child: Icon(Icons.settings_backup_restore_rounded), + child: const Icon(Icons.settings_backup_restore_rounded), ), ), ); diff --git a/lib/src/views/settings/chat/chat_settings.view.dart b/lib/src/views/settings/chat/chat_settings.view.dart index 88ab939..f37b2ed 100644 --- a/lib/src/views/settings/chat/chat_settings.view.dart +++ b/lib/src/views/settings/chat/chat_settings.view.dart @@ -28,7 +28,7 @@ class _ChatSettingsViewState extends State { onTap: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { - return ChatReactionSelectionView(); + return const ChatReactionSelectionView(); })); }, ), diff --git a/lib/src/views/settings/data_and_storage.view.dart b/lib/src/views/settings/data_and_storage.view.dart index a381130..9373640 100644 --- a/lib/src/views/settings/data_and_storage.view.dart +++ b/lib/src/views/settings/data_and_storage.view.dart @@ -1,8 +1,8 @@ import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/material.dart'; import 'package:twonly/src/services/api/media_download.dart'; -import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/utils/misc.dart'; +import 'package:twonly/src/utils/storage.dart'; class DataAndStorageView extends StatefulWidget { const DataAndStorageView({super.key}); @@ -21,7 +21,7 @@ class _DataAndStorageViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { final user = await getUser(); if (user == null) return; setState(() { @@ -31,8 +31,9 @@ class _DataAndStorageViewState extends State { }); } - void showAutoDownloadOptions( + Future showAutoDownloadOptions( BuildContext context, ConnectivityResult connectionMode) async { + // ignore: inference_failure_on_function_invocation await showDialog( context: context, builder: (BuildContext context) { @@ -47,12 +48,12 @@ class _DataAndStorageViewState extends State { ); } - void toggleStoreInGallery() async { + Future toggleStoreInGallery() async { await updateUserdata((u) { u.storeMediaFilesInGallery = !storeMediaFilesInGallery; return u; }); - initAsync(); + await initAsync(); } @override @@ -72,18 +73,18 @@ class _DataAndStorageViewState extends State { onChanged: (a) => toggleStoreInGallery(), ), ), - Divider(), + const Divider(), ListTile( title: Text( context.lang.settingsStorageDataMediaAutoDownload, - style: TextStyle(fontSize: 13), + style: const TextStyle(fontSize: 13), ), ), ListTile( title: Text(context.lang.settingsStorageDataAutoDownMobile), subtitle: Text( - autoDownloadOptions[ConnectivityResult.mobile.name]!.join(", "), - style: TextStyle(color: Colors.grey), + autoDownloadOptions[ConnectivityResult.mobile.name]!.join(', '), + style: const TextStyle(color: Colors.grey), ), onTap: () { showAutoDownloadOptions(context, ConnectivityResult.mobile); @@ -92,8 +93,8 @@ class _DataAndStorageViewState extends State { ListTile( title: Text(context.lang.settingsStorageDataAutoDownWifi), subtitle: Text( - autoDownloadOptions[ConnectivityResult.wifi.name]!.join(", "), - style: TextStyle(color: Colors.grey), + autoDownloadOptions[ConnectivityResult.wifi.name]!.join(', '), + style: const TextStyle(color: Colors.grey), ), onTap: () { showAutoDownloadOptions(context, ConnectivityResult.wifi); @@ -106,16 +107,15 @@ class _DataAndStorageViewState extends State { } class AutoDownloadOptionsDialog extends StatefulWidget { - final Map> autoDownloadOptions; - final ConnectivityResult connectionMode; - final Function() onUpdate; - const AutoDownloadOptionsDialog({ - super.key, required this.autoDownloadOptions, required this.connectionMode, required this.onUpdate, + super.key, }); + final Map> autoDownloadOptions; + final ConnectivityResult connectionMode; + final void Function() onUpdate; @override State createState() => @@ -139,7 +139,7 @@ class _AutoDownloadOptionsDialogState extends State { mainAxisSize: MainAxisSize.min, children: [ CheckboxListTile( - title: Text('Image'), + title: const Text('Image'), value: autoDownloadOptions[widget.connectionMode.name]! .contains(DownloadMediaTypes.image.name), onChanged: (bool? value) async { @@ -147,7 +147,7 @@ class _AutoDownloadOptionsDialogState extends State { }, ), CheckboxListTile( - title: Text('Video'), + title: const Text('Video'), value: autoDownloadOptions[widget.connectionMode.name]! .contains(DownloadMediaTypes.video.name), onChanged: (bool? value) async { diff --git a/lib/src/views/settings/help/contact_us.view.dart b/lib/src/views/settings/help/contact_us.view.dart index 65f97d1..f3984ec 100644 --- a/lib/src/views/settings/help/contact_us.view.dart +++ b/lib/src/views/settings/help/contact_us.view.dart @@ -1,5 +1,4 @@ import 'dart:convert'; -import 'dart:typed_data'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:fixnum/fixnum.dart'; import 'package:flutter/material.dart'; @@ -10,7 +9,7 @@ import 'package:twonly/globals.dart'; import 'package:twonly/src/constants/secure_storage_keys.dart'; import 'package:twonly/src/model/protobuf/api/http/http_requests.pb.dart'; import 'package:twonly/src/services/api/media_upload.dart' - show uint8ListToHex, createDownloadToken; + show createDownloadToken, uint8ListToHex; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/settings/help/contact_us/submit_message.view.dart'; @@ -33,11 +32,11 @@ class _ContactUsState extends State { Future uploadDebugLog() async { if (debugLogDownloadToken != null) return debugLogDownloadToken; - Uint8List downloadToken = createDownloadToken(); + final downloadToken = createDownloadToken(); - String debugLog = await loadLogFile(); + final debugLog = await loadLogFile(); - var messageOnSuccess = TextMessage() + final messageOnSuccess = TextMessage() ..body = [] ..userId = Int64(0); @@ -49,27 +48,27 @@ class _ContactUsState extends State { final uploadRequestBytes = uploadRequest.writeToBuffer(); - String? apiAuthTokenRaw = - await FlutterSecureStorage().read(key: SecureStorageKeys.apiAuthToken); + final apiAuthTokenRaw = await const FlutterSecureStorage() + .read(key: SecureStorageKeys.apiAuthToken); if (apiAuthTokenRaw == null) { - Log.error("api auth token not defined."); + Log.error('api auth token not defined.'); return null; } - String apiAuthToken = uint8ListToHex(base64Decode(apiAuthTokenRaw)); + final apiAuthToken = uint8ListToHex(base64Decode(apiAuthTokenRaw)); - String apiUrl = - "http${apiService.apiSecure}://${apiService.apiHost}/api/upload"; + final apiUrl = + 'http${apiService.apiSecure}://${apiService.apiHost}/api/upload'; - var requestMultipart = http.MultipartRequest( - "POST", + final requestMultipart = http.MultipartRequest( + 'POST', Uri.parse(apiUrl), ); requestMultipart.headers['x-twonly-auth-token'] = apiAuthToken; requestMultipart.files.add(http.MultipartFile.fromBytes( - "file", + 'file', uploadRequestBytes, - filename: "upload", + filename: 'upload', )); final response = await requestMultipart.send(); @@ -86,27 +85,27 @@ class _ContactUsState extends State { setState(() { isLoading = true; }); - String osVersion = ''; - String locale = context.lang.localeName; - DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); - String phoneModel = ""; - PackageInfo packageInfo = await PackageInfo.fromPlatform(); - String appVersion = packageInfo.version; - String packageName = packageInfo.packageName; - final String feedback = _controller.text; - String debugLogToken = ""; + var osVersion = ''; + final locale = context.lang.localeName; + final deviceInfo = DeviceInfoPlugin(); + var phoneModel = ''; + final packageInfo = await PackageInfo.fromPlatform(); + final appVersion = packageInfo.version; + final packageName = packageInfo.packageName; + final feedback = _controller.text; + var debugLogToken = ''; - if (!mounted) return ""; + if (!mounted) return ''; // Get device information if (Theme.of(context).platform == TargetPlatform.android) { - AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; - osVersion = "Android version: ${androidInfo.version.release}"; - phoneModel = " ${androidInfo.model} (${androidInfo.brand})"; + final androidInfo = await deviceInfo.androidInfo; + osVersion = 'Android version: ${androidInfo.version.release}'; + phoneModel = ' ${androidInfo.model} (${androidInfo.brand})'; } else if (Theme.of(context).platform == TargetPlatform.iOS) { - IosDeviceInfo iosInfo = await deviceInfo.iosInfo; - osVersion = "iOS version: ${iosInfo.utsname.release}"; - phoneModel = " ${iosInfo.name}"; + final iosInfo = await deviceInfo.iosInfo; + osVersion = 'iOS version: ${iosInfo.utsname.release}'; + phoneModel = ' ${iosInfo.name}'; } if (includeDebugLog) { @@ -114,11 +113,11 @@ class _ContactUsState extends State { final token = await uploadDebugLog(); if (token != null) { debugLogToken = - "Debug Log: https://api.twonly.eu/api/download/$token"; + 'Debug Log: https://api.twonly.eu/api/download/$token'; } } catch (e) { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Could not upload the debug log!')), + const SnackBar(content: Text('Could not upload the debug log!')), ); } } @@ -144,7 +143,7 @@ $debugLogToken @override Widget build(BuildContext context) { - final List _reasons = [ + final reasons = [ context.lang.contactUsReasonNotWorking, context.lang.contactUsReasonFeatureRequest, context.lang.contactUsReasonQuestion, @@ -156,50 +155,50 @@ $debugLogToken title: Text(context.lang.settingsHelpContactUs), ), body: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: ListView( children: [ Text(context.lang.contactUsMessageTitle), - SizedBox(height: 5), + const SizedBox(height: 5), TextField( controller: _controller, decoration: InputDecoration( hintText: context.lang.contactUsYourMessage, - border: OutlineInputBorder(), + border: const OutlineInputBorder(), ), minLines: 5, maxLines: 10, ), - SizedBox(height: 5), + const SizedBox(height: 5), Text( context.lang.contactUsMessage, textAlign: TextAlign.left, - style: TextStyle( + style: const TextStyle( fontSize: 10, ), ), - SizedBox(height: 20), + const SizedBox(height: 20), Text(context.lang.contactUsReason), - SizedBox(height: 5), + const SizedBox(height: 5), DropdownButton( hint: Text(context.lang.contactUsSelectOption), - underline: SizedBox.shrink(), + underline: const SizedBox.shrink(), value: _selectedReason, onChanged: (String? newValue) { setState(() { _selectedReason = newValue; }); }, - items: _reasons.map>((String reason) { + items: reasons.map>((String reason) { return DropdownMenuItem( value: reason, child: Text(reason), ); }).toList(), ), - SizedBox(height: 20), + const SizedBox(height: 20), Text(context.lang.contactUsEmojis), - SizedBox(height: 5), + const SizedBox(height: 5), FeedbackEmojiRow( selectedFeedback: _selectedFeedback, onFeedbackChanged: (int? newValue) { @@ -208,7 +207,7 @@ $debugLogToken }); }, ), - SizedBox(height: 20), + const SizedBox(height: 20), IncludeDebugLog( isChecked: includeDebugLog, onChanged: (value) { @@ -218,29 +217,29 @@ $debugLogToken }, ), Padding( - padding: EdgeInsets.symmetric(vertical: 40, horizontal: 40), + padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 40), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ GestureDetector( onTap: () { - launchUrl(Uri.parse("https://twonly.eu/en/faq/")); + launchUrl(Uri.parse('https://twonly.eu/en/faq/')); }, child: Text( context.lang.contactUsFaq, - style: TextStyle( + style: const TextStyle( color: Colors.blue, ), ), ), ElevatedButton( - onPressed: (isLoading) + onPressed: isLoading ? null : () async { final fullMessage = await _getFeedbackText(); if (!context.mounted) return; - bool? feedbackSend = await Navigator.push(context, + final feedbackSend = await Navigator.push(context, MaterialPageRoute(builder: (context) { return SubmitMessage( fullMessage: fullMessage, @@ -264,24 +263,24 @@ $debugLogToken } class IncludeDebugLog extends StatefulWidget { - final bool isChecked; - final Function(bool) onChanged; - const IncludeDebugLog({ - super.key, required this.isChecked, required this.onChanged, + super.key, }); + final bool isChecked; + final void Function(bool) onChanged; @override State createState() => _IncludeDebugLogState(); } class _IncludeDebugLogState extends State { - void _launchURL() async { + Future _launchURL() async { const url = 'https://twonly.eu/en/faq/troubleshooting/debug-log.html'; if (await launchUrl(Uri.parse(url))) { } else { + // ignore: only_throw_errors throw 'Could not launch $url'; } } @@ -289,7 +288,6 @@ class _IncludeDebugLogState extends State { @override Widget build(BuildContext context) { return Row( - mainAxisAlignment: MainAxisAlignment.start, children: [ Checkbox( value: widget.isChecked, @@ -301,12 +299,12 @@ class _IncludeDebugLogState extends State { }, ), Text(context.lang.contactUsIncludeLog), - SizedBox(width: 20), + const SizedBox(width: 20), GestureDetector( onTap: _launchURL, child: Text( context.lang.contactUsWhatsThat, - style: TextStyle( + style: const TextStyle( color: Colors.blue, ), ), @@ -317,19 +315,17 @@ class _IncludeDebugLogState extends State { } class FeedbackEmojiRow extends StatelessWidget { - final int? selectedFeedback; - final ValueChanged onFeedbackChanged; - const FeedbackEmojiRow({ - super.key, required this.selectedFeedback, required this.onFeedbackChanged, + super.key, }); + final int? selectedFeedback; + final ValueChanged onFeedbackChanged; @override Widget build(BuildContext context) { return Row( - mainAxisAlignment: MainAxisAlignment.start, children: [ _buildEmojiButton(5, Icons.sentiment_very_satisfied), _buildEmojiButton(4, Icons.sentiment_satisfied), @@ -341,7 +337,7 @@ class FeedbackEmojiRow extends StatelessWidget { } static String getEmoji(int? value) { - if (value == null) return ""; + if (value == null) return ''; switch (value) { case 5: return '๐Ÿ˜„'; @@ -359,7 +355,7 @@ class FeedbackEmojiRow extends StatelessWidget { } Widget _buildEmojiButton(int value, IconData icon) { - bool isSelected = selectedFeedback == value; + final isSelected = selectedFeedback == value; return GestureDetector( onTap: () { diff --git a/lib/src/views/settings/help/credits.view.dart b/lib/src/views/settings/help/credits.view.dart index 4e3dac7..d062807 100644 --- a/lib/src/views/settings/help/credits.view.dart +++ b/lib/src/views/settings/help/credits.view.dart @@ -49,7 +49,7 @@ class _CreditsViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { sticker = (await getStickerIndex()).where((x) => x.source != "").toList(); setState(() {}); } @@ -86,7 +86,7 @@ class _CreditsViewState extends State { title: Center( child: Text( "Animations", - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), )), ), UrlListTitle( @@ -141,7 +141,7 @@ class _CreditsViewState extends State { title: Center( child: Text( "Filters", - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), )), ), ...sticker.map( diff --git a/lib/src/views/settings/help/faq.view.dart b/lib/src/views/settings/help/faq.view.dart index 4f93f59..299eeca 100644 --- a/lib/src/views/settings/help/faq.view.dart +++ b/lib/src/views/settings/help/faq.view.dart @@ -1,3 +1,5 @@ +// ignore_for_file: avoid_dynamic_calls, inference_failure_on_untyped_parameter + import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; @@ -21,22 +23,22 @@ class _FaqViewState extends State { @override void initState() { super.initState(); - domain = "https://twonly.eu"; + domain = 'https://twonly.eu'; _fetchFAQData(); } Future _fetchFAQData() async { try { - final response = await http.get(Uri.parse("$domain/faq.json")); + final response = await http.get(Uri.parse('$domain/faq.json')); if (response.statusCode == 200) { setState(() { - _faqData = json.decode(utf8.decode(response.bodyBytes)); + _faqData = json.decode(utf8.decode(response.bodyBytes)) + as Map?; noInternet = false; }); } else { - Log.error("FAQ got ${response.statusCode}"); - // throw Exception('Failed to load FAQ data'); + Log.error('FAQ got ${response.statusCode}'); } } catch (e) { Log.error(e); @@ -53,8 +55,8 @@ class _FaqViewState extends State { appBar: AppBar( title: Text(context.lang.settingsHelpFAQ), ), - body: Center( - child: Text("Could not load the FAQ."), + body: const Center( + child: Text('Could not load the FAQ.'), ), ); } @@ -64,11 +66,11 @@ class _FaqViewState extends State { appBar: AppBar( title: Text(context.lang.settingsHelpFAQ), ), - body: Center(child: CircularProgressIndicator()), + body: const Center(child: CircularProgressIndicator()), ); } - final faq = _faqData![_locale ?? 'en']; + final faq = _faqData![_locale ?? 'en'] as Map; return Scaffold( appBar: AppBar( @@ -77,19 +79,19 @@ class _FaqViewState extends State { body: ListView.builder( itemCount: faq.keys.length, itemBuilder: (context, index) { - String category = faq.keys.elementAt(index); - var categoryData = faq[category]; + final category = faq.keys.elementAt(index); + final categoryData = faq[category]; return Card( child: ExpansionTile( - title: Text(categoryData['meta']['title']), - subtitle: Text(categoryData['meta']['desc']), + title: Text(categoryData['meta']['title'] as String), + subtitle: Text(categoryData['meta']['desc'] as String), children: categoryData['questions'].map((question) { return ListTile( - title: Text(question['title']), - onTap: () => _launchURL(question['path']), + title: Text(question['title'] as String), + onTap: () => _launchURL(question['path'] as String), ); - }).toList(), + }).toList() as List, ), ); }, @@ -97,11 +99,11 @@ class _FaqViewState extends State { ); } - void _launchURL(String path) async { + Future _launchURL(String path) async { try { - await launchUrl(Uri.parse("$domain$path")); + await launchUrl(Uri.parse('$domain$path')); } catch (e) { - Log.error("Could not launch $e"); + Log.error('Could not launch $e'); } } } diff --git a/lib/src/views/settings/help/help.view.dart b/lib/src/views/settings/help/help.view.dart index e5755b4..cda7089 100644 --- a/lib/src/views/settings/help/help.view.dart +++ b/lib/src/views/settings/help/help.view.dart @@ -23,7 +23,7 @@ class HelpView extends StatelessWidget { title: Text(context.lang.settingsHelpFAQ), onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { - return FaqView(); + return const FaqView(); })); }, ), @@ -31,7 +31,7 @@ class HelpView extends StatelessWidget { title: Text(context.lang.settingsHelpContactUs), onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { - return ContactUsView(); + return const ContactUsView(); })); }, ), @@ -39,7 +39,7 @@ class HelpView extends StatelessWidget { title: Text(context.lang.settingsResetTutorials), subtitle: Text(context.lang.settingsResetTutorialsDesc), onTap: () async { - updateUserdata((user) { + await updateUserdata((user) { user.tutorialDisplayed = []; return user; }); @@ -47,12 +47,12 @@ class HelpView extends StatelessWidget { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(context.lang.settingsResetTutorialsSuccess), - duration: Duration(seconds: 3), + duration: const Duration(seconds: 3), ), ); }, ), - Divider(), + const Divider(), FutureBuilder( future: PackageInfo.fromPlatform(), builder: (context, snap) { @@ -76,7 +76,7 @@ class HelpView extends StatelessWidget { title: Text(context.lang.settingsHelpCredits), onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) { - return CreditsView(); + return const CreditsView(); })); }, ), @@ -85,27 +85,29 @@ class HelpView extends StatelessWidget { onTap: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { - return DiagnosticsView(); + return const DiagnosticsView(); })); }, ), ListTile( title: Text(context.lang.settingsHelpImprint), onTap: () { - launchUrl(Uri.parse("https://twonly.eu/de/legal/")); + launchUrl(Uri.parse('https://twonly.eu/de/legal/')); }, - trailing: FaIcon(FontAwesomeIcons.arrowUpRightFromSquare, size: 15), + trailing: + const FaIcon(FontAwesomeIcons.arrowUpRightFromSquare, size: 15), ), ListTile( title: Text(context.lang.settingsHelpTerms), onTap: () { - launchUrl(Uri.parse("https://twonly.eu/de/legal/agb.html")); + launchUrl(Uri.parse('https://twonly.eu/de/legal/agb.html')); }, - trailing: FaIcon(FontAwesomeIcons.arrowUpRightFromSquare, size: 15), + trailing: + const FaIcon(FontAwesomeIcons.arrowUpRightFromSquare, size: 15), ), - ListTile( + const ListTile( title: Text( - "Copyright twonly", + 'Copyright twonly', style: TextStyle(color: Colors.grey, fontSize: 13), ), ), diff --git a/lib/src/views/settings/notification.view.dart b/lib/src/views/settings/notification.view.dart index 7f28b20..0106ae6 100644 --- a/lib/src/views/settings/notification.view.dart +++ b/lib/src/views/settings/notification.view.dart @@ -1,4 +1,5 @@ import 'dart:io'; + import 'package:fixnum/fixnum.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -7,11 +8,11 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/constants/secure_storage_keys.dart'; import 'package:twonly/src/model/protobuf/push_notification/push_notification.pbserver.dart'; -import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; -import 'package:twonly/src/views/components/alert_dialog.dart'; import 'package:twonly/src/services/fcm.service.dart'; +import 'package:twonly/src/services/notifications/pushkeys.notifications.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/components/alert_dialog.dart'; class NotificationView extends StatelessWidget { const NotificationView({super.key}); @@ -29,17 +30,17 @@ class NotificationView extends StatelessWidget { subtitle: Text(context.lang.settingsNotifyTroubleshootingDesc), onTap: () async { await initFCMAfterAuthenticated(); - String? storedToken = await FlutterSecureStorage() - .read(key: SecureStorageKeys.googleFcm); + final storedToken = const FlutterSecureStorage() + .read(key: SecureStorageKeys.googleFcm) as String?; await setupNotificationWithUsers(force: true); if (!context.mounted) return; if (storedToken == null) { final platform = Platform.isAndroid ? "Google's" : "Apple's"; - showAlertDialog( + await showAlertDialog( context, - "Problem detected", - "twonly is not able to register your app to $platform push server infrastructure. For Android that can happen when you do not have the Google Play Services installed. If you theses installed and want to help us to fix the issue please send us your debug log in Settings > Help > Debug log.", + 'Problem detected', + 'twonly is not able to register your app to $platform push server infrastructure. For Android that can happen when you do not have the Google Play Services installed. If you theses installed and want to help us to fix the issue please send us your debug log in Settings > Help > Debug log.', ); } else { final run = await showAlertDialog( diff --git a/lib/src/views/settings/privacy_view_block.users.dart b/lib/src/views/settings/privacy_view_block.users.dart index e493c64..db0b7e0 100644 --- a/lib/src/views/settings/privacy_view_block.users.dart +++ b/lib/src/views/settings/privacy_view_block.users.dart @@ -27,7 +27,7 @@ class _PrivacyViewBlockUsers extends State { loadAsync(); } - Future loadAsync() async { + Future loadAsync() async { setState(() {}); } @@ -93,7 +93,7 @@ class UserList extends StatelessWidget { const UserList(this.users, {super.key}); final List users; - Future block(BuildContext context, int userId, bool? value) async { + Future block(BuildContext context, int userId, bool? value) async { if (value != null) { final update = ContactsCompanion(blocked: Value(value)); await twonlyDB.contactsDao.updateContact(userId, update); diff --git a/lib/src/views/settings/profile/modify_avatar.view.dart b/lib/src/views/settings/profile/modify_avatar.view.dart index 55469e7..3d10b42 100644 --- a/lib/src/views/settings/profile/modify_avatar.view.dart +++ b/lib/src/views/settings/profile/modify_avatar.view.dart @@ -22,7 +22,7 @@ class _ModifyAvatarState extends State { super.initState(); } - Future updateUserAvatar(String json, String svg) async { + Future updateUserAvatar(String json, String svg) async { await updateUserdata((user) { user.avatarJson = json; user.avatarSvg = svg; diff --git a/lib/src/views/settings/profile/profile.view.dart b/lib/src/views/settings/profile/profile.view.dart index 24c5d5a..e8f7fe7 100644 --- a/lib/src/views/settings/profile/profile.view.dart +++ b/lib/src/views/settings/profile/profile.view.dart @@ -26,12 +26,12 @@ class _ProfileViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { user = await getUser(); setState(() {}); } - Future updateUserDisplayName(String displayName) async { + Future updateUserDisplayName(String displayName) async { await updateUserdata((user) { user.displayName = displayName; user.avatarCounter = user.avatarCounter + 1; diff --git a/lib/src/views/settings/settings_main.view.dart b/lib/src/views/settings/settings_main.view.dart index 5d89cd2..054a61f 100644 --- a/lib/src/views/settings/settings_main.view.dart +++ b/lib/src/views/settings/settings_main.view.dart @@ -1,19 +1,19 @@ -import 'package:font_awesome_flutter/font_awesome_flutter.dart'; -import 'package:twonly/src/views/components/better_list_title.dart'; -import 'package:twonly/src/views/components/initialsavatar.dart'; -import 'package:twonly/src/model/json/userdata.dart'; import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:twonly/src/model/json/userdata.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; +import 'package:twonly/src/views/components/better_list_title.dart'; +import 'package:twonly/src/views/components/initialsavatar.dart'; import 'package:twonly/src/views/settings/account.view.dart'; import 'package:twonly/src/views/settings/appearance.view.dart'; import 'package:twonly/src/views/settings/backup/backup.view.dart'; import 'package:twonly/src/views/settings/chat/chat_settings.view.dart'; import 'package:twonly/src/views/settings/data_and_storage.view.dart'; -import 'package:twonly/src/views/settings/notification.view.dart'; -import 'package:twonly/src/views/settings/profile/profile.view.dart'; import 'package:twonly/src/views/settings/help/help.view.dart'; +import 'package:twonly/src/views/settings/notification.view.dart'; import 'package:twonly/src/views/settings/privacy.view.dart'; +import 'package:twonly/src/views/settings/profile/profile.view.dart'; import 'package:twonly/src/views/settings/share_with_friends.view.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; @@ -33,7 +33,7 @@ class _SettingsMainViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { userData = await getUser(); setState(() {}); } @@ -55,13 +55,14 @@ class _SettingsMainViewState extends State { Expanded( child: GestureDetector( onTap: () async { - await Navigator.push(context, - MaterialPageRoute(builder: (context) { - return ProfileView(); - })); - initAsync(); + await Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const ProfileView(); + }, + )); + await initAsync(); }, - child: Container( + child: ColoredBox( color: context.color.surface.withAlpha(0), child: Row( children: [ @@ -75,12 +76,12 @@ class _SettingsMainViewState extends State { children: [ Text( userData!.displayName, - style: TextStyle(fontSize: 20), + style: const TextStyle(fontSize: 20), textAlign: TextAlign.left, ), Text( userData!.username, - style: TextStyle( + style: const TextStyle( fontSize: 14, ), textAlign: TextAlign.left, @@ -106,30 +107,33 @@ class _SettingsMainViewState extends State { icon: FontAwesomeIcons.user, text: context.lang.settingsAccount, onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return AccountView(); - })); + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const AccountView(); + }, + )); }, ), BetterListTile( icon: FontAwesomeIcons.shieldHeart, text: context.lang.settingsSubscription, onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return SubscriptionView(); - })); + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const SubscriptionView(); + }, + )); }, ), BetterListTile( icon: Icons.lock_clock_rounded, text: context.lang.settingsBackup, onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return BackupView(); - })); + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const BackupView(); + }, + )); }, ), const Divider(), @@ -137,51 +141,56 @@ class _SettingsMainViewState extends State { icon: FontAwesomeIcons.sun, text: context.lang.settingsAppearance, onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return AppearanceView(); - })); + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const AppearanceView(); + }, + )); }, ), BetterListTile( icon: FontAwesomeIcons.comment, text: context.lang.settingsChats, onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return ChatSettingsView(); - })); + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const ChatSettingsView(); + }, + )); }, ), BetterListTile( icon: FontAwesomeIcons.lock, text: context.lang.settingsPrivacy, onTap: () { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return PrivacyView(); - })); + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const PrivacyView(); + }, + )); }, ), BetterListTile( icon: FontAwesomeIcons.bell, text: context.lang.settingsNotification, - onTap: () async { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return NotificationView(); - })); + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const NotificationView(); + }, + )); }, ), BetterListTile( icon: FontAwesomeIcons.chartPie, iconSize: 15, text: context.lang.settingsStorageData, - onTap: () async { - Navigator.push(context, - MaterialPageRoute(builder: (context) { - return DataAndStorageView(); - })); + onTap: () { + Navigator.push(context, MaterialPageRoute( + builder: (context) { + return const DataAndStorageView(); + }, + )); }, ), const Divider(), @@ -202,7 +211,7 @@ class _SettingsMainViewState extends State { onTap: () { Navigator.push(context, MaterialPageRoute( builder: (context) { - return ShareWithFriendsView(); + return const ShareWithFriendsView(); }, )); }, diff --git a/lib/src/views/settings/share_with_friends.view.dart b/lib/src/views/settings/share_with_friends.view.dart index 9ffd07c..550cd88 100644 --- a/lib/src/views/settings/share_with_friends.view.dart +++ b/lib/src/views/settings/share_with_friends.view.dart @@ -43,7 +43,7 @@ class _ShareWithFriendsView extends State { children: [ TextField( controller: _controller, - style: TextStyle(fontSize: 14.0), + style: const TextStyle(fontSize: 14.0), decoration: InputDecoration(), ), SizedBox(height: 16.0), diff --git a/lib/src/views/settings/subscription/additional_users.view.dart b/lib/src/views/settings/subscription/additional_users.view.dart index d3d9ffb..5c45003 100644 --- a/lib/src/views/settings/subscription/additional_users.view.dart +++ b/lib/src/views/settings/subscription/additional_users.view.dart @@ -1,12 +1,11 @@ import 'dart:convert'; - import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; +import 'package:twonly/src/model/protobuf/api/websocket/error.pbserver.dart'; import 'package:twonly/src/model/protobuf/api/websocket/server_to_client.pb.dart'; -import 'package:twonly/src/services/api/utils.dart'; import 'package:twonly/src/utils/log.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; @@ -26,19 +25,17 @@ Future?> loadAdditionalUserInvites() async { final user = await getUser(); if (user != null && user.lastPlanBallance != null) { try { - List decoded = jsonDecode(user.additionalUserInvites!); - return decoded - .map((x) => Response_AddAccountsInvite.fromJson(x)) - .toList(); + final decoded = jsonDecode(user.additionalUserInvites!) as List; + return decoded.map(Response_AddAccountsInvite.fromJson).toList(); } catch (e) { - Log.error("from json: $e"); + Log.error('could not parse additional user json: $e'); } } return null; } class AdditionalUsersView extends StatefulWidget { - const AdditionalUsersView({super.key, required this.ballance}); + const AdditionalUsersView({required this.ballance, super.key}); final Response_PlanBallance? ballance; @@ -54,10 +51,10 @@ class _AdditionalUsersViewState extends State { void initState() { super.initState(); ballance = widget.ballance; - initAsync(false); + initAsync(force: false); } - Future initAsync(bool force) async { + Future initAsync({required bool force}) async { additionalInvites = await loadAdditionalUserInvites(); if (force) { ballance = await loadPlanBalance(); @@ -67,13 +64,13 @@ class _AdditionalUsersViewState extends State { @override Widget build(BuildContext context) { - List plusInvites = []; - List freeInvites = []; + var plusInvites = []; + var freeInvites = []; if (additionalInvites != null) { plusInvites = - additionalInvites!.where((x) => x.planId == "Plus").toList(); + additionalInvites!.where((x) => x.planId == 'Plus').toList(); freeInvites = - additionalInvites!.where((x) => x.planId == "Free").toList(); + additionalInvites!.where((x) => x.planId == 'Free').toList(); } return Scaffold( appBar: AppBar( @@ -85,50 +82,48 @@ class _AdditionalUsersViewState extends State { ListTile( title: Text( context.lang.additionalUsersList, - style: TextStyle(fontSize: 13), + style: const TextStyle(fontSize: 13), ), ), if (ballance != null) ...ballance!.additionalAccounts.map((e) => AdditionalAccount( account: e, refresh: () { - initAsync(true); + initAsync(force: true); }, )), if (plusInvites.isNotEmpty) ListTile( title: Text( context.lang.additionalUsersPlusTokens, - style: TextStyle(fontSize: 13), + style: const TextStyle(fontSize: 13), ), ), Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: GridView.count( crossAxisCount: 2, - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), childAspectRatio: 16 / 5, shrinkWrap: true, - children: - plusInvites.map((x) => AdditionalUserInvite(x)).toList(), + children: plusInvites.map(AdditionalUserInvite.new).toList(), ), ), if (freeInvites.isNotEmpty) ListTile( title: Text( context.lang.additionalUsersFreeTokens, - style: TextStyle(fontSize: 13), + style: const TextStyle(fontSize: 13), ), ), Padding( padding: const EdgeInsets.all(16.0), child: GridView.count( crossAxisCount: 2, - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), childAspectRatio: 16 / 5, shrinkWrap: true, - children: - freeInvites.map((x) => AdditionalUserInvite(x)).toList(), + children: freeInvites.map(AdditionalUserInvite.new).toList(), ), ), ], @@ -138,10 +133,13 @@ class _AdditionalUsersViewState extends State { } class AdditionalAccount extends StatefulWidget { - const AdditionalAccount( - {super.key, required this.account, required this.refresh}); + const AdditionalAccount({ + required this.account, + required this.refresh, + super.key, + }); - final Function() refresh; + final void Function() refresh; final Response_AdditionalAccount account; @override State createState() => _AdditionalAccountState(); @@ -157,7 +155,7 @@ class _AdditionalAccountState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { final contact = await twonlyDB.contactsDao .getContactByUserId(widget.account.userId.toInt()) .getSingleOrNull(); @@ -171,9 +169,9 @@ class _AdditionalAccountState extends State { Widget build(BuildContext context) { return Card( elevation: 4, - margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16), + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), child: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -182,24 +180,25 @@ class _AdditionalAccountState extends State { children: [ Text( username, - style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + style: const TextStyle( + fontSize: 20, fontWeight: FontWeight.bold), ), - SizedBox(height: 4), + const SizedBox(height: 4), Text( widget.account.planId, - style: TextStyle(fontSize: 16, color: Colors.grey), + style: const TextStyle(fontSize: 16, color: Colors.grey), ), ], ), IconButton( - icon: FaIcon(FontAwesomeIcons.userXmark, size: 16), + icon: const FaIcon(FontAwesomeIcons.userXmark, size: 16), onPressed: () async { - bool remove = await showAlertDialog( + final remove = await showAlertDialog( context, - "Remove this additional user", - "The additional user will automatically be downgraded to the preview plan after removal and you will receive a new invitation code to give to another person."); + 'Remove this additional user', + 'The additional user will automatically be downgraded to the preview plan after removal and you will receive a new invitation code to give to another person.'); if (remove) { - Result res = await apiService + final res = await apiService .removeAdditionalUser(widget.account.userId); if (!context.mounted) return; if (res.isSuccess) { @@ -207,7 +206,10 @@ class _AdditionalAccountState extends State { } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text(errorCodeToText(context, res.error))), + content: Text(errorCodeToText( + context, + res.error as ErrorCode, + ))), ); } } @@ -221,8 +223,8 @@ class _AdditionalAccountState extends State { } class AdditionalUserInvite extends StatefulWidget { - final Response_AddAccountsInvite invite; const AdditionalUserInvite(this.invite, {super.key}); + final Response_AddAccountsInvite invite; @override State createState() => _AdditionalUserInviteState(); } @@ -232,7 +234,7 @@ class _AdditionalUserInviteState extends State { Clipboard.setData(ClipboardData(text: widget.invite.inviteCode)); HapticFeedback.heavyImpact(); ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text("${widget.invite.inviteCode} copied.")), + SnackBar(content: Text('${widget.invite.inviteCode} copied.')), ); } @@ -243,11 +245,11 @@ class _AdditionalUserInviteState extends State { child: Card( elevation: 5, child: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: Center( child: Text( widget.invite.inviteCode.toUpperCase(), - style: TextStyle( + style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), diff --git a/lib/src/views/settings/subscription/checkout.view.dart b/lib/src/views/settings/subscription/checkout.view.dart index 522a091..ea70f93 100644 --- a/lib/src/views/settings/subscription/checkout.view.dart +++ b/lib/src/views/settings/subscription/checkout.view.dart @@ -4,11 +4,12 @@ import 'package:twonly/src/views/settings/subscription/select_payment.view.dart' import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; class CheckoutView extends StatefulWidget { - const CheckoutView( - {super.key, - required this.planId, - this.refund, - this.disableMonthlyOption}); + const CheckoutView({ + required this.planId, + super.key, + this.refund, + this.disableMonthlyOption, + }); final String planId; final int? refund; @@ -26,11 +27,11 @@ class _CheckoutViewState extends State { @override void initState() { super.initState(); - setCheckout(true); + setCheckout(init: true); } - void setCheckout(bool init) { - checkoutInCents = getPlanPrice(widget.planId, paidMonthly); + void setCheckout({bool init = false}) { + checkoutInCents = getPlanPrice(widget.planId, paidMonthly: paidMonthly); if (!init) { setState(() {}); } @@ -38,8 +39,8 @@ class _CheckoutViewState extends State { @override Widget build(BuildContext context) { - String totalPrice = - "${localePrizing(context, checkoutInCents)}/${(paidMonthly) ? context.lang.month : context.lang.year}"; + final totalPrice = + '${localePrizing(context, checkoutInCents)}/${paidMonthly ? context.lang.month : context.lang.year}'; return Scaffold( appBar: AppBar( title: Text(context.lang.checkoutOptions), @@ -55,18 +56,18 @@ class _CheckoutViewState extends State { if (widget.disableMonthlyOption == null || !widget.disableMonthlyOption!) Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: ListTile( title: Text(context.lang.checkoutPayYearly), onTap: () { paidMonthly = !paidMonthly; - setCheckout(false); + setCheckout(); }, trailing: Checkbox( value: !paidMonthly, onChanged: (a) { paidMonthly = !paidMonthly; - setCheckout(false); + setCheckout(); }, ), ), @@ -76,19 +77,19 @@ class _CheckoutViewState extends State { ), if (widget.refund != null) Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: Card( child: Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( context.lang.refund, - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), ), Text( - "+${localePrizing(context, widget.refund!)}", + '+${localePrizing(context, widget.refund!)}', textAlign: TextAlign.end, style: TextStyle(color: context.color.primary), ), @@ -98,16 +99,16 @@ class _CheckoutViewState extends State { ), ), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: Card( child: Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( context.lang.checkoutTotal, - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), ), Text( totalPrice, @@ -118,26 +119,26 @@ class _CheckoutViewState extends State { ), ), ), - SizedBox(height: 16), + const SizedBox(height: 16), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: FilledButton( onPressed: () async { - bool? success = await Navigator.push(context, + final success = await Navigator.push(context, MaterialPageRoute(builder: (context) { return SelectPaymentView( planId: widget.planId, payMonthly: paidMonthly, refund: widget.refund, ); - })); + })) as bool?; if (success != null && success && context.mounted) { Navigator.pop(context); } }, child: Text(context.lang.selectPaymentMethod)), ), - SizedBox(height: 20) + const SizedBox(height: 20) ], ), ), diff --git a/lib/src/views/settings/subscription/manage_subscription.view.dart b/lib/src/views/settings/subscription/manage_subscription.view.dart index 0f2e257..742b2e0 100644 --- a/lib/src/views/settings/subscription/manage_subscription.view.dart +++ b/lib/src/views/settings/subscription/manage_subscription.view.dart @@ -2,15 +2,18 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:twonly/globals.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'; -import 'package:twonly/src/services/api/utils.dart'; import 'package:twonly/src/providers/connection.provider.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; class ManageSubscriptionView extends StatefulWidget { - const ManageSubscriptionView( - {super.key, required this.ballance, required this.nextPayment}); + const ManageSubscriptionView({ + required this.ballance, + required this.nextPayment, + super.key, + }); final Response_PlanBallance? ballance; final DateTime? nextPayment; @@ -33,7 +36,7 @@ class _ManageSubscriptionViewState extends State { initAsync(true); } - Future initAsync(bool force) async { + Future initAsync(bool force) async { if (force) { ballance = await loadPlanBalance(useCache: false); if (ballance != null) { @@ -43,12 +46,13 @@ class _ManageSubscriptionViewState extends State { setState(() {}); } - Future toggleRenewalOption() async { - Result res = await apiService.updatePlanOptions(!autoRenewal!); + Future toggleRenewalOption() async { + final res = await apiService.updatePlanOptions(!autoRenewal!); if (res.isError) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorCodeToText(context, res.error))), + SnackBar( + content: Text(errorCodeToText(context, res.error as ErrorCode))), ); } } @@ -57,10 +61,10 @@ class _ManageSubscriptionViewState extends State { @override Widget build(BuildContext context) { - String planId = context.read().plan; - Locale myLocale = Localizations.localeOf(context); - bool? paidMonthly = ballance?.paymentPeriodDays == MONTHLY_PAYMENT_DAYS; - bool isAdditionalUser = planId == "Free" || planId == "Plus"; + final planId = context.read().plan; + final myLocale = Localizations.localeOf(context); + final paidMonthly = ballance?.paymentPeriodDays == MONTHLY_PAYMENT_DAYS; + final isAdditionalUser = planId == 'Free' || planId == 'Plus'; return Scaffold( appBar: AppBar( title: Text(context.lang.manageSubscription), @@ -68,11 +72,11 @@ class _ManageSubscriptionViewState extends State { body: ListView( children: [ PlanCard(planId: planId, paidMonthly: paidMonthly), - if (!isAdditionalUser) SizedBox(height: 20), + if (!isAdditionalUser) const SizedBox(height: 20), if (widget.nextPayment != null && !isAdditionalUser) ListTile( title: Text( - "${context.lang.nextPayment}: ${DateFormat.yMMMMd(myLocale.toString()).format(widget.nextPayment!)}", + '${context.lang.nextPayment}: ${DateFormat.yMMMMd(myLocale.toString()).format(widget.nextPayment!)}', ), ), if (autoRenewal != null && !isAdditionalUser) @@ -80,7 +84,7 @@ class _ManageSubscriptionViewState extends State { title: Text(context.lang.autoRenewal), subtitle: Text( context.lang.autoRenewalLongDesc, - style: TextStyle(fontSize: 12), + style: const TextStyle(fontSize: 12), ), onTap: toggleRenewalOption, trailing: Checkbox( diff --git a/lib/src/views/settings/subscription/select_payment.view.dart b/lib/src/views/settings/subscription/select_payment.view.dart index 96686df..834447a 100644 --- a/lib/src/views/settings/subscription/select_payment.view.dart +++ b/lib/src/views/settings/subscription/select_payment.view.dart @@ -1,6 +1,7 @@ import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:twonly/globals.dart'; +import 'package:twonly/src/model/protobuf/api/websocket/error.pbserver.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; import 'package:twonly/src/views/settings/subscription/subscription.view.dart'; @@ -45,7 +46,7 @@ class _SelectPaymentViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { final balance = await loadPlanBalance(); if (balance == null) { balanceInCents = 0; @@ -60,7 +61,8 @@ class _SelectPaymentViewState extends State { if (widget.valueInCents != null && widget.valueInCents! > 0) { checkoutInCents = widget.valueInCents!; } else if (widget.planId != null) { - checkoutInCents = getPlanPrice(widget.planId!, widget.payMonthly!); + checkoutInCents = + getPlanPrice(widget.planId!, paidMonthly: widget.payMonthly!); } else { /// Nothing to checkout for... Navigator.pop(context); @@ -73,11 +75,11 @@ class _SelectPaymentViewState extends State { @override Widget build(BuildContext context) { - String totalPrice = (widget.planId != null && widget.payMonthly != null) - ? "${localePrizing(context, checkoutInCents)}/${(widget.payMonthly!) ? context.lang.month : context.lang.year}" + final totalPrice = (widget.planId != null && widget.payMonthly != null) + ? '${localePrizing(context, checkoutInCents)}/${(widget.payMonthly!) ? context.lang.month : context.lang.year}' : localePrizing(context, checkoutInCents); - bool canPay = (paymentMethods == PaymentMethods.twonlyCredit && - (balanceInCents == null || balanceInCents! >= checkoutInCents)); + final canPay = paymentMethods == PaymentMethods.twonlyCredit && + (balanceInCents == null || balanceInCents! >= checkoutInCents); return Scaffold( appBar: AppBar( title: Text(context.lang.selectPaymentMethod), @@ -87,15 +89,15 @@ class _SelectPaymentViewState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Container( decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(16), ), - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Text( - context.lang.testPaymentMethode, + context.lang.testPaymentMethod, textAlign: TextAlign.center, ), ), @@ -104,10 +106,10 @@ class _SelectPaymentViewState extends State { child: ListView( children: [ Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Card( child: Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -117,8 +119,8 @@ class _SelectPaymentViewState extends State { Text(context.lang.twonlyCredit), if (balanceInCents != null) Text( - "${context.lang.currentBalance}: ${localePrizing(context, balanceInCents!)}", - style: TextStyle(fontSize: 10), + '${context.lang.currentBalance}: ${localePrizing(context, balanceInCents!)}', + style: const TextStyle(fontSize: 10), ) ], ), @@ -141,29 +143,29 @@ class _SelectPaymentViewState extends State { ), if (!canPay) ...[ Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Text( context.lang.notEnoughCredit, textAlign: TextAlign.center, - style: TextStyle(fontSize: 12), + style: const TextStyle(fontSize: 12), ), ), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: FilledButton( onPressed: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { - return VoucherView(); + return const VoucherView(); })); - initAsync(); + await initAsync(); }, child: Text(context.lang.chargeCredit), ), ), ], Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: ListTile( title: Text(context.lang.autoRenewal), subtitle: Text(context.lang.autoRenewalDesc), @@ -182,19 +184,19 @@ class _SelectPaymentViewState extends State { ), if (widget.refund != null) Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: Card( child: Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( context.lang.refund, - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), ), Text( - "+${localePrizing(context, widget.refund!)}", + '+${localePrizing(context, widget.refund!)}', textAlign: TextAlign.end, style: TextStyle(color: context.color.primary), ), @@ -204,16 +206,16 @@ class _SelectPaymentViewState extends State { ), ), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: Card( child: Padding( - padding: EdgeInsets.all(16), + padding: const EdgeInsets.all(16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( context.lang.checkoutTotal, - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), ), Text( totalPrice, @@ -224,11 +226,11 @@ class _SelectPaymentViewState extends State { ), ), ), - SizedBox(height: 16), + const SizedBox(height: 16), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 16), child: FilledButton( - onPressed: (canPay) + onPressed: canPay ? () async { final res = await apiService.switchToPayedPlan( widget.planId!, widget.payMonthly!, tryAutoRenewal); @@ -246,7 +248,7 @@ class _SelectPaymentViewState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - errorCodeToText(context, res.error), + errorCodeToText(context, res.error as ErrorCode), )), ); } @@ -260,23 +262,23 @@ class _SelectPaymentViewState extends State { children: [ TextButton( onPressed: () => launchUrl(Uri.parse( - "https://twonly.eu/de/legal/#revocation-policy")), - child: Text( - "Widerrufsbelehrung", + 'https://twonly.eu/de/legal/#revocation-policy')), + child: const Text( + 'Widerrufsbelehrung', style: TextStyle(color: Colors.blue), ), ), TextButton( onPressed: () => launchUrl( - Uri.parse("https://twonly.eu/de/legal/agb.html")), - child: Text( - "ABG", + Uri.parse('https://twonly.eu/de/legal/agb.html')), + child: const Text( + 'ABG', style: TextStyle(color: Colors.blue), ), ) ], ), - SizedBox(height: 20) + const SizedBox(height: 20) ], ), ), diff --git a/lib/src/views/settings/subscription/subscription.view.dart b/lib/src/views/settings/subscription/subscription.view.dart index 316dcda..895b363 100644 --- a/lib/src/views/settings/subscription/subscription.view.dart +++ b/lib/src/views/settings/subscription/subscription.view.dart @@ -1,3 +1,4 @@ +// ignore_for_file: inference_failure_on_instance_creation import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; @@ -6,7 +7,6 @@ import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:twonly/globals.dart'; import 'package:twonly/src/database/daos/contacts_dao.dart'; -import 'package:twonly/src/database/twonly_database.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'; import 'package:twonly/src/providers/connection.provider.dart'; @@ -22,12 +22,11 @@ import 'package:twonly/src/views/settings/subscription/transaction.view.dart'; import 'package:twonly/src/views/settings/subscription/voucher.view.dart'; String localePrizing(BuildContext context, int cents) { - Locale myLocale = Localizations.localeOf(context); - - double euros = cents / 100; + final myLocale = Localizations.localeOf(context); + final euros = cents / 100; if (euros == euros.toInt()) { - return "${euros.toInt()}โ‚ฌ"; + return '${euros.toInt()}โ‚ฌ'; } return NumberFormat.currency( @@ -40,7 +39,7 @@ String localePrizing(BuildContext context, int cents) { Future loadPlanBalance({bool useCache = true}) async { final ballance = await apiService.getPlanBallance(); if (ballance != null) { - updateUserdata((u) { + await updateUserdata((u) { u.lastPlanBallance = ballance.writeToJson(); return u; }); @@ -53,7 +52,7 @@ Future loadPlanBalance({bool useCache = true}) async { user.lastPlanBallance!, ); } catch (e) { - Log.error("from json: $e"); + Log.error('from json: $e'); } } return ballance; @@ -65,7 +64,7 @@ const int MONTHLY_PAYMENT_DAYS = 30; const int YEARLY_PAYMENT_DAYS = 365; int calculateRefund(Response_PlanBallance current) { - int refund = getPlanPrice("Pro", true); + var refund = getPlanPrice('Pro', paidMonthly: true); if (current.paymentPeriodDays == YEARLY_PAYMENT_DAYS) { final elapsedDays = DateTime.now() @@ -79,7 +78,7 @@ int calculateRefund(Response_PlanBallance current) { // => 5โ‚ฌ refund = (((YEARLY_PAYMENT_DAYS - elapsedDays) / YEARLY_PAYMENT_DAYS) * - getPlanPrice("Pro", false) / + getPlanPrice('Pro', paidMonthly: false) / 100) .ceil() * 100; @@ -117,11 +116,11 @@ class _SubscriptionViewState extends State { initAsync(); } - Future initAsync() async { + Future initAsync() async { ballance = await loadPlanBalance(); if (ballance != null && ballance!.hasAdditionalAccountOwnerId()) { final ownerId = ballance!.additionalAccountOwnerId.toInt(); - Contact? contact = await twonlyDB.contactsDao + final contact = await twonlyDB.contactsDao .getContactByUserId(ownerId) .getSingleOrNull(); if (contact != null) { @@ -149,44 +148,44 @@ class _SubscriptionViewState extends State { 'Content-Type': 'application/x-www-form-urlencoded', }, body: { - 'feedback': "[TESTER REQUEST] ${user.username} ${user.userId}", + 'feedback': '[TESTER REQUEST] ${user.username} ${user.userId}', }, ); if (!mounted) return; if (response.statusCode == 200) { // Handle successful response ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text("Your request has been submitted.")), + const SnackBar(content: Text('Your request has been submitted.')), ); await updateUserdata((u) { u.requestedTesterAccount = true; return u; }); - initAsync(); + await initAsync(); } else { // Handle error response ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Failed to submit your request.')), + const SnackBar(content: Text('Failed to submit your request.')), ); } } @override Widget build(BuildContext context) { - Locale myLocale = Localizations.localeOf(context); + final myLocale = Localizations.localeOf(context); String? formattedBalance; DateTime? nextPayment; - String currentPlan = context.read().plan; - bool isAdditionalUser = currentPlan == "Free" || currentPlan == "Plus"; + final currentPlan = context.read().plan; + final isAdditionalUser = currentPlan == 'Free' || currentPlan == 'Plus'; if (ballance != null) { - DateTime lastPaymentDateTime = DateTime.fromMillisecondsSinceEpoch( + final lastPaymentDateTime = DateTime.fromMillisecondsSinceEpoch( ballance!.lastPaymentDoneUnixTimestamp.toInt() * 1000); if (!isAdditionalUser) { nextPayment = lastPaymentDateTime .add(Duration(days: ballance!.paymentPeriodDays.toInt())); } - int ballanceInCents = + final ballanceInCents = ballance!.transactions.map((a) => a.depositCents.toInt()).sum; formattedBalance = NumberFormat.currency( locale: myLocale.toString(), @@ -195,8 +194,8 @@ class _SubscriptionViewState extends State { ).format(ballanceInCents / 100); } - int refund = 0; - if (currentPlan == "Pro" && ballance != null) { + var refund = 0; + if (currentPlan == 'Pro' && ballance != null) { refund = calculateRefund(ballance!); } @@ -210,7 +209,7 @@ class _SubscriptionViewState extends State { Center( child: Container( padding: const EdgeInsets.all(16), - margin: EdgeInsets.all(16), + margin: const EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.orangeAccent, borderRadius: BorderRadius.circular(15), @@ -219,20 +218,20 @@ class _SubscriptionViewState extends State { (widget.redirectError == ErrorCode.PlanLimitReached) ? context.lang.planLimitReached : context.lang.planNotAllowed, - style: TextStyle(color: Colors.black), + style: const TextStyle(color: Colors.black), textAlign: TextAlign.center, ), ), ), Padding( - padding: const EdgeInsets.all(32.0), + padding: const EdgeInsets.all(32), child: Center( child: Container( decoration: BoxDecoration( color: context.color.primary, borderRadius: BorderRadius.circular(15), ), - padding: EdgeInsets.symmetric(horizontal: 8, vertical: 3), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), child: Text( currentPlan, style: TextStyle( @@ -249,23 +248,23 @@ class _SubscriptionViewState extends State { child: Text( context.lang.partOfPaidPlanOf(additionalOwnerName!), textAlign: TextAlign.center, - style: TextStyle(color: Colors.orange), + style: const TextStyle(color: Colors.orange), ), ), - if (currentPlan != "Family" && currentPlan != "Pro") + if (currentPlan != 'Family' && currentPlan != 'Pro') Center( child: Padding( - padding: const EdgeInsets.all(18.0), + padding: const EdgeInsets.all(18), child: Text( context.lang.upgradeToPaidPlan, textAlign: TextAlign.center, - style: TextStyle(fontSize: 18), + style: const TextStyle(fontSize: 18), ), ), ), - if (currentPlan != "Tester" && !testerRequested) + if (currentPlan != 'Tester' && !testerRequested) PlanCard( - planId: "Tester", + planId: 'Tester', onTap: () async { bool activate = await showAlertDialog( context, @@ -273,79 +272,79 @@ class _SubscriptionViewState extends State { context.lang.testingAccountBody, ); if (activate) { - _submitTesterRequest(); + await _submitTesterRequest(); } }, ), - if (currentPlan != "Family" && currentPlan != "Pro") + if (currentPlan != 'Family' && currentPlan != 'Pro') PlanCard( - planId: "Pro", + planId: 'Pro', onTap: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { - return CheckoutView( - planId: "Pro", + return const CheckoutView( + planId: 'Pro', ); })); - initAsync(); + await initAsync(); }, ), - if (currentPlan != "Family") + if (currentPlan != 'Family') PlanCard( - planId: "Family", + planId: 'Family', refund: refund, onTap: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { return CheckoutView( - planId: "Family", + planId: 'Family', refund: (refund > 0) ? refund : null, - disableMonthlyOption: (currentPlan == "Pro" && + disableMonthlyOption: currentPlan == 'Pro' && ballance!.paymentPeriodDays.toInt() == - YEARLY_PAYMENT_DAYS), + YEARLY_PAYMENT_DAYS, ); })); - initAsync(); + await initAsync(); }, ), - if (currentPlan == "Preview" || currentPlan == "Free") ...[ - SizedBox(height: 10), + if (currentPlan == 'Preview' || currentPlan == 'Free') ...[ + const SizedBox(height: 10), Center( child: Padding( - padding: const EdgeInsets.all(14.0), + padding: const EdgeInsets.all(14), child: Text( context.lang.redeemUserInviteCode, textAlign: TextAlign.center, - style: TextStyle(fontSize: 18), + style: const TextStyle(fontSize: 18), ), ), ), - SizedBox(height: 10), - if (currentPlan != "Free") + const SizedBox(height: 10), + if (currentPlan != 'Free') PlanCard( - planId: "Free", + planId: 'Free', onTap: () async { - await redeemUserInviteCode(context, "Free"); - initAsync(); + await redeemUserInviteCode(context, 'Free'); + await initAsync(); }, ), PlanCard( - planId: "Plus", + planId: 'Plus', onTap: () async { - await redeemUserInviteCode(context, "Plus"); - initAsync(); + await redeemUserInviteCode(context, 'Plus'); + await initAsync(); }, ), ], - SizedBox(height: 10), - if (currentPlan != "Family") Divider(), - if (currentPlan != "Preview") + const SizedBox(height: 10), + if (currentPlan != 'Family') const Divider(), + if (currentPlan != 'Preview') BetterListTile( icon: FontAwesomeIcons.gears, text: context.lang.manageSubscription, subtitle: (nextPayment != null) ? Text( - "${context.lang.nextPayment}: ${DateFormat.yMMMMd(myLocale.toString()).format(nextPayment)}") + '${context.lang.nextPayment}: ${DateFormat.yMMMMd(myLocale.toString()).format(nextPayment)}') : null, onTap: () async { await Navigator.push(context, @@ -355,14 +354,14 @@ class _SubscriptionViewState extends State { nextPayment: nextPayment, ); })); - initAsync(); + await initAsync(); }, ), BetterListTile( icon: FontAwesomeIcons.moneyBillTransfer, text: context.lang.transactionHistory, subtitle: (formattedBalance != null) - ? Text("${context.lang.currentBalance}: $formattedBalance") + ? Text('${context.lang.currentBalance}: $formattedBalance') : null, onTap: () { if (formattedBalance == null) return; @@ -378,7 +377,7 @@ class _SubscriptionViewState extends State { BetterListTile( icon: FontAwesomeIcons.userPlus, text: context.lang.manageAdditionalUsers, - subtitle: (loaded) ? Text("${context.lang.open}: 3") : null, + subtitle: loaded ? Text('${context.lang.open}: 3') : null, onTap: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { @@ -386,7 +385,7 @@ class _SubscriptionViewState extends State { ballance: ballance, ); })); - initAsync(); + await initAsync(); }, ), BetterListTile( @@ -395,69 +394,65 @@ class _SubscriptionViewState extends State { onTap: () async { await Navigator.push(context, MaterialPageRoute(builder: (context) { - return VoucherView(); + return const VoucherView(); })); - initAsync(); + await initAsync(); }, ), - SizedBox(height: 30) + const SizedBox(height: 30) ], ), ); } } -int getPlanPrice(String planId, bool paidMonthly) { +int getPlanPrice(String planId, {required bool paidMonthly}) { switch (planId) { - case "Pro": - return (paidMonthly) ? 100 : 1000; - case "Family": - return (paidMonthly) ? 200 : 2000; + case 'Pro': + return paidMonthly ? 100 : 1000; + case 'Family': + return paidMonthly ? 200 : 2000; } return 0; } class PlanCard extends StatelessWidget { + const PlanCard({ + required this.planId, + super.key, + this.refund, + this.onTap, + this.paidMonthly, + }); final String planId; - final Function()? onTap; + final void Function()? onTap; final int? refund; final bool? paidMonthly; - const PlanCard( - {super.key, - required this.planId, - this.refund, - this.onTap, - this.paidMonthly}); - @override Widget build(BuildContext context) { - int yearlyPrice = getPlanPrice(planId, false); - int monthlyPrice = getPlanPrice(planId, true); - List features = []; + final yearlyPrice = getPlanPrice(planId, paidMonthly: false); + final monthlyPrice = getPlanPrice(planId, paidMonthly: true); + var features = []; switch (planId) { - case "Free": + case 'Free': features = [context.lang.freeFeature1]; - break; - case "Plus": + case 'Plus': features = [context.lang.plusFeature1]; - break; - case "Tester": - case "Pro": + case 'Tester': + case 'Pro': features = [ context.lang.proFeature1, context.lang.proFeature2, context.lang.proFeature3 ]; - break; - case "Family": + case 'Family': features = [ context.lang.familyFeature1, context.lang.familyFeature2, context.lang.familyFeature3 ]; - break; default: } @@ -473,38 +468,36 @@ class PlanCard extends StatelessWidget { child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), child: Column( - crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( - crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( planId, textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), - if (yearlyPrice != 0) SizedBox(height: 10), + if (yearlyPrice != 0) const SizedBox(height: 10), if (yearlyPrice != 0 && paidMonthly == null) Column( children: [ if (paidMonthly == null || paidMonthly!) Text( - "${localePrizing(context, yearlyPrice)}/${context.lang.year}", + '${localePrizing(context, yearlyPrice)}/${context.lang.year}', textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), if (paidMonthly == null || !paidMonthly!) Text( - "${localePrizing(context, monthlyPrice)}/${context.lang.month}", + '${localePrizing(context, monthlyPrice)}/${context.lang.month}', textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( fontSize: 16, color: Colors.grey, ), @@ -514,20 +507,20 @@ class PlanCard extends StatelessWidget { if (paidMonthly != null) Text( (paidMonthly!) - ? "${localePrizing(context, monthlyPrice)}/${context.lang.month}" - : "${localePrizing(context, yearlyPrice)}/${context.lang.year}", + ? '${localePrizing(context, monthlyPrice)}/${context.lang.month}' + : '${localePrizing(context, yearlyPrice)}/${context.lang.year}', textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), ], ), - SizedBox(height: 10), + const SizedBox(height: 10), ...features.map( (feature) => Padding( - padding: const EdgeInsets.symmetric(vertical: 2.0), + padding: const EdgeInsets.symmetric(vertical: 2), child: Text( feature, textAlign: TextAlign.center, @@ -552,7 +545,7 @@ class PlanCard extends StatelessWidget { padding: const EdgeInsets.only(top: 10), child: FilledButton.icon( onPressed: onTap, - label: (planId == "Free" || planId == "Plus") + label: (planId == 'Free' || planId == 'Plus') ? Text(context.lang.redeemUserInviteCodeTitle) : Text(context.lang.upgradeToPaidPlanButton(planId)), ), @@ -566,8 +559,9 @@ class PlanCard extends StatelessWidget { } } -Future redeemUserInviteCode(BuildContext context, String newPlan) async { - String inviteCode = ''; +Future redeemUserInviteCode(BuildContext context, String newPlan) async { + var inviteCode = ''; + // ignore: inference_failure_on_function_invocation await showDialog( context: context, builder: (BuildContext context) { @@ -580,19 +574,15 @@ Future redeemUserInviteCode(BuildContext context, String newPlan) async { mainAxisSize: MainAxisSize.min, children: [ Padding( - padding: const EdgeInsets.symmetric(vertical: 16.0), + padding: const EdgeInsets.symmetric(vertical: 16), child: TextField( - onChanged: (value) { - // Convert to uppercase - setState(() { - inviteCode = value.toUpperCase(); - }); - }, + onChanged: (value) => setState(() { + inviteCode = value.toUpperCase(); + }), decoration: InputDecoration( labelText: context.lang.registerTwonlyCodeLabel, - border: OutlineInputBorder(), + border: const OutlineInputBorder(), ), - // Set the text to be uppercase textCapitalization: TextCapitalization.characters, ), ), @@ -623,9 +613,12 @@ Future redeemUserInviteCode(BuildContext context, String newPlan) async { await apiService.connect(force: true); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorCodeToText(context, res.error))), + SnackBar( + content: Text( + errorCodeToText(context, res.error as ErrorCode))), ); } + if (!context.mounted) return; Navigator.of(context).pop(); }, child: Text(context.lang.ok), diff --git a/lib/src/views/settings/subscription/transaction.view.dart b/lib/src/views/settings/subscription/transaction.view.dart index c8c8b56..f3156c5 100644 --- a/lib/src/views/settings/subscription/transaction.view.dart +++ b/lib/src/views/settings/subscription/transaction.view.dart @@ -30,7 +30,7 @@ class _TransactionViewState extends State { color: context.color.primary, borderRadius: BorderRadius.circular(15), ), - padding: EdgeInsets.symmetric(horizontal: 8, vertical: 3), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), child: Text( widget.formattedBalance, style: TextStyle( @@ -85,20 +85,20 @@ class _TransactionCardState extends State { @override Widget build(BuildContext context) { final myLocale = Localizations.localeOf(context); - String formattedValue = NumberFormat.currency( + final formattedValue = NumberFormat.currency( locale: myLocale.toString(), symbol: 'โ‚ฌ', decimalDigits: 2, ).format(widget.transaction.depositCents.toInt() / 100); - DateTime timestamp = DateTime.fromMillisecondsSinceEpoch( + final timestamp = DateTime.fromMillisecondsSinceEpoch( widget.transaction.createdAtUnixTimestamp.toInt() * 1000); return Card( margin: const EdgeInsets.all(10), elevation: 5, child: Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -106,19 +106,18 @@ class _TransactionCardState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( - mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( typeToText(widget.transaction.transactionType), - style: TextStyle( + style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), Text( DateFormat.yMMMMd(myLocale.toString()).format(timestamp), - style: TextStyle( + style: const TextStyle( fontSize: 12, color: Colors.grey, ), diff --git a/lib/src/views/settings/subscription/voucher.view.dart b/lib/src/views/settings/subscription/voucher.view.dart index b8cca24..a255e33 100644 --- a/lib/src/views/settings/subscription/voucher.view.dart +++ b/lib/src/views/settings/subscription/voucher.view.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; import 'package:twonly/globals.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'; import 'package:twonly/src/utils/misc.dart'; @@ -21,14 +22,11 @@ class _VoucherViewState extends State { initAsync(); } - Future initAsync() async { - Response_Vouchers? resVouchers = await apiService.getVoucherList(); - if (resVouchers != null) { - setState(() { - vouchers = resVouchers.vouchers; - }); - return; - } + Future initAsync() async { + final resVouchers = await apiService.getVoucherList(); + setState(() { + vouchers = resVouchers?.vouchers ?? []; + }); } @override @@ -45,22 +43,22 @@ class _VoucherViewState extends State { title: Text(context.lang.redeemVoucher), onTap: () async { await redeemVoucher(context); - initAsync(); + await initAsync(); }, ), ListTile( title: Text(context.lang.createVoucher), onTap: () async { await showBuyVoucher(context); - initAsync(); + await initAsync(); }, ), - Divider(), + const Divider(), if (openVoucher.isNotEmpty) ListTile( title: Text( context.lang.openVouchers, - style: TextStyle(fontSize: 13), + style: const TextStyle(fontSize: 13), ), ), ...openVoucher.map((x) => VoucherCard(voucher: x)), @@ -68,7 +66,7 @@ class _VoucherViewState extends State { ListTile( title: Text( context.lang.redeemedVouchers, - style: TextStyle(fontSize: 13), + style: const TextStyle(fontSize: 13), ), ), ...redeemedVoucher.map((x) => VoucherCard(voucher: x)), @@ -79,10 +77,9 @@ class _VoucherViewState extends State { } class VoucherCard extends StatefulWidget { + const VoucherCard({required this.voucher, super.key}); final Response_Voucher voucher; - const VoucherCard({super.key, required this.voucher}); - @override State createState() => _VoucherCardState(); } @@ -93,17 +90,16 @@ class _VoucherCardState extends State { Clipboard.setData(ClipboardData(text: widget.voucher.voucherId)); HapticFeedback.heavyImpact(); ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text("${widget.voucher.voucherId} copied.")), + SnackBar(content: Text('${widget.voucher.voucherId} copied.')), ); } } @override Widget build(BuildContext context) { - bool isRedeemed = widget.voucher.redeemed || widget.voucher.requested; - - Locale myLocale = Localizations.localeOf(context); - String formattedValue = NumberFormat.currency( + final isRedeemed = widget.voucher.redeemed || widget.voucher.requested; + final myLocale = Localizations.localeOf(context); + final formattedValue = NumberFormat.currency( locale: myLocale.toString(), symbol: 'โ‚ฌ', decimalDigits: 2, @@ -127,8 +123,7 @@ class _VoucherCardState extends State { style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, - color: - (isRedeemed) ? Colors.grey : context.color.onSurface, + color: isRedeemed ? Colors.grey : context.color.onSurface, ), ), Text( @@ -136,8 +131,7 @@ class _VoucherCardState extends State { style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, - color: - (isRedeemed) ? Colors.grey : context.color.onSurface, + color: isRedeemed ? Colors.grey : context.color.onSurface, ), ), ], @@ -150,8 +144,10 @@ class _VoucherCardState extends State { } } -Future redeemVoucher(BuildContext context) async { - String voucherCode = ''; +Future redeemVoucher(BuildContext context) async { + var voucherCode = ''; + // + // ignore: inference_failure_on_function_invocation await showDialog( context: context, builder: (BuildContext context) { @@ -174,7 +170,7 @@ Future redeemVoucher(BuildContext context) async { }, decoration: InputDecoration( labelText: context.lang.enterVoucherCode, - border: OutlineInputBorder(), + border: const OutlineInputBorder(), ), // Set the text to be uppercase textCapitalization: TextCapitalization.characters, @@ -202,7 +198,14 @@ Future redeemVoucher(BuildContext context) async { ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorCodeToText(context, res.error))), + SnackBar( + content: Text( + errorCodeToText( + context, + res.error as ErrorCode, + ), + ), + ), ); } Navigator.of(context).pop(); @@ -215,9 +218,10 @@ Future redeemVoucher(BuildContext context) async { ); } -Future showBuyVoucher(BuildContext context) async { - int quantity = 1000; - +Future showBuyVoucher(BuildContext context) async { + var quantity = 1000; + // + // ignore: inference_failure_on_function_invocation await showDialog( context: context, builder: (BuildContext context) { @@ -230,12 +234,12 @@ Future showBuyVoucher(BuildContext context) async { mainAxisSize: MainAxisSize.min, children: [ Text(context.lang.createVoucherDesc), - SizedBox(height: 20), + const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( - icon: Icon(Icons.remove), + icon: const Icon(Icons.remove), onPressed: () { if (quantity > 1) { setState(() { @@ -255,10 +259,10 @@ Future showBuyVoucher(BuildContext context) async { symbol: 'โ‚ฌ', decimalDigits: 2, ).format(quantity / 100), - style: TextStyle(fontSize: 24), + style: const TextStyle(fontSize: 24), ), IconButton( - icon: Icon(Icons.add), + icon: const Icon(Icons.add), onPressed: () { setState(() { if (quantity >= 1000) { @@ -293,7 +297,14 @@ Future showBuyVoucher(BuildContext context) async { ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorCodeToText(context, res.error))), + SnackBar( + content: Text( + errorCodeToText( + context, + res.error as ErrorCode, + ), + ), + ), ); } Navigator.of(context).pop(); // Close the dialog diff --git a/lib/src/views/tutorial/show_tutorial.dart b/lib/src/views/tutorial/show_tutorial.dart index 4b84ae6..df79326 100644 --- a/lib/src/views/tutorial/show_tutorial.dart +++ b/lib/src/views/tutorial/show_tutorial.dart @@ -4,29 +4,21 @@ import 'package:tutorial_coach_mark/tutorial_coach_mark.dart'; import 'package:twonly/src/utils/misc.dart'; import 'package:twonly/src/utils/storage.dart'; -Future showTutorial(BuildContext context, List targets) async { - Completer completer = Completer(); +Future showTutorial( + BuildContext context, + List targets, +) async { + final completer = Completer(); TutorialCoachMark( targets: targets, colorShadow: context.color.primary, textSkip: context.lang.ok, alignSkip: Alignment.bottomCenter, - textStyleSkip: TextStyle( + textStyleSkip: const TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20, ), - onClickTarget: (target) { - print(target); - }, - onClickTargetWithTapPosition: (target, tapDetails) { - print("target: $target"); - print( - "clicked at position local: ${tapDetails.localPosition} - global: ${tapDetails.globalPosition}"); - }, - onClickOverlay: (target) { - print(target); - }, onSkip: () { completer.complete(); return true; @@ -58,10 +50,10 @@ Future checkIfTutorialAlreadyShown(String tutorialId) async { TargetFocus getTargetFocus( BuildContext context, GlobalKey key, String title, String body) { - RenderBox renderBox = key.currentContext?.findRenderObject() as RenderBox; - Offset position = renderBox.localToGlobal(Offset.zero); - double screenHeight = MediaQuery.of(context).size.height; - double centerY = screenHeight / 2; + final renderBox = key.currentContext!.findRenderObject()! as RenderBox; + final position = renderBox.localToGlobal(Offset.zero); + final screenHeight = MediaQuery.of(context).size.height; + final centerY = screenHeight / 2; double top = 0; double bottom = 0; @@ -90,18 +82,18 @@ TargetFocus getTargetFocus( Text( title, textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( fontWeight: FontWeight.bold, color: Colors.black, - fontSize: 20.0, + fontSize: 20, ), ), Padding( - padding: const EdgeInsets.only(top: 10.0), + padding: const EdgeInsets.only(top: 10), child: Text( body, textAlign: TextAlign.center, - style: TextStyle( + style: const TextStyle( color: Colors.black, fontSize: 16, ), diff --git a/lib/src/views/tutorial/tutorials.dart b/lib/src/views/tutorial/tutorials.dart index 0da9c24..3b3ba73 100644 --- a/lib/src/views/tutorial/tutorials.dart +++ b/lib/src/views/tutorial/tutorials.dart @@ -6,7 +6,7 @@ import 'package:twonly/src/views/tutorial/show_tutorial.dart'; final lockDisplayTutorial = Mutex(); -Future showChatListTutorialSearchOtherUsers( +Future showChatListTutorialSearchOtherUsers( BuildContext context, GlobalKey searchForOtherUsers, ) async { @@ -26,7 +26,7 @@ Future showChatListTutorialSearchOtherUsers( }); } -Future showChatListTutorialContextMenu( +Future showChatListTutorialContextMenu( BuildContext context, GlobalKey firstUserListItemKey, ) async { @@ -46,7 +46,7 @@ Future showChatListTutorialContextMenu( }); } -Future showVerifyShieldTutorial( +Future showVerifyShieldTutorial( BuildContext context, GlobalKey firstUserListItemKey, ) async { @@ -66,7 +66,7 @@ Future showVerifyShieldTutorial( }); } -Future showReopenMediaFilesTutorial( +Future showReopenMediaFilesTutorial( BuildContext context, GlobalKey firstUserListItemKey, ) async { diff --git a/pubspec.lock b/pubspec.lock index f7ea4d8..713e790 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1799,6 +1799,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.4" + very_good_analysis: + dependency: "direct dev" + description: + name: very_good_analysis + sha256: e479fbc0941009262343db308133e121bf8660c2c81d48dd8e952df7b7e1e382 + url: "https://pub.dev" + source: hosted + version: "9.0.0" video_compress: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 52bda49..86d55ef 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -81,6 +81,7 @@ dev_dependencies: flutter_lints: ^6.0.0 flutter_launcher_icons: ^0.14.1 drift_dev: ^2.25.2 + very_good_analysis: ^9.0.0 flutter_launcher_icons: android: true diff --git a/generate_proto.sh b/scripts/generate_proto.sh similarity index 83% rename from generate_proto.sh rename to scripts/generate_proto.sh index d3101f6..7fb971d 100755 --- a/generate_proto.sh +++ b/scripts/generate_proto.sh @@ -2,12 +2,21 @@ # Set the source directory +if [ ! -f "pubspec.yaml" ]; then + echo "Must be executed from the flutter main repo." + exit 1 +fi + +# Definitions for twonly Safe protoc --proto_path="./lib/src/model/protobuf/backup/" --dart_out="./lib/src/model/protobuf/backup/" "backup.proto" +# Definitions for the Push Notifications protoc --proto_path="./lib/src/model/protobuf/push_notification/" --dart_out="./lib/src/model/protobuf/push_notification/" "push_notification.proto" protoc --proto_path="./lib/src/model/protobuf/push_notification/" --swift_out="./ios/NotificationService/" "push_notification.proto" +# Definitions for the Server API + SRC_DIR="../twonly-server/twonly/src/" DST_DIR="$(pwd)/lib/src/model/protobuf/" @@ -21,10 +30,7 @@ cd "$SRC_DIR" || { exit 1 } -# Iterate over all .proto files in the source directory for proto_file in "api/"**/*.proto; do - # Check if the file exists to avoid errors if no .proto files are found - if [[ -f "$proto_file" ]]; then # Run the protoc command protoc --proto_path="." --dart_out="$DST_DIR" "$proto_file" @@ -34,7 +40,6 @@ for proto_file in "api/"**/*.proto; do fi done -# Change back to the original directory cd "$ORIGINAL_DIR" || { echo "Failed to change back to the original directory" exit 1