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

Backup: Lots of fixes, refactoring and documentation #887

Merged
merged 18 commits into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
d0597f6
fix(backup): Upload could crash when response body undefined
zatteo Jul 27, 2023
826d3c5
fix(backup): Stop backup only if quota exceeded and not if file too l…
zatteo Jul 27, 2023
a17d491
refactor(backup): Create an upload service distinct from Media model
zatteo Jul 27, 2023
fe5822f
feat(backup): Create backups in /Photos instead of /
zatteo Jul 28, 2023
d332981
fix(backup): Set backup as to do on new start after killing app
zatteo Jul 27, 2023
b5d3084
feat(backup): Disable album management on Android
zatteo Jul 28, 2023
ce52f19
fix(backup): Stop considering trashed files as backuped when restoring
zatteo Jul 28, 2023
82ba33b
fix(backup): Fix restoring when media at backup root path
zatteo Jul 28, 2023
2a1d096
fix(backup): Try to fix "stream was reset: CANCEL" error
zatteo Jul 28, 2023
84c256b
fix(backup): Allow users to rename is backup folder
zatteo Jul 28, 2023
a187a28
feat(backup): Send modification date when uploading
zatteo Jul 28, 2023
1d9348e
feat(backup): Duplicate file and append a number when upload conflict
zatteo Jul 28, 2023
9b50fba
docs(backup): Add schema about backup
zatteo Jul 28, 2023
321c68d
Revert "fix(backup): Try to fix "stream was reset: CANCEL" error"
Crash-- Jul 31, 2023
d7ba638
fix: Add Size to upload URL
Crash-- Jul 31, 2023
c4aa505
chore: Add a task to generate the dependancies graph
Crash-- Aug 1, 2023
d0cfea6
fix: Use okhttp5.0.0-alpha.1 for react-native-background-upload
Crash-- Aug 1, 2023
f7cf0f8
fix: Better check for Upload error type in `uploadMedias()`
Ldoppea Aug 3, 2023
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
10 changes: 5 additions & 5 deletions patches/react-native-background-upload+6.6.0.patch
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ index c89d495..5da9d14 100644
import net.gotev.uploadservice.network.ServerResponse
import net.gotev.uploadservice.observer.request.RequestObserverDelegate
+import net.gotev.uploadservice.exceptions.UploadError

