Files
RRJServer/ServerLMS/ServerLMS/Systems/dataparser.cpp
2024-12-13 13:22:10 +03:00

648 lines
23 KiB
C++
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.
#include "dataparser.h"
#include <QFile>
#include <QDomDocument>
DataParser::DataParser(ProcessingSystem *processingSystem,QObject *parent) :
QObject(parent)
{
this->processingSystem = processingSystem;
mutex = new QMutex;
if (!QDir(staticDataFolderName).exists()){
QDir().mkdir(staticDataFolderName);
}
qDebug() << "ParserThread: " << QThread::currentThreadId();
}
void DataParser::xmlParser(ClientHandler *client, QByteArray array)
{
QXmlStreamReader xmlReader(array);
xmlReader.readNext(); // Переходим к первому элементу в файле
//Крутимся в цикле до тех пор, пока не достигнем конца документа
while(!xmlReader.atEnd())
{
//Проверяем, является ли элемент началом тега
if(xmlReader.isStartElement())
{
//Анализируем теги
if(xmlReader.name() == "ClientAutorization")
{//Запрос авторизации от клиента
ClientAutorization clientAutorization;
/*Перебираем все атрибуты тега*/
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
//addTextToLogger(name + ": " + value);
if(name == "Login")
clientAutorization.Login = value;
else if(name == "Password")
clientAutorization.Password = value;
else if(name == "NumberOfScreen")
clientAutorization.NumberOfScreen = value.toInt();
else if(name == "TypeClient")
clientAutorization.TypeClient = (TypeClientAutorization)value.toInt();
}
processingSystem->processingClientAutorization(client, clientAutorization);
}
else if(xmlReader.name() == "ClientDeAutorization")
{//Запрос ДеАвторизации от клиента
ClientDeAutorization clientDeAutorization;
/*Перебираем все атрибуты тега*/
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
//addTextToLogger(name + ": " + value);
if(name == "Login")
clientDeAutorization.Login = value;
}
processingSystem->processingClientDeAutorization(client, clientDeAutorization);
}
else if(xmlReader.name() == "QueryToDB")
{//Запрос к базе данных от клиента
ClientQueryToDB queryToDB;
int id = 0;
Instructor instructor;
Trainee trainee;
Group group;
void* data = nullptr;
/*Перебираем все атрибуты тега*/
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
//addTextToLogger(name + ": " + value);
if(name == "TypeQuery")
queryToDB.typeQuery = (TypeQueryToDB)value.toInt();
else if(name == "id")
id = value.toInt();
else
{
switch (queryToDB.typeQuery)
{
case TypeQueryToDB::TYPE_QUERY_NEW_INSTRUCTOR:
case TypeQueryToDB::TYPE_QUERY_EDIT_INSTRUCTOR:
if(name == "instructor_id")
instructor.setID(value.toInt());
else if(name == "name")
instructor.setName(value);
else if(name == "login")
instructor.setLogin(value);
else if(name == "password")
instructor.setPassword(value);
else if(name == "is_admin")
instructor.setIsAdmin(value.toInt());
else if(name == "archived")
instructor.setArchived(value.toInt());
else if(name == "logged_in")
instructor.setLoggedIn(value.toInt());
break;
case TypeQueryToDB::TYPE_QUERY_EDIT_TRAINEE:
if(name == "trainee_id")
trainee.setID(value.toInt());
else if(name == "name")
trainee.setName(value);
else if(name == "login")
trainee.setLogin(value);
else if(name == "password")
trainee.setPassword(value);
else if(name == "archived")
trainee.setArchived(value.toInt());
else if(name == "logged_in")
trainee.setLoggedIn(value.toInt());
else if(name == "group_trainee")
{
Group group(value.toInt(), "");
trainee.setGroup(group);
}
else if(name == "computer_trainee")
{
Computer computer(value.toInt(), "", "", Classroom());
trainee.setComputer(computer);
}
break;
case TypeQueryToDB::TYPE_QUERY_EDIT_GROUP:
if(name == "group_id")
group.setID(value.toInt());
else if(name == "name")
group.setName(value);
break;
};
}
}
switch (queryToDB.typeQuery)
{
case TypeQueryToDB::TYPE_QUERY_NEW_INSTRUCTOR:
case TypeQueryToDB::TYPE_QUERY_EDIT_INSTRUCTOR:
data = &instructor;
break;
case TypeQueryToDB::TYPE_QUERY_EDIT_TRAINEE:
data = &trainee;
break;
case TypeQueryToDB::TYPE_QUERY_EDIT_GROUP:
data = &group;
break;
};
processingSystem->processingClientQueryToDB(client, queryToDB, id, data);
}
else if(xmlReader.name() == "ClientMessage")
{//Сообщение от клиента
ClientMessage clientMessage;
/*Перебираем все атрибуты тега*/
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
//addTextToLogger(name + ": " + value);
if(name == "Text")
clientMessage.Text = value;
}
processingSystem->processingClientMessage(client, clientMessage);
}
else if(xmlReader.name() == "ClientNotify")
{//Уведомление от клиента
ClientNotify clientNotify;
/*Перебираем все атрибуты тега*/
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
if(name == "Code")
clientNotify.Code = value;
}
processingSystem->processingClientNotify(client, clientNotify);
}
else if(xmlReader.name() == "DataInfo")
{
dataInfo = new DataInfo;
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
if(name == "path")
dataInfo->path= value.toUtf8();
if(name == "size")
dataInfo->size = value.toLong();
}
}
else
{
emit sigLogMessage("XmlParser: unrecognized tag");
}
}
xmlReader.readNext(); // Переходим к следующему элементу файла
}//while(!xmlReader.atEnd())
}
void DataParser::xmlFileDataParse(QByteArray array)
{
QXmlStreamReader xmlReader(array);
datas = new QList<FileData>;
xmlReader.readNext(); // Переходим к первому элементу в файле
//Крутимся в цикле до тех пор, пока не достигнем конца документа
while(!xmlReader.atEnd())
{
//Проверяем, является ли элемент началом тега
if(xmlReader.isStartElement())
{
if(xmlReader.name() == "FileData")
{
FileData data;
foreach(const QXmlStreamAttribute &attr,xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
if(name == "Path")
data.path = value;
else if(name == "Hash")
data.hash = value;
}
datas->append(data);
}
}
xmlReader.readNext();
}
}
QByteArray DataParser::xmlAnswer(QList<SXmlAnswerTag> listTag, QString elemUp1, QString elemUp2)
{
try {
mutex->lock();
/* Открываем файл для Записи*/
QFile file(tempFile);
file.open(QIODevice::WriteOnly);
/* Создаем объект, с помощью которого осуществляется запись в файл */
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true); // Устанавливаем автоформатирование текста
xmlWriter.writeStartDocument(); // Запускаем запись в документ
if(elemUp1 != "")
xmlWriter.writeStartElement(elemUp1); // Записываем тег
if(elemUp2 != "")
xmlWriter.writeStartElement(elemUp2); // Записываем тег
//Записываем все элементы
foreach(SXmlAnswerTag tag, listTag)
{
xmlWriter.writeStartElement(tag.elementName); // Записываем тег
// Записываем атрибуты
foreach(SAttribute attr, tag.attr)
xmlWriter.writeAttribute(attr.name, attr.value);
xmlWriter.writeEndElement(); // Закрываем тег
}
if(elemUp1 != "")
xmlWriter.writeEndElement(); // Закрываем тег
if(elemUp1 != "")
xmlWriter.writeEndElement(); // Закрываем тег
/* Завершаем запись в документ*/
xmlWriter.writeEndDocument();
file.close(); // Закрываем файл
QByteArray array;
/* Открываем файл для Чтения*/
QFile fileR(tempFile);
if (!fileR.open(QFile::ReadOnly | QFile::Text))
{
QString str = "Не удалось открыть файл";
qDebug() << "xmlAnswer: " << str;
}
else
{
array = fileR.readAll();
fileR.close(); // Закрываем файл
}
mutex->unlock();
return array;
}
catch(const std::exception& e)
{
qDebug() << e.what();
return nullptr;
}
}
QByteArray DataParser::xmlAnswer_authorization(bool result, QString instructorName,QString clientName, QString accessType, QString login)
{
QList<SXmlAnswerTag> listTag;
SAttribute attribute1 = {"Result", result? "true" : "false"};
SAttribute attribute2 = {"InstructorName", instructorName};
SAttribute attribute3 = {"ClientName", clientName};
SAttribute attribute4 = {"AccessType", accessType};
SAttribute attribute5 = {"Login", login};
QList<SAttribute> listAttr = {attribute1, attribute2, attribute3, attribute4, attribute5};
SXmlAnswerTag tag = {"ServerAuthorization", listAttr};
listTag.append(tag);
return xmlAnswer(listTag);
}
QByteArray DataParser::xmlAnswer_deAuthorization(bool result, QString login)
{
QList<SXmlAnswerTag> listTag;
SAttribute attribute1 = {"Result", result? "true" : "false"};
SAttribute attribute2 = {"Login", login};
QList<SAttribute> listAttr = {attribute1, attribute2};
SXmlAnswerTag tag = {"ServerDeAuthorization", listAttr};
listTag.append(tag);
return xmlAnswer(listTag);
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB(bool result, QList<Instructor>* listInstructors,
QList<Trainee>* listTrainees, QList<Group>* listGroups)
{
QDomDocument groupsTraineesDOM;
QFile blankFile(":/blankXML/groupsTrainees.xml");
if (! blankFile.open(QFile::ReadOnly | QFile::Text)) {
qDebug() << "SaveTraineesGroupsXML: Не удалось считать файл :/blankXML/groupsTrainees.xml";
return QByteArray();
}
groupsTraineesDOM.setContent(blankFile.readAll());
blankFile.close();
QDomNode allListsNode = groupsTraineesDOM.namedItem("AllLists");
QDomNode groupsTraineesNode = allListsNode.firstChildElement("GroupsTrainees");
QDomNode allInstructorsNode = allListsNode.firstChildElement("Instructors");
for(Group group : *listGroups)
{
//Группа
QDomNode groupNode = groupsTraineesDOM.createElement("group");
groupsTraineesNode.appendChild(groupNode);
groupNode.toElement().setAttribute("group_id", group.getID());
groupNode.toElement().setAttribute("name", group.getName());
//Обучаемые
for(Trainee trainee : *listTrainees)
{
if(group.getID() != trainee.getGroup().getID())
continue;
QDomNode traineeNode = groupsTraineesDOM.createElement("trainee");
groupNode.appendChild(traineeNode);
traineeNode.toElement().setAttribute("trainee_id", QString::number(trainee.getID()));
traineeNode.toElement().setAttribute("name", trainee.getName());
traineeNode.toElement().setAttribute("login", trainee.getLogin());
traineeNode.toElement().setAttribute("password", trainee.getPassword());
traineeNode.toElement().setAttribute("archived", trainee.getArchived() ? QStringLiteral("true") : QStringLiteral("false"));
traineeNode.toElement().setAttribute("logged_in", trainee.getLoggedIn() ? QStringLiteral("true") : QStringLiteral("false"));
traineeNode.toElement().setAttribute("group_trainee", QString::number(trainee.getGroup().getID()));
traineeNode.toElement().setAttribute("computer_trainee", QString::number(trainee.getComputer().getID()));
}
}
for(Instructor instructor : *listInstructors)
{
//Инструктор
QDomNode instructorNode = groupsTraineesDOM.createElement("instructor");
allInstructorsNode.appendChild(instructorNode);
instructorNode.toElement().setAttribute("instructor_id", QString::number(instructor.getID()));
instructorNode.toElement().setAttribute("name", instructor.getName());
instructorNode.toElement().setAttribute("login", instructor.getLogin());
instructorNode.toElement().setAttribute("password", instructor.getPassword());
instructorNode.toElement().setAttribute("is_admin", instructor.getIsAdmin() ? QStringLiteral("true") : QStringLiteral("false"));
instructorNode.toElement().setAttribute("archived", instructor.getArchived() ? QStringLiteral("true") : QStringLiteral("false"));
instructorNode.toElement().setAttribute("logged_in", instructor.getLoggedIn() ? QStringLiteral("true") : QStringLiteral("false"));
}
QString xmlFileName = /*appDirPath +*/ "GroupsTrainees.xml";
QFile xmlOutFile(xmlFileName);
if (!xmlOutFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "SaveTraineesGroupsXML: Не удалось записать файл " + xmlFileName;
return QByteArray();
}
QTextStream outFile(&xmlOutFile);
groupsTraineesDOM.save(outFile, 4);
xmlOutFile.close();
return groupsTraineesDOM.toByteArray();
}
bool DataParser::loadBlankXML(QString nameFile, QDomDocument *commonDOM)
{
QFile blankFile(":/blankXML/" + nameFile);
if (! blankFile.open(QFile::ReadOnly | QFile::Text)) {
qDebug() << "loadBlankXML: Не удалось считать файл :/blankXML/" + nameFile;
return false;
}
commonDOM->setContent(blankFile.readAll());
blankFile.close();
return true;
}
bool DataParser::saveDOMtoXML(QString nameFile, QDomDocument *commonDOM)
{
QFile xmlOutFile(nameFile);
if (!xmlOutFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "saveDOMtoXML: Не удалось записать файл " + nameFile;
return false;
}
else
{
QTextStream outFile(&xmlOutFile);
commonDOM->save(outFile, 4);
xmlOutFile.close();
}
return true;
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB_ListInstructors(bool result, QList<Instructor> *listInstructors)
{
QDomDocument commonDOM;
if(! loadBlankXML("ListInstructors.xml", &commonDOM))
return QByteArray();
QDomNode listNode = commonDOM.namedItem("ListInstructors");
for(Instructor instructor : *listInstructors)
{
//Инструктор
QDomNode instructorNode = commonDOM.createElement("Instructor");
listNode.appendChild(instructorNode);
instructorNode.toElement().setAttribute("instructor_id", QString::number(instructor.getID()));
instructorNode.toElement().setAttribute("name", instructor.getName());
instructorNode.toElement().setAttribute("login", instructor.getLogin());
instructorNode.toElement().setAttribute("password", instructor.getPassword());
instructorNode.toElement().setAttribute("is_admin", instructor.getIsAdmin());
instructorNode.toElement().setAttribute("archived", instructor.getArchived());
instructorNode.toElement().setAttribute("logged_in", instructor.getLoggedIn());
}
saveDOMtoXML("ListInstructors.xml", &commonDOM);
return commonDOM.toByteArray();
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB_ListGroups(bool result, QList<Group> *listGroups)
{
QDomDocument commonDOM;
if(! loadBlankXML("ListGroups.xml", &commonDOM))
return QByteArray();
QDomNode listNode = commonDOM.namedItem("ListGroups");
for(Group group : *listGroups)
{
//Группа
QDomNode groupNode = commonDOM.createElement("Group");
listNode.appendChild(groupNode);
groupNode.toElement().setAttribute("group_id", QString::number(group.getID()));
groupNode.toElement().setAttribute("name", group.getName());
}
saveDOMtoXML("ListGroups.xml", &commonDOM);
return commonDOM.toByteArray();
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB_ListTrainees(bool result, QList<Trainee> *listTrainees)
{
QDomDocument commonDOM;
if(! loadBlankXML("ListTrainees.xml", &commonDOM))
return QByteArray();
QDomNode listNode = commonDOM.namedItem("ListTrainees");
for(Trainee trainee : *listTrainees)
{
//Обучаемый
QDomNode traineeNode = commonDOM.createElement("Trainee");
listNode.appendChild(traineeNode);
traineeNode.toElement().setAttribute("trainee_id", trainee.getID());
traineeNode.toElement().setAttribute("name", trainee.getName());
traineeNode.toElement().setAttribute("login", trainee.getLogin());
traineeNode.toElement().setAttribute("password", trainee.getPassword());
traineeNode.toElement().setAttribute("archived", trainee.getArchived());
traineeNode.toElement().setAttribute("logged_in", trainee.getLoggedIn());
traineeNode.toElement().setAttribute("group_trainee", trainee.getGroup().getID());
traineeNode.toElement().setAttribute("computer_trainee", trainee.getComputer().getID());
//trainee.setTasks()
}
saveDOMtoXML("ListTrainees.xml", &commonDOM);
return commonDOM.toByteArray();
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB_ListComputers(bool result, QList<Computer> *listComputers)
{
//TODO
return QByteArray();
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB_ListClassrooms(bool result, QList<Classroom> *listClassrooms)
{
//TODO
return QByteArray();
}
QByteArray DataParser::xmlAnswer_ClientQueryToDB_ListTasks(bool result, QList<Task> *listTasks)
{
//TODO
return QByteArray();
}
QByteArray DataParser::xmlAnswer_message(QString text)
{
QList<SXmlAnswerTag> listTag;
SAttribute attribute1 = {"Text", text};
QList<SAttribute> listAttr = {attribute1};
SXmlAnswerTag tag = {"ServerMessage", listAttr};
listTag.append(tag);
return xmlAnswer(listTag);
}
QByteArray DataParser::xmlAnswer_task(QString text)
{
QList<SXmlAnswerTag> listTag;
SAttribute attribute1 = {"Text", text};
QList<SAttribute> listAttr = {attribute1};
SXmlAnswerTag tag = {"ServerTask", listAttr};
listTag.append(tag);
return xmlAnswer(listTag);
}
QByteArray DataParser::xmlAnswer_notify(QString code)
{
QList<SXmlAnswerTag> listTag;
SAttribute attribute1 = {"Code", code};
QList<SAttribute> listAttr = {attribute1};
SXmlAnswerTag tag = {"ServerNotify", listAttr};
listTag.append(tag);
return xmlAnswer(listTag);
}
QByteArray DataParser::xmlAnswer_tasks(QStringList listTasks)
{
QList<SXmlAnswerTag> listTag;
foreach(QString task, listTasks)
{
QList<SAttribute> listAttr;
SAttribute attribute1 = {"Head", task};
SAttribute attribute2 = {"IsComplete", "false"};
listAttr.append(attribute1);
listAttr.append(attribute2);
SXmlAnswerTag tag = {"ServerTask", listAttr};
listTag.append(tag);
}
return xmlAnswer(listTag, "TaskArray", "Tasks");
}
DataInfo *DataParser::getCurrentDataInfo()
{
return dataInfo;
}
void DataParser::clearCurrentDataInfo()
{
delete dataInfo;
}
QList<FileData> *DataParser::getDatas() const
{
return datas;
}
DataParser::~DataParser()
{
}