OTAEquipment.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. from zlib import crc32
  2. from django.core import serializers
  3. from wsgiref.util import FileWrapper
  4. import traceback, hashlib
  5. from Ansjer.config import SERVER_DOMAIN
  6. from django.views.decorators.csrf import csrf_exempt
  7. from django.views.generic import TemplateView
  8. from django.utils.decorators import method_decorator
  9. from Model.models import Equipment_Version
  10. from Model.models import Device_User
  11. from Service.ModelService import ModelService
  12. from Service.CommonService import CommonService
  13. import time, os,simplejson as json
  14. from Object.ResponseObject import ResponseObject
  15. from Object.TokenObject import TokenObject
  16. from django.http import HttpResponse
  17. from Ansjer.settings import BASE_DIR
  18. def addNewEquipmentVersion(deviceContent, token,response):
  19. """
  20. :param deviceContent:
  21. :return:
  22. """
  23. if token is not None:
  24. tko = TokenObject(token)
  25. tko.valid()
  26. # 设置语言
  27. response.lang = tko.res.get('lang', None)
  28. if tko.code == 0:
  29. userID = tko.userID
  30. own_permission = ModelService.check_permission(userID=userID, permID=220)
  31. if own_permission is True:
  32. try:
  33. deviceData = json.loads(deviceContent)
  34. except Exception as e:
  35. print(deviceData)
  36. return response.json(803)
  37. else:
  38. version = deviceData.get('version', None)
  39. if version is not None:
  40. filePath = deviceData.get('filePath', None)
  41. if filePath is not None:
  42. try:
  43. deviceData['filePath'] = ','.join(filePath)
  44. equipmentVersion = Equipment_Version(
  45. eid=CommonService.getUserID(getUser=False, setOTAID=True),
  46. **deviceData)
  47. equipmentVersion.save()
  48. except Exception as e:
  49. errorInfo = traceback.format_exc()
  50. print('添加设备错误: %s ' % errorInfo)
  51. return response.json(806, repr(e))
  52. else:
  53. res =CommonService.qs_to_dict([equipmentVersion])
  54. return response.json(0, res)
  55. else:
  56. return response.json(806)
  57. else:
  58. return response.json(806)
  59. else:
  60. return response.json(404)
  61. else:
  62. return response.json(311)
  63. def downloadUrl(fileType, fileCode, fileVersion, fileName):
  64. fullPath = os.path.join(BASE_DIR, "static/Upgrade").replace('\\', '/')
  65. if fileType == 'IPC':
  66. Path = '/'.join((fullPath, 'IPC', fileCode, fileVersion, fileName)).replace('\\', '/')
  67. elif fileType == 'DVR':
  68. Path = '/'.join((fullPath, 'DVR', fileCode, fileVersion, fileName)).replace('\\', '/')
  69. elif fileType == 'NVR':
  70. Path = '/'.join((fullPath, 'NVR', fileCode, fileVersion, fileName)).replace('\\', '/')
  71. elif fileType == 'XVR':
  72. Path = '/'.join((fullPath, 'IPC', fileCode, fileVersion, fileName)).replace('\\', '/')
  73. else:
  74. if fileType == 'CHM':
  75. Path = fileName
  76. else:
  77. Path = '/'.join((fullPath, 'Other', fileName)).replace('\\', '/')
  78. if os.path.isfile(Path):
  79. try:
  80. JSON = json.dumps(
  81. {
  82. "result_code": 0,
  83. "reason": 'Success',
  84. "result": {},
  85. "error_code": 0,
  86. }, ensure_ascii=False
  87. )
  88. wrapper = FileWrapper(open(Path, 'rb'))
  89. response = HttpResponse(wrapper, content_type="application/octet-stream")
  90. response['Content-Length'] = os.path.getsize(Path)
  91. response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(Path)
  92. response['Content-MD5'] = getMD5orSHA265(Path)
  93. response['Content-SHA265'] = getMD5orSHA265(Path, 'SHA265')
  94. response['Content-CRC32'] = getMD5orSHA265(Path, 'CRC32')
  95. response['Content-Error'] = JSON
  96. return response
  97. except Exception as e:
  98. res =ResponseObject()
  99. errorJSON = res.formal(906, {'details': repr(e)})
  100. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  101. response['Content-Error'] = errorJSON
  102. return response
  103. else:
  104. res = ResponseObject()
  105. errorJSON = res.formal(907)
  106. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  107. response['Content-Error'] = errorJSON
  108. return response
  109. def getMD5orSHA265(fileName, encryptionType='MD5'):
  110. """
  111. :param filePath:
  112. :param encryptionType:
  113. :return:
  114. """
  115. if not os.path.isfile(fileName):
  116. return ''
  117. else:
  118. if encryptionType == 'MD5':
  119. encryption = hashlib.md5()
  120. elif encryptionType == 'SHA265':
  121. encryption = hashlib.sha256()
  122. elif encryptionType == 'CRC32':
  123. f = open(fileName, 'rb')
  124. chunk = f.read()
  125. return crc32(chunk)
  126. f = open(fileName, 'rb')
  127. block_size = 8192 # why is 8192 | 8192 is fast than 2048
  128. while True:
  129. chunk = f.read(block_size)
  130. if not chunk:
  131. break
  132. encryption.update(chunk)
  133. f.close()
  134. return encryption.hexdigest()
  135. @csrf_exempt
  136. def downloadUpdataFileUrl(request):
  137. response = ResponseObject()
  138. if request.method == 'GET':
  139. request_dict = request.GET
  140. elif request.method == 'POST':
  141. request_dict = request.POST
  142. else:
  143. errorJSON = response.formal(801)
  144. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  145. response['Content-Error'] = errorJSON
  146. return response
  147. fileType = request_dict.get('fileType', None)
  148. fileCode = request_dict.get('fileCode', None)
  149. fileVersion = request_dict.get('fileVersion', None)
  150. fileName = request_dict.get('fileName', None)
  151. if fileType != None and fileCode != None and fileVersion != \
  152. None and fileName != None:
  153. return downloadUrl(fileType, fileCode, fileVersion, fileName,response)
  154. else:
  155. errorJSON = response.formal(800)
  156. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  157. response['Content-Error'] = errorJSON
  158. return response
  159. '''
  160. http://192.168.136.40:8077/OTA/getEquipmentVersion?31AX162001A
  161. '''
  162. @csrf_exempt
  163. def getEquipmentVersionInterface(request):
  164. response = ResponseObject()
  165. if request.method == "POST":
  166. request.encoding = 'utf-8'
  167. code = request.POST.get('code', None)
  168. elif request.method == "GET":
  169. request.encoding = 'gb2312'
  170. code = request.GET.get('code', None)
  171. else:
  172. return response.json(801)
  173. if code is not None:
  174. try:
  175. equipmentValid = Equipment_Version.objects.filter(code=code, status=1).order_by('-data_joined')
  176. except Exception as e:
  177. errorInfo = traceback.format_exc()
  178. print('查询数据库错误: %s' % errorInfo)
  179. return response.json(500, {'details': repr(e)})
  180. else:
  181. if equipmentValid:
  182. equipment = equipmentValid[0]
  183. return response.json(0, {'softwareVersion': equipment.softwareVersion})
  184. else:
  185. return response.json(900)
  186. else:
  187. return response.json(800)
  188. @csrf_exempt
  189. def getUpdataFileUrlInterface(request):
  190. response = ResponseObject()
  191. if request.method == "POST":
  192. request.encoding = 'utf-8'
  193. request_dict = request.POST
  194. elif request.method == "GET":
  195. request.encoding = 'utf-8'
  196. request_dict = request.GET
  197. else:
  198. return response.json(801)
  199. code = request_dict.get('code', None)
  200. http_host = request.META.get('HTTP_HOST', None)
  201. if code is not None:
  202. # return getUpdataFileUrl(code, http_host, response)
  203. equipmentValid = Equipment_Version.objects.filter(code=code, status=1).order_by('-data_joined')
  204. # 判断是否有版本存在
  205. if equipmentValid:
  206. equipment = equipmentValid[0]
  207. file_path = equipment.filePath
  208. urls = []
  209. if file_path:
  210. if file_path.find('static/Upgrade/') != -1:
  211. path = file_path.replace('static/Upgrade/', '').replace('\\', '/')
  212. url = SERVER_DOMAIN + '/OTA/downloads/' + path + '?time=' + str(time.time())
  213. https_url = url.replace('http','https')
  214. urls.append(url)
  215. if len(urls) > 0:
  216. return response.json(0, {
  217. "urlCount": len(urls),
  218. "url": urls,
  219. 'https_url': https_url,
  220. "fileSize": equipment.fileSize,
  221. "Description": equipment.Description,
  222. })
  223. else:
  224. return response.json(901)
  225. else:
  226. return response.json(902)
  227. else:
  228. return response.json(800)
  229. @csrf_exempt
  230. def downloadUpdataFileUrlInterface(request, fileType, fileName,
  231. *callback_args, **callback_kwargs):
  232. res = ResponseObject()
  233. if fileType is not None and fileName is not None:
  234. fullPath = os.path.join(BASE_DIR, "static/Upgrade/").replace('\\', '/')
  235. if fileType == 'IPC':
  236. fullPath += 'IPC/' + fileName
  237. elif fileType == 'DVR':
  238. fullPath += 'DVR/' + fileName
  239. elif fileType == 'NVR':
  240. fullPath += 'NVR/' + fileName
  241. elif fileType == 'XVR':
  242. fullPath += 'XVR/' + fileName
  243. elif fileType == 'User':
  244. fullPath = os.path.join(BASE_DIR, "static/").replace('\\', '/')
  245. fullPath += 'User/' + fileName
  246. elif fileType == 'ADCloud':
  247. fullPath = os.path.join(BASE_DIR, "static/APK/").replace('\\', '/')
  248. fullPath += 'ADCloud/' + fileName
  249. elif fileType == 'ACCloud':
  250. fullPath = os.path.join(BASE_DIR, "static/APK/").replace('\\', '/')
  251. fullPath += 'ACCloud/' + fileName
  252. else:
  253. fullPath += 'Other/' + fileName
  254. print(fullPath)
  255. if os.path.isfile(fullPath):
  256. try:
  257. JSON = res.formal(0)
  258. if fileType != 'User':
  259. wrapper = FileWrapper(open(fullPath, 'rb'))
  260. response = HttpResponse(wrapper, content_type="application/octet-stream")
  261. response['Content-Length'] = os.path.getsize(fullPath)
  262. response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(fullPath)
  263. response['Content-MD5'] = getMD5orSHA265(fullPath)
  264. # 校验文件md5值
  265. response['Content-SHA265'] = getMD5orSHA265(fullPath, 'SHA265')
  266. response['Content-CRC32'] = getMD5orSHA265(fullPath, 'CRC32')
  267. response['Content-Error'] = JSON
  268. return response
  269. else:
  270. Imagedata = open(fullPath, 'rb').read()
  271. response = HttpResponse(Imagedata, content_type="image/jpeg")
  272. return response
  273. except Exception as e:
  274. errorJSON = res.formal(906)
  275. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  276. response['Content-Error'] = errorJSON
  277. return response
  278. else:
  279. errorJSON = res.formal(907)
  280. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  281. response['Content-Error'] = errorJSON
  282. return response
  283. else:
  284. errorJSON = res.formal(800)
  285. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  286. response['Content-Error'] = errorJSON
  287. return response
  288. class getUploadFiletoDirView(TemplateView):
  289. @method_decorator(csrf_exempt)
  290. def dispatch(self, *args, **kwargs):
  291. return super(getUploadFiletoDirView, self).dispatch(*args, **kwargs)
  292. def post(self, request, *args, **kwargs):
  293. request.encoding = 'utf-8'
  294. request_dict = request.POST
  295. fileName = request.FILES.get('fileName', None)
  296. return self.ValidationError(request_dict,fileName)
  297. def get(self, request, *args, **kwargs):
  298. request.encoding = 'gb2312'
  299. request_dict = request.GET
  300. fileName = request.FILES.get('fileName', None)
  301. return self.ValidationError(request_dict,fileName)
  302. def ValidationError(self, request_dict,fileName):
  303. response = ResponseObject()
  304. token = request_dict.get('token', None)
  305. fileType = request_dict.get('fileType', None)
  306. fileCode = request_dict.get('fileCode', None)
  307. fileVersion = request_dict.get('fileVersion', None)
  308. if fileName != None and fileType != None and token != None:
  309. tko = TokenObject(token)
  310. tko.valid()
  311. response.lang = tko.lang
  312. if tko.code == 0:
  313. userID = tko.userID
  314. if userID is not None:
  315. own_permission = ModelService.check_permission(userID=userID, permID=210)
  316. if own_permission is True:
  317. if fileVersion != None and fileCode != None:
  318. return self.getUploadFiletoDir(userID, fileType, fileName,response,fileCode, fileVersion=fileVersion)
  319. else:
  320. return self.getUploadFiletoDir(userID, fileType, fileName,response)
  321. else:
  322. return response.json(404)
  323. else:
  324. return response.json(310)
  325. else:
  326. return response.json(tko.code)
  327. else:
  328. return response.json(800)
  329. def getUploadFiletoDir(self, userID, fileType, fileName,response, *args, **kwargs):
  330. """
  331. 将上传的文件写入服务器对应目录下
  332. :param Type: equipment type
  333. :param fileName: File name of upgrade file.
  334. :return: filePath
  335. """
  336. try:
  337. User = Device_User.objects.filter(userID=userID)
  338. except Exception as e:
  339. errorInfo = traceback.format_exc()
  340. print('查询数据库错误: %s' % errorInfo)
  341. return response.json(500, {'details': repr(e)})
  342. else:
  343. if not User:
  344. return response.json(113)
  345. own_perm = ModelService.check_permission(userID, permID=210)
  346. if own_perm is not True:
  347. return response.json(605)
  348. updataFile = fileName.name
  349. updataFile = updataFile.replace(' ', '+')
  350. versionIndex = updataFile.find('.', updataFile.find('.', updataFile.find('.') + 1) + 1)
  351. codeIndex = versionIndex + 12
  352. if codeIndex != -1 and versionIndex != -1:
  353. fileVersion = len(updataFile[1: versionIndex]) > 0 and updataFile[1: versionIndex] or None
  354. fileCode = len(updataFile[versionIndex + 1: codeIndex]) > 0 and \
  355. updataFile[versionIndex + 1: codeIndex] or None
  356. if fileCode is not None and fileVersion is not None:
  357. return self.getDir(fileType, fileName, fileCode, fileVersion)
  358. else:
  359. fileCode = kwargs.get('fileCode', None)
  360. fileVersion = kwargs.get('fileVersion', None)
  361. print(fileCode, fileVersion)
  362. if fileCode != None and fileVersion != None:
  363. return self.getDir(fileType, fileName, fileCode, fileVersion)
  364. else:
  365. return response.json(903)
  366. else:
  367. fileCode = kwargs.get('fileCode', None)
  368. fileVersion = kwargs.get('fileVersion', None)
  369. if fileCode != None and fileVersion != None:
  370. return self.getDir(fileType, fileName, fileCode, fileVersion,response)
  371. else:
  372. return response.json(903)
  373. def getDir(self,fileType, fileName, fileCode, fileVersion, response):
  374. try:
  375. if fileCode != None and fileVersion != None:
  376. path = '/'.join((BASE_DIR, 'static/Upgrade', fileType, fileCode, fileVersion)).replace('\\', '/') + '/'
  377. else:
  378. if fileType != 'IPC' and fileType != 'DVR' and fileType != 'NVR' and fileType != 'XVR':
  379. path = '/'.join((BASE_DIR, "static/Upgrade", 'Other')).replace('\\', '/') + '/'
  380. if not os.path.exists(path):
  381. os.makedirs(path)
  382. file_name = path + str(fileName)
  383. if os.path.exists(file_name):
  384. os.remove(file_name)
  385. destination = open(file_name, 'wb+')
  386. for chunk in fileName.chunks():
  387. destination.write(chunk)
  388. destination.close()
  389. else:
  390. file_name = path + str(fileName)
  391. if os.path.exists(file_name):
  392. os.remove(file_name)
  393. destination = open(file_name, 'wb+')
  394. for chunk in fileName.chunks():
  395. destination.write(chunk)
  396. destination.close()
  397. except Exception as e:
  398. errorInfo = traceback.format_exc()
  399. print('上传文件错误: %s' % errorInfo)
  400. return response.json(700, {'details': repr(e)})
  401. else:
  402. index = file_name.find('static/')
  403. filePath = file_name[index:]
  404. return response.json(0, {'filePath': filePath})
  405. @csrf_exempt
  406. def addNewEquipmentVersionInterface(request):
  407. response = ResponseObject()
  408. if request.method == "POST":
  409. request.encoding = 'utf-8'
  410. request_dict = request.POST
  411. elif request.method == "GET":
  412. request.encoding = 'gb2312'
  413. request_dict = request.GET
  414. else:
  415. return response.json(801)
  416. deviceContent = request_dict.get('content', None).encode('utf-8')
  417. token = request_dict.get('token', None)
  418. deviceContent = str(deviceContent, encoding='utf-8')
  419. deviceContent = deviceContent.replace(' ', ' ').replace('\'', '\"')
  420. if deviceContent is not None:
  421. return addNewEquipmentVersion(deviceContent, token,response)
  422. else:
  423. return response.json(800)
  424. def showAllEquipmentVersion(userID,response):
  425. try:
  426. userValid = Device_User.objects.filter(userID=userID).order_by('-data_joined')
  427. except Exception as e:
  428. errorInfo = traceback.format_exc()
  429. print('查询数据库错误: %s' % errorInfo)
  430. return response.json(500)
  431. else:
  432. if userValid:
  433. own_permission = ModelService.check_permission(userID=userID, permID=240)
  434. if own_permission:
  435. sqlJSON = serializers.serialize('json', Equipment_Version.objects.all()) # .order_by('-data_joined'))
  436. sqlList = json.loads(sqlJSON)
  437. print(sqlList, sqlJSON)
  438. sqlDict = dict(zip(["datas"], [sqlList]))
  439. return response.json(0, sqlDict)
  440. else:
  441. return response.json(604)
  442. else:
  443. return response.json(113)
  444. @csrf_exempt
  445. def showAllEquipmentVersionInterface(request):
  446. response = ResponseObject()
  447. if request.method == 'POST':
  448. token = request.POST.get('token', None)
  449. elif request.method == 'GET':
  450. token = request.GET.get('token', None)
  451. if token is not None:
  452. tko = TokenObject(token)
  453. tko.valid()
  454. response.lang = tko.lang
  455. if tko.code == 0:
  456. userID = tko.userID
  457. if userID:
  458. return showAllEquipmentVersion(userID,response)
  459. else:
  460. return response.json(310)
  461. else:
  462. return response.json(tko.code)
  463. else:
  464. return response.json(800)