nextcloud-server/apps/files/src/services/FolderTree.ts

93 lines
2.4 KiB
TypeScript

/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import type { ContentsWithRoot } from '@nextcloud/files'
import { CancelablePromise } from 'cancelable-promise'
import {
davRemoteURL,
Folder,
} from '@nextcloud/files'
import axios from '@nextcloud/axios'
import { generateOcsUrl } from '@nextcloud/router'
import { getCurrentUser } from '@nextcloud/auth'
import { dirname, encodePath, joinPaths } from '@nextcloud/paths'
import { getContents as getFiles } from './Files.ts'
// eslint-disable-next-line no-use-before-define
type Tree = Array<{
id: number,
basename: string,
displayName?: string,
children: Tree,
}>
export interface TreeNode {
source: string,
path: string,
fileid: number,
basename: string,
displayName?: string,
}
export const folderTreeId = 'folders'
export const sourceRoot = `${davRemoteURL}/files/${getCurrentUser()?.uid}`
const getTreeNodes = (tree: Tree, currentPath: string = '/', nodes: TreeNode[] = []): TreeNode[] => {
for (const { id, basename, displayName, children } of tree) {
const path = joinPaths(currentPath, basename)
const node: TreeNode = {
source: `${sourceRoot}${path}`,
path,
fileid: id,
basename,
}
if (displayName) {
node.displayName = displayName
}
nodes.push(node)
if (children.length > 0) {
getTreeNodes(children, path, nodes)
}
}
return nodes
}
export const getFolderTreeNodes = async (path: string = '/', depth: number = 1): Promise<TreeNode[]> => {
const { data: tree } = await axios.get<Tree>(generateOcsUrl('/apps/files/api/v1/folder-tree'), {
params: new URLSearchParams({ path, depth: String(depth) }),
})
const nodes = getTreeNodes(tree, path)
return nodes
}
export const getContents = (path: string): CancelablePromise<ContentsWithRoot> => getFiles(path)
export const encodeSource = (source: string): string => {
const { origin } = new URL(source)
return origin + encodePath(source.slice(origin.length))
}
export const getSourceParent = (source: string): string => {
const parent = dirname(source)
if (parent === sourceRoot) {
return folderTreeId
}
return encodeSource(parent)
}
export const getFolderTreeViewId = (folder: Folder): string => {
return folder.encodedSource
}
export const getFolderTreeParentId = (folder: Folder): string => {
if (folder.dirname === '/') {
return folderTreeId
}
return dirname(folder.encodedSource)
}