users.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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/topic.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. let redisSession = [
  196. "id", session.id,
  197. "name", session.name,
  198. "type", session.type,
  199. "last_sender_id", session.last_sender_id == null ? "" : session.last_sender_id,
  200. "last_sender_name", session.last_sender_name == null ? "" : session.last_sender_name,
  201. "last_content_type", session.last_content_type == null ? "" : session.last_content_type,
  202. "last_content", session.last_content == null ? "" : session.last_content,
  203. "last_message_time", session.last_message_time == null ? "" : session.last_message_time,
  204. "createDate", ObjectUtil.timestampToLong(session.create_date),
  205. ];
  206. (function (sessionId, userId) {
  207. // cache sessions
  208. redisConn.multi()
  209. .zadd(REDIS_KEYS.Sessions, lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  210. .zadd(RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId), lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  211. .hmset(RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId), redisSession)
  212. .execAsync()
  213. .then(function (res) {
  214. // cache participants
  215. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  216. let sessionParticipantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  217. ParticipantRepo.findParticipants(sessionId, function (err, participants) {
  218. if (err) {
  219. ModelUtil.emitError(self.eventEmitter, err.message);
  220. return;
  221. }
  222. participants.forEach(function (participant) {
  223. let participantId = participant.participant_id;
  224. let participantRole = participant.participant_role;
  225. let score = ObjectUtil.timestampToLong(participant.last_fetch_time);
  226. redisConn.multi()
  227. .zadd(sessionParticipantsKey, score, participantId)
  228. .hset(sessionParticipantsRoleKey, participantRole, participantId)
  229. .execAsync().then(function (res) {
  230. });
  231. });
  232. });
  233. // cache messages
  234. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  235. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  236. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, function (err, messages) {
  237. if (err) {
  238. ModelUtil.emitError(self.eventEmitter, err.message);
  239. return;
  240. }
  241. messages.forEach(function (message) {
  242. let msgJson = {
  243. id: message.id,
  244. sender_id: message.sender_id,
  245. sender_name: message.sender_name,
  246. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  247. content_type: message.content_type,
  248. content: message.content
  249. };
  250. redisConn.multi()
  251. .hset(messagesKey, message.id, JSON.stringify(msgJson))
  252. .zadd(messagesByTimestampKey, ObjectUtil.timestampToLong(message.timestamp), message.id)
  253. .execAsync()
  254. .then(function (res) {
  255. });
  256. });
  257. });
  258. // cache topics for MUC
  259. let topicsKey = RedisModel.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  260. TopicRepo.findAll(sessionId, function (err, topics) {
  261. if (err) {
  262. ModelUtil.emitError(self.eventEmitter, err.message);
  263. return;
  264. }
  265. topics.forEach(function (topic) {
  266. let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  267. let topicId = topic.id;
  268. let name = topic.name;
  269. let createTime = ObjectUtil.timestampToLong(topic.create_time);
  270. let endBy = topic.end_by;
  271. let endTime = ObjectUtil.timestampToLong(topic.end_time);
  272. let startMessageId = topic.start_message_id;
  273. let endMessageId = topic.end_message_id;
  274. redisConn.multi()
  275. .zadd(topicsKey, topicId)
  276. .hmset(topicKey, 'name', name, 'session_id', sessionId, 'create_time',
  277. createTime, 'end_by', endBy, 'end_time', endTime, 'start_message_id',
  278. startMessageId, 'end_message_id', endMessageId)
  279. .execAsync().then(function (res) {
  280. });
  281. });
  282. });
  283. });
  284. })(session.id, userId);
  285. });
  286. });
  287. callback(null, null);
  288. }
  289. ],
  290. function (err, res) {
  291. ModelUtil.emitOK(self.eventEmitter, {});
  292. });
  293. }
  294. logout(userId) {
  295. let self = this;
  296. async.waterfall([
  297. function (callback) {
  298. self.isPatientId(userId, function (err, isPatient) {
  299. callback(null, isPatient)
  300. });
  301. },
  302. function (isPatient, callback) {
  303. let usersKey = REDIS_KEYS.Users;
  304. let userStatusKey = RedisModel.makeRedisKey(isPatient ? REDIS_KEYS.UserWechatStatus : REDIS_KEYS.UserAppStatus, userId);
  305. redisConn.multi()
  306. .zrem(usersKey, userId)
  307. .del(userStatusKey)
  308. .execAsync()
  309. .then(function (res) {
  310. if (res.length > 0 && res[0] === 0) {
  311. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "User not found."});
  312. } else {
  313. ModelUtil.emitOK(self.eventEmitter, {});
  314. }
  315. });
  316. }],
  317. function (err, res) {
  318. }
  319. );
  320. }
  321. /**
  322. * 用户ID是否属于患者。
  323. *
  324. * @param userId
  325. * @param callback
  326. */
  327. isPatientId(userId, callback) {
  328. async.waterfall([
  329. function (callback) {
  330. var sql = "select case when count(*) > 0 then true else false end 'is_patient' from patients where id = ?";
  331. ImDb.execQuery({
  332. "sql": sql,
  333. "args": [userId],
  334. "handler": function (err, res) {
  335. if (err) callback(err, res);
  336. callback(null, res);
  337. }
  338. });
  339. },
  340. function (res, callback) {
  341. if (res.length === 0) return false;
  342. callback(null, res[0].is_patient);
  343. }
  344. ],
  345. function (err, res) {
  346. if (err) {
  347. log.error("User id check failed: ", err);
  348. callback(null, false);
  349. return;
  350. }
  351. callback(null, res !== 0);
  352. });
  353. }
  354. }
  355. let Promises = require('bluebird');
  356. Promises.promisifyAll(Users.prototype);
  357. module.exports = Users;