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

feat: add download on DMS file #881

Merged
merged 2 commits into from
Feb 11, 2025
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
4 changes: 3 additions & 1 deletion android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
android:name=".MainApplication"
Expand Down
5 changes: 5 additions & 0 deletions changelogs/unreleased/89765_core.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"title": "Tools: add new helper to download a file in storage",
"type": "feat",
"packages": "core"
}
8 changes: 8 additions & 0 deletions ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1161,6 +1161,10 @@ PODS:
- RCT-Folly (= 2022.05.16.00)
- React-Core
- React-RCTImage
- RNShare (12.0.3):
- glog
- RCT-Folly (= 2022.05.16.00)
- React-Core
- RNStaticSafeAreaInsets (2.2.0):
- React-Core
- RNSVG (14.0.0):
Expand Down Expand Up @@ -1267,6 +1271,7 @@ DEPENDENCIES:
- RNGestureHandler (from `../node_modules/react-native-gesture-handler`)
- RNReanimated (from `../node_modules/react-native-reanimated`)
- RNScreens (from `../node_modules/react-native-screens`)
- RNShare (from `../node_modules/react-native-share`)
- RNStaticSafeAreaInsets (from `../node_modules/react-native-static-safe-area-insets`)
- RNSVG (from `../node_modules/react-native-svg`)
- RNVectorIcons (from `../node_modules/react-native-vector-icons`)
Expand Down Expand Up @@ -1419,6 +1424,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native-reanimated"
RNScreens:
:path: "../node_modules/react-native-screens"
RNShare:
:path: "../node_modules/react-native-share"
RNStaticSafeAreaInsets:
:path: "../node_modules/react-native-static-safe-area-insets"
RNSVG:
Expand Down Expand Up @@ -1508,6 +1515,7 @@ SPEC CHECKSUMS:
RNGestureHandler: 1155b1898ceddefeebf77792927360d44fe11e77
RNReanimated: 8a4d86eb951a4a99d8e86266dc71d7735c0c30a9
RNScreens: 29418ceffb585b8f0ebd363de304288c3dce8323
RNShare: 1bdc6605a311cd16363450faf740b6b531b496c1
RNStaticSafeAreaInsets: 055ddbf5e476321720457cdaeec0ff2ba40ec1b8
RNSVG: 255767813dac22db1ec2062c8b7e7b856d4e5ae6
RNVectorIcons: 73ab573085f65a572d3b6233e68996d4707fd505
Expand Down
4 changes: 4 additions & 0 deletions jest/setup-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,7 @@ jest.mock('react-native-vision-camera', () => {
});

jest.mock('@react-native-community/slider', () => 'RNSlider');

