tcontroller.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. #include "tcontroller.h"
  2. #include "qglobal.h"
  3. #include "qvariant.h"
  4. #include "teachertr.h"
  5. #include "tmodel.h"
  6. #include <QDir>
  7. #include <QJsonArray>
  8. #include <QJsonObject>
  9. #include <QMimeDatabase>
  10. #include "appevent.h"
  11. #include "qjsonwebtoken.h"
  12. #include <cwf/filemanager.h>
  13. #include <cwf/sqlquery.h>
  14. static CWF::SqlDatabaseStorage storage("QSQLITE", "localhost", "data.db", "", "");
  15. static const QLatin1String tokenSecret("mydirtysecret");
  16. static QJsonObject getJwtToken(qint64 userid)
  17. {
  18. QJsonWebToken token;
  19. const QDateTime time = QDateTime::currentDateTime();
  20. int expDate = 7;
  21. //当前时间
  22. token.setSecret(tokenSecret);
  23. token.appendClaim("iat", QString::number(time.toSecsSinceEpoch()));
  24. // 过期时间
  25. token.appendClaim("exp", QString::number(time.addDays(expDate).toSecsSinceEpoch()));
  26. token.appendClaim("userId", QString::number(userid));
  27. return QJsonObject{{"access_token", token.getToken()},
  28. {"access_expire", time.addDays(expDate).toSecsSinceEpoch()},
  29. {"refresh_after", time.addDays(expDate / 2).toSecsSinceEpoch()}};
  30. }
  31. static QStringList listFiles(const QString &path, const QString &basePath)
  32. {
  33. QDir dir(path);
  34. QStringList fileList;
  35. // 获取所有文件
  36. QFileInfoList files = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
  37. foreach (QFileInfo file, files) {
  38. // 计算相对路径并添加到 fileList 中
  39. QString relativePath = dir.relativeFilePath(file.absoluteFilePath());
  40. fileList.append(relativePath);
  41. }
  42. // 递归获取子目录中的文件
  43. QFileInfoList dirs = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
  44. foreach (QFileInfo subDir, dirs) {
  45. // 递归获取子目录的文件列表
  46. QStringList subDirFiles = listFiles(subDir.absoluteFilePath(), basePath);
  47. // 计算子目录相对于 basePath 的相对路径
  48. QString relativeSubDirPath = dir.relativeFilePath(subDir.absoluteFilePath());
  49. // 将子目录中的文件相对路径添加到 fileList 中
  50. foreach (QString subFile, subDirFiles) {
  51. fileList.append(relativeSubDirPath + "/" + subFile);
  52. }
  53. }
  54. return fileList;
  55. }
  56. void ConfigController::doGet(CWF::Request &request, CWF::Response &response) const
  57. {
  58. // IP 地址是自己配置
  59. static QStringList filter = {"serverIP",
  60. "serverPort",
  61. "webSocketIP",
  62. "webSocketPort",
  63. "savedUsername",
  64. "savedPassword"};
  65. QJsonObject responseConfig;
  66. const QJsonObject object = AppEvent::instance()->config();
  67. for (auto it = object.constBegin(); it != object.constEnd(); ++it) {
  68. const QString key = it.key();
  69. if (!filter.contains(key)) {
  70. responseConfig.insert(key, it.value());
  71. }
  72. }
  73. response.write(QJsonObject{{"status", true},
  74. {"message", TeacherServer::Tr::tr("ok")},
  75. {"code", 200},
  76. {"data", responseConfig}});
  77. }
  78. void LoginController::doPost(CWF::Request &request, CWF::Response &response) const
  79. {
  80. // 获取服务器参数信息
  81. // qDebug() << request.getSession().getId();
  82. // qDebug() << request.getRequestURI() << request.getBody();
  83. QJsonParseError error;
  84. QJsonDocument jdc = QJsonDocument::fromJson(request.getBody(), &error);
  85. QJsonObject jsonObject = jdc.object();
  86. QJsonObject::const_iterator it = jsonObject.constBegin();
  87. QJsonObject::const_iterator end = jsonObject.constEnd();
  88. QMap<QByteArray, QByteArray> par;
  89. while (it != end) {
  90. par.insert(it.key().toUtf8(), it.value().toString().toUtf8());
  91. it++;
  92. }
  93. UserModel user(storage);
  94. request.fillQObject(&user, par, false);
  95. if (user.getName() == "123" && (user.getSwID() == "123" || user.getExamineeNumber() == "123")) {
  96. QJsonObject UserResponse{{"id", 0}, {"name", "123"}, {"JwtToken", getJwtToken(0)}};
  97. response.write(QJsonObject{{"status", true},
  98. {"message", TeacherServer::Tr::tr("Login succeeded")},
  99. {"code", 200},
  100. {"data", UserResponse}});
  101. return;
  102. }
  103. CWF::SqlQueryManager queryManager(storage);
  104. queryManager.select("*", user.getTableName()).where("name=?");
  105. queryManager.prepare();
  106. queryManager.addBindValue(user.getName());
  107. queryManager.exec();
  108. QJsonArray jsonArray = queryManager.toJson();
  109. if (jsonArray.isEmpty()) {
  110. response.write(QJsonObject{{"status", false},
  111. {"message", TeacherServer::Tr::tr("user does not exist")},
  112. {"code", 500},
  113. {"data", QJsonValue()}});
  114. return;
  115. }
  116. // QString name;
  117. // QString phone;
  118. // QString swID;
  119. // QString state;
  120. // QString examineeNumber;
  121. for (const QJsonValue &json : jsonArray) {
  122. if (json.isObject()) {
  123. QJsonObject obj = json.toObject();
  124. bool isok = false;
  125. if (obj.contains("swID")) {
  126. const QString swID = user.getSwID();
  127. if (obj["swID"] == user.getSwID() && !swID.isEmpty()) {
  128. isok = true;
  129. }
  130. }
  131. if (obj.contains("examineeNumber")) {
  132. const QString examineeNumber = user.getExamineeNumber();
  133. if (obj["examineeNumber"] == examineeNumber && !examineeNumber.isEmpty()) {
  134. isok = true;
  135. }
  136. }
  137. if (isok) {
  138. QJsonObject UserResponse{{"id", obj["id"]},
  139. {"name", obj["name"]},
  140. {"JwtToken", getJwtToken(obj["id"].toInt())}};
  141. response.write(QJsonObject{{"status", true},
  142. {"message", TeacherServer::Tr::tr("Login succeeded")},
  143. {"code", 200},
  144. {"data", UserResponse}});
  145. // 修改登录状态
  146. obj["state"] = 1;
  147. // 更新在线状态
  148. user.buildFromJson(obj);
  149. user.save();
  150. AppEvent::instance()->loginUser(obj["id"].toInt());
  151. return;
  152. }
  153. }
  154. }
  155. response.write(QJsonObject{{"status", false},
  156. {"message", TeacherServer::Tr::tr("Login failed")},
  157. {"code", 500},
  158. {"data", QJsonValue()}});
  159. }
  160. void UserInfoController::doGet(CWF::Request &request, CWF::Response &response) const
  161. {
  162. const QString authorization = request.getHttpParser().getHeaderField("Authorization");
  163. if (authorization.isEmpty()) {
  164. response.write(
  165. QJsonObject{{"status", false},
  166. {"message", TeacherServer::Tr::tr("LoginOut failed, no find user")},
  167. {"code", 500},
  168. {"data", QJsonValue()}});
  169. return;
  170. }
  171. QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(authorization.mid(7), tokenSecret);
  172. if (!token.isValid()) {
  173. response.write(QJsonObject{{"status", false},
  174. {"message", TeacherServer::Tr::tr("unauthorized")},
  175. {"code", response.SC_UNAUTHORIZED},
  176. {"data", QJsonValue()}});
  177. return;
  178. }
  179. QString userid = token.claim("userId");
  180. bool isok = false;
  181. qint64 id = userid.toLongLong(&isok, 10);
  182. if (id == 0) {
  183. QJsonObject userInfo;
  184. userInfo.insert("username", "123");
  185. userInfo.insert("maxTime", 0);
  186. userInfo.insert("checkinNumber", "--");
  187. response.write(QJsonObject{{"status", true},
  188. {"message", TeacherServer::Tr::tr("LoginOut succeeded")},
  189. {"code", 200},
  190. {"data", userInfo}});
  191. return;
  192. }
  193. UserModel user(storage);
  194. CWF::SqlQueryManager queryManager(storage);
  195. queryManager.select("*", user.getTableName()).where("id=?");
  196. queryManager.prepare();
  197. queryManager.addBindValue(id);
  198. queryManager.exec();
  199. QJsonArray jsonArray = queryManager.toJson();
  200. if (jsonArray.isEmpty()) {
  201. response.write(QJsonObject{{"status", false},
  202. {"message", TeacherServer::Tr::tr("user does not exist")},
  203. {"code", 500},
  204. {"data", QJsonValue()}});
  205. return;
  206. }
  207. for (const QJsonValue &json : jsonArray) {
  208. if (json.isObject()) {
  209. QJsonObject obj = json.toObject();
  210. QJsonObject userInfo;
  211. userInfo.insert("username", obj.value("name"));
  212. userInfo.insert("maxTime", obj.value("maxTime"));
  213. userInfo.insert("checkinNumber", obj.value("checkinNumber")); // 1 - name
  214. response.write(QJsonObject{{"status", true},
  215. {"message", TeacherServer::Tr::tr("LoginOut succeeded")},
  216. {"code", 200},
  217. {"data", userInfo}});
  218. return;
  219. }
  220. }
  221. response.write(QJsonObject{{"status", false},
  222. {"message", TeacherServer::Tr::tr("Login failed")},
  223. {"code", 500},
  224. {"data", QJsonValue()}});
  225. }
  226. void LoginOutController::doPost(CWF::Request &request, CWF::Response &response) const
  227. {
  228. const QString authorization = request.getHttpParser().getHeaderField("Authorization");
  229. if (authorization.isEmpty()) {
  230. response.write(
  231. QJsonObject{{"status", false},
  232. {"message", TeacherServer::Tr::tr("LoginOut failed, no find user")},
  233. {"code", 500},
  234. {"data", QJsonValue()}});
  235. return;
  236. }
  237. QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(authorization.mid(7), tokenSecret);
  238. if (!token.isValid()) {
  239. response.write(QJsonObject{{"status", false},
  240. {"message", TeacherServer::Tr::tr("unauthorized")},
  241. {"code", response.SC_UNAUTHORIZED},
  242. {"data", QJsonValue()}});
  243. return;
  244. }
  245. QString userid = token.claim("userId");
  246. bool isok = false;
  247. qint64 id = userid.toLongLong(&isok, 10);
  248. if (id == 0) {
  249. response.write(QJsonObject{{"status", true},
  250. {"message", TeacherServer::Tr::tr("LoginOut succeeded")},
  251. {"code", 200},
  252. {"data", QJsonValue()}});
  253. return;
  254. }
  255. UserModel user(storage);
  256. CWF::SqlQueryManager queryManager(storage);
  257. queryManager.select("*", user.getTableName()).where("id=?");
  258. queryManager.prepare();
  259. queryManager.addBindValue(id);
  260. queryManager.exec();
  261. QJsonArray jsonArray = queryManager.toJson();
  262. if (jsonArray.isEmpty()) {
  263. response.write(QJsonObject{{"status", false},
  264. {"message", TeacherServer::Tr::tr("user does not exist")},
  265. {"code", 500},
  266. {"data", QJsonValue()}});
  267. return;
  268. }
  269. for (const QJsonValue &json : jsonArray) {
  270. if (json.isObject()) {
  271. QJsonObject obj = json.toObject();
  272. // 修改登录状态
  273. obj["state"] = 0;
  274. // 更新在线状态
  275. user.buildFromJson(obj);
  276. user.save();
  277. AppEvent::instance()->loginOutUser(obj["id"].toInt());
  278. response.write(QJsonObject{{"status", true},
  279. {"message", TeacherServer::Tr::tr("LoginOut succeeded")},
  280. {"code", 200},
  281. {"data", QJsonValue()}});
  282. return;
  283. }
  284. }
  285. response.write(QJsonObject{{"status", false},
  286. {"message", TeacherServer::Tr::tr("Login failed")},
  287. {"code", 500},
  288. {"data", QJsonValue()}});
  289. }
  290. void ExamsController::doPost(CWF::Request &request, CWF::Response &response) const
  291. {
  292. const QString authorization = request.getHttpParser().getHeaderField("Authorization");
  293. QString examContent;
  294. if (!authorization.isEmpty()) {
  295. // response.write(
  296. // QJsonObject{{"status", false},
  297. // {"message", TeacherServer::Tr::tr("exam content failed, no find user")},
  298. // {"code", 500},
  299. // {"data", QJsonValue()}});
  300. // return;
  301. QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(authorization.mid(7), tokenSecret);
  302. if (!token.isValid()) {
  303. response.write(QJsonObject{{"status", false},
  304. {"message", TeacherServer::Tr::tr("unauthorized")},
  305. {"code", response.SC_UNAUTHORIZED},
  306. {"data", QJsonValue()}});
  307. return;
  308. }
  309. QString userid = token.claim("userId");
  310. bool isok = false;
  311. qint64 id = userid.toLongLong(&isok, 10);
  312. ///////////// 获取个人用户的考题
  313. CWF::SqlQuery query(storage);
  314. QJsonObject status = query.exec(QString("SELECT * FROM user WHERE id = %1").arg(id));
  315. if (status["success"].toBool()) {
  316. const QJsonArray array = query.toJson();
  317. if (!array.isEmpty()) {
  318. QJsonObject object = array[0].toObject();
  319. examContent = object["examTest"].toString();
  320. }
  321. }
  322. }
  323. UserModel user(storage);
  324. ExamsQuestionModel exams(storage);
  325. // 个人考试内容是空 获取默认选择的考试内容
  326. if (examContent.isEmpty()) {
  327. CWF::SqlQuery query(storage);
  328. QJsonObject status = query.exec(QString("SELECT * FROM exams_question WHERE isSelect = 1"));
  329. if (status["success"].toBool()) {
  330. const QJsonArray array = query.toJson();
  331. if (!array.isEmpty()) {
  332. QJsonObject object = array[0].toObject();
  333. examContent = object["name"].toString();
  334. }
  335. }
  336. }
  337. // 获取考试内容
  338. CWF::SqlQueryManager queryManager(storage);
  339. queryManager.select("*", exams.getTableName()).where("name = ?");
  340. queryManager.prepare();
  341. queryManager.addBindValue(examContent);
  342. queryManager.exec();
  343. QJsonArray jsonArray = queryManager.toJson();
  344. if (jsonArray.isEmpty()) {
  345. response.write(
  346. QJsonObject{{"status", false},
  347. {"message", TeacherServer::Tr::tr("Failed to obtain exam content")},
  348. {"code", 500},
  349. {"data", QJsonValue()}});
  350. return;
  351. }
  352. for (const QJsonValue &json : jsonArray) {
  353. if (json.isObject()) {
  354. QJsonObject obj = json.toObject();
  355. const QString dir = obj["fileDir"].toString();
  356. const QStringList files = listFiles(dir, dir);
  357. response.write(QJsonObject{{"status", true},
  358. {"message", TeacherServer::Tr::tr("ok")},
  359. {"code", 200},
  360. {"data", QJsonArray::fromStringList(files)}});
  361. }
  362. }
  363. response.write(QJsonObject{{"status", false},
  364. {"message", TeacherServer::Tr::tr("Failed to obtain exam content")},
  365. {"code", 500},
  366. {"data", QJsonValue()}});
  367. }
  368. void ExamsFilesController::doGet(CWF::Request &request, CWF::Response &response) const
  369. {
  370. const QString authorization = request.getHttpParser().getHeaderField("Authorization");
  371. QString examContent;
  372. if (!authorization.isEmpty()) {
  373. QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(authorization.mid(7), tokenSecret);
  374. if (!token.isValid()) {
  375. response.write(QJsonObject{{"status", false},
  376. {"message", TeacherServer::Tr::tr("unauthorized")},
  377. {"code", response.SC_UNAUTHORIZED},
  378. {"data", QJsonValue()}});
  379. return;
  380. }
  381. QString userid = token.claim("userId");
  382. bool isok = false;
  383. qint64 id = userid.toLongLong(&isok, 10);
  384. ///////////// 获取个人用户的考题
  385. CWF::SqlQuery query(storage);
  386. QJsonObject status = query.exec(QString("SELECT * FROM user WHERE id = %1").arg(id));
  387. if (status["success"].toBool()) {
  388. const QJsonArray array = query.toJson();
  389. if (!array.isEmpty()) {
  390. QJsonObject object = array[0].toObject();
  391. examContent = object["examTest"].toString();
  392. }
  393. }
  394. }
  395. UserModel user(storage);
  396. ExamsQuestionModel exams(storage);
  397. // 个人考试内容是空 获取默认选择的考试内容
  398. if (examContent.isEmpty()) {
  399. CWF::SqlQuery query(storage);
  400. QJsonObject status = query.exec(QString("SELECT * FROM exams_question WHERE isSelect = 1"));
  401. if (status["success"].toBool()) {
  402. const QJsonArray array = query.toJson();
  403. if (!array.isEmpty()) {
  404. QJsonObject object = array[0].toObject();
  405. examContent = object["name"].toString();
  406. }
  407. }
  408. }
  409. QString fileName = request.getParameter("file");
  410. // 获取考试内容
  411. CWF::SqlQueryManager queryManager(storage);
  412. queryManager.select("*", exams.getTableName()).where("name = ?");
  413. queryManager.prepare();
  414. queryManager.addBindValue(examContent);
  415. queryManager.exec();
  416. QJsonArray jsonArray = queryManager.toJson();
  417. if (jsonArray.isEmpty()) {
  418. response.write(
  419. QJsonObject{{"status", false},
  420. {"message", TeacherServer::Tr::tr("Failed to obtain exam content")},
  421. {"code", 500},
  422. {"data", QJsonValue()}});
  423. return;
  424. }
  425. QString dir;
  426. for (const QJsonValue &json : jsonArray) {
  427. if (json.isObject()) {
  428. QJsonObject obj = json.toObject();
  429. dir = obj["fileDir"].toString();
  430. break;
  431. }
  432. }
  433. // 获取扩展类型
  434. auto getMimeType = [](const QString &fileName) {
  435. QMimeDatabase mimeDatabase;
  436. QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileName);
  437. return mimeType.name();
  438. };
  439. const QString path = dir + "/" + fileName;
  440. QFile file(path);
  441. if (file.open(QIODevice::ReadOnly)) {
  442. QString extention = CWF::FileManager::fileExtention(fileName).toLower();
  443. response.addHeader(CWF::HTTP::CONTENT_DISPOSITION,
  444. "filename=" + QUrl::toPercentEncoding(fileName));
  445. response.addHeader(CWF::HTTP::CONTENT_TYPE, getMimeType(fileName).toUtf8());
  446. response.write(file.readAll());
  447. } else {
  448. response.sendJsonError(0, file.errorString().toUtf8());
  449. }
  450. }
  451. void UploadedFilesController::doPost(CWF::Request &request, CWF::Response &response) const
  452. {
  453. const QString authorization = request.getHttpParser().getHeaderField("Authorization");
  454. if (authorization.isEmpty()) {
  455. response.write(
  456. QJsonObject{{"status", false},
  457. {"message", TeacherServer::Tr::tr("LoginOut failed, no find user")},
  458. {"code", 500},
  459. {"data", QJsonValue()}});
  460. return;
  461. }
  462. QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(authorization.mid(7), tokenSecret);
  463. if (!token.isValid()) {
  464. response.write(QJsonObject{{"status", false},
  465. {"message", TeacherServer::Tr::tr("unauthorized")},
  466. {"code", response.SC_UNAUTHORIZED},
  467. {"data", QJsonValue()}});
  468. return;
  469. }
  470. QString userid = token.claim("userId");
  471. bool isok = false;
  472. qint64 id = userid.toLongLong(&isok, 10);
  473. if (id == 0) {
  474. response.write(QJsonObject{{"status", true},
  475. {"message", TeacherServer::Tr::tr("file uploaded successfully")},
  476. {"code", 200},
  477. {"data", QJsonValue()}});
  478. return;
  479. }
  480. UserModel user(storage);
  481. CWF::SqlQueryManager queryManager(storage);
  482. queryManager.select("*", user.getTableName()).where("id=?");
  483. queryManager.prepare();
  484. queryManager.addBindValue(id);
  485. queryManager.exec();
  486. QJsonArray jsonArray = queryManager.toJson();
  487. if (jsonArray.isEmpty()) {
  488. response.write(QJsonObject{{"status", false},
  489. {"message", TeacherServer::Tr::tr("user does not exist")},
  490. {"code", 500},
  491. {"data", QJsonValue()}});
  492. return;
  493. }
  494. for (const QJsonValue &json : jsonArray) {
  495. if (json.isObject()) {
  496. QJsonObject obj = json.toObject();
  497. // 更新在线状态
  498. user.buildFromJson(obj);
  499. user.save();
  500. AppEvent::instance()->loginOutUser(obj["id"].toInt());
  501. }
  502. }
  503. const QMultiMap<QByteArray, QByteArray> &files = request.getUploadedFiles();
  504. if (user.getId() > 0) {
  505. QVariant answerDir = AppEvent::instance()->configValue("answerDir");
  506. const QString path = answerDir.toString();
  507. QDir dir = path;
  508. if (!dir.exists(path)) {
  509. dir.mkpath(path);
  510. }
  511. for (auto it = files.begin(); it != files.end(); ++it) {
  512. QString fileName = user.getAnswerFileName();
  513. if (fileName.isEmpty()) {
  514. fileName = QString("%1_%2.zip").arg(user.getName()).arg(user.getExamineeNumber());
  515. }
  516. const QString filePath = dir.absoluteFilePath(fileName);
  517. QFile file(filePath);
  518. if (!file.open(QIODevice::WriteOnly)) {
  519. qWarning() << "Failed to open file for writing:" << file.errorString() << filePath;
  520. }
  521. file.write(it.value());
  522. file.close();
  523. }
  524. response.write(QJsonObject{{"status", true},
  525. {"message", TeacherServer::Tr::tr("file uploaded successfully")},
  526. {"code", 200},
  527. {"data", QJsonValue()}});
  528. return;
  529. }
  530. response.write(QJsonObject{{"status", false},
  531. {"message", TeacherServer::Tr::tr("Failed to uploaded files")},
  532. {"code", 500},
  533. {"data", QJsonValue()}});
  534. }
  535. void ExamsAnswerTimeController::doPost(CWF::Request &request, CWF::Response &response) const
  536. {
  537. const QString authorization = request.getHttpParser().getHeaderField("Authorization");
  538. if (authorization.isEmpty()) {
  539. response.write(
  540. QJsonObject{{"status", false},
  541. {"message", TeacherServer::Tr::tr("answer Time failed, no find user login")},
  542. {"code", 500},
  543. {"data", QJsonValue()}});
  544. return;
  545. }
  546. QJsonWebToken token = QJsonWebToken::fromTokenAndSecret(authorization.mid(7), tokenSecret);
  547. if (!token.isValid()) {
  548. response.write(QJsonObject{{"status", false},
  549. {"message", TeacherServer::Tr::tr("unauthorized")},
  550. {"code", response.SC_UNAUTHORIZED},
  551. {"data", QJsonValue()}});
  552. return;
  553. }
  554. QString userid = token.claim("userId");
  555. bool isok = false;
  556. qint64 id = userid.toLongLong(&isok, 10);
  557. if (id == 0) {
  558. response.write(
  559. QJsonObject{{"status", true},
  560. {"message", TeacherServer::Tr::tr("Update Answer Time successfully")},
  561. {"code", 200},
  562. {"data", QJsonValue()}});
  563. return;
  564. }
  565. QJsonParseError error;
  566. QJsonDocument jdc = QJsonDocument::fromJson(request.getBody(), &error);
  567. QJsonObject jsonObject = jdc.object();
  568. qint64 time = 0;
  569. if (jsonObject.contains("answerTime")) {
  570. time = jsonObject["answerTime"].toVariant().toLongLong();
  571. }
  572. UserModel user(storage);
  573. CWF::SqlQueryManager queryManager(storage);
  574. queryManager.select("*", user.getTableName()).where("id=?");
  575. queryManager.prepare();
  576. queryManager.addBindValue(id);
  577. queryManager.exec();
  578. QJsonArray jsonArray = queryManager.toJson();
  579. if (jsonArray.isEmpty()) {
  580. response.write(QJsonObject{{"status", false},
  581. {"message", TeacherServer::Tr::tr("user does not exist")},
  582. {"code", 500},
  583. {"data", QJsonValue()}});
  584. return;
  585. }
  586. for (const QJsonValue &json : jsonArray) {
  587. if (json.isObject()) {
  588. QJsonObject obj = json.toObject();
  589. // 修改登录状态
  590. obj["answerTime"] = time;
  591. // 更新在线状态
  592. user.buildFromJson(obj);
  593. user.save();
  594. AppEvent::instance()->loginOutUser(obj["id"].toInt());
  595. {
  596. int examID = 0;
  597. QString sql = QString(R"__(
  598. SELECT eq.id
  599. FROM user u
  600. JOIN exams_question eq
  601. ON (
  602. (u.examTest IS NULL OR u.examTest = '') AND eq.isSelect = 1
  603. OR (u.examTest IS NOT NULL AND u.examTest <> '' AND eq.name = u.examTest)
  604. )
  605. WHERE u.id = %1;
  606. )__")
  607. .arg(id);
  608. CWF::SqlQuery query(storage);
  609. QJsonObject status = query.exec(sql);
  610. if (status["success"].toBool()) {
  611. const QJsonArray array = query.toJson();
  612. if (!array.isEmpty()) {
  613. QJsonObject object = array[0].toObject();
  614. examID = object["id"].toInt();
  615. }
  616. }
  617. const QString examNumber = AppEvent::instance()->examNumber();
  618. const QString examRoom = AppEvent::instance()->examRoom();
  619. QString fileName = user.getAnswerFileName();
  620. if (fileName.isEmpty()) {
  621. fileName = QString("%1_%2.zip").arg(user.getName()).arg(user.getExamineeNumber());
  622. }
  623. ExamsTestModel examsTestModel(storage);
  624. examsTestModel.setUserId(id);
  625. examsTestModel.setExamsId(examID);
  626. examsTestModel.setEndTime(time);
  627. examsTestModel.setExamRoom(examRoom);
  628. examsTestModel.setExamSessions(examNumber);
  629. examsTestModel.setAnswerFileName(fileName);
  630. examsTestModel.save();
  631. qDebug() << " AppEvent::instance()->examsTestUpdate();";
  632. AppEvent::instance()->examsTestUpdate();
  633. }
  634. response.write(
  635. QJsonObject{{"status", true},
  636. {"message", TeacherServer::Tr::tr("Update Answer Time successfully")},
  637. {"code", 200},
  638. {"data", QJsonValue()}});
  639. return;
  640. }
  641. }
  642. response.write(QJsonObject{{"status", false},
  643. {"message", TeacherServer::Tr::tr("Update Answer Time Failed")},
  644. {"code", 500},
  645. {"data", QJsonValue()}});
  646. }
  647. void TableDataController::doPost(CWF::Request &request, CWF::Response &response) const
  648. {
  649. QJsonParseError error;
  650. QJsonDocument jdc = QJsonDocument::fromJson(request.getBody(), &error);
  651. if (error.error != QJsonParseError::NoError) {
  652. response.write(QJsonObject{{"status", false},
  653. {"message", TeacherServer::Tr::tr("json param error")},
  654. {"code", 500},
  655. {"data", error.errorString()}});
  656. return;
  657. }
  658. QJsonObject jsonObject = jdc.object();
  659. int pageNum = jsonObject.value("pageNum").toInt(1);
  660. int pageSize = jsonObject.value("pageSize").toInt(20);
  661. QString examNumber = jsonObject.value("examNumber").toString("");
  662. QString examRoom = jsonObject.value("examRoom").toString("");
  663. int offset = (pageNum - 1) * pageSize;
  664. QStringList wheleList;
  665. if (!examNumber.isEmpty()) {
  666. wheleList += QString("e.exam_sessions='%1'").arg(examNumber);
  667. }
  668. if (!examRoom.isEmpty()) {
  669. wheleList += QString("e.exam_room='%1'").arg(examRoom);
  670. }
  671. QString whele;
  672. if (!wheleList.isEmpty()) {
  673. whele += "WHERE ";
  674. whele += wheleList.join(" AND ");
  675. }
  676. QString sql = QString(R"__(
  677. SELECT
  678. s.name,
  679. s.swID,
  680. s.examineeNumber,
  681. s.checkinNumber,
  682. s.groupName,
  683. s.answerFileName,
  684. s.school,
  685. e.end_time AS exam_time,
  686. e.exam_room,
  687. e.exam_sessions,
  688. eq.name AS examName
  689. FROM
  690. user s
  691. JOIN
  692. exams_test e ON s.id = e.user_id
  693. JOIN
  694. exams_question eq ON e.exams_id = eq.id
  695. %1
  696. ORDER BY
  697. e.end_time ASC
  698. LIMIT %2, %3;
  699. )__")
  700. .arg(whele)
  701. .arg(offset)
  702. .arg(pageSize);
  703. CWF::SqlQuery query(storage);
  704. QJsonObject status = query.exec(sql);
  705. if (status["success"].toBool()) {
  706. const QJsonArray array = query.toJson();
  707. response.write(QJsonObject{{"status", true},
  708. {"message", TeacherServer::Tr::tr("Table data ")},
  709. {"code", 200},
  710. {"data", array}});
  711. return;
  712. }
  713. qDebug().noquote().nospace() << status << sql;
  714. response.write(QJsonObject{{"status", false},
  715. {"message", TeacherServer::Tr::tr("Get Table Data Failed")},
  716. {"code", 500},
  717. {"data", QJsonValue()}});
  718. }
  719. void TableDataExamRoomController::doGet(CWF::Request &, CWF::Response &response) const
  720. {
  721. const QString examNumber = AppEvent::instance()->examNumber();
  722. const QString examRoom = AppEvent::instance()->examRoom();
  723. QJsonObject object;
  724. object.insert("examNumber", examNumber);
  725. object.insert("examRoom", examRoom);
  726. response.write(QJsonObject{{"status", true},
  727. {"message", "Get Table Data ok"},
  728. {"code", 200},
  729. {"data", object}});
  730. }