GatewayFamilyMemberController.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : GatewayFamilyMemberController.py
  4. @Time : 2022/5/25 10:21
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import json
  10. import time
  11. from django.db import transaction
  12. from django.views.generic.base import View
  13. from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyView
  14. from Model.models import UserFamily, FamilyMemberJoin, FamilyMember, SysMsgModel, FamilyMemberPermission, \
  15. Device_User, FamilyRoomDevice, FamilyRoom
  16. from Object.RedisObject import RedisObject
  17. from Object.ResponseObject import ResponseObject
  18. from Object.TokenObject import TokenObject
  19. from Service.CommonService import CommonService
  20. # 家庭房间管理
  21. class GatewayFamilyMemberView(View):
  22. def get(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. return self.validation(request.GET, request, operation)
  26. def post(self, request, *args, **kwargs):
  27. request.encoding = 'utf-8'
  28. operation = kwargs.get('operation')
  29. return self.validation(request.POST, request, operation)
  30. def validation(self, request_dict, request, operation):
  31. token = request.META.get('HTTP_AUTHORIZATION')
  32. token = TokenObject(token)
  33. lang = request_dict.get('lang', None)
  34. response = ResponseObject(lang) if lang else ResponseObject(token.lang)
  35. if token.code != 0:
  36. return response.json(token.code)
  37. app_user_id = token.userID
  38. # 添加设备关联房间
  39. if operation == 'join':
  40. return self.member_join(app_user_id, request_dict, response)
  41. elif operation == 'join/page':
  42. return self.member_join_page(request_dict, response)
  43. elif operation == 'qrcode/generate':
  44. return self.family_generate_token(app_user_id, request_dict, response)
  45. elif operation == 'qrcode/check':
  46. return self.check_qrcode(request_dict, response)
  47. elif operation == 'join/info':
  48. return self.member_join_info(request_dict, response)
  49. elif operation == 'join/update':
  50. return self.user_join_confirm(request_dict, response)
  51. elif operation == 'del':
  52. return self.member_del(app_user_id, request_dict, response)
  53. elif operation == 'created':
  54. return self.family_created(app_user_id, request_dict, response)
  55. elif operation == 'del/home':
  56. return self.del_home(app_user_id, request_dict, response)
  57. elif operation == 'join/del':
  58. return self.member_join_del(app_user_id, request_dict, response)
  59. @classmethod
  60. def member_join_del(cls, app_user_id, request_dict, response):
  61. """
  62. 删除最近联系人
  63. @param app_user_id:
  64. @param request_dict:
  65. @param response:
  66. @return:
  67. """
  68. join_ids = request_dict.get('joinIds', None)
  69. family_id = request_dict.get('familyId', None)
  70. if not join_ids:
  71. return response.json()
  72. is_owner = EquipmentFamilyView.get_family_owner(app_user_id, family_id)
  73. if not is_owner:
  74. return response.json(404)
  75. try:
  76. with transaction.atomic():
  77. items = join_ids.split(',')
  78. for item in items:
  79. family_member_join_qs = FamilyMemberJoin.objects.filter(id=int(item))
  80. if family_member_join_qs.exists():
  81. family_member_join_qs.delete()
  82. return response.json(0)
  83. except Exception as e:
  84. print(e)
  85. return response.json(177, repr(e))
  86. @classmethod
  87. def del_home(cls, app_user_id, request_dict, response):
  88. """
  89. 删除家庭
  90. @param app_user_id:
  91. @param request_dict:
  92. @param response:
  93. @return:
  94. """
  95. family_id = request_dict.get('familyId', None)
  96. if not family_id:
  97. return response.json(444)
  98. is_owner = EquipmentFamilyView.get_family_owner(app_user_id, family_id)
  99. if not is_owner:
  100. return response.json(404)
  101. family_id = int(family_id)
  102. try:
  103. with transaction.atomic():
  104. family_room_device_qs = FamilyRoomDevice.objects.filter(family_id=family_id)
  105. if family_room_device_qs.exists():
  106. family_room_device_qs.delete()
  107. user_family_qs = UserFamily.objects.filter(id=family_id)
  108. if user_family_qs.exists():
  109. user_family_qs.delete()
  110. return response.json(0)
  111. return response.json(176)
  112. except Exception as e:
  113. print(e)
  114. return response.json(177, repr(e))
  115. @classmethod
  116. def family_created(cls, app_user_id, request_dict, response):
  117. """
  118. 创建家庭
  119. @param app_user_id:
  120. @param request_dict:
  121. @param response:
  122. @return:
  123. """
  124. family_name = request_dict.get('familyName', None)
  125. if not family_name:
  126. return response.json(444)
  127. n_time = int(time.time())
  128. location = request_dict.get('location', '')
  129. room_names = request_dict.get('roomNames', None)
  130. try:
  131. with transaction.atomic():
  132. member_permission_qs = FamilyMemberPermission.objects.filter(no='001').values('id')
  133. user_family = UserFamily.objects.create(user_id=app_user_id, name=family_name,
  134. location=location,
  135. updated_time=n_time,
  136. created_time=n_time)
  137. if user_family.id:
  138. device_user = Device_User.objects.get(userID=app_user_id)
  139. permission_id = member_permission_qs.first()['id']
  140. FamilyMember.objects.create(family_id=user_family.id, user_id=app_user_id,
  141. user_name=device_user.username, identity=1,
  142. permission_id=int(permission_id), sort=1, updated_time=n_time,
  143. created_time=n_time)
  144. if room_names:
  145. names = room_names.split(',')
  146. rooms = []
  147. for index, item in enumerate(names):
  148. rooms.append(FamilyRoom(
  149. name=item,
  150. family_id=user_family.id,
  151. sort=index,
  152. updated_time=n_time,
  153. created_time=n_time
  154. ))
  155. FamilyRoom.objects.bulk_create(rooms)
  156. return response.json(0)
  157. except Exception as e:
  158. print(e)
  159. return response.json(177, repr(e))
  160. @classmethod
  161. def member_del(cls, app_user_id, request_dict, response):
  162. """
  163. 成员删除或退出
  164. @param app_user_id:
  165. @param request_dict:
  166. @param response:
  167. @return:
  168. """
  169. member_id = request_dict.get('memberId', None)
  170. family_id = request_dict.get('familyId', None)
  171. if not family_id:
  172. return response.json(444)
  173. try:
  174. family_id = int(family_id)
  175. with transaction.atomic():
  176. # 家庭所有者删除成员
  177. if member_id:
  178. is_owner = EquipmentFamilyView.get_family_owner(app_user_id, family_id)
  179. if not is_owner:
  180. return response.json(404)
  181. member_id = int(member_id)
  182. family_member_qs = FamilyMember.objects.filter(id=member_id)
  183. if not family_member_qs.exists():
  184. return response.json(173)
  185. family_member_qs.delete()
  186. return response.json(0)
  187. else:
  188. # 成员退出当前家庭
  189. family_member = FamilyMember.objects.filter(family_id=family_id, user_id=app_user_id, identity=1)
  190. if family_member.exists():
  191. return response.json(173)
  192. family_member_qs = FamilyMember.objects.filter(family_id=family_id, user_id=app_user_id)
  193. if not family_member_qs.exists():
  194. return response.json(173)
  195. family_member_qs.delete()
  196. return response.json(0)
  197. except Exception as e:
  198. return response.json(177, repr(e))
  199. @classmethod
  200. def user_join_confirm(cls, request_dict, response):
  201. """
  202. 用户加入家庭确认
  203. @param request_dict:
  204. @param response:
  205. @return:
  206. """
  207. join_id = request_dict.get('joinId', None)
  208. confirm = request_dict.get('confirm', None)
  209. lang = request_dict.get('lang', 'en')
  210. if not all([join_id, confirm]):
  211. return response.json(444)
  212. join_id = int(join_id)
  213. family_join = FamilyMemberJoin.objects.filter(id=join_id, status=0)
  214. if not family_join.exists():
  215. return response.json(173)
  216. family_member = FamilyMember.objects.filter(family_id=family_join.first().family_id,
  217. user_id=family_join.first().user_id)
  218. if family_member.exists():
  219. return response.json(174)
  220. try:
  221. now_time = int(time.time())
  222. with transaction.atomic():
  223. family_join.update(status=2 if confirm == 'confirm' else 1)
  224. family_join = FamilyMemberJoin.objects.filter(id=join_id)
  225. family_join = family_join.values('id', 'user_id', 'user__username', 'user__NickName', 'family__name',
  226. 'family_id', 'family__user_id', 'status', 'type', 'updated_time')
  227. family_join = family_join.first()
  228. nick_name = family_join['user__NickName']
  229. family_name = family_join['family__name']
  230. join_type = family_join['type']
  231. data = {
  232. 'addTime': now_time,
  233. 'updTime': now_time,
  234. 'userID_id': family_join['user_id'] if join_type == 1 else family_join['family__user_id'],
  235. 'eventType': 0
  236. }
  237. if confirm == 'confirm':
  238. msg_text = cls.get_confirm_text(nick_name, family_name, join_type, True, lang)
  239. p_id = FamilyMemberPermission.objects.filter(no='002').values('id').first()
  240. p_id = p_id['id']
  241. FamilyMember.objects.create(family_id=family_join['family_id'], updated_time=now_time,
  242. user_id=family_join['user_id'],
  243. created_time=now_time,
  244. permission_id=p_id,
  245. user_name=family_join['user__username'])
  246. elif confirm == 'refusal':
  247. msg_text = cls.get_confirm_text(nick_name, family_name, join_type, False, lang)
  248. else:
  249. ex = Exception("data is null")
  250. raise ex
  251. data['msg'] = msg_text
  252. data['uid'] = family_join['id']
  253. SysMsgModel.objects.create(**data)
  254. return response.json(0)
  255. except Exception as e:
  256. print(e)
  257. return response.json(177, repr(e))
  258. @classmethod
  259. def get_confirm_text(cls, nick_name, family_name, join_type, is_confirm, lang='en'):
  260. # join_type == 1等于扫码请求加u人
  261. if is_confirm:
  262. if join_type == 1:
  263. if lang == 'cn':
  264. msg_text = '{} 同意你的请求'.format(family_name)
  265. else:
  266. msg_text = '{} confirm to your request'.format(family_name)
  267. else:
  268. if lang == 'cn':
  269. msg_text = '{}同意加入{}'.format(nick_name, family_name)
  270. else:
  271. msg_text = '{} confirm to join {}'.format(nick_name, family_name)
  272. else:
  273. if join_type == 1:
  274. if lang == 'cn':
  275. msg_text = '{}拒绝你的请求'.format(family_name)
  276. else:
  277. msg_text = '{} refused your request'.format(family_name)
  278. else:
  279. if lang == 'cn':
  280. msg_text = '{}拒绝加入{}'.format(nick_name, family_name)
  281. else:
  282. msg_text = '{} refused to join '.format(family_name)
  283. return msg_text
  284. @classmethod
  285. def member_join_info(cls, request_dict, response):
  286. """
  287. 查询加入家庭信息
  288. @param request_dict:
  289. @param response:
  290. @return:
  291. """
  292. join_id = request_dict.get('joinId', None)
  293. if not join_id:
  294. return response.json(444)
  295. join_id = int(join_id)
  296. family_join_qs = FamilyMemberJoin.objects.filter(id=join_id)
  297. if not family_join_qs.exists():
  298. return response.json(173)
  299. family_join_qs = family_join_qs.values('type', 'user__NickName', 'family__name', 'status', 'id',
  300. 'family__user__NickName')
  301. family_join_qs = family_join_qs.first()
  302. nick_name = family_join_qs['user__NickName']
  303. if family_join_qs['type'] == 0:
  304. nick_name = family_join_qs['family__user__NickName']
  305. return response.json(0, {
  306. 'id': family_join_qs['id'],
  307. 'type': family_join_qs['type'],
  308. 'nickName': nick_name,
  309. 'familyName': family_join_qs['family__name'],
  310. 'status': family_join_qs['status'],
  311. })
  312. @classmethod
  313. def member_join(cls, app_user_id, request_dict, response):
  314. """
  315. 家庭成员加入
  316. @param app_user_id:
  317. @param request_dict:
  318. @param response:
  319. @return:
  320. """
  321. family_id = request_dict.get('familyId', None)
  322. invite = request_dict.get('QRCodeInvite', 0)
  323. user_id = request_dict.get('app_user_id', None)
  324. lang = request_dict.get('lang', 'en')
  325. if not all([family_id, invite]):
  326. return response.json(444)
  327. invite = int(invite)
  328. family_id = int(family_id)
  329. now_time = int(time.time())
  330. # 判断当前家庭是否已有该成员
  331. if invite == 1:
  332. family_qs = FamilyMember.objects.filter(family_id=family_id, user_id=app_user_id)
  333. elif user_id:
  334. family_qs = FamilyMember.objects.filter(family_id=family_id, user_id=user_id)
  335. else:
  336. return response.json(173)
  337. if family_qs.exists():
  338. return response.json(174)
  339. try:
  340. user_family_qs = UserFamily.objects.filter(id=family_id)
  341. if not user_family_qs:
  342. return response.json(173)
  343. user_family = user_family_qs.first()
  344. family_name = user_family.name
  345. data = {
  346. 'addTime': now_time,
  347. 'updTime': now_time,
  348. 'eventType': 705
  349. }
  350. # 请求加入家庭,用户信息
  351. user_qs = Device_User.objects.filter(userID=app_user_id)
  352. nick_name = user_qs.first().NickName
  353. if invite == 1:
  354. msg_text = cls.get_msg_text(nick_name, family_name, lang, True)
  355. # 通知对象 家庭所有者
  356. join_user_id = app_user_id
  357. data['userID_id'] = user_family.user_id
  358. elif app_user_id:
  359. msg_text = cls.get_msg_text(nick_name, family_name, lang, False)
  360. # 通知对象 被邀请人
  361. join_user_id = user_id
  362. data['userID_id'] = user_id
  363. else:
  364. return response.json(173)
  365. data['msg'] = msg_text
  366. with transaction.atomic():
  367. member_user_id = user_id if user_id else app_user_id
  368. member_join_qs = FamilyMemberJoin.objects.filter(family_id=family_id, user_id=member_user_id)
  369. if member_join_qs.exists():
  370. member_join_qs.update(status=0, updated_time=now_time)
  371. data['uid'] = member_join_qs.first().id
  372. SysMsgModel.objects.create(**data)
  373. return response.json(0)
  374. family_user_join = FamilyMemberJoin.objects.create(family_id=family_id, user_id=join_user_id,
  375. status=0,
  376. updated_time=now_time,
  377. created_time=now_time,
  378. type=invite)
  379. data['uid'] = family_user_join.id
  380. SysMsgModel.objects.create(**data)
  381. return response.json(0)
  382. except Exception as e:
  383. print(e)
  384. return response.json(177, repr(e))
  385. @classmethod
  386. def get_msg_text(cls, nick_name, family_name, lang, is_invite=False):
  387. """
  388. 系统消息通知内容,中英文判断
  389. @param nick_name:
  390. @param family_name:
  391. @param lang:
  392. @param is_invite:
  393. @return:
  394. """
  395. if lang and lang == 'cn':
  396. if is_invite:
  397. msg_text = '{}请求加入你的{}'.format(nick_name, family_name)
  398. else:
  399. msg_text = '{}邀请你加入{}'.format(nick_name, family_name)
  400. else:
  401. if is_invite:
  402. msg_text = '{} Request to join your Homegroup {}'.format(nick_name, family_name)
  403. else:
  404. msg_text = '{} invite you to join the Homegroup {}'.format(nick_name, family_name)
  405. return msg_text
  406. @classmethod
  407. def member_join_page(cls, request_dict, response):
  408. """
  409. 家庭成员邀请记录
  410. @param request_dict:
  411. @param response:
  412. @return:
  413. """
  414. page_no = request_dict.get('pageNo', None)
  415. page_size = request_dict.get('pageSize', None)
  416. family_id = request_dict.get('familyId', None)
  417. if not all([page_no, page_size, family_id]):
  418. return response.json(444)
  419. member_join = FamilyMemberJoin.objects.filter(family_id=family_id).values('id', 'status', 'user__username',
  420. 'user__userIconUrl', 'user__phone',
  421. 'user__userEmail', 'updated_time',
  422. 'created_time',
  423. 'user__NickName')
  424. page_no = int(page_no)
  425. page_size = int(page_size)
  426. member_join = member_join.order_by('-updated_time')[(page_no - 1) * page_size: page_no * page_size]
  427. if not member_join.exists():
  428. return response.json(0, [])
  429. result = []
  430. for item in member_join:
  431. result.append({
  432. 'joinId': item['id'],
  433. 'status': item['status'],
  434. 'userName': item['user__username'],
  435. 'userIconUrl': item['user__userIconUrl'],
  436. 'phone': item['user__phone'],
  437. 'nickName': item['user__NickName'],
  438. 'userEmail': item['user__userEmail'],
  439. 'updatedTime': item['updated_time'],
  440. 'createdTime': item['created_time']
  441. })
  442. return response.json(0, result)
  443. @classmethod
  444. def family_generate_token(cls, app_user_id, request_dict, response):
  445. """
  446. 获取家庭令牌信息
  447. @param app_user_id:
  448. @param request_dict:
  449. @param response:
  450. @return:
  451. """
  452. family_id = request_dict.get('familyId', None)
  453. if not family_id:
  454. return response.json(444)
  455. family_id = int(family_id)
  456. family_qs = UserFamily.objects.filter(id=family_id, user_id=app_user_id) \
  457. .values('name', 'user__userEmail',
  458. 'user__userIconUrl',
  459. 'user__phone', 'user__NickName',
  460. 'user__username')
  461. if not family_qs.exists():
  462. return response.json(173)
  463. family_qs = family_qs.first()
  464. data = {'sharer': app_user_id, 'familyId': family_id}
  465. # -----------------
  466. # share_token = jwt.encode(data, '.#^^&', algorithm='HS256').decode('utf-8')
  467. # +++++++++++++++++
  468. redisObj = RedisObject()
  469. share_token = str(int(time.time())) + CommonService.RandomStr(22)
  470. if not redisObj.set_data(key=share_token, val=json.dumps(data), expire=300):
  471. return response.json(10, '生成失败')
  472. return response.json(0, {
  473. 'shareToken': share_token,
  474. 'userPhone': family_qs['user__phone'],
  475. 'nickName': family_qs['user__NickName'],
  476. 'userIconUrl': family_qs['user__userIconUrl'],
  477. 'userName': family_qs['user__username'],
  478. 'familyName': family_qs['name'],
  479. 'userEmail': family_qs['user__userEmail'],
  480. })
  481. @classmethod
  482. def check_qrcode(cls, request_dict, response):
  483. """
  484. 检查二维码是否过期
  485. @param request_dict:
  486. @param response:
  487. @return:
  488. """
  489. share_token = request_dict.get('shareToken', None)
  490. if not share_token:
  491. return response.json(444)
  492. redisObj = RedisObject()
  493. share_data = redisObj.get_data(key=share_token)
  494. if not share_data:
  495. return response.json(119)
  496. data = json.loads(share_data)
  497. sharer = data.get('sharer', None)
  498. family_id = data.get('familyId', None)
  499. if not all([sharer, family_id]):
  500. return response.json(173)
  501. family_id = int(family_id)
  502. user_family_qs = UserFamily.objects.filter(id=family_id)
  503. if not user_family_qs.exists():
  504. return response.json(173)
  505. user_family_qs = user_family_qs.values('id', 'name', 'user__userEmail',
  506. 'user__userIconUrl',
  507. 'user__phone', 'user__NickName',
  508. 'user__username')
  509. return response.json(0, {
  510. 'familyId': user_family_qs[0]['id'],
  511. 'userPhone': user_family_qs[0]['user__phone'],
  512. 'nickName': user_family_qs[0]['user__NickName'],
  513. 'userIconUrl': user_family_qs[0]['user__userIconUrl'],
  514. 'userName': user_family_qs[0]['user__username'],
  515. 'familyName': user_family_qs[0]['name'],
  516. 'userEmail': user_family_qs[0]['user__userEmail'],
  517. })