DetectControllerV2.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. import datetime
  2. import json
  3. import time
  4. import boto3
  5. import botocore
  6. import oss2
  7. import redis
  8. from botocore import client
  9. from django.http import JsonResponse
  10. from django.views.generic.base import View
  11. from obs import ObsClient
  12. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  13. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, LOGGER, ALGORITHM_COMBO_TYPES, \
  14. HUAWEICLOUD_AK, HUAWEICLOUD_SK, HUAWEICLOUD_OBS_SERVER, HUAWEICLOUD_PUSH_BUKET
  15. from Ansjer.config import PUSH_BUCKET, CONFIG_INFO, CONFIG_CN, CONFIG_EUR, CONFIG_US
  16. from Ansjer.config import PUSH_REDIS_ADDRESS
  17. from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  18. AiService, VodBucketModel
  19. from Object.ETkObject import ETkObject
  20. from Object.OCIObjectStorage import OCIObjectStorage
  21. from Object.RedisObject import RedisObject
  22. from Object.ResponseObject import ResponseObject
  23. from Object.TokenObject import TokenObject
  24. from Object.utils import LocalDateTimeUtil
  25. from Service.CommonService import CommonService
  26. from Service.EquipmentInfoService import EquipmentInfoService
  27. from Service.VodHlsService import SplitVodHlsObject
  28. class DetectControllerViewV2(View):
  29. def get(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. api_version = kwargs.get('apiVersion')
  33. # self.ip = CommonService.get_ip_address(request)
  34. return self.validation(request, request.GET, operation, api_version)
  35. def post(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. operation = kwargs.get('operation')
  38. api_version = kwargs.get('apiVersion')
  39. # self.ip = CommonService.get_ip_address(request)
  40. return self.validation(request, request.POST, operation, api_version)
  41. def validation(self, request, request_dict, operation, api_version):
  42. response = ResponseObject()
  43. if operation is None:
  44. return response.json(444, 'error path')
  45. token = request_dict.get('token', None)
  46. lang = request_dict.get('lang', None)
  47. if lang:
  48. response = ResponseObject(lang)
  49. tko = TokenObject(token)
  50. if tko.code == 0:
  51. userID = tko.userID
  52. # 修改推送设置
  53. if operation == 'changeStatus':
  54. return self.do_change_status(userID, request_dict, response)
  55. # 查询推送信息
  56. elif operation == 'queryInfo':
  57. return self.do_query(request_dict, response, userID)
  58. # 点击推送信息跳转到列表信息
  59. elif operation == 'transferInfo':
  60. return self.do_transfer(request_dict, response, userID)
  61. # 更新推送延迟
  62. elif operation == 'updateInterval':
  63. return self.do_update_interval(userID, request_dict, response)
  64. # 消息提醒配置
  65. elif operation == 'messageNotificationSet':
  66. return self.message_notification_set(api_version, request_dict, response)
  67. else:
  68. return response.json(414)
  69. else:
  70. return response.json(tko.code)
  71. @classmethod
  72. def message_notification_set(cls, api_version, request_dict, response):
  73. """
  74. 消息提醒设置
  75. @param api_version: 版本号
  76. @param request_dict: 参数json格式
  77. @param response: 响应数据
  78. """
  79. try:
  80. msg_data = request_dict.get('msgData', None)
  81. uid = request_dict.get('uid', None)
  82. LOGGER.info('*****DetectControllerViewV2.message_notification_set*****api_version:{},uid:{}'
  83. .format(api_version, uid))
  84. if not all([msg_data, uid]):
  85. return response.json(444)
  86. data = json.loads(msg_data)
  87. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  88. if not uid_set_qs.exists():
  89. return response.json(173)
  90. uid_set_qs.update(msg_notify=data, updTime=int(time.time()))
  91. return response.json(0)
  92. except Exception as e:
  93. LOGGER.info('*****DetectControllerViewV2.message_notification_set:errLine:{}, errMsg:{}'
  94. .format(e.__traceback__.tb_lineno, repr(e)))
  95. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  96. def do_change_status(self, userID, request_dict, response):
  97. token_val = request_dict.get('token_val', None)
  98. jg_token_val = request_dict.get('jg_token_val', '')
  99. appBundleId = request_dict.get('appBundleId', None)
  100. app_type = request_dict.get('app_type', None)
  101. push_type = request_dict.get('push_type', None)
  102. status = request_dict.get('status', None)
  103. m_code = request_dict.get('m_code', None)
  104. uid = request_dict.get('uid', None)
  105. lang = request_dict.get('lang', 'en')
  106. tz = request_dict.get('tz', '0')
  107. company_secrete = request_dict.get('company_secrete', None)
  108. region = request_dict.get('region', None) # app必须传:1:国外,2:国内
  109. electricity_status = request_dict.get('electricity_status', None)
  110. domain_name = request_dict.get('domain_name', None)
  111. if not region:
  112. return response.json(444, 'region')
  113. region = int(region)
  114. # 消息提醒功能新增
  115. # 如果传空上来,就默认为0
  116. if tz == '':
  117. tz = 0
  118. else:
  119. tz = tz.replace("GMT", "")
  120. detect_group = request_dict.get('detect_group', None)
  121. interval = request_dict.get('interval', None)
  122. if not status and not electricity_status:
  123. return response.json(444, 'status and electricity_status')
  124. if not company_secrete:
  125. return response.json(444, 'company_secrete')
  126. company = CompanyModel.objects.filter(secret=company_secrete)
  127. if not company.exists():
  128. return response.json(444, 'company_secrete')
  129. # 关闭推送
  130. if not all([appBundleId, app_type, token_val, uid, m_code]):
  131. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  132. try:
  133. # 判断用户是否拥有设备
  134. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  135. if not device_info_qs.exists():
  136. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  137. if not device_info_qs.exists():
  138. return response.json(14)
  139. # 更新或创建uid_set数据
  140. nowTime = int(time.time())
  141. uid_set_data = {
  142. 'device_type': device_info_qs[0].Type
  143. }
  144. # 设置开关状态,0:关闭,1:开启
  145. if status:
  146. status = int(status)
  147. uid_set_data['detect_status'] = status
  148. device_info_qs.update(NotificationMode=status)
  149. # 检测类型
  150. if detect_group:
  151. uid_set_data['detect_group'] = detect_group
  152. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  153. # 设置消息推送间隔
  154. if interval:
  155. interval = int(interval)
  156. if uid_set_qs.exists() and status == 1 and uid_set_qs.first().detect_status == 0:
  157. interval = 60
  158. uid_set_data['detect_interval'] = interval
  159. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  160. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  161. if ai_service_qs.exists():
  162. topic_name = 'ansjer/generic/{}'.format(uid)
  163. msg = {
  164. 'commandType': 'AIState',
  165. 'payload': {
  166. 'IntervalTime': interval
  167. }
  168. }
  169. CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  170. if uid_set_qs.exists():
  171. msg_data = uid_set_qs.first().msg_notify
  172. if status == 0 and msg_data:
  173. msg_data['appPush'] = -1
  174. uid_set_data['msg_notify'] = msg_data
  175. elif status == 1 and uid_set_qs.first().detect_status == 0:
  176. uid_set_data['detect_interval'] = 60
  177. msg_data = {'appPush': 1,
  178. 'pushTime': {'allDay': 1, 'repeat': 127, 'endTime': 0, 'timeZone': '+08.00',
  179. 'startTime': 0},
  180. 'eventTypes': {'device': ALGORITHM_COMBO_TYPES, 'aiCloud': 1}
  181. }
  182. uid_set_data['msg_notify'] = msg_data
  183. uid_set_id = uid_set_qs[0].id
  184. uid_set_data['updTime'] = nowTime
  185. uid_set_qs.update(**uid_set_data)
  186. else:
  187. uid_set_data['uid'] = uid
  188. uid_set_data['addTime'] = nowTime
  189. uid_set_data['updTime'] = nowTime
  190. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  191. uid_set_id = uid_set_qs.id
  192. # 初始化UidPushModel推送表
  193. if electricity_status:
  194. if m_code != 0 and m_code != '0':
  195. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  196. if uid_push_qs.exists():
  197. uid_push_update_dict = {
  198. 'appBundleId': appBundleId,
  199. 'app_type': app_type,
  200. 'push_type': push_type,
  201. 'token_val': token_val,
  202. 'jg_token_val': jg_token_val,
  203. 'updTime': nowTime,
  204. 'lang': lang,
  205. 'tz': tz
  206. }
  207. uid_push_qs.update(**uid_push_update_dict)
  208. else:
  209. uid_push_create_dict = {
  210. 'uid_set_id': uid_set_id,
  211. 'userID_id': userID,
  212. 'appBundleId': appBundleId,
  213. 'app_type': app_type,
  214. 'push_type': push_type,
  215. 'token_val': token_val,
  216. 'jg_token_val': jg_token_val,
  217. 'm_code': m_code,
  218. 'addTime': nowTime,
  219. 'updTime': nowTime,
  220. 'lang': lang,
  221. 'tz': tz
  222. }
  223. # 绑定设备推送
  224. UidPushModel.objects.create(**uid_push_create_dict)
  225. return response.json(0)
  226. if status == 0:
  227. # 状态为0的时候删除redis缓存数据
  228. self.do_delete_redis(uid)
  229. return response.json(0)
  230. elif status == 1:
  231. if m_code != 0 and m_code != '0':
  232. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  233. if uid_push_qs.exists():
  234. uid_push_update_dict = {
  235. 'appBundleId': appBundleId,
  236. 'app_type': app_type,
  237. 'push_type': push_type,
  238. 'token_val': token_val,
  239. 'jg_token_val': jg_token_val,
  240. 'updTime': nowTime,
  241. 'lang': lang,
  242. 'tz': tz
  243. }
  244. uid_push_qs.update(**uid_push_update_dict)
  245. else:
  246. uid_push_create_dict = {
  247. 'uid_set_id': uid_set_id,
  248. 'userID_id': userID,
  249. 'appBundleId': appBundleId,
  250. 'app_type': app_type,
  251. 'push_type': push_type,
  252. 'token_val': token_val,
  253. 'jg_token_val': jg_token_val,
  254. 'm_code': m_code,
  255. 'addTime': nowTime,
  256. 'updTime': nowTime,
  257. 'lang': lang,
  258. 'tz': tz
  259. }
  260. # 绑定设备推送
  261. UidPushModel.objects.create(**uid_push_create_dict)
  262. if interval:
  263. self.do_delete_redis(uid, interval)
  264. else:
  265. self.do_delete_redis(uid)
  266. etkObj = ETkObject(etk='')
  267. etk = etkObj.encrypt(uid)
  268. if company_secrete == 'MTEyMTNB':
  269. d_type = device_info_qs[0].Type
  270. url = DETECT_PUSH_DOMAIN
  271. if d_type in [103, 26]:
  272. url = DETECT_PUSH_DOMAINS
  273. urls = DETECT_PUSH_DOMAINS
  274. else:
  275. url = DETECT_PUSH_DOMAIN_JIUAN
  276. urls = DETECT_PUSH_DOMAINS_JIUAN
  277. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  278. url = 'http://push.zositeche.com/'
  279. urls = 'https://push.zositeche.com/'
  280. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  281. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  282. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  283. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  284. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  285. else:
  286. return response.json(173)
  287. except Exception as e:
  288. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  289. def do_delete_redis(self, uid, detect_interval=0):
  290. keyPattern = '{uid}*'.format(uid=uid)
  291. redisObj = RedisObject()
  292. keys = redisObj.get_keys(keyPattern)
  293. if keys:
  294. for key in keys:
  295. key = key.decode()
  296. if detect_interval == 0:
  297. redisObj.del_data(key=key)
  298. elif key.find('plt') != -1:
  299. continue
  300. elif key.find('flag') != -1:
  301. redisObj.set_data(key=key, val=1, expire=detect_interval)
  302. else:
  303. redisObj.del_data(key=key)
  304. def do_query(self, request_dict, response, userID):
  305. page = int(request_dict.get('page', None))
  306. line = int(request_dict.get('line', None))
  307. start_time = request_dict.get('startTime', None)
  308. end_time = request_dict.get('endTime', None)
  309. event_type = request_dict.get('eventType', None)
  310. region = int(request_dict.get('region', None))
  311. uids = request_dict.get('uids', None)
  312. try:
  313. uid_list = []
  314. if uids:
  315. uid_list = uids.split(',')
  316. if not start_time and not end_time:
  317. # 默认查询近七天内数据
  318. end_time = int(time.time())
  319. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  320. equipment_info_qs, count = EquipmentInfoService. \
  321. union_equipment_info(userID, uid_list, event_type, start_time, end_time, page, line)
  322. # 查询设备类型,昵称
  323. if uid_list:
  324. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  325. uid_type_dict = {}
  326. for dv in dvqs:
  327. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  328. else:
  329. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  330. uid_type_dict = {}
  331. for dv in dvqs:
  332. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  333. # 没有推送数据返回空列表
  334. if count == 0:
  335. return response.json(0, {'datas': [], 'count': 0})
  336. res = []
  337. # 华为云
  338. obs_client = ObsClient(
  339. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  340. # 阿里云
  341. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  342. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  343. # aws
  344. aws_s3 = boto3.client(
  345. 's3',
  346. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  347. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  348. config=botocore.client.Config(signature_version='s3v4'),
  349. region_name='us-east-1'
  350. )
  351. aws_s3_cn = boto3.client(
  352. 's3',
  353. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  354. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  355. config=botocore.client.Config(signature_version='s3v4'),
  356. region_name='cn-northwest-1'
  357. )
  358. # oci
  359. # 国内生产环境默认不实例OCI对象
  360. oci = self.get_oci_client()
  361. redis_obj = RedisObject(3)
  362. # ai消息标识所有组合标签
  363. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  364. for equipment_info in equipment_info_qs:
  365. uid = equipment_info['devUid']
  366. event_time = equipment_info['eventTime']
  367. channel = equipment_info['Channel']
  368. storage_location = equipment_info['storage_location']
  369. border_coords = equipment_info['borderCoords']
  370. event_type = equipment_info['eventType']
  371. event_tag = equipment_info['eventTag']
  372. if equipment_info['is_st'] == 1:
  373. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  374. if storage_location == 1: # 阿里云oss
  375. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  376. elif storage_location == 5: # 华为云
  377. create_res = obs_client.createSignedUrl(
  378. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  379. img_url = create_res.signedUrl
  380. elif storage_location in [3, 4]:
  381. prefix_name = f'{uid}/'
  382. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  383. if img_url:
  384. img_url = img_url + thumbspng
  385. else:
  386. params = {'Key': thumbspng}
  387. if region == 1: # AWS国外
  388. params['Bucket'] = 'foreignpush'
  389. img_url = aws_s3.generate_presigned_url(
  390. 'get_object', Params=params, ExpiresIn=300)
  391. else: # AWS国内
  392. params['Bucket'] = 'push'
  393. img_url = aws_s3_cn.generate_presigned_url(
  394. 'get_object', Params=params, ExpiresIn=300)
  395. equipment_info['img'] = img_url
  396. equipment_info['img_list'] = [img_url]
  397. elif equipment_info['is_st'] == 2:
  398. # 列表装载回放时间戳标记
  399. split_vod_hls_obj = SplitVodHlsObject()
  400. vodqs = split_vod_hls_obj.get_vod_hls_data(
  401. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  402. if not vodqs.exists():
  403. return response.json(173)
  404. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  405. if not vod_bucket_qs.exists():
  406. return response.json(173)
  407. bucket_name = vod_bucket_qs[0]['bucket']
  408. endpoint = vod_bucket_qs[0]['endpoint']
  409. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  410. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  411. if storage_location == 1: # 阿里云oss
  412. thumb0 = bucket.sign_url('GET', ts, 3600,
  413. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  414. thumb1 = bucket.sign_url('GET', ts, 3600,
  415. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  416. thumb2 = bucket.sign_url('GET', ts, 3600,
  417. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  418. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  419. else:
  420. params = {'Key': ts}
  421. if region == 1: # AWS国外
  422. params['Bucket'] = 'foreignpush'
  423. img_url = aws_s3.generate_presigned_url(
  424. 'get_object', Params=params, ExpiresIn=300)
  425. else: # AWS国内
  426. params['Bucket'] = 'push'
  427. img_url = aws_s3_cn.generate_presigned_url(
  428. 'get_object', Params=params, ExpiresIn=300)
  429. equipment_info['img_list'] = [img_url]
  430. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  431. # 列表装载回放时间戳标记
  432. equipment_info['img_list'] = []
  433. for i in range(equipment_info['is_st']):
  434. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  435. if storage_location == 1: # 阿里云oss
  436. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  437. elif storage_location == 5: # 华为云
  438. create_res = obs_client.createSignedUrl(
  439. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  440. img_url = create_res.signedUrl
  441. elif storage_location in [3, 4]: # 国外OCI云
  442. prefix_name = f'{uid}/'
  443. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  444. if img_url:
  445. img_url = img_url + thumbspng
  446. else:
  447. params = {'Key': thumbspng}
  448. if region == 1: # 国外AWS
  449. params['Bucket'] = 'foreignpush'
  450. img_url = aws_s3.generate_presigned_url(
  451. 'get_object', Params=params, ExpiresIn=300)
  452. else: # 国内AWS
  453. params['Bucket'] = 'push'
  454. img_url = aws_s3_cn.generate_presigned_url(
  455. 'get_object', Params=params, ExpiresIn=300)
  456. equipment_info['img_list'].append(img_url)
  457. if uid in uid_type_dict.keys():
  458. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  459. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  460. else:
  461. equipment_info['uid_type'] = ''
  462. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  463. equipment_info['ai_event_type_list'] = []
  464. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  465. if border_coords and event_type in ai_all_event_type:
  466. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  467. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  468. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  469. res.append(equipment_info)
  470. return response.json(0, {'datas': res, 'count': count})
  471. except Exception as e:
  472. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  473. @staticmethod
  474. def get_oci_client():
  475. """
  476. 获取所在区域客户端
  477. @return:
  478. """
  479. if CONFIG_INFO == CONFIG_CN:
  480. return None
  481. oci = OCIObjectStorage(CONFIG_EUR) if CONFIG_INFO == CONFIG_EUR else OCIObjectStorage(CONFIG_US)
  482. return oci
  483. @staticmethod
  484. def oci_object_url(oci, redis_obj, uid, obj_name):
  485. """
  486. 获取OCI对象存储URL 有效期5分钟
  487. @param uid: 设备UID
  488. @param redis_obj: 缓存客户端
  489. @param oci: oci客户端
  490. @param obj_name: 对象名称或前缀
  491. @return: url
  492. """
  493. try:
  494. if not oci:
  495. return ''
  496. uid_key = f'PUSH:MSG:OCI:URL:{uid}'
  497. oci_url = redis_obj.get_data(uid_key)
  498. if oci_url:
  499. return oci_url
  500. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  501. result = oci.get_preauthenticated_request_url(PUSH_BUCKET, 'ociPush', obj_name, time_expires,
  502. 'AnyObjectRead') # 授权到指定uid文件夹
  503. full_url = result.full_path if result else ''
  504. redis_obj.set_data(uid_key, full_url, 3580)
  505. return full_url
  506. except Exception as e:
  507. LOGGER.error('oci查询消息列表异常error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  508. return
  509. # redis_obj,is_st,storage_location,uid,channel,event_type,event_time,event_tag)
  510. def get_redis_url(self, **params):
  511. try:
  512. oss_img_bucket = params['oss_img_bucket']
  513. # 国内生产环境默认不实例OCI对象
  514. oci = self.get_oci_client()
  515. uid = params['uid']
  516. is_st = params['is_st']
  517. storage_location = params['storage_location']
  518. region = params['region']
  519. aws_s3 = params['aws_s3']
  520. aws_s3_cn = params['aws_s3_cn']
  521. redis_obj = params['redis_obj']
  522. channel = params['channel']
  523. event_time = params['event_time']
  524. event_type = int(params['event_type'])
  525. event_tag = params['event_tag']
  526. img_list = []
  527. img_url = ''
  528. if is_st == 1:
  529. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  530. if storage_location == 1: # 阿里云oss
  531. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  532. elif storage_location in [3, 4]:
  533. prefix_name = f'{uid}/'
  534. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  535. if img_url:
  536. img_url = img_url + thumbspng
  537. else:
  538. params = {'Key': thumbspng}
  539. if region == 1: # AWS国外
  540. params['Bucket'] = 'foreignpush'
  541. img_url = aws_s3.generate_presigned_url(
  542. 'get_object', Params=params, ExpiresIn=300)
  543. else: # AWS国内
  544. params['Bucket'] = 'push'
  545. img_url = aws_s3_cn.generate_presigned_url(
  546. 'get_object', Params=params, ExpiresIn=300)
  547. img_list = [img_url]
  548. elif is_st == 3 or is_st == 4:
  549. # 列表装载回放时间戳标记
  550. img_list = []
  551. for i in range(is_st):
  552. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  553. if storage_location == 1: # 阿里云oss
  554. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  555. elif storage_location in [3, 4]:
  556. prefix_name = f'{uid}/'
  557. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  558. if img_url:
  559. img_url = img_url + thumbspng
  560. else:
  561. params = {'Key': thumbspng}
  562. if region == 1: # 国外AWS
  563. params['Bucket'] = 'foreignpush'
  564. img_url = aws_s3.generate_presigned_url(
  565. 'get_object', Params=params, ExpiresIn=300)
  566. else: # 国内AWS
  567. params['Bucket'] = 'push'
  568. img_url = aws_s3_cn.generate_presigned_url(
  569. 'get_object', Params=params, ExpiresIn=300)
  570. img_list.append(img_url)
  571. ai_event_type_list = EquipmentInfoService.get_combo_types(event_type, event_tag)
  572. msg_data = {
  573. "id": "",
  574. "status": False,
  575. "answer_status": False,
  576. "alarm": "",
  577. "is_st": is_st,
  578. "storage_location": storage_location,
  579. "devUid": uid,
  580. "devNickName": "",
  581. "Channel": channel,
  582. "eventType": event_type,
  583. "eventTime": event_time,
  584. "receiveTime": 0,
  585. "addTime": 0,
  586. "borderCoords": "",
  587. "eventTag": event_tag,
  588. "img": img_url,
  589. "img_list": img_list,
  590. "uid_type": 0,
  591. "ai_event_type_list": ai_event_type_list
  592. }
  593. datas = [msg_data]
  594. return datas
  595. except Exception as e:
  596. LOGGER.error('消息跳转异常:, errLine:{}, errMsg:{}'
  597. .format(e.__traceback__.tb_lineno, repr(e)))
  598. return []
  599. def do_transfer(self, request_dict, response, userID):
  600. event_time = request_dict.get('eventTime', None)
  601. event_type = request_dict.get('eventType', None)
  602. region = int(request_dict.get('region', None))
  603. channel = int(request_dict.get('channel', 1))
  604. uid = request_dict.get('uid', None)
  605. if not all([event_time, region, uid]):
  606. return response.json(444)
  607. try:
  608. msg_key = 'PUSH:MSG:IMAGE:{}:{}:{}'.format(uid, channel, event_time)
  609. redis_client = redis.Redis(connection_pool=redis.ConnectionPool(host=PUSH_REDIS_ADDRESS, port=6379, db=3))
  610. msg_data = redis_client.get(msg_key)
  611. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  612. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  613. aws_s3 = boto3.client(
  614. 's3',
  615. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  616. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  617. config=botocore.client.Config(signature_version='s3v4'),
  618. region_name='us-east-1'
  619. )
  620. aws_s3_cn = boto3.client(
  621. 's3',
  622. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  623. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  624. config=botocore.client.Config(signature_version='s3v4'),
  625. region_name='cn-northwest-1'
  626. )
  627. # 国内生产环境默认不实例OCI对象
  628. oci = self.get_oci_client()
  629. redis_obj = RedisObject(3)
  630. if msg_data:
  631. msg_dict = json.loads(msg_data)
  632. LOGGER.info(f'缓存数据:{msg_dict}')
  633. params = {'redis_obj': redis_obj, 'is_st': msg_dict['is_st'], 'region': region, 'aws_s3': aws_s3,
  634. 'storage_location': msg_dict['storage_location'], 'aws_s3_cn': aws_s3_cn,
  635. 'uid': uid, 'channel': channel, 'event_type': event_type, 'oss_img_bucket': oss_img_bucket,
  636. 'event_time': event_time, 'event_tag': msg_dict['event_tag']}
  637. res = self.get_redis_url(**params)
  638. return response.json(0, {'datas': res, 'count': 1})
  639. kwargs = {'device_user_id': userID, 'device_uid': uid, 'event_time': event_time, 'event_type': event_type}
  640. equipment_info_qs, count = EquipmentInfoService.get_equipment_info(**kwargs)
  641. # 查询设备类型,昵称
  642. dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID).values('UID', 'Type', 'NickName')
  643. uid_type_dict = {}
  644. for dv in dvqs:
  645. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  646. # 没有推送数据返回空列表
  647. if count == 0:
  648. return response.json(0, {'datas': [], 'count': 0})
  649. res = []
  650. # ai消息标识所有组合标签
  651. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  652. for equipment_info in equipment_info_qs:
  653. uid = equipment_info['devUid']
  654. event_time = equipment_info['eventTime']
  655. channel = equipment_info['Channel']
  656. storage_location = equipment_info['storage_location']
  657. border_coords = equipment_info['borderCoords']
  658. event_type = equipment_info['eventType']
  659. event_tag = equipment_info['eventTag']
  660. if equipment_info['is_st'] == 1:
  661. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  662. if storage_location == 1: # 阿里云oss
  663. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  664. elif storage_location in [3, 4]:
  665. prefix_name = f'{uid}/'
  666. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  667. if img_url:
  668. img_url = img_url + thumbspng
  669. else:
  670. params = {'Key': thumbspng}
  671. if region == 1: # AWS国外
  672. params['Bucket'] = 'foreignpush'
  673. img_url = aws_s3.generate_presigned_url(
  674. 'get_object', Params=params, ExpiresIn=300)
  675. else: # AWS国内
  676. params['Bucket'] = 'push'
  677. img_url = aws_s3_cn.generate_presigned_url(
  678. 'get_object', Params=params, ExpiresIn=300)
  679. equipment_info['img'] = img_url
  680. equipment_info['img_list'] = [img_url]
  681. elif equipment_info['is_st'] == 2:
  682. # 列表装载回放时间戳标记
  683. split_vod_hls_obj = SplitVodHlsObject()
  684. vodqs = split_vod_hls_obj.get_vod_hls_data(
  685. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  686. if not vodqs.exists():
  687. return response.json(173)
  688. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  689. if not vod_bucket_qs.exists():
  690. return response.json(173)
  691. bucket_name = vod_bucket_qs[0]['bucket']
  692. endpoint = vod_bucket_qs[0]['endpoint']
  693. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  694. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  695. if storage_location == 1: # 阿里云oss
  696. thumb0 = bucket.sign_url('GET', ts, 3600,
  697. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  698. thumb1 = bucket.sign_url('GET', ts, 3600,
  699. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  700. thumb2 = bucket.sign_url('GET', ts, 3600,
  701. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  702. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  703. else:
  704. params = {'Key': ts}
  705. if region == 1: # AWS国外
  706. params['Bucket'] = 'foreignpush'
  707. img_url = aws_s3.generate_presigned_url(
  708. 'get_object', Params=params, ExpiresIn=300)
  709. else: # AWS国内
  710. params['Bucket'] = 'push'
  711. img_url = aws_s3_cn.generate_presigned_url(
  712. 'get_object', Params=params, ExpiresIn=300)
  713. equipment_info['img_list'] = [img_url]
  714. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  715. # 列表装载回放时间戳标记
  716. equipment_info['img_list'] = []
  717. for i in range(equipment_info['is_st']):
  718. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  719. if storage_location == 1: # 阿里云oss
  720. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  721. elif storage_location in [3, 4]:
  722. prefix_name = f'{uid}/'
  723. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  724. if img_url:
  725. img_url = img_url + thumbspng
  726. else:
  727. params = {'Key': thumbspng}
  728. if region == 1: # 国外AWS
  729. params['Bucket'] = 'foreignpush'
  730. img_url = aws_s3.generate_presigned_url(
  731. 'get_object', Params=params, ExpiresIn=300)
  732. else: # 国内AWS
  733. params['Bucket'] = 'push'
  734. img_url = aws_s3_cn.generate_presigned_url(
  735. 'get_object', Params=params, ExpiresIn=300)
  736. equipment_info['img_list'].append(img_url)
  737. if uid in uid_type_dict.keys():
  738. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  739. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  740. else:
  741. equipment_info['uid_type'] = ''
  742. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  743. equipment_info['ai_event_type_list'] = []
  744. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  745. if border_coords and event_type in ai_all_event_type:
  746. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  747. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  748. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  749. res.append(equipment_info)
  750. return response.json(0, {'datas': res, 'count': count})
  751. except Exception as e:
  752. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  753. def do_update_interval(self, userID, request_dict, response):
  754. uid = request_dict.get('uid', None)
  755. interval = request_dict.get('interval', None)
  756. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  757. if dvqs.exists():
  758. uid_set_qs = UidSetModel.objects. \
  759. filter(uid=uid, uidpushmodel__userID_id=userID)
  760. if uid_set_qs.exists():
  761. uid_set_qs.update(detect_interval=int(interval))
  762. else:
  763. return response.json(173)
  764. else:
  765. return response.json(0)
  766. # 这个接口没有调用过,不敢动
  767. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  768. # 移动侦测接口
  769. class PushNotificationView(View):
  770. def get(self, request, *args, **kwargs):
  771. request.encoding = 'utf-8'
  772. # operation = kwargs.get('operation')
  773. return self.validation(request.GET)
  774. def post(self, request, *args, **kwargs):
  775. request.encoding = 'utf-8'
  776. # operation = kwargs.get('operation')
  777. return self.validation(request.POST)
  778. def validation(self, request_dict):
  779. etk = request_dict.get('etk', None)
  780. channel = request_dict.get('channel', '1')
  781. n_time = request_dict.get('n_time', None)
  782. event_type = request_dict.get('event_type', None)
  783. is_st = request_dict.get('is_st', None)
  784. region = request_dict.get('region', '2')
  785. region = int(region)
  786. eto = ETkObject(etk)
  787. uid = eto.uid
  788. if len(uid) == 20:
  789. redisObj = RedisObject()
  790. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  791. pkey = '{uid}_ptl'.format(uid=uid)
  792. ykey = '{uid}_redis_qs'.format(uid=uid)
  793. if redisObj.get_data(key=pkey):
  794. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  795. return JsonResponse(status=200, data=res_data)
  796. else:
  797. redisObj.set_data(key=pkey, val=1, expire=60)
  798. ##############
  799. redis_data = redisObj.get_data(key=ykey)
  800. if redis_data:
  801. redis_list = eval(redis_data)
  802. else:
  803. # 设置推送时间为60秒一次
  804. redisObj.set_data(key=pkey, val=1, expire=60)
  805. print("从数据库查到数据")
  806. # 从数据库查询出来
  807. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  808. values('token_val', 'app_type', 'appBundleId',
  809. 'push_type', 'userID_id', 'lang', 'm_code',
  810. 'tz', 'uid_set__nickname')
  811. # 新建一个list接收数据
  812. redis_list = []
  813. # 把数据库数据追加进redis_list
  814. for qs in uid_push_qs:
  815. redis_list.append(qs)
  816. # 修改redis数据,并设置过期时间为10分钟
  817. if redis_list:
  818. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  819. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  820. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  821. aws_s3_guonei = boto3.client(
  822. 's3',
  823. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  824. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  825. config=botocore.client.Config(signature_version='s3v4'),
  826. region_name='cn-northwest-1'
  827. )
  828. aws_s3_guowai = boto3.client(
  829. 's3',
  830. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  831. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  832. config=botocore.client.Config(signature_version='s3v4'),
  833. region_name='us-east-1'
  834. )
  835. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  836. if is_st == '0' or is_st == '2':
  837. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  838. elif is_st == '1':
  839. # Endpoint以杭州为例,其它Region请按实际情况填写。
  840. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  841. # 设置此签名URL在60秒内有效。
  842. # url = bucket.sign_url('PUT', obj, 7200)
  843. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  844. if region == 2: # 2:国内
  845. response_url = aws_s3_guonei.generate_presigned_url(
  846. ClientMethod='put_object',
  847. Params={
  848. 'Bucket': 'push',
  849. 'Key': thumbspng
  850. },
  851. ExpiresIn=3600
  852. )
  853. else: # 1:国外
  854. response_url = aws_s3_guowai.generate_presigned_url(
  855. ClientMethod='put_object',
  856. Params={
  857. 'Bucket': 'foreignpush',
  858. 'Key': thumbspng
  859. },
  860. ExpiresIn=3600
  861. )
  862. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  863. # response_url = response_url[:4] + response_url[5:]
  864. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  865. return JsonResponse(status=200, data=res_data)
  866. elif is_st == '3':
  867. # 人形检测带动图
  868. img_url_list = []
  869. for i in range(int(is_st)):
  870. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  871. # format(uid=uid, channel=channel, filename=n_time, st=i)
  872. # 设置此签名URL在60秒内有效。
  873. # url = bucket.sign_url('PUT', obj, 7200)
  874. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  875. format(uid=uid, channel=channel, filename=n_time, st=i)
  876. if region == 2: # 2:国内
  877. response_url = aws_s3_guonei.generate_presigned_url(
  878. ClientMethod='put_object',
  879. Params={
  880. 'Bucket': 'push',
  881. 'Key': thumbspng
  882. },
  883. ExpiresIn=3600
  884. )
  885. else: # 1:国外
  886. response_url = aws_s3_guowai.generate_presigned_url(
  887. ClientMethod='put_object',
  888. Params={
  889. 'Bucket': 'foreignpush',
  890. 'Key': thumbspng
  891. },
  892. ExpiresIn=3600
  893. )
  894. # response_url = response_url[:4] + response_url[5:]
  895. img_url_list.append(response_url)
  896. # img_url_list.append(url)
  897. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  898. return JsonResponse(status=200, data=res_data)
  899. else:
  900. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  901. else:
  902. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  903. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  904. now_time = int(time.time())
  905. # 设备昵称
  906. userID_ids = []
  907. sys_msg_list = []
  908. is_sys_msg = self.is_sys_msg(int(event_type))
  909. is_st = int(is_st)
  910. eq_list = []
  911. nickname = uaqs[0]['uid_set__nickname']
  912. if not nickname:
  913. nickname = uid
  914. for ua in uaqs:
  915. lang = ua['lang']
  916. tz = ua['tz']
  917. userID_id = ua["userID_id"]
  918. if userID_id not in userID_ids:
  919. eq_list.append(Equipment_Info(
  920. userID_id=userID_id,
  921. eventTime=n_time,
  922. eventType=event_type,
  923. devUid=uid,
  924. devNickName=nickname,
  925. Channel=channel,
  926. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  927. is_st=is_st,
  928. receiveTime=n_time,
  929. addTime=now_time,
  930. storage_location=2
  931. ))
  932. if is_sys_msg:
  933. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  934. event_type=event_type, is_sys=1)
  935. sys_msg_list.append(SysMsgModel(
  936. userID_id=userID_id,
  937. msg=sys_msg_text,
  938. addTime=now_time,
  939. updTime=now_time,
  940. uid=uid,
  941. eventType=event_type))
  942. if eq_list:
  943. print('eq_list')
  944. Equipment_Info.objects.bulk_create(eq_list)
  945. if is_sys_msg:
  946. print('sys_msg')
  947. SysMsgModel.objects.bulk_create(sys_msg_list)
  948. return True
  949. def is_sys_msg(self, event_type):
  950. event_type_list = [702, 703, 704]
  951. if event_type in event_type_list:
  952. return True
  953. return False
  954. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  955. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  956. etype = int(event_type)
  957. if lang == 'cn':
  958. if etype == 704:
  959. msg_type = '电量过低'
  960. elif etype == 702:
  961. msg_type = '摄像头休眠'
  962. elif etype == 703:
  963. msg_type = '摄像头唤醒'
  964. else:
  965. msg_type = ''
  966. if is_sys:
  967. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  968. else:
  969. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  970. else:
  971. if etype == 704:
  972. msg_type = 'Low battery'
  973. elif etype == 702:
  974. msg_type = 'Camera sleep'
  975. elif etype == 703:
  976. msg_type = 'Camera wake'
  977. else:
  978. msg_type = ''
  979. if is_sys:
  980. send_text = '{msg_type} channel:{channel}'. \
  981. format(msg_type=msg_type, channel=channel)
  982. else:
  983. send_text = '{msg_type} channel:{channel} date:{date}'. \
  984. format(msg_type=msg_type, channel=channel, date=n_date)
  985. return send_text