Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

feat(mobile): represerve formats + modify link banner + more account options in settings

daniel31x13a1b0fdb57fbc
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
index c16c3ff1..ab78da09 100644
--- a/apps/mobile/app.config.ts
+++ b/apps/mobile/app.config.ts
@@ -59,6 +59,15 @@ const config: ExpoConfig = {
},
],
"expo-secure-store",
+ [
+ "expo-image-picker",
+ {
+ photosPermission:
+ "Allow $(PRODUCT_NAME) to access your photos to upload custom link banners.",
+ cameraPermission: false,
+ microphonePermission: false,
+ },
+ ],
[
"expo-share-intent",
{
diff --git a/apps/mobile/app/(tabs)/dashboard/index.tsx b/apps/mobile/app/(tabs)/dashboard/index.tsx
index a028ef2a..f46f7eb0 100644
--- a/apps/mobile/app/(tabs)/dashboard/index.tsx
+++ b/apps/mobile/app/(tabs)/dashboard/index.tsx
@@ -1,6 +1,5 @@
import {
ActivityIndicator,
- Platform,
ScrollView,
StyleSheet,
Text,
diff --git a/apps/mobile/app/(tabs)/settings/index.tsx b/apps/mobile/app/(tabs)/settings/index.tsx
index dfb4f0c4..66806883 100644
--- a/apps/mobile/app/(tabs)/settings/index.tsx
+++ b/apps/mobile/app/(tabs)/settings/index.tsx
@@ -34,6 +34,7 @@ import {
UserX,
} from "lucide-react-native";
import { SheetManager } from "react-native-actions-sheet";
+import WebViewModal from "@/components/WebViewModal";
import { clearCache } from "@/lib/cache";
import {
formatBytes,
@@ -52,6 +53,7 @@ export default function SettingsScreen() {
const [override, setOverride] = useState<"light" | "dark" | "system">(
data.theme || "system"
);
+ const [showAccountSettings, setShowAccountSettings] = useState(false);
useEffect(() => {
setColorScheme(override);
@@ -97,6 +99,19 @@ export default function SettingsScreen() {
{user?.email || "@" + user?.username}
</Text>
<View className="h-px bg-neutral-content -mr-4" />
+ <TouchableOpacity
+ className="flex-row items-center mt-3 mb-3"
+ onPress={() => setShowAccountSettings(true)}
+ >
+ <Text className="flex-1 text-base text-base-content">
+ More Account Settings
+ </Text>
+ <ChevronRight
+ size={18}
+ color={rawTheme[colorScheme as ThemeName].neutral}
+ />
+ </TouchableOpacity>
+ <View className="h-px bg-neutral-content -mr-4" />
<TouchableOpacity
className="flex-row items-center mt-3"
onPress={() =>
@@ -406,6 +421,14 @@ export default function SettingsScreen() {
{nativeApplicationVersion}
</Text>
</ScrollView>
+
+ <WebViewModal
+ visible={showAccountSettings}
+ onClose={() => setShowAccountSettings(false)}
+ title="Linkwarden Web"
+ uri={`${auth.instance}/settings/account`}
+ sessionToken={auth.session}
+ />
</View>
);
}
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index fc087a9b..9e70ae02 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -42,7 +42,7 @@ export default Sentry.wrap(function RootLayout() {
const router = useRouter();
const pathname = usePathname();
- const { auth, setAuth } = useAuthStore();
+ const { setAuth } = useAuthStore();
const rootNavState = useRootNavigationState();
useEffect(() => {
diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsx
index b791b183..34191c2b 100644
--- a/apps/mobile/app/links/[id].tsx
+++ b/apps/mobile/app/links/[id].tsx
@@ -45,6 +45,8 @@ import { Chromium } from "@/components/ui/Icons";
import * as DropdownMenu from "zeego/dropdown-menu";
import { deleteLinkCache } from "@/lib/cache";
import getOriginalFormat from "@linkwarden/lib/getOriginalFormat";
+import getLinkTypeFromFormat from "@linkwarden/lib/getLinkTypeFromFormat";
+import { formatAvailable } from "@linkwarden/lib/formatStats";
import { cn } from "@linkwarden/lib/utils";
export default function LinkScreen() {
@@ -74,6 +76,29 @@ export default function LinkScreen() {
const { tmp, updateTmp } = useTmpStore();
+ const linkType = format ? getLinkTypeFromFormat(archivedFormat) : null;
+ const formatUnavailable =
+ !!linkType && !!link?.id && link[linkType] === "unavailable";
+ const formatPending =
+ !!linkType &&
+ !!link?.id &&
+ !formatUnavailable &&
+ !formatAvailable(link, linkType);
+
+ useEffect(() => {
+ if (!formatPending) return;
+
+ setIsLoading(true);
+
+ const interval = setInterval(() => {
+ refetchLink().catch((error) => {
+ console.error("Error refetching link:", error);
+ });
+ }, 5000);
+
+ return () => clearInterval(interval);
+ }, [formatPending, refetchLink]);
+
useEffect(() => {
if (link?.id && user?.id)
updateTmp({
@@ -238,6 +263,23 @@ export default function LinkScreen() {
</DropdownMenu.Item>
)}
+ {tmp.link?.url && (
+ <DropdownMenu.Item
+ key="refresh-preserved-formats"
+ onSelect={() => {
+ SheetManager.show("refresh-preserved-formats-sheet", {
+ payload: {
+ linkId: tmp.link?.id as number,
+ },
+ });
+ }}
+ >
+ <DropdownMenu.ItemTitle>
+ Refresh Preserved Formats
+ </DropdownMenu.ItemTitle>
+ </DropdownMenu.Item>
+ )}
+
{tmp.link && (
<DropdownMenu.Item
key="delete-link"
@@ -297,7 +339,23 @@ export default function LinkScreen() {
}}
/>
- {link?.id && isReadableFormat ? (
+ {formatUnavailable ? (
+ <View className="flex-1 justify-center items-center bg-base-100 p-5">
+ <Text className="text-base text-neutral">
+ Format not available...
+ </Text>
+ </View>
+ ) : formatPending ? (
+ <View className="flex-1 justify-center items-center bg-base-100 p-5">
+ <ActivityIndicator size="large" />
+ <Text className="text-base mt-2.5 text-neutral text-center">
+ Link preservation is in the queue
+ </Text>
+ <Text className="text-base text-neutral text-center">
+ Please check back later to see the result
+ </Text>
+ </View>
+ ) : link?.id && isReadableFormat ? (
<ReadableFormat
ref={readableFormatRef}
link={link as any}
@@ -341,7 +399,7 @@ export default function LinkScreen() {
</View>
)}
- {isLoading && (
+ {isLoading && !formatPending && !formatUnavailable && (
<View className="absolute inset-0 flex-1 justify-center items-center bg-base-100 p-5">
<ActivityIndicator size="large" />
<Text className="text-base mt-2.5 text-neutral">Loading...</Text>
diff --git a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
index d12bfcfa..8e5734b8 100644
--- a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
+++ b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
@@ -1,4 +1,4 @@
-import { View, Text, Alert, TouchableOpacity } from "react-native";
+import { View, Text, Alert, TouchableOpacity, Image } from "react-native";
import { useCallback, useEffect, useMemo, useState } from "react";
import ActionSheet, {
FlatList,
@@ -8,11 +8,14 @@ import ActionSheet, {
useSheetRouteParams,
useSheetRouter,
} from "react-native-actions-sheet";
+import * as ImagePicker from "expo-image-picker";
+import * as FileSystem from "expo-file-system/legacy";
import Input from "@/components/ui/Input";
import { Button } from "@/components/ui/Button";
-import { useUpdateLink } from "@linkwarden/router/links";
+import { useUpdateLink, useUpdateFile } from "@linkwarden/router/links";
import useAuthStore from "@/store/auth";
import {
+ ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
TagIncludingLinkCount,
@@ -27,7 +30,15 @@ import {
ChevronLeft,
Check,
Plus,
+ ImageUp,
} from "lucide-react-native";
+import { formatAvailable } from "@linkwarden/lib/formatStats";
+import {
+ getCachePathForFormat,
+ loadCacheOrFetch,
+ seedFormatCache,
+} from "@/lib/cache";
+import { customHeadersFor } from "@/lib/customHeaders";
import useTmpStore from "@/store/tmp";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTags } from "@linkwarden/router/tags";
@@ -45,15 +56,61 @@ const Main = (props: SheetProps<"edit-link-sheet">) => {
LinkIncludingShortenedCollectionAndTags | undefined
>(props.payload?.link);
const updateLink = useUpdateLink({ auth, Alert });
+ const updateFile = useUpdateFile({ auth, Alert });
const router = useSheetRouter("edit-link-sheet");
const { colorScheme } = useColorScheme();
+ const [currentBanner, setCurrentBanner] = useState("");
+ const [newBanner, setNewBanner] =
+ useState<ImagePicker.ImagePickerAsset | null>(null);
+
useEffect(() => {
if (params?.link) {
setLink(params.link);
}
}, [params?.link]);
+ useEffect(() => {
+ if (!link?.id) return;
+
+ loadCacheOrFetch({
+ filePath: getCachePathForFormat(link.id, "preview"),
+ setContent: setCurrentBanner,
+ shouldFetch: formatAvailable(link, "preview"),
+ updatedAt: link.updatedAt,
+ onStart: () => setCurrentBanner(""),
+ errorMessage: "Failed to fetch preview",
+ fetchContent: async (filePath) => {
+ const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`;
+
+ const result = await FileSystem.downloadAsync(apiUrl, filePath, {
+ headers: {
+ ...customHeadersFor(apiUrl),
+ Authorization: `Bearer ${auth.session}`,
+ },
+ });
+
+ return result.uri;
+ },
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [auth.instance, auth.session, link?.id, link?.preview, link?.updatedAt]);
+
+ const pickBanner = async () => {
+ const result = await ImagePicker.launchImageLibraryAsync({
+ mediaTypes: ["images"],
+ quality: 0.8,
+ });
+
+ if (!result.canceled && result.assets[0]) {
+ setNewBanner(result.assets[0]);
+ }
+ };
+
+ const bannerUri =
+ newBanner?.uri ||
+ (currentBanner ? `${currentBanner}?updatedAt=${link?.updatedAt}` : "");
+
const { tmp, updateTmp } = useTmpStore();
return (
@@ -139,8 +196,56 @@ const Main = (props: SheetProps<"edit-link-sheet">) => {
}
/>
+ <TouchableOpacity
+ activeOpacity={0.7}
+ onPress={pickBanner}
+ className="mb-4 h-36 rounded-lg bg-base-100 overflow-hidden items-center justify-center"
+ >
+ {bannerUri ? (
+ <Image
+ source={{ uri: bannerUri }}
+ resizeMode="cover"
+ className="absolute top-0 bottom-0 left-0 right-0 h-full w-full"
+ />
+ ) : null}
+
+ <View className="flex-row items-center justify-center gap-2 bg-base-200/20 w-full h-full rounded-md">
+ <View className="flex-row items-center gap-2 bg-base-200/90 rounded-md px-3 py-1.5">
+ <ImageUp
+ size={16}
+ color={rawTheme[colorScheme as ThemeName].primary}
+ />
+ <Text className="text-base-content">
+ {bannerUri ? "Change Banner" : "Upload Banner"}
+ </Text>
+ </View>
+ </View>
+ </TouchableOpacity>
+
<Button
- onPress={() => {
+ onPress={async () => {
+ if (!link) return;
+
+ if (newBanner && link.id) {
+ const uploaded = await updateFile
+ .mutateAsync({
+ linkId: link.id,
+ file: {
+ uri: newBanner.uri,
+ name: newBanner.fileName || "banner.jpg",
+ type: "image/jpeg",
+ },
+ })
+ .catch(() => null);
+
+ if (uploaded) {
+ await Promise.all([
+ seedFormatCache(link.id, "preview", newBanner.uri),
+ seedFormatCache(link.id, "jpeg", newBanner.uri),
+ ]).catch(() => {});
+ }
+ }
+
updateLink.mutate(link as LinkIncludingShortenedCollectionAndTags);
if (link && tmp.link)
updateTmp({
@@ -148,7 +253,7 @@ const Main = (props: SheetProps<"edit-link-sheet">) => {
});
SheetManager.hide("edit-link-sheet");
}}
- isLoading={updateLink.isPending}
+ isLoading={updateLink.isPending || updateFile.isPending}
variant="accent"
>
<Text className="text-white">Save</Text>
diff --git a/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx b/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx
new file mode 100644
index 00000000..57da2dd2
--- /dev/null
+++ b/apps/mobile/components/ActionSheets/RefreshPreservedFormatsSheet.tsx
@@ -0,0 +1,104 @@
+import { useRef, useState } from "react";
+import { Alert, Text, View } from "react-native";
+import ActionSheet, {
+ ActionSheetRef,
+ SheetManager,
+ SheetProps,
+} from "react-native-actions-sheet";
+import { useColorScheme } from "nativewind";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { useQueryClient } from "@tanstack/react-query";
+import useAuthStore from "@/store/auth";
+import { rawTheme, ThemeName } from "@/lib/colors";
+import { deleteLinkCache } from "@/lib/cache";
+import { Button } from "../ui/Button";
+import SheetHeader from "./SheetHeader";
+
+export default function RefreshPreservedFormatsSheet(
+ props: SheetProps<"refresh-preserved-formats-sheet">
+) {
+ const actionSheetRef = useRef<ActionSheetRef>(null);
+ const { colorScheme } = useColorScheme();
+ const theme = rawTheme[colorScheme as ThemeName];
+ const insets = useSafeAreaInsets();
+
+ const { auth } = useAuthStore();
+ const queryClient = useQueryClient();
+
+ const [loading, setLoading] = useState(false);
+
+ const linkId = props.payload?.linkId;
+
+ const closeSheet = () => {
+ actionSheetRef.current?.hide();
+ };
+
+ const handleRefresh = async () => {
+ if (!linkId || loading) return;
+
+ setLoading(true);
+
+ try {
+ const response = await fetch(
+ `${auth.instance}/api/v1/links/${linkId}/archive`,
+ {
+ method: "PUT",
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
+ );
+
+ if (!response.ok) {
+ const data = await response.json().catch(() => ({}));
+ throw new Error(
+ data?.response || "Could not refresh the preserved formats."
+ );
+ }
+
+ await deleteLinkCache(linkId);
+ queryClient.invalidateQueries({ queryKey: ["link", linkId] });
+
+ await SheetManager.hide(props.sheetId);
+ } catch (error: any) {
+ Alert.alert(
+ "Error",
+ error?.message || "Could not refresh the preserved formats."
+ );
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <ActionSheet
+ ref={actionSheetRef}
+ gestureEnabled
+ indicatorStyle={{ display: "none" }}
+ containerStyle={{ backgroundColor: theme["base-100"] }}
+ safeAreaInsets={insets}
+ >
+ <SheetHeader
+ title="Refresh Preserved Formats"
+ onClose={closeSheet}
+ align="left"
+ />
+
+ <View className="px-8 pb-5">
+ <Text className="text-base-content">
+ This will delete the current preserved formats and re-preserve this
+ link.
+ </Text>
+
+ <Button
+ onPress={handleRefresh}
+ isLoading={loading}
+ variant="destructive"
+ className="mt-5"
+ >
+ <Text className="text-white font-semibold">Refresh</Text>
+ </Button>
+ </View>
+ </ActionSheet>
+ );
+}
diff --git a/apps/mobile/components/ActionSheets/Sheets.tsx b/apps/mobile/components/ActionSheets/Sheets.tsx
index 7dfab570..6279125d 100644
--- a/apps/mobile/components/ActionSheets/Sheets.tsx
+++ b/apps/mobile/components/ActionSheets/Sheets.tsx
@@ -20,6 +20,7 @@ import VerifyEmailSheet from "./VerifyEmailSheet";
import SelfHostedServerSheet from "./SelfHostedServerSheet";
import DeleteAccountSheet from "./DeleteAccountSheet";
import WhatsNewSheet from "./WhatsNewSheet";
+import RefreshPreservedFormatsSheet from "./RefreshPreservedFormatsSheet";
import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";
registerSheet("support-sheet", SupportSheet);
@@ -37,6 +38,7 @@ registerSheet("readable-highlights-sheet", ReadableHighlightsSheet);
registerSheet("reader-settings-sheet", ReaderSettingsSheet);
registerSheet("delete-account-sheet", DeleteAccountSheet);
registerSheet("whats-new-sheet", WhatsNewSheet);
+registerSheet("refresh-preserved-formats-sheet", RefreshPreservedFormatsSheet);
declare module "react-native-actions-sheet" {
interface Sheets {
@@ -93,6 +95,11 @@ declare module "react-native-actions-sheet" {
"reader-settings-sheet": SheetDefinition;
"delete-account-sheet": SheetDefinition;
"whats-new-sheet": SheetDefinition;
+ "refresh-preserved-formats-sheet": SheetDefinition<{
+ payload: {
+ linkId: number;
+ };
+ }>;
}
}
diff --git a/apps/mobile/components/Formats/ImageFormat.tsx b/apps/mobile/components/Formats/ImageFormat.tsx
index 2a48d460..38e47ada 100644
--- a/apps/mobile/components/Formats/ImageFormat.tsx
+++ b/apps/mobile/components/Formats/ImageFormat.tsx
@@ -39,6 +39,7 @@ export default function ImageFormat({ link, setIsLoading, format }: Props) {
FileSystem.documentDirectory +
`archivedData/${extension}/link_${link.id}.${extension}`,
setContent,
+ updatedAt: link.updatedAt,
fetchContent: async (filePath) => {
const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
@@ -52,7 +53,7 @@ export default function ImageFormat({ link, setIsLoading, format }: Props) {
return result.uri;
},
});
- }, [FORMAT, auth.instance, auth.session, extension, link.id]);
+ }, [FORMAT, auth.instance, auth.session, extension, link.id, link.updatedAt]);
if (Platform.OS === "ios")
return (
diff --git a/apps/mobile/components/Formats/PdfFormat.tsx b/apps/mobile/components/Formats/PdfFormat.tsx
index 98427e68..d37c7af9 100644
--- a/apps/mobile/components/Formats/PdfFormat.tsx
+++ b/apps/mobile/components/Formats/PdfFormat.tsx
@@ -23,6 +23,7 @@ export default function PdfFormat({ link, setIsLoading }: Props) {
filePath:
FileSystem.documentDirectory + `archivedData/pdf/link_${link.id}.pdf`,
setContent,
+ updatedAt: link.updatedAt,
fetchContent: async (filePath) => {
const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
@@ -36,7 +37,7 @@ export default function PdfFormat({ link, setIsLoading }: Props) {
return result.uri;
},
});
- }, [FORMAT, auth.instance, auth.session, link.id]);
+ }, [FORMAT, auth.instance, auth.session, link.id, link.updatedAt]);
return (
content && (
diff --git a/apps/mobile/components/Formats/ReadableFormat.tsx b/apps/mobile/components/Formats/ReadableFormat.tsx
index 5a1755ff..dd04c687 100644
--- a/apps/mobile/components/Formats/ReadableFormat.tsx
+++ b/apps/mobile/components/Formats/ReadableFormat.tsx
@@ -250,6 +250,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(
FileSystem.documentDirectory +
`archivedData/readable/link_${link.id}.html`,
setContent,
+ updatedAt: link.updatedAt,
getCachedContent: (filePath) => FileSystem.readAsStringAsync(filePath),
fetchContent: async (filePath) => {
const apiUrl = `${auth.instance}/api/v1/archives/${link.id}?format=${FORMAT}`;
@@ -267,7 +268,7 @@ const ReadableFormat = forwardRef<ReadableFormatRef, Props>(
return data;
},
});
- }, [FORMAT, auth.instance, auth.session, link.id]);
+ }, [FORMAT, auth.instance, auth.session, link.id, link.updatedAt]);
const systemTheme: ThemeName = colorScheme === "dark" ? "dark" : "light";
const { theme, isDark } = resolveReaderTheme(
diff --git a/apps/mobile/components/Formats/WebpageFormat.tsx b/apps/mobile/components/Formats/WebpageFormat.tsx
index e7abc334..7c054fd2 100644
--- a/apps/mobile/components/Formats/WebpageFormat.tsx
+++ b/apps/mobile/components/Formats/WebpageFormat.tsx
@@ -27,6 +27,7 @@ export default function WebpageFormat({ link, setIsLoading }: Props) {
FileSystem.documentDirectory + `archivedData/webpage/link_${link.id}.html`,
setContent,
shouldFetch: !isConfigLoading,
+ updatedAt: link.updatedAt,
fetchContent: async (filePath) => {
const apiUrl = config?.USER_CONTENT_DOMAIN
? await getPreservedFormatUrl({
diff --git a/apps/mobile/components/LinkListing.tsx b/apps/mobile/components/LinkListing.tsx
index 2c9c5e54..592d2fb7 100644
--- a/apps/mobile/components/LinkListing.tsx
+++ b/apps/mobile/components/LinkListing.tsx
@@ -69,6 +69,7 @@ const LinkListing = ({ link, dashboard }: Props) => {
`archivedData/previews/link_${link.id}.jpg`,
setContent: setPreview,
shouldFetch: formatAvailable(link, "preview"),
+ updatedAt: link.updatedAt,
onStart: () => setPreview(""),
errorMessage: "Failed to fetch preview",
fetchContent: async (filePath) => {
@@ -175,7 +176,7 @@ const LinkListing = ({ link, dashboard }: Props) => {
preview ? (
<Image
source={{
- uri: preview,
+ uri: `${preview}?updatedAt=${link.updatedAt}`,
}}
className="rounded-md h-[60px] w-[90px] object-cover scale-105"
/>
diff --git a/apps/mobile/components/WebViewModal.tsx b/apps/mobile/components/WebViewModal.tsx
index 585a7636..5fcdd58d 100644
--- a/apps/mobile/components/WebViewModal.tsx
+++ b/apps/mobile/components/WebViewModal.tsx
@@ -1,4 +1,5 @@
-import { Modal, View } from "react-native";
+import { useEffect, useRef } from "react";
+import { Modal, Platform, View } from "react-native";
import { WebView } from "react-native-webview";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import SheetHeader from "./ActionSheets/SheetHeader";
@@ -8,26 +9,84 @@ type WebViewModalProps = {
onClose: () => void;
title: string;
uri: string;
+ sessionToken?: string | null;
};
+const buildSessionCookieScript = (sessionToken: string, uri: string) => `
+ (function () {
+ try {
+ var secure = window.location.protocol === "https:";
+ var name = (secure ? "__Secure-" : "") + "next-auth.session-token";
+ document.cookie =
+ name +
+ "=" +
+ ${JSON.stringify(sessionToken)} +
+ "; path=/; SameSite=Lax" +
+ (secure ? "; Secure" : "");
+ if (window.location.pathname.indexOf("/login") === 0) {
+ window.location.replace(${JSON.stringify(uri)});
+ }
+ } catch (e) {}
+ })();
+ true;
+`;
+
export default function WebViewModal({
visible,
onClose,
title,
uri,
+ sessionToken,
}: WebViewModalProps) {
const insets = useSafeAreaInsets();
+ const webViewRef = useRef<WebView>(null);
+ const recoveredFromLogin = useRef(false);
+
+ useEffect(() => {
+ if (visible) recoveredFromLogin.current = false;
+ }, [visible]);
+
+ const sessionCookieScript = sessionToken
+ ? buildSessionCookieScript(sessionToken, uri)
+ : undefined;
return (
<Modal visible={visible} animationType="slide" onRequestClose={onClose}>
- <View style={{ flex: 1, paddingTop: insets.top }} className="bg-base-100">
+ <View
+ style={{
+ flex: 1,
+ paddingTop: insets.top,
+ paddingBottom: Platform.OS === "android" ? insets.bottom : undefined,
+ }}
+ className="bg-base-100"
+ >
<SheetHeader
title={title}
onClose={onClose}
titleClassName="text-2xl"
align="left"
/>
- {visible && <WebView source={{ uri }} className="flex-1" />}
+ {visible && (
+ <WebView
+ ref={webViewRef}
+ source={{ uri }}
+ className="flex-1"
+ injectedJavaScriptBeforeContentLoaded={sessionCookieScript}
+ onNavigationStateChange={
+ sessionCookieScript
+ ? (navState) => {
+ if (
+ !recoveredFromLogin.current &&
+ navState.url.includes("/login")
+ ) {
+ recoveredFromLogin.current = true;
+ webViewRef.current?.injectJavaScript(sessionCookieScript);
+ }
+ }
+ : undefined
+ }
+ />
+ )}
</View>
</Modal>
);
diff --git a/apps/mobile/lib/cache.ts b/apps/mobile/lib/cache.ts
index fa97a071..f6418183 100644
--- a/apps/mobile/lib/cache.ts
+++ b/apps/mobile/lib/cache.ts
@@ -10,16 +10,20 @@ type LoadCacheOrFetchOptions<T> = {
getCachedContent?: (filePath: string) => Promise<T>;
fetchContent?: (filePath: string) => Promise<T>;
shouldFetch?: boolean;
+ updatedAt?: string | Date | null;
onStart?: () => void;
errorMessage?: string;
};
+const staleFileGraceMs = 5000;
+
export const loadCacheOrFetch = async <T = string>({
filePath,
setContent,
getCachedContent = async (filePath) => filePath as T,
fetchContent,
shouldFetch = true,
+ updatedAt,
onStart,
errorMessage = "Failed to fetch content",
}: LoadCacheOrFetchOptions<T>) => {
@@ -34,18 +38,31 @@ export const loadCacheOrFetch = async <T = string>({
const [info] = await Promise.all([FileSystem.getInfoAsync(filePath)]);
- if (info.exists) {
- const cachedContent = await getCachedContent(filePath);
- setContent(cachedContent);
+ const isStale =
+ info.exists &&
+ updatedAt != null &&
+ ((info as any).modificationTime ?? 0) * 1000 + staleFileGraceMs <
+ new Date(updatedAt).getTime();
+
+ const showCached = async () => {
+ if (info.exists) setContent(await getCachedContent(filePath));
+ };
+
+ if (!isStale) {
+ await showCached();
+
+ if (updatedAt != null && info.exists) return;
}
if (!shouldFetch || !fetchContent) {
+ if (isStale) await showCached();
return;
}
const net = await NetInfo.fetch();
if (!net.isConnected) {
+ if (isStale) await showCached();
return;
}
@@ -54,6 +71,7 @@ export const loadCacheOrFetch = async <T = string>({
setContent(freshContent);
} catch (e) {
+ if (isStale) await showCached();
console.error(errorMessage, e);
}
};
@@ -101,6 +119,23 @@ export const getCachePathForFormat = (
}
};
+export const seedFormatCache = async (
+ linkId: number,
+ format: CacheFormat,
+ sourceUri: string
+) => {
+ const filePath = getCachePathForFormat(linkId, format);
+
+ await FileSystem.makeDirectoryAsync(
+ filePath.substring(0, filePath.lastIndexOf("/")),
+ { intermediates: true }
+ ).catch(() => {});
+
+ await FileSystem.deleteAsync(filePath, { idempotent: true }).catch(() => {});
+
+ await FileSystem.copyAsync({ from: sourceUri, to: filePath });
+};
+
type FetchFormatToCacheOptions = {
link: { id: number; updatedAt?: string | Date | null };
format: CacheFormat;
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index cd1b1f46..8d67a10f 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -42,6 +42,7 @@
"expo-font": "~14.0.11",
"expo-haptics": "~15.0.8",
"expo-iap": "~4.3.6",
+ "expo-image-picker": "~17.0.11",
"expo-linking": "~8.0.11",
"expo-navigation-bar": "~5.0.10",
"expo-router": "~6.0.23",
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index 1ee33347..824b1417 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -1006,7 +1006,17 @@ const useUploadFile = () => {
});
};
-const useUpdateFile = () => {
+const useUpdateFile = ({
+ auth,
+ Alert,
+ toast,
+ t,
+}: {
+ auth?: MobileAuth;
+ Alert?: any;
+ toast?: typeof toaster;
+ t?: TFunction;
+} = {}) => {
const queryClient = useQueryClient();
return useMutation({
@@ -1016,7 +1026,7 @@ const useUpdateFile = () => {
isPreview,
}: {
linkId: number;
- file: File;
+ file: File | { uri: string; name: string; type: string };
isPreview?: boolean;
}) => {
const formBody = new FormData();
@@ -1028,21 +1038,34 @@ const useUpdateFile = () => {
if (!linkId || !file)
throw new Error("Error generating preview: Invalid parameters");
- formBody.append("file", file);
+ formBody.append("file", file as any);
const res = await fetch(
- `/api/v1/archives/${linkId}?format=` +
+ (auth?.instance ? auth?.instance : "") +
+ `/api/v1/archives/${linkId}?format=` +
format +
(isPreview ? "&preview=true" : ""),
{
body: formBody,
method: "POST",
+ headers: {
+ ...(auth?.session
+ ? { Authorization: `Bearer ${auth.session}` }
+ : {}),
+ },
}
);
- const data = res.json();
+ const data = await res.json();
- return data;
+ if (!res.ok) throw new Error(data.response);
+
+ return data.response;
+ },
+ onError: (error) => {
+ if (toast && t) toast.error(t(error.message));
+ else if (Alert)
+ Alert.alert("Error", "There was an error uploading the file.");
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["links"] });
diff --git a/yarn.lock b/yarn.lock
index be57423e..9514434b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5283,6 +5283,7 @@ __metadata:
expo-font: "npm:~14.0.11"
expo-haptics: "npm:~15.0.8"
expo-iap: "npm:~4.3.6"
+ expo-image-picker: "npm:~17.0.11"
expo-linking: "npm:~8.0.11"
expo-navigation-bar: "npm:~5.0.10"
expo-router: "npm:~6.0.23"
@@ -12985,6 +12986,26 @@ __metadata:
languageName: node
linkType: hard
+"expo-image-loader@npm:~6.0.0":
+ version: 6.0.0
+ resolution: "expo-image-loader@npm:6.0.0"
+ peerDependencies:
+ expo: "*"
+ checksum: 10c0/36f1e80d2b3d2a1cce440c7d938cd3cf3138f2b1fa706a1954e415bfae87b5b8eeaec65be0ab17880eb7585dd28c9225d056ebdb98ac81e0ffbfe880d952b0eb
+ languageName: node
+ linkType: hard
+
+"expo-image-picker@npm:~17.0.11":
+ version: 17.0.11
+ resolution: "expo-image-picker@npm:17.0.11"
+ dependencies:
+ expo-image-loader: "npm:~6.0.0"
+ peerDependencies:
+ expo: "*"
+ checksum: 10c0/4708eca0f93258b9214d4a107edeed52562ade4bc1b53c5fa6dcb1218ccdf56ba46e5993110cda81b19e6d5a52e61572e057ccbcb7efdd6a48d99f5633b178ec
+ languageName: node
+ linkType: hard
+
"expo-json-utils@npm:~0.15.0":
version: 0.15.0
resolution: "expo-json-utils@npm:0.15.0"