n8n-nodes-smartgent
Version:
SmartGent custom nodes for n8n - AI-powered automation and intelligent workflow integrations including LiteLLM chat completions, SharePoint file monitoring, and enterprise search
399 lines • 15.3 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadResult = exports.getSiteRelativePathByUrl = exports.getFileContentByUrl = exports.downloadFile = exports.getFileContentByFileId = exports.tagFile = exports.moveFile = exports.getFileByListId = exports.getAllFilesByListId = exports.getAllFilesByFolderId = exports.getAllFiles = exports.getFolderId = exports.getDriveId = exports.getListId = exports.getSiteId = void 0;
const axios_1 = __importDefault(require("axios"));
const fs = __importStar(require("fs"));
const json_2_csv_1 = __importDefault(require("json-2-csv"));
const getSiteId = async (siteUrl, token) => {
try {
const paths = siteUrl.split('sites/');
const siteName = paths[1].split('/')[0];
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url: `https://graph.microsoft.com/v1.0/sites?search=${siteName}`
};
const response = await (0, axios_1.default)(options);
const res = response.data;
const siteIndex = res.value.findIndex((x) => x.name === siteName);
if (siteIndex === -1) {
throw new Error(`Site '${siteName}' not found`);
}
return res.value[siteIndex].id;
}
catch (error) {
console.error('Error getting site ID:', error);
console.error('Site URL:', siteUrl);
throw error;
}
};
exports.getSiteId = getSiteId;
const getListId = async (siteUrl, token, siteId) => {
const pattern = /sites\/[^\/]+\/([^\/]+)/;
const match = siteUrl.match(pattern);
let basicDriveName = '';
if (match && match[1]) {
basicDriveName = match[1];
}
const webUrl = siteUrl.split(basicDriveName)[0] + basicDriveName;
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url: `https://graph.microsoft.com/v1.0/sites/${siteId}/lists`
};
const response = await (0, axios_1.default)(options);
const res = response.data;
const listIndex = res.value.findIndex((x) => x.webUrl === webUrl);
if (listIndex === -1) {
throw new Error(`List not found for URL: ${webUrl}`);
}
return res.value[listIndex].id;
};
exports.getListId = getListId;
const getDriveId = async (siteUrl, token, siteId) => {
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url: `https://graph.microsoft.com/v1.0/sites/${siteId}/drives`
};
const response = await (0, axios_1.default)(options);
const res = response.data;
const driveIndex = res.value.findIndex((x) => siteUrl.toLowerCase().startsWith(x.webUrl.toLowerCase()));
if (driveIndex === -1) {
throw new Error(`Drive not found for site URL: ${siteUrl}`);
}
return res.value[driveIndex].id;
};
exports.getDriveId = getDriveId;
const getFolderId = async (siteUrl, token, driveId) => {
const pattern = /sites\/[^\/]+\/([^\/]+)/;
const match = siteUrl.match(pattern);
let basicDriveName = '';
if (match && match[1]) {
basicDriveName = match[1];
}
const path = siteUrl.split(basicDriveName)[1];
let url;
if (path.length === 0) {
url = `https://graph.microsoft.com/v1.0/drives/${driveId}/root`;
}
else {
url = `https://graph.microsoft.com/v1.0/drives/${driveId}/root:/${path}`;
}
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url
};
const response = await (0, axios_1.default)(options);
return response.data.id;
};
exports.getFolderId = getFolderId;
const getAllFiles = async (siteUrl, token, driveId) => {
const pattern = /sites\/[^\/]+\/([^\/]+)/;
const match = siteUrl.match(pattern);
let basicDriveName = '';
if (match && match[1]) {
basicDriveName = match[1];
}
const path = siteUrl.split(basicDriveName)[1];
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url: `https://graph.microsoft.com/v1.0/drives/${driveId}/root:/${path}:/children`
};
const response = await (0, axios_1.default)(options);
const res = response.data;
const result = [];
for (const item of res.value) {
if (item.file !== undefined) {
result.push({
id: item.id,
name: item.name
});
}
}
return result;
};
exports.getAllFiles = getAllFiles;
const getAllFilesByFolderId = async (folderId, driveId, token) => {
let filesData = [];
let url = `https://graph.microsoft.com/v1.0/drives/${driveId}/items/${folderId}/children`;
do {
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url
};
const response = await (0, axios_1.default)(options);
const res = response.data;
const pageFiles = res.value
.filter(item => item.file !== undefined)
.map(item => ({
mic_id: item.id,
name: item.name,
downloadlink: item['@microsoft.graph.downloadUrl'] || '',
last_update: item.lastModifiedDateTime
}));
filesData = filesData.concat(pageFiles);
url = res['@odata.nextLink'];
} while (url !== undefined);
return filesData;
};
exports.getAllFilesByFolderId = getAllFilesByFolderId;
const getAllFilesByListId = async (siteId, listId, folderPath, token) => {
let filesData = [];
let url = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${listId}/items`;
do {
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url
};
const response = await (0, axios_1.default)(options);
const res = response.data;
const pageFiles = res.value
.filter(item => item.webUrl === folderPath)
.map(item => ({
mic_id: item.id,
name: item.name,
downloadlink: item['@microsoft.graph.downloadUrl'] || '',
last_update: item.lastModifiedDateTime
}));
filesData = filesData.concat(pageFiles);
url = res['@odata.nextLink'];
} while (url !== undefined);
return filesData;
};
exports.getAllFilesByListId = getAllFilesByListId;
const getFileByListId = async (siteId, listId, fileId, token) => {
const url = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${listId}/items/${fileId}`;
const options = {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + token },
url
};
const response = await (0, axios_1.default)(options);
const res = response.data;
return {
mic_id: res.value.id,
name: res.value.name,
downloadlink: res.value['@microsoft.graph.downloadUrl'] || '',
last_update: res.value.lastModifiedDateTime
};
};
exports.getFileByListId = getFileByListId;
const moveFile = async (request) => {
const { driveId, fileId, destinationFolderId, token } = request;
const url = `https://graph.microsoft.com/v1.0/drives/${driveId}/items/${fileId}?@microsoft.graph.conflictBehavior=rename`;
const body = {
parentReference: {
id: destinationFolderId
},
'@microsoft.graph.conflictBehavior': 'rename'
};
const options = {
method: 'PATCH',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
data: JSON.stringify(body),
url
};
return await (0, axios_1.default)(options);
};
exports.moveFile = moveFile;
const tagFile = async (fileId, siteId, listId, token, tags) => {
try {
const url_getId = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${listId}/items?$select=driveItem&$expand=driveItem`;
const options1 = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
url: url_getId
};
const res1 = await (0, axios_1.default)(options1);
const items = res1.data.value.filter((item) => { var _a; return ((_a = item.driveItem) === null || _a === void 0 ? void 0 : _a.id) === fileId; });
if (items.length === 0) {
throw new Error(`File with ID ${fileId} not found in list`);
}
const url = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${listId}/items/${items[0].id}`;
const cleanedTags = tags.replace(/'/g, '"');
const tagData = JSON.parse(cleanedTags);
const tagMetadata = {
fields: {
Tag: tagData.tag.department,
JSON: cleanedTags,
Department: tagData.tag.department,
Sensitivity_info: tagData.tag.have_sensitivity_information,
}
};
const options = {
method: 'PATCH',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
data: JSON.stringify(tagMetadata),
url
};
return await (0, axios_1.default)(options);
}
catch (error) {
console.error('Error tagging file:', error);
throw error;
}
};
exports.tagFile = tagFile;
const getFileContentByFileId = async (siteId, driveId, fileId, token) => {
const url = `https://graph.microsoft.com/v1.0/sites/${siteId}/drives/${driveId}/items/${fileId}/content`;
const options = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/octet-stream'
},
responseType: 'stream',
url
};
const response = await (0, axios_1.default)(options);
return response.data;
};
exports.getFileContentByFileId = getFileContentByFileId;
const downloadFile = async (siteId, driveId, fileId, filename, token) => {
const folderPath = `/fileStore/app/${driveId.replace('!', '')}`;
const path = `${folderPath}/${filename}`;
const resData = await (0, exports.getFileContentByFileId)(siteId, driveId, fileId, token);
try {
try {
fs.rmSync(`.${path}`);
}
catch {
}
resData.pipe(fs.createWriteStream(`.${path}`));
}
catch (error) {
console.error('File system error:', error);
await fs.promises.writeFile(`.${path}`, resData);
}
return path;
};
exports.downloadFile = downloadFile;
const getFileContentByUrl = async (url, token) => {
const options = {
method: 'GET',
responseType: 'stream',
url
};
if (token) {
options.headers = { 'Authorization': 'Bearer ' + token };
}
const response = await (0, axios_1.default)(options);
return response.data;
};
exports.getFileContentByUrl = getFileContentByUrl;
const getSiteRelativePathByUrl = (siteUrl) => {
let match = siteUrl.match(/^https:\/\/[^.]+.sharepoint.com\/(sites|teams)\/([^\/]+)/);
if (match && match[2]) {
return `/${match[1]}/${match[2]}`;
}
match = siteUrl.match(/^https:\/\/[^.]+.sharepoint.com\/([^\/]+)/);
if (match && match[1]) {
return `/${match[1]}`;
}
throw new Error('Incorrect SharePoint site format');
};
exports.getSiteRelativePathByUrl = getSiteRelativePathByUrl;
const uploadResult = async (results, folderUrl, token) => {
const csv = json_2_csv_1.default.json2csv(results);
const csvBuffer = Buffer.from(csv);
const siteId = await (0, exports.getSiteId)(folderUrl, token);
const driveId = await (0, exports.getDriveId)(folderUrl, token, siteId);
const folderId = await (0, exports.getFolderId)(folderUrl, token, driveId);
const filename = `${new Date().toISOString().replace(/(-|T|:|\.|Z)/g, '')}_results.csv`;
if (csvBuffer.length < 250 * 1024 * 1024) {
const url = `https://graph.microsoft.com/v1.0/drives/${driveId}/items/${folderId}:/${filename}:/content`;
const options = {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'text/plain'
},
data: csvBuffer,
url
};
return await (0, axios_1.default)(options);
}
else {
const sessionUrl = `https://graph.microsoft.com/v1.0/drives/${driveId}/items/${folderId}:/${filename}:/createUploadSession`;
const sessionOptions = {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
data: JSON.stringify({
'@microsoft.graph.conflictBehavior': 'replace'
}),
url: sessionUrl
};
const sessionResponse = await (0, axios_1.default)(sessionOptions);
const uploadUrl = sessionResponse.data.uploadUrl;
const segSize = 327680;
let finalResponse = sessionResponse;
for (let i = 0; i < csvBuffer.length; i += segSize) {
const options = {
method: 'PUT',
headers: {
'Content-Type': 'text/plain',
'Content-Range': `bytes ${i}-${Math.min(i + segSize - 1, csvBuffer.length - 1)}/${csvBuffer.length}`
},
data: csvBuffer.subarray(i, Math.min(i + segSize, csvBuffer.length)),
url: uploadUrl
};
finalResponse = await (0, axios_1.default)(options);
}
return finalResponse;
}
};
exports.uploadResult = uploadResult;
//# sourceMappingURL=sharepoint.js.map