List Files
One script reply has been approved by the moderators Verified

List files in a folder using webdav

Created by nextcloud 13 days ago Picked 3 times
Submitted by nextcloud Bun
Verified 13 days ago
1
import { createClient, FileStat } from "webdav";
2

3
type Nextcloud = {
4
  baseUrl: string;
5
  userId: string;
6
  token: string;
7
};
8

9
/**
10
 * Lists files in a Nextcloud folder via WebDAV.
11
 * Optionally filter results by content type (e.g. "application/pdf" or ["image/jpeg", "image/png"]).
12
 */
13
export async function main(
14
  ncResource: Nextcloud,
15
  folderPath: string,
16
  contentTypesFilter: string | string[] | null = null,
17
  recursive: boolean = false
18
): Promise<FileStat[]> {
19
  const baseUrl = ncResource.baseUrl.replace(/\/$/, "");
20
  const davBaseUrl = `${baseUrl}/remote.php/dav/files/${encodeURIComponent(ncResource.userId)}`;
21

22
  const client = createClient(davBaseUrl, {
23
    username: ncResource.userId,
24
    password: ncResource.token,
25
  });
26

27
  let path = `${folderPath}/`;
28
  if (path.startsWith("/")) {
29
    path = path.slice(1);
30
  }
31

32
  const items = await client.getDirectoryContents(path, {
33
    deep: recursive,
34
  });
35

36
  const contentTypes = normalizeContentFilter(contentTypesFilter);
37
  if (contentTypes.length === 0) {
38
    return items;
39
  }
40

41
  return items.filter((item) =>
42
    contentTypes.includes((item.mime || "").toLowerCase())
43
  );
44
}
45

46
function normalizeContentFilter(
47
  filter: string | string[] | null
48
): string[] {
49
  if (filter == null || filter === "") return [];
50
  if (Array.isArray(filter)) {
51
    return filter.map((f) => String(f).trim().toLowerCase()).filter(Boolean);
52
  }
53
  return [String(filter).trim().toLowerCase()].filter(Boolean);
54
}
55