serve_client.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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.config import SERVER_POINT
  9. from tools.oss_client import oss_handle
  10. from tools.logger_handle import logger
  11. class ServerClient:
  12. def __init__(self, server_host, user_name, password):
  13. self.user_name = user_name
  14. self.password = password
  15. self.serve_host = server_host
  16. self.access_token = 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.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 check_resp(self, resp):
  62. if resp.json()['code'] == -2:
  63. self.login()
  64. return True
  65. return False
  66. def download_file(self, file_info, storage_path):
  67. try:
  68. resp = requests.get(f'{self.serve_host}/mgr/document/dcLibrary/file/get/file/{file_info["id"]}',
  69. headers=self.headers)
  70. local_file_name = file_info['filePath'].replace('/', '_')
  71. with open(os.path.join(storage_path, local_file_name), 'wb') as f:
  72. f.write(resp.content)
  73. with open(os.path.join(storage_path, local_file_name + '.metadata'), 'w', encoding='utf-8') as f:
  74. f.write(json.dumps({
  75. 'serve': oss_handle.service,
  76. 'access_key': oss_handle.access_key,
  77. 'secret_key': oss_handle.secret_key,
  78. 'file_id': file_info["id"],
  79. 'bucket_name': file_info['bucketName'],
  80. 'md5': self.get_file_md5(os.path.join(storage_path, local_file_name)),
  81. 'file_name': file_info['name'],
  82. 'oss_path': file_info['filePath'],
  83. 'update_time': file_info['updateTime']
  84. }))
  85. except Exception as e:
  86. logger.exception(e)
  87. return False
  88. return True
  89. def upload_file(self, file_path):
  90. try:
  91. with open(f'{file_path}.metadata', 'r', encoding='utf-8') as f:
  92. file_metadata = json.loads(f.read())
  93. file_id = file_metadata['file_id']
  94. files = [('file', (file_metadata['file_name'], open(file_path, 'rb'),
  95. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))]
  96. resp = requests.post(
  97. f'{self.serve_host}/mgr/document/dcLibrary/saveByPython/{file_id}',
  98. headers=self.headers,
  99. files=files,
  100. data={}
  101. )
  102. if self.check_resp(resp):
  103. resp = requests.post(
  104. f'{self.serve_host}/mgr/document/dcLibrary/saveByPython/{file_id}',
  105. headers=self.headers,
  106. files=files,
  107. data={})
  108. if resp.json()['code'] == 0:
  109. return True
  110. else:
  111. logger.error(resp.json())
  112. return False
  113. except Exception as e:
  114. logger.exception(e)
  115. return False
  116. @staticmethod
  117. def get_file_md5(file_path):
  118. md5 = hashlib.md5()
  119. with open(file_path, 'rb') as f:
  120. # 分块读取以支持大文件
  121. while chunk := f.read(8192):
  122. md5.update(chunk)
  123. return md5.hexdigest()
  124. @staticmethod
  125. def load_metadata(local_path):
  126. with open(f'{local_path}.metadata', 'r', encoding='utf-8') as f:
  127. file_metadata = json.loads(f.read())
  128. return file_metadata
  129. def get_file_info(self, file_id):
  130. '''
  131. {'createTime': '2025-06-03 15:57:37',
  132. 'updateTime': '2025-06-16 11:17:52',
  133. 'createById': '1',
  134. 'createBy': '超级管理员',
  135. 'updateBy': '超级管理员',
  136. 'id': 'c5a8f3d5811e572265501eeaf6d8b1cf',
  137. 'filePath': 'ten_1/lujie/document-mgr/SYG测试文库/test2.docx/2025/06/16/2025-06-161119224319835017216-c9b17214ea4144cf922f2fbfc0cdf70d.office_doc.docx',
  138. 'bucketName': 'document-mgr',
  139. 'name': 'test2.docx',
  140. 'shareRole': 'user',
  141. 'size': 26424,
  142. 'parentId': '6b79a0c8359b89653b95a14ad08b4954',
  143. 'type': 'office_doc',
  144. 'orderId': 12, 'delFlag': False,
  145. 'pathId': ['6b79a0c8359b89653b95a14ad08b4954'],
  146. 'knowledgeId': '6b79a0c8359b89653b95a14ad08b4954',
  147. 'tenantId': '1', 'commentable': True, '
  148. readNotify': True, 'nameSuffix': 'docx',
  149. 'fileStatus': 'NORMAL'}
  150. :param file_id:
  151. :return:
  152. '''
  153. try:
  154. resp = requests.get(f'{self.serve_host}/mgr/document/no/auth/dcLibrary/info/{file_id}',
  155. headers=self.headers)
  156. if not self.check_resp(resp):
  157. resp = requests.get(f'{self.serve_host}/mgr/document/no/auth/dcLibrary/info/{file_id}',
  158. headers=self.headers)
  159. if not resp.json()['data']:
  160. return 2
  161. return self.decryption(resp.json()['data'])
  162. except Exception as e:
  163. logger.exception(e)
  164. return False
  165. if __name__ == '__main__':
  166. client = ServerClient('http://172.10.3.71:10001','admin', '123456')
  167. # client = ServerClient('admin', 'jxkj123456')
  168. # client.download_file(
  169. # {'file_name': 'test.docx', 'file_id': 'c5a8f3d5811e572265501eeaf6d8b1cf', 'bucket_name': 'aaa', }, '')
  170. res = client.get_file_info(r'585ec718900fa82ce3d35d515c9d8a4b')
  171. res = client.decryption(
  172. "")
  173. for row in res['data']:
  174. print(row)
  175. a = {'createTime': '2025-06-13 11:48:35', 'updateTime': '2025-06-13 14:01:48', 'createById': '1',
  176. 'createBy': '超级管理员', 'updateBy': '超级管理员', 'id': 'c04b39ebfa8141746c20b88c7417f972',
  177. 'filePath': 'ten_1/2_2/document-mgr/法律法规/新建文件.docx/2025/06/13/2025-06-131118178409944354816-e251bced912f4d68bc50d80a33cbbd5d.office_doc.docx',
  178. 'bucketName': 'document-mgr', 'name': '新建文件.docx', 'shareRole': 'user', 'size': 29527,
  179. 'parentId': 'a3d958a6bba28357757ca20c87af9954', 'type': 'office_doc', 'orderId': 24, 'delFlag': False,
  180. 'pathId': ['a3d958a6bba28357757ca20c87af9954'], 'knowledgeId': 'a3d958a6bba28357757ca20c87af9954',
  181. 'tenantId': '1', 'commentable': True, 'readNotify': True, 'nameSuffix': 'docx', 'fileStatus': 'NORMAL',
  182. 'dcIdentifying': [
  183. {'id': '1', 'identifyingName': '文档分享', 'name': '文档分享', 'identifyingKey': 'document_share',
  184. 'identifyingType': 'document', 'isSelect': False, 'possessorIs': False},
  185. {'id': '11', 'identifyingName': '文库删除', 'name': '文库删除', 'identifyingKey': 'library_delete',
  186. 'identifyingType': 'library', 'isSelect': False, 'possessorIs': False},
  187. {'id': '12', 'identifyingName': '文库编辑', 'name': '文库编辑', 'identifyingKey': 'library_update',
  188. 'identifyingType': 'library', 'isSelect': False, 'possessorIs': False},
  189. {'id': '13', 'identifyingName': '文库下载', 'name': '文库下载', 'identifyingKey': 'library_down',
  190. 'identifyingType': 'library', 'isSelect': False, 'possessorIs': False},
  191. {'id': '5', 'identifyingName': '文档删除', 'name': '文档删除', 'identifyingKey': 'document_delete',
  192. 'identifyingType': 'document', 'isSelect': False, 'possessorIs': False},
  193. {'id': '6', 'identifyingName': '新建文档', 'name': '新建文档', 'identifyingKey': 'document_add',
  194. 'identifyingType': 'document', 'isSelect': False, 'possessorIs': False},
  195. {'id': '7', 'identifyingName': '文档下载', 'name': '文档下载', 'identifyingKey': 'document_down',
  196. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False},
  197. {'id': '8', 'identifyingName': '文档编辑', 'name': '文档编辑', 'identifyingKey': 'document_update',
  198. 'identifyingType': 'document', 'isSelect': False, 'possessorIs': False},
  199. {'id': '9', 'identifyingName': '文档移动', 'name': '文档移动', 'identifyingKey': 'document_move',
  200. 'identifyingType': 'document', 'isSelect': False, 'possessorIs': False},
  201. {'id': '14', 'identifyingName': '文档消息设置', 'name': '文档消息设置',
  202. 'identifyingKey': 'document_remind_settings', 'identifyingType': 'document', 'isSelect': False,
  203. 'possessorIs': False}, {'id': '15', 'identifyingName': '文库权限设置', 'name': '文库权限设置',
  204. 'identifyingKey': 'library_auth_settings', 'identifyingType': 'document',
  205. 'isSelect': False, 'possessorIs': False},
  206. {'id': '3', 'identifyingName': '文库消息设置', 'name': '文库消息设置',
  207. 'identifyingKey': 'library_remind_settings', 'identifyingType': 'library', 'isSelect': False,
  208. 'possessorIs': False}, {'id': '4', 'identifyingName': '文档权限设置', 'name': '文档权限设置',
  209. 'identifyingKey': 'document_auth_settings', 'identifyingType': 'document',
  210. 'isSelect': False, 'possessorIs': False},
  211. {'id': '1', 'identifyingName': '文档分享', 'name': '', 'identifyingKey': 'document_share',
  212. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  213. {'id': '10', 'identifyingName': '查看', 'name': '', 'identifyingKey': 'view',
  214. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  215. {'id': '11', 'identifyingName': '文库删除', 'name': '', 'identifyingKey': 'library_delete',
  216. 'identifyingType': 'library', 'isSelect': True, 'possessorIs': False, 'select': True},
  217. {'id': '12', 'identifyingName': '文库编辑', 'name': '', 'identifyingKey': 'library_update',
  218. 'identifyingType': 'library', 'isSelect': True, 'possessorIs': False, 'select': True},
  219. {'id': '13', 'identifyingName': '文库下载', 'name': '', 'identifyingKey': 'library_down',
  220. 'identifyingType': 'library', 'isSelect': True, 'possessorIs': False, 'select': True},
  221. {'id': '14', 'identifyingName': '文档消息设置', 'name': '', 'identifyingKey': 'document_remind_settings',
  222. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  223. {'id': '15', 'identifyingName': '文库权限设置', 'name': '', 'identifyingKey': 'library_auth_settings',
  224. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  225. {'id': '2', 'identifyingName': '文库转移项目', 'name': '', 'identifyingKey': 'library_transfer',
  226. 'identifyingType': 'library', 'isSelect': True, 'possessorIs': True, 'select': True},
  227. {'id': '3', 'identifyingName': '文库消息设置', 'name': '', 'identifyingKey': 'library_remind_settings',
  228. 'identifyingType': 'library', 'isSelect': True, 'possessorIs': False, 'select': True},
  229. {'id': '4', 'identifyingName': '文档权限设置', 'name': '', 'identifyingKey': 'document_auth_settings',
  230. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  231. {'id': '5', 'identifyingName': '文档删除', 'name': '', 'identifyingKey': 'document_delete',
  232. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  233. {'id': '6', 'identifyingName': '新建文档', 'name': '', 'identifyingKey': 'document_add',
  234. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  235. {'id': '7', 'identifyingName': '文档下载', 'name': '', 'identifyingKey': 'document_down',
  236. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  237. {'id': '8', 'identifyingName': '文档编辑', 'name': '', 'identifyingKey': 'document_update',
  238. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True},
  239. {'id': '9', 'identifyingName': '文档移动', 'name': '', 'identifyingKey': 'document_move',
  240. 'identifyingType': 'document', 'isSelect': True, 'possessorIs': False, 'select': True}], 'share': False}
  241. # access_token = client.login()
  242. # print(requests.post('http://120.195.49.22:7215/mgr/document/dcLibrary/knowledges?size=1000&current=1', headers={
  243. # 'authorization': f'Bearer {access_token}'}).json())