DetectController.py 48 KB

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