c11_api.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import base64
  2. import os
  3. import requests
  4. from requests_toolbelt.multipart import decoder
  5. import jinja2
  6. import json
  7. import re
  8. from bs4 import BeautifulSoup
  9. from .xml_prettify import prettify_xml
  10. import logging
  11. class c11_api:
  12. webservice = ""
  13. templates_dir = ""
  14. # templates_dir = "C:/GlobalCube/Tasks/gctools/templates"
  15. export_dir = "C:/GlobalCube/ReportOutput"
  16. log_dir = "C:/GlobalCube/Tasks/gctools/logs"
  17. headers = {}
  18. caf = ""
  19. cam = ""
  20. reports = []
  21. folders = []
  22. jobs = []
  23. def __init__(self, webservice="http://localhost:9300/bi/"):
  24. self.webservice = webservice
  25. self.templates_dir = os.path.dirname(__file__) + '/templates'
  26. self._env = jinja2.Environment(
  27. loader=jinja2.FileSystemLoader(self.templates_dir),
  28. autoescape=jinja2.select_autoescape(['html', 'xml'])
  29. )
  30. self.templates = {
  31. 'get_report': self._env.get_template('get_report.xml'),
  32. 'create_report': self._env.get_template('create_report.xml'),
  33. 'update_report': self._env.get_template('update_report.xml'),
  34. 'get_package': self._env.get_template('get_package.xml'),
  35. }
  36. @staticmethod
  37. def generate_token(message_base64):
  38. version = "V1".encode("utf-8")
  39. header_len = 4
  40. msg = base64.b64decode(message_base64)[1:]
  41. chunks = []
  42. while len(msg) >= header_len:
  43. chunk_len = int.from_bytes(msg[:header_len], byteorder="little")
  44. msg = msg[header_len:]
  45. chunks.append(msg[:chunk_len])
  46. msg = msg[chunk_len:]
  47. return base64.b64encode(version + chunks[-1]).decode("utf-8")
  48. def login(self, user='Global1', password='Cognos#11'):
  49. credentials = {
  50. "parameters": [
  51. {"name": "CAMNamespace", "value": "CognosEx"},
  52. {"name": "h_CAM_action", "value": "logonAs"},
  53. {"name": "CAMUsername", "value": user},
  54. {"name": "CAMPassword", "value": password}
  55. ]
  56. }
  57. self.session = requests.Session()
  58. r = self.session.get(self.webservice)
  59. self.headers = {'Content-Type': "application/json; charset=UTF-8", 'X-XSRF-TOKEN': self.session.cookies.get('XSRF-TOKEN')}
  60. r = self.session.post(self.webservice + "v1/login", data=json.dumps(credentials), headers=self.headers)
  61. self.caf = r.json()['cafContextId']
  62. self.cam = self.generate_token(r.cookies["usersessionid"])
  63. return self
  64. def get_folders(self):
  65. if len(self.folders) == 0:
  66. self.folders.append({'id': '_dot_public_folders', 'name': 'Team Content'})
  67. self.load_folder_list()
  68. return self.folders
  69. def load_folder_list(self, folder_id='_dot_public_folders', prefix='Team Content'):
  70. res = self.session.get(f"{self.webservice}v1/objects/{folder_id}/items", headers=self.headers)
  71. folder_list = sorted(res.json()['data'], key=lambda x: x['defaultName'])
  72. for f in folder_list:
  73. if f['type'] == 'folder':
  74. folder = {
  75. 'id': f['id'],
  76. 'name': prefix + '/' + f['defaultName'].replace('/', '-')
  77. }
  78. self.folders.append(folder)
  79. self.load_folder_list(folder['id'], folder['name'])
  80. elif f['type'] == 'report':
  81. report = {
  82. 'id': f['id'],
  83. 'name': f['defaultName'].replace('/', '-'),
  84. 'path': prefix
  85. }
  86. self.reports.append(report)
  87. elif f['type'] == 'jobDefinition':
  88. job = {
  89. 'id': f['id'],
  90. 'name': f['defaultName'],
  91. 'path': prefix
  92. }
  93. job['details'] = self.get_job_details(job['id'])
  94. self.jobs.append(job)
  95. def get_job_details(self, job_id):
  96. fields = ",".join([
  97. 'userInterfaces,disabled',
  98. 'runInAdvancedViewer,modificationTime,canBurst',
  99. 'defaultPortalAction',
  100. 'base.defaultName,tags,target.searchPath,target.disabled',
  101. 'options,base.options'
  102. ])
  103. res = self.session.get(f"{self.webservice}v1/objects/{job_id}?fields={fields}", headers=self.headers)
  104. job = res.json()['data'][0]
  105. job.pop('_meta', None)
  106. job.pop('id', None)
  107. job.pop('type', None)
  108. job.pop('defaultName', None)
  109. fields2 = ",".join([
  110. r'id,displaySequence,stepObject{defaultName}',
  111. r'stepObject{id},stepObject{parameters}',
  112. r'stepObject{canBurst},options,parameters'
  113. ])
  114. res = self.session.get(
  115. f"{self.webservice}v1/objects/{job_id}/items?types=jobStepDefinition&fields={fields2}",
  116. headers=self.headers
  117. )
  118. steps = res.json()['data']
  119. for s in steps:
  120. s.pop('_meta', None)
  121. if s['stepObject'] is not None:
  122. s['report_id'] = s['stepObject'][0]['id']
  123. s.pop('stepObject', None)
  124. job['steps'] = steps
  125. return job
  126. def get_report(self, report_id):
  127. self.get_folders()
  128. report = [r for r in self.reports if r['id'] == report_id]
  129. if len(report) == 0:
  130. return None
  131. report = report[0]
  132. if 'meta' not in report:
  133. report = self.get_report_specs(report)
  134. return report
  135. def get_reports_in_folder(self, folder, recursive=False, specs=False):
  136. self.get_folders()
  137. if recursive:
  138. res = [r for r in self.reports if r['path'].startswith(folder)]
  139. else:
  140. res = [r for r in self.reports if r['path'] == folder]
  141. if specs:
  142. return [self.get_report_specs(r) for r in res]
  143. return res
  144. def get_report_specs(self, report):
  145. headers = {
  146. 'Content-Type': 'text/xml; charset=UTF-8',
  147. 'X-XSRF-TOKEN': self.headers['X-XSRF-TOKEN'],
  148. 'X-RsCMStoreID': report['id'],
  149. 'X-UseRsConsumerMode': 'true',
  150. 'SOAPAction': 'http://www.ibm.com/xmlns/prod/cognos/reportService/202004/'
  151. }
  152. soap = self.templates['get_report'].render(
  153. {"caf": self.caf, "cam": self.cam,
  154. "report": report, "format": 'XHTML',
  155. "prompt": 'true', "tracking": "", "params": {}}
  156. )
  157. r = self.session.post(self.webservice + 'v1/reports', data=soap, headers=headers)
  158. if r.status_code == 500:
  159. bs = BeautifulSoup(r.text, 'xml')
  160. report['error'] = bs.find_all('messageString')[0].string
  161. logging.error(report['error'])
  162. return report
  163. parts = decoder.MultipartDecoder.from_response(r).parts
  164. meta = {'required': {}, 'optional': {}}
  165. bs = BeautifulSoup(parts[1].content, 'lxml')
  166. for sv in bs.find_all('selectvalue'):
  167. k = sv['parameter']
  168. req = 'required' if sv['required'] == 'true' else 'optional'
  169. v = dict([(opt['usevalue'], opt['displayvalue']) for opt in sv.find_all('selectoption')])
  170. meta[req][k] = v
  171. for sv in bs.find_all('selectdate'):
  172. k = sv['parameter']
  173. req = 'required' if sv['required'] == 'true' else 'optional'
  174. v = dict([(opt['usevalue'], opt.get('displayvalue', '')) for opt in sv.find_all('selectoption')])
  175. meta[req][k] = v
  176. filename = self.log_dir + f"/config/{report['path']}/{report['name']}.json"
  177. os.makedirs(os.path.dirname(filename), exist_ok=True)
  178. json.dump(meta, open(filename, 'w'), indent=2)
  179. report['meta'] = meta
  180. report['spec'] = parts[2].text
  181. path = report['path'].replace('Team Content/ReportOutput', '')
  182. report['filename'] = f"{self.export_dir}/{path}/{report['name']}.pdf"
  183. report['params'] = list(re.findall(r'\[([^\]]+)\]', report['filename']))
  184. for i, p in enumerate(report['params']):
  185. report['filename'] = report['filename'].replace('[' + p + ']', '{' + str(i) + '}')
  186. return report
  187. def request_unstubbed(self, report_id):
  188. report = self.get_report(report_id)
  189. if 'spec' not in report:
  190. return ''
  191. payload = json.dumps({'reportspec_stubbed': report['spec'], 'storeid': report['id']})
  192. headers = {
  193. 'Content-Type': 'application/json; charset=UTF-8',
  194. 'X-XSRF-TOKEN': self.session.cookies.get('XSRF-TOKEN'),
  195. 'authenticityToken': self.cam,
  196. 'X-UseRsConsumerMode': 'true',
  197. 'cafContextId': self.caf
  198. }
  199. r = self.session.post(self.webservice + 'v1/reports/unstubreport', data=payload, headers=headers)
  200. unstubbed = json.loads(r.text)['reportspec_full']
  201. unstubbed = re.sub(r' iid="[^"]*"', '', unstubbed)
  202. bs = BeautifulSoup(unstubbed, 'xml')
  203. for xa in bs.find_all('XMLAttributes'):
  204. if (
  205. xa.find_all('XMLAttribute', {'name': 'RS_dataType'}) or
  206. xa.find_all('XMLAttribute', {'name': 'RS_CreateExtendedDataItems'}) or
  207. xa.find_all('XMLAttribute', {'name': 'RS_legacyDrillDown'})
  208. ):
  209. continue
  210. if xa.find_all('XMLAttribute', {'name': 'supportsDefaultDataFormatting'}):
  211. for xa2 in xa.find_all('XMLAttribute'):
  212. if xa2.attrs['name'] != 'supportsDefaultDataFormatting':
  213. xa2.decompose()
  214. continue
  215. xa.decompose()
  216. for cti in bs.find_all('crosstabIntersection'):
  217. if len(list(cti.children)) == 0:
  218. cti.decompose()
  219. unstubbed_report = str(bs)
  220. unstubbed_report = prettify_xml(unstubbed_report).replace("'", '"')
  221. return unstubbed_report
  222. def get_report_headers(self, report_id=None):
  223. res = {
  224. 'Content-Type': 'text/xml; charset=UTF-8',
  225. 'X-XSRF-TOKEN': self.headers['X-XSRF-TOKEN'],
  226. 'X-UseRsConsumerMode': 'true',
  227. 'SOAPAction': 'http://www.ibm.com/xmlns/prod/cognos/reportService/202004/'
  228. }
  229. if report_id is not None:
  230. res['X-RsCMStoreID'] = report_id
  231. return res
  232. def request_file(self, report_id, params, format='PDF'):
  233. report = self.get_report(report_id)
  234. headers = self.get_report_headers(report_id)
  235. soap = self.templates['get_report'].render(
  236. {"caf": self.caf, "cam": self.cam,
  237. "report": report, "format": format,
  238. "prompt": 'false', "tracking": "", "params": params}
  239. ).encode("utf-8")
  240. r = self.session.post(self.webservice + 'v1/reports', data=soap, headers=headers)
  241. bs = BeautifulSoup(r.text, 'xml')
  242. if r.status_code == 200:
  243. try:
  244. parts = decoder.MultipartDecoder.from_response(r).parts
  245. except decoder.NonMultipartContentTypeException:
  246. return 500, 'Timeout'
  247. return 200, parts[1].content
  248. error = bs.find_all('messageString')[0].string
  249. logging.debug(error)
  250. return r.status_code, error
  251. def create_report(self, folder_id, fullpath):
  252. # self.session.get(self.webservice + 'v1/reports/templates?path=%2Fcontent%2Ffolder%5B%40name%3D%27Templates%27%5D/*[@objectClass=%27interactiveReport%27%20or%20@objectClass=%27report%27%20or%20@objectClass=%27reportTemplate%27]&maxResults=100&locale=de')
  253. # self.session.get(self.webservice + 'v1/reports/startupconfig?keys=supportedContentLocales,supportedCurrencies,supportedFonts,metadataInformationURI,glossaryURI&locale=de')
  254. headers = self.get_report_headers()
  255. soap = self.templates['get_package'].render(
  256. {"caf": self.caf, "cam": self.cam}
  257. ).encode("utf-8")
  258. r = self.session.post(self.webservice + 'v1/reports', data=soap, headers=headers)
  259. open('package.xml', 'wb').write(r.content)
  260. search_path = self.request_search_path(folder_id)
  261. report_name = os.path.basename(fullpath)
  262. unstubbed = open(fullpath, 'rb').read()
  263. headers['SOAPAction'] = 'http://www.ibm.com/xmlns/prod/cognos/reportService/202004/.session'
  264. headers['Referer'] = 'http://localhost:9300/bi/pat/rsapp.htm'
  265. # headers['caf'] = self.caf
  266. soap = self.templates['create_report'].render(
  267. {"caf": self.caf, "cam": self.cam,
  268. "search_path": search_path,
  269. "report_name": report_name, "unstubbed": unstubbed}
  270. ).encode("utf-8")
  271. r = self.session.post(self.webservice + 'v1/reports', data=soap, headers=headers)
  272. open('request_create.xml', 'wb').write(r.request.body)
  273. print(r.status_code)
  274. print(r.text)
  275. def update_report(self, report, fullpath):
  276. search_path = self.request_search_path(report['id'])
  277. unstubbed = open(fullpath, 'r').read()
  278. headers = self.get_report_headers(report['id'])
  279. # headers['Referer'] = 'http://localhost:9300/bi/pat/rsapp.htm'
  280. headers['caf'] = self.caf
  281. soap = self.templates['update_report'].render(
  282. {"caf": self.caf, "cam": self.cam,
  283. "search_path": search_path, "unstubbed": unstubbed}
  284. ) # .encode("utf-8")
  285. r = self.session.post(self.webservice + 'v1/reports', data=soap, headers=headers)
  286. # open('request_update.xml', 'wb').write(r.request.body)
  287. print(r.status_code)
  288. print(r.text)
  289. def create_folder(self, parent_id, folder_name):
  290. data = json.dumps({"defaultName": folder_name, "type": "folder"})
  291. res = self.session.post(
  292. f"{self.webservice}v1/objects/{parent_id}/items",
  293. headers=self.headers,
  294. data=data
  295. )
  296. if res.status_code == 201:
  297. loc = res.headers.get('Location')
  298. folder_id = loc.split('/')[-1]
  299. self.folders.append({'id': folder_id, 'name': folder_name})
  300. return folder_id
  301. def request_search_path(self, id):
  302. res = self.session.get(f"{self.webservice}v1/objects/{id}?fields=searchPath", headers=self.headers)
  303. return res.json()['data'][0]['searchPath']
  304. if __name__ == '__main__':
  305. api = c11_api()
  306. api.login()
  307. folders = api.get_folders()
  308. filename = 'C:/GlobalCube/Tasks/gctools/logs/config/folders.json'
  309. json.dump(folders, open(filename, 'w'), indent=2)
  310. filename = 'C:/GlobalCube/Tasks/gctools/logs/config/reports.json'
  311. json.dump(api.reports, open(filename, 'w'), indent=2)
  312. filename = 'C:/GlobalCube/Tasks/gctools/logs/config/jobs.json'
  313. json.dump(api.jobs, open(filename, 'w'), indent=2)