users.js 19 KB

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