EquipmentManagerV3.py 19 KB

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