tcontroller.cpp 30 KB

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