SF.net SVN: fclient: [107] trunk/sandbox/fcp/fcp2_0_client.py
Status: Pre-Alpha
Brought to you by:
jurner
|
From: <ju...@us...> - 2008-02-02 05:14:02
|
Revision: 107
http://fclient.svn.sourceforge.net/fclient/?rev=107&view=rev
Author: jurner
Date: 2008-02-01 21:14:06 -0800 (Fri, 01 Feb 2008)
Log Message:
-----------
adapt to recent
combed over documentation
Modified Paths:
--------------
trunk/sandbox/fcp/fcp2_0_client.py
Modified: trunk/sandbox/fcp/fcp2_0_client.py
===================================================================
--- trunk/sandbox/fcp/fcp2_0_client.py 2008-02-02 05:13:24 UTC (rev 106)
+++ trunk/sandbox/fcp/fcp2_0_client.py 2008-02-02 05:14:06 UTC (rev 107)
@@ -3,11 +3,11 @@
Compatibility: >= Freenet 0.7 Build #1084
-@newfield event, events
+@newfield event: event, events
-@note: The client implementation never uses or watches the global queue. No (in words N-O)
-implementation should ever do so. Global is evil... so avoid it. Already filed a bug report regarding this.
+@note: The client implementation never uses or watches the global queue. No implementation
+should ever do so. Global is evil.
"""
@@ -149,7 +149,7 @@
def saveWriteFile(fpath, data):
- """Writes data to a file i the savest manner possible
+ """Writes data to a file in the savest manner possible
@param fpath: file to write
@param data: data to write to file
@return: True if successful, False otherwise
@@ -172,6 +172,9 @@
#
#*************************************************************************************************
class FcpClient(object):
+ """
+ @ivar events: events the client supports
+ """
DefaultFcpHost = os.environ.get('FCP_HOST', '127.0.0.1').strip()
try:
@@ -191,24 +194,7 @@
ExpectedNodeBuild = 1107
from fcp2_0_config import Config
- from fcp2_0_consts import (
- ConnectReason,
- DebugVerbosity,
- DisconnectReason,
- FetchError,
- FilenameCollision,
- InsertError,
- KeyType,
- LogMessages,
- PeerNodeStatus,
- PeerNoteType,
- Persistence,
- Priority,
- ProtocolError,
- ReturnType,
- UploadFrom,
- Verbosity,
- )
+ consts = consts
from fcp2_0_message import Message
import fcp2_0_params as FcParams
from fcp2_0_uri import Uri
@@ -271,10 +257,9 @@
debugVerbosity=None,
):
"""
- @param conectionName: name of the connection or None to use an arbitrary connection name
- @param debugVerbosity: verbosity level for debugging. Default is L{DebugVerbosity.Warning}
-
- @ivar events: events the client supports
+ @param connectionName: name of the connection or None to use an arbitrary connection name
+ @param debugVerbosity: verbosity level for debugging. Default is L{consts.DebugVerbosity.Warning}
+
"""
self._connectionName = self.setConnectionName(connectionName)
self._ddaTests = [] # currently running DDA tests (request0, ... requestN)
@@ -287,7 +272,7 @@
self.events = self.Events()
- self.setDebugVerbosity(self.DebugVerbosity.Warning if debugVerbosity is None else debugVerbosity)
+ self.setDebugVerbosity(consts.DebugVerbosity.Warning if debugVerbosity is None else debugVerbosity)
atexit.register(self.close)
@@ -316,7 +301,7 @@
'FcPersistentUserData': persistentUserData, # any user defined persistent data
# non persistent params
- 'FcStatus': self.Message.StatusPending,
+ 'FcStatus': consts.MessageStatus.Pending,
'FcErrorMessage': None, # did an error occur?
'FcUserData': userData, # any user defined runtime data here
@@ -358,11 +343,11 @@
):
"""Registers a message
@param msg: message to register for track keeping
+ @param userData: any user defined data
@param msgSubType: one of the message sub type consts
- @param requestIdentifier: (str)
- @param userData: (str)
@param initTime: (python time)
- @param handleCollisions: (bool)
+ @param persistentUserData: (str) user defined persistent data
+ @param filenameCollision: (bool)
@return: (str) uuid
@note: the identifier returned is unique to the client but may not be unique to the node
@@ -404,12 +389,12 @@
)
# fix some Fcp inconsistencies ClientGet vs. PersistentGet
- if msg.name == self.Message.MessagePersistentGet:
+ if msg.name == consts.Message.PersistentGet:
del msg.params['Started']
#FIX: [0001965: Persistence vs PersistenceType]
if 'PersistenceType' in msg.params:
msg['Persistence'] = msg.params.pop('PersistenceType')
- elif msg.name == self.Message.MessagePersistentPut:
+ elif msg.name == consts.Message.PersistentPut:
del msg.params['Started']
return msg
@@ -423,7 +408,7 @@
"""Closes the client
@note: make shure to call close() when done with the client
"""
- self._log.info(self.LogMessages.ClientClose)
+ self._log.info(consts.LogMessages.ClientClose)
if self._socket is not None:
self._socket.close()
self._socket = None
@@ -444,11 +429,12 @@
@param port: (int) port of the node
@param duration: (int) how many seconds try to connect before giving up
@param timeout: (int) how much time to wait before another attempt to connect
- @event: Connected(event, params). Triggered as soon as the client is connected. Params
- will be the parameters of the NodeHello message.
- @return: (Message) NodeHello if successful, None otherwise for the next iteration
+
+ @return: (L{fcp2_0_message.Message}) NodeHello if successful, None otherwise for the next iteration
+
+ @event: ClientConnected(event, message) is triggered as soon as the client is connected
"""
- self._log.info(self.LogMessages.Connecting)
+ self._log.info(consts.LogMessages.Connecting)
# try to Connect socket
if self._socket is not None:
@@ -468,7 +454,7 @@
except socket.error, d:
yield None
else:
- self._log.info(self.LogMessages.Connected)
+ self._log.info(consts.LogMessages.Connected)
# send ClientHello and wait for NodeHello
#NOTE: thought I could leave ClientHelloing up to the caller
@@ -476,49 +462,49 @@
# as expected when not doing so, the node disconnects.
# So take it over here.
self.sendMessage(
- self.Message.MessageClientHello,
+ consts.Message.ClientHello,
Name=self._connectionName,
ExpectedVersion=self.ExpectedFcpVersion,
)
while timeElapsed <= duration:
msg = self.next(dispatch=False)
- if msg.name == self.Message.MessageClientSocketTimeout:
+ if msg.name == consts.Message.ClientSocketTimeout:
timeElapsed += self.SocketTimeout
yield None
- elif msg.name == self.Message.MessageNodeHello:
+ elif msg.name == consts.Message.NodeHello:
self._nodeHelloMessage = msg
- self._log.debug(self.LogMessages.MessageReceived + msg.pprint())
+ self._log.debug(consts.LogMessages.MessageReceived + msg.pprint())
# check if version is ok
if self.versionCheckNodeHello(msg):
self.events.ClientConnected(msg)
else:
self.close()
msg = self.Message(
- self.Message.MessageClientDisconnected,
- DisconnectReason=self.DisconnectReason.VersionMissmatch
+ consts.Message.ClientDisconnected,
+ DisconnectReason=consts.DisconnectReason.VersionMissmatch
)
self.events.ClientDisconnected(msg)
yield self._nodeHelloMessage
raise StopIteration
else:
- self._log.debug(self.LogMessages.MessageReceived + msg.pprint())
+ self._log.debug(consts.LogMessages.MessageReceived + msg.pprint())
break
break
# continue polling
- self._log.info(self.LogMessages.ConnectionRetry)
+ self._log.info(consts.LogMessages.ConnectionRetry)
timeElapsed += timeout
time.sleep(timeout)
msg = self.Message(
- self.Message.MessageClientDisconnected,
- DisconnectReason=self.DisconnectReason.ConnectingFailed
+ consts.Message.ClientDisconnected,
+ DisconnectReason=consts.DisconnectReason.ConnectingFailed
)
self.events.ClientDisconnected(msg)
- self._log.info(self.LogMessages.ConnectingFailed)
+ self._log.info(consts.LogMessages.ConnectingFailed)
self.close()
raise StopIteration
@@ -540,7 +526,7 @@
def setDebugVerbosity(self, debugVerbosity):
"""Sets the verbosity level of the client
- @note: see L{DebugVerbosity}
+ @note: see L{consts.DebugVerbosity}
"""
self._log.setLevel(debugVerbosity)
@@ -548,7 +534,7 @@
def startFreenet(self, cmdline):
"""Starts freenet
@param cmdline: commandline to start freenet (like '/freenet/run.sh start' or 'c:\freenet\start.bat')
- @return: (string) whatever freenet returns
+ @return: (str) whatever freenet returns
"""
#TODO: on windows it may be necessary to hide the command window
p = subprocess.Popen(
@@ -585,9 +571,9 @@
CancelPersistentRequests = 0 # for testing... if True, cancels all PersistentRequests
- if msg.name == self.Message.MessageClientSocketTimeout:
+ if msg.name == consts.Message.ClientSocketTimeout:
return True
- self._log.debug(self.LogMessages.MessageReceived + msg.pprint())
+ self._log.debug(consts.LogMessages.MessageReceived + msg.pprint())
# check if we have an initial request corrosponding to msg
requestIdentifier = msg.get('Identifier', None)
@@ -597,7 +583,7 @@
## errors
##
####################################################
- if msg.name == self.Message.MessageIdentifierCollision:
+ if msg.name == consts.Message.IdentifierCollision:
if initialRequest is not None:
# resend request with new identifier
@@ -605,37 +591,36 @@
self._requests[newIdentifier] = initialRequest
del self._requests[requestIdentifier]
initialRequest['Identifier'] = newIdentifier
- initialRequest['FcModified'] = {self.Message.ModifiedRequestIdentifier: requestIdentifier}
+ initialRequest['FcModified'] = {consts.RequestModified.Identifier: requestIdentifier}
self.events.RequestModified(initialRequest)
self.sendMessageEx(initialRequest)
return True
- elif msg.name == self.Message.MessageProtocolError:
+ elif msg.name == consts.Message.ProtocolError:
code = msg['Code']
- if requestIdentifier is None:
- #TODO: check how to handle this
- raise self.ProtocolError(msg)
-
- if initialRequest is None:
- #TODO: check how to handle this
- raise self.ProtocolError(msg)
-
-
- if code == self.ProtocolError.ShuttingDown:
+ if code == consts.ProtocolError.ShuttingDown:
self.close()
msg = self.Message(
- self.Message.MessageClientDisconnected,
+ consts.Message.ClientDisconnected,
DisconnectReason=DisconnectReason.Shutdown,
)
self.events.ClientDisconnected(msg)
return True
+ if requestIdentifier is None:
+ #TODO: check how to handle this
+ raise consts.ProtocolError(msg)
+
+ if initialRequest is None:
+ #TODO: check how to handle this
+ raise consts.ProtocolError(msg)
+
# handle DDA errors
- elif code == self.ProtocolError.DDADenied:
- ddaRequestMsg = self.Message(self.Message.MessageTestDDARequest)
- if initialRequest.name == self.Message.MessageClientGet:
+ elif code == consts.ProtocolError.DDADenied:
+ ddaRequestMsg = self.Message(consts.Message.TestDDARequest)
+ if initialRequest.name == consts.Message.ClientGet:
ddaRequestMsg['WantWriteDirectory'] = True
directory = os.path.dirname(initialRequest['Filename'])
else:
@@ -658,44 +643,44 @@
# handle filename collisions
- elif code == self.ProtocolError.DiskTargetExists:
- handleCollision = initialRequest.get('FcFilenameCollision', self.FilenameCollision.HandleNever)
- collisionHandled = bool(handleCollision & self.FilenameCollision.CollisionHandled)
+ elif code == consts.ProtocolError.DiskTargetExists:
+ handleCollision = initialRequest.get('FcFilenameCollision', consts.FilenameCollision.HandleNever)
+ collisionHandled = bool(handleCollision & consts.FilenameCollision.CollisionHandled)
# rename filename
- if handleCollision & self.FilenameCollision.HandleRename:
+ if handleCollision & consts.FilenameCollision.HandleRename:
filename = initialRequest['Filename']
- initialRequest['FcFilenameCollision'] |= self.FilenameCollision.CollisionHandled
+ initialRequest['FcFilenameCollision'] |= consts.FilenameCollision.CollisionHandled
newFilename = namespace.unique_filename(filename, extensions=1, ispostfixed=collisionHandled)
initialRequest['Filename'] = newFilename
- initialRequest['FcModified'] = {self.Message.ModifiedRequestFilename: filename}
+ initialRequest['FcModified'] = {consts.RequestModified.Filename: filename}
self.sendMessageEx(initialRequest)
self.events.RequestModified(initialRequest)
return True
# don't handle
else:
- initialRequest['FcFilenameCollision'] &= ~self.FilenameCollision.CollisionHandled
+ initialRequest['FcFilenameCollision'] &= ~consts.FilenameCollision.CollisionHandled
# handle plugin related request failures
- elif code == self.ProtocolError.NoSuchPlugin:
- if initialRequest.name == self.Message.MessagePluginInfo:
+ elif code == consts.ProtocolError.NoSuchPlugin:
+ if initialRequest.name == consts.Message.PluginInfo:
del self._requests[requestIdentifier]
self.events.PluginInfoFailed(initialRequest)
return True
- elif initialRequest.name == self.Message.MessageFCPPluginMessage:
+ elif initialRequest.name == consts.Message.FCPPluginMessage:
del self._requests[requestIdentifier]
self.events.PluginMessageFailed(initialRequest)
return True
- elif code == self.ProtocolError.AccessDenied:
- if initialRequest.name == self.Message.MessagePluginInfo:
+ elif code == consts.ProtocolError.AccessDenied:
+ if initialRequest.name == consts.Message.PluginInfo:
del self._requests[requestIdentifier]
self.events.PluginInfoFailed(initialRequest)
return True
# TODO: just a guess that FCPPluginMessage can trigger an AccessDenied error
- elif initialRequest.name == self.Message.MessageFCPPluginMessage:
+ elif initialRequest.name == consts.Message.FCPPluginMessage:
del self._requests[requestIdentifier]
self.events.PluginMessageFailed(initialRequest)
return True
@@ -707,7 +692,7 @@
# NOTE: Fcp already removed the request
del self._requests[requestIdentifier]
initialRequest['FcErrorMessage'] = msg
- initialRequest['FcStatus'] = self.Message.StatusError | self.Message.StatusRemoved
+ initialRequest['FcStatus'] = consts.MessageStatus.Error | consts.MessageStatus.Removed
self.events.RequestFailed(initialRequest)
return True
@@ -721,7 +706,7 @@
## TestDDA drill.
##
####################################################
- elif msg.name == self.Message.MessageTestDDAReply:
+ elif msg.name == consts.Message.TestDDAReply:
directory = msg['Directory']
# find message that triggered the call
@@ -752,14 +737,14 @@
initialRequest['FcTestDDA']['TmpFile'] = fpathWrite
self.sendMessage(
- self.Message.MessageTestDDAResponse,
+ consts.Message.TestDDAResponse,
Directory=msg['Directory'],
ReadContent=readContent,
)
return True
- elif msg.name == self.Message.MessageTestDDAComplete:
+ elif msg.name == consts.Message.TestDDAComplete:
# clean up tmp file
directory = msg['Directory']
@@ -790,7 +775,7 @@
#TODO: check if errorMsg gives reasonable feedback
del self._requests[initialRequest['Identifier']]
- initialRequest['FcStatus'] = self.Message.StatusError | self.Message.StatusRemoved
+ initialRequest['FcStatus'] = consts.MessageStatus.Error | consts.MessageStatus.Removed
initialRequest['FcErrorMessage'] = initialRequest['FcTestDDA']['ErrorMsg']
self.events.ProtocolError(initialRequest)
return True
@@ -807,11 +792,11 @@
## config related
##
####################################################
- elif msg.name == self.Message.MessageConfigData:
+ elif msg.name == consts.Message.ConfigData:
self.events.ConfigData(msg)
return True
- elif msg.name == self.Message.MessageNodeData:
+ elif msg.name == consts.Message.NodeData:
self.events.NodeData(msg)
return True
@@ -821,7 +806,7 @@
## get / put related
##
####################################################
- elif msg.name == self.Message.MessageAllData:
+ elif msg.name == consts.Message.AllData:
if initialRequest is None:
return False
@@ -829,13 +814,13 @@
self.events.RequestCompleted(initialRequest)
return True
- elif msg.name == self.Message.MessageDataFound:
+ elif msg.name == consts.Message.DataFound:
if initialRequest is None:
# something is going wrong
return False
- initialRequest['FcStatus'] = self.Message.StatusComplete
+ initialRequest['FcStatus'] = consts.MessageStatus.Complete
initialRequest['FcMetadataContentType'] = msg.get('Metadata.ContentType', '')
initialRequest['FcDataLength'] = msg.get('DataLength', '')
self.events.RequestCompleted(initialRequest)
@@ -843,15 +828,15 @@
- elif msg.name == self.Message.MessageGetFailed:
+ elif msg.name == consts.Message.GetFailed:
code = msg['Code']
if initialRequest is None:
# something is going wrong
return False
# check if it is one of our requests for key information
- if code == self.FetchError.TooBig and initialRequest['FcSubType'] == self.Message.SubTypeGetKeyInfo:
- initialRequest['FcStatus'] = self.Message.StatusComplete
+ if code == self.FetchError.TooBig and initialRequest['FcSubType'] == consts.MessageSubType.GetKeyInfo:
+ initialRequest['FcStatus'] = consts.MessageStatus.Complete
initialRequest['FcMetadataContentType'] = msg.get('ExpectedMetadata.ContentType', '')
initialRequest['FcDataLength'] = msg.get('ExpectedDataLength', -1)
initialRequest['FcProgressCompleted'] = True
@@ -863,13 +848,13 @@
#TODO: check if Fcp removed the request
initialRequest['FcErrorMessage'] = msg
- initialRequest['FcStatus'] = self.Message.StatusError
+ initialRequest['FcStatus'] = consts.MessageStatus.Error
self.events.RequestFailed(initialRequest)
return True
- elif msg.name == self.Message.MessagePersistentGet:
+ elif msg.name == consts.Message.PersistentGet:
# unknown request... try to restore it
if initialRequest is None:
@@ -878,24 +863,24 @@
# not one of our requests... so cancel it
if restoredRequest is None or CancelPersistentRequests:
self.sendMessage(
- self.Message.MessageRemovePersistentRequest,
+ consts.Message.RemovePersistentRequest,
Identifier=msg['Identifier'],
Global=msg['Global'],
)
return True
# determine initial message name
- restoredRequest.name = self.Message.MessageClientGet
+ restoredRequest.name = consts.Message.ClientGet
# restore request
self._requests[requestIdentifier] = restoredRequest
- restoredRequest['FcStatus'] = self.Message.StatusStarted
+ restoredRequest['FcStatus'] = consts.MessageStatus.Started
self.events.RequestRestored(restoredRequest)
return True
# known request... filter out multiple PersistentGets
- if initialRequest['FcStatus'] == self.Message.StatusPending:
- initialRequest['FcStatus'] = self.Message.StatusStarted
+ if initialRequest['FcStatus'] == consts.MessageStatus.Pending:
+ initialRequest['FcStatus'] = consts.MessageStatus.Started
#TODO: update initialRequest with params from PersistentGet?
@@ -904,7 +889,7 @@
return True
- elif msg.name == self.Message.MessagePersistentPut:
+ elif msg.name == consts.Message.PersistentPut:
# unknown request... try to restore it
if initialRequest is None:
@@ -913,29 +898,29 @@
# not one of our requests... so cancel it
if restoredRequest is None or CancelPersistentRequests:
self.sendMessage(
- self.Message.MessageRemovePersistentRequest,
+ consts.Message.RemovePersistentRequest,
Identifier=msg['Identifier'],
Global=msg['Global'],
)
return True
# determine initial message name
- if restoredRequest['FcSubType'] == self.Message.SubTypePut:
- restoredRequest.name = self.Message.MessageClientPut
- elif restoredRequest['FcSubType'] == self.Message.SubTypePutDiskDir:
- restoredRequest.name = self.Message.MessageClientPutDiskDir
- elif restoredRequest['FcSubType'] == self.Message.SubTypePutComplexDir:
- restoredRequest.name = self.Message.MessageClientPutComplexDir
+ if restoredRequest['FcSubType'] == consts.MessageSubType.Put:
+ restoredRequest.name = consts.Message.ClientPut
+ elif restoredRequest['FcSubType'] == consts.MessageSubType.PutDiskDir:
+ restoredRequest.name = consts.Message.ClientPutDiskDir
+ elif restoredRequest['FcSubType'] == consts.MessageSubType.PutComplexDir:
+ restoredRequest.name = consts.Message.ClientPutComplexDir
# restore request
self._requests[requestIdentifier] = restoredRequest
- restoredRequest['FcStatus'] = self.Message.StatusStarted
+ restoredRequest['FcStatus'] = consts.MessageStatus.Started
self.events.RequestRestored(restoredRequest)
return True
# known request... filter out multiple PersistentGets
- if initialRequest['FcStatus'] == self.Message.StatusPending:
- initialRequest['FcStatus'] = self.Message.StatusStarted
+ if initialRequest['FcStatus'] == consts.MessageStatus.Pending:
+ initialRequest['FcStatus'] = consts.MessageStatus.Started
#TODO: update initialRequest with params from PersistentPut?
#TODO: update initialRequest with params from PersistentPut?
@@ -946,7 +931,7 @@
return True
- elif msg.name == self.Message.MessagePersistentRequestModified:
+ elif msg.name == consts.Message.PersistentRequestModified:
if initialRequest is None:
return False
@@ -962,14 +947,14 @@
# ...as long as no other param is changed at runtime we are ok
# otherwise we would have to set flags to indicate wich member
# of ClientToken changed. See --> modifyRequest()
- modified[self.Message.ModifiedRequestPersistentUserData] = None
+ modified[consts.RequestModified.PersistentUserData] = None
for i, fcParam in enumerate(self.FcParams.FcParams):
initialRequest[fcParam] = params[i]
# check if PriorityClass has changed
priorityClass = msg.get('PriorityClass', None)
if priorityClass is not None:
- modified[self.Message.ModifiedRequestPriorityClass] = None
+ modified[consts.RequestModified.PriorityClass] = None
initialRequest['PriorityClass'] = priorityClass
initialRequest['FcModified'] = modified
@@ -977,7 +962,7 @@
return True
- elif msg.name == self.Message.MessagePersistentRequestRemoved:
+ elif msg.name == consts.Message.PersistentRequestRemoved:
if initialRequest is None:
return False
@@ -985,7 +970,7 @@
return True
- elif msg.name == self.Message.MessageSimpleProgress:
+ elif msg.name == consts.Message.SimpleProgress:
if initialRequest is None:
# something went wrong
return False
@@ -1000,14 +985,14 @@
## put related
- elif msg.name == self.Message.MessageURIGenerated:
+ elif msg.name == consts.Message.URIGenerated:
if initialRequest is None: # something went wrong
return False
initialRequest['URI'] = msg['URI']
return True
- elif msg.name == self.Message.MessagePutFetchable:
+ elif msg.name == consts.Message.PutFetchable:
if initialRequest is None:
# something went wrong
return False
@@ -1016,7 +1001,7 @@
return True
- elif msg.name == self.Message.MessagePutSuccessful:
+ elif msg.name == consts.Message.PutSuccessful:
if initialRequest is None:
# something went wrong
return False
@@ -1034,27 +1019,27 @@
## Peer related messages
##
####################################################
- elif msg.name == self.Message.MessageEndListPeers:
+ elif msg.name == consts.Message.EndListPeers:
self.events.EndListPeers(msg)
return True
- elif msg.name == self.Message.MessageEndListPeerNotes:
+ elif msg.name == consts.Message.EndListPeerNotes:
self.events.EndListPeerNotes(msg.params)
return True
- elif msg.name == self.Message.MessagePeer:
+ elif msg.name == consts.Message.Peer:
self.events.Peer(msg)
return True
- elif msg.name == self.Message.MessagePeerNote:
+ elif msg.name == consts.Message.PeerNote:
self.events.PeerNote(msg)
return True
- elif msg.name == self.Message.MessagePeerRemoved:
+ elif msg.name == consts.Message.PeerRemoved:
self.events.PeerRemoved(msg)
return True
- elif msg.name == self.Message.MessageUnknownNodeIdentifier:
+ elif msg.name == consts.Message.UnknownNodeIdentifier:
self.events.UnknownNodeIdentifier(msg)
return True
@@ -1063,7 +1048,7 @@
## plugins
##
####################################################
- elif msg.name == self.Message.MessagePluginInfo:
+ elif msg.name == consts.Message.PluginInfo:
if initialRequest is None:
return False
@@ -1071,7 +1056,7 @@
self.events.PluginInfo(msg)
return True
- elif msg.name == self.Message.MessageFCPPluginReply:
+ elif msg.name == consts.Message.FCPPluginReply:
if initialRequest is None:
return False
@@ -1084,7 +1069,7 @@
## others
##
####################################################
- elif msg.name == self.Message.MessageSSKKeypair:
+ elif msg.name == consts.Message.SSKKeypair:
if requestIdentifier not in self._sskRequests:
return False
@@ -1104,9 +1089,9 @@
return True
- elif msg.name == self.Message.MessageCloseConnectionDuplicateClientName:
+ elif msg.name == consts.Message.CloseConnectionDuplicateClientName:
msg = self.Message(
- self.Message.MessageClientDisconnected,
+ consts.Message.ClientDisconnected,
DisconnectReason=DisconnectReason.DuplicateClientName,
)
self.events.ClientDisconnect(msg)
@@ -1123,13 +1108,13 @@
@note: use this method instead of run() to run the client step by step
"""
msg = self.Message.fromSocket(self._socket)
- if msg.name == self.Message.MessageClientSocketDied:
+ if msg.name == consts.Message.ClientSocketDied:
if dispatch:
- msg['DisconnectReason'] = self.DisconnectReason.SocketDied
+ msg['DisconnectReason'] = consts.DisconnectReason.SocketDied
self.events.ClientDisconnected(msg)
raise socket.error(msg['Details'])
- elif msg.name == self.Message.MessageClientSocketTimeout:
+ elif msg.name == consts.Message.ClientSocketTimeout:
if dispatch:
self.events.Idle(msg)
@@ -1160,16 +1145,16 @@
If an error handler is passed to the client it is called emidiately before the error
is raised.
"""
- self._log.debug(self.LogMessages.MessageSend + msg.pprint())
+ self._log.debug(consts.LogMessages.MessageSend + msg.pprint())
try:
msg.send(self._socket)
except socket.error, d:
- self._log.info(self.LogMessages.SocketDied)
+ self._log.info(consts.LogMessages.SocketDied)
self.close()
errorMsg = self.Message(
- self.Message.MessageClientSocketDied,
- DisconnectReason=self.DisconnectReason.SocketDied,
+ consts.Message.ClientSocketDied,
+ DisconnectReason=consts.DisconnectReason.SocketDied,
Exception=socket.error,
Details=d
)
@@ -1196,7 +1181,7 @@
@event: ConfigData(event, msg)
"""
self.sendMessage(
- self.Message.MessageGetConfig,
+ consts.Message.GetConfig,
WithSortOrder=withSortOrder,
WithCurrent=withCurrent,
WithDefaults=withDefaults,
@@ -1211,7 +1196,7 @@
"""Modifies node configuration values
@param params: (dict) containing parameters to modify
"""
- msg = self.Message(self.Message.MessageModifyConfig)
+ msg = self.Message(consts.Message.ModifyConfig)
msg.params = params
self.sendMessageEx(msg)
@@ -1230,8 +1215,8 @@
**messageParams
):
"""Requests a key from the node
- @param uri: uri of the file to request (may contain prefixes like 'freenet:' or 'http://')
- @param messageSubType: one of the Message.SubType* consts to the desired request
+ @param uri: (str) uri of the file to request (may contain prefixes like 'freenet:' or 'http://')
+ @param messageSubType: (L{consts.MessageSubType}) sub type of the message
@param userData: any non persistent data to associate to the request or None
@param persistentUserData: any string to associate to the request as persistent data or None
@param filenameCollision: what to do if the disk target alreaady exists. One of the FilenameCollision.* consts
@@ -1243,7 +1228,7 @@
"""
uri = self.Uri(uri).uri
- msg = self.Message(self.Message.MessageClientGet, URI=uri)
+ msg = self.Message(consts.Message.ClientGet, URI=uri)
for paramName, value in messageParams.items():
if value is not None:
msg[paramName] = value
@@ -1281,13 +1266,13 @@
@param uri: uri of the file to request (may contain prefixes like 'freenet:' or 'http://')
@param allowedMimeTypes: (str) list of allowed mime types
- @param binaryBlob: if True, the file is retrieved as binary blob file
- @param dsOnly: if True, retrieves the file from the local data store only
- @param ignoreDs: If True, ignores the local data store
+ @param binaryBlob: (bool) if True, the file is retrieved as binary blob file
+ @param dsOnly: (bool) if True, retrieves the file from the local data store only
+ @param ignoreDS: (bool) if True, ignores the local data store
@param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide
@param maxSize: (int) maximum size of the file in bytes or None to set no limited
- @param persistence: persistence of the request as one of the L{consts.Persistence} constants
- @param priorityClass: priority of the request as one of the L{consts.Priority} consts
+ @param persistence: (L{consts.Persistence}) persistence of the request
+ @param priorityClass: (L{consts.Priority}) priority of the request
@param userData: any non persistent data to associate to the request
@param persistentUserData: any string to associate to the request as persistent data
@@ -1297,7 +1282,7 @@
"""
return self.clientGet(
uri,
- self.Message.SubTypeGetData,
+ consts.MessageSubType.GetData,
userData,
persistentUserData,
consts.FilenameCollision.HandleNever,
@@ -1313,9 +1298,9 @@
MaxSize = maxSize,
Persistence=persistence,
PriorityClass=priorityClass,
- ReturnType=self.ReturnType.Direct,
+ ReturnType=consts.ReturnType.Direct,
URI=self.Uri(uri).uri,
- Verbosity=self.Verbosity.ReportProgress,
+ Verbosity=consts.Verbosity.ReportProgress,
)
@@ -1344,11 +1329,11 @@
@param allowedMimeTypes: (str) list of allowed mime types
@param binaryBlob: if True, the file is retrieved as binary blob file
@param dsOnly: if True, retrieves the file from the local data store only
- @param ignoreDs: If True, ignores the local data store
+ @param ignoreDS: If True, ignores the local data store
@param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide
@param maxSize: (int) maximum size of the file in bytes or None to set no limited
- @param persistence: persistence of the request as one of the L{consts.Persistence} constants
- @param priorityClass: priority of the request as one of the L{consts.Priority} consts
+ @param persistence: (L{consts.Persistence}) persistence of the request
+ @param priorityClass: (L{consts.Priority}) priority of the request
@param filenameCollision: what to do if the disk target alreaady exists. One of the FilenameCollision.* consts
@param userData: any non persistent data to associate to the request
@@ -1359,7 +1344,7 @@
"""
return self.clientGet(
uri,
- self.Message.SubTypeGetFile,
+ consts.MessageSubType.GetFile,
userData,
persistentUserData,
filenameCollision,
@@ -1376,9 +1361,9 @@
MaxSize = maxSize,
Persistence=persistence,
PriorityClass=priorityClass,
- ReturnType=self.ReturnType.Disk,
+ ReturnType=consts.ReturnType.Disk,
URI=self.Uri(uri).uri,
- Verbosity=self.Verbosity.ReportProgress,
+ Verbosity=consts.Verbosity.ReportProgress,
)
@@ -1399,10 +1384,10 @@
@param uri: uri of the file to request (may contain prefixes like 'freenet:' or 'http://')
@param dsOnly: if True, retrieves the file from the local data store only
- @param ignoreDs: If True, ignores the local data store
+ @param ignoreDS: If True, ignores the local data store
@param maxRetries: (int) maximum number of retries or -1 to retry forver or None to leave it to the node to decide
- @param persistence: persistence of the request as one of the L{consts.Persistence} constants
- @param priorityClass: priority of the request as one of the L{consts.Priority} consts
+ @param persistence: (L{consts.Persistence}) persistence of the request
+ @param priorityClass: (L{consts.Priority}) priority of the request
@param userData: any non persistent data to associate to the request
@param persistentUserData: any string to associate to the request as persistent data
@@ -1411,7 +1396,7 @@
# how to retrieve meta info about a key? ...idea is to provoke a GetFailed (TooBig)
return self.clientGet(
uri,
- self.Message.SubTypeGetKeyInfo,
+ consts.MessageSubType.GetKeyInfo,
userData,
persistentUserData,
consts.FilenameCollision.HandleNever,
@@ -1425,9 +1410,9 @@
MaxSize=self.MaxSizeKeyInfo,
Persistence=persistence,
PriorityClass=priorityClass,
- ReturnType=self.ReturnType.Nothing,
+ ReturnType=consts.ReturnType.Nothing,
URI=self.Uri(uri).uri,
- Verbosity=self.Verbosity.ReportProgress,
+ Verbosity=consts.Verbosity.ReportProgress,
)
@@ -1443,12 +1428,12 @@
raise ValueError('Nothing to upload')
# determine SubType
- if msg.name == self.Message.MessageClientPut:
- messageSubType = self.Message.SubTypePut
- elif msg.name == self.Message.MessageClientPutDiskDir:
- messageSubType = self.Message.SubTypePutDiskDir
+ if msg.name == consts.Message.ClientPut:
+ messageSubType = consts.MessageSubType.Put
+ elif msg.name == consts.Message.ClientPutDiskDir:
+ messageSubType = consts.MessageSubType.PutDiskDir
else:
- messageSubType = self.Message.SubTypePutComplexDir
+ messageSubType = consts.MessageSubType.PutComplexDir
self._registerRequest(
msg,
@@ -1476,7 +1461,7 @@
data,
**messageParams):
- msg = self.Message(self.Message.MessageClientPut, URI=uri)
+ msg = self.Message(consts.Message.ClientPut, URI=uri)
for paramName, value in messageParams.items():
if value is not None:
msg[paramName] = value
@@ -1517,7 +1502,7 @@
return self.clientPut(
consts.KeyType.CHK,
- self.Message.SubTypePut,
+ consts.MessageSubType.Put,
userData,
persistentUserData,
data,
@@ -1533,8 +1518,8 @@
DontCompress=dontCompress,
Persistence=persistence,
TargetFilename=targetFilename,
- UploadFrom=self.UploadFrom.Direct,
- Verbosity=self.Verbosity.ReportProgress | self.Verbosity.ReportCompression,
+ UploadFrom=consts.UploadFrom.Direct,
+ Verbosity=consts.Verbosity.ReportProgress | consts.Verbosity.ReportCompression,
)
def putFile(self,
@@ -1553,7 +1538,7 @@
):
return self.clientPut(
concts.KeyType.CHK,
- self.Message.SubTypePut,
+ consts.MessageSubType.Put,
userData,
persistentUserData,
None,
@@ -1569,8 +1554,8 @@
DontCompress=dontCompress,
Persistence=persistence,
TergetFilename=targetFilename,
- UploadFrom=self.UploadFrom.Disk,
- Verbosity=self.Verbosity.ReportProgress | self.Verbosity.ReportCompression,
+ UploadFrom=consts.UploadFrom.Disk,
+ Verbosity=consts.Verbosity.ReportProgress | consts.Verbosity.ReportCompression,
)
@@ -1596,15 +1581,15 @@
def modifyRequest(self, requestIdentifier, persistentUserData=None, priorityClass=None):
"""Modifies a request
- @param identifier: identifier of the request to modify
- @param clientToken: new client token or None
- @param priorityClass: new priority or None
+ @param requestIdentifier: identifier of the request to modify
+ @param persistentUserData: (str) persistent user data or None
+ @param priorityClass: (L{consts.Priority}) new priority or None
@note: a RequestModified event is triggered as soon as the request has actually been modified
"""
initialRequest = self._requests[requestIdentifier]
msg = self.Message(
- self.Message.MessageModifyPersistentRequest,
+ consts.Message.ModifyPersistentRequest,
Identifier=initialRequest['Identifier'],
Global=False,
)
@@ -1618,14 +1603,14 @@
def removeRequest(self, requestIdentifier):
"""Removes a request
- @param identifier: (str) identifier of the request to remove
+ @param requestIdentifier: (str) identifier of the request to remove
@note: a RequestRemoved event is triggered as soon as the request has actually been removed
"""
initialRequest = self._requests[requestIdentifier]
- initialRequest['FcStatus'] = self.Message.StatusRemoved
+ initialRequest['FcStatus'] = consts.MessageStatus.Removed
self.sendMessage(
- self.Message.MessageRemovePersistentRequest,
+ consts.Message.RemovePersistentRequest,
Global=False,
Identifier=requestIdentifier,
)
@@ -1648,36 +1633,36 @@
"""Request information about the node
@param withPrivate: if True, private data is included
@param withVolatile: if True, statistical data is included
- @param giveOppennetRef: if True, the opennet reference is retuned instead of the darknet
+ @param giveOpennetRef: if True, the opennet reference is retuned instead of the darknet
"""
self.sendMessage(
- self.Message.MessageGetNode,
+ consts.Message.GetNode,
WithPrivate=withPrivate,
WithVolatile=withVolatile,
GiveOpennetRef=giveOpennetRef,
)
- def listPeer(self, identity):
+ def listPeer(self, nodeIdentity):
"""Requests information about a peer node
- @param identifier: identifier of the peer to request information for
+ @param nodeIdentity: identity of the peer to request information for
"""
- self.jobClient.sendMessage(
- self.Message.MessageListPeer,
+ self.sendMessage(
+ consts.Message.ListPeer,
NodeIdentifier=identity,
)
- def listPeerNotes(self, identity):
+ def listPeerNotes(self, nodeIdentity):
"""Lists all text notes associated to a peer
- @param identifier: peer as returned in a call to L{peerList}
+ @param nodeIdentity: peer as returned in a call to L{listPeer}
@event: ListPeerNote(event, params)
@event: EndListPeerNotes(event, params)
@note: listPeerNotes() is only available for darknet nodes
"""
self.sendMessage(
- self.Message.MessageListPeerNotes,
- NodeIdentifier=identity
+ consts.Message.ListPeerNotes,
+ NodeIdentifier=nodeIdentity
)
@@ -1690,54 +1675,54 @@
@event: EndListPeers(event, params).
"""
self.sendMessage(
- self.Message.MessageListPeers,
+ consts.Message.ListPeers,
WithMetadata=withMetaData,
WithVolatile=withVolantile,
)
- def modifyPeer(self, identity, allowLocalAddresses=None, isDisabled=None, isListenOnly=None):
+
+ def modifyPeer(self, nodeIdentifier, allowLocalAddresses=None, isDisabled=None, isListenOnly=None):
"""Modifies a peer node
- @param identity: identity of the peer node to modify
+ @param nodeIdentifier: identitfier of the peer node to modify
@param allowLocalAddresses: if True, whatever is done
@param isDisabled: if True, the peer is disabled
@param isListenOnly: if True, the peer is set to listen only status
"""
msg = Message(
- self.Message.MessageModifyPeer,
- NodeIdentifier=identity,
+ consts.Message.ModifyPeer,
+ NodeIdentifier=nodeidentifier,
)
if allowLocalAddresses is not None:
msg['AllowLocalAddresses'] = allowLocalAddresses
if isDisabled is not None:
- msg['isDisabled'] = isDisabled
+ msg['IsDisabled'] = isDisabled
if isListenOnly is not None:
- msg['isListenOnly'] = isListenOnly
- self.jobClient.sendMessageEx(msg)
+ msg['IsListenOnly'] = isListenOnly
self.sendMessageEx(msg)
-
+
- def modifyPeerNote(self, identity, note):
+ def modifyPeerNote(self, nodeIdentifier, note):
"""Modifies the note associated to a peer
- @param identity: identity of the peer node to modify
+ @param nodeIdentifier: identitifier of the peer node to modify
@param note: (str) new note to associate to the peer
"""
self.sendMessage(
- self.Message.MessageModifyPeerNote,
- NodeIdentifier=identity,
+ consts.Message.ModifyPeerNote,
+ NodeIdentifier=nodeIdentifier,
#NOTE: currently fcp supports only this one type
- PeerNoteType=self.PeerNoteType.Private,
+ PeerNoteType=consts.PeerNoteType.Private,
NoteText=note
)
- def removePeer(self, identity):
+ def removePeer(self, nodeIdentifier):
"""Removes a peer
- @param identity: identity of the peer node to remove
+ @param nodeIdentifier: identitfier of the peer node to remove
"""
self.sendMessage(
- self.Message.MessageRemovePeer,
- NodeIdentifier=identity,
+ consts.Message.RemovePeer,
+ NodeIdentifier=nodeidentifier,
)
##########################################################
@@ -1757,7 +1742,7 @@
if identifier not in self._requests:
break
msg = self.Message(
- self.Message.MessageGetPluginInfo,
+ consts.Message.GetPluginInfo,
Identifier=identifier,
PluginName=pluginName,
Detailed=detailed,
@@ -1770,7 +1755,7 @@
def sendPluginMessage(self, pluginName, params, data=None):
"""Sends a message to a plugin
@param pluginName: name of the plugin to send the message to
- @param poarams: (dict) additional params to pass to the plugin (each parameter has to be prefixed with 'Param.')
+ @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
"""
@@ -1779,7 +1764,7 @@
if identifier not in self._requests:
break
msg = self.Message(
- self.Message.MessageGetPluginInfo,
+ consts.Message.GetPluginInfo,
Identifier=identifier,
PluginName=pluginName,
**params
@@ -1802,7 +1787,7 @@
##########################################################
def generateKeypair(self, keypairType=consts.KeyType.SSK):
"""
- @param keypairType: type of keypair to generate (either L{KeyType.SSK} or L{KeyType.SSK})
+ @param keypairType: type of keypair to generate (either L{consts.KeyType.SSK} or L{consts.KeyType.SSK})
@return: identifier of the request
@event: KeypairGenerated(event, params) is triggered when the request is complete
"""
@@ -1816,7 +1801,7 @@
break
self._sskRequests.append(identifier)
self.sendMessage(
- self.Message.MessageGenerateSSK,
+ consts.Message.GenerateSSK,
Identifier=identifier,
)
return identifier
@@ -1828,7 +1813,7 @@
if __name__ == '__main__':
c = FcpClient(
connectionName='test',
- debugVerbosity=FcpClient.DebugVerbosity.Debug
+ debugVerbosity=consts.DebugVerbosity.Debug
)
for nodeHello in c.connect(): pass
@@ -2012,3 +1997,10 @@
#testGetPluginInfo()
+
+ def testListPeers():
+ c.listPeers()
+ for i in xrange(30):
+ c.next()
+
+ #testListPeers()
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|