jest.mock('react-native-share', () => ({
turboModuleRegistry: jest.fn(),
}));
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"react-native-reanimated": "3.8.1",
"react-native-safe-area-context": "4.10.9",
"react-native-screens": "3.34.0",
"react-native-share": "12.0.3",
"react-native-static-safe-area-insets": "^2.2.0",
"react-native-svg": "14.0.0",
"react-native-system-navigation-bar": "2.2.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import React, {useMemo} from 'react';
import React, {useCallback, useMemo} from 'react';
import {
downloadFileOnPhone,
useDispatch,
useNavigation,
useSelector,
Expand All @@ -40,8 +41,9 @@ const DocumentActionCard = ({document}: DocumentActionCardProps) => {
const navigation = useNavigation();
const dispatch = useDispatch();

const {mobileSettings} = useSelector((state: any) => state.appConfig);
const {mobileSettings} = useSelector(state => state.appConfig);
const {user} = useSelector(state => state.user);
const {baseUrl, token, jsessionId} = useSelector(state => state.auth);

const isFavorite = useMemo(
() => user?.favouriteFileSet.some(({id}) => id === document.id),
Expand All @@ -53,14 +55,22 @@ const DocumentActionCard = ({document}: DocumentActionCardProps) => {
[isFavorite],
);

const handleDownloadFile = useCallback(async () => {
await downloadFileOnPhone(
{fileName: document.fileName, id: document.id, isMetaFile: false},
{baseUrl, token, jsessionId},
I18n,
);
}, [I18n, baseUrl, document, jsessionId, token]);

return (
<ActionCard
actionList={[
{
iconName: 'download',
helper: I18n.t('Dms_Download'),
large: true,
onPress: () => console.log('Download'),
onPress: handleDownloadFile,
hidden: !mobileSettings?.isDownloadAllowed,
},
{
Expand Down
2 changes: 2 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"react-native-mmkv": "2.12.2",
"react-native-safe-area-context": "4.10.9",
"react-native-screens": "3.34.0",
"react-native-share": "12.0.3",
"react-native-static-safe-area-insets": "^2.2.0",
"react-native-toast-message": "2.2.0",
"react-native-vision-camera": "4.2.1",
Expand All @@ -84,6 +85,7 @@
"react-native-mmkv": "2.12.2",
"react-native-reanimated": "3.8.1",
"react-native-safe-area-context": "4.10.9",
"react-native-share": "12.0.3",
"react-native-static-safe-area-insets": "^2.2.0",
"react-native-toast-message": "2.2.0",
"react-native-vision-camera": "4.2.1",
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,12 @@
"Base_Print": "Print",
"Base_PrintTemplate": "Print template",
"Base_NoRecordsFound": "No records found",
"Base_StoragePermissionRequired": "Storage permission required",
"Base_StoragePermissionDetails": "This app needs access to your storage to download files.",
"Base_ErrorOnDownload": "Something went wrong while downloading the file.",
"Base_FileDownload": "Download complete, file saved to your download folder.",
"Base_FileDownloadiOS": "Download complete, file saved.",
"Base_DownloadPermissionDenied": "The application does not have the necessary permissions to download the file.",
"Base_SliceAction_FetchFilesDetails": "fetch file details",
"Base_SliceAction_FetchMetaModule": "fetch meta modules",
"Base_SliceAction_FetchMailMessages": "fetch mail messages",
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,12 @@
"Base_Print": "Imprimer",
"Base_PrintTemplate": "Modèle d'impression",
"Base_NoRecordsFound": "Aucun enregistrement trouvé",
"Base_StoragePermissionRequired": "Accès au stockage requis",
"Base_StoragePermissionDetails": "L'application a besoin d'avoir accès à votre stockage pour télécharger des fichiers.",
"Base_ErrorOnDownload": "Il y a eu un problème lors du téléchargement du fichier.",
"Base_FileDownload": "Téléchargement complété, document sauvegardé dans votre dossier téléchargements.",
"Base_FileDownloadiOS": "Téléchargement complété, document sauvegardé.",
"Base_DownloadPermissionDenied": "L'application ne possède pas les permissions nécessaires au téléchargement du fichier.",
"Base_SliceAction_FetchFilesDetails": "récupération des détails du fichier",
"Base_SliceAction_FetchMetaModule": "récupération des modules",
"Base_SliceAction_FetchMailMessages": "récupération des mail messages",
Expand Down
132 changes: 132 additions & 0 deletions packages/core/src/tools/FileDownloader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Axelor Business Solutions
*
* Copyright (C) 2025 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import {PermissionsAndroid, Platform} from 'react-native';
import RNFetchBlob from 'react-native-blob-util';
import Share from 'react-native-share';
import {TranslatorProps} from '../i18n/hooks/use-translator';
import {showToastMessage} from '../utils/show-toast-message';

interface FileItem {
fileName: string;
id: number;
isMetaFile?: boolean;
}

interface ConnexionNeed {
baseUrl: string;
token: string;
jsessionId?: string;
}

async function requestStoragePermission(I18n: TranslatorProps) {
if (Platform.OS === 'ios') {
return true;
}

if (Number(Platform.Version) >= 33) {
return true;
}

try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: I18n.t('Base_StoragePermissionRequired'),
message: I18n.t('Base_StoragePermissionDetails'),
buttonPositive: I18n.t('Base_OK'),
buttonNegative: I18n.t('Base_Cancel'),
},
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
return false;
}
}

export const downloadFileOnPhone = async (
file: FileItem,
authentification: ConnexionNeed,
I18n: TranslatorProps,
) => {
if (file == null) return;

const hasPermission = await requestStoragePermission(I18n);

if (!hasPermission) {
showToastMessage({
type: 'error',
position: 'bottom',
text1: I18n.t('Base_Error'),
text2: I18n.t('Base_DownloadPermissionDenied'),
});
return;
}

const {config, fs} = RNFetchBlob;

const downloadUrl = file.isMetaFile
? `${authentification.baseUrl}ws/rest/com.axelor.meta.db.MetaFile/${
file.id
}/content/download`
: `${authentification.baseUrl}ws/dms/download/${file.id}`;

const downloadPath = `${Platform.OS === 'ios' ? fs.dirs.DocumentDir : fs.dirs.LegacyDownloadDir}/${file.fileName}`;

config({
fileCache: true,
path: downloadPath,
IOSBackgroundTask: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
title: file.fileName,
path: downloadPath,
description: 'Downloading file...',
mediaScannable: true,
},
})
.fetch('GET', downloadUrl, {
Cookie: `CSRF-TOKEN=${authentification.token}; ${authentification.jsessionId}`,
})
.then(async res => {
if (Platform.OS === 'ios') {
await Share.open({
url: 'file://' + res.path(),
saveToFiles: true,
}).catch(console.error);
}

showToastMessage({
type: 'success',
position: 'bottom',
text1: I18n.t('Base_Success'),
text2: I18n.t(
Platform.OS === 'ios' ? 'Base_FileDownloadiOS' : 'Base_FileDownload',
),
});
})
.catch(() => {
showToastMessage({
type: 'error',
position: 'bottom',
text1: I18n.t('Base_Error'),
text2: I18n.t('Base_ErrorOnDownload'),
});
});
};
1 change: 1 addition & 0 deletions packages/core/src/tools/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

export {clipboardProvider} from './ClipboardProvider';
export {contactProvider} from './ContactProvider';
export {downloadFileOnPhone} from './FileDownloader';
export {handleDocumentSelection} from './FilePicker';
export {openFileInExternalApp} from './FileViewer';
export {linkingProvider} from './LinkingProvider';
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -11195,6 +11195,11 @@ [email protected]:
react-freeze "^1.0.0"
warn-once "^0.1.0"

[email protected]:
version "12.0.3"
resolved "https://registry.npmjs.org/react-native-share/-/react-native-share-12.0.3.tgz#1f2d6fc0c8f1e7ec9e75e0b4915bee78e06dce5b"
integrity sha512-Bg96AjouSbcpdlI/AzWXMBwpjyWcm4NvGr49mSF1cz8aw8E1sMXwpsHa6I841SJML8Im6sRN3aXnK+/QManrtQ==

[email protected]:
version "4.5.1"
resolved "https://registry.npmjs.org/react-native-signature-canvas/-/react-native-signature-canvas-4.5.1.tgz#7b363bc6051e919c29696da181e8b9390aa3f7da"
Expand Down