Compare commits
28 Commits
feature/sc
...
374-improv
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3c9c8610d | ||
|
|
9c2d50c7b0 | ||
|
|
0cd9df7415 | ||
|
|
a4a3112dc6 | ||
|
|
6351e1f3d0 | ||
|
|
2959d8cbcc | ||
|
|
c98680347a | ||
|
|
35367bb28b | ||
|
|
8a1890bc10 | ||
|
|
bf4035fcfe | ||
|
|
d3dfbaab4b | ||
|
|
227074efb6 | ||
|
|
69f79c1b20 | ||
|
|
000d1254ec | ||
|
|
324fc1f2ee | ||
|
|
52121c6a85 | ||
|
|
c6f494ac33 | ||
|
|
400e171bc5 | ||
|
|
41e6e67e87 | ||
|
|
8277283ebc | ||
|
|
71806178d0 | ||
|
|
aa2e4b856d | ||
|
|
cfb185b53d | ||
|
|
c3b6612591 | ||
|
|
fefcf8f30e | ||
|
|
e95cc84a15 | ||
|
|
c0ed185612 | ||
|
|
61c871f782 |
45
.github/workflows/build.yml
vendored
45
.github/workflows/build.yml
vendored
@@ -78,7 +78,7 @@ jobs:
|
||||
|
||||
# - name: Build keepass2android (net)
|
||||
# run: |
|
||||
# make dotnetbuild Flavor=Net
|
||||
# make msbuild Flavor=Net
|
||||
|
||||
# - name: Build APK (net)
|
||||
# run: |
|
||||
@@ -96,7 +96,7 @@ jobs:
|
||||
|
||||
# - name: Build keepass2android (nonet)
|
||||
# run: |
|
||||
# make dotnetbuild Flavor=NoNet
|
||||
# make msbuild Flavor=NoNet
|
||||
|
||||
# - name: Build APK (nonet)
|
||||
# run: |
|
||||
@@ -212,7 +212,7 @@ jobs:
|
||||
|
||||
# - name: Build keepass2android (net)
|
||||
# run: |
|
||||
# make dotnetbuild Flavor=Net
|
||||
# make msbuild Flavor=Net
|
||||
|
||||
# - name: Build APK (net)
|
||||
# run: |
|
||||
@@ -230,7 +230,7 @@ jobs:
|
||||
|
||||
# - name: Build keepass2android (nonet)
|
||||
# run: |
|
||||
# make dotnetbuild Flavor=NoNet
|
||||
# make msbuild Flavor=NoNet
|
||||
|
||||
# - name: Build APK (nonet)
|
||||
# run: |
|
||||
@@ -279,7 +279,7 @@ jobs:
|
||||
with:
|
||||
minimum-size: 8GB
|
||||
|
||||
- name: Add dotnetbuild to PATH
|
||||
- name: Add msbuild to PATH
|
||||
uses: microsoft/setup-msbuild@v2
|
||||
# If we want to also have nmake, use this instead
|
||||
#uses: ilammy/msvc-dev-cmd@v1
|
||||
@@ -309,49 +309,30 @@ jobs:
|
||||
run: |
|
||||
make java
|
||||
|
||||
- name: Update dotnet workloads
|
||||
run: |
|
||||
dotnet workload update
|
||||
|
||||
- name: Select the manifest
|
||||
run: |
|
||||
make manifestlink Flavor=Net
|
||||
|
||||
- name: Install NuGet dependencies (net)
|
||||
run: make nuget Flavor=Net
|
||||
|
||||
- name: Build keepass2android (net)
|
||||
run: |
|
||||
make dotnetbuild Flavor=Net
|
||||
make msbuild Flavor=Net
|
||||
|
||||
- name: Build APK (net)
|
||||
if: github.ref == 'refs/heads/master'
|
||||
env:
|
||||
DropboxAppKey: ${{ secrets.DROPBOX_APP_KEY }}
|
||||
DropboxAppSecret: ${{ secrets.DROPBOX_APP_SECRET }}
|
||||
DropboxAppFolderAppKey: ${{ secrets.DROPBOX_APP_FOLDER_APP_KEY }}
|
||||
DropboxAppFolderAppSecret: ${{ secrets.DROPBOX_APP_FOLDER_APP_SECRET }}
|
||||
run: |
|
||||
make apk Configuration=Release Flavor=Net
|
||||
make apk Flavor=Net
|
||||
|
||||
- name: Archive production artifacts (net)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: archive APK ('net' built on ${{ github.job }})
|
||||
name: signed APK ('net' built on ${{ github.job }})
|
||||
path: |
|
||||
src/keepass2android-app/bin/Release/net9.0-android/publish/*.apk
|
||||
|
||||
- name: Select the manifest
|
||||
run: |
|
||||
make manifestlink Flavor=NoNet
|
||||
src/keepass2android/bin/*/*-Signed.apk
|
||||
|
||||
- name: Install NuGet dependencies (nonet)
|
||||
run: make nuget Flavor=NoNet
|
||||
|
||||
- name: Build keepass2android (nonet)
|
||||
run: |
|
||||
make dotnetbuild Flavor=NoNet
|
||||
|
||||
make msbuild Flavor=NoNet
|
||||
- name: Test Autofill
|
||||
working-directory: ./src/Kp2aAutofillParser.Tests
|
||||
run: dotnet test
|
||||
@@ -363,7 +344,9 @@ jobs:
|
||||
- name: Archive production artifacts (nonet)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: archive APK ('nonet' built on ${{ github.job }})
|
||||
name: signed APK ('nonet' built on ${{ github.job }})
|
||||
path: |
|
||||
src/keepass2android-app/bin/Release/net9.0-android/publish/*.apk
|
||||
src/keepass2android/bin/*/*-Signed.apk
|
||||
|
||||
- name: Perform "make distclean"
|
||||
run: make distclean
|
||||
|
||||
146
.github/workflows/release.yml
vendored
146
.github/workflows/release.yml
vendored
@@ -1,146 +0,0 @@
|
||||
name: Create keepass2android release
|
||||
env:
|
||||
NAME: 'Release'
|
||||
|
||||
on:
|
||||
# the workflow is always triggered manually. This allows to test the apks
|
||||
# before publishing the release and not having a broken tag in the repo if that test fails.
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
|
||||
build-release:
|
||||
|
||||
runs-on: windows-2022
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
flavor: [Net, NoNet]
|
||||
target: [apk, apk_split]
|
||||
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Extract key store
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||
KeyStore: "${{ github.workspace }}/kp2a.keystore"
|
||||
|
||||
shell: bash
|
||||
run: |
|
||||
echo $KeyStore
|
||||
echo $KEYSTORE_BASE64 | base64 --decode > $KeyStore
|
||||
|
||||
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v3
|
||||
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.nuget/packages
|
||||
key: ${{ runner.os }}-nuget-${{ hashFiles('src/**/*.csproj', 'src/**/packages.config') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-nuget-
|
||||
|
||||
# Workaround an issue when building on windows-2022. Error was
|
||||
# D8 : OpenJDK 64-Bit Server VM warning : INFO: os::commit_memory(0x00000000ae400000, 330301440, 0) failed; error='The paging file is too small for this operation to complete' (DOS error/errno=1455) [D:\a\keepass2android\keepass2android\src\keepass2android\keepass2android-app.csproj]
|
||||
# C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Xamarin\Android\Xamarin.Android.D8.targets(81,5): error MSB6006: "java.exe" exited with code 1. [D:\a\keepass2android\keepass2android\src\keepass2android\keepass2android-app.csproj]
|
||||
- name: Configure Pagefile
|
||||
uses: al-cheb/configure-pagefile-action@a3b6ebd6b634da88790d9c58d4b37a7f4a7b8708 # v1.4
|
||||
with:
|
||||
minimum-size: 8GB
|
||||
|
||||
- name: Add msbuild/dotnet to PATH
|
||||
uses: microsoft/setup-msbuild@v2
|
||||
# If we want to also have nmake, use this instead
|
||||
#uses: ilammy/msvc-dev-cmd@v1
|
||||
|
||||
- name: Switch to JDK-17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Display java version
|
||||
run: java -version
|
||||
|
||||
- name: Build native dependencies
|
||||
shell: cmd
|
||||
run: |
|
||||
make native
|
||||
|
||||
- name: Build java dependencies
|
||||
shell: cmd
|
||||
run: |
|
||||
make java
|
||||
|
||||
- name: List apks
|
||||
run: find . -type f -name "*.apk"
|
||||
shell: bash
|
||||
|
||||
- name: Update dotnet workloads
|
||||
run: |
|
||||
dotnet workload update
|
||||
|
||||
- name: List apks
|
||||
run: find . -type f -name "*.apk"
|
||||
shell: bash
|
||||
|
||||
|
||||
- name: Select the manifest
|
||||
run: |
|
||||
make manifestlink Flavor=${{ matrix.flavor }}
|
||||
|
||||
- name: List apks
|
||||
run: find . -type f -name "*.apk"
|
||||
shell: bash
|
||||
|
||||
|
||||
- name: Install NuGet dependencies
|
||||
run: make nuget Flavor=${{ matrix.flavor }}
|
||||
|
||||
- name: List apks
|
||||
run: find . -type f -name "*.apk"
|
||||
shell: bash
|
||||
|
||||
- name: Build APK (net)
|
||||
env:
|
||||
KeyStore: "${{ github.workspace }}/kp2a.keystore"
|
||||
MyAndroidSigningStorePass: ${{ secrets.KEY_STORE_PASSWORD }}
|
||||
MyAndroidSigningKeyPass: ${{ secrets.KEY_PASSWORD }}
|
||||
DropboxAppKey: ${{ secrets.DROPBOX_APP_KEY }}
|
||||
DropboxAppSecret: ${{ secrets.DROPBOX_APP_SECRET }}
|
||||
DropboxAppFolderAppKey: ${{ secrets.DROPBOX_APP_FOLDER_APP_KEY }}
|
||||
DropboxAppFolderAppSecret: ${{ secrets.DROPBOX_APP_FOLDER_APP_SECRET }}
|
||||
|
||||
run: |
|
||||
make ${{ matrix.target }} Configuration=Release Flavor=${{ matrix.flavor }}
|
||||
|
||||
- name: List apks
|
||||
run: find . -type f -name "*.apk"
|
||||
shell: bash
|
||||
|
||||
- name: Archive production artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: keepass2android_${{ matrix.target }}_${{ matrix.flavor }}
|
||||
# the first line is for "apk" target, the second line is for "apk_split" target
|
||||
path: |
|
||||
src/keepass2android-app/bin/Release/net9.0-android/publish/*.apk
|
||||
src/keepass2android-app/bin/Release/net9.0-android/*/publish/*.apk
|
||||
|
||||
- name: List apks
|
||||
run: find . -type f -name "*.apk"
|
||||
shell: bash
|
||||
|
||||
- name: Upload APK to GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
draft: true
|
||||
files: |
|
||||
src/keepass2android-app/bin/Release/net9.0-android/publish/*.apk
|
||||
src/keepass2android-app/bin/Release/net9.0-android/*/publish/*.apk
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -64,7 +64,7 @@ Thumbs.db
|
||||
/src/java/android-filechooser/code/projectzip/project.zip
|
||||
/src/java/android-filechooser/code/unused.txt
|
||||
|
||||
/src/Kp2aBusinessLogic/Io/DropboxFileStorage.g.cs
|
||||
/src/Kp2aBusinessLogic/Io/DropboxFileStorageKeys.cs
|
||||
|
||||
/src/java/workspace/DriveTest
|
||||
|
||||
|
||||
89
Makefile
89
Makefile
@@ -4,10 +4,10 @@
|
||||
# This Makefile can be used on both unix-like (use make) & windows (with GNU make)
|
||||
#
|
||||
# append the Configuration variable to 'make' call with value to use in '/p:Configuration='
|
||||
# of dotnetbuild command.
|
||||
# of msbuild command.
|
||||
#
|
||||
# append the Flavor variable to 'make' call with value to use in '/p:Flavor='
|
||||
# of dotnetbuild command.
|
||||
# of msbuild command.
|
||||
#
|
||||
# Example:
|
||||
# make Configuration=Release Flavor=NoNet
|
||||
@@ -18,7 +18,7 @@
|
||||
# - native: build the native libs
|
||||
# - java: build the java libs
|
||||
# - nuget: restore NuGet packages
|
||||
# - dotnetbuild: build the project
|
||||
# - msbuild: build the project
|
||||
# - apk: same as all
|
||||
# - manifestlink: creates a symlink (to be used in building) to the AndroidManifest corresponding to the selected Flavor
|
||||
#
|
||||
@@ -27,7 +27,7 @@
|
||||
# - clean_native: clean native lib
|
||||
# - clean_java: call clean target of java libs
|
||||
# - clean_nuget: cleanup the 'nuget restore'
|
||||
# - clean_dotnet: call clean target of dotnetbuild
|
||||
# - clean_msbuild: call clean target of msbuild
|
||||
#
|
||||
#
|
||||
#
|
||||
@@ -60,23 +60,45 @@ $(info MAKESHELL: $(MAKESHELL))
|
||||
$(info SHELL: $(SHELL))
|
||||
$(info )
|
||||
|
||||
# On linux use xabuild, on Windows use MSBuild.exe, otherwise (macos?) use msbuild.
|
||||
ifeq ($(detected_OS),Linux)
|
||||
DOTNET_binary := dotnet
|
||||
DOTNET := $(shell $(WHICH) $(DOTNET_binary))
|
||||
MSBUILD_binary := xabuild
|
||||
MSBUILD := $(shell $(WHICH) $(MSBUILD_binary))
|
||||
else ifeq ($(detected_OS),Windows)
|
||||
DOTNET_binary := dotnet
|
||||
DOTNET := $(shell $(WHICH) $(DOTNET_binary) 2> nul)
|
||||
MSBUILD_binary := MSBuild.exe
|
||||
MSBUILD := $(shell $(WHICH) $(MSBUILD_binary) 2> nul)
|
||||
ifeq ($(MSBUILD),)
|
||||
# Additional heuristic to find MSBUILD_BINARY on Windows
|
||||
VSWHERE := "%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
VSWHERE_CHECK := $(shell @echo off & $(VSWHERE) 2> nul || echo VSWHERE_NOT_FOUND)
|
||||
ifneq ($(VSWHERE_CHECK),VSWHERE_NOT_FOUND)
|
||||
MSBUILD := $(shell @echo off & $(VSWHERE) -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe)
|
||||
VS_INSTALL_PATH := $(shell @echo off & $(VSWHERE) -property installationPath)
|
||||
endif
|
||||
endif
|
||||
else
|
||||
DOTNET_binary := dotnet
|
||||
DOTNET := $(shell $(WHICH) $(DOTNET_binary))
|
||||
MSBUILD_binary := msbuild
|
||||
MSBUILD := $(shell $(WHICH) $(MSBUILD_binary))
|
||||
endif
|
||||
|
||||
ifeq ($(DOTNET),)
|
||||
ifeq ($(MSBUILD),)
|
||||
$(info )
|
||||
$(info '$(DOTNET_binary)' binary could not be found. Check it is in your PATH.)
|
||||
$(info '$(MSBUILD_binary)' binary could not be found. Check it is in your PATH.)
|
||||
ifeq ($(detected_OS),Windows)
|
||||
ifneq ($(VSWHERE_CHECK),VSWHERE_NOT_FOUND)
|
||||
$(info )
|
||||
$(info You may retry after running in the command prompt:)
|
||||
$(info )
|
||||
$(info "$(VS_INSTALL_PATH)\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64)
|
||||
$(info )
|
||||
$(info If this doesn't work, install/find the location of vcvarsall.bat)
|
||||
$(info or install and add msbuild.exe to your PATH)
|
||||
$(info )
|
||||
endif
|
||||
endif
|
||||
$(error )
|
||||
endif
|
||||
$(info DOTNET: $(DOTNET))
|
||||
$(info MSBUILD: $(MSBUILD))
|
||||
$(info )
|
||||
|
||||
ifeq ($(ANDROID_SDK_ROOT),)
|
||||
@@ -95,7 +117,7 @@ endif
|
||||
$(info ANDROID_NDK_ROOT: $(ANDROID_NDK_ROOT))
|
||||
|
||||
ifneq ($(Configuration),)
|
||||
DOTNET_PARAM = -p:Configuration="$(Configuration)"
|
||||
MSBUILD_PARAM = -p:Configuration="$(Configuration)"
|
||||
else
|
||||
$(warning Configuration environment variable not set.)
|
||||
endif
|
||||
@@ -105,7 +127,7 @@ CREATE_MANIFEST_LINK :=
|
||||
|
||||
MANIFEST_FILE :=
|
||||
ifneq ($(Flavor),)
|
||||
DOTNET_PARAM += -p:Flavor="$(Flavor)"
|
||||
MSBUILD_PARAM += -p:Flavor="$(Flavor)"
|
||||
ifneq ($(Flavor),)
|
||||
ifeq ($(Flavor),Debug)
|
||||
MANIFEST_FILE := AndroidManifest_debug.xml
|
||||
@@ -130,7 +152,7 @@ else
|
||||
endif
|
||||
|
||||
ifneq ($(KeyStore),)
|
||||
DOTNET_PARAM += -p:AndroidKeyStore=True -p:AndroidSigningKeyStore="$(KeyStore)" -p:AndroidSigningStorePass=env:MyAndroidSigningStorePass -p:AndroidSigningKeyPass=env:MyAndroidSigningKeyPass -p:AndroidSigningKeyAlias="kp2a"
|
||||
MSBUILD_PARAM += -p:AndroidKeyStore=True -p:AndroidSigningKeyStore="$(KeyStore)" -p:AndroidSigningStorePass=env:MyAndroidSigningStorePass -p:AndroidSigningKeyPass=env:MyAndroidSigningKeyPass -p:AndroidSigningKeyAlias="kp2a"
|
||||
endif
|
||||
|
||||
ifeq ($(detected_OS),Windows)
|
||||
@@ -154,7 +176,7 @@ endif
|
||||
# Recursive wildcard: https://stackoverflow.com/a/18258352
|
||||
rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d))
|
||||
|
||||
$(info DOTNET_PARAM: $(DOTNET_PARAM))
|
||||
$(info MSBUILD_PARAM: $(MSBUILD_PARAM))
|
||||
$(info nuget path: $(shell $(WHICH) nuget))
|
||||
$(info )
|
||||
|
||||
@@ -232,7 +254,7 @@ OUTPUT_PluginQR = src/java/Keepass2AndroidPluginSDK2/app/build/outputs/aar/Keepa
|
||||
.PHONY: native $(NATIVE_COMPONENTS) clean_native $(NATIVE_CLEAN_TARGETS) \
|
||||
java $(JAVA_COMPONENTS) clean_java $(JAVA_CLEAN_TARGETS) \
|
||||
nuget clean_nuget \
|
||||
dotnetbuild clean_dotnet \
|
||||
msbuild clean_msbuild \
|
||||
apk all clean
|
||||
|
||||
all: apk
|
||||
@@ -281,7 +303,7 @@ ifeq ($(shell $(WHICH) nuget),)
|
||||
endif
|
||||
$(RMFILE) stamp.nuget_*
|
||||
nuget restore src/KeePass.sln
|
||||
$(DOTNET) restore src/KeePass.sln $(DOTNET_PARAM) -p:RestorePackagesConfig=true
|
||||
$(MSBUILD) src/KeePass.sln -t:restore $(MSBUILD_PARAM) -p:RestorePackagesConfig=true
|
||||
@echo "" > stamp.nuget_$(Flavor)
|
||||
|
||||
manifestlink:
|
||||
@@ -290,21 +312,20 @@ manifestlink:
|
||||
$(CREATE_MANIFEST_LINK)
|
||||
|
||||
#####
|
||||
src/Kp2aBusinessLogic/Io/DropboxFileStorageKeys.cs:
|
||||
ifeq ($(detected_OS),Windows)
|
||||
$(CP) src\Kp2aBusinessLogic\Io\DropboxFileStorageKeysDummy.cs src\Kp2aBusinessLogic\Io\DropboxFileStorageKeys.cs
|
||||
else
|
||||
$(CP) src/Kp2aBusinessLogic/Io/DropboxFileStorageKeysDummy.cs $@
|
||||
endif
|
||||
|
||||
dotnetbuild: manifestlink native java nuget
|
||||
$(DOTNET) build src/KeePass.sln -target:keepass2android-app -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -p:BuildProjectReferences=true $(DOTNET_PARAM) -p:Platform="Any CPU" -m
|
||||
msbuild: manifestlink native java nuget src/Kp2aBusinessLogic/Io/DropboxFileStorageKeys.cs
|
||||
$(MSBUILD) src/KeePass.sln -target:keepass2android-app -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -p:BuildProjectReferences=true $(MSBUILD_PARAM) -p:Platform="Any CPU" -m
|
||||
|
||||
apk: manifestlink native java nuget
|
||||
$(DOTNET) publish src/keepass2android-app/keepass2android-app.csproj -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -t:SignAndroidPackage $(DOTNET_PARAM) -p:Platform=AnyCPU -m
|
||||
apk: msbuild
|
||||
$(MSBUILD) src/keepass2android-app/keepass2android-app.csproj -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -t:SignAndroidPackage $(MSBUILD_PARAM) -p:Platform=AnyCPU -m
|
||||
|
||||
apk_split: manifestlink native java nuget
|
||||
$(DOTNET) publish src/keepass2android-app/keepass2android-app.csproj -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -t:SignAndroidPackage $(DOTNET_PARAM) -p:Platform=AnyCPU -m -p:RuntimeIdentifier=android-arm
|
||||
$(DOTNET) publish src/keepass2android-app/keepass2android-app.csproj -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -t:SignAndroidPackage $(DOTNET_PARAM) -p:Platform=AnyCPU -m -p:RuntimeIdentifier=android-arm64
|
||||
$(DOTNET) publish src/keepass2android-app/keepass2android-app.csproj -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -t:SignAndroidPackage $(DOTNET_PARAM) -p:Platform=AnyCPU -m -p:RuntimeIdentifier=android-x86
|
||||
$(DOTNET) publish src/keepass2android-app/keepass2android-app.csproj -p:AndroidSdkDirectory="$(ANDROID_SDK_ROOT)" -t:SignAndroidPackage $(DOTNET_PARAM) -p:Platform=AnyCPU -m -p:RuntimeIdentifier=android-x64
|
||||
src/build-scripts/rename-output-apks.sh src/keepass2android-app/bin/Release/net8.0-android/
|
||||
|
||||
build_all: dotnetbuild
|
||||
build_all: msbuild
|
||||
|
||||
##### Cleanup targets
|
||||
|
||||
@@ -348,10 +369,10 @@ else
|
||||
endif
|
||||
$(RMFILE) stamp.nuget_*
|
||||
|
||||
clean_dotnet:
|
||||
$(DOTNET) clean src/KeePass.sln $(DOTNET_PARAM)
|
||||
clean_msbuild:
|
||||
$(MSBUILD) src/KeePass.sln -target:clean $(MSBUILD_PARAM)
|
||||
|
||||
clean: clean_native clean_java clean_nuget clean_dotnet
|
||||
clean: clean_native clean_java clean_nuget clean_msbuild
|
||||
|
||||
distclean: clean
|
||||
ifneq ("$(wildcard ./allow_git_clean)","")
|
||||
|
||||
@@ -11,10 +11,10 @@ Regular stable releases of Keepass2Android are available on [Google Play](https:
|
||||
Beta-releases can be obtained by opting in to the [Beta testing channel](https://play.google.com/apps/testing/keepass2android.keepass2android) or [Beta testing channel for Keepass2Android Offline](https://play.google.com/apps/testing/keepass2android.keepass2android_nonet).
|
||||
|
||||
# How can I contribute?
|
||||
* Help to translate Keepass2Android into your language or improve translations at [our Crowdin page](https://crowdin.net/project/keepass2android)
|
||||
* Help to translate Keepass2Android into your language or improve translations at [our Crowdin page](http://crowdin.net/project/keepass2android)
|
||||
* Add features by [creating a plugin](How-to-create-a-plug-in_.md) or creating a pull request. You might want to contact me before you start working so I can coordinate efforts.
|
||||
* [Become a GitHub sponsor to boost 🚀 development](https://github.com/sponsors/PhilippC)
|
||||
* [Make a donation](https://philipp.crocoll.net/donate.php)
|
||||
* [Make a donation](http://philipp.crocoll.net/donate.php)
|
||||
|
||||
# How do I learn more?
|
||||
Please see the [wiki](https://github.com/PhilippC/keepass2android/wiki/Documentation) for further information.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2025 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -29,226 +29,197 @@ using KeePassLib.Utility;
|
||||
|
||||
namespace KeePassLib.Cryptography
|
||||
{
|
||||
/// <summary>
|
||||
/// Algorithms supported by <c>CryptoRandomStream</c>.
|
||||
/// </summary>
|
||||
public enum CrsAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Not supported.
|
||||
/// </summary>
|
||||
Null = 0,
|
||||
/// <summary>
|
||||
/// Algorithms supported by <c>CryptoRandomStream</c>.
|
||||
/// </summary>
|
||||
public enum CrsAlgorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// Not supported.
|
||||
/// </summary>
|
||||
Null = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A variant of the ArcFour algorithm (RC4 incompatible).
|
||||
/// Insecure; for backward compatibility only.
|
||||
/// </summary>
|
||||
ArcFourVariant = 1,
|
||||
/// <summary>
|
||||
/// A variant of the ARCFour algorithm (RC4 incompatible).
|
||||
/// </summary>
|
||||
/// </summary>
|
||||
ArcFourVariant = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Salsa20 stream cipher algorithm.
|
||||
/// </summary>
|
||||
Salsa20 = 2,
|
||||
/// <summary>
|
||||
/// Salsa20 stream cipher algorithm.
|
||||
/// </summary>
|
||||
Salsa20 = 2,
|
||||
|
||||
/// <summary>
|
||||
/// ChaCha20 stream cipher algorithm.
|
||||
/// </summary>
|
||||
ChaCha20 = 3,
|
||||
/// <summary>
|
||||
/// ChaCha20 stream cipher algorithm.
|
||||
/// </summary>
|
||||
ChaCha20 = 3,
|
||||
|
||||
Count = 4
|
||||
}
|
||||
Count = 4
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A random stream class. The class is initialized using random
|
||||
/// bytes provided by the caller. The produced stream has random
|
||||
/// properties, but for the same seed always the same stream
|
||||
/// is produced, i.e. this class can be used as stream cipher.
|
||||
/// </summary>
|
||||
public sealed class CryptoRandomStream : IDisposable
|
||||
{
|
||||
private readonly CrsAlgorithm m_alg;
|
||||
private bool m_bDisposed = false;
|
||||
/// <summary>
|
||||
/// A random stream class. The class is initialized using random
|
||||
/// bytes provided by the caller. The produced stream has random
|
||||
/// properties, but for the same seed always the same stream
|
||||
/// is produced, i.e. this class can be used as stream cipher.
|
||||
/// </summary>
|
||||
public sealed class CryptoRandomStream : IDisposable
|
||||
{
|
||||
private readonly CrsAlgorithm m_crsAlgorithm;
|
||||
|
||||
private readonly byte[] m_pbKey = null;
|
||||
private readonly byte[] m_pbIV = null;
|
||||
private byte[] m_pbState = null;
|
||||
private byte m_i = 0;
|
||||
private byte m_j = 0;
|
||||
|
||||
private readonly ChaCha20Cipher m_chacha20 = null;
|
||||
private readonly Salsa20Cipher m_salsa20 = null;
|
||||
private Salsa20Cipher m_salsa20 = null;
|
||||
private ChaCha20Cipher m_chacha20 = null;
|
||||
|
||||
private readonly byte[] m_pbState = null;
|
||||
private byte m_i = 0;
|
||||
private byte m_j = 0;
|
||||
/// <summary>
|
||||
/// Construct a new cryptographically secure random stream object.
|
||||
/// </summary>
|
||||
/// <param name="genAlgorithm">Algorithm to use.</param>
|
||||
/// <param name="pbKey">Initialization key. Must not be <c>null</c> and
|
||||
/// must contain at least 1 byte.</param>
|
||||
public CryptoRandomStream(CrsAlgorithm a, byte[] pbKey)
|
||||
{
|
||||
if(pbKey == null) { Debug.Assert(false); throw new ArgumentNullException("pbKey"); }
|
||||
/// <exception cref="System.ArgumentNullException">Thrown if the
|
||||
int cbKey = pbKey.Length;
|
||||
if(cbKey <= 0)
|
||||
{
|
||||
Debug.Assert(false); // Need at least one byte
|
||||
throw new ArgumentOutOfRangeException("pbKey");
|
||||
}
|
||||
/// <paramref name="pbKey" /> parameter is <c>null</c>.</exception>
|
||||
m_crsAlgorithm = a;
|
||||
/// <exception cref="System.ArgumentException">Thrown if the
|
||||
if(a == CrsAlgorithm.ChaCha20)
|
||||
{
|
||||
byte[] pbKey32 = new byte[32];
|
||||
byte[] pbIV12 = new byte[12];
|
||||
/// <paramref name="pbKey" /> parameter contains no bytes or the
|
||||
using(SHA512Managed h = new SHA512Managed())
|
||||
{
|
||||
byte[] pbHash = h.ComputeHash(pbKey);
|
||||
Array.Copy(pbHash, pbKey32, 32);
|
||||
Array.Copy(pbHash, 32, pbIV12, 0, 12);
|
||||
MemUtil.ZeroByteArray(pbHash);
|
||||
}
|
||||
/// algorithm is unknown.</exception>
|
||||
m_chacha20 = new ChaCha20Cipher(pbKey32, pbIV12, true);
|
||||
}
|
||||
else if(a == CrsAlgorithm.Salsa20)
|
||||
{
|
||||
byte[] pbKey32 = CryptoUtil.HashSha256(pbKey);
|
||||
byte[] pbIV8 = new byte[8] { 0xE8, 0x30, 0x09, 0x4B,
|
||||
0x97, 0x20, 0x5D, 0x2A }; // Unique constant
|
||||
|
||||
/// <summary>
|
||||
/// Construct a new cryptographically secure random stream object.
|
||||
/// </summary>
|
||||
/// <param name="a">Algorithm to use.</param>
|
||||
/// <param name="pbKey">Initialization key. Must not be <c>null</c>
|
||||
/// and must contain at least 1 byte.</param>
|
||||
public CryptoRandomStream(CrsAlgorithm a, byte[] pbKey)
|
||||
{
|
||||
if (pbKey == null) { Debug.Assert(false); throw new ArgumentNullException("pbKey"); }
|
||||
m_salsa20 = new Salsa20Cipher(pbKey32, pbIV8);
|
||||
}
|
||||
else if(a == CrsAlgorithm.ArcFourVariant)
|
||||
{
|
||||
// Fill the state linearly
|
||||
m_pbState = new byte[256];
|
||||
for(int w = 0; w < 256; ++w) m_pbState[w] = (byte)w;
|
||||
|
||||
int cbKey = pbKey.Length;
|
||||
if (cbKey <= 0)
|
||||
{
|
||||
Debug.Assert(false); // Need at least one byte
|
||||
throw new ArgumentOutOfRangeException("pbKey");
|
||||
}
|
||||
unchecked
|
||||
{
|
||||
byte j = 0, t;
|
||||
int inxKey = 0;
|
||||
for(int w = 0; w < 256; ++w) // Key setup
|
||||
{
|
||||
j += (byte)(m_pbState[w] + pbKey[inxKey]);
|
||||
|
||||
m_alg = a;
|
||||
t = m_pbState[0]; // Swap entries
|
||||
m_pbState[0] = m_pbState[j];
|
||||
m_pbState[j] = t;
|
||||
|
||||
if (a == CrsAlgorithm.ChaCha20)
|
||||
{
|
||||
m_pbKey = new byte[32];
|
||||
m_pbIV = new byte[12];
|
||||
++inxKey;
|
||||
if(inxKey >= cbKey) inxKey = 0;
|
||||
}
|
||||
}
|
||||
|
||||
using (SHA512Managed h = new SHA512Managed())
|
||||
{
|
||||
byte[] pbHash = h.ComputeHash(pbKey);
|
||||
Array.Copy(pbHash, m_pbKey, 32);
|
||||
Array.Copy(pbHash, 32, m_pbIV, 0, 12);
|
||||
MemUtil.ZeroByteArray(pbHash);
|
||||
}
|
||||
GetRandomBytes(512); // Increases security, see cryptanalysis
|
||||
}
|
||||
else // Unknown algorithm
|
||||
{
|
||||
Debug.Assert(false);
|
||||
throw new ArgumentOutOfRangeException("a");
|
||||
}
|
||||
}
|
||||
|
||||
m_chacha20 = new ChaCha20Cipher(m_pbKey, m_pbIV, true);
|
||||
}
|
||||
else if (a == CrsAlgorithm.Salsa20)
|
||||
{
|
||||
m_pbKey = CryptoUtil.HashSha256(pbKey);
|
||||
m_pbIV = new byte[8] { 0xE8, 0x30, 0x09, 0x4B,
|
||||
0x97, 0x20, 0x5D, 0x2A }; // Unique constant
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
m_salsa20 = new Salsa20Cipher(m_pbKey, m_pbIV);
|
||||
}
|
||||
else if (a == CrsAlgorithm.ArcFourVariant)
|
||||
{
|
||||
// Fill the state linearly
|
||||
m_pbState = new byte[256];
|
||||
for (int w = 0; w < 256; ++w) m_pbState[w] = (byte)w;
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if(disposing)
|
||||
{
|
||||
if(m_crsAlgorithm == CrsAlgorithm.ChaCha20)
|
||||
m_chacha20.Dispose();
|
||||
else if(m_crsAlgorithm == CrsAlgorithm.Salsa20)
|
||||
m_salsa20.Dispose();
|
||||
else if(m_crsAlgorithm == CrsAlgorithm.ArcFourVariant)
|
||||
{
|
||||
MemUtil.ZeroByteArray(m_pbState);
|
||||
m_i = 0;
|
||||
m_j = 0;
|
||||
}
|
||||
else { Debug.Assert(false); }
|
||||
}
|
||||
}
|
||||
|
||||
unchecked
|
||||
{
|
||||
byte j = 0, t;
|
||||
int inxKey = 0;
|
||||
for (int w = 0; w < 256; ++w) // Key setup
|
||||
{
|
||||
j += (byte)(m_pbState[w] + pbKey[inxKey]);
|
||||
/// <summary>
|
||||
/// Get <paramref name="uRequestedCount" /> random bytes.
|
||||
/// </summary>
|
||||
/// <param name="uRequestedCount">Number of random bytes to retrieve.</param>
|
||||
/// <returns>Returns <paramref name="uRequestedCount" /> random bytes.</returns>
|
||||
public byte[] GetRandomBytes(uint uRequestedCount)
|
||||
{
|
||||
if(uRequestedCount == 0) return MemUtil.EmptyByteArray;
|
||||
|
||||
t = m_pbState[0]; // Swap entries
|
||||
m_pbState[0] = m_pbState[j];
|
||||
m_pbState[j] = t;
|
||||
if(uRequestedCount > (uint)int.MaxValue)
|
||||
throw new ArgumentOutOfRangeException("uRequestedCount");
|
||||
int cb = (int)uRequestedCount;
|
||||
|
||||
++inxKey;
|
||||
if (inxKey >= cbKey) inxKey = 0;
|
||||
}
|
||||
}
|
||||
byte[] pbRet = new byte[cb];
|
||||
|
||||
GetRandomBytes(512); // Increases security, see cryptanalysis
|
||||
}
|
||||
else // Unknown algorithm
|
||||
{
|
||||
Debug.Assert(false);
|
||||
throw new ArgumentOutOfRangeException("a");
|
||||
}
|
||||
}
|
||||
if(m_crsAlgorithm == CrsAlgorithm.ChaCha20)
|
||||
m_chacha20.Encrypt(pbRet, 0, cb);
|
||||
else if(m_crsAlgorithm == CrsAlgorithm.Salsa20)
|
||||
m_salsa20.Encrypt(pbRet, 0, cb);
|
||||
else if(m_crsAlgorithm == CrsAlgorithm.ArcFourVariant)
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
for(int w = 0; w < cb; ++w)
|
||||
{
|
||||
++m_i;
|
||||
m_j += m_pbState[m_i];
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
byte t = m_pbState[m_i]; // Swap entries
|
||||
m_pbState[m_i] = m_pbState[m_j];
|
||||
m_pbState[m_j] = t;
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
if (m_alg == CrsAlgorithm.ChaCha20)
|
||||
m_chacha20.Dispose();
|
||||
else if (m_alg == CrsAlgorithm.Salsa20)
|
||||
m_salsa20.Dispose();
|
||||
else if (m_alg == CrsAlgorithm.ArcFourVariant)
|
||||
{
|
||||
MemUtil.ZeroByteArray(m_pbState);
|
||||
m_i = 0;
|
||||
m_j = 0;
|
||||
}
|
||||
else { Debug.Assert(false); }
|
||||
t = (byte)(m_pbState[m_i] + m_pbState[m_j]);
|
||||
pbRet[w] = m_pbState[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
else { Debug.Assert(false); }
|
||||
|
||||
if (m_pbKey != null) MemUtil.ZeroByteArray(m_pbKey);
|
||||
if (m_pbIV != null) MemUtil.ZeroByteArray(m_pbIV);
|
||||
return pbRet;
|
||||
}
|
||||
|
||||
m_bDisposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get <paramref name="uRequestedCount" /> random bytes.
|
||||
/// </summary>
|
||||
/// <param name="uRequestedCount">Number of random bytes to retrieve.</param>
|
||||
/// <returns>Returns <paramref name="uRequestedCount" /> random bytes.</returns>
|
||||
public byte[] GetRandomBytes(uint uRequestedCount)
|
||||
{
|
||||
if (m_bDisposed) throw new ObjectDisposedException(null);
|
||||
|
||||
if (uRequestedCount == 0) return MemUtil.EmptyByteArray;
|
||||
if (uRequestedCount > (uint)int.MaxValue)
|
||||
throw new ArgumentOutOfRangeException("uRequestedCount");
|
||||
int cb = (int)uRequestedCount;
|
||||
|
||||
byte[] pbRet = new byte[cb];
|
||||
|
||||
if (m_alg == CrsAlgorithm.ChaCha20)
|
||||
m_chacha20.Encrypt(pbRet, 0, cb);
|
||||
else if (m_alg == CrsAlgorithm.Salsa20)
|
||||
m_salsa20.Encrypt(pbRet, 0, cb);
|
||||
else if (m_alg == CrsAlgorithm.ArcFourVariant)
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
for (int w = 0; w < cb; ++w)
|
||||
{
|
||||
++m_i;
|
||||
m_j += m_pbState[m_i];
|
||||
|
||||
byte t = m_pbState[m_i]; // Swap entries
|
||||
m_pbState[m_i] = m_pbState[m_j];
|
||||
m_pbState[m_j] = t;
|
||||
|
||||
t = (byte)(m_pbState[m_i] + m_pbState[m_j]);
|
||||
pbRet[w] = m_pbState[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
else { Debug.Assert(false); }
|
||||
|
||||
return pbRet;
|
||||
}
|
||||
|
||||
public ulong GetRandomUInt64()
|
||||
{
|
||||
byte[] pb = GetRandomBytes(8);
|
||||
return MemUtil.BytesToUInt64(pb);
|
||||
}
|
||||
|
||||
internal ulong GetRandomUInt64(ulong uMaxExcl)
|
||||
{
|
||||
if (uMaxExcl == 0) { Debug.Assert(false); throw new ArgumentOutOfRangeException("uMaxExcl"); }
|
||||
|
||||
ulong uGen, uRem;
|
||||
do
|
||||
{
|
||||
uGen = GetRandomUInt64();
|
||||
uRem = uGen % uMaxExcl;
|
||||
}
|
||||
while ((uGen - uRem) > (ulong.MaxValue - (uMaxExcl - 1UL)));
|
||||
// This ensures that the last number of the block (i.e.
|
||||
// (uGen - uRem) + (uMaxExcl - 1)) is generatable;
|
||||
// for signed longs, overflow to negative number:
|
||||
// while((uGen - uRem) + (uMaxExcl - 1) < 0);
|
||||
|
||||
return uRem;
|
||||
}
|
||||
public ulong GetRandomUInt64()
|
||||
{
|
||||
byte[] pb = GetRandomBytes(8);
|
||||
return MemUtil.BytesToUInt64(pb);
|
||||
}
|
||||
|
||||
#if CRSBENCHMARK
|
||||
public static string Benchmark()
|
||||
@@ -266,21 +237,22 @@ namespace KeePassLib.Cryptography
|
||||
return str;
|
||||
}
|
||||
|
||||
private static int BenchTime(CrsAlgorithm a, int nRounds, int cbData)
|
||||
private static int BenchTime(CrsAlgorithm cra, int nRounds, int nDataSize)
|
||||
{
|
||||
byte[] pbKey = new byte[4] { 0x00, 0x01, 0x02, 0x03 };
|
||||
|
||||
int tStart = Environment.TickCount;
|
||||
int nStart = Environment.TickCount;
|
||||
for(int i = 0; i < nRounds; ++i)
|
||||
{
|
||||
using(CryptoRandomStream crs = new CryptoRandomStream(a, pbKey))
|
||||
using(CryptoRandomStream c = new CryptoRandomStream(cra, pbKey))
|
||||
{
|
||||
crs.GetRandomBytes((uint)cbData);
|
||||
c.GetRandomBytes((uint)nDataSize);
|
||||
}
|
||||
}
|
||||
int nEnd = Environment.TickCount;
|
||||
|
||||
return (Environment.TickCount - tStart);
|
||||
return (nEnd - nStart);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
|
||||
using KeePassLib.Security;
|
||||
using KeePassLib.Utility;
|
||||
|
||||
namespace KeePassLib.Cryptography.PasswordGenerator
|
||||
{
|
||||
internal static class CharSetBasedGenerator
|
||||
{
|
||||
internal static PwgError Generate(out ProtectedString psOut,
|
||||
PwProfile pwProfile, CryptoRandomStream crsRandomSource)
|
||||
{
|
||||
psOut = ProtectedString.Empty;
|
||||
if(pwProfile.Length == 0) return PwgError.Success;
|
||||
|
||||
PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString());
|
||||
char[] vGenerated = new char[pwProfile.Length];
|
||||
|
||||
PwGenerator.PrepareCharSet(pcs, pwProfile);
|
||||
|
||||
for(int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex)
|
||||
{
|
||||
char ch = PwGenerator.GenerateCharacter(pwProfile, pcs,
|
||||
crsRandomSource);
|
||||
|
||||
if(ch == char.MinValue)
|
||||
{
|
||||
MemUtil.ZeroArray<char>(vGenerated);
|
||||
return PwgError.TooFewCharacters;
|
||||
}
|
||||
|
||||
vGenerated[nIndex] = ch;
|
||||
}
|
||||
|
||||
byte[] pbUtf8 = StrUtil.Utf8.GetBytes(vGenerated);
|
||||
psOut = new ProtectedString(true, pbUtf8);
|
||||
MemUtil.ZeroByteArray(pbUtf8);
|
||||
MemUtil.ZeroArray<char>(vGenerated);
|
||||
|
||||
return PwgError.Success;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
|
||||
using KeePassLib.Security;
|
||||
using KeePassLib.Utility;
|
||||
|
||||
namespace KeePassLib.Cryptography.PasswordGenerator
|
||||
{
|
||||
internal static class PatternBasedGenerator
|
||||
{
|
||||
internal static PwgError Generate(out ProtectedString psOut,
|
||||
PwProfile pwProfile, CryptoRandomStream crsRandomSource)
|
||||
{
|
||||
psOut = ProtectedString.Empty;
|
||||
LinkedList<char> vGenerated = new LinkedList<char>();
|
||||
PwCharSet pcsCurrent = new PwCharSet();
|
||||
PwCharSet pcsCustom = new PwCharSet();
|
||||
PwCharSet pcsUsed = new PwCharSet();
|
||||
bool bInCharSetDef = false;
|
||||
|
||||
string strPattern = ExpandPattern(pwProfile.Pattern);
|
||||
if(strPattern.Length == 0) return PwgError.Success;
|
||||
|
||||
CharStream csStream = new CharStream(strPattern);
|
||||
char ch = csStream.ReadChar();
|
||||
|
||||
while(ch != char.MinValue)
|
||||
{
|
||||
pcsCurrent.Clear();
|
||||
|
||||
bool bGenerateChar = false;
|
||||
|
||||
if(ch == '\\')
|
||||
{
|
||||
ch = csStream.ReadChar();
|
||||
if(ch == char.MinValue) // Backslash at the end
|
||||
{
|
||||
vGenerated.AddLast('\\');
|
||||
break;
|
||||
}
|
||||
|
||||
if(bInCharSetDef) pcsCustom.Add(ch);
|
||||
else
|
||||
{
|
||||
vGenerated.AddLast(ch);
|
||||
pcsUsed.Add(ch);
|
||||
}
|
||||
}
|
||||
else if(ch == '[')
|
||||
{
|
||||
pcsCustom.Clear();
|
||||
bInCharSetDef = true;
|
||||
}
|
||||
else if(ch == ']')
|
||||
{
|
||||
pcsCurrent.Add(pcsCustom.ToString());
|
||||
|
||||
bInCharSetDef = false;
|
||||
bGenerateChar = true;
|
||||
}
|
||||
else if(bInCharSetDef)
|
||||
{
|
||||
if(pcsCustom.AddCharSet(ch) == false)
|
||||
pcsCustom.Add(ch);
|
||||
}
|
||||
else if(pcsCurrent.AddCharSet(ch) == false)
|
||||
{
|
||||
vGenerated.AddLast(ch);
|
||||
pcsUsed.Add(ch);
|
||||
}
|
||||
else bGenerateChar = true;
|
||||
|
||||
if(bGenerateChar)
|
||||
{
|
||||
PwGenerator.PrepareCharSet(pcsCurrent, pwProfile);
|
||||
|
||||
if(pwProfile.NoRepeatingCharacters)
|
||||
pcsCurrent.Remove(pcsUsed.ToString());
|
||||
|
||||
char chGen = PwGenerator.GenerateCharacter(pwProfile,
|
||||
pcsCurrent, crsRandomSource);
|
||||
|
||||
if(chGen == char.MinValue) return PwgError.TooFewCharacters;
|
||||
|
||||
vGenerated.AddLast(chGen);
|
||||
pcsUsed.Add(chGen);
|
||||
}
|
||||
|
||||
ch = csStream.ReadChar();
|
||||
}
|
||||
|
||||
if(vGenerated.Count == 0) return PwgError.Success;
|
||||
|
||||
char[] vArray = new char[vGenerated.Count];
|
||||
vGenerated.CopyTo(vArray, 0);
|
||||
|
||||
if(pwProfile.PatternPermutePassword)
|
||||
PwGenerator.ShufflePassword(vArray, crsRandomSource);
|
||||
|
||||
byte[] pbUtf8 = StrUtil.Utf8.GetBytes(vArray);
|
||||
psOut = new ProtectedString(true, pbUtf8);
|
||||
MemUtil.ZeroByteArray(pbUtf8);
|
||||
MemUtil.ZeroArray<char>(vArray);
|
||||
vGenerated.Clear();
|
||||
|
||||
return PwgError.Success;
|
||||
}
|
||||
|
||||
private static string ExpandPattern(string strPattern)
|
||||
{
|
||||
Debug.Assert(strPattern != null); if(strPattern == null) return string.Empty;
|
||||
string str = strPattern;
|
||||
|
||||
while(true)
|
||||
{
|
||||
int nOpen = FindFirstUnescapedChar(str, '{');
|
||||
int nClose = FindFirstUnescapedChar(str, '}');
|
||||
|
||||
if((nOpen >= 0) && (nOpen < nClose))
|
||||
{
|
||||
string strCount = str.Substring(nOpen + 1, nClose - nOpen - 1);
|
||||
str = str.Remove(nOpen, nClose - nOpen + 1);
|
||||
|
||||
uint uRepeat;
|
||||
if(StrUtil.TryParseUInt(strCount, out uRepeat) && (nOpen >= 1))
|
||||
{
|
||||
if(uRepeat == 0)
|
||||
str = str.Remove(nOpen - 1, 1);
|
||||
else
|
||||
str = str.Insert(nOpen, new string(str[nOpen - 1], (int)uRepeat - 1));
|
||||
}
|
||||
}
|
||||
else break;
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
private static int FindFirstUnescapedChar(string str, char ch)
|
||||
{
|
||||
for(int i = 0; i < str.Length; ++i)
|
||||
{
|
||||
char chCur = str[i];
|
||||
|
||||
if(chCur == '\\') ++i; // Next is escaped, skip it
|
||||
else if(chCur == ch) return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2025 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -19,311 +19,333 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
using KeePassLib.Utility;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace KeePassLib.Cryptography.PasswordGenerator
|
||||
{
|
||||
public sealed class PwCharSet : IEquatable<PwCharSet>
|
||||
{
|
||||
public static readonly string UpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
public static readonly string LowerCase = "abcdefghijklmnopqrstuvwxyz";
|
||||
public static readonly string Digits = "0123456789";
|
||||
public sealed class PwCharSet
|
||||
{
|
||||
public const string UpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
public const string LowerCase = "abcdefghijklmnopqrstuvwxyz";
|
||||
public const string Digits = "0123456789";
|
||||
|
||||
public static readonly string UpperConsonants = "BCDFGHJKLMNPQRSTVWXYZ";
|
||||
public static readonly string LowerConsonants = "bcdfghjklmnpqrstvwxyz";
|
||||
public static readonly string UpperVowels = "AEIOU";
|
||||
public static readonly string LowerVowels = "aeiou";
|
||||
public const string UpperConsonants = "BCDFGHJKLMNPQRSTVWXYZ";
|
||||
public const string LowerConsonants = "bcdfghjklmnpqrstvwxyz";
|
||||
public const string UpperVowels = "AEIOU";
|
||||
public const string LowerVowels = "aeiou";
|
||||
|
||||
public static readonly string Punctuation = ",.;:";
|
||||
public static readonly string Brackets = @"[]{}()<>";
|
||||
public const string Punctuation = @",.;:";
|
||||
public const string Brackets = @"[]{}()<>";
|
||||
|
||||
public static readonly string Special = "!\"#$%&'*+,./:;=?@\\^`|~";
|
||||
public static readonly string PrintableAsciiSpecial = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
|
||||
public const string PrintableAsciiSpecial = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
|
||||
|
||||
public static readonly string UpperHex = "0123456789ABCDEF";
|
||||
public static readonly string LowerHex = "0123456789abcdef";
|
||||
public const string UpperHex = "0123456789ABCDEF";
|
||||
public const string LowerHex = "0123456789abcdef";
|
||||
|
||||
public static readonly string LookAlike = "O0Il1|";
|
||||
public const string Invalid = "\t\r\n";
|
||||
public const string LookAlike = @"O0l1I|";
|
||||
|
||||
/// <summary>
|
||||
/// Latin-1 Supplement except U+00A0 (NBSP) and U+00AD (SHY).
|
||||
/// </summary>
|
||||
public static readonly string Latin1S =
|
||||
"\u00A1\u00A2\u00A3\u00A4\u00A5\u00A6\u00A7" +
|
||||
"\u00A8\u00A9\u00AA\u00AB\u00AC\u00AE\u00AF" +
|
||||
"\u00B0\u00B1\u00B2\u00B3\u00B4\u00B5\u00B6\u00B7" +
|
||||
"\u00B8\u00B9\u00BA\u00BB\u00BC\u00BD\u00BE\u00BF" +
|
||||
"\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C6\u00C7" +
|
||||
"\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF" +
|
||||
"\u00D0\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D7" +
|
||||
"\u00D8\u00D9\u00DA\u00DB\u00DC\u00DD\u00DE\u00DF" +
|
||||
"\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5\u00E6\u00E7" +
|
||||
"\u00E8\u00E9\u00EA\u00EB\u00EC\u00ED\u00EE\u00EF" +
|
||||
"\u00F0\u00F1\u00F2\u00F3\u00F4\u00F5\u00F6\u00F7" +
|
||||
"\u00F8\u00F9\u00FA\u00FB\u00FC\u00FD\u00FE\u00FF";
|
||||
internal const string MenuAccels = PwCharSet.LowerCase + PwCharSet.Digits;
|
||||
|
||||
// internal static readonly string MenuAccels = PwCharSet.LowerCase + PwCharSet.Digits;
|
||||
private const int CharTabSize = (0x10000 / 8);
|
||||
|
||||
[Obsolete]
|
||||
public static string SpecialChars { get { return PwCharSet.Special; } }
|
||||
[Obsolete]
|
||||
public static string HighAnsiChars { get { return PwCharSet.Latin1S; } }
|
||||
private List<char> m_vChars = new List<char>();
|
||||
private byte[] m_vTab = new byte[CharTabSize];
|
||||
|
||||
private readonly List<char> m_lChars = new List<char>();
|
||||
private readonly byte[] m_vTab = new byte[0x10000 / 8];
|
||||
private static string m_strHighAnsi = null;
|
||||
public static string HighAnsiChars
|
||||
{
|
||||
get
|
||||
{
|
||||
if(m_strHighAnsi == null) { new PwCharSet(); } // Create string
|
||||
Debug.Assert(m_strHighAnsi != null);
|
||||
return m_strHighAnsi;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new, empty character set.
|
||||
/// </summary>
|
||||
public PwCharSet()
|
||||
{
|
||||
Debug.Assert(PwCharSet.Latin1S.Length == (16 * 6 - 2));
|
||||
}
|
||||
private static string m_strSpecial = null;
|
||||
public static string SpecialChars
|
||||
{
|
||||
get
|
||||
{
|
||||
if(m_strSpecial == null) { new PwCharSet(); } // Create string
|
||||
Debug.Assert(m_strSpecial != null);
|
||||
return m_strSpecial;
|
||||
}
|
||||
}
|
||||
|
||||
public PwCharSet(string strCharSet)
|
||||
{
|
||||
Add(strCharSet);
|
||||
}
|
||||
/// <summary>
|
||||
/// Create a new, empty character set collection object.
|
||||
/// </summary>
|
||||
public PwCharSet()
|
||||
{
|
||||
Initialize(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Number of characters in this set.
|
||||
/// </summary>
|
||||
public uint Size
|
||||
{
|
||||
get { return (uint)m_lChars.Count; }
|
||||
}
|
||||
public PwCharSet(string strCharSet)
|
||||
{
|
||||
Initialize(true);
|
||||
Add(strCharSet);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a character of the set using an index.
|
||||
/// </summary>
|
||||
/// <param name="uPos">Index of the character to get.</param>
|
||||
/// <returns>Character at the specified position. If the index is invalid,
|
||||
/// an <c>ArgumentOutOfRangeException</c> is thrown.</returns>
|
||||
public char this[uint uPos]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (uPos >= (uint)m_lChars.Count)
|
||||
throw new ArgumentOutOfRangeException("uPos");
|
||||
private PwCharSet(bool bFullInitialize)
|
||||
{
|
||||
Initialize(bFullInitialize);
|
||||
}
|
||||
|
||||
return m_lChars[(int)uPos];
|
||||
}
|
||||
}
|
||||
private void Initialize(bool bFullInitialize)
|
||||
{
|
||||
Clear();
|
||||
|
||||
public bool Equals(PwCharSet other)
|
||||
{
|
||||
if (object.ReferenceEquals(other, this)) return true;
|
||||
if (object.ReferenceEquals(other, null)) return false;
|
||||
if(!bFullInitialize) return;
|
||||
|
||||
if (m_lChars.Count != other.m_lChars.Count) return false;
|
||||
if(m_strHighAnsi == null)
|
||||
{
|
||||
StringBuilder sbHighAnsi = new StringBuilder();
|
||||
// [U+0080, U+009F] are C1 control characters,
|
||||
// U+00A0 is non-breaking space
|
||||
for(char ch = '\u00A1'; ch <= '\u00AC'; ++ch)
|
||||
sbHighAnsi.Append(ch);
|
||||
// U+00AD is soft hyphen (format character)
|
||||
for(char ch = '\u00AE'; ch < '\u00FF'; ++ch)
|
||||
sbHighAnsi.Append(ch);
|
||||
sbHighAnsi.Append('\u00FF');
|
||||
|
||||
return MemUtil.ArraysEqual(m_vTab, other.m_vTab);
|
||||
}
|
||||
m_strHighAnsi = sbHighAnsi.ToString();
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return Equals(obj as PwCharSet);
|
||||
}
|
||||
if(m_strSpecial == null)
|
||||
{
|
||||
PwCharSet pcs = new PwCharSet(false);
|
||||
pcs.AddRange('!', '/');
|
||||
pcs.AddRange(':', '@');
|
||||
pcs.AddRange('[', '`');
|
||||
pcs.Add(@"|~");
|
||||
pcs.Remove(@"-_ ");
|
||||
pcs.Remove(PwCharSet.Brackets);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return (int)MemUtil.Hash32(m_vTab, 0, m_vTab.Length);
|
||||
}
|
||||
m_strSpecial = pcs.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove all characters from this set.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
m_lChars.Clear();
|
||||
Array.Clear(m_vTab, 0, m_vTab.Length);
|
||||
}
|
||||
/// <summary>
|
||||
/// Number of characters in this set.
|
||||
/// </summary>
|
||||
public uint Size
|
||||
{
|
||||
get { return (uint)m_vChars.Count; }
|
||||
}
|
||||
|
||||
public bool Contains(char ch)
|
||||
{
|
||||
return (((m_vTab[ch / 8] >> (ch % 8)) & 1) != char.MinValue);
|
||||
}
|
||||
/// <summary>
|
||||
/// Get a character of the set using an index.
|
||||
/// </summary>
|
||||
/// <param name="uPos">Index of the character to get.</param>
|
||||
/// <returns>Character at the specified position. If the index is invalid,
|
||||
/// an <c>ArgumentOutOfRangeException</c> is thrown.</returns>
|
||||
public char this[uint uPos]
|
||||
{
|
||||
get
|
||||
{
|
||||
if(uPos >= (uint)m_vChars.Count)
|
||||
throw new ArgumentOutOfRangeException("uPos");
|
||||
|
||||
public bool Contains(string strCharacters)
|
||||
{
|
||||
Debug.Assert(strCharacters != null);
|
||||
if (strCharacters == null) throw new ArgumentNullException("strCharacters");
|
||||
return m_vChars[(int)uPos];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (char ch in strCharacters)
|
||||
{
|
||||
if (!Contains(ch)) return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Remove all characters from this set.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
m_vChars.Clear();
|
||||
Array.Clear(m_vTab, 0, m_vTab.Length);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
public bool Contains(char ch)
|
||||
{
|
||||
return (((m_vTab[ch / 8] >> (ch % 8)) & 1) != char.MinValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add characters to the set.
|
||||
/// </summary>
|
||||
/// <param name="ch">Character to add.</param>
|
||||
public void Add(char ch)
|
||||
{
|
||||
if (ch == char.MinValue) { Debug.Assert(false); return; }
|
||||
public bool Contains(string strCharacters)
|
||||
{
|
||||
Debug.Assert(strCharacters != null);
|
||||
if(strCharacters == null) throw new ArgumentNullException("strCharacters");
|
||||
|
||||
if (!Contains(ch))
|
||||
{
|
||||
m_lChars.Add(ch);
|
||||
m_vTab[ch / 8] |= (byte)(1 << (ch % 8));
|
||||
}
|
||||
}
|
||||
foreach(char ch in strCharacters)
|
||||
{
|
||||
if(!Contains(ch)) return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add characters to the set.
|
||||
/// </summary>
|
||||
/// <param name="strCharSet">String containing characters to add.</param>
|
||||
public void Add(string strCharSet)
|
||||
{
|
||||
Debug.Assert(strCharSet != null);
|
||||
if (strCharSet == null) throw new ArgumentNullException("strCharSet");
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (char ch in strCharSet)
|
||||
Add(ch);
|
||||
}
|
||||
/// <summary>
|
||||
/// Add characters to the set.
|
||||
/// </summary>
|
||||
/// <param name="ch">Character to add.</param>
|
||||
public void Add(char ch)
|
||||
{
|
||||
if(ch == char.MinValue) { Debug.Assert(false); return; }
|
||||
|
||||
public void Add(string strCharSet1, string strCharSet2)
|
||||
{
|
||||
Add(strCharSet1);
|
||||
Add(strCharSet2);
|
||||
}
|
||||
if(!Contains(ch))
|
||||
{
|
||||
m_vChars.Add(ch);
|
||||
m_vTab[ch / 8] |= (byte)(1 << (ch % 8));
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(string strCharSet1, string strCharSet2, string strCharSet3)
|
||||
{
|
||||
Add(strCharSet1);
|
||||
Add(strCharSet2);
|
||||
Add(strCharSet3);
|
||||
}
|
||||
/// <summary>
|
||||
/// Add characters to the set.
|
||||
/// </summary>
|
||||
/// <param name="strCharSet">String containing characters to add.</param>
|
||||
public void Add(string strCharSet)
|
||||
{
|
||||
Debug.Assert(strCharSet != null);
|
||||
if(strCharSet == null) throw new ArgumentNullException("strCharSet");
|
||||
|
||||
public void AddRange(char chMin, char chMax)
|
||||
{
|
||||
for (char ch = chMin; ch < chMax; ++ch)
|
||||
Add(ch);
|
||||
m_vChars.Capacity = m_vChars.Count + strCharSet.Length;
|
||||
|
||||
Add(chMax);
|
||||
}
|
||||
foreach(char ch in strCharSet)
|
||||
Add(ch);
|
||||
}
|
||||
|
||||
public bool AddCharSet(char chCharSetIdentifier)
|
||||
{
|
||||
bool bResult = true;
|
||||
public void Add(string strCharSet1, string strCharSet2)
|
||||
{
|
||||
Add(strCharSet1);
|
||||
Add(strCharSet2);
|
||||
}
|
||||
|
||||
switch (chCharSetIdentifier)
|
||||
{
|
||||
case 'a': Add(PwCharSet.LowerCase, PwCharSet.Digits); break;
|
||||
case 'A':
|
||||
Add(PwCharSet.LowerCase, PwCharSet.UpperCase,
|
||||
PwCharSet.Digits); break;
|
||||
case 'U': Add(PwCharSet.UpperCase, PwCharSet.Digits); break;
|
||||
case 'c': Add(PwCharSet.LowerConsonants); break;
|
||||
case 'C':
|
||||
Add(PwCharSet.LowerConsonants,
|
||||
PwCharSet.UpperConsonants); break;
|
||||
case 'z': Add(PwCharSet.UpperConsonants); break;
|
||||
case 'd': Add(PwCharSet.Digits); break; // Digit
|
||||
case 'h': Add(PwCharSet.LowerHex); break;
|
||||
case 'H': Add(PwCharSet.UpperHex); break;
|
||||
case 'l': Add(PwCharSet.LowerCase); break;
|
||||
case 'L': Add(PwCharSet.LowerCase, PwCharSet.UpperCase); break;
|
||||
case 'u': Add(PwCharSet.UpperCase); break;
|
||||
case 'p': Add(PwCharSet.Punctuation); break;
|
||||
case 'b': Add(PwCharSet.Brackets); break;
|
||||
case 's': Add(PwCharSet.PrintableAsciiSpecial); break;
|
||||
case 'S':
|
||||
Add(PwCharSet.UpperCase, PwCharSet.LowerCase);
|
||||
Add(PwCharSet.Digits, PwCharSet.PrintableAsciiSpecial); break;
|
||||
case 'v': Add(PwCharSet.LowerVowels); break;
|
||||
case 'V': Add(PwCharSet.LowerVowels, PwCharSet.UpperVowels); break;
|
||||
case 'Z': Add(PwCharSet.UpperVowels); break;
|
||||
case 'x': Add(PwCharSet.Latin1S); break;
|
||||
default: bResult = false; break;
|
||||
}
|
||||
public void Add(string strCharSet1, string strCharSet2, string strCharSet3)
|
||||
{
|
||||
Add(strCharSet1);
|
||||
Add(strCharSet2);
|
||||
Add(strCharSet3);
|
||||
}
|
||||
|
||||
return bResult;
|
||||
}
|
||||
public void AddRange(char chMin, char chMax)
|
||||
{
|
||||
m_vChars.Capacity = m_vChars.Count + (chMax - chMin) + 1;
|
||||
|
||||
public bool Remove(char ch)
|
||||
{
|
||||
m_vTab[ch / 8] &= (byte)(~(1 << (ch % 8)));
|
||||
return m_lChars.Remove(ch);
|
||||
}
|
||||
for(char ch = chMin; ch < chMax; ++ch)
|
||||
Add(ch);
|
||||
|
||||
public bool Remove(string strCharacters)
|
||||
{
|
||||
Debug.Assert(strCharacters != null);
|
||||
if (strCharacters == null) throw new ArgumentNullException("strCharacters");
|
||||
Add(chMax);
|
||||
}
|
||||
|
||||
bool bResult = true;
|
||||
foreach (char ch in strCharacters)
|
||||
{
|
||||
if (!Remove(ch)) bResult = false;
|
||||
}
|
||||
public bool AddCharSet(char chCharSetIdentifier)
|
||||
{
|
||||
bool bResult = true;
|
||||
|
||||
return bResult;
|
||||
}
|
||||
switch(chCharSetIdentifier)
|
||||
{
|
||||
case 'a': Add(PwCharSet.LowerCase, PwCharSet.Digits); break;
|
||||
case 'A': Add(PwCharSet.LowerCase, PwCharSet.UpperCase,
|
||||
PwCharSet.Digits); break;
|
||||
case 'U': Add(PwCharSet.UpperCase, PwCharSet.Digits); break;
|
||||
case 'c': Add(PwCharSet.LowerConsonants); break;
|
||||
case 'C': Add(PwCharSet.LowerConsonants,
|
||||
PwCharSet.UpperConsonants); break;
|
||||
case 'z': Add(PwCharSet.UpperConsonants); break;
|
||||
case 'd': Add(PwCharSet.Digits); break; // Digit
|
||||
case 'h': Add(PwCharSet.LowerHex); break;
|
||||
case 'H': Add(PwCharSet.UpperHex); break;
|
||||
case 'l': Add(PwCharSet.LowerCase); break;
|
||||
case 'L': Add(PwCharSet.LowerCase, PwCharSet.UpperCase); break;
|
||||
case 'u': Add(PwCharSet.UpperCase); break;
|
||||
case 'p': Add(PwCharSet.Punctuation); break;
|
||||
case 'b': Add(PwCharSet.Brackets); break;
|
||||
case 's': Add(PwCharSet.PrintableAsciiSpecial); break;
|
||||
case 'S': Add(PwCharSet.UpperCase, PwCharSet.LowerCase);
|
||||
Add(PwCharSet.Digits, PwCharSet.PrintableAsciiSpecial); break;
|
||||
case 'v': Add(PwCharSet.LowerVowels); break;
|
||||
case 'V': Add(PwCharSet.LowerVowels, PwCharSet.UpperVowels); break;
|
||||
case 'Z': Add(PwCharSet.UpperVowels); break;
|
||||
case 'x': Add(m_strHighAnsi); break;
|
||||
default: bResult = false; break;
|
||||
}
|
||||
|
||||
public bool RemoveIfAllExist(string strCharacters)
|
||||
{
|
||||
Debug.Assert(strCharacters != null);
|
||||
if (strCharacters == null) throw new ArgumentNullException("strCharacters");
|
||||
return bResult;
|
||||
}
|
||||
|
||||
if (!Contains(strCharacters))
|
||||
return false;
|
||||
public bool Remove(char ch)
|
||||
{
|
||||
m_vTab[ch / 8] &= (byte)(~(1 << (ch % 8)));
|
||||
return m_vChars.Remove(ch);
|
||||
}
|
||||
|
||||
return Remove(strCharacters);
|
||||
}
|
||||
public bool Remove(string strCharacters)
|
||||
{
|
||||
Debug.Assert(strCharacters != null);
|
||||
if(strCharacters == null) throw new ArgumentNullException("strCharacters");
|
||||
|
||||
/// <summary>
|
||||
/// Convert the character set to a string containing all its characters.
|
||||
/// </summary>
|
||||
/// <returns>String containing all character set characters.</returns>
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder(m_lChars.Count);
|
||||
foreach (char ch in m_lChars)
|
||||
sb.Append(ch);
|
||||
bool bResult = true;
|
||||
foreach(char ch in strCharacters)
|
||||
{
|
||||
if(!Remove(ch)) bResult = false;
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
return bResult;
|
||||
}
|
||||
|
||||
public string PackAndRemoveCharRanges()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
public bool RemoveIfAllExist(string strCharacters)
|
||||
{
|
||||
Debug.Assert(strCharacters != null);
|
||||
if(strCharacters == null) throw new ArgumentNullException("strCharacters");
|
||||
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.UpperCase) ? 'U' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.LowerCase) ? 'L' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Digits) ? 'D' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Special) ? 'S' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Punctuation) ? 'P' : '_');
|
||||
sb.Append(RemoveIfAllExist("-") ? 'm' : '_');
|
||||
sb.Append(RemoveIfAllExist("_") ? 'u' : '_');
|
||||
sb.Append(RemoveIfAllExist(" ") ? 's' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Brackets) ? 'B' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Latin1S) ? 'H' : '_');
|
||||
if(!Contains(strCharacters))
|
||||
return false;
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
return Remove(strCharacters);
|
||||
}
|
||||
|
||||
public void UnpackCharRanges(string strRanges)
|
||||
{
|
||||
if (strRanges == null) { Debug.Assert(false); return; }
|
||||
if (strRanges.Length < 10) { Debug.Assert(false); return; }
|
||||
/// <summary>
|
||||
/// Convert the character set to a string containing all its characters.
|
||||
/// </summary>
|
||||
/// <returns>String containing all character set characters.</returns>
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
foreach(char ch in m_vChars)
|
||||
sb.Append(ch);
|
||||
|
||||
if (strRanges[0] != '_') Add(PwCharSet.UpperCase);
|
||||
if (strRanges[1] != '_') Add(PwCharSet.LowerCase);
|
||||
if (strRanges[2] != '_') Add(PwCharSet.Digits);
|
||||
if (strRanges[3] != '_') Add(PwCharSet.Special);
|
||||
if (strRanges[4] != '_') Add(PwCharSet.Punctuation);
|
||||
if (strRanges[5] != '_') Add('-');
|
||||
if (strRanges[6] != '_') Add('_');
|
||||
if (strRanges[7] != '_') Add(' ');
|
||||
if (strRanges[8] != '_') Add(PwCharSet.Brackets);
|
||||
if (strRanges[9] != '_') Add(PwCharSet.Latin1S);
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public string PackAndRemoveCharRanges()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.UpperCase) ? 'U' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.LowerCase) ? 'L' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Digits) ? 'D' : '_');
|
||||
sb.Append(RemoveIfAllExist(m_strSpecial) ? 'S' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Punctuation) ? 'P' : '_');
|
||||
sb.Append(RemoveIfAllExist(@"-") ? 'm' : '_');
|
||||
sb.Append(RemoveIfAllExist(@"_") ? 'u' : '_');
|
||||
sb.Append(RemoveIfAllExist(@" ") ? 's' : '_');
|
||||
sb.Append(RemoveIfAllExist(PwCharSet.Brackets) ? 'B' : '_');
|
||||
sb.Append(RemoveIfAllExist(m_strHighAnsi) ? 'H' : '_');
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public void UnpackCharRanges(string strRanges)
|
||||
{
|
||||
if(strRanges == null) { Debug.Assert(false); return; }
|
||||
if(strRanges.Length < 10) { Debug.Assert(false); return; }
|
||||
|
||||
if(strRanges[0] != '_') Add(PwCharSet.UpperCase);
|
||||
if(strRanges[1] != '_') Add(PwCharSet.LowerCase);
|
||||
if(strRanges[2] != '_') Add(PwCharSet.Digits);
|
||||
if(strRanges[3] != '_') Add(m_strSpecial);
|
||||
if(strRanges[4] != '_') Add(PwCharSet.Punctuation);
|
||||
if(strRanges[5] != '_') Add('-');
|
||||
if(strRanges[6] != '_') Add('_');
|
||||
if(strRanges[7] != '_') Add(' ');
|
||||
if(strRanges[8] != '_') Add(PwCharSet.Brackets);
|
||||
if(strRanges[9] != '_') Add(m_strHighAnsi);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2025 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
Copyright (C) 2003-2016 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,172 +20,133 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
#if !KeePassUAP
|
||||
using System.Security.Cryptography;
|
||||
#endif
|
||||
|
||||
using KeePassLib.Resources;
|
||||
using KeePassLib.Security;
|
||||
using KeePassLib.Utility;
|
||||
|
||||
namespace KeePassLib.Cryptography.PasswordGenerator
|
||||
{
|
||||
public enum PwgError
|
||||
{
|
||||
Success = 0,
|
||||
Unknown = 1,
|
||||
TooFewCharacters = 2,
|
||||
UnknownAlgorithm = 3,
|
||||
InvalidCharSet = 4,
|
||||
InvalidPattern = 5
|
||||
}
|
||||
public enum PwgError
|
||||
{
|
||||
Success = 0,
|
||||
Unknown = 1,
|
||||
TooFewCharacters = 2,
|
||||
UnknownAlgorithm = 3
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Password generator.
|
||||
/// </summary>
|
||||
public static class PwGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Utility functions for generating random passwords.
|
||||
/// </summary>
|
||||
public static class PwGenerator
|
||||
{
|
||||
public static PwgError Generate(out ProtectedString psOut,
|
||||
PwProfile pwProfile, byte[] pbUserEntropy,
|
||||
CustomPwGeneratorPool pwAlgorithmPool)
|
||||
{
|
||||
Debug.Assert(pwProfile != null);
|
||||
if (pwProfile == null) throw new ArgumentNullException("pwProfile");
|
||||
|
||||
private static CryptoRandomStream CreateRandomStream(byte[] pbAdditionalEntropy,
|
||||
out byte[] pbKey)
|
||||
{
|
||||
pbKey = CryptoRandom.Instance.GetRandomBytes(128);
|
||||
CryptoRandomStream crs = CreateCryptoStream(pbUserEntropy);
|
||||
PwgError e = PwgError.Unknown;
|
||||
|
||||
// Mix in additional entropy
|
||||
Debug.Assert(pbKey.Length >= 64);
|
||||
if ((pbAdditionalEntropy != null) && (pbAdditionalEntropy.Length != 0))
|
||||
{
|
||||
using (SHA512Managed h = new SHA512Managed())
|
||||
{
|
||||
byte[] pbHash = h.ComputeHash(pbAdditionalEntropy);
|
||||
MemUtil.XorArray(pbHash, 0, pbKey, 0, pbHash.Length);
|
||||
MemUtil.ZeroByteArray(pbHash);
|
||||
}
|
||||
}
|
||||
if (pwProfile.GeneratorType == PasswordGeneratorType.CharSet)
|
||||
e = CharSetBasedGenerator.Generate(out psOut, pwProfile, crs);
|
||||
else if (pwProfile.GeneratorType == PasswordGeneratorType.Pattern)
|
||||
e = PatternBasedGenerator.Generate(out psOut, pwProfile, crs);
|
||||
else if (pwProfile.GeneratorType == PasswordGeneratorType.Custom)
|
||||
e = GenerateCustom(out psOut, pwProfile, crs, pwAlgorithmPool);
|
||||
else { Debug.Assert(false); psOut = ProtectedString.Empty; }
|
||||
|
||||
return new CryptoRandomStream(CrsAlgorithm.ChaCha20, pbKey);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
internal static char GenerateCharacter(PwCharSet pwCharSet,
|
||||
CryptoRandomStream crsRandomSource)
|
||||
{
|
||||
uint cc = pwCharSet.Size;
|
||||
if (cc == 0) return char.MinValue;
|
||||
private static CryptoRandomStream CreateCryptoStream(byte[] pbAdditionalEntropy)
|
||||
{
|
||||
byte[] pbKey = CryptoRandom.Instance.GetRandomBytes(128);
|
||||
|
||||
uint i = (uint)crsRandomSource.GetRandomUInt64(cc);
|
||||
return pwCharSet[i];
|
||||
}
|
||||
// Mix in additional entropy
|
||||
Debug.Assert(pbKey.Length >= 64);
|
||||
if ((pbAdditionalEntropy != null) && (pbAdditionalEntropy.Length > 0))
|
||||
{
|
||||
using (SHA512Managed h = new SHA512Managed())
|
||||
{
|
||||
byte[] pbHash = h.ComputeHash(pbAdditionalEntropy);
|
||||
MemUtil.XorArray(pbHash, 0, pbKey, 0, pbHash.Length);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool PrepareCharSet(PwCharSet pwCharSet, PwProfile pwProfile)
|
||||
{
|
||||
uint cc = pwCharSet.Size;
|
||||
for (uint i = 0; i < cc; ++i)
|
||||
{
|
||||
char ch = pwCharSet[i];
|
||||
if ((ch == char.MinValue) || (ch == '\t') || (ch == '\r') ||
|
||||
(ch == '\n') || char.IsSurrogate(ch))
|
||||
return false;
|
||||
}
|
||||
return new CryptoRandomStream(CrsAlgorithm.ChaCha20, pbKey);
|
||||
}
|
||||
|
||||
if (pwProfile.ExcludeLookAlike) pwCharSet.Remove(PwCharSet.LookAlike);
|
||||
internal static char GenerateCharacter(PwProfile pwProfile,
|
||||
PwCharSet pwCharSet, CryptoRandomStream crsRandomSource)
|
||||
{
|
||||
if (pwCharSet.Size == 0) return char.MinValue;
|
||||
|
||||
if (!string.IsNullOrEmpty(pwProfile.ExcludeCharacters))
|
||||
pwCharSet.Remove(pwProfile.ExcludeCharacters);
|
||||
ulong uIndex = crsRandomSource.GetRandomUInt64();
|
||||
uIndex %= (ulong)pwCharSet.Size;
|
||||
|
||||
return true;
|
||||
}
|
||||
char ch = pwCharSet[(uint)uIndex];
|
||||
|
||||
internal static void Shuffle(char[] v, CryptoRandomStream crsRandomSource)
|
||||
{
|
||||
if (v == null) { Debug.Assert(false); return; }
|
||||
if (crsRandomSource == null) { Debug.Assert(false); return; }
|
||||
if (pwProfile.NoRepeatingCharacters)
|
||||
pwCharSet.Remove(ch);
|
||||
|
||||
for (int i = v.Length - 1; i >= 1; --i)
|
||||
{
|
||||
int j = (int)crsRandomSource.GetRandomUInt64((ulong)(i + 1));
|
||||
return ch;
|
||||
}
|
||||
|
||||
char t = v[i];
|
||||
v[i] = v[j];
|
||||
v[j] = t;
|
||||
}
|
||||
}
|
||||
internal static void PrepareCharSet(PwCharSet pwCharSet, PwProfile pwProfile)
|
||||
{
|
||||
pwCharSet.Remove(PwCharSet.Invalid);
|
||||
|
||||
private static PwgError GenerateCustom(out ProtectedString psOut,
|
||||
PwProfile pwProfile, CryptoRandomStream crs,
|
||||
CustomPwGeneratorPool pwAlgorithmPool)
|
||||
{
|
||||
psOut = ProtectedString.Empty;
|
||||
if (pwProfile.ExcludeLookAlike) pwCharSet.Remove(PwCharSet.LookAlike);
|
||||
|
||||
Debug.Assert(pwProfile.GeneratorType == PasswordGeneratorType.Custom);
|
||||
if (pwAlgorithmPool == null) return PwgError.UnknownAlgorithm;
|
||||
if (pwProfile.ExcludeCharacters.Length > 0)
|
||||
pwCharSet.Remove(pwProfile.ExcludeCharacters);
|
||||
}
|
||||
|
||||
string strID = pwProfile.CustomAlgorithmUuid;
|
||||
if (string.IsNullOrEmpty(strID)) return PwgError.UnknownAlgorithm;
|
||||
internal static void ShufflePassword(char[] pPassword,
|
||||
CryptoRandomStream crsRandomSource)
|
||||
{
|
||||
Debug.Assert(pPassword != null); if (pPassword == null) return;
|
||||
Debug.Assert(crsRandomSource != null); if (crsRandomSource == null) return;
|
||||
|
||||
byte[] pbUuid = Convert.FromBase64String(strID);
|
||||
PwUuid uuid = new PwUuid(pbUuid);
|
||||
CustomPwGenerator pwg = pwAlgorithmPool.Find(uuid);
|
||||
if (pwg == null) { Debug.Assert(false); return PwgError.UnknownAlgorithm; }
|
||||
if (pPassword.Length <= 1) return; // Nothing to shuffle
|
||||
|
||||
ProtectedString pwd = pwg.Generate(pwProfile.CloneDeep(), crs);
|
||||
if (pwd == null) return PwgError.Unknown;
|
||||
for (int nSelect = 0; nSelect < pPassword.Length; ++nSelect)
|
||||
{
|
||||
ulong uRandomIndex = crsRandomSource.GetRandomUInt64();
|
||||
uRandomIndex %= (ulong)(pPassword.Length - nSelect);
|
||||
|
||||
psOut = pwd;
|
||||
return PwgError.Success;
|
||||
}
|
||||
char chTemp = pPassword[nSelect];
|
||||
pPassword[nSelect] = pPassword[nSelect + (int)uRandomIndex];
|
||||
pPassword[nSelect + (int)uRandomIndex] = chTemp;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string ErrorToString(PwgError e, bool bHeader)
|
||||
{
|
||||
if (e == PwgError.Success) { Debug.Assert(false); return string.Empty; }
|
||||
if ((e == PwgError.Unknown) && bHeader) return KLRes.PwGenFailed;
|
||||
private static PwgError GenerateCustom(out ProtectedString psOut,
|
||||
PwProfile pwProfile, CryptoRandomStream crs,
|
||||
CustomPwGeneratorPool pwAlgorithmPool)
|
||||
{
|
||||
psOut = ProtectedString.Empty;
|
||||
|
||||
string str = KLRes.UnknownError;
|
||||
switch (e)
|
||||
{
|
||||
// case PwgError.Success:
|
||||
// break;
|
||||
Debug.Assert(pwProfile.GeneratorType == PasswordGeneratorType.Custom);
|
||||
if (pwAlgorithmPool == null) return PwgError.UnknownAlgorithm;
|
||||
|
||||
case PwgError.Unknown:
|
||||
break;
|
||||
string strID = pwProfile.CustomAlgorithmUuid;
|
||||
if (string.IsNullOrEmpty(strID)) { Debug.Assert(false); return PwgError.UnknownAlgorithm; }
|
||||
|
||||
case PwgError.TooFewCharacters:
|
||||
str = KLRes.CharSetTooFewChars;
|
||||
break;
|
||||
byte[] pbUuid = Convert.FromBase64String(strID);
|
||||
PwUuid uuid = new PwUuid(pbUuid);
|
||||
CustomPwGenerator pwg = pwAlgorithmPool.Find(uuid);
|
||||
if (pwg == null) { Debug.Assert(false); return PwgError.UnknownAlgorithm; }
|
||||
|
||||
case PwgError.UnknownAlgorithm:
|
||||
str = KLRes.AlgorithmUnknown;
|
||||
break;
|
||||
ProtectedString pwd = pwg.Generate(pwProfile.CloneDeep(), crs);
|
||||
if (pwd == null) return PwgError.Unknown;
|
||||
|
||||
case PwgError.InvalidCharSet:
|
||||
str = KLRes.CharSetInvalid;
|
||||
break;
|
||||
|
||||
case PwgError.InvalidPattern:
|
||||
str = KLRes.PatternInvalid;
|
||||
break;
|
||||
|
||||
default:
|
||||
Debug.Assert(false);
|
||||
break;
|
||||
}
|
||||
|
||||
if (bHeader)
|
||||
str = KLRes.PwGenFailed + MessageService.NewParagraph + str;
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
internal static string ErrorToString(Exception ex, bool bHeader)
|
||||
{
|
||||
string str = ((ex == null) ? KLRes.UnknownError :
|
||||
StrUtil.FormatException(ex));
|
||||
|
||||
if (bHeader)
|
||||
str = KLRes.PwGenFailed + MessageService.NewParagraph + str;
|
||||
|
||||
return str;
|
||||
}
|
||||
}
|
||||
psOut = pwd;
|
||||
return PwgError.Success;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2025 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -19,115 +19,114 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
|
||||
using KeePassLib.Utility;
|
||||
|
||||
namespace KeePassLib.Cryptography
|
||||
{
|
||||
public static class PopularPasswords
|
||||
{
|
||||
private static readonly Dictionary<int, Dictionary<char[], bool>> g_dicts =
|
||||
new Dictionary<int, Dictionary<char[], bool>>();
|
||||
public static class PopularPasswords
|
||||
{
|
||||
private static Dictionary<int, Dictionary<string, bool>> m_dicts =
|
||||
new Dictionary<int, Dictionary<string, bool>>();
|
||||
|
||||
internal static int MaxLength
|
||||
{
|
||||
get
|
||||
{
|
||||
Debug.Assert(g_dicts.Count > 0); // Should be initialized
|
||||
internal static int MaxLength
|
||||
{
|
||||
get
|
||||
{
|
||||
int iMaxLen = 0;
|
||||
foreach(int iLen in m_dicts.Keys)
|
||||
{
|
||||
if(iLen > iMaxLen) iMaxLen = iLen;
|
||||
}
|
||||
|
||||
int iMaxLen = 0;
|
||||
foreach (int iLen in g_dicts.Keys)
|
||||
{
|
||||
if (iLen > iMaxLen) iMaxLen = iLen;
|
||||
}
|
||||
return iMaxLen;
|
||||
}
|
||||
}
|
||||
|
||||
return iMaxLen;
|
||||
}
|
||||
}
|
||||
internal static bool ContainsLength(int nLength)
|
||||
{
|
||||
Dictionary<string, bool> dDummy;
|
||||
return m_dicts.TryGetValue(nLength, out dDummy);
|
||||
}
|
||||
|
||||
internal static bool ContainsLength(int nLength)
|
||||
{
|
||||
Dictionary<char[], bool> dDummy;
|
||||
return g_dicts.TryGetValue(nLength, out dDummy);
|
||||
}
|
||||
public static bool IsPopularPassword(char[] vPassword)
|
||||
{
|
||||
ulong uDummy;
|
||||
return IsPopularPassword(vPassword, out uDummy);
|
||||
}
|
||||
|
||||
public static bool IsPopularPassword(char[] vPassword)
|
||||
{
|
||||
ulong uDummy;
|
||||
return IsPopularPassword(vPassword, out uDummy);
|
||||
}
|
||||
public static bool IsPopularPassword(char[] vPassword, out ulong uDictSize)
|
||||
{
|
||||
if(vPassword == null) throw new ArgumentNullException("vPassword");
|
||||
if(vPassword.Length == 0) { uDictSize = 0; return false; }
|
||||
|
||||
public static bool IsPopularPassword(char[] vPassword, out ulong uDictSize)
|
||||
{
|
||||
if (vPassword == null) throw new ArgumentNullException("vPassword");
|
||||
if (vPassword.Length == 0) { uDictSize = 0; return false; }
|
||||
string str = new string(vPassword);
|
||||
|
||||
#if DEBUG
|
||||
Array.ForEach(vPassword, ch => Debug.Assert(ch == char.ToLower(ch)));
|
||||
#endif
|
||||
try { return IsPopularPasswordPriv(str, out uDictSize); }
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
|
||||
try { return IsPopularPasswordPriv(vPassword, out uDictSize); }
|
||||
catch (Exception) { Debug.Assert(false); }
|
||||
uDictSize = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
uDictSize = 0;
|
||||
return false;
|
||||
}
|
||||
private static bool IsPopularPasswordPriv(string str, out ulong uDictSize)
|
||||
{
|
||||
Debug.Assert(m_dicts.Count > 0); // Should be initialized with data
|
||||
|
||||
private static bool IsPopularPasswordPriv(char[] vPassword, out ulong uDictSize)
|
||||
{
|
||||
Debug.Assert(g_dicts.Count > 0); // Should be initialized with data
|
||||
Dictionary<string, bool> d;
|
||||
if(!m_dicts.TryGetValue(str.Length, out d))
|
||||
{
|
||||
uDictSize = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
Dictionary<char[], bool> d;
|
||||
if (!g_dicts.TryGetValue(vPassword.Length, out d))
|
||||
{
|
||||
uDictSize = 0;
|
||||
return false;
|
||||
}
|
||||
uDictSize = (ulong)d.Count;
|
||||
return d.ContainsKey(str);
|
||||
}
|
||||
|
||||
uDictSize = (ulong)d.Count;
|
||||
return d.ContainsKey(vPassword);
|
||||
}
|
||||
public static void Add(byte[] pbData, bool bGZipped)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(bGZipped)
|
||||
pbData = MemUtil.Decompress(pbData);
|
||||
|
||||
public static void Add(byte[] pbData, bool bGZipped)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (bGZipped)
|
||||
pbData = MemUtil.Decompress(pbData);
|
||||
string strData = StrUtil.Utf8.GetString(pbData, 0, pbData.Length);
|
||||
if(string.IsNullOrEmpty(strData)) { Debug.Assert(false); return; }
|
||||
|
||||
string strData = StrUtil.Utf8.GetString(pbData, 0, pbData.Length);
|
||||
if (string.IsNullOrEmpty(strData)) { Debug.Assert(false); return; }
|
||||
if(!char.IsWhiteSpace(strData[strData.Length - 1]))
|
||||
strData += "\n";
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i <= strData.Length; ++i)
|
||||
{
|
||||
char ch = ((i == strData.Length) ? ' ' : strData[i]);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for(int i = 0; i < strData.Length; ++i)
|
||||
{
|
||||
char ch = strData[i];
|
||||
|
||||
if (char.IsWhiteSpace(ch))
|
||||
{
|
||||
int cc = sb.Length;
|
||||
if (cc > 0)
|
||||
{
|
||||
char[] vWord = new char[cc];
|
||||
sb.CopyTo(0, vWord, 0, cc);
|
||||
if(char.IsWhiteSpace(ch))
|
||||
{
|
||||
int cc = sb.Length;
|
||||
if(cc > 0)
|
||||
{
|
||||
string strWord = sb.ToString();
|
||||
Debug.Assert(strWord.Length == cc);
|
||||
|
||||
Dictionary<char[], bool> d;
|
||||
if (!g_dicts.TryGetValue(cc, out d))
|
||||
{
|
||||
d = new Dictionary<char[], bool>(MemUtil.ArrayHelperExOfChar);
|
||||
g_dicts[cc] = d;
|
||||
}
|
||||
Dictionary<string, bool> d;
|
||||
if(!m_dicts.TryGetValue(cc, out d))
|
||||
{
|
||||
d = new Dictionary<string, bool>();
|
||||
m_dicts[cc] = d;
|
||||
}
|
||||
|
||||
d[vWord] = true;
|
||||
sb.Remove(0, cc);
|
||||
}
|
||||
}
|
||||
else sb.Append(char.ToLower(ch));
|
||||
}
|
||||
}
|
||||
catch (Exception) { Debug.Assert(false); }
|
||||
}
|
||||
}
|
||||
d[strWord] = true;
|
||||
sb.Remove(0, cc);
|
||||
}
|
||||
}
|
||||
else sb.Append(char.ToLower(ch));
|
||||
}
|
||||
}
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -46,12 +46,4 @@ namespace KeePassLib.Delegates
|
||||
public delegate void VoidDelegate();
|
||||
|
||||
public delegate string StrPwEntryDelegate(string str, PwEntry pe);
|
||||
|
||||
public delegate TResult GFunc<TResult>();
|
||||
public delegate TResult GFunc<T, TResult>(T o);
|
||||
public delegate TResult GFunc<T1, T2, TResult>(T1 o1, T2 o2);
|
||||
public delegate TResult GFunc<T1, T2, T3, TResult>(T1 o1, T2 o2, T3 o3);
|
||||
public delegate TResult GFunc<T1, T2, T3, T4, TResult>(T1 o1, T2 o2, T3 o3, T4 o4);
|
||||
public delegate TResult GFunc<T1, T2, T3, T4, T5, TResult>(T1 o1, T2 o2, T3 o3, T4 o4, T5 o5);
|
||||
public delegate TResult GFunc<T1, T2, T3, T4, T5, T6, TResult>(T1 o1, T2 o2, T3 o3, T4 o4, T5 o5, T6 o6);
|
||||
}
|
||||
|
||||
@@ -86,12 +86,17 @@ namespace KeePassLib.Interfaces
|
||||
/// the current work.</returns>
|
||||
bool SetText(string strNewText, LogStatusType lsType);
|
||||
|
||||
/// <summary>
|
||||
/// Check if the user cancelled the current work.
|
||||
/// </summary>
|
||||
/// <returns>Returns <c>true</c> if the caller should continue
|
||||
/// the current work.</returns>
|
||||
bool ContinueWork();
|
||||
void UpdateMessage(String message);
|
||||
|
||||
|
||||
void UpdateSubMessage(String submessage);
|
||||
|
||||
/// <summary>
|
||||
/// Check if the user cancelled the current work.
|
||||
/// </summary>
|
||||
/// <returns>Returns <c>true</c> if the caller should continue
|
||||
/// the current work.</returns>
|
||||
bool ContinueWork();
|
||||
}
|
||||
|
||||
public sealed class NullStatusLogger : IStatusLogger
|
||||
@@ -100,6 +105,12 @@ namespace KeePassLib.Interfaces
|
||||
public void EndLogging() { }
|
||||
public bool SetProgress(uint uPercent) { return true; }
|
||||
public bool SetText(string strNewText, LogStatusType lsType) { return true; }
|
||||
public bool ContinueWork() { return true; }
|
||||
public void UpdateMessage(string message){
|
||||
}
|
||||
|
||||
public void UpdateSubMessage(string submessage){
|
||||
}
|
||||
|
||||
public bool ContinueWork() { return true; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -21,6 +21,7 @@ using System.IO;
|
||||
using Android;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Android.Preferences;
|
||||
using KeePassLib.Serialization;
|
||||
|
||||
@@ -34,9 +35,17 @@ namespace keepass2android
|
||||
|
||||
public static void Log(string message)
|
||||
{
|
||||
if (message != null)
|
||||
Android.Util.Log.Debug("KP2A", message);
|
||||
if (LogToFile)
|
||||
if (message != null)
|
||||
{
|
||||
message += Thread.CurrentThread.ManagedThreadId != 0
|
||||
? " (Thread ID: " + Thread.CurrentThread.ManagedThreadId + ")"
|
||||
: "";
|
||||
if (Looper.MainLooper == Looper.MyLooper())
|
||||
message += " (Main Looper)";
|
||||
Android.Util.Log.Debug("KP2A", message);
|
||||
}
|
||||
|
||||
if (LogToFile)
|
||||
{
|
||||
lock (_fileLocker)
|
||||
{
|
||||
@@ -116,23 +125,12 @@ namespace keepass2android
|
||||
|
||||
Intent sendIntent = new Intent();
|
||||
sendIntent.SetAction(Intent.ActionSend);
|
||||
string logText = File.ReadAllText(LogFilename);
|
||||
|
||||
sendIntent.PutExtra(Intent.ExtraText, logText);
|
||||
sendIntent.PutExtra(Intent.ExtraText, File.ReadAllText(LogFilename));
|
||||
sendIntent.PutExtra(Intent.ExtraEmail, "crocoapps@gmail.com");
|
||||
sendIntent.PutExtra(Intent.ExtraSubject, "Keepass2Android log");
|
||||
sendIntent.SetType("text/plain");
|
||||
try
|
||||
{
|
||||
ctx.StartActivity(Intent.CreateChooser(sendIntent, "Send log to..."));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Toast.MakeText(ctx, $"Error sending log of length {logText.Length} bytes: " + e.Message, ToastLength.Long)?.Show();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
ctx.StartActivity(Intent.CreateChooser(sendIntent, "Send log to..."));
|
||||
}
|
||||
|
||||
public static void LogTask(object task, string activityName)
|
||||
{
|
||||
|
||||
@@ -208,7 +208,7 @@ namespace KeePassLib.Serialization
|
||||
if (!string.IsNullOrEmpty(strHash) && (m_pbHashOfHeader != null) &&
|
||||
!m_bRepairMode)
|
||||
{
|
||||
Debug.Assert(m_uFileVersion < FileVersion32_4);
|
||||
// Debug.Assert(m_uFileVersion < FileVersion32_4);
|
||||
|
||||
byte[] pbHash = Convert.FromBase64String(strHash);
|
||||
if (!MemUtil.ArraysEqual(pbHash, m_pbHashOfHeader))
|
||||
|
||||
@@ -83,7 +83,6 @@ namespace KeePassLib.Serialization
|
||||
if (m_bUsedOnce)
|
||||
throw new InvalidOperationException("Do not reuse KdbxFile objects!");
|
||||
m_bUsedOnce = true;
|
||||
Kp2aLog.Log("Starting to load KDBX file...");
|
||||
|
||||
#if KDBX_BENCHMARK
|
||||
Stopwatch swTime = Stopwatch.StartNew();
|
||||
@@ -258,8 +257,7 @@ namespace KeePassLib.Serialization
|
||||
MessageService.ShowInfo("Loading KDBX took " +
|
||||
swTime.ElapsedMilliseconds.ToString() + " ms.");
|
||||
#endif
|
||||
Kp2aLog.Log("Finished loading KDBX file.");
|
||||
}
|
||||
}
|
||||
|
||||
private void CommonCleanUpRead(List<Stream> lStreams, HashingStreamEx sHashing)
|
||||
{
|
||||
@@ -490,7 +488,7 @@ namespace KeePassLib.Serialization
|
||||
|
||||
ProtectedBinary pb = new ProtectedBinary(bProt, pbData,
|
||||
1, pbData.Length - 1);
|
||||
Debug.Assert(m_pbsBinaries.Find(pb) < 0); // No deduplication?
|
||||
//Debug.Assert(m_pbsBinaries.Find(pb) < 0); // No deduplication?
|
||||
m_pbsBinaries.Add(pb);
|
||||
|
||||
if (bProt) MemUtil.ZeroByteArray(pbData);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -95,7 +95,7 @@ namespace Kp2aAutofillParserTest
|
||||
StructureParserBase<TestInputField> parser =
|
||||
new StructureParserBase<TestInputField>(new TestLogger(), new TestDalSourceTrustAll());
|
||||
|
||||
var result = parser.ParseForFill(autofillView);
|
||||
var result = parser.ParseForFill(false, autofillView);
|
||||
if (expectedPackageName != null)
|
||||
Assert.Equal(expectedPackageName, result.PackageName);
|
||||
if (expectedWebDomain != null)
|
||||
|
||||
@@ -58,8 +58,7 @@
|
||||
"IsFocused": false,
|
||||
"InputType": 97,
|
||||
"HtmlInfoTag": null,
|
||||
"HtmlInfoTypeAttribute": null,
|
||||
"ExpectedAssignedHints": [ "username" ]
|
||||
"HtmlInfoTypeAttribute": null
|
||||
},
|
||||
{
|
||||
"IdEntry": "password_text_input_layout",
|
||||
@@ -82,7 +81,6 @@
|
||||
"InputType": 129,
|
||||
"HtmlInfoTag": null,
|
||||
"HtmlInfoTypeAttribute": null,
|
||||
"ExpectedAssignedHints": [ "password" ]
|
||||
|
||||
},
|
||||
{
|
||||
|
||||
@@ -476,16 +476,8 @@ namespace Kp2aAutofillParser
|
||||
|
||||
foreach (var field in autofillFields.HintMap.Values.Distinct())
|
||||
{
|
||||
if (field == null || field.AutofillHints == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
foreach (var hint in field.AutofillHints)
|
||||
{
|
||||
if (hint == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (GetPartitionIndex(hint) == partitionIndex)
|
||||
{
|
||||
filteredCollection.Add(field);
|
||||
@@ -801,14 +793,14 @@ namespace Kp2aAutofillParser
|
||||
}
|
||||
}
|
||||
|
||||
public AutofillTargetId ParseForFill(AutofillView<FieldT> autofillView)
|
||||
public AutofillTargetId ParseForFill(bool isManual, AutofillView<FieldT> autofillView)
|
||||
{
|
||||
return Parse(true, autofillView);
|
||||
return Parse(true, isManual, autofillView);
|
||||
}
|
||||
|
||||
public AutofillTargetId ParseForSave(AutofillView<FieldT> autofillView)
|
||||
{
|
||||
return Parse(false, autofillView);
|
||||
return Parse(false, true, autofillView);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -816,7 +808,8 @@ namespace Kp2aAutofillParser
|
||||
/// </summary>
|
||||
/// <returns>The parse.</returns>
|
||||
/// <param name="forFill">If set to <c>true</c> for fill.</param>
|
||||
protected virtual AutofillTargetId Parse(bool forFill, AutofillView<FieldT> autofillView)
|
||||
/// <param name="isManualRequest"></param>
|
||||
protected virtual AutofillTargetId Parse(bool forFill, bool isManualRequest, AutofillView<FieldT> autofillView)
|
||||
{
|
||||
AutofillTargetId result = new AutofillTargetId()
|
||||
{
|
||||
@@ -883,9 +876,8 @@ namespace Kp2aAutofillParser
|
||||
|
||||
}
|
||||
|
||||
//for "heuristic determination" we demand that there is a password field or one of the username fields is focused:
|
||||
//Note that "IsFocused" might be false even when tapping the field. It might require long-press to autofill.
|
||||
if (passwordFields.Any() || usernameFields.Any(f => f.IsFocused))
|
||||
//for "heuristic determination" we demand that one of the filled fields is focused:
|
||||
if (passwordFields.Concat(usernameFields).Any(f => f.IsFocused))
|
||||
{
|
||||
foreach (var uf in usernameFields)
|
||||
AddFieldToHintMap(uf, new string[] { AutofillHintsHelper.AutofillHintUsername });
|
||||
|
||||
53
src/Kp2aBusinessLogic/BlockingOperationStarter.cs
Normal file
53
src/Kp2aBusinessLogic/BlockingOperationStarter.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll. This file is based on Keepassdroid, Copyright Brian Pellin.
|
||||
|
||||
Keepass2Android is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Keepass2Android is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Java.Lang;
|
||||
using Java.Security;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to run a task while a progress dialog is shown
|
||||
/// </summary>
|
||||
public class BlockingOperationStarter
|
||||
{
|
||||
|
||||
private readonly OperationWithFinishHandler _task;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
public BlockingOperationStarter(IKp2aApp app, OperationWithFinishHandler task)
|
||||
{
|
||||
_task = task;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
_app.CancelBackgroundOperations();
|
||||
OperationRunner.Instance.Run(_app, _task, true);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace keepass2android
|
||||
/// Interface through which Activities and the logic layer can access some app specific functionalities and Application static data
|
||||
/// </summary>
|
||||
/// This also contains methods which are UI specific and should be replacable for testing.
|
||||
public interface IKp2aApp : ICertificateValidationHandler
|
||||
public interface IKp2aApp : ICertificateValidationHandler, IActiveContextProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Locks all currently open databases, quicklocking if available (unless false is passed for allowQuickUnlock)
|
||||
@@ -52,7 +52,9 @@ namespace keepass2android
|
||||
/// <summary>
|
||||
/// Loads the specified data as the currently open database, as unlocked.
|
||||
/// </summary>
|
||||
Database LoadDatabase(IOConnectionInfo ioConnectionInfo, MemoryStream memoryStream, CompositeKey compKey, ProgressDialogStatusLogger statusLogger, IDatabaseFormat databaseFormat, bool makeCurrent);
|
||||
Database LoadDatabase(IOConnectionInfo ioConnectionInfo, MemoryStream memoryStream, CompositeKey compKey,
|
||||
IKp2aStatusLogger statusLogger, IDatabaseFormat databaseFormat, bool makeCurrent,
|
||||
IDatabaseModificationWatcher modificationWatcher);
|
||||
|
||||
|
||||
HashSet<PwGroup> DirtyGroups { get; }
|
||||
@@ -96,7 +98,6 @@ namespace keepass2android
|
||||
EventHandler<DialogClickEventArgs> yesHandler,
|
||||
EventHandler<DialogClickEventArgs> noHandler,
|
||||
EventHandler<DialogClickEventArgs> cancelHandler,
|
||||
Context ctx,
|
||||
string messageSuffix = "");
|
||||
|
||||
/// <summary>
|
||||
@@ -107,7 +108,6 @@ namespace keepass2android
|
||||
EventHandler<DialogClickEventArgs> yesHandler,
|
||||
EventHandler<DialogClickEventArgs> noHandler,
|
||||
EventHandler<DialogClickEventArgs> cancelHandler,
|
||||
Context ctx,
|
||||
string messageSuffix = "");
|
||||
|
||||
void ShowMessage(Context ctx, int resourceId, MessageSeverity severity);
|
||||
@@ -136,14 +136,17 @@ namespace keepass2android
|
||||
bool CheckForDuplicateUuids { get; }
|
||||
#if !NoNet && !EXCLUDE_JAVAFILESTORAGE
|
||||
ICertificateErrorHandler CertificateErrorHandler { get; }
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
int WebDavChunkedUploadSize
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
bool SyncInBackgroundPreference { get; set; }
|
||||
void StartBackgroundSyncService();
|
||||
|
||||
ReaderWriterLockSlim DatabasesBackgroundModificationLock { get; }
|
||||
bool CancelBackgroundOperations();
|
||||
|
||||
/// <summary>
|
||||
/// Registers an action that should be executed when the context instance with the given id has been resumed.
|
||||
/// </summary>
|
||||
void RegisterPendingActionForContextInstance(int contextInstanceId, ActionOnOperationFinished actionToPerformWhenContextIsResumed);
|
||||
}
|
||||
}
|
||||
@@ -186,8 +186,11 @@ namespace keepass2android.Io
|
||||
Kp2aLog.Log("couldn't open from remote " + ioc.Path);
|
||||
#endif
|
||||
Kp2aLog.Log(ex.ToString());
|
||||
|
||||
_cacheSupervisor.CouldntOpenFromRemote(ioc, ex);
|
||||
if (TriggerWarningWhenFallingBackToCache)
|
||||
{
|
||||
_cacheSupervisor.CouldntOpenFromRemote(ioc, ex);
|
||||
}
|
||||
|
||||
return File.OpenRead(cachedFilePath);
|
||||
}
|
||||
}
|
||||
@@ -327,7 +330,10 @@ namespace keepass2android.Io
|
||||
Kp2aLog.Log("couldn't save to remote " + ioc.Path);
|
||||
Kp2aLog.Log(e.ToString());
|
||||
//notify the supervisor so it might display a warning or schedule a retry
|
||||
_cacheSupervisor.CouldntSaveToRemote(ioc, e);
|
||||
if (TriggerWarningWhenFallingBackToCache)
|
||||
{
|
||||
_cacheSupervisor.CouldntSaveToRemote(ioc, e); }
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -632,7 +638,9 @@ namespace keepass2android.Io
|
||||
set { _cachedStorage.IsOffline = value; }
|
||||
}
|
||||
|
||||
public void OnRequestPermissionsResult(IFileStorageSetupActivity fileStorageSetupActivity, int requestCode,
|
||||
public bool TriggerWarningWhenFallingBackToCache { get; set; }
|
||||
|
||||
public void OnRequestPermissionsResult(IFileStorageSetupActivity fileStorageSetupActivity, int requestCode,
|
||||
string[] permissions, Permission[] grantResults)
|
||||
{
|
||||
_cachedStorage.OnRequestPermissionsResult(fileStorageSetupActivity, requestCode, permissions, grantResults);
|
||||
|
||||
@@ -15,9 +15,7 @@ namespace keepass2android.Io
|
||||
{
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
static public bool IsConfigured => !string.IsNullOrEmpty(AppKey) && !string.IsNullOrEmpty(AppSecret);
|
||||
}
|
||||
}
|
||||
|
||||
public partial class DropboxAppFolderFileStorage: JavaFileStorage
|
||||
{
|
||||
@@ -31,7 +29,6 @@ namespace keepass2android.Io
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
static public bool IsConfigured => !string.IsNullOrEmpty(AppKey) && !string.IsNullOrEmpty(AppSecret);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
13
src/Kp2aBusinessLogic/Io/DropboxFileStorageKeysDummy.cs
Normal file
13
src/Kp2aBusinessLogic/Io/DropboxFileStorageKeysDummy.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace keepass2android.Io
|
||||
{
|
||||
public partial class DropboxFileStorage
|
||||
{
|
||||
private const string AppKey = "dummy";
|
||||
private const string AppSecret = "dummy";
|
||||
}
|
||||
public partial class DropboxAppFolderFileStorage
|
||||
{
|
||||
private const string AppKey = "dummy";
|
||||
private const string AppSecret = "dummy";
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<Project>
|
||||
<Target Name="GenerateDropboxSecrets" BeforeTargets="BeforeCompile"
|
||||
Inputs="@(DropboxSecretLines)"
|
||||
Outputs="DropboxFileStorage.g.cs">
|
||||
|
||||
<WriteLinesToFile
|
||||
File="Io/DropboxFileStorage.g.cs"
|
||||
Lines="@(DropboxSecretLines->'%(Text)')"
|
||||
Overwrite="true"
|
||||
/>
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<DropboxSecretLines Include="GeneratedDropboxSecrets">
|
||||
<Text>namespace keepass2android.Io {
|
||||
public partial class DropboxFileStorage {
|
||||
private const string AppKey = "$(DropboxAppKey)";
|
||||
private const string AppSecret = "$(DropboxAppSecret)";
|
||||
}
|
||||
public partial class DropboxAppFolderFileStorage {
|
||||
private const string AppKey = "$(DropboxAppFolderAppKey)";
|
||||
private const string AppSecret = "$(DropboxAppFolderAppSecret)";
|
||||
}
|
||||
}</Text>
|
||||
</DropboxSecretLines>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -111,6 +111,11 @@ namespace keepass2android.Io
|
||||
}
|
||||
|
||||
Java.Lang.Exception exception = e as Java.Lang.Exception;
|
||||
|
||||
if ((exception is Java.Lang.InterruptedException) || (exception is Java.IO.InterruptedIOException))
|
||||
{
|
||||
throw new Java.Lang.InterruptedException(exception.Message);
|
||||
}
|
||||
if (exception != null)
|
||||
{
|
||||
var ex = new Exception(exception.LocalizedMessage ??
|
||||
@@ -123,7 +128,7 @@ namespace keepass2android.Io
|
||||
|
||||
}
|
||||
|
||||
public virtual IWriteTransaction OpenWriteTransaction(IOConnectionInfo ioc, bool useFileTransaction)
|
||||
public IWriteTransaction OpenWriteTransaction(IOConnectionInfo ioc, bool useFileTransaction)
|
||||
{
|
||||
return new JavaFileStorageWriteTransaction(IocToPath(ioc), useFileTransaction, this);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ using Android.Content;
|
||||
using Android.OS;
|
||||
using FluentFTP;
|
||||
using FluentFTP.Exceptions;
|
||||
using FluentFTP.GnuTLS;
|
||||
using KeePass.Util;
|
||||
using KeePassLib;
|
||||
using KeePassLib.Serialization;
|
||||
@@ -141,7 +140,6 @@ namespace keepass2android.Io
|
||||
var settings = ConnectionSettings.FromIoc(ioc);
|
||||
|
||||
FtpClient client = new FtpClient();
|
||||
client.Config.CustomStream = typeof(GnuTlsStream);
|
||||
client.Config.RetryAttempts = 3;
|
||||
if ((settings.Username.Length > 0) || (settings.Password.Length > 0))
|
||||
client.Credentials = new NetworkCredential(settings.Username, settings.Password);
|
||||
|
||||
@@ -11,7 +11,8 @@ namespace keepass2android.Io
|
||||
public interface IOfflineSwitchable
|
||||
{
|
||||
bool IsOffline { get; set; }
|
||||
}
|
||||
bool TriggerWarningWhenFallingBackToCache { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encapsulates another IFileStorage. Allows to switch to offline mode by throwing
|
||||
@@ -21,8 +22,9 @@ namespace keepass2android.Io
|
||||
{
|
||||
private readonly IFileStorage _baseStorage;
|
||||
public bool IsOffline { get; set; }
|
||||
public bool TriggerWarningWhenFallingBackToCache { get; set; }
|
||||
|
||||
public OfflineSwitchableFileStorage(IFileStorage baseStorage)
|
||||
public OfflineSwitchableFileStorage(IFileStorage baseStorage)
|
||||
{
|
||||
_baseStorage = baseStorage;
|
||||
}
|
||||
|
||||
@@ -1,617 +0,0 @@
|
||||
#if !NoNet
|
||||
using System.Net;
|
||||
using Android.Content;
|
||||
using keepass2android;
|
||||
using keepass2android.Io;
|
||||
using KeePassLib.Serialization;
|
||||
using SMBLibrary.Client;
|
||||
using SMBLibrary;
|
||||
using FileAttributes = SMBLibrary.FileAttributes;
|
||||
using KeePassLib.Utility;
|
||||
using Java.Nio.FileNio;
|
||||
|
||||
namespace Kp2aBusinessLogic.Io
|
||||
{
|
||||
public class SmbFileStorage : IFileStorage
|
||||
{
|
||||
public IEnumerable<string> SupportedProtocols
|
||||
{
|
||||
get { yield return "smb"; }
|
||||
}
|
||||
|
||||
public bool UserShouldBackup
|
||||
{
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
public void Delete(IOConnectionInfo ioc)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool CheckForFileChangeFast(IOConnectionInfo ioc, string previousFileVersion)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public string GetCurrentFileVersionFast(IOConnectionInfo ioc)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public struct SmbConnectionInfo
|
||||
{
|
||||
public string Host;
|
||||
public string Username;
|
||||
public string Password;
|
||||
public string? Domain;
|
||||
public string? Share;
|
||||
public string? LocalPath;
|
||||
|
||||
public static SmbConnectionInfo FromUrlAndCredentials(string url, string username, string password, string? domain)
|
||||
{
|
||||
string userDomain = username;
|
||||
if (domain != null)
|
||||
{
|
||||
userDomain = domain + "\\" + username;
|
||||
}
|
||||
if (url.StartsWith("smb://"))
|
||||
{
|
||||
url = url.Substring(6);
|
||||
}
|
||||
|
||||
if (url.StartsWith("\\\\"))
|
||||
{
|
||||
url = url.Substring(2);
|
||||
}
|
||||
|
||||
url = url.Replace("\\", "/");
|
||||
|
||||
string fullPath = "smb://" + WebUtility.UrlEncode(userDomain) + ":" + WebUtility.UrlEncode(password) + "@" + url;
|
||||
return new SmbConnectionInfo(new IOConnectionInfo() { Path = fullPath} );
|
||||
}
|
||||
|
||||
|
||||
public SmbConnectionInfo(IOConnectionInfo ioc)
|
||||
{
|
||||
string fullpath = ioc.Path;
|
||||
if (!fullpath.StartsWith("smb://"))
|
||||
{
|
||||
throw new Exception("Invalid smb path!");
|
||||
}
|
||||
|
||||
fullpath = fullpath.Substring(6);
|
||||
string[] authAndPath = fullpath.Split('@');
|
||||
if (authAndPath.Length != 2)
|
||||
{
|
||||
throw new Exception("Invalid smb path!");
|
||||
}
|
||||
|
||||
string[] userAndPwd = authAndPath[0].Split(':');
|
||||
if (userAndPwd.Length != 2)
|
||||
{
|
||||
throw new Exception("Invalid smb path!");
|
||||
}
|
||||
|
||||
string[] pathParts = authAndPath[1].Split('/');
|
||||
if (pathParts.Length < 1)
|
||||
{
|
||||
throw new Exception("Invalid smb path!");
|
||||
}
|
||||
|
||||
Host = pathParts[0];
|
||||
if (pathParts.Length > 1)
|
||||
{
|
||||
Share = pathParts[1];
|
||||
}
|
||||
LocalPath = String.Join("/", pathParts.Skip(2));
|
||||
if (LocalPath.EndsWith("/"))
|
||||
{
|
||||
LocalPath = LocalPath.Substring(0, LocalPath.Length - 1);
|
||||
}
|
||||
|
||||
Username = WebUtility.UrlDecode(userAndPwd[0]);
|
||||
if (Username.Contains("\\"))
|
||||
{
|
||||
string[] domainAndUser = Username.Split('\\');
|
||||
Domain = domainAndUser[0];
|
||||
Username = domainAndUser[1];
|
||||
}
|
||||
else Domain = null;
|
||||
|
||||
Password = WebUtility.UrlDecode(userAndPwd[1]);
|
||||
}
|
||||
|
||||
public string ToPath()
|
||||
{
|
||||
string domainUser = Username;
|
||||
if (Domain != null)
|
||||
{
|
||||
domainUser = Domain + "\\" + Username;
|
||||
}
|
||||
|
||||
return "smb://" + WebUtility.UrlEncode(domainUser) + ":" + WebUtility.UrlEncode(Password) + "@" + Host +
|
||||
"/" + Share + "/" + LocalPath;
|
||||
}
|
||||
|
||||
public string GetPathWithoutCredentials()
|
||||
{
|
||||
return "smb://" + Host + "/" + Share + "/" + LocalPath;
|
||||
}
|
||||
|
||||
public string GetLocalSmbPath()
|
||||
{
|
||||
return LocalPath?.Replace("/", "\\") ?? "";
|
||||
}
|
||||
|
||||
public SmbConnectionInfo GetParent()
|
||||
{
|
||||
SmbConnectionInfo parent = new SmbConnectionInfo
|
||||
{
|
||||
Host = Host,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
Domain = Domain,
|
||||
Share = Share
|
||||
};
|
||||
string[] pathParts = LocalPath?.Split('/') ?? [];
|
||||
if (pathParts.Length > 0)
|
||||
{
|
||||
parent.LocalPath = string.Join("/", pathParts.Take(pathParts.Length - 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
parent.LocalPath = "";
|
||||
parent.Share = "";
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
|
||||
public string Stem()
|
||||
{
|
||||
return LocalPath?.Split('/').Last() ?? "";
|
||||
}
|
||||
|
||||
|
||||
public SmbConnectionInfo GetChild(string childName)
|
||||
{
|
||||
SmbConnectionInfo child = new SmbConnectionInfo();
|
||||
child.Host = Host;
|
||||
child.Username = Username;
|
||||
child.Password = Password;
|
||||
child.Domain = Domain;
|
||||
if (string.IsNullOrEmpty(Share))
|
||||
{
|
||||
child.Share = childName;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
child.Share = Share;
|
||||
var pathPartsList = LocalPath?.Split('/').Where(p => !string.IsNullOrEmpty(p)).ToList() ?? [];
|
||||
pathPartsList.Add(childName);
|
||||
child.LocalPath = string.Join("/", pathPartsList);
|
||||
}
|
||||
|
||||
return child;
|
||||
}
|
||||
|
||||
public string ToDisplayString()
|
||||
{
|
||||
return "smb://" + Host + "/" + Share + "/" + LocalPath;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class SmbConnection: IDisposable
|
||||
{
|
||||
public SmbConnection(SmbConnectionInfo info)
|
||||
{
|
||||
_isLoggedIn = false;
|
||||
var isConnected = Client.Connect(info.Host, SMBTransportType.DirectTCPTransport);
|
||||
if (!isConnected)
|
||||
{
|
||||
throw new Exception($"Failed to connect to SMB server {info.Host}");
|
||||
}
|
||||
|
||||
var status = Client.Login(info.Domain ?? string.Empty, info.Username, info.Password);
|
||||
if (status != NTStatus.STATUS_SUCCESS)
|
||||
{
|
||||
throw new Exception($"Failed to login to SMB as {info.Username}");
|
||||
}
|
||||
|
||||
_isLoggedIn = true;
|
||||
|
||||
if (!string.IsNullOrEmpty(info.Share))
|
||||
{
|
||||
FileStore = Client.TreeConnect(info.Share, out status);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public readonly SMB2Client Client = new SMB2Client();
|
||||
|
||||
|
||||
public readonly ISMBFileStore? FileStore;
|
||||
private readonly bool _isLoggedIn;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
FileStore?.Disconnect();
|
||||
|
||||
if (_isLoggedIn)
|
||||
Client.Logoff();
|
||||
|
||||
if (!Client.IsConnected) return;
|
||||
Client.Disconnect();
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Stream OpenFileForRead(IOConnectionInfo ioc)
|
||||
{
|
||||
|
||||
SmbConnectionInfo info = new SmbConnectionInfo(ioc);
|
||||
using SmbConnection conn = new SmbConnection(info);
|
||||
|
||||
if (conn.FileStore == null)
|
||||
{
|
||||
throw new Exception($"Failed to read to {info.GetPathWithoutCredentials()}");
|
||||
}
|
||||
|
||||
|
||||
NTStatus status = conn.FileStore.CreateFile(out var fileHandle, out _, info.GetLocalSmbPath(),
|
||||
AccessMask.GENERIC_READ | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.Read,
|
||||
CreateDisposition.FILE_OPEN,
|
||||
CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null);
|
||||
|
||||
if (status != NTStatus.STATUS_SUCCESS)
|
||||
{
|
||||
throw new Exception($"Failed to open file {info.LocalPath}");
|
||||
}
|
||||
|
||||
var stream = new MemoryStream();
|
||||
long bytesRead = 0;
|
||||
while (true)
|
||||
{
|
||||
status = conn.FileStore.ReadFile(out var data, fileHandle, bytesRead, (int)conn.Client.MaxReadSize);
|
||||
if (status != NTStatus.STATUS_SUCCESS && status != NTStatus.STATUS_END_OF_FILE)
|
||||
{
|
||||
throw new Exception("Failed to read from file");
|
||||
}
|
||||
|
||||
if (status == NTStatus.STATUS_END_OF_FILE || data.Length == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
bytesRead += data.Length;
|
||||
stream.Write(data, 0, data.Length);
|
||||
}
|
||||
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
return stream;
|
||||
}
|
||||
|
||||
|
||||
class SmbFileStorageWriteTransaction : IWriteTransaction
|
||||
{
|
||||
private bool UseFileTransaction { get; }
|
||||
private readonly string _path;
|
||||
private readonly string _uploadPath;
|
||||
private readonly SmbFileStorage _fileStorage;
|
||||
private MemoryStream? _memoryStream;
|
||||
|
||||
public SmbFileStorageWriteTransaction(string path, SmbFileStorage fileStorage, bool useFileTransaction)
|
||||
{
|
||||
UseFileTransaction = useFileTransaction;
|
||||
_path = path;
|
||||
if (useFileTransaction)
|
||||
{
|
||||
_uploadPath = _path + Guid.NewGuid().ToString().Substring(0, 8) + ".tmp";
|
||||
}
|
||||
else
|
||||
{
|
||||
_uploadPath = _path;
|
||||
}
|
||||
|
||||
|
||||
_fileStorage = fileStorage;
|
||||
_memoryStream = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_memoryStream?.Dispose();
|
||||
}
|
||||
|
||||
public Stream OpenFile()
|
||||
{
|
||||
_memoryStream = new MemoryStream();
|
||||
return _memoryStream;
|
||||
}
|
||||
|
||||
public void CommitWrite()
|
||||
{
|
||||
_fileStorage.UploadData(new MemoryStream(_memoryStream!.ToArray()), new SmbConnectionInfo(new IOConnectionInfo() { Path = _uploadPath}));
|
||||
if (UseFileTransaction)
|
||||
{
|
||||
SmbConnectionInfo uploadPath = new SmbConnectionInfo(new IOConnectionInfo() { Path = _uploadPath });
|
||||
SmbConnectionInfo finalPath = new SmbConnectionInfo(new IOConnectionInfo() { Path = _path });
|
||||
_fileStorage.RenameFile(uploadPath, finalPath);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void RenameFile(SmbConnectionInfo fromPath, SmbConnectionInfo toPath)
|
||||
{
|
||||
using var connection = new SmbConnection(fromPath);
|
||||
|
||||
// Open existing file
|
||||
var status = connection.FileStore!.CreateFile(out var handle, out _, fromPath.GetLocalSmbPath(), AccessMask.MAXIMUM_ALLOWED, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, null);
|
||||
if (status != NTStatus.STATUS_SUCCESS)
|
||||
throw new Exception($"Failed to open {fromPath.LocalPath} for renaming!");
|
||||
|
||||
FileRenameInformationType2 renameInfo = new FileRenameInformationType2
|
||||
{
|
||||
FileName = toPath.GetLocalSmbPath(),
|
||||
ReplaceIfExists = true
|
||||
};
|
||||
connection.FileStore.SetFileInformation(handle, renameInfo);
|
||||
connection.FileStore.CloseFile(handle);
|
||||
|
||||
}
|
||||
|
||||
private void UploadData(Stream data, SmbConnectionInfo uploadPath)
|
||||
{
|
||||
using var connection = new SmbConnection(uploadPath);
|
||||
var status = connection.FileStore!.CreateFile(out var fileHandle, out _, uploadPath.GetLocalSmbPath(), AccessMask.GENERIC_WRITE | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.None, CreateDisposition.FILE_CREATE, CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null);
|
||||
if (status == NTStatus.STATUS_OBJECT_NAME_COLLISION)
|
||||
status = connection.FileStore!.CreateFile(out fileHandle, out _, uploadPath.GetLocalSmbPath(), AccessMask.GENERIC_WRITE | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.None, CreateDisposition.FILE_OVERWRITE, CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null);
|
||||
if (status != NTStatus.STATUS_SUCCESS)
|
||||
{
|
||||
throw new Exception($"Failed to open {uploadPath.LocalPath} for writing!");
|
||||
}
|
||||
|
||||
long writeOffset = 0;
|
||||
while (data.Position < data.Length)
|
||||
{
|
||||
byte[] buffer = new byte[(int)connection.Client.MaxWriteSize];
|
||||
int bytesRead = data.Read(buffer, 0, buffer.Length);
|
||||
if (bytesRead < (int)connection.Client.MaxWriteSize)
|
||||
{
|
||||
Array.Resize(ref buffer, bytesRead);
|
||||
}
|
||||
|
||||
status = connection.FileStore.WriteFile(out _, fileHandle, writeOffset, buffer);
|
||||
if (status != NTStatus.STATUS_SUCCESS)
|
||||
{
|
||||
throw new Exception("Failed to write to file");
|
||||
}
|
||||
writeOffset += bytesRead;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public IWriteTransaction OpenWriteTransaction(IOConnectionInfo ioc, bool useFileTransaction)
|
||||
{
|
||||
return new SmbFileStorageWriteTransaction(ioc.Path, this, useFileTransaction);
|
||||
}
|
||||
|
||||
public string GetFilenameWithoutPathAndExt(IOConnectionInfo ioc)
|
||||
{
|
||||
return UrlUtil.StripExtension(
|
||||
UrlUtil.GetFileName(ioc.Path));
|
||||
|
||||
}
|
||||
|
||||
public string GetFileExtension(IOConnectionInfo ioc)
|
||||
{
|
||||
return UrlUtil.GetExtension(ioc.Path);
|
||||
}
|
||||
|
||||
public bool RequiresCredentials(IOConnectionInfo ioc)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public void CreateDirectory(IOConnectionInfo ioc, string newDirName)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static IEnumerable<FileDescription> ListShares(SmbConnection conn, SmbConnectionInfo parent)
|
||||
{
|
||||
foreach (string share in conn.Client.ListShares(out _))
|
||||
{
|
||||
yield return new FileDescription()
|
||||
{
|
||||
CanRead = true,
|
||||
CanWrite = true,
|
||||
DisplayName = share,
|
||||
IsDirectory = true,
|
||||
Path = parent.GetChild(share).ToPath()
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public IEnumerable<FileDescription> ListContents(IOConnectionInfo ioc)
|
||||
{
|
||||
List<FileDescription> result = [];
|
||||
SmbConnectionInfo info = new SmbConnectionInfo(ioc);
|
||||
using SmbConnection conn = new SmbConnection(info);
|
||||
if (string.IsNullOrEmpty(info.Share))
|
||||
{
|
||||
var shares = ListShares(conn, info).ToList();
|
||||
return shares;
|
||||
}
|
||||
|
||||
NTStatus status = conn.FileStore!.CreateFile(out var directoryHandle, out _, info.GetLocalSmbPath(), AccessMask.GENERIC_READ, FileAttributes.Directory, ShareAccess.Read | ShareAccess.Write, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null);
|
||||
if (status == NTStatus.STATUS_SUCCESS)
|
||||
{
|
||||
conn.FileStore.QueryDirectory(out List<QueryDirectoryFileInformation> fileList, directoryHandle, "*", FileInformationClass.FileDirectoryInformation);
|
||||
foreach (var fi in fileList)
|
||||
{
|
||||
var fileDirectoryInformation = fi as FileDirectoryInformation;
|
||||
if (fileDirectoryInformation == null)
|
||||
continue;
|
||||
|
||||
if (fileDirectoryInformation.FileName is "." or "..")
|
||||
continue;
|
||||
|
||||
var fileDescription = FileDescriptionConvert(ioc, fileDirectoryInformation);
|
||||
|
||||
result.Add(fileDescription);
|
||||
}
|
||||
conn.FileStore.CloseFile(directoryHandle);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private FileDescription FileDescriptionConvert(IOConnectionInfo parentIoc,
|
||||
FileDirectoryInformation fileDirectoryInformation)
|
||||
{
|
||||
FileDescription fileDescription = new FileDescription
|
||||
{
|
||||
CanRead = true,
|
||||
CanWrite = true,
|
||||
IsDirectory = (fileDirectoryInformation.FileAttributes & FileAttributes.Directory) != 0,
|
||||
DisplayName = fileDirectoryInformation.FileName
|
||||
};
|
||||
fileDescription.Path = CreateFilePath(parentIoc.Path, fileDescription.DisplayName);
|
||||
fileDescription.LastModified = fileDirectoryInformation.LastWriteTime;
|
||||
|
||||
fileDescription.SizeInBytes = fileDirectoryInformation.EndOfFile;
|
||||
return fileDescription;
|
||||
}
|
||||
|
||||
public FileDescription GetFileDescription(IOConnectionInfo ioc)
|
||||
{
|
||||
SmbConnectionInfo info = new SmbConnectionInfo(ioc);
|
||||
|
||||
if (string.IsNullOrEmpty(info.Share))
|
||||
{
|
||||
return new FileDescription
|
||||
{
|
||||
CanRead = true, CanWrite = true,
|
||||
DisplayName = info.Host,
|
||||
IsDirectory = true,
|
||||
Path = info.ToPath()
|
||||
};
|
||||
}
|
||||
|
||||
using SmbConnection conn = new SmbConnection(info);
|
||||
NTStatus status = conn.FileStore!.CreateFile(out var directoryHandle, out _, info.GetParent().GetLocalSmbPath(), AccessMask.GENERIC_READ, FileAttributes.Directory, ShareAccess.Read | ShareAccess.Write, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null);
|
||||
if (status != NTStatus.STATUS_SUCCESS) throw new Exception($"Failed to query details for {info.LocalPath}");
|
||||
conn.FileStore.QueryDirectory(out List<QueryDirectoryFileInformation> fileList, directoryHandle, info.Stem(), FileInformationClass.FileDirectoryInformation);
|
||||
foreach (var fi in fileList)
|
||||
{
|
||||
var fileDirectoryInformation = fi as FileDirectoryInformation;
|
||||
if (fileDirectoryInformation == null)
|
||||
continue;
|
||||
|
||||
if (fileDirectoryInformation.FileName is "." or "..")
|
||||
continue;
|
||||
|
||||
return FileDescriptionConvert(ioc, fileDirectoryInformation);
|
||||
|
||||
|
||||
}
|
||||
conn.FileStore.CloseFile(directoryHandle);
|
||||
|
||||
throw new Exception($"Failed to query details for {info.LocalPath}");
|
||||
}
|
||||
|
||||
public bool RequiresSetup(IOConnectionInfo ioConnection)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public string IocToPath(IOConnectionInfo ioc)
|
||||
{
|
||||
return ioc.Path;
|
||||
}
|
||||
|
||||
public void StartSelectFile(IFileStorageSetupInitiatorActivity activity, bool isForSave, int requestCode, string protocolId)
|
||||
{
|
||||
activity.PerformManualFileSelect(isForSave, requestCode, protocolId);
|
||||
|
||||
}
|
||||
|
||||
public void PrepareFileUsage(IFileStorageSetupInitiatorActivity activity, IOConnectionInfo ioc, int requestCode,
|
||||
bool alwaysReturnSuccess)
|
||||
{
|
||||
Intent intent = new Intent();
|
||||
activity.IocToIntent(intent, ioc);
|
||||
activity.OnImmediateResult(requestCode, (int)FileStorageResults.FileUsagePrepared, intent);
|
||||
}
|
||||
|
||||
public void PrepareFileUsage(Context ctx, IOConnectionInfo ioc)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void OnCreate(IFileStorageSetupActivity activity, Bundle savedInstanceState)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void OnResume(IFileStorageSetupActivity activity)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void OnStart(IFileStorageSetupActivity activity)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void OnActivityResult(IFileStorageSetupActivity activity, int requestCode, int resultCode, Intent data)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public string GetDisplayName(IOConnectionInfo ioc)
|
||||
{
|
||||
return new SmbConnectionInfo(ioc).ToDisplayString();
|
||||
}
|
||||
|
||||
public string CreateFilePath(string parent, string newFilename)
|
||||
{
|
||||
return new SmbConnectionInfo(new IOConnectionInfo() { Path = parent}).GetChild(newFilename).ToPath();
|
||||
}
|
||||
|
||||
public IOConnectionInfo GetParentPath(IOConnectionInfo ioc)
|
||||
{
|
||||
SmbConnectionInfo connectionInfo = new SmbConnectionInfo(ioc);
|
||||
return new IOConnectionInfo() { Path = connectionInfo.GetParent().ToPath() };
|
||||
}
|
||||
|
||||
public IOConnectionInfo GetFilePath(IOConnectionInfo folderPath, string filename)
|
||||
{
|
||||
return new IOConnectionInfo() { Path = CreateFilePath(folderPath.Path, filename)};
|
||||
}
|
||||
|
||||
public bool IsPermanentLocation(IOConnectionInfo ioc)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool IsReadOnly(IOConnectionInfo ioc, OptionalOut<UiStringKey> reason = null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -6,12 +6,10 @@ using System.Text;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Android.Preferences;
|
||||
using Android.Runtime;
|
||||
using Android.Views;
|
||||
using Android.Widget;
|
||||
#if !NoNet && !EXCLUDE_JAVAFILESTORAGE
|
||||
|
||||
using Keepass2android.Javafilestorage;
|
||||
#endif
|
||||
using KeePassLib.Serialization;
|
||||
@@ -21,15 +19,9 @@ namespace keepass2android.Io
|
||||
#if !NoNet && !EXCLUDE_JAVAFILESTORAGE
|
||||
public class WebDavFileStorage: JavaFileStorage
|
||||
{
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly WebDavStorage baseWebdavStorage;
|
||||
|
||||
public WebDavFileStorage(IKp2aApp app, int chunkSize) : base(new Keepass2android.Javafilestorage.WebDavStorage(app.CertificateErrorHandler, chunkSize), app)
|
||||
{
|
||||
_app = app;
|
||||
baseWebdavStorage = (WebDavStorage)Jfs;
|
||||
|
||||
}
|
||||
public WebDavFileStorage(IKp2aApp app) : base(new Keepass2android.Javafilestorage.WebDavStorage(app.CertificateErrorHandler), app)
|
||||
{
|
||||
}
|
||||
|
||||
public override IEnumerable<string> SupportedProtocols
|
||||
{
|
||||
@@ -83,15 +75,6 @@ namespace keepass2android.Io
|
||||
}
|
||||
return base.IocToPath(ioc);
|
||||
}
|
||||
|
||||
|
||||
public override IWriteTransaction OpenWriteTransaction(IOConnectionInfo ioc, bool useFileTransaction)
|
||||
{
|
||||
baseWebdavStorage.SetUploadChunkSize(_app.WebDavChunkedUploadSize);
|
||||
return base.OpenWriteTransaction(ioc, useFileTransaction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,48 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<DefineConstants Condition="'$(Flavor)'=='NoNet'">NO_QR_SCANNER;EXCLUDE_JAVAFILESTORAGE;NoNet</DefineConstants>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="Resources\" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentFTP" Version="52.1.0" Condition="'$(Flavor)'!='NoNet'"/>
|
||||
<PackageReference Include="FluentFTP.GnuTLS" Version="1.0.37" Condition="'$(Flavor)'!='NoNet'"/>
|
||||
<PackageReference Include="MegaApiClient" Version="1.10.4" Condition="'$(Flavor)'!='NoNet'"/>
|
||||
<PackageReference Include="Microsoft.Graph" Version="5.68.0" Condition="'$(Flavor)'!='NoNet'"/>
|
||||
<PackageReference Include="Microsoft.Identity.Client" Version="4.67.1" Condition="'$(Flavor)'!='NoNet'"/>
|
||||
<PackageReference Include="SMBLibrary" Version="1.5.4" Condition="'$(Flavor)'!='NoNet'"/>
|
||||
<PackageReference Include="FluentFTP" Version="51.1.0" />
|
||||
<PackageReference Include="MegaApiClient" Version="1.10.4" />
|
||||
<PackageReference Include="Microsoft.Graph" Version="5.68.0" />
|
||||
<PackageReference Include="Microsoft.Identity.Client" Version="4.67.1" />
|
||||
<PackageReference Include="Xamarin.AndroidX.Browser" Version="1.8.0" />
|
||||
<PackageReference Include="Xamarin.AndroidX.Core" Version="1.13.1.5" />
|
||||
<PackageReference Include="Xamarin.Google.Android.Material" Version="1.11.0.3" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndroidFileChooserBinding\AndroidFileChooserBinding.csproj" />
|
||||
<ProjectReference Include="..\JavaFileStorageBindings\JavaFileStorageBindings.csproj" Condition="'$(Flavor)'!='NoNet'" />
|
||||
<ProjectReference Include="..\JavaFileStorageBindings\JavaFileStorageBindings.csproj" />
|
||||
<ProjectReference Include="..\KeePassLib2Android\KeePassLib2Android.csproj" />
|
||||
<ProjectReference Include="..\KP2AKdbLibraryBinding\KP2AKdbLibraryBinding.csproj" />
|
||||
<ProjectReference Include="..\TwofishCipher\TwofishCipher.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
<None Remove="Io/DropboxFileStorageKeysDummy.cs" />
|
||||
<Compile Remove="Io/DropboxFileStorageKeysDummy.cs" />
|
||||
<Content Remove="Io/DropboxFileStorageKeysDummy.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(Flavor)'=='NoNet'">
|
||||
<None Remove="Io/OneDrive2FileStorage.cs" />
|
||||
<Compile Remove="Io/OneDrive2FileStorage.cs" />
|
||||
<Content Remove="Io/OneDrive2FileStorage.cs" />
|
||||
<None Remove="Io/MegaFileStorage.cs" />
|
||||
<Compile Remove="Io/MegaFileStorage.cs" />
|
||||
<Content Remove="Io/MegaFileStorage.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="Io/GenerateSecrets.targets" />
|
||||
<ItemGroup>
|
||||
<Compile Include="Io/DropboxFileStorage.g.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
</Project>
|
||||
239
src/Kp2aBusinessLogic/OperationRunner.cs
Normal file
239
src/Kp2aBusinessLogic/OperationRunner.cs
Normal file
@@ -0,0 +1,239 @@
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using System.Threading.Tasks;
|
||||
using Thread = Java.Lang.Thread;
|
||||
|
||||
namespace keepass2android;
|
||||
|
||||
/// <summary>
|
||||
/// Allows to run tasks in the background. The UI is not blocked by the task. Tasks continue to run in the BackgroundSyncService if the app goes to background while tasks are active.
|
||||
/// </summary>
|
||||
public class OperationRunner
|
||||
{
|
||||
//singleton instance
|
||||
private static OperationRunner _instance = null;
|
||||
|
||||
public static OperationRunner Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
_instance = new OperationRunner();
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
void Initialize(IKp2aApp app)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public struct OperationWithMetadata
|
||||
{
|
||||
public OperationWithMetadata()
|
||||
{
|
||||
Operation = null;
|
||||
}
|
||||
|
||||
public OperationWithFinishHandler Operation { get; set; }
|
||||
public bool RunBlocking { get; set; } = false;
|
||||
}
|
||||
|
||||
public ProgressUiAsStatusLoggerAdapter StatusLogger => _statusLogger;
|
||||
|
||||
private OperationRunner()
|
||||
{
|
||||
//private constructor
|
||||
}
|
||||
|
||||
private readonly Queue<OperationWithMetadata> _taskQueue = new Queue<OperationWithMetadata>();
|
||||
private readonly object _taskQueueLock = new object();
|
||||
private Java.Lang.Thread? _thread = null;
|
||||
private OperationWithMetadata? _currentlyRunningTask = null;
|
||||
private ProgressUiAsStatusLoggerAdapter _statusLogger = null;
|
||||
private IProgressDialog _progressDialog;
|
||||
private IKp2aApp _app;
|
||||
|
||||
public void Run(IKp2aApp app, OperationWithFinishHandler operation, bool runBlocking = false)
|
||||
{
|
||||
lock (Instance._taskQueueLock)
|
||||
{
|
||||
_taskQueue.Enqueue(new OperationWithMetadata(){ Operation = operation, RunBlocking = runBlocking});
|
||||
operation.SetStatusLogger(_statusLogger);
|
||||
|
||||
// Start thread to run the task (unless it's already running)
|
||||
if (_thread == null)
|
||||
{
|
||||
_statusLogger.StartLogging("", false);
|
||||
_thread = new Java.Lang.Thread(() =>
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
|
||||
lock (_taskQueueLock)
|
||||
{
|
||||
if (!_taskQueue.Any())
|
||||
{
|
||||
_thread = null;
|
||||
_statusLogger.EndLogging();
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
_currentlyRunningTask = _taskQueue.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
if (_currentlyRunningTask.Value.RunBlocking)
|
||||
{
|
||||
app.UiThreadHandler.Post(
|
||||
() =>
|
||||
{
|
||||
TrySetupProgressDialog();
|
||||
});
|
||||
}
|
||||
|
||||
var originalFinishedHandler = _currentlyRunningTask.Value.Operation.operationFinishedHandler;
|
||||
_currentlyRunningTask.Value.Operation.operationFinishedHandler = new ActionOnOperationFinished(app, (
|
||||
(success, message, context) =>
|
||||
{
|
||||
if (_currentlyRunningTask?.RunBlocking == true)
|
||||
{
|
||||
_app.UiThreadHandler.Post(() =>
|
||||
{
|
||||
_progressDialog?.Dismiss();
|
||||
}
|
||||
);
|
||||
}
|
||||
_currentlyRunningTask = null;
|
||||
|
||||
}), originalFinishedHandler);
|
||||
_currentlyRunningTask.Value.Operation.Run();
|
||||
|
||||
while (_currentlyRunningTask != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Kp2aLog.Log("Thread interrupted.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
_thread.Start();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private bool TrySetupProgressDialog()
|
||||
{
|
||||
string currentMessage = "Initializing...";
|
||||
string currentSubmessage = "";
|
||||
|
||||
if (_statusLogger != null)
|
||||
{
|
||||
currentMessage = _statusLogger.LastMessage;
|
||||
currentSubmessage = _statusLogger.LastSubMessage;
|
||||
}
|
||||
|
||||
if (_progressDialog != null)
|
||||
{
|
||||
var pd = _progressDialog;
|
||||
_app.UiThreadHandler.Post(() =>
|
||||
{
|
||||
pd.Dismiss();
|
||||
});
|
||||
}
|
||||
|
||||
// Show process dialog
|
||||
_progressDialog = _app.CreateProgressDialog(_app.ActiveContext);
|
||||
if (_progressDialog == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
var progressUi = new ProgressDialogUi(_app, _app.UiThreadHandler, _progressDialog);
|
||||
_statusLogger.SetNewProgressUi(progressUi);
|
||||
|
||||
_statusLogger.StartLogging("", false);
|
||||
_statusLogger.UpdateMessage(currentMessage);
|
||||
_statusLogger.UpdateSubMessage(currentSubmessage);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SetNewActiveContext(IKp2aApp app)
|
||||
{
|
||||
_app = app;
|
||||
Context? context = app.ActiveContext;
|
||||
bool isAppContext = context == null || (context.ApplicationContext == context);
|
||||
lock (_taskQueueLock)
|
||||
{
|
||||
if (isAppContext && _thread != null)
|
||||
{
|
||||
//this will register the service as new active context (see BackgroundSyncService.OnStartCommand())
|
||||
app.StartBackgroundSyncService();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_currentlyRunningTask?.RunBlocking == true && (context is Activity { IsFinishing: false, IsDestroyed:false}))
|
||||
{
|
||||
app.UiThreadHandler.Post(() =>
|
||||
{
|
||||
TrySetupProgressDialog();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
var progressUi = (context as IProgressUiProvider)?.ProgressUi;
|
||||
if (_statusLogger == null)
|
||||
{
|
||||
_statusLogger = new ProgressUiAsStatusLoggerAdapter(progressUi, app);
|
||||
}
|
||||
else
|
||||
{
|
||||
_statusLogger.SetNewProgressUi(progressUi);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var task in _taskQueue.Concat(_currentlyRunningTask == null ?
|
||||
new List<OperationWithMetadata>() : [_currentlyRunningTask.Value])
|
||||
)
|
||||
{
|
||||
task.Operation.SetStatusLogger(_statusLogger);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void CancelAll()
|
||||
{
|
||||
lock (_taskQueueLock)
|
||||
{
|
||||
if (_thread != null)
|
||||
{
|
||||
_thread.Interrupt();
|
||||
_thread = null;
|
||||
_statusLogger?.EndLogging();
|
||||
}
|
||||
|
||||
_taskQueue.Clear();
|
||||
_currentlyRunningTask = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,116 +22,152 @@ using KeePassLib.Interfaces;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
/// <summary>
|
||||
/// StatusLogger implementation which shows the progress in a progress dialog
|
||||
/// </summary>
|
||||
public class ProgressDialogStatusLogger: IStatusLogger {
|
||||
public interface IKp2aStatusLogger : IStatusLogger
|
||||
{
|
||||
void UpdateMessage(UiStringKey stringKey);
|
||||
string LastMessage { get; }
|
||||
string LastSubMessage { get; }
|
||||
}
|
||||
|
||||
public interface IProgressUi
|
||||
{
|
||||
void Show();
|
||||
void Hide();
|
||||
void UpdateMessage(String message);
|
||||
void UpdateSubMessage(String submessage);
|
||||
}
|
||||
|
||||
public interface IProgressUiProvider
|
||||
{
|
||||
IProgressUi? ProgressUi { get; }
|
||||
}
|
||||
|
||||
|
||||
public class Kp2aNullStatusLogger : IKp2aStatusLogger
|
||||
{
|
||||
public void StartLogging(string strOperation, bool bWriteOperationToLog)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void EndLogging()
|
||||
{
|
||||
}
|
||||
|
||||
public bool SetProgress(uint uPercent)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool SetText(string strNewText, LogStatusType lsType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
private string _lastMessage;
|
||||
private string _lastSubMessage;
|
||||
public void UpdateMessage(string message)
|
||||
{
|
||||
_lastMessage = message;
|
||||
}
|
||||
|
||||
public void UpdateSubMessage(string submessage)
|
||||
{
|
||||
_lastSubMessage = submessage;
|
||||
}
|
||||
|
||||
public bool ContinueWork()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void UpdateMessage(UiStringKey stringKey)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public string LastMessage { get { return _lastMessage; } }
|
||||
public string LastSubMessage { get { return _lastSubMessage; } }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// StatusLogger implementation which shows the progress in a progress dialog
|
||||
/// </summary>
|
||||
public class ProgressDialogUi: IProgressUi
|
||||
{
|
||||
private readonly IProgressDialog _progressDialog;
|
||||
readonly IKp2aApp _app;
|
||||
|
||||
private readonly Handler _handler;
|
||||
private string _message = "";
|
||||
private string _submessage;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
public String SubMessage => _submessage;
|
||||
public String Message => _message;
|
||||
public String LastSubMessage => _submessage;
|
||||
public String LastMessage => _message;
|
||||
|
||||
public ProgressDialogStatusLogger() {
|
||||
|
||||
}
|
||||
|
||||
public ProgressDialogStatusLogger(IKp2aApp app, Handler handler, IProgressDialog pd) {
|
||||
_app = app;
|
||||
public ProgressDialogUi(IKp2aApp app, Handler handler, IProgressDialog pd)
|
||||
{
|
||||
_app = app;
|
||||
_progressDialog = pd;
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public void UpdateMessage(UiStringKey stringKey) {
|
||||
if (_app != null)
|
||||
UpdateMessage(_app.GetResourceString(stringKey));
|
||||
}
|
||||
|
||||
public void UpdateMessage (String message)
|
||||
{
|
||||
Kp2aLog.Log("status message: " + message);
|
||||
public void UpdateSubMessage(String submessage)
|
||||
{
|
||||
Kp2aLog.Log("status submessage: " + submessage);
|
||||
_submessage = submessage;
|
||||
if (_app != null && _progressDialog != null && _handler != null)
|
||||
{
|
||||
_handler.Post(() =>
|
||||
{
|
||||
if (!String.IsNullOrEmpty(submessage))
|
||||
{
|
||||
_progressDialog.SetMessage(_message + " (" + submessage + ")");
|
||||
}
|
||||
else
|
||||
{
|
||||
_progressDialog.SetMessage(_message);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public void Show()
|
||||
{
|
||||
_handler.Post(() =>
|
||||
{
|
||||
_progressDialog?.Show();
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public void Hide()
|
||||
{
|
||||
_handler.Post(() =>
|
||||
{
|
||||
_progressDialog?.Dismiss();
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
public void UpdateMessage(string message)
|
||||
{
|
||||
Kp2aLog.Log("status message: " + message);
|
||||
_message = message;
|
||||
if ( _app!= null && _progressDialog != null && _handler != null ) {
|
||||
_handler.Post(() => {_progressDialog.SetMessage(message); } );
|
||||
}
|
||||
}
|
||||
if (_app != null && _progressDialog != null && _handler != null)
|
||||
{
|
||||
_handler.Post(() =>
|
||||
{
|
||||
_progressDialog.SetMessage(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateSubMessage(String submessage)
|
||||
{
|
||||
Kp2aLog.Log("status submessage: " + submessage);
|
||||
_submessage = submessage;
|
||||
if (_app != null && _progressDialog != null && _handler != null)
|
||||
{
|
||||
_handler.Post(() =>
|
||||
{
|
||||
if (!String.IsNullOrEmpty(submessage))
|
||||
{
|
||||
_progressDialog.SetMessage(_message + " (" + submessage + ")");
|
||||
}
|
||||
else
|
||||
{
|
||||
_progressDialog.SetMessage(_message);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region IStatusLogger implementation
|
||||
|
||||
public void StartLogging (string strOperation, bool bWriteOperationToLog)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void EndLogging ()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public bool SetProgress (uint uPercent)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool SetText (string strNewText, LogStatusType lsType)
|
||||
{
|
||||
if (strNewText.StartsWith("KP2AKEY_"))
|
||||
{
|
||||
UiStringKey key;
|
||||
if (Enum.TryParse(strNewText.Substring("KP2AKEY_".Length), true, out key))
|
||||
{
|
||||
UpdateMessage(_app.GetResourceString(key), lsType);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
UpdateMessage(strNewText, lsType);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void UpdateMessage(string message, LogStatusType lsType)
|
||||
{
|
||||
if (lsType == LogStatusType.AdditionalInfo)
|
||||
{
|
||||
UpdateSubMessage(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
public bool ContinueWork ()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
/*
|
||||
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll. This file is based on Keepassdroid, Copyright Brian Pellin.
|
||||
|
||||
Keepass2Android is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Keepass2Android is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using Java.Lang;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to run a task while a progress dialog is shown
|
||||
/// </summary>
|
||||
public class ProgressTask
|
||||
{
|
||||
//for handling Activity recreation situations, we need access to the currently active task. It must hold that there is no more than one active task.
|
||||
private static ProgressTask _currentTask = null;
|
||||
|
||||
public static void SetNewActiveActivity(Activity activeActivity)
|
||||
{
|
||||
if (_currentTask != null)
|
||||
{
|
||||
_currentTask.ActiveActivity = activeActivity;
|
||||
}
|
||||
}
|
||||
public static void RemoveActiveActivity(Activity activity)
|
||||
{
|
||||
if ((_currentTask != null) && (_currentTask._activeActivity == activity))
|
||||
_currentTask.ActiveActivity = null;
|
||||
|
||||
}
|
||||
|
||||
public Activity ActiveActivity
|
||||
{
|
||||
get { return _activeActivity; }
|
||||
private set
|
||||
{
|
||||
if (_activeActivity != null && _activeActivity != _previouslyActiveActivity)
|
||||
{
|
||||
_previouslyActiveActivity = _activeActivity;
|
||||
|
||||
}
|
||||
_activeActivity = value;
|
||||
if (_task != null)
|
||||
_task.ActiveActivity = _activeActivity;
|
||||
if (_activeActivity != null)
|
||||
{
|
||||
SetupProgressDialog(_app);
|
||||
_progressDialog.Show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Activity PreviouslyActiveActivity
|
||||
{
|
||||
get { return _previouslyActiveActivity; }
|
||||
|
||||
}
|
||||
|
||||
private readonly Handler _handler;
|
||||
private readonly RunnableOnFinish _task;
|
||||
private IProgressDialog _progressDialog;
|
||||
private readonly IKp2aApp _app;
|
||||
private Java.Lang.Thread _thread;
|
||||
private Activity _activeActivity, _previouslyActiveActivity;
|
||||
private ProgressDialogStatusLogger _progressDialogStatusLogger;
|
||||
|
||||
public ProgressTask(IKp2aApp app, Activity activity, RunnableOnFinish task)
|
||||
{
|
||||
_activeActivity = activity;
|
||||
_task = task;
|
||||
_handler = app.UiThreadHandler;
|
||||
_app = app;
|
||||
|
||||
SetupProgressDialog(app);
|
||||
|
||||
// Set code to run when this is finished
|
||||
_task.OnFinishToRun = new AfterTask(activity, task.OnFinishToRun, _handler, this);
|
||||
|
||||
_task.SetStatusLogger(_progressDialogStatusLogger);
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void SetupProgressDialog(IKp2aApp app)
|
||||
{
|
||||
string currentMessage = "Initializing...";
|
||||
string currentSubmessage = "";
|
||||
|
||||
if (_progressDialogStatusLogger != null)
|
||||
{
|
||||
currentMessage = _progressDialogStatusLogger.Message;
|
||||
currentSubmessage = _progressDialogStatusLogger.SubMessage;
|
||||
}
|
||||
|
||||
if (_progressDialog != null)
|
||||
{
|
||||
var pd = _progressDialog;
|
||||
app.UiThreadHandler.Post(() =>
|
||||
{
|
||||
pd.Dismiss();
|
||||
});
|
||||
}
|
||||
|
||||
// Show process dialog
|
||||
_progressDialog = app.CreateProgressDialog(_activeActivity);
|
||||
_progressDialog.SetTitle(_app.GetResourceString(UiStringKey.progress_title));
|
||||
_progressDialogStatusLogger = new ProgressDialogStatusLogger(_app, _handler, _progressDialog);
|
||||
_progressDialogStatusLogger.UpdateMessage(currentMessage);
|
||||
_progressDialogStatusLogger.UpdateSubMessage(currentSubmessage);
|
||||
}
|
||||
|
||||
public void Run(bool allowOverwriteCurrentTask = false)
|
||||
{
|
||||
if ((!allowOverwriteCurrentTask) && (_currentTask != null))
|
||||
throw new System.Exception("Cannot start another ProgressTask while ProgressTask is already running! " + _task.GetType().Name + "/" + _currentTask._task.GetType().Name);
|
||||
_currentTask = this;
|
||||
|
||||
// Show process dialog
|
||||
_progressDialog.Show();
|
||||
|
||||
|
||||
// Start Thread to Run task
|
||||
_thread = new Java.Lang.Thread(_task.Run);
|
||||
_thread.Start();
|
||||
}
|
||||
|
||||
public void JoinWorkerThread()
|
||||
{
|
||||
_thread.Join();
|
||||
}
|
||||
|
||||
private class AfterTask : OnFinish {
|
||||
readonly ProgressTask _progressTask;
|
||||
|
||||
public AfterTask (Activity activity, OnFinish finish, Handler handler, ProgressTask pt): base(activity, finish, handler)
|
||||
{
|
||||
_progressTask = pt;
|
||||
}
|
||||
|
||||
public override void Run() {
|
||||
base.Run();
|
||||
|
||||
if (Handler != null) //can be null in tests
|
||||
{
|
||||
// Remove the progress dialog
|
||||
Handler.Post(delegate
|
||||
{
|
||||
_progressTask._progressDialog.Dismiss();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
_progressTask._progressDialog.Dismiss();
|
||||
}
|
||||
_currentTask = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
94
src/Kp2aBusinessLogic/ProgressUiAsStatusLoggerAdapter.cs
Normal file
94
src/Kp2aBusinessLogic/ProgressUiAsStatusLoggerAdapter.cs
Normal file
@@ -0,0 +1,94 @@
|
||||
using KeePassLib.Interfaces;
|
||||
|
||||
namespace keepass2android;
|
||||
|
||||
public class ProgressUiAsStatusLoggerAdapter : IKp2aStatusLogger
|
||||
{
|
||||
private IProgressUi? _progressUi;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
private string _lastMessage = "";
|
||||
private string _lastSubMessage = "";
|
||||
private bool _isVisible = false;
|
||||
|
||||
public ProgressUiAsStatusLoggerAdapter(IProgressUi progressUi, IKp2aApp app)
|
||||
{
|
||||
_progressUi = progressUi;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
public void SetNewProgressUi(IProgressUi progressUi)
|
||||
{
|
||||
_progressUi?.Hide();
|
||||
_progressUi = progressUi;
|
||||
if (_isVisible)
|
||||
{
|
||||
progressUi?.Show();
|
||||
progressUi?.UpdateMessage(_lastMessage);
|
||||
progressUi?.UpdateSubMessage(_lastSubMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
progressUi?.Hide();
|
||||
}
|
||||
}
|
||||
|
||||
public void StartLogging(string strOperation, bool bWriteOperationToLog)
|
||||
{
|
||||
_progressUi?.Show();
|
||||
_isVisible = true;
|
||||
}
|
||||
|
||||
public void EndLogging()
|
||||
{
|
||||
_progressUi?.Hide();
|
||||
_isVisible = false;
|
||||
}
|
||||
|
||||
public bool SetProgress(uint uPercent)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool SetText(string strNewText, LogStatusType lsType)
|
||||
{
|
||||
if (strNewText.StartsWith("KP2AKEY_"))
|
||||
{
|
||||
UiStringKey key;
|
||||
if (Enum.TryParse(strNewText.Substring("KP2AKEY_".Length), true, out key))
|
||||
{
|
||||
UpdateMessage(_app.GetResourceString(key));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
UpdateMessage(strNewText);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void UpdateMessage(string message)
|
||||
{
|
||||
_progressUi?.UpdateMessage(message);
|
||||
_lastMessage = message;
|
||||
}
|
||||
|
||||
public void UpdateSubMessage(string submessage)
|
||||
{
|
||||
_progressUi?.UpdateSubMessage(submessage);
|
||||
_lastSubMessage = submessage;
|
||||
}
|
||||
|
||||
public bool ContinueWork()
|
||||
{
|
||||
return !Java.Lang.Thread.Interrupted();
|
||||
}
|
||||
|
||||
public void UpdateMessage(UiStringKey stringKey)
|
||||
{
|
||||
if (_app != null)
|
||||
UpdateMessage(_app.GetResourceString(stringKey));
|
||||
}
|
||||
|
||||
public string LastMessage { get { return _lastMessage; } }
|
||||
public string LastSubMessage { get { return _lastSubMessage; } }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
@@ -15,14 +16,7 @@ namespace KeePass.Util
|
||||
string errorMessage = e.Message;
|
||||
if (e is Java.Lang.Exception javaException)
|
||||
{
|
||||
try
|
||||
{
|
||||
errorMessage = javaException.LocalizedMessage ?? javaException.Message ?? errorMessage;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
errorMessage = javaException.Message ?? errorMessage;
|
||||
}
|
||||
|
||||
return errorMessage;
|
||||
|
||||
@@ -13,16 +13,15 @@ using keepass2android.Io;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class CheckDatabaseForChanges: RunnableOnFinish
|
||||
public class CheckDatabaseForChanges: OperationWithFinishHandler
|
||||
{
|
||||
private readonly Context _context;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
|
||||
public CheckDatabaseForChanges(Activity context, IKp2aApp app, OnFinish finish)
|
||||
: base(context, finish)
|
||||
public CheckDatabaseForChanges(IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_context = context;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,17 +85,14 @@ namespace keepass2android
|
||||
/// <summary>
|
||||
/// Do not call this method directly. Call App.Kp2a.LoadDatabase instead.
|
||||
/// </summary>
|
||||
public void LoadData(IKp2aApp app, IOConnectionInfo iocInfo, MemoryStream databaseData, CompositeKey compositeKey, ProgressDialogStatusLogger status, IDatabaseFormat databaseFormat)
|
||||
public void LoadData(IKp2aApp app, IOConnectionInfo iocInfo, MemoryStream databaseData, CompositeKey compositeKey, IKp2aStatusLogger status, IDatabaseFormat databaseFormat)
|
||||
{
|
||||
PwDatabase pwDatabase = new PwDatabase();
|
||||
|
||||
IFileStorage fileStorage = _app.GetFileStorage(iocInfo);
|
||||
Kp2aLog.Log("LoadData: Retrieving stream");
|
||||
Stream s = databaseData ?? fileStorage.OpenFileForRead(iocInfo);
|
||||
Kp2aLog.Log("LoadData: GetCurrentFileVersion");
|
||||
var fileVersion = _app.GetFileStorage(iocInfo).GetCurrentFileVersionFast(iocInfo);
|
||||
Kp2aLog.Log("LoadData: PopulateDatabaseFromStream");
|
||||
PopulateDatabaseFromStream(pwDatabase, s, iocInfo, compositeKey, status, databaseFormat);
|
||||
Stream s = databaseData ?? fileStorage.OpenFileForRead(iocInfo);
|
||||
var fileVersion = _app.GetFileStorage(iocInfo).GetCurrentFileVersionFast(iocInfo);
|
||||
PopulateDatabaseFromStream(pwDatabase, s, iocInfo, compositeKey, status, databaseFormat);
|
||||
LastFileVersion = fileVersion;
|
||||
|
||||
status.UpdateSubMessage("");
|
||||
@@ -152,7 +149,7 @@ namespace keepass2android
|
||||
get { return GetFingerprintModePrefKey(Ioc); }
|
||||
}
|
||||
|
||||
protected virtual void PopulateDatabaseFromStream(PwDatabase pwDatabase, Stream s, IOConnectionInfo iocInfo, CompositeKey compositeKey, ProgressDialogStatusLogger status, IDatabaseFormat databaseFormat)
|
||||
protected virtual void PopulateDatabaseFromStream(PwDatabase pwDatabase, Stream s, IOConnectionInfo iocInfo, CompositeKey compositeKey, IKp2aStatusLogger status, IDatabaseFormat databaseFormat)
|
||||
{
|
||||
IFileStorage fileStorage = _app.GetFileStorage(iocInfo);
|
||||
var filename = fileStorage.GetFilenameWithoutPathAndExt(iocInfo);
|
||||
@@ -197,9 +194,9 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
|
||||
public void SaveData() {
|
||||
public void SaveData(IFileStorage fileStorage) {
|
||||
|
||||
using (IWriteTransaction trans = _app.GetFileStorage(Ioc).OpenWriteTransaction(Ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions)))
|
||||
using (IWriteTransaction trans = fileStorage.OpenWriteTransaction(Ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions)))
|
||||
{
|
||||
DatabaseFormat.Save(KpDatabase, trans.OpenFile());
|
||||
|
||||
|
||||
@@ -396,8 +396,6 @@ namespace keepass2android
|
||||
{
|
||||
PwGroupV3 toGroup = new PwGroupV3();
|
||||
toGroup.Name = fromGroup.Name;
|
||||
//todo remove
|
||||
Android.Util.Log.Debug("KP2A", "save kdb: group " + fromGroup.Name);
|
||||
|
||||
toGroup.TCreation = new PwDate(ConvertTime(fromGroup.CreationTime));
|
||||
toGroup.TLastAccess= new PwDate(ConvertTime(fromGroup.LastAccessTime));
|
||||
|
||||
@@ -4,109 +4,152 @@ using System.IO;
|
||||
using System.Text;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using KeePassLib.Serialization;
|
||||
using keepass2android.Io;
|
||||
using KeePass.Util;
|
||||
using Group.Pals.Android.Lib.UI.Filechooser.Utils;
|
||||
using KeePassLib;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class SynchronizeCachedDatabase: RunnableOnFinish
|
||||
public class SynchronizeCachedDatabase: OperationWithFinishHandler
|
||||
{
|
||||
private readonly Activity _context;
|
||||
private readonly IKp2aApp _app;
|
||||
private SaveDb _saveDb;
|
||||
private IDatabaseModificationWatcher _modificationWatcher;
|
||||
private readonly Database _database;
|
||||
|
||||
public SynchronizeCachedDatabase(Activity context, IKp2aApp app, OnFinish finish)
|
||||
: base(context, finish)
|
||||
{
|
||||
_context = context;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
public SynchronizeCachedDatabase(IKp2aApp app, Database database, OnOperationFinishedHandler operationFinishedHandler, IDatabaseModificationWatcher modificationWatcher)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_app = app;
|
||||
_database = database;
|
||||
_modificationWatcher = modificationWatcher;
|
||||
}
|
||||
|
||||
public override void Run()
|
||||
{
|
||||
try
|
||||
{
|
||||
IOConnectionInfo ioc = _app.CurrentDb.Ioc;
|
||||
IFileStorage fileStorage = _app.GetFileStorage(ioc);
|
||||
if (!(fileStorage is CachingFileStorage))
|
||||
{
|
||||
throw new Exception("Cannot sync a non-cached database!");
|
||||
}
|
||||
StatusLogger.UpdateMessage(UiStringKey.SynchronizingCachedDatabase);
|
||||
CachingFileStorage cachingFileStorage = (CachingFileStorage) fileStorage;
|
||||
try
|
||||
{
|
||||
IOConnectionInfo ioc = _database.Ioc;
|
||||
IFileStorage fileStorage = _app.GetFileStorage(ioc);
|
||||
if (!(fileStorage is CachingFileStorage))
|
||||
{
|
||||
throw new Exception("Cannot sync a non-cached database!");
|
||||
}
|
||||
|
||||
//download file from remote location and calculate hash:
|
||||
StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.DownloadingRemoteFile));
|
||||
string hash;
|
||||
|
||||
MemoryStream remoteData;
|
||||
try
|
||||
{
|
||||
remoteData = cachingFileStorage.GetRemoteDataAndHash(ioc, out hash);
|
||||
Kp2aLog.Log("Checking for file change. Current hash = " + hash);
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.RestoringRemoteFile));
|
||||
cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
StatusLogger.UpdateMessage(UiStringKey.SynchronizingCachedDatabase);
|
||||
CachingFileStorage cachingFileStorage = (CachingFileStorage)fileStorage;
|
||||
|
||||
//download file from remote location and calculate hash:
|
||||
StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.DownloadingRemoteFile));
|
||||
string hash;
|
||||
|
||||
MemoryStream remoteData;
|
||||
try
|
||||
{
|
||||
remoteData = cachingFileStorage.GetRemoteDataAndHash(ioc, out hash);
|
||||
Kp2aLog.Log("Checking for file change. Current hash = " + hash);
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.RestoringRemoteFile));
|
||||
cachingFileStorage.UpdateRemoteFile(ioc,
|
||||
_app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
Kp2aLog.Log("Checking for file change: file not found");
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
//check if remote file was modified:
|
||||
//check if remote file was modified:
|
||||
var baseVersionHash = cachingFileStorage.GetBaseVersionHash(ioc);
|
||||
Kp2aLog.Log("Checking for file change. baseVersionHash = " + baseVersionHash);
|
||||
if (baseVersionHash != hash)
|
||||
{
|
||||
//remote file is modified
|
||||
if (cachingFileStorage.HasLocalChanges(ioc))
|
||||
{
|
||||
//conflict! need to merge
|
||||
_saveDb = new SaveDb(_context, _app, new ActionOnFinish(ActiveActivity, (success, result, activity) =>
|
||||
{
|
||||
if (!success)
|
||||
{
|
||||
Finish(false, result);
|
||||
}
|
||||
else
|
||||
{
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
}
|
||||
_saveDb = null;
|
||||
}), _app.CurrentDb, false, remoteData);
|
||||
_saveDb.Run();
|
||||
if (baseVersionHash != hash)
|
||||
{
|
||||
//remote file is modified
|
||||
if (cachingFileStorage.HasLocalChanges(ioc))
|
||||
{
|
||||
//conflict! need to merge
|
||||
var _saveDb = new SaveDb(_app, new ActionOnOperationFinished(_app,
|
||||
(success, result, activity) =>
|
||||
{
|
||||
if (!success)
|
||||
{
|
||||
Finish(false, result);
|
||||
}
|
||||
else
|
||||
{
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
}
|
||||
}), _database, false, remoteData, _modificationWatcher);
|
||||
_saveDb.SetStatusLogger(StatusLogger);
|
||||
_saveDb.DoNotSetStatusLoggerMessage = true; //Keep "sync db" as main message
|
||||
_saveDb.SyncInBackground = false;
|
||||
_saveDb.Run();
|
||||
|
||||
_app.CurrentDb.UpdateGlobals();
|
||||
_database.UpdateGlobals();
|
||||
|
||||
_app.MarkAllGroupsAsDirty();
|
||||
}
|
||||
else
|
||||
{
|
||||
//only the remote file was modified -> reload database.
|
||||
//note: it's best to lock the database and do a complete reload here (also better for UI consistency in case something goes wrong etc.)
|
||||
_app.TriggerReload(_context, (bool result) => Finish(result));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//remote file is unmodified
|
||||
if (cachingFileStorage.HasLocalChanges(ioc))
|
||||
{
|
||||
//but we have local changes -> upload:
|
||||
StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.UploadingFile));
|
||||
cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
|
||||
StatusLogger.UpdateSubMessage("");
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
}
|
||||
else
|
||||
{
|
||||
//files are in sync: just set the result
|
||||
Finish(true, _app.GetResourceString(UiStringKey.FilesInSync));
|
||||
}
|
||||
}
|
||||
}
|
||||
_app.MarkAllGroupsAsDirty();
|
||||
}
|
||||
else
|
||||
{
|
||||
//only the remote file was modified -> reload database.
|
||||
var onFinished = new ActionOnOperationFinished(_app, (success, result, activity) =>
|
||||
{
|
||||
if (!success)
|
||||
{
|
||||
Finish(false, result);
|
||||
}
|
||||
else
|
||||
{
|
||||
new Handler(Looper.MainLooper).Post(() =>
|
||||
{
|
||||
_database.UpdateGlobals();
|
||||
|
||||
_app.MarkAllGroupsAsDirty();
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
var _loadDb = new LoadDb(_app, ioc, Task.FromResult(remoteData),
|
||||
_database.KpDatabase.MasterKey, null, onFinished, true, false, _modificationWatcher);
|
||||
_loadDb.SetStatusLogger(StatusLogger);
|
||||
_loadDb.DoNotSetStatusLoggerMessage = true; //Keep "sync db" as main message
|
||||
_loadDb.Run();
|
||||
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//remote file is unmodified
|
||||
if (cachingFileStorage.HasLocalChanges(ioc))
|
||||
{
|
||||
//but we have local changes -> upload:
|
||||
StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.UploadingFile));
|
||||
cachingFileStorage.UpdateRemoteFile(ioc,
|
||||
_app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
|
||||
StatusLogger.UpdateSubMessage("");
|
||||
Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
|
||||
}
|
||||
else
|
||||
{
|
||||
//files are in sync: just set the result
|
||||
Finish(true, _app.GetResourceString(UiStringKey.FilesInSync));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Java.Lang.InterruptedException e)
|
||||
{
|
||||
Kp2aLog.LogUnexpectedError(e);
|
||||
//no Finish()
|
||||
}
|
||||
catch (Java.IO.InterruptedIOException e)
|
||||
{
|
||||
Kp2aLog.LogUnexpectedError(e);
|
||||
//no Finish()
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Kp2aLog.LogUnexpectedError(e);
|
||||
@@ -115,10 +158,5 @@ namespace keepass2android
|
||||
|
||||
}
|
||||
|
||||
public void JoinWorkerThread()
|
||||
{
|
||||
if (_saveDb != null)
|
||||
_saveDb.JoinWorkerThread();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll.
|
||||
|
||||
Keepass2Android is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Keepass2Android is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using Android.App;
|
||||
using Android.OS;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class ActionOnFinish: OnFinish
|
||||
{
|
||||
public delegate void ActionToPerformOnFinsh(bool success, String message, Activity activeActivity);
|
||||
|
||||
readonly ActionToPerformOnFinsh _actionToPerform;
|
||||
|
||||
public ActionOnFinish(Activity activity, ActionToPerformOnFinsh actionToPerform) : base(activity, null, null)
|
||||
{
|
||||
_actionToPerform = actionToPerform;
|
||||
}
|
||||
|
||||
public ActionOnFinish(Activity activity, ActionToPerformOnFinsh actionToPerform, OnFinish finish) : base(activity, finish)
|
||||
{
|
||||
_actionToPerform = actionToPerform;
|
||||
}
|
||||
|
||||
//if set to true, the previously active active will be passed to ActionToPerformOnFinish instead null if no activity is on foreground
|
||||
public bool AllowInactiveActivity { get; set; }
|
||||
|
||||
public override void Run()
|
||||
{
|
||||
if (Message == null)
|
||||
Message = "";
|
||||
if (Handler != null)
|
||||
{
|
||||
Handler.Post(() => {_actionToPerform(Success, Message, ActiveActivity);});
|
||||
}
|
||||
else
|
||||
_actionToPerform(Success, Message, AllowInactiveActivity ? (ActiveActivity ?? PreviouslyActiveActivity) : ActiveActivity);
|
||||
base.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll.
|
||||
|
||||
Keepass2Android is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Keepass2Android is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.OS;
|
||||
using keepass2android;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class ActionOnOperationFinished: OnOperationFinishedHandler
|
||||
{
|
||||
public delegate void ActionToPerformOnFinsh(bool success, String message, Context activeContext);
|
||||
|
||||
readonly ActionToPerformOnFinsh _actionToPerform;
|
||||
|
||||
public ActionOnOperationFinished(IKp2aApp app, ActionToPerformOnFinsh actionToPerform) : base(app, null, null)
|
||||
{
|
||||
_actionToPerform = actionToPerform;
|
||||
}
|
||||
|
||||
public ActionOnOperationFinished(IKp2aApp app, ActionToPerformOnFinsh actionToPerform, OnOperationFinishedHandler operationFinishedHandler) : base(app, operationFinishedHandler)
|
||||
{
|
||||
_actionToPerform = actionToPerform;
|
||||
}
|
||||
|
||||
public override void Run()
|
||||
{
|
||||
if (Message == null)
|
||||
Message = "";
|
||||
if (Handler != null)
|
||||
{
|
||||
Handler.Post(() =>
|
||||
{
|
||||
_actionToPerform(Success, Message, ActiveContext);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
_actionToPerform(Success, Message, ActiveContext);
|
||||
}
|
||||
base.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Action which runs when the contextInstanceId is the active context
|
||||
// otherwise it is registered as pending action for the context instance.
|
||||
public class ActionInContextInstanceOnOperationFinished : ActionOnOperationFinished
|
||||
{
|
||||
private readonly int _contextInstanceId;
|
||||
private IKp2aApp _app;
|
||||
|
||||
public ActionInContextInstanceOnOperationFinished(int contextInstanceId, IKp2aApp app, ActionToPerformOnFinsh actionToPerform) : base(app, actionToPerform)
|
||||
{
|
||||
_contextInstanceId = contextInstanceId;
|
||||
_app = app;
|
||||
}
|
||||
public ActionInContextInstanceOnOperationFinished(int contextInstanceId, IKp2aApp app, ActionToPerformOnFinsh actionToPerform, OnOperationFinishedHandler operationFinishedHandler) : base(app, actionToPerform, operationFinishedHandler)
|
||||
{
|
||||
_contextInstanceId = contextInstanceId;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
public override void Run()
|
||||
{
|
||||
if ((ActiveContext as IContextInstanceIdProvider)?.ContextInstanceId != _contextInstanceId)
|
||||
{
|
||||
_app.RegisterPendingActionForContextInstance(_contextInstanceId, this);
|
||||
}
|
||||
else _app.UiThreadHandler.Post(() => base.Run());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ using KeePassLib;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class AddEntry : RunnableOnFinish {
|
||||
public class AddEntry : OperationWithFinishHandler {
|
||||
protected Database Db
|
||||
{
|
||||
get { return _app.CurrentDb; }
|
||||
@@ -30,22 +30,20 @@ namespace keepass2android
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly PwEntry _entry;
|
||||
private readonly PwGroup _parentGroup;
|
||||
private readonly Activity _ctx;
|
||||
private readonly Database _db;
|
||||
|
||||
public static AddEntry GetInstance(Activity ctx, IKp2aApp app, PwEntry entry, PwGroup parentGroup, OnFinish finish, Database db) {
|
||||
public static AddEntry GetInstance(IKp2aApp app, PwEntry entry, PwGroup parentGroup, OnOperationFinishedHandler operationFinishedHandler, Database db) {
|
||||
|
||||
return new AddEntry(ctx, db, app, entry, parentGroup, finish);
|
||||
return new AddEntry(db, app, entry, parentGroup, operationFinishedHandler);
|
||||
}
|
||||
|
||||
public AddEntry(Activity ctx, Database db, IKp2aApp app, PwEntry entry, PwGroup parentGroup, OnFinish finish):base(ctx, finish) {
|
||||
_ctx = ctx;
|
||||
public AddEntry(Database db, IKp2aApp app, PwEntry entry, PwGroup parentGroup, OnOperationFinishedHandler operationFinishedHandler):base(app, operationFinishedHandler) {
|
||||
_db = db;
|
||||
_parentGroup = parentGroup;
|
||||
_app = app;
|
||||
_entry = entry;
|
||||
|
||||
_onFinishToRun = new AfterAdd(ctx, app.CurrentDb, entry, app,OnFinishToRun);
|
||||
_operationFinishedHandler = new AfterAdd(app.CurrentDb, entry, app,operationFinishedHandler);
|
||||
}
|
||||
|
||||
|
||||
@@ -65,17 +63,17 @@ namespace keepass2android
|
||||
_db.Elements.Add(_entry);
|
||||
|
||||
// Commit to disk
|
||||
SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun);
|
||||
SaveDb save = new SaveDb(_app, _app.CurrentDb, operationFinishedHandler);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.Run();
|
||||
}
|
||||
|
||||
private class AfterAdd : OnFinish {
|
||||
private class AfterAdd : OnOperationFinishedHandler {
|
||||
private readonly Database _db;
|
||||
private readonly PwEntry _entry;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
public AfterAdd(Activity activity, Database db, PwEntry entry, IKp2aApp app, OnFinish finish):base(activity, finish) {
|
||||
public AfterAdd( Database db, PwEntry entry, IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler):base(app, operationFinishedHandler) {
|
||||
_db = db;
|
||||
_entry = entry;
|
||||
_app = app;
|
||||
|
||||
@@ -23,7 +23,7 @@ using KeePassLib;
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public class AddGroup : RunnableOnFinish {
|
||||
public class AddGroup : OperationWithFinishHandler {
|
||||
internal Database Db
|
||||
{
|
||||
get { return _app.CurrentDb; }
|
||||
@@ -38,18 +38,16 @@ namespace keepass2android
|
||||
public PwGroup Group;
|
||||
internal PwGroup Parent;
|
||||
protected bool DontSave;
|
||||
readonly Activity _ctx;
|
||||
|
||||
|
||||
public static AddGroup GetInstance(Activity ctx, IKp2aApp app, string name, int iconid, PwUuid groupCustomIconId, PwGroup parent, OnFinish finish, bool dontSave) {
|
||||
return new AddGroup(ctx, app, name, iconid, groupCustomIconId, parent, finish, dontSave);
|
||||
|
||||
|
||||
public static AddGroup GetInstance(IKp2aApp app, string name, int iconid, PwUuid groupCustomIconId, PwGroup parent, OnOperationFinishedHandler operationFinishedHandler, bool dontSave) {
|
||||
return new AddGroup(app, name, iconid, groupCustomIconId, parent, operationFinishedHandler, dontSave);
|
||||
}
|
||||
|
||||
|
||||
private AddGroup(Activity ctx, IKp2aApp app, String name, int iconid, PwUuid groupCustomIconId, PwGroup parent, OnFinish finish, bool dontSave)
|
||||
: base(ctx, finish)
|
||||
private AddGroup(IKp2aApp app, String name, int iconid, PwUuid groupCustomIconId, PwGroup parent, OnOperationFinishedHandler operationFinishedHandler, bool dontSave)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_name = name;
|
||||
_iconId = iconid;
|
||||
_groupCustomIconId = groupCustomIconId;
|
||||
@@ -57,7 +55,7 @@ namespace keepass2android
|
||||
DontSave = dontSave;
|
||||
_app = app;
|
||||
|
||||
_onFinishToRun = new AfterAdd(ctx, this, OnFinishToRun);
|
||||
_operationFinishedHandler = new AfterAdd(_app, this, operationFinishedHandler);
|
||||
}
|
||||
|
||||
|
||||
@@ -74,15 +72,15 @@ namespace keepass2android
|
||||
_app.CurrentDb.Elements.Add(Group);
|
||||
|
||||
// Commit to disk
|
||||
SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun, DontSave);
|
||||
SaveDb save = new SaveDb(_app, _app.CurrentDb, operationFinishedHandler, DontSave, null);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.Run();
|
||||
}
|
||||
|
||||
private class AfterAdd : OnFinish {
|
||||
private class AfterAdd : OnOperationFinishedHandler {
|
||||
readonly AddGroup _addGroup;
|
||||
|
||||
public AfterAdd(Activity activity, AddGroup addGroup,OnFinish finish): base(activity, finish) {
|
||||
public AfterAdd(IKp2aApp app, AddGroup addGroup,OnOperationFinishedHandler operationFinishedHandler): base(app, operationFinishedHandler) {
|
||||
_addGroup = addGroup;
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ using KeePassLib.Utility;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class AddTemplateEntries : RunnableOnFinish {
|
||||
public class AddTemplateEntries : OperationWithFinishHandler {
|
||||
|
||||
public class TemplateEntry
|
||||
{
|
||||
@@ -130,15 +130,13 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly Activity _ctx;
|
||||
|
||||
public AddTemplateEntries(Activity ctx, IKp2aApp app, OnFinish finish)
|
||||
: base(ctx, finish)
|
||||
|
||||
public AddTemplateEntries(IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_app = app;
|
||||
_app = app;
|
||||
|
||||
//_onFinishToRun = new AfterAdd(this, OnFinishToRun);
|
||||
//_operationFinishedHandler = new AfterAdd(this, operationFinishedHandler);
|
||||
}
|
||||
|
||||
public static readonly List<TemplateEntry> TemplateEntries = new List<TemplateEntry>()
|
||||
@@ -313,7 +311,7 @@ namespace keepass2android
|
||||
_app.DirtyGroups.Add(templateGroup);
|
||||
|
||||
// Commit to disk
|
||||
SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun);
|
||||
SaveDb save = new SaveDb(_app, _app.CurrentDb, operationFinishedHandler);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.Run();
|
||||
}
|
||||
@@ -337,7 +335,6 @@ namespace keepass2android
|
||||
_app.DirtyGroups.Add(_app.CurrentDb.KpDatabase.RootGroup);
|
||||
_app.CurrentDb.GroupsById[templateGroup.Uuid] = templateGroup;
|
||||
_app.CurrentDb.Elements.Add(templateGroup);
|
||||
|
||||
}
|
||||
addedEntries = new List<PwEntry>();
|
||||
|
||||
@@ -369,11 +366,11 @@ namespace keepass2android
|
||||
return entry;
|
||||
}
|
||||
|
||||
private class AfterAdd : OnFinish {
|
||||
private class AfterAdd : OnOperationFinishedHandler {
|
||||
private readonly Database _db;
|
||||
private readonly List<PwEntry> _entries;
|
||||
|
||||
public AfterAdd(Activity activity, Database db, List<PwEntry> entries, OnFinish finish):base(activity, finish) {
|
||||
public AfterAdd(IKp2aApp app, Database db, List<PwEntry> entries, OnOperationFinishedHandler operationFinishedHandler):base(app, operationFinishedHandler) {
|
||||
_db = db;
|
||||
_entries = entries;
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ namespace keepass2android.database.edit
|
||||
{
|
||||
public class CopyEntry: AddEntry
|
||||
{
|
||||
public CopyEntry(Activity ctx, IKp2aApp app, PwEntry entry, OnFinish finish, Database db)
|
||||
: base(ctx, db, app, CreateCopy(entry, app), entry.ParentGroup, finish)
|
||||
public CopyEntry(IKp2aApp app, PwEntry entry, OnOperationFinishedHandler operationFinishedHandler, Database db)
|
||||
: base(db, app, CreateCopy(entry, app), entry.ParentGroup, operationFinishedHandler)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
@@ -26,27 +26,24 @@ using KeePassLib.Keys;
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public class CreateDb : RunnableOnFinish {
|
||||
public class CreateDb : OperationWithFinishHandler {
|
||||
private readonly IOConnectionInfo _ioc;
|
||||
private readonly bool _dontSave;
|
||||
private readonly Activity _ctx;
|
||||
private readonly IKp2aApp _app;
|
||||
private CompositeKey _key;
|
||||
private readonly bool _makeCurrent;
|
||||
|
||||
public CreateDb(IKp2aApp app, Activity ctx, IOConnectionInfo ioc, OnFinish finish, bool dontSave, bool makeCurrent): base(ctx, finish) {
|
||||
_ctx = ctx;
|
||||
_ioc = ioc;
|
||||
public CreateDb(IKp2aApp app, Activity ctx, IOConnectionInfo ioc, OnOperationFinishedHandler operationFinishedHandler, bool dontSave, bool makeCurrent): base(app, operationFinishedHandler) {
|
||||
_ioc = ioc;
|
||||
_dontSave = dontSave;
|
||||
_makeCurrent = makeCurrent;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
public CreateDb(IKp2aApp app, Activity ctx, IOConnectionInfo ioc, OnFinish finish, bool dontSave, CompositeKey key, bool makeCurrent)
|
||||
: base(ctx, finish)
|
||||
public CreateDb(IKp2aApp app, Activity ctx, IOConnectionInfo ioc, OnOperationFinishedHandler operationFinishedHandler, bool dontSave, CompositeKey key, bool makeCurrent)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_ioc = ioc;
|
||||
_ioc = ioc;
|
||||
_dontSave = dontSave;
|
||||
_app = app;
|
||||
_key = key;
|
||||
@@ -77,19 +74,19 @@ namespace keepass2android
|
||||
db.SearchHelper = new SearchDbHelper(_app);
|
||||
|
||||
// Add a couple default groups
|
||||
AddGroup internet = AddGroup.GetInstance(_ctx, _app, "Internet", 1, null, db.KpDatabase.RootGroup, null, true);
|
||||
AddGroup internet = AddGroup.GetInstance(_app, "Internet", 1, null, db.KpDatabase.RootGroup, null, true);
|
||||
internet.Run();
|
||||
AddGroup email = AddGroup.GetInstance(_ctx, _app, "eMail", 19, null, db.KpDatabase.RootGroup, null, true);
|
||||
AddGroup email = AddGroup.GetInstance(_app, "eMail", 19, null, db.KpDatabase.RootGroup, null, true);
|
||||
email.Run();
|
||||
|
||||
List<PwEntry> addedEntries;
|
||||
AddTemplateEntries addTemplates = new AddTemplateEntries(_ctx, _app, null);
|
||||
AddTemplateEntries addTemplates = new AddTemplateEntries(_app, null);
|
||||
addTemplates.AddTemplates(out addedEntries);
|
||||
|
||||
// Commit changes
|
||||
SaveDb save = new SaveDb(_ctx, _app, db, OnFinishToRun, _dontSave);
|
||||
SaveDb save = new SaveDb(_app, db, operationFinishedHandler, _dontSave, null);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
_onFinishToRun = null;
|
||||
_operationFinishedHandler = null;
|
||||
save.Run();
|
||||
|
||||
db.UpdateGlobals();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using Java.Lang;
|
||||
|
||||
namespace keepass2android;
|
||||
|
||||
public interface IDatabaseModificationWatcher
|
||||
{
|
||||
void BeforeModifyDatabases();
|
||||
void AfterModifyDatabases();
|
||||
}
|
||||
|
||||
public class NullDatabaseModificationWatcher : IDatabaseModificationWatcher
|
||||
{
|
||||
public void BeforeModifyDatabases() { }
|
||||
public void AfterModifyDatabases() { }
|
||||
}
|
||||
|
||||
public class BackgroundDatabaseModificationLocker(IKp2aApp app) : IDatabaseModificationWatcher
|
||||
{
|
||||
public void BeforeModifyDatabases()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (app.DatabasesBackgroundModificationLock.TryEnterWriteLock(TimeSpan.FromSeconds(0.1)))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (Java.Lang.Thread.Interrupted())
|
||||
{
|
||||
throw new InterruptedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AfterModifyDatabases()
|
||||
{
|
||||
app.DatabasesBackgroundModificationLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
@@ -29,8 +29,8 @@ namespace keepass2android
|
||||
private readonly PwEntry _entry;
|
||||
private UiStringKey _statusMessage;
|
||||
|
||||
public DeleteEntry(Activity activiy, IKp2aApp app, PwEntry entry, OnFinish finish):base(activiy, finish, app) {
|
||||
Ctx = activiy;
|
||||
public DeleteEntry(IKp2aApp app, PwEntry entry, OnOperationFinishedHandler operationFinishedHandler):base(operationFinishedHandler, app) {
|
||||
|
||||
Db = app.FindDatabaseForElement(entry);
|
||||
_entry = entry;
|
||||
|
||||
|
||||
@@ -29,25 +29,25 @@ namespace keepass2android
|
||||
private PwGroup _group;
|
||||
protected bool DontSave;
|
||||
|
||||
public DeleteGroup(Activity activity, IKp2aApp app, PwGroup group, OnFinish finish)
|
||||
: base(activity, finish, app)
|
||||
public DeleteGroup(Activity activity, IKp2aApp app, PwGroup group, OnOperationFinishedHandler operationFinishedHandler)
|
||||
: base(operationFinishedHandler, app)
|
||||
{
|
||||
SetMembers(activity, app, group, false);
|
||||
SetMembers(app, group, false);
|
||||
}
|
||||
/*
|
||||
public DeleteGroup(Context ctx, Database db, PwGroup group, Activity act, OnFinish finish, bool dontSave)
|
||||
: base(finish)
|
||||
public DeleteGroup(Context ctx, Database db, PwGroup group, Activity act, OnOperationFinishedHandler operationFinishedHandler, bool dontSave)
|
||||
: base(operationFinishedHandler)
|
||||
{
|
||||
SetMembers(ctx, db, group, act, dontSave);
|
||||
}
|
||||
|
||||
public DeleteGroup(Context ctx, Database db, PwGroup group, OnFinish finish, bool dontSave):base(finish) {
|
||||
public DeleteGroup(Context ctx, Database db, PwGroup group, OnOperationFinishedHandler operationFinishedHandler, bool dontSave):base(operationFinishedHandler) {
|
||||
SetMembers(ctx, db, group, null, dontSave);
|
||||
}
|
||||
*/
|
||||
private void SetMembers(Activity activity, IKp2aApp app, PwGroup group, bool dontSave)
|
||||
private void SetMembers(IKp2aApp app, PwGroup group, bool dontSave)
|
||||
{
|
||||
base.SetMembers(activity, app.FindDatabaseForElement(group));
|
||||
base.SetMembers(app.FindDatabaseForElement(group));
|
||||
|
||||
_group = group;
|
||||
DontSave = dontSave;
|
||||
|
||||
@@ -12,11 +12,11 @@ namespace keepass2android
|
||||
private readonly List<IStructureItem> _elementsToDelete;
|
||||
private readonly bool _canRecycle;
|
||||
|
||||
public DeleteMultipleItemsFromOneDatabase(Activity activity, Database db, List<IStructureItem> elementsToDelete, OnFinish finish, IKp2aApp app)
|
||||
: base(activity, finish, app)
|
||||
public DeleteMultipleItemsFromOneDatabase(Activity activity, Database db, List<IStructureItem> elementsToDelete, OnOperationFinishedHandler operationFinishedHandler, IKp2aApp app)
|
||||
: base(operationFinishedHandler, app)
|
||||
{
|
||||
_elementsToDelete = elementsToDelete;
|
||||
SetMembers(activity, db);
|
||||
SetMembers(db);
|
||||
|
||||
//determine once. The property is queried for each delete operation, but might return false
|
||||
//after one entry/group is deleted (and thus in recycle bin and thus can't be recycled anymore)
|
||||
|
||||
@@ -6,10 +6,10 @@ using KeePassLib;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public abstract class DeleteRunnable : RunnableOnFinish
|
||||
public abstract class DeleteRunnable : OperationWithFinishHandler
|
||||
{
|
||||
protected DeleteRunnable(Activity activity, OnFinish finish, IKp2aApp app)
|
||||
: base(activity, finish)
|
||||
protected DeleteRunnable(OnOperationFinishedHandler operationFinishedHandler, IKp2aApp app)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
App = app;
|
||||
}
|
||||
@@ -18,11 +18,10 @@ namespace keepass2android
|
||||
|
||||
protected Database Db;
|
||||
|
||||
protected Activity Ctx;
|
||||
|
||||
|
||||
protected void SetMembers(Activity activity, Database db)
|
||||
protected void SetMembers( Database db)
|
||||
{
|
||||
Ctx = activity;
|
||||
Db = db;
|
||||
}
|
||||
|
||||
@@ -131,18 +130,18 @@ namespace keepass2android
|
||||
(dlgSender, dlgEvt) =>
|
||||
{
|
||||
DeletePermanently = true;
|
||||
ProgressTask pt = new ProgressTask(App, Ctx, this);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App, this);
|
||||
pt.Run();
|
||||
|
||||
},
|
||||
(dlgSender, dlgEvt) =>
|
||||
{
|
||||
DeletePermanently = false;
|
||||
ProgressTask pt = new ProgressTask(App, Ctx, this);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App, this);
|
||||
pt.Run();
|
||||
},
|
||||
(dlgSender, dlgEvt) => { },
|
||||
Ctx, messageSuffix);
|
||||
messageSuffix);
|
||||
|
||||
|
||||
|
||||
@@ -153,12 +152,12 @@ namespace keepass2android
|
||||
QuestionNoRecycleResourceId,
|
||||
(dlgSender, dlgEvt) =>
|
||||
{
|
||||
ProgressTask pt = new ProgressTask(App, Ctx, this);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App, this);
|
||||
pt.Run();
|
||||
},
|
||||
null,
|
||||
(dlgSender, dlgEvt) => { },
|
||||
Ctx, messageSuffix);
|
||||
messageSuffix);
|
||||
|
||||
|
||||
}
|
||||
@@ -215,7 +214,7 @@ namespace keepass2android
|
||||
Android.Util.Log.Debug("KP2A", "Calling PerformDelete..");
|
||||
PerformDelete(touchedGroups, permanentlyDeletedGroups);
|
||||
|
||||
_onFinishToRun = new ActionOnFinish(ActiveActivity,(success, message, activity) =>
|
||||
_operationFinishedHandler = new ActionOnOperationFinished(App,(success, message, context) =>
|
||||
{
|
||||
if (success)
|
||||
{
|
||||
@@ -236,10 +235,10 @@ namespace keepass2android
|
||||
// Let's not bother recovering from a failure to save. It is too much work.
|
||||
App.Lock(false, false);
|
||||
}
|
||||
}, OnFinishToRun);
|
||||
}, operationFinishedHandler);
|
||||
|
||||
// Commit database
|
||||
SaveDb save = new SaveDb(Ctx, App, Db, OnFinishToRun, false);
|
||||
SaveDb save = new SaveDb( App, Db, operationFinishedHandler, false, null);
|
||||
save.ShowDatabaseIocInStatus = ShowDatabaseIocInStatus;
|
||||
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
|
||||
@@ -23,7 +23,7 @@ using KeePassLib;
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public class EditGroup : RunnableOnFinish {
|
||||
public class EditGroup : OperationWithFinishHandler {
|
||||
internal Database Db
|
||||
{
|
||||
get { return _app.FindDatabaseForElement(Group); }
|
||||
@@ -36,19 +36,17 @@ namespace keepass2android
|
||||
private readonly PwIcon _iconId;
|
||||
private readonly PwUuid _customIconId;
|
||||
internal PwGroup Group;
|
||||
readonly Activity _ctx;
|
||||
|
||||
public EditGroup(Activity ctx, IKp2aApp app, String name, PwIcon iconid, PwUuid customIconId, PwGroup group, OnFinish finish)
|
||||
: base(ctx, finish)
|
||||
public EditGroup(IKp2aApp app, String name, PwIcon iconid, PwUuid customIconId, PwGroup group, OnOperationFinishedHandler operationFinishedHandler)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_name = name;
|
||||
_iconId = iconid;
|
||||
Group = group;
|
||||
_customIconId = customIconId;
|
||||
_app = app;
|
||||
|
||||
_onFinishToRun = new AfterEdit(ctx, this, OnFinishToRun);
|
||||
_operationFinishedHandler = new AfterEdit(app, this, operationFinishedHandler);
|
||||
}
|
||||
|
||||
|
||||
@@ -60,16 +58,16 @@ namespace keepass2android
|
||||
Group.Touch(true);
|
||||
|
||||
// Commit to disk
|
||||
SaveDb save = new SaveDb(_ctx, _app, Db, OnFinishToRun);
|
||||
SaveDb save = new SaveDb(_app, Db, operationFinishedHandler);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.Run();
|
||||
}
|
||||
|
||||
private class AfterEdit : OnFinish {
|
||||
private class AfterEdit : OnOperationFinishedHandler {
|
||||
readonly EditGroup _editGroup;
|
||||
|
||||
public AfterEdit(Activity ctx, EditGroup editGroup, OnFinish finish)
|
||||
: base(ctx, finish)
|
||||
public AfterEdit(IKp2aApp app, EditGroup editGroup, OnOperationFinishedHandler operationFinishedHandler)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_editGroup = editGroup;
|
||||
}
|
||||
|
||||
@@ -21,10 +21,10 @@ using Android.App;
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public abstract class FileOnFinish : OnFinish {
|
||||
public abstract class FileOnFinish : OnOperationFinishedHandler {
|
||||
private String _filename = "";
|
||||
|
||||
protected FileOnFinish(Activity activity, FileOnFinish finish):base(activity, finish) {
|
||||
protected FileOnFinish(IKp2aApp app, FileOnFinish operationFinishedHandler):base(app, operationFinishedHandler) {
|
||||
}
|
||||
|
||||
public string Filename
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace keepass2android;
|
||||
|
||||
// A context instance can be the instance of an Activity. Even if the activity is recreated (due to a configuration change, for example), the instance id must remain the same
|
||||
// but it must be different for other activities/services or if the activity is finished and then starts again.
|
||||
// We want to be able to perform actions on a context instance, even though that instance might not live at the time when we want to perform the action.
|
||||
// In that case, we want to be able to register the action such that it is performed when the activity is recreated.
|
||||
public interface IContextInstanceIdProvider
|
||||
{
|
||||
|
||||
int ContextInstanceId { get; }
|
||||
|
||||
|
||||
}
|
||||
@@ -21,60 +21,88 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Android.App;
|
||||
using Android.OS;
|
||||
using KeePass.Util;
|
||||
using keepass2android.database.edit;
|
||||
using keepass2android.Io;
|
||||
using KeePassLib;
|
||||
using KeePassLib.Keys;
|
||||
using KeePassLib.Serialization;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class LoadDb : RunnableOnFinish {
|
||||
public class LoadDb : OperationWithFinishHandler {
|
||||
private readonly IOConnectionInfo _ioc;
|
||||
private readonly Task<MemoryStream> _databaseData;
|
||||
private readonly CompositeKey _compositeKey;
|
||||
private readonly string _keyfileOrProvider;
|
||||
private readonly string? _keyfileOrProvider;
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly bool _rememberKeyfile;
|
||||
IDatabaseFormat _format;
|
||||
|
||||
public LoadDb(Activity activity, IKp2aApp app, IOConnectionInfo ioc, Task<MemoryStream> databaseData, CompositeKey compositeKey, String keyfileOrProvider, OnFinish finish, bool updateLastUsageTimestamp, bool makeCurrent): base(activity, finish)
|
||||
|
||||
public bool DoNotSetStatusLoggerMessage = false;
|
||||
|
||||
|
||||
public LoadDb(IKp2aApp app, IOConnectionInfo ioc, Task<MemoryStream> databaseData, CompositeKey compositeKey,
|
||||
string keyfileOrProvider, OnOperationFinishedHandler operationFinishedHandler,
|
||||
bool updateLastUsageTimestamp, bool makeCurrent, IDatabaseModificationWatcher modificationWatcher = null): base(app, operationFinishedHandler)
|
||||
{
|
||||
_app = app;
|
||||
_modificationWatcher = modificationWatcher ?? new NullDatabaseModificationWatcher();
|
||||
_app = app;
|
||||
_ioc = ioc;
|
||||
_databaseData = databaseData;
|
||||
_compositeKey = compositeKey;
|
||||
_keyfileOrProvider = keyfileOrProvider;
|
||||
_updateLastUsageTimestamp = updateLastUsageTimestamp;
|
||||
_makeCurrent = makeCurrent;
|
||||
|
||||
|
||||
_rememberKeyfile = app.GetBooleanPreference(PreferenceKey.remember_keyfile);
|
||||
}
|
||||
_rememberKeyfile = app.GetBooleanPreference(PreferenceKey.remember_keyfile);
|
||||
}
|
||||
|
||||
protected bool success = false;
|
||||
private bool _updateLastUsageTimestamp;
|
||||
private readonly bool _makeCurrent;
|
||||
private readonly IDatabaseModificationWatcher _modificationWatcher;
|
||||
|
||||
public override void Run()
|
||||
public override void Run()
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
//make sure the file data is stored in the recent files list even if loading fails
|
||||
SaveFileData(_ioc, _keyfileOrProvider);
|
||||
SaveFileData(_ioc, _keyfileOrProvider);
|
||||
|
||||
|
||||
var fileStorage = _app.GetFileStorage(_ioc);
|
||||
|
||||
RequiresSubsequentSync = false;
|
||||
|
||||
|
||||
StatusLogger.UpdateMessage(UiStringKey.loading_database);
|
||||
if (!DoNotSetStatusLoggerMessage)
|
||||
{
|
||||
StatusLogger.UpdateMessage(UiStringKey.loading_database);
|
||||
}
|
||||
|
||||
//get the stream data into a single stream variable (databaseStream) regardless whether its preloaded or not:
|
||||
MemoryStream preloadedMemoryStream = _databaseData == null ? null : _databaseData.Result;
|
||||
MemoryStream databaseStream;
|
||||
if (preloadedMemoryStream != null)
|
||||
databaseStream = preloadedMemoryStream;
|
||||
else
|
||||
if (preloadedMemoryStream != null)
|
||||
{
|
||||
//note: if the stream has been loaded already, we don't need to trigger another sync later on
|
||||
databaseStream = preloadedMemoryStream;
|
||||
}
|
||||
else
|
||||
{
|
||||
using (Stream s = _app.GetFileStorage(_ioc).OpenFileForRead(_ioc))
|
||||
if (_app.SyncInBackgroundPreference && fileStorage is CachingFileStorage cachingFileStorage &&
|
||||
cachingFileStorage.IsCached(_ioc))
|
||||
{
|
||||
cachingFileStorage.IsOffline = true;
|
||||
//no warning. We'll trigger a sync later.
|
||||
cachingFileStorage.TriggerWarningWhenFallingBackToCache = false;
|
||||
RequiresSubsequentSync = true;
|
||||
|
||||
}
|
||||
using (Stream s = fileStorage.OpenFileForRead(_ioc))
|
||||
{
|
||||
databaseStream = new MemoryStream();
|
||||
s.CopyTo(databaseStream);
|
||||
@@ -82,8 +110,13 @@ namespace keepass2android
|
||||
}
|
||||
}
|
||||
|
||||
if (!StatusLogger.ContinueWork())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//ok, try to load the database. Let's start with Kdbx format and retry later if that is the wrong guess:
|
||||
_format = new KdbxDatabaseFormat(KdbxDatabaseFormat.GetFormatToUse(_app.GetFileStorage(_ioc).GetFileExtension(_ioc)));
|
||||
_format = new KdbxDatabaseFormat(KdbxDatabaseFormat.GetFormatToUse(fileStorage.GetFileExtension(_ioc)));
|
||||
TryLoad(databaseStream);
|
||||
|
||||
|
||||
@@ -120,7 +153,13 @@ namespace keepass2android
|
||||
Finish(false, _app.GetResourceString(UiStringKey.DuplicateUuidsError) + " " + ExceptionUtil.GetErrorMessage(e) + _app.GetResourceString(UiStringKey.DuplicateUuidsErrorAdditional), false, Exception);
|
||||
return;
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Java.Lang.InterruptedException)
|
||||
{
|
||||
Kp2aLog.Log("Load interrupted");
|
||||
//close without Finish()
|
||||
return;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (!(e is InvalidCompositeKeyException))
|
||||
Kp2aLog.LogUnexpectedError(e);
|
||||
@@ -131,14 +170,15 @@ namespace keepass2android
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
public bool RequiresSubsequentSync { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Holds the exception which was thrown during execution (if any)
|
||||
/// </summary>
|
||||
public Exception Exception { get; set; }
|
||||
|
||||
Database TryLoad(MemoryStream databaseStream)
|
||||
{
|
||||
Kp2aLog.Log("LoadDb: Copying database in memory");
|
||||
//create a copy of the stream so we can try again if we get an exception which indicates we should change parameters
|
||||
//This is not optimal in terms of (short-time) memory usage but is hard to avoid because the Keepass library closes streams also in case of errors.
|
||||
//Alternatives would involve increased traffic (if file is on remote) and slower loading times, so this seems to be the best choice.
|
||||
@@ -147,16 +187,21 @@ namespace keepass2android
|
||||
workingCopy.Seek(0, SeekOrigin.Begin);
|
||||
//reset stream if we need to reuse it later:
|
||||
databaseStream.Seek(0, SeekOrigin.Begin);
|
||||
Kp2aLog.Log("LoadDb: Ready to start loading");
|
||||
//now let's go:
|
||||
if (!StatusLogger.ContinueWork())
|
||||
{
|
||||
throw new Java.Lang.InterruptedException();
|
||||
}
|
||||
|
||||
//now let's go:
|
||||
try
|
||||
{
|
||||
Database newDb = _app.LoadDatabase(_ioc, workingCopy, _compositeKey, StatusLogger, _format, _makeCurrent);
|
||||
Kp2aLog.Log("LoadDB OK");
|
||||
|
||||
{
|
||||
Database newDb =
|
||||
_app.LoadDatabase(_ioc, workingCopy, _compositeKey, StatusLogger, _format, _makeCurrent, _modificationWatcher);
|
||||
Kp2aLog.Log("LoadDB OK");
|
||||
|
||||
Finish(true, _format.SuccessMessage);
|
||||
return newDb;
|
||||
}
|
||||
return newDb;
|
||||
}
|
||||
catch (OldFormatException)
|
||||
{
|
||||
_format = new KdbDatabaseFormat(_app);
|
||||
|
||||
@@ -10,18 +10,16 @@ using KeePassLib.Interfaces;
|
||||
|
||||
namespace keepass2android.database.edit
|
||||
{
|
||||
public class MoveElements: RunnableOnFinish
|
||||
public class MoveElements: OperationWithFinishHandler
|
||||
{
|
||||
private readonly List<IStructureItem> _elementsToMove;
|
||||
private readonly PwGroup _targetGroup;
|
||||
private readonly Activity _ctx;
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
public MoveElements(List<IStructureItem> elementsToMove, PwGroup targetGroup, Activity ctx, IKp2aApp app, OnFinish finish) : base(ctx, finish)
|
||||
public MoveElements(List<IStructureItem> elementsToMove, PwGroup targetGroup,IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler) : base(app, operationFinishedHandler)
|
||||
{
|
||||
_elementsToMove = elementsToMove;
|
||||
_targetGroup = targetGroup;
|
||||
_ctx = ctx;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
@@ -123,24 +121,24 @@ namespace keepass2android.database.edit
|
||||
|
||||
int indexToSave = 0;
|
||||
bool allSavesSuccess = true;
|
||||
void ContinueSave(bool success, string message, Activity activeActivity)
|
||||
void ContinueSave(bool success, string message, Context activeActivity)
|
||||
{
|
||||
allSavesSuccess &= success;
|
||||
indexToSave++;
|
||||
if (indexToSave == allDatabasesToSave.Count)
|
||||
{
|
||||
OnFinishToRun.SetResult(allSavesSuccess);
|
||||
OnFinishToRun.Run();
|
||||
operationFinishedHandler.SetResult(allSavesSuccess);
|
||||
operationFinishedHandler.Run();
|
||||
return;
|
||||
}
|
||||
SaveDb saveDb = new SaveDb(_ctx, _app, allDatabasesToSave[indexToSave], new ActionOnFinish(activeActivity, ContinueSave), false);
|
||||
SaveDb saveDb = new SaveDb( _app, allDatabasesToSave[indexToSave], new ActionOnOperationFinished(_app, ContinueSave), false, null);
|
||||
saveDb.SetStatusLogger(StatusLogger);
|
||||
saveDb.ShowDatabaseIocInStatus = allDatabasesToSave.Count > 1;
|
||||
saveDb.Run();
|
||||
}
|
||||
|
||||
|
||||
SaveDb save = new SaveDb(_ctx, _app, allDatabasesToSave[0], new ActionOnFinish(ActiveActivity, ContinueSave), false);
|
||||
SaveDb save = new SaveDb(_app, allDatabasesToSave[0], new ActionOnOperationFinished(_app, ContinueSave), false, null);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.ShowDatabaseIocInStatus = allDatabasesToSave.Count > 1;
|
||||
save.Run();
|
||||
|
||||
@@ -22,10 +22,16 @@ using Android.Content;
|
||||
using Android.OS;
|
||||
using Android.Widget;
|
||||
using Google.Android.Material.Dialog;
|
||||
using KeePassLib.Interfaces;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public abstract class OnFinish
|
||||
public interface IActiveContextProvider
|
||||
{
|
||||
Context ActiveContext { get; }
|
||||
}
|
||||
|
||||
public abstract class OnOperationFinishedHandler
|
||||
{
|
||||
protected bool Success;
|
||||
protected String Message;
|
||||
@@ -37,63 +43,41 @@ namespace keepass2android
|
||||
set;
|
||||
}
|
||||
|
||||
protected OnFinish BaseOnFinish;
|
||||
protected Context ActiveContext
|
||||
{
|
||||
get
|
||||
{
|
||||
return _activeContextProvider?.ActiveContext;
|
||||
}
|
||||
}
|
||||
|
||||
protected OnOperationFinishedHandler NextOnOperationFinishedHandler;
|
||||
protected Handler Handler;
|
||||
private ProgressDialogStatusLogger _statusLogger = new ProgressDialogStatusLogger(); //default: no logging but not null -> can be used whenever desired
|
||||
private Activity _activeActivity, _previouslyActiveActivity;
|
||||
private IKp2aStatusLogger _statusLogger = new Kp2aNullStatusLogger(); //default: no logging but not null -> can be used whenever desired
|
||||
private readonly IActiveContextProvider _activeContextProvider;
|
||||
|
||||
|
||||
public ProgressDialogStatusLogger StatusLogger
|
||||
public IKp2aStatusLogger StatusLogger
|
||||
{
|
||||
get { return _statusLogger; }
|
||||
set { _statusLogger = value; }
|
||||
}
|
||||
|
||||
public Activity ActiveActivity
|
||||
{
|
||||
get { return _activeActivity; }
|
||||
set
|
||||
{
|
||||
if (_activeActivity != null && _activeActivity != _previouslyActiveActivity)
|
||||
{
|
||||
_previouslyActiveActivity = _activeActivity;
|
||||
|
||||
}
|
||||
_activeActivity = value;
|
||||
if (BaseOnFinish != null)
|
||||
{
|
||||
BaseOnFinish.ActiveActivity = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Activity PreviouslyActiveActivity
|
||||
} protected OnOperationFinishedHandler(IActiveContextProvider activeContextProvider, Handler handler)
|
||||
{
|
||||
get { return _previouslyActiveActivity; }
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected OnFinish(Activity activeActivity, Handler handler)
|
||||
{
|
||||
ActiveActivity = activeActivity;
|
||||
BaseOnFinish = null;
|
||||
Handler = handler;
|
||||
|
||||
}
|
||||
|
||||
protected OnFinish(Activity activeActivity, OnFinish finish, Handler handler)
|
||||
{
|
||||
ActiveActivity = activeActivity;
|
||||
BaseOnFinish = finish;
|
||||
_activeContextProvider = activeContextProvider;
|
||||
NextOnOperationFinishedHandler = null;
|
||||
Handler = handler;
|
||||
}
|
||||
|
||||
protected OnFinish(Activity activeActivity, OnFinish finish)
|
||||
protected OnOperationFinishedHandler(IActiveContextProvider activeContextProvider, OnOperationFinishedHandler operationFinishedHandler, Handler handler)
|
||||
{
|
||||
ActiveActivity = activeActivity;
|
||||
BaseOnFinish = finish;
|
||||
_activeContextProvider = activeContextProvider;
|
||||
NextOnOperationFinishedHandler = operationFinishedHandler;
|
||||
Handler = handler;
|
||||
}
|
||||
|
||||
protected OnOperationFinishedHandler(IActiveContextProvider activeContextProvider, OnOperationFinishedHandler operationFinishedHandler)
|
||||
{
|
||||
_activeContextProvider = activeContextProvider;
|
||||
NextOnOperationFinishedHandler = operationFinishedHandler;
|
||||
Handler = null;
|
||||
}
|
||||
|
||||
@@ -110,14 +94,19 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
public virtual void Run() {
|
||||
if (BaseOnFinish == null) return;
|
||||
if (NextOnOperationFinishedHandler == null) return;
|
||||
// Pass on result on call finish
|
||||
BaseOnFinish.SetResult(Success, Message, ImportantMessage, Exception);
|
||||
|
||||
if ( Handler != null ) {
|
||||
Handler.Post(BaseOnFinish.Run);
|
||||
NextOnOperationFinishedHandler.SetResult(Success, Message, ImportantMessage, Exception);
|
||||
|
||||
var handler = Handler ?? NextOnOperationFinishedHandler.Handler ?? null;
|
||||
|
||||
if (handler != null ) {
|
||||
handler.Post(() =>
|
||||
{
|
||||
NextOnOperationFinishedHandler.Run();
|
||||
});
|
||||
} else {
|
||||
BaseOnFinish.Run();
|
||||
NextOnOperationFinishedHandler.Run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +117,7 @@ namespace keepass2android
|
||||
public static void DisplayMessage(Context ctx, string message, bool makeDialog)
|
||||
{
|
||||
if ( !String.IsNullOrEmpty(message) ) {
|
||||
Kp2aLog.Log("OnFinish message: " + message);
|
||||
Kp2aLog.Log("OnOperationFinishedHandler message: " + message);
|
||||
if (makeDialog && ctx != null)
|
||||
{
|
||||
try
|
||||
@@ -152,3 +141,4 @@ namespace keepass2android
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll. This file is based on Keepassdroid, Copyright Brian Pellin.
|
||||
|
||||
Keepass2Android is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Keepass2Android is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using KeePassLib.Interfaces;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public abstract class OperationWithFinishHandler {
|
||||
|
||||
protected OnOperationFinishedHandler _operationFinishedHandler;
|
||||
public IKp2aStatusLogger StatusLogger = new Kp2aNullStatusLogger(); //default: empty but not null
|
||||
private IActiveContextProvider _activeContextProvider;
|
||||
|
||||
protected OperationWithFinishHandler(IActiveContextProvider activeContextProvider, OnOperationFinishedHandler operationFinishedHandler)
|
||||
{
|
||||
_activeContextProvider = activeContextProvider;
|
||||
_operationFinishedHandler = operationFinishedHandler;
|
||||
}
|
||||
|
||||
public OnOperationFinishedHandler operationFinishedHandler
|
||||
{
|
||||
get { return _operationFinishedHandler; }
|
||||
set { _operationFinishedHandler = value; }
|
||||
}
|
||||
|
||||
|
||||
protected void Finish(bool result, String message, bool importantMessage = false, Exception exception = null) {
|
||||
if ( operationFinishedHandler != null ) {
|
||||
operationFinishedHandler.SetResult(result, message, importantMessage, exception);
|
||||
operationFinishedHandler.Run();
|
||||
}
|
||||
}
|
||||
|
||||
protected void Finish(bool result) {
|
||||
if ( operationFinishedHandler != null ) {
|
||||
operationFinishedHandler.SetResult(result);
|
||||
operationFinishedHandler.Run();
|
||||
}
|
||||
}
|
||||
|
||||
public void SetStatusLogger(IKp2aStatusLogger statusLogger) {
|
||||
if (operationFinishedHandler != null)
|
||||
{
|
||||
operationFinishedHandler.StatusLogger = statusLogger;
|
||||
}
|
||||
StatusLogger = statusLogger;
|
||||
}
|
||||
|
||||
public abstract void Run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll. This file is based on Keepassdroid, Copyright Brian Pellin.
|
||||
|
||||
Keepass2Android is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Keepass2Android is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public abstract class RunnableOnFinish {
|
||||
|
||||
protected OnFinish _onFinishToRun;
|
||||
public ProgressDialogStatusLogger StatusLogger = new ProgressDialogStatusLogger(); //default: empty but not null
|
||||
private Activity _activeActivity;
|
||||
|
||||
protected RunnableOnFinish(Activity activeActivity, OnFinish finish)
|
||||
{
|
||||
_activeActivity = activeActivity;
|
||||
_onFinishToRun = finish;
|
||||
}
|
||||
|
||||
public OnFinish OnFinishToRun
|
||||
{
|
||||
get { return _onFinishToRun; }
|
||||
set { _onFinishToRun = value; }
|
||||
}
|
||||
|
||||
public Activity ActiveActivity
|
||||
{
|
||||
get { return _activeActivity; }
|
||||
set
|
||||
{
|
||||
_activeActivity = value;
|
||||
if (_onFinishToRun != null)
|
||||
_onFinishToRun.ActiveActivity = _activeActivity;
|
||||
}
|
||||
}
|
||||
|
||||
protected void Finish(bool result, String message, bool importantMessage = false, Exception exception = null) {
|
||||
if ( OnFinishToRun != null ) {
|
||||
OnFinishToRun.SetResult(result, message, importantMessage, exception);
|
||||
OnFinishToRun.Run();
|
||||
}
|
||||
}
|
||||
|
||||
protected void Finish(bool result) {
|
||||
if ( OnFinishToRun != null ) {
|
||||
OnFinishToRun.SetResult(result);
|
||||
OnFinishToRun.Run();
|
||||
}
|
||||
}
|
||||
|
||||
public void SetStatusLogger(ProgressDialogStatusLogger status) {
|
||||
if (OnFinishToRun != null)
|
||||
{
|
||||
OnFinishToRun.StatusLogger = status;
|
||||
}
|
||||
StatusLogger = status;
|
||||
}
|
||||
|
||||
public abstract void Run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,57 +30,69 @@ using keepass2android.Io;
|
||||
using Debug = System.Diagnostics.Debug;
|
||||
using Exception = System.Exception;
|
||||
using KeePass.Util;
|
||||
using Thread = System.Threading.Thread;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Save the database. If the file has changed, ask the user if he wants to overwrite or sync.
|
||||
/// </summary>
|
||||
|
||||
public class SaveDb : RunnableOnFinish {
|
||||
public class SaveDb : OperationWithFinishHandler {
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly Database _db;
|
||||
private readonly bool _dontSave;
|
||||
private readonly IDatabaseModificationWatcher _modificationWatcher;
|
||||
private bool requiresSubsequentSync = false; //if true, we need to sync the file after saving.
|
||||
|
||||
public bool DoNotSetStatusLoggerMessage = false;
|
||||
|
||||
/// <summary>
|
||||
/// stream for reading the data from the original file. If this is set to a non-null value, we know we need to sync
|
||||
/// </summary>
|
||||
private readonly Stream _streamForOrigFile;
|
||||
private readonly Context _ctx;
|
||||
|
||||
private Java.Lang.Thread _workerThread;
|
||||
|
||||
public SaveDb(Activity ctx, IKp2aApp app, Database db, OnFinish finish, bool dontSave)
|
||||
: base(ctx, finish)
|
||||
public SaveDb(IKp2aApp app, Database db, OnOperationFinishedHandler operationFinishedHandler, bool dontSave, IDatabaseModificationWatcher modificationWatcher)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_db = db;
|
||||
_ctx = ctx;
|
||||
_app = app;
|
||||
_dontSave = dontSave;
|
||||
_modificationWatcher = modificationWatcher ?? new NullDatabaseModificationWatcher();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for sync
|
||||
/// </summary>
|
||||
/// <param name="ctx"></param>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="finish"></param>
|
||||
/// <param name="operationFinishedHandler"></param>
|
||||
/// <param name="dontSave"></param>
|
||||
/// <param name="streamForOrigFile">Stream for reading the data from the (changed) original location</param>
|
||||
public SaveDb(Activity ctx, IKp2aApp app, OnFinish finish, Database db, bool dontSave, Stream streamForOrigFile)
|
||||
: base(ctx, finish)
|
||||
public SaveDb(IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler, Database db, bool dontSave, Stream streamForOrigFile, IDatabaseModificationWatcher modificationWatcher = null)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_db = db;
|
||||
_ctx = ctx;
|
||||
_modificationWatcher = modificationWatcher ?? new NullDatabaseModificationWatcher();
|
||||
_db = db;
|
||||
_app = app;
|
||||
_dontSave = dontSave;
|
||||
_streamForOrigFile = streamForOrigFile;
|
||||
}
|
||||
SyncInBackground = _app.SyncInBackgroundPreference;
|
||||
|
||||
public SaveDb(Activity ctx, IKp2aApp app, Database db, OnFinish finish)
|
||||
: base(ctx, finish)
|
||||
}
|
||||
|
||||
public SaveDb(IKp2aApp app, Database db, OnOperationFinishedHandler operationFinishedHandler, IDatabaseModificationWatcher modificationWatcher = null)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_app = app;
|
||||
|
||||
_modificationWatcher = modificationWatcher ?? new NullDatabaseModificationWatcher();
|
||||
_app = app;
|
||||
_db = db;
|
||||
_dontSave = false;
|
||||
}
|
||||
SyncInBackground = _app.SyncInBackgroundPreference;
|
||||
}
|
||||
|
||||
public bool ShowDatabaseIocInStatus { get; set; }
|
||||
|
||||
@@ -103,29 +115,42 @@ namespace keepass2android
|
||||
if (ShowDatabaseIocInStatus)
|
||||
message += " (" + _app.GetFileStorage(_db.Ioc).GetDisplayName(_db.Ioc) + ")";
|
||||
|
||||
StatusLogger.UpdateMessage(message);
|
||||
|
||||
IOConnectionInfo ioc = _db.Ioc;
|
||||
if (!DoNotSetStatusLoggerMessage)
|
||||
{
|
||||
StatusLogger.UpdateMessage(message);
|
||||
}
|
||||
|
||||
IOConnectionInfo ioc = _db.Ioc;
|
||||
IFileStorage fileStorage = _app.GetFileStorage(ioc);
|
||||
|
||||
if (_streamForOrigFile == null)
|
||||
if (SyncInBackground && fileStorage is IOfflineSwitchable offlineSwitchable)
|
||||
{
|
||||
offlineSwitchable.IsOffline = true;
|
||||
//no warning. We'll trigger a sync later.
|
||||
offlineSwitchable.TriggerWarningWhenFallingBackToCache = false;
|
||||
requiresSubsequentSync = true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (_streamForOrigFile == null)
|
||||
{
|
||||
if ((!_app.GetBooleanPreference(PreferenceKey.CheckForFileChangesOnSave))
|
||||
|| (_db.KpDatabase.HashOfFileOnDisk == null)) //first time saving
|
||||
{
|
||||
PerformSaveWithoutCheck(fileStorage, ioc);
|
||||
Finish(true);
|
||||
FinishWithSuccess();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool hasStreamForOrigFile = (_streamForOrigFile != null);
|
||||
bool hasChangeFast = hasStreamForOrigFile ||
|
||||
fileStorage.CheckForFileChangeFast(ioc, _db.LastFileVersion); //first try to use the fast change detection;
|
||||
bool hasHashChanged = hasChangeFast ||
|
||||
bool hasHashChanged = !requiresSubsequentSync && (
|
||||
hasChangeFast ||
|
||||
(FileHashChanged(ioc, _db.KpDatabase.HashOfFileOnDisk) ==
|
||||
FileHashChange.Changed); //if that fails, hash the file and compare:
|
||||
FileHashChange.Changed)); //if that fails, hash the file and compare:
|
||||
|
||||
if (hasHashChanged)
|
||||
{
|
||||
@@ -158,15 +183,14 @@ namespace keepass2android
|
||||
RunInWorkerThread(() =>
|
||||
{
|
||||
PerformSaveWithoutCheck(fileStorage, ioc);
|
||||
Finish(true);
|
||||
FinishWithSuccess();
|
||||
});
|
||||
},
|
||||
//cancel
|
||||
(sender, args) =>
|
||||
{
|
||||
RunInWorkerThread(() => Finish(false));
|
||||
},
|
||||
_ctx
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -174,7 +198,7 @@ namespace keepass2android
|
||||
else
|
||||
{
|
||||
PerformSaveWithoutCheck(fileStorage, ioc);
|
||||
Finish(true);
|
||||
FinishWithSuccess();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -194,22 +218,67 @@ namespace keepass2android
|
||||
}
|
||||
else
|
||||
{
|
||||
Finish(true);
|
||||
FinishWithSuccess();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public bool SyncInBackground { get; set; }
|
||||
|
||||
private void FinishWithSuccess()
|
||||
{
|
||||
if (requiresSubsequentSync)
|
||||
{
|
||||
var syncTask = new SynchronizeCachedDatabase(_app, _db, new ActionOnOperationFinished(_app,
|
||||
(success, message, context) =>
|
||||
{
|
||||
if (!System.String.IsNullOrEmpty(message))
|
||||
_app.ShowMessage(context, message, success ? MessageSeverity.Info : MessageSeverity.Error);
|
||||
|
||||
}), new BackgroundDatabaseModificationLocker(_app)
|
||||
);
|
||||
OperationRunner.Instance.Run(_app, syncTask);
|
||||
}
|
||||
Finish(true);
|
||||
}
|
||||
|
||||
private void MergeAndFinish(IFileStorage fileStorage, IOConnectionInfo ioc)
|
||||
{
|
||||
//note: when synced, the file might be downloaded once again from the server. Caching the data
|
||||
//in the hashing function would solve this but increases complexity. I currently assume the files are
|
||||
//small.
|
||||
MergeIn(fileStorage, ioc);
|
||||
|
||||
try
|
||||
{
|
||||
_modificationWatcher.BeforeModifyDatabases();
|
||||
}
|
||||
catch (Java.Lang.InterruptedException)
|
||||
{
|
||||
// leave without Finish()
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
MergeIn(fileStorage, ioc);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_modificationWatcher.AfterModifyDatabases();
|
||||
|
||||
}
|
||||
|
||||
PerformSaveWithoutCheck(fileStorage, ioc);
|
||||
_db.UpdateGlobals();
|
||||
Finish(true);
|
||||
new Handler(Looper.MainLooper).Post(() =>
|
||||
{
|
||||
_db.UpdateGlobals();
|
||||
});
|
||||
|
||||
FinishWithSuccess();
|
||||
}
|
||||
|
||||
|
||||
private void RunInWorkerThread(Action runHandler)
|
||||
{
|
||||
try
|
||||
@@ -282,7 +351,7 @@ namespace keepass2android
|
||||
private void PerformSaveWithoutCheck(IFileStorage fileStorage, IOConnectionInfo ioc)
|
||||
{
|
||||
StatusLogger.UpdateSubMessage("");
|
||||
_db.SaveData();
|
||||
_db.SaveData(fileStorage);
|
||||
_db.LastFileVersion = fileStorage.GetCurrentFileVersionFast(ioc);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,26 +22,24 @@ using KeePassLib.Keys;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class SetPassword : RunnableOnFinish {
|
||||
public class SetPassword : OperationWithFinishHandler {
|
||||
|
||||
private readonly String _password;
|
||||
private readonly String _keyfile;
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly bool _dontSave;
|
||||
private readonly Activity _ctx;
|
||||
|
||||
public SetPassword(Activity ctx, IKp2aApp app, String password, String keyfile, OnFinish finish): base(ctx, finish) {
|
||||
_ctx = ctx;
|
||||
public SetPassword(IKp2aApp app, String password, String keyfile, OnOperationFinishedHandler operationFinishedHandler): base(app, operationFinishedHandler) {
|
||||
|
||||
_app = app;
|
||||
_password = password;
|
||||
_keyfile = keyfile;
|
||||
_dontSave = false;
|
||||
}
|
||||
|
||||
public SetPassword(Activity ctx, IKp2aApp app, String password, String keyfile, OnFinish finish, bool dontSave)
|
||||
: base(ctx, finish)
|
||||
public SetPassword(IKp2aApp app, String password, String keyfile, OnOperationFinishedHandler operationFinishedHandler, bool dontSave)
|
||||
: base(app, operationFinishedHandler)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_app = app;
|
||||
_password = password;
|
||||
_keyfile = keyfile;
|
||||
@@ -73,18 +71,18 @@ namespace keepass2android
|
||||
pm.MasterKey = newKey;
|
||||
|
||||
// Save Database
|
||||
_onFinishToRun = new AfterSave(ActiveActivity, previousKey, previousMasterKeyChanged, pm, OnFinishToRun);
|
||||
SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun, _dontSave);
|
||||
_operationFinishedHandler = new AfterSave(_app, previousKey, previousMasterKeyChanged, pm, operationFinishedHandler);
|
||||
SaveDb save = new SaveDb(_app, _app.CurrentDb, operationFinishedHandler, _dontSave, null);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.Run();
|
||||
}
|
||||
|
||||
private class AfterSave : OnFinish {
|
||||
private class AfterSave : OnOperationFinishedHandler {
|
||||
private readonly CompositeKey _backup;
|
||||
private readonly DateTime _previousKeyChanged;
|
||||
private readonly PwDatabase _db;
|
||||
|
||||
public AfterSave(Activity activity, CompositeKey backup, DateTime previousKeyChanged, PwDatabase db, OnFinish finish): base(activity, finish) {
|
||||
public AfterSave(IActiveContextProvider activeContextProvider, CompositeKey backup, DateTime previousKeyChanged, PwDatabase db, OnOperationFinishedHandler operationFinishedHandler): base(activeContextProvider, operationFinishedHandler) {
|
||||
_previousKeyChanged = previousKeyChanged;
|
||||
_backup = backup;
|
||||
_db = db;
|
||||
|
||||
@@ -22,31 +22,29 @@ using KeePassLib;
|
||||
namespace keepass2android
|
||||
{
|
||||
|
||||
public class UpdateEntry : RunnableOnFinish {
|
||||
public class UpdateEntry : OperationWithFinishHandler {
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly Activity _ctx;
|
||||
|
||||
public UpdateEntry(Activity ctx, IKp2aApp app, PwEntry oldE, PwEntry newE, OnFinish finish):base(ctx, finish) {
|
||||
_ctx = ctx;
|
||||
_app = app;
|
||||
|
||||
_onFinishToRun = new AfterUpdate(ctx, oldE, newE, app, finish);
|
||||
public UpdateEntry(IKp2aApp app, PwEntry oldE, PwEntry newE, OnOperationFinishedHandler operationFinishedHandler):base(app, operationFinishedHandler) {
|
||||
_app = app;
|
||||
|
||||
_operationFinishedHandler = new AfterUpdate( oldE, newE, app, operationFinishedHandler);
|
||||
}
|
||||
|
||||
|
||||
public override void Run() {
|
||||
// Commit to disk
|
||||
SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun);
|
||||
SaveDb save = new SaveDb(_app, _app.CurrentDb, operationFinishedHandler);
|
||||
save.SetStatusLogger(StatusLogger);
|
||||
save.Run();
|
||||
}
|
||||
|
||||
private class AfterUpdate : OnFinish {
|
||||
private class AfterUpdate : OnOperationFinishedHandler {
|
||||
private readonly PwEntry _backup;
|
||||
private readonly PwEntry _updatedEntry;
|
||||
private readonly IKp2aApp _app;
|
||||
|
||||
public AfterUpdate(Activity activity, PwEntry backup, PwEntry updatedEntry, IKp2aApp app, OnFinish finish):base(activity, finish) {
|
||||
public AfterUpdate(PwEntry backup, PwEntry updatedEntry, IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler):base(app, operationFinishedHandler) {
|
||||
_backup = backup;
|
||||
_updatedEntry = updatedEntry;
|
||||
_app = app;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0-android</TargetFramework>
|
||||
<TargetFramework>net8.0-android</TargetFramework>
|
||||
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -20,6 +20,7 @@ git clone --recurse-submodules https://github.com/PhilippC/keepass2android.git
|
||||
cd keepass2android/src/build-scripts
|
||||
./build-java.sh && ./build-native.sh
|
||||
cd ..
|
||||
cp Kp2aBusinessLogic/Io/DropboxFileStorageKeysDummy.cs Kp2aBusinessLogic/Io/DropboxFileStorageKeys.cs
|
||||
cd keepass2android-app
|
||||
ln -s Manifests/AndroidManifest_debug.xml AndroidManifest.xml
|
||||
dotnet workload restore
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
BASE_DIR="${1}"
|
||||
|
||||
for arch_dir in "$BASE_DIR"/android-*/; do
|
||||
arch=$(basename "$arch_dir")
|
||||
arch=${arch#android-}
|
||||
APK_DIR="${arch_dir}publish"
|
||||
if [[ -d "$APK_DIR" ]]; then
|
||||
apk_path=$(find "$APK_DIR" -maxdepth 1 -type f -name "*.apk" | head -n1)
|
||||
if [[ -n "$apk_path" ]]; then
|
||||
base=$(basename "$apk_path" .apk)
|
||||
new_path="$APK_DIR/${base}-${arch}.apk"
|
||||
mv "$apk_path" "$new_path"
|
||||
echo "Renamed $apk_path to $new_path"
|
||||
else
|
||||
echo "No APK found in $APK_DIR"
|
||||
fi
|
||||
else
|
||||
echo "Directory $APK_DIR does not exist"
|
||||
fi
|
||||
done
|
||||
@@ -1,7 +1,6 @@
|
||||
package keepass2android.javafilestorage;
|
||||
|
||||
import android.content.Context;
|
||||
import java.math.BigInteger;
|
||||
import android.content.Intent;
|
||||
|
||||
import android.net.Uri;
|
||||
@@ -16,10 +15,7 @@ import com.burgstaller.okhttp.basic.BasicAuthenticator;
|
||||
import com.burgstaller.okhttp.digest.CachingAuthenticator;
|
||||
import com.burgstaller.okhttp.digest.DigestAuthenticator;
|
||||
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringReader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
@@ -28,7 +24,6 @@ import java.security.KeyManagementException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
@@ -49,33 +44,23 @@ import keepass2android.javafilestorage.webdav.DecoratedTrustManager;
|
||||
import keepass2android.javafilestorage.webdav.PropfindXmlParser;
|
||||
import keepass2android.javafilestorage.webdav.WebDavUtil;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.internal.tls.OkHostnameVerifier;
|
||||
import okio.BufferedSink;
|
||||
|
||||
public class WebDavStorage extends JavaFileStorageBase {
|
||||
|
||||
private final ICertificateErrorHandler mCertificateErrorHandler;
|
||||
private Context appContext;
|
||||
|
||||
int chunkSize;
|
||||
|
||||
public WebDavStorage(ICertificateErrorHandler certificateErrorHandler, int chunkSize)
|
||||
public WebDavStorage(ICertificateErrorHandler certificateErrorHandler)
|
||||
{
|
||||
this.chunkSize = chunkSize;
|
||||
|
||||
mCertificateErrorHandler = certificateErrorHandler;
|
||||
}
|
||||
|
||||
public void setUploadChunkSize(int chunkSize)
|
||||
{
|
||||
this.chunkSize = chunkSize;
|
||||
}
|
||||
|
||||
public String buildFullPath(String url, String username, String password) throws UnsupportedEncodingException {
|
||||
String scheme = url.substring(0, url.indexOf("://"));
|
||||
url = url.substring(scheme.length() + 3);
|
||||
@@ -196,119 +181,21 @@ public class WebDavStorage extends JavaFileStorageBase {
|
||||
return client;
|
||||
}
|
||||
|
||||
public void renameOrMoveWebDavResource(String sourcePath, String destinationPath, boolean overwrite) throws Exception {
|
||||
|
||||
ConnectionInfo sourceCi = splitStringToConnectionInfo(sourcePath);
|
||||
ConnectionInfo destinationCi = splitStringToConnectionInfo(destinationPath);
|
||||
|
||||
Request.Builder requestBuilder = new Request.Builder()
|
||||
.url(new URL(sourceCi.URL))
|
||||
.method("MOVE", null) // "MOVE" is the HTTP method
|
||||
.header("Destination", destinationCi.URL); // New URI for the resource
|
||||
|
||||
// Add Overwrite header
|
||||
if (overwrite) {
|
||||
requestBuilder.header("Overwrite", "T"); // 'T' for true
|
||||
} else {
|
||||
requestBuilder.header("Overwrite", "F"); // 'F' for false
|
||||
}
|
||||
|
||||
Request request = requestBuilder.build();
|
||||
|
||||
Response response = getClient(sourceCi).newCall(request).execute();
|
||||
|
||||
// Check the status code
|
||||
if (response.isSuccessful()) {
|
||||
// WebDAV MOVE can return 201 (Created) if a new resource was created at dest,
|
||||
// or 204 (No Content) if moved to a pre-existing destination (e.g., just renamed).
|
||||
// A 200 OK might also be returned by some servers, though 201/204 are more common.
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Rename/Move failed for " + sourceCi.URL + " to " + destinationCi.URL + ": " + response.code() + " " + response.message());
|
||||
}
|
||||
}
|
||||
|
||||
public static String generateRandomHexString(int length) {
|
||||
SecureRandom secureRandom = new SecureRandom();
|
||||
// Generate enough bytes to ensure we can get the desired number of hex characters.
|
||||
// Each byte converts to two hex characters.
|
||||
// For 8 hex characters, we need 4 bytes.
|
||||
int numBytes = (int) Math.ceil(length / 2.0);
|
||||
byte[] randomBytes = new byte[numBytes];
|
||||
secureRandom.nextBytes(randomBytes);
|
||||
|
||||
// Convert the byte array to a hexadecimal string
|
||||
// BigInteger(1, randomBytes) treats the byte array as a positive number.
|
||||
// toString(16) converts it to a hexadecimal string.
|
||||
String hexString = new BigInteger(1, randomBytes).toString(16);
|
||||
|
||||
// Pad with leading zeros if necessary (e.g., if the generated number is small)
|
||||
// and then take the first 'length' characters.
|
||||
// Using String.format to ensure leading zeros if the hexString is shorter.
|
||||
return String.format("%0" + length + "d", new BigInteger(hexString, 16)).substring(0, length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uploadFile(String path, byte[] data, boolean writeTransactional)
|
||||
throws Exception {
|
||||
|
||||
if (writeTransactional)
|
||||
{
|
||||
String randomSuffix = ".tmp." + generateRandomHexString(8);
|
||||
uploadFile(path + randomSuffix, data, false);
|
||||
renameOrMoveWebDavResource(path+randomSuffix, path, true);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
ConnectionInfo ci = splitStringToConnectionInfo(path);
|
||||
|
||||
|
||||
RequestBody requestBody;
|
||||
if (chunkSize > 0)
|
||||
{
|
||||
// use chunked upload
|
||||
requestBody = new RequestBody() {
|
||||
@Override
|
||||
public MediaType contentType() {
|
||||
return MediaType.parse("application/binary");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(BufferedSink sink) throws IOException {
|
||||
try (InputStream in = new ByteArrayInputStream(data)) {
|
||||
byte[] buffer = new byte[chunkSize];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) != -1) {
|
||||
sink.write(buffer, 0, read);
|
||||
sink.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long contentLength() {
|
||||
return -1; // use chunked upload
|
||||
}
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
requestBody = new MultipartBody.Builder()
|
||||
.addPart(RequestBody.create(data, MediaType.parse("application/binary")))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(new URL(ci.URL))
|
||||
.put(requestBody)
|
||||
.put(RequestBody.create(MediaType.parse("application/binary"), data))
|
||||
.build();
|
||||
|
||||
|
||||
//TODO consider writeTransactional
|
||||
//TODO check for error
|
||||
|
||||
Response response = getClient(ci).newCall(request).execute();
|
||||
checkStatus(response);
|
||||
@@ -403,10 +290,7 @@ public class WebDavStorage extends JavaFileStorageBase {
|
||||
e.sizeInBytes = -1;
|
||||
}
|
||||
}
|
||||
|
||||
e.isDirectory = r.href.endsWith("/") || okprop.IsCollection;
|
||||
|
||||
|
||||
e.isDirectory = r.href.endsWith("/");
|
||||
|
||||
e.displayName = okprop.DisplayName;
|
||||
if (e.displayName == null)
|
||||
@@ -635,4 +519,3 @@ public class WebDavStorage extends JavaFileStorageBase {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,6 @@ public class PropfindXmlParser
|
||||
public String DisplayName;
|
||||
public String LastModified;
|
||||
public String ContentLength;
|
||||
|
||||
public boolean IsCollection;
|
||||
}
|
||||
public String status;
|
||||
public Prop prop;
|
||||
@@ -193,8 +191,6 @@ public class PropfindXmlParser
|
||||
continue;
|
||||
}
|
||||
String name = parser.getName();
|
||||
String namespace = parser.getNamespace();
|
||||
|
||||
|
||||
android.util.Log.d("PARSE", "4name = " + name);
|
||||
if (name.equals("getcontentlength"))
|
||||
@@ -204,9 +200,6 @@ public class PropfindXmlParser
|
||||
prop.LastModified = readText(parser);
|
||||
} else if (name.equals("displayname")) {
|
||||
prop.DisplayName = readText(parser);
|
||||
} else if (name.equals("resourcetype") && namespace.equals(ns)) {
|
||||
// We found the <d:resourcetype> tag
|
||||
prop.IsCollection = readResourceType(parser);
|
||||
} else {
|
||||
skip(parser);
|
||||
}
|
||||
@@ -215,37 +208,6 @@ public class PropfindXmlParser
|
||||
return prop;
|
||||
}
|
||||
|
||||
private boolean readResourceType(XmlPullParser parser) throws IOException, XmlPullParserException {
|
||||
boolean isCollection = false;
|
||||
parser.require(XmlPullParser.START_TAG, ns, "resourcetype");
|
||||
|
||||
while (parser.next() != XmlPullParser.END_TAG) {
|
||||
|
||||
if (parser.getEventType() != XmlPullParser.START_TAG) {
|
||||
continue;
|
||||
}
|
||||
String name = parser.getName();
|
||||
String namespace = parser.getNamespace();
|
||||
|
||||
if (name.equals("collection") && namespace.equals(ns)) {
|
||||
// We found <d:collection/>, so it's a folder
|
||||
isCollection = true;
|
||||
// Since <d:collection/> is usually an empty tag, just consume it.
|
||||
// It might contain text if there's whitespace, so consume text then end tag.
|
||||
if (parser.next() == XmlPullParser.TEXT) {
|
||||
parser.nextTag(); // Move to the end tag
|
||||
}
|
||||
parser.require(XmlPullParser.END_TAG, ns, "collection");
|
||||
} else {
|
||||
// Skip any other unexpected tags within <d:resourcetype>
|
||||
skip(parser);
|
||||
}
|
||||
}
|
||||
// After reading all children of <d:resourcetype>, ensure we are at its END_TAG
|
||||
parser.require(XmlPullParser.END_TAG, ns, "resourcetype");
|
||||
return isCollection;
|
||||
}
|
||||
|
||||
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
|
||||
android.util.Log.d("PARSE", "skipping " + parser.getName());
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true">
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/AppTheme">
|
||||
<activity android:name="com.crocoapps.javafilestoragetest2.MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
|
||||
@@ -548,7 +548,7 @@ public class MainActivity extends Activity implements JavaFileStorage.FileStorag
|
||||
|
||||
|
||||
//storageToTest = new GoogleDriveAppDataFileStorage();
|
||||
storageToTest = new WebDavStorage(new ICertificateErrorHandler() {
|
||||
/*storageToTest = new WebDavStorage(new ICertificateErrorHandler() {
|
||||
@Override
|
||||
public boolean onValidationError(String error) {
|
||||
return false;
|
||||
@@ -558,12 +558,12 @@ public class MainActivity extends Activity implements JavaFileStorage.FileStorag
|
||||
public boolean alwaysFailOnValidationError() {
|
||||
return false;
|
||||
}
|
||||
}, 64*1024);
|
||||
|
||||
});
|
||||
*/
|
||||
//storageToTest = new DropboxV2Storage(ctx,"4ybka4p4a1027n6", "1z5lv528un9nre8", !simulateRestart);
|
||||
//storageToTest = new DropboxFileStorage(ctx,"4ybka4p4a1027n6", "1z5lv528un9nre8", !simulateRestart);
|
||||
//storageToTest = new DropboxAppFolderFileStorage(ctx,"ax0268uydp1ya57", "3s86datjhkihwyc", true);
|
||||
// storageToTest = new GoogleDriveFullFileStorage();
|
||||
storageToTest = new GoogleDriveFullFileStorage();
|
||||
|
||||
|
||||
return storageToTest;
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="fill_parent">
|
||||
<LinearLayout
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="fill_parent"
|
||||
@@ -219,5 +216,4 @@
|
||||
android:layout_marginLeft="5dp"
|
||||
android:text="Resolve" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
</LinearLayout>
|
||||
@@ -1,7 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="fill_parent">
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="fill_parent"
|
||||
@@ -39,5 +36,4 @@
|
||||
android:hint="@string/hint_pass"
|
||||
android:importantForAccessibility="no" />
|
||||
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
</LinearLayout>
|
||||
@@ -56,15 +56,15 @@
|
||||
<string name="afc_title_sort_by">Ordina per…</string>
|
||||
<string name="afc_yesterday">Ieri</string>
|
||||
<plurals name="afc_title_choose_directories">
|
||||
<item quantity="one">Scegli cartella...</item>
|
||||
<item quantity="other">Scegli le cartelle...</item>
|
||||
<item quantity="one">Scegli la cartella…</item>
|
||||
<item quantity="other">Scegli le cartelle…</item>
|
||||
</plurals>
|
||||
<plurals name="afc_title_choose_files">
|
||||
<item quantity="one">Scegli il file</item>
|
||||
<item quantity="other">Scegli i file</item>
|
||||
<item quantity="one">Scegli il file…</item>
|
||||
<item quantity="other">Scegli i file…</item>
|
||||
</plurals>
|
||||
<plurals name="afc_title_choose_files_directories">
|
||||
<item quantity="one">Scegli file/cartella</item>
|
||||
<item quantity="other">Scegli file/cartelle</item>
|
||||
<item quantity="one">Scegli file/ cartella…</item>
|
||||
<item quantity="other">Scegli file/ cartelle…</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
|
||||
@@ -14,7 +14,7 @@ using keepass2android;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
[Activity(Label = AppNames.AppName, Theme = "@style/Kp2aTheme_BlueNoActionBar")]
|
||||
[Activity(Label = AppNames.AppName)]
|
||||
public class AppKilledInfo : Activity, IDialogInterfaceOnDismissListener
|
||||
{
|
||||
protected override void OnCreate(Bundle bundle)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -31,12 +31,6 @@ namespace keepass2android
|
||||
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(ctx);
|
||||
builder.SetTitle(ctx.GetString(Resource.String.ChangeLog_title));
|
||||
List<string> changeLog = new List<string>{
|
||||
#if !NoNet
|
||||
BuildChangelogString(ctx, new List<int>{Resource.Array.ChangeLog_1_14_net}, "1.14"),
|
||||
#endif
|
||||
|
||||
BuildChangelogString(ctx, new List<int>{Resource.Array.ChangeLog_1_13}, "1.13"),
|
||||
|
||||
BuildChangelogString(ctx, new List<int>{Resource.Array.ChangeLog_1_12
|
||||
#if !NoNet
|
||||
,Resource.Array.ChangeLog_1_12_net
|
||||
|
||||
@@ -228,9 +228,9 @@ namespace keepass2android
|
||||
newEntry.SetUuid(new PwUuid(true), true); // Create new UUID
|
||||
string strTitle = newEntry.Strings.ReadSafe(PwDefs.TitleField);
|
||||
newEntry.Strings.Set(PwDefs.TitleField, new ProtectedString(false, strTitle + " (" + Android.OS.Build.Model + ")"));
|
||||
var addTask = new AddEntry(this, App.Kp2a.CurrentDb, App.Kp2a, newEntry,item.Entry.ParentGroup,new ActionOnFinish(this, (success, message, activity) => ((ConfigureChildDatabasesActivity)activity).Update()));
|
||||
var addTask = new AddEntry( App.Kp2a.CurrentDb, App.Kp2a, newEntry,item.Entry.ParentGroup,new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a, (success, message, context) => (context as ConfigureChildDatabasesActivity)?.Update()));
|
||||
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this, addTask);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, addTask);
|
||||
pt.Run();
|
||||
|
||||
}
|
||||
@@ -260,9 +260,9 @@ namespace keepass2android
|
||||
|
||||
private void Save(AutoExecItem item)
|
||||
{
|
||||
var addTask = new SaveDb(this, App.Kp2a, App.Kp2a.FindDatabaseForElement(item.Entry), new ActionOnFinish(this, (success, message, activity) => ((ConfigureChildDatabasesActivity)activity).Update()));
|
||||
var addTask = new SaveDb(App.Kp2a, App.Kp2a.FindDatabaseForElement(item.Entry), new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a, (success, message, context) => (context as ConfigureChildDatabasesActivity)?.Update()));
|
||||
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this, addTask);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, addTask);
|
||||
pt.Run();
|
||||
}
|
||||
|
||||
@@ -343,7 +343,7 @@ namespace keepass2android
|
||||
}
|
||||
if (autoOpenGroup == null)
|
||||
{
|
||||
AddGroup addGroupTask = AddGroup.GetInstance(this, App.Kp2a, "AutoOpen", 1, null, rootGroup, null, true);
|
||||
AddGroup addGroupTask = AddGroup.GetInstance(App.Kp2a, "AutoOpen", 1, null, rootGroup, null, true);
|
||||
addGroupTask.Run();
|
||||
autoOpenGroup = addGroupTask.Group;
|
||||
}
|
||||
@@ -367,9 +367,9 @@ namespace keepass2android
|
||||
{KeeAutoExecExt.ThisDeviceId, true}
|
||||
})));
|
||||
|
||||
var addTask = new AddEntry(this, db, App.Kp2a, newEntry, autoOpenGroup, new ActionOnFinish(this, (success, message, activity) => (activity as ConfigureChildDatabasesActivity)?.Update()));
|
||||
var addTask = new AddEntry( db, App.Kp2a, newEntry, autoOpenGroup, new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a, (success, message, context) => (context as ConfigureChildDatabasesActivity)?.Update()));
|
||||
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this, addTask);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, addTask);
|
||||
pt.Run();
|
||||
}
|
||||
|
||||
|
||||
@@ -213,10 +213,9 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
// Create the new database
|
||||
CreateDb create = new CreateDb(App.Kp2a, this, _ioc, new LaunchGroupActivity(_ioc, this), false, newKey, makeCurrent);
|
||||
ProgressTask createTask = new ProgressTask(
|
||||
App.Kp2a,
|
||||
this, create);
|
||||
CreateDb create = new CreateDb(App.Kp2a, this, _ioc, new LaunchGroupActivity(_ioc, App.Kp2a, this), false, newKey, makeCurrent);
|
||||
BlockingOperationStarter createTask = new BlockingOperationStarter(
|
||||
App.Kp2a, create);
|
||||
createTask.Run();
|
||||
}
|
||||
|
||||
@@ -317,7 +316,7 @@ namespace keepass2android
|
||||
|
||||
if (resultCode == KeePass.ResultOkPasswordGenerator)
|
||||
{
|
||||
String generatedPassword = data.GetStringExtra("keepass2android.password.generated_password");
|
||||
String generatedPassword = data.GetStringExtra(GeneratePasswordActivity.GeneratedPasswordKey);
|
||||
FindViewById<TextView>(Resource.Id.entry_password).Text = generatedPassword;
|
||||
FindViewById<TextView>(Resource.Id.entry_confpassword).Text = generatedPassword;
|
||||
}
|
||||
@@ -403,14 +402,14 @@ namespace keepass2android
|
||||
|
||||
private class LaunchGroupActivity : FileOnFinish
|
||||
{
|
||||
readonly CreateDatabaseActivity _activity;
|
||||
private readonly IOConnectionInfo _ioc;
|
||||
private readonly CreateDatabaseActivity _activity;
|
||||
|
||||
public LaunchGroupActivity(IOConnectionInfo ioc, CreateDatabaseActivity activity)
|
||||
: base(activity, null)
|
||||
public LaunchGroupActivity(IOConnectionInfo ioc, IKp2aApp app, CreateDatabaseActivity activity)
|
||||
: base(app, null)
|
||||
{
|
||||
_activity = activity;
|
||||
_ioc = ioc;
|
||||
_activity = activity;
|
||||
_ioc = ioc;
|
||||
}
|
||||
|
||||
public override void Run()
|
||||
@@ -420,7 +419,7 @@ namespace keepass2android
|
||||
// Update the ongoing notification
|
||||
App.Kp2a.UpdateOngoingNotification();
|
||||
|
||||
if (PreferenceManager.GetDefaultSharedPreferences(_activity).GetBoolean(_activity.GetString(Resource.String.RememberRecentFiles_key), _activity.Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default)))
|
||||
if (PreferenceManager.GetDefaultSharedPreferences(App.Context).GetBoolean(App.Context.GetString(Resource.String.RememberRecentFiles_key), App.Context.Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default)))
|
||||
{
|
||||
// Add to recent files
|
||||
FileDbHelper dbHelper = App.Kp2a.FileDbHelper;
|
||||
|
||||
@@ -4,12 +4,12 @@ using KeePassLib.Serialization;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
class CreateNewFilename : RunnableOnFinish
|
||||
class CreateNewFilename : OperationWithFinishHandler
|
||||
{
|
||||
private readonly string _filename;
|
||||
|
||||
public CreateNewFilename(Activity activity, OnFinish finish, string filename)
|
||||
: base(activity,finish)
|
||||
public CreateNewFilename(IKp2aApp app, OnOperationFinishedHandler operationFinishedHandler, string filename)
|
||||
: base(app,operationFinishedHandler)
|
||||
{
|
||||
_filename = filename;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ using keepass2android.services.AutofillBase;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
[Activity(Label = "DisableAutofillForQueryActivity", Theme = "@style/Kp2aTheme_ActionBar")]
|
||||
[Activity(Label = "DisableAutofillForQueryActivity")]
|
||||
public class DisableAutofillForQueryActivity : Activity
|
||||
{
|
||||
public IAutofillIntentBuilder IntentBuilder = new Kp2aAutofillIntentBuilder();
|
||||
@@ -63,6 +63,8 @@ namespace keepass2android
|
||||
|
||||
prefs.Edit().PutStringSet("AutoFillDisabledQueries", disabledValues).Commit();
|
||||
|
||||
bool isManual = Intent.GetBooleanExtra(ChooseForAutofillActivityBase.ExtraIsManualRequest, false);
|
||||
|
||||
Intent reply = new Intent();
|
||||
FillResponse.Builder builder = new FillResponse.Builder();
|
||||
AssistStructure structure = (AssistStructure)Intent.GetParcelableExtra(AutofillManager.ExtraAssistStructure);
|
||||
@@ -75,7 +77,7 @@ namespace keepass2android
|
||||
StructureParser parser = new StructureParser(this, structure);
|
||||
try
|
||||
{
|
||||
parser.ParseForFill();
|
||||
parser.ParseForFill(isManual);
|
||||
|
||||
}
|
||||
catch (Java.Lang.SecurityException e)
|
||||
|
||||
@@ -56,6 +56,7 @@ using Android.Util;
|
||||
using AndroidX.Core.Content;
|
||||
using Google.Android.Material.Dialog;
|
||||
using keepass2android;
|
||||
using keepass2android.views;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
@@ -63,7 +64,7 @@ namespace keepass2android
|
||||
{
|
||||
private readonly string _binaryToSave;
|
||||
|
||||
public ExportBinaryProcessManager(int requestCode, Activity activity, string key) : base(requestCode, activity)
|
||||
public ExportBinaryProcessManager(int requestCode, LifecycleAwareActivity activity, string key) : base(requestCode, activity)
|
||||
{
|
||||
_binaryToSave = key;
|
||||
}
|
||||
@@ -75,13 +76,13 @@ namespace keepass2android
|
||||
|
||||
protected override void SaveFile(IOConnectionInfo ioc)
|
||||
{
|
||||
var task = new EntryActivity.WriteBinaryTask(_activity, App.Kp2a, new ActionOnFinish(_activity, (success, message, activity) =>
|
||||
var task = new EntryActivity.WriteBinaryTask(App.Kp2a, new ActionOnOperationFinished(App.Kp2a, (success, message, context) =>
|
||||
{
|
||||
if (!success)
|
||||
App.Kp2a.ShowMessage(activity, message, MessageSeverity.Error);
|
||||
App.Kp2a.ShowMessage(context, message, MessageSeverity.Error);
|
||||
}
|
||||
), ((EntryActivity)_activity).Entry.Binaries.Get(_binaryToSave), ioc);
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, _activity, task);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, task);
|
||||
pt.Run();
|
||||
|
||||
}
|
||||
@@ -89,6 +90,7 @@ namespace keepass2android
|
||||
public override void OnSaveInstanceState(Bundle outState)
|
||||
{
|
||||
outState.PutString("BinaryToSave", _binaryToSave);
|
||||
base.OnSaveInstanceState(outState);
|
||||
}
|
||||
|
||||
|
||||
@@ -97,7 +99,7 @@ namespace keepass2android
|
||||
|
||||
[Activity (Label = "@string/app_name", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden,
|
||||
Theme = "@style/Kp2aTheme_ActionBar")]
|
||||
public class EntryActivity : LockCloseActivity
|
||||
public class EntryActivity : LockCloseActivity, IProgressUiProvider
|
||||
{
|
||||
public const String KeyEntry = "entry";
|
||||
public const String KeyRefreshPos = "refresh_pos";
|
||||
@@ -110,6 +112,45 @@ namespace keepass2android
|
||||
|
||||
protected override View? SnackbarAnchorView => FindViewById(Resource.Id.main_content);
|
||||
|
||||
public class UpdateEntryActivityBroadcastReceiver : BroadcastReceiver
|
||||
{
|
||||
private readonly EntryActivity _activity;
|
||||
|
||||
public UpdateEntryActivityBroadcastReceiver(EntryActivity activity)
|
||||
{
|
||||
_activity = activity;
|
||||
}
|
||||
|
||||
public override void OnReceive(Context? context, Intent? intent)
|
||||
{
|
||||
if (intent?.Action == Intents.DataUpdated)
|
||||
{
|
||||
_activity.OnDataUpdated();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDataUpdated()
|
||||
{
|
||||
if (Entry == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var entryUId = Entry.Uuid;
|
||||
if (!App.Kp2a.CurrentDb.EntriesById.ContainsKey(entryUId))
|
||||
{
|
||||
Finish();
|
||||
return;
|
||||
}
|
||||
var newEntry = App.Kp2a.CurrentDb.EntriesById[entryUId];
|
||||
if (!newEntry.EqualsEntry(Entry, PwCompareOptions.None, MemProtCmpMode.Full))
|
||||
{
|
||||
Recreate();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void Launch(Activity act, PwEntry pw, int pos, AppTask appTask, ActivityFlags? flags = null, int historyIndex=-1)
|
||||
{
|
||||
Intent i = new Intent(act, typeof(EntryActivity));
|
||||
@@ -481,8 +522,8 @@ namespace keepass2android
|
||||
Entry.Expires = true;
|
||||
Entry.Touch(true);
|
||||
RequiresRefresh();
|
||||
UpdateEntry update = new UpdateEntry(this, App.Kp2a, backupEntry, Entry, null);
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this, update);
|
||||
UpdateEntry update = new UpdateEntry(App.Kp2a, backupEntry, Entry, null);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, update);
|
||||
pt.Run();
|
||||
}
|
||||
FillData();
|
||||
@@ -501,7 +542,13 @@ namespace keepass2android
|
||||
|
||||
//the rest of the things to do depends on the current app task:
|
||||
AppTask.CompleteOnCreateEntryActivity(this, notifyPluginsOnOpenThread);
|
||||
}
|
||||
|
||||
_dataUpdatedIntentReceiver = new UpdateEntryActivityBroadcastReceiver(this);
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.AddAction(Intents.DataUpdated);
|
||||
ContextCompat.RegisterReceiver(this, _dataUpdatedIntentReceiver, filter, (int)ReceiverFlags.Exported);
|
||||
|
||||
}
|
||||
|
||||
private void RemoveFromHistory()
|
||||
{
|
||||
@@ -525,13 +572,17 @@ namespace keepass2android
|
||||
App.Kp2a.DirtyGroups.Add(parent);
|
||||
}
|
||||
|
||||
var saveTask = new SaveDb(this, App.Kp2a, App.Kp2a.FindDatabaseForElement(Entry), new ActionOnFinish(this, (success, message, activity) =>
|
||||
var saveTask = new SaveDb( App.Kp2a, App.Kp2a.FindDatabaseForElement(Entry), new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a, (success, message, context) =>
|
||||
{
|
||||
activity.SetResult(KeePass.ExitRefresh);
|
||||
activity.Finish();
|
||||
if (context is Activity activity)
|
||||
{
|
||||
activity.SetResult(KeePass.ExitRefresh);
|
||||
activity.Finish();
|
||||
}
|
||||
|
||||
}));
|
||||
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this, saveTask);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, saveTask);
|
||||
pt.Run();
|
||||
}
|
||||
|
||||
@@ -1078,7 +1129,9 @@ namespace keepass2android
|
||||
UnregisterReceiver(_pluginActionReceiver);
|
||||
if (_pluginFieldReceiver != null)
|
||||
UnregisterReceiver(_pluginFieldReceiver);
|
||||
base.OnDestroy();
|
||||
if (_dataUpdatedIntentReceiver != null)
|
||||
UnregisterReceiver(_dataUpdatedIntentReceiver);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
private void NotifyPluginsOnClose()
|
||||
@@ -1260,13 +1313,13 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
|
||||
public class WriteBinaryTask : RunnableOnFinish
|
||||
public class WriteBinaryTask : OperationWithFinishHandler
|
||||
{
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly ProtectedBinary _data;
|
||||
private IOConnectionInfo _targetIoc;
|
||||
|
||||
public WriteBinaryTask(Activity activity, IKp2aApp app, OnFinish onFinish, ProtectedBinary data, IOConnectionInfo targetIoc) : base(activity, onFinish)
|
||||
public WriteBinaryTask(IKp2aApp app, OnOperationFinishedHandler onOperationFinishedHandler, ProtectedBinary data, IOConnectionInfo targetIoc) : base(app, onOperationFinishedHandler)
|
||||
{
|
||||
_app = app;
|
||||
_data = data;
|
||||
@@ -1354,6 +1407,7 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
bool isPaused = false;
|
||||
private UpdateEntryActivityBroadcastReceiver _dataUpdatedIntentReceiver;
|
||||
|
||||
protected override void OnPause()
|
||||
{
|
||||
@@ -1440,8 +1494,8 @@ namespace keepass2android
|
||||
Finish();
|
||||
return true;
|
||||
case Resource.Id.menu_delete:
|
||||
DeleteEntry task = new DeleteEntry(this, App.Kp2a, Entry,
|
||||
new ActionOnFinish(this, (success, message, activity) => { if (success) { RequiresRefresh(); Finish();}}));
|
||||
DeleteEntry task = new DeleteEntry(App.Kp2a, Entry,
|
||||
new ActionOnOperationFinished(App.Kp2a, (success, message, context) => { if (success) { RequiresRefresh(); Finish();}}));
|
||||
task.Start();
|
||||
break;
|
||||
case Resource.Id.menu_toggle_pass:
|
||||
@@ -1504,16 +1558,16 @@ namespace keepass2android
|
||||
|
||||
//save the entry:
|
||||
|
||||
ActionOnFinish closeOrShowError = new ActionOnFinish(this, (success, message, activity) =>
|
||||
ActionOnOperationFinished closeOrShowError = new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a, (success, message, context) =>
|
||||
{
|
||||
OnFinish.DisplayMessage(this, message, true);
|
||||
finishAction((EntryActivity)activity);
|
||||
OnOperationFinishedHandler.DisplayMessage(this, message, true);
|
||||
finishAction(context as EntryActivity);
|
||||
});
|
||||
|
||||
|
||||
RunnableOnFinish runnable = new UpdateEntry(this, App.Kp2a, initialEntry, newEntry, closeOrShowError);
|
||||
OperationWithFinishHandler runnable = new UpdateEntry(App.Kp2a, initialEntry, newEntry, closeOrShowError);
|
||||
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this, runnable);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, runnable);
|
||||
pt.Run();
|
||||
|
||||
}
|
||||
@@ -1546,10 +1600,10 @@ namespace keepass2android
|
||||
string url = _stringViews[urlFieldKey].Text;
|
||||
if (url == null) return false;
|
||||
|
||||
// Default https:// if no protocol specified
|
||||
// Default http:// if no protocol specified
|
||||
if ((!url.Contains(":") || (url.StartsWith("www."))))
|
||||
{
|
||||
url = "https://" + url;
|
||||
url = "http://" + url;
|
||||
}
|
||||
|
||||
try
|
||||
@@ -1603,5 +1657,7 @@ namespace keepass2android
|
||||
imageViewerIntent.PutExtra("EntryKey", key);
|
||||
StartActivity(imageViewerIntent);
|
||||
}
|
||||
}
|
||||
|
||||
public IProgressUi? ProgressUi => FindViewById<BackgroundOperationContainer>(Resource.Id.background_ops_container);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -62,7 +62,7 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds the state of the EntrryEditActivity. This is required to be able to keep a partially modified entry in memory
|
||||
/// Holds the state of the EntryEditActivity. This is required to be able to keep a partially modified entry in memory
|
||||
/// through the App variable. Serializing this state (especially the Entry/EntryInDatabase) can be a performance problem
|
||||
/// when there are big attachements.
|
||||
/// </summary>
|
||||
|
||||
@@ -19,23 +19,23 @@ namespace keepass2android
|
||||
{
|
||||
private readonly FileFormatProvider _ffp;
|
||||
|
||||
public ExportDbProcessManager(int requestCode, Activity activity, FileFormatProvider ffp) : base(requestCode, activity)
|
||||
public ExportDbProcessManager(int requestCode, LifecycleAwareActivity activity, FileFormatProvider ffp) : base(requestCode, activity)
|
||||
{
|
||||
_ffp = ffp;
|
||||
}
|
||||
|
||||
protected override void SaveFile(IOConnectionInfo ioc)
|
||||
{
|
||||
var exportDb = new ExportDatabaseActivity.ExportDb(_activity, App.Kp2a, new ActionOnFinish(_activity, (success, message, activity) =>
|
||||
var exportDb = new ExportDatabaseActivity.ExportDb(App.Kp2a, new ActionInContextInstanceOnOperationFinished(_activity.ContextInstanceId, App.Kp2a, (success, message, context) =>
|
||||
{
|
||||
if (!success)
|
||||
App.Kp2a.ShowMessage(activity, message, MessageSeverity.Error);
|
||||
App.Kp2a.ShowMessage(context, message, MessageSeverity.Error);
|
||||
else
|
||||
App.Kp2a.ShowMessage(activity, _activity.GetString(Resource.String.export_database_successful), MessageSeverity.Info);
|
||||
activity.Finish();
|
||||
App.Kp2a.ShowMessage(context, _activity.GetString(Resource.String.export_database_successful), MessageSeverity.Info);
|
||||
(context as Activity)?.Finish();
|
||||
}
|
||||
), _ffp, ioc);
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, _activity, exportDb);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, exportDb);
|
||||
pt.Run();
|
||||
|
||||
}
|
||||
@@ -93,13 +93,13 @@ namespace keepass2android
|
||||
get { return 0; }
|
||||
}
|
||||
|
||||
public class ExportDb : RunnableOnFinish
|
||||
public class ExportDb : OperationWithFinishHandler
|
||||
{
|
||||
private readonly IKp2aApp _app;
|
||||
private readonly FileFormatProvider _fileFormat;
|
||||
private IOConnectionInfo _targetIoc;
|
||||
|
||||
public ExportDb(Activity activity, IKp2aApp app, OnFinish onFinish, FileFormatProvider fileFormat, IOConnectionInfo targetIoc) : base(activity, onFinish)
|
||||
public ExportDb(IKp2aApp app, OnOperationFinishedHandler onOperationFinishedHandler, FileFormatProvider fileFormat, IOConnectionInfo targetIoc) : base(app, onOperationFinishedHandler)
|
||||
{
|
||||
_app = app;
|
||||
this._fileFormat = fileFormat;
|
||||
|
||||
@@ -12,9 +12,9 @@ namespace keepass2android
|
||||
{
|
||||
|
||||
protected readonly int _requestCode;
|
||||
protected readonly Activity _activity;
|
||||
protected readonly LifecycleAwareActivity _activity;
|
||||
|
||||
public FileSaveProcessManager(int requestCode, Activity activity)
|
||||
public FileSaveProcessManager(int requestCode, LifecycleAwareActivity activity)
|
||||
{
|
||||
_requestCode = requestCode;
|
||||
_activity = activity;
|
||||
@@ -103,7 +103,7 @@ namespace keepass2android
|
||||
}
|
||||
else
|
||||
{
|
||||
var task = new CreateNewFilename(_activity, new ActionOnFinish(_activity, (success, messageOrFilename, activity) =>
|
||||
var task = new CreateNewFilename(App.Kp2a, new ActionOnOperationFinished(App.Kp2a, (success, messageOrFilename, activity) =>
|
||||
{
|
||||
if (!success)
|
||||
{
|
||||
@@ -115,7 +115,7 @@ namespace keepass2android
|
||||
|
||||
}), filename);
|
||||
|
||||
new ProgressTask(App.Kp2a, _activity, task).Run();
|
||||
new BlockingOperationStarter(App.Kp2a, task).Run();
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -4,15 +4,12 @@ using System.Linq;
|
||||
using System.Net;
|
||||
#if !NoNet
|
||||
using FluentFTP;
|
||||
using static Kp2aBusinessLogic.Io.SmbFileStorage;
|
||||
#endif
|
||||
using System.Text;
|
||||
|
||||
using Android.App;
|
||||
using Android.Content;
|
||||
using Android.Content.Res;
|
||||
using Android.OS;
|
||||
using Android.Preferences;
|
||||
using Android.Runtime;
|
||||
using Android.Views;
|
||||
using Android.Widget;
|
||||
@@ -26,7 +23,6 @@ using Keepass2android.Javafilestorage;
|
||||
using KeePassLib.Serialization;
|
||||
using KeePassLib.Utility;
|
||||
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public class FileSelectHelper
|
||||
@@ -278,8 +274,7 @@ namespace keepass2android
|
||||
|
||||
builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
|
||||
builder.SetTitle(activity.GetString(Resource.String.enter_sftp_login_title));
|
||||
builder.SetCancelable(false);
|
||||
Dialog dialog = builder.Create();
|
||||
Dialog dialog = builder.Create();
|
||||
|
||||
dialog.Show();
|
||||
#endif
|
||||
@@ -324,7 +319,7 @@ namespace keepass2android
|
||||
View dlgContents = activity.LayoutInflater.Inflate(Resource.Layout.httpcredentials, null);
|
||||
if (!defaultPath.EndsWith(_schemeSeparator))
|
||||
{
|
||||
var webdavStorage = CreateWebdavStorage(activity);
|
||||
var webdavStorage = new Keepass2android.Javafilestorage.WebDavStorage(App.Kp2a.CertificateErrorHandler);
|
||||
var connInfo = webdavStorage.SplitStringToConnectionInfo(defaultPath);
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.http_url).Text = connInfo.Url;
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.http_user).Text = connInfo.Username;
|
||||
@@ -344,7 +339,7 @@ namespace keepass2android
|
||||
string scheme = defaultPath.Substring(0, defaultPath.IndexOf(_schemeSeparator, StringComparison.Ordinal));
|
||||
if (host.Contains(_schemeSeparator) == false)
|
||||
host = scheme + _schemeSeparator + host;
|
||||
string httpPath = CreateWebdavStorage(activity).BuildFullPath(host, user,
|
||||
string httpPath = new Keepass2android.Javafilestorage.WebDavStorage(null).BuildFullPath(host, user,
|
||||
password);
|
||||
onStartBrowse(httpPath);
|
||||
});
|
||||
@@ -352,61 +347,13 @@ namespace keepass2android
|
||||
|
||||
builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
|
||||
builder.SetTitle(activity.GetString(Resource.String.enter_http_login_title));
|
||||
builder.SetCancelable(false);
|
||||
Dialog dialog = builder.Create();
|
||||
Dialog dialog = builder.Create();
|
||||
|
||||
dialog.Show();
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
private void ShowSmbDialog(Activity activity, Util.FileSelectedHandler onStartBrowse, Action onCancel, string defaultPath)
|
||||
{
|
||||
#if !EXCLUDE_JAVAFILESTORAGE && !NoNet
|
||||
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(activity);
|
||||
View dlgContents = activity.LayoutInflater.Inflate(Resource.Layout.smbcredentials, null);
|
||||
if (!defaultPath.EndsWith(_schemeSeparator))
|
||||
{
|
||||
SmbConnectionInfo ci = new SmbConnectionInfo(new IOConnectionInfo() { Path = defaultPath });
|
||||
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.smb_url).Text = ci.GetPathWithoutCredentials();
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.smb_domain).Text = ci.Domain;
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.smb_user).Text = ci.Username;
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.smb_password).Text = ci.Password;
|
||||
|
||||
|
||||
}
|
||||
builder.SetView(dlgContents);
|
||||
builder.SetPositiveButton(Android.Resource.String.Ok,
|
||||
(sender, args) =>
|
||||
{
|
||||
string url = dlgContents.FindViewById<EditText>(Resource.Id.smb_url).Text;
|
||||
|
||||
string user = dlgContents.FindViewById<EditText>(Resource.Id.smb_user).Text;
|
||||
string password = dlgContents.FindViewById<EditText>(Resource.Id.smb_password).Text;
|
||||
string domain = dlgContents.FindViewById<EditText>(Resource.Id.smb_domain).Text;
|
||||
|
||||
string fullPath = SmbConnectionInfo.FromUrlAndCredentials(url, user, password, domain).ToPath();
|
||||
onStartBrowse(fullPath);
|
||||
});
|
||||
builder.SetCancelable(false);
|
||||
|
||||
EventHandler<DialogClickEventArgs> evtH = new EventHandler<DialogClickEventArgs>((sender, e) => onCancel());
|
||||
|
||||
builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
|
||||
builder.SetTitle(activity.GetString(Resource.String.enter_smb_login_title));
|
||||
Dialog dialog = builder.Create();
|
||||
|
||||
dialog.Show();
|
||||
#endif
|
||||
}
|
||||
#if !NoNet
|
||||
private static WebDavStorage CreateWebdavStorage(Activity activity)
|
||||
{
|
||||
return new WebDavStorage(App.Kp2a.CertificateErrorHandler, App.Kp2a.WebDavChunkedUploadSize);
|
||||
}
|
||||
#endif
|
||||
private void ShowFtpDialog(Activity activity, Util.FileSelectedHandler onStartBrowse, Action onCancel, string defaultPath)
|
||||
private void ShowFtpDialog(Activity activity, Util.FileSelectedHandler onStartBrowse, Action onCancel, string defaultPath)
|
||||
{
|
||||
#if !NoNet
|
||||
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(activity);
|
||||
@@ -456,8 +403,7 @@ namespace keepass2android
|
||||
|
||||
builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
|
||||
builder.SetTitle(activity.GetString(Resource.String.enter_ftp_login_title));
|
||||
builder.SetCancelable(false);
|
||||
Dialog dialog = builder.Create();
|
||||
Dialog dialog = builder.Create();
|
||||
|
||||
dialog.Show();
|
||||
#endif
|
||||
@@ -517,8 +463,7 @@ namespace keepass2android
|
||||
|
||||
builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
|
||||
builder.SetTitle(activity.GetString(Resource.String.enter_mega_login_title));
|
||||
builder.SetCancelable(false);
|
||||
Dialog dialog = builder.Create();
|
||||
Dialog dialog = builder.Create();
|
||||
|
||||
dialog.Show();
|
||||
#endif
|
||||
@@ -534,9 +479,7 @@ namespace keepass2android
|
||||
ShowFtpDialog(_activity, ReturnFileOrStartFileChooser, ReturnCancel, defaultPath);
|
||||
else if ((defaultPath.StartsWith("http://")) || (defaultPath.StartsWith("https://")))
|
||||
ShowHttpDialog(_activity, ReturnFileOrStartFileChooser, ReturnCancel, defaultPath);
|
||||
else if ((defaultPath.StartsWith("smb://")))
|
||||
ShowSmbDialog(_activity, ReturnFileOrStartFileChooser, ReturnCancel, defaultPath);
|
||||
else if (defaultPath.StartsWith("owncloud://"))
|
||||
else if (defaultPath.StartsWith("owncloud://"))
|
||||
ShowOwncloudDialog(_activity, ReturnFileOrStartFileChooser, ReturnCancel, defaultPath, "owncloud");
|
||||
else if (defaultPath.StartsWith("nextcloud://"))
|
||||
ShowOwncloudDialog(_activity, ReturnFileOrStartFileChooser, ReturnCancel, defaultPath, "nextcloud");
|
||||
@@ -575,7 +518,7 @@ namespace keepass2android
|
||||
string scheme = defaultPath.Substring(0,defaultPath.IndexOf(_schemeSeparator, StringComparison.Ordinal));
|
||||
if (host.Contains(_schemeSeparator) == false)
|
||||
host = scheme + _schemeSeparator + host;
|
||||
string httpPath = CreateWebdavStorage(activity).BuildFullPath(WebDavFileStorage.Owncloud2Webdav(host, subtype == "owncloud" ? WebDavFileStorage.owncloudPrefix : WebDavFileStorage.nextcloudPrefix), user,
|
||||
string httpPath = new Keepass2android.Javafilestorage.WebDavStorage(null).BuildFullPath(WebDavFileStorage.Owncloud2Webdav(host, subtype == "owncloud" ? WebDavFileStorage.owncloudPrefix : WebDavFileStorage.nextcloudPrefix), user,
|
||||
password);
|
||||
onStartBrowse(httpPath);
|
||||
});
|
||||
@@ -583,8 +526,7 @@ namespace keepass2android
|
||||
|
||||
builder.SetNegativeButton(Android.Resource.String.Cancel, evtH);
|
||||
builder.SetTitle(activity.GetString(subtype == "owncloud" ? Resource.String.enter_owncloud_login_title : Resource.String.enter_nextcloud_login_title));
|
||||
builder.SetCancelable(false);
|
||||
Dialog dialog = builder.Create();
|
||||
Dialog dialog = builder.Create();
|
||||
dlgContents.FindViewById<EditText>(Resource.Id.owncloud_url).SetHint(subtype == "owncloud" ? Resource.String.hint_owncloud_url : Resource.String.hint_nextcloud_url);
|
||||
dialog.Show();
|
||||
#endif
|
||||
@@ -725,10 +667,10 @@ namespace keepass2android
|
||||
return true;
|
||||
}
|
||||
|
||||
private void IocSelected(Activity activity, IOConnectionInfo ioc)
|
||||
private void IocSelected(Context context, IOConnectionInfo ioc)
|
||||
{
|
||||
if (OnOpen != null)
|
||||
OnOpen(activity, ioc);
|
||||
OnOpen(context, ioc);
|
||||
}
|
||||
|
||||
public bool StartFileChooser(string defaultPath)
|
||||
@@ -839,7 +781,7 @@ namespace keepass2android
|
||||
}
|
||||
else
|
||||
{
|
||||
var task = new CreateNewFilename(activity, new ActionOnFinish(activity, (success, messageOrFilename, newActivity) =>
|
||||
var task = new CreateNewFilename(App.Kp2a, new ActionOnOperationFinished(App.Kp2a, (success, messageOrFilename, newActivity) =>
|
||||
{
|
||||
if (!success)
|
||||
{
|
||||
@@ -851,7 +793,7 @@ namespace keepass2android
|
||||
|
||||
}), filename);
|
||||
|
||||
new ProgressTask(App.Kp2a, activity, task).Run();
|
||||
new BlockingOperationStarter(App.Kp2a, task).Run();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@ using Android.App;
|
||||
using Android.App.Admin;
|
||||
using Android.Content;
|
||||
using Android.Content.PM;
|
||||
using Android.Content.Res;
|
||||
using Android.Graphics;
|
||||
using Android.OS;
|
||||
using Android.Preferences;
|
||||
@@ -47,7 +46,9 @@ namespace keepass2android
|
||||
#endif
|
||||
|
||||
{
|
||||
private readonly int[] _buttonLengthButtonIds = new[] {Resource.Id.btn_length6,
|
||||
public const string GeneratedPasswordKey = "keepass2android.password.generated_password";
|
||||
|
||||
private readonly int[] _buttonLengthButtonIds = new[] {Resource.Id.btn_length6,
|
||||
Resource.Id.btn_length8,
|
||||
Resource.Id.btn_length12,
|
||||
Resource.Id.btn_length16,
|
||||
@@ -67,15 +68,10 @@ namespace keepass2android
|
||||
Resource.Id.cb_exclude_lookalike
|
||||
};
|
||||
|
||||
|
||||
|
||||
PasswordFont _passwordFont = new PasswordFont();
|
||||
|
||||
private static object _popularPasswordsLock = new object();
|
||||
private static bool _popularPasswordsInitialized = false;
|
||||
|
||||
|
||||
private ActivityDesign _design;
|
||||
private ActivityDesign _design;
|
||||
public GeneratePasswordActivity()
|
||||
{
|
||||
_design = new ActivityDesign(this);
|
||||
@@ -145,14 +141,12 @@ namespace keepass2android
|
||||
protected override void OnCreate(Bundle savedInstanceState) {
|
||||
_design.ApplyTheme();
|
||||
base.OnCreate(savedInstanceState);
|
||||
|
||||
|
||||
SetContentView(Resource.Layout.generate_password);
|
||||
SetResult(KeePass.ExitNormal);
|
||||
|
||||
|
||||
new Util.InsetListener(FindViewById(Resource.Id.main_container)).Apply();
|
||||
|
||||
|
||||
var prefs = GetPreferences(FileCreationMode.Private);
|
||||
var prefs = GetPreferences(FileCreationMode.Private);
|
||||
|
||||
|
||||
|
||||
@@ -267,7 +261,7 @@ namespace keepass2android
|
||||
EditText password = (EditText) FindViewById(Resource.Id.password_edit);
|
||||
|
||||
Intent intent = new Intent();
|
||||
intent.PutExtra("keepass2android.password.generated_password", password.Text);
|
||||
intent.PutExtra(GeneratedPasswordKey, password.Text);
|
||||
|
||||
SetResult(KeePass.ResultOkPasswordGenerator, intent);
|
||||
|
||||
@@ -310,10 +304,6 @@ namespace keepass2android
|
||||
|
||||
|
||||
EditText txtPasswordToSet = (EditText) FindViewById(Resource.Id.password_edit);
|
||||
txtPasswordToSet.TextChanged += (sender, args) =>
|
||||
{
|
||||
Task.Run(() => UpdatePasswordStrengthEstimate(txtPasswordToSet.Text));
|
||||
};
|
||||
|
||||
_passwordFont.ApplyTo(txtPasswordToSet);
|
||||
|
||||
@@ -479,76 +469,51 @@ namespace keepass2android
|
||||
return;
|
||||
|
||||
String password = "";
|
||||
|
||||
uint passwordBits = 0;
|
||||
|
||||
Task.Run(() =>
|
||||
{
|
||||
password = GeneratePassword();
|
||||
passwordBits = QualityEstimation.EstimatePasswordBits(password.ToCharArray());
|
||||
RunOnUiThread(() =>
|
||||
{
|
||||
EditText txtPassword = (EditText)FindViewById(Resource.Id.password_edit);
|
||||
txtPassword.Text = password;
|
||||
|
||||
var progressBar = FindViewById<ProgressBar>(Resource.Id.pb_password_strength);
|
||||
|
||||
progressBar.Progress = (int)passwordBits;
|
||||
progressBar.Max = 128;
|
||||
|
||||
Color color = new Color(196, 63, 49);
|
||||
if (passwordBits > 40)
|
||||
{
|
||||
color = new Color(219, 152, 55);
|
||||
}
|
||||
|
||||
if (passwordBits > 64)
|
||||
{
|
||||
color = new Color(96, 138, 38);
|
||||
}
|
||||
|
||||
if (passwordBits > 100)
|
||||
{
|
||||
color = new Color(31, 128, 31);
|
||||
}
|
||||
|
||||
progressBar.ProgressDrawable.SetColorFilter(new PorterDuffColorFilter(color,
|
||||
PorterDuff.Mode.SrcIn));
|
||||
|
||||
FindViewById<TextView>(Resource.Id.tv_password_strength).Text = " " + passwordBits + " bits";
|
||||
|
||||
|
||||
|
||||
UpdateProfileSpinnerSelection();
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
private void UpdatePasswordStrengthEstimate(string password)
|
||||
{
|
||||
lock (_popularPasswordsLock)
|
||||
{
|
||||
if (!_popularPasswordsInitialized)
|
||||
{
|
||||
|
||||
using (StreamReader sr = new StreamReader(Assets.Open("MostPopularPasswords.txt")))
|
||||
{
|
||||
var bytes = default(byte[]);
|
||||
using (var memstream = new MemoryStream())
|
||||
{
|
||||
sr.BaseStream.CopyTo(memstream);
|
||||
bytes = memstream.ToArray();
|
||||
}
|
||||
PopularPasswords.Add(bytes, false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
uint passwordBits = QualityEstimation.EstimatePasswordBits(password.ToCharArray());
|
||||
|
||||
|
||||
|
||||
|
||||
RunOnUiThread(() =>
|
||||
{
|
||||
var progressBar = FindViewById<ProgressBar>(Resource.Id.pb_password_strength);
|
||||
|
||||
progressBar.Progress = (int)passwordBits;
|
||||
progressBar.Max = 128;
|
||||
|
||||
Color color = new Color(196, 63, 49);
|
||||
if (passwordBits > 40)
|
||||
{
|
||||
color = new Color(219, 152, 55);
|
||||
}
|
||||
|
||||
if (passwordBits > 64)
|
||||
{
|
||||
color = new Color(96, 138, 38);
|
||||
}
|
||||
|
||||
if (passwordBits > 100)
|
||||
{
|
||||
color = new Color(31, 128, 31);
|
||||
}
|
||||
|
||||
progressBar.ProgressDrawable.SetColorFilter(new PorterDuffColorFilter(color,
|
||||
PorterDuff.Mode.SrcIn));
|
||||
|
||||
FindViewById<TextView>(Resource.Id.tv_password_strength).Text = " " + passwordBits + " bits";
|
||||
});
|
||||
}
|
||||
|
||||
private void UpdateProfileSpinnerSelection()
|
||||
{
|
||||
int? lastUsedIndex = _profiles.TryFindLastUsedProfileIndex();
|
||||
|
||||
@@ -223,9 +223,9 @@ namespace keepass2android
|
||||
(o, args) =>
|
||||
{
|
||||
//yes
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, this,
|
||||
new AddTemplateEntries(this, App.Kp2a, new ActionOnFinish(this,
|
||||
(success, message, activity) => ((GroupActivity)activity)?.StartAddEntry())));
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a,
|
||||
new AddTemplateEntries(App.Kp2a, new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a,
|
||||
(success, message, context) => (context as GroupActivity)?.StartAddEntry())));
|
||||
pt.Run();
|
||||
},
|
||||
(o, args) =>
|
||||
@@ -235,7 +235,7 @@ namespace keepass2android
|
||||
edit.Commit();
|
||||
//no
|
||||
StartAddEntry();
|
||||
},null, this);
|
||||
},null);
|
||||
|
||||
}
|
||||
else
|
||||
|
||||
@@ -43,11 +43,13 @@ using keepass2android;
|
||||
using KeeTrayTOTP.Libraries;
|
||||
using AndroidX.AppCompat.Widget;
|
||||
using Google.Android.Material.Dialog;
|
||||
using keepass2android.views;
|
||||
using SearchView = AndroidX.AppCompat.Widget.SearchView;
|
||||
using AndroidX.Core.Content;
|
||||
|
||||
namespace keepass2android
|
||||
{
|
||||
public abstract class GroupBaseActivity : LockCloseActivity
|
||||
public abstract class GroupBaseActivity : LockCloseActivity, IProgressUiProvider
|
||||
{
|
||||
public const String KeyEntry = "entry";
|
||||
public const String KeyMode = "mode";
|
||||
@@ -201,19 +203,18 @@ namespace keepass2android
|
||||
new PwUuid(MemUtil.HexStringToByteArray(data.Extras.GetString(GroupEditActivity.KeyCustomIconId)));
|
||||
String strGroupUuid = data.Extras.GetString(GroupEditActivity.KeyGroupUuid);
|
||||
GroupBaseActivity act = this;
|
||||
Handler handler = new Handler();
|
||||
RunnableOnFinish task;
|
||||
OperationWithFinishHandler task;
|
||||
if (strGroupUuid == null)
|
||||
{
|
||||
task = AddGroup.GetInstance(this, App.Kp2a, groupName, groupIconId, groupCustomIconId, Group, new RefreshTask(handler, this), false);
|
||||
task = AddGroup.GetInstance(App.Kp2a, groupName, groupIconId, groupCustomIconId, Group, CreateRefreshAction(), false);
|
||||
}
|
||||
else
|
||||
{
|
||||
PwUuid groupUuid = new PwUuid(MemUtil.HexStringToByteArray(strGroupUuid));
|
||||
task = new EditGroup(this, App.Kp2a, groupName, (PwIcon)groupIconId, groupCustomIconId, App.Kp2a.FindGroup(groupUuid),
|
||||
new RefreshTask(handler, this));
|
||||
task = new EditGroup(App.Kp2a, groupName, (PwIcon)groupIconId, groupCustomIconId, App.Kp2a.FindGroup(groupUuid),
|
||||
CreateRefreshAction());
|
||||
}
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, act, task);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, task);
|
||||
pt.Run();
|
||||
}
|
||||
|
||||
@@ -274,6 +275,7 @@ namespace keepass2android
|
||||
private IMenuItem searchItem;
|
||||
private IMenuItem searchItemDummy;
|
||||
private bool isPaused;
|
||||
private UpdateGroupBaseActivityBroadcastReceiver _dataUpdatedIntentReceiver;
|
||||
|
||||
protected override void OnResume()
|
||||
{
|
||||
@@ -745,9 +747,10 @@ namespace keepass2android
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
_dataUpdatedIntentReceiver = new UpdateGroupBaseActivityBroadcastReceiver(this);
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.AddAction(Intents.DataUpdated);
|
||||
ContextCompat.RegisterReceiver(this, _dataUpdatedIntentReceiver, filter, (int)ReceiverFlags.Exported);
|
||||
|
||||
SetResult(KeePass.ExitNormal);
|
||||
|
||||
@@ -894,14 +897,9 @@ namespace keepass2android
|
||||
RegisterInfoTextDisplay(
|
||||
"DbReadOnly"); //this ensures that we don't show the general info texts too soon
|
||||
|
||||
var infotext_view = FindViewById<TextView>(Resource.Id.dbreadonly_infotext_text);
|
||||
if (infotext_view != null)
|
||||
{
|
||||
infotext_view.Text =
|
||||
(GetString(Resource.String.FileReadOnlyMessagePre) + " " +
|
||||
App.Kp2a.GetResourceString(reason.Result));
|
||||
}
|
||||
|
||||
FindViewById<TextView>(Resource.Id.dbreadonly_infotext_text).Text =
|
||||
(GetString(Resource.String.FileReadOnlyMessagePre) + " " +
|
||||
App.Kp2a.GetResourceString(reason.Result));
|
||||
}
|
||||
}
|
||||
UpdateBottomBarElementVisibility(Resource.Id.dbreadonly_infotext, canShow);
|
||||
@@ -929,14 +927,14 @@ namespace keepass2android
|
||||
|
||||
|
||||
|
||||
var moveElement = new MoveElements(elementsToMove.ToList(), Group, this, App.Kp2a, new ActionOnFinish(this,
|
||||
(success, message, activity) =>
|
||||
var moveElement = new MoveElements(elementsToMove.ToList(), Group, App.Kp2a, new ActionInContextInstanceOnOperationFinished(ContextInstanceId, App.Kp2a,
|
||||
(success, message, context) =>
|
||||
{
|
||||
((GroupBaseActivity)activity)?.StopMovingElements();
|
||||
(context as GroupBaseActivity)?.StopMovingElements();
|
||||
if (!String.IsNullOrEmpty(message))
|
||||
App.Kp2a.ShowMessage(activity, message, MessageSeverity.Error);
|
||||
App.Kp2a.ShowMessage(context, message, MessageSeverity.Error);
|
||||
}));
|
||||
var progressTask = new ProgressTask(App.Kp2a, this, moveElement);
|
||||
var progressTask = new BlockingOperationStarter(App.Kp2a, moveElement);
|
||||
progressTask.Run();
|
||||
|
||||
}
|
||||
@@ -1038,6 +1036,13 @@ namespace keepass2android
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnDestroy()
|
||||
{
|
||||
UnregisterReceiver(_dataUpdatedIntentReceiver);
|
||||
base.OnDestroy();
|
||||
|
||||
}
|
||||
|
||||
public override bool OnCreateOptionsMenu(IMenu menu)
|
||||
{
|
||||
|
||||
@@ -1217,7 +1222,7 @@ namespace keepass2android
|
||||
return true;
|
||||
|
||||
case Resource.Id.menu_sync:
|
||||
new SyncUtil(this).SynchronizeDatabase(() => { });
|
||||
new SyncUtil(this).StartSynchronizeDatabase(App.Kp2a.CurrentDb.Ioc);
|
||||
return true;
|
||||
|
||||
case Resource.Id.menu_work_offline:
|
||||
@@ -1228,7 +1233,7 @@ namespace keepass2android
|
||||
case Resource.Id.menu_work_online:
|
||||
App.Kp2a.OfflineMode = App.Kp2a.OfflineModePreference = false;
|
||||
UpdateOfflineModeMenu();
|
||||
new SyncUtil(this).SynchronizeDatabase(() => { });
|
||||
new SyncUtil(this).StartSynchronizeDatabase(App.Kp2a.CurrentDb.Ioc);
|
||||
return true;
|
||||
case Resource.Id.menu_open_other_db:
|
||||
AppTask.SetActivityResult(this, KeePass.ExitLoadAnotherDb);
|
||||
@@ -1298,51 +1303,7 @@ namespace keepass2android
|
||||
|
||||
}
|
||||
|
||||
public class RefreshTask : OnFinish
|
||||
{
|
||||
public RefreshTask(Handler handler, GroupBaseActivity act)
|
||||
: base(act, handler)
|
||||
{
|
||||
}
|
||||
|
||||
public override void Run()
|
||||
{
|
||||
if (Success)
|
||||
{
|
||||
((GroupBaseActivity)ActiveActivity)?.RefreshIfDirty();
|
||||
}
|
||||
else
|
||||
{
|
||||
DisplayMessage(ActiveActivity);
|
||||
}
|
||||
}
|
||||
}
|
||||
public class AfterDeleteGroup : OnFinish
|
||||
{
|
||||
public AfterDeleteGroup(Handler handler, GroupBaseActivity act)
|
||||
: base(act, handler)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
public override void Run()
|
||||
{
|
||||
if (Success)
|
||||
{
|
||||
((GroupBaseActivity)ActiveActivity)?.RefreshIfDirty();
|
||||
}
|
||||
else
|
||||
{
|
||||
Handler.Post(() =>
|
||||
{
|
||||
App.Kp2a.ShowMessage(ActiveActivity ?? LocaleManager.LocalizedAppContext, "Unrecoverable error: " + Message, MessageSeverity.Error);
|
||||
});
|
||||
|
||||
App.Kp2a.Lock(false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public bool IsBeingMoved(PwUuid uuid)
|
||||
{
|
||||
@@ -1413,6 +1374,79 @@ namespace keepass2android
|
||||
{
|
||||
GroupEditActivity.Launch(this, pwGroup.ParentGroup, pwGroup);
|
||||
}
|
||||
|
||||
public IProgressUi ProgressUi
|
||||
{
|
||||
get
|
||||
{
|
||||
return FindViewById<BackgroundOperationContainer>(Resource.Id.background_ops_container);
|
||||
}
|
||||
}
|
||||
|
||||
public void OnDataUpdated()
|
||||
{
|
||||
if (Group == null || FragmentManager.IsDestroyed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var groupId = Group.Uuid;
|
||||
if (!App.Kp2a.CurrentDb.GroupsById.ContainsKey(groupId))
|
||||
{
|
||||
Finish();
|
||||
return;
|
||||
}
|
||||
Group = App.Kp2a.CurrentDb.GroupsById[groupId];
|
||||
var fragment = FragmentManager.FindFragmentById<GroupListFragment>(Resource.Id.list_fragment);
|
||||
if (fragment == null)
|
||||
{
|
||||
throw new Exception("did not find fragment");
|
||||
}
|
||||
fragment.ListAdapter = new PwGroupListAdapter(this, Group);
|
||||
SetGroupIcon();
|
||||
SetGroupTitle();
|
||||
ListAdapter?.NotifyDataSetChanged();
|
||||
|
||||
}
|
||||
|
||||
public OnOperationFinishedHandler CreateRefreshAction()
|
||||
{
|
||||
return new ActionInContextInstanceOnOperationFinished(
|
||||
ContextInstanceId, App.Kp2a,
|
||||
(success, message, context) =>
|
||||
{
|
||||
if (success)
|
||||
{
|
||||
RunOnUiThread(() =>
|
||||
{
|
||||
(context as GroupBaseActivity)?.RefreshIfDirty();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
App.Kp2a.ShowMessage(context, message, MessageSeverity.Error);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public class UpdateGroupBaseActivityBroadcastReceiver : BroadcastReceiver
|
||||
{
|
||||
private readonly GroupBaseActivity _groupBaseActivity;
|
||||
|
||||
public UpdateGroupBaseActivityBroadcastReceiver(GroupBaseActivity groupBaseActivity)
|
||||
{
|
||||
_groupBaseActivity = groupBaseActivity;
|
||||
}
|
||||
|
||||
public override void OnReceive(Context? context, Intent? intent)
|
||||
{
|
||||
if (intent?.Action == Intents.DataUpdated)
|
||||
{
|
||||
_groupBaseActivity.OnDataUpdated();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class GroupListFragment : ListFragment, AbsListView.IMultiChoiceModeListener
|
||||
@@ -1475,12 +1509,12 @@ namespace keepass2android
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Handler handler = new Handler();
|
||||
|
||||
switch (item.ItemId)
|
||||
{
|
||||
|
||||
case Resource.Id.menu_delete:
|
||||
DeleteMultipleItems((GroupBaseActivity)Activity, checkedItems, new GroupBaseActivity.RefreshTask(handler, ((GroupBaseActivity)Activity)), App.Kp2a);
|
||||
DeleteMultipleItems((GroupBaseActivity)Activity, checkedItems, ((GroupBaseActivity)Activity).CreateRefreshAction(), App.Kp2a);
|
||||
break;
|
||||
case Resource.Id.menu_move:
|
||||
var navMove = new NavigateToFolderAndLaunchMoveElementTask(App.Kp2a.CurrentDb, checkedItems.First().ParentGroup, checkedItems.Select(i => i.Uuid).ToList(), ((GroupBaseActivity)Activity).IsSearchResult);
|
||||
@@ -1488,10 +1522,10 @@ namespace keepass2android
|
||||
break;
|
||||
case Resource.Id.menu_copy:
|
||||
|
||||
var copyTask = new CopyEntry((GroupBaseActivity)Activity, App.Kp2a, (PwEntry)checkedItems.First(),
|
||||
new GroupBaseActivity.RefreshTask(handler, ((GroupBaseActivity)Activity)), App.Kp2a.CurrentDb);
|
||||
var copyTask = new CopyEntry(App.Kp2a, (PwEntry)checkedItems.First(),
|
||||
((GroupBaseActivity)Activity).CreateRefreshAction(), App.Kp2a.CurrentDb);
|
||||
|
||||
ProgressTask pt = new ProgressTask(App.Kp2a, Activity, copyTask);
|
||||
BlockingOperationStarter pt = new BlockingOperationStarter(App.Kp2a, copyTask);
|
||||
pt.Run();
|
||||
break;
|
||||
|
||||
@@ -1636,7 +1670,7 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
|
||||
public void DeleteMultipleItems(GroupBaseActivity activity, List<IStructureItem> checkedItems, OnFinish onFinish, Kp2aApp app)
|
||||
public void DeleteMultipleItems(GroupBaseActivity activity, List<IStructureItem> checkedItems, OnOperationFinishedHandler onOperationFinishedHandler, Kp2aApp app)
|
||||
{
|
||||
if (checkedItems.Any() == false)
|
||||
return;
|
||||
@@ -1667,30 +1701,30 @@ namespace keepass2android
|
||||
}
|
||||
|
||||
int dbIndex = 0;
|
||||
Action<bool, string, Activity> action = null;
|
||||
action = (success, message, activeActivity) =>
|
||||
Action<bool, string, Context> action = null;
|
||||
action = (success, message, context) =>
|
||||
{
|
||||
if (success)
|
||||
{
|
||||
dbIndex++;
|
||||
if (dbIndex == itemsForDatabases.Count)
|
||||
{
|
||||
onFinish.SetResult(true);
|
||||
onFinish.Run();
|
||||
onOperationFinishedHandler.SetResult(true);
|
||||
onOperationFinishedHandler.Run();
|
||||
return;
|
||||
}
|
||||
new DeleteMultipleItemsFromOneDatabase(activity, itemsForDatabases[dbIndex].Key,
|
||||
itemsForDatabases[dbIndex].Value, new ActionOnFinish(activeActivity, (b, s, activity1) => action(b, s, activity1)), app)
|
||||
itemsForDatabases[dbIndex].Value, new ActionOnOperationFinished(App.Kp2a, (b, s, activity1) => action(b, s, activity1)), app)
|
||||
.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
onFinish.SetResult(false, message, true, null);
|
||||
onOperationFinishedHandler.SetResult(false, message, true, null);
|
||||
}
|
||||
};
|
||||
|
||||
new DeleteMultipleItemsFromOneDatabase(activity, itemsForDatabases[dbIndex].Key,
|
||||
itemsForDatabases[dbIndex].Value, new ActionOnFinish(activity, (b, s, activity1) => action(b, s, activity1)), app)
|
||||
itemsForDatabases[dbIndex].Value, new ActionOnOperationFinished(App.Kp2a, (b, s, activity1) => action(b, s, activity1)), app)
|
||||
.Start();
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user