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: Upload DB files to the Cozy instead of sending them by email #1251

Open
wants to merge 2 commits into
base: docs/document_offline_debug
Choose a base branch
from
Open
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: 0 additions & 4 deletions __tests__/jestSetupFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,3 @@ jest.mock('cozy-pouch-link', () => {
jest.mock('react-native-mail', () => ({
mail: jest.fn()
}))

jest.mock('rn-fetch-blob', () => ({
mail: jest.fn()
}))
6 changes: 0 additions & 6 deletions ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -650,8 +650,6 @@ PODS:
- React-jsi (= 0.72.12)
- React-logger (= 0.72.12)
- React-perflogger (= 0.72.12)
- rn-fetch-blob (0.12.0):
- React-Core
- RNBackgroundFetch (4.2.5):
- React-Core
- RNBackgroundGeolocation (4.16.4):
Expand Down Expand Up @@ -808,7 +806,6 @@ DEPENDENCIES:
- React-runtimescheduler (from `../node_modules/react-native/ReactCommon/react/renderer/runtimescheduler`)
- React-utils (from `../node_modules/react-native/ReactCommon/react/utils`)
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
- rn-fetch-blob (from `../node_modules/rn-fetch-blob`)
- RNBackgroundFetch (from `../node_modules/react-native-background-fetch`)
- RNBackgroundGeolocation (from `../node_modules/react-native-background-geolocation`)
- RNBootSplash (from `../node_modules/react-native-bootsplash`)
Expand Down Expand Up @@ -999,8 +996,6 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native/ReactCommon/react/utils"
ReactCommon:
:path: "../node_modules/react-native/ReactCommon"
rn-fetch-blob:
:path: "../node_modules/rn-fetch-blob"
RNBackgroundFetch:
:path: "../node_modules/react-native-background-fetch"
RNBackgroundGeolocation:
Expand Down Expand Up @@ -1148,7 +1143,6 @@ SPEC CHECKSUMS:
React-runtimescheduler: 8aea338c561b2175f47018124c076d89d3808d30
React-utils: 9a24cb88f950d1020ee55bddacbc8c16a611e2dc
ReactCommon: 76843a9bb140596351ac2786257ac9fe60cafabb
rn-fetch-blob: f065bb7ab7fb48dd002629f8bdcb0336602d3cba
RNBackgroundFetch: 2f800a04434620db15ede2e8f21886608a2d1743
RNBackgroundGeolocation: 7df16548756b443aac809663cba8a4e03f0b8732
RNBootSplash: 4844706cbb56a3270556c9b94e59dedadccd47e4
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@
"react-scripts": "4.0.3",
"redux-logger": "3.0.6",
"redux-persist": "^6.0.0",
"rn-fetch-blob": "^0.12.0",
"rn-flipper-async-storage-advanced": "^1.0.4",
"semver": "^7.3.2"
},
Expand Down
83 changes: 51 additions & 32 deletions src/pouchdb/sendDbByEmail.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { Alert, PermissionsAndroid, Platform } from 'react-native'
import { format } from 'date-fns'
import { Alert, PermissionsAndroid } from 'react-native'
import Mailer from 'react-native-mail'
import RNFS from 'react-native-fs'
import RNFetchBlob from 'rn-fetch-blob'
import DeviceInfo from 'react-native-device-info'

import type CozyClient from 'cozy-client'
// @ts-expect-error Not typed
import { getSharingLink } from 'cozy-client/dist/models/sharing'
import Minilog from 'cozy-minilog'

import { fetchSupportMail } from '/app/domain/logger/supportEmail'
import { uploadFileWithConflictStrategy } from '/app/domain/upload/services'
import {
hideSplashScreen,
showSplashScreen,
Expand Down Expand Up @@ -42,32 +45,36 @@ export const sendDbByEmail = async (client?: CozyClient): Promise<void> => {

const dbFiles = files.filter(f => f.name.startsWith(`${fqdn}_`))

const externalFiles = []
for (const dbFile of dbFiles) {
const dirs = RNFetchBlob.fs.dirs

const internalPath = dbFile.path
const token = client.getStackClient().token.accessToken

if (Platform.OS === 'android') {
const date = Number(new Date())
const externalPath = `${dirs.DCIMDir}/DbFile_${dbFile.name}${date}.sqlite`
if (!token) {
throw new Error('No token found')
}

await RNFS.copyFile(internalPath, externalPath)
const date = format(new Date(), 'yyyyMMddHHmmssSSS')
const existingLogsFolderId = await client
.collection('io.cozy.files')
.ensureDirectoryExists(`/Settings/AALogs/${date}`)

externalFiles.push({
path: externalPath
})
} else {
externalFiles.push({
path: dbFile.path,
type: 'pdf' // there is no compatible MIME type, so we use PDF one as replacement, this should change nothing expect the email aspect
})
}
for (const dbFile of dbFiles) {
const url = getUrl(client, existingLogsFolderId, dbFile.name)

log.info('Send file', dbFile.name)
await uploadFileWithConflictStrategy({
url,
token,
filename: dbFile.name,
filepath: dbFile.path,
mimetype: '.sqlite'
})
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
const link: string = await getSharingLink(client, [existingLogsFolderId])

await showSplashScreen(splashScreens.SEND_LOG_EMAIL)
log.info('Start email intent', externalFiles)
await sendMailPromise(subject, supportEmail, externalFiles).catch(
log.info('Start email intent')
await sendMailPromise(subject, supportEmail, link).catch(
(errorData: sendMailError) => {
const { error, event } = errorData
Alert.alert(
Expand Down Expand Up @@ -98,16 +105,15 @@ export const sendDbByEmail = async (client?: CozyClient): Promise<void> => {
const sendMailPromise = (
subject: string,
email: string,
attachments: Attachment[]
link: string
): Promise<void> => {
return new Promise((resolve, reject) => {
Mailer.mail(
{
subject: subject,
recipients: [email],
body: buildMessageBody(),
isHTML: true,
attachments: attachments
body: buildMessageBody(link),
isHTML: true
},
(error, event) => {
if (error) {
Expand All @@ -120,7 +126,7 @@ const sendMailPromise = (
})
}

const buildMessageBody = (): string => {
const buildMessageBody = (link: string): string => {
const appVersion = DeviceInfo.getVersion()
const appBuild = DeviceInfo.getBuildNumber()
const bundle = DeviceInfo.getBundleId()
Expand All @@ -129,18 +135,31 @@ const buildMessageBody = (): string => {
const os = DeviceInfo.getSystemName()
const version = DeviceInfo.getSystemVersion()

const linkText = `Link: ${link}`
const appInfo = `App info: ${appVersion} (${appBuild})`
const bundleInfo = `App bundle: ${bundle}`
const deviceInfo = `Device info: ${deviceBrand} ${deviceModel} ${os} ${version}`

return `${appInfo}\n${bundleInfo}\n${deviceInfo}`
return `${linkText}${appInfo}\n${bundleInfo}\n${deviceInfo}`
}

const getUrl = (client: CozyClient, dirId: string, name: string): string => {
const createdAt = new Date().toISOString()
const modifiedAt = new Date().toISOString()

const toURL = new URL(client.getStackClient().uri)
toURL.pathname = `/files/${dirId}`
toURL.searchParams.append('Name', name)
toURL.searchParams.append('Type', 'file')
toURL.searchParams.append('Tags', 'library')
toURL.searchParams.append('Executable', 'false')
toURL.searchParams.append('CreatedAt', createdAt)
toURL.searchParams.append('UpdatedAt', modifiedAt)

return toURL.toString()
}

interface sendMailError {
error: string
event?: string
}

interface Attachment {
path: string
}
22 changes: 1 addition & 21 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7167,7 +7167,7 @@ balanced-match@^1.0.0:
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==

base-64@0.1.0, base-64@^0.1.0:
base-64@^0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/base-64/-/base-64-0.1.0.tgz#780a99c84e7d600260361511c4877613bf24f6bb"
integrity sha1-eAqZyE59YAJgNhURxId2E78k9rs=
Expand Down Expand Up @@ -11042,18 +11042,6 @@ glob-to-regexp@^0.4.1:
resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e"
integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==

[email protected]:
version "7.0.6"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.0.6.tgz#211bafaf49e525b8cd93260d14ab136152b3f57a"
integrity sha512-f8c0rE8JiCxpa52kWPAOa3ZaYEnzofDzCQLCn3Vdk0Z5OVLq3BsRFJI4S4ykpeVW6QMGBUkMeUpoEgWnMTnw5Q==
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
inherits "2"
minimatch "^3.0.2"
once "^1.3.0"
path-is-absolute "^1.0.0"

[email protected]:
version "7.1.6"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6"
Expand Down Expand Up @@ -18170,14 +18158,6 @@ ripemd160@^2.0.0, ripemd160@^2.0.1:
hash-base "^3.0.0"
inherits "^2.0.1"

rn-fetch-blob@^0.12.0:
version "0.12.0"
resolved "https://registry.yarnpkg.com/rn-fetch-blob/-/rn-fetch-blob-0.12.0.tgz#ec610d2f9b3f1065556b58ab9c106eeb256f3cba"
integrity sha512-+QnR7AsJ14zqpVVUbzbtAjq0iI8c9tCg49tIoKO2ezjzRunN7YL6zFSFSWZm6d+mE/l9r+OeDM3jmb2tBb2WbA==
dependencies:
base-64 "0.1.0"
glob "7.0.6"

rn-flipper-async-storage-advanced@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/rn-flipper-async-storage-advanced/-/rn-flipper-async-storage-advanced-1.0.4.tgz#ca3d0c315a75f379fef3771cc6ee3bef2d774265"
Expand Down
Loading