users.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. /**
  2. * 用户集合。管理Redis中的用户列表。
  3. *
  4. * author: Sand
  5. * since: 12/13/2016
  6. */
  7. "use strict";
  8. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  9. const PLATFORMS = require('../../include/commons').PLATFORM;
  10. let RedisModel = require('../redis.model');
  11. let Doctor = require('./doctor');
  12. let Patient = require('./patient');
  13. let ImDb = require('../../repository/mysql/db/im.db');
  14. let ParticipantRepo = require('../../repository/mysql/participant.repo');
  15. let DoctorRepo = require('../../repository/mysql/doctor.repo');
  16. let PatientRepo = require('../../repository/mysql/patient.repo');
  17. let AppStatusRepo = require('../../repository/mysql/app.status.repo');
  18. let SessionRepo = require('../../repository/mysql/session.repo');
  19. let TopicRepo = require('../../repository/mysql/topic.repo');
  20. let MessageRepo = require('../../repository/mysql/message.repo');
  21. let ModelUtil = require('../../util/model.util');
  22. let RedisClient = require('../../repository/redis/redis.client');
  23. let redisConn = RedisClient.redisClient().connection;
  24. let async = require('async');
  25. let log = require('../../util/log');
  26. let configFile = require('../../include/commons').CONFIG_FILE;
  27. let config = require('../../resources/config/' + configFile);
  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.UserWechatStatus : 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.multiAsync()
  168. .zadd(usersKey, lastLoginTime.getMilliseconds(), userId)
  169. .hmset(userKey, 'avatar', userInfo.avatar, '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 i = 0; i < sessions.length; ++i) {
  187. let sessionId = sessions[i].id;
  188. let name = sessions[i].name;
  189. let type = sessions[i].type;
  190. let createDate = sessions[i].create_date;
  191. (function (sessionId, userId) {
  192. // cache sessions
  193. redisConn.multiAsync()
  194. .zadd(self.makeRedisKey(REDIS_KEYS.UserSessions, userId))
  195. .hmset(self.makeRedisKey(REDIS_KEYS.Session, sessionId, 'name', name, 'type', type, 'create_date', createDate))
  196. .execAsync().then(function (res) {
  197. // cache participants
  198. let sessionParticipantsKey = self.makeRedisKey(REDIS_KEYS.Participants, sessionId);
  199. let sessionParticipantsRoleKey = self.makeRedisKey(REDIS_KEYS.ParticipantsRole, sessionId);
  200. ParticipantRepo.findParticipants(sessionId, function (err, participants) {
  201. for (let participant in participants) {
  202. let participantId = participant.participant_id;
  203. let participantRole = participant.participant_role;
  204. let score = new Date().getMilliseconds();
  205. redisConn.multiAsync()
  206. .zaddAsync(sessionParticipantsKey, participantId, score)
  207. .hsetAsync(sessionParticipantsRoleKey, participantId, participantRole)
  208. .execAsync().then(function (res) {
  209. });
  210. }
  211. });
  212. // cache messages
  213. let messagesKey = self.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  214. let messagesByTimestampKey = self.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  215. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, function (err, messages) {
  216. for (let message in messages) {
  217. let id = message.id;
  218. let msgJson = {
  219. sessionId: message.session_id,
  220. senderId: message.sender_id,
  221. senderName: message.sender_name,
  222. contentType: message.content_type,
  223. content: message.content,
  224. timestamp: message.timestamp
  225. };
  226. redisConn.multiAsync()
  227. .hset(messagesKey, id, msgJson)
  228. .zadd(messagesByTimestampKey, id)
  229. .execAsync()
  230. .then(function (res) {
  231. });
  232. }
  233. });
  234. // cache topics for MUC session
  235. let topicsKey = self.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  236. TopicRepo.findAll(sessionId, function (err, topics) {
  237. for (let topic in topics) {
  238. let topicKey = self.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  239. let topicId = topic.id;
  240. let name = topic.name;
  241. let createTime = topic.create_time;
  242. let endBy = topic.end_by;
  243. let startMesssageId = topic.start_message_id;
  244. let endMessageId = topic.end_message_id;
  245. redisConn.multiAsync()
  246. .zadd(topicsKey, topicId)
  247. .hmset(topicKey, 'name', name, 'session_id', sessionId, 'create_time',
  248. createTime, 'end_by', endBy, 'start_message_id',
  249. startMesssageId, 'end_message_id', endMessageId)
  250. .execAsync().then(function (res) {
  251. });
  252. }
  253. });
  254. });
  255. })(sessionId, userId);
  256. }
  257. });
  258. ModelUtil.emitData(self.eventEmitter, {});
  259. }
  260. ]);
  261. }
  262. logout(userId) {
  263. let self = this;
  264. async.waterfall([
  265. function (callback) {
  266. self.isPatientId(userId, function (err, isPatient) {
  267. callback(null, isPatient)
  268. });
  269. },
  270. function (callback, isPatient) {
  271. let usersKey = REDIS_KEYS.Users;
  272. let userKey = self.makeRedisKey(REDIS_KEYS.User, userId);
  273. let userStatusKey = self.makeRedisKey(isPatient ? REDIS_KEYS.UserWechatStatus : REDIS_KEYS.UserAppStatus, userId);
  274. redisConn.multiAsync()
  275. .del(usersKey)
  276. .del(userKey)
  277. .del(userStatusKey)
  278. .execAsync().then(function (res) {
  279. })
  280. }],
  281. function (err, res) {
  282. ModelUtil.emitData(self.eventEmitter, {});
  283. }
  284. );
  285. }
  286. /**
  287. * 用户ID是否属于患者。
  288. *
  289. * @param userId
  290. * @param callback
  291. */
  292. isPatientId(userId, callback) {
  293. async.waterfall([
  294. function (callback) {
  295. var sql = "select case when count(*) > 0 then true else false end 'is_patient' from patients where id = ?";
  296. ImDb.execQuery({
  297. "sql": sql,
  298. "args": [userId],
  299. "handler": function (err, res) {
  300. if (err) callback(err, res);
  301. callback(null, res);
  302. }
  303. });
  304. },
  305. function (res, callback) {
  306. if (res.length === 0) return false;
  307. callback(null, res[0].is_patient);
  308. }
  309. ],
  310. function (err, res) {
  311. if (err) {
  312. log.error("User id check failed: ", err);
  313. callback(null, false);
  314. return;
  315. }
  316. callback(null, res !== 0);
  317. });
  318. }
  319. }
  320. let Promises = require('bluebird');
  321. Promises.promisifyAll(Users.prototype);
  322. module.exports = Users;