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