users.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. if(platform){
  83. platform = parseInt(platform);
  84. }
  85. let loginFromApp = (platform === PLATFORMS.Android)||(platform === PLATFORMS.iOS);
  86. let loginFromPc = platform === PLATFORMS.PC;
  87. log.error(userId+" "+ platform+" "+deviceToken+" "+clientId);
  88. let usersKey = REDIS_KEYS.Users;
  89. let userKey = RedisModel.makeRedisKey(REDIS_KEYS.User, userId);
  90. let userStatusKey = RedisModel.makeRedisKey(loginFromApp ? REDIS_KEYS.UserAppStatus : (loginFromPc?REDIS_KEYS.UserPcStatus:REDIS_KEYS.UserWechatStatus), userId);
  91. let lastLoginTime = new Date();
  92. async.waterfall([
  93. // get user info from mysql
  94. function (callback) {
  95. self.getUserFromMySQL(userId, function (err, userInfo) {
  96. if (!userInfo) {
  97. ModelUtil.emitDataNotFound(self, 'User not exists.');
  98. return;
  99. }
  100. callback(null, userInfo);
  101. })
  102. },
  103. // cache user and app/wechat status
  104. function (userInfo, callback) {
  105. let multi = redisConn.multi()
  106. .zadd(usersKey, lastLoginTime.getTime(), userId);
  107. /*.hmset(userKey,
  108. 'avatar', userInfo.avatar ? userInfo.avatar : '',
  109. 'birthdate', userInfo.birthdate ? ObjectUtil.timestampToLong(userInfo.birthdate) : '',
  110. 'name', userInfo.name,
  111. 'role', loginFromApp ? 'doctor' : 'patient');*/
  112. if (loginFromApp) {
  113. AppStatusRepo.save(userId, deviceToken, clientId, platform, function (err, res) {
  114. if (err) log.error(err);
  115. });
  116. // cache app status
  117. multi = multi.hmset(userStatusKey,
  118. 'app_in_bg', 0,
  119. 'client_id', clientId,
  120. 'device_token', deviceToken,
  121. 'last_login_time', lastLoginTime.getTime(),
  122. 'platform', platform);
  123. } else if(loginFromPc){
  124. // cache pc status
  125. multi = multi.hmset(userStatusKey,
  126. 'last_login_time', lastLoginTime.getTime(),
  127. 'platform', platform);
  128. }else {
  129. // cache wechat status
  130. multi = multi.hmset(userStatusKey,
  131. 'last_login_time', lastLoginTime.getTime(),
  132. 'openid', userInfo.openid,
  133. 'platform', platform);
  134. }
  135. multi.execAsync()
  136. .then(function (res) {
  137. callback(null);
  138. })
  139. .catch(function (ex) {
  140. log.error("Login failed while cache user status: ", ex);
  141. });
  142. },
  143. // cache sessions, participants, topics, messages
  144. function (callback) {
  145. SessionRepo.findAllIgnoreRole(userId, function (err, sessions) {
  146. if (err) {
  147. ModelUtil.emitError(self.eventEmitter, err.message);
  148. return;
  149. }
  150. sessions.forEach(function (session) {
  151. redisConn.zscore(REDIS_KEYS.Sessions, session.id, function (err, res) {
  152. if (res != null) return; // 已经缓存过的会话不再缓存
  153. // if(session.id =="915ce5ab-5b1d-11e6-8344-fa163e8aee56_828c1a62000d4838a0c8bab1acdfadff_8"){
  154. // log.error("1111");
  155. // }else if(res != null){
  156. // return;
  157. // }
  158. (function (sessionId, userId) {
  159. let redisSession = [
  160. "id", session.id,
  161. "name", session.name,
  162. "type", session.type,
  163. "business_type", session.business_type,
  164. "last_sender_id", session.last_sender_id||"",
  165. "last_sender_name", session.last_sender_name||"",
  166. "last_content_type", session.last_content_type||"",
  167. "last_content", session.last_content||"",
  168. "last_message_time", session.last_message_time||"",
  169. "create_date", ObjectUtil.timestampToLong(session.create_date),
  170. "status",session.status==null?0:session.status
  171. ];
  172. // cache sessions
  173. redisConn.multi()
  174. .zadd(REDIS_KEYS.Sessions, lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  175. .zadd(RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId), lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  176. .hmset(RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId), redisSession)
  177. .execAsync()
  178. .then(function (res) {
  179. // cache participants
  180. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  181. let sessionParticipantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  182. ParticipantRepo.findAll(sessionId, function (err, participants) {
  183. if (err) {
  184. ModelUtil.emitError(self.eventEmitter, err.message);
  185. return;
  186. }
  187. let multi = redisConn.multi();
  188. participants.forEach(function (participant) {
  189. let participantId = participant.id;
  190. let participantRole = participant.role;
  191. let score = ObjectUtil.timestampToLong(participant.last_fetch_time||(new Date()));
  192. multi = multi.zadd(sessionParticipantsKey, score, participantId)
  193. .hset(sessionParticipantsRoleKey, participantId, participantRole);
  194. });
  195. multi.execAsync()
  196. .then(function (res) {
  197. })
  198. .catch(function (ex) {
  199. log.error("Login failed while caching participants: ", ex);
  200. });
  201. });
  202. // cache messages
  203. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  204. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  205. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, null, function (err, messages) {
  206. if (err) {
  207. ModelUtil.emitError(self.eventEmitter, err.message);
  208. return;
  209. }
  210. let multi = redisConn.multi();
  211. messages.forEach(function (message) {
  212. let msgJson = {
  213. id: message.id,
  214. sender_id: message.sender_id,
  215. sender_name: message.sender_name,
  216. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  217. content_type: message.content_type,
  218. content: message.content
  219. };
  220. multi = multi.hset(messagesKey, message.id, JSON.stringify(msgJson))
  221. .zadd(messagesByTimestampKey, ObjectUtil.timestampToLong(message.timestamp), message.id);
  222. });
  223. multi.execAsync()
  224. .then(function (res) {
  225. })
  226. .catch(function (ex) {
  227. log.error("Login failed while caching messages: ", ex);
  228. });
  229. });
  230. // cache topics for MUC
  231. let topicsKey = RedisModel.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  232. TopicRepo.findAllBySessionId(sessionId, function (err, topics) {
  233. if (err) {
  234. ModelUtil.emitError(self.eventEmitter, err.message);
  235. return;
  236. }
  237. topics.forEach(function (topic) {
  238. let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  239. let topicId = topic.id;
  240. let name = topic.name == null ? "" : topic.name;
  241. let createTime = ObjectUtil.timestampToLong(topic.create_time);
  242. let endBy = topic.end_by == null ? "" : topic.end_by;
  243. let endTime = topic.end_time == null ? 0 : ObjectUtil.timestampToLong(topic.end_time);
  244. let startMessageId = topic.start_message_id == null ? "" : topic.start_message_id;
  245. let endMessageId = topic.end_message_id == null ? "" : topic.end_message_id;
  246. let description = topic.description == null ? "" : topic.description;
  247. let status = topic.status == null ? 0 : topic.status;
  248. redisConn.multi()
  249. .zadd(topicsKey, createTime, topicId)
  250. .hmset(topicKey,
  251. 'name', name,
  252. 'session_id', sessionId,
  253. 'create_time', createTime,
  254. 'end_by', endBy,
  255. 'end_time', endTime,
  256. 'start_message_id', startMessageId,
  257. 'end_message_id', endMessageId,
  258. 'description', description,
  259. 'status', status)
  260. .execAsync()
  261. .catch(function (ex) {
  262. log.error("Login failed while caching topics: ", ex);
  263. });
  264. });
  265. });
  266. })
  267. .catch(function (ex) {
  268. log.error("Login failed while caching sessions: ", ex);
  269. });
  270. })(session.id, userId);
  271. });
  272. });
  273. });
  274. callback(null, null);
  275. }
  276. ],
  277. function (err, res) {
  278. ModelUtil.emitOK(self.eventEmitter, {});
  279. });
  280. }
  281. logout(userId,platform) {
  282. let self = this;
  283. async.waterfall([
  284. function (callback) {
  285. Users.isPatientId(userId, function (err, isPatient) {
  286. callback(null, isPatient)
  287. });
  288. },
  289. function (isPatient, callback) {
  290. let usersKey = REDIS_KEYS.Users;
  291. let userStatusKey;
  292. if(platform){
  293. userStatusKey = RedisModel.makeRedisKey(isPatient ? REDIS_KEYS.UserWechatStatus : (platform==PLATFORM.PC?REDIS_KEYS.UserPcStatus:REDIS_KEYS.UserAppStatus), userId);
  294. }else {
  295. userStatusKey = RedisModel.makeRedisKey(isPatient ? REDIS_KEYS.UserWechatStatus :REDIS_KEYS.UserAppStatus, userId);
  296. }
  297. redisConn.multi()
  298. .zrem(usersKey, userId)
  299. .del(userStatusKey)
  300. .execAsync()
  301. .then(function (res) {
  302. if (res.length > 0 && res[0] === 0) {
  303. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "User not found."});
  304. } else {
  305. ModelUtil.emitOK(self.eventEmitter, {});
  306. }
  307. })
  308. .catch(function (ex) {
  309. log.error("Logout failed: ", ex);
  310. });
  311. if(!platform||platform!=PLATFORM.PC){
  312. AppStatusRepo.destroy(userId, function (err, res) {
  313. if(err) log.error("Delete user status failed: " + err);
  314. });
  315. }
  316. callback(null, null);
  317. }],
  318. function (err, res) {
  319. }
  320. );
  321. }
  322. /**
  323. * 用户ID是否属于患者。
  324. *
  325. * @param userId
  326. * @param callback
  327. */
  328. static isPatientId(userId, callback) {
  329. async.waterfall([
  330. function (callback) {
  331. ImDb.execQuery({
  332. "sql": "select case when count(*) > 0 then true else false end 'is_patient' from patients where id = ?",
  333. "args": [userId],
  334. "handler": function (err, res) {
  335. if (err) {
  336. callback(err, res);
  337. return;
  338. }
  339. callback(null, res);
  340. }
  341. });
  342. },
  343. function (res, callback) {
  344. if (res.length === 0) return false;
  345. callback(null, res[0].is_patient);
  346. }
  347. ],
  348. function (err, res) {
  349. if (err) {
  350. log.error("User id check failed: ", err);
  351. callback(null, false);
  352. return;
  353. }
  354. callback(null, res !== 0);
  355. });
  356. }
  357. }
  358. let Promises = require('bluebird');
  359. Promises.promisifyAll(Users.prototype);
  360. module.exports = Users;