UserDeviceShareController.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UserDeviceShareController.py
  4. @Time : 2023/1/7 15:05
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import logging
  10. import time
  11. from django.db import transaction
  12. from django.db.models import Q
  13. from django.views import View
  14. from Model.models import DeviceSharePermission, DeviceChannelUserSet, DeviceChannelUserPermission, UidChannelSetModel, \
  15. Device_Info
  16. from Object.ResponseObject import ResponseObject
  17. from Object.TokenObject import TokenObject
  18. from Service.UserDeviceService import UserDeviceService
  19. from Ansjer.config import CONFIG_CN, CONFIG_INFO, CONFIG_TEST, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
  20. AWS_SES_ACCESS_REGION, AWS_IOT_SES_ACCESS_CHINA_REGION
  21. from Model.models import DeviceWallpaper
  22. from Object.AWS.AmazonS3Util import AmazonS3Util
  23. LOGGER = logging.getLogger('info')
  24. class UserDeviceShareView(View):
  25. def get(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.GET, request, operation)
  29. def post(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. return self.validation(request.POST, request, operation)
  33. def validation(self, request_dict, request, operation):
  34. token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  35. lang = request_dict.get('lang', token.lang)
  36. response = ResponseObject(lang)
  37. if token.code != 0:
  38. return response.json(token.code)
  39. if operation == 'user-permissions':
  40. return self.get_user_share_permission(request_dict, response)
  41. elif operation == 'permissions-save':
  42. return self.user_channel_permission_save(request_dict, response)
  43. elif operation == 'permissions-test':
  44. return self.synch_share_device_permission(response)
  45. elif operation == 'getWallpaperList':
  46. return self.get_wallpaper_list(request_dict, response)
  47. else:
  48. return response.json(404)
  49. @classmethod
  50. def get_user_share_permission(cls, request_dict, response):
  51. """
  52. 获取用户分享权限
  53. @param request_dict: 设备uid
  54. @param response: 响应对象
  55. @return: permission List
  56. """
  57. try:
  58. uid = request_dict.get('uid', None)
  59. user_id = request_dict.get('userId', None)
  60. channel_count = request_dict.get('channelCount', None)
  61. if not all([user_id, uid, channel_count]):
  62. return response(444, 'uid, userId and channelCount is required')
  63. user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
  64. .values('id', 'channels')
  65. if not user_permission_qs.exists():
  66. return response.json(0, {})
  67. up_id = user_permission_qs[0]['id']
  68. channel_permission_qs = DeviceChannelUserPermission.objects.filter(channel_user_id=up_id) \
  69. .values('permission_id', 'channel_user_id')
  70. if not channel_permission_qs.exists():
  71. return response.json(0, {})
  72. channel_list = list(range(1, int(channel_count) + 1))
  73. share_channel_list = user_permission_qs[0]['channels'].split(',')
  74. c_list = []
  75. for channel in channel_list:
  76. is_select = 1 if str(channel) in share_channel_list else 0
  77. c_list.append({'channelIndex': channel, 'isSelect': is_select})
  78. p_list = []
  79. permission_qs = DeviceSharePermission.objects.all()
  80. share_permission_list = [item['permission_id'] for item in channel_permission_qs]
  81. for item in permission_qs:
  82. is_select = 1 if item.id in share_permission_list else 0
  83. p_list.append({'permissionId': item.id, 'code': item.code, 'isSelect': is_select})
  84. data = {'channels': c_list, 'permissions': p_list}
  85. return response.json(0, data)
  86. except Exception as e:
  87. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  88. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  89. @classmethod
  90. def user_channel_permission_save(cls, request_dict, response):
  91. """
  92. 主用户分享设备时设置通道权限保存
  93. """
  94. try:
  95. uid = request_dict.get('uid', None)
  96. channels = request_dict.get('channels', None) # 通道集合,多个','隔开
  97. user_id = request_dict.get('userId', None)
  98. permission_ids = request_dict.get('permissionIds', None) # 权限集合,多个','隔开
  99. if not all([user_id, uid, channels, permission_ids]):
  100. return response.json(444)
  101. p_ids = []
  102. device_user_set = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid)
  103. now_time = int(time.time())
  104. with transaction.atomic():
  105. is_delete = False
  106. if not device_user_set.exists():
  107. device_set = {'uid': uid, 'user_id': user_id, 'channels': channels,
  108. 'created_time': now_time, 'updated_time': now_time}
  109. device_user_set = DeviceChannelUserSet.objects.create(**device_set)
  110. channel_user_id = device_user_set.id
  111. else:
  112. DeviceChannelUserSet.objects.update(channels=channels, updated_time=now_time)
  113. channel_user_id = device_user_set.first().id
  114. is_delete = True
  115. if ',' in permission_ids:
  116. p_ids = [int(val) for val in permission_ids.split(',')]
  117. if is_delete:
  118. DeviceChannelUserPermission.objects.filter(
  119. channel_user_id=channel_user_id).delete()
  120. if not p_ids:
  121. channel_permission = {'permission_id': int(permission_ids),
  122. 'channel_user_id': channel_user_id,
  123. 'created_time': now_time}
  124. DeviceChannelUserPermission.objects.create(**channel_permission)
  125. else:
  126. channel_permission_list = []
  127. for item in p_ids:
  128. channel_permission_list.append(DeviceChannelUserPermission(
  129. permission_id=int(item),
  130. channel_user_id=channel_user_id,
  131. created_time=now_time))
  132. DeviceChannelUserPermission.objects.bulk_create(channel_permission_list)
  133. return response.json(0)
  134. except Exception as e:
  135. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  136. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  137. @staticmethod
  138. def qrcode_share_channel_permission_save(user_id, uid):
  139. """
  140. 二维码分享保存通道权限
  141. @param user_id: 用户id
  142. @param uid: 用户设备ID
  143. @return: True | False
  144. """
  145. try:
  146. if not all([user_id, uid]):
  147. return False
  148. with transaction.atomic():
  149. ds_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid)
  150. if ds_qs.exists():
  151. return True
  152. UserDeviceService.update_device_channel(uid)
  153. channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid).values('channel')
  154. if not channel_qs.exists():
  155. return False
  156. channel_list = [str(val['channel']) for val in channel_qs]
  157. channel_str = ','.join(channel_list)
  158. now_time = int(time.time())
  159. device_set = {'uid': uid, 'user_id': user_id, 'channels': channel_str,
  160. 'created_time': now_time, 'updated_time': now_time}
  161. device_user_set = DeviceChannelUserSet.objects.create(**device_set)
  162. channel_permission_qs = DeviceSharePermission.objects \
  163. .all().values('id', 'code').order_by('sort')
  164. user_set_id = device_user_set.id
  165. channel_permission_list = []
  166. for item in channel_permission_qs:
  167. channel_permission_list.append(DeviceChannelUserPermission(
  168. permission_id=item['id'],
  169. channel_user_id=user_set_id,
  170. created_time=now_time))
  171. DeviceChannelUserPermission.objects.bulk_create(channel_permission_list)
  172. return True
  173. except Exception as e:
  174. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  175. return False
  176. @staticmethod
  177. def synch_share_device_permission(response):
  178. """
  179. 同步分析设备权限
  180. @param response: 响应结果
  181. """
  182. device_info_qs = Device_Info.objects \
  183. .filter(~Q(Type__in=[1, 2, 3, 4, 10001]), ~Q(primaryUserID=''), isShare=1) \
  184. .values('userID_id', 'UID').order_by('-data_joined')
  185. if not device_info_qs.exists():
  186. return response.json(0)
  187. for item in device_info_qs:
  188. UserDeviceShareView.qrcode_share_channel_permission_save(item['userID_id'], item['UID'])
  189. return response.json(0)
  190. @classmethod
  191. def get_wallpaper_list(cls, request_dict, response):
  192. """
  193. 获取设备壁纸列表
  194. @param request_dict:
  195. @param response:
  196. @return:
  197. """
  198. try:
  199. device_type = int(request_dict.get('deviceType', None))
  200. uid = request_dict.get('uid', None)
  201. channel = int(request_dict.get('channel', 1))
  202. if not all([device_type, uid]):
  203. return response.json(444)
  204. # 查询用户自定义壁纸
  205. user_wallpaper_qs = DeviceWallpaper.objects.filter(channel=channel, uid=uid,
  206. device_type=device_type, parent_id=0, status=1)
  207. # 查询系统默认壁纸
  208. def_wallpaper_qs = DeviceWallpaper.objects.filter(classification=1, device_type=device_type, status=1)
  209. # 查询用户选中的壁纸
  210. user_checked_qs = DeviceWallpaper.objects.filter(channel=channel, uid=uid,
  211. device_type=device_type, parent_id__gt=0, status=1)
  212. checked_id = user_checked_qs[0].parent_id if user_checked_qs.exists() else 0
  213. wallpaper_list = []
  214. if def_wallpaper_qs.exists() or user_wallpaper_qs.exists():
  215. # 初始化存储桶客户端
  216. s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[0], AWS_SECRET_ACCESS_KEY[0], AWS_IOT_SES_ACCESS_CHINA_REGION) \
  217. if CONFIG_CN == CONFIG_INFO or CONFIG_TEST == CONFIG_INFO \
  218. else AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
  219. bucket_name = "ansjerfilemanager"
  220. # 处理系统默认壁纸和用户自定义壁纸
  221. all_wallpapers_qs = def_wallpaper_qs.union(user_wallpaper_qs)
  222. for item in all_wallpapers_qs:
  223. obj_key = item.obj_prefix + item.obj_name
  224. response_url = s3.generate_file_obj_url(bucket_name, obj_key)
  225. wallpaper = {
  226. 'id': item.id,
  227. 'url': response_url,
  228. 'state': 1 if checked_id == item.id else 0,
  229. 'classification': item.classification
  230. }
  231. wallpaper_list.append(wallpaper)
  232. return response.json(0, {'wallpapers': wallpaper_list})
  233. except Exception as e:
  234. LOGGER.error('查询设备壁纸异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  235. return response.json(5)