users.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /**
  2. * 用户集合。管理Redis中的用户列表。
  3. *
  4. * author: Sand
  5. * since: 12/13/2016
  6. */
  7. "use strict";
  8. let RedisModel = require('../redis.model');
  9. let Doctor = require('./doctor');
  10. let Patient = require('./patient');
  11. let ImDb = require('../../repository/mysql/db/im.db');
  12. let ParticipantRepo = require('../../repository/mysql/participant.repo');
  13. let DoctorRepo = require('../../repository/mysql/doctor.repo');
  14. let PatientRepo = require('../../repository/mysql/patient.repo');
  15. let AppStatusRepo = require('../../repository/mysql/app.status.repo');
  16. let SessionRepo = require('../../repository/mysql/session.repo');
  17. let TopicRepo = require('../../repository/mysql/topics.repo');
  18. let MessageRepo = require('../../repository/mysql/message.repo');
  19. let ModelUtil = require('../../util/model.util');
  20. let ObjectUtil = require("../../util/object.util.js");
  21. let RedisClient = require('../../repository/redis/redis.client');
  22. let redisConn = RedisClient.redisClient().connection;
  23. let async = require('async');
  24. let log = require('../../util/log');
  25. let configFile = require('../../include/commons').CONFIG_FILE;
  26. let config = require('../../resources/config/' + configFile);
  27. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  28. const PLATFORMS = require('../../include/commons').PLATFORM;
  29. class Users extends RedisModel {
  30. constructor() {
  31. super();
  32. }
  33. /**
  34. * 获取用户,直接从MYSQL获取,缓存是否有在不能确定。
  35. *
  36. * @param userId
  37. * @param outCallback
  38. */
  39. getUserFromMySQL(userId, outCallback) {
  40. let self = this;
  41. async.waterfall([
  42. // determine user type
  43. function (callback) {
  44. self.isPatientId(userId, function (err, isPatient) {
  45. callback(null, isPatient);
  46. });
  47. },
  48. // get from mysql
  49. function (isPatientId) {
  50. let repoProto = isPatientId ? PatientRepo : DoctorRepo;
  51. repoProto.findOne(userId, function (err, res) {
  52. let user = isPatientId ? new Doctor() : new Patient();
  53. if (res.length > 0) {
  54. user.name = res[0].name;
  55. user.sex = res[0].sex;
  56. user.birthdate = res[0].birthdate;
  57. user.avatar = res[0].avatar;
  58. }
  59. outCallback(null, user);
  60. });
  61. }
  62. ]);
  63. }
  64. /**
  65. * 取得用户微信端状态。
  66. *
  67. * @param userId
  68. * @param outCallback
  69. */
  70. getWechatStatus(userId) {
  71. let self = this;
  72. redisConn.hgetallAsync(RedisModel.makeRedisKey(REDIS_KEYS.UserWechatStatus, userId))
  73. .then(function (res) {
  74. if (res) {
  75. ModelUtil.emitOK(self, res);
  76. } else {
  77. ModelUtil.emitDataNotFound(self, {"message": "User is offline, unable to get wechat status."});
  78. }
  79. });
  80. }
  81. /**
  82. * 获取客户端App状态。
  83. *
  84. * @param userId
  85. * @param outCallback
  86. */
  87. getAppStatus(userId, outCallback) {
  88. let self = this;
  89. async.waterfall([
  90. // get from redis
  91. function (callback) {
  92. let userStatusKey = RedisModel.makeRedisKey(REDIS_KEYS.UserStatus, userId);
  93. redisConn.hgetallAsync(userStatusKey).then(function (res) {
  94. if (res === null) {
  95. callback(null); // get from mysql
  96. } else {
  97. outCallback(null, res);
  98. }
  99. });
  100. },
  101. // get from MySQL
  102. function () {
  103. AppStatusRepo.findOne(userId, function (err, res) {
  104. let userStatus = null;
  105. if (res.length > 0) {
  106. userStatus = {};
  107. userStatus.platform = res[0].platform;
  108. userStatus.token = res[0].token;
  109. userStatus.client_id = res[0].client_id;
  110. userStatus.app_in_bg = res[0].app_in_bg;
  111. userStatus.last_login_time = res[0].last_login_time;
  112. }
  113. outCallback(null, userStatus);
  114. });
  115. }
  116. ]);
  117. }
  118. /**
  119. * 更新客户端App状态。
  120. *
  121. * @param userId
  122. * @param appInBg
  123. */
  124. updateAppStatus(userId, appInBg) {
  125. let self = this;
  126. let userStatusKey = RedisModel.makeRedisKey(REDIS_KEYS.UserAppStatus, userId);
  127. redisConn.hgetAsync(userStatusKey, 'app_in_bg').then(function (res) {
  128. if (res !== null) {
  129. redisConn.hsetAsync(userStatusKey, 'app_in_bg', appInBg).then(function (res) {
  130. ModelUtil.emitOK(self.eventEmitter, {});
  131. });
  132. } else {
  133. ModelUtil.emitDataNotFound(self.eventEmitter, {"message": "User is offline, unable to update app status."});
  134. }
  135. });
  136. }
  137. /**
  138. * 用户登录,仅缓存用户客户端状态信息,不缓存用户基本信息。
  139. *
  140. * 用户登录时会加载与之相关的会话列表,会话消息,用户自身信息:App状态与微信状态。
  141. *
  142. * TODO: 如果用户已经登录,但因为异常退出重新登录,是否需要刷新状态信息。
  143. *
  144. * @param userId
  145. * @param platform
  146. * @param token
  147. * @param clientId
  148. *
  149. * @return 用户token
  150. */
  151. login(userId, platform, token, clientId) {
  152. let self = this;
  153. let loginFromApp = platform !== PLATFORMS.Wechat;
  154. let usersKey = REDIS_KEYS.Users;
  155. let userKey = RedisModel.makeRedisKey(REDIS_KEYS.User, userId);
  156. let userStatusKey = RedisModel.makeRedisKey(loginFromApp ? REDIS_KEYS.UserAppStatus : REDIS_KEYS.UserWechatStatus, userId);
  157. let lastLoginTime = new Date();
  158. async.waterfall([
  159. // get user info from mysql
  160. function (callback) {
  161. self.getUserFromMySQL(userId, function (err, userInfo) {
  162. if (userInfo === null) {
  163. ModelUtil.emitDataNotFound(self, 'User not exists.');
  164. return;
  165. }
  166. callback(null, userInfo);
  167. })
  168. },
  169. // cache user app/wechat status
  170. function (userInfo, callback) {
  171. let multi = redisConn.multi()
  172. .zadd(usersKey, lastLoginTime.getTime(), userId);
  173. //.hmset(userKey, 'avatar', userInfo.avatar ? userInfo.avatar : '', 'birthdate', userInfo.birthdate ? userInfo.birthdate : '',
  174. // 'name', userInfo.name, 'role', loginFromApp ? 'doctor' : 'patient');
  175. if (loginFromApp) {
  176. // cache app status
  177. multi = multi.hmset(userStatusKey, 'platform', platform, 'app_in_bg', false, 'client_id', clientId,
  178. 'token', token, 'last_login_time', lastLoginTime.getTime());
  179. } else {
  180. // cache wechat status
  181. multi = multi.hmset(userKey, 'open_id', userInfo.open_id, 'last_login_time', lastLoginTime.getTime());
  182. }
  183. multi.execAsync().then(function (res) {
  184. callback(null);
  185. });
  186. },
  187. // cache sessions, participants, topics, messages
  188. function (callback) {
  189. SessionRepo.findAll(userId, function (err, sessions) {
  190. if (err) {
  191. ModelUtil.emitError(self.eventEmitter, err.message);
  192. return;
  193. }
  194. sessions.forEach(function (session) {
  195. redisConn.zscore(REDIS_KEYS.Sessions, session.id, function (err, res) {
  196. // 已经缓存过的会话不再缓存
  197. if(res != null) return;
  198. (function (sessionId, userId) {
  199. let redisSession = [
  200. "id", session.id,
  201. "name", session.name,
  202. "type", session.type,
  203. "last_sender_id", session.last_sender_id == null ? "" : session.last_sender_id,
  204. "last_sender_name", session.last_sender_name == null ? "" : session.last_sender_name,
  205. "last_content_type", session.last_content_type == null ? "" : session.last_content_type,
  206. "last_content", session.last_content == null ? "" : session.last_content,
  207. "last_message_time", session.last_message_time == null ? "" : session.last_message_time,
  208. "create_date", ObjectUtil.timestampToLong(session.create_date),
  209. ];
  210. // cache sessions
  211. redisConn.multi()
  212. .zadd(REDIS_KEYS.Sessions, lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  213. .zadd(RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId), lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  214. .hmset(RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId), redisSession)
  215. .execAsync()
  216. .then(function (res) {
  217. // cache participants
  218. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  219. let sessionParticipantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  220. ParticipantRepo.findParticipants(sessionId, function (err, participants) {
  221. if (err) {
  222. ModelUtil.emitError(self.eventEmitter, err.message);
  223. return;
  224. }
  225. let multi = redisConn.multi();
  226. participants.forEach(function (participant) {
  227. let participantId = participant.participant_id;
  228. let participantRole = participant.participant_role;
  229. let score = ObjectUtil.timestampToLong(participant.last_fetch_time);
  230. multi = multi.zadd(sessionParticipantsKey, score, participantId)
  231. .hset(sessionParticipantsRoleKey, participantId, participantRole);
  232. });
  233. multi.execAsync().then(function (res) {
  234. });
  235. });
  236. // cache messages
  237. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  238. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  239. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount,null, function (err, messages) {
  240. if (err) {
  241. ModelUtil.emitError(self.eventEmitter, err.message);
  242. return;
  243. }
  244. let multi = redisConn.multi();
  245. messages.forEach(function (message) {
  246. let msgJson = {
  247. id: message.id,
  248. sender_id: message.sender_id,
  249. sender_name: message.sender_name,
  250. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  251. content_type: message.content_type,
  252. content: message.content
  253. };
  254. multi = multi.hset(messagesKey, message.id, JSON.stringify(msgJson))
  255. .zadd(messagesByTimestampKey, ObjectUtil.timestampToLong(message.timestamp), message.id);
  256. });
  257. multi.execAsync().then(function (res) {
  258. });
  259. });
  260. // cache topics for MUC
  261. let topicsKey = RedisModel.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  262. TopicRepo.findAllBySessionId(sessionId, function (err, topics) {
  263. if (err) {
  264. ModelUtil.emitError(self.eventEmitter, err.message);
  265. return;
  266. }
  267. topics.forEach(function (topic) {
  268. let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  269. let topicId = topic.id;
  270. let name = topic.name == null ? "" : topic.name;
  271. let createTime = ObjectUtil.timestampToLong(topic.create_time);
  272. let endBy = topic.end_by == null ? "" : topic.end_by;
  273. let endTime = topic.end_time == null ? 0 : ObjectUtil.timestampToLong(topic.end_time);
  274. let startMessageId = topic.start_message_id == null ? "" : topic.start_message_id;
  275. let endMessageId = topic.end_message_id == null ? "" : topic.end_message_id;
  276. let description = topic.description == null ? "" : topic.description;
  277. let status = topic.status == null ? 0 : topic.status;
  278. redisConn.multi()
  279. .zadd(topicsKey, topicId)
  280. .hmset(topicKey,
  281. 'name', name,
  282. 'session_id', sessionId,
  283. 'create_time', createTime,
  284. 'end_by', endBy,
  285. 'end_time', endTime,
  286. 'start_message_id', startMessageId,
  287. 'end_message_id', endMessageId,
  288. 'description', description,
  289. 'status', status)
  290. .execAsync().then(function (res) {
  291. });
  292. });
  293. });
  294. });
  295. })(session.id, userId);
  296. });
  297. });
  298. });
  299. callback(null, null);
  300. }
  301. ],
  302. function (err, res) {
  303. ModelUtil.emitOK(self.eventEmitter, {});
  304. });
  305. }
  306. logout(userId) {
  307. let self = this;
  308. async.waterfall([
  309. function (callback) {
  310. self.isPatientId(userId, function (err, isPatient) {
  311. callback(null, isPatient)
  312. });
  313. },
  314. function (isPatient, callback) {
  315. let usersKey = REDIS_KEYS.Users;
  316. let userStatusKey = RedisModel.makeRedisKey(isPatient ? REDIS_KEYS.UserWechatStatus : REDIS_KEYS.UserAppStatus, userId);
  317. redisConn.multi()
  318. .zrem(usersKey, userId)
  319. .del(userStatusKey)
  320. .execAsync()
  321. .then(function (res) {
  322. if (res.length > 0 && res[0] === 0) {
  323. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "User not found."});
  324. } else {
  325. ModelUtil.emitOK(self.eventEmitter, {});
  326. }
  327. });
  328. }],
  329. function (err, res) {
  330. }
  331. );
  332. }
  333. /**
  334. * 用户ID是否属于患者。
  335. *
  336. * @param userId
  337. * @param callback
  338. */
  339. isPatientId(userId, callback) {
  340. async.waterfall([
  341. function (callback) {
  342. var sql = "select case when count(*) > 0 then true else false end 'is_patient' from patients where id = ?";
  343. ImDb.execQuery({
  344. "sql": sql,
  345. "args": [userId],
  346. "handler": function (err, res) {
  347. if (err) callback(err, res);
  348. callback(null, res);
  349. }
  350. });
  351. },
  352. function (res, callback) {
  353. if (res.length === 0) return false;
  354. callback(null, res[0].is_patient);
  355. }
  356. ],
  357. function (err, res) {
  358. if (err) {
  359. log.error("User id check failed: ", err);
  360. callback(null, false);
  361. return;
  362. }
  363. callback(null, res !== 0);
  364. });
  365. }
  366. }
  367. let Promises = require('bluebird');
  368. Promises.promisifyAll(Users.prototype);
  369. module.exports = Users;