Compare commits
177 Commits
0.1.4
...
ai-bullshit
| Author | SHA1 | Date | |
|---|---|---|---|
| ff8e2fdd49 | |||
| 514b8859c7 | |||
| c18a7963bf | |||
| 255a194c25 | |||
| 6b7f8f2397 | |||
| 0ffd92b875 | |||
| 68fff3ebee | |||
| f6c6ed59f3 | |||
| f24eae8209 | |||
| 96f45aef6a | |||
| 5dc000341b | |||
| 6961ac7240 | |||
| c380c1a73d | |||
| 2bf81c60d6 | |||
| 2e472733d9 | |||
| d91b726b9d | |||
| 3bb4de24a7 | |||
| 22d13fcbe5 | |||
| cb653eddc2 | |||
| df2c61d8d7 | |||
| 97c59a85b6 | |||
| 155a3666ad | |||
| ce375c902c | |||
| 96b4fc8539 | |||
| e3e9157dd5 | |||
| 5aa28066d7 | |||
| 1638d70ef2 | |||
| 8c13d9e7e1 | |||
| 5dd829b6f6 | |||
| 2a238fa1bf | |||
| 3f54961ac6 | |||
| 045f2e8268 | |||
| 3eb33b2612 | |||
| f2d565fd3e | |||
| 7ab333280c | |||
| 45ee0acea5 | |||
| 7b6571f208 | |||
| 389d3f9e52 | |||
| 69a50f8fcd | |||
| 8839015249 | |||
| 478639e427 | |||
| dcbfd43896 | |||
| 7b2c102470 | |||
| 5310596cf6 | |||
| 65ff74622a | |||
| f48878f003 | |||
| c666bd46f3 | |||
| 421ca27758 | |||
| 8231062ca5 | |||
| 723555f634 | |||
| 3e05744a18 | |||
| 821ee46cef | |||
| dcddddea9b | |||
| 018151ad18 | |||
| 6f55251fb7 | |||
| 83772fb3ec | |||
| d5ee50a979 | |||
| 079c4178ec | |||
| 21bcacded8 | |||
| 3a272376c1 | |||
| ea6c094b4d | |||
| 91b87f6fa5 | |||
| a5952098a2 | |||
| 4f1149c8d8 | |||
| 56bf6ac063 | |||
| 1b9401673d | |||
| db92b261c0 | |||
| 42ad04093d | |||
| 9535847bf3 | |||
| b3c35ec6f5 | |||
| f5853f61c3 | |||
| 620cf53c65 | |||
| 411776b767 | |||
| 8cb3ed8784 | |||
| 4677e484d9 | |||
| 799ed820e3 | |||
| 3fd679e65d | |||
| 6b95deb7bf | |||
| 47c1f623f0 | |||
| 600aed40e7 | |||
| 22e8a5c09e | |||
| 252f6ec21e | |||
| 7e25bc3a8d | |||
| 7b0f6fe2a6 | |||
| 6d5b09ef81 | |||
| 268e0a8beb | |||
| 9e67ad0834 | |||
| 34ea8ef944 | |||
| 3d0c310575 | |||
| 602cf8f18b | |||
| 1b3581fcfd | |||
| 4b254d7d41 | |||
| d98dca83f1 | |||
| 9e6b079bf6 | |||
| d2aaac68e2 | |||
| ada9c13947 | |||
| cd4c1d6d76 | |||
| fab92d50d6 | |||
| 9e4521c3a0 | |||
| 70b552412c | |||
| a7307e7862 | |||
| 60a30b9422 | |||
| 93d81f1e9e | |||
| 5be101deec | |||
| 76dd1e2ce7 | |||
| 56683bea96 | |||
| 3dae1fe101 | |||
| c1e76e1c60 | |||
| c14ee45d53 | |||
| 9d4e3f50ea | |||
| 17b5c944ac | |||
| 5aa1f21183 | |||
| a916dc649c | |||
| 7e0b9d49ba | |||
| d525a1573c | |||
| 091a88dd45 | |||
| a3a970115a | |||
| e36c1ea0ca | |||
| f2437f67cb | |||
| 049bcfd2da | |||
| d5e24214ce | |||
| c94e128e64 | |||
| 0836816391 | |||
| be58949372 | |||
| 618388a719 | |||
| 7369fd5c70 | |||
| b668e86622 | |||
| aa4326f09e | |||
| 0a8d26a8f0 | |||
| 08d20f7a0f | |||
| 325211ad5f | |||
| b63cc86e48 | |||
| 628b93e4ab | |||
| 7e696ec8c8 | |||
| b184d98670 | |||
| 43539139e8 | |||
| f45a106ed8 | |||
| 8b31e88caf | |||
| 4cb34327cf | |||
| c7b414b9f0 | |||
| 9a296c8b84 | |||
| ca569354fb | |||
| 89748b72ed | |||
| add67b6f8d | |||
| 25e7e39ed0 | |||
| 935d313257 | |||
| 5b5e8f8446 | |||
| f1892670da | |||
| d46c72f7e6 | |||
| 157c0c71fe | |||
| 988da07852 | |||
| f02822a011 | |||
| da9644cde1 | |||
| 9aa85d40c6 | |||
| f66123ba94 | |||
| b80babed9c | |||
| 85c5a10891 | |||
| 51356aa4dd | |||
| 807c23926e | |||
| 37a654790c | |||
| a36060654d | |||
| da5fa8d77a | |||
| 4d18c86f04 | |||
| 296c3ce7a0 | |||
| 0ae05709db | |||
| 3dbf2bd8a4 | |||
| 3b02e2ff61 | |||
| b21675d6f2 | |||
| 9e301af076 | |||
| 3fdb574971 | |||
| ad6e413bbb | |||
| 8dc47c3fa5 | |||
| 0eb3146428 | |||
| b2879d8756 | |||
| 30e132d418 | |||
| 7e5843759d | |||
| 7c14df1824 |
+36
-22
@@ -1,10 +1,10 @@
|
||||
name: Android CI Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "dev", "release/*", "hotfix/*" ]
|
||||
pull_request:
|
||||
branches: [ "dev", "release/*", "hotfix/*" ]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
@@ -12,37 +12,51 @@ env:
|
||||
RELEASE_SIGN_KEY_PASSWORD: ${{ secrets.RELEASE_SIGN_KEY_PASSWORD }}
|
||||
|
||||
jobs:
|
||||
build_apk_aab:
|
||||
build_apks:
|
||||
runs-on: ubuntu-24.04
|
||||
name: Build artifacts
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Build and sign debug APK
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Upload debug APK
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: app-debug.apk
|
||||
path: app/build/outputs/apk/debug/app-debug.apk
|
||||
|
||||
- name: Build and sign release APK
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Upload release APK
|
||||
uses: actions/upload-artifact@v4
|
||||
- name: Find generated release APK name
|
||||
id: find_apk_release
|
||||
run: |
|
||||
APK_PATH=$(find app/build/outputs/apk/release -name "*.apk" | head -n 1)
|
||||
echo "APK_PATH=$APK_PATH" >> $GITHUB_ENV
|
||||
echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload APK with original name
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-release.apk
|
||||
path: app/build/outputs/apk/release/app-release.apk
|
||||
name: ${{ env.APK_NAME }}
|
||||
path: ${{ env.APK_PATH }}
|
||||
|
||||
- name: Build and sign debug APK
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Find generated debug APK name
|
||||
id: find_apk_debug
|
||||
run: |
|
||||
APK_PATH=$(find app/build/outputs/apk/debug -name "*.apk" | head -n 1)
|
||||
echo "APK_PATH=$APK_PATH" >> $GITHUB_ENV
|
||||
echo "APK_NAME=$(basename $APK_PATH)" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload APK with original name
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ env.APK_NAME }}
|
||||
path: ${{ env.APK_PATH }}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
name: Android CI Release
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [ "release/*"]
|
||||
|
||||
env:
|
||||
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
|
||||
@@ -15,50 +18,32 @@ jobs:
|
||||
name: Build artifacts
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
- name: set up JDK 21
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '21'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Build and sign debug APK
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Upload debug APK
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: app-debug.apk
|
||||
path: app/build/outputs/apk/debug/app-debug.apk
|
||||
|
||||
- name: Build and sign release APK
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Upload release APK
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-release.apk
|
||||
path: app/build/outputs/apk/release/app-release.apk
|
||||
|
||||
- name: Build and sign debug Bundle
|
||||
run: ./gradlew bundleDebug
|
||||
|
||||
- name: Upload debug Bundle
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: app-debug.aab
|
||||
path: app/build/outputs/bundle/debug/app-debug.aab
|
||||
|
||||
- name: Build and sign release Bundle
|
||||
run: ./gradlew bundleRelease
|
||||
|
||||
- name: Upload release Bundle
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-release.aab
|
||||
path: app/build/outputs/bundle/release/app-release.aab
|
||||
|
||||
@@ -7,52 +7,64 @@ Unofficial messenger for russian social network VKontakte
|
||||
- [x] 2FA support
|
||||
- [x] Resend otp
|
||||
- [x] Captcha support
|
||||
- [ ] Support for new authorization with service and refresh tokens
|
||||
- [x] Support for new authorization with service and refresh tokens
|
||||
- [ ] Handle token expiration
|
||||
- [x] Ability to export/import tokens
|
||||
- [x] Conversations list
|
||||
- [x] Pagination
|
||||
- [x] Manual refresh
|
||||
- [x] Pin & unpin conversations
|
||||
- [x] Delete conversations
|
||||
- [ ] Archive
|
||||
- [ ] View archived conversations
|
||||
- [ ] Archive & unarchive conversations
|
||||
- [x] Archive
|
||||
- [x] View archived conversations
|
||||
- [x] Archive & unarchive conversations
|
||||
- [x] Friends list
|
||||
- [ ] Sort alphabetically, by priority or random
|
||||
- [ ] Separate tab with only friends who are online
|
||||
- [x] Sort alphabetically, by priority or random
|
||||
- [x] Separate tab with only friends who are online
|
||||
- [x] Settings screen
|
||||
- [ ] TODO
|
||||
- [x] Chat screen
|
||||
- [ ] Pagination
|
||||
- [x] Pagination
|
||||
- [x] Manual refresh
|
||||
- [x] Message bubbles
|
||||
- [x] Text
|
||||
- [ ] Date
|
||||
- [ ] Message's attachments
|
||||
- [ ] Photo
|
||||
- [ ] Video
|
||||
- [ ] Audio
|
||||
- [ ] File
|
||||
- [ ] Link
|
||||
- [x] Date
|
||||
- [x] Read status
|
||||
- [x] Edit status
|
||||
- [x] Sending status
|
||||
- [x] Message's attachments
|
||||
- [x] Photo
|
||||
- [x] Video
|
||||
- [x] Audio
|
||||
- [x] File
|
||||
- [x] Link
|
||||
- [x] Sticker
|
||||
- [x] Reply
|
||||
- [ ] Forwarded messages
|
||||
- [ ] Wall post
|
||||
- [ ] Comment in wall post
|
||||
- [ ] Poll
|
||||
- [ ] TODO
|
||||
- [x] Send messages
|
||||
- [ ] Pinned message
|
||||
- [ ] Pin & unpin messages
|
||||
- [ ] Reply to message
|
||||
- [ ] Delete message
|
||||
- [ ] Select multiple messages
|
||||
- [ ] Delete
|
||||
- [x] Pinned message
|
||||
- [x] Pin & unpin messages
|
||||
- [x] Reply to message
|
||||
- [x] Swipe to reply to message
|
||||
- [x] Delete message
|
||||
- [x] Select multiple messages
|
||||
- [x] Delete
|
||||
- [ ] Forward
|
||||
- [ ] Forward in current chat
|
||||
- [ ] Send attachments to chat
|
||||
- [ ] TODO
|
||||
- [x] Chat materials (attachments)
|
||||
- [x] Separate tabs for each attachment type
|
||||
- [ ] Pagination
|
||||
- [x] Pagination
|
||||
- [x] Manual refresh
|
||||
- [x] View attachments
|
||||
- [x] Open photo
|
||||
- [x] Internal viewer
|
||||
- [ ] External viewer
|
||||
- [x] External viewer
|
||||
- [ ] Open video in external player
|
||||
- [ ] TODO
|
||||
- [ ] Caching
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# Fast Messenger Tech Debt Audit
|
||||
|
||||
## Critical
|
||||
|
||||
### `core/network/src/main/kotlin/dev/meloda/fast/network/interceptor/Error14HandlingInterceptor.kt`
|
||||
- captcha flow is built around `wait/notify`, a raw executor, and shared mutable state.
|
||||
- risk: deadlocks, leaked jobs, hard-to-reproduce auth hangs.
|
||||
- fix: rewrite as suspend-based flow with timeout and explicit cancellation.
|
||||
|
||||
### `core/domain/src/main/kotlin/dev/meloda/fast/domain/LongPollEventParser.kt`
|
||||
- file mixes parsing, dispatching, IO loading, and concurrency orchestration.
|
||||
- risk: regressions when VK event format changes.
|
||||
- fix: split by event family and add parser tests.
|
||||
|
||||
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/MessagesHistoryViewModelImpl.kt`
|
||||
- view model is doing too much: loaders, navigation, selection, long poll hooks, read peers, dialog flow.
|
||||
- risk: brittle state transitions and untestable branching.
|
||||
- fix: extract coordinators/handlers per concern.
|
||||
|
||||
### `app/src/main/kotlin/dev/meloda/fast/MainViewModel.kt`
|
||||
- root bootstrap handles auth, locale, long poll, permissions, profile, and start destination in one class.
|
||||
- risk: startup bugs and hidden coupling between flows.
|
||||
- fix: move startup/permission orchestration into dedicated controllers.
|
||||
|
||||
### `app/src/main/kotlin/dev/meloda/fast/presentation/RootScreen.kt`
|
||||
- root composable owns too many top-level flows and dialogs.
|
||||
- risk: UI orchestration drift and hard-to-read navigation logic.
|
||||
- fix: split dialogs, bootstrap, and navigation concern into smaller composables.
|
||||
|
||||
## High
|
||||
|
||||
### `core/domain/src/main/kotlin/dev/meloda/fast/domain/LongPollEventParser.kt`
|
||||
- uses many `Log.d` calls and large `when` branches.
|
||||
- fix: reduce logging noise and add structured tracing only where needed.
|
||||
|
||||
### `core/network/src/main/kotlin/dev/meloda/fast/network/ResponseConverterFactory.kt`
|
||||
- double-parsing response bodies and only logging malformed payloads.
|
||||
- risk: opaque failures and harder debugging.
|
||||
- fix: normalize error conversion and surface typed failures.
|
||||
|
||||
### `feature/profile/src/main/kotlin/dev/meloda/fast/profile/ProfileViewModel.kt`
|
||||
- `loadAccountInfo()` has an empty error branch.
|
||||
- risk: profile can fail silently.
|
||||
- fix: set `baseError` and show fallback UI.
|
||||
|
||||
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/attachments/Attachments.kt`
|
||||
- attachment preview logic still sits in UI layer and mixes fallback behavior.
|
||||
- risk: silent drops of unsupported attachments.
|
||||
- fix: move preview mapping to domain/ui-model layer.
|
||||
|
||||
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/Link.kt`
|
||||
- title handling is nullable and duplicated with preview logic.
|
||||
- fix: create a small UI model for link rendering.
|
||||
|
||||
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/File.kt`
|
||||
- preview extraction is inline and branches on raw model internals.
|
||||
- fix: extract to mapper/UI model.
|
||||
|
||||
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/presentation/MessagesList.kt`
|
||||
- message-item interaction is dense and repeated.
|
||||
- fix: normalize scroll/reply handlers and reduce nested callbacks.
|
||||
|
||||
## Medium
|
||||
|
||||
### `core/data/src/main/kotlin/dev/meloda/fast/data/VkUsersMap.kt`
|
||||
- lookup helpers were using unsafe assumptions on external data.
|
||||
- status: already improved, but should stay covered by tests.
|
||||
|
||||
### `core/data/src/main/kotlin/dev/meloda/fast/data/VkGroupsMap.kt`
|
||||
- same risk profile as users map.
|
||||
- status: already improved, still needs tests.
|
||||
|
||||
### `core/domain/src/main/kotlin/dev/meloda/fast/domain/OAuthUseCaseImpl.kt`
|
||||
- auth success mapping used forced unwraps on server data.
|
||||
- status: already improved, but auth contract should be validated.
|
||||
|
||||
### `app/src/main/kotlin/dev/meloda/fast/presentation/MainActivity.kt`
|
||||
- service lifecycle now respects config changes, but app exit semantics should be documented.
|
||||
- fix: keep explicit separation of app-close vs config-change behavior.
|
||||
|
||||
### `build-logic/convention/src/main/kotlin/dev/meloda/fast/KotlinAndroid.kt`
|
||||
- build-tools are pinned to the local environment.
|
||||
- risk: portable builds may drift between machines.
|
||||
- fix: prefer SDK-managed consistency or document required SDK version.
|
||||
|
||||
### `app/src/main/kotlin/dev/meloda/fast/presentation/RootErrorDialog.kt`
|
||||
- currently hardcodes English strings for some errors.
|
||||
- fix: localize all texts through resources.
|
||||
|
||||
### `app/src/main/kotlin/dev/meloda/fast/presentation/RootScreen.kt`
|
||||
- root-level error dialog is better, but some orchestration still remains in the root composable.
|
||||
- fix: split into smaller root flows over time.
|
||||
|
||||
## Low
|
||||
|
||||
### `core/ui/src/main/kotlin/dev/meloda/fast/ui/components/AnimatedDots.kt`
|
||||
- marked TODO rewrite.
|
||||
- fix when touching related loading UI.
|
||||
|
||||
### `core/ui/src/main/kotlin/dev/meloda/fast/ui/theme/AppTheme.kt`
|
||||
- color picker TODO suggests unfinished theme customization.
|
||||
|
||||
### `core/model/src/main/kotlin/dev/meloda/fast/model/api/data/LongPollUpdates.kt`
|
||||
- `List<List<Any>>` is a weakly typed API boundary.
|
||||
- fix: introduce explicit event DTOs.
|
||||
|
||||
### `core/model/src/main/kotlin/dev/meloda/fast/model/api/domain/VkMessage.kt`
|
||||
- attachment persistence is still a TODO area.
|
||||
|
||||
### `core/model/src/main/kotlin/dev/meloda/fast/model/database/VkMessageEntity.kt`
|
||||
- attachment storage/restoration is unresolved.
|
||||
|
||||
### `core/common/src/main/kotlin/dev/meloda/fast/common/model/LongPollState.kt`
|
||||
- Android 15 support TODO.
|
||||
|
||||
### `feature/messageshistory/src/main/kotlin/dev/meloda/fast/messageshistory/MessagesHistoryViewModelImpl.kt`
|
||||
- large commented-out legacy block should be removed once upload flow is reimplemented.
|
||||
|
||||
### `feature/auth/src/main/kotlin/dev/meloda/fast/auth/login/LoginViewModel.kt`
|
||||
- debug/auth token acquisition TODO indicates unfinished auth path.
|
||||
|
||||
## What To Do First
|
||||
1. Rewrite captcha interceptor.
|
||||
2. Split `LongPollEventParser`.
|
||||
3. Extract `MessagesHistoryViewModelImpl` orchestration.
|
||||
4. Localize `RootErrorDialog` strings.
|
||||
5. Add tests for auth, long poll parsing, and attachment mapping.
|
||||
|
||||
## Note
|
||||
- Current code is already better on crash-prone nullable handling and service lifecycle.
|
||||
- Remaining work is mostly structural and testability-focused.
|
||||
+22
-5
@@ -1,3 +1,4 @@
|
||||
import com.android.build.gradle.internal.api.BaseVariantOutputImpl
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
@@ -7,13 +8,13 @@ plugins {
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "dev.meloda.fast"
|
||||
namespace = "dev.meloda.fastvk"
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "dev.meloda.fast"
|
||||
applicationId = "dev.meloda.fastvk"
|
||||
|
||||
versionCode = libs.versions.versionCode.get().toInt()
|
||||
versionName = libs.versions.versionName.get()
|
||||
versionCode = 11
|
||||
versionName = "0.2.3"
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
@@ -58,6 +59,18 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// applicationVariants.all {
|
||||
// outputs.all {
|
||||
// val date = System.currentTimeMillis() / 1000
|
||||
// val buildType = buildType.name
|
||||
// val appVersion = versionName
|
||||
// val appVersionCode = versionCode
|
||||
//
|
||||
// val newApkName = "app-$buildType-v$appVersion($appVersionCode)-$date.apk"
|
||||
// (this as? BaseVariantOutputImpl)?.outputFileName = newApkName
|
||||
// }
|
||||
// }
|
||||
|
||||
packaging {
|
||||
resources {
|
||||
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||
@@ -66,10 +79,13 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.acra.email)
|
||||
implementation(libs.acra.dialog)
|
||||
|
||||
implementation(projects.feature.auth)
|
||||
|
||||
implementation(projects.feature.chatmaterials)
|
||||
implementation(projects.feature.conversations)
|
||||
implementation(projects.feature.convos)
|
||||
implementation(projects.feature.languagepicker)
|
||||
implementation(projects.feature.messageshistory)
|
||||
implementation(projects.feature.photoviewer)
|
||||
@@ -77,6 +93,7 @@ dependencies {
|
||||
implementation(projects.feature.friends)
|
||||
implementation(projects.feature.profile)
|
||||
implementation(projects.feature.photoviewer)
|
||||
implementation(projects.feature.createchat)
|
||||
|
||||
implementation(projects.core.common)
|
||||
implementation(projects.core.ui)
|
||||
|
||||
Binary file not shown.
@@ -22,7 +22,7 @@
|
||||
tools:targetApi="tiramisu">
|
||||
|
||||
<activity
|
||||
android:name=".presentation.MainActivity"
|
||||
android:name="dev.meloda.fast.presentation.MainActivity"
|
||||
android:exported="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
|
||||
@@ -38,13 +38,13 @@
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".service.longpolling.LongPollingService"
|
||||
android:name="dev.meloda.fast.service.longpolling.LongPollingService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
<service
|
||||
android:name=".service.OnlineService"
|
||||
android:name="dev.meloda.fast.service.OnlineService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
@@ -2,7 +2,6 @@ package dev.meloda.fast
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.os.LocaleListCompat
|
||||
@@ -24,6 +23,7 @@ import dev.meloda.fast.datastore.UserSettings
|
||||
import dev.meloda.fast.domain.GetCurrentAccountUseCase
|
||||
import dev.meloda.fast.domain.LoadUserByIdUseCase
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.navigation.Main
|
||||
import dev.meloda.fast.settings.navigation.Settings
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -36,15 +36,16 @@ interface MainViewModel {
|
||||
|
||||
val startDestination: StateFlow<Any?>
|
||||
val isNeedToReplaceWithAuth: StateFlow<Boolean>
|
||||
val currentUser: StateFlow<VkUser?>
|
||||
val baseError: StateFlow<BaseError?>
|
||||
|
||||
val isNeedToShowNotificationsDeniedDialog: StateFlow<Boolean>
|
||||
val isNeedToShowNotificationsRationaleDialog: StateFlow<Boolean>
|
||||
val isNeedToCheckNotificationsPermission: StateFlow<Boolean>
|
||||
val isNeedToRequestNotifications: StateFlow<Boolean>
|
||||
|
||||
val profileImageUrl: StateFlow<String?>
|
||||
|
||||
fun onError(error: BaseError)
|
||||
fun onErrorConsumed()
|
||||
|
||||
fun onNavigatedToAuth()
|
||||
|
||||
@@ -59,6 +60,8 @@ interface MainViewModel {
|
||||
fun onNotificationsDeniedDialogDismissed()
|
||||
fun onNotificationsRationaleDialogDismissed()
|
||||
fun onNotificationsRationaleDialogCancelClicked()
|
||||
|
||||
fun onUserAuthenticated()
|
||||
}
|
||||
|
||||
class MainViewModelImpl(
|
||||
@@ -70,24 +73,37 @@ class MainViewModelImpl(
|
||||
|
||||
override val startDestination = MutableStateFlow<Any?>(null)
|
||||
override val isNeedToReplaceWithAuth = MutableStateFlow(false)
|
||||
override val currentUser = MutableStateFlow<VkUser?>(null)
|
||||
override val baseError = MutableStateFlow<BaseError?>(null)
|
||||
|
||||
override val isNeedToShowNotificationsDeniedDialog = MutableStateFlow(false)
|
||||
override val isNeedToShowNotificationsRationaleDialog = MutableStateFlow(false)
|
||||
override val isNeedToCheckNotificationsPermission = MutableStateFlow(false)
|
||||
override val isNeedToRequestNotifications = MutableStateFlow(false)
|
||||
|
||||
override val profileImageUrl = MutableStateFlow<String?>(null)
|
||||
|
||||
private var openNotificationsSettings = false
|
||||
private var openAppSettings = false
|
||||
|
||||
init {
|
||||
listenLongPollState()
|
||||
}
|
||||
|
||||
override fun onError(error: BaseError) {
|
||||
when (error) {
|
||||
BaseError.SessionExpired -> {
|
||||
BaseError.SessionExpired,
|
||||
BaseError.AccountBlocked -> {
|
||||
isNeedToReplaceWithAuth.update { true }
|
||||
}
|
||||
|
||||
else -> {
|
||||
baseError.update { error }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onErrorConsumed() {
|
||||
baseError.update { null }
|
||||
}
|
||||
|
||||
override fun onNavigatedToAuth() {
|
||||
isNeedToReplaceWithAuth.update { false }
|
||||
@@ -168,17 +184,20 @@ class MainViewModelImpl(
|
||||
disableBackgroundLongPoll()
|
||||
}
|
||||
|
||||
override fun onUserAuthenticated() {
|
||||
loadProfile()
|
||||
}
|
||||
|
||||
private fun loadProfile() {
|
||||
loadUserByIdUseCase(userId = null)
|
||||
.listenValue(viewModelScope) { state ->
|
||||
state.processState(
|
||||
error = { error ->
|
||||
profileImageUrl.emit(null)
|
||||
currentUser.emit(null)
|
||||
},
|
||||
success = { response ->
|
||||
val user = response ?: return@listenValue
|
||||
|
||||
profileImageUrl.emit(user.photo100)
|
||||
currentUser.emit(user)
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -196,10 +215,6 @@ class MainViewModelImpl(
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val currentAccount = getCurrentAccountUseCase()
|
||||
|
||||
Log.d("MainViewModel", "currentAccount: $currentAccount")
|
||||
|
||||
listenLongPollState()
|
||||
|
||||
if (currentAccount != null) {
|
||||
UserConfig.apply {
|
||||
this.userId = currentAccount.userId
|
||||
@@ -209,7 +224,7 @@ class MainViewModelImpl(
|
||||
}
|
||||
|
||||
longPollController.setStateToApply(
|
||||
if (AppSettings.Debug.longPollInBackground) {
|
||||
if (AppSettings.Experimental.longPollInBackground) {
|
||||
LongPollState.Background
|
||||
} else {
|
||||
LongPollState.InApp
|
||||
@@ -233,7 +248,7 @@ class MainViewModelImpl(
|
||||
}
|
||||
|
||||
private fun disableBackgroundLongPoll() {
|
||||
AppSettings.Debug.longPollInBackground = false
|
||||
AppSettings.Experimental.longPollInBackground = false
|
||||
longPollController.setStateToApply(LongPollState.InApp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,14 @@ import android.app.Application
|
||||
import androidx.preference.PreferenceManager
|
||||
import coil.ImageLoader
|
||||
import coil.ImageLoaderFactory
|
||||
import com.skydoves.compose.stability.runtime.ComposeStabilityAnalyzer
|
||||
import dev.meloda.fast.auth.BuildConfig
|
||||
import dev.meloda.fast.common.di.applicationModule
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import org.acra.config.dialog
|
||||
import org.acra.config.mailSender
|
||||
import org.acra.data.StringFormat
|
||||
import org.acra.ktx.initAcra
|
||||
import org.koin.android.ext.android.get
|
||||
import org.koin.android.ext.koin.androidContext
|
||||
import org.koin.android.ext.koin.androidLogger
|
||||
@@ -18,10 +24,14 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
||||
|
||||
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
|
||||
AppSettings.init(preferences)
|
||||
ComposeStabilityAnalyzer.setEnabled(BuildConfig.DEBUG)
|
||||
|
||||
initKoin()
|
||||
initAcra()
|
||||
}
|
||||
|
||||
override fun newImageLoader(): ImageLoader = get()
|
||||
|
||||
private fun initKoin() {
|
||||
startKoin {
|
||||
androidLogger()
|
||||
@@ -30,5 +40,21 @@ class AppGlobal : Application(), ImageLoaderFactory {
|
||||
}
|
||||
}
|
||||
|
||||
override fun newImageLoader(): ImageLoader = get()
|
||||
private fun initAcra() {
|
||||
initAcra {
|
||||
buildConfigClass = BuildConfig::class.java
|
||||
reportFormat = StringFormat.JSON
|
||||
|
||||
mailSender {
|
||||
mailTo = "lischenkodev@gmail.com"
|
||||
reportAsFile = true
|
||||
reportFileName = "Crash.txt"
|
||||
}
|
||||
|
||||
dialog {
|
||||
text = "App crashed"
|
||||
enabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,17 +5,17 @@ import android.content.res.Resources
|
||||
import android.os.PowerManager
|
||||
import androidx.preference.PreferenceManager
|
||||
import coil.ImageLoader
|
||||
import coil.annotation.ExperimentalCoilApi
|
||||
import dev.meloda.fast.MainViewModelImpl
|
||||
import dev.meloda.fast.auth.captcha.di.captchaModule
|
||||
import dev.meloda.fast.auth.login.di.loginModule
|
||||
import dev.meloda.fast.auth.validation.di.validationModule
|
||||
import dev.meloda.fast.auth.authModule
|
||||
import dev.meloda.fast.chatmaterials.di.chatMaterialsModule
|
||||
import dev.meloda.fast.common.LongPollController
|
||||
import dev.meloda.fast.common.LongPollControllerImpl
|
||||
import dev.meloda.fast.common.provider.Provider
|
||||
import dev.meloda.fast.common.provider.ResourceProvider
|
||||
import dev.meloda.fast.common.provider.ResourceProviderImpl
|
||||
import dev.meloda.fast.conversations.di.conversationsModule
|
||||
import dev.meloda.fast.convos.di.convosModule
|
||||
import dev.meloda.fast.convos.di.createChatModule
|
||||
import dev.meloda.fast.domain.di.domainModule
|
||||
import dev.meloda.fast.friends.di.friendsModule
|
||||
import dev.meloda.fast.languagepicker.di.languagePickerModule
|
||||
@@ -26,19 +26,18 @@ import dev.meloda.fast.provider.ApiLanguageProvider
|
||||
import dev.meloda.fast.service.longpolling.di.longPollModule
|
||||
import dev.meloda.fast.settings.di.settingsModule
|
||||
import org.koin.android.ext.koin.androidContext
|
||||
import org.koin.androidx.viewmodel.dsl.viewModelOf
|
||||
import org.koin.core.module.dsl.singleOf
|
||||
import org.koin.core.module.dsl.viewModelOf
|
||||
import org.koin.core.qualifier.qualifier
|
||||
import org.koin.dsl.bind
|
||||
import org.koin.dsl.module
|
||||
|
||||
@OptIn(ExperimentalCoilApi::class)
|
||||
val applicationModule = module {
|
||||
includes(domainModule)
|
||||
includes(
|
||||
loginModule,
|
||||
validationModule,
|
||||
captchaModule,
|
||||
conversationsModule,
|
||||
authModule,
|
||||
convosModule,
|
||||
settingsModule,
|
||||
messagesHistoryModule,
|
||||
photoViewModule,
|
||||
@@ -46,10 +45,10 @@ val applicationModule = module {
|
||||
longPollModule,
|
||||
friendsModule,
|
||||
profileModule,
|
||||
chatMaterialsModule
|
||||
chatMaterialsModule,
|
||||
createChatModule
|
||||
)
|
||||
|
||||
// TODO: 14/05/2024, Danil Nikolaev: research on memory leaks and potentials errors
|
||||
// TODO: 14/05/2024, Danil Nikolaev: extract all operations with preferences to standalone class
|
||||
singleOf(PreferenceManager::getDefaultSharedPreferences)
|
||||
single<Resources> { androidContext().resources }
|
||||
@@ -61,10 +60,11 @@ val applicationModule = module {
|
||||
qualifier = qualifier("main")
|
||||
}
|
||||
|
||||
single {
|
||||
single<ImageLoader> {
|
||||
ImageLoader.Builder(get())
|
||||
.crossfade(true)
|
||||
.build()
|
||||
.also { it.diskCache?.directory?.toFile()?.listFiles() }
|
||||
}
|
||||
|
||||
singleOf(::LongPollControllerImpl) bind LongPollController::class
|
||||
|
||||
@@ -2,16 +2,15 @@ package dev.meloda.fast.navigation
|
||||
|
||||
import androidx.navigation.NavGraphBuilder
|
||||
import androidx.navigation.compose.composable
|
||||
import dev.meloda.fast.MainViewModel
|
||||
import dev.meloda.fast.conversations.navigation.Conversations
|
||||
import dev.meloda.fast.convos.navigation.ConvoGraph
|
||||
import dev.meloda.fast.friends.navigation.Friends
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.BottomNavigationItem
|
||||
import dev.meloda.fast.presentation.MainScreen
|
||||
import dev.meloda.fast.profile.navigation.Profile
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
import kotlinx.serialization.Serializable
|
||||
import dev.meloda.fast.ui.R as UiR
|
||||
|
||||
@Serializable
|
||||
object MainGraph
|
||||
@@ -22,27 +21,28 @@ object Main
|
||||
fun NavGraphBuilder.mainScreen(
|
||||
onError: (BaseError) -> Unit,
|
||||
onSettingsButtonClicked: () -> Unit,
|
||||
onConversationClicked: (conversationId: Int) -> Unit,
|
||||
onNavigateToMessagesHistory: (convoId: Long) -> Unit,
|
||||
onPhotoClicked: (url: String) -> Unit,
|
||||
viewModel: MainViewModel
|
||||
onMessageClicked: (userid: Long) -> Unit,
|
||||
onNavigateToCreateChat: () -> Unit
|
||||
) {
|
||||
val navigationItems = ImmutableList.of(
|
||||
BottomNavigationItem(
|
||||
titleResId = UiR.string.title_friends,
|
||||
selectedIconResId = UiR.drawable.baseline_people_alt_24,
|
||||
unselectedIconResId = UiR.drawable.outline_people_alt_24,
|
||||
titleResId = R.string.title_friends,
|
||||
selectedIconResId = R.drawable.ic_group_fill_round_24,
|
||||
unselectedIconResId = R.drawable.ic_group_round_24,
|
||||
route = Friends,
|
||||
),
|
||||
BottomNavigationItem(
|
||||
titleResId = UiR.string.title_conversations,
|
||||
selectedIconResId = UiR.drawable.baseline_chat_24,
|
||||
unselectedIconResId = UiR.drawable.outline_chat_24,
|
||||
route = Conversations
|
||||
titleResId = R.string.title_convos,
|
||||
selectedIconResId = R.drawable.ic_mail_fill_round_24,
|
||||
unselectedIconResId = R.drawable.ic_mail_round_24,
|
||||
route = ConvoGraph
|
||||
),
|
||||
BottomNavigationItem(
|
||||
titleResId = UiR.string.title_profile,
|
||||
selectedIconResId = UiR.drawable.baseline_account_circle_24,
|
||||
unselectedIconResId = UiR.drawable.outline_account_circle_24,
|
||||
titleResId = R.string.title_profile,
|
||||
selectedIconResId = R.drawable.ic_account_circle_fill_round_24,
|
||||
unselectedIconResId = R.drawable.ic_account_circle_round_24,
|
||||
route = Profile
|
||||
)
|
||||
)
|
||||
@@ -52,9 +52,10 @@ fun NavGraphBuilder.mainScreen(
|
||||
navigationItems = navigationItems,
|
||||
onError = onError,
|
||||
onSettingsButtonClicked = onSettingsButtonClicked,
|
||||
onConversationItemClicked = onConversationClicked,
|
||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
||||
onPhotoClicked = onPhotoClicked,
|
||||
viewModel = viewModel
|
||||
onMessageClicked = onMessageClicked,
|
||||
onNavigateToCreateChat = onNavigateToCreateChat
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,54 +4,29 @@ import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.conena.nanokt.android.content.pxToDp
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.google.accompanist.permissions.isGranted
|
||||
import com.google.accompanist.permissions.rememberPermissionState
|
||||
import dev.meloda.fast.MainViewModel
|
||||
import dev.meloda.fast.MainViewModelImpl
|
||||
import dev.meloda.fast.common.AppConstants
|
||||
import dev.meloda.fast.common.LongPollController
|
||||
import dev.meloda.fast.common.model.LongPollState
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.datastore.UserSettings
|
||||
import dev.meloda.fast.service.OnlineService
|
||||
import dev.meloda.fast.service.longpolling.LongPollingService
|
||||
import dev.meloda.fast.ui.model.DeviceSize
|
||||
import dev.meloda.fast.ui.model.SizeConfig
|
||||
import dev.meloda.fast.ui.model.ThemeConfig
|
||||
import dev.meloda.fast.ui.theme.AppTheme
|
||||
import dev.meloda.fast.ui.theme.LocalSizeConfig
|
||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||
import dev.meloda.fast.ui.util.isNeedToEnableDarkMode
|
||||
import dev.meloda.fast.ui.R
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
import org.koin.compose.KoinContext
|
||||
import org.koin.compose.koinInject
|
||||
import dev.meloda.fast.ui.R as UiR
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
@@ -85,17 +60,9 @@ class MainActivity : AppCompatActivity() {
|
||||
)
|
||||
|
||||
createNotificationChannels()
|
||||
requestNotificationPermissions()
|
||||
|
||||
setContent {
|
||||
KoinContext {
|
||||
val context = LocalContext.current
|
||||
|
||||
val userSettings: UserSettings = koinInject()
|
||||
val longPollController: LongPollController = koinInject()
|
||||
|
||||
val longPollCurrentState by longPollController.currentState.collectAsStateWithLifecycle()
|
||||
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
||||
|
||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||
|
||||
LifecycleResumeEffect(true) {
|
||||
@@ -103,178 +70,46 @@ class MainActivity : AppCompatActivity() {
|
||||
onPauseOrDispose {}
|
||||
}
|
||||
|
||||
val permissionState =
|
||||
rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS)
|
||||
|
||||
val isNeedToCheckPermission by viewModel.isNeedToCheckNotificationsPermission.collectAsStateWithLifecycle()
|
||||
val isNeedToRequestPermission by viewModel.isNeedToRequestNotifications.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(isNeedToCheckPermission) {
|
||||
if (isNeedToCheckPermission) {
|
||||
viewModel.onPermissionCheckStatus(permissionState.status)
|
||||
|
||||
if (permissionState.status.isGranted) {
|
||||
if (longPollCurrentState == LongPollState.InApp) {
|
||||
toggleLongPollService(false)
|
||||
}
|
||||
|
||||
RootScreen(
|
||||
toggleLongPollService = { enable, inBackground ->
|
||||
toggleLongPollService(
|
||||
enable = true,
|
||||
inBackground = true
|
||||
enable = enable,
|
||||
inBackground = inBackground ?: AppSettings.Experimental.longPollInBackground
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(isNeedToRequestPermission) {
|
||||
if (isNeedToRequestPermission) {
|
||||
viewModel.onPermissionsRequested()
|
||||
permissionState.launchPermissionRequest()
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(longPollStateToApply) {
|
||||
if (longPollStateToApply != LongPollState.Background) {
|
||||
if (longPollStateToApply.isLaunched() && longPollCurrentState.isLaunched()
|
||||
&& longPollCurrentState != longPollStateToApply
|
||||
) {
|
||||
toggleLongPollService(false)
|
||||
Log.d("LongPoll", "recreate()")
|
||||
}
|
||||
|
||||
toggleLongPollService(
|
||||
enable = longPollStateToApply.isLaunched(),
|
||||
inBackground = longPollStateToApply == LongPollState.Background
|
||||
},
|
||||
toggleOnlineService = ::toggleOnlineService
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val sendOnline by userSettings.sendOnlineStatus.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(sendOnline) {
|
||||
toggleOnlineService(sendOnline)
|
||||
|
||||
onPauseOrDispose {
|
||||
toggleOnlineService(false)
|
||||
}
|
||||
}
|
||||
|
||||
val deviceWidthDp = remember(true) {
|
||||
context.resources.displayMetrics.widthPixels.pxToDp()
|
||||
}
|
||||
val deviceHeightDp = remember(true) {
|
||||
context.resources.displayMetrics.heightPixels.pxToDp()
|
||||
}
|
||||
|
||||
val deviceWidthSize by remember(deviceWidthDp) {
|
||||
derivedStateOf {
|
||||
when {
|
||||
deviceWidthDp <= 360 -> DeviceSize.Small
|
||||
deviceWidthDp <= 600 -> DeviceSize.Compact
|
||||
deviceWidthDp <= 840 -> DeviceSize.Medium
|
||||
else -> DeviceSize.Expanded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val deviceHeightSize by remember(deviceHeightDp) {
|
||||
derivedStateOf {
|
||||
when {
|
||||
deviceHeightDp <= 480 -> DeviceSize.Small
|
||||
deviceHeightDp <= 700 -> DeviceSize.Compact
|
||||
deviceHeightDp <= 900 -> DeviceSize.Medium
|
||||
else -> DeviceSize.Expanded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val sizeConfig by remember(deviceWidthSize, deviceHeightSize) {
|
||||
mutableStateOf(
|
||||
SizeConfig(
|
||||
widthSize = deviceWidthSize,
|
||||
heightSize = deviceHeightSize
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
val darkMode by userSettings.darkMode.collectAsStateWithLifecycle()
|
||||
val dynamicColors by userSettings.enableDynamicColors.collectAsStateWithLifecycle()
|
||||
val amoledDark by userSettings.enableAmoledDark.collectAsStateWithLifecycle()
|
||||
val enableBlur by userSettings.useBlur.collectAsStateWithLifecycle()
|
||||
val enableMultiline by userSettings.enableMultiline.collectAsStateWithLifecycle()
|
||||
val useSystemFont by userSettings.useSystemFont.collectAsStateWithLifecycle()
|
||||
|
||||
val setDarkMode = isNeedToEnableDarkMode(darkMode = darkMode)
|
||||
|
||||
val themeConfig by remember(
|
||||
darkMode,
|
||||
dynamicColors,
|
||||
amoledDark,
|
||||
enableBlur,
|
||||
enableMultiline,
|
||||
setDarkMode,
|
||||
useSystemFont
|
||||
) {
|
||||
mutableStateOf(
|
||||
ThemeConfig(
|
||||
darkMode = setDarkMode,
|
||||
dynamicColors = dynamicColors,
|
||||
selectedColorScheme = 0,
|
||||
amoledDark = amoledDark,
|
||||
enableBlur = enableBlur,
|
||||
enableMultiline = enableMultiline,
|
||||
useSystemFont = useSystemFont
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
CompositionLocalProvider(
|
||||
LocalThemeConfig provides themeConfig,
|
||||
LocalSizeConfig provides sizeConfig
|
||||
) {
|
||||
AppTheme(
|
||||
useDarkTheme = themeConfig.darkMode,
|
||||
useDynamicColors = themeConfig.dynamicColors,
|
||||
selectedColorScheme = themeConfig.selectedColorScheme,
|
||||
useAmoledBackground = themeConfig.amoledDark,
|
||||
useSystemFont = themeConfig.useSystemFont
|
||||
) {
|
||||
RootScreen(viewModel = viewModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createNotificationChannels() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val noCategoryName = getString(UiR.string.notification_channel_no_category_name)
|
||||
val noCategoryName = getString(R.string.notification_channel_no_category_name)
|
||||
val noCategoryDescriptionText =
|
||||
getString(UiR.string.notification_channel_no_category_description)
|
||||
val noCategoryImportance = NotificationManagerCompat.IMPORTANCE_HIGH
|
||||
getString(R.string.notification_channel_no_category_description)
|
||||
val noCategoryChannel =
|
||||
NotificationChannel(
|
||||
AppConstants.NOTIFICATION_CHANNEL_UNCATEGORIZED,
|
||||
noCategoryName,
|
||||
noCategoryImportance
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
).apply {
|
||||
description = noCategoryDescriptionText
|
||||
}
|
||||
|
||||
val longPollName = getString(UiR.string.notification_channel_long_polling_service_name)
|
||||
val longPollName = getString(R.string.notification_channel_long_polling_service_name)
|
||||
val longPollDescriptionText =
|
||||
getString(UiR.string.notification_channel_long_polling_service_description)
|
||||
val longPollImportance = NotificationManagerCompat.IMPORTANCE_NONE
|
||||
getString(R.string.notification_channel_long_polling_service_description)
|
||||
val longPollChannel =
|
||||
NotificationChannel(
|
||||
AppConstants.NOTIFICATION_CHANNEL_LONG_POLLING,
|
||||
longPollName,
|
||||
longPollImportance
|
||||
NotificationManager.IMPORTANCE_NONE
|
||||
).apply {
|
||||
description = longPollDescriptionText
|
||||
}
|
||||
|
||||
val notificationManager: NotificationManager =
|
||||
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
|
||||
notificationManager.createNotificationChannels(
|
||||
listOf(
|
||||
@@ -285,12 +120,28 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestNotificationPermissions() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
requestPermissions(
|
||||
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
|
||||
REQUEST_NOTIFICATION_PERMISSION_CODE
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private val longPollingServiceIntent by lazy {
|
||||
Intent(this, LongPollingService::class.java)
|
||||
}
|
||||
private val onlineServiceIntent by lazy {
|
||||
Intent(this, OnlineService::class.java)
|
||||
}
|
||||
|
||||
private fun toggleLongPollService(
|
||||
enable: Boolean,
|
||||
inBackground: Boolean = AppSettings.Debug.longPollInBackground
|
||||
inBackground: Boolean = AppSettings.Experimental.longPollInBackground
|
||||
) {
|
||||
if (enable) {
|
||||
val longPollIntent = Intent(this, LongPollingService::class.java)
|
||||
val longPollIntent = longPollingServiceIntent
|
||||
|
||||
if (inBackground) {
|
||||
ContextCompat.startForegroundService(this, longPollIntent)
|
||||
@@ -298,22 +149,22 @@ class MainActivity : AppCompatActivity() {
|
||||
startService(longPollIntent)
|
||||
}
|
||||
} else {
|
||||
stopService(Intent(this, LongPollingService::class.java))
|
||||
stopService(longPollingServiceIntent)
|
||||
}
|
||||
}
|
||||
|
||||
private fun toggleOnlineService(enable: Boolean) {
|
||||
if (enable) {
|
||||
startService(Intent(this, OnlineService::class.java))
|
||||
startService(onlineServiceIntent)
|
||||
} else {
|
||||
stopService(Intent(this, OnlineService::class.java))
|
||||
stopService(onlineServiceIntent)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopServices() {
|
||||
toggleOnlineService(enable = false)
|
||||
|
||||
val asForeground = AppSettings.Debug.longPollInBackground
|
||||
val asForeground = AppSettings.Experimental.longPollInBackground
|
||||
|
||||
if (!asForeground) {
|
||||
toggleLongPollService(enable = false)
|
||||
@@ -324,4 +175,8 @@ class MainActivity : AppCompatActivity() {
|
||||
super.onDestroy()
|
||||
stopServices()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_NOTIFICATION_PERMISSION_CODE = 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package dev.meloda.fast.presentation
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.LocalActivity
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -25,27 +27,32 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.navigation
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import coil.compose.SubcomposeAsyncImage
|
||||
import dev.chrisbanes.haze.HazeState
|
||||
import dev.chrisbanes.haze.hazeChild
|
||||
import dev.chrisbanes.haze.hazeEffect
|
||||
import dev.chrisbanes.haze.materials.ExperimentalHazeMaterialsApi
|
||||
import dev.chrisbanes.haze.materials.HazeMaterials
|
||||
import dev.meloda.fast.MainViewModel
|
||||
import dev.meloda.fast.conversations.navigation.conversationsScreen
|
||||
import dev.meloda.fast.convos.navigation.ConvoGraph
|
||||
import dev.meloda.fast.convos.navigation.convosGraph
|
||||
import dev.meloda.fast.friends.navigation.Friends
|
||||
import dev.meloda.fast.friends.navigation.friendsScreen
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.model.BottomNavigationItem
|
||||
import dev.meloda.fast.navigation.MainGraph
|
||||
import dev.meloda.fast.profile.navigation.Profile
|
||||
import dev.meloda.fast.profile.navigation.profileScreen
|
||||
import dev.meloda.fast.ui.theme.LocalBottomPadding
|
||||
import dev.meloda.fast.ui.theme.LocalHazeState
|
||||
import dev.meloda.fast.ui.theme.LocalNavController
|
||||
import dev.meloda.fast.ui.theme.LocalReselectedTab
|
||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||
import dev.meloda.fast.ui.theme.LocalUser
|
||||
import dev.meloda.fast.ui.util.ImmutableList
|
||||
|
||||
@OptIn(ExperimentalHazeMaterialsApi::class)
|
||||
@@ -54,36 +61,55 @@ fun MainScreen(
|
||||
navigationItems: ImmutableList<BottomNavigationItem>,
|
||||
onError: (BaseError) -> Unit = {},
|
||||
onSettingsButtonClicked: () -> Unit = {},
|
||||
onConversationItemClicked: (conversationId: Int) -> Unit = {},
|
||||
onNavigateToMessagesHistory: (convoId: Long) -> Unit = {},
|
||||
onPhotoClicked: (url: String) -> Unit = {},
|
||||
viewModel: MainViewModel
|
||||
onMessageClicked: (userid: Long) -> Unit = {},
|
||||
onNavigateToCreateChat: () -> Unit = {}
|
||||
) {
|
||||
val currentTheme = LocalThemeConfig.current
|
||||
val hazeState = remember { HazeState() }
|
||||
val activity = LocalActivity.current as? AppCompatActivity ?: return
|
||||
val theme = LocalThemeConfig.current
|
||||
val hazeState = remember { HazeState(true) }
|
||||
val navController = rememberNavController()
|
||||
|
||||
val profileImageUrl by viewModel.profileImageUrl.collectAsStateWithLifecycle()
|
||||
val defaultTabIndex = remember(navigationItems) {
|
||||
navigationItems.indexOfFirst { it.route == ConvoGraph }.takeIf { it >= 0 } ?: 0
|
||||
}
|
||||
|
||||
var selectedItemIndex by rememberSaveable {
|
||||
mutableIntStateOf(1)
|
||||
mutableIntStateOf(defaultTabIndex)
|
||||
}
|
||||
|
||||
BackHandler(enabled = selectedItemIndex != defaultTabIndex) {
|
||||
val currentRoute = navigationItems[selectedItemIndex].route
|
||||
|
||||
selectedItemIndex = defaultTabIndex
|
||||
navController.navigate(navigationItems[selectedItemIndex].route) {
|
||||
popUpTo(route = currentRoute) {
|
||||
inclusive = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val profileImageUrl = LocalUser.current?.photo100
|
||||
|
||||
var tabReselected by remember {
|
||||
mutableStateOf(navigationItems.associate { it.route to false })
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
bottomBar = {
|
||||
NavigationBar(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.then(
|
||||
if (currentTheme.enableBlur) {
|
||||
Modifier.hazeChild(
|
||||
if (theme.enableBlur) {
|
||||
Modifier.hazeEffect(
|
||||
state = hazeState,
|
||||
style = HazeMaterials.thick()
|
||||
style = HazeMaterials.regular(NavigationBarDefaults.containerColor)
|
||||
)
|
||||
} else Modifier
|
||||
)
|
||||
.fillMaxWidth(),
|
||||
containerColor = NavigationBarDefaults.containerColor.copy(
|
||||
alpha = if (currentTheme.enableBlur) 0f else 1f
|
||||
)
|
||||
),
|
||||
containerColor = if (theme.enableBlur) Color.Transparent
|
||||
else NavigationBarDefaults.containerColor
|
||||
) {
|
||||
navigationItems.forEachIndexed { index, item ->
|
||||
NavigationBarItem(
|
||||
@@ -98,10 +124,14 @@ fun MainScreen(
|
||||
inclusive = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tabReselected = tabReselected.toMutableMap().also {
|
||||
it[navigationItems[index].route] = true
|
||||
}
|
||||
}
|
||||
},
|
||||
icon = {
|
||||
if (index == navigationItems.size - 1) {
|
||||
if (item.route == Profile) {
|
||||
var isLoading by remember {
|
||||
mutableStateOf(true)
|
||||
}
|
||||
@@ -121,9 +151,7 @@ fun MainScreen(
|
||||
.size(24.dp)
|
||||
.clip(CircleShape)
|
||||
.alpha(if (isLoading) 0f else 1f),
|
||||
onSuccess = {
|
||||
isLoading = false
|
||||
}
|
||||
onSuccess = { isLoading = false }
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
@@ -144,11 +172,12 @@ fun MainScreen(
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(bottom = if (currentTheme.enableBlur) 0.dp else padding.calculateBottomPadding())
|
||||
) {
|
||||
CompositionLocalProvider(
|
||||
LocalHazeState provides hazeState,
|
||||
LocalBottomPadding provides if (currentTheme.enableBlur) padding.calculateBottomPadding() else 0.dp
|
||||
LocalBottomPadding provides padding.calculateBottomPadding(),
|
||||
LocalReselectedTab provides tabReselected,
|
||||
LocalNavController provides navController
|
||||
) {
|
||||
NavHost(
|
||||
navController = navController,
|
||||
@@ -156,23 +185,38 @@ fun MainScreen(
|
||||
enterTransition = { fadeIn(animationSpec = tween(200)) },
|
||||
exitTransition = { fadeOut(animationSpec = tween(200)) }
|
||||
) {
|
||||
navigation<MainGraph>(startDestination = navigationItems[selectedItemIndex].route) {
|
||||
navigation<MainGraph>(
|
||||
startDestination = navigationItems[selectedItemIndex].route,
|
||||
enterTransition = { fadeIn(animationSpec = tween(200)) },
|
||||
exitTransition = { fadeOut(animationSpec = tween(200)) }
|
||||
) {
|
||||
friendsScreen(
|
||||
activity = activity,
|
||||
onError = onError,
|
||||
navController = navController,
|
||||
onPhotoClicked = onPhotoClicked
|
||||
onPhotoClicked = onPhotoClicked,
|
||||
onMessageClicked = onMessageClicked,
|
||||
onScrolledToTop = {
|
||||
tabReselected = tabReselected.toMutableMap().also {
|
||||
it[Friends] = false
|
||||
}
|
||||
},
|
||||
)
|
||||
conversationsScreen(
|
||||
convosGraph(
|
||||
activity = activity,
|
||||
onError = onError,
|
||||
onConversationItemClicked = onConversationItemClicked,
|
||||
navController = navController,
|
||||
onPhotoClicked = onPhotoClicked
|
||||
onNavigateToMessagesHistory = onNavigateToMessagesHistory,
|
||||
onNavigateToCreateChat = onNavigateToCreateChat,
|
||||
onScrolledToTop = {
|
||||
tabReselected = tabReselected.toMutableMap().also {
|
||||
it[ConvoGraph] = false
|
||||
}
|
||||
}
|
||||
)
|
||||
profileScreen(
|
||||
activity = activity,
|
||||
onError = onError,
|
||||
onSettingsButtonClicked = onSettingsButtonClicked,
|
||||
onPhotoClicked = onPhotoClicked,
|
||||
navController = navController
|
||||
onPhotoClicked = onPhotoClicked
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.meloda.fast.presentation
|
||||
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.ui.R
|
||||
|
||||
@Composable
|
||||
fun RootErrorDialog(
|
||||
baseError: BaseError?,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit,
|
||||
) {
|
||||
if (baseError == null) return
|
||||
|
||||
val errorText = when (baseError) {
|
||||
BaseError.ConnectionError -> "Connection error"
|
||||
BaseError.InternalError -> "Internal error"
|
||||
BaseError.UnknownError -> "Unknown error"
|
||||
is BaseError.SimpleError -> baseError.message
|
||||
BaseError.SessionExpired -> "Session expired"
|
||||
BaseError.AccountBlocked -> "Account blocked"
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(text = stringResource(id = R.string.warning)) },
|
||||
text = { Text(text = errorText) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = onConfirm) {
|
||||
Text(text = stringResource(id = R.string.try_again))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -1,50 +1,238 @@
|
||||
package dev.meloda.fast.presentation
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.LocalActivity
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalResources
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavController
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import com.conena.nanokt.android.content.pxToDp
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.google.accompanist.permissions.isGranted
|
||||
import com.google.accompanist.permissions.rememberPermissionState
|
||||
import dev.meloda.fast.MainViewModel
|
||||
import dev.meloda.fast.MainViewModelImpl
|
||||
import dev.meloda.fast.auth.authNavGraph
|
||||
import dev.meloda.fast.auth.captcha.presentation.CaptchaScreen
|
||||
import dev.meloda.fast.auth.navigateToAuth
|
||||
import dev.meloda.fast.chatmaterials.navigation.chatMaterialsScreen
|
||||
import dev.meloda.fast.chatmaterials.navigation.navigateToChatMaterials
|
||||
import dev.meloda.fast.common.LongPollController
|
||||
import dev.meloda.fast.common.model.LongPollState
|
||||
import dev.meloda.fast.convos.navigation.createChatScreen
|
||||
import dev.meloda.fast.convos.navigation.navigateToCreateChat
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.datastore.CaptchaTokenResult
|
||||
import dev.meloda.fast.datastore.UserSettings
|
||||
import dev.meloda.fast.languagepicker.navigation.languagePickerScreen
|
||||
import dev.meloda.fast.languagepicker.navigation.navigateToLanguagePicker
|
||||
import dev.meloda.fast.messageshistory.navigation.messagesHistoryScreen
|
||||
import dev.meloda.fast.messageshistory.navigation.navigateToMessagesHistory
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.navigation.Main
|
||||
import dev.meloda.fast.navigation.mainScreen
|
||||
import dev.meloda.fast.photoviewer.navigation.navigateToPhotoView
|
||||
import dev.meloda.fast.photoviewer.navigation.photoViewScreen
|
||||
import dev.meloda.fast.photoviewer.presentation.PhotoViewDialog
|
||||
import dev.meloda.fast.settings.navigation.navigateToSettings
|
||||
import dev.meloda.fast.settings.navigation.settingsScreen
|
||||
import dev.meloda.fast.ui.R
|
||||
import dev.meloda.fast.ui.common.LocalSizeConfig
|
||||
import dev.meloda.fast.ui.model.DeviceSize
|
||||
import dev.meloda.fast.ui.model.SizeConfig
|
||||
import dev.meloda.fast.ui.model.ThemeConfig
|
||||
import dev.meloda.fast.ui.theme.AppTheme
|
||||
import dev.meloda.fast.ui.theme.LocalNavController
|
||||
import dev.meloda.fast.ui.theme.LocalNavRootController
|
||||
import dev.meloda.fast.ui.theme.LocalThemeConfig
|
||||
import dev.meloda.fast.ui.theme.LocalUser
|
||||
import dev.meloda.fast.ui.util.ImmutableList.Companion.toImmutableList
|
||||
import dev.meloda.fast.ui.util.isNeedToEnableDarkMode
|
||||
import org.koin.androidx.compose.koinViewModel
|
||||
import org.koin.compose.koinInject
|
||||
|
||||
@OptIn(ExperimentalPermissionsApi::class)
|
||||
@Composable
|
||||
fun RootScreen(
|
||||
navController: NavHostController = rememberNavController(),
|
||||
viewModel: MainViewModel
|
||||
toggleLongPollService: (enable: Boolean, inBackground: Boolean?) -> Unit,
|
||||
toggleOnlineService: (enable: Boolean) -> Unit
|
||||
) {
|
||||
val resources = LocalResources.current
|
||||
|
||||
val userSettings: UserSettings = koinInject()
|
||||
val longPollController: LongPollController = koinInject()
|
||||
|
||||
val longPollCurrentState by longPollController.currentState.collectAsStateWithLifecycle()
|
||||
val longPollStateToApply by longPollController.stateToApply.collectAsStateWithLifecycle()
|
||||
|
||||
val viewModel: MainViewModel = koinViewModel<MainViewModelImpl>()
|
||||
|
||||
val currentUser: VkUser? by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||
|
||||
val permissionState =
|
||||
rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS)
|
||||
|
||||
val isNeedToCheckPermission by viewModel.isNeedToCheckNotificationsPermission.collectAsStateWithLifecycle()
|
||||
val isNeedToRequestPermission by viewModel.isNeedToRequestNotifications.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(isNeedToCheckPermission) {
|
||||
if (isNeedToCheckPermission) {
|
||||
viewModel.onPermissionCheckStatus(permissionState.status)
|
||||
|
||||
if (permissionState.status.isGranted) {
|
||||
if (longPollCurrentState == LongPollState.InApp) {
|
||||
toggleLongPollService(false, null)
|
||||
}
|
||||
|
||||
toggleLongPollService(true, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(isNeedToRequestPermission) {
|
||||
if (isNeedToRequestPermission) {
|
||||
viewModel.onPermissionsRequested()
|
||||
permissionState.launchPermissionRequest()
|
||||
}
|
||||
}
|
||||
|
||||
LifecycleResumeEffect(longPollStateToApply) {
|
||||
if (longPollStateToApply != LongPollState.Background) {
|
||||
if (longPollStateToApply.isLaunched() && longPollCurrentState.isLaunched()
|
||||
&& longPollCurrentState != longPollStateToApply
|
||||
) {
|
||||
toggleLongPollService(false, null)
|
||||
}
|
||||
|
||||
toggleLongPollService(
|
||||
longPollStateToApply.isLaunched(),
|
||||
longPollStateToApply == LongPollState.Background
|
||||
)
|
||||
}
|
||||
|
||||
onPauseOrDispose {}
|
||||
}
|
||||
|
||||
val sendOnline by userSettings.sendOnlineStatus.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(sendOnline) {
|
||||
toggleOnlineService(sendOnline)
|
||||
|
||||
onPauseOrDispose {
|
||||
toggleOnlineService(false)
|
||||
}
|
||||
}
|
||||
|
||||
val deviceWidthDp = remember(true) {
|
||||
resources.displayMetrics.widthPixels.pxToDp()
|
||||
}
|
||||
val deviceHeightDp = remember(true) {
|
||||
resources.displayMetrics.heightPixels.pxToDp()
|
||||
}
|
||||
|
||||
val deviceWidthSize by remember(deviceWidthDp) {
|
||||
derivedStateOf {
|
||||
when {
|
||||
deviceWidthDp <= 360 -> DeviceSize.Small
|
||||
deviceWidthDp <= 600 -> DeviceSize.Compact
|
||||
deviceWidthDp <= 840 -> DeviceSize.Medium
|
||||
else -> DeviceSize.Expanded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val deviceHeightSize by remember(deviceHeightDp) {
|
||||
derivedStateOf {
|
||||
when {
|
||||
deviceHeightDp <= 480 -> DeviceSize.Small
|
||||
deviceHeightDp <= 700 -> DeviceSize.Compact
|
||||
deviceHeightDp <= 900 -> DeviceSize.Medium
|
||||
else -> DeviceSize.Expanded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val sizeConfig by remember(deviceWidthSize, deviceHeightSize) {
|
||||
mutableStateOf(
|
||||
SizeConfig(
|
||||
widthSize = deviceWidthSize,
|
||||
heightSize = deviceHeightSize
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
val darkMode by userSettings.darkMode.collectAsStateWithLifecycle()
|
||||
val dynamicColors by userSettings.enableDynamicColors.collectAsStateWithLifecycle()
|
||||
val amoledDark by userSettings.enableAmoledDark.collectAsStateWithLifecycle()
|
||||
val enableBlur by userSettings.useBlur.collectAsStateWithLifecycle()
|
||||
val enableMultiline by userSettings.enableMultiline.collectAsStateWithLifecycle()
|
||||
val useSystemFont by userSettings.useSystemFont.collectAsStateWithLifecycle()
|
||||
val enableAnimations by userSettings.enableAnimations.collectAsStateWithLifecycle()
|
||||
|
||||
val setDarkMode = isNeedToEnableDarkMode(darkMode = darkMode)
|
||||
|
||||
val themeConfig by remember(
|
||||
darkMode,
|
||||
dynamicColors,
|
||||
amoledDark,
|
||||
enableBlur,
|
||||
enableMultiline,
|
||||
setDarkMode,
|
||||
useSystemFont
|
||||
) {
|
||||
derivedStateOf {
|
||||
ThemeConfig(
|
||||
darkMode = setDarkMode,
|
||||
dynamicColors = dynamicColors,
|
||||
selectedColorScheme = 0,
|
||||
amoledDark = amoledDark,
|
||||
enableBlur = enableBlur,
|
||||
enableMultiline = enableMultiline,
|
||||
useSystemFont = useSystemFont,
|
||||
enableAnimations = enableAnimations
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(
|
||||
LocalThemeConfig provides themeConfig,
|
||||
LocalSizeConfig provides sizeConfig,
|
||||
LocalUser provides currentUser
|
||||
) {
|
||||
AppTheme(
|
||||
useDarkTheme = themeConfig.darkMode,
|
||||
useDynamicColors = themeConfig.dynamicColors,
|
||||
selectedColorScheme = themeConfig.selectedColorScheme,
|
||||
useAmoledBackground = themeConfig.amoledDark,
|
||||
useSystemFont = themeConfig.useSystemFont
|
||||
) {
|
||||
val navController: NavHostController = rememberNavController()
|
||||
val activity = LocalActivity.current
|
||||
val context = LocalContext.current
|
||||
val startDestination by viewModel.startDestination.collectAsStateWithLifecycle()
|
||||
val isNeedToOpenAuth by viewModel.isNeedToReplaceWithAuth.collectAsStateWithLifecycle()
|
||||
val baseError by viewModel.baseError.collectAsStateWithLifecycle()
|
||||
val isNeedToShowDeniedDialog by viewModel.isNeedToShowNotificationsDeniedDialog.collectAsStateWithLifecycle()
|
||||
val isNeedToShowRationaleDialog by viewModel.isNeedToShowNotificationsRationaleDialog.collectAsStateWithLifecycle()
|
||||
|
||||
@@ -108,7 +296,25 @@ fun RootScreen(
|
||||
)
|
||||
}
|
||||
|
||||
RootErrorDialog(
|
||||
baseError = baseError,
|
||||
onDismiss = viewModel::onErrorConsumed,
|
||||
onConfirm = viewModel::onErrorConsumed
|
||||
)
|
||||
|
||||
if (startDestination != null) {
|
||||
CompositionLocalProvider(
|
||||
LocalNavRootController provides navController,
|
||||
LocalNavController provides navController
|
||||
) {
|
||||
var photoViewerInfo by rememberSaveable {
|
||||
mutableStateOf<Pair<List<String>, Int?>?>(null)
|
||||
}
|
||||
|
||||
val captchaRedirectUri by AppSettings.getCaptchaRedirectUriFlow()
|
||||
.collectAsStateWithLifecycle()
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = requireNotNull(startDestination),
|
||||
@@ -116,35 +322,84 @@ fun RootScreen(
|
||||
exitTransition = { fadeOut(animationSpec = tween(200)) }
|
||||
) {
|
||||
authNavGraph(
|
||||
onNavigateToMain = navController::navigateToMain,
|
||||
onNavigateToMain = {
|
||||
viewModel.onUserAuthenticated()
|
||||
navController.navigateToMain()
|
||||
},
|
||||
onNavigateToSettings = navController::navigateToSettings,
|
||||
navController = navController
|
||||
)
|
||||
|
||||
mainScreen(
|
||||
onError = viewModel::onError,
|
||||
onSettingsButtonClicked = navController::navigateToSettings,
|
||||
onConversationClicked = navController::navigateToMessagesHistory,
|
||||
onPhotoClicked = { url -> navController.navigateToPhotoView(listOf(url)) },
|
||||
viewModel = viewModel
|
||||
onNavigateToMessagesHistory = navController::navigateToMessagesHistory,
|
||||
onPhotoClicked = { url ->
|
||||
photoViewerInfo = listOf(url) to null
|
||||
},
|
||||
onMessageClicked = navController::navigateToMessagesHistory,
|
||||
onNavigateToCreateChat = navController::navigateToCreateChat,
|
||||
)
|
||||
|
||||
messagesHistoryScreen(
|
||||
onError = viewModel::onError,
|
||||
onBack = navController::navigateUp,
|
||||
onChatMaterialsDropdownItemClicked = navController::navigateToChatMaterials
|
||||
onNavigateToChatMaterials = navController::navigateToChatMaterials,
|
||||
onNavigateToPhotoViewer = { photos, index ->
|
||||
photoViewerInfo = photos to index
|
||||
}
|
||||
)
|
||||
chatMaterialsScreen(
|
||||
onBack = navController::navigateUp,
|
||||
onPhotoClicked = { url -> navController.navigateToPhotoView(listOf(url)) }
|
||||
onPhotoClicked = { url ->
|
||||
photoViewerInfo = listOf(url) to null
|
||||
}
|
||||
)
|
||||
createChatScreen(
|
||||
onChatCreated = { convoId ->
|
||||
navController.popBackStack()
|
||||
navController.navigateToMessagesHistory(convoId)
|
||||
},
|
||||
navController = navController
|
||||
)
|
||||
|
||||
settingsScreen(
|
||||
onBack = navController::navigateUp,
|
||||
onLogOutButtonClicked = { navController.navigateToAuth(true) },
|
||||
onLanguageItemClicked = navController::navigateToLanguagePicker
|
||||
onLanguageItemClicked = navController::navigateToLanguagePicker,
|
||||
onRestartRequired = {
|
||||
activity?.let {
|
||||
val intent = Intent(activity, MainActivity::class.java)
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
||||
activity.startActivity(intent)
|
||||
activity.finish()
|
||||
}
|
||||
}
|
||||
)
|
||||
languagePickerScreen(onBack = navController::navigateUp)
|
||||
}
|
||||
|
||||
photoViewScreen(onBack = navController::navigateUp)
|
||||
PhotoViewDialog(
|
||||
photoViewerInfo = photoViewerInfo?.let { info ->
|
||||
info.first.toImmutableList() to info.second
|
||||
},
|
||||
onDismiss = { photoViewerInfo = null }
|
||||
)
|
||||
|
||||
CaptchaScreen(
|
||||
captchaRedirectUri = captchaRedirectUri,
|
||||
onBack = {
|
||||
AppSettings.setCaptchaResult(CaptchaTokenResult.Cancelled)
|
||||
},
|
||||
onResult = { result ->
|
||||
AppSettings.setCaptchaResult(
|
||||
CaptchaTokenResult.Success(result)
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,11 +95,6 @@ class OnlineService : Service() {
|
||||
}.also { coroutine -> coroutine.invokeOnCompletion { onlineJob = null } }
|
||||
}
|
||||
|
||||
override fun onLowMemory() {
|
||||
Log.d(STATE_TAG, "onLowMemory")
|
||||
super.onLowMemory()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
Log.d(STATE_TAG, "onDestroy")
|
||||
|
||||
|
||||
@@ -16,11 +16,17 @@ import dev.meloda.fast.common.LongPollController
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.common.extensions.listenValue
|
||||
import dev.meloda.fast.common.model.LongPollState
|
||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||
import dev.meloda.fast.domain.LongPollUseCase
|
||||
import dev.meloda.fast.data.VkMemoryCache
|
||||
import dev.meloda.fast.data.UserConfig
|
||||
import dev.meloda.fast.data.processState
|
||||
import dev.meloda.fast.datastore.AppSettings
|
||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||
import dev.meloda.fast.domain.LongPollUseCase
|
||||
import dev.meloda.fast.domain.MessagesUseCase
|
||||
import dev.meloda.fast.domain.StoreUsersUseCase
|
||||
import dev.meloda.fast.model.api.data.VkGroupData
|
||||
import dev.meloda.fast.model.api.data.VkUserData
|
||||
import dev.meloda.fast.model.api.data.asDomain
|
||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||
import dev.meloda.fast.ui.R
|
||||
@@ -30,11 +36,14 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.flow.last
|
||||
import org.koin.android.ext.android.inject
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class LongPollingService : Service() {
|
||||
|
||||
@@ -42,15 +51,9 @@ class LongPollingService : Service() {
|
||||
|
||||
private val job = SupervisorJob()
|
||||
|
||||
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
|
||||
Log.e(TAG, "error: $throwable")
|
||||
|
||||
if (throwable !is NoAccessTokenException) {
|
||||
throwable.printStackTrace()
|
||||
}
|
||||
|
||||
longPollController.updateCurrentState(LongPollState.Exception)
|
||||
longPollController.setStateToApply(LongPollState.Exception)
|
||||
private val exceptionHandler =
|
||||
CoroutineExceptionHandler { _, throwable ->
|
||||
handleError(throwable)
|
||||
}
|
||||
|
||||
private val coroutineContext: CoroutineContext
|
||||
@@ -59,10 +62,14 @@ class LongPollingService : Service() {
|
||||
private val coroutineScope = CoroutineScope(coroutineContext)
|
||||
|
||||
private val longPollUseCase: LongPollUseCase by inject()
|
||||
private val messagesUseCase: MessagesUseCase by inject()
|
||||
private val storeUsersUseCase: StoreUsersUseCase by inject()
|
||||
private val updatesParser: LongPollUpdatesParser by inject()
|
||||
|
||||
private var currentJob: Job? = null
|
||||
|
||||
private val inBackground get() = AppSettings.Experimental.longPollInBackground
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Log.d(STATE_TAG, "onCreate()")
|
||||
@@ -76,21 +83,12 @@ class LongPollingService : Service() {
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (startId > 1) return START_STICKY
|
||||
|
||||
val inBackground = AppSettings.Debug.longPollInBackground
|
||||
|
||||
Log.d(
|
||||
STATE_TAG,
|
||||
"onStartCommand: asForeground: $inBackground; flags: $flags; startId: $startId;\ninstance: $this"
|
||||
)
|
||||
|
||||
if (currentJob != null) {
|
||||
currentJob?.cancel()
|
||||
currentJob = null
|
||||
}
|
||||
|
||||
coroutineScope.launch {
|
||||
currentJob = startPolling().also { it.join() }
|
||||
}
|
||||
startJob()
|
||||
|
||||
val openCategorySettingsIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
|
||||
@@ -108,11 +106,6 @@ class LongPollingService : Service() {
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
longPollController.updateCurrentState(
|
||||
if (inBackground) LongPollState.Background
|
||||
else LongPollState.InApp
|
||||
)
|
||||
|
||||
if (inBackground) {
|
||||
val notification =
|
||||
NotificationsUtils.createNotification(
|
||||
@@ -134,22 +127,40 @@ class LongPollingService : Service() {
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
private fun startJob() {
|
||||
if (currentJob != null) {
|
||||
currentJob?.cancel()
|
||||
currentJob = null
|
||||
}
|
||||
|
||||
coroutineScope.launch {
|
||||
currentJob = startPolling().also { it.join() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun startPolling(): Job {
|
||||
if (job.isCompleted || job.isCancelled) {
|
||||
Log.d(STATE_TAG, "job is completed or cancelled")
|
||||
Log.d(STATE_TAG, "Job is completed or cancelled")
|
||||
throw Exception("Job is over")
|
||||
}
|
||||
|
||||
Log.d(STATE_TAG, "job started")
|
||||
Log.d(STATE_TAG, "Starting job...")
|
||||
|
||||
return coroutineScope.launch(coroutineContext) {
|
||||
longPollController.updateCurrentState(
|
||||
if (inBackground) LongPollState.Background
|
||||
else LongPollState.InApp
|
||||
)
|
||||
|
||||
return coroutineScope.launch {
|
||||
if (UserConfig.accessToken.isEmpty()) {
|
||||
throw NoAccessTokenException
|
||||
throw NoAccessTokenException()
|
||||
}
|
||||
|
||||
var serverInfo = getServerInfo()
|
||||
?: throw LongPollException(message = "bad VK response (server info)")
|
||||
|
||||
syncLongPollHistory(serverInfo)
|
||||
|
||||
var lastUpdatesResponse: LongPollUpdates? = getUpdatesResponse(serverInfo)
|
||||
?: throw LongPollException(message = "initiation error: bad VK response (last updates)")
|
||||
|
||||
@@ -160,6 +171,7 @@ class LongPollingService : Service() {
|
||||
failCount++
|
||||
serverInfo = getServerInfo()
|
||||
?: throw LongPollException(message = "failed retrieving server info after error: bad VK response (server info #2)")
|
||||
syncLongPollHistory(serverInfo)
|
||||
lastUpdatesResponse = getUpdatesResponse(serverInfo)
|
||||
continue
|
||||
}
|
||||
@@ -179,6 +191,7 @@ class LongPollingService : Service() {
|
||||
?: throw LongPollException(
|
||||
message = "failed retrieving server info after error: bad VK response (server info #3)"
|
||||
)
|
||||
syncLongPollHistory(serverInfo)
|
||||
lastUpdatesResponse = getUpdatesResponse(serverInfo)
|
||||
}
|
||||
|
||||
@@ -196,6 +209,9 @@ class LongPollingService : Service() {
|
||||
updates.forEach(updatesParser::parseNextUpdate)
|
||||
}
|
||||
|
||||
AppSettings.LongPoll.ts = lastUpdatesResponse.ts ?: serverInfo.ts
|
||||
AppSettings.LongPoll.pts = lastUpdatesResponse.pts ?: AppSettings.LongPoll.pts
|
||||
|
||||
lastUpdatesResponse = getUpdatesResponse(serverInfo.copy(ts = newTs))
|
||||
}
|
||||
}
|
||||
@@ -204,7 +220,7 @@ class LongPollingService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getServerInfo(): VkLongPollData? = suspendCoroutine {
|
||||
private suspend fun getServerInfo(): VkLongPollData? = suspendCancellableCoroutine {
|
||||
longPollUseCase.getLongPollServer(
|
||||
needPts = true,
|
||||
version = VkConstants.LP_VERSION
|
||||
@@ -224,7 +240,7 @@ class LongPollingService : Service() {
|
||||
|
||||
private suspend fun getUpdatesResponse(
|
||||
server: VkLongPollData
|
||||
): LongPollUpdates? = suspendCoroutine {
|
||||
): LongPollUpdates? = suspendCancellableCoroutine {
|
||||
longPollUseCase.getLongPollUpdates(
|
||||
serverUrl = "https://${server.server}",
|
||||
key = server.key,
|
||||
@@ -246,6 +262,88 @@ class LongPollingService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun syncLongPollHistory(serverInfo: VkLongPollData) {
|
||||
val cursorTs = AppSettings.LongPoll.ts ?: serverInfo.ts
|
||||
val cursorPts = AppSettings.LongPoll.pts ?: serverInfo.pts
|
||||
val maxMsgId = messagesUseCase.getLocalMaxMessageId()
|
||||
|
||||
var currentTs = cursorTs
|
||||
var currentPts = cursorPts
|
||||
var more: Int?
|
||||
|
||||
do {
|
||||
val historyResponse = getLongPollHistory(
|
||||
ts = currentTs,
|
||||
pts = currentPts,
|
||||
maxMsgId = maxMsgId
|
||||
) ?: return
|
||||
|
||||
historyResponse.history.orEmpty().forEach(updatesParser::parseNextUpdate)
|
||||
|
||||
historyResponse.messages?.items.orEmpty().takeIf { it.isNotEmpty() }?.let { rawMessages ->
|
||||
val messages = rawMessages.map { it.asDomain() }
|
||||
messagesUseCase.storeMessages(messages)
|
||||
}
|
||||
|
||||
historyResponse.profiles.orEmpty().takeIf { it.isNotEmpty() }?.let { profiles ->
|
||||
val users = profiles.map(VkUserData::mapToDomain)
|
||||
VkMemoryCache.appendUsers(users)
|
||||
storeUsersUseCase(users).last()
|
||||
}
|
||||
|
||||
historyResponse.groups.orEmpty().takeIf { it.isNotEmpty() }?.let { groups ->
|
||||
VkMemoryCache.appendGroups(groups.map(VkGroupData::mapToDomain))
|
||||
}
|
||||
|
||||
currentTs = historyResponse.ts ?: historyResponse.fromPts ?: currentTs
|
||||
currentPts = historyResponse.newPts ?: historyResponse.pts ?: currentPts
|
||||
more = historyResponse.more
|
||||
|
||||
AppSettings.LongPoll.ts = currentTs
|
||||
AppSettings.LongPoll.pts = currentPts
|
||||
} while (more == 1)
|
||||
}
|
||||
|
||||
private suspend fun getLongPollHistory(
|
||||
ts: Int,
|
||||
pts: Int,
|
||||
maxMsgId: Long?
|
||||
): dev.meloda.fast.model.api.data.LongPollHistoryResponse? = suspendCancellableCoroutine {
|
||||
longPollUseCase.getLongPollHistory(
|
||||
ts = ts,
|
||||
pts = pts,
|
||||
lpVersion = VkConstants.LP_VERSION,
|
||||
maxMsgId = maxMsgId,
|
||||
eventsLimit = 1000,
|
||||
msgsLimit = 200
|
||||
).listenValue(coroutineScope) { state ->
|
||||
state.processState(
|
||||
success = { response ->
|
||||
it.resume(response)
|
||||
},
|
||||
error = { error ->
|
||||
Log.e(TAG, "getLongPollHistory: error: $error")
|
||||
it.resume(null)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleError(throwable: Throwable) {
|
||||
Log.e(TAG, "error: $throwable")
|
||||
|
||||
if (throwable !is NoAccessTokenException) {
|
||||
throwable.printStackTrace()
|
||||
}
|
||||
|
||||
coroutineScope.launch {
|
||||
delay(5.seconds)
|
||||
startJob()
|
||||
}
|
||||
|
||||
longPollController.updateCurrentState(LongPollState.Exception)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
Log.d(STATE_TAG, "onDestroy")
|
||||
longPollController.updateCurrentState(LongPollState.Stopped)
|
||||
@@ -258,10 +356,9 @@ class LongPollingService : Service() {
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onLowMemory() {
|
||||
Log.d(STATE_TAG, "onLowMemory")
|
||||
longPollController.updateCurrentState(LongPollState.Stopped)
|
||||
super.onLowMemory()
|
||||
override fun onTrimMemory(level: Int) {
|
||||
Log.d(STATE_TAG, "onTrimMemory. Level: $level")
|
||||
super.onTrimMemory(level)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -276,4 +373,4 @@ class LongPollingService : Service() {
|
||||
}
|
||||
|
||||
private data class LongPollException(override val message: String) : Throwable()
|
||||
private data object NoAccessTokenException : Throwable()
|
||||
private class NoAccessTokenException : Throwable()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.meloda.fast.service.longpolling.di
|
||||
|
||||
import dev.meloda.fast.domain.LongPollUpdatesParser
|
||||
import dev.meloda.fast.domain.LongPollUpdatesReducer
|
||||
import dev.meloda.fast.domain.LongPollUseCase
|
||||
import dev.meloda.fast.domain.LongPollUseCaseImpl
|
||||
import org.koin.core.module.dsl.singleOf
|
||||
@@ -10,4 +11,5 @@ import org.koin.dsl.module
|
||||
val longPollModule = module {
|
||||
singleOf(::LongPollUseCaseImpl) bind LongPollUseCase::class
|
||||
singleOf(::LongPollUpdatesParser)
|
||||
singleOf(::LongPollUpdatesReducer)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import android.content.Context
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import dev.meloda.fast.common.AppConstants
|
||||
import dev.meloda.fast.ui.R as UiR
|
||||
import dev.meloda.fast.ui.R
|
||||
|
||||
object NotificationsUtils {
|
||||
|
||||
@@ -28,7 +28,7 @@ object NotificationsUtils {
|
||||
actions: List<NotificationCompat.Action> = emptyList(),
|
||||
): NotificationCompat.Builder {
|
||||
val builder = NotificationCompat.Builder(context, channelId)
|
||||
.setSmallIcon(UiR.drawable.ic_fast_logo)
|
||||
.setSmallIcon(R.drawable.ic_fast_logo)
|
||||
.setContentTitle(title)
|
||||
.setPriority(priority.value)
|
||||
.setContentIntent(contentIntent)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<network-security-config xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Allow cleartext network traffic -->
|
||||
<base-config
|
||||
cleartextTrafficPermitted="true"
|
||||
cleartextTrafficPermitted="false"
|
||||
tools:ignore="InsecureBaseConfiguration">
|
||||
<trust-anchors>
|
||||
<!-- Trust pre-installed CAs -->
|
||||
|
||||
@@ -7,13 +7,13 @@ plugins {
|
||||
group = "dev.meloda.fast.buildlogic"
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget = JvmTarget.JVM_17
|
||||
jvmTarget = JvmTarget.JVM_21
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ class AndroidApplicationComposeConventionPlugin : Plugin<Project> {
|
||||
with(target) {
|
||||
apply(plugin = "com.android.application")
|
||||
apply(plugin = "org.jetbrains.kotlin.plugin.compose")
|
||||
apply(plugin = "com.github.skydoves.compose.stability.analyzer")
|
||||
|
||||
val extension = extensions.getByType<ApplicationExtension>()
|
||||
configureAndroidCompose(extension)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import dev.meloda.fast.configureKotlinAndroid
|
||||
import dev.meloda.fast.libs
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
@@ -10,12 +10,15 @@ class AndroidApplicationConventionPlugin : Plugin<Project> {
|
||||
with(target) {
|
||||
with(pluginManager) {
|
||||
apply("com.android.application")
|
||||
apply("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
extensions.configure<ApplicationExtension> {
|
||||
configureKotlinAndroid(this)
|
||||
defaultConfig.targetSdk = libs.findVersion("targetSdk").get().toString().toInt()
|
||||
defaultConfig {
|
||||
minSdk = getVersionInt("minSdk")
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
targetSdk = getVersionInt("targetSdk")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import com.android.build.gradle.LibraryExtension
|
||||
import com.android.build.api.dsl.LibraryExtension
|
||||
import dev.meloda.fast.configureAndroidCompose
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.apply
|
||||
import org.gradle.kotlin.dsl.getByType
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
|
||||
class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
|
||||
override fun apply(target: Project) {
|
||||
with(target) {
|
||||
apply(plugin = "com.android.library")
|
||||
apply(plugin = "org.jetbrains.kotlin.plugin.compose")
|
||||
apply(plugin = "com.github.skydoves.compose.stability.analyzer")
|
||||
|
||||
val extension = extensions.getByType<LibraryExtension>()
|
||||
configureAndroidCompose(extension)
|
||||
extensions.configure<LibraryExtension> {
|
||||
configureAndroidCompose(this)
|
||||
androidResources.enable = false
|
||||
defaultConfig {
|
||||
minSdk = getVersionInt("minSdk")
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import com.android.build.api.dsl.LibraryExtension
|
||||
import com.android.build.api.variant.LibraryAndroidComponentsExtension
|
||||
import com.android.build.gradle.LibraryExtension
|
||||
import dev.meloda.fast.configureKotlinAndroid
|
||||
import dev.meloda.fast.disableUnnecessaryAndroidTests
|
||||
import dev.meloda.fast.libs
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
@@ -14,14 +13,13 @@ class AndroidLibraryConventionPlugin : Plugin<Project> {
|
||||
with(target) {
|
||||
with(pluginManager) {
|
||||
apply("com.android.library")
|
||||
apply("org.jetbrains.kotlin.android")
|
||||
apply("org.jetbrains.kotlin.plugin.parcelize")
|
||||
apply("org.jetbrains.kotlin.plugin.serialization")
|
||||
}
|
||||
|
||||
extensions.configure<LibraryExtension> {
|
||||
configureKotlinAndroid(this)
|
||||
defaultConfig.targetSdk = libs.findVersion("targetSdk").get().toString().toInt()
|
||||
androidResources.enable = false
|
||||
defaultConfig.testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
extensions.configure<LibraryAndroidComponentsExtension> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import com.android.build.gradle.TestExtension
|
||||
import com.android.build.api.dsl.TestExtension
|
||||
import dev.meloda.fast.configureKotlinAndroid
|
||||
import dev.meloda.fast.libs
|
||||
import dev.meloda.fast.getVersionInt
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
@@ -10,12 +10,15 @@ class AndroidTestConventionPlugin : Plugin<Project> {
|
||||
with(target) {
|
||||
with(pluginManager) {
|
||||
apply("com.android.test")
|
||||
apply("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
extensions.configure<TestExtension> {
|
||||
configureKotlinAndroid(this)
|
||||
defaultConfig.targetSdk = libs.findVersion("targetSdk").get().toString().toInt()
|
||||
defaultConfig {
|
||||
minSdk = getVersionInt("minSdk")
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
targetSdk = getVersionInt("targetSdk")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,10 @@ import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.dependencies
|
||||
|
||||
internal fun Project.configureAndroidCompose(
|
||||
commonExtension: CommonExtension<*, *, *, *, *, *>,
|
||||
commonExtension: CommonExtension,
|
||||
) {
|
||||
commonExtension.apply {
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
buildFeatures.compose = true
|
||||
|
||||
dependencies {
|
||||
val bom = libs.findLibrary("compose-bom").get()
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package dev.meloda.fast
|
||||
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import com.android.build.api.dsl.CommonExtension
|
||||
import com.android.build.api.dsl.CompileOptions
|
||||
import com.android.build.api.dsl.LibraryExtension
|
||||
import org.gradle.api.JavaVersion
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.plugins.JavaPluginExtension
|
||||
@@ -9,53 +12,57 @@ import org.gradle.kotlin.dsl.configure
|
||||
import org.gradle.kotlin.dsl.provideDelegate
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension
|
||||
import org.jetbrains.kotlin.gradle.dsl.KotlinBaseExtension
|
||||
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension
|
||||
import org.jetbrains.kotlin.gradle.dsl.KotlinTopLevelExtension
|
||||
|
||||
internal fun Project.configureKotlinAndroid(
|
||||
commonExtension: CommonExtension<*, *, *, *, *, *>,
|
||||
commonExtension: CommonExtension,
|
||||
) {
|
||||
when (commonExtension) {
|
||||
is ApplicationExtension -> commonExtension.compileOptions(buildCompileOptions())
|
||||
is LibraryExtension -> commonExtension.compileOptions(buildCompileOptions())
|
||||
}
|
||||
|
||||
commonExtension.apply {
|
||||
compileSdk = libs.findVersion("compileSdk").get().toString().toInt()
|
||||
|
||||
defaultConfig {
|
||||
minSdk = libs.findVersion("minSdk").get().toString().toInt()
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
compileSdk = getVersionInt("compileSdk")
|
||||
buildToolsVersion = "36.1.0"
|
||||
}
|
||||
|
||||
configureKotlin<KotlinAndroidProjectExtension>()
|
||||
}
|
||||
|
||||
private fun buildCompileOptions(): CompileOptions.() -> Unit = {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
|
||||
internal fun Project.configureKotlinJvm() {
|
||||
extensions.configure<JavaPluginExtension> {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
|
||||
configureKotlin<KotlinJvmProjectExtension>()
|
||||
}
|
||||
|
||||
private inline fun <reified T : KotlinTopLevelExtension> Project.configureKotlin() = configure<T> {
|
||||
private inline fun <reified T : KotlinBaseExtension> Project.configureKotlin() = configure<T> {
|
||||
// Treat all Kotlin warnings as errors (disabled by default)
|
||||
// Override by setting warningsAsErrors=true in your ~/.gradle/gradle.properties
|
||||
val warningsAsErrors: String? by project
|
||||
when (this) {
|
||||
is KotlinAndroidProjectExtension -> compilerOptions
|
||||
is KotlinJvmProjectExtension -> compilerOptions
|
||||
else -> TODO("Unsupported project extension $this ${T::class}")
|
||||
else -> throw IllegalArgumentException("Unsupported project extension $this ${T::class}")
|
||||
}.apply {
|
||||
jvmTarget = JvmTarget.JVM_17
|
||||
jvmTarget = JvmTarget.JVM_21
|
||||
allWarningsAsErrors = warningsAsErrors.toBoolean()
|
||||
freeCompilerArgs.addAll(
|
||||
"-opt-in=kotlin.RequiresOptIn",
|
||||
// Enable experimental coroutines APIs, including Flow
|
||||
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
|
||||
"-opt-in=kotlinx.coroutines.FlowPreview"
|
||||
"-opt-in=kotlinx.coroutines.FlowPreview",
|
||||
"-Xannotation-default-target=param-property",
|
||||
"-Xcontext-parameters"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,3 +7,8 @@ import org.gradle.kotlin.dsl.getByType
|
||||
|
||||
val Project.libs
|
||||
get(): VersionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
|
||||
|
||||
|
||||
fun Project.getVersionInt(alias: String): Int {
|
||||
return libs.findVersion(alias).get().requiredVersion.toInt()
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,7 +1,6 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.android.library) apply false
|
||||
alias(libs.plugins.kotlin.android) apply false
|
||||
alias(libs.plugins.kotlin.parcelize) apply false
|
||||
alias(libs.plugins.kotlin.serialization) apply false
|
||||
alias(libs.plugins.kotlin.jvm) apply false
|
||||
@@ -9,4 +8,6 @@ plugins {
|
||||
alias(libs.plugins.room) apply false
|
||||
alias(libs.plugins.ksp) apply false
|
||||
alias(libs.plugins.module.graph) apply true
|
||||
alias(libs.plugins.versions) apply true
|
||||
alias(libs.plugins.stability.analyzer) apply false
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ object AppConstants {
|
||||
|
||||
const val INSTALL_APP_MIME_TYPE = "application/vnd.android.package-archive"
|
||||
|
||||
const val API_VERSION = "5.173"
|
||||
const val URL_OAUTH = "https://oauth.vk.com"
|
||||
const val URL_API = "https://api.vk.com/method"
|
||||
const val API_VERSION = "5.238"
|
||||
const val URL_OAUTH = "https://oauth.vk.ru"
|
||||
const val URL_API = "https://api.vk.ru/method"
|
||||
|
||||
const val NOTIFICATION_CHANNEL_UNCATEGORIZED = "uncategorized"
|
||||
const val NOTIFICATION_CHANNEL_LONG_POLLING = "long_polling"
|
||||
|
||||
@@ -5,12 +5,12 @@ object VkConstants {
|
||||
const val GROUP_FIELDS = "description,members_count,counters,status,verified"
|
||||
|
||||
const val USER_FIELDS =
|
||||
"photo_50,photo_100,photo_200,photo_400_orig,status,screen_name,online,online_mobile,last_seen,verified,sex,online_info,bdate"
|
||||
"photo_50,photo_100,photo_200,photo_400_orig,status,screen_name,online_info,last_seen,verified,sex,bdate"
|
||||
|
||||
const val ALL_FIELDS =
|
||||
"$USER_FIELDS,$GROUP_FIELDS"
|
||||
|
||||
const val LP_VERSION = 10
|
||||
const val LP_VERSION = 19
|
||||
|
||||
const val VK_APP_ID = "2274003"
|
||||
const val VK_SECRET = "hHbZxrka2uZ6jB1inYsH"
|
||||
@@ -18,6 +18,11 @@ object VkConstants {
|
||||
const val FAST_GROUP_ID = -119516304
|
||||
const val FAST_APP_ID = "6964679"
|
||||
|
||||
const val MESSENGER_APP_ID = 51453752
|
||||
const val MESSENGER_APP_SECRET = "4UyuCUsdK8pVCNoeQuGi"
|
||||
|
||||
const val MESSENGER_APP_SCOPE = 1454174
|
||||
|
||||
object Auth {
|
||||
const val SCOPE = "notify," +
|
||||
"friends," +
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package dev.meloda.fast.common.extensions
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -13,6 +13,8 @@ import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
@@ -25,11 +27,33 @@ fun <T> MutableList<T>.addIf(element: T, condition: () -> Boolean) {
|
||||
if (condition.invoke()) add(element)
|
||||
}
|
||||
|
||||
fun <T> MutableList<T>.removeIfCompat(condition: (T) -> Boolean): Boolean {
|
||||
var removed = false
|
||||
|
||||
val each = iterator()
|
||||
while (each.hasNext()) {
|
||||
if (condition(each.next())) {
|
||||
each.remove()
|
||||
removed = true
|
||||
}
|
||||
}
|
||||
|
||||
return removed
|
||||
}
|
||||
|
||||
fun <T> Flow<T>.listenValue(
|
||||
coroutineScope: CoroutineScope,
|
||||
action: suspend (T) -> Unit
|
||||
): Job = onEach(action::invoke).launchIn(coroutineScope)
|
||||
|
||||
fun CoroutineScope.launchDbRefresh(
|
||||
load: suspend () -> Unit,
|
||||
after: suspend () -> Unit
|
||||
): Job = launch {
|
||||
load()
|
||||
after()
|
||||
}
|
||||
|
||||
fun createTimerFlow(
|
||||
time: Int,
|
||||
onStartAction: (suspend () -> Unit)? = null,
|
||||
@@ -77,6 +101,11 @@ fun <T> MutableStateFlow<T>.setValue(function: (T) -> T) {
|
||||
update { newValue }
|
||||
}
|
||||
|
||||
fun <T> MutableStateFlow<T>.updateValue(block: T.() -> T) {
|
||||
val newValue = block(value)
|
||||
update { newValue }
|
||||
}
|
||||
|
||||
fun Any.asInt(): Int {
|
||||
return when (this) {
|
||||
is Number -> this.toInt()
|
||||
@@ -85,6 +114,14 @@ fun Any.asInt(): Int {
|
||||
}
|
||||
}
|
||||
|
||||
fun Any.asLong(): Long {
|
||||
return when (this) {
|
||||
is Number -> this.toLong()
|
||||
|
||||
else -> throw IllegalArgumentException("Object is not numeric")
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> Any.toList(mapper: (old: Any) -> T): List<T> {
|
||||
return when (this) {
|
||||
is List<*> -> this.mapNotNull { it?.run(mapper) }
|
||||
@@ -92,3 +129,33 @@ fun <T> Any.toList(mapper: (old: Any) -> T): List<T> {
|
||||
else -> emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> Bundle.getParcelableCompat(key: String, clazz: Class<T>): T? {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
getParcelable(key, clazz)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
getParcelable(key)
|
||||
}
|
||||
}
|
||||
|
||||
fun <T : Any> Bundle.getParcelableCompat(key: String, clazz: KClass<T>): T? {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
getParcelable(key, clazz.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
getParcelable(key)
|
||||
}
|
||||
}
|
||||
|
||||
infix fun ClosedRange<Int>.collidesWith(other: ClosedRange<Int>): Boolean {
|
||||
return this.start < other.endInclusive && other.start < this.endInclusive
|
||||
}
|
||||
|
||||
operator fun ClosedRange<Int>.minus(other: ClosedRange<Int>): ClosedRange<Int> {
|
||||
return (this.start - other.start)..(this.endInclusive - other.endInclusive)
|
||||
}
|
||||
|
||||
operator fun ClosedRange<Int>.minus(other: Int): ClosedRange<Int> {
|
||||
return (this.start - other)..(this.endInclusive - other)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package dev.meloda.fast.common.paging
|
||||
|
||||
fun canPaginate(pageSize: Int, loadedCount: Int): Boolean = loadedCount == pageSize
|
||||
|
||||
fun isPaginationExhausted(
|
||||
pageSize: Int,
|
||||
loadedCount: Int,
|
||||
hasExistingItems: Boolean
|
||||
): Boolean = loadedCount != pageSize && hasExistingItems
|
||||
|
||||
fun <T> mergePage(
|
||||
existing: List<T>,
|
||||
page: List<T>,
|
||||
offset: Int
|
||||
): List<T> = if (offset == 0) page else existing + page
|
||||
|
||||
data class LoadingFlags(
|
||||
val isLoading: Boolean,
|
||||
val isPaginating: Boolean
|
||||
)
|
||||
|
||||
fun loadingFlags(offset: Int, isLoading: Boolean): LoadingFlags = LoadingFlags(
|
||||
isLoading = offset == 0 && isLoading,
|
||||
isPaginating = offset > 0 && isLoading
|
||||
)
|
||||
@@ -86,7 +86,7 @@ object AndroidUtils {
|
||||
action = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
Settings.ACTION_SECURITY_SETTINGS
|
||||
} else {
|
||||
data = Uri.parse("package:dev.meloda.fast")
|
||||
data = Uri.parse("package:dev.meloda.fastvk")
|
||||
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
package dev.meloda.fast.common.util
|
||||
|
||||
import android.content.res.Resources
|
||||
import com.conena.nanokt.jvm.util.dayOfMonth
|
||||
import com.conena.nanokt.jvm.util.hour
|
||||
import com.conena.nanokt.jvm.util.hourOfDay
|
||||
import com.conena.nanokt.jvm.util.millisecond
|
||||
import com.conena.nanokt.jvm.util.minute
|
||||
import com.conena.nanokt.jvm.util.month
|
||||
import com.conena.nanokt.jvm.util.second
|
||||
import com.conena.nanokt.jvm.util.year
|
||||
import dev.meloda.fast.common.R
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration.Companion.days
|
||||
import kotlin.time.Duration.Companion.hours
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.Instant
|
||||
|
||||
object TimeUtils {
|
||||
|
||||
@@ -27,7 +30,11 @@ object TimeUtils {
|
||||
}.timeInMillis
|
||||
}
|
||||
|
||||
fun getLocalizedDate(resources: Resources, date: Long): String {
|
||||
fun getLocalizedDate(
|
||||
date: Long,
|
||||
yesterday: () -> String,
|
||||
today: () -> String
|
||||
): String {
|
||||
val now = Calendar.getInstance()
|
||||
val then = Calendar.getInstance().also { it.timeInMillis = date }
|
||||
|
||||
@@ -36,48 +43,41 @@ object TimeUtils {
|
||||
now.month != then.month -> "dd MMMM"
|
||||
now.dayOfMonth != then.dayOfMonth -> {
|
||||
if (now.dayOfMonth - then.dayOfMonth == 1) {
|
||||
return resources.getString(R.string.yesterday)
|
||||
return yesterday()
|
||||
} else {
|
||||
"dd MMMM"
|
||||
}
|
||||
}
|
||||
|
||||
else -> return resources.getString(R.string.today)
|
||||
else -> return today()
|
||||
}
|
||||
|
||||
return SimpleDateFormat(pattern, Locale.getDefault()).format(date)
|
||||
}
|
||||
|
||||
fun getLocalizedTime(resources: Resources, date: Long): String {
|
||||
val now = Calendar.getInstance()
|
||||
val then = Calendar.getInstance().also { it.timeInMillis = date }
|
||||
fun getLocalizedTime(
|
||||
date: Long,
|
||||
yearShort: () -> String,
|
||||
monthShort: () -> String,
|
||||
weekShort: () -> String,
|
||||
dayShort: () -> String,
|
||||
minuteShort: () -> String,
|
||||
secondShort: () -> String,
|
||||
now: () -> String
|
||||
): String {
|
||||
val now = Clock.System.now()
|
||||
val then = Instant.fromEpochMilliseconds(date)
|
||||
val diff = now - then
|
||||
|
||||
return when {
|
||||
now.year != then.year -> {
|
||||
"${now.year - then.year}${resources.getString(R.string.year_short).lowercase()}"
|
||||
}
|
||||
|
||||
now.month != then.month -> {
|
||||
"${now.month - then.month}${resources.getString(R.string.month_short).lowercase()}"
|
||||
}
|
||||
|
||||
now.dayOfMonth != then.dayOfMonth -> {
|
||||
val change = now.dayOfMonth - then.dayOfMonth
|
||||
|
||||
if (change % 7 == 0) {
|
||||
"${change / 7}${resources.getString(R.string.week_short).lowercase()}"
|
||||
} else {
|
||||
"$change${resources.getString(R.string.day_short).lowercase()}"
|
||||
}
|
||||
}
|
||||
|
||||
now.hour == then.hour && now.minute == then.minute -> {
|
||||
resources.getString(R.string.time_now).lowercase()
|
||||
}
|
||||
|
||||
else -> {
|
||||
SimpleDateFormat("HH:mm", Locale.getDefault()).format(date)
|
||||
}
|
||||
diff > 365.days -> "${diff.inWholeDays / 365}${yearShort().lowercase()}"
|
||||
diff > 30.days -> "${diff.inWholeDays / 30}${monthShort().lowercase()}"
|
||||
diff > 7.days -> "${diff.inWholeDays / 7}${weekShort().lowercase()}"
|
||||
diff > 1.days -> "${diff.inWholeDays}${dayShort().lowercase()}"
|
||||
diff > 1.hours -> "${diff.inWholeHours}h"
|
||||
diff > 1.minutes -> "${diff.inWholeMinutes}${minuteShort().lowercase()}"
|
||||
diff > 1.seconds -> "${diff.inWholeSeconds}${secondShort().lowercase()}"
|
||||
else -> now().lowercase()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.meloda.fast.common.util
|
||||
|
||||
import java.net.URLEncoder
|
||||
import java.security.MessageDigest
|
||||
|
||||
fun String.urlEncode(encoding: String = "utf-8"): String {
|
||||
return URLEncoder.encode(this, encoding)
|
||||
}
|
||||
|
||||
fun String.sha256() = this.hashString("SHA-256")
|
||||
|
||||
fun String.hashString(algorithm: String): String {
|
||||
return MessageDigest
|
||||
.getInstance(algorithm)
|
||||
.digest(this.toByteArray())
|
||||
.fold("") { str, it -> str + "%02x".format(it) }
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="yesterday">Вчера</string>
|
||||
<string name="today">Сегодня</string>
|
||||
<string name="year_short">Г</string>
|
||||
<string name="month_short">М</string>
|
||||
<string name="week_short">Н</string>
|
||||
<string name="day_short">Д</string>
|
||||
<string name="time_now">Сейчас</string>
|
||||
</resources>
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="yesterday">Yesterday</string>
|
||||
<string name="today">Today</string>
|
||||
<string name="year_short">Y</string>
|
||||
<string name="month_short">M</string>
|
||||
<string name="week_short">W</string>
|
||||
<string name="day_short">D</string>
|
||||
<string name="time_now">Now</string>
|
||||
</resources>
|
||||
@@ -14,7 +14,6 @@ dependencies {
|
||||
api(projects.core.network)
|
||||
api(projects.core.database)
|
||||
|
||||
// TODO: 11/08/2024, Danil Nikolaev: remove?
|
||||
implementation(libs.retrofit)
|
||||
implementation(libs.eithernet)
|
||||
implementation(libs.koin.android)
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
package dev.meloda.fast.data
|
||||
|
||||
import androidx.core.net.toUri
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Response
|
||||
import java.net.URLEncoder
|
||||
|
||||
class AccessTokenInterceptor : Interceptor {
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val builder = chain.request().url.newBuilder()
|
||||
val request = chain.request()
|
||||
val urlBuilder = request.url.newBuilder()
|
||||
|
||||
val uri = builder.build().toUri().toString().toUri()
|
||||
|
||||
if (uri.getQueryParameter("access_token") == null) {
|
||||
builder.addQueryParameter(
|
||||
"access_token",
|
||||
URLEncoder.encode(UserConfig.accessToken, "utf-8")
|
||||
)
|
||||
if (request.url.queryParameter("access_token") == null) {
|
||||
urlBuilder.addQueryParameter("access_token", UserConfig.accessToken)
|
||||
}
|
||||
|
||||
return chain.proceed(chain.request().newBuilder().apply { url(builder.build()) }.build())
|
||||
return chain.proceed(request.newBuilder().url(urlBuilder.build()).build())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ sealed class State<out T> {
|
||||
|
||||
data object ConnectionError : Error()
|
||||
|
||||
data object Unknown : Error()
|
||||
data object UnknownError : Error()
|
||||
|
||||
data object InternalError : Error()
|
||||
|
||||
@@ -31,21 +31,21 @@ sealed class State<out T> {
|
||||
|
||||
companion object {
|
||||
|
||||
val UNKNOWN_ERROR = Error.Unknown
|
||||
val UNKNOWN_ERROR = Error.UnknownError
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <T> State<T>.processState(
|
||||
error: (error: State.Error) -> (Unit),
|
||||
success: (data: T) -> (Unit),
|
||||
error: (error: State.Error) -> Unit,
|
||||
success: (data: T) -> Unit,
|
||||
idle: (() -> (Unit)) = {},
|
||||
loading: (() -> (Unit)) = {},
|
||||
any: () -> Unit = {}
|
||||
) {
|
||||
when (this) {
|
||||
is State.Error -> {
|
||||
error(this)
|
||||
any()
|
||||
error(this)
|
||||
}
|
||||
|
||||
State.Idle -> idle()
|
||||
@@ -53,17 +53,47 @@ inline fun <T> State<T>.processState(
|
||||
State.Loading -> loading()
|
||||
|
||||
is State.Success -> {
|
||||
success(data)
|
||||
any()
|
||||
success(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun OAuthErrorDomain?.toStateApiError(): State.Error {
|
||||
if (this == null) return State.Error.ConnectionError
|
||||
return State.Error.OAuthError(this)
|
||||
}
|
||||
|
||||
fun RestApiErrorDomain?.toStateApiError(): State.Error = when (this) {
|
||||
null -> State.Error.ConnectionError
|
||||
else -> State.Error.ApiError(VkErrorCode.parse(code), message)
|
||||
}
|
||||
|
||||
fun <T : Any> ApiResult<T, OAuthErrorDomain>.asState() = when (this) {
|
||||
is ApiResult.Success -> State.Success(this.value)
|
||||
|
||||
is ApiResult.Failure.NetworkFailure -> State.Error.ConnectionError
|
||||
is ApiResult.Failure.UnknownFailure -> State.UNKNOWN_ERROR
|
||||
is ApiResult.Failure.HttpFailure -> this.error.toStateApiError()
|
||||
is ApiResult.Failure.ApiFailure -> this.error.toStateApiError()
|
||||
}
|
||||
|
||||
fun <T : Any, N> ApiResult<T, OAuthErrorDomain>.asState(successMapper: (T) -> N) =
|
||||
when (this) {
|
||||
is ApiResult.Success -> State.Success(successMapper(this.value))
|
||||
|
||||
is ApiResult.Failure.NetworkFailure -> State.Error.ConnectionError
|
||||
is ApiResult.Failure.UnknownFailure -> State.UNKNOWN_ERROR
|
||||
is ApiResult.Failure.HttpFailure -> this.error.toStateApiError()
|
||||
is ApiResult.Failure.ApiFailure -> this.error.toStateApiError()
|
||||
}
|
||||
|
||||
fun <T : Any, E : Any> ApiResult<T, E>.success(): T =
|
||||
when (this) {
|
||||
is ApiResult.Success -> value
|
||||
else -> throw IllegalArgumentException()
|
||||
}
|
||||
|
||||
fun <T : Any> ApiResult<T, RestApiErrorDomain>.mapToState() = when (this) {
|
||||
is ApiResult.Success -> State.Success(this.value)
|
||||
|
||||
@@ -73,11 +103,12 @@ fun <T : Any> ApiResult<T, RestApiErrorDomain>.mapToState() = when (this) {
|
||||
is ApiResult.Failure.ApiFailure -> this.error.toStateApiError()
|
||||
}
|
||||
|
||||
fun <T : Any, N> ApiResult<T, RestApiErrorDomain>.mapToState(successMapper: (T) -> N) = when (this) {
|
||||
fun <T : Any, N> ApiResult<T, RestApiErrorDomain>.mapToState(successMapper: (T) -> N) =
|
||||
when (this) {
|
||||
is ApiResult.Success -> State.Success(successMapper(this.value))
|
||||
|
||||
is ApiResult.Failure.NetworkFailure -> State.Error.ConnectionError
|
||||
is ApiResult.Failure.UnknownFailure -> State.UNKNOWN_ERROR
|
||||
is ApiResult.Failure.HttpFailure -> this.error.toStateApiError()
|
||||
is ApiResult.Failure.ApiFailure -> this.error.toStateApiError()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,23 +6,27 @@ object UserConfig {
|
||||
|
||||
private const val ARG_CURRENT_USER_ID = "current_user_id"
|
||||
|
||||
var currentUserId: Int = -1
|
||||
get() = AppSettings.getInt(ARG_CURRENT_USER_ID, -1)
|
||||
var currentUserId: Long = -1
|
||||
get() = AppSettings.getLong(ARG_CURRENT_USER_ID, -1)
|
||||
set(value) {
|
||||
field = value
|
||||
AppSettings.edit { putInt(ARG_CURRENT_USER_ID, value) }
|
||||
AppSettings.edit { putLong(ARG_CURRENT_USER_ID, value) }
|
||||
}
|
||||
|
||||
var userId: Int = -1
|
||||
var userId: Long = -1
|
||||
var accessToken: String = ""
|
||||
var fastToken: String? = ""
|
||||
var trustedHash: String? = null
|
||||
var exchangeToken: String? = null
|
||||
|
||||
fun clear() {
|
||||
currentUserId = -1
|
||||
accessToken = ""
|
||||
fastToken = ""
|
||||
userId = -1
|
||||
trustedHash = null
|
||||
exchangeToken = null
|
||||
AppSettings.LongPoll.clear()
|
||||
}
|
||||
|
||||
fun isLoggedIn(): Boolean {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package dev.meloda.fast.data
|
||||
|
||||
import dev.meloda.fast.model.api.data.VkMessageData
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.model.api.domain.VkGroupDomain
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
import kotlin.math.abs
|
||||
@@ -10,23 +10,21 @@ class VkGroupsMap(
|
||||
private val groups: List<VkGroupDomain>
|
||||
) {
|
||||
|
||||
private val map: HashMap<Int, VkGroupDomain> by lazy {
|
||||
private val map: HashMap<Long, VkGroupDomain> by lazy {
|
||||
HashMap(groups.associateBy(VkGroupDomain::id))
|
||||
}
|
||||
|
||||
fun groups(): List<VkGroupDomain> = map.values.toList()
|
||||
|
||||
fun conversationGroup(conversation: VkConversation): VkGroupDomain? =
|
||||
if (!conversation.peerType.isGroup()) null
|
||||
else map[abs(conversation.id)]
|
||||
fun convoGroup(convo: VkConvo): VkGroupDomain? =
|
||||
if (!convo.peerType.isGroup()) null
|
||||
else map[abs(convo.id)]
|
||||
|
||||
fun messageActionGroup(message: VkMessage): VkGroupDomain? =
|
||||
if (message.actionMemberId == null || message.actionMemberId!! >= 0) null
|
||||
else map[abs(message.actionMemberId!!)]
|
||||
message.actionMemberId?.takeIf { it < 0 }?.let { map[abs(it)] }
|
||||
|
||||
fun messageActionGroup(message: VkMessageData): VkGroupDomain? =
|
||||
if (message.action?.memberId == null || message.action!!.memberId!! >= 0) null
|
||||
else map[abs(message.action!!.memberId!!)]
|
||||
message.action?.memberId?.takeIf { it < 0 }?.let { map[abs(it)] }
|
||||
|
||||
fun messageGroup(message: VkMessage): VkGroupDomain? =
|
||||
if (!message.isGroup()) null
|
||||
@@ -36,7 +34,7 @@ class VkGroupsMap(
|
||||
if (message.fromId >= 0) null
|
||||
else map[abs(message.fromId)]
|
||||
|
||||
fun group(groupId: Int): VkGroupDomain? = map[abs(groupId)]
|
||||
fun group(groupId: Long): VkGroupDomain? = map[abs(groupId)]
|
||||
|
||||
companion object {
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package dev.meloda.fast.data
|
||||
|
||||
import dev.meloda.fast.model.api.domain.VkContactDomain
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.model.api.domain.VkGroupDomain
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
@@ -9,11 +9,11 @@ import kotlin.math.abs
|
||||
|
||||
object VkMemoryCache {
|
||||
|
||||
private val users: HashMap<Int, VkUser> = hashMapOf()
|
||||
private val groups: HashMap<Int, VkGroupDomain> = hashMapOf()
|
||||
private val messages: HashMap<Int, VkMessage> = hashMapOf()
|
||||
private val conversations: HashMap<Int, VkConversation> = hashMapOf()
|
||||
private val contacts: HashMap<Int, VkContactDomain> = hashMapOf()
|
||||
private val users: HashMap<Long, VkUser> = hashMapOf()
|
||||
private val groups: HashMap<Long, VkGroupDomain> = hashMapOf()
|
||||
private val messages: HashMap<Long, VkMessage> = hashMapOf()
|
||||
private val convos: HashMap<Long, VkConvo> = hashMapOf()
|
||||
private val contacts: HashMap<Long, VkContactDomain> = hashMapOf()
|
||||
|
||||
fun appendUsers(users: List<VkUser>) {
|
||||
users.forEach { user -> VkMemoryCache.users[user.id] = user }
|
||||
@@ -27,9 +27,9 @@ object VkMemoryCache {
|
||||
messages.forEach { message -> VkMemoryCache.messages[message.id] = message }
|
||||
}
|
||||
|
||||
fun appendConversations(conversations: List<VkConversation>) {
|
||||
conversations.forEach { conversation ->
|
||||
VkMemoryCache.conversations[conversation.id] = conversation
|
||||
fun appendConvos(convos: List<VkConvo>) {
|
||||
convos.forEach { convo ->
|
||||
VkMemoryCache.convos[convo.id] = convo
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,83 +37,91 @@ object VkMemoryCache {
|
||||
contacts.forEach { contact -> VkMemoryCache.contacts[contact.userId] = contact }
|
||||
}
|
||||
|
||||
operator fun set(userId: Int, user: VkUser) {
|
||||
fun clear() {
|
||||
users.clear()
|
||||
groups.clear()
|
||||
messages.clear()
|
||||
convos.clear()
|
||||
contacts.clear()
|
||||
}
|
||||
|
||||
operator fun set(userId: Long, user: VkUser) {
|
||||
users[userId] = user
|
||||
}
|
||||
|
||||
operator fun set(groupId: Int, group: VkGroupDomain) {
|
||||
operator fun set(groupId: Long, group: VkGroupDomain) {
|
||||
groups[groupId] = group
|
||||
}
|
||||
|
||||
operator fun set(messageId: Int, message: VkMessage) {
|
||||
operator fun set(messageId: Long, message: VkMessage) {
|
||||
messages[messageId] = message
|
||||
}
|
||||
|
||||
operator fun set(conversationId: Int, conversation: VkConversation) {
|
||||
conversations[conversationId] = conversation
|
||||
operator fun set(convoId: Long, convo: VkConvo) {
|
||||
convos[convoId] = convo
|
||||
}
|
||||
|
||||
operator fun set(contactId: Int, contact: VkContactDomain) {
|
||||
operator fun set(contactId: Long, contact: VkContactDomain) {
|
||||
contacts[contactId] = contact
|
||||
}
|
||||
|
||||
fun getUser(id: Int): VkUser? {
|
||||
fun getUser(id: Long): VkUser? {
|
||||
return getUsers(id).firstOrNull()
|
||||
}
|
||||
|
||||
fun getUsers(vararg ids: Int): List<VkUser> {
|
||||
fun getUsers(vararg ids: Long): List<VkUser> {
|
||||
return getUsers(ids.toList())
|
||||
}
|
||||
|
||||
fun getUsers(ids: List<Int>): List<VkUser> {
|
||||
fun getUsers(ids: List<Long>): List<VkUser> {
|
||||
return ids.mapNotNull { id -> users[id] }
|
||||
}
|
||||
|
||||
fun getGroup(id: Int): VkGroupDomain? {
|
||||
fun getGroup(id: Long): VkGroupDomain? {
|
||||
return getGroups(id).firstOrNull()
|
||||
}
|
||||
|
||||
fun getGroups(vararg ids: Int): List<VkGroupDomain> {
|
||||
fun getGroups(vararg ids: Long): List<VkGroupDomain> {
|
||||
return getGroups(ids.toList())
|
||||
}
|
||||
|
||||
fun getGroups(ids: List<Int>): List<VkGroupDomain> {
|
||||
fun getGroups(ids: List<Long>): List<VkGroupDomain> {
|
||||
return ids.mapNotNull { id -> groups[id] }
|
||||
}
|
||||
|
||||
fun getMessage(id: Int): VkMessage? {
|
||||
fun getMessage(id: Long): VkMessage? {
|
||||
return getMessages(id).firstOrNull()
|
||||
}
|
||||
|
||||
fun getMessages(vararg ids: Int): List<VkMessage> {
|
||||
fun getMessages(vararg ids: Long): List<VkMessage> {
|
||||
return getMessages(ids.toList())
|
||||
}
|
||||
|
||||
fun getMessages(ids: List<Int>): List<VkMessage> {
|
||||
fun getMessages(ids: List<Long>): List<VkMessage> {
|
||||
return ids.mapNotNull { id -> messages[id] }
|
||||
}
|
||||
|
||||
fun getConversation(id: Int): VkConversation? {
|
||||
return getConversations(id).firstOrNull()
|
||||
fun getConvo(id: Long): VkConvo? {
|
||||
return getConvos(id).firstOrNull()
|
||||
}
|
||||
|
||||
fun getConversations(vararg ids: Int): List<VkConversation> {
|
||||
return getConversations(ids.toList())
|
||||
fun getConvos(vararg ids: Long): List<VkConvo> {
|
||||
return getConvos(ids.toList())
|
||||
}
|
||||
|
||||
fun getConversations(ids: List<Int>): List<VkConversation> {
|
||||
return ids.mapNotNull { id -> conversations[id] }
|
||||
fun getConvos(ids: List<Long>): List<VkConvo> {
|
||||
return ids.mapNotNull { id -> convos[id] }
|
||||
}
|
||||
|
||||
fun getContact(id: Int): VkContactDomain? {
|
||||
fun getContact(id: Long): VkContactDomain? {
|
||||
return getContacts(id).firstOrNull()
|
||||
}
|
||||
|
||||
fun getContacts(vararg ids: Int): List<VkContactDomain> {
|
||||
fun getContacts(vararg ids: Long): List<VkContactDomain> {
|
||||
return getContacts(ids.toList())
|
||||
}
|
||||
|
||||
fun getContacts(ids: List<Int>): List<VkContactDomain> {
|
||||
fun getContacts(ids: List<Long>): List<VkContactDomain> {
|
||||
return ids.mapNotNull { id -> contacts[id] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package dev.meloda.fast.data
|
||||
|
||||
import dev.meloda.fast.model.api.data.VkMessageData
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
|
||||
@@ -9,23 +9,21 @@ class VkUsersMap(
|
||||
private val users: List<VkUser>
|
||||
) {
|
||||
|
||||
private val map: HashMap<Int, VkUser> by lazy {
|
||||
private val map: HashMap<Long, VkUser> by lazy {
|
||||
HashMap(users.associateBy(VkUser::id))
|
||||
}
|
||||
|
||||
fun users(): List<VkUser> = map.values.toList()
|
||||
|
||||
fun conversationUser(conversation: VkConversation): VkUser? =
|
||||
if (!conversation.peerType.isUser()) null
|
||||
else map[conversation.id]
|
||||
fun convoUser(convo: VkConvo): VkUser? =
|
||||
if (!convo.peerType.isUser()) null
|
||||
else map[convo.id]
|
||||
|
||||
fun messageActionUser(message: VkMessage): VkUser? =
|
||||
if (message.actionMemberId == null || message.actionMemberId!! <= 0) null
|
||||
else map[message.actionMemberId]
|
||||
message.actionMemberId?.takeIf { it > 0 }?.let(map::get)
|
||||
|
||||
fun messageActionUser(message: VkMessageData): VkUser? =
|
||||
if (message.action?.memberId == null || message.action!!.memberId!! <= 0) null
|
||||
else map[message.action!!.memberId]
|
||||
message.action?.memberId?.takeIf { it > 0 }?.let(map::get)
|
||||
|
||||
fun messageUser(message: VkMessage): VkUser? =
|
||||
if (!message.isUser()) null
|
||||
@@ -35,7 +33,7 @@ class VkUsersMap(
|
||||
if (message.fromId > 0) map[message.fromId]
|
||||
else null
|
||||
|
||||
fun user(userId: Int): VkUser? = map[userId]
|
||||
fun user(userId: Long): VkUser? = map[userId]
|
||||
|
||||
companion object {
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package dev.meloda.fast.data
|
||||
|
||||
import dev.meloda.fast.model.BaseError
|
||||
import dev.meloda.fast.network.VkErrorCode
|
||||
|
||||
object VkUtils {
|
||||
|
||||
fun parseError(error: State.Error): BaseError? {
|
||||
return when (error) {
|
||||
is State.Error.ApiError -> {
|
||||
when (error.errorCode) {
|
||||
VkErrorCode.USER_AUTHORIZATION_FAILED -> {
|
||||
if (error.errorMessage.startsWith(
|
||||
"User authorization failed: user is blocked."
|
||||
)
|
||||
) {
|
||||
BaseError.AccountBlocked
|
||||
} else {
|
||||
BaseError.SessionExpired
|
||||
}
|
||||
}
|
||||
|
||||
else -> BaseError.SimpleError(message = error.errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
State.Error.ConnectionError -> BaseError.ConnectionError
|
||||
State.Error.InternalError -> BaseError.InternalError
|
||||
State.Error.UnknownError -> BaseError.UnknownError
|
||||
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,32 @@
|
||||
package dev.meloda.fast.data.api.auth
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.model.api.responses.ExchangeSilentTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetAnonymTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetExchangeTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.ValidatePhoneResponse
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import com.slack.eithernet.ApiResult
|
||||
|
||||
interface AuthRepository {
|
||||
|
||||
suspend fun logout(): ApiResult<Int, RestApiErrorDomain>
|
||||
|
||||
suspend fun validatePhone(
|
||||
validationSid: String
|
||||
): ApiResult<ValidatePhoneResponse, RestApiErrorDomain>
|
||||
|
||||
suspend fun getAnonymToken(
|
||||
clientId: String,
|
||||
clientSecret: String
|
||||
): ApiResult<GetAnonymTokenResponse, RestApiErrorDomain>
|
||||
|
||||
suspend fun exchangeSilentToken(
|
||||
anonymToken: String,
|
||||
silentToken: String,
|
||||
silentUuid: String
|
||||
): ApiResult<ExchangeSilentTokenResponse, RestApiErrorDomain>
|
||||
|
||||
suspend fun getExchangeToken(
|
||||
accessToken: String
|
||||
): ApiResult<GetExchangeTokenResponse, RestApiErrorDomain>
|
||||
}
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
package dev.meloda.fast.data.api.auth
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.model.api.requests.ExchangeSilentTokenRequest
|
||||
import dev.meloda.fast.model.api.requests.GetAnonymTokenRequest
|
||||
import dev.meloda.fast.model.api.requests.GetExchangeTokenRequest
|
||||
import dev.meloda.fast.model.api.responses.ExchangeSilentTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetAnonymTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetExchangeTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.ValidatePhoneResponse
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import dev.meloda.fast.network.mapApiDefault
|
||||
import dev.meloda.fast.network.service.auth.AuthService
|
||||
import com.slack.eithernet.ApiResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -12,9 +19,50 @@ class AuthRepositoryImpl(
|
||||
private val service: AuthService
|
||||
) : AuthRepository {
|
||||
|
||||
override suspend fun logout(): ApiResult<Int, RestApiErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
service.logout(
|
||||
clientId = VkConstants.MESSENGER_APP_ID.toString(),
|
||||
clientSecret = VkConstants.MESSENGER_APP_SECRET
|
||||
).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun validatePhone(
|
||||
validationSid: String
|
||||
): ApiResult<ValidatePhoneResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
service.validatePhone(validationSid).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun getAnonymToken(
|
||||
clientId: String,
|
||||
clientSecret: String
|
||||
): ApiResult<GetAnonymTokenResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = GetAnonymTokenRequest(
|
||||
clientId = clientId,
|
||||
clientSecret = clientSecret
|
||||
)
|
||||
|
||||
service.getAnonymToken(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun exchangeSilentToken(
|
||||
anonymToken: String,
|
||||
silentToken: String,
|
||||
silentUuid: String
|
||||
): ApiResult<ExchangeSilentTokenResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = ExchangeSilentTokenRequest(
|
||||
anonymToken = anonymToken,
|
||||
silentToken = silentToken,
|
||||
silentUuid = silentUuid
|
||||
)
|
||||
|
||||
service.exchangeSilentToken(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun getExchangeToken(
|
||||
accessToken: String
|
||||
): ApiResult<GetExchangeTokenResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = GetExchangeTokenRequest(accessToken = accessToken)
|
||||
service.getExchangeToken(requestModel.map).mapApiDefault()
|
||||
}
|
||||
}
|
||||
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package dev.meloda.fast.data.api.conversations
|
||||
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import com.slack.eithernet.ApiResult
|
||||
|
||||
interface ConversationsRepository {
|
||||
|
||||
suspend fun getConversations(
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<List<VkConversation>, RestApiErrorDomain>
|
||||
|
||||
suspend fun storeConversations(conversations: List<VkConversation>)
|
||||
suspend fun delete(peerId: Int): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun pin(peerId: Int): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun unpin(peerId: Int): ApiResult<Int, RestApiErrorDomain>
|
||||
}
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
package dev.meloda.fast.data.api.conversations
|
||||
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.data.VkGroupsMap
|
||||
import dev.meloda.fast.data.VkMemoryCache
|
||||
import dev.meloda.fast.data.VkUsersMap
|
||||
import dev.meloda.fast.database.dao.ConversationDao
|
||||
import dev.meloda.fast.model.api.data.VkContactData
|
||||
import dev.meloda.fast.model.api.data.VkGroupData
|
||||
import dev.meloda.fast.model.api.data.VkUserData
|
||||
import dev.meloda.fast.model.api.data.asDomain
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import dev.meloda.fast.model.api.domain.asEntity
|
||||
import dev.meloda.fast.model.api.requests.ConversationsDeleteRequest
|
||||
import dev.meloda.fast.model.api.requests.ConversationsGetRequest
|
||||
import dev.meloda.fast.model.api.requests.ConversationsPinRequest
|
||||
import dev.meloda.fast.model.api.requests.ConversationsUnpinRequest
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import dev.meloda.fast.network.mapApiDefault
|
||||
import dev.meloda.fast.network.mapApiResult
|
||||
import dev.meloda.fast.network.service.conversations.ConversationsService
|
||||
import com.slack.eithernet.ApiResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class ConversationsRepositoryImpl(
|
||||
private val conversationsService: ConversationsService,
|
||||
private val conversationDao: ConversationDao
|
||||
) : ConversationsRepository {
|
||||
|
||||
override suspend fun getConversations(
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<List<VkConversation>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = ConversationsGetRequest(
|
||||
count = count,
|
||||
offset = offset,
|
||||
fields = VkConstants.ALL_FIELDS,
|
||||
filter = "all",
|
||||
extended = true,
|
||||
startMessageId = null
|
||||
)
|
||||
|
||||
conversationsService.getConversations(requestModel.map).mapApiResult(
|
||||
successMapper = { apiResponse ->
|
||||
val response = apiResponse.requireResponse()
|
||||
|
||||
val profilesList = response.profiles.orEmpty().map(VkUserData::mapToDomain)
|
||||
val groupsList = response.groups.orEmpty().map(VkGroupData::mapToDomain)
|
||||
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
||||
|
||||
val usersMap = VkUsersMap.forUsers(profilesList)
|
||||
val groupsMap = VkGroupsMap.forGroups(groupsList)
|
||||
|
||||
VkMemoryCache.appendUsers(profilesList)
|
||||
VkMemoryCache.appendGroups(groupsList)
|
||||
VkMemoryCache.appendContacts(contactsList)
|
||||
|
||||
response.items.map { item ->
|
||||
val lastMessage = item.lastMessage?.asDomain()?.let { message ->
|
||||
message.copy(
|
||||
user = usersMap.messageUser(message),
|
||||
group = groupsMap.messageGroup(message),
|
||||
actionUser = usersMap.messageActionUser(message),
|
||||
actionGroup = groupsMap.messageActionGroup(message)
|
||||
).also { VkMemoryCache[message.id] = it }
|
||||
}
|
||||
item.conversation.asDomain(lastMessage).let { conversation ->
|
||||
conversation.copy(
|
||||
user = usersMap.conversationUser(conversation),
|
||||
group = groupsMap.conversationGroup(conversation)
|
||||
).also { VkMemoryCache[conversation.id] = it }
|
||||
}
|
||||
}
|
||||
},
|
||||
errorMapper = { error ->
|
||||
error?.toDomain()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun storeConversations(conversations: List<VkConversation>) {
|
||||
conversationDao.insertAll(conversations.map(VkConversation::asEntity))
|
||||
}
|
||||
|
||||
override suspend fun delete(peerId: Int): ApiResult<Int, RestApiErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val requestModel = ConversationsDeleteRequest(peerId = peerId)
|
||||
|
||||
conversationsService.delete(requestModel.map).mapApiResult(
|
||||
successMapper = { response -> response.requireResponse().lastDeletedId },
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun pin(
|
||||
peerId: Int
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = ConversationsPinRequest(peerId = peerId)
|
||||
conversationsService.pin(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun unpin(
|
||||
peerId: Int
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = ConversationsUnpinRequest(peerId = peerId)
|
||||
conversationsService.unpin(requestModel.map).mapApiDefault()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.meloda.fast.data.api.convos
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.model.ConvosFilter
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
|
||||
interface ConvosRepository {
|
||||
|
||||
suspend fun storeConvos(convos: List<VkConvo>)
|
||||
suspend fun getLocalConvos(): List<VkConvo>
|
||||
suspend fun getLocalConvoById(peerId: Long): VkConvo?
|
||||
suspend fun deleteLocalConvo(peerId: Long)
|
||||
|
||||
suspend fun getConvos(
|
||||
count: Int?,
|
||||
offset: Int?,
|
||||
filter: ConvosFilter
|
||||
): ApiResult<List<VkConvo>, RestApiErrorDomain>
|
||||
|
||||
suspend fun getConvosById(
|
||||
peerIds: List<Long>,
|
||||
extended: Boolean? = null,
|
||||
fields: String? = null
|
||||
): ApiResult<List<VkConvo>, RestApiErrorDomain>
|
||||
|
||||
suspend fun delete(peerId: Long): ApiResult<Long, RestApiErrorDomain>
|
||||
suspend fun pin(peerId: Long): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun unpin(peerId: Long): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun reorderPinned(peerIds: List<Long>): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun archive(peerId: Long): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun unarchive(peerId: Long): ApiResult<Int, RestApiErrorDomain>
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package dev.meloda.fast.data.api.convos
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.data.VkGroupsMap
|
||||
import dev.meloda.fast.data.VkMemoryCache
|
||||
import dev.meloda.fast.data.VkUsersMap
|
||||
import dev.meloda.fast.database.dao.ConvoDao
|
||||
import dev.meloda.fast.database.dao.GroupDao
|
||||
import dev.meloda.fast.database.dao.MessageDao
|
||||
import dev.meloda.fast.database.dao.UserDao
|
||||
import dev.meloda.fast.model.ConvosFilter
|
||||
import dev.meloda.fast.model.api.data.VkContactData
|
||||
import dev.meloda.fast.model.api.data.VkGroupData
|
||||
import dev.meloda.fast.model.api.data.VkUserData
|
||||
import dev.meloda.fast.model.api.data.asDomain
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.model.api.domain.VkGroupDomain
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.model.api.domain.asEntity
|
||||
import dev.meloda.fast.model.database.VkConvoEntity
|
||||
import dev.meloda.fast.model.api.requests.ConvosGetRequest
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import dev.meloda.fast.network.mapApiDefault
|
||||
import dev.meloda.fast.network.mapApiResult
|
||||
import dev.meloda.fast.network.service.convos.ConvosService
|
||||
import dev.meloda.fast.model.database.asExternalModel
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class ConvosRepositoryImpl(
|
||||
private val convosService: ConvosService,
|
||||
private val messageDao: MessageDao,
|
||||
private val userDao: UserDao,
|
||||
private val groupDao: GroupDao,
|
||||
private val convoDao: ConvoDao
|
||||
) : ConvosRepository {
|
||||
|
||||
override suspend fun storeConvos(convos: List<VkConvo>) {
|
||||
convoDao.insertAll(convos.map(VkConvo::asEntity))
|
||||
}
|
||||
|
||||
override suspend fun getLocalConvos(): List<VkConvo> = withContext(Dispatchers.IO) {
|
||||
convoDao.getAllWithMessage().map { convoWithMessage ->
|
||||
convoWithMessage.convo.asExternalModel().copy(
|
||||
lastMessage = convoWithMessage.message?.asExternalModel()
|
||||
)
|
||||
}.sorted()
|
||||
}
|
||||
|
||||
override suspend fun getLocalConvoById(peerId: Long): VkConvo? = withContext(Dispatchers.IO) {
|
||||
convoDao.getByIdWithMessage(peerId)?.let { convoWithMessage ->
|
||||
convoWithMessage.convo.asExternalModel().copy(
|
||||
lastMessage = convoWithMessage.message?.asExternalModel()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteLocalConvo(peerId: Long) {
|
||||
withContext(Dispatchers.IO) {
|
||||
convoDao.deleteById(peerId)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getConvos(
|
||||
count: Int?,
|
||||
offset: Int?,
|
||||
filter: ConvosFilter
|
||||
): ApiResult<List<VkConvo>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = ConvosGetRequest(
|
||||
count = count,
|
||||
offset = offset,
|
||||
fields = VkConstants.ALL_FIELDS,
|
||||
filter = filter,
|
||||
extended = true,
|
||||
startMessageId = null
|
||||
)
|
||||
|
||||
convosService.getConvos(requestModel.map).mapApiResult(
|
||||
successMapper = { apiResponse ->
|
||||
val response = apiResponse.requireResponse()
|
||||
|
||||
val profilesList = response.profiles.orEmpty().map(VkUserData::mapToDomain)
|
||||
val groupsList = response.groups.orEmpty().map(VkGroupData::mapToDomain)
|
||||
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
||||
|
||||
val usersMap = VkUsersMap.forUsers(profilesList)
|
||||
val groupsMap = VkGroupsMap.forGroups(groupsList)
|
||||
|
||||
VkMemoryCache.appendUsers(profilesList)
|
||||
VkMemoryCache.appendGroups(groupsList)
|
||||
VkMemoryCache.appendContacts(contactsList)
|
||||
|
||||
val convos = response.items.map { item ->
|
||||
val lastMessage = item.lastMessage?.asDomain()?.let { message ->
|
||||
message.copy(
|
||||
user = usersMap.messageUser(message),
|
||||
group = groupsMap.messageGroup(message),
|
||||
actionUser = usersMap.messageActionUser(message),
|
||||
actionGroup = groupsMap.messageActionGroup(message),
|
||||
replyMessage = message.replyMessage?.copy(
|
||||
user = usersMap.messageUser(message),
|
||||
group = groupsMap.messageGroup(message),
|
||||
actionUser = usersMap.messageActionUser(message),
|
||||
actionGroup = groupsMap.messageActionGroup(message),
|
||||
)
|
||||
).also { VkMemoryCache[message.id] = it }
|
||||
}
|
||||
item.convo.asDomain(lastMessage).let { convo ->
|
||||
convo.copy(
|
||||
user = usersMap.convoUser(convo),
|
||||
group = groupsMap.convoGroup(convo)
|
||||
).also { VkMemoryCache[convo.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
val messages = convos.mapNotNull(VkConvo::lastMessage)
|
||||
|
||||
launch(Dispatchers.IO) {
|
||||
convoDao.insertAll(convos.map(VkConvo::asEntity))
|
||||
messageDao.insertAll(messages.map(VkMessage::asEntity))
|
||||
userDao.insertAll(profilesList.map(VkUser::asEntity))
|
||||
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
||||
}
|
||||
|
||||
convos
|
||||
},
|
||||
errorMapper = { error ->
|
||||
error?.toDomain()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun getConvosById(
|
||||
peerIds: List<Long>,
|
||||
extended: Boolean?,
|
||||
fields: String?
|
||||
): ApiResult<List<VkConvo>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestParams = mutableMapOf(
|
||||
"peer_ids" to peerIds.joinToString(separator = ",")
|
||||
).apply {
|
||||
extended?.let { this["extended"] = if (it) "1" else "0" }
|
||||
fields?.let { this["fields"] = it }
|
||||
}
|
||||
|
||||
convosService.getConvosById(requestParams).mapApiResult(
|
||||
successMapper = { apiResponse ->
|
||||
val response = apiResponse.requireResponse()
|
||||
|
||||
val profilesList = response.profiles.orEmpty().map(VkUserData::mapToDomain)
|
||||
val groupsList = response.groups.orEmpty().map(VkGroupData::mapToDomain)
|
||||
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
||||
|
||||
val usersMap = VkUsersMap.forUsers(profilesList)
|
||||
val groupsMap = VkGroupsMap.forGroups(groupsList)
|
||||
|
||||
val convos = response.items.map { item ->
|
||||
item.asDomain().let { convo ->
|
||||
convo.copy(
|
||||
user = usersMap.convoUser(convo),
|
||||
group = groupsMap.convoGroup(convo)
|
||||
).also { VkMemoryCache[convo.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
launch(Dispatchers.IO) {
|
||||
convoDao.insertAll(convos.map(VkConvo::asEntity))
|
||||
userDao.insertAll(profilesList.map(VkUser::asEntity))
|
||||
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
||||
}
|
||||
|
||||
VkMemoryCache.appendUsers(profilesList)
|
||||
VkMemoryCache.appendGroups(groupsList)
|
||||
VkMemoryCache.appendContacts(contactsList)
|
||||
|
||||
convos
|
||||
},
|
||||
errorMapper = { error ->
|
||||
error?.toDomain()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun delete(peerId: Long): ApiResult<Long, RestApiErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
convosService.delete(mapOf("peer_id" to peerId.toString())).mapApiResult(
|
||||
successMapper = { response -> response.requireResponse().lastDeletedId },
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun pin(
|
||||
peerId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
convosService.pin(mapOf("peer_id" to peerId.toString())).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun unpin(
|
||||
peerId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
convosService.unpin(mapOf("peer_id" to peerId.toString())).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun reorderPinned(
|
||||
peerIds: List<Long>
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
convosService
|
||||
.reorderPinned(mapOf("peer_ids" to peerIds.joinToString(",")))
|
||||
.mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun archive(
|
||||
peerId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
convosService.archive(mapOf("peer_id" to peerId.toString())).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun unarchive(
|
||||
peerId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
convosService.unarchive(mapOf("peer_id" to peerId.toString())).mapApiDefault()
|
||||
}
|
||||
|
||||
private fun List<VkConvo>.sorted(): List<VkConvo> {
|
||||
val newConvos = toMutableList()
|
||||
|
||||
val pinnedConvos = newConvos
|
||||
.filter(VkConvo::isPinned)
|
||||
.sortedWith { c1, c2 ->
|
||||
val diff = c2.majorId - c1.majorId
|
||||
|
||||
if (diff == 0) {
|
||||
c2.minorId - c1.minorId
|
||||
} else {
|
||||
diff
|
||||
}
|
||||
}
|
||||
|
||||
newConvos.removeAll(pinnedConvos)
|
||||
newConvos.sortWith { c1, c2 ->
|
||||
(c2.lastMessage?.date ?: 0) - (c1.lastMessage?.date ?: 0)
|
||||
}
|
||||
|
||||
newConvos.addAll(0, pinnedConvos)
|
||||
return newConvos
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ class FilesRepository(
|
||||
// AUDIO_MESSAGE("audio_message")
|
||||
// }
|
||||
//
|
||||
// suspend fun getMessagesUploadServer(peerId: Int, type: FileType) =
|
||||
// suspend fun getMessagesUploadServer(peerid: Long, type: FileType) =
|
||||
// filesService.getUploadServer(
|
||||
// mapOf(
|
||||
// "peer_id" to peerId.toString(),
|
||||
|
||||
@@ -8,11 +8,13 @@ import com.slack.eithernet.ApiResult
|
||||
interface FriendsRepository {
|
||||
|
||||
suspend fun getAllFriends(
|
||||
order: String,
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<FriendsInfo, RestApiErrorDomain>
|
||||
|
||||
suspend fun getFriends(
|
||||
order: String,
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<List<VkUser>, RestApiErrorDomain>
|
||||
@@ -20,7 +22,7 @@ interface FriendsRepository {
|
||||
suspend fun getOnlineFriends(
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<List<Int>, RestApiErrorDomain>
|
||||
): ApiResult<List<Long>, RestApiErrorDomain>
|
||||
|
||||
suspend fun storeUsers(users: List<VkUser>)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package dev.meloda.fast.data.api.friends
|
||||
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.data.VkMemoryCache
|
||||
import dev.meloda.fast.database.dao.UsersDao
|
||||
import dev.meloda.fast.database.dao.UserDao
|
||||
import dev.meloda.fast.model.FriendsInfo
|
||||
import dev.meloda.fast.model.api.data.VkUserData
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
@@ -21,14 +21,15 @@ import kotlinx.coroutines.withContext
|
||||
|
||||
class FriendsRepositoryImpl(
|
||||
private val service: FriendsService,
|
||||
private val dao: UsersDao
|
||||
private val dao: UserDao
|
||||
) : FriendsRepository {
|
||||
|
||||
override suspend fun getAllFriends(
|
||||
order: String,
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<FriendsInfo, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val friends = async { getFriends(count, offset) }.await()
|
||||
val friends = async { getFriends(order, count, offset) }.await()
|
||||
.successOrElse { failure ->
|
||||
return@withContext failure
|
||||
}
|
||||
@@ -42,11 +43,12 @@ class FriendsRepositoryImpl(
|
||||
}
|
||||
|
||||
override suspend fun getFriends(
|
||||
order: String,
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<List<VkUser>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = GetFriendsRequest(
|
||||
order = "hints",
|
||||
order = order,
|
||||
count = count,
|
||||
offset = offset,
|
||||
fields = VkConstants.USER_FIELDS
|
||||
@@ -67,7 +69,7 @@ class FriendsRepositoryImpl(
|
||||
override suspend fun getOnlineFriends(
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): ApiResult<List<Int>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
): ApiResult<List<Long>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = GetOnlineFriendsRequest(
|
||||
order = "hints",
|
||||
count = count,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.meloda.fast.data.api.longpoll
|
||||
|
||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import com.slack.eithernet.ApiResult
|
||||
@@ -21,4 +22,14 @@ interface LongPollRepository {
|
||||
mode: Int,
|
||||
version: Int
|
||||
): ApiResult<LongPollUpdates, RestApiErrorDomain>
|
||||
|
||||
suspend fun getLongPollHistory(
|
||||
ts: Int,
|
||||
pts: Int,
|
||||
lpVersion: Int,
|
||||
lastN: Int? = null,
|
||||
maxMsgId: Long? = null,
|
||||
eventsLimit: Int? = null,
|
||||
msgsLimit: Int? = null
|
||||
): ApiResult<LongPollHistoryResponse, RestApiErrorDomain>
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package dev.meloda.fast.data.api.longpoll
|
||||
|
||||
import dev.meloda.fast.model.api.data.LongPollUpdates
|
||||
import dev.meloda.fast.model.api.data.LongPollHistoryResponse
|
||||
import dev.meloda.fast.model.api.data.VkLongPollData
|
||||
import dev.meloda.fast.model.api.requests.LongPollGetHistoryRequest
|
||||
import dev.meloda.fast.model.api.requests.LongPollGetUpdatesRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesGetLongPollServerRequest
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
@@ -52,4 +54,29 @@ class LongPollRepositoryImpl(
|
||||
|
||||
longPollService.getResponse(serverUrl, requestModel.map).mapDefault()
|
||||
}
|
||||
|
||||
override suspend fun getLongPollHistory(
|
||||
ts: Int,
|
||||
pts: Int,
|
||||
lpVersion: Int,
|
||||
lastN: Int?,
|
||||
maxMsgId: Long?,
|
||||
eventsLimit: Int?,
|
||||
msgsLimit: Int?
|
||||
): ApiResult<LongPollHistoryResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = LongPollGetHistoryRequest(
|
||||
ts = ts,
|
||||
pts = pts,
|
||||
lpVersion = lpVersion,
|
||||
lastN = lastN,
|
||||
maxMsgId = maxMsgId,
|
||||
eventsLimit = eventsLimit,
|
||||
msgsLimit = msgsLimit
|
||||
)
|
||||
|
||||
messagesService.getLongPollHistory(requestModel.map).mapApiResult(
|
||||
successMapper = { response -> response.requireResponse() },
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package dev.meloda.fast.data.api.messages
|
||||
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
|
||||
data class MessagesHistoryInfo(
|
||||
val messages: List<VkMessage>,
|
||||
val conversations: List<VkConversation>
|
||||
val convos: List<VkConvo>
|
||||
)
|
||||
|
||||
@@ -1,77 +1,125 @@
|
||||
package dev.meloda.fast.data.api.messages
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.model.api.data.VkChatData
|
||||
import dev.meloda.fast.model.api.domain.VkAttachment
|
||||
import dev.meloda.fast.model.api.domain.VkAttachmentHistoryMessage
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
import dev.meloda.fast.model.api.responses.MessagesGetConvoMembersResponse
|
||||
import dev.meloda.fast.model.api.responses.MessagesGetReadPeersResponse
|
||||
import dev.meloda.fast.model.api.responses.MessagesSendResponse
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import com.slack.eithernet.ApiResult
|
||||
|
||||
interface MessagesRepository {
|
||||
|
||||
suspend fun storeMessages(messages: List<VkMessage>)
|
||||
|
||||
suspend fun getLocalMessages(convoId: Long): List<VkMessage>
|
||||
suspend fun getLocalMessageById(messageId: Long): VkMessage?
|
||||
suspend fun getLocalMessageByConvoMessageId(convoId: Long, cmId: Long): VkMessage?
|
||||
suspend fun getLocalMaxMessageId(): Long?
|
||||
suspend fun deleteLocalMessages(messageIds: List<Long>)
|
||||
|
||||
suspend fun getHistory(
|
||||
conversationId: Int,
|
||||
convoId: Long,
|
||||
offset: Int?,
|
||||
count: Int?
|
||||
): ApiResult<MessagesHistoryInfo, RestApiErrorDomain>
|
||||
|
||||
suspend fun getById(
|
||||
messagesIds: List<Int>,
|
||||
peerCmIds: List<Long>?,
|
||||
peerId: Long?,
|
||||
messagesIds: List<Long>?,
|
||||
cmIds: List<Long>?,
|
||||
extended: Boolean?,
|
||||
fields: String?
|
||||
): ApiResult<List<VkMessage>, RestApiErrorDomain>
|
||||
|
||||
suspend fun send(
|
||||
peerId: Int,
|
||||
randomId: Int,
|
||||
peerId: Long,
|
||||
randomId: Long,
|
||||
message: String?,
|
||||
replyTo: Int?,
|
||||
attachments: List<VkAttachment>?
|
||||
): ApiResult<Int, RestApiErrorDomain>
|
||||
forward: String?,
|
||||
attachments: List<VkAttachment>?,
|
||||
formatData: VkMessage.FormatData?
|
||||
): ApiResult<MessagesSendResponse, RestApiErrorDomain>
|
||||
|
||||
suspend fun markAsRead(
|
||||
peerId: Int,
|
||||
startMessageId: Int?
|
||||
peerId: Long,
|
||||
startMessageId: Long?
|
||||
): ApiResult<Int, RestApiErrorDomain>
|
||||
|
||||
suspend fun getHistoryAttachments(
|
||||
peerId: Int,
|
||||
peerId: Long,
|
||||
count: Int?,
|
||||
offset: Int?,
|
||||
attachmentTypes: List<String>,
|
||||
conversationMessageId: Int
|
||||
cmId: Long
|
||||
): ApiResult<List<VkAttachmentHistoryMessage>, RestApiErrorDomain>
|
||||
|
||||
suspend fun storeMessages(messages: List<VkMessage>)
|
||||
suspend fun createChat(
|
||||
userIds: List<Long>?,
|
||||
title: String?
|
||||
): ApiResult<Long, RestApiErrorDomain>
|
||||
|
||||
// suspend fun markAsImportant(
|
||||
// params: MessagesMarkAsImportantRequest
|
||||
// ): ApiResult<List<Int>, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun pin(
|
||||
// params: MessagesPinMessageRequest
|
||||
// ): ApiResult<VkMessageData, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun unpin(
|
||||
// params: MessagesUnPinMessageRequest
|
||||
// ): ApiResult<Unit, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun delete(
|
||||
// params: MessagesDeleteRequest
|
||||
// ): ApiResult<Unit, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun edit(
|
||||
// params: MessagesEditRequest
|
||||
// ): ApiResult<Int, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun getChat(
|
||||
// params: MessagesGetChatRequest
|
||||
// ): ApiResult<VkChatData, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun getConversationMembers(
|
||||
// params: MessagesGetConversationMembersRequest
|
||||
// ): ApiResult<MessagesGetConversationMembersResponse, RestApiErrorDomain>
|
||||
//
|
||||
// suspend fun removeChatUser(
|
||||
// params: MessagesRemoveChatUserRequest
|
||||
// ): ApiResult<Int, RestApiErrorDomain>
|
||||
suspend fun pin(
|
||||
peerId: Long,
|
||||
messageId: Long? = null,
|
||||
cmId: Long? = null
|
||||
): ApiResult<VkMessage, RestApiErrorDomain>
|
||||
|
||||
suspend fun unpin(
|
||||
peerId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain>
|
||||
|
||||
suspend fun markAsImportant(
|
||||
peerId: Long,
|
||||
messageIds: List<Long>? = null,
|
||||
cmIds: List<Long>? = null,
|
||||
important: Boolean
|
||||
): ApiResult<List<Long>, RestApiErrorDomain>
|
||||
|
||||
suspend fun delete(
|
||||
peerId: Long,
|
||||
messageIds: List<Long>?,
|
||||
cmIds: List<Long>?,
|
||||
spam: Boolean,
|
||||
deleteForAll: Boolean
|
||||
): ApiResult<List<Any>, RestApiErrorDomain>
|
||||
|
||||
suspend fun edit(
|
||||
peerId: Long,
|
||||
messageId: Long? = null,
|
||||
cmId: Long? = null,
|
||||
message: String? = null,
|
||||
lat: Float? = null,
|
||||
long: Float? = null,
|
||||
attachments: List<VkAttachment>? = null,
|
||||
notParseLinks: Boolean = false,
|
||||
keepSnippets: Boolean = true,
|
||||
keepForwardedMessages: Boolean = true
|
||||
): ApiResult<Int, RestApiErrorDomain>
|
||||
|
||||
suspend fun getChat(
|
||||
chatId: Long,
|
||||
fields: String? = null
|
||||
): ApiResult<VkChatData, RestApiErrorDomain>
|
||||
|
||||
suspend fun getConvoMembers(
|
||||
peerId: Long,
|
||||
offset: Int? = null,
|
||||
count: Int? = null,
|
||||
extended: Boolean? = null,
|
||||
fields: String? = null
|
||||
): ApiResult<MessagesGetConvoMembersResponse, RestApiErrorDomain>
|
||||
|
||||
suspend fun removeChatUser(
|
||||
chatId: Long,
|
||||
memberId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain>
|
||||
|
||||
suspend fun getMessageReadPeers(
|
||||
peerId: Long,
|
||||
cmId: Long
|
||||
): ApiResult<MessagesGetReadPeersResponse, RestApiErrorDomain>
|
||||
}
|
||||
|
||||
+290
-103
@@ -1,46 +1,71 @@
|
||||
package dev.meloda.fast.data.api.messages
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.data.VkGroupsMap
|
||||
import dev.meloda.fast.data.VkMemoryCache
|
||||
import dev.meloda.fast.data.VkUsersMap
|
||||
import dev.meloda.fast.database.dao.ConvoDao
|
||||
import dev.meloda.fast.database.dao.GroupDao
|
||||
import dev.meloda.fast.database.dao.MessageDao
|
||||
import dev.meloda.fast.database.dao.UserDao
|
||||
import dev.meloda.fast.model.api.data.VkAttachmentHistoryMessageData
|
||||
import dev.meloda.fast.model.api.data.VkChatData
|
||||
import dev.meloda.fast.model.api.data.VkContactData
|
||||
import dev.meloda.fast.model.api.data.VkGroupData
|
||||
import dev.meloda.fast.model.api.data.VkUserData
|
||||
import dev.meloda.fast.model.api.data.asDomain
|
||||
import dev.meloda.fast.model.api.domain.VkAttachment
|
||||
import dev.meloda.fast.model.api.domain.VkAttachmentHistoryMessage
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import dev.meloda.fast.model.api.domain.VkGroupDomain
|
||||
import dev.meloda.fast.model.api.domain.VkMessage
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.model.api.domain.asEntity
|
||||
import dev.meloda.fast.model.database.VkMessageEntity
|
||||
import dev.meloda.fast.model.api.requests.MessagesCreateChatRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesDeleteRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesEditRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesGetByIdRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesGetChatRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesGetConvoMembersRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesGetHistoryAttachmentsRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesGetHistoryRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesMarkAsImportantRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesMarkAsReadRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesPinMessageRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesRemoveChatUserRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesSendRequest
|
||||
import dev.meloda.fast.model.api.requests.MessagesUnpinMessageRequest
|
||||
import dev.meloda.fast.model.api.responses.MessagesGetConvoMembersResponse
|
||||
import dev.meloda.fast.model.api.responses.MessagesGetReadPeersResponse
|
||||
import dev.meloda.fast.model.api.responses.MessagesSendResponse
|
||||
import dev.meloda.fast.model.database.asExternalModel
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import dev.meloda.fast.network.mapApiDefault
|
||||
import dev.meloda.fast.network.mapApiResult
|
||||
import dev.meloda.fast.network.service.messages.MessagesService
|
||||
import com.slack.eithernet.ApiResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class MessagesRepositoryImpl(
|
||||
private val messagesService: MessagesService,
|
||||
private val messageDao: MessageDao,
|
||||
private val userDao: UserDao,
|
||||
private val groupDao: GroupDao,
|
||||
private val convoDao: ConvoDao
|
||||
) : MessagesRepository {
|
||||
|
||||
override suspend fun getHistory(
|
||||
conversationId: Int,
|
||||
convoId: Long,
|
||||
offset: Int?,
|
||||
count: Int?
|
||||
): ApiResult<MessagesHistoryInfo, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesGetHistoryRequest(
|
||||
count = count,
|
||||
offset = offset,
|
||||
peerId = conversationId,
|
||||
peerId = convoId,
|
||||
extended = true,
|
||||
startMessageId = null,
|
||||
rev = null,
|
||||
@@ -68,25 +93,40 @@ class MessagesRepositoryImpl(
|
||||
user = usersMap.messageUser(message),
|
||||
group = groupsMap.messageGroup(message),
|
||||
actionUser = usersMap.messageActionUser(message),
|
||||
actionGroup = groupsMap.messageActionGroup(message)
|
||||
actionGroup = groupsMap.messageActionGroup(message),
|
||||
replyMessage = message.replyMessage.let { replyMessage ->
|
||||
replyMessage?.copy(
|
||||
user = usersMap.messageUser(replyMessage),
|
||||
group = groupsMap.messageGroup(replyMessage),
|
||||
actionUser = usersMap.messageActionUser(replyMessage),
|
||||
actionGroup = groupsMap.messageActionGroup(replyMessage),
|
||||
)
|
||||
}
|
||||
).also { VkMemoryCache[message.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
val conversations = response.conversations.orEmpty().map { item ->
|
||||
val convos = response.convos.orEmpty().map { item ->
|
||||
val message = messages.firstOrNull { it.id == item.lastMessageId }
|
||||
item.asDomain(message)
|
||||
.let { conversation ->
|
||||
conversation.copy(
|
||||
user = usersMap.conversationUser(conversation),
|
||||
group = groupsMap.conversationGroup(conversation)
|
||||
).also { VkMemoryCache[conversation.id] = it }
|
||||
.let { convo ->
|
||||
convo.copy(
|
||||
user = usersMap.convoUser(convo),
|
||||
group = groupsMap.convoGroup(convo)
|
||||
).also { VkMemoryCache[convo.id] = it }
|
||||
}
|
||||
}
|
||||
|
||||
launch(Dispatchers.IO) {
|
||||
convoDao.insertAll(convos.map(VkConvo::asEntity))
|
||||
messageDao.insertAll(messages.map(VkMessage::asEntity))
|
||||
userDao.insertAll(profilesList.map(VkUser::asEntity))
|
||||
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
||||
}
|
||||
|
||||
MessagesHistoryInfo(
|
||||
messages = messages,
|
||||
conversations = conversations
|
||||
convos = convos
|
||||
)
|
||||
},
|
||||
errorMapper = { error ->
|
||||
@@ -96,12 +136,18 @@ class MessagesRepositoryImpl(
|
||||
}
|
||||
|
||||
override suspend fun getById(
|
||||
messagesIds: List<Int>,
|
||||
peerCmIds: List<Long>?,
|
||||
peerId: Long?,
|
||||
messagesIds: List<Long>?,
|
||||
cmIds: List<Long>?,
|
||||
extended: Boolean?,
|
||||
fields: String?
|
||||
): ApiResult<List<VkMessage>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesGetByIdRequest(
|
||||
peerCmIds = peerCmIds,
|
||||
peerId = peerId,
|
||||
messagesIds = messagesIds,
|
||||
cmIds = cmIds,
|
||||
extended = extended,
|
||||
fields = fields
|
||||
)
|
||||
@@ -111,45 +157,70 @@ class MessagesRepositoryImpl(
|
||||
val response = apiResponse.requireResponse()
|
||||
|
||||
val messages = response.items
|
||||
val usersMap =
|
||||
VkUsersMap.forUsers(response.profiles.orEmpty().map(VkUserData::mapToDomain))
|
||||
val groupsMap =
|
||||
VkGroupsMap.forGroups(response.groups.orEmpty().map(VkGroupData::mapToDomain))
|
||||
|
||||
messages.map { message ->
|
||||
val profilesList = response.profiles.orEmpty().map(VkUserData::mapToDomain)
|
||||
val groupsList = response.groups.orEmpty().map(VkGroupData::mapToDomain)
|
||||
val contactsList = response.contacts.orEmpty().map(VkContactData::mapToDomain)
|
||||
|
||||
val usersMap = VkUsersMap.forUsers(profilesList)
|
||||
val groupsMap = VkGroupsMap.forGroups(groupsList)
|
||||
|
||||
val domainMessages = messages.map { message ->
|
||||
message.asDomain().copy(
|
||||
user = usersMap.messageUser(message),
|
||||
group = groupsMap.messageGroup(message),
|
||||
actionUser = usersMap.messageActionUser(message),
|
||||
actionGroup = groupsMap.messageActionGroup(message)
|
||||
actionGroup = groupsMap.messageActionGroup(message),
|
||||
replyMessage = message.replyMessage?.asDomain().let { replyMessage ->
|
||||
replyMessage?.copy(
|
||||
user = usersMap.messageUser(replyMessage),
|
||||
group = groupsMap.messageGroup(replyMessage),
|
||||
actionUser = usersMap.messageActionUser(replyMessage),
|
||||
actionGroup = groupsMap.messageActionGroup(replyMessage),
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
launch(Dispatchers.IO) {
|
||||
messageDao.insertAll(domainMessages.map(VkMessage::asEntity))
|
||||
userDao.insertAll(profilesList.map(VkUser::asEntity))
|
||||
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
||||
}
|
||||
|
||||
VkMemoryCache.appendUsers(profilesList)
|
||||
VkMemoryCache.appendGroups(groupsList)
|
||||
VkMemoryCache.appendContacts(contactsList)
|
||||
|
||||
domainMessages
|
||||
},
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun send(
|
||||
peerId: Int,
|
||||
randomId: Int,
|
||||
peerId: Long,
|
||||
randomId: Long,
|
||||
message: String?,
|
||||
replyTo: Int?,
|
||||
attachments: List<VkAttachment>?
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
forward: String?,
|
||||
attachments: List<VkAttachment>?,
|
||||
formatData: VkMessage.FormatData?
|
||||
): ApiResult<MessagesSendResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesSendRequest(
|
||||
peerId = peerId,
|
||||
randomId = randomId,
|
||||
message = message,
|
||||
replyTo = replyTo,
|
||||
attachments = attachments
|
||||
forward = forward,
|
||||
attachments = attachments,
|
||||
formatData = formatData
|
||||
)
|
||||
|
||||
messagesService.send(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun markAsRead(
|
||||
peerId: Int,
|
||||
startMessageId: Int?
|
||||
peerId: Long,
|
||||
startMessageId: Long?
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesMarkAsReadRequest(
|
||||
peerId = peerId,
|
||||
@@ -160,11 +231,11 @@ class MessagesRepositoryImpl(
|
||||
}
|
||||
|
||||
override suspend fun getHistoryAttachments(
|
||||
peerId: Int,
|
||||
peerId: Long,
|
||||
count: Int?,
|
||||
offset: Int?,
|
||||
attachmentTypes: List<String>,
|
||||
conversationMessageId: Int
|
||||
cmId: Long
|
||||
): ApiResult<List<VkAttachmentHistoryMessage>, RestApiErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesGetHistoryAttachmentsRequest(
|
||||
@@ -174,7 +245,7 @@ class MessagesRepositoryImpl(
|
||||
offset = offset,
|
||||
preserveOrder = true,
|
||||
attachmentTypes = attachmentTypes,
|
||||
conversationMessageId = conversationMessageId,
|
||||
cmId = cmId,
|
||||
fields = VkConstants.ALL_FIELDS
|
||||
)
|
||||
|
||||
@@ -190,6 +261,11 @@ class MessagesRepositoryImpl(
|
||||
VkMemoryCache.appendGroups(groupsList)
|
||||
VkMemoryCache.appendContacts(contactsList)
|
||||
|
||||
launch(Dispatchers.IO) {
|
||||
userDao.insertAll(profilesList.map(VkUser::asEntity))
|
||||
groupDao.insertAll(groupsList.map(VkGroupDomain::asEntity))
|
||||
}
|
||||
|
||||
response.items.map(VkAttachmentHistoryMessageData::toDomain)
|
||||
},
|
||||
errorMapper = { error ->
|
||||
@@ -198,81 +274,192 @@ class MessagesRepositoryImpl(
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun createChat(
|
||||
userIds: List<Long>?,
|
||||
title: String?
|
||||
): ApiResult<Long, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesCreateChatRequest(
|
||||
userIds = userIds,
|
||||
title = title
|
||||
)
|
||||
|
||||
messagesService.createChat(requestModel.map).mapApiResult(
|
||||
successMapper = { apiResponse ->
|
||||
apiResponse.requireResponse().chatId
|
||||
},
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun pin(
|
||||
peerId: Long,
|
||||
messageId: Long?,
|
||||
cmId: Long?
|
||||
): ApiResult<VkMessage, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesPinMessageRequest(
|
||||
peerId = peerId,
|
||||
messageId = messageId,
|
||||
cmId = cmId
|
||||
)
|
||||
|
||||
messagesService.pin(requestModel.map).mapApiResult(
|
||||
successMapper = { apiResponse ->
|
||||
apiResponse.requireResponse().asDomain()
|
||||
},
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun unpin(
|
||||
peerId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesUnpinMessageRequest(peerId = peerId)
|
||||
messagesService.unpin(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun markAsImportant(
|
||||
peerId: Long,
|
||||
messageIds: List<Long>?,
|
||||
cmIds: List<Long>?,
|
||||
important: Boolean
|
||||
): ApiResult<List<Long>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesMarkAsImportantRequest(
|
||||
messagesIds = messageIds.orEmpty(),
|
||||
important = important
|
||||
)
|
||||
messagesService.markAsImportant(requestModel.map).mapApiResult(
|
||||
successMapper = { apiResponse ->
|
||||
apiResponse.requireResponse().marked.map { it.cmId }
|
||||
},
|
||||
errorMapper = { error -> error?.toDomain() }
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun delete(
|
||||
peerId: Long,
|
||||
messageIds: List<Long>?,
|
||||
cmIds: List<Long>?,
|
||||
spam: Boolean,
|
||||
deleteForAll: Boolean
|
||||
): ApiResult<List<Any>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesDeleteRequest(
|
||||
peerId = peerId,
|
||||
messagesIds = messageIds,
|
||||
cmIds = cmIds,
|
||||
isSpam = spam,
|
||||
deleteForAll = deleteForAll
|
||||
)
|
||||
messagesService.delete(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun storeMessages(messages: List<VkMessage>) {
|
||||
messageDao.insertAll(messages.map(VkMessage::asEntity))
|
||||
}
|
||||
|
||||
// override suspend fun markAsImportant(
|
||||
// params: MessagesMarkAsImportantRequest
|
||||
// ): ApiResult<List<Int>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.markAsImportant(params.map).mapResult(
|
||||
// successMapper = { response -> response.requireResponse() },
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun pin(
|
||||
// params: MessagesPinMessageRequest
|
||||
// ): ApiResult<VkMessageData, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.pin(params.map).mapResult(
|
||||
// successMapper = { response -> response.requireResponse() },
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun unpin(
|
||||
// params: MessagesUnPinMessageRequest
|
||||
// ): ApiResult<Unit, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.unpin(params.map).mapResult(
|
||||
// successMapper = {},
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun delete(
|
||||
// params: MessagesDeleteRequest
|
||||
// ): ApiResult<Unit, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.delete(params.map).mapResult(
|
||||
// successMapper = {},
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun edit(
|
||||
// params: MessagesEditRequest
|
||||
// ): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.edit(params.map).mapResult(
|
||||
// successMapper = { response -> response.requireResponse() },
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun getChat(
|
||||
// params: MessagesGetChatRequest
|
||||
// ): ApiResult<VkChatData, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.getChat(params.map).mapResult(
|
||||
// successMapper = { response -> response.requireResponse() },
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun getConversationMembers(
|
||||
// params: MessagesGetConversationMembersRequest
|
||||
// ): ApiResult<MessagesGetConversationMembersResponse, RestApiErrorDomain> =
|
||||
// withContext(Dispatchers.IO) {
|
||||
// messagesService.getConversationMembers(params.map).mapResult(
|
||||
// successMapper = { response -> response.requireResponse() },
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// override suspend fun removeChatUser(
|
||||
// params: MessagesRemoveChatUserRequest
|
||||
// ): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
// messagesService.removeChatUser(params.map).mapResult(
|
||||
// successMapper = { response -> response.requireResponse() },
|
||||
// errorMapper = { error -> error?.toDomain() }
|
||||
// )
|
||||
// }
|
||||
}
|
||||
override suspend fun getLocalMessages(convoId: Long): List<VkMessage> = withContext(Dispatchers.IO) {
|
||||
messageDao.getAll(convoId).map(VkMessageEntity::asExternalModel)
|
||||
}
|
||||
|
||||
override suspend fun getLocalMessageById(messageId: Long): VkMessage? = withContext(Dispatchers.IO) {
|
||||
messageDao.getById(messageId)?.asExternalModel()
|
||||
}
|
||||
|
||||
override suspend fun getLocalMessageByConvoMessageId(convoId: Long, cmId: Long): VkMessage? = withContext(Dispatchers.IO) {
|
||||
messageDao.getByConvoMessageId(convoId, cmId)?.asExternalModel()
|
||||
}
|
||||
|
||||
override suspend fun getLocalMaxMessageId(): Long? = withContext(Dispatchers.IO) {
|
||||
messageDao.getMaxId()
|
||||
}
|
||||
|
||||
override suspend fun deleteLocalMessages(messageIds: List<Long>) {
|
||||
withContext(Dispatchers.IO) {
|
||||
messageDao.deleteByIds(messageIds)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun edit(
|
||||
peerId: Long,
|
||||
messageId: Long?,
|
||||
cmId: Long?,
|
||||
message: String?,
|
||||
lat: Float?,
|
||||
long: Float?,
|
||||
attachments: List<VkAttachment>?,
|
||||
notParseLinks: Boolean,
|
||||
keepSnippets: Boolean,
|
||||
keepForwardedMessages: Boolean
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesEditRequest(
|
||||
peerId = peerId,
|
||||
messageId = messageId,
|
||||
cmId = cmId,
|
||||
message = message,
|
||||
lat = lat,
|
||||
long = long,
|
||||
attachments = attachments,
|
||||
notParseLinks = notParseLinks,
|
||||
keepSnippets = keepSnippets,
|
||||
keepForwardedMessages = keepForwardedMessages
|
||||
)
|
||||
|
||||
messagesService.edit(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun getChat(
|
||||
chatId: Long,
|
||||
fields: String?
|
||||
): ApiResult<VkChatData, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesGetChatRequest(
|
||||
chatId = chatId,
|
||||
fields = fields
|
||||
)
|
||||
|
||||
messagesService.getChat(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun getConvoMembers(
|
||||
peerId: Long,
|
||||
offset: Int?,
|
||||
count: Int?,
|
||||
extended: Boolean?,
|
||||
fields: String?
|
||||
): ApiResult<MessagesGetConvoMembersResponse, RestApiErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesGetConvoMembersRequest(
|
||||
peerId = peerId,
|
||||
offset = offset,
|
||||
count = count,
|
||||
extended = extended,
|
||||
fields = fields
|
||||
)
|
||||
|
||||
messagesService.getConvoMembers(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun removeChatUser(
|
||||
chatId: Long,
|
||||
memberId: Long
|
||||
): ApiResult<Int, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = MessagesRemoveChatUserRequest(
|
||||
chatId = chatId,
|
||||
memberId = memberId
|
||||
)
|
||||
|
||||
messagesService.removeChatUser(requestModel.map).mapApiDefault()
|
||||
}
|
||||
|
||||
override suspend fun getMessageReadPeers(
|
||||
peerId: Long,
|
||||
cmId: Long
|
||||
): ApiResult<MessagesGetReadPeersResponse, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
messagesService.getMessageReadPeers(
|
||||
mapOf(
|
||||
"peer_id" to peerId.toString(),
|
||||
"cmid" to cmId.toString(),
|
||||
"extended" to "1",
|
||||
"fields" to VkConstants.USER_FIELDS
|
||||
)
|
||||
).mapApiDefault()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package dev.meloda.fast.data.api.oauth
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.model.api.responses.AuthDirectResponse
|
||||
import dev.meloda.fast.model.api.responses.GetSilentTokenResponse
|
||||
import dev.meloda.fast.network.OAuthErrorDomain
|
||||
|
||||
interface OAuthRepository {
|
||||
|
||||
@@ -11,5 +14,15 @@ interface OAuthRepository {
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?
|
||||
): AuthDirectResponse
|
||||
): ApiResult<AuthDirectResponse, OAuthErrorDomain>
|
||||
|
||||
suspend fun getSilentToken(
|
||||
login: String,
|
||||
password: String,
|
||||
forceSms: Boolean,
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?,
|
||||
successToken: String?
|
||||
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain>
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package dev.meloda.fast.data.api.oauth
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.common.VkConstants
|
||||
import dev.meloda.fast.model.api.requests.AuthDirectRequest
|
||||
import dev.meloda.fast.model.api.responses.AuthDirectResponse
|
||||
import dev.meloda.fast.model.api.responses.GetSilentTokenResponse
|
||||
import dev.meloda.fast.network.OAuthErrorDomain
|
||||
import dev.meloda.fast.network.ValidationType
|
||||
import dev.meloda.fast.network.VkOAuthError
|
||||
import dev.meloda.fast.network.VkOAuthErrorType
|
||||
import dev.meloda.fast.network.mapResult
|
||||
import dev.meloda.fast.network.service.oauth.OAuthService
|
||||
import com.slack.eithernet.ApiResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -18,37 +24,194 @@ class OAuthRepositoryImpl(
|
||||
forceSms: Boolean,
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?
|
||||
): AuthDirectResponse = withContext(Dispatchers.IO) {
|
||||
captchaKey: String?,
|
||||
): ApiResult<AuthDirectResponse, OAuthErrorDomain> = withContext(Dispatchers.IO) {
|
||||
val requestModel = AuthDirectRequest(
|
||||
grantType = VkConstants.Auth.GrantType.PASSWORD,
|
||||
clientId = VkConstants.VK_APP_ID,
|
||||
clientSecret = VkConstants.VK_SECRET,
|
||||
clientId = VkConstants.MESSENGER_APP_ID.toString(),
|
||||
clientSecret = VkConstants.MESSENGER_APP_SECRET,
|
||||
username = login,
|
||||
password = password,
|
||||
scope = VkConstants.Auth.SCOPE,
|
||||
scope = VkConstants.MESSENGER_APP_SCOPE.toString(),
|
||||
validationForceSms = forceSms,
|
||||
validationCode = validationCode,
|
||||
captchaSid = captchaSid,
|
||||
captchaKey = captchaKey,
|
||||
)
|
||||
|
||||
when (val result = oAuthService.auth(requestModel.map)) {
|
||||
is ApiResult.Success -> result.value
|
||||
oAuthService.auth(requestModel.map).mapResult(
|
||||
successMapper = {
|
||||
it
|
||||
},
|
||||
errorMapper = { response ->
|
||||
val error = response?.error?.let(VkOAuthError::parse)
|
||||
val errorType = response?.errorType?.let(VkOAuthErrorType::parse)
|
||||
|
||||
is ApiResult.Failure.HttpFailure -> {
|
||||
requireNotNull(result.error)
|
||||
when (error) {
|
||||
null -> OAuthErrorDomain.UnknownError
|
||||
|
||||
VkOAuthError.FLOOD_CONTROL -> OAuthErrorDomain.TooManyTriesError
|
||||
|
||||
VkOAuthError.NEED_VALIDATION -> {
|
||||
if (response.banInfo != null) {
|
||||
val info = requireNotNull(response.banInfo)
|
||||
|
||||
OAuthErrorDomain.UserBannedError(
|
||||
memberName = info.memberName,
|
||||
message = info.message,
|
||||
accessToken = info.accessToken,
|
||||
restoreUrl = info.restoreUrl
|
||||
)
|
||||
} else {
|
||||
OAuthErrorDomain.ValidationRequiredError(
|
||||
description = response.errorDescription.orEmpty(),
|
||||
validationType = response.validationType.orEmpty()
|
||||
.let(ValidationType::parse),
|
||||
validationSid = response.validationSid.orEmpty(),
|
||||
phoneMask = response.phoneMask.orEmpty(),
|
||||
redirectUri = response.redirectUri.orEmpty(),
|
||||
validationResend = response.validationResend,
|
||||
restoreIfCannotGetCode = response.restoreIfCannotGetCode
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is ApiResult.Failure.ApiFailure -> TODO()
|
||||
|
||||
is ApiResult.Failure.NetworkFailure -> {
|
||||
// TODO: 13/07/2024, Danil Nikolaev: implement showing network error
|
||||
TODO()
|
||||
VkOAuthError.NEED_CAPTCHA -> {
|
||||
OAuthErrorDomain.CaptchaRequiredError(
|
||||
captchaSid = response.captchaSid.orEmpty(),
|
||||
captchaImageUrl = response.captchaImage.orEmpty(),
|
||||
redirectUri = response.redirectUri
|
||||
)
|
||||
}
|
||||
is ApiResult.Failure.UnknownFailure -> TODO()
|
||||
|
||||
else -> throw IllegalStateException("Unknown result")
|
||||
VkOAuthError.INVALID_CLIENT -> {
|
||||
OAuthErrorDomain.InvalidCredentialsError
|
||||
}
|
||||
|
||||
VkOAuthError.INVALID_REQUEST -> {
|
||||
when (errorType) {
|
||||
null -> OAuthErrorDomain.UnknownError
|
||||
|
||||
VkOAuthErrorType.WRONG_OTP -> {
|
||||
OAuthErrorDomain.WrongValidationCode
|
||||
}
|
||||
|
||||
VkOAuthErrorType.WRONG_OTP_FORMAT -> {
|
||||
OAuthErrorDomain.WrongValidationCodeFormat
|
||||
}
|
||||
|
||||
VkOAuthErrorType.PASSWORD_BRUTEFORCE_ATTEMPT -> {
|
||||
OAuthErrorDomain.TooManyTriesError
|
||||
}
|
||||
|
||||
VkOAuthErrorType.USERNAME_OR_PASSWORD_IS_INCORRECT -> {
|
||||
OAuthErrorDomain.InvalidCredentialsError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
VkOAuthError.UNKNOWN -> OAuthErrorDomain.UnknownError
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun getSilentToken(
|
||||
login: String,
|
||||
password: String,
|
||||
forceSms: Boolean,
|
||||
validationCode: String?,
|
||||
captchaSid: String?,
|
||||
captchaKey: String?,
|
||||
successToken: String?
|
||||
): ApiResult<GetSilentTokenResponse, OAuthErrorDomain> =
|
||||
withContext(Dispatchers.IO) {
|
||||
val requestModel = AuthDirectRequest(
|
||||
grantType = VkConstants.Auth.GrantType.PASSWORD,
|
||||
clientId = VkConstants.MESSENGER_APP_ID.toString(),
|
||||
clientSecret = VkConstants.MESSENGER_APP_SECRET,
|
||||
username = login,
|
||||
password = password,
|
||||
scope = VkConstants.MESSENGER_APP_SCOPE.toString(),
|
||||
validationForceSms = forceSms,
|
||||
validationCode = validationCode,
|
||||
captchaSid = captchaSid,
|
||||
captchaKey = captchaKey,
|
||||
successToken = successToken
|
||||
)
|
||||
|
||||
oAuthService.getSilentToken(requestModel.map).mapResult(
|
||||
successMapper = { it },
|
||||
errorMapper = { response ->
|
||||
val error = response?.error?.let(VkOAuthError::parse)
|
||||
val errorType = response?.errorType?.let(VkOAuthErrorType::parse)
|
||||
|
||||
when (error) {
|
||||
null -> OAuthErrorDomain.UnknownError
|
||||
|
||||
VkOAuthError.FLOOD_CONTROL -> OAuthErrorDomain.TooManyTriesError
|
||||
|
||||
VkOAuthError.NEED_VALIDATION -> {
|
||||
if (response.banInfo != null) {
|
||||
val info = requireNotNull(response.banInfo)
|
||||
|
||||
OAuthErrorDomain.UserBannedError(
|
||||
memberName = info.memberName,
|
||||
message = info.message,
|
||||
accessToken = info.accessToken,
|
||||
restoreUrl = info.restoreUrl
|
||||
)
|
||||
} else {
|
||||
OAuthErrorDomain.ValidationRequiredError(
|
||||
description = response.errorDescription.orEmpty(),
|
||||
validationType = response.validationType.orEmpty()
|
||||
.let(ValidationType::parse),
|
||||
validationSid = response.validationSid.orEmpty(),
|
||||
phoneMask = response.phoneMask.orEmpty(),
|
||||
redirectUri = response.redirectUri.orEmpty(),
|
||||
validationResend = response.validationResend,
|
||||
restoreIfCannotGetCode = response.restoreIfCannotGetCode
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
VkOAuthError.NEED_CAPTCHA -> {
|
||||
OAuthErrorDomain.CaptchaRequiredError(
|
||||
captchaSid = response.captchaSid.orEmpty(),
|
||||
captchaImageUrl = response.captchaImage.orEmpty(),
|
||||
redirectUri = response.redirectUri
|
||||
)
|
||||
}
|
||||
|
||||
VkOAuthError.INVALID_CLIENT -> {
|
||||
OAuthErrorDomain.InvalidCredentialsError
|
||||
}
|
||||
|
||||
VkOAuthError.INVALID_REQUEST -> {
|
||||
when (errorType) {
|
||||
null -> OAuthErrorDomain.UnknownError
|
||||
|
||||
VkOAuthErrorType.WRONG_OTP -> {
|
||||
OAuthErrorDomain.WrongValidationCode
|
||||
}
|
||||
|
||||
VkOAuthErrorType.WRONG_OTP_FORMAT -> {
|
||||
OAuthErrorDomain.WrongValidationCodeFormat
|
||||
}
|
||||
|
||||
VkOAuthErrorType.PASSWORD_BRUTEFORCE_ATTEMPT -> {
|
||||
OAuthErrorDomain.TooManyTriesError
|
||||
}
|
||||
|
||||
VkOAuthErrorType.USERNAME_OR_PASSWORD_IS_INCORRECT -> {
|
||||
OAuthErrorDomain.InvalidCredentialsError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
VkOAuthError.UNKNOWN -> OAuthErrorDomain.UnknownError
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ class PhotosRepository(
|
||||
private val photosService: PhotosService
|
||||
) {
|
||||
|
||||
suspend fun getMessagesUploadServer(peerId: Int) =
|
||||
suspend fun getMessagesUploadServer(peerId: Long) =
|
||||
photosService.getUploadServer(mapOf("peer_id" to peerId.toString()))
|
||||
|
||||
suspend fun uploadPhoto(url: String, photo: MultipartBody.Part) =
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
package dev.meloda.fast.data.api.users
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import com.slack.eithernet.ApiResult
|
||||
|
||||
interface UsersRepository {
|
||||
|
||||
suspend fun get(
|
||||
userIds: List<Int>?,
|
||||
userIds: List<Long>?,
|
||||
fields: String?,
|
||||
nomCase: String?
|
||||
): ApiResult<List<VkUser>, RestApiErrorDomain>
|
||||
|
||||
suspend fun getLocalUsers(userIds: List<Int>): List<VkUser>
|
||||
suspend fun getLocalUsers(userIds: List<Long>): List<VkUser>
|
||||
|
||||
suspend fun storeUsers(users: List<VkUser>)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package dev.meloda.fast.data.api.users
|
||||
|
||||
import com.slack.eithernet.ApiResult
|
||||
import dev.meloda.fast.data.VkMemoryCache
|
||||
import dev.meloda.fast.database.dao.UsersDao
|
||||
import dev.meloda.fast.database.dao.UserDao
|
||||
import dev.meloda.fast.model.api.data.VkUserData
|
||||
import dev.meloda.fast.model.api.domain.VkUser
|
||||
import dev.meloda.fast.model.api.domain.asEntity
|
||||
@@ -11,18 +12,17 @@ import dev.meloda.fast.model.database.asExternalModel
|
||||
import dev.meloda.fast.network.RestApiErrorDomain
|
||||
import dev.meloda.fast.network.mapApiResult
|
||||
import dev.meloda.fast.network.service.users.UsersService
|
||||
import com.slack.eithernet.ApiResult
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class UsersRepositoryImpl(
|
||||
private val service: UsersService,
|
||||
private val dao: UsersDao
|
||||
private val dao: UserDao
|
||||
) : UsersRepository {
|
||||
|
||||
override suspend fun get(
|
||||
userIds: List<Int>?,
|
||||
userIds: List<Long>?,
|
||||
fields: String?,
|
||||
nomCase: String?
|
||||
): ApiResult<List<VkUser>, RestApiErrorDomain> = withContext(Dispatchers.IO) {
|
||||
@@ -38,7 +38,9 @@ class UsersRepositoryImpl(
|
||||
|
||||
val users = response.map(VkUserData::mapToDomain)
|
||||
|
||||
launch { storeUsers(users) }
|
||||
launch(Dispatchers.IO) {
|
||||
storeUsers(users)
|
||||
}
|
||||
|
||||
VkMemoryCache.appendUsers(users)
|
||||
|
||||
@@ -51,7 +53,7 @@ class UsersRepositoryImpl(
|
||||
}
|
||||
|
||||
override suspend fun getLocalUsers(
|
||||
userIds: List<Int>
|
||||
userIds: List<Long>
|
||||
): List<VkUser> = withContext(Dispatchers.IO) {
|
||||
dao.getAllByIds(userIds).map(VkUserEntity::asExternalModel)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ interface AccountsRepository {
|
||||
|
||||
suspend fun getAccounts(): List<AccountEntity>
|
||||
|
||||
suspend fun getAccountById(userId: Int): AccountEntity?
|
||||
suspend fun getAccountById(userId: Long): AccountEntity?
|
||||
|
||||
suspend fun storeAccounts(accounts: List<AccountEntity>)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ class AccountsRepositoryImpl(
|
||||
|
||||
override suspend fun getAccounts(): List<AccountEntity> = accountDao.getAll()
|
||||
|
||||
override suspend fun getAccountById(userId: Int): AccountEntity? =
|
||||
override suspend fun getAccountById(userId: Long): AccountEntity? =
|
||||
accountDao.getById(userId)
|
||||
|
||||
override suspend fun storeAccounts(
|
||||
|
||||
@@ -6,8 +6,8 @@ import dev.meloda.fast.data.api.account.AccountRepositoryImpl
|
||||
import dev.meloda.fast.data.api.audios.AudiosRepository
|
||||
import dev.meloda.fast.data.api.auth.AuthRepository
|
||||
import dev.meloda.fast.data.api.auth.AuthRepositoryImpl
|
||||
import dev.meloda.fast.data.api.conversations.ConversationsRepository
|
||||
import dev.meloda.fast.data.api.conversations.ConversationsRepositoryImpl
|
||||
import dev.meloda.fast.data.api.convos.ConvosRepository
|
||||
import dev.meloda.fast.data.api.convos.ConvosRepositoryImpl
|
||||
import dev.meloda.fast.data.api.files.FilesRepository
|
||||
import dev.meloda.fast.data.api.friends.FriendsRepository
|
||||
import dev.meloda.fast.data.api.friends.FriendsRepositoryImpl
|
||||
@@ -45,7 +45,7 @@ val dataModule = module {
|
||||
|
||||
singleOf(::AuthRepositoryImpl) bind AuthRepository::class
|
||||
|
||||
singleOf(::ConversationsRepositoryImpl) bind ConversationsRepository::class
|
||||
singleOf(::ConvosRepositoryImpl) bind ConvosRepository::class
|
||||
|
||||
singleOf(::FilesRepository)
|
||||
|
||||
@@ -65,7 +65,6 @@ val dataModule = module {
|
||||
|
||||
singleOf(::FriendsRepositoryImpl) bind FriendsRepository::class
|
||||
|
||||
// TODO: 11/08/2024, Danil Nikolaev: find a better solution
|
||||
single<Interceptor>(named("token_interceptor")) {
|
||||
AccessTokenInterceptor()
|
||||
}
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 2,
|
||||
"identityHash": "3ebd234270e36902d3d461af38664869",
|
||||
"identityHash": "ca007bca2ab4a9b901662792042770ad",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "accounts",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userId` INTEGER NOT NULL, `accessToken` TEXT NOT NULL, `fastToken` TEXT, `trustedHash` TEXT, PRIMARY KEY(`userId`))",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userId` INTEGER NOT NULL, `accessToken` TEXT NOT NULL, `fastToken` TEXT, `trustedHash` TEXT, `exchangeToken` TEXT, PRIMARY KEY(`userId`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "userId",
|
||||
@@ -31,6 +31,12 @@
|
||||
"columnName": "trustedHash",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "exchangeToken",
|
||||
"columnName": "exchangeToken",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
@@ -46,7 +52,7 @@
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '3ebd234270e36902d3d461af38664869')"
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ca007bca2ab4a9b901662792042770ad')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 3,
|
||||
"identityHash": "ca007bca2ab4a9b901662792042770ad",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "accounts",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userId` INTEGER NOT NULL, `accessToken` TEXT NOT NULL, `fastToken` TEXT, `trustedHash` TEXT, `exchangeToken` TEXT, PRIMARY KEY(`userId`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "userId",
|
||||
"columnName": "userId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "accessToken",
|
||||
"columnName": "accessToken",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fastToken",
|
||||
"columnName": "fastToken",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "trustedHash",
|
||||
"columnName": "trustedHash",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "exchangeToken",
|
||||
"columnName": "exchangeToken",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"userId"
|
||||
]
|
||||
},
|
||||
"indices": [],
|
||||
"foreignKeys": []
|
||||
}
|
||||
],
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ca007bca2ab4a9b901662792042770ad')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 10,
|
||||
"identityHash": "6c315b7f800694f635318d86032746ec",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "users",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `firstName` TEXT NOT NULL, `lastName` TEXT NOT NULL, `isOnline` INTEGER NOT NULL, `isOnlineMobile` INTEGER NOT NULL, `onlineAppId` INTEGER, `lastSeen` INTEGER, `lastSeenStatus` TEXT, `birthday` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `photo400Orig` TEXT, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "firstName",
|
||||
"columnName": "firstName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastName",
|
||||
"columnName": "lastName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOnline",
|
||||
"columnName": "isOnline",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOnlineMobile",
|
||||
"columnName": "isOnlineMobile",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "onlineAppId",
|
||||
"columnName": "onlineAppId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastSeen",
|
||||
"columnName": "lastSeen",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastSeenStatus",
|
||||
"columnName": "lastSeenStatus",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "birthday",
|
||||
"columnName": "birthday",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo400Orig",
|
||||
"columnName": "photo400Orig",
|
||||
"affinity": "TEXT"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "groups",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `screenName` TEXT NOT NULL, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `membersCount` INTEGER, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenName",
|
||||
"columnName": "screenName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "membersCount",
|
||||
"columnName": "membersCount",
|
||||
"affinity": "INTEGER"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "messages",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `cmId` INTEGER NOT NULL, `text` TEXT, `isOut` INTEGER NOT NULL, `peerId` INTEGER NOT NULL, `fromId` INTEGER NOT NULL, `date` INTEGER NOT NULL, `randomId` INTEGER NOT NULL, `action` TEXT, `actionMemberId` INTEGER, `actionText` TEXT, `actionCmId` INTEGER, `actionMessage` TEXT, `updateTime` INTEGER, `important` INTEGER NOT NULL, `forwardIds` TEXT, `attachments` TEXT, `replyMessageId` INTEGER, `geoType` TEXT, `pinnedAt` INTEGER, `isPinned` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "cmId",
|
||||
"columnName": "cmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "text",
|
||||
"columnName": "text",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOut",
|
||||
"columnName": "isOut",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "peerId",
|
||||
"columnName": "peerId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fromId",
|
||||
"columnName": "fromId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "date",
|
||||
"columnName": "date",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "randomId",
|
||||
"columnName": "randomId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "action",
|
||||
"columnName": "action",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionMemberId",
|
||||
"columnName": "actionMemberId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionText",
|
||||
"columnName": "actionText",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionCmId",
|
||||
"columnName": "actionCmId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionMessage",
|
||||
"columnName": "actionMessage",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "updateTime",
|
||||
"columnName": "updateTime",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "important",
|
||||
"columnName": "important",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "forwardIds",
|
||||
"columnName": "forwardIds",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "attachments",
|
||||
"columnName": "attachments",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "replyMessageId",
|
||||
"columnName": "replyMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "geoType",
|
||||
"columnName": "geoType",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pinnedAt",
|
||||
"columnName": "pinnedAt",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPinned",
|
||||
"columnName": "isPinned",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "conversations",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `localId` INTEGER NOT NULL, `ownerId` INTEGER, `title` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `isPhantom` INTEGER NOT NULL, `lastCmId` INTEGER NOT NULL, `inReadCmId` INTEGER NOT NULL, `outReadCmId` INTEGER NOT NULL, `inRead` INTEGER NOT NULL, `outRead` INTEGER NOT NULL, `lastMessageId` INTEGER, `unreadCount` INTEGER NOT NULL, `membersCount` INTEGER, `canChangePin` INTEGER NOT NULL, `canChangeInfo` INTEGER NOT NULL, `majorId` INTEGER NOT NULL, `minorId` INTEGER NOT NULL, `pinnedMessageId` INTEGER, `peerType` TEXT NOT NULL, `isArchived` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "localId",
|
||||
"columnName": "localId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "ownerId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "title",
|
||||
"columnName": "title",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPhantom",
|
||||
"columnName": "isPhantom",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastCmId",
|
||||
"columnName": "lastCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "inReadCmId",
|
||||
"columnName": "inReadCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "outReadCmId",
|
||||
"columnName": "outReadCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "inRead",
|
||||
"columnName": "inRead",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "outRead",
|
||||
"columnName": "outRead",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastMessageId",
|
||||
"columnName": "lastMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "unreadCount",
|
||||
"columnName": "unreadCount",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "membersCount",
|
||||
"columnName": "membersCount",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "canChangePin",
|
||||
"columnName": "canChangePin",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "canChangeInfo",
|
||||
"columnName": "canChangeInfo",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "majorId",
|
||||
"columnName": "majorId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "minorId",
|
||||
"columnName": "minorId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "pinnedMessageId",
|
||||
"columnName": "pinnedMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "peerType",
|
||||
"columnName": "peerType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isArchived",
|
||||
"columnName": "isArchived",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '6c315b7f800694f635318d86032746ec')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 11,
|
||||
"identityHash": "a746865995959331f8a1b512c049dacb",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "users",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `firstName` TEXT NOT NULL, `lastName` TEXT NOT NULL, `isOnline` INTEGER NOT NULL, `isOnlineMobile` INTEGER NOT NULL, `onlineAppId` INTEGER, `lastSeen` INTEGER, `lastSeenStatus` TEXT, `birthday` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `photo400Orig` TEXT, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "firstName",
|
||||
"columnName": "firstName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastName",
|
||||
"columnName": "lastName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOnline",
|
||||
"columnName": "isOnline",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOnlineMobile",
|
||||
"columnName": "isOnlineMobile",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "onlineAppId",
|
||||
"columnName": "onlineAppId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastSeen",
|
||||
"columnName": "lastSeen",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastSeenStatus",
|
||||
"columnName": "lastSeenStatus",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "birthday",
|
||||
"columnName": "birthday",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo400Orig",
|
||||
"columnName": "photo400Orig",
|
||||
"affinity": "TEXT"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "groups",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `name` TEXT NOT NULL, `screenName` TEXT NOT NULL, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `membersCount` INTEGER, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenName",
|
||||
"columnName": "screenName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "membersCount",
|
||||
"columnName": "membersCount",
|
||||
"affinity": "INTEGER"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "messages",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `cmId` INTEGER NOT NULL, `text` TEXT, `isOut` INTEGER NOT NULL, `peerId` INTEGER NOT NULL, `fromId` INTEGER NOT NULL, `date` INTEGER NOT NULL, `randomId` INTEGER NOT NULL, `action` TEXT, `actionMemberId` INTEGER, `actionText` TEXT, `actionCmId` INTEGER, `actionMessage` TEXT, `updateTime` INTEGER, `important` INTEGER NOT NULL, `forwardIds` TEXT, `attachments` TEXT, `replyMessageId` INTEGER, `geoType` TEXT, `pinnedAt` INTEGER, `isPinned` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "cmId",
|
||||
"columnName": "cmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "text",
|
||||
"columnName": "text",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isOut",
|
||||
"columnName": "isOut",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "peerId",
|
||||
"columnName": "peerId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fromId",
|
||||
"columnName": "fromId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "date",
|
||||
"columnName": "date",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "randomId",
|
||||
"columnName": "randomId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "action",
|
||||
"columnName": "action",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionMemberId",
|
||||
"columnName": "actionMemberId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionText",
|
||||
"columnName": "actionText",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionCmId",
|
||||
"columnName": "actionCmId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "actionMessage",
|
||||
"columnName": "actionMessage",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "updateTime",
|
||||
"columnName": "updateTime",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "important",
|
||||
"columnName": "important",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "forwardIds",
|
||||
"columnName": "forwardIds",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "attachments",
|
||||
"columnName": "attachments",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "replyMessageId",
|
||||
"columnName": "replyMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "geoType",
|
||||
"columnName": "geoType",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pinnedAt",
|
||||
"columnName": "pinnedAt",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPinned",
|
||||
"columnName": "isPinned",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "convos",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `localId` INTEGER NOT NULL, `ownerId` INTEGER, `title` TEXT, `photo50` TEXT, `photo100` TEXT, `photo200` TEXT, `isPhantom` INTEGER NOT NULL, `lastCmId` INTEGER NOT NULL, `inReadCmId` INTEGER NOT NULL, `outReadCmId` INTEGER NOT NULL, `inRead` INTEGER NOT NULL, `outRead` INTEGER NOT NULL, `lastMessageId` INTEGER, `unreadCount` INTEGER NOT NULL, `membersCount` INTEGER, `canChangePin` INTEGER NOT NULL, `canChangeInfo` INTEGER NOT NULL, `majorId` INTEGER NOT NULL, `minorId` INTEGER NOT NULL, `pinnedMessageId` INTEGER, `peerType` TEXT NOT NULL, `isArchived` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "localId",
|
||||
"columnName": "localId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "ownerId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "title",
|
||||
"columnName": "title",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo50",
|
||||
"columnName": "photo50",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo100",
|
||||
"columnName": "photo100",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "photo200",
|
||||
"columnName": "photo200",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPhantom",
|
||||
"columnName": "isPhantom",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastCmId",
|
||||
"columnName": "lastCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "inReadCmId",
|
||||
"columnName": "inReadCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "outReadCmId",
|
||||
"columnName": "outReadCmId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "inRead",
|
||||
"columnName": "inRead",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "outRead",
|
||||
"columnName": "outRead",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastMessageId",
|
||||
"columnName": "lastMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "unreadCount",
|
||||
"columnName": "unreadCount",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "membersCount",
|
||||
"columnName": "membersCount",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "canChangePin",
|
||||
"columnName": "canChangePin",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "canChangeInfo",
|
||||
"columnName": "canChangeInfo",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "majorId",
|
||||
"columnName": "majorId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "minorId",
|
||||
"columnName": "minorId",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "pinnedMessageId",
|
||||
"columnName": "pinnedMessageId",
|
||||
"affinity": "INTEGER"
|
||||
},
|
||||
{
|
||||
"fieldPath": "peerType",
|
||||
"columnName": "peerType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isArchived",
|
||||
"columnName": "isArchived",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a746865995959331f8a1b512c049dacb')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import dev.meloda.fast.model.database.AccountEntity
|
||||
|
||||
@Database(
|
||||
entities = [AccountEntity::class],
|
||||
version = 2
|
||||
version = 3
|
||||
)
|
||||
abstract class AccountsDatabase : RoomDatabase() {
|
||||
abstract fun accountDao(): AccountDao
|
||||
|
||||
@@ -3,12 +3,12 @@ package dev.meloda.fast.database
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import dev.meloda.fast.database.dao.ConversationDao
|
||||
import dev.meloda.fast.database.dao.ConvoDao
|
||||
import dev.meloda.fast.database.dao.GroupDao
|
||||
import dev.meloda.fast.database.dao.MessageDao
|
||||
import dev.meloda.fast.database.dao.UsersDao
|
||||
import dev.meloda.fast.database.dao.UserDao
|
||||
import dev.meloda.fast.database.typeconverters.Converters
|
||||
import dev.meloda.fast.model.database.VkConversationEntity
|
||||
import dev.meloda.fast.model.database.VkConvoEntity
|
||||
import dev.meloda.fast.model.database.VkGroupEntity
|
||||
import dev.meloda.fast.model.database.VkMessageEntity
|
||||
import dev.meloda.fast.model.database.VkUserEntity
|
||||
@@ -18,15 +18,15 @@ import dev.meloda.fast.model.database.VkUserEntity
|
||||
VkUserEntity::class,
|
||||
VkGroupEntity::class,
|
||||
VkMessageEntity::class,
|
||||
VkConversationEntity::class
|
||||
VkConvoEntity::class
|
||||
],
|
||||
|
||||
version = 7
|
||||
version = 11
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class CacheDatabase : RoomDatabase() {
|
||||
abstract fun userDao(): UsersDao
|
||||
abstract fun userDao(): UserDao
|
||||
abstract fun groupDao(): GroupDao
|
||||
abstract fun messageDao(): MessageDao
|
||||
abstract fun conversationDao(): ConversationDao
|
||||
abstract fun convoDao(): ConvoDao
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@ abstract class AccountDao : EntityDao<AccountEntity> {
|
||||
abstract suspend fun getAll(): List<AccountEntity>
|
||||
|
||||
@Query("SELECT * FROM accounts WHERE userId = :userId")
|
||||
abstract suspend fun getById(userId: Int): AccountEntity?
|
||||
abstract suspend fun getById(userId: Long): AccountEntity?
|
||||
|
||||
@Query("DELETE FROM accounts WHERE userId = :userId")
|
||||
abstract suspend fun deleteById(userId: Int)
|
||||
abstract suspend fun deleteById(userId: Long)
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
package dev.meloda.fast.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import dev.meloda.fast.model.database.ConversationWithMessage
|
||||
import dev.meloda.fast.model.database.VkConversationEntity
|
||||
|
||||
@Dao
|
||||
abstract class ConversationDao : EntityDao<VkConversationEntity> {
|
||||
|
||||
@Query("SELECT * FROM conversations")
|
||||
abstract suspend fun getAll(): List<VkConversationEntity>
|
||||
|
||||
@Query("SELECT * FROM conversations WHERE id IN (:ids)")
|
||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkConversationEntity>
|
||||
|
||||
@Query("SELECT * FROM conversations WHERE id IS (:id)")
|
||||
abstract suspend fun getById(id: Int): VkConversationEntity?
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM conversations WHERE id IS (:id)")
|
||||
abstract suspend fun getByIdWithMessage(id: Int): ConversationWithMessage?
|
||||
|
||||
@Query("DELETE FROM conversations WHERE rowid IN (:ids)")
|
||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package dev.meloda.fast.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import dev.meloda.fast.model.database.ConvoWithMessage
|
||||
import dev.meloda.fast.model.database.VkConvoEntity
|
||||
|
||||
@Dao
|
||||
abstract class ConvoDao : EntityDao<VkConvoEntity> {
|
||||
|
||||
@Query("SELECT * FROM convos ORDER BY majorId DESC, minorId DESC")
|
||||
abstract suspend fun getAll(): List<VkConvoEntity>
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM convos ORDER BY majorId DESC, minorId DESC")
|
||||
abstract suspend fun getAllWithMessage(): List<ConvoWithMessage>
|
||||
|
||||
@Query("SELECT * FROM convos WHERE id IN (:ids)")
|
||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkConvoEntity>
|
||||
|
||||
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
||||
abstract suspend fun getById(id: Long): VkConvoEntity?
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM convos WHERE id IS (:id)")
|
||||
abstract suspend fun getByIdWithMessage(id: Long): ConvoWithMessage?
|
||||
|
||||
@Query("DELETE FROM convos WHERE id IS (:id)")
|
||||
abstract suspend fun deleteById(id: Long): Int
|
||||
|
||||
@Query("DELETE FROM convos WHERE rowid IN (:ids)")
|
||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -10,15 +10,21 @@ abstract class MessageDao : EntityDao<VkMessageEntity> {
|
||||
@Query("SELECT * FROM messages")
|
||||
abstract suspend fun getAll(): List<VkMessageEntity>
|
||||
|
||||
@Query("SELECT * FROM messages WHERE peerId IS (:conversationId)")
|
||||
abstract suspend fun getAll(conversationId: Int): List<VkMessageEntity>
|
||||
@Query("SELECT * FROM messages WHERE peerId IS (:convoId) ORDER BY date DESC, id DESC")
|
||||
abstract suspend fun getAll(convoId: Long): List<VkMessageEntity>
|
||||
|
||||
@Query("SELECT * FROM messages WHERE id IN (:ids)")
|
||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkMessageEntity>
|
||||
abstract suspend fun getAllByIds(ids: List<Long>): List<VkMessageEntity>
|
||||
|
||||
@Query("SELECT * FROM messages WHERE id IS (:messageId)")
|
||||
abstract suspend fun getById(messageId: Int): VkMessageEntity?
|
||||
abstract suspend fun getById(messageId: Long): VkMessageEntity?
|
||||
|
||||
@Query("SELECT * FROM messages WHERE peerId IS (:convoId) AND cmId IS (:cmId)")
|
||||
abstract suspend fun getByConvoMessageId(convoId: Long, cmId: Long): VkMessageEntity?
|
||||
|
||||
@Query("SELECT MAX(id) FROM messages")
|
||||
abstract suspend fun getMaxId(): Long?
|
||||
|
||||
@Query("DELETE FROM messages WHERE id IN (:ids)")
|
||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||
abstract suspend fun deleteByIds(ids: List<Long>): Int
|
||||
}
|
||||
|
||||
+3
-3
@@ -5,14 +5,14 @@ import androidx.room.Query
|
||||
import dev.meloda.fast.model.database.VkUserEntity
|
||||
|
||||
@Dao
|
||||
abstract class UsersDao : EntityDao<VkUserEntity> {
|
||||
abstract class UserDao : EntityDao<VkUserEntity> {
|
||||
|
||||
@Query("SELECT * FROM users")
|
||||
abstract suspend fun getAll(): List<VkUserEntity>
|
||||
|
||||
@Query("SELECT * FROM users WHERE id IN (:ids)")
|
||||
abstract suspend fun getAllByIds(ids: List<Int>): List<VkUserEntity>
|
||||
abstract suspend fun getAllByIds(ids: List<Long>): List<VkUserEntity>
|
||||
|
||||
@Query("DELETE FROM users WHERE id IN (:ids)")
|
||||
abstract suspend fun deleteByIds(ids: List<Int>): Int
|
||||
abstract suspend fun deleteByIds(ids: List<Long>): Int
|
||||
}
|
||||
@@ -2,24 +2,28 @@ package dev.meloda.fast.database.di
|
||||
|
||||
import androidx.room.Room
|
||||
import dev.meloda.fast.database.AccountsDatabase
|
||||
import dev.meloda.fast.database.CacheDatabase
|
||||
import dev.meloda.fast.database.di.migration.migrationFrom2To3
|
||||
import org.koin.core.scope.Scope
|
||||
import org.koin.dsl.module
|
||||
|
||||
val databaseModule = module {
|
||||
single {
|
||||
Room.databaseBuilder(get(), AccountsDatabase::class.java, "accounts").build()
|
||||
Room.databaseBuilder(get(), AccountsDatabase::class.java, "accounts")
|
||||
.addMigrations(migrationFrom2To3)
|
||||
.build()
|
||||
}
|
||||
single { get<AccountsDatabase>().accountDao() }
|
||||
|
||||
single {
|
||||
Room.databaseBuilder(get(), dev.meloda.fast.database.CacheDatabase::class.java, "cache")
|
||||
.fallbackToDestructiveMigration()
|
||||
Room.databaseBuilder(get(), CacheDatabase::class.java, "cache")
|
||||
.fallbackToDestructiveMigration(true)
|
||||
.build()
|
||||
}
|
||||
single { cacheDB().userDao() }
|
||||
single { cacheDB().groupDao() }
|
||||
single { cacheDB().messageDao() }
|
||||
single { cacheDB().conversationDao() }
|
||||
single { cacheDB().convoDao() }
|
||||
}
|
||||
|
||||
private fun Scope.cacheDB(): dev.meloda.fast.database.CacheDatabase = get()
|
||||
private fun Scope.cacheDB(): CacheDatabase = get()
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package dev.meloda.fast.database.di.migration
|
||||
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
|
||||
val migrationFrom2To3 = object : Migration(
|
||||
startVersion = 2,
|
||||
endVersion = 3
|
||||
) {
|
||||
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE accounts ADD COLUMN exchangeToken TEXT DEFAULT null")
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,15 @@ class Converters {
|
||||
.split(", ")
|
||||
.mapNotNull(String::toIntOrNull)
|
||||
|
||||
@TypeConverter
|
||||
fun longListToString(list: List<Long>): String = list.joinToString()
|
||||
|
||||
@TypeConverter
|
||||
fun stringToLongList(string: String): List<Long> =
|
||||
string
|
||||
.split(", ")
|
||||
.mapNotNull(String::toLongOrNull)
|
||||
|
||||
@TypeConverter
|
||||
fun stringListToString(list: List<String>): String = list.joinToString()
|
||||
|
||||
|
||||
@@ -4,13 +4,32 @@ import android.content.SharedPreferences
|
||||
import androidx.core.content.edit
|
||||
import dev.meloda.fast.common.model.DarkMode
|
||||
import dev.meloda.fast.common.model.LogLevel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlin.properties.Delegates
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
sealed class CaptchaTokenResult {
|
||||
data object Initial : CaptchaTokenResult()
|
||||
data object Null : CaptchaTokenResult()
|
||||
data object Cancelled : CaptchaTokenResult()
|
||||
data class Success(val token: String) : CaptchaTokenResult()
|
||||
}
|
||||
|
||||
object AppSettings {
|
||||
|
||||
private var preferences: SharedPreferences by Delegates.notNull()
|
||||
|
||||
private val captchaResult = MutableStateFlow<CaptchaTokenResult>(CaptchaTokenResult.Initial)
|
||||
fun getCaptchaResultFlow(): StateFlow<CaptchaTokenResult> = captchaResult.asStateFlow()
|
||||
fun setCaptchaResult(result: CaptchaTokenResult) = captchaResult.update { result }
|
||||
|
||||
private val captchaRedirectUri = MutableStateFlow<String?>(null)
|
||||
fun getCaptchaRedirectUriFlow() = captchaRedirectUri.asStateFlow()
|
||||
fun setCaptchaRedirectUri(redirectUri: String?) = captchaRedirectUri.update { redirectUri }
|
||||
|
||||
fun init(preferences: SharedPreferences) {
|
||||
this.preferences = preferences
|
||||
}
|
||||
@@ -89,12 +108,34 @@ object AppSettings {
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_USE_CONTACT_NAMES, value)
|
||||
|
||||
var enablePullToRefresh: Boolean
|
||||
var showEmojiButton: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_ENABLE_PULL_TO_REFRESH,
|
||||
SettingsKeys.DEFAULT_VALUE_ENABLE_PULL_TO_REFRESH
|
||||
SettingsKeys.KEY_SHOW_EMOJI_BUTTON,
|
||||
SettingsKeys.DEFAULT_VALUE_KEY_SHOW_EMOJI_BUTTON
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_ENABLE_PULL_TO_REFRESH, value)
|
||||
set(value) = put(SettingsKeys.KEY_SHOW_EMOJI_BUTTON, value)
|
||||
|
||||
var showAttachmentButton: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_SHOW_ATTACHMENT_BUTTON,
|
||||
SettingsKeys.DEFAULT_VALUE_SHOW_ATTACHMENT_BUTTON
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_SHOW_ATTACHMENT_BUTTON, value)
|
||||
|
||||
var showManualRefreshOptions: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_SHOW_MANUAL_REFRESH_OPTIONS,
|
||||
SettingsKeys.DEFAULT_VALUE_SHOW_MANUAL_REFRESH_OPTIONS
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_SHOW_MANUAL_REFRESH_OPTIONS, value)
|
||||
|
||||
var enableHaptic: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_ENABLE_HAPTIC,
|
||||
SettingsKeys.DEFAULT_ENABLE_HAPTIC
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_ENABLE_HAPTIC, value)
|
||||
|
||||
}
|
||||
|
||||
object Appearance {
|
||||
@@ -126,6 +167,13 @@ object AppSettings {
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_USE_DYNAMIC_COLORS, value)
|
||||
|
||||
var useSystemFont: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_USE_SYSTEM_FONT,
|
||||
SettingsKeys.DEFAULT_USE_SYSTEM_FONT
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_USE_SYSTEM_FONT, value)
|
||||
|
||||
var appLanguage: String
|
||||
get() = get(
|
||||
SettingsKeys.KEY_APPEARANCE_LANGUAGE,
|
||||
@@ -152,6 +200,51 @@ object AppSettings {
|
||||
set(value) = put(SettingsKeys.KEY_ACTIVITY_SEND_ONLINE_STATUS, value)
|
||||
}
|
||||
|
||||
object Experimental {
|
||||
var longPollInBackground: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_LONG_POLL_IN_BACKGROUND,
|
||||
SettingsKeys.DEFAULT_LONG_POLL_IN_BACKGROUND
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_LONG_POLL_IN_BACKGROUND, value)
|
||||
|
||||
var showTimeInActionMessages: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_SHOW_TIME_IN_ACTION_MESSAGES,
|
||||
SettingsKeys.DEFAULT_SHOW_TIME_IN_ACTION_MESSAGES
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_SHOW_TIME_IN_ACTION_MESSAGES, value)
|
||||
|
||||
var useBlur: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_USE_BLUR,
|
||||
SettingsKeys.DEFAULT_USE_BLUR
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_USE_BLUR, value)
|
||||
|
||||
var moreAnimations: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_MORE_ANIMATIONS,
|
||||
SettingsKeys.DEFAULT_MORE_ANIMATIONS
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_MORE_ANIMATIONS, value)
|
||||
}
|
||||
|
||||
object LongPoll {
|
||||
var ts: Int?
|
||||
get() = get(SettingsKeys.KEY_LONG_POLL_TS, 0).takeIf { it > 0 }
|
||||
set(value) = put(SettingsKeys.KEY_LONG_POLL_TS, value ?: 0)
|
||||
|
||||
var pts: Int?
|
||||
get() = get(SettingsKeys.KEY_LONG_POLL_PTS, 0).takeIf { it > 0 }
|
||||
set(value) = put(SettingsKeys.KEY_LONG_POLL_PTS, value ?: 0)
|
||||
|
||||
fun clear() {
|
||||
ts = null
|
||||
pts = null
|
||||
}
|
||||
}
|
||||
|
||||
object Debug {
|
||||
var showAlertAfterCrash: Boolean
|
||||
get() = get(
|
||||
@@ -160,41 +253,6 @@ object AppSettings {
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_DEBUG_SHOW_CRASH_ALERT, value)
|
||||
|
||||
var longPollInBackground: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_FEATURES_LONG_POLL_IN_BACKGROUND,
|
||||
SettingsKeys.DEFAULT_VALUE_FEATURES_LONG_POLL_IN_BACKGROUND
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_FEATURES_LONG_POLL_IN_BACKGROUND, value)
|
||||
|
||||
var useBlur: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_APPEARANCE_USE_BLUR,
|
||||
SettingsKeys.DEFAULT_VALUE_KEY_APPEARANCE_USE_BLUR
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_APPEARANCE_USE_BLUR, value)
|
||||
|
||||
var showEmojiButton: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_SHOW_EMOJI_BUTTON,
|
||||
SettingsKeys.DEFAULT_VALUE_KEY_SHOW_EMOJI_BUTTON
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_SHOW_EMOJI_BUTTON, value)
|
||||
|
||||
var showTimeInActionMessages: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_APPEARANCE_SHOW_TIME_IN_ACTION_MESSAGES,
|
||||
SettingsKeys.DEFAULT_VALUE_APPEARANCE_SHOW_TIME_IN_ACTION_MESSAGES
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_APPEARANCE_SHOW_TIME_IN_ACTION_MESSAGES, value)
|
||||
|
||||
var enableHaptic: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_DEBUG_ENABLE_HAPTIC,
|
||||
SettingsKeys.DEFAULT_DEBUG_ENABLE_HAPTIC
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_DEBUG_ENABLE_HAPTIC, value)
|
||||
|
||||
var networkLogLevel: LogLevel
|
||||
get() = get(
|
||||
SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL,
|
||||
@@ -202,13 +260,6 @@ object AppSettings {
|
||||
).let(LogLevel::parse)
|
||||
set(level) = put(SettingsKeys.KEY_DEBUG_NETWORK_LOG_LEVEL, level.value)
|
||||
|
||||
var useSystemFont: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_DEBUG_USE_SYSTEM_FONT,
|
||||
SettingsKeys.DEFAULT_DEBUG_USE_SYSTEM_FONT
|
||||
)
|
||||
set(value) = put(SettingsKeys.KEY_DEBUG_USE_SYSTEM_FONT, value)
|
||||
|
||||
var showDebugCategory: Boolean
|
||||
get() = get(
|
||||
SettingsKeys.KEY_SHOW_DEBUG_CATEGORY,
|
||||
|
||||
@@ -7,12 +7,14 @@ object SettingsKeys {
|
||||
const val KEY_ACCOUNT_LOGOUT = "account_logout"
|
||||
|
||||
const val KEY_GENERAL = "general"
|
||||
const val KEY_USE_CONTACT_NAMES = "general_use_contact_names"
|
||||
const val KEY_USE_CONTACT_NAMES = "use_contact_names"
|
||||
const val DEFAULT_VALUE_USE_CONTACT_NAMES = false
|
||||
const val KEY_ENABLE_PULL_TO_REFRESH = "general_pull_to_refresh"
|
||||
const val DEFAULT_VALUE_ENABLE_PULL_TO_REFRESH = false
|
||||
const val KEY_SHOW_EMOJI_BUTTON = "general_show_emoji_button"
|
||||
const val KEY_SHOW_EMOJI_BUTTON = "show_emoji_button"
|
||||
const val DEFAULT_VALUE_KEY_SHOW_EMOJI_BUTTON = false
|
||||
const val KEY_SHOW_ATTACHMENT_BUTTON = "show_attachment_button"
|
||||
const val DEFAULT_VALUE_SHOW_ATTACHMENT_BUTTON = false
|
||||
const val KEY_SHOW_MANUAL_REFRESH_OPTIONS = "show_manual_refresh_options"
|
||||
const val DEFAULT_VALUE_SHOW_MANUAL_REFRESH_OPTIONS = false
|
||||
|
||||
const val KEY_APPEARANCE = "appearance"
|
||||
const val KEY_APPEARANCE_MULTILINE = "appearance_multiline"
|
||||
@@ -23,20 +25,22 @@ object SettingsKeys {
|
||||
const val DEFAULT_VALUE_APPEARANCE_AMOLED_THEME = false
|
||||
const val KEY_USE_DYNAMIC_COLORS = "appearance_use_dynamic_colors"
|
||||
const val DEFAULT_VALUE_USE_DYNAMIC_COLORS = false
|
||||
const val KEY_APPEARANCE_COLOR_SCHEME = "appearance_color_scheme"
|
||||
const val DEFAULT_VALUE_APPEARANCE_COLOR_SCHEME = 0
|
||||
const val KEY_COLOR_SCHEME = "appearance_color_scheme"
|
||||
const val DEFAULT_COLOR_SCHEME = 0
|
||||
const val KEY_APPEARANCE_LANGUAGE = "appearance_language"
|
||||
const val DEFAULT_APPEARANCE_LANGUAGE = ""
|
||||
const val KEY_APPEARANCE_USE_BLUR = "appearance_use_blur"
|
||||
const val DEFAULT_VALUE_KEY_APPEARANCE_USE_BLUR = false
|
||||
const val KEY_APPEARANCE_SHOW_TIME_IN_ACTION_MESSAGES =
|
||||
"appearance_show_time_in_action_messages"
|
||||
const val DEFAULT_VALUE_APPEARANCE_SHOW_TIME_IN_ACTION_MESSAGES = false
|
||||
const val KEY_USE_BLUR = "use_blur"
|
||||
const val DEFAULT_USE_BLUR = false
|
||||
const val KEY_SHOW_TIME_IN_ACTION_MESSAGES =
|
||||
"show_time_in_action_messages"
|
||||
const val DEFAULT_SHOW_TIME_IN_ACTION_MESSAGES = false
|
||||
|
||||
const val KEY_FEATURES_FAST_TEXT = "features_fast_text"
|
||||
const val DEFAULT_VALUE_FEATURES_FAST_TEXT = "¯\\_(ツ)_/¯"
|
||||
const val KEY_FEATURES_LONG_POLL_IN_BACKGROUND = "features_lp_background"
|
||||
const val DEFAULT_VALUE_FEATURES_LONG_POLL_IN_BACKGROUND = false
|
||||
const val KEY_LONG_POLL_IN_BACKGROUND = "lp_background"
|
||||
const val DEFAULT_LONG_POLL_IN_BACKGROUND = false
|
||||
const val KEY_LONG_POLL_TS = "lp_ts"
|
||||
const val KEY_LONG_POLL_PTS = "lp_pts"
|
||||
|
||||
const val KEY_ACTIVITY_SEND_ONLINE_STATUS = "activity_send_online_status"
|
||||
const val DEFAULT_VALUE_KEY_ACTIVITY_SEND_ONLINE_STATUS = false
|
||||
@@ -44,15 +48,19 @@ object SettingsKeys {
|
||||
const val KEY_DEBUG_PERFORM_CRASH = "debug_perform_crash"
|
||||
const val KEY_DEBUG_SHOW_CRASH_ALERT = "debug_show_crash_alert"
|
||||
const val KEY_DEBUG_HIDE_DEBUG_LIST = "debug_hide_debug_list"
|
||||
const val KEY_ENABLE_ANIMATIONS_IN_MESSAGES = "debug_enable_animations_in_messages"
|
||||
const val KEY_DEBUG_ENABLE_HAPTIC = "debug_enable_haptic"
|
||||
const val DEFAULT_DEBUG_ENABLE_HAPTIC = true
|
||||
const val KEY_ENABLE_HAPTIC = "enable_haptic"
|
||||
const val DEFAULT_ENABLE_HAPTIC = true
|
||||
const val KEY_DEBUG_NETWORK_LOG_LEVEL = "debug_network_log_level"
|
||||
const val DEFAULT_NETWORK_LOG_LEVEL = 0
|
||||
const val KEY_DEBUG_USE_SYSTEM_FONT = "debug_use_system_font"
|
||||
const val DEFAULT_DEBUG_USE_SYSTEM_FONT = false
|
||||
const val DEFAULT_NETWORK_LOG_LEVEL = 3
|
||||
const val KEY_DEBUG_IMPORT_AUTH_DATA = "debug_import_auth_data"
|
||||
const val KEY_DEBUG_EXPORT_AUTH_DATA = "debug_export_auth_data"
|
||||
|
||||
const val KEY_USE_SYSTEM_FONT = "use_system_font"
|
||||
const val DEFAULT_USE_SYSTEM_FONT = false
|
||||
const val KEY_MORE_ANIMATIONS = "more_animations"
|
||||
const val DEFAULT_MORE_ANIMATIONS = false
|
||||
|
||||
|
||||
const val KEY_SHOW_DEBUG_CATEGORY = "show_debug_category"
|
||||
|
||||
const val ID_DMITRY = 37610580
|
||||
const val ID_DMITRY = 37610580L
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
interface UserSettings {
|
||||
|
||||
val useContactNames: StateFlow<Boolean>
|
||||
val enablePullToRefresh: StateFlow<Boolean>
|
||||
|
||||
val enableMultiline: StateFlow<Boolean>
|
||||
val darkMode: StateFlow<DarkMode>
|
||||
@@ -15,20 +14,15 @@ interface UserSettings {
|
||||
val enableDynamicColors: StateFlow<Boolean>
|
||||
val appLanguage: StateFlow<String>
|
||||
|
||||
val fastText: StateFlow<String>
|
||||
|
||||
val sendOnlineStatus: StateFlow<Boolean>
|
||||
|
||||
val showAlertAfterCrash: StateFlow<Boolean>
|
||||
val longPollInBackground: StateFlow<Boolean>
|
||||
val useBlur: StateFlow<Boolean>
|
||||
val showEmojiButton: StateFlow<Boolean>
|
||||
val showTimeInActionMessages: StateFlow<Boolean>
|
||||
val useSystemFont: StateFlow<Boolean>
|
||||
val enableAnimations: StateFlow<Boolean>
|
||||
val showDebugCategory: StateFlow<Boolean>
|
||||
|
||||
fun onUseContactNamesChanged(use: Boolean)
|
||||
fun onEnablePullToRefreshChanged(enable: Boolean)
|
||||
|
||||
fun onEnableMultilineChanged(enable: Boolean)
|
||||
fun onDarkModeChanged(mode: DarkMode)
|
||||
@@ -36,15 +30,10 @@ interface UserSettings {
|
||||
fun onEnableDynamicColorsChanged(enable: Boolean)
|
||||
fun onAppLanguageChanged(language: String)
|
||||
|
||||
fun onFastTextChanged(text: String)
|
||||
|
||||
fun onSendOnlineStatusChanged(send: Boolean)
|
||||
|
||||
fun onShowAlertAfterCrashChanged(show: Boolean)
|
||||
fun onLongPollInBackgroundChanged(inBackground: Boolean)
|
||||
fun onUseBlurChanged(use: Boolean)
|
||||
fun onShowEmojiButtonChanged(show: Boolean)
|
||||
fun onShowTimeInActionMessagesChanged(show: Boolean)
|
||||
fun onUseSystemFontChanged(use: Boolean)
|
||||
fun onShowDebugCategoryChanged(show: Boolean)
|
||||
}
|
||||
@@ -52,7 +41,6 @@ interface UserSettings {
|
||||
class UserSettingsImpl : UserSettings {
|
||||
|
||||
override val useContactNames = MutableStateFlow(AppSettings.General.useContactNames)
|
||||
override val enablePullToRefresh = MutableStateFlow(AppSettings.General.enablePullToRefresh)
|
||||
|
||||
override val enableMultiline = MutableStateFlow(AppSettings.Appearance.enableMultiline)
|
||||
override val darkMode = MutableStateFlow(AppSettings.Appearance.darkMode)
|
||||
@@ -60,27 +48,19 @@ class UserSettingsImpl : UserSettings {
|
||||
override val enableDynamicColors = MutableStateFlow(AppSettings.Appearance.enableDynamicColors)
|
||||
override val appLanguage = MutableStateFlow(AppSettings.Appearance.appLanguage)
|
||||
|
||||
override val fastText = MutableStateFlow(AppSettings.Features.fastText)
|
||||
|
||||
override val sendOnlineStatus = MutableStateFlow(AppSettings.Activity.sendOnlineStatus)
|
||||
|
||||
override val showAlertAfterCrash = MutableStateFlow(AppSettings.Debug.showAlertAfterCrash)
|
||||
override val longPollInBackground = MutableStateFlow(AppSettings.Debug.longPollInBackground)
|
||||
override val useBlur = MutableStateFlow(AppSettings.Debug.useBlur)
|
||||
override val showEmojiButton = MutableStateFlow(AppSettings.Debug.showEmojiButton)
|
||||
override val showTimeInActionMessages =
|
||||
MutableStateFlow(AppSettings.Debug.showTimeInActionMessages)
|
||||
override val useSystemFont = MutableStateFlow(AppSettings.Debug.useSystemFont)
|
||||
override val longPollInBackground =
|
||||
MutableStateFlow(AppSettings.Experimental.longPollInBackground)
|
||||
override val useBlur = MutableStateFlow(AppSettings.Experimental.useBlur)
|
||||
override val useSystemFont = MutableStateFlow(AppSettings.Appearance.useSystemFont)
|
||||
override val enableAnimations = MutableStateFlow(AppSettings.Experimental.moreAnimations)
|
||||
override val showDebugCategory = MutableStateFlow(AppSettings.Debug.showDebugCategory)
|
||||
|
||||
override fun onUseContactNamesChanged(use: Boolean) {
|
||||
useContactNames.value = use
|
||||
}
|
||||
|
||||
override fun onEnablePullToRefreshChanged(enable: Boolean) {
|
||||
enablePullToRefresh.value = enable
|
||||
}
|
||||
|
||||
override fun onEnableMultilineChanged(enable: Boolean) {
|
||||
enableMultiline.value = enable
|
||||
}
|
||||
@@ -101,18 +81,10 @@ class UserSettingsImpl : UserSettings {
|
||||
appLanguage.value = language
|
||||
}
|
||||
|
||||
override fun onFastTextChanged(text: String) {
|
||||
fastText.value = text
|
||||
}
|
||||
|
||||
override fun onSendOnlineStatusChanged(send: Boolean) {
|
||||
sendOnlineStatus.value = send
|
||||
}
|
||||
|
||||
override fun onShowAlertAfterCrashChanged(show: Boolean) {
|
||||
showAlertAfterCrash.value = show
|
||||
}
|
||||
|
||||
override fun onLongPollInBackgroundChanged(inBackground: Boolean) {
|
||||
longPollInBackground.value = inBackground
|
||||
}
|
||||
@@ -121,14 +93,6 @@ class UserSettingsImpl : UserSettings {
|
||||
useBlur.value = use
|
||||
}
|
||||
|
||||
override fun onShowEmojiButtonChanged(show: Boolean) {
|
||||
showEmojiButton.value = show
|
||||
}
|
||||
|
||||
override fun onShowTimeInActionMessagesChanged(show: Boolean) {
|
||||
showTimeInActionMessages.value = show
|
||||
}
|
||||
|
||||
override fun onUseSystemFontChanged(use: Boolean) {
|
||||
useSystemFont.value = use
|
||||
}
|
||||
|
||||
@@ -8,11 +8,16 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(projects.core.common)
|
||||
api(projects.core.data)
|
||||
api(projects.core.model)
|
||||
|
||||
// TODO: 11/08/2024, Danil Nikolaev: remove?
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.koin.core)
|
||||
implementation(libs.eithernet)
|
||||
|
||||
implementation(libs.bundles.nanokt)
|
||||
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.compose.ui)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,32 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.model.api.responses.ExchangeSilentTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetAnonymTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetExchangeTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.ValidatePhoneResponse
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface AuthUseCase {
|
||||
interface AuthUseCase : BaseUseCase {
|
||||
|
||||
fun logout(): Flow<State<Int>>
|
||||
|
||||
fun validatePhone(
|
||||
validationSid: String
|
||||
): Flow<State<ValidatePhoneResponse>>
|
||||
|
||||
suspend fun getAnonymToken(
|
||||
clientId: String,
|
||||
clientSecret: String
|
||||
): Flow<State<GetAnonymTokenResponse>>
|
||||
|
||||
suspend fun exchangeSilentToken(
|
||||
anonymToken: String,
|
||||
silentToken: String,
|
||||
silentUuid: String
|
||||
): Flow<State<ExchangeSilentTokenResponse>>
|
||||
|
||||
suspend fun getExchangeToken(
|
||||
accessToken: String
|
||||
): Flow<State<GetExchangeTokenResponse>>
|
||||
}
|
||||
|
||||
@@ -3,16 +3,44 @@ package dev.meloda.fast.domain
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.data.api.auth.AuthRepository
|
||||
import dev.meloda.fast.data.mapToState
|
||||
import dev.meloda.fast.model.api.responses.ExchangeSilentTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetAnonymTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.GetExchangeTokenResponse
|
||||
import dev.meloda.fast.model.api.responses.ValidatePhoneResponse
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
class AuthUseCaseImpl(private val repository: AuthRepository) : AuthUseCase {
|
||||
|
||||
override fun validatePhone(validationSid: String): Flow<State<ValidatePhoneResponse>> = flow {
|
||||
emit(State.Loading)
|
||||
override fun logout(): Flow<State<Int>> = flowNewState { repository.logout().mapToState() }
|
||||
|
||||
val newState = repository.validatePhone(validationSid).mapToState()
|
||||
emit(newState)
|
||||
override fun validatePhone(validationSid: String): Flow<State<ValidatePhoneResponse>> =
|
||||
flowNewState { repository.validatePhone(validationSid = validationSid).mapToState() }
|
||||
|
||||
override suspend fun getAnonymToken(
|
||||
clientId: String,
|
||||
clientSecret: String
|
||||
): Flow<State<GetAnonymTokenResponse>> = flowNewState {
|
||||
repository.getAnonymToken(
|
||||
clientId = clientId,
|
||||
clientSecret = clientSecret
|
||||
).mapToState()
|
||||
}
|
||||
|
||||
override suspend fun exchangeSilentToken(
|
||||
anonymToken: String,
|
||||
silentToken: String,
|
||||
silentUuid: String
|
||||
): Flow<State<ExchangeSilentTokenResponse>> = flowNewState {
|
||||
repository.exchangeSilentToken(
|
||||
anonymToken = anonymToken,
|
||||
silentToken = silentToken,
|
||||
silentUuid = silentUuid
|
||||
).mapToState()
|
||||
}
|
||||
|
||||
override suspend fun getExchangeToken(
|
||||
accessToken: String
|
||||
): Flow<State<GetExchangeTokenResponse>> = flowNewState {
|
||||
repository.getExchangeToken(accessToken = accessToken).mapToState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import kotlinx.coroutines.flow.FlowCollector
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
interface BaseUseCase {
|
||||
|
||||
suspend fun <T> FlowCollector<State<T>>.emitState(stateBlock: suspend () -> State<T>) {
|
||||
emit(State.Loading)
|
||||
emit(stateBlock())
|
||||
}
|
||||
|
||||
fun <T> flowNewState(stateBlock: suspend () -> State<T>) =
|
||||
flow { emitState(stateBlock) }
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface ConversationsUseCase {
|
||||
|
||||
fun getConversations(
|
||||
count: Int?,
|
||||
offset: Int?,
|
||||
): Flow<State<List<VkConversation>>>
|
||||
|
||||
fun delete(peerId: Int): Flow<State<Int>>
|
||||
|
||||
fun changePinState(peerId: Int, pin: Boolean): Flow<State<Int>>
|
||||
|
||||
suspend fun storeConversations(conversations: List<VkConversation>)
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.data.api.conversations.ConversationsRepository
|
||||
import dev.meloda.fast.data.mapToState
|
||||
import dev.meloda.fast.model.api.domain.VkConversation
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class ConversationsUseCaseImpl(
|
||||
private val repository: ConversationsRepository,
|
||||
) : ConversationsUseCase {
|
||||
|
||||
// override fun getConversations(
|
||||
// count: Int?,
|
||||
// offset: Int?,
|
||||
// fields: String,
|
||||
// filter: String,
|
||||
// extended: Boolean?,
|
||||
// startMessageId: Int?
|
||||
// ): Flow<dev.meloda.fast.network.State<ConversationsResponseDomain>> = flow {
|
||||
// emit(dev.meloda.fast.network.State.Loading)
|
||||
//
|
||||
// val newState = conversationsRepository.getConversations(
|
||||
// params = ConversationsGetRequest(
|
||||
// count = count,
|
||||
// offset = offset,
|
||||
// fields = fields,
|
||||
// filter = filter,
|
||||
// extended = extended,
|
||||
// startMessageId = startMessageId
|
||||
// )
|
||||
// ).fold(
|
||||
// onSuccess = { response -> dev.meloda.fast.network.State.Success(response.toDomain()) },
|
||||
// onNetworkFailure = { dev.meloda.fast.network.State.Error.ConnectionError },
|
||||
// onUnknownFailure = { dev.meloda.fast.network.State.UNKNOWN_ERROR },
|
||||
// onHttpFailure = { result -> result.error.toStateApiError() },
|
||||
// onApiFailure = { result -> result.error.toStateApiError() }
|
||||
// )
|
||||
// emit(newState)
|
||||
// }
|
||||
//
|
||||
|
||||
//
|
||||
// override fun pin(peerId: Int): Flow<dev.meloda.fast.network.State<Unit>> = flow {
|
||||
// emit(dev.meloda.fast.network.State.Loading)
|
||||
//
|
||||
// val newState = conversationsRepository.pin(
|
||||
// ConversationsPinRequest(peerId = peerId)
|
||||
// ).fold(
|
||||
// onSuccess = { dev.meloda.fast.network.State.Success(Unit) },
|
||||
// onNetworkFailure = { dev.meloda.fast.network.State.Error.ConnectionError },
|
||||
// onUnknownFailure = { dev.meloda.fast.network.State.UNKNOWN_ERROR },
|
||||
// onHttpFailure = { result -> result.error.toStateApiError() },
|
||||
// onApiFailure = { result -> result.error.toStateApiError() }
|
||||
// )
|
||||
// emit(newState)
|
||||
// }
|
||||
//
|
||||
// override fun unpin(peerId: Int): Flow<dev.meloda.fast.network.State<Unit>> = flow {
|
||||
// emit(dev.meloda.fast.network.State.Loading)
|
||||
//
|
||||
// val newState = conversationsRepository.unpin(
|
||||
// ConversationsUnpinRequest(peerId = peerId)
|
||||
// ).fold(
|
||||
// onSuccess = { dev.meloda.fast.network.State.Success(Unit) },
|
||||
// onNetworkFailure = { dev.meloda.fast.network.State.Error.ConnectionError },
|
||||
// onUnknownFailure = { dev.meloda.fast.network.State.UNKNOWN_ERROR },
|
||||
// onHttpFailure = { result -> result.error.toStateApiError() },
|
||||
// onApiFailure = { result -> result.error.toStateApiError() }
|
||||
// )
|
||||
// emit(newState)
|
||||
// }
|
||||
//
|
||||
// override suspend fun storeConversations(conversations: List<VkConversationDomain>) {
|
||||
// conversationsDao.insertAll(conversations.map(VkConversationDomain::mapToDb))
|
||||
// }
|
||||
//
|
||||
// override suspend fun storeGroups(groups: List<VkGroupDomain>) {
|
||||
// groupsDao.insertAll(groups.map(VkGroupDomain::mapToDB))
|
||||
// }
|
||||
override fun getConversations(
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): Flow<State<List<VkConversation>>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = repository.getConversations(count, offset).mapToState()
|
||||
emit(newState)
|
||||
}
|
||||
|
||||
override suspend fun storeConversations(
|
||||
conversations: List<VkConversation>
|
||||
) = withContext(Dispatchers.IO) {
|
||||
repository.storeConversations(conversations)
|
||||
}
|
||||
|
||||
override fun delete(peerId: Int): Flow<State<Int>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = repository.delete(peerId = peerId).mapToState()
|
||||
emit(newState)
|
||||
}
|
||||
|
||||
override fun changePinState(peerId: Int, pin: Boolean): Flow<State<Int>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = if (pin) {
|
||||
repository.pin(peerId)
|
||||
} else {
|
||||
repository.unpin(peerId)
|
||||
}.mapToState()
|
||||
|
||||
emit(newState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.model.ConvosFilter
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface ConvoUseCase : BaseUseCase {
|
||||
|
||||
suspend fun storeConvos(convos: List<VkConvo>)
|
||||
suspend fun getLocalConvos(): List<VkConvo>
|
||||
suspend fun getLocalConvoById(peerId: Long): VkConvo?
|
||||
suspend fun deleteLocalConvo(peerId: Long)
|
||||
|
||||
fun getConvos(
|
||||
count: Int? = null,
|
||||
offset: Int? = null,
|
||||
filter: ConvosFilter
|
||||
): Flow<State<List<VkConvo>>>
|
||||
|
||||
fun getById(
|
||||
peerIds: List<Long>,
|
||||
extended: Boolean? = null,
|
||||
fields: String? = null
|
||||
): Flow<State<List<VkConvo>>>
|
||||
|
||||
fun delete(peerId: Long): Flow<State<Long>>
|
||||
|
||||
fun changePinState(peerId: Long, pin: Boolean): Flow<State<Int>>
|
||||
|
||||
fun changeArchivedState(peerId: Long, archive: Boolean): Flow<State<Int>>
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.data.api.convos.ConvosRepository
|
||||
import dev.meloda.fast.data.mapToState
|
||||
import dev.meloda.fast.model.ConvosFilter
|
||||
import dev.meloda.fast.model.api.domain.VkConvo
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class ConvoUseCaseImpl(
|
||||
private val repository: ConvosRepository,
|
||||
) : ConvoUseCase {
|
||||
|
||||
override suspend fun storeConvos(
|
||||
convos: List<VkConvo>
|
||||
) = withContext(Dispatchers.IO) {
|
||||
repository.storeConvos(convos)
|
||||
}
|
||||
|
||||
override suspend fun getLocalConvos(): List<VkConvo> = withContext(Dispatchers.IO) {
|
||||
repository.getLocalConvos()
|
||||
}
|
||||
|
||||
override suspend fun getLocalConvoById(peerId: Long): VkConvo? = withContext(Dispatchers.IO) {
|
||||
repository.getLocalConvoById(peerId)
|
||||
}
|
||||
|
||||
override suspend fun deleteLocalConvo(peerId: Long) = withContext(Dispatchers.IO) {
|
||||
repository.deleteLocalConvo(peerId)
|
||||
}
|
||||
|
||||
override fun getConvos(
|
||||
count: Int?,
|
||||
offset: Int?,
|
||||
filter: ConvosFilter
|
||||
): Flow<State<List<VkConvo>>> = flowNewState {
|
||||
repository.getConvos(
|
||||
count = count,
|
||||
offset = offset,
|
||||
filter = filter
|
||||
).mapToState()
|
||||
}
|
||||
|
||||
override fun getById(
|
||||
peerIds: List<Long>,
|
||||
extended: Boolean?,
|
||||
fields: String?
|
||||
): Flow<State<List<VkConvo>>> = flowNewState {
|
||||
repository.getConvosById(
|
||||
peerIds = peerIds,
|
||||
extended = extended,
|
||||
fields = fields
|
||||
).mapToState()
|
||||
}
|
||||
|
||||
override fun delete(peerId: Long): Flow<State<Long>> = flowNewState {
|
||||
repository.delete(peerId = peerId).mapToState()
|
||||
}
|
||||
|
||||
override fun changePinState(
|
||||
peerId: Long,
|
||||
pin: Boolean
|
||||
): Flow<State<Int>> = flowNewState {
|
||||
if (pin) {
|
||||
repository.pin(peerId)
|
||||
} else {
|
||||
repository.unpin(peerId)
|
||||
}.mapToState()
|
||||
}
|
||||
|
||||
override fun changeArchivedState(
|
||||
peerId: Long,
|
||||
archive: Boolean
|
||||
): Flow<State<Int>> = flowNewState {
|
||||
if (archive) {
|
||||
repository.archive(peerId)
|
||||
} else {
|
||||
repository.unarchive(peerId)
|
||||
}.mapToState()
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,13 @@ import kotlinx.coroutines.flow.Flow
|
||||
interface FriendsUseCase {
|
||||
|
||||
fun getAllFriends(
|
||||
order: String = "hints",
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): Flow<State<FriendsInfo>>
|
||||
|
||||
fun getFriends(
|
||||
order: String = "hints",
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): Flow<State<List<VkUser>>>
|
||||
@@ -20,7 +22,7 @@ interface FriendsUseCase {
|
||||
fun getOnlineFriends(
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): Flow<State<List<Int>>>
|
||||
): Flow<State<List<Long>>>
|
||||
|
||||
suspend fun storeUsers(users: List<VkUser>)
|
||||
}
|
||||
|
||||
@@ -11,25 +11,32 @@ import kotlinx.coroutines.flow.flow
|
||||
class FriendsUseCaseImpl(private val repository: FriendsRepository) :
|
||||
FriendsUseCase {
|
||||
|
||||
override fun getAllFriends(count: Int?, offset: Int?): Flow<State<FriendsInfo>> = flow {
|
||||
override fun getAllFriends(order: String, count: Int?, offset: Int?): Flow<State<FriendsInfo>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = repository.getAllFriends(count, offset).mapToState()
|
||||
val newState = repository.getAllFriends(order, count, offset).mapToState()
|
||||
emit(newState)
|
||||
}
|
||||
|
||||
override fun getFriends(
|
||||
count: Int?, offset: Int?
|
||||
order: String,
|
||||
count: Int?,
|
||||
offset: Int?
|
||||
): Flow<State<List<VkUser>>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = repository.getFriends(count, offset).mapToState()
|
||||
val newState = repository.getFriends(
|
||||
order = order,
|
||||
count = count,
|
||||
offset = offset
|
||||
).mapToState()
|
||||
|
||||
emit(newState)
|
||||
}
|
||||
|
||||
override fun getOnlineFriends(
|
||||
count: Int?, offset: Int?
|
||||
): Flow<State<List<Int>>> = flow {
|
||||
): Flow<State<List<Long>>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = repository.getOnlineFriends(count, offset).mapToState()
|
||||
|
||||
@@ -6,10 +6,7 @@ import dev.meloda.fast.model.database.AccountEntity
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class GetCurrentAccountUseCase(
|
||||
private val accountsRepository: AccountsRepository
|
||||
) {
|
||||
|
||||
class GetCurrentAccountUseCase(private val accountsRepository: AccountsRepository) {
|
||||
suspend operator fun invoke(): AccountEntity? = withContext(Dispatchers.IO) {
|
||||
accountsRepository.getAccountById(UserConfig.currentUserId)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import kotlinx.coroutines.flow.flow
|
||||
|
||||
class GetLocalUserByIdUseCase(private val repository: UsersRepository) {
|
||||
|
||||
operator fun invoke(userId: Int): Flow<State<VkUser?>> = flow {
|
||||
operator fun invoke(userId: Long): Flow<State<VkUser?>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = kotlin.runCatching {
|
||||
@@ -20,4 +20,8 @@ class GetLocalUserByIdUseCase(private val repository: UsersRepository) {
|
||||
|
||||
emit(newState)
|
||||
}
|
||||
|
||||
suspend fun proceed(userId: Long): VkUser? {
|
||||
return repository.getLocalUsers(userIds = listOf(userId)).singleOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import kotlinx.coroutines.flow.flow
|
||||
|
||||
class GetLocalUsersByIdsUseCase(private val repository: UsersRepository) {
|
||||
|
||||
operator fun invoke(userIds: List<Int>): Flow<State<List<VkUser>>> = flow {
|
||||
operator fun invoke(userIds: List<Long>): Flow<State<List<VkUser>>> = flow {
|
||||
emit(State.Loading)
|
||||
|
||||
val newState = kotlin.runCatching {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.meloda.fast.domain
|
||||
|
||||
import dev.meloda.fast.data.State
|
||||
import dev.meloda.fast.data.api.messages.MessagesRepository
|
||||
import dev.meloda.fast.data.mapToState
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class GetMessageReadPeersUseCase(
|
||||
private val repository: MessagesRepository
|
||||
) : BaseUseCase {
|
||||
|
||||
operator fun invoke(
|
||||
peerId: Long,
|
||||
cmId: Long
|
||||
): Flow<State<Int>> = flowNewState {
|
||||
repository.getMessageReadPeers(
|
||||
peerId = peerId,
|
||||
cmId = cmId
|
||||
).mapToState(successMapper = { it.totalCount })
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user