tcontroller.cpp 38 KB

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