class GlobalRequestObserverDelegate(reactContext: ReactApplicationContext) : RequestObserverDelegate {
private val TAG = "UploadReceiver"
@@ -28,6 +29,10 @@ class GlobalRequestObserverDelegate(reactContext: ReactApplicationContext) : Req
Expand All @@ -26,11 +26,11 @@ index 8b2a07c..80cff93 100644
--- a/node_modules/react-native-background-upload/index.d.ts
+++ b/node_modules/react-native-background-upload/index.d.ts
@@ -11,6 +11,8 @@ declare module "react-native-background-upload" {

export interface ErrorData extends EventData {
error: string
+ responseCode: number
+ responseBody: string
+ responseCode?: number
+ responseBody?: string
}

export interface CompletedData extends EventData {
4 changes: 4 additions & 0 deletions src/@types/cozy-client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ declare module 'cozy-client' {
) => Promise<{ included: { attributes: unknown }[] }>
createDirectoryByPath: (path: string) => Promise<FileCollectionGetResult>
ensureDirectoryExists: (path: string) => Promise<string>
getDirectoryOrCreate: (
name: string,
parentDirectory: object
) => Promise<FileCollectionGetResult>
createFileMetadata: (metadata: object) => Promise<{ data: { id: string } }>
addReferencesTo: (references: object, dirs: object[]) => Promise<void>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
15 changes: 12 additions & 3 deletions src/app/domain/backup/helpers/error.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { UploadError } from '/app/domain/upload/models'

export class BackupError extends Error {
statusCode: number | undefined

Expand All @@ -13,6 +15,13 @@ export class BackupError extends Error {
}
}

export const STACK_ERRORS_INTERRUPTING_BACKUP = [
413 // quota exceeded
]
export const isQuotaExceededError = (error: UploadError): boolean => {
return (
error.statusCode === 413 &&
error.errors[0].detail === 'The file is too big and exceeds the disk quota'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error.errors content should be checked first here to prevent undefined access error if error[0] does not exist

)
}

export const isFatalError = (error: UploadError): boolean => {
return isQuotaExceededError(error)
}
12 changes: 0 additions & 12 deletions src/app/domain/backup/models/Media.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { StackErrors, IOCozyFile } from 'cozy-client'

import { Album } from '/app/domain/backup/models'

/**
Expand Down Expand Up @@ -30,13 +28,3 @@ export interface BackupedMedia {
name: string
remotePath: string
}

export type UploadMediaError = {
statusCode: number
} & StackErrors

// These type is incomplete there is more information in data
export interface UploadMediaResult {
statusCode: number
data: IOCozyFile
}
2 changes: 1 addition & 1 deletion src/app/domain/backup/services/manageBackup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
import {
cancelUpload,
getCurrentUploadId
} from '/app/domain/backup/services/uploadMedia'
} from '/app/domain/upload/services/upload'
import {
fetchDeviceRemoteBackupConfig,
fetchBackupedMedias,
Expand Down
59 changes: 58 additions & 1 deletion src/app/domain/backup/services/manageRemoteBackupConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ import { IOCozyFile } from 'cozy-client/types/types'
const DOCTYPE_APPS = 'io.cozy.apps'
const DOCTYPE_FILES = 'io.cozy.files'
const BACKUP_REF = `io.cozy.apps/photos/mobile`
const PHOTOS_REF = `io.cozy.apps/photos`

interface Folder {
_id: string
attributes: {
name: string
path: string
}
}

interface BackupFolder {
_id: string
Expand Down Expand Up @@ -119,17 +128,65 @@ const createRemoteBackupFolderWithConflictStrategy = async (
}
}

export const getOrCreatePhotosMagicFolder = async (
Crash-- marked this conversation as resolved.
Show resolved Hide resolved
client: CozyClient
): Promise<Folder> => {
const { included } = await client.collection(DOCTYPE_FILES).findReferencedBy({
_type: DOCTYPE_APPS,
_id: PHOTOS_REF
})

let photosMagicFolders = included as Folder[]

photosMagicFolders = photosMagicFolders.filter(
folder => !isInTrash(folder.attributes.path)
)

if (photosMagicFolders.length > 0) {
return photosMagicFolders[0]
}

const { data: newPhotosMagicFolder } = await client
.collection(DOCTYPE_FILES)
.createDirectoryByPath('/Photos')
Crash-- marked this conversation as resolved.
Show resolved Hide resolved

await client.collection(DOCTYPE_FILES).addReferencesTo(
{
_id: PHOTOS_REF,
_type: DOCTYPE_APPS
},
[
{
_id: newPhotosMagicFolder._id
}
]
)

return {
_id: newPhotosMagicFolder._id,
attributes: {
name: newPhotosMagicFolder.name,
path: newPhotosMagicFolder.path
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pourquoi ne pas retourner tout newPhotosMagicFolder? 🤔

}

export const createRemoteBackupFolder = async (
client: CozyClient
): Promise<RemoteBackupConfig> => {
const deviceName = await getDeviceName()
const deviceId = await getDeviceId()

const photosMagicFolder = await getOrCreatePhotosMagicFolder(client)

const {
data: { _id: backupRootId }
} = await client
.collection(DOCTYPE_FILES)
.createDirectoryByPath(t('services.backup.backupRootPath'))
.getDirectoryOrCreate(
t('services.backup.backupRootName'),
photosMagicFolder
)

const backupFolderAttributes = {
type: 'directory',
Expand Down
132 changes: 32 additions & 100 deletions src/app/domain/backup/services/uploadMedia.android.ts
Original file line number Diff line number Diff line change
@@ -1,114 +1,46 @@
/* eslint-disable promise/always-return */
import RNBackgroundUpload, {
UploadOptions
} from 'react-native-background-upload'

import { getMimeType } from '/app/domain/backup/services/getMedias'
import { Media, UploadMediaResult } from '/app/domain/backup/models/Media'
import { Media } from '/app/domain/backup/models/Media'
import { t } from '/locales/i18n'

import CozyClient, { StackErrors, IOCozyFile } from 'cozy-client'

let currentUploadId: string | undefined
import CozyClient from 'cozy-client'

export const getCurrentUploadId = (): string | undefined => {
return currentUploadId
}

const setCurrentUploadId = (value: string): void => {
currentUploadId = value
}
import { uploadFile } from '/app/domain/upload/services/upload'
import { UploadResult } from '/app/domain/upload/models'

export const uploadMedia = async (
client: CozyClient,
uploadUrl: string,
media: Media
): Promise<UploadMediaResult> => {
): Promise<UploadResult> => {
const filepath = media.path.replace('file://', '')

return new Promise((resolve, reject) => {
const options = {
url: uploadUrl,
path: filepath,
method: 'POST',
type: 'raw',
headers: {
Accept: 'application/json',
'Content-Type': getMimeType(media),
Authorization: `Bearer ${
// @ts-expect-error Type issue which will be fixed in another PR
client.getStackClient().token.accessToken as string
}`
},
notification: {
enabled: true,
autoClear: true,
onProgressTitle: t('services.backup.notifications.onProgressTitle'),
onProgressMessage: t(
'services.backup.notifications.onProgressMessage',
{
filename: media.name
}
),
onCompleteTitle: t('services.backup.notifications.onCompleteTitle'),
onCompleteMessage: t(
'services.backup.notifications.onCompleteMessage',
{
filename: media.name
}
),
onErrorTitle: t('services.backup.notifications.onErrorTitle'),
onErrorMessage: t('services.backup.notifications.onErrorMessage', {
return uploadFile({
url: uploadUrl,
// @ts-expect-error Type issue which will be fixed in another PR
token: client.getStackClient().token.accessToken as string,
filename: media.name,
filepath,
mimetype: getMimeType(media),
notification: {
onProgressTitle: t('services.backup.notifications.onProgressTitle'),
onProgressMessage: t('services.backup.notifications.onProgressMessage', {
filename: media.name
}),
onCompleteTitle: t('services.backup.notifications.onCompleteTitle'),
onCompleteMessage: t('services.backup.notifications.onCompleteMessage', {
filename: media.name
}),
onErrorTitle: t('services.backup.notifications.onErrorTitle'),
onErrorMessage: t('services.backup.notifications.onErrorMessage', {
filename: media.name
}),
onCancelledTitle: t('services.backup.notifications.onCancelledTitle'),
onCancelledMessage: t(
'services.backup.notifications.onCancelledMessage',
{
filename: media.name
}),
onCancelledTitle: t('services.backup.notifications.onCancelledTitle'),
onCancelledMessage: t(
'services.backup.notifications.onCancelledMessage',
{
filename: media.name
}
)
}
} as UploadOptions

RNBackgroundUpload.startUpload(options)
.then(uploadId => {
setCurrentUploadId(uploadId)

RNBackgroundUpload.addListener('error', uploadId, error => {
const { errors } = JSON.parse(error.responseBody) as StackErrors
reject({
statusCode: error.responseCode,
errors
})
})
RNBackgroundUpload.addListener('cancelled', uploadId, data => {
reject({ success: false, data })
})
RNBackgroundUpload.addListener('completed', uploadId, response => {
const { data } = JSON.parse(response.responseBody) as {
data: IOCozyFile
}

if (response.responseCode === 201) {
resolve({
statusCode: response.responseCode,
data
})
} else {
reject({
statusCode: response.responseCode,
data
})
}
})
})
.catch(e => {
reject(e)
})
}
)
}
})
}

export const cancelUpload = (uploadId: string): Promise<boolean> => {
return RNBackgroundUpload.cancelUpload(uploadId)
}
Loading