EquipmentManagerV3.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import re
  2. import threading
  3. import time
  4. import traceback
  5. from Controller.CheckUserData import RandomStr
  6. import oss2, base64
  7. from django.db.models import Q
  8. from django.views.generic.base import View
  9. from Object.RedisObject import RedisObject
  10. from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
  11. from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel
  12. from Object.ResponseObject import ResponseObject
  13. from Object.TokenObject import TokenObject
  14. from Service.CommonService import CommonService
  15. from Service.ModelService import ModelService
  16. import time,json
  17. class EquipmentManagerV3(View):
  18. def get(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. operation = kwargs.get('operation')
  21. return self.validation(request.GET, request, operation)
  22. def post(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. return self.validation(request.POST, request, operation)
  26. def validation(self, request_dict, request, operation):
  27. response = ResponseObject()
  28. token = request_dict.get('token', None)
  29. # 设备主键uid
  30. tko = TokenObject(token)
  31. if tko.code == 0:
  32. response.lang = tko.lang
  33. userID = tko.userID
  34. # 手机端添加设备,查询,修改
  35. if operation == 'add':
  36. return self.do_add(userID, request_dict, response, request)
  37. elif operation == 'query':
  38. return self.do_query(userID, request_dict, response)
  39. elif operation == 'modify':
  40. return self.do_modify(userID, request_dict, response)
  41. else:
  42. return response.json(414)
  43. else:
  44. return response.json(tko.code)
  45. def do_add(self, userID, request_dict, response, request):
  46. token = request_dict.get('token', None)
  47. UID = request_dict.get('UID', None)
  48. NickName = request_dict.get('NickName', None)
  49. View_Account = request_dict.get('View_Account', None)
  50. View_Password = request_dict.get('View_Password', '')
  51. print("准备解密")
  52. View_Password = self.decode_pwd(View_Password)
  53. Type = request_dict.get('Type', None)
  54. ChannelIndex = request_dict.get('ChannelIndex', None)
  55. if all([UID, NickName, View_Account, Type, ChannelIndex]):
  56. tko = TokenObject(token)
  57. response.lang = tko.lang
  58. if tko.code == 0:
  59. userID = tko.userID
  60. re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
  61. if re_uid.match(UID):
  62. is_exist = Device_Info.objects.filter(UID=UID, userID_id=userID)
  63. if is_exist:
  64. # 判断设备是否已存在
  65. if is_exist[0].isExist == 1:
  66. return response.json(174)
  67. else:
  68. is_exist.delete()
  69. # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
  70. # # 判断是否有已绑定用户
  71. # if is_bind:
  72. # return response.json(15)
  73. try:
  74. # 判断是否有用户绑定
  75. nowTime = int(time.time())
  76. us_qs = UidSetModel.objects.filter(uid=UID)
  77. if not us_qs.exists():
  78. uid_set_create_dict = {
  79. 'uid': UID,
  80. 'addTime': nowTime,
  81. 'updTime': nowTime,
  82. 'ip': CommonService.get_ip_address(request_dict),
  83. 'channel': ChannelIndex,
  84. 'nickname': NickName,
  85. }
  86. UidSetModel.objects.create(**uid_set_create_dict)
  87. pk = CommonService.getUserID(getUser=False)
  88. userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
  89. NickName=NickName, View_Account=View_Account,
  90. View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex)
  91. userDevice.save()
  92. redisObj = RedisObject(db=8)
  93. redisObj.del_data(key='uid_qs_' + userID)
  94. except Exception as e:
  95. return response.json(10, repr(e))
  96. else:
  97. dvqs = Device_Info.objects.filter(id=pk).values('id', 'userID', 'NickName', 'UID',
  98. 'View_Account',
  99. 'View_Password', 'ChannelIndex', 'Type',
  100. 'isShare',
  101. 'primaryUserID', 'primaryMaster',
  102. 'data_joined', 'version',
  103. 'isVod', 'isExist')
  104. dvql = CommonService.qs_to_list(dvqs)
  105. ubqs = UID_Bucket.objects.filter(uid=UID). \
  106. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  107. res = dvql[0]
  108. res['vod'] = list(ubqs)
  109. return response.json(0, res)
  110. else:
  111. return response.json(444, {'param': 'UID'})
  112. else:
  113. return response.json(tko.code)
  114. else:
  115. return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})
  116. def do_modify(self, userID, request_dict, response):
  117. token = request_dict.get('token', None)
  118. deviceContent = request_dict.get('content', None)
  119. id = request_dict.get('id', None)
  120. if not deviceContent or not id:
  121. return response.json(444, 'content,id')
  122. tko = TokenObject(token)
  123. response.lang = tko.lang
  124. if tko.code != 0:
  125. return response.json(tko.code)
  126. userID = tko.userID
  127. if userID is None:
  128. return response.json(309)
  129. try:
  130. deviceData = json.loads(deviceContent)
  131. print(deviceData['View_Password'])
  132. deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
  133. dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
  134. dev_info_qs.update(**deviceData)
  135. except Exception as e:
  136. return response.json(177, repr(e))
  137. else:
  138. qs = Device_Info.objects.filter(userID_id=userID, id=id)
  139. res = CommonService.qs_to_dict(qs)
  140. if qs.exists():
  141. uid = qs[0].UID
  142. nickname = qs[0].NickName
  143. # 增加设备影子信息修改昵称 start
  144. us_qs = UidSetModel.objects.filter(uid=uid)
  145. if us_qs.exists():
  146. us_qs.update(nickname=nickname)
  147. else:
  148. ChannelIndex = qs[0].ChannelIndex
  149. nowTime = int(time.time())
  150. uid_set_create_dict = {
  151. 'uid': uid,
  152. 'addTime': nowTime,
  153. 'updTime': nowTime,
  154. 'ip': CommonService.get_ip_address(request),
  155. 'channel': ChannelIndex,
  156. 'nickname': nickname,
  157. }
  158. UidSetModel.objects.create(**uid_set_create_dict)
  159. Device_Info.objects.filter(UID=uid).update(NickName=nickname)
  160. redisObj = RedisObject(db=8)
  161. redisObj.del_data(key='uid_qs_' + userID)
  162. return response.json(0, res)
  163. # 新查询设备字段
  164. def do_query(self, userID, request_dict, response):
  165. token = request_dict.get('token', None)
  166. page = request_dict.get('page', None)
  167. line = request_dict.get('line', None)
  168. NickName = request_dict.get('NickName', None)
  169. page = int(page)
  170. line = int(line)
  171. uid = request_dict.get('uid', None)
  172. tko = TokenObject(token)
  173. response.lang = tko.lang
  174. if page <= 0:
  175. return response.json(0)
  176. if tko.code == 0:
  177. redisObj = RedisObject(db=8)
  178. redis_value = redisObj.get_data(key='uid_qs_'+userID)
  179. if redis_value == False:
  180. # print('缓存不存在就开始添加到缓存')
  181. userID = tko.userID
  182. dvqs = Device_Info.objects.filter(userID_id=userID)
  183. # # 过滤已重置的设备
  184. dvqs = dvqs.filter(~Q(isExist=2))
  185. dvql = dvqs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
  186. 'View_Password', 'ChannelIndex', 'Type', 'isShare',
  187. 'primaryUserID', 'primaryMaster', 'data_joined',
  188. 'version',
  189. 'isVod', 'isExist', 'NotificationMode', 'OutdoorModel',
  190. 'WIFIName', 'isDetector', 'DetectorRank', 'MirrorType',
  191. 'RecordType', 'TimeZone', 'SpaceUsable', 'SpaceSum')
  192. dvls = CommonService.qs_to_list(dvql)
  193. uid_list = []
  194. for dvl in dvls:
  195. uid_list.append(dvl['UID'])
  196. ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
  197. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  198. upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  199. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  200. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  201. nowTime = int(time.time())
  202. data = []
  203. # 设备拓展信息表
  204. us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname', 'ucode', 'detect_status', 'detect_group', 'detect_interval', 'region_alexa', 'is_alexa', 'light_alarm_type',
  205. 'light_alarm_level', 'light_alarm_man_en', 'light_alarm_vol', 'light_long_light', 'light_night_model')
  206. uv_dict = {}
  207. for us in us_qs:
  208. uv_dict[us['uid']] = {
  209. 'version': us['version'],
  210. 'nickname': us['nickname'],
  211. 'ucode': us['ucode'],
  212. 'detect_interval': us['detect_interval'],
  213. 'detect_group': us['detect_group'],
  214. 'detect_status': us['detect_status'],
  215. 'region_alexa': us['region_alexa'],
  216. 'is_alexa': us['is_alexa'],
  217. 'light_alarm_type': us['light_alarm_type'],
  218. 'light_alarm_level': us['light_alarm_level'],
  219. 'light_alarm_man_en': us['light_alarm_man_en'],
  220. 'light_alarm_vol': us['light_alarm_vol'],
  221. 'light_long_light': us['light_long_light'],
  222. 'light_night_model': us['light_night_model']
  223. }
  224. for p in dvls:
  225. p['vod'] = []
  226. for dm in ubqs:
  227. if p['UID'] == dm['uid']:
  228. if dm['endTime'] > nowTime:
  229. p['vod'].append(dm)
  230. p['preview'] = []
  231. for up in upqs:
  232. if p['UID'] == up['uid']:
  233. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  234. img_sign = bucket.sign_url('GET', obj, 300)
  235. p['preview'].append(img_sign)
  236. p_uid = p['UID']
  237. if p_uid in uv_dict:
  238. # 设备版本号
  239. p['uid_version'] = uv_dict[p_uid]['version']
  240. p['ucode'] = uv_dict[p_uid]['ucode']
  241. p['detect_interval'] = uv_dict[p_uid]['detect_interval']
  242. p['detect_status'] = uv_dict[p_uid]['detect_status']
  243. p['detect_group'] = uv_dict[p_uid]['detect_group']
  244. p['region_alexa'] = uv_dict[p_uid]['region_alexa']
  245. p['is_alexa'] = uv_dict[p_uid]['is_alexa']
  246. p['light_alarm_type'] = uv_dict[p_uid]['light_alarm_type']
  247. p['light_alarm_level'] = uv_dict[p_uid]['light_alarm_level']
  248. p['light_alarm_man_en'] = uv_dict[p_uid]['light_alarm_man_en']
  249. p['light_alarm_vol'] = uv_dict[p_uid]['light_alarm_vol']
  250. p['light_long_light'] = uv_dict[p_uid]['light_long_light']
  251. p['light_night_model'] = uv_dict[p_uid]['light_night_model']
  252. # 设备昵称 调用影子信息昵称,先阶段不可
  253. if uv_dict[p_uid]['nickname']:
  254. p['NickName'] = uv_dict[p_uid]['nickname']
  255. else:
  256. # 设备版本号
  257. p['uid_version'] = ''
  258. p['ucode'] = ''
  259. data.append(p)
  260. # 缓存时间为一个钟
  261. redisObj.set_data(key='uid_qs_'+userID, val=data, expire=3600)
  262. print('分页')
  263. items=[]
  264. for index, item in enumerate(data):
  265. if (page - 1) * line <= index:
  266. if index < page * line:
  267. item['View_Password']=self.encrypt_pwd(item['View_Password'])
  268. items.append(item)
  269. return response.json(0, items)
  270. else:
  271. # print('去缓存找数据')
  272. redis_value = redis_value.replace("'", '"')
  273. redis_value = redis_value.replace('"isShare": True', '"isShare": true')
  274. redis_value = redis_value.replace('"isShare": False', '"isShare": false')
  275. redis_value = redis_value.replace('"version": None', '"version": ""')
  276. try:
  277. redis_value = json.loads(redis_value)
  278. except Exception as e:
  279. print(repr(e))
  280. return response.json(0, {'data': redis_value})
  281. if NickName:
  282. # print('NickName搜索缓存')
  283. for index, item in enumerate(redis_value):
  284. if NickName ==item['NickName']:
  285. # 加密
  286. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  287. return response.json(0, item)
  288. if uid:
  289. # print('uid搜索缓存')
  290. for index, item in enumerate(redis_value):
  291. if uid == item['UID']:
  292. # 加密
  293. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  294. return response.json(0, item)
  295. items = []
  296. # print('缓存分页')
  297. for index, item in enumerate(redis_value):
  298. if (page - 1) * line <= index:
  299. if index < page * line:
  300. # 加密
  301. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  302. items.append(item)
  303. return response.json(0, items)
  304. else:
  305. return response.json(tko.code)
  306. # 加密
  307. def encrypt_pwd(self,userPwd):
  308. for i in range(1, 4):
  309. if i == 1:
  310. userPwd = RandomStr(3, False)+userPwd+RandomStr(3, False)
  311. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  312. if i == 2:
  313. userPwd = RandomStr(2, False)+str(userPwd)+RandomStr(2, False)
  314. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  315. if i == 3:
  316. userPwd = RandomStr(1, False)+str(userPwd)+RandomStr(1, False)
  317. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  318. return userPwd
  319. # 解密
  320. def decode_pwd(self, password):
  321. for i in range(1, 4):
  322. if i == 1:
  323. # 第一次先解密
  324. password = base64.b64decode(password)
  325. password = password.decode('utf-8')
  326. # 截去第一位,最后一位
  327. password = password[1:-1]
  328. if i == 2:
  329. # 第2次先解密
  330. password = base64.b64decode(password)
  331. password = password.decode('utf-8')
  332. # 去前2位,后2位
  333. password = password[2:-2]
  334. if i == 3:
  335. # 第3次先解密
  336. password = base64.b64decode(password)
  337. password = password.decode('utf-8')
  338. # 去前3位,后3位
  339. password = password[3:-3]
  340. return password