idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
39,900
def send_html ( self , html , body = None , msgtype = "m.text" ) : return self . client . api . send_message_event ( self . room_id , "m.room.message" , self . get_html_content ( html , body , msgtype ) )
Send an html formatted message .
39,901
def send_file ( self , url , name , ** fileinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.file" , extra_information = fileinfo )
Send a pre - uploaded file to the room .
39,902
def send_image ( self , url , name , ** imageinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.image" , extra_information = imageinfo )
Send a pre - uploaded image to the room .
39,903
def send_location ( self , geo_uri , name , thumb_url = None , ** thumb_info ) : return self . client . api . send_location ( self . room_id , geo_uri , name , thumb_url , thumb_info )
Send a location to the room .
39,904
def send_video ( self , url , name , ** videoinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.video" , extra_information = videoinfo )
Send a pre - uploaded video to the room .
39,905
def send_audio ( self , url , name , ** audioinfo ) : return self . client . api . send_content ( self . room_id , url , name , "m.audio" , extra_information = audioinfo )
Send a pre - uploaded audio to the room .
39,906
def redact_message ( self , event_id , reason = None ) : return self . client . api . redact_event ( self . room_id , event_id , reason )
Redacts the message with specified event_id for the given reason .
39,907
def add_listener ( self , callback , event_type = None ) : listener_id = uuid4 ( ) self . listeners . append ( { 'uid' : listener_id , 'callback' : callback , 'event_type' : event_type } ) return listener_id
Add a callback handler for events going to this room .
39,908
def remove_listener ( self , uid ) : self . listeners [ : ] = ( listener for listener in self . listeners if listener [ 'uid' ] != uid )
Remove listener with given uid .
39,909
def add_ephemeral_listener ( self , callback , event_type = None ) : listener_id = uuid4 ( ) self . ephemeral_listeners . append ( { 'uid' : listener_id , 'callback' : callback , 'event_type' : event_type } ) return listener_id
Add a callback handler for ephemeral events going to this room .
39,910
def remove_ephemeral_listener ( self , uid ) : self . ephemeral_listeners [ : ] = ( listener for listener in self . ephemeral_listeners if listener [ 'uid' ] != uid )
Remove ephemeral listener with given uid .
39,911
def invite_user ( self , user_id ) : try : self . client . api . invite_user ( self . room_id , user_id ) return True except MatrixRequestError : return False
Invite a user to this room .
39,912
def kick_user ( self , user_id , reason = "" ) : try : self . client . api . kick_user ( self . room_id , user_id ) return True except MatrixRequestError : return False
Kick a user from this room .
39,913
def leave ( self ) : try : self . client . api . leave_room ( self . room_id ) del self . client . rooms [ self . room_id ] return True except MatrixRequestError : return False
Leave the room .
39,914
def update_room_name ( self ) : try : response = self . client . api . get_room_name ( self . room_id ) if "name" in response and response [ "name" ] != self . name : self . name = response [ "name" ] return True else : return False except MatrixRequestError : return False
Updates self . name and returns True if room name has changed .
39,915
def set_room_name ( self , name ) : try : self . client . api . set_room_name ( self . room_id , name ) self . name = name return True except MatrixRequestError : return False
Return True if room name successfully changed .
39,916
def send_state_event ( self , event_type , content , state_key = "" ) : return self . client . api . send_state_event ( self . room_id , event_type , content , state_key )
Send a state event to the room .
39,917
def update_room_topic ( self ) : try : response = self . client . api . get_room_topic ( self . room_id ) if "topic" in response and response [ "topic" ] != self . topic : self . topic = response [ "topic" ] return True else : return False except MatrixRequestError : return False
Updates self . topic and returns True if room topic has changed .
39,918
def set_room_topic ( self , topic ) : try : self . client . api . set_room_topic ( self . room_id , topic ) self . topic = topic return True except MatrixRequestError : return False
Set room topic .
39,919
def update_aliases ( self ) : try : response = self . client . api . get_room_state ( self . room_id ) for chunk in response : if "content" in chunk and "aliases" in chunk [ "content" ] : if chunk [ "content" ] [ "aliases" ] != self . aliases : self . aliases = chunk [ "content" ] [ "aliases" ] return True else : return False except MatrixRequestError : return False
Get aliases information from room state .
39,920
def add_room_alias ( self , room_alias ) : try : self . client . api . set_room_alias ( self . room_id , room_alias ) return True except MatrixRequestError : return False
Add an alias to the room and return True if successful .
39,921
def backfill_previous_messages ( self , reverse = False , limit = 10 ) : res = self . client . api . get_room_messages ( self . room_id , self . prev_batch , direction = "b" , limit = limit ) events = res [ "chunk" ] if not reverse : events = reversed ( events ) for event in events : self . _put_event ( event )
Backfill handling of previous messages .
39,922
def modify_user_power_levels ( self , users = None , users_default = None ) : try : content = self . client . api . get_power_levels ( self . room_id ) if users_default : content [ "users_default" ] = users_default if users : if "users" in content : content [ "users" ] . update ( users ) else : content [ "users" ] = users for user , power_level in list ( content [ "users" ] . items ( ) ) : if power_level is None : del content [ "users" ] [ user ] self . client . api . set_power_levels ( self . room_id , content ) return True except MatrixRequestError : return False
Modify the power level for a subset of users
39,923
def modify_required_power_levels ( self , events = None , ** kwargs ) : try : content = self . client . api . get_power_levels ( self . room_id ) content . update ( kwargs ) for key , value in list ( content . items ( ) ) : if value is None : del content [ key ] if events : if "events" in content : content [ "events" ] . update ( events ) else : content [ "events" ] = events for event , power_level in list ( content [ "events" ] . items ( ) ) : if power_level is None : del content [ "events" ] [ event ] self . client . api . set_power_levels ( self . room_id , content ) return True except MatrixRequestError : return False
Modifies room power level requirements .
39,924
def set_invite_only ( self , invite_only ) : join_rule = "invite" if invite_only else "public" try : self . client . api . set_join_rule ( self . room_id , join_rule ) self . invite_only = invite_only return True except MatrixRequestError : return False
Set how the room can be joined .
39,925
def set_guest_access ( self , allow_guests ) : guest_access = "can_join" if allow_guests else "forbidden" try : self . client . api . set_guest_access ( self . room_id , guest_access ) self . guest_access = allow_guests return True except MatrixRequestError : return False
Set whether guests can join the room and return True if successful .
39,926
def enable_encryption ( self ) : try : self . send_state_event ( "m.room.encryption" , { "algorithm" : "m.megolm.v1.aes-sha2" } ) self . encrypted = True return True except MatrixRequestError : return False
Enables encryption in the room .
39,927
def example ( host , user , password , token ) : client = None try : if token : print ( 'token login' ) client = MatrixClient ( host , token = token , user_id = user ) else : print ( 'password login' ) client = MatrixClient ( host ) token = client . login_with_password ( user , password ) print ( 'got token: %s' % token ) except MatrixRequestError as e : print ( e ) if e . code == 403 : print ( "Bad username or password" ) exit ( 2 ) elif e . code == 401 : print ( "Bad username or token" ) exit ( 3 ) else : print ( "Verify server details." ) exit ( 4 ) except MissingSchema as e : print ( e ) print ( "Bad formatting of URL." ) exit ( 5 ) except InvalidSchema as e : print ( e ) print ( "Invalid URL schema" ) exit ( 6 ) print ( "is in rooms" ) for room_id , room in client . get_rooms ( ) . items ( ) : print ( room_id )
run the example .
39,928
def main ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "--host" , type = str , required = True ) parser . add_argument ( "--user" , type = str , required = True ) parser . add_argument ( "--password" , type = str ) parser . add_argument ( "--token" , type = str ) args = parser . parse_args ( ) if not args . password and not args . token : print ( 'password or token is required' ) exit ( 1 ) example ( args . host , args . user , args . password , args . token )
Main entry .
39,929
def sync ( self , since = None , timeout_ms = 30000 , filter = None , full_state = None , set_presence = None ) : request = { "timeout" : int ( timeout_ms ) } if since : request [ "since" ] = since if filter : request [ "filter" ] = filter if full_state : request [ "full_state" ] = json . dumps ( full_state ) if set_presence : request [ "set_presence" ] = set_presence return self . _send ( "GET" , "/sync" , query_params = request , api_path = MATRIX_V2_API_PATH )
Perform a sync request .
39,930
def send_location ( self , room_id , geo_uri , name , thumb_url = None , thumb_info = None , timestamp = None ) : content_pack = { "geo_uri" : geo_uri , "msgtype" : "m.location" , "body" : name , } if thumb_url : content_pack [ "thumbnail_url" ] = thumb_url if thumb_info : content_pack [ "thumbnail_info" ] = thumb_info return self . send_message_event ( room_id , "m.room.message" , content_pack , timestamp = timestamp )
Send m . location message event
39,931
def kick_user ( self , room_id , user_id , reason = "" ) : self . set_membership ( room_id , user_id , "leave" , reason )
Calls set_membership with membership = leave for the user_id provided
39,932
def media_download ( self , mxcurl , allow_remote = True ) : query_params = { } if not allow_remote : query_params [ "allow_remote" ] = False if mxcurl . startswith ( 'mxc://' ) : return self . _send ( "GET" , mxcurl [ 6 : ] , api_path = "/_matrix/media/r0/download/" , query_params = query_params , return_json = False ) else : raise ValueError ( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl )
Download raw media from provided mxc URL .
39,933
def get_thumbnail ( self , mxcurl , width , height , method = 'scale' , allow_remote = True ) : if method not in [ 'scale' , 'crop' ] : raise ValueError ( "Unsupported thumb method '%s'" % method ) query_params = { "width" : width , "height" : height , "method" : method } if not allow_remote : query_params [ "allow_remote" ] = False if mxcurl . startswith ( 'mxc://' ) : return self . _send ( "GET" , mxcurl [ 6 : ] , query_params = query_params , api_path = "/_matrix/media/r0/thumbnail/" , return_json = False ) else : raise ValueError ( "MXC URL '%s' did not begin with 'mxc://'" % mxcurl )
Download raw media thumbnail from provided mxc URL .
39,934
def get_url_preview ( self , url , ts = None ) : params = { 'url' : url } if ts : params [ 'ts' ] = ts return self . _send ( "GET" , "" , query_params = params , api_path = "/_matrix/media/r0/preview_url" )
Get preview for URL .
39,935
def get_room_id ( self , room_alias ) : content = self . _send ( "GET" , "/directory/room/{}" . format ( quote ( room_alias ) ) ) return content . get ( "room_id" , None )
Get room id from its alias .
39,936
def set_room_alias ( self , room_id , room_alias ) : data = { "room_id" : room_id } return self . _send ( "PUT" , "/directory/room/{}" . format ( quote ( room_alias ) ) , content = data )
Set alias to room id
39,937
def set_join_rule ( self , room_id , join_rule ) : content = { "join_rule" : join_rule } return self . send_state_event ( room_id , "m.room.join_rules" , content )
Set the rule for users wishing to join the room .
39,938
def set_guest_access ( self , room_id , guest_access ) : content = { "guest_access" : guest_access } return self . send_state_event ( room_id , "m.room.guest_access" , content )
Set the guest access policy of the room .
39,939
def update_device_info ( self , device_id , display_name ) : content = { "display_name" : display_name } return self . _send ( "PUT" , "/devices/%s" % device_id , content = content )
Update the display name of a device .
39,940
def delete_device ( self , auth_body , device_id ) : content = { "auth" : auth_body } return self . _send ( "DELETE" , "/devices/%s" % device_id , content = content )
Deletes the given device and invalidates any access token associated with it .
39,941
def delete_devices ( self , auth_body , devices ) : content = { "auth" : auth_body , "devices" : devices } return self . _send ( "POST" , "/delete_devices" , content = content )
Bulk deletion of devices .
39,942
def upload_keys ( self , device_keys = None , one_time_keys = None ) : content = { } if device_keys : content [ "device_keys" ] = device_keys if one_time_keys : content [ "one_time_keys" ] = one_time_keys return self . _send ( "POST" , "/keys/upload" , content = content )
Publishes end - to - end encryption keys for the device .
39,943
def query_keys ( self , user_devices , timeout = None , token = None ) : content = { "device_keys" : user_devices } if timeout : content [ "timeout" ] = timeout if token : content [ "token" ] = token return self . _send ( "POST" , "/keys/query" , content = content )
Query HS for public keys by user and optionally device .
39,944
def claim_keys ( self , key_request , timeout = None ) : content = { "one_time_keys" : key_request } if timeout : content [ "timeout" ] = timeout return self . _send ( "POST" , "/keys/claim" , content = content )
Claims one - time keys for use in pre - key messages .
39,945
def key_changes ( self , from_token , to_token ) : params = { "from" : from_token , "to" : to_token } return self . _send ( "GET" , "/keys/changes" , query_params = params )
Gets a list of users who have updated their device identity keys .
39,946
def send_to_device ( self , event_type , messages , txn_id = None ) : txn_id = txn_id if txn_id else self . _make_txn_id ( ) return self . _send ( "PUT" , "/sendToDevice/{}/{}" . format ( event_type , txn_id ) , content = { "messages" : messages } )
Sends send - to - device events to a set of client devices .
39,947
def register_with_password ( self , username , password ) : response = self . api . register ( auth_body = { "type" : "m.login.dummy" } , kind = 'user' , username = username , password = password , ) return self . _post_registration ( response )
Register for a new account on this HS .
39,948
def login_with_password_no_sync ( self , username , password ) : warn ( "login_with_password_no_sync is deprecated. Use login with sync=False." , DeprecationWarning ) return self . login ( username , password , sync = False )
Deprecated . Use login with sync = False .
39,949
def login_with_password ( self , username , password , limit = 10 ) : warn ( "login_with_password is deprecated. Use login with sync=True." , DeprecationWarning ) return self . login ( username , password , limit , sync = True )
Deprecated . Use login with sync = True .
39,950
def login ( self , username , password , limit = 10 , sync = True , device_id = None ) : response = self . api . login ( "m.login.password" , user = username , password = password , device_id = device_id ) self . user_id = response [ "user_id" ] self . token = response [ "access_token" ] self . hs = response [ "home_server" ] self . api . token = self . token self . device_id = response [ "device_id" ] if self . _encryption : self . olm_device = OlmDevice ( self . api , self . user_id , self . device_id , ** self . encryption_conf ) self . olm_device . upload_identity_keys ( ) self . olm_device . upload_one_time_keys ( ) if sync : self . sync_filter = '{ "room": { "timeline" : { "limit" : %i } } }' % limit self . _sync ( ) return self . token
Login to the homeserver .
39,951
def create_room ( self , alias = None , is_public = False , invitees = None ) : response = self . api . create_room ( alias = alias , is_public = is_public , invitees = invitees ) return self . _mkroom ( response [ "room_id" ] )
Create a new room on the homeserver .
39,952
def add_listener ( self , callback , event_type = None ) : listener_uid = uuid4 ( ) self . listeners . append ( { 'uid' : listener_uid , 'callback' : callback , 'event_type' : event_type } ) return listener_uid
Add a listener that will send a callback when the client recieves an event .
39,953
def add_presence_listener ( self , callback ) : listener_uid = uuid4 ( ) self . presence_listeners [ listener_uid ] = callback return listener_uid
Add a presence listener that will send a callback when the client receives a presence update .
39,954
def listen_forever ( self , timeout_ms = 30000 , exception_handler = None , bad_sync_timeout = 5 ) : _bad_sync_timeout = bad_sync_timeout self . should_listen = True while ( self . should_listen ) : try : self . _sync ( timeout_ms ) _bad_sync_timeout = bad_sync_timeout except MatrixRequestError as e : logger . warning ( "A MatrixRequestError occured during sync." ) if e . code >= 500 : logger . warning ( "Problem occured serverside. Waiting %i seconds" , bad_sync_timeout ) sleep ( bad_sync_timeout ) _bad_sync_timeout = min ( _bad_sync_timeout * 2 , self . bad_sync_timeout_limit ) elif exception_handler is not None : exception_handler ( e ) else : raise except Exception as e : logger . exception ( "Exception thrown during sync" ) if exception_handler is not None : exception_handler ( e ) else : raise
Keep listening for events forever .
39,955
def start_listener_thread ( self , timeout_ms = 30000 , exception_handler = None ) : try : thread = Thread ( target = self . listen_forever , args = ( timeout_ms , exception_handler ) ) thread . daemon = True self . sync_thread = thread self . should_listen = True thread . start ( ) except RuntimeError : e = sys . exc_info ( ) [ 0 ] logger . error ( "Error: unable to start thread. %s" , str ( e ) )
Start a listener thread to listen for events in the background .
39,956
def stop_listener_thread ( self ) : if self . sync_thread : self . should_listen = False self . sync_thread . join ( ) self . sync_thread = None
Stop listener thread running in the background
39,957
def upload ( self , content , content_type , filename = None ) : try : response = self . api . media_upload ( content , content_type , filename ) if "content_uri" in response : return response [ "content_uri" ] else : raise MatrixUnexpectedResponse ( "The upload was successful, but content_uri wasn't found." ) except MatrixRequestError as e : raise MatrixRequestError ( code = e . code , content = "Upload failed: %s" % e )
Upload content to the home server and recieve a MXC url .
39,958
def remove_room_alias ( self , room_alias ) : try : self . api . remove_room_alias ( room_alias ) return True except MatrixRequestError : return False
Remove mapping of an alias
39,959
def upload_identity_keys ( self ) : device_keys = { 'user_id' : self . user_id , 'device_id' : self . device_id , 'algorithms' : self . _algorithms , 'keys' : { '{}:{}' . format ( alg , self . device_id ) : key for alg , key in self . identity_keys . items ( ) } } self . sign_json ( device_keys ) ret = self . api . upload_keys ( device_keys = device_keys ) self . one_time_keys_manager . server_counts = ret [ 'one_time_key_counts' ] logger . info ( 'Uploaded identity keys.' )
Uploads this device s identity keys to HS .
39,960
def upload_one_time_keys ( self , force_update = False ) : if force_update or not self . one_time_keys_manager . server_counts : counts = self . api . upload_keys ( ) [ 'one_time_key_counts' ] self . one_time_keys_manager . server_counts = counts signed_keys_to_upload = self . one_time_keys_manager . signed_curve25519_to_upload unsigned_keys_to_upload = self . one_time_keys_manager . curve25519_to_upload self . olm_account . generate_one_time_keys ( signed_keys_to_upload + unsigned_keys_to_upload ) one_time_keys = { } keys = self . olm_account . one_time_keys [ 'curve25519' ] for i , key_id in enumerate ( keys ) : if i < signed_keys_to_upload : key = self . sign_json ( { 'key' : keys [ key_id ] } ) key_type = 'signed_curve25519' else : key = keys [ key_id ] key_type = 'curve25519' one_time_keys [ '{}:{}' . format ( key_type , key_id ) ] = key ret = self . api . upload_keys ( one_time_keys = one_time_keys ) self . one_time_keys_manager . server_counts = ret [ 'one_time_key_counts' ] self . olm_account . mark_keys_as_published ( ) keys_uploaded = { } if unsigned_keys_to_upload : keys_uploaded [ 'curve25519' ] = unsigned_keys_to_upload if signed_keys_to_upload : keys_uploaded [ 'signed_curve25519' ] = signed_keys_to_upload logger . info ( 'Uploaded new one-time keys: %s.' , keys_uploaded ) return keys_uploaded
Uploads new one - time keys to the HS if needed .
39,961
def update_one_time_key_counts ( self , counts ) : self . one_time_keys_manager . server_counts = counts if self . one_time_keys_manager . should_upload ( ) : logger . info ( 'Uploading new one-time keys.' ) self . upload_one_time_keys ( )
Update data on one - time keys count and upload new ones if necessary .
39,962
def sign_json ( self , json ) : signatures = json . pop ( 'signatures' , { } ) unsigned = json . pop ( 'unsigned' , None ) signature_base64 = self . olm_account . sign ( encode_canonical_json ( json ) ) key_id = 'ed25519:{}' . format ( self . device_id ) signatures . setdefault ( self . user_id , { } ) [ key_id ] = signature_base64 json [ 'signatures' ] = signatures if unsigned : json [ 'unsigned' ] = unsigned return json
Signs a JSON object .
39,963
def verify_json ( self , json , user_key , user_id , device_id ) : try : signatures = json . pop ( 'signatures' ) except KeyError : return False key_id = 'ed25519:{}' . format ( device_id ) try : signature_base64 = signatures [ user_id ] [ key_id ] except KeyError : json [ 'signatures' ] = signatures return False unsigned = json . pop ( 'unsigned' , None ) try : olm . ed25519_verify ( user_key , encode_canonical_json ( json ) , signature_base64 ) success = True except olm . utility . OlmVerifyError : success = False json [ 'signatures' ] = signatures if unsigned : json [ 'unsigned' ] = unsigned return success
Verifies a signed key object s signature .
39,964
def get_display_name ( self , room = None ) : if room : try : return room . members_displaynames [ self . user_id ] except KeyError : return self . user_id if not self . displayname : self . displayname = self . api . get_display_name ( self . user_id ) return self . displayname or self . user_id
Get this user s display name .
39,965
def set_display_name ( self , display_name ) : self . displayname = display_name return self . api . set_display_name ( self . user_id , display_name )
Set this users display name .
39,966
def prepare_encrypted_request ( self , session , endpoint , message ) : host = urlsplit ( endpoint ) . hostname if self . protocol == 'credssp' and len ( message ) > self . SIXTEN_KB : content_type = 'multipart/x-multi-encrypted' encrypted_message = b'' message_chunks = [ message [ i : i + self . SIXTEN_KB ] for i in range ( 0 , len ( message ) , self . SIXTEN_KB ) ] for message_chunk in message_chunks : encrypted_chunk = self . _encrypt_message ( message_chunk , host ) encrypted_message += encrypted_chunk else : content_type = 'multipart/encrypted' encrypted_message = self . _encrypt_message ( message , host ) encrypted_message += self . MIME_BOUNDARY + b"--\r\n" request = requests . Request ( 'POST' , endpoint , data = encrypted_message ) prepared_request = session . prepare_request ( request ) prepared_request . headers [ 'Content-Length' ] = str ( len ( prepared_request . body ) ) prepared_request . headers [ 'Content-Type' ] = '{0};protocol="{1}";boundary="Encrypted Boundary"' . format ( content_type , self . protocol_string . decode ( ) ) return prepared_request
Creates a prepared request to send to the server with an encrypted message and correct headers
39,967
def parse_encrypted_response ( self , response ) : content_type = response . headers [ 'Content-Type' ] if 'protocol="{0}"' . format ( self . protocol_string . decode ( ) ) in content_type : host = urlsplit ( response . request . url ) . hostname msg = self . _decrypt_response ( response , host ) else : msg = response . text return msg
Takes in the encrypted response from the server and decrypts it
39,968
def open_shell ( self , i_stream = 'stdin' , o_stream = 'stdout stderr' , working_directory = None , env_vars = None , noprofile = False , codepage = 437 , lifetime = None , idle_timeout = None ) : req = { 'env:Envelope' : self . _get_soap_header ( resource_uri = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd' , action = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Create' ) } header = req [ 'env:Envelope' ] [ 'env:Header' ] header [ 'w:OptionSet' ] = { 'w:Option' : [ { '@Name' : 'WINRS_NOPROFILE' , '#text' : str ( noprofile ) . upper ( ) } , { '@Name' : 'WINRS_CODEPAGE' , '#text' : str ( codepage ) } ] } shell = req [ 'env:Envelope' ] . setdefault ( 'env:Body' , { } ) . setdefault ( 'rsp:Shell' , { } ) shell [ 'rsp:InputStreams' ] = i_stream shell [ 'rsp:OutputStreams' ] = o_stream if working_directory : shell [ 'rsp:WorkingDirectory' ] = working_directory if idle_timeout : shell [ 'rsp:IdleTimeOut' ] = idle_timeout if env_vars : env = shell . setdefault ( 'rsp:Environment' , { } ) for key , value in env_vars . items ( ) : env [ 'rsp:Variable' ] = { '@Name' : key , '#text' : value } res = self . send_message ( xmltodict . unparse ( req ) ) root = ET . fromstring ( res ) return next ( node for node in root . findall ( './/*' ) if node . get ( 'Name' ) == 'ShellId' ) . text
Create a Shell on the destination host
39,969
def close_shell ( self , shell_id ) : message_id = uuid . uuid4 ( ) req = { 'env:Envelope' : self . _get_soap_header ( resource_uri = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd' , action = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete' , shell_id = shell_id , message_id = message_id ) } req [ 'env:Envelope' ] . setdefault ( 'env:Body' , { } ) res = self . send_message ( xmltodict . unparse ( req ) ) root = ET . fromstring ( res ) relates_to = next ( node for node in root . findall ( './/*' ) if node . tag . endswith ( 'RelatesTo' ) ) . text assert uuid . UUID ( relates_to . replace ( 'uuid:' , '' ) ) == message_id
Close the shell
39,970
def run_command ( self , shell_id , command , arguments = ( ) , console_mode_stdin = True , skip_cmd_shell = False ) : req = { 'env:Envelope' : self . _get_soap_header ( resource_uri = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd' , action = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command' , shell_id = shell_id ) } header = req [ 'env:Envelope' ] [ 'env:Header' ] header [ 'w:OptionSet' ] = { 'w:Option' : [ { '@Name' : 'WINRS_CONSOLEMODE_STDIN' , '#text' : str ( console_mode_stdin ) . upper ( ) } , { '@Name' : 'WINRS_SKIP_CMD_SHELL' , '#text' : str ( skip_cmd_shell ) . upper ( ) } ] } cmd_line = req [ 'env:Envelope' ] . setdefault ( 'env:Body' , { } ) . setdefault ( 'rsp:CommandLine' , { } ) cmd_line [ 'rsp:Command' ] = { '#text' : command } if arguments : unicode_args = [ a if isinstance ( a , text_type ) else a . decode ( 'utf-8' ) for a in arguments ] cmd_line [ 'rsp:Arguments' ] = u' ' . join ( unicode_args ) res = self . send_message ( xmltodict . unparse ( req ) ) root = ET . fromstring ( res ) command_id = next ( node for node in root . findall ( './/*' ) if node . tag . endswith ( 'CommandId' ) ) . text return command_id
Run a command on a machine with an open shell
39,971
def get_command_output ( self , shell_id , command_id ) : stdout_buffer , stderr_buffer = [ ] , [ ] command_done = False while not command_done : try : stdout , stderr , return_code , command_done = self . _raw_get_command_output ( shell_id , command_id ) stdout_buffer . append ( stdout ) stderr_buffer . append ( stderr ) except WinRMOperationTimeoutError as e : pass return b'' . join ( stdout_buffer ) , b'' . join ( stderr_buffer ) , return_code
Get the Output of the given shell and command
39,972
def run_ps ( self , script ) : encoded_ps = b64encode ( script . encode ( 'utf_16_le' ) ) . decode ( 'ascii' ) rs = self . run_cmd ( 'powershell -encodedcommand {0}' . format ( encoded_ps ) ) if len ( rs . std_err ) : rs . std_err = self . _clean_error_msg ( rs . std_err ) return rs
base64 encodes a Powershell script and executes the powershell encoded script command
39,973
def _clean_error_msg ( self , msg ) : if msg . startswith ( b"#< CLIXML\r\n" ) : msg_xml = msg [ 11 : ] try : msg_xml = self . _strip_namespace ( msg_xml ) root = ET . fromstring ( msg_xml ) nodes = root . findall ( "./S" ) new_msg = "" for s in nodes : new_msg += s . text . replace ( "_x000D__x000A_" , "\n" ) except Exception as e : print ( "Warning: there was a problem converting the Powershell" " error message: %s" % ( e ) ) else : if len ( new_msg ) : return new_msg . strip ( ) . encode ( 'utf-8' ) return msg
converts a Powershell CLIXML message to a more human readable string
39,974
def _strip_namespace ( self , xml ) : p = re . compile ( b"xmlns=*[\"\"][^\"\"]*[\"\"]" ) allmatches = p . finditer ( xml ) for match in allmatches : xml = xml . replace ( match . group ( ) , b"" ) return xml
strips any namespaces from an xml string
39,975
def return_handler ( module_logger , first_is_session = True ) : def _outer ( visa_library_method ) : def _inner ( self , session , * args , ** kwargs ) : ret_value = visa_library_method ( * args , ** kwargs ) module_logger . debug ( '%s%s -> %r' , visa_library_method . __name__ , _args_to_str ( args , kwargs ) , ret_value ) try : ret_value = constants . StatusCode ( ret_value ) except ValueError : pass if first_is_session : self . _last_status = ret_value self . _last_status_in_session [ session ] = ret_value if ret_value < 0 : raise VisaIOError ( ret_value ) if ret_value in self . issue_warning_on : if session and ret_value not in self . _ignore_warning_in_session [ session ] : module_logger . warn ( VisaIOWarning ( ret_value ) , stacklevel = 2 ) return ret_value return _inner return _outer
Decorator for VISA library classes .
39,976
def list_backends ( ) : return [ 'ni' ] + [ name for ( loader , name , ispkg ) in pkgutil . iter_modules ( ) if name . startswith ( 'pyvisa-' ) and not name . endswith ( '-script' ) ]
Return installed backends .
39,977
def get_wrapper_class ( backend_name ) : try : return _WRAPPERS [ backend_name ] except KeyError : if backend_name == 'ni' : from . ctwrapper import NIVisaLibrary _WRAPPERS [ 'ni' ] = NIVisaLibrary return NIVisaLibrary try : pkg = __import__ ( 'pyvisa-' + backend_name ) _WRAPPERS [ backend_name ] = cls = pkg . WRAPPER_CLASS return cls except ImportError : raise ValueError ( 'Wrapper not found: No package named pyvisa-%s' % backend_name )
Return the WRAPPER_CLASS for a given backend .
39,978
def open_visa_library ( specification ) : if not specification : logger . debug ( 'No visa library specified, trying to find alternatives.' ) try : specification = os . environ [ 'PYVISA_LIBRARY' ] except KeyError : logger . debug ( 'Environment variable PYVISA_LIBRARY is unset.' ) try : argument , wrapper = specification . split ( '@' ) except ValueError : argument = specification wrapper = None if wrapper is None : if argument : wrapper = 'ni' else : wrapper = _get_default_wrapper ( ) cls = get_wrapper_class ( wrapper ) try : return cls ( argument ) except Exception as e : logger . debug ( 'Could not open VISA wrapper %s: %s\n%s' , cls , str ( argument ) , e ) raise
Helper function to create a VISA library wrapper .
39,979
def get_last_status_in_session ( self , session ) : try : return self . _last_status_in_session [ session ] except KeyError : raise errors . Error ( 'The session %r does not seem to be valid as it does not have any last status' % session )
Last status in session .
39,980
def ignore_warning ( self , session , * warnings_constants ) : self . _ignore_warning_in_session [ session ] . update ( warnings_constants ) yield self . _ignore_warning_in_session [ session ] . difference_update ( warnings_constants )
A session dependent context for ignoring warnings
39,981
def uninstall_all_visa_handlers ( self , session ) : if session is not None : self . __uninstall_all_handlers_helper ( session ) else : for session in list ( self . handlers ) : self . __uninstall_all_handlers_helper ( session )
Uninstalls all previously installed handlers for a particular session .
39,982
def write_memory ( self , session , space , offset , data , width , extended = False ) : if width == 8 : return self . out_8 ( session , space , offset , data , extended ) elif width == 16 : return self . out_16 ( session , space , offset , data , extended ) elif width == 32 : return self . out_32 ( session , space , offset , data , extended ) elif width == 64 : return self . out_64 ( session , space , offset , data , extended ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32, or 64' % width )
Write in an 8 - bit 16 - bit 32 - bit 64 - bit value to the specified memory space and offset .
39,983
def peek ( self , session , address , width ) : if width == 8 : return self . peek_8 ( session , address ) elif width == 16 : return self . peek_16 ( session , address ) elif width == 32 : return self . peek_32 ( session , address ) elif width == 64 : return self . peek_64 ( session , address ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32 or 64' % width )
Read an 8 16 32 or 64 - bit value from the specified address .
39,984
def poke ( self , session , address , width , data ) : if width == 8 : return self . poke_8 ( session , address , data ) elif width == 16 : return self . poke_16 ( session , address , data ) elif width == 32 : return self . poke_32 ( session , address , data ) elif width == 64 : return self . poke_64 ( session , address , data ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32, or 64' % width )
Writes an 8 16 32 or 64 - bit value from the specified address .
39,985
def close ( self ) : try : logger . debug ( 'Closing ResourceManager (session: %s)' , self . session ) for resource in self . _created_resources : resource . close ( ) self . visalib . close ( self . session ) self . session = None self . visalib . resource_manager = None except errors . InvalidSession : pass
Close the resource manager session .
39,986
def list_resources_info ( self , query = '?*::INSTR' ) : return dict ( ( resource , self . resource_info ( resource ) ) for resource in self . list_resources ( query ) )
Returns a dictionary mapping resource names to resource extended information of all connected devices matching query .
39,987
def open_bare_resource ( self , resource_name , access_mode = constants . AccessModes . no_lock , open_timeout = constants . VI_TMO_IMMEDIATE ) : return self . visalib . open ( self . session , resource_name , access_mode , open_timeout )
Open the specified resource without wrapping into a class
39,988
def open_resource ( self , resource_name , access_mode = constants . AccessModes . no_lock , open_timeout = constants . VI_TMO_IMMEDIATE , resource_pyclass = None , ** kwargs ) : if resource_pyclass is None : info = self . resource_info ( resource_name , extended = True ) try : resource_pyclass = self . _resource_classes [ ( info . interface_type , info . resource_class ) ] except KeyError : resource_pyclass = self . _resource_classes [ ( constants . InterfaceType . unknown , '' ) ] logger . warning ( 'There is no class defined for %r. Using Resource' , ( info . interface_type , info . resource_class ) ) res = resource_pyclass ( self , resource_name ) for key in kwargs . keys ( ) : try : getattr ( res , key ) present = True except AttributeError : present = False except errors . InvalidSession : present = True if not present : raise ValueError ( '%r is not a valid attribute for type %s' % ( key , res . __class__ . __name__ ) ) res . open ( access_mode , open_timeout ) self . _created_resources . add ( res ) for key , value in kwargs . items ( ) : setattr ( res , key , value ) return res
Return an instrument for the resource name .
39,989
def register_subclass ( cls ) : key = cls . interface_type , cls . resource_class if key in _SUBCLASSES : raise ValueError ( 'Class already registered for %s and %s' % key ) _SUBCLASSES [ ( cls . interface_type , cls . resource_class ) ] = cls _INTERFACE_TYPES . add ( cls . interface_type ) _RESOURCE_CLASSES [ cls . interface_type ] . add ( cls . resource_class ) if cls . is_rc_optional : if cls . interface_type in _DEFAULT_RC : raise ValueError ( 'Default already specified for %s' % cls . interface_type ) _DEFAULT_RC [ cls . interface_type ] = cls . resource_class return cls
Register a subclass for a given interface type and resource class .
39,990
def bad_syntax ( cls , syntax , resource_name , ex = None ) : if ex : msg = "The syntax is '%s' (%s)." % ( syntax , ex ) else : msg = "The syntax is '%s'." % syntax msg = "Could not parse '%s'. %s" % ( resource_name , msg ) return cls ( msg )
Exception used when the resource name cannot be parsed .
39,991
def rc_notfound ( cls , interface_type , resource_name = None ) : msg = "Resource class for %s not provided and default not found." % interface_type if resource_name : msg = "Could not parse '%s'. %s" % ( resource_name , msg ) return cls ( msg )
Exception used when no resource class is provided and no default is found .
39,992
def from_string ( cls , resource_name ) : uname = resource_name . upper ( ) for interface_type in _INTERFACE_TYPES : if not uname . startswith ( interface_type ) : continue if len ( resource_name ) == len ( interface_type ) : parts = ( ) else : parts = resource_name [ len ( interface_type ) : ] . split ( '::' ) if parts and parts [ - 1 ] in _RESOURCE_CLASSES [ interface_type ] : parts , resource_class = parts [ : - 1 ] , parts [ - 1 ] else : try : resource_class = _DEFAULT_RC [ interface_type ] except KeyError : raise InvalidResourceName . rc_notfound ( interface_type , resource_name ) try : subclass = _SUBCLASSES [ ( interface_type , resource_class ) ] except KeyError : raise InvalidResourceName . subclass_notfound ( ( interface_type , resource_class ) , resource_name ) try : rn = subclass . from_parts ( * parts ) rn . user = resource_name return rn except ValueError as ex : raise InvalidResourceName . bad_syntax ( subclass . _visa_syntax , resource_name , ex ) raise InvalidResourceName ( 'Could not parse %s: unknown interface type' % resource_name )
Parse a resource name and return a ResourceName
39,993
def set_user_handle_type ( library , user_handle ) : global ViHndlr if user_handle is None : user_handle_p = c_void_p else : user_handle_p = POINTER ( type ( user_handle ) ) ViHndlr = FUNCTYPE ( ViStatus , ViSession , ViEventType , ViEvent , user_handle_p ) library . viInstallHandler . argtypes = [ ViSession , ViEventType , ViHndlr , user_handle_p ] library . viUninstallHandler . argtypes = [ ViSession , ViEventType , ViHndlr , user_handle_p ]
Set the type of the user handle to install and uninstall handler signature .
39,994
def set_signature ( library , function_name , argtypes , restype , errcheck ) : func = getattr ( library , function_name ) func . argtypes = argtypes if restype is not None : func . restype = restype if errcheck is not None : func . errcheck = errcheck
Set the signature of single function in a library .
39,995
def assert_interrupt_signal ( library , session , mode , status_id ) : return library . viAssertIntrSignal ( session , mode , status_id )
Asserts the specified interrupt or signal .
39,996
def discard_events ( library , session , event_type , mechanism ) : return library . viDiscardEvents ( session , event_type , mechanism )
Discards event occurrences for specified event types and mechanisms in a session .
39,997
def enable_event ( library , session , event_type , mechanism , context = None ) : if context is None : context = constants . VI_NULL elif context != constants . VI_NULL : warnings . warn ( 'In enable_event, context will be set VI_NULL.' ) context = constants . VI_NULL return library . viEnableEvent ( session , event_type , mechanism , context )
Enable event occurrences for specified event types and mechanisms in a session .
39,998
def find_resources ( library , session , query ) : find_list = ViFindList ( ) return_counter = ViUInt32 ( ) instrument_description = create_string_buffer ( constants . VI_FIND_BUFLEN ) ret = library . viFindRsrc ( session , query , byref ( find_list ) , byref ( return_counter ) , instrument_description ) return find_list , return_counter . value , buffer_to_text ( instrument_description ) , ret
Queries a VISA system to locate the resources associated with a specified interface .
39,999
def gpib_command ( library , session , data ) : return_count = ViUInt32 ( ) ret = library . viGpibCommand ( session , data , len ( data ) , byref ( return_count ) ) return return_count . value , ret
Write GPIB command bytes on the bus .