OTAEquipment.py 20 KB

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