OTAEquipment.py 24 KB

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