Guest User

Untitled

a guest
Apr 13th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.32 KB | None | 0 0
  1. """
  2. """
  3. import sys
  4. import os
  5.  
  6. import os
  7. from twisted.python import log
  8. from twisted.internet import reactor
  9. from twisted.internet import task
  10.  
  11. from autonomotorrent.BTManager import BTManager
  12. from autonomotorrent.factory import BTServerFactories
  13. from autonomotorrent.MetaInfo import BTMetaInfo
  14. from autonomotorrent.DHTProtocol import DHTProtocol
  15.  
  16. import json
  17.  
  18. class BTConfig(object):
  19. def __init__(self, torrent_path=None, meta_info=None):
  20. if torrent_path:
  21. self.metainfo = BTMetaInfo(path=torrent_path)
  22. elif meta_info:
  23. self.metainfo = BTMetaInfo(meta_info=meta_info)
  24. args = [self.metaInfo]
  25.  
  26. else:
  27. raise Exception("Must provide either a torrent path or meta_info.")
  28.  
  29. self.generatedInfo = self.metainfo.create_meta_info(torrent_path)
  30. self.info_hash = self.metainfo.info_hash
  31. self.downloadList = None
  32. reactor.callWhenRunning(insertMetaInfo).addCallback(succesfulQuery)
  33.  
  34. def check(self) :
  35. if self.downloadList is None:
  36. self.downloadList = range(len(self.metainfo.files))
  37. for i in self.downloadList :
  38. f = self.metainfo.files[i]
  39. size = f['length']
  40. name = f['path']
  41. log.msg("File: {0} Size: {1}".format(name, size)) # TODO: Do we really need this?
  42.  
  43. def getMetaInfo(self):
  44. '''
  45. return metainfo object
  46. '''
  47. return self.metainfo
  48.  
  49. def insertMetaInfo(self):
  50. '''
  51. insertMetaInfo into the database
  52. '''
  53. return dbpool.runQuery("INSERT INTO `torrents` (torrent, name, active, uid, comment, createdBy, creationDate, numberPieces, pieceLength, path, announceUrls, pieces, files) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (self.info_hash, self.genereatedInfo['name'], 1, uid, self.generatedInfo['comment'], self.generatedInfo['created by'], self.generatedInfo['creation date'], len(self.generatedInfo['info']['pieces']), self.generatedInfo['info']['piece_length'], str(torrent_path), json.encode(self.generatedInfo['announce']), self.generatedInfo['info']['pieces'], self.generatedInfo['info']['files'],))
  54.  
  55. def succesfulQuery()
  56. print 'success'
  57.  
  58.  
  59. class BTApp:
  60. def __init__(self, save_dir=".",
  61. listen_port=6881,
  62. enable_DHT=False,
  63. remote_debugging=False):
  64. """
  65. @param remote_degugging enables telnet login via port 9999 with a
  66. username and password of 'admin'
  67. """
  68. log.startLogging(sys.stdout) # Start logging to stdout
  69. self.save_dir = save_dir
  70. self.listen_port = listen_port
  71. self.enable_DHT = enable_DHT
  72. self.tasks = {}
  73. self.btServer = BTServerFactories(self.listen_port)
  74. reactor.listenTCP(self.listen_port, self.btServer)
  75. if enable_DHT:
  76. log.msg("Turning DHT on.")
  77. self.dht = DHTProtocol()
  78. reactor.listenUDP(self.listen_port, self.dht)
  79.  
  80. if remote_debugging:
  81. log.msg("Turning remote debugging on. You may login via telnet " +\
  82. "on port 9999 username & password are 'admin'")
  83. import twisted.manhole.telnet
  84. dbg = twisted.manhole.telnet.ShellFactory()
  85. dbg.username = "admin"
  86. dbg.password = "admin"
  87. dbg.namespace['app'] = self
  88. reactor.listenTCP(9999, dbg)
  89.  
  90. def add_torrent(self, config):
  91. config.check()
  92. info_hash = config.info_hash
  93. if info_hash in self.tasks:
  94. log.msg('Torrent {0} already in download list'.format(config.metainfo.pretty_info_hash))
  95. else:
  96. btm = BTManager(self, config)
  97. self.tasks[info_hash] = btm
  98. btm.startDownload()
  99. return info_hash
  100.  
  101. def stop_torrent(self, key):
  102. info_hash = key
  103. if info_hash in self.tasks:
  104. btm = self.tasks[info_hash]
  105. btm.stopDownload()
  106.  
  107. def remove_torrent(self, key):
  108. info_hash = key
  109. if info_hash in self.tasks:
  110. btm = self.tasks[info_hash]
  111. btm.exit()
  112.  
  113. def stop_all_torrents(self):
  114. for task in self.tasks.itervalues() :
  115. task.stopDownload()
  116.  
  117. def get_status(self):
  118. """Returns a dictionary of stats on every torrent and total speed.
  119. """
  120. status = {}
  121. for torrent_hash, bt_manager in self.tasks.iteritems():
  122. pretty_hash = bt_manager.metainfo.pretty_info_hash
  123. speed = bt_manager.get_speed()
  124. num_connections = bt_manager.get_num_connections()
  125. progress = bt_manager.get_progress()
  126.  
  127. status[pretty_hash] = {
  128. "state": bt_manager.status,
  129. "speed_up": speed["up"],
  130. "speed_down": speed["down"],
  131. "num_seeds": num_connections["server"],
  132. "num_peers": num_connections["client"],
  133. "progress": progress,
  134. }
  135. try:
  136. status["all"]["speed_up"] += status[pretty_hash]["speed_up"]
  137. status["all"]["speed_down"] += status[pretty_hash]["speed_down"]
  138. except KeyError:
  139. status["all"] = {
  140. "speed_up": status[pretty_hash]["speed_up"],
  141. "speed_down": status[pretty_hash]["speed_down"]
  142. }
  143.  
  144.  
  145. return status
  146.  
  147. def start_reactor(self, *args, **kwargs):
  148. reactor.run(*args, **kwargs)
Add Comment
Please, Sign In to add comment