cis: bug fixes
[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
8 def create_torrent(source):
9     """
10     Creates a torrent file for the video source file.
11     """
12
13     if isinstance(source, unicode):
14         usource = source
15     else:
16         usource = source.decode(sys.getfilesystemencoding())
17
18     duration = config.AVINFO_CLASS.get_video_duration(source, True)
19
20     tdef = TorrentDef()
21     tdef.add_content(usource, playtime=duration)
22     tdef.set_tracker(config.BT_TRACKER)
23
24     tdef.set_piece_length(32768)
25
26     tdef.finalize()
27     tdef.save(source + '.tstream')
28
29
30 class BitTorrent:
31     """
32     Implementation of BitTorrent operations that uses Next-Share library.
33     """
34
35     def __init__(self):
36
37         port = random.randint(10000, 65535)
38         
39         # setup session
40         sscfg = SessionStartupConfig()
41         statedir = tempfile.mkdtemp()
42         sscfg.set_state_dir(statedir)
43         sscfg.set_listen_port(port)
44         sscfg.set_megacache(False)
45         sscfg.set_overlay(False)
46         sscfg.set_dialback(True)
47         sscfg.set_internal_tracker(False)
48         
49         self.session = Session(sscfg)
50
51     def start_download(self, torrent, output_dir='.'):
52         """
53         Download (leech or seed) a file via BitTorrent.
54         The code is adapted from Next-Share's 'BaseLib/Tools/cmdlinedl.py'.
55
56         @param torrent .torrent file or URL
57         """
58
59         # setup and start download
60         dscfg = DownloadStartupConfig()
61         dscfg.set_dest_dir(output_dir);
62
63         if torrent.startswith("http") or torrent.startswith(P2PURL_SCHEME):
64             tdef = TorrentDef.load_from_url(torrent)
65         else: 
66             tdef = TorrentDef.load(torrent)
67         if tdef.get_live():
68             raise ValueError("CIS does not support live torrents")
69             
70         d = self.session.start_download(tdef, dscfg)
71         #d.set_state_callback(state_callback, getpeerlist=False)