Advertisement
Guest User

magnet2torrent.py

a guest
Jul 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.25 KB | None | 0 0
  1. #!/usr/bin/env python
  2. '''
  3. Created on Apr 19, 2012
  4. @author: dan, Faless
  5.  
  6. GNU GENERAL PUBLIC LICENSE - Version 3
  7.  
  8. This program is free software: you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation, either version 3 of the License, or
  11. (at your option) any later version.
  12.  
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with this program. If not, see <http://www.gnu.org/licenses/>.
  20.  
  21. http://www.gnu.org/licenses/gpl-3.0.txt
  22.  
  23. '''
  24.  
  25. import shutil
  26. import tempfile
  27. import os.path as pt
  28. import sys
  29. import subprocess
  30. import os
  31. import libtorrent as lt
  32. from time import sleep
  33. from argparse import ArgumentParser
  34.  
  35.  
  36. def magnet2torrent(magnet, output_name=None):
  37. if output_name and \
  38. not pt.isdir(output_name) and \
  39. not pt.isdir(pt.dirname(pt.abspath(output_name))):
  40. print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
  41. print("")
  42. sys.exit(0)
  43.  
  44. tempdir = tempfile.mkdtemp()
  45. ses = lt.session()
  46. params = {
  47. 'save_path': tempdir,
  48. 'storage_mode': lt.storage_mode_t(2),
  49. 'paused': False,
  50. 'auto_managed': True,
  51. 'duplicate_is_error': True
  52. }
  53. ses.add_dht_router("router.bittorrent.com", 6881)
  54. ses.add_dht_router("router.utorrent.com", 6881)
  55. ses.add_dht_router("dht.transmissionbt.com", 6881)
  56. ses.add_dht_router("dht.aelitis.com", 6881)
  57. ses.add_dht_router("router.bitcomet.com", 6881)
  58. ses.start_dht()
  59. sleep(2)
  60. handle = lt.add_magnet_uri(ses, magnet, params)
  61.  
  62. print("Downloading Metadata (this may take a while)")
  63. while (not handle.has_metadata()):
  64. try:
  65. sleep(1)
  66. except KeyboardInterrupt:
  67. print("Aborting...")
  68. ses.pause()
  69. print("Cleanup dir " + tempdir)
  70. shutil.rmtree(tempdir)
  71. sys.exit(0)
  72. ses.pause()
  73. print("Done")
  74.  
  75. torinfo = handle.get_torrent_info()
  76. torfile = lt.create_torrent(torinfo)
  77.  
  78. output = pt.abspath(torinfo.name() + ".torrent")
  79.  
  80. if output_name:
  81. if pt.isdir(output_name):
  82. output = pt.abspath(pt.join(
  83. output_name, torinfo.name() + ".torrent"))
  84. elif pt.isdir(pt.dirname(pt.abspath(output_name))):
  85. output = pt.abspath(output_name)
  86.  
  87. print("Saving torrent file here : " + output + " ...")
  88. torcontent = lt.bencode(torfile.generate())
  89. f = open(output, "wb")
  90. f.write(lt.bencode(torfile.generate()))
  91. f.close()
  92. print("Saved! Cleaning up dir: " + tempdir)
  93. ses.remove_torrent(handle)
  94. shutil.rmtree(tempdir)
  95. subprocess.call(('sh','xdg-open',output))
  96. os.remove(output)
  97.  
  98. return output
  99.  
  100. def main():
  101. parser = ArgumentParser(description="A command line tool that converts magnet links in to .torrent files")
  102. parser.add_argument('-m','--magnet', help='The magnet url')
  103. parser.add_argument('-o','--output', help='The output torrent file name')
  104.  
  105. #
  106. # This second parser is created to force the user to provide
  107. # the 'output' arg if they provide the 'magnet' arg.
  108. #
  109. # The current version of argparse does not have support
  110. # for conditionally required arguments. That is the reason
  111. # for creating the second parser
  112. #
  113. # Side note: one should look into forking argparse and adding this
  114. # feature.
  115. #
  116. conditionally_required_arg_parser = ArgumentParser(description="A command line tool that converts magnet links in to .torrent files")
  117. conditionally_required_arg_parser.add_argument('-m','--magnet', help='The magnet url')
  118. conditionally_required_arg_parser.add_argument('-o','--output', help='The output torrent file name', required=True)
  119.  
  120. magnet = None
  121. output_name = None
  122.  
  123. #
  124. # Attempting to retrieve args using the new method
  125. #
  126. args = vars(parser.parse_known_args()[0])
  127. if args['magnet'] is not None:
  128. magnet = args['magnet']
  129. argsHack = vars(conditionally_required_arg_parser.parse_known_args()[0])
  130. output_name = argsHack['output']
  131. if args['output'] is not None and output_name is None:
  132. output_name = args['output']
  133. if magnet is None:
  134. #
  135. # This is a special case.
  136. # This is when the user provides only the "output" args.
  137. # We're forcing him to provide the 'magnet' args in the new method
  138. #
  139. print ('usage: {0} [-h] [-m MAGNET] -o OUTPUT'.format(sys.argv[0]))
  140. print ('{0}: error: argument -m/--magnet is required'.format(sys.argv[0]))
  141. sys.exit()
  142. #
  143. # Defaulting to the old of doing things
  144. #
  145. if output_name is None and magnet is None:
  146. if len(sys.argv) >= 2:
  147. magnet = sys.argv[1]
  148. if len(sys.argv) >= 3:
  149. output_name = sys.argv[2]
  150.  
  151. magnet2torrent(magnet, output_name)
  152.  
  153.  
  154. if __name__ == "__main__":
  155. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement