EquipmentManagerV3.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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')
  190. dvls = CommonService.qs_to_list(dvql)
  191. uid_list = []
  192. for dvl in dvls:
  193. uid_list.append(dvl['UID'])
  194. ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
  195. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  196. upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  197. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  198. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  199. nowTime = int(time.time())
  200. data = []
  201. # 设备拓展信息表
  202. us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname','ucode')
  203. uv_dict = {}
  204. for us in us_qs:
  205. uv_dict[us['uid']] = {'version': us['version'], 'nickname': us['nickname'],'ucode':us['ucode']}
  206. for p in dvls:
  207. p['vod'] = []
  208. for dm in ubqs:
  209. if p['UID'] == dm['uid']:
  210. if dm['endTime'] > nowTime:
  211. p['vod'].append(dm)
  212. p['preview'] = []
  213. for up in upqs:
  214. if p['UID'] == up['uid']:
  215. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  216. img_sign = bucket.sign_url('GET', obj, 300)
  217. p['preview'].append(img_sign)
  218. p_uid = p['UID']
  219. if p_uid in uv_dict:
  220. # 设备版本号
  221. p['uid_version'] = uv_dict[p_uid]['version']
  222. p['ucode'] = uv_dict[p_uid]['ucode']
  223. # 设备昵称 调用影子信息昵称,先阶段不可
  224. if uv_dict[p_uid]['nickname']:
  225. p['NickName'] = uv_dict[p_uid]['nickname']
  226. else:
  227. # 设备版本号
  228. p['uid_version'] = ''
  229. p['ucode'] = ''
  230. data.append(p)
  231. # 缓存时间为一个钟
  232. redisObj.set_data(key='uid_qs_'+userID, val=data, expire=3600)
  233. print('分页')
  234. items=[]
  235. for index, item in enumerate(data):
  236. if (page - 1) * line <= index:
  237. if index < page * line:
  238. item['View_Password']=self.encrypt_pwd(item['View_Password'])
  239. items.append(item)
  240. return response.json(0, items)
  241. else:
  242. # print('去缓存找数据')
  243. redis_value = redis_value.replace("'", '"')
  244. redis_value = redis_value.replace('"isShare": True', '"isShare": true')
  245. redis_value = redis_value.replace('"isShare": False', '"isShare": false')
  246. redis_value = redis_value.replace('"version": None', '"version": ""')
  247. try:
  248. redis_value = json.loads(redis_value)
  249. except Exception as e:
  250. print(repr(e))
  251. return response.json(0, {'data': redis_value})
  252. if NickName:
  253. # print('NickName搜索缓存')
  254. for index, item in enumerate(redis_value):
  255. if NickName ==item['NickName']:
  256. # 加密
  257. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  258. return response.json(0, item)
  259. if uid:
  260. # print('uid搜索缓存')
  261. for index, item in enumerate(redis_value):
  262. if uid == item['UID']:
  263. # 加密
  264. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  265. return response.json(0, item)
  266. items = []
  267. # print('缓存分页')
  268. for index, item in enumerate(redis_value):
  269. if (page - 1) * line <= index:
  270. if index < page * line:
  271. # 加密
  272. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  273. items.append(item)
  274. return response.json(0, items)
  275. else:
  276. return response.json(tko.code)
  277. # 加密
  278. def encrypt_pwd(self,userPwd):
  279. for i in range(1, 4):
  280. if i == 1:
  281. userPwd = RandomStr(3, False)+userPwd+RandomStr(3, False)
  282. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  283. if i == 2:
  284. userPwd = RandomStr(2, False)+str(userPwd)+RandomStr(2, False)
  285. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  286. if i == 3:
  287. userPwd = RandomStr(1, False)+str(userPwd)+RandomStr(1, False)
  288. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  289. return userPwd
  290. # 解密
  291. def decode_pwd(self, password):
  292. for i in range(1, 4):
  293. if i == 1:
  294. # 第一次先解密
  295. password = base64.b64decode(password)
  296. password = password.decode('utf-8')
  297. # 截去第一位,最后一位
  298. password = password[1:-1]
  299. if i == 2:
  300. # 第2次先解密
  301. password = base64.b64decode(password)
  302. password = password.decode('utf-8')
  303. # 去前2位,后2位
  304. password = password[2:-2]
  305. if i == 3:
  306. # 第3次先解密
  307. password = base64.b64decode(password)
  308. password = password.decode('utf-8')
  309. # 去前3位,后3位
  310. password = password[3:-3]
  311. return password