Files
cloudron-box/src/models/DirectoryModel.js
T

58 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-02-26 23:34:31 +01:00
import superagent from 'superagent';
import safe from 'safetydance';
2023-04-02 10:06:14 +02:00
import { sanitize } from 'pankow/utils';
2023-02-26 23:34:31 +01:00
export function createDirectoryModel(origin, accessToken, appId) {
return {
name: 'DirectoryModel',
async listFiles(path) {
const [error, result] = await safe(superagent.get(`${origin}/api/v1/apps/${appId}/files/${path}`).query({ access_token: accessToken }));
if (error) {
console.error('Failed to list files', error);
return [];
}
2023-04-02 10:41:02 +02:00
// this prepares the entries to be compatible with all components
2023-03-29 20:02:26 +02:00
result.body.entries.forEach(item => {
2023-04-02 10:41:02 +02:00
// if we have an image, attach previewUrl
2023-03-29 20:02:26 +02:00
if (item.mimeType.indexOf('image/') === 0) {
item.previewUrl = `${origin}/api/v1/apps/${appId}/files/${encodeURIComponent(path + '/' + item.fileName)}?access_token=${accessToken}`
}
2023-04-02 10:41:02 +02:00
item.folderPath = path;
2023-03-29 20:02:26 +02:00
});
2023-02-26 23:34:31 +01:00
return result.body.entries;
},
2023-04-02 10:06:14 +02:00
async remove(filePath) {
const [error] = await safe(superagent.del(`${origin}/api/v1/apps/${appId}/files/${filePath}`)
.query({ access_token: accessToken }));
if (error) throw error;
},
async rename(fromFilePath, toFilePath) {
const [error] = await safe(superagent.put(`${origin}/api/v1/apps/${appId}/files/${fromFilePath}`)
.send({ action: 'rename', newFilePath: sanitize(toFilePath) })
.query({ access_token: accessToken }));
if (error) throw error;
2023-02-26 23:34:31 +01:00
},
async getFile(path) {
const [error, result] = await safe(fetch(`${origin}/api/v1/apps/${appId}/files/${path}?access_token=${accessToken}`));
2023-02-26 23:34:31 +01:00
if (error) {
console.error('Failed to get file', error);
return null;
}
const text = await result.text();
return text;
2023-04-01 11:33:22 +02:00
},
getFileUrl(path) {
return `${origin}/api/v1/apps/${appId}/files/${path}?access_token=${accessToken}`;
2023-02-26 23:34:31 +01:00
}
};
}
export default {
createDirectoryModel
};