|
| 1 | +# |----------------------------------------------------------------------------- |
| 2 | +# | This source code is provided under the Apache 2.0 license -- |
| 3 | +# | and is provided AS IS with no warranty or guarantee of fit for purpose. -- |
| 4 | +# | See the project's LICENSE.md for details. -- |
| 5 | +# | Copyright LSEG 2025. All rights reserved. -- |
| 6 | +# |----------------------------------------------------------------------------- |
| 7 | + |
| 8 | + |
| 9 | +#!/usr/bin/env python |
| 10 | +import os |
| 11 | +import sys |
| 12 | +import datetime |
| 13 | +import time |
| 14 | +import json |
| 15 | +import base64 |
| 16 | +import zlib |
| 17 | +import binascii |
| 18 | +import lseg.data as ld |
| 19 | +from lseg.data.delivery import omm_stream |
| 20 | +from lseg.data import session |
| 21 | +from dotenv import load_dotenv |
| 22 | + |
| 23 | +# list to contain the news envelopes |
| 24 | +_news_envelopes = [] |
| 25 | +RIC_CODE = 'MRN_STORY' |
| 26 | +DOMAIN = 'NewsTextAnalytics' |
| 27 | +SERVICE = 'ELEKTRON_DD' |
| 28 | + |
| 29 | +# Config the encoding for the console |
| 30 | +sys.stdin.reconfigure(encoding='utf-8') |
| 31 | +sys.stdout.reconfigure(encoding='utf-8') |
| 32 | + |
| 33 | +username = '' |
| 34 | +password = '' |
| 35 | +app_key = '' |
| 36 | + |
| 37 | + |
| 38 | +def display_event(eventType, event): |
| 39 | + """Retrieve data: Callback function to display data or status events. """ |
| 40 | + current_time = datetime.datetime.now().time() |
| 41 | + print('----------------------------------------------------------') |
| 42 | + print(f'>>> {eventType} event received at {current_time}') |
| 43 | + print(json.dumps(event, indent=2)) |
| 44 | + |
| 45 | + return |
| 46 | + |
| 47 | + |
| 48 | +def process_mrn_update(event): |
| 49 | + """Process MRN Update messages.""" |
| 50 | + message_json = event |
| 51 | + fields_data = message_json['Fields'] |
| 52 | + |
| 53 | + # declare variables |
| 54 | + tot_size = 0 |
| 55 | + guid = None |
| 56 | + |
| 57 | + try: |
| 58 | + # Get data for all required fields |
| 59 | + fragment = base64.b64decode(fields_data['FRAGMENT']) |
| 60 | + frag_num = int(fields_data['FRAG_NUM']) |
| 61 | + guid = fields_data['GUID'] |
| 62 | + mrn_src = fields_data['MRN_SRC'] |
| 63 | + |
| 64 | + # print("GUID = %s" % guid) |
| 65 | + # print("FRAG_NUM = %d" % frag_num) |
| 66 | + # print("MRN_SRC = %s" % mrn_src) |
| 67 | + |
| 68 | + if frag_num > 1: # We are now processing more than one part of an envelope - retrieve the current details |
| 69 | + guid_index = next((index for (index, d) in enumerate( |
| 70 | + _news_envelopes) if d['GUID'] == guid), None) |
| 71 | + envelop = _news_envelopes[guid_index] |
| 72 | + if envelop and envelop['data']['MRN_SRC'] == mrn_src and frag_num == envelop['data']['FRAG_NUM'] + 1: |
| 73 | + print(f'process multiple fragments for guid {envelop["GUID"]}') |
| 74 | + |
| 75 | + # print(f'fragment before merge = {len(envelop["data"]["FRAGMENT"])}') |
| 76 | + # Merge incoming data to existing news envelop and getting FRAGMENT and TOT_SIZE data to local variables |
| 77 | + fragment = envelop['data']['FRAGMENT'] = envelop['data']['FRAGMENT'] + fragment |
| 78 | + envelop['data']['FRAG_NUM'] = frag_num |
| 79 | + tot_size = envelop['data']['tot_size'] |
| 80 | + print(f'TOT_SIZE = {tot_size}') |
| 81 | + print(f'Current FRAGMENT length = {len(fragment)}') |
| 82 | + |
| 83 | + # The multiple fragments news are not completed, waiting. |
| 84 | + if tot_size != len(fragment): |
| 85 | + return None |
| 86 | + # The multiple fragments news are completed, delete associate GUID envelop |
| 87 | + elif tot_size == len(fragment): |
| 88 | + del _news_envelopes[guid_index] |
| 89 | + else: |
| 90 | + print( |
| 91 | + f'Error: Cannot find fragment for GUID {guid} with matching FRAG_NUM or MRN_SRC {mrn_src}') |
| 92 | + return None |
| 93 | + else: # FRAG_NUM = 1 The first fragment |
| 94 | + tot_size = int(fields_data['TOT_SIZE']) |
| 95 | + print(f'FRAGMENT length = {len(fragment)}') |
| 96 | + # The fragment news is not completed, waiting and add this news data to envelop object. |
| 97 | + if tot_size != len(fragment): |
| 98 | + print(f'Add new fragments to news envelop for guid {guid}') |
| 99 | + _news_envelopes.append({ # the envelop object is a Python dictionary with GUID as a key and other fields are data |
| 100 | + 'GUID': guid, |
| 101 | + 'data': { |
| 102 | + 'FRAGMENT': fragment, |
| 103 | + 'MRN_SRC': mrn_src, |
| 104 | + 'FRAG_NUM': frag_num, |
| 105 | + "tot_size": tot_size |
| 106 | + } |
| 107 | + }) |
| 108 | + return None |
| 109 | + |
| 110 | + # News Fragment(s) completed, decompress and print data as JSON to console |
| 111 | + if tot_size == len(fragment): |
| 112 | + print(f'decompress News FRAGMENT(s) for GUID {guid}') |
| 113 | + decompressed_data = zlib.decompress(fragment, zlib.MAX_WBITS | 32) |
| 114 | + print(f'News = {json.loads(decompressed_data)}') |
| 115 | + |
| 116 | + except KeyError as keyerror: |
| 117 | + print('KeyError exception: ', keyerror) |
| 118 | + except IndexError as indexerror: |
| 119 | + print('IndexError exception: ', indexerror) |
| 120 | + except binascii.Error as b64error: |
| 121 | + print('base64 decoding exception:', b64error) |
| 122 | + except zlib.error as error: |
| 123 | + print('zlib decompressing exception: ', error) |
| 124 | + # Some console environments like Windows may encounter this unicode display as a limitation of OS |
| 125 | + except UnicodeEncodeError as encodeerror: |
| 126 | + print( |
| 127 | + f'UnicodeEncodeError exception. Cannot decode unicode character for {guid} in this environment: ', encodeerror) |
| 128 | + except Exception as specific_error: |
| 129 | + print(f'exception: str{specific_error}', sys.exc_info()[0]) |
| 130 | + |
| 131 | + |
| 132 | +if __name__ == '__main__': |
| 133 | + try: |
| 134 | + load_dotenv() |
| 135 | + username = os.getenv('RDP_MACHINEID') |
| 136 | + password = os.getenv('RDP_PASSWORD') |
| 137 | + app_key = os.getenv('APP_KEY') |
| 138 | + |
| 139 | + if not username or not password or not app_key: |
| 140 | + print("RDP_MACHINEID, RDP_PASSWORD, and APP_KEY are required environment variables") |
| 141 | + sys.exit(2) |
| 142 | + |
| 143 | + # Open the data session |
| 144 | + session = ld.session.platform.Definition( |
| 145 | + app_key=app_key, |
| 146 | + grant=ld.session.platform.GrantPassword( |
| 147 | + username=username, |
| 148 | + password=password |
| 149 | + ), |
| 150 | + signon_control=True |
| 151 | + ).get_session() |
| 152 | + ld.session.set_default(session) |
| 153 | + session.open() |
| 154 | + # ld.open_session() |
| 155 | + # ld.open_session(config_name='./lseg-data.devrel.config.json') |
| 156 | + except Exception as ex: |
| 157 | + print(f'Error in open_session: {str(ex)}') |
| 158 | + sys.exit(1) |
| 159 | + |
| 160 | + if str(session.open_state) == 'OpenState.Opened': |
| 161 | + print('Session opens, starting request data') |
| 162 | + else: |
| 163 | + print('Session open fail, exit an application') |
| 164 | + sys.exit(1) |
| 165 | + |
| 166 | + # Create an OMM stream and register event callbacks |
| 167 | + stream = omm_stream.Definition( |
| 168 | + name=RIC_CODE, |
| 169 | + domain=DOMAIN, |
| 170 | + service=SERVICE).get_stream() |
| 171 | + |
| 172 | + # Define the event callbacks |
| 173 | + # Refresh - the first full image we get back from the server |
| 174 | + stream.on_refresh( |
| 175 | + lambda event, item_stream: display_event('Refresh', event)) |
| 176 | + |
| 177 | + # Update - as and when field values change, we receive updates from the server and process the MRN data |
| 178 | + stream.on_update(lambda event, item_stream: process_mrn_update(event)) |
| 179 | + |
| 180 | + # Status - if data goes stale or item closes, we get a status message |
| 181 | + stream.on_status(lambda event, item_stream: display_event('Status', event)) |
| 182 | + |
| 183 | + # Other errors |
| 184 | + stream.on_error(lambda event, item_stream: display_event('Error', event)) |
| 185 | + |
| 186 | + # Open the stream |
| 187 | + |
| 188 | + # Send request to server and open stream |
| 189 | + stream.open() |
| 190 | + # We should receive the initial Refresh for the current field values |
| 191 | + # followed by updates for the fields as and when they occur |
| 192 | + |
| 193 | + try: |
| 194 | + while True: |
| 195 | + time.sleep(1) |
| 196 | + except KeyboardInterrupt: |
| 197 | + stream.close() |
| 198 | + # Close the session |
| 199 | + session.close() |
| 200 | + ld.close_session() |
0 commit comments