UserDeviceShareController.py 13 KB

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