PcInfo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. a = os.path.splitext(str(file_name))[-1]
  81. if not a:
  82. return response.json(444, "文件无后缀")
  83. name = pc_version + '_' + bundle_version + '_' + pc_test + str(a)
  84. file_path = file_path + '/' + str(name)
  85. upload_path = os.path.join(BASE_DIR, file_path)
  86. print('upload_path:', upload_path)
  87. with open(upload_path, 'wb+') as destination:
  88. for chunk in file_name.chunks():
  89. destination.write(chunk)
  90. add_time = time.time()
  91. create_dict = {
  92. 'pc_name': pc_name,
  93. 'bundle_version': bundle_version,
  94. 'pc_version': pc_version,
  95. 'pc_test': pc_test,
  96. 'lang': lang,
  97. 'download_link': file_path,
  98. 'add_time': add_time,
  99. 'update_time': add_time
  100. }
  101. pc_Info = Pc_Info(**create_dict)
  102. pc_Info.save()
  103. except Exception:
  104. errorInfo = traceback.format_exc()
  105. print(errorInfo)
  106. return response.json(700, {'details': errorInfo})
  107. else:
  108. if pc_Info.id:
  109. res = {'pc_name': pc_Info.pc_name,
  110. 'bundle_version': pc_Info.bundle_version,
  111. 'pc_version': pc_Info.pc_version,
  112. 'pc_test': pc_Info.pc_test,
  113. 'download_link': pc_Info.download_link,
  114. 'lang': pc_Info.lang,
  115. 'add_time': pc_Info.add_time,
  116. 'update_time': pc_Info.update_time
  117. }
  118. return response.json(0, res)
  119. else:
  120. return response.json(500)
  121. def query(self, request_dict, response):
  122. pc_name = request_dict.get('pc_name', None)
  123. queryset = Pc_Info.objects.filter(pc_name=pc_name)
  124. if queryset.exists():
  125. count = queryset.count()
  126. res = queryset
  127. send_json = CommonService.qs_to_dict(res)
  128. send_json['count'] = count
  129. return response.json(0, send_json)
  130. else:
  131. return response.json(173)
  132. def queryall(self, request_dict, response):
  133. token = request_dict.get('token', None)
  134. tko = TokenObject(token)
  135. response.lang = tko.lang
  136. if tko.code != 0:
  137. return response.json(tko.code)
  138. userID = tko.userID
  139. if not userID:
  140. return response.json(104)
  141. page = int(request_dict.get('page', None))
  142. line = int(request_dict.get('line', None))
  143. if page is None or line is None:
  144. return response.json(444, 'page,line')
  145. queryset = Pc_Info.objects.all()
  146. if queryset.exists():
  147. count = queryset.count()
  148. res = queryset[(page - 1) * line:page * line]
  149. send_json = CommonService.qs_to_dict(res)
  150. send_json['count'] = count
  151. return response.json(0, send_json)
  152. else:
  153. return response.json(173)
  154. def download(self, request_dict, response):
  155. pc_name = request_dict.get('pc_name', None)
  156. bundle_version = request_dict.get('bundle_version', None)
  157. pc_version = request_dict.get('pc_version', None)
  158. pc_test = request_dict.get('pc_test', None)
  159. param_flag = CommonService.get_param_flag(
  160. data=[pc_name, bundle_version, pc_version, pc_test])
  161. if param_flag is not True:
  162. return response.json(444)
  163. path = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version, pc_version=pc_version,
  164. pc_test=pc_test).values('download_link')
  165. if not path:
  166. return response.json(173)
  167. filepath = path[0]['download_link']
  168. fullPath = os.path.join(BASE_DIR, filepath)
  169. fullPath.replace('\\', '/')
  170. res = ResponseObject()
  171. print('fullPath:')
  172. print(fullPath)
  173. print(os.path.basename(fullPath))
  174. if fullPath:
  175. if os.path.isfile(fullPath):
  176. try:
  177. wrapper = FileWrapper(open(fullPath, 'rb'))
  178. response = HttpResponse(wrapper, content_type="application/octet-stream")
  179. response['Content-Length'] = os.path.getsize(fullPath)
  180. response['Content-Disposition'] = 'attachment; filename={}'.format(parse.quote_plus(os.path.basename(fullPath), encoding="utf-8"))
  181. response['Content-MD5'] = getMD5orSHA265(fullPath)
  182. # 校验文件md5值
  183. response['Content-SHA265'] = getMD5orSHA265(fullPath, 'SHA265')
  184. response['Content-CRC32'] = getMD5orSHA265(fullPath, 'CRC32')
  185. response['Content-Error'] = res.formal(0)
  186. return response
  187. except Exception as e:
  188. return res.json(906, repr(e))
  189. else:
  190. return res.json(907)
  191. else:
  192. return res.json(444, 'fullPath')
  193. def delete(self, request_dict, response):
  194. token = request_dict.get('token', None)
  195. tko = TokenObject(token)
  196. response.lang = tko.lang
  197. if tko.code != 0:
  198. return response.json(tko.code)
  199. userID = tko.userID
  200. if not userID:
  201. return response.json(104)
  202. id = request_dict.get('id', None)
  203. param_flag = CommonService.get_param_flag(data=[id])
  204. if param_flag is not True:
  205. return response.json(444)
  206. file = Pc_Info.objects.filter(id=id)
  207. if not file.exists():
  208. return response.json(173)
  209. try:
  210. # 删除文件,文件夹和数据库里的相应数据
  211. file_path = file[0].download_link
  212. file_path = os.path.join(BASE_DIR, file_path).replace('\\', '/')
  213. os.remove(file_path)
  214. # file_path = file_path.split("/")
  215. # file_path = [str(i) for i in file_path][:-1]
  216. # file_path = "/".join(file_path)
  217. # shutil.rmtree(file_path)
  218. file.delete()
  219. except Exception as e:
  220. return response.json(176, repr(e))
  221. else:
  222. return response.json(0)
  223. def s3addandupload(self, request_dict, response, request):
  224. token = request_dict.get('token', None)
  225. tko = TokenObject(token)
  226. response.lang = tko.lang
  227. if tko.code != 0:
  228. return response.json(tko.code)
  229. userID = tko.userID
  230. if not userID:
  231. return response.json(104)
  232. pc_name = request_dict.get('pc_name', None)
  233. bundle_version = request_dict.get('bundle_version', None)
  234. pc_version = request_dict.get('pc_version', None)
  235. pc_test = request_dict.get('pc_test', None)
  236. lang = request_dict.get('lang', None)
  237. file_name = request_dict.get('file_name', None)
  238. param_flag = CommonService.get_param_flag(
  239. data=[pc_name, bundle_version, pc_version, pc_test, lang, file_name])
  240. if param_flag is not True:
  241. return response.json(444)
  242. else:
  243. file = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version,
  244. pc_version=pc_version)
  245. if file:
  246. return response.json(174)
  247. try:
  248. # 把安装包上传到s3
  249. aws_s3_guowai = boto3.client(
  250. 's3',
  251. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  252. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  253. config=botocore.client.Config(signature_version='s3v4'),
  254. region_name='us-east-1'
  255. )
  256. download_link = '{pc_name}/{bundle_version}/{pc_version}/{file_s}'.format(
  257. pc_name=pc_name, bundle_version=bundle_version, pc_version=pc_version, file_s=str(file_name))
  258. response_url = aws_s3_guowai.generate_presigned_url(
  259. ClientMethod='put_object',
  260. Params={
  261. 'Bucket': 'pc-installation-package',
  262. 'Key': download_link
  263. },
  264. ExpiresIn=3600
  265. )
  266. add_time = time.time()
  267. create_dict = {
  268. 'pc_name': pc_name,
  269. 'bundle_version': bundle_version,
  270. 'pc_version': pc_version,
  271. 'pc_test': pc_test,
  272. 'lang': lang,
  273. 'download_link': download_link,
  274. 'add_time': add_time,
  275. 'update_time': add_time
  276. }
  277. pc_Info = Pc_Info(**create_dict)
  278. pc_Info.save()
  279. except Exception:
  280. errorInfo = traceback.format_exc()
  281. print(errorInfo)
  282. return response.json(500, {'details': errorInfo})
  283. else:
  284. if pc_Info.id:
  285. res = {'pc_name': pc_Info.pc_name,
  286. 'bundle_version': pc_Info.bundle_version,
  287. 'pc_version': pc_Info.pc_version,
  288. 'pc_test': pc_Info.pc_test,
  289. 'download_link': pc_Info.download_link,
  290. 'lang': pc_Info.lang,
  291. 'add_time': pc_Info.add_time,
  292. 'update_time': pc_Info.update_time,
  293. 'response_url': response_url
  294. }
  295. return response.json(0, res)
  296. else:
  297. return response.json(500)
  298. def s3download(self, request_dict, response):
  299. pc_name = request_dict.get('pc_name', None)
  300. bundle_version = request_dict.get('bundle_version', None)
  301. pc_version = request_dict.get('pc_version', None)
  302. if not pc_name or not pc_version or not bundle_version:
  303. return response.json(444, 'pc_name,bundle_version,pc_version')
  304. file = Pc_Info.objects.filter(pc_name=pc_name, bundle_version=bundle_version, pc_version=pc_version).values()
  305. path = file[0]['download_link']
  306. aws_s3_guowai = boto3.client(
  307. 's3',
  308. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  309. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  310. config=botocore.client.Config(signature_version='s3v4'),
  311. region_name='us-east-1'
  312. )
  313. response_url = aws_s3_guowai.generate_presigned_url(
  314. ClientMethod='get_object',
  315. Params={
  316. 'Bucket': 'pc-installation-package',
  317. 'Key': path
  318. },
  319. ExpiresIn=3600
  320. )
  321. res = {'pc_name': file[0]['pc_name'],
  322. 'bundle_version': file[0]['bundle_version'],
  323. 'pc_version': file[0]['pc_version'],
  324. 'pc_test': file[0]['pc_test'],
  325. 'download_link': file[0]['download_link'],
  326. 'lang': file[0]['lang'],
  327. 'add_time': file[0]['add_time'],
  328. 'update_time': file[0]['update_time'],
  329. 'response_url': response_url
  330. }
  331. return response.json(0, res)
  332. def getMD5orSHA265(fileName, encryptionType='MD5'):
  333. """
  334. :param filePath:
  335. :param encryptionType:
  336. :return:
  337. """
  338. if not os.path.isfile(fileName):
  339. return ''
  340. else:
  341. if encryptionType == 'MD5':
  342. encryption = hashlib.md5()
  343. elif encryptionType == 'SHA265':
  344. encryption = hashlib.sha256()
  345. elif encryptionType == 'CRC32':
  346. f = open(fileName, 'rb')
  347. chunk = f.read()
  348. return crc32(chunk)
  349. f = open(fileName, 'rb')
  350. block_size = 8192 # why is 8192 | 8192 is fast than 2048
  351. while True:
  352. chunk = f.read(block_size)
  353. if not chunk:
  354. break
  355. encryption.update(chunk)
  356. f.close()
  357. return encryption.hexdigest()