Compare commits
214 commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
ae61fc9c6f | ||
![]() |
c291fa70d3 | ||
![]() |
232acfa211 | ||
![]() |
f25f119ca1 | ||
![]() |
89a61b3bf7 | ||
![]() |
380d37267b | ||
![]() |
9cf5691e42 | ||
![]() |
8f474a4500 | ||
![]() |
c7be2270ff | ||
![]() |
ced1f0bd79 | ||
![]() |
9f58f1eeb3 | ||
![]() |
04be2b6a2c | ||
![]() |
9f361237b1 | ||
![]() |
8cb7cae7b7 | ||
![]() |
a2a209a849 | ||
![]() |
d413c4f4c1 | ||
![]() |
ee8976e92b | ||
![]() |
baa90c42ad | ||
![]() |
30ade541df | ||
![]() |
86fb8ebfaf | ||
![]() |
b2e8c3c0eb | ||
![]() |
e203a8378e | ||
![]() |
b100f1d4bf | ||
![]() |
7b4559f3ca | ||
![]() |
eac142025d | ||
![]() |
c5aa536c3b | ||
![]() |
05406333e4 | ||
![]() |
8ebd50606a | ||
![]() |
cbcfc243fc | ||
![]() |
7d497b5ae1 | ||
![]() |
b28f6c3d8c | ||
![]() |
71a8049a35 | ||
![]() |
e95cba0ace | ||
![]() |
e836ada0d6 | ||
![]() |
19a104374d | ||
![]() |
693ef45e2c | ||
![]() |
55bdb070ce | ||
![]() |
27127ff3d4 | ||
![]() |
345c706814 | ||
![]() |
49133b7b86 | ||
![]() |
3a5311cdcc | ||
![]() |
7182795732 | ||
![]() |
ca00b3b558 | ||
![]() |
4bcb765810 | ||
![]() |
17b49595a0 | ||
![]() |
b99c573d3a | ||
![]() |
d3d3e4dbed | ||
![]() |
ba1af5eaf0 | ||
![]() |
14cf59c1e5 | ||
![]() |
452872156a | ||
![]() |
4f31bd625d | ||
![]() |
6bf6f78147 | ||
![]() |
5576f99548 | ||
![]() |
5bbe768acb | ||
![]() |
babe378301 | ||
![]() |
b2fda16561 | ||
![]() |
6d289d73db | ||
![]() |
17acf4b3ee | ||
![]() |
4d666d4b01 | ||
![]() |
619f8319ed | ||
![]() |
3261da3515 | ||
![]() |
d0d491f7f5 | ||
![]() |
db3764d448 | ||
![]() |
5fe5451f5c | ||
![]() |
6d3d5d03f8 | ||
![]() |
582eb9e1ea | ||
![]() |
51770a11ef | ||
![]() |
1ea7a8f3a7 | ||
![]() |
b4536a7aee | ||
![]() |
9d2be29fad | ||
![]() |
f92a18efca | ||
![]() |
af382d483d | ||
![]() |
99f1ba799d | ||
![]() |
1548bcd378 | ||
![]() |
c2fc0a3d57 | ||
![]() |
39a706ea20 | ||
![]() |
38d6464f55 | ||
![]() |
c5b6297cea | ||
![]() |
390b4b1f81 | ||
![]() |
b19b34b3dc | ||
![]() |
5690d613bb | ||
![]() |
bb713cfc76 | ||
![]() |
4a0c93373d | ||
![]() |
b42759d473 | ||
![]() |
2e93281368 | ||
![]() |
c18be32c09 | ||
![]() |
650163c341 | ||
![]() |
d101208baa | ||
![]() |
76f7215269 | ||
![]() |
621c482529 | ||
![]() |
314c8f69f2 | ||
![]() |
1f45cf00c7 | ||
![]() |
e0e80ee91f | ||
![]() |
225278adb7 | ||
![]() |
8d30bfbefa | ||
![]() |
ad96f679c9 | ||
![]() |
4b896d3aab | ||
![]() |
533e6d06e7 | ||
![]() |
e88b5c99ba | ||
![]() |
1ec7e02695 | ||
![]() |
19e08cf803 | ||
![]() |
08073b927c | ||
![]() |
711a44412d | ||
![]() |
c9f94f062b | ||
![]() |
c8205b8475 | ||
![]() |
b0d3fcfe79 | ||
![]() |
11a354c560 | ||
![]() |
823f739c32 | ||
![]() |
f8876c8154 | ||
![]() |
90db45d845 | ||
![]() |
6a1f5945b9 | ||
![]() |
f7ca838428 | ||
![]() |
2b065dd68d | ||
![]() |
f168ea9e1e | ||
![]() |
58702103f3 | ||
![]() |
dfb3a6f65c | ||
![]() |
491f38b120 | ||
![]() |
79c0880c9c | ||
![]() |
834b8f78b7 | ||
![]() |
cbf0336cd0 | ||
![]() |
431d629641 | ||
![]() |
94c1cc011b | ||
![]() |
b26b0759d6 | ||
![]() |
d51fb99fd3 | ||
![]() |
0379216e05 | ||
![]() |
ccd486f659 | ||
![]() |
ce3ab55069 | ||
![]() |
34effef810 | ||
![]() |
56aceb589d | ||
![]() |
92a2506f8a | ||
![]() |
e23bc2602f | ||
![]() |
69beecb7bb | ||
![]() |
880b13f436 | ||
![]() |
9061caac99 | ||
![]() |
11cc8e46b7 | ||
![]() |
54820689c2 | ||
![]() |
acebb86fec | ||
![]() |
367e09599d | ||
![]() |
b9fe509567 | ||
![]() |
82bffd81de | ||
![]() |
7340443b86 | ||
![]() |
2cd1dfd720 | ||
![]() |
3c8d29bcdc | ||
![]() |
06a698ddbb | ||
![]() |
3b8c48e92d | ||
![]() |
3c0cb20a9b | ||
![]() |
74bb169f0d | ||
![]() |
302890baef | ||
![]() |
54e33d3f42 | ||
![]() |
0adb94f405 | ||
![]() |
7d634aa703 | ||
![]() |
b1e0c83733 | ||
![]() |
d4af7792d4 | ||
![]() |
f301ab57f2 | ||
![]() |
7b0f5909b5 | ||
![]() |
e9064f6904 | ||
![]() |
0d21fc77b5 | ||
![]() |
b26c6e9c0d | ||
![]() |
057d11f39b | ||
![]() |
c9de6d7a82 | ||
![]() |
698ac9f29e | ||
![]() |
a0d26c860c | ||
![]() |
bd2444d353 | ||
![]() |
ca24a86179 | ||
![]() |
fffe96a4c7 | ||
![]() |
0ec75c2435 | ||
![]() |
cb78c848d6 | ||
![]() |
6594db9393 | ||
![]() |
f6c40ee67d | ||
![]() |
36aa33ed5a | ||
![]() |
776dba4fb0 | ||
![]() |
7f49f530c5 | ||
![]() |
ef6fe80944 | ||
![]() |
370b28f9e4 | ||
![]() |
05e737cb11 | ||
![]() |
0fdb58eda1 | ||
![]() |
1ce90839fe | ||
![]() |
697946f415 | ||
![]() |
cc91cb8012 | ||
![]() |
754de7065f | ||
![]() |
5587373b42 | ||
![]() |
f1d1a4a9e1 | ||
![]() |
dc38a8bc9f | ||
![]() |
edf9f743f4 | ||
![]() |
fec040e528 | ||
![]() |
86f96a5713 | ||
![]() |
c3fb472287 | ||
![]() |
eaf8b9cebc | ||
![]() |
2ce9212457 | ||
![]() |
4fa59ce258 | ||
![]() |
59ed89cba1 | ||
![]() |
623b71715d | ||
![]() |
a74943698f | ||
![]() |
bfe8fd83ac | ||
![]() |
0a01cac57b | ||
![]() |
b7f248fa93 | ||
![]() |
d814b6cdf0 | ||
![]() |
1712bf60cb | ||
![]() |
369a5a5233 | ||
![]() |
9bae31d748 | ||
![]() |
11453b327f | ||
![]() |
7780c1c7b7 | ||
![]() |
0f1c98d0d0 | ||
![]() |
48fcbdc98c | ||
![]() |
90d0196d47 | ||
![]() |
30a8691c7f | ||
![]() |
69cea6786d | ||
![]() |
ccac5e73a3 | ||
![]() |
3e79c8cf28 | ||
![]() |
31dee1249d | ||
![]() |
e5a293a6ab | ||
![]() |
ffcb68b32f | ||
![]() |
a8af90dfee | ||
![]() |
51756d45d9 |
271 changed files with 2385 additions and 1826 deletions
14
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
14
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
@ -4,11 +4,12 @@ labels: ["triage"]
|
|||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: >
|
||||
Before opening a new issue, please ensure you are on the latest
|
||||
version (it might've already been fixed), and that you've searched
|
||||
for existing issues (please add you observations as a comment
|
||||
there instead of creating a duplicate).
|
||||
value: |
|
||||
Before opening a new bug report, please ensure
|
||||
1. you are on the latest version (it might've already been fixed),
|
||||
2. you've searched for existing issues (please add your observations as a comment there instead of creating a duplicate).
|
||||
|
||||
If you are self hosting, please create a community [Q&A](https://github.com/ente-io/ente/discussions/categories/q-a) instead.
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Description
|
||||
|
@ -16,7 +17,8 @@ body:
|
|||
Please describe the bug. If possible, also include the steps to
|
||||
reproduce the behaviour, and the expected behaviour (sometimes
|
||||
bugs are just expectation mismatches, in which case this would be
|
||||
a good fit for Discussions).
|
||||
a good fit for [feature
|
||||
requests](https://github.com/ente-io/ente/discussions/categories/feature-requests)).
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
|
|
|
@ -20,6 +20,8 @@
|
|||
"codeIssuerHint": "発行者",
|
||||
"codeSecretKeyHint": "秘密鍵",
|
||||
"codeAccountHint": "アカウント (you@domain.com)",
|
||||
"codeTagHint": "タグ",
|
||||
"accountKeyType": "鍵の種類",
|
||||
"sessionExpired": "セッションが失効しました",
|
||||
"@sessionExpired": {
|
||||
"description": "Title of the dialog when the users current session is invalid/expired"
|
||||
|
@ -77,6 +79,7 @@
|
|||
"data": "データ",
|
||||
"importCodes": "コードをインポート",
|
||||
"importTypePlainText": "プレーンテキスト",
|
||||
"importTypeEnteEncrypted": "Ente 暗号化されたエクスポート",
|
||||
"passwordForDecryptingExport": "復号化用パスワード",
|
||||
"passwordEmptyError": "パスワードは空欄にできません",
|
||||
"importFromApp": "{appName} からコードをインポート",
|
||||
|
@ -121,6 +124,7 @@
|
|||
"suggestFeatures": "機能を提案",
|
||||
"faq": "FAQ",
|
||||
"faq_q_1": "Authはどのくらい安全ですか?",
|
||||
"faq_a_1": "Ente Authでバックアップされたコードはすべてエンドツーエンドで暗号化されて保存されます。つまり、コードにアクセスできるのはあなただけです。当社のアプリはオープンソースであり、暗号化技術は外部監査を受けています。",
|
||||
"faq_q_2": "パソコンから私のコードにアクセスできますか?",
|
||||
"faq_a_2": "auth.ente.io で Web からコードにアクセス可能です。",
|
||||
"faq_q_3": "コードを削除するにはどうすればいいですか?",
|
||||
|
@ -154,6 +158,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"invalidQRCode": "QRコードが無効です",
|
||||
"noRecoveryKeyTitle": "回復キーがありませんか?",
|
||||
"enterEmailHint": "メールアドレスを入力してください",
|
||||
"invalidEmailTitle": "メールアドレスが無効です",
|
||||
|
@ -347,6 +352,7 @@
|
|||
"deleteCodeAuthMessage": "コードを削除するためには認証が必要です",
|
||||
"showQRAuthMessage": "QR コードを表示するためには認証が必要です",
|
||||
"confirmAccountDeleteTitle": "アカウントの削除に同意",
|
||||
"confirmAccountDeleteMessage": "このアカウントは他のEnteアプリも使用している場合はそれらにも紐づけされています。\nすべてのEnteアプリでアップロードされたデータは削除され、アカウントは完全に削除されます。",
|
||||
"androidBiometricHint": "本人を確認する",
|
||||
"@androidBiometricHint": {
|
||||
"description": "Hint message advising the user how to authenticate with biometrics. It is used on Android side. Maximum 60 characters."
|
||||
|
@ -417,5 +423,18 @@
|
|||
"invalidEndpoint": "無効なエンドポイントです",
|
||||
"invalidEndpointMessage": "入力されたエンドポイントは無効です。有効なエンドポイントを入力して再試行してください。",
|
||||
"endpointUpdatedMessage": "エンドポイントの更新に成功しました",
|
||||
"customEndpoint": "{endpoint} に接続しました"
|
||||
"customEndpoint": "{endpoint} に接続しました",
|
||||
"pinText": "固定",
|
||||
"unpinText": "固定を解除",
|
||||
"pinnedCodeMessage": "{code} を固定しました",
|
||||
"unpinnedCodeMessage": "{code} の固定が解除されました",
|
||||
"tags": "タグ",
|
||||
"createNewTag": "新しいタグの作成",
|
||||
"tag": "タグ",
|
||||
"create": "作成",
|
||||
"editTag": "タグの編集",
|
||||
"deleteTagTitle": "タグを削除しますか?",
|
||||
"deleteTagMessage": "このタグを削除してもよろしいですか?この操作は取り消しできません。",
|
||||
"somethingWentWrongParsingCode": "{x} のコードを解析できませんでした。",
|
||||
"updateNotAvailable": "アップデートは利用できません"
|
||||
}
|
|
@ -30,7 +30,7 @@
|
|||
"compare-versions": "^6.1",
|
||||
"electron-log": "^5.1",
|
||||
"electron-store": "^8.2",
|
||||
"electron-updater": "^6.1",
|
||||
"electron-updater": "^6.2",
|
||||
"ffmpeg-static": "^5.2",
|
||||
"html-entities": "^2.5",
|
||||
"jpeg-js": "^0.4",
|
||||
|
|
|
@ -743,10 +743,10 @@ buffer@^5.1.0, buffer@^5.5.0:
|
|||
base64-js "^1.3.1"
|
||||
ieee754 "^1.1.13"
|
||||
|
||||
builder-util-runtime@9.2.3:
|
||||
version "9.2.3"
|
||||
resolved "https://registry.yarnpkg.com/builder-util-runtime/-/builder-util-runtime-9.2.3.tgz#0a82c7aca8eadef46d67b353c638f052c206b83c"
|
||||
integrity sha512-FGhkqXdFFZ5dNC4C+yuQB9ak311rpGAw+/ASz8ZdxwODCv1GGMWgLDeofRkdi0F3VCHQEWy/aXcJQozx2nOPiw==
|
||||
builder-util-runtime@9.2.4:
|
||||
version "9.2.4"
|
||||
resolved "https://registry.yarnpkg.com/builder-util-runtime/-/builder-util-runtime-9.2.4.tgz#13cd1763da621e53458739a1e63f7fcba673c42a"
|
||||
integrity sha512-upp+biKpN/XZMLim7aguUyW8s0FUpDvOtK6sbanMFDAMBzpHDqdhgVYm6zc9HJ6nWo7u2Lxk60i2M6Jd3aiNrA==
|
||||
dependencies:
|
||||
debug "^4.3.4"
|
||||
sax "^1.2.4"
|
||||
|
@ -1251,12 +1251,12 @@ electron-store@^8.2:
|
|||
conf "^10.2.0"
|
||||
type-fest "^2.17.0"
|
||||
|
||||
electron-updater@^6.1:
|
||||
version "6.1.8"
|
||||
resolved "https://registry.yarnpkg.com/electron-updater/-/electron-updater-6.1.8.tgz#17637bca165322f4e526b13c99165f43e6f697d8"
|
||||
integrity sha512-hhOTfaFAd6wRHAfUaBhnAOYc+ymSGCWJLtFkw4xJqOvtpHmIdNHnXDV9m1MHC+A6q08Abx4Ykgyz/R5DGKNAMQ==
|
||||
electron-updater@^6.2:
|
||||
version "6.2.1"
|
||||
resolved "https://registry.yarnpkg.com/electron-updater/-/electron-updater-6.2.1.tgz#1c9adb9ba2a21a5dc50a8c434c45360d5e9fe6c9"
|
||||
integrity sha512-83eKIPW14qwZqUUM6wdsIRwVKZyjmHxQ4/8G+1C6iS5PdDt7b1umYQyj1/qPpH510GmHEQe4q0kCPe3qmb3a0Q==
|
||||
dependencies:
|
||||
builder-util-runtime "9.2.3"
|
||||
builder-util-runtime "9.2.4"
|
||||
fs-extra "^10.1.0"
|
||||
js-yaml "^4.1.0"
|
||||
lazy-val "^1.0.5"
|
||||
|
|
|
@ -163,6 +163,10 @@ export const sidebar = [
|
|||
text: "From Authy",
|
||||
link: "/auth/migration-guides/authy/",
|
||||
},
|
||||
{
|
||||
text: "From Steam",
|
||||
link: "/auth/migration-guides/steam/",
|
||||
},
|
||||
{
|
||||
text: "Exporting your data",
|
||||
link: "/auth/migration-guides/export",
|
||||
|
|
|
@ -7,4 +7,5 @@ description:
|
|||
# Migrating to/from Ente Auth
|
||||
|
||||
- [Migrating from Authy](authy/)
|
||||
- [Importing codes from Steam](steam/)
|
||||
- [Exporting your data out of Ente Auth](export)
|
||||
|
|
79
docs/docs/auth/migration-guides/steam/index.md
Normal file
79
docs/docs/auth/migration-guides/steam/index.md
Normal file
|
@ -0,0 +1,79 @@
|
|||
---
|
||||
title: Migrating from Steam Authenticator
|
||||
description: Guide for importing from Steam Authenticator to Ente Auth
|
||||
---
|
||||
|
||||
# Migrating from Steam Authenticator
|
||||
|
||||
A guide written by an ente.io lover
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> Steam Authenticator code is only supported after auth-v3.0.3, check the app's
|
||||
> version number before migration.
|
||||
|
||||
One way to migrate is to
|
||||
[use this tool by dyc3](https://github.com/dyc3/steamguard-cli/releases/latest)
|
||||
to simplify the process and skip directly to generating a qr code to Ente
|
||||
Authenticator.
|
||||
|
||||
## Download/Install steamguard-cli
|
||||
|
||||
### Windows
|
||||
|
||||
1. Download `steamguard.exe` from the [releases page][releases].
|
||||
2. Place `steamguard.exe` in a folder of your choice. For this example, we will
|
||||
use `%USERPROFILE%\Desktop`.
|
||||
3. Open Powershell or Command Prompt. The prompt should be at `%USERPROFILE%`
|
||||
(eg. `C:\Users\<username>`).
|
||||
4. Use `cd` to change directory into the folder where you placed
|
||||
`steamguard.exe`. For this example, it would be `cd Desktop`.
|
||||
5. You should now be able to run `steamguard.exe` by typing
|
||||
`.\steamguard.exe --help` and pressing enter.
|
||||
|
||||
### Linux
|
||||
|
||||
#### Ubuntu/Debian
|
||||
|
||||
1. Download the `.deb` from the [releases page][releases].
|
||||
2. Open a terminal and run this to install it:
|
||||
|
||||
```bash
|
||||
sudo dpkg -i ./steamguard-cli_<version>_amd64.deb
|
||||
```
|
||||
|
||||
#### Other Linux
|
||||
|
||||
1. Download `steamguard` from the [releases page][releases]
|
||||
2. Make it executable, and move `steamguard` to `/usr/local/bin` or any other
|
||||
directory in your `$PATH`.
|
||||
|
||||
```bash
|
||||
chmod +x ./steamguard
|
||||
sudo mv ./steamguard /usr/local/bin
|
||||
```
|
||||
|
||||
3. You should now be able to run `steamguard` by typing `steamguard --help` and
|
||||
pressing enter.
|
||||
|
||||
## Login to Steam account
|
||||
|
||||
Set up a new account with steamguard-cli
|
||||
|
||||
```bash
|
||||
steamguard setup # set up a new account with steamguard-cli
|
||||
```
|
||||
|
||||
## Generate & importing QR codes
|
||||
|
||||
steamguard-cli can then generate a QR code for your 2FA secret.
|
||||
|
||||
```bash
|
||||
steamguard qr # print QR code for the first account in your maFiles
|
||||
steamguard -u <account name> qr # print QR code for a specific account
|
||||
```
|
||||
|
||||
Open Ente Auth, press the '+' button, select `Scan a QR code`, and scan the qr
|
||||
code.
|
||||
|
||||
You should now have your steam code inside Ente Auth
|
|
@ -78,3 +78,23 @@ To summarize:
|
|||
Set the S3 bucket `endpoint` in `credentials.yaml` to a `yourserverip:3200` or
|
||||
some such IP/hostname that accessible from both where you are running the Ente
|
||||
clients (e.g. the mobile app) and also from within the Docker compose cluster.
|
||||
|
||||
### 403 Forbidden
|
||||
|
||||
If museum (`2`) is able to make a network connection to your S3 bucket (`3`) but
|
||||
uploads are still failing, it could be a credentials or permissions issue. A
|
||||
telltale sign of this is that in the museum logs you can see `403 Forbidden`
|
||||
errors about it not able to find the size of a file even though the
|
||||
corresponding object exists in the S3 bucket.
|
||||
|
||||
To fix these, you should ensure the following:
|
||||
|
||||
1. The bucket CORS rules do not allow museum to access these objects.
|
||||
|
||||
> For uploading files from the browser, you will need to currently set
|
||||
> allowedOrigins to "\*", and allow the "X-Auth-Token", "X-Client-Package"
|
||||
> headers configuration too.
|
||||
> [Here is an example of a working configuration](https://github.com/ente-io/ente/discussions/1764#discussioncomment-9478204).
|
||||
|
||||
2. The credentials are not being picked up (you might be setting the correct
|
||||
creds, but not in the place where museum picks them from).
|
||||
|
|
|
@ -35,10 +35,10 @@ import 'package:photos/services/sync_service.dart';
|
|||
import 'package:photos/utils/crypto_util.dart';
|
||||
import 'package:photos/utils/file_uploader.dart';
|
||||
import 'package:photos/utils/validator_util.dart';
|
||||
import "package:photos/utils/wakelock_util.dart";
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import "package:tuple/tuple.dart";
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
|
||||
class Configuration {
|
||||
Configuration._privateConstructor();
|
||||
|
@ -585,7 +585,7 @@ class Configuration {
|
|||
|
||||
Future<void> setShouldKeepDeviceAwake(bool value) async {
|
||||
await _preferences.setBool(keyShouldKeepDeviceAwake, value);
|
||||
await WakelockPlus.toggle(enable: value);
|
||||
await EnteWakeLock.toggle(enable: value);
|
||||
}
|
||||
|
||||
Future<void> setShouldBackupVideos(bool value) async {
|
||||
|
|
|
@ -69,6 +69,8 @@ const galleryGridSpacing = 2.0;
|
|||
|
||||
const kSearchSectionLimit = 9;
|
||||
|
||||
const maxPickAssetLimit = 50;
|
||||
|
||||
const iOSGroupID = "group.io.ente.frame.SlideshowWidget";
|
||||
|
||||
const blackThumbnailBase64 = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEB'
|
||||
|
|
|
@ -13,6 +13,8 @@ import "package:photos/face/model/face.dart";
|
|||
import "package:photos/models/file/file.dart";
|
||||
import "package:photos/services/machine_learning/face_ml/face_clustering/face_info_for_clustering.dart";
|
||||
import 'package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart';
|
||||
import "package:photos/services/machine_learning/face_ml/face_ml_result.dart";
|
||||
import "package:photos/utils/ml_util.dart";
|
||||
import 'package:sqlite_async/sqlite_async.dart';
|
||||
|
||||
/// Stores all data for the FacesML-related features. The database can be accessed by `FaceMLDataDB.instance.database`.
|
||||
|
@ -33,6 +35,15 @@ class FaceMLDataDB {
|
|||
|
||||
static final FaceMLDataDB instance = FaceMLDataDB._privateConstructor();
|
||||
|
||||
static final _migrationScripts = [
|
||||
createFacesTable,
|
||||
createFaceClustersTable,
|
||||
createClusterPersonTable,
|
||||
createClusterSummaryTable,
|
||||
createNotPersonFeedbackTable,
|
||||
fcClusterIDIndex,
|
||||
];
|
||||
|
||||
// only have a single app-wide reference to the database
|
||||
static Future<SqliteDatabase>? _sqliteAsyncDBFuture;
|
||||
|
||||
|
@ -48,17 +59,42 @@ class FaceMLDataDB {
|
|||
_logger.info("Opening sqlite_async access: DB path " + databaseDirectory);
|
||||
final asyncDBConnection =
|
||||
SqliteDatabase(path: databaseDirectory, maxReaders: 2);
|
||||
await _onCreate(asyncDBConnection);
|
||||
final stopwatch = Stopwatch()..start();
|
||||
_logger.info("FaceMLDataDB: Starting migration");
|
||||
await _migrate(asyncDBConnection);
|
||||
_logger.info(
|
||||
"FaceMLDataDB Migration took ${stopwatch.elapsedMilliseconds} ms",
|
||||
);
|
||||
stopwatch.stop();
|
||||
|
||||
return asyncDBConnection;
|
||||
}
|
||||
|
||||
Future<void> _onCreate(SqliteDatabase asyncDBConnection) async {
|
||||
await asyncDBConnection.execute(createFacesTable);
|
||||
await asyncDBConnection.execute(createFaceClustersTable);
|
||||
await asyncDBConnection.execute(createClusterPersonTable);
|
||||
await asyncDBConnection.execute(createClusterSummaryTable);
|
||||
await asyncDBConnection.execute(createNotPersonFeedbackTable);
|
||||
await asyncDBConnection.execute(fcClusterIDIndex);
|
||||
Future<void> _migrate(
|
||||
SqliteDatabase database,
|
||||
) async {
|
||||
final result = await database.execute('PRAGMA user_version');
|
||||
final currentVersion = result[0]['user_version'] as int;
|
||||
final toVersion = _migrationScripts.length;
|
||||
|
||||
if (currentVersion < toVersion) {
|
||||
_logger.info("Migrating database from $currentVersion to $toVersion");
|
||||
await database.writeTransaction((tx) async {
|
||||
for (int i = currentVersion + 1; i <= toVersion; i++) {
|
||||
try {
|
||||
await tx.execute(_migrationScripts[i - 1]);
|
||||
} catch (e) {
|
||||
_logger.severe("Error running migration script index ${i - 1}", e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
await tx.execute('PRAGMA user_version = $toVersion');
|
||||
});
|
||||
} else if (currentVersion > toVersion) {
|
||||
throw AssertionError(
|
||||
"currentVersion($currentVersion) cannot be greater than toVersion($toVersion)",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// bulkInsertFaces inserts the faces in the database in batches of 1000.
|
||||
|
@ -193,10 +229,10 @@ class FaceMLDataDB {
|
|||
final db = await instance.asyncDB;
|
||||
|
||||
await db.execute(deleteFacesTable);
|
||||
await db.execute(dropClusterPersonTable);
|
||||
await db.execute(dropClusterSummaryTable);
|
||||
await db.execute(deletePersonTable);
|
||||
await db.execute(dropNotPersonFeedbackTable);
|
||||
await db.execute(deleteFaceClustersTable);
|
||||
await db.execute(deleteClusterPersonTable);
|
||||
await db.execute(deleteClusterSummaryTable);
|
||||
await db.execute(deleteNotPersonFeedbackTable);
|
||||
}
|
||||
|
||||
Future<Iterable<Uint8List>> getFaceEmbeddingsForCluster(
|
||||
|
@ -249,7 +285,7 @@ class FaceMLDataDB {
|
|||
final List<int> fileId = [recentFileID];
|
||||
int? avatarFileId;
|
||||
if (avatarFaceId != null) {
|
||||
avatarFileId = int.tryParse(avatarFaceId.split('_')[0]);
|
||||
avatarFileId = tryGetFileIdFromFaceId(avatarFaceId);
|
||||
if (avatarFileId != null) {
|
||||
fileId.add(avatarFileId);
|
||||
}
|
||||
|
@ -401,8 +437,10 @@ class FaceMLDataDB {
|
|||
final personID = map[personIdColumn] as String;
|
||||
final clusterID = map[fcClusterID] as int;
|
||||
final faceID = map[fcFaceId] as String;
|
||||
result.putIfAbsent(personID, () => {}).putIfAbsent(clusterID, () => {})
|
||||
.add(faceID);
|
||||
result
|
||||
.putIfAbsent(personID, () => {})
|
||||
.putIfAbsent(clusterID, () => {})
|
||||
.add(faceID);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
@ -476,8 +514,7 @@ class FaceMLDataDB {
|
|||
for (final map in maps) {
|
||||
final clusterID = map[fcClusterID] as int;
|
||||
final faceID = map[fcFaceId] as String;
|
||||
final x = faceID.split('_').first;
|
||||
final fileID = int.parse(x);
|
||||
final fileID = getFileIdFromFaceId(faceID);
|
||||
result[fileID] = (result[fileID] ?? {})..add(clusterID);
|
||||
}
|
||||
return result;
|
||||
|
@ -665,19 +702,55 @@ class FaceMLDataDB {
|
|||
return maps.first['count'] as int;
|
||||
}
|
||||
|
||||
Future<int> getClusteredFaceCount() async {
|
||||
Future<int> getClusteredOrFacelessFileCount() async {
|
||||
final db = await instance.asyncDB;
|
||||
final List<Map<String, dynamic>> maps = await db.getAll(
|
||||
'SELECT COUNT(DISTINCT $fcFaceId) as count FROM $faceClustersTable',
|
||||
final List<Map<String, dynamic>> clustered = await db.getAll(
|
||||
'SELECT $fcFaceId FROM $faceClustersTable',
|
||||
);
|
||||
return maps.first['count'] as int;
|
||||
final Set<int> clusteredFileIDs = {};
|
||||
for (final map in clustered) {
|
||||
final int fileID = getFileIdFromFaceId(map[fcFaceId] as String);
|
||||
clusteredFileIDs.add(fileID);
|
||||
}
|
||||
|
||||
final List<Map<String, dynamic>> badFacesFiles = await db.getAll(
|
||||
'SELECT DISTINCT $fileIDColumn FROM $facesTable WHERE $faceScore <= $kMinimumQualityFaceScore OR $faceBlur <= $kLaplacianHardThreshold',
|
||||
);
|
||||
final Set<int> badFileIDs = {};
|
||||
for (final map in badFacesFiles) {
|
||||
badFileIDs.add(map[fileIDColumn] as int);
|
||||
}
|
||||
|
||||
final List<Map<String, dynamic>> goodFacesFiles = await db.getAll(
|
||||
'SELECT DISTINCT $fileIDColumn FROM $facesTable WHERE $faceScore > $kMinimumQualityFaceScore AND $faceBlur > $kLaplacianHardThreshold',
|
||||
);
|
||||
final Set<int> goodFileIDs = {};
|
||||
for (final map in goodFacesFiles) {
|
||||
goodFileIDs.add(map[fileIDColumn] as int);
|
||||
}
|
||||
final trulyFacelessFiles = badFileIDs.difference(goodFileIDs);
|
||||
return clusteredFileIDs.length + trulyFacelessFiles.length;
|
||||
}
|
||||
|
||||
Future<double> getClusteredToTotalFacesRatio() async {
|
||||
final int totalFaces = await getTotalFaceCount();
|
||||
final int clusteredFaces = await getClusteredFaceCount();
|
||||
Future<double> getClusteredToIndexableFilesRatio() async {
|
||||
final int indexableFiles = (await getIndexableFileIDs()).length;
|
||||
final int clusteredFiles = await getClusteredOrFacelessFileCount();
|
||||
|
||||
return clusteredFaces / totalFaces;
|
||||
return clusteredFiles / indexableFiles;
|
||||
}
|
||||
|
||||
Future<int> getUnclusteredFaceCount() async {
|
||||
final db = await instance.asyncDB;
|
||||
const String query = '''
|
||||
SELECT f.$faceIDColumn
|
||||
FROM $facesTable f
|
||||
LEFT JOIN $faceClustersTable fc ON f.$faceIDColumn = fc.$fcFaceId
|
||||
WHERE f.$faceScore > $kMinimumQualityFaceScore
|
||||
AND f.$faceBlur > $kLaplacianHardThreshold
|
||||
AND fc.$fcFaceId IS NULL
|
||||
''';
|
||||
final List<Map<String, dynamic>> maps = await db.getAll(query);
|
||||
return maps.length;
|
||||
}
|
||||
|
||||
Future<int> getBlurryFaceCount([
|
||||
|
@ -695,7 +768,7 @@ class FaceMLDataDB {
|
|||
try {
|
||||
final db = await instance.asyncDB;
|
||||
|
||||
await db.execute(dropFaceClustersTable);
|
||||
await db.execute(deleteFaceClustersTable);
|
||||
await db.execute(createFaceClustersTable);
|
||||
await db.execute(fcClusterIDIndex);
|
||||
} catch (e, s) {
|
||||
|
@ -795,7 +868,7 @@ class FaceMLDataDB {
|
|||
for (final map in maps) {
|
||||
final clusterID = map[clusterIDColumn] as int;
|
||||
final String faceID = map[fcFaceId] as String;
|
||||
final fileID = int.parse(faceID.split('_').first);
|
||||
final fileID = getFileIdFromFaceId(faceID);
|
||||
result[fileID] = (result[fileID] ?? {})..add(clusterID);
|
||||
}
|
||||
return result;
|
||||
|
@ -814,8 +887,8 @@ class FaceMLDataDB {
|
|||
final Map<int, Set<int>> result = {};
|
||||
for (final map in maps) {
|
||||
final clusterID = map[fcClusterID] as int;
|
||||
final faceId = map[fcFaceId] as String;
|
||||
final fileID = int.parse(faceId.split("_").first);
|
||||
final faceID = map[fcFaceId] as String;
|
||||
final fileID = getFileIdFromFaceId(faceID);
|
||||
result[fileID] = (result[fileID] ?? {})..add(clusterID);
|
||||
}
|
||||
return result;
|
||||
|
@ -906,16 +979,15 @@ class FaceMLDataDB {
|
|||
if (faces) {
|
||||
await db.execute(deleteFacesTable);
|
||||
await db.execute(createFacesTable);
|
||||
await db.execute(dropFaceClustersTable);
|
||||
await db.execute(deleteFaceClustersTable);
|
||||
await db.execute(createFaceClustersTable);
|
||||
await db.execute(fcClusterIDIndex);
|
||||
}
|
||||
|
||||
await db.execute(deletePersonTable);
|
||||
await db.execute(dropClusterPersonTable);
|
||||
await db.execute(dropNotPersonFeedbackTable);
|
||||
await db.execute(dropClusterSummaryTable);
|
||||
await db.execute(dropFaceClustersTable);
|
||||
await db.execute(deleteClusterPersonTable);
|
||||
await db.execute(deleteNotPersonFeedbackTable);
|
||||
await db.execute(deleteClusterSummaryTable);
|
||||
await db.execute(deleteFaceClustersTable);
|
||||
|
||||
await db.execute(createClusterPersonTable);
|
||||
await db.execute(createNotPersonFeedbackTable);
|
||||
|
@ -933,9 +1005,8 @@ class FaceMLDataDB {
|
|||
final db = await instance.asyncDB;
|
||||
|
||||
// Drop the tables
|
||||
await db.execute(deletePersonTable);
|
||||
await db.execute(dropClusterPersonTable);
|
||||
await db.execute(dropNotPersonFeedbackTable);
|
||||
await db.execute(deleteClusterPersonTable);
|
||||
await db.execute(deleteNotPersonFeedbackTable);
|
||||
|
||||
// Recreate the tables
|
||||
await db.execute(createClusterPersonTable);
|
||||
|
@ -964,7 +1035,7 @@ class FaceMLDataDB {
|
|||
final Map<String, int> faceIDToClusterID = {};
|
||||
for (final row in faceIdsResult) {
|
||||
final faceID = row[fcFaceId] as String;
|
||||
if (fileIds.contains(faceID.split('_').first)) {
|
||||
if (fileIds.contains(getFileIdFromFaceId(faceID))) {
|
||||
maxClusterID += 1;
|
||||
faceIDToClusterID[faceID] = maxClusterID;
|
||||
}
|
||||
|
@ -990,7 +1061,7 @@ class FaceMLDataDB {
|
|||
final Map<String, int> faceIDToClusterID = {};
|
||||
for (final row in faceIdsResult) {
|
||||
final faceID = row[fcFaceId] as String;
|
||||
if (fileIds.contains(faceID.split('_').first)) {
|
||||
if (fileIds.contains(getFileIdFromFaceId(faceID))) {
|
||||
maxClusterID += 1;
|
||||
faceIDToClusterID[faceID] = maxClusterID;
|
||||
}
|
||||
|
|
|
@ -29,7 +29,7 @@ const createFacesTable = '''CREATE TABLE IF NOT EXISTS $facesTable (
|
|||
);
|
||||
''';
|
||||
|
||||
const deleteFacesTable = 'DROP TABLE IF EXISTS $facesTable';
|
||||
const deleteFacesTable = 'DELETE FROM $facesTable';
|
||||
// End of Faces Table Fields & Schema Queries
|
||||
|
||||
//##region Face Clusters Table Fields & Schema Queries
|
||||
|
@ -48,15 +48,9 @@ CREATE TABLE IF NOT EXISTS $faceClustersTable (
|
|||
// -- Creating a non-unique index on clusterID for query optimization
|
||||
const fcClusterIDIndex =
|
||||
'''CREATE INDEX IF NOT EXISTS idx_fcClusterID ON $faceClustersTable($fcClusterID);''';
|
||||
const dropFaceClustersTable = 'DROP TABLE IF EXISTS $faceClustersTable';
|
||||
const deleteFaceClustersTable = 'DELETE FROM $faceClustersTable';
|
||||
//##endregion
|
||||
|
||||
// People Table Fields & Schema Queries
|
||||
const personTable = 'person';
|
||||
|
||||
const deletePersonTable = 'DROP TABLE IF EXISTS $personTable';
|
||||
//End People Table Fields & Schema Queries
|
||||
|
||||
// Clusters Table Fields & Schema Queries
|
||||
const clusterPersonTable = 'cluster_person';
|
||||
const personIdColumn = 'person_id';
|
||||
|
@ -69,7 +63,7 @@ CREATE TABLE IF NOT EXISTS $clusterPersonTable (
|
|||
PRIMARY KEY($personIdColumn, $clusterIDColumn)
|
||||
);
|
||||
''';
|
||||
const dropClusterPersonTable = 'DROP TABLE IF EXISTS $clusterPersonTable';
|
||||
const deleteClusterPersonTable = 'DELETE FROM $clusterPersonTable';
|
||||
// End Clusters Table Fields & Schema Queries
|
||||
|
||||
/// Cluster Summary Table Fields & Schema Queries
|
||||
|
@ -85,7 +79,7 @@ CREATE TABLE IF NOT EXISTS $clusterSummaryTable (
|
|||
);
|
||||
''';
|
||||
|
||||
const dropClusterSummaryTable = 'DROP TABLE IF EXISTS $clusterSummaryTable';
|
||||
const deleteClusterSummaryTable = 'DELETE FROM $clusterSummaryTable';
|
||||
|
||||
/// End Cluster Summary Table Fields & Schema Queries
|
||||
|
||||
|
@ -99,5 +93,5 @@ CREATE TABLE IF NOT EXISTS $notPersonFeedback (
|
|||
PRIMARY KEY($personIdColumn, $clusterIDColumn)
|
||||
);
|
||||
''';
|
||||
const dropNotPersonFeedbackTable = 'DROP TABLE IF EXISTS $notPersonFeedback';
|
||||
const deleteNotPersonFeedbackTable = 'DELETE FROM $notPersonFeedback';
|
||||
// End Clusters Table Fields & Schema Queries
|
||||
|
|
2
mobile/lib/generated/intl/messages_cs.dart
generated
2
mobile/lib/generated/intl/messages_cs.dart
generated
|
@ -54,6 +54,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"Please note that this will result in a higher bandwidth and battery usage until all items are indexed."),
|
||||
"fileTypes": MessageLookupByLibrary.simpleMessage("File types"),
|
||||
"foundFaces": MessageLookupByLibrary.simpleMessage("Found faces"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"joinDiscord": MessageLookupByLibrary.simpleMessage("Join Discord"),
|
||||
"locations": MessageLookupByLibrary.simpleMessage("Locations"),
|
||||
"longPressAnEmailToVerifyEndToEndEncryption":
|
||||
|
|
2
mobile/lib/generated/intl/messages_de.dart
generated
2
mobile/lib/generated/intl/messages_de.dart
generated
|
@ -819,6 +819,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"Falscher Wiederherstellungs-Schlüssel"),
|
||||
"indexedItems":
|
||||
MessageLookupByLibrary.simpleMessage("Indizierte Elemente"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Unsicheres Gerät"),
|
||||
"installManually":
|
||||
|
|
2
mobile/lib/generated/intl/messages_en.dart
generated
2
mobile/lib/generated/intl/messages_en.dart
generated
|
@ -813,6 +813,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"incorrectRecoveryKeyTitle":
|
||||
MessageLookupByLibrary.simpleMessage("Incorrect recovery key"),
|
||||
"indexedItems": MessageLookupByLibrary.simpleMessage("Indexed items"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused. It will automatically resume when device is ready."),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Insecure device"),
|
||||
"installManually":
|
||||
|
|
2
mobile/lib/generated/intl/messages_es.dart
generated
2
mobile/lib/generated/intl/messages_es.dart
generated
|
@ -699,6 +699,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"La clave de recuperación introducida es incorrecta"),
|
||||
"incorrectRecoveryKeyTitle": MessageLookupByLibrary.simpleMessage(
|
||||
"Clave de recuperación incorrecta"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Dispositivo inseguro"),
|
||||
"installManually":
|
||||
|
|
2
mobile/lib/generated/intl/messages_fr.dart
generated
2
mobile/lib/generated/intl/messages_fr.dart
generated
|
@ -804,6 +804,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"La clé de secours que vous avez entrée est incorrecte"),
|
||||
"incorrectRecoveryKeyTitle":
|
||||
MessageLookupByLibrary.simpleMessage("Clé de secours non valide"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Appareil non sécurisé"),
|
||||
"installManually":
|
||||
|
|
2
mobile/lib/generated/intl/messages_it.dart
generated
2
mobile/lib/generated/intl/messages_it.dart
generated
|
@ -773,6 +773,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"Il codice che hai inserito non è corretto"),
|
||||
"incorrectRecoveryKeyTitle":
|
||||
MessageLookupByLibrary.simpleMessage("Chiave di recupero errata"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Dispositivo non sicuro"),
|
||||
"installManually":
|
||||
|
|
2
mobile/lib/generated/intl/messages_ko.dart
generated
2
mobile/lib/generated/intl/messages_ko.dart
generated
|
@ -54,6 +54,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"Please note that this will result in a higher bandwidth and battery usage until all items are indexed."),
|
||||
"fileTypes": MessageLookupByLibrary.simpleMessage("File types"),
|
||||
"foundFaces": MessageLookupByLibrary.simpleMessage("Found faces"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"joinDiscord": MessageLookupByLibrary.simpleMessage("Join Discord"),
|
||||
"locations": MessageLookupByLibrary.simpleMessage("Locations"),
|
||||
"longPressAnEmailToVerifyEndToEndEncryption":
|
||||
|
|
2
mobile/lib/generated/intl/messages_nl.dart
generated
2
mobile/lib/generated/intl/messages_nl.dart
generated
|
@ -840,6 +840,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
MessageLookupByLibrary.simpleMessage("Onjuiste herstelsleutel"),
|
||||
"indexedItems":
|
||||
MessageLookupByLibrary.simpleMessage("Geïndexeerde bestanden"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Onveilig apparaat"),
|
||||
"installManually":
|
||||
|
|
2
mobile/lib/generated/intl/messages_no.dart
generated
2
mobile/lib/generated/intl/messages_no.dart
generated
|
@ -72,6 +72,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"feedback": MessageLookupByLibrary.simpleMessage("Tilbakemelding"),
|
||||
"fileTypes": MessageLookupByLibrary.simpleMessage("File types"),
|
||||
"foundFaces": MessageLookupByLibrary.simpleMessage("Found faces"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"invalidEmailAddress":
|
||||
MessageLookupByLibrary.simpleMessage("Ugyldig e-postadresse"),
|
||||
"joinDiscord": MessageLookupByLibrary.simpleMessage("Join Discord"),
|
||||
|
|
2
mobile/lib/generated/intl/messages_pl.dart
generated
2
mobile/lib/generated/intl/messages_pl.dart
generated
|
@ -131,6 +131,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
MessageLookupByLibrary.simpleMessage("Kod jest nieprawidłowy"),
|
||||
"incorrectRecoveryKeyTitle": MessageLookupByLibrary.simpleMessage(
|
||||
"Nieprawidłowy klucz odzyskiwania"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"invalidEmailAddress":
|
||||
MessageLookupByLibrary.simpleMessage("Nieprawidłowy adres e-mail"),
|
||||
"joinDiscord": MessageLookupByLibrary.simpleMessage("Join Discord"),
|
||||
|
|
23
mobile/lib/generated/intl/messages_pt.dart
generated
23
mobile/lib/generated/intl/messages_pt.dart
generated
|
@ -98,7 +98,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"${storageAmountInGB} GB cada vez que alguém se inscrever para um plano pago e aplica o seu código";
|
||||
|
||||
static String m25(freeAmount, storageUnit) =>
|
||||
"${freeAmount} ${storageUnit} grátis";
|
||||
"${freeAmount} ${storageUnit} livre";
|
||||
|
||||
static String m26(endDate) => "Teste gratuito acaba em ${endDate}";
|
||||
|
||||
|
@ -225,6 +225,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"Eu entendo que se eu perder minha senha, posso perder meus dados, já que meus dados são <underline>criptografados de ponta a ponta</underline>."),
|
||||
"activeSessions":
|
||||
MessageLookupByLibrary.simpleMessage("Sessões ativas"),
|
||||
"addAName": MessageLookupByLibrary.simpleMessage("Adicione um nome"),
|
||||
"addANewEmail":
|
||||
MessageLookupByLibrary.simpleMessage("Adicionar um novo email"),
|
||||
"addCollaborator":
|
||||
|
@ -446,7 +447,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"clubByFileName": MessageLookupByLibrary.simpleMessage(
|
||||
"Agrupar pelo nome de arquivo"),
|
||||
"clusteringProgress":
|
||||
MessageLookupByLibrary.simpleMessage("Clustering progress"),
|
||||
MessageLookupByLibrary.simpleMessage("Progresso de agrupamento"),
|
||||
"codeAppliedPageTitle":
|
||||
MessageLookupByLibrary.simpleMessage("Código aplicado"),
|
||||
"codeCopiedToClipboard": MessageLookupByLibrary.simpleMessage(
|
||||
|
@ -692,6 +693,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"enterPassword": MessageLookupByLibrary.simpleMessage("Digite a senha"),
|
||||
"enterPasswordToEncrypt": MessageLookupByLibrary.simpleMessage(
|
||||
"Insira a senha para criptografar seus dados"),
|
||||
"enterPersonName":
|
||||
MessageLookupByLibrary.simpleMessage("Inserir nome da pessoa"),
|
||||
"enterReferralCode": MessageLookupByLibrary.simpleMessage(
|
||||
"Insira o código de referência"),
|
||||
"enterThe6digitCodeFromnyourAuthenticatorApp":
|
||||
|
@ -717,9 +720,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"exportYourData":
|
||||
MessageLookupByLibrary.simpleMessage("Exportar seus dados"),
|
||||
"faceRecognition":
|
||||
MessageLookupByLibrary.simpleMessage("Face recognition"),
|
||||
MessageLookupByLibrary.simpleMessage("Reconhecimento facial"),
|
||||
"faceRecognitionIndexingDescription": MessageLookupByLibrary.simpleMessage(
|
||||
"Please note that this will result in a higher bandwidth and battery usage until all items are indexed."),
|
||||
"Por favor, note que isso resultará em uma largura de banda maior e uso de bateria até que todos os itens sejam indexados."),
|
||||
"faces": MessageLookupByLibrary.simpleMessage("Rostos"),
|
||||
"failedToApplyCode":
|
||||
MessageLookupByLibrary.simpleMessage("Falha ao aplicar o código"),
|
||||
|
@ -761,12 +764,15 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
MessageLookupByLibrary.simpleMessage("Arquivos excluídos"),
|
||||
"filesSavedToGallery":
|
||||
MessageLookupByLibrary.simpleMessage("Arquivos salvos na galeria"),
|
||||
"findPeopleByName": MessageLookupByLibrary.simpleMessage(
|
||||
"Encontre pessoas rapidamente por nome"),
|
||||
"flip": MessageLookupByLibrary.simpleMessage("Inverter"),
|
||||
"forYourMemories":
|
||||
MessageLookupByLibrary.simpleMessage("para suas memórias"),
|
||||
"forgotPassword":
|
||||
MessageLookupByLibrary.simpleMessage("Esqueceu sua senha"),
|
||||
"foundFaces": MessageLookupByLibrary.simpleMessage("Found faces"),
|
||||
"foundFaces":
|
||||
MessageLookupByLibrary.simpleMessage("Rostos encontrados"),
|
||||
"freeStorageClaimed": MessageLookupByLibrary.simpleMessage(
|
||||
"Armazenamento gratuito reivindicado"),
|
||||
"freeStorageOnReferralSuccess": m24,
|
||||
|
@ -830,6 +836,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"incorrectRecoveryKeyTitle": MessageLookupByLibrary.simpleMessage(
|
||||
"Chave de recuperação incorreta"),
|
||||
"indexedItems": MessageLookupByLibrary.simpleMessage("Itens indexados"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice":
|
||||
MessageLookupByLibrary.simpleMessage("Dispositivo não seguro"),
|
||||
"installManually":
|
||||
|
@ -1064,6 +1072,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"pendingItems": MessageLookupByLibrary.simpleMessage("Itens pendentes"),
|
||||
"pendingSync":
|
||||
MessageLookupByLibrary.simpleMessage("Sincronização pendente"),
|
||||
"people": MessageLookupByLibrary.simpleMessage("Pessoas"),
|
||||
"peopleUsingYourCode":
|
||||
MessageLookupByLibrary.simpleMessage("Pessoas que usam seu código"),
|
||||
"permDeleteWarning": MessageLookupByLibrary.simpleMessage(
|
||||
|
@ -1197,6 +1206,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"removeParticipant":
|
||||
MessageLookupByLibrary.simpleMessage("Remover participante"),
|
||||
"removeParticipantBody": m43,
|
||||
"removePersonLabel":
|
||||
MessageLookupByLibrary.simpleMessage("Remover etiqueta da pessoa"),
|
||||
"removePublicLink":
|
||||
MessageLookupByLibrary.simpleMessage("Remover link público"),
|
||||
"removeShareItemsWarning": MessageLookupByLibrary.simpleMessage(
|
||||
|
@ -1260,7 +1271,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"searchDatesEmptySection": MessageLookupByLibrary.simpleMessage(
|
||||
"Pesquisar por data, mês ou ano"),
|
||||
"searchFaceEmptySection": MessageLookupByLibrary.simpleMessage(
|
||||
"Encontre todas as fotos de uma pessoa"),
|
||||
"Pessoas serão exibidas aqui uma vez que a indexação é feita"),
|
||||
"searchFileTypesAndNamesEmptySection":
|
||||
MessageLookupByLibrary.simpleMessage("Tipos de arquivo e nomes"),
|
||||
"searchHint1": MessageLookupByLibrary.simpleMessage(
|
||||
|
|
2
mobile/lib/generated/intl/messages_zh.dart
generated
2
mobile/lib/generated/intl/messages_zh.dart
generated
|
@ -686,6 +686,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
|||
"incorrectRecoveryKeyTitle":
|
||||
MessageLookupByLibrary.simpleMessage("不正确的恢复密钥"),
|
||||
"indexedItems": MessageLookupByLibrary.simpleMessage("已索引项目"),
|
||||
"indexingIsPaused": MessageLookupByLibrary.simpleMessage(
|
||||
"Indexing is paused, will automatically resume when device is ready"),
|
||||
"insecureDevice": MessageLookupByLibrary.simpleMessage("设备不安全"),
|
||||
"installManually": MessageLookupByLibrary.simpleMessage("手动安装"),
|
||||
"invalidEmailAddress":
|
||||
|
|
10
mobile/lib/generated/l10n.dart
generated
10
mobile/lib/generated/l10n.dart
generated
|
@ -8793,6 +8793,16 @@ class S {
|
|||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Indexing is paused. It will automatically resume when device is ready.`
|
||||
String get indexingIsPaused {
|
||||
return Intl.message(
|
||||
'Indexing is paused. It will automatically resume when device is ready.',
|
||||
name: 'indexingIsPaused',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppLocalizationDelegate extends LocalizationsDelegate<S> {
|
||||
|
|
|
@ -24,5 +24,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1212,5 +1212,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1235,5 +1235,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
}
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused. It will automatically resume when device is ready."
|
||||
}
|
||||
|
|
|
@ -986,5 +986,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1167,5 +1167,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1129,5 +1129,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -24,5 +24,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1230,5 +1230,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -38,5 +38,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -125,5 +125,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1235,5 +1235,6 @@
|
|||
"faceRecognition": "Reconhecimento facial",
|
||||
"faceRecognitionIndexingDescription": "Por favor, note que isso resultará em uma largura de banda maior e uso de bateria até que todos os itens sejam indexados.",
|
||||
"foundFaces": "Rostos encontrados",
|
||||
"clusteringProgress": "Progresso de agrupamento"
|
||||
"clusteringProgress": "Progresso de agrupamento",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -1230,5 +1230,6 @@
|
|||
"faceRecognition": "Face recognition",
|
||||
"faceRecognitionIndexingDescription": "Please note that this will result in a higher bandwidth and battery usage until all items are indexed.",
|
||||
"foundFaces": "Found faces",
|
||||
"clusteringProgress": "Clustering progress"
|
||||
"clusteringProgress": "Clustering progress",
|
||||
"indexingIsPaused": "Indexing is paused, will automatically resume when device is ready"
|
||||
}
|
|
@ -51,6 +51,7 @@ import 'package:photos/services/user_service.dart';
|
|||
import 'package:photos/ui/tools/app_lock.dart';
|
||||
import 'package:photos/ui/tools/lock_screen.dart';
|
||||
import 'package:photos/utils/crypto_util.dart';
|
||||
import "package:photos/utils/email_util.dart";
|
||||
import 'package:photos/utils/file_uploader.dart';
|
||||
import 'package:photos/utils/local_settings.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
@ -180,6 +181,16 @@ void _headlessTaskHandler(HeadlessTask task) {
|
|||
}
|
||||
|
||||
Future<void> _init(bool isBackground, {String via = ''}) async {
|
||||
bool initComplete = false;
|
||||
Future.delayed(const Duration(seconds: 15), () {
|
||||
if (!initComplete && !isBackground) {
|
||||
sendLogsForInit(
|
||||
"support@ente.io",
|
||||
"Stuck on splash screen for >= 15 seconds",
|
||||
null,
|
||||
);
|
||||
}
|
||||
});
|
||||
_isProcessRunning = true;
|
||||
_logger.info("Initializing... inBG =$isBackground via: $via");
|
||||
final SharedPreferences preferences = await SharedPreferences.getInstance();
|
||||
|
@ -235,17 +246,11 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
|
|||
|
||||
unawaited(SemanticSearchService.instance.init());
|
||||
MachineLearningController.instance.init();
|
||||
// Can not including existing tf/ml binaries as they are not being built
|
||||
// from source.
|
||||
// See https://gitlab.com/fdroid/fdroiddata/-/merge_requests/12671#note_1294346819
|
||||
if (!UpdateService.instance.isFdroidFlavor()) {
|
||||
// unawaited(ObjectDetectionService.instance.init());
|
||||
if (flagService.faceSearchEnabled) {
|
||||
unawaited(FaceMlService.instance.init());
|
||||
} else {
|
||||
if (LocalSettings.instance.isFaceIndexingEnabled) {
|
||||
unawaited(LocalSettings.instance.toggleFaceIndexing());
|
||||
}
|
||||
if (flagService.faceSearchEnabled) {
|
||||
unawaited(FaceMlService.instance.init());
|
||||
} else {
|
||||
if (LocalSettings.instance.isFaceIndexingEnabled) {
|
||||
unawaited(LocalSettings.instance.toggleFaceIndexing());
|
||||
}
|
||||
}
|
||||
PersonService.init(
|
||||
|
@ -254,6 +259,7 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
|
|||
preferences,
|
||||
);
|
||||
|
||||
initComplete = true;
|
||||
_logger.info("Initialization done");
|
||||
}
|
||||
|
||||
|
|
|
@ -498,19 +498,8 @@ class FaceClusteringService {
|
|||
}
|
||||
}
|
||||
|
||||
// Sort the faceInfos based on fileCreationTime, in ascending order, so oldest faces are first
|
||||
if (fileIDToCreationTime != null) {
|
||||
faceInfos.sort((a, b) {
|
||||
if (a.fileCreationTime == null && b.fileCreationTime == null) {
|
||||
return 0;
|
||||
} else if (a.fileCreationTime == null) {
|
||||
return 1;
|
||||
} else if (b.fileCreationTime == null) {
|
||||
return -1;
|
||||
} else {
|
||||
return a.fileCreationTime!.compareTo(b.fileCreationTime!);
|
||||
}
|
||||
});
|
||||
_sortFaceInfosOnCreationTime(faceInfos);
|
||||
}
|
||||
|
||||
// Sort the faceInfos such that the ones with null clusterId are at the end
|
||||
|
@ -796,19 +785,8 @@ class FaceClusteringService {
|
|||
);
|
||||
}
|
||||
|
||||
// Sort the faceInfos based on fileCreationTime, in ascending order, so oldest faces are first
|
||||
if (fileIDToCreationTime != null) {
|
||||
faceInfos.sort((a, b) {
|
||||
if (a.fileCreationTime == null && b.fileCreationTime == null) {
|
||||
return 0;
|
||||
} else if (a.fileCreationTime == null) {
|
||||
return 1;
|
||||
} else if (b.fileCreationTime == null) {
|
||||
return -1;
|
||||
} else {
|
||||
return a.fileCreationTime!.compareTo(b.fileCreationTime!);
|
||||
}
|
||||
});
|
||||
_sortFaceInfosOnCreationTime(faceInfos);
|
||||
}
|
||||
|
||||
if (faceInfos.isEmpty) {
|
||||
|
@ -996,19 +974,8 @@ class FaceClusteringService {
|
|||
);
|
||||
}
|
||||
|
||||
// Sort the faceInfos based on fileCreationTime, in ascending order, so oldest faces are first
|
||||
if (fileIDToCreationTime != null) {
|
||||
faceInfos.sort((a, b) {
|
||||
if (a.fileCreationTime == null && b.fileCreationTime == null) {
|
||||
return 0;
|
||||
} else if (a.fileCreationTime == null) {
|
||||
return 1;
|
||||
} else if (b.fileCreationTime == null) {
|
||||
return -1;
|
||||
} else {
|
||||
return a.fileCreationTime!.compareTo(b.fileCreationTime!);
|
||||
}
|
||||
});
|
||||
_sortFaceInfosOnCreationTime(faceInfos);
|
||||
}
|
||||
|
||||
// Get the embeddings
|
||||
|
@ -1027,3 +994,20 @@ class FaceClusteringService {
|
|||
return clusteredFaceIDs;
|
||||
}
|
||||
}
|
||||
|
||||
/// Sort the faceInfos based on fileCreationTime, in descending order, so newest faces are first
|
||||
void _sortFaceInfosOnCreationTime(
|
||||
List<FaceInfo> faceInfos,
|
||||
) {
|
||||
faceInfos.sort((b, a) {
|
||||
if (a.fileCreationTime == null && b.fileCreationTime == null) {
|
||||
return 0;
|
||||
} else if (a.fileCreationTime == null) {
|
||||
return 1;
|
||||
} else if (b.fileCreationTime == null) {
|
||||
return -1;
|
||||
} else {
|
||||
return a.fileCreationTime!.compareTo(b.fileCreationTime!);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
@ -8,6 +8,18 @@ class GeneralFaceMlException implements Exception {
|
|||
String toString() => 'GeneralFaceMlException: $message';
|
||||
}
|
||||
|
||||
class ThumbnailRetrievalException implements Exception {
|
||||
final String message;
|
||||
final StackTrace stackTrace;
|
||||
|
||||
ThumbnailRetrievalException(this.message, this.stackTrace);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ThumbnailRetrievalException: $message\n$stackTrace';
|
||||
}
|
||||
}
|
||||
|
||||
class CouldNotRetrieveAnyFileData implements Exception {}
|
||||
|
||||
class CouldNotInitializeFaceDetector implements Exception {}
|
||||
|
|
|
@ -310,5 +310,9 @@ class FaceResultBuilder {
|
|||
}
|
||||
|
||||
int getFileIdFromFaceId(String faceId) {
|
||||
return int.parse(faceId.split("_")[0]);
|
||||
return int.parse(faceId.split("_").first);
|
||||
}
|
||||
|
||||
int? tryGetFileIdFromFaceId(String faceId) {
|
||||
return int.tryParse(faceId.split("_").first);
|
||||
}
|
|
@ -9,10 +9,10 @@ import "dart:ui" show Image;
|
|||
import "package:computer/computer.dart";
|
||||
import "package:dart_ui_isolate/dart_ui_isolate.dart";
|
||||
import "package:flutter/foundation.dart" show debugPrint, kDebugMode;
|
||||
import "package:flutter/services.dart";
|
||||
import "package:logging/logging.dart";
|
||||
import "package:onnxruntime/onnxruntime.dart";
|
||||
import "package:package_info_plus/package_info_plus.dart";
|
||||
import "package:photos/core/configuration.dart";
|
||||
import "package:photos/core/event_bus.dart";
|
||||
import "package:photos/db/files_db.dart";
|
||||
import "package:photos/events/diff_sync_complete_event.dart";
|
||||
|
@ -43,6 +43,7 @@ import 'package:photos/services/machine_learning/face_ml/face_ml_result.dart';
|
|||
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
|
||||
import 'package:photos/services/machine_learning/file_ml/file_ml.dart';
|
||||
import 'package:photos/services/machine_learning/file_ml/remote_fileml_service.dart';
|
||||
import "package:photos/services/machine_learning/machine_learning_controller.dart";
|
||||
import "package:photos/services/search_service.dart";
|
||||
import "package:photos/utils/file_util.dart";
|
||||
import 'package:photos/utils/image_ml_isolate.dart';
|
||||
|
@ -99,6 +100,7 @@ class FaceMlService {
|
|||
|
||||
final int _fileDownloadLimit = 5;
|
||||
final int _embeddingFetchLimit = 200;
|
||||
final int _kForceClusteringFaceCount = 8000;
|
||||
|
||||
Future<void> init({bool initializeImageMlIsolate = false}) async {
|
||||
if (LocalSettings.instance.isFaceIndexingEnabled == false) {
|
||||
|
@ -162,9 +164,16 @@ class FaceMlService {
|
|||
pauseIndexingAndClustering();
|
||||
}
|
||||
});
|
||||
if (Platform.isIOS &&
|
||||
MachineLearningController.instance.isDeviceHealthy) {
|
||||
_logger.info("Starting face indexing and clustering on iOS from init");
|
||||
unawaited(indexAndClusterAll());
|
||||
}
|
||||
|
||||
_listenIndexOnDiffSync();
|
||||
_listenOnPeopleChangedSync();
|
||||
|
||||
_logger.info('init done');
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -358,16 +367,17 @@ class FaceMlService {
|
|||
if (_cannotRunMLFunction()) return;
|
||||
|
||||
await sync(forceSync: _shouldSyncPeople);
|
||||
await indexAllImages();
|
||||
final indexingCompleteRatio = await _getIndexedDoneRatio();
|
||||
if (indexingCompleteRatio < 0.95) {
|
||||
|
||||
final int unclusteredFacesCount =
|
||||
await FaceMLDataDB.instance.getUnclusteredFaceCount();
|
||||
if (unclusteredFacesCount > _kForceClusteringFaceCount) {
|
||||
_logger.info(
|
||||
"Indexing is not far enough to start clustering, skipping clustering. Indexing is at $indexingCompleteRatio",
|
||||
"There are $unclusteredFacesCount unclustered faces, doing clustering first",
|
||||
);
|
||||
return;
|
||||
} else {
|
||||
await clusterAllImages();
|
||||
}
|
||||
await indexAllImages();
|
||||
await clusterAllImages();
|
||||
}
|
||||
|
||||
void pauseIndexingAndClustering() {
|
||||
|
@ -445,7 +455,8 @@ class FaceMlService {
|
|||
|
||||
if (LocalSettings.instance.remoteFetchEnabled) {
|
||||
try {
|
||||
final List<int> fileIds = [];
|
||||
final Set<int> fileIds =
|
||||
{}; // if there are duplicates here server returns 400
|
||||
// Try to find embeddings on the remote server
|
||||
for (final f in chunk) {
|
||||
fileIds.add(f.uploadedFileID!);
|
||||
|
@ -590,8 +601,8 @@ class FaceMlService {
|
|||
allFaceInfoForClustering.add(faceInfo);
|
||||
}
|
||||
}
|
||||
// sort the embeddings based on file creation time, oldest first
|
||||
allFaceInfoForClustering.sort((a, b) {
|
||||
// sort the embeddings based on file creation time, newest first
|
||||
allFaceInfoForClustering.sort((b, a) {
|
||||
return fileIDToCreationTime[a.fileID]!
|
||||
.compareTo(fileIDToCreationTime[b.fileID]!);
|
||||
});
|
||||
|
@ -843,13 +854,22 @@ class FaceMlService {
|
|||
}
|
||||
await FaceMLDataDB.instance.bulkInsertFaces(faces);
|
||||
return true;
|
||||
} on ThumbnailRetrievalException catch (e, s) {
|
||||
_logger.severe(
|
||||
'ThumbnailRetrievalException while processing image with ID ${enteFile.uploadedFileID}, storing empty face so indexing does not get stuck',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
await FaceMLDataDB.instance
|
||||
.bulkInsertFaces([Face.empty(enteFile.uploadedFileID!, error: true)]);
|
||||
return true;
|
||||
} catch (e, s) {
|
||||
_logger.severe(
|
||||
"Failed to analyze using FaceML for image with ID: ${enteFile.uploadedFileID}",
|
||||
e,
|
||||
s,
|
||||
);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1003,7 +1023,16 @@ class FaceMlService {
|
|||
final stopwatch = Stopwatch()..start();
|
||||
File? file;
|
||||
if (enteFile.fileType == FileType.video) {
|
||||
file = await getThumbnailForUploadedFile(enteFile);
|
||||
try {
|
||||
file = await getThumbnailForUploadedFile(enteFile);
|
||||
} on PlatformException catch (e, s) {
|
||||
_logger.severe(
|
||||
"Could not get thumbnail for $enteFile due to PlatformException",
|
||||
e,
|
||||
s,
|
||||
);
|
||||
throw ThumbnailRetrievalException(e.toString(), s);
|
||||
}
|
||||
} else {
|
||||
file = await getFile(enteFile, isOrigin: true);
|
||||
// TODO: This is returning null for Pragadees for all files, so something is wrong here!
|
||||
|
@ -1171,24 +1200,6 @@ class FaceMlService {
|
|||
}
|
||||
}
|
||||
|
||||
Future<double> _getIndexedDoneRatio() async {
|
||||
final w = (kDebugMode ? EnteWatch('_getIndexedDoneRatio') : null)?..start();
|
||||
|
||||
final int alreadyIndexedCount = await FaceMLDataDB.instance
|
||||
.getIndexedFileCount(minimumMlVersion: faceMlVersion);
|
||||
final int totalIndexableCount = (await getIndexableFileIDs()).length;
|
||||
final ratio = alreadyIndexedCount / totalIndexableCount;
|
||||
|
||||
w?.log('getIndexedDoneRatio');
|
||||
|
||||
return ratio;
|
||||
}
|
||||
|
||||
static Future<List<int>> getIndexableFileIDs() async {
|
||||
return FilesDB.instance
|
||||
.getOwnedFileIDs(Configuration.instance.getUserID()!);
|
||||
}
|
||||
|
||||
bool _skipAnalysisEnteFile(EnteFile enteFile, Map<int, int> indexedFileIds) {
|
||||
if (_isIndexingOrClusteringRunning == false ||
|
||||
_mlControllerStatus == false) {
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import "dart:async";
|
||||
import "dart:convert";
|
||||
|
||||
import "package:computer/computer.dart";
|
||||
import "package:logging/logging.dart";
|
||||
import "package:photos/core/network/network.dart";
|
||||
import "package:photos/db/files_db.dart";
|
||||
|
@ -16,6 +17,8 @@ import "package:shared_preferences/shared_preferences.dart";
|
|||
class RemoteFileMLService {
|
||||
RemoteFileMLService._privateConstructor();
|
||||
|
||||
static final Computer _computer = Computer.shared();
|
||||
|
||||
static final RemoteFileMLService instance =
|
||||
RemoteFileMLService._privateConstructor();
|
||||
|
||||
|
@ -52,13 +55,13 @@ class RemoteFileMLService {
|
|||
}
|
||||
|
||||
Future<FilesMLDataResponse> getFilessEmbedding(
|
||||
List<int> fileIds,
|
||||
Set<int> fileIds,
|
||||
) async {
|
||||
try {
|
||||
final res = await _dio.post(
|
||||
"/embeddings/files",
|
||||
data: {
|
||||
"fileIDs": fileIds,
|
||||
"fileIDs": fileIds.toList(),
|
||||
"model": 'file-ml-clip-face',
|
||||
},
|
||||
);
|
||||
|
@ -107,15 +110,17 @@ class RemoteFileMLService {
|
|||
final input = EmbeddingsDecoderInput(embedding, fileKey);
|
||||
inputs.add(input);
|
||||
}
|
||||
// todo: use compute or isolate
|
||||
return decryptFileMLComputer(
|
||||
{
|
||||
return _computer.compute<Map<String, dynamic>, Map<int, FileMl>>(
|
||||
_decryptFileMLComputer,
|
||||
param: {
|
||||
"inputs": inputs,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<Map<int, FileMl>> decryptFileMLComputer(
|
||||
}
|
||||
|
||||
Future<Map<int, FileMl>> _decryptFileMLComputer(
|
||||
Map<String, dynamic> args,
|
||||
) async {
|
||||
final result = <int, FileMl>{};
|
||||
|
@ -134,5 +139,4 @@ class RemoteFileMLService {
|
|||
result[input.embedding.fileID] = decodedEmbedding;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,7 +4,6 @@ import "dart:io";
|
|||
import "package:battery_info/battery_info_plugin.dart";
|
||||
import "package:battery_info/model/android_battery_info.dart";
|
||||
import "package:battery_info/model/iso_battery_info.dart";
|
||||
import "package:flutter/foundation.dart" show kDebugMode;
|
||||
import "package:logging/logging.dart";
|
||||
import "package:photos/core/event_bus.dart";
|
||||
import "package:photos/events/machine_learning_control_event.dart";
|
||||
|
@ -19,8 +18,7 @@ class MachineLearningController {
|
|||
|
||||
static const kMaximumTemperature = 42; // 42 degree celsius
|
||||
static const kMinimumBatteryLevel = 20; // 20%
|
||||
static const kDefaultInteractionTimeout =
|
||||
kDebugMode ? Duration(seconds: 3) : Duration(seconds: 5);
|
||||
static const kDefaultInteractionTimeout = Duration(seconds: 10);
|
||||
static const kUnhealthyStates = ["over_heat", "over_voltage", "dead"];
|
||||
|
||||
bool _isDeviceHealthy = true;
|
||||
|
@ -28,7 +26,10 @@ class MachineLearningController {
|
|||
bool _canRunML = false;
|
||||
late Timer _userInteractionTimer;
|
||||
|
||||
bool get isDeviceHealthy => _isDeviceHealthy;
|
||||
|
||||
void init() {
|
||||
_logger.info('init called');
|
||||
if (Platform.isAndroid) {
|
||||
_startInteractionTimer();
|
||||
BatteryInfoPlugin()
|
||||
|
@ -45,6 +46,7 @@ class MachineLearningController {
|
|||
});
|
||||
}
|
||||
_fireControlEvent();
|
||||
_logger.info('init done');
|
||||
}
|
||||
|
||||
void onUserInteraction() {
|
||||
|
|
|
@ -23,6 +23,7 @@ import 'package:photos/services/machine_learning/semantic_search/frameworks/onnx
|
|||
import "package:photos/utils/debouncer.dart";
|
||||
import "package:photos/utils/device_info.dart";
|
||||
import "package:photos/utils/local_settings.dart";
|
||||
import "package:photos/utils/ml_util.dart";
|
||||
import "package:photos/utils/thumbnail_util.dart";
|
||||
|
||||
class SemanticSearchService {
|
||||
|
@ -160,8 +161,7 @@ class SemanticSearchService {
|
|||
}
|
||||
|
||||
Future<IndexStatus> getIndexStatus() async {
|
||||
final indexableFileIDs = await FilesDB.instance
|
||||
.getOwnedFileIDs(Configuration.instance.getUserID()!);
|
||||
final indexableFileIDs = await getIndexableFileIDs();
|
||||
return IndexStatus(
|
||||
min(_cachedEmbeddings.length, indexableFileIDs.length),
|
||||
(await _getFileIDsToBeIndexed()).length,
|
||||
|
@ -222,8 +222,7 @@ class SemanticSearchService {
|
|||
}
|
||||
|
||||
Future<List<int>> _getFileIDsToBeIndexed() async {
|
||||
final uploadedFileIDs = await FilesDB.instance
|
||||
.getOwnedFileIDs(Configuration.instance.getUserID()!);
|
||||
final uploadedFileIDs = await getIndexableFileIDs();
|
||||
final embeddedFileIDs =
|
||||
await EmbeddingsDB.instance.getFileIDs(_currentModel);
|
||||
|
||||
|
|
|
@ -754,15 +754,6 @@ class SearchService {
|
|||
|
||||
Future<List<GenericSearchResult>> getAllFace(int? limit) async {
|
||||
try {
|
||||
// Don't return anything if clustering is not nearly complete yet
|
||||
final foundFaces = await FaceMLDataDB.instance.getTotalFaceCount();
|
||||
final clusteredFaces =
|
||||
await FaceMLDataDB.instance.getClusteredFaceCount();
|
||||
final clusteringDoneRatio = clusteredFaces / foundFaces;
|
||||
if (clusteringDoneRatio < 0.9) {
|
||||
return [];
|
||||
}
|
||||
|
||||
debugPrint("getting faces");
|
||||
final Map<int, Set<int>> fileIdToClusterID =
|
||||
await FaceMLDataDB.instance.getFileIdToClusterIds();
|
||||
|
|
|
@ -177,7 +177,7 @@ class _FaceDebugSectionWidgetState extends State<FaceDebugSectionWidget> {
|
|||
sectionOptionSpacing,
|
||||
MenuItemWidget(
|
||||
captionedTextWidget: FutureBuilder<double>(
|
||||
future: FaceMLDataDB.instance.getClusteredToTotalFacesRatio(),
|
||||
future: FaceMLDataDB.instance.getClusteredToIndexableFilesRatio(),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasData) {
|
||||
return CaptionedTextWidget(
|
||||
|
|
|
@ -11,6 +11,7 @@ import "package:photos/generated/l10n.dart";
|
|||
import "package:photos/models/ml/ml_versions.dart";
|
||||
import "package:photos/service_locator.dart";
|
||||
import "package:photos/services/machine_learning/face_ml/face_ml_service.dart";
|
||||
import "package:photos/services/machine_learning/machine_learning_controller.dart";
|
||||
import 'package:photos/services/machine_learning/semantic_search/frameworks/ml_framework.dart';
|
||||
import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
|
||||
import "package:photos/services/remote_assets_service.dart";
|
||||
|
@ -26,6 +27,8 @@ import "package:photos/ui/components/title_bar_widget.dart";
|
|||
import "package:photos/ui/components/toggle_switch_widget.dart";
|
||||
import "package:photos/utils/data_util.dart";
|
||||
import "package:photos/utils/local_settings.dart";
|
||||
import "package:photos/utils/ml_util.dart";
|
||||
import "package:photos/utils/wakelock_util.dart";
|
||||
|
||||
final _logger = Logger("MachineLearningSettingsPage");
|
||||
|
||||
|
@ -40,6 +43,7 @@ class MachineLearningSettingsPage extends StatefulWidget {
|
|||
class _MachineLearningSettingsPageState
|
||||
extends State<MachineLearningSettingsPage> {
|
||||
late InitializationState _state;
|
||||
final EnteWakeLock _wakeLock = EnteWakeLock();
|
||||
|
||||
late StreamSubscription<MLFrameworkInitializationUpdateEvent>
|
||||
_eventSubscription;
|
||||
|
@ -53,6 +57,7 @@ class _MachineLearningSettingsPageState
|
|||
setState(() {});
|
||||
});
|
||||
_fetchState();
|
||||
_wakeLock.enable();
|
||||
}
|
||||
|
||||
void _fetchState() {
|
||||
|
@ -63,6 +68,7 @@ class _MachineLearningSettingsPageState
|
|||
void dispose() {
|
||||
super.dispose();
|
||||
_eventSubscription.cancel();
|
||||
_wakeLock.disable();
|
||||
}
|
||||
|
||||
@override
|
||||
|
@ -83,8 +89,8 @@ class _MachineLearningSettingsPageState
|
|||
iconButtonType: IconButtonType.secondary,
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(context);
|
||||
if (Navigator.canPop(context)) Navigator.pop(context);
|
||||
if (Navigator.canPop(context)) Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
|
@ -438,19 +444,24 @@ class FaceRecognitionStatusWidgetState
|
|||
});
|
||||
}
|
||||
|
||||
Future<(int, int, int, double)> getIndexStatus() async {
|
||||
Future<(int, int, double, bool)> getIndexStatus() async {
|
||||
try {
|
||||
final indexedFiles = await FaceMLDataDB.instance
|
||||
.getIndexedFileCount(minimumMlVersion: faceMlVersion);
|
||||
final indexableFiles = (await FaceMlService.getIndexableFileIDs()).length;
|
||||
final indexableFiles = (await getIndexableFileIDs()).length;
|
||||
final showIndexedFiles = min(indexedFiles, indexableFiles);
|
||||
final pendingFiles = max(indexableFiles - indexedFiles, 0);
|
||||
final foundFaces = await FaceMLDataDB.instance.getTotalFaceCount();
|
||||
final clusteredFaces =
|
||||
await FaceMLDataDB.instance.getClusteredFaceCount();
|
||||
final clusteringDoneRatio = clusteredFaces / foundFaces;
|
||||
final clusteringDoneRatio =
|
||||
await FaceMLDataDB.instance.getClusteredToIndexableFilesRatio();
|
||||
final bool deviceIsHealthy =
|
||||
MachineLearningController.instance.isDeviceHealthy;
|
||||
|
||||
return (showIndexedFiles, pendingFiles, foundFaces, clusteringDoneRatio);
|
||||
return (
|
||||
showIndexedFiles,
|
||||
pendingFiles,
|
||||
clusteringDoneRatio,
|
||||
deviceIsHealthy
|
||||
);
|
||||
} catch (e, s) {
|
||||
_logger.severe('Error getting face recognition status', e, s);
|
||||
rethrow;
|
||||
|
@ -479,10 +490,17 @@ class FaceRecognitionStatusWidgetState
|
|||
if (snapshot.hasData) {
|
||||
final int indexedFiles = snapshot.data!.$1;
|
||||
final int pendingFiles = snapshot.data!.$2;
|
||||
final int foundFaces = snapshot.data!.$3;
|
||||
final double clusteringDoneRatio = snapshot.data!.$4;
|
||||
final double clusteringDoneRatio = snapshot.data!.$3;
|
||||
final double clusteringPercentage =
|
||||
(clusteringDoneRatio * 100).clamp(0, 100);
|
||||
final bool isDeviceHealthy = snapshot.data!.$4;
|
||||
|
||||
if (!isDeviceHealthy &&
|
||||
(pendingFiles > 0 || clusteringPercentage < 99)) {
|
||||
return MenuSectionDescriptionWidget(
|
||||
content: S.of(context).indexingIsPaused,
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
|
@ -512,19 +530,6 @@ class FaceRecognitionStatusWidgetState
|
|||
isGestureDetectorDisabled: true,
|
||||
key: ValueKey("pending_items_" + pendingFiles.toString()),
|
||||
),
|
||||
MenuItemWidget(
|
||||
captionedTextWidget: CaptionedTextWidget(
|
||||
title: S.of(context).foundFaces,
|
||||
),
|
||||
trailingWidget: Text(
|
||||
NumberFormat().format(foundFaces),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
singleBorderRadius: 8,
|
||||
alignCaptionedTextToLeft: true,
|
||||
isGestureDetectorDisabled: true,
|
||||
key: ValueKey("found_faces_" + foundFaces.toString()),
|
||||
),
|
||||
MenuItemWidget(
|
||||
captionedTextWidget: CaptionedTextWidget(
|
||||
title: S.of(context).clusteringProgress,
|
||||
|
|
|
@ -17,9 +17,9 @@ import 'package:photos/ui/viewer/file/video_controls.dart';
|
|||
import "package:photos/utils/dialog_util.dart";
|
||||
import 'package:photos/utils/file_util.dart';
|
||||
import 'package:photos/utils/toast_util.dart';
|
||||
import "package:photos/utils/wakelock_util.dart";
|
||||
import 'package:video_player/video_player.dart';
|
||||
import 'package:visibility_detector/visibility_detector.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
|
||||
class VideoWidget extends StatefulWidget {
|
||||
final EnteFile file;
|
||||
|
@ -45,7 +45,7 @@ class _VideoWidgetState extends State<VideoWidget> {
|
|||
ChewieController? _chewieController;
|
||||
final _progressNotifier = ValueNotifier<double?>(null);
|
||||
bool _isPlaying = false;
|
||||
bool _wakeLockEnabledHere = false;
|
||||
final EnteWakeLock _wakeLock = EnteWakeLock();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
|
@ -126,13 +126,7 @@ class _VideoWidgetState extends State<VideoWidget> {
|
|||
_chewieController?.dispose();
|
||||
_progressNotifier.dispose();
|
||||
|
||||
if (_wakeLockEnabledHere) {
|
||||
unawaited(
|
||||
WakelockPlus.enabled.then((isEnabled) {
|
||||
isEnabled ? WakelockPlus.disable() : null;
|
||||
}),
|
||||
);
|
||||
}
|
||||
_wakeLock.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
|
@ -257,17 +251,10 @@ class _VideoWidgetState extends State<VideoWidget> {
|
|||
|
||||
Future<void> _keepScreenAliveOnPlaying(bool isPlaying) async {
|
||||
if (isPlaying) {
|
||||
return WakelockPlus.enabled.then((value) {
|
||||
if (value == false) {
|
||||
WakelockPlus.enable();
|
||||
//wakeLockEnabledHere will not be set to true if wakeLock is already enabled from settings on iOS.
|
||||
//We shouldn't disable when video is not playing if it was enabled manually by the user from ente settings by user.
|
||||
_wakeLockEnabledHere = true;
|
||||
}
|
||||
});
|
||||
_wakeLock.enable();
|
||||
}
|
||||
if (_wakeLockEnabledHere && !isPlaying) {
|
||||
return WakelockPlus.disable();
|
||||
if (!isPlaying) {
|
||||
_wakeLock.disable();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -5,6 +5,7 @@ import "package:flutter/material.dart";
|
|||
import "package:flutter_animate/flutter_animate.dart";
|
||||
import "package:modal_bottom_sheet/modal_bottom_sheet.dart";
|
||||
import "package:photos/core/configuration.dart";
|
||||
import "package:photos/core/constants.dart";
|
||||
import "package:photos/db/files_db.dart";
|
||||
import "package:photos/generated/l10n.dart";
|
||||
import "package:photos/l10n/l10n.dart";
|
||||
|
@ -167,7 +168,14 @@ class AddPhotosPhotoWidget extends StatelessWidget {
|
|||
|
||||
Future<void> _onPickFromDeviceClicked(BuildContext context) async {
|
||||
try {
|
||||
final List<AssetEntity>? result = await AssetPicker.pickAssets(context);
|
||||
final assetPickerTextDelegate = await _getAssetPickerTextDelegate();
|
||||
final List<AssetEntity>? result = await AssetPicker.pickAssets(
|
||||
context,
|
||||
pickerConfig: AssetPickerConfig(
|
||||
maxAssets: maxPickAssetLimit,
|
||||
textDelegate: assetPickerTextDelegate,
|
||||
),
|
||||
);
|
||||
if (result != null && result.isNotEmpty) {
|
||||
final ca = CollectionActions(
|
||||
CollectionsService.instance,
|
||||
|
@ -204,6 +212,39 @@ class AddPhotosPhotoWidget extends StatelessWidget {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// _getAssetPickerTextDelegate returns the text delegate for the asset picker
|
||||
// This custom method is required to enforce English as the default fallback
|
||||
// instead of Chinese.
|
||||
Future<AssetPickerTextDelegate> _getAssetPickerTextDelegate() async {
|
||||
final Locale locale = await getLocale();
|
||||
switch (locale.languageCode.toLowerCase()) {
|
||||
case "en":
|
||||
return const EnglishAssetPickerTextDelegate();
|
||||
case "he":
|
||||
return const HebrewAssetPickerTextDelegate();
|
||||
case "de":
|
||||
return const GermanAssetPickerTextDelegate();
|
||||
case "ru":
|
||||
return const RussianAssetPickerTextDelegate();
|
||||
case "ja":
|
||||
return const JapaneseAssetPickerTextDelegate();
|
||||
case "ar":
|
||||
return const ArabicAssetPickerTextDelegate();
|
||||
case "fr":
|
||||
return const FrenchAssetPickerTextDelegate();
|
||||
case "vi":
|
||||
return const VietnameseAssetPickerTextDelegate();
|
||||
case "tr":
|
||||
return const TurkishAssetPickerTextDelegate();
|
||||
case "ko":
|
||||
return const KoreanAssetPickerTextDelegate();
|
||||
case "zh":
|
||||
return const AssetPickerTextDelegate();
|
||||
default:
|
||||
return const EnglishAssetPickerTextDelegate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DelayedGallery extends StatefulWidget {
|
||||
|
|
|
@ -97,7 +97,7 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
|
|||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
actions: kDebugMode ? _getDefaultActions(context) : null,
|
||||
actions: _getDefaultActions(context),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -161,43 +161,45 @@ class _ClusterPageState extends State<ClusterPage> {
|
|||
),
|
||||
),
|
||||
showNamingBanner
|
||||
? Dismissible(
|
||||
key: const Key("namingBanner"),
|
||||
direction: DismissDirection.horizontal,
|
||||
onDismissed: (direction) {
|
||||
setState(() {
|
||||
userDismissedNamingBanner = true;
|
||||
});
|
||||
},
|
||||
child: PeopleBanner(
|
||||
type: PeopleBannerType.addName,
|
||||
faceWidget: PersonFaceWidget(
|
||||
files.first,
|
||||
clusterID: widget.clusterID,
|
||||
),
|
||||
actionIcon: Icons.add_outlined,
|
||||
text: S.of(context).addAName,
|
||||
subText: S.of(context).findPeopleByName,
|
||||
onTap: () async {
|
||||
if (widget.personID == null) {
|
||||
final result = await showAssignPersonAction(
|
||||
context,
|
||||
clusterID: widget.clusterID,
|
||||
);
|
||||
if (result != null &&
|
||||
result is (PersonEntity, EnteFile)) {
|
||||
Navigator.pop(context);
|
||||
// ignore: unawaited_futures
|
||||
routeToPage(context, PeoplePage(person: result.$1));
|
||||
} else if (result != null && result is PersonEntity) {
|
||||
Navigator.pop(context);
|
||||
// ignore: unawaited_futures
|
||||
routeToPage(context, PeoplePage(person: result));
|
||||
}
|
||||
} else {
|
||||
showShortToast(context, "No personID or clusterID");
|
||||
}
|
||||
? SafeArea(
|
||||
child: Dismissible(
|
||||
key: const Key("namingBanner"),
|
||||
direction: DismissDirection.horizontal,
|
||||
onDismissed: (direction) {
|
||||
setState(() {
|
||||
userDismissedNamingBanner = true;
|
||||
});
|
||||
},
|
||||
child: PeopleBanner(
|
||||
type: PeopleBannerType.addName,
|
||||
faceWidget: PersonFaceWidget(
|
||||
files.first,
|
||||
clusterID: widget.clusterID,
|
||||
),
|
||||
actionIcon: Icons.add_outlined,
|
||||
text: S.of(context).addAName,
|
||||
subText: S.of(context).findPeopleByName,
|
||||
onTap: () async {
|
||||
if (widget.personID == null) {
|
||||
final result = await showAssignPersonAction(
|
||||
context,
|
||||
clusterID: widget.clusterID,
|
||||
);
|
||||
if (result != null &&
|
||||
result is (PersonEntity, EnteFile)) {
|
||||
Navigator.pop(context);
|
||||
// ignore: unawaited_futures
|
||||
routeToPage(context, PeoplePage(person: result.$1));
|
||||
} else if (result != null && result is PersonEntity) {
|
||||
Navigator.pop(context);
|
||||
// ignore: unawaited_futures
|
||||
routeToPage(context, PeoplePage(person: result));
|
||||
}
|
||||
} else {
|
||||
showShortToast(context, "No personID or clusterID");
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
|
|
|
@ -38,12 +38,17 @@ class _PersonClustersPageState extends State<PersonClustersPage> {
|
|||
.getClusterFilesForPersonID(widget.person.remoteID),
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasData) {
|
||||
final List<int> keys = snapshot.data!.keys.toList();
|
||||
final clusters = snapshot.data!;
|
||||
final List<int> keys = clusters.keys.toList();
|
||||
// Sort the clusters by the number of files in each cluster, largest first
|
||||
keys.sort(
|
||||
(b, a) => clusters[a]!.length.compareTo(clusters[b]!.length),
|
||||
);
|
||||
return ListView.builder(
|
||||
itemCount: keys.length,
|
||||
itemBuilder: (context, index) {
|
||||
final int clusterID = keys[index];
|
||||
final List<EnteFile> files = snapshot.data![keys[index]]!;
|
||||
final List<EnteFile> files = clusters[clusterID]!;
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
|
@ -93,34 +98,37 @@ class _PersonClustersPageState extends State<PersonClustersPage> {
|
|||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
"${snapshot.data![keys[index]]!.length} photos",
|
||||
"${files.length} photos",
|
||||
style: getEnteTextTheme(context).body,
|
||||
),
|
||||
GestureDetector(
|
||||
onTap: () async {
|
||||
try {
|
||||
await PersonService.instance
|
||||
.removeClusterToPerson(
|
||||
personID: widget.person.remoteID,
|
||||
clusterID: clusterID,
|
||||
);
|
||||
_logger.info(
|
||||
"Removed cluster $clusterID from person ${widget.person.remoteID}",
|
||||
);
|
||||
Bus.instance.fire(PeopleChangedEvent());
|
||||
setState(() {});
|
||||
} catch (e) {
|
||||
_logger.severe(
|
||||
"removing cluster from person,",
|
||||
e,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Icon(
|
||||
CupertinoIcons.minus_circled,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
(index != 0)
|
||||
? GestureDetector(
|
||||
onTap: () async {
|
||||
try {
|
||||
await PersonService.instance
|
||||
.removeClusterToPerson(
|
||||
personID: widget.person.remoteID,
|
||||
clusterID: clusterID,
|
||||
);
|
||||
_logger.info(
|
||||
"Removed cluster $clusterID from person ${widget.person.remoteID}",
|
||||
);
|
||||
Bus.instance
|
||||
.fire(PeopleChangedEvent());
|
||||
setState(() {});
|
||||
} catch (e) {
|
||||
_logger.severe(
|
||||
"removing cluster from person,",
|
||||
e,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Icon(
|
||||
CupertinoIcons.minus_circled,
|
||||
color: Colors.red,
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
|
|
@ -203,7 +203,7 @@ class SearchWidgetState extends State<SearchWidget> {
|
|||
String query,
|
||||
) {
|
||||
int resultCount = 0;
|
||||
final maxResultCount = _isYearValid(query) ? 13 : 12;
|
||||
final maxResultCount = _isYearValid(query) ? 12 : 11;
|
||||
final streamController = StreamController<List<SearchResult>>();
|
||||
|
||||
if (query.isEmpty) {
|
||||
|
@ -260,10 +260,11 @@ class SearchWidgetState extends State<SearchWidget> {
|
|||
onResultsReceived(locationResult);
|
||||
},
|
||||
);
|
||||
|
||||
_searchService.getAllFace(null).then(
|
||||
(locationResult) {
|
||||
(faceResult) {
|
||||
final List<GenericSearchResult> filteredResults = [];
|
||||
for (final result in locationResult) {
|
||||
for (final result in faceResult) {
|
||||
if (result.name().toLowerCase().contains(query.toLowerCase())) {
|
||||
filteredResults.add(result);
|
||||
}
|
||||
|
|
|
@ -16,6 +16,7 @@ import 'package:path_provider/path_provider.dart';
|
|||
import 'package:photos/core/configuration.dart';
|
||||
import 'package:photos/core/error-reporting/super_logging.dart';
|
||||
import "package:photos/generated/l10n.dart";
|
||||
import "package:photos/ui/common/progress_dialog.dart";
|
||||
import 'package:photos/ui/components/buttons/button_widget.dart';
|
||||
import 'package:photos/ui/components/dialog_widget.dart';
|
||||
import 'package:photos/ui/components/models/button_type.dart';
|
||||
|
@ -122,9 +123,28 @@ Future<void> _sendLogs(
|
|||
}
|
||||
}
|
||||
|
||||
Future<String> getZippedLogsFile(BuildContext context) async {
|
||||
final dialog = createProgressDialog(context, S.of(context).preparingLogs);
|
||||
await dialog.show();
|
||||
Future<void> sendLogsForInit(
|
||||
String toEmail,
|
||||
String? subject,
|
||||
String? body,
|
||||
) async {
|
||||
final String zipFilePath = await getZippedLogsFile(null);
|
||||
final Email email = Email(
|
||||
recipients: [toEmail],
|
||||
subject: subject ?? '',
|
||||
body: body ?? '',
|
||||
attachmentPaths: [zipFilePath],
|
||||
isHTML: false,
|
||||
);
|
||||
await FlutterEmailSender.send(email);
|
||||
}
|
||||
|
||||
Future<String> getZippedLogsFile(BuildContext? context) async {
|
||||
late final ProgressDialog dialog;
|
||||
if (context != null) {
|
||||
dialog = createProgressDialog(context, S.of(context).preparingLogs);
|
||||
await dialog.show();
|
||||
}
|
||||
final logsPath = (await getApplicationSupportDirectory()).path;
|
||||
final logsDirectory = Directory(logsPath + "/logs");
|
||||
final tempPath = (await getTemporaryDirectory()).path;
|
||||
|
@ -134,7 +154,9 @@ Future<String> getZippedLogsFile(BuildContext context) async {
|
|||
encoder.create(zipFilePath);
|
||||
await encoder.addDirectory(logsDirectory);
|
||||
encoder.close();
|
||||
await dialog.hide();
|
||||
if (context != null) {
|
||||
await dialog.hide();
|
||||
}
|
||||
return zipFilePath;
|
||||
}
|
||||
|
||||
|
|
7
mobile/lib/utils/ml_util.dart
Normal file
7
mobile/lib/utils/ml_util.dart
Normal file
|
@ -0,0 +1,7 @@
|
|||
import "package:photos/core/configuration.dart";
|
||||
import "package:photos/db/files_db.dart";
|
||||
|
||||
Future<List<int>> getIndexableFileIDs() async {
|
||||
return FilesDB.instance
|
||||
.getOwnedFileIDs(Configuration.instance.getUserID()!);
|
||||
}
|
38
mobile/lib/utils/wakelock_util.dart
Normal file
38
mobile/lib/utils/wakelock_util.dart
Normal file
|
@ -0,0 +1,38 @@
|
|||
import "dart:async" show unawaited;
|
||||
|
||||
import "package:wakelock_plus/wakelock_plus.dart";
|
||||
|
||||
class EnteWakeLock {
|
||||
bool _wakeLockEnabledHere = false;
|
||||
|
||||
void enable() {
|
||||
WakelockPlus.enabled.then((value) {
|
||||
if (value == false) {
|
||||
WakelockPlus.enable();
|
||||
//wakeLockEnabledHere will not be set to true if wakeLock is already enabled from settings on iOS.
|
||||
//We shouldn't disable when video is not playing if it was enabled manually by the user from ente settings by user.
|
||||
_wakeLockEnabledHere = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void disable() {
|
||||
if (_wakeLockEnabledHere) {
|
||||
WakelockPlus.disable();
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
if (_wakeLockEnabledHere) {
|
||||
unawaited(
|
||||
WakelockPlus.enabled.then((isEnabled) {
|
||||
isEnabled ? WakelockPlus.disable() : null;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> toggle({required bool enable}) async {
|
||||
await WakelockPlus.toggle(enable: enable);
|
||||
}
|
||||
}
|
|
@ -12,7 +12,7 @@ description: ente photos application
|
|||
# Read more about iOS versioning at
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
|
||||
version: 0.8.108+632
|
||||
version: 0.8.112+636
|
||||
publish_to: none
|
||||
|
||||
environment:
|
||||
|
|
|
@ -95,6 +95,15 @@ db:
|
|||
# Map of data centers
|
||||
#
|
||||
# Each data center also specifies which bucket in that provider should be used.
|
||||
#
|
||||
# If you're not using replication (it is off by default), you only need to
|
||||
# provide valid credentials for the first entry (the default hot storage,
|
||||
# "b2-eu-cen").
|
||||
#
|
||||
# Note that you need to use the same key names (e.g. "b2-eu-cen") as below. The
|
||||
# values and the S3 provider itself can any arbitrary S3 storage, it is not tied
|
||||
# to the region (eu-cen) or provider (b2, wasabi), but for historical reasons
|
||||
# the key names have to be one of those in the list below.
|
||||
s3:
|
||||
# Override the primary and secondary hot storage. The commented out values
|
||||
# are the defaults.
|
||||
|
|
File diff suppressed because one or more lines are too long
|
@ -1,17 +1,16 @@
|
|||
import { CustomHead } from "@/next/components/Head";
|
||||
import { setupI18n } from "@/next/i18n";
|
||||
import { logUnhandledErrorsAndRejections } from "@/next/log-web";
|
||||
import type { AppName, BaseAppContextT } from "@/next/types/app";
|
||||
import { ensure } from "@/utils/ensure";
|
||||
import { PAGES } from "@ente/accounts/constants/pages";
|
||||
import { accountLogout } from "@ente/accounts/services/logout";
|
||||
import { APPS, APP_TITLES } from "@ente/shared/apps/constants";
|
||||
import { Overlay } from "@ente/shared/components/Container";
|
||||
import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
|
||||
import {
|
||||
DialogBoxAttributesV2,
|
||||
SetDialogBoxAttributesV2,
|
||||
} from "@ente/shared/components/DialogBoxV2/types";
|
||||
import type { DialogBoxAttributesV2 } from "@ente/shared/components/DialogBoxV2/types";
|
||||
import EnteSpinner from "@ente/shared/components/EnteSpinner";
|
||||
import AppNavbar from "@ente/shared/components/Navbar/app";
|
||||
import { AppNavbar } from "@ente/shared/components/Navbar/app";
|
||||
import { useLocalState } from "@ente/shared/hooks/useLocalState";
|
||||
import HTTPService from "@ente/shared/network/HTTPService";
|
||||
import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
|
||||
|
@ -22,25 +21,28 @@ import { ThemeProvider } from "@mui/material/styles";
|
|||
import { t } from "i18next";
|
||||
import { AppProps } from "next/app";
|
||||
import { useRouter } from "next/router";
|
||||
import { createContext, useEffect, useState } from "react";
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
import "styles/global.css";
|
||||
|
||||
interface AppContextProps {
|
||||
isMobile: boolean;
|
||||
showNavBar: (show: boolean) => void;
|
||||
setDialogBoxAttributesV2: SetDialogBoxAttributesV2;
|
||||
logout: () => void;
|
||||
}
|
||||
/** The accounts app has no extra properties on top of the base context. */
|
||||
type AppContextT = BaseAppContextT;
|
||||
|
||||
export const AppContext = createContext<AppContextProps>({} as AppContextProps);
|
||||
/** The React {@link Context} available to all pages. */
|
||||
export const AppContext = createContext<AppContextT | undefined>(undefined);
|
||||
|
||||
/** Utility hook to reduce amount of boilerplate in account related pages. */
|
||||
export const useAppContext = () => ensure(useContext(AppContext));
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
const appName: AppName = "account";
|
||||
|
||||
const [isI18nReady, setIsI18nReady] = useState<boolean>(false);
|
||||
|
||||
const [showNavbar, setShowNavBar] = useState(false);
|
||||
|
||||
const [dialogBoxAttributeV2, setDialogBoxAttributesV2] =
|
||||
useState<DialogBoxAttributesV2>();
|
||||
const [dialogBoxAttributeV2, setDialogBoxAttributesV2] = useState<
|
||||
DialogBoxAttributesV2 | undefined
|
||||
>();
|
||||
|
||||
const [dialogBoxV2View, setDialogBoxV2View] = useState(false);
|
||||
|
||||
|
@ -85,8 +87,17 @@ export default function App({ Component, pageProps }: AppProps) {
|
|||
void accountLogout().then(() => router.push(PAGES.ROOT));
|
||||
};
|
||||
|
||||
const appContext = {
|
||||
appName,
|
||||
logout,
|
||||
showNavBar,
|
||||
isMobile,
|
||||
setDialogBoxAttributesV2,
|
||||
};
|
||||
|
||||
// TODO: This string doesn't actually exist
|
||||
const title = isI18nReady
|
||||
? t("TITLE", { context: APPS.ACCOUNTS })
|
||||
? t("title", { context: "accounts" })
|
||||
: APP_TITLES.get(APPS.ACCOUNTS);
|
||||
|
||||
return (
|
||||
|
@ -102,15 +113,7 @@ export default function App({ Component, pageProps }: AppProps) {
|
|||
attributes={dialogBoxAttributeV2 as any}
|
||||
/>
|
||||
|
||||
<AppContext.Provider
|
||||
value={{
|
||||
isMobile,
|
||||
showNavBar,
|
||||
setDialogBoxAttributesV2:
|
||||
setDialogBoxAttributesV2 as any,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
<AppContext.Provider value={appContext}>
|
||||
{!isI18nReady && (
|
||||
<Overlay
|
||||
sx={(theme) => ({
|
||||
|
|
6
web/apps/accounts/src/pages/credentials.tsx
Normal file
6
web/apps/accounts/src/pages/credentials.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/credentials";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,9 +0,0 @@
|
|||
import CredentialPage from "@ente/accounts/pages/credentials";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { useContext } from "react";
|
||||
import { AppContext } from "../_app";
|
||||
|
||||
export default function Credential() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <CredentialPage appContext={appContext} appName={APPS.ACCOUNTS} />;
|
||||
}
|
6
web/apps/accounts/src/pages/generate.tsx
Normal file
6
web/apps/accounts/src/pages/generate.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/generate";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,9 +0,0 @@
|
|||
import GeneratePage from "@ente/accounts/pages/generate";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function Generate() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <GeneratePage appContext={appContext} appName={APPS.ACCOUNTS} />;
|
||||
}
|
6
web/apps/accounts/src/pages/login.tsx
Normal file
6
web/apps/accounts/src/pages/login.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/login";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,9 +0,0 @@
|
|||
import LoginPage from "@ente/accounts/pages/login";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { useContext } from "react";
|
||||
import { AppContext } from "../_app";
|
||||
|
||||
export default function Login() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <LoginPage appContext={appContext} appName={APPS.ACCOUNTS} />;
|
||||
}
|
|
@ -1,16 +1,12 @@
|
|||
import { TwoFactorType } from "@ente/accounts/constants/twofactor";
|
||||
import RecoverPage from "@ente/accounts/pages/recover";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import RecoverPage from "@ente/accounts/pages/two-factor/recover";
|
||||
import { useAppContext } from "../../_app";
|
||||
|
||||
export default function Recover() {
|
||||
const appContext = useContext(AppContext);
|
||||
return (
|
||||
<RecoverPage
|
||||
appContext={appContext}
|
||||
appName={APPS.PHOTOS}
|
||||
twoFactorType={TwoFactorType.PASSKEY}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const Page = () => (
|
||||
<RecoverPage
|
||||
appContext={useAppContext()}
|
||||
twoFactorType={TwoFactorType.PASSKEY}
|
||||
/>
|
||||
);
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -9,14 +9,8 @@ import { t } from "i18next";
|
|||
import _sodium from "libsodium-wrappers";
|
||||
import { useRouter } from "next/router";
|
||||
import { AppContext } from "pages/_app";
|
||||
import {
|
||||
Dispatch,
|
||||
SetStateAction,
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
import { Passkey } from "types/passkey";
|
||||
import {
|
||||
finishPasskeyRegistration,
|
||||
|
|
6
web/apps/accounts/src/pages/recover.tsx
Normal file
6
web/apps/accounts/src/pages/recover.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/recover";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,9 +0,0 @@
|
|||
import RecoverPage from "@ente/accounts/pages/recover";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function Recover() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <RecoverPage appContext={appContext} appName={APPS.ACCOUNTS} />;
|
||||
}
|
6
web/apps/accounts/src/pages/signup.tsx
Normal file
6
web/apps/accounts/src/pages/signup.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/signup";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,9 +0,0 @@
|
|||
import SignupPage from "@ente/accounts/pages/signup";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function Sigup() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <SignupPage appContext={appContext} appName={APPS.ACCOUNTS} />;
|
||||
}
|
6
web/apps/accounts/src/pages/two-factor/recover.tsx
Normal file
6
web/apps/accounts/src/pages/two-factor/recover.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/two-factor/recover";
|
||||
import { useAppContext } from "../_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,11 +0,0 @@
|
|||
import TwoFactorRecoverPage from "@ente/accounts/pages/two-factor/recover";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function TwoFactorRecover() {
|
||||
const appContext = useContext(AppContext);
|
||||
return (
|
||||
<TwoFactorRecoverPage appContext={appContext} appName={APPS.ACCOUNTS} />
|
||||
);
|
||||
}
|
6
web/apps/accounts/src/pages/two-factor/setup.tsx
Normal file
6
web/apps/accounts/src/pages/two-factor/setup.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/two-factor/setup";
|
||||
import { useAppContext } from "../_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,11 +0,0 @@
|
|||
import TwoFactorSetupPage from "@ente/accounts/pages/two-factor/setup";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function TwoFactorSetup() {
|
||||
const appContext = useContext(AppContext);
|
||||
return (
|
||||
<TwoFactorSetupPage appContext={appContext} appName={APPS.ACCOUNTS} />
|
||||
);
|
||||
}
|
6
web/apps/accounts/src/pages/two-factor/verify.tsx
Normal file
6
web/apps/accounts/src/pages/two-factor/verify.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/two-factor/verify";
|
||||
import { useAppContext } from "../_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,11 +0,0 @@
|
|||
import TwoFactorVerifyPage from "@ente/accounts/pages/two-factor/verify";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function TwoFactorVerify() {
|
||||
const appContext = useContext(AppContext);
|
||||
return (
|
||||
<TwoFactorVerifyPage appContext={appContext} appName={APPS.ACCOUNTS} />
|
||||
);
|
||||
}
|
6
web/apps/accounts/src/pages/verify.tsx
Normal file
6
web/apps/accounts/src/pages/verify.tsx
Normal file
|
@ -0,0 +1,6 @@
|
|||
import Page_ from "@ente/accounts/pages/verify";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
|
@ -1,9 +0,0 @@
|
|||
import VerifyPage from "@ente/accounts/pages/verify";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
|
||||
export default function Verify() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <VerifyPage appContext={appContext} appName={APPS.ACCOUNTS} />;
|
||||
}
|
|
@ -1 +1,4 @@
|
|||
NEXT_TELEMETRY_DISABLED = 1
|
||||
|
||||
# For details on how to populate a .env.local to run auth and get it to connect
|
||||
# to an arbitrary Ente instance, see `apps/photos/.env`.
|
||||
|
|
|
@ -9,5 +9,5 @@ module.exports = {
|
|||
tsconfigRootDir: __dirname,
|
||||
project: "./tsconfig.json",
|
||||
},
|
||||
ignorePatterns: [".eslintrc.js", "out"],
|
||||
ignorePatterns: [".eslintrc.js", "next.config.js", "out"],
|
||||
};
|
||||
|
|
|
@ -3,9 +3,12 @@
|
|||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@/build-config": "*",
|
||||
"@/next": "*",
|
||||
"@ente/accounts": "*",
|
||||
"@ente/eslint-config": "*",
|
||||
"@ente/shared": "*"
|
||||
"@ente/shared": "*",
|
||||
"jssha": "~3.3.1",
|
||||
"otpauth": "^9"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,6 +4,8 @@ import {
|
|||
logStartupBanner,
|
||||
logUnhandledErrorsAndRejections,
|
||||
} from "@/next/log-web";
|
||||
import type { AppName, BaseAppContextT } from "@/next/types/app";
|
||||
import { ensure } from "@/utils/ensure";
|
||||
import { accountLogout } from "@ente/accounts/services/logout";
|
||||
import {
|
||||
APPS,
|
||||
|
@ -12,45 +14,46 @@ import {
|
|||
} from "@ente/shared/apps/constants";
|
||||
import { Overlay } from "@ente/shared/components/Container";
|
||||
import DialogBoxV2 from "@ente/shared/components/DialogBoxV2";
|
||||
import {
|
||||
DialogBoxAttributesV2,
|
||||
SetDialogBoxAttributesV2,
|
||||
} from "@ente/shared/components/DialogBoxV2/types";
|
||||
import type { DialogBoxAttributesV2 } from "@ente/shared/components/DialogBoxV2/types";
|
||||
import EnteSpinner from "@ente/shared/components/EnteSpinner";
|
||||
import { MessageContainer } from "@ente/shared/components/MessageContainer";
|
||||
import AppNavbar from "@ente/shared/components/Navbar/app";
|
||||
import { AppNavbar } from "@ente/shared/components/Navbar/app";
|
||||
import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
|
||||
import { useLocalState } from "@ente/shared/hooks/useLocalState";
|
||||
import HTTPService from "@ente/shared/network/HTTPService";
|
||||
import { LS_KEYS, getData } from "@ente/shared/storage/localStorage";
|
||||
import { getTheme } from "@ente/shared/themes";
|
||||
import { THEME_COLOR } from "@ente/shared/themes/constants";
|
||||
import { SetTheme } from "@ente/shared/themes/types";
|
||||
import type { User } from "@ente/shared/user/types";
|
||||
import { CssBaseline, useMediaQuery } from "@mui/material";
|
||||
import { ThemeProvider } from "@mui/material/styles";
|
||||
import { t } from "i18next";
|
||||
import { AppProps } from "next/app";
|
||||
import type { AppProps } from "next/app";
|
||||
import { useRouter } from "next/router";
|
||||
import { createContext, useEffect, useRef, useState } from "react";
|
||||
import LoadingBar from "react-top-loading-bar";
|
||||
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||
import LoadingBar, { type LoadingBarRef } from "react-top-loading-bar";
|
||||
import "../../public/css/global.css";
|
||||
|
||||
type AppContextType = {
|
||||
showNavBar: (show: boolean) => void;
|
||||
/**
|
||||
* Properties available via the {@link AppContext} to the Auth app's React tree.
|
||||
*/
|
||||
type AppContextT = BaseAppContextT & {
|
||||
startLoading: () => void;
|
||||
finishLoading: () => void;
|
||||
isMobile: boolean;
|
||||
themeColor: THEME_COLOR;
|
||||
setThemeColor: SetTheme;
|
||||
setThemeColor: (themeColor: THEME_COLOR) => void;
|
||||
somethingWentWrong: () => void;
|
||||
setDialogBoxAttributesV2: SetDialogBoxAttributesV2;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
export const AppContext = createContext<AppContextType>(null);
|
||||
/** The React {@link Context} available to all pages. */
|
||||
export const AppContext = createContext<AppContextT | undefined>(undefined);
|
||||
|
||||
/** Utility hook to reduce amount of boilerplate in account related pages. */
|
||||
export const useAppContext = () => ensure(useContext(AppContext));
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
const appName: AppName = "auth";
|
||||
|
||||
const router = useRouter();
|
||||
const [isI18nReady, setIsI18nReady] = useState<boolean>(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
@ -58,10 +61,11 @@ export default function App({ Component, pageProps }: AppProps) {
|
|||
typeof window !== "undefined" && !window.navigator.onLine,
|
||||
);
|
||||
const [showNavbar, setShowNavBar] = useState(false);
|
||||
const isLoadingBarRunning = useRef(false);
|
||||
const loadingBar = useRef(null);
|
||||
const [dialogBoxAttributeV2, setDialogBoxAttributesV2] =
|
||||
useState<DialogBoxAttributesV2>();
|
||||
const isLoadingBarRunning = useRef<boolean>(false);
|
||||
const loadingBar = useRef<LoadingBarRef>(null);
|
||||
const [dialogBoxAttributeV2, setDialogBoxAttributesV2] = useState<
|
||||
DialogBoxAttributesV2 | undefined
|
||||
>();
|
||||
const [dialogBoxV2View, setDialogBoxV2View] = useState(false);
|
||||
const isMobile = useMediaQuery("(max-width:428px)");
|
||||
const [themeColor, setThemeColor] = useLocalState(
|
||||
|
@ -134,9 +138,23 @@ export default function App({ Component, pageProps }: AppProps) {
|
|||
void accountLogout().then(() => router.push(PAGES.ROOT));
|
||||
};
|
||||
|
||||
const appContext = {
|
||||
appName,
|
||||
logout,
|
||||
showNavBar,
|
||||
isMobile,
|
||||
setDialogBoxAttributesV2,
|
||||
startLoading,
|
||||
finishLoading,
|
||||
themeColor,
|
||||
setThemeColor,
|
||||
somethingWentWrong,
|
||||
};
|
||||
|
||||
// TODO: Refactor this to have a fallback
|
||||
const title = isI18nReady
|
||||
? t("TITLE", { context: APPS.AUTH })
|
||||
: APP_TITLES.get(APPS.AUTH);
|
||||
? t("title", { context: "auth" })
|
||||
: APP_TITLES.get(APPS.AUTH) ?? "";
|
||||
|
||||
return (
|
||||
<>
|
||||
|
@ -158,19 +176,7 @@ export default function App({ Component, pageProps }: AppProps) {
|
|||
attributes={dialogBoxAttributeV2}
|
||||
/>
|
||||
|
||||
<AppContext.Provider
|
||||
value={{
|
||||
showNavBar,
|
||||
startLoading,
|
||||
finishLoading,
|
||||
isMobile,
|
||||
themeColor,
|
||||
setThemeColor,
|
||||
somethingWentWrong,
|
||||
setDialogBoxAttributesV2,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
<AppContext.Provider value={appContext}>
|
||||
{(loading || !isI18nReady) && (
|
||||
<Overlay
|
||||
sx={(theme) => ({
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import { ensure } from "@/utils/ensure";
|
||||
import {
|
||||
HorizontalFlex,
|
||||
VerticallyCentered,
|
||||
|
@ -12,29 +13,30 @@ import { CustomError } from "@ente/shared/error";
|
|||
import InMemoryStore, { MS_KEYS } from "@ente/shared/storage/InMemoryStore";
|
||||
import LogoutOutlined from "@mui/icons-material/LogoutOutlined";
|
||||
import MoreHoriz from "@mui/icons-material/MoreHoriz";
|
||||
import { Button, ButtonBase, Snackbar, TextField } from "@mui/material";
|
||||
import { Button, ButtonBase, Snackbar, TextField, styled } from "@mui/material";
|
||||
import { t } from "i18next";
|
||||
import { useRouter } from "next/router";
|
||||
import { HOTP, TOTP } from "otpauth";
|
||||
import { AppContext } from "pages/_app";
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { Code } from "services/code";
|
||||
import { generateOTPs, type Code } from "services/code";
|
||||
import { getAuthCodes } from "services/remote";
|
||||
|
||||
const AuthenticatorCodesPage = () => {
|
||||
const appContext = useContext(AppContext);
|
||||
const Page: React.FC = () => {
|
||||
const appContext = ensure(useContext(AppContext));
|
||||
const router = useRouter();
|
||||
const [codes, setCodes] = useState([]);
|
||||
const [codes, setCodes] = useState<Code[]>([]);
|
||||
const [hasFetched, setHasFetched] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const fetchCodes = async () => {
|
||||
try {
|
||||
const res = await getAuthCodes();
|
||||
setCodes(res);
|
||||
} catch (err) {
|
||||
if (err.message === CustomError.KEY_MISSING) {
|
||||
setCodes(await getAuthCodes());
|
||||
} catch (e) {
|
||||
if (
|
||||
e instanceof Error &&
|
||||
e.message == CustomError.KEY_MISSING
|
||||
) {
|
||||
InMemoryStore.set(MS_KEYS.REDIRECT_URL, PAGES.AUTH);
|
||||
router.push(PAGES.ROOT);
|
||||
} else {
|
||||
|
@ -43,27 +45,22 @@ const AuthenticatorCodesPage = () => {
|
|||
}
|
||||
setHasFetched(true);
|
||||
};
|
||||
fetchCodes();
|
||||
void fetchCodes();
|
||||
appContext.showNavBar(false);
|
||||
}, []);
|
||||
|
||||
const lcSearch = searchTerm.toLowerCase();
|
||||
const filteredCodes = codes.filter(
|
||||
(secret) =>
|
||||
(secret.issuer ?? "")
|
||||
.toLowerCase()
|
||||
.includes(searchTerm.toLowerCase()) ||
|
||||
(secret.account ?? "")
|
||||
.toLowerCase()
|
||||
.includes(searchTerm.toLowerCase()),
|
||||
(code) =>
|
||||
code.issuer?.toLowerCase().includes(lcSearch) ||
|
||||
code.account?.toLowerCase().includes(lcSearch),
|
||||
);
|
||||
|
||||
if (!hasFetched) {
|
||||
return (
|
||||
<>
|
||||
<VerticallyCentered>
|
||||
<EnteSpinner></EnteSpinner>
|
||||
</VerticallyCentered>
|
||||
</>
|
||||
<VerticallyCentered>
|
||||
<EnteSpinner />
|
||||
</VerticallyCentered>
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -81,7 +78,7 @@ const AuthenticatorCodesPage = () => {
|
|||
}}
|
||||
>
|
||||
<div style={{ marginBottom: "1rem" }} />
|
||||
{filteredCodes.length === 0 && searchTerm.length === 0 ? (
|
||||
{filteredCodes.length == 0 && searchTerm.length == 0 ? (
|
||||
<></>
|
||||
) : (
|
||||
<TextField
|
||||
|
@ -105,7 +102,7 @@ const AuthenticatorCodesPage = () => {
|
|||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{filteredCodes.length === 0 ? (
|
||||
{filteredCodes.length == 0 ? (
|
||||
<div
|
||||
style={{
|
||||
alignItems: "center",
|
||||
|
@ -114,30 +111,28 @@ const AuthenticatorCodesPage = () => {
|
|||
marginTop: "32px",
|
||||
}}
|
||||
>
|
||||
{searchTerm.length !== 0 ? (
|
||||
{searchTerm.length > 0 ? (
|
||||
<p>{t("NO_RESULTS")}</p>
|
||||
) : (
|
||||
<div />
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
filteredCodes.map((code) => (
|
||||
<CodeDisplay codeInfo={code} key={code.id} />
|
||||
<CodeDisplay key={code.id} code={code} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<div style={{ marginBottom: "2rem" }} />
|
||||
<AuthFooter />
|
||||
<div style={{ marginBottom: "4rem" }} />
|
||||
<Footer />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthenticatorCodesPage;
|
||||
export default Page;
|
||||
|
||||
const AuthNavbar: React.FC = () => {
|
||||
const { isMobile, logout } = useContext(AppContext);
|
||||
const { isMobile, logout } = ensure(useContext(AppContext));
|
||||
|
||||
return (
|
||||
<NavbarBase isMobile={isMobile}>
|
||||
|
@ -162,98 +157,61 @@ const AuthNavbar: React.FC = () => {
|
|||
);
|
||||
};
|
||||
|
||||
interface CodeDisplay {
|
||||
codeInfo: Code;
|
||||
interface CodeDisplayProps {
|
||||
code: Code;
|
||||
}
|
||||
|
||||
const CodeDisplay: React.FC<CodeDisplay> = ({ codeInfo }) => {
|
||||
const CodeDisplay: React.FC<CodeDisplayProps> = ({ code }) => {
|
||||
const [otp, setOTP] = useState("");
|
||||
const [nextOTP, setNextOTP] = useState("");
|
||||
const [codeErr, setCodeErr] = useState("");
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [hasCopied, setHasCopied] = useState(false);
|
||||
|
||||
const generateCodes = () => {
|
||||
const regen = () => {
|
||||
try {
|
||||
const currentTime = new Date().getTime();
|
||||
if (codeInfo.type === "totp") {
|
||||
const totp = new TOTP({
|
||||
secret: codeInfo.secret,
|
||||
algorithm: codeInfo.algorithm,
|
||||
period: codeInfo.period,
|
||||
digits: codeInfo.digits,
|
||||
});
|
||||
setOTP(totp.generate());
|
||||
setNextOTP(
|
||||
totp.generate({
|
||||
timestamp: currentTime + codeInfo.period * 1000,
|
||||
}),
|
||||
);
|
||||
} else if (codeInfo.type === "hotp") {
|
||||
const hotp = new HOTP({
|
||||
secret: codeInfo.secret,
|
||||
counter: 0,
|
||||
algorithm: codeInfo.algorithm,
|
||||
});
|
||||
setOTP(hotp.generate());
|
||||
setNextOTP(hotp.generate({ counter: 1 }));
|
||||
}
|
||||
} catch (err) {
|
||||
setCodeErr(err.message);
|
||||
const [m, n] = generateOTPs(code);
|
||||
setOTP(m);
|
||||
setNextOTP(n);
|
||||
} catch (e) {
|
||||
setErrorMessage(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
const copyCode = () => {
|
||||
navigator.clipboard.writeText(otp);
|
||||
setHasCopied(true);
|
||||
setTimeout(() => {
|
||||
setHasCopied(false);
|
||||
}, 2000);
|
||||
setTimeout(() => setHasCopied(false), 2000);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// this is to set the initial code and nextCode on component mount
|
||||
generateCodes();
|
||||
const codeType = codeInfo.type;
|
||||
const codePeriodInMs = codeInfo.period * 1000;
|
||||
const timeToNextCode =
|
||||
codePeriodInMs - (new Date().getTime() % codePeriodInMs);
|
||||
const intervalId = null;
|
||||
// wait until we are at the start of the next code period,
|
||||
// and then start the interval loop
|
||||
// Generate to set the initial otp and nextOTP on component mount.
|
||||
regen();
|
||||
|
||||
const periodMs = code.period * 1000;
|
||||
const timeToNextCode = periodMs - (Date.now() % periodMs);
|
||||
|
||||
let interval: ReturnType<typeof setInterval> | undefined;
|
||||
// Wait until we are at the start of the next code period, and then
|
||||
// start the interval loop.
|
||||
setTimeout(() => {
|
||||
// we need to call generateCodes() once before the interval loop
|
||||
// to set the initial code and nextCode
|
||||
generateCodes();
|
||||
codeType.toLowerCase() === "totp" ||
|
||||
codeType.toLowerCase() === "hotp"
|
||||
? setInterval(() => {
|
||||
generateCodes();
|
||||
}, codePeriodInMs)
|
||||
: null;
|
||||
// We need to call regen() once before the interval loop to set the
|
||||
// initial otp and nextOTP.
|
||||
regen();
|
||||
interval = setInterval(regen, periodMs);
|
||||
}, timeToNextCode);
|
||||
|
||||
return () => {
|
||||
if (intervalId) clearInterval(intervalId);
|
||||
};
|
||||
}, [codeInfo]);
|
||||
return () => interval && clearInterval(interval);
|
||||
}, [code]);
|
||||
|
||||
return (
|
||||
<div style={{ padding: "8px" }}>
|
||||
{codeErr === "" ? (
|
||||
<ButtonBase
|
||||
component="div"
|
||||
onClick={() => {
|
||||
copyCode();
|
||||
}}
|
||||
>
|
||||
<OTPDisplay code={codeInfo} otp={otp} nextOTP={nextOTP} />
|
||||
<Snackbar
|
||||
open={hasCopied}
|
||||
message="Code copied to clipboard"
|
||||
/>
|
||||
</ButtonBase>
|
||||
{errorMessage ? (
|
||||
<UnparseableCode {...{ code, errorMessage }} />
|
||||
) : (
|
||||
<BadCodeInfo codeInfo={codeInfo} codeErr={codeErr} />
|
||||
<ButtonBase component="div" onClick={copyCode}>
|
||||
<OTPDisplay {...{ code, otp, nextOTP }} />
|
||||
<Snackbar open={hasCopied} message={t("COPIED")} />
|
||||
</ButtonBase>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
@ -274,7 +232,7 @@ const OTPDisplay: React.FC<OTPDisplayProps> = ({ code, otp, nextOTP }) => {
|
|||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<TimerProgress period={code.period} />
|
||||
<CodeValidityBar code={code} />
|
||||
<div
|
||||
style={{
|
||||
padding: "12px 20px 0px 20px",
|
||||
|
@ -301,7 +259,7 @@ const OTPDisplay: React.FC<OTPDisplayProps> = ({ code, otp, nextOTP }) => {
|
|||
textAlign: "left",
|
||||
}}
|
||||
>
|
||||
{code.issuer}
|
||||
{code.issuer ?? ""}
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
|
@ -314,7 +272,7 @@ const OTPDisplay: React.FC<OTPDisplayProps> = ({ code, otp, nextOTP }) => {
|
|||
color: "grey",
|
||||
}}
|
||||
>
|
||||
{code.account}
|
||||
{code.account ?? ""}
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
|
@ -370,28 +328,25 @@ const OTPDisplay: React.FC<OTPDisplayProps> = ({ code, otp, nextOTP }) => {
|
|||
);
|
||||
};
|
||||
|
||||
interface TimerProgressProps {
|
||||
period: number;
|
||||
interface CodeValidityBarProps {
|
||||
code: Code;
|
||||
}
|
||||
|
||||
const TimerProgress: React.FC<TimerProgressProps> = ({ period }) => {
|
||||
const [progress, setProgress] = useState(0);
|
||||
const microSecondsInPeriod = period * 1000000;
|
||||
const CodeValidityBar: React.FC<CodeValidityBarProps> = ({ code }) => {
|
||||
const [progress, setProgress] = useState(code.type == "hotp" ? 1 : 0);
|
||||
|
||||
useEffect(() => {
|
||||
const updateTimeRemaining = () => {
|
||||
const timeRemaining =
|
||||
microSecondsInPeriod -
|
||||
((new Date().getTime() * 1000) % microSecondsInPeriod);
|
||||
setProgress(timeRemaining / microSecondsInPeriod);
|
||||
const advance = () => {
|
||||
const us = code.period * 1e6;
|
||||
const timeRemaining = us - ((Date.now() * 1000) % us);
|
||||
setProgress(timeRemaining / us);
|
||||
};
|
||||
|
||||
const ticker = setInterval(() => {
|
||||
updateTimeRemaining();
|
||||
}, 10);
|
||||
const ticker =
|
||||
code.type == "hotp" ? undefined : setInterval(advance, 10);
|
||||
|
||||
return () => clearInterval(ticker);
|
||||
}, []);
|
||||
return () => ticker && clearInterval(ticker);
|
||||
}, [code]);
|
||||
|
||||
const color = progress > 0.4 ? "green" : "orange";
|
||||
|
||||
|
@ -407,17 +362,25 @@ const TimerProgress: React.FC<TimerProgressProps> = ({ period }) => {
|
|||
);
|
||||
};
|
||||
|
||||
function BadCodeInfo({ codeInfo, codeErr }) {
|
||||
interface UnparseableCodeProps {
|
||||
code: Code;
|
||||
errorMessage: string;
|
||||
}
|
||||
|
||||
const UnparseableCode: React.FC<UnparseableCodeProps> = ({
|
||||
code,
|
||||
errorMessage,
|
||||
}) => {
|
||||
const [showRawData, setShowRawData] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="code-info">
|
||||
<div>{codeInfo.title}</div>
|
||||
<div>{codeErr}</div>
|
||||
<div>{code.issuer}</div>
|
||||
<div>{errorMessage}</div>
|
||||
<div>
|
||||
{showRawData ? (
|
||||
<div onClick={() => setShowRawData(false)}>
|
||||
{codeInfo.uriString ?? "(no raw data)"}
|
||||
{code.uriString}
|
||||
</div>
|
||||
) : (
|
||||
<div onClick={() => setShowRawData(true)}>Show rawData</div>
|
||||
|
@ -425,18 +388,11 @@ function BadCodeInfo({ codeInfo, codeErr }) {
|
|||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const AuthFooter: React.FC = () => {
|
||||
const Footer: React.FC = () => {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
<Footer_>
|
||||
<p>{t("AUTH_DOWNLOAD_MOBILE_APP")}</p>
|
||||
<a
|
||||
href="https://github.com/ente-io/ente/tree/main/auth#-download"
|
||||
|
@ -444,6 +400,15 @@ const AuthFooter: React.FC = () => {
|
|||
>
|
||||
<Button color="accent">{t("DOWNLOAD")}</Button>
|
||||
</a>
|
||||
</div>
|
||||
</Footer_>
|
||||
);
|
||||
};
|
||||
|
||||
const Footer_ = styled("div")`
|
||||
margin-block-start: 2rem;
|
||||
margin-block-end: 4rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import ChangeEmailPage from "@ente/accounts/pages/change-email";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/change-email";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function ChangeEmail() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <ChangeEmailPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import ChangePasswordPage from "@ente/accounts/pages/change-password";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/change-password";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function ChangePassword() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <ChangePasswordPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import CredentialPage from "@ente/accounts/pages/credentials";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/credentials";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function Credential() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <CredentialPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import GeneratePage from "@ente/accounts/pages/generate";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/generate";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function Generate() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <GeneratePage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect } from "react";
|
||||
import React, { useEffect } from "react";
|
||||
|
||||
const IndexPage = () => {
|
||||
const Page: React.FC = () => {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
router.push(PAGES.LOGIN);
|
||||
|
@ -11,4 +11,4 @@ const IndexPage = () => {
|
|||
return <></>;
|
||||
};
|
||||
|
||||
export default IndexPage;
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import LoginPage from "@ente/accounts/pages/login";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/login";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function Login() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <LoginPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,11 +1,3 @@
|
|||
import PasskeysFinishPage from "@ente/accounts/pages/passkeys/finish";
|
||||
import Page from "@ente/accounts/pages/passkeys/finish";
|
||||
|
||||
const PasskeysFinish = () => {
|
||||
return (
|
||||
<>
|
||||
<PasskeysFinishPage />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PasskeysFinish;
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import RecoverPage from "@ente/accounts/pages/recover";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/recover";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function Recover() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <RecoverPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import SignupPage from "@ente/accounts/pages/signup";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/signup";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function Sigup() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <SignupPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import TwoFactorRecoverPage from "@ente/accounts/pages/two-factor/recover";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/two-factor/recover";
|
||||
import { useAppContext } from "../_app";
|
||||
|
||||
export default function TwoFactorRecover() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <TwoFactorRecoverPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import TwoFactorSetupPage from "@ente/accounts/pages/two-factor/setup";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/two-factor/setup";
|
||||
import { useAppContext } from "../_app";
|
||||
|
||||
export default function TwoFactorSetup() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <TwoFactorSetupPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import TwoFactorVerifyPage from "@ente/accounts/pages/two-factor/verify";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { useContext } from "react";
|
||||
import { AppContext } from "../_app";
|
||||
import Page_ from "@ente/accounts/pages/two-factor/verify";
|
||||
import { useAppContext } from "../_app";
|
||||
|
||||
export default function TwoFactorVerify() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <TwoFactorVerifyPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
import VerifyPage from "@ente/accounts/pages/verify";
|
||||
import { APPS } from "@ente/shared/apps/constants";
|
||||
import { AppContext } from "pages/_app";
|
||||
import { useContext } from "react";
|
||||
import Page_ from "@ente/accounts/pages/verify";
|
||||
import { useAppContext } from "./_app";
|
||||
|
||||
export default function Verify() {
|
||||
const appContext = useContext(AppContext);
|
||||
return <VerifyPage appContext={appContext} appName={APPS.AUTH} />;
|
||||
}
|
||||
const Page = () => <Page_ appContext={useAppContext()} />;
|
||||
|
||||
export default Page;
|
||||
|
|
|
@ -1,32 +1,52 @@
|
|||
import { URI } from "vscode-uri";
|
||||
import { ensure } from "@/utils/ensure";
|
||||
import { HOTP, TOTP } from "otpauth";
|
||||
import { Steam } from "./steam";
|
||||
|
||||
/**
|
||||
* A parsed representation of an xOTP code URI.
|
||||
* A parsed representation of an *OTP code URI.
|
||||
*
|
||||
* This is all the data we need to drive a OTP generator.
|
||||
*/
|
||||
export interface Code {
|
||||
/** The uniquue id for the corresponding auth entity. */
|
||||
id?: String;
|
||||
/** A unique id for the corresponding "auth entity" in our system. */
|
||||
id: string;
|
||||
/** The type of the code. */
|
||||
type: "totp" | "hotp";
|
||||
type: "totp" | "hotp" | "steam";
|
||||
/** The user's account or email for which this code is used. */
|
||||
account: string;
|
||||
account?: string;
|
||||
/** The name of the entity that issued this code. */
|
||||
issuer: string;
|
||||
/** Number of digits in the code. */
|
||||
digits: number;
|
||||
/**
|
||||
* Length of the generated OTP.
|
||||
*
|
||||
* This is vernacularly called "digits", which is an accurate description
|
||||
* for the OG TOTP/HOTP codes. However, steam codes are not just digits, so
|
||||
* we name this as a content-neutral "length".
|
||||
*/
|
||||
length: number;
|
||||
/**
|
||||
* The time period (in seconds) for which a single OTP generated from this
|
||||
* code remains valid.
|
||||
*/
|
||||
period: number;
|
||||
/** The secret that is used to drive the OTP generator. */
|
||||
secret: string;
|
||||
/** The (hashing) algorithim used by the OTP generator. */
|
||||
/** The (HMAC) algorithm used by the OTP generator. */
|
||||
algorithm: "sha1" | "sha256" | "sha512";
|
||||
/**
|
||||
* HOTP counter.
|
||||
*
|
||||
* Only valid for HOTP codes. It might be even missing for HOTP codes, in
|
||||
* which case we should start from 0.
|
||||
*/
|
||||
counter?: number;
|
||||
/**
|
||||
* The secret that is used to drive the OTP generator.
|
||||
*
|
||||
* This is an arbitrary key encoded in Base32 that drives the HMAC (in a
|
||||
* {@link type}-specific manner).
|
||||
*/
|
||||
secret: string;
|
||||
/** The original string from which this code was generated. */
|
||||
uriString?: string;
|
||||
uriString: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -38,98 +58,139 @@ export interface Code {
|
|||
* code. These strings are of the form:
|
||||
*
|
||||
* - (TOTP)
|
||||
* otpauth://totp/account:user@example.org?algorithm=SHA1&digits=6&issuer=issuer&period=30&secret=ALPHANUM
|
||||
* otpauth://totp/ACME:user@example.org?algorithm=SHA1&digits=6&issuer=acme&period=30&secret=ALPHANUM
|
||||
*
|
||||
* - (HOTP)
|
||||
* otpauth://hotp/Test?secret=AAABBBCCCDDDEEEFFF&issuer=Test&counter=0
|
||||
*
|
||||
* - (Steam)
|
||||
* otpauth://steam/Steam:SteamAccount?algorithm=SHA1&digits=5&issuer=Steam&period=30&secret=AAABBBCCCDDDEEEFFF
|
||||
*
|
||||
* See also `auth/test/models/code_test.dart`.
|
||||
*/
|
||||
export const codeFromURIString = (id: string, uriString: string): Code => {
|
||||
let santizedRawData = uriString
|
||||
.replace(/\+/g, "%2B")
|
||||
.replace(/:/g, "%3A")
|
||||
.replaceAll("\r", "");
|
||||
if (santizedRawData.startsWith('"')) {
|
||||
santizedRawData = santizedRawData.substring(1);
|
||||
}
|
||||
if (santizedRawData.endsWith('"')) {
|
||||
santizedRawData = santizedRawData.substring(
|
||||
0,
|
||||
santizedRawData.length - 1,
|
||||
);
|
||||
try {
|
||||
return _codeFromURIString(id, uriString);
|
||||
} catch (e) {
|
||||
// We might have legacy encodings of account names that contain a "#",
|
||||
// which causes the rest of the URL to be treated as a fragment, and
|
||||
// ignored. See if this was potentially such a case, otherwise rethrow.
|
||||
if (uriString.includes("#"))
|
||||
return _codeFromURIString(id, uriString.replaceAll("#", "%23"));
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
const uriParams = {};
|
||||
const searchParamsString =
|
||||
decodeURIComponent(santizedRawData).split("?")[1];
|
||||
searchParamsString.split("&").forEach((pair) => {
|
||||
const [key, value] = pair.split("=");
|
||||
uriParams[key] = value;
|
||||
});
|
||||
const _codeFromURIString = (id: string, uriString: string): Code => {
|
||||
const url = new URL(uriString);
|
||||
|
||||
const uri = URI.parse(santizedRawData);
|
||||
let uriPath = decodeURIComponent(uri.path);
|
||||
if (uriPath.startsWith("/otpauth://") || uriPath.startsWith("otpauth://")) {
|
||||
uriPath = uriPath.split("otpauth://")[1];
|
||||
} else if (uriPath.startsWith("otpauth%3A//")) {
|
||||
uriPath = uriPath.split("otpauth%3A//")[1];
|
||||
}
|
||||
const [type, path] = parsePathname(url);
|
||||
|
||||
return {
|
||||
id,
|
||||
type: _getType(uriPath),
|
||||
account: _getAccount(uriPath),
|
||||
issuer: _getIssuer(uriPath, uriParams),
|
||||
digits: parseDigits(uriParams),
|
||||
period: parsePeriod(uriParams),
|
||||
secret: getSanitizedSecret(uriParams),
|
||||
algorithm: parseAlgorithm(uriParams),
|
||||
type,
|
||||
account: parseAccount(path),
|
||||
issuer: parseIssuer(url, path),
|
||||
length: parseLength(url, type),
|
||||
period: parsePeriod(url),
|
||||
algorithm: parseAlgorithm(url),
|
||||
counter: parseCounter(url),
|
||||
secret: parseSecret(url),
|
||||
uriString,
|
||||
};
|
||||
};
|
||||
|
||||
const _getAccount = (uriPath: string): string => {
|
||||
try {
|
||||
const path = decodeURIComponent(uriPath);
|
||||
if (path.includes(":")) {
|
||||
return path.split(":")[1];
|
||||
} else if (path.includes("/")) {
|
||||
return path.split("/")[1];
|
||||
}
|
||||
} catch (e) {
|
||||
return "";
|
||||
const parsePathname = (url: URL): [type: Code["type"], path: string] => {
|
||||
// A URL like
|
||||
//
|
||||
// new
|
||||
// URL("otpauth://hotp/Test?secret=AAABBBCCCDDDEEEFFF&issuer=Test&counter=0")
|
||||
//
|
||||
// is parsed differently by different browsers, and there are differences
|
||||
// even depending on the scheme.
|
||||
//
|
||||
// When the scheme is http(s), then all of them consider "hotp" as the
|
||||
// `host`. However, when the scheme is "otpauth", as is our case, Safari
|
||||
// splits it into
|
||||
//
|
||||
// host: "hotp"
|
||||
// pathname: "/Test"
|
||||
//
|
||||
// while Chrome and Firefox consider the entire thing as part of the
|
||||
// pathname
|
||||
//
|
||||
// host: ""
|
||||
// pathname: "//hotp/Test"
|
||||
//
|
||||
// So we try to handle both scenarios by first checking for the host match,
|
||||
// and if not fall back to deducing the "host" from the pathname.
|
||||
|
||||
switch (url.host.toLowerCase()) {
|
||||
case "totp":
|
||||
return ["totp", url.pathname.toLowerCase()];
|
||||
case "hotp":
|
||||
return ["hotp", url.pathname.toLowerCase()];
|
||||
case "steam":
|
||||
return ["steam", url.pathname.toLowerCase()];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const p = url.pathname.toLowerCase();
|
||||
if (p.startsWith("//totp")) return ["totp", url.pathname.slice(6)];
|
||||
if (p.startsWith("//hotp")) return ["hotp", url.pathname.slice(6)];
|
||||
if (p.startsWith("//steam")) return ["steam", url.pathname.slice(7)];
|
||||
|
||||
throw new Error(`Unsupported code or unparseable path "${url.pathname}"`);
|
||||
};
|
||||
|
||||
const _getIssuer = (uriPath: string, uriParams: { get?: any }): string => {
|
||||
try {
|
||||
if (uriParams["issuer"] !== undefined) {
|
||||
let issuer = uriParams["issuer"];
|
||||
// This is to handle bug in the ente auth app
|
||||
if (issuer.endsWith("period")) {
|
||||
issuer = issuer.substring(0, issuer.length - 6);
|
||||
}
|
||||
return issuer;
|
||||
}
|
||||
let path = decodeURIComponent(uriPath);
|
||||
if (path.startsWith("totp/") || path.startsWith("hotp/")) {
|
||||
path = path.substring(5);
|
||||
}
|
||||
if (path.includes(":")) {
|
||||
return path.split(":")[0];
|
||||
} else if (path.includes("-")) {
|
||||
return path.split("-")[0];
|
||||
}
|
||||
return path;
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
const parseAccount = (path: string): string | undefined => {
|
||||
// "/ACME:user@example.org" => "user@example.org"
|
||||
let p = decodeURIComponent(path);
|
||||
if (p.startsWith("/")) p = p.slice(1);
|
||||
if (p.includes(":")) p = p.split(":").slice(1).join(":");
|
||||
return p;
|
||||
};
|
||||
|
||||
const parseDigits = (uriParams): number =>
|
||||
parseInt(uriParams["digits"] ?? "", 10) || 6;
|
||||
const parseIssuer = (url: URL, path: string): string => {
|
||||
// If there is a "issuer" search param, use that.
|
||||
let issuer = url.searchParams.get("issuer");
|
||||
if (issuer) {
|
||||
// This is to handle bug in old versions of Ente Auth app.
|
||||
if (issuer.endsWith("period")) {
|
||||
issuer = issuer.substring(0, issuer.length - 6);
|
||||
}
|
||||
return issuer;
|
||||
}
|
||||
|
||||
const parsePeriod = (uriParams): number =>
|
||||
parseInt(uriParams["period"] ?? "", 10) || 30;
|
||||
// Otherwise use the `prefix:` from the account as the issuer.
|
||||
// "/ACME:user@example.org" => "ACME"
|
||||
let p = decodeURIComponent(path);
|
||||
if (p.startsWith("/")) p = p.slice(1);
|
||||
|
||||
const parseAlgorithm = (uriParams): Code["algorithm"] => {
|
||||
switch (uriParams["algorithm"]?.toLowerCase()) {
|
||||
if (p.includes(":")) p = ensure(p.split(":")[0]);
|
||||
else if (p.includes("-")) p = ensure(p.split("-")[0]);
|
||||
|
||||
return p;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse the length of the generated code.
|
||||
*
|
||||
* The URI query param is called digits since originally TOTP/HOTP codes used
|
||||
* this for generating numeric codes. Now we also support steam, which instead
|
||||
* shows non-numeric codes, and also with a different default length of 5.
|
||||
*/
|
||||
const parseLength = (url: URL, type: Code["type"]): number => {
|
||||
const defaultLength = type == "steam" ? 5 : 6;
|
||||
return parseInt(url.searchParams.get("digits") ?? "", 10) || defaultLength;
|
||||
};
|
||||
|
||||
const parsePeriod = (url: URL): number =>
|
||||
parseInt(url.searchParams.get("period") ?? "", 10) || 30;
|
||||
|
||||
const parseAlgorithm = (url: URL): Code["algorithm"] => {
|
||||
switch (url.searchParams.get("algorithm")?.toLowerCase()) {
|
||||
case "sha256":
|
||||
return "sha256";
|
||||
case "sha512":
|
||||
|
@ -139,16 +200,62 @@ const parseAlgorithm = (uriParams): Code["algorithm"] => {
|
|||
}
|
||||
};
|
||||
|
||||
const _getType = (uriPath: string): Code["type"] => {
|
||||
const oauthType = uriPath.split("/")[0].substring(0);
|
||||
if (oauthType.toLowerCase() === "totp") {
|
||||
return "totp";
|
||||
} else if (oauthType.toLowerCase() === "hotp") {
|
||||
return "hotp";
|
||||
}
|
||||
throw new Error(`Unsupported format with host ${oauthType}`);
|
||||
const parseCounter = (url: URL): number | undefined => {
|
||||
const c = url.searchParams.get("counter");
|
||||
return c ? parseInt(c, 10) : undefined;
|
||||
};
|
||||
|
||||
const getSanitizedSecret = (uriParams): string => {
|
||||
return uriParams["secret"].replace(/ /g, "").toUpperCase();
|
||||
const parseSecret = (url: URL): string =>
|
||||
ensure(url.searchParams.get("secret")).replaceAll(" ", "").toUpperCase();
|
||||
|
||||
/**
|
||||
* Generate a pair of OTPs (one time passwords) from the given {@link code}.
|
||||
*
|
||||
* @param code The parsed code data, including the secret and code type.
|
||||
*
|
||||
* @returns a pair of OTPs, the current one and the next one, using the given
|
||||
* {@link code}.
|
||||
*/
|
||||
export const generateOTPs = (code: Code): [otp: string, nextOTP: string] => {
|
||||
let otp: string;
|
||||
let nextOTP: string;
|
||||
switch (code.type) {
|
||||
case "totp": {
|
||||
const totp = new TOTP({
|
||||
secret: code.secret,
|
||||
algorithm: code.algorithm,
|
||||
period: code.period,
|
||||
digits: code.length,
|
||||
});
|
||||
otp = totp.generate();
|
||||
nextOTP = totp.generate({
|
||||
timestamp: Date.now() + code.period * 1000,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "hotp": {
|
||||
const counter = code.counter || 0;
|
||||
const hotp = new HOTP({
|
||||
secret: code.secret,
|
||||
counter: counter,
|
||||
algorithm: code.algorithm,
|
||||
});
|
||||
otp = hotp.generate({ counter });
|
||||
nextOTP = hotp.generate({ counter: counter + 1 });
|
||||
break;
|
||||
}
|
||||
|
||||
case "steam": {
|
||||
const steam = new Steam({
|
||||
secret: code.secret,
|
||||
});
|
||||
otp = steam.generate();
|
||||
nextOTP = steam.generate({
|
||||
timestamp: Date.now() + code.period * 1000,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
return [otp, nextOTP];
|
||||
};
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue