users.js 20 KB

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