Files
RRJServer/ServerLMS/ServerLMS/Systems/dataparser.cpp
2025-01-13 14:22:52 +03:00

691 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(AssetsManager *assetManager,ProcessingSystem *processingSystem,QObject *parent) :
QObject(parent)
{
this->processingSystem = processingSystem;
this->assetsManager = assetManager;
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() == "ToClientMessage")
{//Отправка сообщения Клиенту
ToClientMessage toClientMessage;
/*Перебираем все атрибуты тега*/
foreach(const QXmlStreamAttribute &attr, xmlReader.attributes())
{
QString name = attr.name().toString();
QString value = attr.value().toString();
//addTextToLogger(name + ": " + value);
if(name == "id")
toClientMessage.id = value.toInt();
else if(name == "Text")
toClientMessage.Text = value;
else if(name == "Login")
toClientMessage.Login = value;
}
processingSystem->processingToClientMessage(client, toClientMessage);
}
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_NEW_TRAINEE:
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_NEW_GROUP:
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_NEW_TRAINEE:
case TypeQueryToDB::TYPE_QUERY_EDIT_TRAINEE:
data = &trainee;
break;
case TypeQueryToDB::TYPE_QUERY_NEW_GROUP:
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->processingFromClientMessage(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;
array = readTempFile();
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);
}
bool DataParser::loadBlankXML(QString nameFile, QDomDocument *commonDOM)
{
QFile blankFile(nameFile);
if (! blankFile.open(QFile::ReadOnly | QFile::Text)) {
qDebug() << "loadBlankXML: Couldn't read the file: " + 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: Failed to write a file: " + 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(":/resources/blankXML/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(":/resources/blankXML/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(":/resources/blankXML/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, QString login)
{
QList<SXmlAnswerTag> listTag;
SAttribute attribute2;
SAttribute attribute1 = {"Text", text};
QList<SAttribute> listAttr = {attribute1};
if(login != "")
{
attribute2 = {"Login", login};
listAttr.append(attribute2);
}
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");
}
QByteArray DataParser::xmlAnswer_currentVersion()
{
QByteArray array;
QFile fileR(version);
if (!fileR.open(QFile::ReadOnly | QFile::Text))
{
QString str = "Не удалось открыть файл";
qDebug() << "xmlAnswer: " << str;
}
else
{
array = fileR.readAll();
fileR.close(); // Закрываем файл
}
return array;
}
void DataParser::createVersionListXmlAnswer(QList<StreamingVersionData *> version)
{
QList<SXmlAnswerTag> listTag;
foreach(StreamingVersionData* ver,version)
{
SAttribute attribute1 = {"Version", ver->getViewName()};
SAttribute attribute2 = {"Created", ver->getCreateData().toString()};
QList<SAttribute> listAttr = {attribute1, attribute2};
SXmlAnswerTag tag = {"VersionData", listAttr};
listTag.append(tag);
}
QFile file(versionListFile);
file.open(QIODevice::WriteOnly);
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("VersionList");
foreach(SXmlAnswerTag tag,listTag)
{
xmlWriter.writeStartElement(tag.elementName);
foreach(SAttribute attribute,tag.attr)
{
xmlWriter.writeAttribute(attribute.name,attribute.value);
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
file.close();
}
QByteArray DataParser::readTempFile()
{
QByteArray array;
QFile fileR(tempFile);
if (!fileR.open(QFile::ReadOnly | QFile::Text))
{
QString str = "Не удалось открыть файл";
qDebug() << "xmlAnswer: " << str;
}
else
{
array = fileR.readAll();
fileR.close(); // Закрываем файл
}
return array;
}
void DataParser::saveVersionToFile(StreamingVersionData *streamingVersion)
{
QFile file(version);
file.open(QFile::WriteOnly);
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("VersionData");
xmlWriter.writeAttribute("Version",streamingVersion->getViewName());
xmlWriter.writeAttribute("Created",streamingVersion->getCreateData().toString());
xmlWriter.writeEndElement();
xmlWriter.writeEndDocument();
file.close();
}
DataInfo *DataParser::getCurrentDataInfo()
{
return dataInfo;
}
void DataParser::clearCurrentDataInfo()
{
delete dataInfo;
}
QList<FileData> *DataParser::getDatas() const
{
return datas;
}
DataParser::~DataParser()
{
}