Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

refactor: Only import from nextcloud-axios not axios directly #1224

Merged
merged 3 commits into from
Jun 4, 2024
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
49 changes: 49 additions & 0 deletions __tests__/utils/uploader.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { Uploader } from '../../lib/uploader.js'

import type { NextcloudUser } from '@nextcloud/auth'

const initialState = vi.hoisted(() => ({ loadState: vi.fn() }))
const auth = vi.hoisted(() => ({ getCurrentUser: vi.fn<never, NextcloudUser | null>(() => null) }))
vi.mock('@nextcloud/initial-state', () => initialState)
vi.mock('@nextcloud/auth', () => auth)

describe('uploader', () => {
beforeEach(() => {
vi.resetAllMocks()
const node = document.getElementById('sharingToken')
if (node) {
document.body.removeChild(node)
}
})

test('constructor sets default target folder for user', async () => {
auth.getCurrentUser.mockImplementationOnce(() => ({ uid: 'my-user', displayName: 'User', isAdmin: false }))
const uploader = new Uploader()
expect(uploader.destination.source).match(/\/remote\.php\/dav\/files\/my-user\/?$/)
})

test('constructor sets default target folder for public share', async () => {
initialState.loadState.mockImplementationOnce((app, key) => app === 'files_sharing' && key === 'sharingToken' ? 'token-123' : null)
const uploader = new Uploader(true)
expect(uploader.destination.source).match(/\/public\.php\/dav\/files\/token-123\/?$/)
})

test('constructor sets default target folder for legacy public share', async () => {
const input = document.createElement('input')
input.id = 'sharingToken'
input.value = 'legacy-token'
document.body.appendChild(input)
const uploader = new Uploader(true)
expect(uploader.destination.source).match(/\/public\.php\/dav\/files\/legacy-token\/?$/)
})

test('fails if no sharingToken on public share', async () => {
expect(() => new Uploader(true)).toThrow(/No sharing token found/)
})

test('fails if not logged in and not on public share', async () => {
expect(() => new Uploader()).toThrow(/User is not logged in/)
expect(initialState.loadState).not.toBeCalled()
})
})
38 changes: 27 additions & 11 deletions lib/uploader.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import type { AxiosError, AxiosResponse } from 'axios'
import type { WebDAVClient } from 'webdav'

import { CanceledError } from 'axios'
import { encodePath } from '@nextcloud/paths'
import { getCurrentUser } from '@nextcloud/auth'
import { Folder, Permission, davGetClient } from '@nextcloud/files'
import { loadState } from '@nextcloud/initial-state'
import { encodePath } from '@nextcloud/paths'
import { generateRemoteUrl } from '@nextcloud/router'
import { getCurrentUser } from '@nextcloud/auth'
import { normalize } from 'path'
import axios from '@nextcloud/axios'

import axios, { isCancel } from '@nextcloud/axios'
import PCancelable from 'p-cancelable'
import PQueue from 'p-queue'

Expand Down Expand Up @@ -53,11 +54,26 @@ export class Uploader {
this._isPublic = isPublic

if (!destinationFolder) {
const owner = getCurrentUser()?.uid
const source = generateRemoteUrl(`dav/files/${owner}`)
if (!owner) {
throw new Error('User is not logged in')
let owner: string
let source: string

if (isPublic) {
const sharingToken = loadState<string | null>('files_sharing', 'sharingToken', null) ?? document.querySelector<HTMLInputElement>('input#sharingToken')?.value
if (!sharingToken) {
logger.error('No sharing token found for public shares, please specify the destination folder manually.')
throw new Error('No sharing token found.')
}
owner = sharingToken
source = generateRemoteUrl(`dav/files/${sharingToken}`).replace('remote.php', 'public.php')
} else {
const user = getCurrentUser()?.uid
if (!user) {
throw new Error('User is not logged in')
}
owner = user
source = generateRemoteUrl(`dav/files/${owner}`)
}

destinationFolder = new Folder({
id: 0,
owner,
Expand Down Expand Up @@ -406,7 +422,7 @@ export class Uploader {
throw error
}

if (!(error instanceof CanceledError)) {
if (!isCancel(error)) {
logger.error(`Chunk ${chunk + 1} ${bufferStart} - ${bufferEnd} uploading failed`, { error, upload })
// TODO: support retrying ?
// https://github.com/nextcloud-libraries/nextcloud-upload/issues/5
Expand Down Expand Up @@ -439,7 +455,7 @@ export class Uploader {
logger.debug(`Successfully uploaded ${file.name}`, { file, upload })
resolve(upload)
} catch (error) {
if (!(error instanceof CanceledError)) {
if (!isCancel(error)) {
upload.status = UploadStatus.FAILED
reject('Failed assembling the chunks together')
} else {
Expand Down Expand Up @@ -486,7 +502,7 @@ export class Uploader {
logger.debug(`Successfully uploaded ${file.name}`, { file, upload })
resolve(upload)
} catch (error) {
if (error instanceof CanceledError) {
if (isCancel(error)) {
upload.status = UploadStatus.FAILED
reject(t('Upload has been cancelled'))
return
Expand Down
17 changes: 10 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@
},
"dependencies": {
"@nextcloud/auth": "^2.2.1",
"@nextcloud/axios": "^2.4.0",
"@nextcloud/axios": "^2.5.0",
"@nextcloud/dialogs": "^5.2.0",
"@nextcloud/files": "^3.3.1",
"@nextcloud/initial-state": "^2.2.0",
"@nextcloud/l10n": "^3.0.1",
"@nextcloud/logger": "^3.0.1",
"@nextcloud/paths": "^2.1.0",
"@nextcloud/router": "^3.0.0",
"axios": "^1.6.8",
"buffer": "^6.0.3",
"axios": "^1.7.2",
"crypto-browserify": "^3.12.0",
"p-cancelable": "^4.0.1",
"p-queue": "^8.0.0",
Expand Down
5 changes: 5 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export default async (env) => {
exclude: ['lib/utils/l10n.ts'],
reporter: ['lcov', 'text'],
},
server: {
deps: {
inline: ['@nextcloud/files'],
},
},
} as UserConfig
return cfg
}
Loading