serve_client.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import base64
  2. import hashlib
  3. import json
  4. import os.path
  5. import re
  6. import requests
  7. from Crypto.Cipher import AES
  8. from tools.logger_handle import logger
  9. class ServerClient:
  10. def __init__(self, server_host, user_name, password):
  11. self.user_name = user_name
  12. self.password = password
  13. self.serve_host = server_host
  14. self.access_token = None
  15. self.login_reply = None
  16. self.headers = {
  17. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
  18. }
  19. self.login()
  20. def login(self):
  21. url = self.serve_host + '/auth/oauth2/token'
  22. reply = requests.post(url, params={
  23. 'username': self.user_name,
  24. 'password': self.encryption(self.password),
  25. 'grant_type': 'password',
  26. 'scope': 'server',
  27. 'client_id': 'knowledge',
  28. 'client_secret': 'knowledge'
  29. }, headers={'Content-Type': 'multipart/form-data',
  30. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'})
  31. self.access_token = reply.json()['access_token']
  32. self.login_reply = reply.json()
  33. self.headers['Authorization'] = f'Bearer {self.access_token}'
  34. def decryption(self, hex_str, secret='anZz000000000000'):
  35. key_bytes = secret.encode('utf-8')
  36. iv = key_bytes
  37. base64_str = base64.b64encode(bytes.fromhex(hex_str)).decode('utf-8')
  38. cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
  39. decrypted = cipher.decrypt(base64.b64decode(base64_str))
  40. try:
  41. decoded = decrypted.decode('utf-8')
  42. except UnicodeDecodeError:
  43. decoded = decrypted.decode('utf-8', errors='ignore')
  44. # 清除控制字符(类似 JS 中的 [\u0000-\u001F\u007F-\u009F])
  45. cleaned = re.sub(r'[\x00-\x1F\x7F-\x9F]', ' ', decoded)
  46. try:
  47. return json.loads(cleaned)
  48. except json.JSONDecodeError:
  49. return cleaned.strip()
  50. def zero_pad(self, data, block_size=16):
  51. pad_len = block_size - (len(data) % block_size)
  52. if pad_len == 0:
  53. return data
  54. return data + b'\x00' * pad_len
  55. def encryption(self, payload, secret='a25vd2xlZGdl0000'.encode('utf-8')):
  56. data_bytes = payload.encode('utf-8')
  57. padded_data = self.zero_pad(data_bytes)
  58. cipher = AES.new(secret, AES.MODE_CBC, secret)
  59. encrypted = cipher.encrypt(padded_data)
  60. return encrypted.hex()
  61. def get_base_path(self):
  62. url = self.serve_host + '/mgr/document/dcLibrary/knowledges/owner?size=1000&current=1'
  63. reply = requests.get(url, headers=self.headers)
  64. reply_data = reply.json()
  65. if reply_data.get('code') != 0:
  66. return []
  67. data = self.decryption(reply_data['data'])
  68. return data.get('records', [])
  69. def get_folder_by_id(self, _id):
  70. url = f'{self.serve_host}/mgr/document/dcLibrary/tree?id={_id}'
  71. self.headers['documentid'] = _id
  72. reply = requests.get(url, headers=self.headers)
  73. reply_data = reply.json()
  74. if reply_data.get('code') != 0:
  75. return []
  76. data = self.decryption(reply_data['data'])
  77. return data.get('data', [])
  78. def check_resp(self, resp):
  79. if resp.json()['code'] == -2:
  80. self.login()
  81. return True
  82. return False
  83. def download_file(self, file_info, storage_path):
  84. try:
  85. resp = requests.get(f'{self.serve_host}/mgr/document/dcLibrary/file/get/file/{file_info["id"]}',
  86. headers=self.headers)
  87. local_file_name = file_info['filePath'].replace('/', '_')
  88. with open(os.path.join(storage_path, local_file_name), 'wb') as f:
  89. f.write(resp.content)
  90. with open(os.path.join(storage_path, local_file_name + '.metadata'), 'w', encoding='utf-8') as f:
  91. f.write(json.dumps({
  92. 'file_id': file_info["id"],
  93. 'bucket_name': file_info['bucketName'],
  94. 'md5': self.get_file_md5(os.path.join(storage_path, local_file_name)),
  95. 'file_name': file_info['name'],
  96. 'oss_path': file_info['filePath'],
  97. 'update_time': file_info['updateTime']
  98. }))
  99. except Exception as e:
  100. logger.exception(e)
  101. return False
  102. return True
  103. def upload_file(self, file_path):
  104. try:
  105. with open(f'{file_path}.metadata', 'r', encoding='utf-8') as f:
  106. file_metadata = json.loads(f.read())
  107. file_id = file_metadata['file_id']
  108. files = [('file', (file_metadata['file_name'], open(file_path, 'rb'),
  109. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))]
  110. resp = requests.post(
  111. f'{self.serve_host}/mgr/document/dcLibrary/saveByPython/{file_id}',
  112. headers=self.headers,
  113. files=files,
  114. data={}
  115. )
  116. if self.check_resp(resp):
  117. resp = requests.post(
  118. f'{self.serve_host}/mgr/document/dcLibrary/saveByPython/{file_id}',
  119. headers=self.headers,
  120. files=files,
  121. data={})
  122. if resp.json()['code'] == 0:
  123. return True
  124. else:
  125. logger.error(resp.json())
  126. return False
  127. except Exception as e:
  128. logger.exception(e)
  129. return False
  130. @staticmethod
  131. def get_file_md5(file_path):
  132. md5 = hashlib.md5()
  133. with open(file_path, 'rb') as f:
  134. # 分块读取以支持大文件
  135. while chunk := f.read(8192):
  136. md5.update(chunk)
  137. return md5.hexdigest()
  138. @staticmethod
  139. def load_metadata(local_path):
  140. with open(f'{local_path}.metadata', 'r', encoding='utf-8') as f:
  141. file_metadata = json.loads(f.read())
  142. return file_metadata
  143. def create_cloud_file(self, local_file='D:/bussion/法律法规/道路交通安全法.docx',
  144. folder_id='5b091f1007c880528bd913530987d5e5'):
  145. payload = {'module': '/jvs-knowledge-ui/jvs-knowledge-import/'}
  146. files = [
  147. ('file', (os.path.basename(local_file), open(local_file, 'rb'),
  148. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))]
  149. resp = requests.post(f'http://120.195.49.22:7215/mgr/document/dcLibrary/upload/{folder_id}',
  150. headers=self.headers, data=payload, files=files)
  151. if resp.json().get('code') == 0:
  152. return True
  153. else:
  154. return False
  155. def get_folder_tree(self):
  156. resp = requests.get('http://120.195.49.22:7215/mgr/document/dcLibrary/tree/myFolder', headers=self.headers)
  157. if resp.json().get('code') == 0:
  158. return self.decryption(resp.json()['data'])
  159. else:
  160. return []
  161. def get_template_file_info(self, file_id):
  162. try:
  163. resp = requests.get(f'http://120.195.49.22:7215/mgr/document/dcLibrary/template/get/{file_id}',
  164. headers=self.headers)
  165. if resp.json().get('code') == 0:
  166. return self.decryption(resp.json()['data'])
  167. return False
  168. except Exception as e:
  169. logger.error('获取模板信息出错')
  170. logger.exception(e)
  171. return False
  172. def download_template(self, url, file_path):
  173. try:
  174. resp = requests.get(url)
  175. with open(file_path, 'wb') as f:
  176. f.write(resp.content)
  177. return True
  178. except Exception as e:
  179. logger.error('下载模板文件出错')
  180. logger.exception(e)
  181. return False
  182. def get_file_info(self, file_id):
  183. '''
  184. :param file_id:
  185. :return:
  186. '''
  187. logger.info(self.headers)
  188. try:
  189. resp = requests.get(f'{self.serve_host}/mgr/document/no/auth/dcLibrary/info/{file_id}',
  190. headers=self.headers)
  191. if not self.check_resp(resp):
  192. resp = requests.get(f'{self.serve_host}/mgr/document/no/auth/dcLibrary/info/{file_id}',
  193. headers=self.headers)
  194. if not resp.json()['data']:
  195. return False
  196. return self.decryption(resp.json()['data'])
  197. except Exception as e:
  198. logger.exception(e)
  199. return False
  200. if __name__ == '__main__':
  201. client = ServerClient('http://120.195.49.22:7215', 'admin', 'jxkj123456')
  202. res = client.decryption(
  203. "")
  204. print(res)