Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/wallet 500 download as copy #60

Merged
merged 6 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion api/apiRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ export const makeApiRequest = async <T>(
endpoint: string,
method: string = "GET",
body: unknown = null,
contentType: string | null = "application/json"
contentType: string | null = "application/json",
isBlob: boolean = false
): Promise<T> => {
const session = await SecureStore.getItemAsync(SESSION_KEY);
if (!session) return {} as T;
Expand Down Expand Up @@ -61,6 +62,10 @@ export const makeApiRequest = async <T>(
);
}

if (isBlob) {
return (await response.blob()) as unknown as T;
quanvo298Wizeline marked this conversation as resolved.
Show resolved Hide resolved
}

const responseType = response.headers.get("content-type");
if (
responseType?.includes("application/json") ||
Expand Down
10 changes: 10 additions & 0 deletions api/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,13 @@ export const getFile = async (fileId: string): Promise<Blob> => {
"GET"
);
};

export const downloadFile = async (fileId: string): Promise<Blob> => {
return makeApiRequest<Blob>(
`wallet/${encodeURIComponent(fileId)}?raw=true`,
"GET",
null,
null,
true
);
};
2 changes: 1 addition & 1 deletion app/access-prompt/confirmed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const Page: React.FC = () => {
<CustomButton
variant="primary"
title="Done"
onPress={() => router.replace("/")}
onPress={() => router.replace("/requests")}
customStyle={styles.button}
/>
</View>
Expand Down
7 changes: 7 additions & 0 deletions components/PopupMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { faImage } from "@fortawesome/free-solid-svg-icons/faImage";
import { faFile } from "@fortawesome/free-solid-svg-icons/faFile";
import { faCamera } from "@fortawesome/free-solid-svg-icons/faCamera";
import { faQrcode } from "@fortawesome/free-solid-svg-icons/faQrcode";
import { useError } from "@/hooks/useError";
import * as Linking from "expo-linking";
import { ThemedText } from "./ThemedText";

Expand All @@ -52,13 +53,19 @@ const PopupMenu: React.FC<PopupMenuProps> = ({
}) => {
const router = useRouter();
const menuRef = useRef(null);
const { showErrorMsg } = useError();

const queryClient = useQueryClient();

const mutation = useMutation({
mutationFn: postFile,
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["files"] });
},
onError: (error) => {
console.debug("A non-HTTP error occurred.", error);
showErrorMsg("Unable to save the file into your Wallet.");
},
mutationKey: ["filesMutation"],
});
if (!visible) return null;
Expand Down
6 changes: 3 additions & 3 deletions components/error/ErrorPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ const styles = StyleSheet.create({
errorPopup: {
position: "absolute",
bottom: 80,
left: 24,
right: 24,
left: 16,
right: 16,
backgroundColor: "white",
justifyContent: "space-between",
alignItems: "center",
Expand All @@ -61,7 +61,7 @@ const styles = StyleSheet.create({
},
closeView: {
alignItems: "center",
paddingLeft: 24,
paddingLeft: 8,
paddingRight: 16,
},
});
Expand Down
80 changes: 57 additions & 23 deletions components/files/BottomModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
import React, { useState } from "react";
import { View, StyleSheet, TouchableOpacity } from "react-native";
import React, { useCallback, useEffect, useState } from "react";
import {
View,
StyleSheet,
TouchableOpacity,
ActivityIndicator,
} from "react-native";
import { BottomSheetView } from "@gorhom/bottom-sheet";
import { FontAwesome6 } from "@expo/vector-icons";
import { Colors } from "@/constants/Colors";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { deleteFile, getFile } from "@/api/files";
import { deleteFile, downloadFile } from "@/api/files";
import * as Sharing from "expo-sharing";
import * as FileSystem from "expo-file-system";
import QRCode from "react-native-qrcode-svg";
Expand All @@ -43,6 +48,7 @@ const BottomModal: React.FC<BottomModalProps> = ({
onChangeSnapPoint,
}) => {
const [modalVisible, setModalVisible] = useState(false);
const [fileDownload, setFileDownload] = useState<string | null>(null);
const { data: userInfo } = useQuery<UserInfo>({
queryKey: ["userInfo"],
staleTime: Infinity,
Expand All @@ -53,27 +59,46 @@ const BottomModal: React.FC<BottomModalProps> = ({
onSuccess: () => queryClient.refetchQueries({ queryKey: ["files"] }),
mutationKey: ["filesMutation"],
});
const { data } = useQuery<Blob>({
queryKey: ["file", file?.fileName],
queryFn: () => getFile(file?.fileName as string),
});
const queryClient = useQueryClient();

const onFileShare = async (fileName: string) => {
if (!data) return;
const fr = new FileReader();
fr.onload = async () => {
const fileUri = `${FileSystem.documentDirectory}/${fileName}`;
if (typeof fr.result !== "string") {
throw new Error("An error happened while reading the file.");
}
await FileSystem.writeAsStringAsync(fileUri, fr.result?.split(",")[1], {
encoding: FileSystem.EncodingType.Base64,
const onFileShare = useCallback(
async (fileName: string) => {
const data = await queryClient.fetchQuery<Blob>({
queryKey: ["downloadFile", fileName],
queryFn: () => downloadFile(fileName),
});
await Sharing.shareAsync(fileUri);
};
fr.readAsDataURL(data);
};

setFileDownload(null);

if (!data) return;
const fr = new FileReader();
fr.onload = async () => {
const fileUri = new URL(fileName, FileSystem.documentDirectory!);
if (typeof fr.result !== "string") {
throw new Error("An error occurred while reading the file.");
}
await FileSystem.writeAsStringAsync(
fileUri.toString(),
fr.result.split(",")[1],
{
encoding: FileSystem.EncodingType.Base64,
}
);
await Sharing.shareAsync(fileUri.toString());
};
fr.readAsDataURL(data);
},
[queryClient]
);

useEffect(() => {
if (fileDownload) {
onFileShare(fileDownload).catch(() =>
console.log("Error while sharing data")
);
}
}, [fileDownload, onFileShare]);

const onDeleteFile = async (fileName: string) => {
deleteMutation
.mutateAsync(fileName)
Expand Down Expand Up @@ -108,6 +133,8 @@ const BottomModal: React.FC<BottomModalProps> = ({
)}

<ThemedText
ellipsizeMode={"tail"}
numberOfLines={1}
style={{ fontSize: 18, paddingLeft: isShowQRCode ? 16 : 0 }}
>
{formatResourceName(
Expand Down Expand Up @@ -139,12 +166,19 @@ const BottomModal: React.FC<BottomModalProps> = ({
</TouchableOpacity>
<TouchableOpacity
style={styles.fileDetailMenuContainer}
onPress={() => file && onFileShare(file?.fileName)}
onPress={() => file && setFileDownload(file?.fileName)}
>
<FontAwesome6 size={24} name="download" />
<ThemedText style={{ paddingLeft: 24, fontSize: 16 }}>
<ThemedText style={{ paddingLeft: 16, fontSize: 16 }}>
Download a copy
</ThemedText>
{Boolean(fileDownload) && (
<ActivityIndicator
style={{ paddingLeft: 24 }}
size={24}
color="#000"
/>
)}
</TouchableOpacity>
<TouchableOpacity
style={styles.fileDetailMenuContainer}
Expand Down
2 changes: 1 addition & 1 deletion components/files/FileList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ const styles = StyleSheet.create({
paddingLeft: 18,
flex: 1,
fontSize: 16,
paddingRight: 2,
paddingRight: 8,
},
menuIconContainer: {
width: 30,
Expand Down