serve_client.py 9.0 KB

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