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

Recreate a receipt for native #54358

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Changes from 3 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
acdd2e2
Add file handling utilities and enhance form data processing draft
rezkiy37 Dec 19, 2024
50c4f59
remove dev prop
rezkiy37 Dec 19, 2024
0c2b632
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Dec 19, 2024
2446bb8
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Dec 20, 2024
18d637f
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Dec 23, 2024
04cff7b
Refactor file reading logic to import readFileAsync dynamically and r…
rezkiy37 Dec 23, 2024
8dd63c2
remove import
rezkiy37 Dec 23, 2024
a9dbba9
Add initiatedOffline parameter to HTTP request handling for offline s…
rezkiy37 Dec 24, 2024
02ae8cd
Add initiatedOffline property to persistedRequest in SequentialQueueTest
rezkiy37 Dec 24, 2024
754949c
Add initiatedOffline property to persistedRequest in SequentialQueueTest
rezkiy37 Dec 24, 2024
0888f6b
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Dec 27, 2024
6f7f4a4
clean processFormData
rezkiy37 Dec 27, 2024
c1a5306
integrate prepareRequestPayload
rezkiy37 Dec 27, 2024
e12d29c
integrate prepareRequestPayload
rezkiy37 Dec 27, 2024
3a389bf
clean
rezkiy37 Dec 27, 2024
b899c11
lazy load readFileAsync in prepareRequestPayload
rezkiy37 Dec 28, 2024
38b1224
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Dec 28, 2024
713c51f
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Jan 7, 2025
8841ac4
Merge branch 'main' of https://github.com/rezkiy37/Expensify into fix…
rezkiy37 Jan 10, 2025
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
110 changes: 101 additions & 9 deletions src/libs/HttpUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {Platform} from 'react-native';
rezkiy37 marked this conversation as resolved.
Show resolved Hide resolved
import Onyx from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import alert from '@components/Alert';
Expand Down Expand Up @@ -150,6 +151,94 @@ function processHTTPRequest(url: string, method: RequestType = 'get', body: Form
});
}

/**
* Returns the filename replacing special characters with underscore
*/
function cleanFileName(fileName: string): string {
return fileName.replace(/[^a-zA-Z0-9\-._]/g, '_');
}

type ReadFileAsync = (path: string, fileName: string, fileType?: string) => Promise<File | void>;

/**
* Reads a locally uploaded file
* @param path - the blob url of the locally uploaded file
* @param fileName - name of the file to read
*/
const readFileAsync: ReadFileAsync = (path, fileName, fileType = '') =>
new Promise((resolve) => {
if (!path) {
resolve();
return;
}
fetch(path)
.then((res) => {
// For some reason, fetch is "Unable to read uploaded file"
// on Android even though the blob is returned, so we'll ignore
// in that case
if (!res.ok && Platform.OS !== 'android') {
throw Error(res.statusText);
}
res.blob()
.then((blob) => {
// On Android devices, fetching blob for a file with name containing spaces fails to retrieve the type of file.
// In this case, let us fallback on fileType provided by the caller of this function.
const file = new File([blob], cleanFileName(fileName), {type: blob.type || fileType});
file.source = path;
// For some reason, the File object on iOS does not have a uri property
// so images aren't uploaded correctly to the backend
file.uri = path;
resolve(file);
})
.catch((e) => {
console.debug('[FileUtils] Could not read uploaded file', e);
resolve();
});
})
.catch((e) => {
console.debug('[FileUtils] Could not read uploaded file', e);
resolve();
});
});

function processFormData(data: Record<string, unknown>): Promise<FormData> {
const formData = new FormData();
let promiseChain = Promise.resolve();

Object.keys(data).forEach((key) => {
promiseChain = promiseChain.then(() => {
if (typeof data[key] === 'undefined') {
return Promise.resolve();
}

if (key === CONST.SEARCH.TABLE_COLUMNS.RECEIPT) {
const {uri: path = '', source} = data[key] as File;

console.debug('[dev] data[key]:', data[key]);
console.debug('[dev] path', path);
console.debug('[dev] source', source);

return readFileAsync(source, path)
.then((file) => {
console.debug('[dev] file', file);
if (file) {
formData.append(key, file);
}
})
.catch(() => {
console.debug('[dev] Error reading photo');
});
}

formData.append(key, data[key] as string | Blob);

return Promise.resolve();
});
});

return promiseChain.then(() => formData);
}

/**
* Makes XHR request
* @param command the name of the API command
Expand All @@ -158,18 +247,21 @@ function processHTTPRequest(url: string, method: RequestType = 'get', body: Form
* @param shouldUseSecure should we use the secure server
*/
function xhr(command: string, data: Record<string, unknown>, type: RequestType = CONST.NETWORK.METHOD.POST, shouldUseSecure = false): Promise<Response> {
const formData = new FormData();
Object.keys(data).forEach((key) => {
if (typeof data[key] === 'undefined') {
return;
if (command === 'RequestMoney') {
console.debug('[dev] data:', data);
}

return processFormData(data).then((formData) => {
if (command === 'RequestMoney') {
console.debug('[dev] formData:', formData);
console.debug("[dev] formData.getAll('receipt'):", formData.getAll('receipt'));
}
formData.append(key, data[key] as string | Blob);
});

const url = ApiUtils.getCommandURL({shouldUseSecure, command});
const url = ApiUtils.getCommandURL({shouldUseSecure, command});

const abortSignalController = data.canCancel ? abortControllerMap.get(command as AbortCommand) ?? abortControllerMap.get(ABORT_COMMANDS.All) : undefined;
return processHTTPRequest(url, type, formData, abortSignalController?.signal);
const abortSignalController = data.canCancel ? abortControllerMap.get(command as AbortCommand) ?? abortControllerMap.get(ABORT_COMMANDS.All) : undefined;
return processHTTPRequest(url, type, formData, abortSignalController?.signal);
});
}

function cancelPendingRequests(command: AbortCommand = ABORT_COMMANDS.All) {
Expand Down
Loading