FeedBack.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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/18 10:45
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: SysMsg.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import json
  15. import time
  16. import boto3
  17. import oss2
  18. from django.db import transaction
  19. from django.views.generic.base import View
  20. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  21. from Model.models import FeedBackModel, StatResModel, EquipmentInfoMonday, EquipmentInfoTuesday, EquipmentInfoWednesday, \
  22. EquipmentInfoThursday, EquipmentInfoFriday, EquipmentInfoSaturday, EquipmentInfoSunday, PushInaccurateFeedback
  23. from Object.ResponseObject import ResponseObject
  24. from Object.TokenObject import TokenObject
  25. from Service.CommonService import CommonService
  26. from Service.ModelService import ModelService
  27. from Object.AWS.AmazonS3Util import AmazonS3Util
  28. class FeedBackView(View):
  29. def get(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation', None)
  32. return self.validation(request.GET, operation)
  33. def post(self, request, *args, **kwargs):
  34. request.encoding = 'utf-8'
  35. operation = kwargs.get('operation', None)
  36. return self.validation(request.POST, operation)
  37. def validation(self, request_dict, operation):
  38. response = ResponseObject()
  39. token = request_dict.get('token', None)
  40. tko = TokenObject(token)
  41. if tko.code == 0:
  42. userID = tko.userID
  43. if operation == 'add':
  44. return self.do_add(userID, request_dict, response)
  45. elif operation == 'getUploadUrl':
  46. return self.do_get_upload_url(request_dict, response)
  47. elif operation == 'query':
  48. return self.do_query(userID, request_dict, response)
  49. elif operation == 'delete':
  50. return self.do_delete(userID, request_dict, response)
  51. elif operation == 'queryByAdmin':
  52. return self.do_query_by_admin(userID, request_dict, response)
  53. elif operation == 'deleteByAdmin':
  54. return self.do_delete_by_admin(userID, request_dict, response)
  55. elif operation == 'deleteImage':
  56. return self.do_delete_image(userID, request_dict, response)
  57. elif operation == 'aiRecognition':
  58. return self.ai_recognition(userID, request_dict, response)
  59. else:
  60. return response.json(414)
  61. else:
  62. return response.json(tko.code)
  63. def do_query(self, userID, request_dict, response):
  64. page = request_dict.get('page', None)
  65. line = request_dict.get('line', None)
  66. if page and line:
  67. page = int(page)
  68. line = int(line)
  69. else:
  70. return response.json(444, 'page,line')
  71. fb_qs = FeedBackModel.objects.filter(userID_id=userID)[(page - 1) * line:page * line]. \
  72. values('id', 'status', 'content', 'addTime', 'updTime', 'type')
  73. sid_list = []
  74. for fb in fb_qs:
  75. sid_list.append(fb['id'])
  76. sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=sid_list).values('id', 'name', 'feedbackmodel__id')
  77. # return response.json(0,list(sm_qs))
  78. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  79. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  80. res = []
  81. for fb in fb_qs:
  82. fb['img_url'] = []
  83. for sm in sm_qs:
  84. if sm['feedbackmodel__id'] == fb['id']:
  85. obj = 'feedback/' + sm['name']
  86. img_url = bucket.sign_url('GET', obj, 3600)
  87. fb['img_url'].append(img_url)
  88. # fb['FS__name'] = sm['name']
  89. res.append(fb)
  90. return response.json(0, res)
  91. def do_add(self, userID, request_dict, response):
  92. nowTime = int(time.time())
  93. content = request_dict.get('content', None)
  94. type = request_dict.get('type', None)
  95. res_1 = request_dict.get('res_1', None)
  96. res_2 = request_dict.get('res_2', None)
  97. res_3 = request_dict.get('res_3', None)
  98. app = request_dict.get('app', None)
  99. phone_model = request_dict.get('phone_model', None)
  100. os_version = request_dict.get('os_version', None)
  101. uid = request_dict.get('uid', None)
  102. product_type = request_dict.get('product_type', None)
  103. app_version = request_dict.get('app_version', None)
  104. appBundleId = request_dict.get('appBundleId', None)
  105. email = request_dict.get('email', None)
  106. score = request_dict.get('score', None)
  107. try:
  108. with transaction.atomic():
  109. fb = FeedBackModel()
  110. fb.addTime = nowTime
  111. fb.updTime = nowTime
  112. fb.content = content
  113. if type:
  114. fb.type = type
  115. if app:
  116. fb.app = app
  117. if phone_model:
  118. fb.phone_model = phone_model
  119. if os_version:
  120. fb.os_version = os_version
  121. if uid:
  122. fb.uid = uid
  123. if product_type:
  124. fb.product_type = product_type
  125. if app_version:
  126. fb.app_version = app_version
  127. if appBundleId:
  128. fb.appBundleId = appBundleId
  129. if email:
  130. fb.email = email
  131. if score:
  132. fb.score = score
  133. fb.userID_id = userID
  134. fb.save()
  135. if res_1:
  136. fb.FS.add(StatResModel.objects.create(addTime=nowTime, name=res_1))
  137. if res_2:
  138. fb.FS.add(StatResModel.objects.create(addTime=nowTime, name=res_2))
  139. if res_3:
  140. fb.FS.add(StatResModel.objects.create(addTime=nowTime, name=res_3))
  141. except Exception as e:
  142. print(repr(e))
  143. return response.json(500, repr(e))
  144. else:
  145. return response.json(0)
  146. def do_get_upload_url(self, request_dict, response):
  147. uploadType = request_dict.get('uploadType', None)
  148. uploadType = json.loads(uploadType)
  149. if len(uploadType):
  150. res = []
  151. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  152. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  153. for upType in uploadType:
  154. name = CommonService.createOrderID()
  155. s_name = str(name) + '.' + upType
  156. obj = 'feedback/' + s_name
  157. url = bucket.sign_url('PUT', obj, 7200)
  158. res.append({'put_url': url, 'res_name': s_name})
  159. return response.json(0, res)
  160. else:
  161. return response.json(444, 'uploadType')
  162. def do_delete(self, userID, request_dict, response):
  163. id = request_dict.get('id', None)
  164. try:
  165. fb_qs = FeedBackModel.objects.get(userID_id=userID, id=id)
  166. sr_id_list = fb_qs.FS.values_list('id', flat=True)
  167. StatResModel.objects.filter(id__in=sr_id_list).delete()
  168. fb_qs.delete()
  169. # is_delete = StatResModel.objects.filter(id__in=sr_id_list).delete()
  170. # print(is_delete)
  171. print('----------')
  172. except Exception as e:
  173. return response.json(500, repr(e))
  174. else:
  175. return response.json(0)
  176. def do_query_by_admin(self, userID, request_dict, response):
  177. own_perm = ModelService.check_perm(userID, 30)
  178. if own_perm:
  179. page = request_dict.get('page', None)
  180. line = request_dict.get('line', None)
  181. status = request_dict.get('status', None)
  182. username = request_dict.get('username', None)
  183. type = request_dict.get('type', None)
  184. if page and line:
  185. page = int(page)
  186. line = int(line)
  187. filter_data = {}
  188. if status:
  189. filter_data = {'status': status}
  190. if username:
  191. filter_data = {'userID_id': ModelService.get_userID_byname(username)}
  192. if type:
  193. filter_data = {'type': type}
  194. try:
  195. fb_qs = FeedBackModel.objects.filter()
  196. except Exception as e:
  197. return response.json(500, repr(e))
  198. print('----------')
  199. if filter_data:
  200. fb_qs = fb_qs.filter(**filter_data)
  201. count = fb_qs.count()
  202. fb_qs = fb_qs[(page - 1) * line:page * line].values('id', 'type', 'status', 'content', 'addTime', 'app',
  203. 'uid', 'os_version', 'phone_model', 'product_type',
  204. 'updTime', 'userID__username', 'userID__phone',
  205. 'userID__userEmail', 'app_version', 'appBundleId',
  206. 'email', 'score'
  207. )
  208. sid_list = []
  209. print(fb_qs)
  210. for fb in fb_qs:
  211. sid_list.append(fb['id'])
  212. sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=sid_list).values('id', 'name',
  213. 'feedbackmodel__id')
  214. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  215. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  216. res = []
  217. print(sm_qs)
  218. for fb in fb_qs:
  219. fb['img_url'] = []
  220. for sm in sm_qs:
  221. if sm['feedbackmodel__id'] == fb['id']:
  222. obj = 'feedback/' + sm['name']
  223. img_url = bucket.sign_url('GET', obj, 3600)
  224. # img_url.replace('statres.oss-cn-hongkong.aliyuncs.com','static.zositech.xyz')
  225. fb['img_url'].append(img_url)
  226. # fb['FS__name'] = sm['name']
  227. if fb['userID__username'] == '':
  228. fb['userID__username'] = fb['userID__userEmail']
  229. if fb['userID__username'] == '':
  230. fb['userID__username'] = fb['userID__phone']
  231. res.append(fb)
  232. return response.json(0, {'datas': res, 'count': count})
  233. else:
  234. return response.json(444, 'page,line')
  235. else:
  236. return response.json(404)
  237. def do_delete_by_admin(self, userID, request_dict, response):
  238. own_perm = ModelService.check_perm(userID, 10)
  239. if own_perm:
  240. id = request_dict.get('id', None)
  241. try:
  242. fb_qs = FeedBackModel.objects.get(id=id)
  243. sr_id_list = fb_qs.FS.values_list('id', flat=True)
  244. StatResModel.objects.filter(id__in=sr_id_list).delete()
  245. fb_qs.delete()
  246. print('----------')
  247. except Exception as e:
  248. return response.json(500, repr(e))
  249. else:
  250. return response.json(0)
  251. else:
  252. return response.json(404)
  253. def do_delete_image(self, userID, request_dict, response):
  254. # own_perm = ModelService.check_perm(userID, 10)
  255. # if not own_perm:
  256. # return response.json(404)
  257. end_time = request_dict.get('end_time', None)
  258. if end_time is None:
  259. return response.json(444)
  260. sys_ms_qs = FeedBackModel.objects.filter(addTime__lt=end_time).order_by('id').values('id')
  261. ids = []
  262. for sys_ms in sys_ms_qs:
  263. ids.append(sys_ms['id'])
  264. sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=ids).values('id', 'name')
  265. names = []
  266. time_struct = time.localtime()
  267. current_year = time_struct.tm_year
  268. target_year = current_year - 1
  269. str_prefix = str(target_year)
  270. print(str_prefix)
  271. for sm in sm_qs:
  272. name = sm['name']
  273. if name.find(str_prefix) == 0:
  274. names.append('feedback/' + name)
  275. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  276. # bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  277. # bucket.batch_delete_objects(names)
  278. # FeedBackModel.objects.filter(id__in=ids).delete()
  279. print(names)
  280. print(len(names))
  281. return response.json(0)
  282. @staticmethod
  283. def ai_recognition(user_id, request_dict, response):
  284. equipment_info_id = request_dict.get('equipmentInfoId', None)
  285. region_id = request_dict.get('regionId', None)
  286. if not all([equipment_info_id, region_id]):
  287. return response.json(444)
  288. region_id = int(region_id)
  289. week = int(equipment_info_id[0])
  290. equipment_info_id = equipment_info_id[1:]
  291. now_time = int(time.time())
  292. try:
  293. if region_id == 1: # 国内
  294. s3 = AmazonS3Util(
  295. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  296. secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  297. region_name='cn-northwest-1'
  298. )
  299. else: # 国外
  300. s3 = AmazonS3Util(
  301. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  302. secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  303. region_name='us-east-1'
  304. )
  305. if week == 1:
  306. equipment_info_qs = EquipmentInfoMonday.objects.filter(id=equipment_info_id).values('device_uid',
  307. 'channel',
  308. 'event_time',
  309. 'event_type',
  310. 'is_st')
  311. elif week == 2:
  312. equipment_info_qs = EquipmentInfoMonday.objects.filter(id=equipment_info_id).values('device_uid',
  313. 'channel',
  314. 'event_time',
  315. 'event_type',
  316. 'is_st')
  317. elif week == 3:
  318. equipment_info_qs = EquipmentInfoWednesday.objects.filter(id=equipment_info_id).values('device_uid',
  319. 'channel',
  320. 'event_time',
  321. 'event_type',
  322. 'is_st')
  323. elif week == 4:
  324. equipment_info_qs = EquipmentInfoThursday.objects.filter(id=equipment_info_id).values('device_uid',
  325. 'channel',
  326. 'event_time',
  327. 'event_type',
  328. 'is_st')
  329. elif week == 5:
  330. equipment_info_qs = EquipmentInfoFriday.objects.filter(id=equipment_info_id).values('device_uid',
  331. 'channel',
  332. 'event_time',
  333. 'event_type',
  334. 'is_st')
  335. elif week == 6:
  336. equipment_info_qs = EquipmentInfoSaturday.objects.filter(id=equipment_info_id).values('device_uid',
  337. 'channel',
  338. 'event_time',
  339. 'event_type',
  340. 'is_st')
  341. else:
  342. equipment_info_qs = EquipmentInfoSunday.objects.filter(id=equipment_info_id).values('device_uid',
  343. 'channel',
  344. 'event_time',
  345. 'event_type',
  346. 'is_st')
  347. if not equipment_info_qs.exists():
  348. return response.json(173)
  349. equipment_info = equipment_info_qs.first()
  350. uid = equipment_info['device_uid']
  351. channel = equipment_info['channel']
  352. event_time = equipment_info['event_time']
  353. event_type = equipment_info['event_type']
  354. is_st = equipment_info['is_st']
  355. if is_st != 3:
  356. file_path = '{uid}/{channel}/{event_time}.jpeg'.format(uid=uid,
  357. channel=channel,
  358. event_time=event_time)
  359. s3.copy_obj('push', 'push-inaccurate', file_path)
  360. else:
  361. for index in range(3):
  362. file_path = '{uid}/{channel}/{event_time}_{index}.jpeg'.format(uid=uid,
  363. channel=channel,
  364. event_time=event_time,
  365. index=index)
  366. s3.copy_obj('push', 'push-inaccurate', file_path)
  367. PushInaccurateFeedback.objects.create(equipment_info_id=equipment_info_id,
  368. user_id=user_id, event_type=event_type,
  369. uid=uid, channel=channel, add_time=now_time,
  370. is_st=is_st)
  371. return response.json(0)
  372. except Exception as e:
  373. return response.json(500, repr(e))