users.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 RedisClient = require('../../repository/redis/redis.client');
  21. let redisConn = RedisClient.redisClient().connection;
  22. let async = require('async');
  23. let log = require('../../util/log');
  24. let configFile = require('../../include/commons').CONFIG_FILE;
  25. let config = require('../../resources/config/' + configFile);
  26. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  27. const PLATFORMS = require('../../include/commons').PLATFORM;
  28. class Users extends RedisModel {
  29. constructor() {
  30. super();
  31. this._key = REDIS_KEYS.Users;
  32. }
  33. /**
  34. * 获取用户,直接从MYSQL获取,缓存是否有在不能确定。
  35. *
  36. * @param userId
  37. * @param outCallback
  38. */
  39. getUser(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(self.makeRedisKey(REDIS_KEYS.UserWechatStatus, userId))
  73. .then(function (res) {
  74. if (res) {
  75. ModelUtil.emitData(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 = self.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. redisConn.hsetAsync(self.makeRedisKey(REDIS_KEYS.UserAppStatus, userId), 'app_in_bg', appInBg)
  127. .then(function (res) {
  128. if (res) {
  129. ModelUtil.emitData(self.eventEmitter, {});
  130. } else {
  131. ModelUtil.emitDataNotFound(self.eventEmitter, {"message": "User is offline, unable to update app status."});
  132. }
  133. });
  134. }
  135. /**
  136. * 用户登录。
  137. *
  138. * 用户登录时会加载与之相关的会话列表,会话消息,用户自身信息:App状态与微信状态。
  139. *
  140. * @param userId
  141. * @param platform
  142. * @param token
  143. * @param clientId
  144. *
  145. * @return 用户token
  146. */
  147. login(userId, platform, token, clientId) {
  148. let self = this;
  149. let loginFromApp = platform !== PLATFORMS.Wechat;
  150. let usersKey = REDIS_KEYS.Users;
  151. let userKey = self.makeRedisKey(REDIS_KEYS.User, userId);
  152. let userStatusKey = self.makeRedisKey(loginFromApp ? REDIS_KEYS.UserAppStatus : REDIS_KEYS.UserWechatStatus, userId);
  153. let lastLoginTime = new Date();
  154. async.waterfall([
  155. // get user info from mysql
  156. function (callback) {
  157. self.getUser(userId, function (err, userInfo) {
  158. if (userInfo === null) {
  159. ModelUtil.emitDataNotFound(self, 'User not exists.');
  160. return;
  161. }
  162. callback(null, userInfo);
  163. })
  164. },
  165. // cache user info and app/wechat status
  166. function (userInfo, callback) {
  167. let multi = redisConn.multi()
  168. .zadd(usersKey, lastLoginTime.getMilliseconds(), userId)
  169. .hmset(userKey, 'avatar', userInfo.avatar ? userInfo.avatar : '', 'birthdate', userInfo.birthdate? userInfo.birthdate : '',
  170. 'name', userInfo.name, 'role', loginFromApp ? 'doctor' : 'patient');
  171. if (loginFromApp) {
  172. // cache app status
  173. multi = multi.hmset(userStatusKey, 'platform', platform, 'app_in_bg', false, 'client_id', clientId,
  174. 'token', token, 'last_login_time', lastLoginTime);
  175. } else {
  176. // cache wechat status
  177. multi = multi.hmset(userKey, 'open_id', userInfo.open_id);
  178. }
  179. multi.execAsync().then(function (res) {
  180. callback(null);
  181. });
  182. },
  183. // cache sessions, participants, topics, messages
  184. function (callback) {
  185. SessionRepo.findAll(userId, function (err, sessions) {
  186. for (let session in sessions) {
  187. let sessionId = session.id;
  188. let name = session.name;
  189. let type = session.type;
  190. let createDate = session.create_date;
  191. (function (sessionId, userId) {
  192. // cache sessions
  193. redisConn.multi()
  194. .zadd(self.makeRedisKey(REDIS_KEYS.Sessions), lastLoginTime) // 会话的最后活动时间设置为此用户的登录时间
  195. .zadd(self.makeRedisKey(REDIS_KEYS.UserSessions, userId), lastLoginTime) // 会话的最后活动时间设置为此用户的登录时间
  196. .hmset(self.makeRedisKey(REDIS_KEYS.Session, sessionId, 'name', name, 'type', type, 'create_date', createDate))
  197. .execAsync().then(function (res) {
  198. // cache participants
  199. let sessionParticipantsKey = self.makeRedisKey(REDIS_KEYS.Participants, sessionId);
  200. let sessionParticipantsRoleKey = self.makeRedisKey(REDIS_KEYS.ParticipantsRole, sessionId);
  201. ParticipantRepo.findParticipants(sessionId, function (err, participants) {
  202. for (let participant in participants) {
  203. let participantId = participant.participant_id;
  204. let participantRole = participant.participant_role;
  205. let score = new Date().getMilliseconds();
  206. redisConn.multi()
  207. .zadd(sessionParticipantsKey, participantId, score)
  208. .hset(sessionParticipantsRoleKey, participantId, participantRole)
  209. .execAsync().then(function (res) {
  210. });
  211. }
  212. });
  213. // cache messages
  214. let messagesKey = self.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  215. let messagesByTimestampKey = self.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  216. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, function (err, messages) {
  217. for (let message in messages) {
  218. let id = message.id;
  219. let msgJson = {
  220. sessionId: message.session_id,
  221. senderId: message.sender_id,
  222. senderName: message.sender_name,
  223. contentType: message.content_type,
  224. content: message.content,
  225. timestamp: message.timestamp
  226. };
  227. redisConn.multi()
  228. .hset(messagesKey, id, msgJson)
  229. .zadd(messagesByTimestampKey, id)
  230. .execAsync()
  231. .then(function (res) {
  232. });
  233. }
  234. });
  235. // cache topics for MUC
  236. let topicsKey = self.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  237. TopicRepo.findAll(sessionId, function (err, topics) {
  238. for (let topic in topics) {
  239. let topicKey = self.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  240. let topicId = topic.id;
  241. let name = topic.name;
  242. let createTime = topic.create_time;
  243. let endBy = topic.end_by;
  244. let endTime = topic.end_time;
  245. let startMessageId = topic.start_message_id;
  246. let endMessageId = topic.end_message_id;
  247. redisConn.multi()
  248. .zadd(topicsKey, topicId)
  249. .hmset(topicKey, 'name', name, 'session_id', sessionId, 'create_time',
  250. createTime, 'end_by', endBy, 'end_time', endTime, 'start_message_id',
  251. startMessageId, 'end_message_id', endMessageId)
  252. .execAsync().then(function (res) {
  253. });
  254. }
  255. });
  256. });
  257. })(sessionId, userId);
  258. }
  259. });
  260. ModelUtil.emitData(self.eventEmitter, {});
  261. }
  262. ]);
  263. }
  264. logout(userId) {
  265. let self = this;
  266. async.waterfall([
  267. function (callback) {
  268. self.isPatientId(userId, function (err, isPatient) {
  269. callback(null, isPatient)
  270. });
  271. },
  272. function (callback, isPatient) {
  273. let usersKey = REDIS_KEYS.Users;
  274. let userKey = self.makeRedisKey(REDIS_KEYS.User, userId);
  275. let userStatusKey = self.makeRedisKey(isPatient ? REDIS_KEYS.UserWechatStatus : REDIS_KEYS.UserAppStatus, userId);
  276. redisConn.multiAsync()
  277. .del(usersKey)
  278. .del(userKey)
  279. .del(userStatusKey)
  280. .execAsync().then(function (res) {
  281. })
  282. }],
  283. function (err, res) {
  284. ModelUtil.emitData(self.eventEmitter, {});
  285. }
  286. );
  287. }
  288. /**
  289. * 用户ID是否属于患者。
  290. *
  291. * @param userId
  292. * @param callback
  293. */
  294. isPatientId(userId, callback) {
  295. async.waterfall([
  296. function (callback) {
  297. var sql = "select case when count(*) > 0 then true else false end 'is_patient' from patients where id = ?";
  298. ImDb.execQuery({
  299. "sql": sql,
  300. "args": [userId],
  301. "handler": function (err, res) {
  302. if (err) callback(err, res);
  303. callback(null, res);
  304. }
  305. });
  306. },
  307. function (res, callback) {
  308. if (res.length === 0) return false;
  309. callback(null, res[0].is_patient);
  310. }
  311. ],
  312. function (err, res) {
  313. if (err) {
  314. log.error("User id check failed: ", err);
  315. callback(null, false);
  316. return;
  317. }
  318. callback(null, res !== 0);
  319. });
  320. }
  321. }
  322. let Promises = require('bluebird');
  323. Promises.promisifyAll(Users.prototype);
  324. module.exports = Users;