LangArea.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: langer
  7. @software: PyCharm
  8. @DATE: 2019/6/4 11:44
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: LangArea.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import json
  15. from django.http import HttpResponse
  16. from django.views.generic import TemplateView
  17. from django.views.decorators.csrf import csrf_exempt
  18. from django.utils.decorators import method_decorator
  19. from object.ResponseObject import ResponseObject
  20. from django.contrib.auth.hashers import make_password, check_password
  21. from model.models import UserModel, LangSetModel, LangAreaModel, LangValModel, LangKeyModel, LangKeyClassModel, \
  22. SearchToolBlock, SearchToolKeyModel, LangLocationModel
  23. import time
  24. from object.TokenObject import TokenObject
  25. from django.http import StreamingHttpResponse
  26. class LangAreaView(TemplateView):
  27. def post(self, request, *args, **kwargs):
  28. request.encoding = 'utf-8'
  29. operation = kwargs.get('operation', None)
  30. request_dict = json.loads(request.body.decode('utf-8'))
  31. return self.validate(request_dict, operation)
  32. def get(self, request, *args, **kwargs):
  33. request.encoding = 'utf-8'
  34. request_dict = request.GET
  35. operation = kwargs.get('operation', None)
  36. return self.validate(request_dict, operation)
  37. def validate(self, request_dict, operation):
  38. response = ResponseObject()
  39. token = request_dict.get('token', None)
  40. tko = TokenObject(token)
  41. if tko.code == 0:
  42. userID = tko.userID
  43. user_qs = UserModel.objects.filter(id=userID, username='admin')
  44. if not user_qs.exists():
  45. return response.json(403)
  46. if operation == 'add':
  47. return self.do_add(request_dict, response)
  48. elif operation == 'update':
  49. return self.do_update(request_dict, response)
  50. elif operation == 'delete':
  51. return self.do_delete(request_dict, response)
  52. elif operation == 'query':
  53. return self.do_query(request_dict, response, userID)
  54. elif operation == 'export':
  55. return self.do_export(request_dict, response, userID)
  56. else:
  57. return response.json(414)
  58. else:
  59. return response.json(tko.code)
  60. def do_add(self, request_dict, response):
  61. lang = request_dict.get('lang', None)
  62. if lang:
  63. nowTime = int(time.time())
  64. create_dict = {
  65. 'lang': lang,
  66. 'addTime': nowTime,
  67. 'updTime': nowTime
  68. }
  69. try:
  70. LangAreaModel.objects.create(**create_dict)
  71. except Exception as e:
  72. return response.json(404, repr(e))
  73. else:
  74. return response.json(0)
  75. else:
  76. return response.json(414)
  77. def do_update(self, request_dict, response):
  78. lang = request_dict.get('lang', None)
  79. id = request_dict.get('id', None)
  80. nowTime = int(time.time())
  81. update_dict = {
  82. 'lang': lang,
  83. 'updTime': nowTime
  84. }
  85. try:
  86. LangAreaModel.objects.filter(id=id).update(**update_dict)
  87. except Exception as e:
  88. return response.json(404, repr(e))
  89. else:
  90. return response.json(0)
  91. def do_delete(self, request_dict, response):
  92. id = request_dict.get('id', None)
  93. try:
  94. LangAreaModel.objects.filter(id=id).delete()
  95. except Exception as e:
  96. return response.json(404, repr(e))
  97. else:
  98. return response.json(0)
  99. def do_query(self, request_dict, response, userID):
  100. user_qs = UserModel.objects.filter(id=userID, username='admin')
  101. if not user_qs.exists():
  102. return response.json(403)
  103. la_qs = LangAreaModel.objects.filter().values('lang', 'id')
  104. return response.json(0, list(la_qs))
  105. def do_export(self, request_dict, response, userID):
  106. print("进来了")
  107. id = request_dict.get('id', None)
  108. type = request_dict.get('type', None)
  109. # key_list = LangKeyModel.objects.filter().values_list('word_key', flat=True)
  110. print('id = ' + id)
  111. langType = (1, 3, 5, 7)
  112. if type == 'avss':
  113. langType = (2, 3, 6, 7)
  114. elif type == 'link_ios' or type == 'link_android':
  115. langType = (4, 5, 6, 7)
  116. en_qs = LangKeyModel.objects.filter(langvalmodel__la__id=20, type__in=langType).values('word_key',
  117. 'langvalmodel__word_val')
  118. en_kv = {}
  119. for e in en_qs:
  120. en_kv[e['word_key']] = e['langvalmodel__word_val']
  121. content = ''
  122. if type == 'ios' or type == 'link_ios':
  123. res_qs = LangKeyModel.objects.filter(langvalmodel__la__id=id, type__in=langType). \
  124. values('word_key', 'langvalmodel__word_val')
  125. res = {}
  126. for r in res_qs:
  127. print(r['langvalmodel__word_val'])
  128. if r['langvalmodel__word_val']:
  129. res[r['word_key']] = r['langvalmodel__word_val']
  130. elif en_kv[r['word_key']]:
  131. res[r['word_key']] = en_kv[r['word_key']]
  132. for l in res:
  133. content_val = res[l].replace('"', '\'')
  134. content = content + '"' + l + '"="' + content_val + '";\n'
  135. elif type == 'android' or type == 'link_android':
  136. res_qs = LangKeyModel.objects.filter(langvalmodel__la__id=id, type__in=langType). \
  137. values('word_key', 'langvalmodel__word_val').order_by('addTime')
  138. res = {}
  139. for r in res_qs:
  140. print(r['langvalmodel__word_val'])
  141. if r['langvalmodel__word_val']:
  142. res[r['word_key']] = r['langvalmodel__word_val']
  143. elif en_kv[r['word_key']]:
  144. res[r['word_key']] = en_kv[r['word_key']]
  145. for l in res:
  146. lk = l
  147. lk = lk.replace('.', '_')
  148. lk = lk.replace('\\n', '_')
  149. lk = lk.replace('“', '_')
  150. lk = lk.replace('”', '_')
  151. lk = lk.replace(' ', '_')
  152. lk = lk.replace('\\\'', '_')
  153. lk = lk.replace('\'', '_')
  154. lk = lk.replace('\\', '_')
  155. lk = lk.replace('!', '_')
  156. lk = lk.replace('’', '_')
  157. lk = lk.replace('...', '_')
  158. lk = lk.replace('…', '_')
  159. lk = lk.replace(':', '_')
  160. lk = lk.replace(':', '_')
  161. lk = lk.replace('(', '_')
  162. lk = lk.replace(')', '_')
  163. lk = lk.replace('?', '_')
  164. lk = lk.replace(',', '_')
  165. lk = lk.replace('-', '_')
  166. lk = lk.replace('%', '_')
  167. lk = lk.replace(';', '_')
  168. lk = lk.replace('‘', '_')
  169. lk = lk.replace('&', '&')
  170. # 正则表达式
  171. # re.sub("[a-z]+", "$", "123abc78ab9cdeg00t8")
  172. content_val = res[l].replace("'", "\\'")
  173. content_val = content_val.replace('"', '\\"')
  174. content = content + '<string name="' + lk + '">' + content_val + '</string>\n'
  175. elif type == 'avss':
  176. content = self.do_download_avss(id)
  177. elif type == 'new_searchTool':
  178. content = self.do_download_SearchTool(id, 0)
  179. elif type == 'old_searchTool':
  180. content = self.do_download_SearchTool(id, 1)
  181. response = StreamingHttpResponse(content)
  182. response['Content-Type'] = 'application/octet-stream'
  183. response['Content-Disposition'] = 'attachment;filename="lang.txt"'
  184. return response
  185. return response.json(0, res)
  186. def do_download_avss(self, id):
  187. content = ''
  188. en_result = self.get_area_language(20)
  189. target_result = self.get_area_language(id)
  190. if target_result:
  191. content += '<TS version=\"2.1\" language=\"' + self.get_avss_language(int(id)) + '\">\n'
  192. # keys = result.keys()
  193. keys = en_result.keys()
  194. for key in keys:
  195. content += '<context>\n<name>'
  196. content += key
  197. content += '</name>\n'
  198. messages = None
  199. if target_result.__contains__(key):
  200. messages = target_result[key]
  201. else:
  202. messages = en_result[key]
  203. messageKeys = en_result[key].keys()
  204. for messageKey in messageKeys:
  205. message = None
  206. if messages.__contains__(messageKey):
  207. message = messages[messageKey]
  208. else:
  209. message = en_result[key][messageKey]
  210. # message = messages[messageKey]
  211. content += '<message>\n'
  212. content += '<source>'
  213. content += message['source']
  214. content += '</source>\n'
  215. content += '<translation>'
  216. translation = message['translation']
  217. # if translation is None or translation == '':
  218. # content += '23333'
  219. # else:
  220. content += translation
  221. content += '</translation>\n'
  222. locations = message['locations']
  223. print(message)
  224. for location in locations:
  225. if location['filename'] != '':
  226. content += '<location filename=\"' + location['filename'] + '\" line=\"' + str(
  227. location['line']) + '\"/>\n'
  228. content += '</message>\n'
  229. content += '</context>\n'
  230. content += '</TS>'
  231. return content
  232. else:
  233. print('none')
  234. return content
  235. def get_area_language(self, id):
  236. result = {}
  237. lkc_qs = LangKeyModel.objects.filter(langvalmodel__la__id=id, type__in=(2, 3, 6, 7)).values('word_key',
  238. 'langkeyclassmodel__clazz__name',
  239. 'langvalmodel__word_val',
  240. 'langlocationmodel__filename',
  241. 'langlocationmodel__line')
  242. for lkc in lkc_qs:
  243. # print(lkc)
  244. name = lkc['langkeyclassmodel__clazz__name']
  245. hasClass = result.__contains__(name)
  246. if hasClass is False:
  247. result[name] = {}
  248. source = lkc['word_key']
  249. if not result[name].__contains__(source):
  250. result[name][source] = {}
  251. message = result[name][source]
  252. message['source'] = source
  253. message['translation'] = lkc['langvalmodel__word_val']
  254. # location
  255. locations = []
  256. locations.append({'filename': lkc['langlocationmodel__filename'], 'line': lkc['langlocationmodel__line']})
  257. message['locations'] = locations
  258. print(result)
  259. return result
  260. def get_area_language_search(self, id):
  261. result = {}
  262. lkc_qs = LangKeyModel.objects.filter(langvalmodel__la__id=id, project__id=4).values('word_key',
  263. 'searchtoolkeymodel__bk__name',
  264. 'langvalmodel__word_val',
  265. 'langlocationmodel__filename',
  266. 'langlocationmodel__line')
  267. for lkc in lkc_qs:
  268. # print(lkc)
  269. name = lkc['searchtoolkeymodel__bk__name']
  270. hasClass = result.__contains__(name)
  271. if hasClass is False:
  272. result[name] = {}
  273. source = lkc['word_key']
  274. if not result[name].__contains__(source):
  275. result[name][source] = {}
  276. message = result[name][source]
  277. message['source'] = source[(len(name) + 1):]
  278. message['translation'] = lkc['langvalmodel__word_val']
  279. # location
  280. locations = []
  281. locations.append({'filename': lkc['langlocationmodel__filename'], 'line': lkc['langlocationmodel__line']})
  282. message['locations'] = locations
  283. print(result)
  284. return result
  285. def get_avss_language(self, id):
  286. if id == 18: # 简体中文
  287. return 'zh_CN'
  288. elif id == 19: # 繁体中文
  289. return 'zh_HK'
  290. elif id == 20: # 英文
  291. return 'en_US'
  292. elif id == 21: # 俄语
  293. return 'ru'
  294. elif id == 22: # 德语
  295. return 'de'
  296. elif id == 23: # 波兰语
  297. return 'pl'
  298. elif id == 24: # 法语
  299. return 'fr'
  300. elif id == 25: # 西班牙语
  301. return 'es'
  302. elif id == 26: # 日语
  303. return 'ja'
  304. elif id == 27: # 阿拉伯语
  305. return 'ar'
  306. elif id == 29: # 意大利语
  307. return 'it'
  308. elif id == 30: # 葡萄牙语
  309. return 'pt'
  310. elif id == 31: # 荷兰语
  311. return 'nl'
  312. elif id == 32: # 越南语
  313. return 'vi'
  314. else:
  315. return 'en'
  316. def do_download_SearchTool(self, id, searchtype):
  317. content = ''
  318. en_result = self.get_area_language_search(20)
  319. print(en_result)
  320. target_result = self.get_area_language_search(id)
  321. if target_result:
  322. content += '<TS version=\"2.1\" language=\"' + self.get_avss_language(int(id)) + '\">\n'
  323. # keys = result.keys()
  324. keys = en_result.keys()
  325. for key in keys:
  326. content += '<context>\n<name>'
  327. content += key
  328. content += '</name>\n'
  329. messages = None
  330. if target_result.__contains__(key):
  331. messages = target_result[key]
  332. else:
  333. messages = en_result[key]
  334. messageKeys = en_result[key].keys()
  335. for messageKey in messageKeys:
  336. message = None
  337. if messages.__contains__(messageKey):
  338. message = messages[messageKey]
  339. else:
  340. message = en_result[key][messageKey]
  341. # message = messages[messageKey]
  342. content += '<message>\n'
  343. content += '<source>'
  344. content += message['source']
  345. content += '</source>\n'
  346. content += '<translation>'
  347. translation = message['translation']
  348. # if translation is None or translation == '':
  349. # content += '23333'
  350. # else:
  351. content += translation
  352. content += '</translation>\n'
  353. locations = message['locations']
  354. print(message)
  355. for location in locations:
  356. if location['filename'] != '':
  357. content += '<location filename=\"' + location['filename'] + '\" line=\"' + str(
  358. location['line']) + '\"/>\n'
  359. content += '</message>\n'
  360. content += '</context>\n'
  361. content += '</TS>'
  362. return content
  363. else:
  364. print('none')
  365. return content
  366. class exportLangView(TemplateView):
  367. def post(self, request, *args, **kwargs):
  368. request.encoding = 'utf-8'
  369. request_dict = json.loads(request.body.decode('utf-8'))
  370. return self.validate(request_dict)
  371. def get(self, request, *args, **kwargs):
  372. request.encoding = 'utf-8'
  373. request_dict = request.GET
  374. return self.validate(request_dict)
  375. def validate(self, request_dict):
  376. # 得到即将下载文件的路径和名称
  377. response = StreamingHttpResponse('123l4kjlkfjlksadjlfksdajlf')
  378. response['Content-Type'] = 'application/octet-stream'
  379. response['Content-Disposition'] = 'attachment;filename="lang.txt"'
  380. return response