DetectController.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import os
  15. import time
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse
  20. from django.views.generic.base import View
  21. from pyfcm import FCMNotification
  22. from Object.RedisObject import RedisObject
  23. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN,\
  24. JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, \
  25. BASE_DIR, APNS_MODE, SERVER_TYPE
  26. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, SysMsgModel
  27. from Object.ETkObject import ETkObject
  28. from Object.RedisObject import RedisObject
  29. from Object.ResponseObject import ResponseObject
  30. from Object.TokenObject import TokenObject
  31. from Object.UidTokenObject import UidTokenObject
  32. from Service.CommonService import CommonService
  33. from Service.ModelService import ModelService
  34. '''
  35. http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  36. http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  37. http://www.dvema.com/detect/changeStatus?push_type=2&token_val=1a0018970a332cca935&appBundleId=com.ansjer.zccloud_ab&tz=+08.00&uid=HLK7EJ2VYLNHHUMG111A&status=1&m_code=AN02000025070000001207.zccloud_ab&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJsYW5nIjoiZW4iLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJ1c2VySUQiOiIxNTQ0ODM4MjMyOTczMTM4MDAxMzgwMDAiLCJleHAiOjE1ODQxNDc0NjN9.NjK91B26jZDtdmq8tW-8hXNQPqqDfo9Zwf_Jg6Uf7co&lang=cn&app_type=2
  38. http://127.0.0.1:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
  39. http://192.168.136.140:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
  40. detect/changeStatus
  41. '''
  42. class DetectControllerView(View):
  43. def get(self, request, *args, **kwargs):
  44. request.encoding = 'utf-8'
  45. operation = kwargs.get('operation')
  46. # self.ip = CommonService.get_ip_address(request)
  47. return self.validation(request.GET, operation)
  48. def post(self, request, *args, **kwargs):
  49. request.encoding = 'utf-8'
  50. operation = kwargs.get('operation')
  51. # self.ip = CommonService.get_ip_address(request)
  52. return self.validation(request.POST, operation)
  53. def validation(self, request_dict, operation):
  54. response = ResponseObject()
  55. if operation is None:
  56. return response.json(444, 'error path')
  57. token = request_dict.get('token', None)
  58. tko = TokenObject(token)
  59. if tko.code == 0:
  60. userID = tko.userID
  61. # 修改推送设置
  62. if operation == 'changeStatus':
  63. print("进入changeStatus")
  64. return self.do_change_status(userID, request_dict, response)
  65. # 查询推送信息
  66. elif operation == 'queryInfo':
  67. return self.do_query(request_dict, response, userID)
  68. # 更新推送延迟
  69. elif operation == 'updateInterval':
  70. return self.do_update_interval(userID, request_dict, response)
  71. else:
  72. return response.json(414)
  73. else:
  74. return response.json(tko.code)
  75. def do_query(self, request_dict, response, userID):
  76. page = int(request_dict.get('page', None))
  77. line = int(request_dict.get('line', None))
  78. if not page or not line:
  79. return response.json(444, 'page,line')
  80. startTime = request_dict.get('startTime', None)
  81. endTime = request_dict.get('endTime', None)
  82. eventType = request_dict.get('eventType', None)
  83. qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
  84. if startTime and endTime:
  85. qs = qs.filter(eventTime__range=(startTime, endTime))
  86. if eventType:
  87. qs = qs.filter(eventType=eventType)
  88. uids = request_dict.get('uids', None)
  89. if uids:
  90. uid_list = uids.split(',')
  91. qs = qs.filter(devUid__in=uid_list)
  92. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  93. uid_type_dict = {}
  94. for dv in dvqs:
  95. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  96. else:
  97. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  98. uid_type_dict = {}
  99. for dv in dvqs:
  100. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  101. # print(uid_type_dict)
  102. if not qs.exists():
  103. return response.json(0, {'datas': [], 'count': 0})
  104. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  105. 'receiveTime', 'is_st', 'addTime')
  106. count = qs.count()
  107. qr = qs[(page - 1) * line:page * line]
  108. res = []
  109. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  110. img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  111. # vod_time_list = []
  112. for p in qr:
  113. devUid = p['devUid']
  114. eventTime = p['eventTime']
  115. channel = p['Channel']
  116. if p['is_st'] == 1:
  117. p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  118. format(uid=devUid, channel=p['Channel'], time=eventTime), 300)
  119. p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  120. format(uid=devUid, channel=channel, time=eventTime), 300)]
  121. elif p['is_st'] == 2:
  122. # 列表装载回放时间戳标记
  123. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  124. .values("bucket__bucket", "bucket__endpoint")
  125. # print(vodqs)
  126. if vodqs.exists():
  127. bucket_name = vodqs[0]['bucket__bucket']
  128. endpoint = vodqs[0]['bucket__endpoint']
  129. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  130. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  131. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  132. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  133. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  134. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  135. p['img_list'] = [thumb0, thumb1, thumb2]
  136. elif p['is_st'] == 3:
  137. # 列表装载回放时间戳标记
  138. p['img_list'] = []
  139. for i in range(p['is_st']):
  140. img = img_bucket.sign_url('GET', '{uid}/{channel}/{time}_{st}.jpeg'.
  141. format(uid=devUid, channel=p['Channel'], time=eventTime, st=i), 300)
  142. p['img_list'].append(img)
  143. if devUid in uid_type_dict.keys():
  144. p['uid_type'] = uid_type_dict[devUid]['type']
  145. p['devNickName'] = uid_type_dict[devUid]['NickName']
  146. else:
  147. p['uid_type'] = ''
  148. res.append(p)
  149. return response.json(0, {'datas': res, 'count': count})
  150. def do_change_status(self, userID, request_dict, response):
  151. token_val = request_dict.get('token_val', None)
  152. appBundleId = request_dict.get('appBundleId', None)
  153. app_type = request_dict.get('app_type', None)
  154. push_type = request_dict.get('push_type', None)
  155. status = request_dict.get('status', None)
  156. m_code = request_dict.get('m_code', None)
  157. uid = request_dict.get('uid', None)
  158. # 设备语言
  159. lang = request_dict.get('lang', 'en')
  160. tz = request_dict.get('tz', '0')
  161. # 消息提醒功能新增
  162. # 如果传空上来,就默认为0
  163. if tz == '':
  164. tz = 0
  165. detect_group = request_dict.get('detect_group', None)
  166. interval = request_dict.get('interval', None)
  167. if not status:
  168. return response.json(444, 'status')
  169. # 关闭推送
  170. if not all([appBundleId, app_type, token_val, uid, m_code]):
  171. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  172. # 判断推送类型对应key是否存在
  173. print('push_type:', push_type)
  174. if push_type == '0':
  175. if appBundleId not in APNS_CONFIG.keys():
  176. return response.json(904)
  177. elif push_type == '1':
  178. if appBundleId not in FCM_CONFIG.keys():
  179. return response.json(904)
  180. elif push_type == '2':
  181. if appBundleId not in JPUSH_CONFIG.keys():
  182. return response.json(904)
  183. else:
  184. return response.json(173)
  185. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  186. status = int(status)
  187. # 获取用户区域
  188. # ip = self.ip
  189. # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  190. # area = ipInfo['country_name']
  191. # if area == 'China':
  192. # DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
  193. # else:
  194. # DETECT_PUSH_DOMAIN = 'en.push.dvema.com'
  195. nowTime = int(time.time())
  196. if dvqs.exists():
  197. # 修改状态
  198. dvqs.update(NotificationMode=status)
  199. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  200. # uid配置信息是否存在
  201. if uid_set_qs.exists():
  202. uid_set_id = uid_set_qs[0].id
  203. qs_data = {
  204. 'detect_status': status,
  205. 'updTime': nowTime,
  206. }
  207. if interval:
  208. qs_data['detect_interval'] = int(interval)
  209. if detect_group:
  210. qs_data['detect_group'] = detect_group
  211. print(qs_data)
  212. uid_set_qs.update(**qs_data)
  213. else:
  214. qs_data = {
  215. 'uid': uid,
  216. 'addTime': nowTime,
  217. 'updTime': nowTime,
  218. 'detect_status': status,
  219. }
  220. if interval:
  221. qs_data['detect_interval'] = int(interval)
  222. if detect_group:
  223. qs_data['detect_group'] = detect_group
  224. # 添加设备配置
  225. uid_set_qs = UidSetModel.objects.create(**qs_data)
  226. uid_set_id = uid_set_qs.id
  227. if status == 0:
  228. UidPushModel.objects.filter(uid_set__uid=uid).delete()
  229. # 状态为0的时候删除redis缓存数据
  230. self.do_delete_redis(uid)
  231. return response.json(0)
  232. elif status == 1:
  233. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  234. # ykey = '{uid}_redis_qs'.format(uid=uid)
  235. # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  236. # redisObj.del_data(key=ykey)
  237. if uid_push_qs.exists():
  238. uid_push_update_dict = {
  239. 'appBundleId': appBundleId,
  240. 'app_type': app_type,
  241. 'push_type': push_type,
  242. 'token_val': token_val,
  243. 'updTime': nowTime,
  244. 'lang': lang,
  245. 'tz': tz
  246. }
  247. uid_push_qs.update(**uid_push_update_dict)
  248. else:
  249. # uid_set_id = uid_set_qs[0].id
  250. uid_push_create_dict = {
  251. 'uid_set_id': uid_set_id,
  252. 'userID_id': userID,
  253. 'appBundleId': appBundleId,
  254. 'app_type': app_type,
  255. 'push_type': push_type,
  256. 'token_val': token_val,
  257. 'm_code': m_code,
  258. 'addTime': nowTime,
  259. 'updTime': nowTime,
  260. 'lang': lang,
  261. 'tz': tz
  262. }
  263. # 绑定设备推送
  264. UidPushModel.objects.create(**uid_push_create_dict)
  265. if interval:
  266. self.do_delete_redis(uid, int(interval))
  267. else:
  268. self.do_delete_redis(uid)
  269. # utko = UidTokenObject()
  270. # # right
  271. # utko.generate(data={'uid': uid})
  272. etkObj = ETkObject(etk='')
  273. etk = etkObj.encrypt(uid)
  274. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \
  275. format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  276. return response.json(0, {'detectUrl': detectUrl})
  277. else:
  278. return response.json(14)
  279. def do_delete_redis(self, uid, detect_interval=0):
  280. keyPattern = '{uid}*'.format(uid=uid)
  281. redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  282. keys = redisObj.get_keys(keyPattern)
  283. if keys:
  284. for key in keys:
  285. key = key.decode()
  286. if detect_interval == 0:
  287. redisObj.del_data(key=key)
  288. elif key.find('plt') != -1:
  289. continue
  290. elif key.find('flag') != -1:
  291. redisObj.set_data(key=key, val=1, expire=detect_interval)
  292. else:
  293. redisObj.del_data(key=key)
  294. def do_update_interval(self, userID, request_dict, response):
  295. uid = request_dict.get('uid', None)
  296. interval = request_dict.get('interval', None)
  297. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  298. if dvqs.exists():
  299. uid_set_qs = UidSetModel.objects. \
  300. filter(uid=uid, uidpushmodel__userID_id=userID)
  301. # redisObj = RedisObject(db=8)
  302. # redisObj.del_data(key='uid_qs_' + userID)
  303. if uid_set_qs.exists():
  304. uid_set_qs.update(interval=int(interval))
  305. else:
  306. return response.json(173)
  307. else:
  308. return response.json(0)
  309. '''
  310. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  311. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  312. '''
  313. # 移动侦测接口
  314. class NotificationView(View):
  315. def get(self, request, *args, **kwargs):
  316. request.encoding = 'utf-8'
  317. return self.validation(request.GET)
  318. def post(self, request, *args, **kwargs):
  319. request.encoding = 'utf-8'
  320. return self.validation(request.POST)
  321. def validation(self, request_dict):
  322. uidToken = request_dict.get('uidToken', None)
  323. etk = request_dict.get('etk', None)
  324. channel = request_dict.get('channel', '1')
  325. n_time = request_dict.get('n_time', None)
  326. event_type = request_dict.get('event_type', None)
  327. is_st = request_dict.get('is_st', None)
  328. # print("aaa")
  329. # return JsonResponse(0,safe=False)
  330. if not all([channel, n_time]):
  331. return JsonResponse(status=200, data={
  332. 'code': 444,
  333. 'msg': 'param is wrong'})
  334. if etk:
  335. eto = ETkObject(etk)
  336. uid = eto.uid
  337. if len(uid) != 20:
  338. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  339. else:
  340. utko = UidTokenObject(uidToken)
  341. uid = utko.UID
  342. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  343. # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
  344. ykey = '{uid}_redis_qs'.format(uid=uid)
  345. # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  346. is_sys_msg = self.is_sys_msg(int(event_type))
  347. if is_sys_msg is True:
  348. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  349. else:
  350. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  351. # 判断redisObj.get_data(key=pkey):不为空
  352. redisObj = RedisObject(db=6)
  353. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  354. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  355. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  356. # 一分钟外,推送开启状态
  357. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  358. # 暂时注销
  359. if have_pkey:
  360. if SERVER_TYPE != "Ansjer.formal_settings":
  361. res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
  362. else:
  363. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  364. return JsonResponse(status=200, data=res_data)
  365. # 数据库读取数据
  366. if have_ykey:
  367. redis_list = eval(redisObj.get_data(key=ykey))
  368. print(have_ykey)
  369. else:
  370. # 从数据库查询出来
  371. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid,uid_set__detect_status=1). \
  372. values('token_val', 'app_type', 'appBundleId','m_code',
  373. 'push_type', 'userID_id', 'userID__NickName',
  374. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  375. 'uid_set__channel')
  376. print(uid_push_qs)
  377. # 新建一个list接收数据
  378. redis_list = []
  379. # 把数据库数据追加进redis_list
  380. for qs in uid_push_qs:
  381. redis_list.append(qs)
  382. # 修改redis数据,并设置过期时间为10分钟
  383. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  384. if not redis_list:
  385. res_data = {'code': 404, 'msg': 'error !'}
  386. return JsonResponse(status=200, data=res_data)
  387. # 此时应该更新一下redis里面的dkey的有效时间
  388. # detect_interval = redis_list[0]['uid_set__detect_interval']
  389. # tmp_channel = redis_list[0]['uid_set__channel']
  390. # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
  391. if not redis_list:
  392. print("没有redi_list")
  393. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  394. return JsonResponse(status=200, data=res_data)
  395. # is_sys_msg = self.is_sys_msg(int(event_type))
  396. nickname = redis_list[0]['uid_set__nickname']
  397. detect_interval = redis_list[0]['uid_set__detect_interval']
  398. detect_group = redis_list[0]['uid_set__detect_group']
  399. now_time = int(time.time())
  400. if not nickname:
  401. nickname = uid
  402. if detect_group is not None:
  403. if have_dkey:
  404. detect_med_type = 1 # 1为存库不推送
  405. else:
  406. detect_med_type = 2 # 为2的话,既推送,又存库
  407. # detect_group=0允许全部推送的时候
  408. if detect_group == '0'or detect_group == '':
  409. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  410. else:
  411. detect_group_list = detect_group.split(',')
  412. if event_type in detect_group_list:
  413. if detect_interval < 60:
  414. detect_interval = 60
  415. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  416. # 改为1秒
  417. # 如果不是正式
  418. if SERVER_TYPE!="Ansjer.formal_settings":
  419. redisObj.set_data(key=pkey, val=1, expire=10)
  420. else:
  421. redisObj.set_data(key=pkey, val=1, expire=60)
  422. # 打印have_ykey
  423. # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
  424. # 旧模式并且没有pkey,重新创建一个
  425. if not detect_group and not have_pkey:
  426. # 设置推送时间为60秒一次
  427. # 如果不是正式
  428. if SERVER_TYPE != "Ansjer.formal_settings":
  429. redisObj.set_data(key=pkey, val=1, expire=10)
  430. else:
  431. redisObj.set_data(key=pkey, val=1, expire=60)
  432. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  433. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  434. kwag_args = {
  435. 'uid': uid,
  436. 'channel': channel,
  437. 'event_type': event_type,
  438. 'n_time': n_time,
  439. # 'appBundleId': appBundleId,
  440. # 'token_val': token_val,
  441. # 'msg_title': msg_title,
  442. # 'msg_text': msg_text
  443. }
  444. eq_list = []
  445. sys_msg_list = []
  446. userID_ids = []
  447. do_apns_code = ''
  448. do_fcm_code = ''
  449. do_jpush_code = ''
  450. for up in redis_list:
  451. push_type = up['push_type']
  452. appBundleId = up['appBundleId']
  453. token_val = up['token_val']
  454. lang = up['lang']
  455. tz = up['tz']
  456. if tz is None or tz == '':
  457. tz = 0
  458. # 发送标题
  459. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  460. # 发送内容
  461. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  462. event_type=event_type)
  463. kwag_args['appBundleId'] = appBundleId
  464. kwag_args['token_val'] = token_val
  465. kwag_args['msg_title'] = msg_title
  466. kwag_args['msg_text'] = msg_text
  467. push_server_status = 0
  468. #推送
  469. if detect_med_type == 2 or detect_med_type == 0:
  470. if push_type == 0: # ios apns
  471. print('do_apns')
  472. # self.do_apns(**kwag_args)
  473. do_apns_code = self.do_apns(**kwag_args)
  474. if isinstance(do_apns_code, int):
  475. push_server_status = do_apns_code
  476. else:
  477. push_server_status = 400
  478. elif push_type == 1: # android gcm
  479. print('do_fcm')
  480. do_fcm_code = self.do_fcm(**kwag_args)
  481. push_server_status = 200
  482. elif push_type == 2: # android jpush
  483. print('do_jpush')
  484. do_jpush_code = self.do_jpush(**kwag_args)
  485. push_server_status = do_jpush_code
  486. # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
  487. if detect_med_type == 1:
  488. do_apns_code = '只存库不推送'
  489. do_fcm_code = '只存库不推送'
  490. do_jpush_code = '只存库不推送'
  491. # 以下是存库
  492. userID_id = up["userID_id"]
  493. int_is_st = int(is_st)
  494. if userID_id not in userID_ids:
  495. eq_list.append(Equipment_Info(
  496. userID_id=userID_id,
  497. eventTime=n_time,
  498. eventType=event_type,
  499. devUid=uid,
  500. devNickName=nickname,
  501. Channel=channel,
  502. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  503. is_st=int_is_st,
  504. receiveTime=n_time,
  505. addTime=now_time,
  506. storage_location=1
  507. ))
  508. if is_sys_msg:
  509. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  510. event_type=event_type, is_sys=1)
  511. sys_msg_list.append(SysMsgModel(
  512. userID_id=userID_id,
  513. msg=sys_msg_text,
  514. addTime=now_time,
  515. updTime=now_time,
  516. uid=uid,
  517. eventType=event_type))
  518. userID_ids.append(userID_id)
  519. if is_sys_msg:
  520. SysMsgModel.objects.bulk_create(sys_msg_list)
  521. Equipment_Info.objects.bulk_create(eq_list)
  522. if is_st == '0' or is_st == '2':
  523. print("is_st=0or2")
  524. for up in redis_list:
  525. if up['push_type'] == 0: # ios apns
  526. up['do_apns_code'] = do_apns_code
  527. elif up['push_type'] == 1: # android gcm
  528. up['do_fcm_code'] = do_fcm_code
  529. elif up['push_type'] == 2: # android jpush
  530. up['do_jpush_code'] = do_jpush_code
  531. up['test_or_www'] = SERVER_TYPE
  532. del up['push_type']
  533. del up['userID_id']
  534. del up['userID__NickName']
  535. del up['lang']
  536. del up['tz']
  537. del up['uid_set__nickname']
  538. del up['uid_set__detect_interval']
  539. del up['uid_set__detect_group']
  540. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2' ,'re_list':redis_list})
  541. elif is_st == '1':
  542. print("is_st=1")
  543. # Endpoint以杭州为例,其它Region请按实际情况填写。
  544. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  545. # 设置此签名URL在60秒内有效。
  546. url = bucket.sign_url('PUT', obj, 7200)
  547. for up in redis_list:
  548. up['do_apns_code'] = do_apns_code
  549. up['do_fcm_code'] = do_fcm_code
  550. up['do_jpush_code'] = do_jpush_code
  551. up['test_or_www'] = SERVER_TYPE
  552. del up['push_type']
  553. del up['userID_id']
  554. del up['userID__NickName']
  555. del up['lang']
  556. del up['tz']
  557. del up['uid_set__nickname']
  558. del up['uid_set__detect_interval']
  559. del up['uid_set__detect_group']
  560. # 不是正式服务器
  561. if SERVER_TYPE != "Ansjer.formal_settings":
  562. res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
  563. else:
  564. # 是正式服务器的时候
  565. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  566. return JsonResponse(status=200, data=res_data)
  567. elif is_st == '3':
  568. print("is_st=3")
  569. # 人形检测带动图
  570. # Endpoint以杭州为例,其它Region请按实际情况填写。
  571. img_url_list = []
  572. for i in range(int(is_st)):
  573. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  574. format(uid=uid, channel=channel, filename=n_time, st=i)
  575. # 设置此签名URL在60秒内有效。
  576. url = bucket.sign_url('PUT', obj, 7200)
  577. img_url_list.append(url)
  578. for up in redis_list:
  579. up['do_apns_code'] = do_apns_code
  580. up['do_fcm_code'] = do_fcm_code
  581. up['do_jpush_code'] = do_jpush_code
  582. up['test_or_www'] = SERVER_TYPE
  583. del up['push_type']
  584. del up['userID_id']
  585. del up['userID__NickName']
  586. del up['lang']
  587. del up['tz']
  588. del up['uid_set__nickname']
  589. del up['uid_set__detect_interval']
  590. del up['uid_set__detect_group']
  591. # 不是正式服务器
  592. if SERVER_TYPE != "Ansjer.formal_settings":
  593. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
  594. else:
  595. # 是正式服务器的时候
  596. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  597. return JsonResponse(status=200, data=res_data)
  598. def get_msg_title(self, appBundleId, nickname):
  599. package_title_config = {
  600. 'com.ansjer.customizedd_a': 'DVS',
  601. 'com.ansjer.zccloud_a': 'ZosiSmart',
  602. 'com.ansjer.zccloud_ab': '周视',
  603. 'com.ansjer.adcloud_a': 'ADCloud',
  604. 'com.ansjer.adcloud_ab': 'ADCloud',
  605. 'com.ansjer.accloud_a': 'ACCloud',
  606. 'com.ansjer.loocamccloud_a': 'Loocam',
  607. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  608. 'com.ansjer.customizedb_a': 'COCOONHD',
  609. 'com.ansjer.customizeda_a': 'Guardian365',
  610. 'com.ansjer.customizedc_a': 'PatrolSecure',
  611. }
  612. if appBundleId in package_title_config.keys():
  613. return package_title_config[appBundleId] + '(' + nickname + ')'
  614. else:
  615. return nickname
  616. def is_sys_msg(self, event_type):
  617. event_type_list = [702, 703, 704]
  618. if event_type in event_type_list:
  619. return True
  620. return False
  621. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  622. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  623. etype = int(event_type)
  624. if lang == 'cn':
  625. if etype == 704:
  626. msg_type = '电量过低'
  627. elif etype == 702:
  628. msg_type = '摄像头休眠'
  629. elif etype == 703:
  630. msg_type = '摄像头唤醒'
  631. else:
  632. msg_type = ''
  633. if is_sys:
  634. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  635. else:
  636. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  637. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  638. else:
  639. if etype == 704:
  640. msg_type = 'Low battery'
  641. elif etype == 702:
  642. msg_type = 'Camera sleep'
  643. elif etype == 703:
  644. msg_type = 'Camera wake'
  645. else:
  646. msg_type = ''
  647. if is_sys:
  648. send_text = '{msg_type} channel:{channel}'. \
  649. format(msg_type=msg_type, channel=channel)
  650. else:
  651. send_text = '{msg_type} channel:{channel} date:{date}'. \
  652. format(msg_type=msg_type, channel=channel, date=n_date)
  653. return send_text
  654. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  655. msg_title, msg_text):
  656. app_key = JPUSH_CONFIG[appBundleId]['Key']
  657. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  658. # 此处换成各自的app_key和master_secre
  659. _jpush = jpush.JPush(app_key, master_secret)
  660. push = _jpush.create_push()
  661. # if you set the logging level to "DEBUG",it will show the debug logging.
  662. # _jpush.set_logging("DEBUG")
  663. # push.audience = jpush.all_
  664. push.audience = jpush.registration_id(token_val)
  665. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  666. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  667. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  668. big_text=msg_text, title=msg_title,
  669. extras=push_data)
  670. push.notification = jpush.notification(android=android)
  671. push.platform = jpush.all_
  672. res = push.send()
  673. print(res)
  674. return res.status_code
  675. # try:
  676. # res = push.send()
  677. # print(res)
  678. # except Exception as e:
  679. # print("jpush fail")
  680. # print("Exception")
  681. # print(repr(e))
  682. # return
  683. # else:
  684. # print("jpush success")
  685. # return
  686. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  687. try:
  688. serverKey = FCM_CONFIG[appBundleId]
  689. except Exception as e:
  690. return 'serverKey abnormal'
  691. push_service = FCMNotification(api_key=serverKey)
  692. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  693. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  694. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  695. message_body=msg_text, data_message=data,
  696. extra_kwargs={
  697. 'default_vibrate_timings': True,
  698. 'default_sound': True,
  699. 'default_light_settings': True
  700. })
  701. print('fcm push ing')
  702. print(result)
  703. return result
  704. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  705. msg_text):
  706. try:
  707. cli = apns2.APNSClient(mode=APNS_MODE,
  708. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  709. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  710. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  711. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  712. payload = apns2.Payload(alert=alert, custom=push_data)
  713. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  714. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  715. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  716. print(res.status_code)
  717. # 200, 推送成功。
  718. #   400, 请求有问题。
  719. #   403, 证书或Token有问题。
  720. #   405, 请求方式不正确, 只支持POST请求
  721. #   410, 设备的Token与证书不一致
  722. if res.status_code == 200:
  723. return res.status_code
  724. else:
  725. print('apns push fail')
  726. print(res.reason)
  727. return res.status_code
  728. except (ValueError, ArithmeticError):
  729. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  730. except Exception as e:
  731. print(repr(e))
  732. return repr(e)
  733. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  734. if channel == 0:
  735. channel = 17
  736. else:
  737. channel += 1
  738. for i in range(1, channel):
  739. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  740. if tmpDKey is not False:
  741. llt = redisObject.get_ttl(tmpDKey)
  742. if llt > detect_interval:
  743. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  744. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  745. if tmpDKey is not False:
  746. llt = redisObject.get_ttl(tmpDKey)
  747. if llt > detect_interval:
  748. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  749. # 新增 把代码封装以便后面分侦测类型
  750. def detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st):
  751. redisObj = RedisObject(db=6)
  752. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  753. if redisObj.get_data(key=pkey):
  754. res_data = {'code': 0, 'msg': 'success,!'}
  755. return JsonResponse(status=200, data=res_data)
  756. else:
  757. # 设置推送间隔60秒一次
  758. redisObj.set_data(key=pkey, val=1, expire=60)
  759. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  760. values('token_val', 'app_type', 'appBundleId',
  761. 'push_type', 'userID_id', 'userID__NickName',
  762. 'lang', 'tz', 'uid_set__nickname')
  763. if uid_push_qs.exists():
  764. nickname = uid_push_qs[0]['uid_set__nickname']
  765. if not nickname:
  766. nickname = uid
  767. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  768. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  769. for up in uid_push_qs:
  770. push_type = up['push_type']
  771. # ios apns
  772. print(push_type)
  773. if push_type == 0:
  774. self.do_apns(request_dict, up, response, uid, channel, nickname)
  775. # android gcm
  776. elif push_type == 1:
  777. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  778. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  779. # android jpush
  780. elif push_type == 2:
  781. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  782. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  783. # 需求不一样,所以这么做的
  784. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  785. if is_st == '0' or is_st == '2':
  786. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  787. elif is_st == '1':
  788. # Endpoint以杭州为例,其它Region请按实际情况填写。
  789. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  790. # 设置此签名URL在60秒内有效。
  791. url = bucket.sign_url('PUT', obj, 7200)
  792. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  793. return JsonResponse(status=200, data=res_data)
  794. elif is_st == '3':
  795. # 人形检测带动图
  796. # Endpoint以杭州为例,其它Region请按实际情况填写。
  797. img_url_list = []
  798. for i in range(int(is_st)):
  799. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  800. format(uid=uid, channel=channel, filename=n_time, st=i)
  801. # 设置此签名URL在60秒内有效。
  802. url = bucket.sign_url('PUT', obj, 7200)
  803. img_url_list.append(url)
  804. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  805. return JsonResponse(status=200, data=res_data)
  806. else:
  807. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  808. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  809. #
  810. qs_list = []
  811. nowTime = int(time.time())
  812. # 设备昵称
  813. userID_ids = []
  814. for dv in uaqs:
  815. userID_id = dv["userID_id"]
  816. if userID_id not in userID_ids:
  817. if dv['uid_set__nickname']:
  818. uid_nickname = dv['uid_set__nickname']
  819. else:
  820. uid_nickname = uid
  821. add_data = {
  822. 'userID_id': dv["userID_id"],
  823. 'eventTime': n_time,
  824. 'eventType': event_type,
  825. 'devUid': uid,
  826. 'devNickName': uid_nickname,
  827. 'Channel': channel,
  828. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  829. 'is_st': int(is_st),
  830. 'receiveTime': n_time,
  831. 'addTime': nowTime
  832. }
  833. qs_list.append(Equipment_Info(**add_data))
  834. userID_ids.append(userID_id)
  835. if qs_list:
  836. print(1)
  837. Equipment_Info.objects.bulk_create(qs_list)
  838. return True
  839. else:
  840. return False
  841. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  842. # 移动侦测接口
  843. class PushNotificationView(View):
  844. def get(self, request, *args, **kwargs):
  845. request.encoding = 'utf-8'
  846. # operation = kwargs.get('operation')
  847. return self.validation(request.GET)
  848. def post(self, request, *args, **kwargs):
  849. request.encoding = 'utf-8'
  850. # operation = kwargs.get('operation')
  851. return self.validation(request.POST)
  852. def validation(self, request_dict):
  853. etk = request_dict.get('etk', None)
  854. channel = request_dict.get('channel', '1')
  855. n_time = request_dict.get('n_time', None)
  856. event_type = request_dict.get('event_type', None)
  857. is_st = request_dict.get('is_st', None)
  858. eto = ETkObject(etk)
  859. uid = eto.uid
  860. if len(uid) == 20:
  861. redisObj = RedisObject(db=6)
  862. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  863. pkey = '{uid}_ptl'.format(uid=uid)
  864. ykey = '{uid}_redis_qs'.format(uid=uid)
  865. if redisObj.get_data(key=pkey):
  866. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  867. return JsonResponse(status=200, data=res_data)
  868. else:
  869. redisObj.set_data(key=pkey, val=1, expire=60)
  870. ##############
  871. redis_data = redisObj.get_data(key=ykey)
  872. if redis_data:
  873. redis_list = eval(redis_data)
  874. else:
  875. # 设置推送时间为60秒一次
  876. redisObj.set_data(key=pkey, val=1, expire=60)
  877. print("从数据库查到数据")
  878. # 从数据库查询出来
  879. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  880. values('token_val', 'app_type', 'appBundleId',
  881. 'push_type', 'userID_id', 'lang','m_code',
  882. 'tz', 'uid_set__nickname')
  883. # 新建一个list接收数据
  884. redis_list = []
  885. # 把数据库数据追加进redis_list
  886. for qs in uid_push_qs:
  887. redis_list.append(qs)
  888. # 修改redis数据,并设置过期时间为10分钟
  889. if redis_list:
  890. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  891. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  892. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  893. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  894. if is_st == '0' or is_st == '2':
  895. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  896. elif is_st == '1':
  897. # Endpoint以杭州为例,其它Region请按实际情况填写。
  898. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  899. # 设置此签名URL在60秒内有效。
  900. url = bucket.sign_url('PUT', obj, 7200)
  901. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  902. return JsonResponse(status=200, data=res_data)
  903. elif is_st == '3':
  904. # 人形检测带动图
  905. img_url_list = []
  906. for i in range(int(is_st)):
  907. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  908. format(uid=uid, channel=channel, filename=n_time, st=i)
  909. # 设置此签名URL在60秒内有效。
  910. url = bucket.sign_url('PUT', obj, 7200)
  911. img_url_list.append(url)
  912. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  913. return JsonResponse(status=200, data=res_data)
  914. else:
  915. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  916. else:
  917. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  918. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  919. now_time = int(time.time())
  920. # 设备昵称
  921. userID_ids = []
  922. sys_msg_list = []
  923. is_sys_msg = self.is_sys_msg(int(event_type))
  924. is_st = int(is_st)
  925. eq_list = []
  926. nickname = uaqs[0]['uid_set__nickname']
  927. if not nickname:
  928. nickname = uid
  929. for ua in uaqs:
  930. lang = ua['lang']
  931. tz = ua['tz']
  932. userID_id = ua["userID_id"]
  933. if userID_id not in userID_ids:
  934. eq_list.append(Equipment_Info(
  935. userID_id=userID_id,
  936. eventTime=n_time,
  937. eventType=event_type,
  938. devUid=uid,
  939. devNickName=nickname,
  940. Channel=channel,
  941. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  942. is_st=is_st,
  943. receiveTime=n_time,
  944. addTime=now_time,
  945. storage_location=1
  946. ))
  947. if is_sys_msg:
  948. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  949. event_type=event_type, is_sys=1)
  950. sys_msg_list.append(SysMsgModel(
  951. userID_id=userID_id,
  952. msg=sys_msg_text,
  953. addTime=now_time,
  954. updTime=now_time,
  955. uid=uid,
  956. eventType=event_type))
  957. if eq_list:
  958. print('eq_list')
  959. Equipment_Info.objects.bulk_create(eq_list)
  960. if is_sys_msg:
  961. print('sys_msg')
  962. SysMsgModel.objects.bulk_create(sys_msg_list)
  963. return True
  964. def is_sys_msg(self, event_type):
  965. event_type_list = [702, 703, 704]
  966. if event_type in event_type_list:
  967. return True
  968. return False
  969. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  970. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  971. etype = int(event_type)
  972. if lang == 'cn':
  973. if etype == 704:
  974. msg_type = '电量过低'
  975. elif etype == 702:
  976. msg_type = '摄像头休眠'
  977. elif etype == 703:
  978. msg_type = '摄像头唤醒'
  979. else:
  980. msg_type = ''
  981. if is_sys:
  982. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  983. else:
  984. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  985. else:
  986. if etype == 704:
  987. msg_type = 'Low battery'
  988. elif etype == 702:
  989. msg_type = 'Camera sleep'
  990. elif etype == 703:
  991. msg_type = 'Camera wake'
  992. else:
  993. msg_type = ''
  994. if is_sys:
  995. send_text = '{msg_type} channel:{channel}'. \
  996. format(msg_type=msg_type, channel=channel)
  997. else:
  998. send_text = '{msg_type} channel:{channel} date:{date}'. \
  999. format(msg_type=msg_type, channel=channel, date=n_date)
  1000. return send_text