Files
crm.clientright.ru/crm_extensions/file_storage/nextcloud_fileid_indexer.js
Fedor cd90b0d58a feat: Добавлен инструмент генерации документов для AI Ассистента
- Создан API create_document_with_text.php для создания DOCX/XLSX/PPTX с текстом от AI
- Поддержка Markdown форматирования (заголовки, жирный, курсив, списки, код)
- Установлен PHPWord для красивого форматирования документов
- Исправлены пути сохранения (crm2/CRM_Active_Files/... без /crm/ в начале)
- Замена пробелов на подчеркивания в именах папок
- Создана документация для AI и разработчиков
- Добавлены API для работы с шаблонами Nextcloud
2025-11-12 19:46:06 +03:00

131 lines
4.5 KiB
JavaScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* Nextcloud FileID Indexer
*
* Индексирует fileId из Nextcloud БД в Redis для быстрого доступа
* Структура: crm:nc:fileid:{path} => fileId
*/
const mysql = require('mysql2/promise');
const Redis = require('ioredis');
const CONFIG = {
nextcloud_db: {
host: '192.168.128.3',
user: 'nextcloud',
password: 'nextcloud_password',
database: 'nextcloud'
},
redis: {
host: '147.45.146.17',
port: 6379,
password: 'CRM_Redis_Pass_2025_Secure!'
},
// Индексируем только файлы из этих папок
pathPrefixes: [
'crm2/CRM_Active_Files/', // ИСПРАВЛЕНО: без 'files/' префикса!
'erv_app/'
],
indexInterval: 60000 // Обновляем индекс каждую минуту
};
const redis = new Redis(CONFIG.redis);
let connection = null;
async function connectDB() {
try {
connection = await mysql.createConnection(CONFIG.nextcloud_db);
console.log('✅ Подключились к БД Nextcloud');
} catch (err) {
console.error('❌ Ошибка подключения к БД:', err.message);
process.exit(1);
}
}
async function indexFiles() {
try {
console.log(`\n🔍 Индексация файлов... (${new Date().toISOString()})`);
let totalIndexed = 0;
for (const prefix of CONFIG.pathPrefixes) {
// Получаем все файлы из этой папки
const [rows] = await connection.execute(
'SELECT fileid, path, name, size, mtime FROM oc_filecache WHERE path LIKE ? AND mimetype != 2',
[prefix + '%']
);
console.log(` 📁 ${prefix}: найдено ${rows.length} файлов`);
// Индексируем в Redis
const pipeline = redis.pipeline();
for (const row of rows) {
const key = `crm:nc:fileid:${row.path}`;
const value = JSON.stringify({
fileId: row.fileid,
name: row.name,
size: row.size,
mtime: row.mtime
});
// Храним 24 часа (обновляется каждую минуту)
pipeline.setex(key, 86400, value);
totalIndexed++;
}
await pipeline.exec();
}
console.log(`✅ Проиндексировано: ${totalIndexed} файлов`);
} catch (err) {
console.error('❌ Ошибка индексации:', err.message);
console.error(err.stack);
}
}
async function start() {
console.log('🚀 Nextcloud FileID Indexer');
console.log('════════════════════════════════════════════════════════════════════════════════');
console.log(`🗄️ Nextcloud DB: ${CONFIG.nextcloud_db.host}/${CONFIG.nextcloud_db.database}`);
console.log(`📡 Redis: ${CONFIG.redis.host}:${CONFIG.redis.port}`);
console.log(`🔄 Интервал: ${CONFIG.indexInterval / 1000}с`);
console.log('════════════════════════════════════════════════════════════════════════════════\n');
await connectDB();
console.log('👂 Начинаем индексацию...\n');
// Первая индексация
await indexFiles();
// Периодическая индексация
setInterval(indexFiles, CONFIG.indexInterval);
}
// Запуск
redis.on('connect', () => {
console.log('✅ Подключились к Redis\n');
start();
});
redis.on('error', (err) => {
console.error('❌ Redis ошибка:', err.message);
});
process.on('SIGINT', async () => {
console.log('\n\n⛔ Остановка индексатора...');
if (connection) await connection.end();
redis.disconnect();
process.exit(0);
});
process.on('SIGTERM', async () => {
console.log('\n\n⛔ Остановка индексатора...');
if (connection) await connection.end();
redis.disconnect();
process.exit(0);
});