feat: add favorite action with tests

Signed-off-by: John Molakvoæ <skjnldsv@protonmail.com>
pull/38939/head
John Molakvoæ 2023-06-22 10:31:29 +07:00
parent 1112963385
commit 723edb5654
No known key found for this signature in database
GPG Key ID: 60C25B8C072916CF
2 changed files with 490 additions and 0 deletions

@ -0,0 +1,391 @@
/**
* @copyright Copyright (c) 2023 John Molakvoæ <skjnldsv@protonmail.com>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 * as favoriteAction from './favoriteAction'
import { action } from './favoriteAction'
import { expect } from '@jest/globals'
import { File, Folder, Permission } from '@nextcloud/files'
import { FileAction } from '../services/FileAction'
import * as eventBus from '@nextcloud/event-bus'
import axios from '@nextcloud/axios'
import type { Navigation } from '../services/Navigation'
import logger from '../logger'
const view = {
id: 'files',
name: 'Files',
} as Navigation
const favoriteView = {
id: 'favorites',
name: 'Favorites',
} as Navigation
global.window.OC = {
TAG_FAVORITE: '_$!<Favorite>!$_',
}
describe('Favorite action conditions tests', () => {
test('Default values', () => {
const file = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
})
expect(action).toBeInstanceOf(FileAction)
expect(action.id).toBe('favorite')
expect(action.displayName([file], view)).toBe('Add to favorites')
expect(action.iconSvgInline([], view)).toBe('SvgMock')
expect(action.default).toBe(false)
expect(action.order).toBe(-50)
})
test('Display name is Remove from favorites if already in favorites', () => {
const file = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
attributes: {
favorite: 1,
},
})
expect(action.displayName([file], view)).toBe('Remove from favorites')
})
test('Display name for multiple state files', () => {
const file1 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 1,
},
})
const file2 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 0,
},
})
const file3 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 1,
},
})
expect(action.displayName([file1, file2, file3], view)).toBe('Add to favorites')
expect(action.displayName([file1, file2], view)).toBe('Add to favorites')
expect(action.displayName([file2, file3], view)).toBe('Add to favorites')
expect(action.displayName([file1, file3], view)).toBe('Remove from favorites')
})
})
describe('Favorite action enabled tests', () => {
test('Enabled for dav file', () => {
const file = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
})
expect(action.enabled).toBeDefined()
expect(action.enabled!([file], view)).toBe(true)
})
test('Disabled for non-dav ressources', () => {
const file = new File({
id: 1,
source: 'https://domain.com/data/foobar.txt',
owner: 'admin',
mime: 'text/plain',
})
expect(action.enabled).toBeDefined()
expect(action.enabled!([file], view)).toBe(false)
})
})
describe('Favorite action execute tests', () => {
afterEach(() => {
jest.spyOn(axios, 'post').mockRestore()
})
test('Favorite triggers tag addition', async () => {
jest.spyOn(axios, 'post')
jest.spyOn(eventBus, 'emit')
const file = new File({
id: 1,
source: 'http://localhost/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
})
const exec = await action.exec(file, view, '/')
expect(exec).toBe(true)
// Check POST request
expect(axios.post).toBeCalledTimes(1)
expect(axios.post).toBeCalledWith('/index.php/apps/files/api/v1/files/foobar.txt', { tags: ['_$!<Favorite>!$_'] })
// Check node change propagation
expect(file.attributes.favorite).toBe(1)
expect(eventBus.emit).toBeCalledTimes(1)
expect(eventBus.emit).toBeCalledWith('files:favorites:added', file)
})
test('Favorite triggers tag removal', async () => {
jest.spyOn(axios, 'post')
jest.spyOn(eventBus, 'emit')
const file = new File({
id: 1,
source: 'http://localhost/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
attributes: {
favorite: 1,
},
})
const exec = await action.exec(file, view, '/')
expect(exec).toBe(true)
// Check POST request
expect(axios.post).toBeCalledTimes(1)
expect(axios.post).toBeCalledWith('/index.php/apps/files/api/v1/files/foobar.txt', { tags: [] })
// Check node change propagation
expect(file.attributes.favorite).toBe(0)
expect(eventBus.emit).toBeCalledTimes(1)
expect(eventBus.emit).toBeCalledWith('files:favorites:removed', file)
})
test('Favorite triggers node removal if favorite view and root dir', async () => {
jest.spyOn(axios, 'post')
jest.spyOn(eventBus, 'emit')
const file = new File({
id: 1,
source: 'http://localhost/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
attributes: {
favorite: 1,
},
})
const exec = await action.exec(file, favoriteView, '/')
expect(exec).toBe(true)
// Check POST request
expect(axios.post).toBeCalledTimes(1)
expect(axios.post).toBeCalledWith('/index.php/apps/files/api/v1/files/foobar.txt', { tags: [] })
// Check node change propagation
expect(file.attributes.favorite).toBe(0)
expect(eventBus.emit).toBeCalledTimes(2)
expect(eventBus.emit).toHaveBeenNthCalledWith(1, 'files:node:deleted', file)
expect(eventBus.emit).toHaveBeenNthCalledWith(2, 'files:favorites:removed', file)
})
test('Favorite does NOT triggers node removal if favorite view but NOT root dir', async () => {
jest.spyOn(axios, 'post')
jest.spyOn(eventBus, 'emit')
const file = new File({
id: 1,
source: 'http://localhost/remote.php/dav/files/admin/Foo/Bar/foobar.txt',
root: '/files/admin',
owner: 'admin',
mime: 'text/plain',
attributes: {
favorite: 1,
},
})
const exec = await action.exec(file, favoriteView, '/')
expect(exec).toBe(true)
// Check POST request
expect(axios.post).toBeCalledTimes(1)
expect(axios.post).toBeCalledWith('/index.php/apps/files/api/v1/files/Foo/Bar/foobar.txt', { tags: [] })
// Check node change propagation
expect(file.attributes.favorite).toBe(0)
expect(eventBus.emit).toBeCalledTimes(1)
expect(eventBus.emit).toBeCalledWith('files:favorites:removed', file)
})
test('Favorite fails and show error', async () => {
const error = new Error('Mock error')
jest.spyOn(axios, 'post').mockImplementation(() => { throw new Error('Mock error') })
jest.spyOn(logger, 'error').mockImplementation(() => jest.fn())
const file = new File({
id: 1,
source: 'http://localhost/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
attributes: {
favorite: 0,
},
})
const exec = await action.exec(file, view, '/')
expect(exec).toBe(false)
// Check POST request
expect(axios.post).toBeCalledTimes(1)
expect(axios.post).toBeCalledWith('/index.php/apps/files/api/v1/files/foobar.txt', { tags: ['_$!<Favorite>!$_'] })
// Check node change propagation
expect(logger.error).toBeCalledTimes(1)
expect(logger.error).toBeCalledWith('Error while adding a file to favourites', { error, source: file.source, node: file })
expect(file.attributes.favorite).toBe(0)
expect(eventBus.emit).toBeCalledTimes(0)
})
test('Removing from favorites fails and show error', async () => {
const error = new Error('Mock error')
jest.spyOn(axios, 'post').mockImplementation(() => { throw error })
jest.spyOn(logger, 'error').mockImplementation(() => jest.fn())
const file = new File({
id: 1,
source: 'http://localhost/remote.php/dav/files/admin/foobar.txt',
owner: 'admin',
mime: 'text/plain',
attributes: {
favorite: 1,
},
})
const exec = await action.exec(file, view, '/')
expect(exec).toBe(false)
// Check POST request
expect(axios.post).toBeCalledTimes(1)
expect(axios.post).toBeCalledWith('/index.php/apps/files/api/v1/files/foobar.txt', { tags: [] })
// Check node change propagation
expect(logger.error).toBeCalledTimes(1)
expect(logger.error).toBeCalledWith('Error while removing a file from favourites', { error, source: file.source, node: file })
expect(file.attributes.favorite).toBe(1)
expect(eventBus.emit).toBeCalledTimes(0)
})
})
describe('Favorite action batch execute tests', () => {
test('Favorite action batch execute with mixed files', async () => {
jest.spyOn(favoriteAction, 'favoriteNode')
jest.spyOn(axios, 'post')
const file1 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foo.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 1,
},
})
const file2 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/bar.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 0,
},
})
// Mixed states triggers favorite action
const exec = await action.execBatch!([file1, file2], view, '/')
expect(exec).toStrictEqual([true, true])
expect([file1, file2].every(file => file.attributes.favorite === 1)).toBe(true)
expect(favoriteAction.favoriteNode).toBeCalledTimes(2)
expect(axios.post).toBeCalledTimes(2)
expect(axios.post).toHaveBeenNthCalledWith(1, '/index.php/apps/files/api/v1/files/foo.txt', { tags: ['_$!<Favorite>!$_'] })
expect(axios.post).toHaveBeenNthCalledWith(2, '/index.php/apps/files/api/v1/files/bar.txt', { tags: ['_$!<Favorite>!$_'] })
})
test('Remove from favorite action batch execute with favorites only files', async () => {
jest.spyOn(favoriteAction, 'favoriteNode')
jest.spyOn(axios, 'post')
const file1 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/foo.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 1,
},
})
const file2 = new File({
id: 1,
source: 'https://cloud.domain.com/remote.php/dav/files/admin/bar.txt',
owner: 'admin',
mime: 'text/plain',
permissions: Permission.ALL,
attributes: {
favorite: 1,
},
})
// Mixed states triggers favorite action
const exec = await action.execBatch!([file1, file2], view, '/')
expect(exec).toStrictEqual([true, true])
expect([file1, file2].every(file => file.attributes.favorite === 0)).toBe(true)
expect(favoriteAction.favoriteNode).toBeCalledTimes(2)
expect(axios.post).toBeCalledTimes(2)
expect(axios.post).toHaveBeenNthCalledWith(1, '/index.php/apps/files/api/v1/files/foo.txt', { tags: [] })
expect(axios.post).toHaveBeenNthCalledWith(2, '/index.php/apps/files/api/v1/files/bar.txt', { tags: [] })
})
})

@ -0,0 +1,99 @@
/**
* @copyright Copyright (c) 2023 John Molakvoæ <skjnldsv@protonmail.com>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 { emit } from '@nextcloud/event-bus'
import { translate as t } from '@nextcloud/l10n'
import axios from '@nextcloud/axios'
import Star from '@mdi/svg/svg/star.svg?raw'
import type { Node } from '@nextcloud/files'
import { generateUrl } from '@nextcloud/router'
import { registerFileAction, FileAction } from '../services/FileAction'
import logger from '../logger.js'
import type { Navigation } from '../services/Navigation'
// If any of the nodes is not favorited, we display the favorite action.
const shouldFavorite = (nodes: Node[]): boolean => {
return nodes.some(node => node.attributes.favorite !== 1)
}
export const favoriteNode = async (node: Node, view: Navigation, willFavorite: boolean): Promise<boolean> => {
try {
// TODO: migrate to webdav tags plugin
const url = generateUrl('/apps/files/api/v1/files') + node.path
await axios.post(url, {
tags: willFavorite
? [window.OC.TAG_FAVORITE]
: [],
})
// Let's delete if we are in the favourites view
// AND if it is removed from the user favorites
// AND it's in the root of the favorites view
if (view.id === 'favorites' && !willFavorite && node.dirname === '/') {
emit('files:node:deleted', node)
}
// Update the node webdav attribute
node.attributes.favorite = willFavorite ? 1 : 0
// Dispatch event to whoever is interested
if (willFavorite) {
emit('files:favorites:added', node)
} else {
emit('files:favorites:removed', node)
}
return true
} catch (error) {
const action = willFavorite ? 'adding a file to favourites' : 'removing a file from favourites'
logger.error('Error while ' + action, { error, source: node.source, node })
return false
}
}
export const action = new FileAction({
id: 'favorite',
displayName(nodes: Node[]) {
return shouldFavorite(nodes)
? t('files', 'Add to favorites')
: t('files', 'Remove from favorites')
},
iconSvgInline: () => Star,
enabled(nodes: Node[]) {
// We can only favorite nodes within files
return !nodes.some(node => !node.root?.startsWith?.('/files'))
},
async exec(node: Node, view: Navigation) {
const willFavorite = shouldFavorite([node])
return await favoriteNode(node, view, willFavorite)
},
async execBatch(nodes: Node[], view: Navigation) {
const willFavorite = shouldFavorite(nodes)
return Promise.all(nodes.map(async node => await favoriteNode(node, view, willFavorite)))
},
order: -50,
})
registerFileAction(action)