OTAEquipment.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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.config 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.lang
  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. print(deviceContent)
  34. print(type(deviceContent))
  35. deviceData = json.loads(deviceContent)
  36. except Exception as e:
  37. return response.json(803, repr(e))
  38. else:
  39. version = deviceData.get('version', None)
  40. if version is not None:
  41. filePath = deviceData.get('filePath', None)
  42. if filePath is not None:
  43. try:
  44. deviceData['filePath'] = ','.join(filePath)
  45. equipmentVersion = Equipment_Version(
  46. eid=CommonService.getUserID(getUser=False, setOTAID=True),
  47. **deviceData)
  48. equipmentVersion.save()
  49. except Exception as e:
  50. errorInfo = traceback.format_exc()
  51. print('添加设备错误: %s ' % errorInfo)
  52. return response.json(806, repr(e))
  53. else:
  54. res = CommonService.qs_to_dict([equipmentVersion])
  55. return response.json(0, res)
  56. else:
  57. return response.json(806)
  58. else:
  59. return response.json(806)
  60. else:
  61. return response.json(404)
  62. else:
  63. return response.json(309)
  64. def downloadUrl(fileType, fileCode, fileVersion, fileName):
  65. fullPath = os.path.join(BASE_DIR, "static/Upgrade").replace('\\', '/')
  66. if fileType == 'IPC':
  67. Path = '/'.join((fullPath, 'IPC', fileCode, fileVersion, fileName)).replace('\\', '/')
  68. elif fileType == 'DVR':
  69. Path = '/'.join((fullPath, 'DVR', fileCode, fileVersion, fileName)).replace('\\', '/')
  70. elif fileType == 'NVR':
  71. Path = '/'.join((fullPath, 'NVR', fileCode, fileVersion, fileName)).replace('\\', '/')
  72. elif fileType == 'XVR':
  73. Path = '/'.join((fullPath, 'IPC', fileCode, fileVersion, fileName)).replace('\\', '/')
  74. else:
  75. if fileType == 'CHM':
  76. Path = fileName
  77. else:
  78. Path = '/'.join((fullPath, 'Other', fileName)).replace('\\', '/')
  79. if os.path.isfile(Path):
  80. try:
  81. JSON = json.dumps(
  82. {
  83. "result_code": 0,
  84. "reason": 'Success',
  85. "result": {},
  86. "error_code": 0,
  87. }, ensure_ascii=False
  88. )
  89. wrapper = FileWrapper(open(Path, 'rb'))
  90. response = HttpResponse(wrapper, content_type="application/octet-stream")
  91. response['Content-Length'] = os.path.getsize(Path)
  92. response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(Path)
  93. response['Content-MD5'] = getMD5orSHA265(Path)
  94. response['Content-SHA265'] = getMD5orSHA265(Path, 'SHA265')
  95. response['Content-CRC32'] = getMD5orSHA265(Path, 'CRC32')
  96. response['Content-Error'] = JSON
  97. return response
  98. except Exception as e:
  99. res = ResponseObject()
  100. errorJSON = res.formal(906, {'details': repr(e)})
  101. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  102. response['Content-Error'] = errorJSON
  103. return response
  104. else:
  105. res = ResponseObject()
  106. errorJSON = res.formal(907)
  107. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  108. response['Content-Error'] = errorJSON
  109. return response
  110. def getMD5orSHA265(fileName, encryptionType='MD5'):
  111. """
  112. :param filePath:
  113. :param encryptionType:
  114. :return:
  115. """
  116. if not os.path.isfile(fileName):
  117. return ''
  118. else:
  119. if encryptionType == 'MD5':
  120. encryption = hashlib.md5()
  121. elif encryptionType == 'SHA265':
  122. encryption = hashlib.sha256()
  123. elif encryptionType == 'CRC32':
  124. f = open(fileName, 'rb')
  125. chunk = f.read()
  126. return crc32(chunk)
  127. f = open(fileName, 'rb')
  128. block_size = 8192 # why is 8192 | 8192 is fast than 2048
  129. while True:
  130. chunk = f.read(block_size)
  131. if not chunk:
  132. break
  133. encryption.update(chunk)
  134. f.close()
  135. return encryption.hexdigest()
  136. @csrf_exempt
  137. def downloadUpdataFileUrl(request):
  138. response = ResponseObject()
  139. if request.method == 'GET':
  140. request_dict = request.GET
  141. elif request.method == 'POST':
  142. request_dict = request.POST
  143. else:
  144. errorJSON = response.formal(801)
  145. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  146. response['Content-Error'] = errorJSON
  147. return response
  148. fileType = request_dict.get('fileType', None)
  149. fileCode = request_dict.get('fileCode', None)
  150. fileVersion = request_dict.get('fileVersion', None)
  151. fileName = request_dict.get('fileName', None)
  152. if fileType != None and fileCode != None and fileVersion != \
  153. None and fileName != None:
  154. return downloadUrl(fileType, fileCode, fileVersion, fileName, response)
  155. else:
  156. errorJSON = response.formal(800)
  157. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  158. response['Content-Error'] = errorJSON
  159. return response
  160. '''
  161. http://192.168.136.40:8077/OTA/getEquipmentVersion?31AX162001A
  162. '''
  163. @csrf_exempt
  164. def getEquipmentVersionInterface(request):
  165. response = ResponseObject()
  166. if request.method == "POST":
  167. request.encoding = 'utf-8'
  168. request_dict = request.POST
  169. elif request.method == "GET":
  170. request.encoding = 'gb2312'
  171. request_dict = request.GET
  172. else:
  173. return response.json(801)
  174. code = request_dict.get('code', None)
  175. ov = request_dict.get('ov', None)
  176. if code is not None:
  177. try:
  178. equipmentValid = Equipment_Version.objects.filter(code=code, status=1, lang='en').order_by('-data_joined')
  179. except Exception as e:
  180. errorInfo = traceback.format_exc()
  181. print('查询数据库错误: %s' % errorInfo)
  182. return response.json(500, {'details': repr(e)})
  183. else:
  184. if equipmentValid:
  185. # 判断大小
  186. if ov is not None:
  187. nv = equipmentValid[0].softwareVersion
  188. if ov > nv:
  189. return response.json(900)
  190. equipment = equipmentValid[0]
  191. return response.json(0, {'softwareVersion': equipment.softwareVersion})
  192. else:
  193. return response.json(900)
  194. else:
  195. return response.json(800)
  196. @csrf_exempt
  197. def getUpdataFileUrlInterface(request):
  198. response = ResponseObject()
  199. if request.method == "POST":
  200. request.encoding = 'utf-8'
  201. request_dict = request.POST
  202. elif request.method == "GET":
  203. request.encoding = 'utf-8'
  204. request_dict = request.GET
  205. else:
  206. return response.json(801)
  207. code = request_dict.get('code', None)
  208. # http_host = request.META.get('HTTP_HOST', None)
  209. if code:
  210. equipmentValid = Equipment_Version.objects.filter(code=code, status=1,lang='en').order_by('-data_joined')
  211. # 判断是否有版本存在
  212. if equipmentValid.exists():
  213. equipment = equipmentValid[0]
  214. file_path = equipment.filePath
  215. urls = []
  216. if file_path:
  217. if file_path.find('static/Upgrade/') != -1:
  218. path = file_path.replace('static/Upgrade/', '').replace('\\', '/')
  219. url = SERVER_DOMAIN + 'OTA/downloads/' + path + '?time=' + str(time.time())
  220. urls.append(url)
  221. if file_path.find('static/otapack') != -1:
  222. url = SERVER_DOMAIN + 'OTA/downloadsPack/' + file_path + '?time=' + str(time.time())
  223. urls.append(url)
  224. if len(urls) > 0:
  225. return response.json(0, {
  226. "urlCount": len(urls),
  227. "url": urls,
  228. "fileSize": equipment.fileSize,
  229. "Description": equipment.Description,
  230. })
  231. else:
  232. return response.json(901)
  233. else:
  234. return response.json(902)
  235. else:
  236. return response.json(800)
  237. @csrf_exempt
  238. def downloadUpdataFileUrlInterface(request, fileType, fileName,
  239. *callback_args, **callback_kwargs):
  240. res = ResponseObject()
  241. if fileType is not None and fileName is not None:
  242. fullPath = os.path.join(BASE_DIR, "static/Upgrade/").replace('\\', '/')
  243. if fileType == 'IPC':
  244. fullPath += 'IPC/' + fileName
  245. elif fileType == 'DVR':
  246. fullPath += 'DVR/' + fileName
  247. elif fileType == 'NVR':
  248. fullPath += 'NVR/' + fileName
  249. elif fileType == 'XVR':
  250. fullPath += 'XVR/' + fileName
  251. elif fileType == 'User':
  252. fullPath = os.path.join(BASE_DIR, "static/").replace('\\', '/')
  253. fullPath += 'User/' + fileName
  254. elif fileType == 'ADCloud':
  255. fullPath = os.path.join(BASE_DIR, "static/APK/").replace('\\', '/')
  256. fullPath += 'ADCloud/' + fileName
  257. elif fileType == 'ACCloud':
  258. fullPath = os.path.join(BASE_DIR, "static/APK/").replace('\\', '/')
  259. fullPath += 'ACCloud/' + fileName
  260. else:
  261. fullPath += 'Other/' + fileName
  262. print(fullPath)
  263. if os.path.isfile(fullPath):
  264. try:
  265. JSON = res.formal(0)
  266. if fileType != 'User':
  267. wrapper = FileWrapper(open(fullPath, 'rb'))
  268. response = HttpResponse(wrapper, content_type="application/octet-stream")
  269. response['Content-Length'] = os.path.getsize(fullPath)
  270. response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(fullPath)
  271. response['Content-MD5'] = getMD5orSHA265(fullPath)
  272. # 校验文件md5值
  273. response['Content-SHA265'] = getMD5orSHA265(fullPath, 'SHA265')
  274. response['Content-CRC32'] = getMD5orSHA265(fullPath, 'CRC32')
  275. response['Content-Error'] = JSON
  276. return response
  277. else:
  278. Imagedata = open(fullPath, 'rb').read()
  279. response = HttpResponse(Imagedata, content_type="image/jpeg")
  280. return response
  281. except Exception as e:
  282. errorJSON = res.formal(906)
  283. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  284. response['Content-Error'] = errorJSON
  285. return response
  286. else:
  287. errorJSON = res.formal(907)
  288. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  289. response['Content-Error'] = errorJSON
  290. return response
  291. else:
  292. errorJSON = res.formal(800)
  293. response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
  294. response['Content-Error'] = errorJSON
  295. return response
  296. class getUploadFiletoDirView(TemplateView):
  297. @method_decorator(csrf_exempt)
  298. def dispatch(self, *args, **kwargs):
  299. return super(getUploadFiletoDirView, self).dispatch(*args, **kwargs)
  300. def post(self, request, *args, **kwargs):
  301. request.encoding = 'utf-8'
  302. request_dict = request.POST
  303. fileName = request.FILES.get('fileName', None)
  304. return self.ValidationError(request_dict, fileName)
  305. def get(self, request, *args, **kwargs):
  306. request.encoding = 'gb2312'
  307. request_dict = request.GET
  308. fileName = request.FILES.get('fileName', None)
  309. return self.ValidationError(request_dict, fileName)
  310. def ValidationError(self, request_dict, fileName):
  311. response = ResponseObject()
  312. token = request_dict.get('token', None)
  313. fileType = request_dict.get('fileType', None)
  314. fileCode = request_dict.get('fileCode', None)
  315. fileVersion = request_dict.get('fileVersion', None)
  316. if fileName != None and fileType != None and token != None:
  317. tko = TokenObject(token)
  318. tko.valid()
  319. response.lang = tko.lang
  320. if tko.code == 0:
  321. userID = tko.userID
  322. if userID is not None:
  323. own_permission = ModelService.check_permission(userID=userID, permID=210)
  324. if own_permission is True:
  325. if fileVersion != None and fileCode != None:
  326. return self.getUploadFiletoDir(userID, fileType, fileName, response, fileCode,
  327. fileVersion=fileVersion)
  328. else:
  329. return self.getUploadFiletoDir(userID, fileType, fileName, response)
  330. else:
  331. return response.json(404)
  332. else:
  333. return response.json(309)
  334. else:
  335. return response.json(tko.code)
  336. else:
  337. return response.json(800)
  338. def getUploadFiletoDir(self, userID, fileType, fileName, response, *args, **kwargs):
  339. """
  340. 将上传的文件写入服务器对应目录下
  341. :param Type: equipment type
  342. :param fileName: File name of upgrade file.
  343. :return: filePath
  344. """
  345. try:
  346. User = Device_User.objects.filter(userID=userID)
  347. except Exception as e:
  348. errorInfo = traceback.format_exc()
  349. print('查询数据库错误: %s' % errorInfo)
  350. return response.json(500, {'details': repr(e)})
  351. else:
  352. if not User:
  353. return response.json(113)
  354. own_perm = ModelService.check_permission(userID, permID=210)
  355. if own_perm is not True:
  356. return response.json(605)
  357. updataFile = fileName.name
  358. updataFile = updataFile.replace(' ', '+')
  359. versionIndex = updataFile.find('.', updataFile.find('.', updataFile.find('.') + 1) + 1)
  360. codeIndex = versionIndex + 12
  361. if codeIndex != -1 and versionIndex != -1:
  362. fileVersion = len(updataFile[1: versionIndex]) > 0 and updataFile[1: versionIndex] or None
  363. fileCode = len(updataFile[versionIndex + 1: codeIndex]) > 0 and \
  364. updataFile[versionIndex + 1: codeIndex] or None
  365. if fileCode is not None and fileVersion is not None:
  366. return self.getDir(fileType, fileName, fileCode, fileVersion, response)
  367. else:
  368. fileCode = kwargs.get('fileCode', None)
  369. fileVersion = kwargs.get('fileVersion', None)
  370. print(fileCode, fileVersion)
  371. if fileCode != None and fileVersion != None:
  372. return self.getDir(fileType, fileName, fileCode, fileVersion)
  373. else:
  374. return response.json(903)
  375. else:
  376. fileCode = kwargs.get('fileCode', None)
  377. fileVersion = kwargs.get('fileVersion', None)
  378. if fileCode != None and fileVersion != None:
  379. return self.getDir(fileType, fileName, fileCode, fileVersion, response)
  380. else:
  381. return response.json(903)
  382. def getDir(self, fileType, fileName, fileCode, fileVersion, response):
  383. try:
  384. if fileCode != None and fileVersion != None:
  385. path = '/'.join((BASE_DIR, 'static/Upgrade', fileType, fileCode, fileVersion)).replace('\\', '/') + '/'
  386. else:
  387. if fileType != 'IPC' and fileType != 'DVR' and fileType != 'NVR' and fileType != 'XVR':
  388. path = '/'.join((BASE_DIR, "static/Upgrade", 'Other')).replace('\\', '/') + '/'
  389. if not os.path.exists(path):
  390. os.makedirs(path)
  391. file_name = path + str(fileName)
  392. if os.path.exists(file_name):
  393. os.remove(file_name)
  394. destination = open(file_name, 'wb+')
  395. for chunk in fileName.chunks():
  396. destination.write(chunk)
  397. destination.close()
  398. else:
  399. file_name = path + str(fileName)
  400. if os.path.exists(file_name):
  401. os.remove(file_name)
  402. destination = open(file_name, 'wb+')
  403. for chunk in fileName.chunks():
  404. destination.write(chunk)
  405. destination.close()
  406. except Exception as e:
  407. errorInfo = traceback.format_exc()
  408. print('上传文件错误: %s' % errorInfo)
  409. return response.json(700, {'details': repr(e)})
  410. else:
  411. index = file_name.find('static/')
  412. filePath = file_name[index:]
  413. return response.json(0, {'filePath': filePath})
  414. @csrf_exempt
  415. def addNewEquipmentVersionInterface(request):
  416. response = ResponseObject()
  417. if request.method == "POST":
  418. request.encoding = 'utf-8'
  419. request_dict = request.POST
  420. elif request.method == "GET":
  421. request.encoding = 'gb2312'
  422. request_dict = request.GET
  423. else:
  424. return response.json(801)
  425. deviceContent = request_dict.get('content', None).encode('utf-8')
  426. token = request_dict.get('token', None)
  427. deviceContent = str(deviceContent, encoding='utf-8')
  428. deviceContent = deviceContent.replace(' ', ' ').replace('\'', '\"')
  429. if deviceContent is not None:
  430. return addNewEquipmentVersion(deviceContent, token, response)
  431. else:
  432. return response.json(800)
  433. def showAllEquipmentVersion(userID, response):
  434. try:
  435. userValid = Device_User.objects.filter(userID=userID).order_by('-data_joined')
  436. except Exception as e:
  437. errorInfo = traceback.format_exc()
  438. print('查询数据库错误: %s' % errorInfo)
  439. return response.json(500)
  440. else:
  441. if userValid:
  442. own_permission = ModelService.check_permission(userID=userID, permID=240)
  443. if own_permission:
  444. sqlJSON = serializers.serialize('json', Equipment_Version.objects.all()) # .order_by('-data_joined'))
  445. sqlList = json.loads(sqlJSON)
  446. print(sqlList, sqlJSON)
  447. sqlDict = dict(zip(["datas"], [sqlList]))
  448. return response.json(0, sqlDict)
  449. else:
  450. return response.json(612)
  451. else:
  452. return response.json(113)
  453. # 检测ota更新包
  454. @csrf_exempt
  455. def getNewVerInterface(request):
  456. response = ResponseObject()
  457. if request.method == "POST":
  458. request.encoding = 'utf-8'
  459. code = request.POST.get('code', None)
  460. token = request.POST.get('token', None)
  461. lang = request.POST.get('lang', None)
  462. elif request.method == "GET":
  463. request.encoding = 'gb2312'
  464. code = request.GET.get('code', None)
  465. token = request.GET.get('token', None)
  466. # 利用语言包判断传递
  467. lang = request.GET.get('lang', None)
  468. else:
  469. return response.json(801)
  470. if code is not None and token is not None:
  471. tko = TokenObject(token)
  472. tko.valid()
  473. response.lang = tko.lang
  474. if tko.code == 0:
  475. try:
  476. if lang == 'zh-Hans':
  477. equipmentValid = Equipment_Version.objects.filter(code=code, status=1, lang=lang).order_by(
  478. '-data_joined')
  479. # if lang is not None and lang != '':
  480. # equipmentValid = Equipment_Version.objects.filter(code=code, status=1, lang=lang).order_by(
  481. # '-data_joined')
  482. else:
  483. equipmentValid = Equipment_Version.objects.filter(code=code, status=1,lang='en').order_by('-data_joined')
  484. except Exception as e:
  485. return response.json(500, {'details': repr(e)})
  486. else:
  487. if equipmentValid.exists():
  488. ver = equipmentValid[0].softwareVersion
  489. equipment = equipmentValid[0]
  490. file_path = equipment.filePath
  491. # path = file_path.replace('static/Upgrade/', '').replace('\\', '/')
  492. # url = SERVER_DOMAIN + 'OTA/downloads/' + path + '?time=' + str(time.time())
  493. # 检测ip进行替换
  494. serverip = '54.215.154.29'
  495. client_ip = CommonService.get_ip_address(request)
  496. if serverip == client_ip:
  497. url = 'http://54.215.154.29/OTA/downloadsPack/' + file_path + '?time=' + str(time.time())
  498. else:
  499. url = SERVER_DOMAIN + 'OTA/downloadsPack/' + file_path + '?time=' + str(time.time())
  500. # get_ip_address =
  501. return response.json(0, {
  502. 'ver': ver,
  503. 'url': url,
  504. # "fileSize": equipment.fileSize,
  505. "Description": equipment.Description,
  506. })
  507. else:
  508. return response.json(902)
  509. else:
  510. return response.json(tko.code)
  511. else:
  512. return response.json(444, 'token,code')
  513. # ota包上传
  514. class uploadOTAInterfaceView(TemplateView):
  515. @method_decorator(csrf_exempt)
  516. def dispatch(self, *args, **kwargs):
  517. return super(uploadOTAInterfaceView, self).dispatch(*args, **kwargs)
  518. def post(self, request, *args, **kwargs):
  519. request.encoding = 'utf-8'
  520. token = request.POST.get('token', None)
  521. fileName = request.FILES.get('fileName', None)
  522. fileType = request.POST.get('fileType', None)
  523. language = request.POST.get('language', None)
  524. return self.validate(token, fileName, fileType, language)
  525. def get(self, request, *args, **kwargs):
  526. request.encoding = 'gb2312'
  527. token = request.GET.get('token', None)
  528. fileName = request.FILES.get('fileName', None)
  529. fileType = request.GET.get('fileType', None)
  530. language = request.GET.get('language', None)
  531. return self.validate(token, fileName, fileType, language)
  532. def validate(self, token, fileName, fileType, language):
  533. response = ResponseObject()
  534. print(token)
  535. print(fileName)
  536. if fileName is not None and token is not None and fileType is not None:
  537. tko = TokenObject(token)
  538. tko.valid()
  539. response.lang = tko.lang
  540. if tko.code == 0:
  541. userID = tko.userID
  542. if userID is not None:
  543. own_permission = ModelService.check_permission(userID=userID, permID=210)
  544. if own_permission is True:
  545. return self.upload_ota_file(fileName, response, fileType, language)
  546. else:
  547. return response.json(404)
  548. else:
  549. return response.json(309)
  550. else:
  551. return response.json(tko.code)
  552. else:
  553. return response.json(800)
  554. def upload_ota_file(self, fileName, response,fileType,language):
  555. try:
  556. if not language:
  557. language = 0
  558. path = '/'.join((BASE_DIR, 'static/otapack', fileType,str(language))).replace('\\', '/') + '/'
  559. if not os.path.exists(path):
  560. os.makedirs(path)
  561. file_name = path + str(fileName)
  562. if os.path.exists(file_name):
  563. os.remove(file_name)
  564. destination = open(file_name, 'wb+')
  565. for chunk in fileName.chunks():
  566. destination.write(chunk)
  567. destination.close()
  568. else:
  569. file_name = path + str(fileName)
  570. if os.path.exists(file_name):
  571. os.remove(file_name)
  572. destination = open(file_name, 'wb+')
  573. for chunk in fileName.chunks():
  574. destination.write(chunk)
  575. destination.close()
  576. except Exception as e:
  577. errorInfo = traceback.format_exc()
  578. print('上传文件错误: %s' % errorInfo)
  579. return response.json(700, {'details': repr(e)})
  580. else:
  581. index = file_name.find('static/')
  582. filePath = file_name[index:]
  583. return response.json(0, {'filePath': filePath})
  584. # ota包下载
  585. # class downloadOTAInterfaceView(TemplateView):
  586. @csrf_exempt
  587. def downloadOTAInterface(request, fullPath, *callback_args, **callback_kwargs):
  588. res = ResponseObject()
  589. print('fullPath:')
  590. print(fullPath)
  591. if fullPath:
  592. if os.path.isfile(fullPath):
  593. try:
  594. JSON = res.formal(0)
  595. wrapper = FileWrapper(open(fullPath, 'rb'))
  596. response = HttpResponse(wrapper, content_type="application/octet-stream")
  597. response['Content-Length'] = os.path.getsize(fullPath)
  598. response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(fullPath)
  599. response['Content-MD5'] = getMD5orSHA265(fullPath)
  600. # 校验文件md5值
  601. response['Content-SHA265'] = getMD5orSHA265(fullPath, 'SHA265')
  602. response['Content-CRC32'] = getMD5orSHA265(fullPath, 'CRC32')
  603. response['Content-Error'] = JSON
  604. return response
  605. except Exception as e:
  606. return res.json(906, repr(e))
  607. else:
  608. return res.json(907)
  609. else:
  610. return res.json(800)