Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Optimize create new credential for Android (#846)
Leendert de Borst85bb5cf944ce
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.ktindex 5051b7cf8..ce5a00977 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/AutofillService.kt@@ -133,10 +133,11 @@ class AutofillService : AutofillService() {for (credential in filteredCredentials) {responseBuilder.addDataset(createCredentialDataset(fieldFinder, credential))}++ // Add "Open AliasVault app" as the last option+ responseBuilder.addDataset(createOpenAppDataset(fieldFinder))}- // Add "Open AliasVault app" as the last option- responseBuilder.addDataset(createOpenAppDataset(fieldFinder))callback.onSuccess(responseBuilder.build())} catch (e: Exception) {Log.e(TAG, "Error parsing credentials", e)@@ -245,15 +246,22 @@ class AutofillService : AutofillService() {val presentation = RemoteViews(packageName, R.layout.autofill_dataset_item_logo)presentation.setTextViewText(R.id.text,- "AliasVault: no matches"+ "No match found, create new?")val dataSetBuilder = Dataset.Builder(presentation)- // Add a click listener to open AliasVault app- val intent = Intent(this@AutofillService, MainActivity::class.java).apply {+ // Get the app/website information to use as service URL+ val appInfo = fieldFinder.getAppInfo()+ val encodedUrl = appInfo?.let { java.net.URLEncoder.encode(it, "UTF-8") } ?: ""++ // Create deep link URL+ val deepLinkUrl = "net.aliasvault.app://credentials/add-edit-page?serviceUrl=$encodedUrl"++ // Add a click listener to open AliasVault app with deep link+ val intent = Intent(Intent.ACTION_VIEW).apply {+ data = android.net.Uri.parse(deepLinkUrl)addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- putExtra("OPEN_CREDENTIALS", true)}val pendingIntent = PendingIntent.getActivity(this@AutofillService,@@ -282,10 +290,17 @@ class AutofillService : AutofillService() {val dataSetBuilder = Dataset.Builder(openAppPresentation)- // Add a click listener to open AliasVault app- val intent = Intent(this@AutofillService, MainActivity::class.java).apply {+ // Get the app/website information to use as service URL+ val appInfo = fieldFinder.getAppInfo()+ val encodedUrl = appInfo?.let { java.net.URLEncoder.encode(it, "UTF-8") } ?: ""++ // Create deep link URL to credentials page with service URL+ val deepLinkUrl = "net.aliasvault.app://credentials?serviceUrl=$encodedUrl"++ // Add a click listener to open AliasVault app with deep link+ val intent = Intent(Intent.ACTION_VIEW).apply {+ data = android.net.Uri.parse(deepLinkUrl)addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- putExtra("OPEN_CREDENTIALS", true)}val pendingIntent = PendingIntent.getActivity(this@AutofillService,diff --git a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsxindex 418281ed4..dfc735ab2 100644--- a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx+++ b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx@@ -24,6 +24,7 @@ import { credentialSchema } from '@/utils/validationSchema';import LoadingOverlay from '@/components/LoadingOverlay';import { useAuth } from '@/context/AuthContext';import { ThemedContainer } from '@/components/themed/ThemedContainer';+import { extractServiceNameFromUrl } from '@/utils/shared/service-url';type CredentialMode = 'random' | 'manual';@@ -302,35 +303,6 @@ export default function AddEditCredentialScreen() : React.ReactNode {}}, [isEditMode, id, serviceUrl, router, executeVaultMutation, dbContext.sqliteClient, mode, generateRandomAlias, webApi, watch]);- /**- * Extract the service name from the service URL.- */- function extractServiceNameFromUrl(url: string): string {- try {- const urlObj = new URL(url);- const hostParts = urlObj.hostname.split('.');-- // Remove common subdomains- const commonSubdomains = ['www', 'app', 'login', 'auth', 'account', 'portal'];- while (hostParts.length > 2 && commonSubdomains.includes(hostParts[0].toLowerCase())) {- hostParts.shift();- }-- // For domains like google.com, return Google.com- if (hostParts.length <= 2) {- const domain = hostParts.join('.');- return domain.charAt(0).toUpperCase() + domain.slice(1);- }-- // For domains like app.example.com, return Example.com- const mainDomain = hostParts.slice(-2).join('.');- return mainDomain.charAt(0).toUpperCase() + mainDomain.slice(1);- } catch {- // If URL parsing fails, return the original URL- return url;- }- }-/*** Generate a random username.*/diff --git a/apps/mobile-app/app/(tabs)/credentials/index.tsx b/apps/mobile-app/app/(tabs)/credentials/index.tsxindex 1dda34dcd..24e2e5b8b 100644--- a/apps/mobile-app/app/(tabs)/credentials/index.tsx+++ b/apps/mobile-app/app/(tabs)/credentials/index.tsx@@ -1,7 +1,7 @@import { StyleSheet, Text, FlatList, TouchableOpacity, TextInput, RefreshControl, Platform, Animated, Alert } from 'react-native';import { useState, useEffect, useCallback, useRef, useMemo } from 'react';-import { useNavigation } from '@react-navigation/native';-import { useRouter } from 'expo-router';+import { useNavigation, useFocusEffect } from '@react-navigation/native';+import { useRouter, useLocalSearchParams } from 'expo-router';import Toast from 'react-native-toast-message';import MaterialIcons from '@expo/vector-icons/MaterialIcons';import * as Haptics from 'expo-haptics';@@ -22,6 +22,7 @@ import emitter from '@/utils/EventEmitter';import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';import { useWebApi } from '@/context/WebApiContext';import { ThemedContainer } from '@/components/themed/ThemedContainer';+import { ServiceUrlNotice } from '@/components/credentials/ServiceUrlNotice';/*** Credentials screen.@@ -36,9 +37,11 @@ export default function CredentialsScreen() : React.ReactNode {const navigation = useNavigation();const [isTabFocused, setIsTabFocused] = useState(false);const router = useRouter();+ const { serviceUrl: serviceUrlParam } = useLocalSearchParams<{ serviceUrl?: string }>();const [credentialsList, setCredentialsList] = useState<Credential[]>([]);const [isLoadingCredentials, setIsLoadingCredentials] = useMinDurationLoading(false, 200);const [refreshing, setRefreshing] = useMinDurationLoading(false, 200);+ const [serviceUrl, setServiceUrl] = useState<string | null>(null);const authContext = useAuth();const dbContext = useDb();@@ -265,6 +268,15 @@ export default function CredentialsScreen() : React.ReactNode {});}, [navigation, headerButtons]);+ // Handle deep link parameters+ useFocusEffect(+ useCallback(() => {+ // Always check the current serviceUrlParam when screen comes into focus+ const currentServiceUrl = serviceUrlParam ? decodeURIComponent(serviceUrlParam) : null;+ setServiceUrl(currentServiceUrl);+ }, [serviceUrlParam])+ );+return (<ThemedContainer><CollapsibleHeader@@ -294,6 +306,12 @@ export default function CredentialsScreen() : React.ReactNode {ListHeaderComponent={<ThemedView><TitleContainer title="Credentials" />+ {serviceUrl && (+ <ServiceUrlNotice+ serviceUrl={serviceUrl}+ onDismiss={() => setServiceUrl(null)}+ />+ )}<ThemedView style={styles.searchContainer}><MaterialIconsname="search"diff --git a/apps/mobile-app/components/credentials/ServiceUrlNotice.tsx b/apps/mobile-app/components/credentials/ServiceUrlNotice.tsxnew file mode 100644index 000000000..2a46081e6--- /dev/null+++ b/apps/mobile-app/components/credentials/ServiceUrlNotice.tsx@@ -0,0 +1,77 @@+import { StyleSheet, TouchableOpacity } from 'react-native';+import { useRouter } from 'expo-router';+import MaterialIcons from '@expo/vector-icons/MaterialIcons';++import { ThemedText } from '@/components/themed/ThemedText';+import { ThemedView } from '@/components/themed/ThemedView';+import { useColors } from '@/hooks/useColorScheme';+import { extractServiceNameFromUrl } from '@/utils/shared/service-url';++interface IServiceUrlNoticeProps {+ serviceUrl: string;+ onDismiss: () => void;+}++/**+ * A dismissable notice that appears when a service URL is provided via deep link.+ * Clicking the notice navigates to the add-edit page with the service URL.+ */+export function ServiceUrlNotice({ serviceUrl, onDismiss }: IServiceUrlNoticeProps): React.ReactNode {+ const router = useRouter();+ const colors = useColors();+ const serviceName = extractServiceNameFromUrl(serviceUrl);++ /**+ * Handle press on the notice to navigate to add-edit page+ */+ const handlePress = (): void => {+ router.push({+ pathname: '/(tabs)/credentials/add-edit',+ params: { serviceUrl }+ });+ };++ const styles = StyleSheet.create({+ container: {+ alignItems: 'center',+ backgroundColor: colors.accentBackground,+ borderRadius: 8,+ flexDirection: 'row',+ marginBottom: 16,+ padding: 12,+ },+ content: {+ alignItems: 'center',+ flex: 1,+ flexDirection: 'row',+ gap: 8,+ },+ dismissButton: {+ padding: 4,+ },+ text: {+ flex: 1,+ fontSize: 14,+ },+ });++ return (+ <ThemedView style={styles.container}>+ <TouchableOpacity+ style={styles.content}+ onPress={handlePress}+ >+ <MaterialIcons name="add-circle" size={20} color={colors.primary} />+ <ThemedText style={styles.text}>+ Create new alias for “{serviceName}”?+ </ThemedText>+ </TouchableOpacity>+ <TouchableOpacity+ style={styles.dismissButton}+ onPress={onDismiss}+ >+ <MaterialIcons name="close" size={20} color={colors.textMuted} />+ </TouchableOpacity>+ </ThemedView>+ );+}\ No newline at end of filediff --git a/apps/mobile-app/components/ui/TitleContainer.tsx b/apps/mobile-app/components/ui/TitleContainer.tsxindex d5e0ff98b..cc2b28ec5 100644--- a/apps/mobile-app/components/ui/TitleContainer.tsx+++ b/apps/mobile-app/components/ui/TitleContainer.tsx@@ -16,9 +16,9 @@ export function TitleContainer({ title, showLogo = true }: TitleContainerProps):// On Android, we don't show the title container as the native header is used, so we only return the offline banner.if (Platform.OS === 'android') {return (- <>+ <View style={styles.titleContainer}><OfflineBanner />- </>+ </View>);}diff --git a/apps/mobile-app/utils/shared/service-url.ts b/apps/mobile-app/utils/shared/service-url.tsnew file mode 100644index 000000000..705503d99--- /dev/null+++ b/apps/mobile-app/utils/shared/service-url.ts@@ -0,0 +1,34 @@+/**+ * Utility functions for handling service URLs and names+ */++/**+ * Extract the service name from a service URL.+ * @param url The service URL to extract the name from+ * @returns The extracted service name+ */+export function extractServiceNameFromUrl(url: string): string {+ try {+ const urlObj = new URL(url);+ const hostParts = urlObj.hostname.split('.');++ // Remove common subdomains+ const commonSubdomains = ['www', 'app', 'login', 'auth', 'account', 'portal'];+ while (hostParts.length > 2 && commonSubdomains.includes(hostParts[0].toLowerCase())) {+ hostParts.shift();+ }++ // For domains like google.com, return Google.com+ if (hostParts.length <= 2) {+ const domain = hostParts.join('.');+ return domain.charAt(0).toUpperCase() + domain.slice(1);+ }++ // For domains like app.example.com, return Example.com+ const mainDomain = hostParts.slice(-2).join('.');+ return mainDomain.charAt(0).toUpperCase() + mainDomain.slice(1);+ } catch {+ // If URL parsing fails, return the original URL+ return url;+ }+}\ No newline at end of file