SF.net SVN: fclient: [337] trunk/sandbox/fcp2/client.py
Status: Pre-Alpha
Brought to you by:
jurner
|
From: <jU...@us...> - 2008-03-08 11:10:19
|
Revision: 337
http://fclient.svn.sourceforge.net/fclient/?rev=337&view=rev
Author: jUrner
Date: 2008-03-08 03:10:20 -0800 (Sat, 08 Mar 2008)
Log Message:
-----------
adapt to new message handling and a few fixes
PluginMessage is not kept track of anymore
Modified Paths:
--------------
trunk/sandbox/fcp2/client.py
Modified: trunk/sandbox/fcp2/client.py
===================================================================
--- trunk/sandbox/fcp2/client.py 2008-03-08 11:05:30 UTC (rev 336)
+++ trunk/sandbox/fcp2/client.py 2008-03-08 11:10:20 UTC (rev 337)
@@ -319,7 +319,7 @@
that the request has been completed and remove it fom our queue if necessary.
Non Get / Put requests will be removed in any case.
"""
- removeRequest = msg.name in (consts.Message.ProtocolError, consts.Message.PersistentRequestRemoved)
+ removeRequest = msg == message.ProtocolError or msg == message.PersistentRequestRemoved
if not removeRequest:
#NOTE: non Get / Put related requests do not have a Persistence param
removeRequest = request.params.get('Persistence', consts.Persistence.Connection) == consts.Persistence.Connection
@@ -358,80 +358,42 @@
"""
identifier = fcparams.newUuid(uuids=self._requests) if identifier is None else identifier
+ # equip requests with some additional params
+
#TODO: keep an eye on additional params, they may collide with Fcp parameters
- Private = message.Message.privateParamName
+ Private = message.PrivateParam
- if requestType & (consts.RequestType.MaskGet | consts.RequestType.MaskPut):
-
- msg.params.update({
-
- # persistent params that will go into identifier
- Private('RequestType'): requestType, # identifies sub message types
- Private('InitTime'): time.time() if initTime is None else initTime, # when was the request started?
- Private('FilenameCollision'): filenameCollision, # handle fielanem collisions?
- Private('PersistentUserData'): persistentUserData, # any user defined persistent data
-
- # non persistent params
- Private('RequestStatus'): consts.RequestStatus.Null,
- Private('ErrorMessage'): None, # error message in case an error occured
- Private('UserData'): userData, # any user defined runtime data here
-
- # params for SSKKeypair
- Private('PrivateKey'): None,
- Private('PublicKey'): None,
-
- # params from DataFound
- Private('MetadataContentType'): '', # contecnt type
- Private('MetadataSize'): 0, # content size
-
- # params from PersistentRequestModified
- Private('Modified'): {},
-
- # params for DDA test
- Private('TestDDA'): {},
-
- # params for SimpleProgress
- Private('ProgressTotal'): 0,
- Private('ProgressRequired'): 0,
- Private('ProgressFailed'): 0,
- Private('ProgressFatalyFailed'): 0,
- Private('ProgressSucceeeded'): 0,
-
- })
- # equip msg with some persistent pparams
- if msg.get('ClientToken', None) is None:
- msg['ClientToken'] = fcparams.messageToParams(msg)
-
+ """
+ @requestparam: B{ErrorMessage:} (L{messageMessage}) if an error occured
+ @requestparam: B{Modified:} (dict)
+ @requestparam: B{Modified:} (dict)
+ @requestparam: B{PrivateKey:} None. Will contain the private key as soon as the key is generated
+ @requestparam: B{PublicKey:} None. Will contain the public key as soon as the key is generated
+ @requestparam: B{RequestStatus:} one or more of the L{consts.RequestStatus} flags
+ @requestparam: B{RequestType:} one or more of the L{consts.RequestType} flags
+ @requestparam: B{Identifier:} identifier of the request
+ """
+ msg['Identifier'] = fcparams.newUuid(uuids=self._requests) if identifier is None else identifier
+ msg['RequestType'] = requestType
+ msg['InitTime'] = time.time() if initTime is None else initTime
+ if requestType & consts.RequestType.MaskGet:
+ msg['FilenameCollision'] = filenameCollision
+ msg['UserData'] = userData
+ msg['PersistentUserData'] = persistentUserData
+ msg['ClientToken'] = fcparams.messageToParams(msg)
+ elif requestType & consts.RequestType.MaskPut:
+ msg['UserData'] = userData
+ msg['PersistentUserData'] = persistentUserData
+ msg['ClientToken'] = fcparams.messageToParams(msg)
elif requestType & consts.RequestType.MaskGenerateKeypair:
- msg.params.update({
- Private('RequestType'): requestType, # identifies sub message types
- Private('RequestStatus'): consts.RequestStatus.Null,
- Private('InitTime'): initTime, # when was the request started?
- Private('Modified'): {},
-
- Private('PrivateKey'): None,
- Private('PublicKey'): None,
- })
-
- elif requestType & consts.RequestType.PluginMessage:
- msg.params.update({
- Private('RequestType'): requestType, # identifies sub message types
- Private('RequestStatus'): consts.RequestStatus.Null,
- Private('InitTime'): initTime, # when was the request started?
- Private('Modified'): {},
-
- Private('PluginReply'): None,
- })
-
+ pass
+ elif requestType & consts.RequestType.SubscribeUSK:
+ msg['UserData'] = userData
+ elif requestType & consts.RequestType.PluginInfo:
+ pass
else:
- msg.params.update({
- Private('RequestType'): requestType, # identifies sub message types
- Private('RequestStatus'): consts.RequestStatus.Null,
- Private('InitTime'): initTime, # when was the request started?
- Private('Modified'): {},
- })
-
- msg['Identifier'] = identifier
+ raise ValueError('Can not register request: ' + msg.name)
+
self._requests[identifier] = msg
###############################################################
@@ -443,8 +405,7 @@
"""Closes the client
@note: make shure to call close() when done with the client
"""
- msg = message.Message(
- consts.Message.ClientDisconnected,
+ msg = message.ClientDisconnected(
DisconnectReason=consts.DisconnectReason.Close,
Param=None,
)
@@ -453,7 +414,7 @@
def closeFreenet(self):
"""Shuts down the freenet node"""
- self.sendMessage(consts.Message.Shutdown)
+ self.sendMessage(message.Shutdown())
def connect(self, host=DefaultFcpHost, port=DefaultFcpPort, duration=20, timeout=0.5):
@@ -495,9 +456,10 @@
# try to get handshake
if result:
errorMsg = self.sendMessage(
- consts.Message.ClientHello,
- Name=self._connectionName,
- ExpectedVersion=self.ExpectedFcpVersion,
+ message.ClientHello(
+ Name=self._connectionName,
+ ExpectedVersion=self.ExpectedFcpVersion,
+ )
)
yield None
if errorMsg is None:
@@ -505,11 +467,11 @@
while timeElapsed <= duration:
yield None
msg = self.next(dispatch=False)
- if msg.name == consts.Message.ClientSocketTimeout:
+ if msg == message.ClientSocketTimeout:
timeElapsed += max(self.ioHandler.io.Timeout, 0.1)
yield None
- elif msg.name == consts.Message.NodeHello:
+ elif msg == message.NodeHello:
self._nodeHelloMessage = msg
# check if version is ok
if self.versionCheckNodeHello(msg):
@@ -522,14 +484,13 @@
break
else:
- disconnectReason = consts.DisconnectReason.UnkownNodeHello
+ disconnectReason = consts.DisconnectReason.UnknownNodeHello
disconnectParam = msg
break
if disconnectReason is None:
disconnectReason=consts.DisconnectReason.ConnectingFailed
- disconnectMsg = message.Message(
- consts.Message.ClientDisconnected,
+ disconnectMsg = message.ClientDisconnected(
DisconnectReason=disconnectReason,
Param=disconnectParam,
)
@@ -611,8 +572,9 @@
## errors
##
####################################################
- if msg.name == consts.Message.IdentifierCollision:
+ if msg == message.IdentifierCollision:
if initialRequest is None:
+ self.events.IdentifierCollision(msg)
return False
# resend request with new identifier
@@ -622,15 +584,14 @@
initialRequest['Identifier'] = newIdentifier
initialRequest['Modified'] = {consts.RequestModified.Identifier: requestIdentifier}
self.events.RequestModified(initialRequest)
- self.sendMessageEx(initialRequest)
+ self.sendMessage(initialRequest)
return True
- elif msg.name == consts.Message.ProtocolError:
+ elif msg == message.ProtocolError:
code = msg['Code']
if code == consts.ProtocolError.ShuttingDown:
- disconnectMsg = message.Message(
- consts.Message.ClientDisconnected,
+ disconnectMsg = message.ClientDisconnected(
DisconnectReason=consts.DisconnectReason.Shutdown,
Param=None,
)
@@ -643,13 +604,13 @@
return True
if initialRequest is None:
+ self.events.ProtocolError(msg)
return False
-
-
+
# handle DDA errors
elif code == consts.ProtocolError.DDADenied:
- ddaRequestMsg = message.Message(consts.Message.TestDDARequest)
- if initialRequest.name == consts.Message.ClientGet:
+ ddaRequestMsg = message.TestDDARequest()
+ if initialRequest == message.ClientGet:
ddaRequestMsg['WantWriteDirectory'] = True
directory = os.path.dirname(initialRequest['Filename'])
else:
@@ -666,7 +627,7 @@
'ErrorMsg': msg,
}
self._ddaTests.append(initialRequest)
- self.sendMessageEx(ddaRequestMsg)
+ self.sendMessage(ddaRequestMsg)
return True
@@ -682,7 +643,7 @@
newFilename = namespace.unique_filename(filename, extensions=1, ispostfixed=collisionHandled)
initialRequest['Filename'] = newFilename
initialRequest['Modified'] = {consts.RequestModified.Filename: filename}
- self.sendMessageEx(initialRequest)
+ self.sendMessage(initialRequest)
self.events.RequestModified(initialRequest)
return True
@@ -693,18 +654,12 @@
# handle plugin related request failures
elif code == consts.ProtocolError.NoSuchPlugin or code == consts.ProtocolError.AccessDenied:
- if initialRequest.name == consts.Message.GetPluginInfo:
+ if initialRequest == message.GetPluginInfo:
initialRequest['ErrorMessage'] = msg
initialRequest['RequestStatus'] |= consts.RequestStatus.Error
self._finalizeRequest(msg, initialRequest, self.events.PluginInfoFailed)
return True
- elif initialRequest.name == consts.Message.FCPPluginMessage:
- initialRequest['ErrorMessage'] = msg
- initialRequest['RequestStatus'] |= consts.RequestStatus.Error
- self._finalizeRequest(msg, initialRequest, self.events.PluginMessageFailed)
- return True
-
# only requests should get through to here
# NOTE: Fcp already removed the request
@@ -723,7 +678,7 @@
## TestDDA drill.
##
####################################################
- elif msg.name == consts.Message.TestDDAReply:
+ elif msg == message.TestDDAReply:
directory = msg['Directory']
# find message that triggered the call
@@ -754,14 +709,15 @@
initialRequest['TestDDA']['TmpFile'] = fpathWrite
self.sendMessage(
- consts.Message.TestDDAResponse,
- Directory=msg['Directory'],
- ReadContent=readContent,
+ message.TestDDAResponse(
+ Directory=msg['Directory'],
+ ReadContent=readContent,
+ )
)
return True
- elif msg.name == consts.Message.TestDDAComplete:
+ elif msg == message.TestDDAComplete:
# clean up tmp file
directory = msg['Directory']
@@ -794,7 +750,7 @@
return True
# else: resend message
- self.sendMessageEx(initialRequest)
+ self.sendMessage(initialRequest)
return True
####################################################
@@ -802,11 +758,11 @@
## config related
##
####################################################
- elif msg.name == consts.Message.ConfigData:
+ elif msg == message.ConfigData:
self.events.ConfigData(msg)
return True
- elif msg.name == consts.Message.NodeData:
+ elif msg == message.NodeData:
self.events.NodeData(msg)
return True
@@ -815,7 +771,7 @@
## get / put related
##
####################################################
- elif msg.name == consts.Message.AllData:
+ elif msg == message.AllData:
if initialRequest is None:
return False
@@ -824,7 +780,7 @@
self._finalizeRequest(msg, initialRequest, self.events.RequestCompleted)
return True
- elif msg.name == consts.Message.DataFound:
+ elif msg == message.DataFound:
if initialRequest is None:
return False
@@ -840,10 +796,11 @@
if initialRequest['RequestType'] == consts.RequestType.GetData:
if initialRequest['Persistence'] != consts.Persistence.Connection:
self.sendMessage(
- consts.Message.GetRequestStatus,
- Identifier=initialRequest['Identifier'],
- Global=False,
- OnlyData=True
+ message.GetRequestStatus(
+ Identifier=initialRequest['Identifier'],
+ Global=False,
+ OnlyData=True
+ )
)
else:
self._finalizeRequest(msg, initialRequest, self.events.RequestCompleted)
@@ -851,7 +808,7 @@
return True
- elif msg.name == consts.Message.GetFailed:
+ elif msg == message.GetFailed:
if initialRequest is None:
return False
@@ -872,7 +829,7 @@
return True
- elif msg.name == consts.Message.PersistentGet:
+ elif msg == message.PersistentGet:
# unknown request... try to restore it
if initialRequest is None:
@@ -883,13 +840,14 @@
if fcParams is None:
self._loggers['Runtime'].critical(consts.LogMessages.RequestInvalidClientToken)
self.sendMessage(
- consts.Message.RemovePersistentRequest,
- Identifier=requestIdentifier,
- Global=msg['Global'],
+ message.RemovePersistentRequest(
+ Identifier=requestIdentifier,
+ Global=msg['Global'],
+ )
)
return True
- initialRequest = copy.deepcopy(msg)
+ initialRequest = message.ClientGet()
self._registerRequest(
initialRequest,
fcParams[fcparams.IRequestType],
@@ -899,8 +857,8 @@
persistentUserData=fcParams[fcparams.IPersistentUserData],
filenameCollision=fcParams[fcparams.IFilenameCollision],
)
-
- initialRequest.name = consts.Message.ClientGet
+
+ initialRequest.params.update(msg.params)
#FIX: remove Started param from PersistentGet / Put
del initialRequest.params['Started']
#FIX: [0001965: Persistence vs PersistenceType]
@@ -914,7 +872,7 @@
return False
- elif msg.name == consts.Message.PersistentRequestModified:
+ elif msg == message.PersistentRequestModified:
if initialRequest is None:
return False
@@ -949,7 +907,7 @@
return True
- elif msg.name == consts.Message.PersistentRequestRemoved:
+ elif msg == message.PersistentRequestRemoved:
if initialRequest is None:
return False
@@ -958,7 +916,7 @@
return True
- elif msg.name == consts.Message.SimpleProgress:
+ elif msg == message.SimpleProgress:
if initialRequest is None:
return False
@@ -972,7 +930,7 @@
## put related
- elif msg.name == consts.Message.PersistentPut:
+ elif msg == message.PersistentPut or msg == message.PersistentPutDir:
# unknown request... try to restore it
if initialRequest is None:
@@ -983,14 +941,21 @@
if fcParams is None:
self._loggers['Runtime'].critical(consts.LogMessages.RequestInvalidClientToken)
self.sendMessage(
- consts.Message.RemovePersistentRequest,
- Identifier=requestIdentifier,
- Global=msg['Global'],
+ message.RemovePersistentRequest(
+ Identifier=requestIdentifier,
+ Global=msg['Global'],
+ )
)
return True
- initialRequest = copy.deepcopy(msg)
requestType = fcParams[fcparams.IRequestType]
+ if requestType in (consts.RequestType.PutData, consts.RequestType.PutFile):
+ initialRequest = message.ClientPut()
+ elif requestType == consts.RequestType.PutDir:
+ initialRequest = message.ClientPutDiskDir()
+ elif request == consts.RequestType.PutMultiple:
+ initialRequest = message.ClientPutComplexDir()
+
self._registerRequest(
initialRequest,
requestType,
@@ -1000,15 +965,7 @@
persistentUserData=fcParams[fcparams.IPersistentUserData],
filenameCollision=fcParams[fcparams.IFilenameCollision],
)
-
- # determine initial message name
- if requestType in (consts.RequestType.PutData, consts.RequestType.PutFile):
- initialRequest.name = consts.Message.ClientPut
- elif requestType == consts.RequestType.PutDir:
- initialRequest.name = consts.Message.ClientPutDiskDir
- elif requestType == consts.RequestType.PutMultiple:
- initialRequest.name = consts.Message.ClientPutComplexDir
-
+
#FIX: remove Started param from PersistentGet / Put
del initialRequest.params['Started']
initialRequest['RequestStatus'] |= consts.RequestStatus.Restored
@@ -1019,7 +976,7 @@
return False
- elif msg.name == consts.Message.PutFailed:
+ elif msg == message.PutFailed:
if initialRequest is None:
return False
@@ -1033,7 +990,7 @@
return True
- elif msg.name == consts.Message.PutFetchable:
+ elif msg == message.PutFetchable:
if initialRequest is None:
# something went wrong
return False
@@ -1042,7 +999,7 @@
return True
- elif msg.name == consts.Message.PutSuccessful:
+ elif msg == message.PutSuccessful:
if initialRequest is None:
return False
# TODO: StartupTime and CompletionTime are passed, but
@@ -1054,20 +1011,20 @@
return True
- elif msg.name == consts.Message.URIGenerated:
+ elif msg == message.URIGenerated:
if initialRequest is None:
return False
initialRequest['URI'] = msg['URI']
return True
- elif msg.name == consts.Message.FinishedCompression:
+ elif msg == message.FinishedCompression:
if initialRequest is None:
return False
initialRequest['RequestStatus'] |= consts.RequestStatus.Compressed
self.events.RequestCompressionFinished(initialRequest)
return True
- elif msg.name == consts.Message.StartedCompression:
+ elif msg == message.StartedCompression:
if initialRequest is None:
return False
initialRequest['RequestStatus'] |= consts.RequestStatus.Compressing
@@ -1079,31 +1036,31 @@
## Peer related messages
##
####################################################
- elif msg.name == consts.Message.EndListPeers:
+ elif msg == message.EndListPeers:
self.events.EndListPeers(msg)
return True
- elif msg.name == consts.Message.EndListPeerNotes:
+ elif msg == message.EndListPeerNotes:
self.events.EndListPeerNotes(msg.params)
return True
- elif msg.name == consts.Message.Peer:
+ elif msg == message.Peer:
self.events.Peer(msg)
return True
- elif msg.name == consts.Message.PeerNote:
+ elif msg == message.PeerNote:
self.events.PeerNote(msg)
return True
- elif msg.name == consts.Message.PeerRemoved:
+ elif msg == message.PeerRemoved:
self.events.PeerRemoved(msg)
return True
- elif msg.name == consts.Message.UnknownNodeIdentifier:
+ elif msg == message.UnknownNodeIdentifier:
self.events.PeerUnknown(msg)
return True
- elif msg.name == consts.Message.UnknownPeerNoteType:
+ elif msg == message.UnknownPeerNoteType:
self.events.PeerNoteTypeUnknown(msg)
return True
####################################################
@@ -1111,7 +1068,7 @@
## plugins
##
####################################################
- elif msg.name == consts.Message.PluginInfo:
+ elif msg == message.PluginInfo:
if initialRequest is None:
return False
@@ -1119,12 +1076,8 @@
self._finalizeRequest(msg, initialRequest, self.events.PluginInfo)
return True
- elif msg.name == consts.Message.FCPPluginReply:
- if initialRequest is None:
- return False
- initialRequest['RequestStatus'] |= consts.RequestStatus.Success
- initialRequest['PluginReply'] = msg
- self._finalizeRequest(msg, initialRequest, self.events.PluginMessage)
+ elif msg == message.FCPPluginReply:
+ self.events.PluginMessage(msg)
return True
####################################################
@@ -1132,9 +1085,8 @@
## others
##
####################################################
- elif msg.name == consts.Message.CloseConnectionDuplicateClientName:
- disconnectMsg = message.Message(
- consts.Message.ClientDisconnected,
+ elif msg == message.CloseConnectionDuplicateClientName:
+ disconnectMsg = message.ClientDisconnected(
DisconnectReason=consts.DisconnectReason.DuplicateClientName,
Param=None,
)
@@ -1142,7 +1094,7 @@
return True
- elif msg.name == consts.Message.SSKKeypair:
+ elif msg == message.SSKKeypair:
if initialRequest is None:
return False
@@ -1160,7 +1112,7 @@
self._finalizeRequest(msg, initialRequest, self.events.KeypairGenerated)
return True
- elif msg.name == consts.Message.SubscribedUSKUpdate:
+ elif msg == message.SubscribedUSKUpdate:
if initialRequest is None:
return False
self.events.USKUpdated(msg)
@@ -1180,12 +1132,11 @@
try:
msg = self.ioHandler.readMessage()
except iohandler.IOTimeout, details:
- msg = message.Message(consts.Message.ClientSocketTimeout)
+ msg = message.ClientSocketTimeout()
if dispatch:
self.events.Idle(msg)
except iohandler.IOBroken, details:
- msg = message.Message(
- consts.Message.ClientDisconnected,
+ msg = message.ClientDisconnected(
DisconnectReason=consts.DisconnectReason.SocketDied,
Param=details,
)
@@ -1211,7 +1162,7 @@
except KeyboardInterrupt:
self._loggers['Runtime'].info(consts.LogMessages.KeyboardInterrupt)
return
- if msg.name == consts.Message.ClientSocketDied:
+ if msg == message.ClientSocketDied:
return
#n = 0
@@ -1236,26 +1187,12 @@
self._loggers['Runtime'].info(consts.LogMessages.KeyboardInterrupt)
break
- if msg.name == consts.Message.ClientSocketDied:
+ if msg == message.ClientSocketDied:
break
- def sendMessage(self, name, data=None, **params):
+ def sendMessage(self, msg):
"""Sends a message to freenet
- @param name: name of the message to send
- @param data: data to atatch to the message
- @param params: {para-name: param-calue, ...} of parameters to pass along
- with the message (see freenet protocol)
-
-
- @note: you can use this method to send a message to the node, bypassing all
- track keeping methods of the client
- """
- return self.sendMessageEx(message.Message(name, data=data, **params))
-
-
- def sendMessageEx(self, msg):
- """Sends a message to freenet
@param msg: (L{message.Message}) message to send
@return: (L{message.Message}) disconnect if something went wrong
@@ -1267,8 +1204,7 @@
try:
self.ioHandler.sendMessageEx(msg)
except iohandler.IOBroken, details:
- errorMsg = message.Message(
- consts.Message.ClientDisconnected,
+ errorMsg = message.ClientDisconnected(
DisconnectReason=consts.DisconnectReason.SocketDied,
Param=details
)
@@ -1296,15 +1232,16 @@
@event: ConfigData(event, msg)
"""
self.sendMessage(
- consts.Message.GetConfig,
- WithSortOrder=withSortOrder,
- WithCurrent=withCurrent,
- WithDefaults=withDefaults,
- WithExpertFlag=withExpertFlag,
- WithForceWriteFlag=withForceWriteFlag,
- WithShortDescription=withShortDescription,
- WithLongDescription=withLongDescription,
- WithDataTypes=withDataTypes,
+ message.GetConfig(
+ WithSortOrder=withSortOrder,
+ WithCurrent=withCurrent,
+ WithDefaults=withDefaults,
+ WithExpertFlag=withExpertFlag,
+ WithForceWriteFlag=withForceWriteFlag,
+ WithShortDescription=withShortDescription,
+ WithLongDescription=withLongDescription,
+ WithDataTypes=withDataTypes,
+ )
)
@@ -1312,9 +1249,9 @@
"""Modifies node configuration values
@param params: (dict) containing parameters to modify
"""
- msg = message.Message(consts.Message.ModifyConfig)
+ msg = message.ModifyConfig()
msg.params = params
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
########################################################
@@ -1341,7 +1278,7 @@
@return: (str) identifier of the request
"""
- msg = message.Message(consts.Message.ClientGet, URI=key)
+ msg = message.ClientGet(URI=key)
for paramName, value in messageParams.items():
if value is not None:
msg[paramName] = value
@@ -1353,7 +1290,7 @@
persistentUserData=persistentUserData,
userData=userData,
)
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
return msg['Identifier']
@@ -1562,14 +1499,13 @@
@todo: looks like USK subscribes will persist untill connection is closed. Can they be removed somehow?
"""
- msg = message.Message(
- consts.Message.SubscribeUSK,
+ msg = message.SubscribeUSK(
URI=key,
DontPoll=dontPoll,
)
self._registerRequest(msg, consts.RequestType.SubscribeUSK)
msg['RequestStatus'] |= consts.RequestStatus.Completed
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
return msg['Identifier']
@@ -1611,16 +1547,16 @@
only 'Uri' is requested from freenet) is always the first item in the list.
"""
if requestType in (consts.RequestType.PutData, consts.RequestType.PutFile):
- msgName = consts.Message.ClientPut
+ msgName = message.ClientPut.name
elif requestType == consts.RequestType.PutDir:
- msgName = consts.Message.ClientPutDiskDir
+ msgName = message.ClientPutDiskDir.name
elif requestType == consts.RequestType.PutMultiple:
- msgName = consts.Message.ClientPutComplexDir
+ msgName = message.ClientPutComplexDir.name
else:
raise ValueError('Unsupported request type')
#TODO: autoconvert keys to python classes???
- msg = message.Message(msgName, URI=key)
+ msg = message.MessagesAll[msgName](URI=key)
contentType = msgParams.get('ContentType', None)
if contentType is not None:
del msgParams['ContentType']
@@ -1710,7 +1646,7 @@
persistentUserData=persistentUserData,
userData=userData,
)
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
return msg['Identifier']
@@ -1774,8 +1710,7 @@
@param userData: (any) any data to be associated to the request at runtime
@return: (str) request identifier
"""
- msg = message.Message(
- consts.Message.ClientPut,
+ msg = message.ClientPut(
URI=consts.KeyType.KSK + name,
Persistence=persistence,
PriorityClass=priorityClass,
@@ -1788,7 +1723,7 @@
persistentUserData=persistentUserData,
userData=userData,
)
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
return msg['Identifier']
#CHK
@@ -1978,7 +1913,7 @@
@note: for other params see L{chkPutData}
@note: to upload multiple items at once pass a dict for each item containig the following members:
- - FcRequestType: L{consts.RequestType.PutData}, L{consts.RequestType.PutFile} or L{consts.RequestType.PutRedirect}
+ - RequestType: L{consts.RequestType.PutData}, L{consts.RequestType.PutFile} or L{consts.RequestType.PutRedirect}
- Data: if requestType is L{consts.RequestType.PutData}, data to upload
- Filename: if requestType is L{consts.RequestType.PutFile}, filepath of the file to upload
- TargetURI: if requestType is L{consts.RequestType.PutRedirect}, uri to redirect to
@@ -2193,8 +2128,7 @@
self.events.RequestModified(initialRequest)
return
- msg = message.Message(
- consts.Message.ModifyPersistentRequest,
+ msg = message.ModifyPersistentRequest(
Identifier=initialRequest['Identifier'],
Global=False,
)
@@ -2204,7 +2138,7 @@
if priorityClass is not None:
msg['PriorityClass'] = priorityClass
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
def removeRequest(self, requestIdentifier):
@@ -2218,13 +2152,14 @@
# remove Persistence.Connection emidiately
# ..make up a PersistentRequestRemoved message for this case
if initialRequest['Persistence'] == consts.Persistence.Connection:
- msg = message.Message(consts.Message.PersistentRequestRemoved, Identifier=requestIdentifier, Global=False)
+ msg = message.PersistentRequestRemoved(Identifier=requestIdentifier, Global=False)
self._finalizeRequest(msg, initialRequest, self.events.RequestRemoved)
else:
self.sendMessage(
- consts.Message.RemovePersistentRequest,
- Global=False,
- Identifier=requestIdentifier,
+ message.RemovePersistentRequest(
+ Global=False,
+ Identifier=requestIdentifier,
+ )
)
else:
del self._requests[requestIdentifier]
@@ -2248,7 +2183,7 @@
"""
requestType = request.get('RequestType', consts.RequestType.Null)
if not requestType & (consts.RequestType.MaskGet | consts.RequestType.MaskPut):
- raise ValueError('Can not resend request: %s' % requestMessage.name)
+ raise ValueError('Can not resend request: %s' % request.name)
# we don't know what UserData may be, so back it up before copying
oldIdentifier = request['Identifier']
@@ -2285,7 +2220,7 @@
request['UserData'] = oldUserData
self.removeRequest(request['Identifier'])
- self.sendMessageEx(newRequest)
+ self.sendMessage(newRequest)
return newRequest['Identifier']
########################################################
@@ -2304,10 +2239,11 @@
@param giveOpennetRef: if True, the opennet reference is retuned instead of the darknet
"""
self.sendMessage(
- consts.Message.GetNode,
- WithPrivate=withPrivate,
- WithVolatile=withVolatile,
- GiveOpennetRef=giveOpennetRef,
+ message.GetNode(
+ WithPrivate=withPrivate,
+ WithVolatile=withVolatile,
+ GiveOpennetRef=giveOpennetRef,
+ )
)
@@ -2316,8 +2252,9 @@
@param identity: identity of the peer to request information for
"""
self.sendMessage(
- consts.Message.ListPeer,
- NodeIdentifier=identity,
+ message.ListPeer(
+ NodeIdentifier=identity,
+ )
)
@@ -2329,8 +2266,9 @@
@note: listPeerNotes() is only available for darknet nodes
"""
self.sendMessage(
- consts.Message.ListPeerNotes,
- NodeIdentifier=identity
+ message.ListPeerNotes(
+ NodeIdentifier=identity
+ )
)
@@ -2343,9 +2281,10 @@
@event: EndListPeers(event, params).
"""
self.sendMessage(
- consts.Message.ListPeers,
- WithMetadata=withMetaData,
- WithVolatile=withVolantile,
+ message.ListPeers(
+ WithMetadata=withMetaData,
+ WithVolatile=withVolantile,
+ )
)
@@ -2358,9 +2297,10 @@
@note: you can only modify darknet peers
"""
- msg = Message(
- consts.Message.ModifyPeer,
- NodeIdentifier=identity,
+ msg = MessageEx(
+ message.ModifyPeer(
+ NodeIdentifier=identity,
+ )
)
if allowLocalAddresses is not None:
msg['AllowLocalAddresses'] = allowLocalAddresses
@@ -2368,7 +2308,7 @@
msg['IsDisabled'] = isDisabled
if isListenOnly is not None:
msg['IsListenOnly'] = isListenOnly
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
def modifyPeerNote(self, identity, note):
@@ -2379,11 +2319,12 @@
@note: you can only modify notes of darknet peers
"""
self.sendMessage(
- consts.Message.ModifyPeerNote,
- NodeIdentifier=identity,
- #NOTE: currently fcp supports only this one type
- PeerNoteType=consts.PeerNoteType.Private,
- NoteText=note
+ message.ModifyPeerNote(
+ NodeIdentifier=identity,
+ #NOTE: currently fcp supports only this one type
+ PeerNoteType=consts.PeerNoteType.Private,
+ NoteText=note
+ )
)
@@ -2392,8 +2333,9 @@
@param identity: identity of the peer node to remove
"""
self.sendMessage(
- consts.Message.RemovePeer,
- NodeIdentifier=identity,
+ message.RemovePeer(
+ NodeIdentifier=identity,
+ )
)
##########################################################
@@ -2407,34 +2349,41 @@
@param detailed: (bool) If True, detailed information is returned
@return: (str) request identifier
"""
- msg = message.Message(
- consts.Message.GetPluginInfo,
+ msg = message.GetPluginInfo(
PluginName=pluginName,
Detailed=detailed,
)
self._registerRequest(msg, consts.RequestType.PluginInfo)
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
return msg['Identifier']
- def sendPluginMessage(self, pluginName, params, data=None):
+ def sendPluginMessage(self, pluginName, identifier, params, data=None):
"""Sends a message to a plugin
@param pluginName: name of the plugin to send the message to
+ @param identifier: (str) identifier to identify plugin responses or protocol errors
@param params: (dict) additional params to pass to the plugin (each parameter has to be prefixed with 'Param.')
@param data: (str) data to pass along with the messaage or None
- @return: (str) request identifier
+ @return: (L{message.FCPPluginMessage})
+
+ @note: the client does not keep track of messages send to a plugin, because the plugin
+ may or may not return. If the plugin sends a reply, a L{events.PluginMessage} is triggered.
+ If something goes wrong, L{events.ProtocolError} or an is L{events.IdentifierCollision}
+ is triggered. Use the identifier passed to identify responses.
+
+ @todo: this is method not tested. Assumption: identifer does not have to be unique to
+ the node. Most likely it has to be unique to the plugin.
"""
- msg = message.Message(
- consts.Message.FCPPluginMessage,
+ msg = message.FCPPluginMessage(
PluginName=pluginName,
+ Identifier=identifier,
**params
)
if data is not None:
msg['DataLength'] = len(data)
msg.data = data
- self._registerRequest(msg, consts.RequestType.PluginMessage)
- self.sendMessageEx(msg)
- return msg['Identifier']
+ self.sendMessage(msg)
+ return msg
##########################################################
##
@@ -2448,21 +2397,14 @@
@return: identifier of the request
@event: L{events.Events.KeypairGenerated} triggered as soon as the request is complete
-
- @requestparam: B{FcModified:} (dict)
- @requestparam: B{FcPrivateKey:} None. Will contain the private key as soon as the key is generated
- @requestparam: B{FcPublivcKey:} None. Will contain the public key as soon as the key is generated
- @requestparam: B{FcRequestStatus:} one or more of the L{consts.RequestStatus} flags
- @requestparam: B{FcRequestType:} one or more of the L{consts.RequestType} flags
- @requestparam: B{Identifier:} identifier of the request
"""
if keypairType not in (consts.KeyType.SSK, consts.KeyType.USK):
raise ValueError('keypairType must be %s or %s' % (consts.KeyType.SSK, consts.KeyType.USK))
requestType = consts.RequestType.GenerateSSKKeypair if keypairType == consts.KeyType.SSK else consts.RequestType.GenerateUSKKeypair
- msg = message.Message(consts.Message.GenerateSSK)
+ msg = message.GenerateSSK()
self._registerRequest(msg, requestType)
- self.sendMessageEx(msg)
+ self.sendMessage(msg)
return msg['Identifier']
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|