spacepaste

  1.  
  2. #!/usr/bin/python
  3. """
  4. XDCC file downloader
  5. Hacked together by Gregory Eric Sanderson Turcot Temlett MacDonnell Forbes
  6. Requires the python package "twisted"
  7. This script connects to an IRC server and batch downloads files using the XDCC
  8. protocol.
  9. TODO:
  10. * Manage partial downloads
  11. * Manage unexpected DCC connections
  12. * Add optional port to command line
  13. License:
  14. This program is free software: you can redistribute it and/or modify
  15. it under the terms of the GNU General Public License as published by
  16. the Free Software Foundation, either version 3 of the License, or
  17. (at your option) any later version.
  18. This program is distributed in the hope that it will be useful,
  19. but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. GNU General Public License for more details.
  22. You should have received a copy of the GNU General Public License
  23. along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. """
  25. import sys
  26. import logging as log
  27. from twisted.words.protocols import irc
  28. from twisted.internet import reactor, protocol
  29. from twisted.python import log as twistedlog
  30. def setup_logger(logger_name, log_file, level=log.INFO):
  31. l = log.getLogger(logger_name)
  32. formatter = log.Formatter('%(asctime)s : %(message)s')
  33. fileHandler = log.FileHandler(log_file, mode='w')
  34. fileHandler.setFormatter(formatter)
  35. #streamHandler = log.StreamHandler()
  36. #streamHandler.setFormatter(formatter)
  37. l.setLevel(level)
  38. l.addHandler(fileHandler)
  39. #l.addHandler(streamHandler)
  40. class XdccBot( irc.IRCClient ):
  41. @property
  42. def nickname( self ):
  43. return self.factory.nickname
  44. def connectionMade( self ):
  45. irc.IRCClient.connectionMade( self )
  46. logP.info("Bot connection made")
  47. def signedOn( self ):
  48. logP.info("Bot has signed on")
  49. self.join( self.factory.channel )
  50. def joined( self, channel ):
  51. logP.info("Bot has joined channel %s" % channel )
  52. self.processXdccRequests()
  53. def processXdccRequests( self ):
  54. xdccmsg = "XDCC SEND #%s"
  55. if len( self.factory.xdccRequests ) > 0:
  56. number = self.factory.xdccRequests.pop(0)
  57. message = xdccmsg % str(number)
  58. print "message: ", self.factory.xdccBot, message
  59. self.msg( self.factory.xdccBot, message )
  60. else:
  61. reactor.stop()
  62. def privmsg( self, user, channel, msg ):
  63. if channel == self.nickname:
  64. logP.info(user, channel, msg)
  65. print "private: ", user, channel, msg
  66. else:
  67. #print "gobal:", user, channel, msg
  68. logC.info( "<%s> %s" % (user, msg) )
  69. def dccDoSend( self, user, address, port, filename, size, data ):
  70. print "dccDoSend", user, address, port, filename, size, data
  71. factory = XdccDownloaderFactory(
  72. self,
  73. filename,
  74. self.factory.destdir,
  75. (user, self.factory.channel, data) )
  76. if not hasattr( self, 'dcc_sessions' ):
  77. self.dcc_sessions = []
  78. self.dcc_sessions.append( factory )
  79. reactor.connectTCP(address, port, factory)
  80. def dccDownloadFinished( self, filename, success ):
  81. logP.info("Download of %s finished. Download status: %s" %
  82. ( filename, success ) )
  83. self.processXdccRequests()
  84. class XdccBotFactory( protocol.ClientFactory ):
  85. def __init__( self, channel, nickname, xdccBot, xdccRequests, destdir = '.' ):
  86. self.channel = channel
  87. self.nickname = nickname
  88. self.destdir = destdir
  89. self.xdccBot = xdccBot
  90. self.xdccRequests = xdccRequests
  91. def clientConnectionLost(self, connector, reason):
  92. logP.warning("Lost connection. Will try to reconnect. reason : %s" %
  93. reason)
  94. connector.connect()
  95. def buildProtocol( self, addr ):
  96. bot = XdccBot()
  97. bot.factory = self
  98. return bot
  99. def clientConnectionFailed(self, connector, reason):
  100. logP.warning("Connection failed. reason: %s" % reason)
  101. reactor.stop()
  102. class XdccDownloader( irc.DccFileReceive ):
  103. notifyBlockSize = 1024 * 1024
  104. def __init__( self, filename, filesize=-1, queryData=None, destDir='.',
  105. resumeOffset=0):
  106. irc.DccFileReceive.__init__( self, filename, filesize, queryData, destDir,
  107. resumeOffset )
  108. self.bytesNotify = 0
  109. def isDownloadSuccessful( self ):
  110. return self.bytesReceived == self.fileSize
  111. def dataReceived( self, data ):
  112. irc.DccFileReceive.dataReceived( self, data )
  113. if self.bytesReceived >= self.bytesNotify + self.notifyBlockSize:
  114. self.bytesNotify += self.notifyBlockSize
  115. logP.info("%s is now at %s bytes" % (self.filename,
  116. self.bytesReceived) )
  117. def connectionLost( self, reason ):
  118. logP.info(reason)
  119. self.fileSize = self.file.tell()
  120. irc.DccFileReceive.connectionLost( self, reason )
  121. if hasattr( self.factory.client, 'dccDownloadFinished' ):
  122. self.factory.client.dccDownloadFinished( self.filename,
  123. self.isDownloadSuccessful() )
  124. class XdccDownloaderFactory( protocol.ClientFactory ):
  125. def __init__( self, client, filename, destdir, queryData ):
  126. self.client = client
  127. self.queryData = queryData
  128. self.filename = filename
  129. self.destdir = destdir
  130. def buildProtocol( self, addr ):
  131. downloader = XdccDownloader(
  132. self.filename,
  133. -1,
  134. self.queryData,
  135. self.destdir)
  136. downloader.factory = self
  137. return downloader
  138. def clientConnectionFailed( self, connector, reason ):
  139. logP.warning("connection failed during DCC download. reason: %s" %
  140. reason)
  141. self.client.dcc_sessions.remove(self)
  142. def clientConnectionLost( self, connector, reason ):
  143. self.client.dcc_sessions.remove(self)
  144. if __name__ == "__main__":
  145. if( len( sys.argv ) < 6 ):
  146. print "Usage: %s IRC_SERVER CHANNEL NICKNAME BOTNICKNAME XDCC_REQUESTS"
  147. sys.exit(1)
  148. #log.basicConfig( level = log.INFO )
  149. #log.basicConfig(
  150. # filename='twitter_effect.log',
  151. # level=log.INFO,
  152. #)
  153. setup_logger('log_private', '/tmp/log_private')
  154. setup_logger('log_channel', '/tmp/log_channel')
  155. logP = log.getLogger('log_private')
  156. logC = log.getLogger('log_channel')
  157. observer = twistedlog.PythonLoggingObserver()
  158. observer.start()
  159. server, channel, nickname, xdccbot = sys.argv[1:5]
  160. xdccrequests = sys.argv[5:]
  161. print server, channel, nickname, xdccbot, xdccrequests
  162. factory = XdccBotFactory( channel, nickname, xdccbot, xdccrequests )
  163. reactor.connectTCP( server, 6667, factory )
  164. reactor.run()
  165.