928187637d430a53b70a156c55004ea7480d984c
[living-lab-site.git] / cis / bt.py
1 #!/usr/bin/env python
2
3 from BaseLib.Core.API import *
4 import tempfile
5 import random
6 import config
7 import logger
8
9 def create_torrent(source):
10     """
11     Creates a torrent file for the video source file.
12     """
13
14     if isinstance(source, unicode):
15         usource = source
16     else:
17         usource = source.decode(sys.getfilesystemencoding())
18
19     duration = config.AVINFO_CLASS.get_video_duration(source, True)
20
21     tdef = TorrentDef()
22     tdef.add_content(usource, playtime=duration)
23     tdef.set_tracker(config.BT_TRACKER)
24
25     tdef.set_piece_length(32768)
26
27     tdef.finalize()
28     tdef.save(source + '.tstream')
29
30
31 class BitTorrent:
32     """
33     Implementation of BitTorrent operations that uses Next-Share library.
34     """
35
36     def __init__(self):
37
38         port = random.randint(10000, 65535)
39         
40         # setup session
41         sscfg = SessionStartupConfig()
42         statedir = tempfile.mkdtemp()
43         sscfg.set_state_dir(statedir)
44         sscfg.set_listen_port(port)
45         sscfg.set_megacache(False)
46         sscfg.set_overlay(False)
47         sscfg.set_dialback(True)
48         sscfg.set_internal_tracker(False)
49         
50         self.session = Session(sscfg)
51
52     def start_download(self, torrent, output_dir='.'):
53         """
54         Download (leech or seed) a file via BitTorrent.
55         The code is adapted from Next-Share's 'BaseLib/Tools/cmdlinedl.py'.
56
57         @param torrent .torrent file or URL
58         """
59
60         # setup and start download
61         dscfg = DownloadStartupConfig()
62         dscfg.set_dest_dir(output_dir)
63
64         if torrent.startswith("http") or torrent.startswith(P2PURL_SCHEME):
65             tdef = TorrentDef.load_from_url(torrent)
66         else: 
67             tdef = TorrentDef.load(torrent)
68         if tdef.get_live():
69             raise ValueError("CIS does not support live torrents")
70         
71         new_download = True
72         try:
73             d = self.session.start_download(tdef, dscfg)
74         except DuplicateDownloadException:
75             new_download = False
76         #d.set_state_callback(state_callback, getpeerlist=False)
77         
78         if new_download:
79             logger.log_msg('download of torrent "%s" started' % torrent)
80         #else:
81             #logger.log_msg('download of torrent "%s" already started' \
82                     #% torrent, logger.LOG_LEVEL_DEBUG)