users.js 20 KB

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