PcInfo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import hashlib
  2. import shutil
  3. import time
  4. import traceback
  5. import os
  6. from urllib import request, parse
  7. from django.http import HttpResponse
  8. from django.views.generic.base import View
  9. from Model.models import Pc_Info
  10. from Object.ResponseObject import ResponseObject
  11. from Object.TokenObject import TokenObject
  12. from Service.CommonService import CommonService
  13. from Ansjer.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, BASE_DIR
  14. import boto3
  15. import botocore
  16. from botocore import client
  17. from wsgiref.util import FileWrapper
  18. from zlib import crc32
  19. class PcInfo(View):
  20. def dispatch(self, requset, *args, **kwargs):
  21. return super(PcInfo, self).dispatch(requset, *args, **kwargs)
  22. def get(self, request, *args, **kwargs):
  23. operation = kwargs.get('operation')
  24. request.encoding = 'utf-8'
  25. return self.validation(request.GET, request, operation)
  26. def post(self, request, *args, **kwargs):
  27. operation = kwargs.get('operation')
  28. request.encoding = 'utf-8'
  29. return self.validation(request.POST, request, operation)
  30. def validation(self, request_dict, request, operation):
  31. response = ResponseObject()
  32. if not operation:
  33. return response.json(444, 'operation')
  34. else:
  35. if operation == 'query':
  36. return self.query(request_dict, response)
  37. elif operation == 'queryall':
  38. return self.queryall(request_dict, response)
  39. elif operation == 'addandupload': # 上传到服务器
  40. return self.addandupload(request_dict, response, request)
  41. elif operation == 'download': # 服务器下载
  42. return self.download(request_dict, response)
  43. elif operation == 'delete':
  44. return self.delete(request_dict, response)
  45. elif operation == 's3addandupload':
  46. return self.s3addandupload(request_dict, response, request)
  47. elif operation == 's3download':
  48. return self.s3download(request_dict, response)
  49. else:
  50. return response.json(414)
  51. def addandupload(self, request_dict, response, request):
  52. token = request_dict.get('token', None)
  53. tko = TokenObject(token)
  54. response.lang = tko.lang
  55. if tko.code != 0:
  56. return response.json(tko.code)
  57. userID = tko.userID
  58. if not userID:
  59. return response.json(104)
  60. pc_name = request_dict.get('pc_name', None)
  61. bundle_version = request_dict.get('bundle_version', None)
  62. pc_version = request_dict.get('pc_version', None)
  63. pc_test = request_dict.get('pc_test', None)
  64. lang = request_dict.get('lang', None)
  65. file_name = request.FILES.get('file_name', None)
  66. param_flag = CommonService.get_param_flag(
  67. data=[pc_name, bundle_version, pc_version, pc_test, lang, file_name])
  68. if param_flag is not True:
  69. return response.json(444)
  70. else:
  71. file = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version,
  72. pc_version=pc_version, pc_test=pc_test)
  73. if file:
  74. return response.json(174)
  75. try:
  76. # 安装包上传到服务器本地
  77. file_path = 'static/pc/' + pc_name
  78. if not os.path.exists(file_path):
  79. os.makedirs(os.path.join(BASE_DIR, file_path))
  80. name = pc_version + '_' + bundle_version + '_' + pc_test + '_' + str(file_name)
  81. file_path = file_path + '/' + str(name)
  82. upload_path = os.path.join(BASE_DIR, file_path)
  83. print('upload_path:', upload_path)
  84. with open(upload_path, 'wb+') as destination:
  85. for chunk in file_name.chunks():
  86. destination.write(chunk)
  87. add_time = time.time()
  88. create_dict = {
  89. 'pc_name': pc_name,
  90. 'bundle_version': bundle_version,
  91. 'pc_version': pc_version,
  92. 'pc_test': pc_test,
  93. 'lang': lang,
  94. 'download_link': file_path,
  95. 'add_time': add_time,
  96. 'update_time': add_time
  97. }
  98. pc_Info = Pc_Info(**create_dict)
  99. pc_Info.save()
  100. except Exception:
  101. errorInfo = traceback.format_exc()
  102. print(errorInfo)
  103. return response.json(500, {'details': errorInfo})
  104. else:
  105. if pc_Info.id:
  106. res = {'pc_name': pc_Info.pc_name,
  107. 'bundle_version': pc_Info.bundle_version,
  108. 'pc_version': pc_Info.pc_version,
  109. 'pc_test': pc_Info.pc_test,
  110. 'download_link': pc_Info.download_link,
  111. 'lang': pc_Info.lang,
  112. 'add_time': pc_Info.add_time,
  113. 'update_time': pc_Info.update_time
  114. }
  115. return response.json(0, res)
  116. else:
  117. return response.json(500)
  118. def query(self, request_dict, response):
  119. pc_name = request_dict.get('pc_name', None)
  120. queryset = Pc_Info.objects.filter(pc_name=pc_name)
  121. if queryset.exists():
  122. count = queryset.count()
  123. res = queryset
  124. send_json = CommonService.qs_to_dict(res)
  125. send_json['count'] = count
  126. return response.json(0, send_json)
  127. else:
  128. return response.json(173)
  129. def queryall(self, request_dict, response):
  130. token = request_dict.get('token', None)
  131. tko = TokenObject(token)
  132. response.lang = tko.lang
  133. if tko.code != 0:
  134. return response.json(tko.code)
  135. userID = tko.userID
  136. if not userID:
  137. return response.json(104)
  138. page = int(request_dict.get('page', None))
  139. line = int(request_dict.get('line', None))
  140. if page is None or line is None:
  141. return response.json(444, 'page,line')
  142. queryset = Pc_Info.objects.all()
  143. if queryset.exists():
  144. count = queryset.count()
  145. res = queryset[(page - 1) * line:page * line]
  146. send_json = CommonService.qs_to_dict(res)
  147. send_json['count'] = count
  148. return response.json(0, send_json)
  149. else:
  150. return response.json(173)
  151. def download(self, request_dict, response):
  152. pc_name = request_dict.get('pc_name', None)
  153. bundle_version = request_dict.get('bundle_version', None)
  154. pc_version = request_dict.get('pc_version', None)
  155. pc_test = request_dict.get('pc_test', None)
  156. param_flag = CommonService.get_param_flag(
  157. data=[pc_name, bundle_version, pc_version, pc_test])
  158. if param_flag is not True:
  159. return response.json(444)
  160. path = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version, pc_version=pc_version,
  161. pc_test=pc_test).values('download_link')
  162. if not path:
  163. return response.json(173)
  164. filepath = path[0]['download_link']
  165. fullPath = os.path.join(BASE_DIR, filepath)
  166. fullPath.replace('\\', '/')
  167. res = ResponseObject()
  168. print('fullPath:')
  169. print(fullPath)
  170. print(os.path.basename(fullPath))
  171. if fullPath:
  172. if os.path.isfile(fullPath):
  173. try:
  174. wrapper = FileWrapper(open(fullPath, 'rb'))
  175. response = HttpResponse(wrapper, content_type="application/octet-stream")
  176. response['Content-Length'] = os.path.getsize(fullPath)
  177. response['Content-Disposition'] = 'attachment; filename={}'.format(parse.quote_plus(os.path.basename(fullPath), encoding="utf-8"))
  178. response['Content-MD5'] = getMD5orSHA265(fullPath)
  179. # 校验文件md5值
  180. response['Content-SHA265'] = getMD5orSHA265(fullPath, 'SHA265')
  181. response['Content-CRC32'] = getMD5orSHA265(fullPath, 'CRC32')
  182. response['Content-Error'] = res.formal(0)
  183. return response
  184. except Exception as e:
  185. return res.json(906, repr(e))
  186. else:
  187. return res.json(907)
  188. else:
  189. return res.json(444, 'fullPath')
  190. def delete(self, request_dict, response):
  191. token = request_dict.get('token', None)
  192. tko = TokenObject(token)
  193. response.lang = tko.lang
  194. if tko.code != 0:
  195. return response.json(tko.code)
  196. userID = tko.userID
  197. if not userID:
  198. return response.json(104)
  199. id = request_dict.get('id', None)
  200. param_flag = CommonService.get_param_flag(data=[id])
  201. if param_flag is not True:
  202. return response.json(444)
  203. file = Pc_Info.objects.filter(id=id)
  204. if not file.exists():
  205. return response.json(173)
  206. try:
  207. # 删除文件,文件夹和数据库里的相应数据
  208. file_path = file[0].download_link
  209. file_path = os.path.join(BASE_DIR, file_path).replace('\\', '/')
  210. os.remove(file_path)
  211. # file_path = file_path.split("/")
  212. # file_path = [str(i) for i in file_path][:-1]
  213. # file_path = "/".join(file_path)
  214. # shutil.rmtree(file_path)
  215. file.delete()
  216. except Exception as e:
  217. return response.json(176, repr(e))
  218. else:
  219. return response.json(0)
  220. def s3addandupload(self, request_dict, response, request):
  221. token = request_dict.get('token', None)
  222. tko = TokenObject(token)
  223. response.lang = tko.lang
  224. if tko.code != 0:
  225. return response.json(tko.code)
  226. userID = tko.userID
  227. if not userID:
  228. return response.json(104)
  229. pc_name = request_dict.get('pc_name', None)
  230. bundle_version = request_dict.get('bundle_version', None)
  231. pc_version = request_dict.get('pc_version', None)
  232. pc_test = request_dict.get('pc_test', None)
  233. lang = request_dict.get('lang', None)
  234. file_name = request_dict.get('file_name', None)
  235. param_flag = CommonService.get_param_flag(
  236. data=[pc_name, bundle_version, pc_version, pc_test, lang, file_name])
  237. if param_flag is not True:
  238. return response.json(444)
  239. else:
  240. file = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version,
  241. pc_version=pc_version)
  242. if file:
  243. return response.json(174)
  244. try:
  245. # 把安装包上传到s3
  246. aws_s3_guowai = boto3.client(
  247. 's3',
  248. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  249. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  250. config=botocore.client.Config(signature_version='s3v4'),
  251. region_name='us-east-1'
  252. )
  253. download_link = '{pc_name}/{bundle_version}/{pc_version}/{file_s}'.format(
  254. pc_name=pc_name, bundle_version=bundle_version, pc_version=pc_version, file_s=str(file_name))
  255. response_url = aws_s3_guowai.generate_presigned_url(
  256. ClientMethod='put_object',
  257. Params={
  258. 'Bucket': 'pc-installation-package',
  259. 'Key': download_link
  260. },
  261. ExpiresIn=3600
  262. )
  263. add_time = time.time()
  264. create_dict = {
  265. 'pc_name': pc_name,
  266. 'bundle_version': bundle_version,
  267. 'pc_version': pc_version,
  268. 'pc_test': pc_test,
  269. 'lang': lang,
  270. 'download_link': download_link,
  271. 'add_time': add_time,
  272. 'update_time': add_time
  273. }
  274. pc_Info = Pc_Info(**create_dict)
  275. pc_Info.save()
  276. except Exception:
  277. errorInfo = traceback.format_exc()
  278. print(errorInfo)
  279. return response.json(500, {'details': errorInfo})
  280. else:
  281. if pc_Info.id:
  282. res = {'pc_name': pc_Info.pc_name,
  283. 'bundle_version': pc_Info.bundle_version,
  284. 'pc_version': pc_Info.pc_version,
  285. 'pc_test': pc_Info.pc_test,
  286. 'download_link': pc_Info.download_link,
  287. 'lang': pc_Info.lang,
  288. 'add_time': pc_Info.add_time,
  289. 'update_time': pc_Info.update_time,
  290. 'response_url': response_url
  291. }
  292. return response.json(0, res)
  293. else:
  294. return response.json(500)
  295. def s3download(self, request_dict, response):
  296. pc_name = request_dict.get('pc_name', None)
  297. bundle_version = request_dict.get('bundle_version', None)
  298. pc_version = request_dict.get('pc_version', None)
  299. if not pc_name or not pc_version or not bundle_version:
  300. return response.json(444, 'pc_name,bundle_version,pc_version')
  301. file = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version, pc_version=pc_version).values()
  302. path = file[0]['download_link']
  303. aws_s3_guowai = boto3.client(
  304. 's3',
  305. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  306. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  307. config=botocore.client.Config(signature_version='s3v4'),
  308. region_name='us-east-1'
  309. )
  310. response_url = aws_s3_guowai.generate_presigned_url(
  311. ClientMethod='get_object',
  312. Params={
  313. 'Bucket': 'pc-installation-package',
  314. 'Key': path
  315. },
  316. ExpiresIn=3600
  317. )
  318. res = {'pc_name': file[0]['pc_name'],
  319. 'bundle_version': file[0]['bundle_version'],
  320. 'pc_version': file[0]['pc_version'],
  321. 'pc_test': file[0]['pc_test'],
  322. 'download_link': file[0]['download_link'],
  323. 'lang': file[0]['lang'],
  324. 'add_time': file[0]['add_time'],
  325. 'update_time': file[0]['update_time'],
  326. 'response_url': response_url
  327. }
  328. return response.json(0, res)
  329. def getMD5orSHA265(fileName, encryptionType='MD5'):
  330. """
  331. :param filePath:
  332. :param encryptionType:
  333. :return:
  334. """
  335. if not os.path.isfile(fileName):
  336. return ''
  337. else:
  338. if encryptionType == 'MD5':
  339. encryption = hashlib.md5()
  340. elif encryptionType == 'SHA265':
  341. encryption = hashlib.sha256()
  342. elif encryptionType == 'CRC32':
  343. f = open(fileName, 'rb')
  344. chunk = f.read()
  345. return crc32(chunk)
  346. f = open(fileName, 'rb')
  347. block_size = 8192 # why is 8192 | 8192 is fast than 2048
  348. while True:
  349. chunk = f.read(block_size)
  350. if not chunk:
  351. break
  352. encryption.update(chunk)
  353. f.close()
  354. return encryption.hexdigest()