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 17 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
13 changes: 13 additions & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,19 @@ dependencies {
because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib")
}
}
implementation(project(":react-native-background-upload")) {
exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.1'
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'com.squareup.okhttp3' && details.requested.name == 'okhttp') {
if (details.requested.name == 'net.gotev:uploadservice-okhttp') {
details.useVersion 'com.squareup.okhttp3:okhttp:5.0.0-alpha.1'
}
}
}
}
}

// Run this once to be able to run the application with BUCK
Expand Down
4 changes: 4 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@ allprojects {
// A temporary workaround for that is to disable Javadoc generation for all modules
// tasks.withType(Javadoc).all { enabled = false }
}

subprojects {
task allDeps(type: DependencyReportTask) {}
}
284 changes: 284 additions & 0 deletions docs/images/backup.drawio

Large diffs are not rendered by default.

Binary file added docs/images/backup.drawio.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
221 changes: 221 additions & 0 deletions docs/images/backup_front.drawio

Large diffs are not rendered by default.

Binary file added docs/images/backup_front.drawio.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
2 changes: 2 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { useCookieResyncOnResume } from '/hooks/useCookieResyncOnResume'
import { useCozyEnvironmentOverride } from '/hooks/useCozyEnvironmentOverride'
import { useNotifications } from '/hooks/useNotifications'
import { useSynchronizeOnInit } from '/hooks/useSynchronizeOnInit'
import { useInitBackup } from '/app/domain/backup/hooks'
import { useNetService } from '/libs/services/NetService'
import { withSentry } from '/libs/monitoring/Sentry'
import { ThemeProvider } from '/app/theme/ThemeProvider'
Expand All @@ -50,6 +51,7 @@ const App = ({ setClient }) => {
useSynchronizeOnInit()
useNetService(client)
useInitI18n(client)
useInitBackup(client)

const { initialRoute, isLoading } = useAppBootstrap(client)

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)
}
1 change: 1 addition & 0 deletions src/app/domain/backup/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '/app/domain/backup/hooks/useInitBackup'
33 changes: 33 additions & 0 deletions src/app/domain/backup/hooks/useInitBackup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useEffect } from 'react'

import { useClient } from 'cozy-client'

import {
getLocalBackupConfig,
setBackupAsToDo
} from '/app/domain/backup/services/manageLocalBackupConfig'

import Minilog from 'cozy-minilog'

const log = Minilog('💿 Backup')

export const useInitBackup = (): void => {
const client = useClient()

useEffect(() => {
const checkAndFixIfBackupStuckInRunning = async (): Promise<void> => {
if (!client) {
return
}

const backupConfig = await getLocalBackupConfig(client)

if (backupConfig.currentBackup.status === 'running') {
log.debug('A running backup has been set as to do.')
await setBackupAsToDo(client)
}
}

void checkAndFixIfBackupStuckInRunning()
}, [client])
Copy link
Member

Choose a reason for hiding this comment

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

How do we ensure this is called only on startup if there is a dependency on client? (however if the client changes I suppose it is expected to clear the backup status)

}
16 changes: 4 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 All @@ -18,25 +16,19 @@ export interface Media {
subType?: 'PhotoLive'
mimeType?: string
creationDate: number
modificationDate: number
albums: Album[]
fileSize: number | null
}

