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