/**
* A selection of media metadata stored locally to identify if a media has already been backuped
* @member {string} name
* @member {string} remotePath e.g. /Sauvegardé depuis mon mobile/My Android/Download
* @member {string} remoteName e.g. IMG_001 (1).jpg (added only if different from name)
*/
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
remoteName?: string
}
16 changes: 12 additions & 4 deletions src/app/domain/backup/services/getMedias.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('formatMediasFromPhotoIdentifier', () => {
group_name: 'Pictures',
image: {
extension: 'jpg',
fileSize: null,
fileSize: 1234,
filename: 'IMG_20230519_204453.jpg',
height: null,
orientation: null,
Expand All @@ -70,7 +70,9 @@ describe('formatMediasFromPhotoIdentifier', () => {
remotePath: '/Pictures',
type: 'image',
mimeType: 'image/jpeg',
fileSize: 1234,
creationDate: 1684521894234,
modificationDate: 1684521894000,
albums: [{ name: 'Pictures' }]
}
])
Expand All @@ -84,7 +86,7 @@ describe('formatMediasFromPhotoIdentifier', () => {
group_name: ['Pictures'],
image: {
extension: 'heic',
fileSize: null,
fileSize: 1234,
filename: 'IMG_0744.HEIC',
height: null,
playableDuration: null,
Expand All @@ -109,8 +111,10 @@ describe('formatMediasFromPhotoIdentifier', () => {
path: 'ph://5FD84686-207F-40F1-BCE8-3A837275B0E3/L0/001',
remotePath: '/',
type: 'image',
fileSize: 1234,
mimeType: undefined,
creationDate: 1682604478599,
modificationDate: 1688756699463.186,
albums: [{ name: 'Pictures' }]
}
])
Expand All @@ -124,7 +128,7 @@ describe('formatMediasFromPhotoIdentifier', () => {
group_name: ['Pictures'],
image: {
extension: 'heic',
fileSize: null,
fileSize: 1234,
filename: 'IMG_0744.HEIC',
height: null,
playableDuration: null,
Expand Down Expand Up @@ -152,7 +156,9 @@ describe('formatMediasFromPhotoIdentifier', () => {
subType: 'PhotoLive',
mimeType: undefined,
creationDate: 1682604478599,
albums: [{ name: 'Pictures' }]
modificationDate: 1688756699463.186,
albums: [{ name: 'Pictures' }],
fileSize: null
},
{
name: 'IMG_0744.HEIC',
Expand All @@ -161,7 +167,9 @@ describe('formatMediasFromPhotoIdentifier', () => {
type: 'image',
subType: 'PhotoLive',
mimeType: undefined,
fileSize: 1234,
creationDate: 1682604478599,
modificationDate: 1688756699463.186,
albums: [{ name: 'Pictures' }]
}
])
Expand Down
20 changes: 13 additions & 7 deletions src/app/domain/backup/services/getMedias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ const getPhotoIdentifiersPage = async (
const photoIdentifiersPage = await CameraRoll.getPhotos({
first: MEDIAS_BY_PAGE,
after: after,
include: ['filename', 'fileExtension']
include: ['filename', 'fileExtension', 'fileSize']
})

return photoIdentifiersPage
}

Expand Down Expand Up @@ -72,10 +71,11 @@ export const formatMediasFromPhotoIdentifier = (
): Media[] => {
const {
node: {
image: { filename, uri },
image: { filename, uri, fileSize },
type,
subTypes,
timestamp
timestamp,
modificationTimestamp
}
} = photoIdentifier

Expand All @@ -92,7 +92,9 @@ export const formatMediasFromPhotoIdentifier = (
type: 'video',
subType: 'PhotoLive',
creationDate: timestamp * 1000,
albums
modificationDate: modificationTimestamp * 1000,
albums,
fileSize: null
},
{
name: filename,
Expand All @@ -101,7 +103,9 @@ export const formatMediasFromPhotoIdentifier = (
type: 'image',
subType: 'PhotoLive',
creationDate: timestamp * 1000,
albums
modificationDate: modificationTimestamp * 1000,
albums,
fileSize
}
]
}
Expand All @@ -114,7 +118,9 @@ export const formatMediasFromPhotoIdentifier = (
type: type.includes('image') ? 'image' : 'video',
mimeType: Platform.OS == 'android' ? type : undefined,
creationDate: timestamp * 1000,
albums
modificationDate: modificationTimestamp * 1000,
albums,
fileSize
}
]
}
Expand Down
5 changes: 5 additions & 0 deletions src/app/domain/backup/services/manageAlbums.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CameraRoll } from '@react-native-camera-roll/camera-roll'
import { Platform } from 'react-native'

import { Album, BackupedAlbum } from '/app/domain/backup/models'
import { getLocalBackupConfig } from '/app/domain/backup/services/manageLocalBackupConfig'
Expand All @@ -11,6 +12,10 @@ import {

import type CozyClient from 'cozy-client'

export const areAlbumsEnabled = (): boolean => {
return Platform.OS === 'ios'
}

export const getAlbums = async (): Promise<Album[]> => {
const cameraRollAlbums = await CameraRoll.getAlbums()

Expand Down
16 changes: 11 additions & 5 deletions src/app/domain/backup/services/manageBackup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import {
setBackupAsReady,
setBackupAsRunning,
setBackupAsDone,
saveAlbums
saveAlbums,
updateRemoteBackupConfigLocally
} from '/app/domain/backup/services/manageLocalBackupConfig'
import {
areAlbumsEnabled,
getAlbums,
createRemoteAlbums,
fetchBackupedAlbums
Expand All @@ -22,7 +24,7 @@ import {
import {
cancelUpload,
getCurrentUploadId
} from '/app/domain/backup/services/uploadMedia'
} from '/app/domain/upload/services/upload'
import {
fetchDeviceRemoteBackupConfig,
fetchBackupedMedias,
Expand Down Expand Up @@ -66,11 +68,13 @@ export const prepareBackup = async (

void onProgress(await getBackupInfo(client))

const albums = await getAlbums()
if (areAlbumsEnabled()) {
const albums = await getAlbums()

const createdAlbums = await createRemoteAlbums(client, albums)
const createdAlbums = await createRemoteAlbums(client, albums)

await saveAlbums(client, createdAlbums)
await saveAlbums(client, createdAlbums)
}

const mediasToBackup = await getMediasToBackup(client)

Expand All @@ -89,6 +93,8 @@ export const startBackup = async (
): Promise<BackupInfo> => {
log.debug('Backup started')

await updateRemoteBackupConfigLocally(client)

const localBackupConfig = await getLocalBackupConfig(client)

await setBackupAsRunning(client)
Expand Down
Loading
Loading