예제 #1
0
def result():
    print(request.values['type']) # should display 'bar'   
    if(request.values['type']=="music"):
        print("ok")
        #videoFile = "c:/Users/龔鈺翔/Documents/BT stream/tmp/a"
        #workingPath = "c:/Users/龔鈺翔/Documents/BT stream/tmp"
        #mainPath = "c:/Users/龔鈺翔/Documents/BT stream/tmp"

        fs = lt.file_storage()
        lt.add_files(fs, videoFile)
        t = lt.create_torrent(fs)
        t.add_tracker("udp://tracker.publicbt.com:80")
        t.add_tracker("udp://open.stealth.si:80")
        t.add_tracker("udp://tracker.opentrackr.org:1337")
        t.add_tracker("udp://tracker.leechers-paradise.org:6969")
        t.add_tracker("udp://tracker.coppersurfer.tk:6969")
        t.add_tracker("udp://140.115.152.14:2255")
        t.add_tracker("http://54.39.98.124:80/announce")
        t.add_tracker("udp://p4p.arenabg.com:1337/announce")

        t.set_creator("My Torrent")
        t.set_comment("Test")
        lt.set_piece_hashes(t, workingPath)
        torrent = t.generate()

        f = open(workingPath+"/"+"mytorrent.torrent", "wb")
        f.write(lt.bencode(torrent))
        f.close()

#ps = lt.proxy_settings()
#ps.type = lt.proxy_type.http
#ps.hostname = "hostname.de"
#ps.port = 1003

        ses = lt.session()
        ses.listen_on(6881, 6891)
#ses.set_proxy(ps)
#ses.set_web_seed_proxy(ps)

        handle = ses.add_torrent({'ti': lt.torrent_info(torrent), 'save_path': workingPath,})
#handle.is_seed(1)
#h=lt.add_magnet_uri(ses,lt.make_magnet_uri(lt.torrent_info(torrent)),{'save_path':workingPath,'seed_mode':True})
        print(lt.make_magnet_uri(lt.torrent_info(torrent)))
    #z=input('press anything to go')
        
        print(handle.is_seed()) 
        thread1=threading.Thread(target=server)
        thread1.setDaemon(True)
        thread1.start()
        return lt.make_magnet_uri(lt.torrent_info(torrent))

        
    else:
        print("request.values['type']")
        return"error"
예제 #2
0
파일: torrent.py 프로젝트: cvieri/solar
 def _create_torrent(self, resource, fs, root='.', use_sudo=False):
     t = lt.create_torrent(fs)
     transports = resource.transports()
     torrent_transport = next(
         (x for x in transports if x['name'] == 'torrent'))
     trackers = torrent_transport['trackers']
     for tracker in trackers:
         t.add_tracker(tracker)
     lt.set_piece_hashes(t, os.path.join(root, '..'))
     torrent = t.generate()
     torrent['priv'] = True  # private torrent, no DHT, only trackers
     name = self._create_torrent_name()
     try:
         # not checking for path existence
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     except IOError as e:
         if e.errno != errno.ENOENT:
             raise
         os.makedirs(self._torrent_path)
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     log.debug("Created torrent file %s", name)
     magnet_uri = lt.make_magnet_uri(lt.torrent_info(name))
     # self._torrents[root] = (name, magnet_uri)
     if not use_sudo:
         self._torrents.append((name, magnet_uri, root))
     else:
         self._sudo_torrents.append((name, magnet_uri, root))
     return name
예제 #3
0
파일: torrent.py 프로젝트: Mirantis/solar
 def _create_torrent(self, resource, fs, root='.', use_sudo=False):
     t = lt.create_torrent(fs)
     transports = resource.transports()
     torrent_transport = next(
         (x for x in transports if x['name'] == 'torrent'))
     trackers = torrent_transport['trackers']
     for tracker in trackers:
         t.add_tracker(tracker)
     lt.set_piece_hashes(t, os.path.join(root, '..'))
     torrent = t.generate()
     torrent['priv'] = True  # private torrent, no DHT, only trackers
     name = self._create_torrent_name()
     try:
         # not checking for path existence
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     except IOError as e:
         if e.errno != errno.ENOENT:
             raise
         os.makedirs(self._torrent_path)
         with open(name, 'wb') as f:
             f.write(lt.bencode(torrent))
     log.debug("Created torrent file %s", name)
     magnet_uri = lt.make_magnet_uri(lt.torrent_info(name))
     # self._torrents[root] = (name, magnet_uri)
     if not use_sudo:
         self._torrents.append((name, magnet_uri, root))
     else:
         self._sudo_torrents.append((name, magnet_uri, root))
     return name
예제 #4
0
    def convert_torrent_info(torrent_info):
        """from libtorrent torrent_info to python dictionary object"""
        try:
            import libtorrent as lt
        except ImportError:
            raise ImportError('libtorrent package required')

        return {
            'name':
            torrent_info.name(),
            'num_files':
            torrent_info.num_files(),
            'total_size':
            torrent_info.total_size(),  # in byte
            'total_size_fmt':
            Logic.size_fmt(torrent_info.total_size()),  # in byte
            'info_hash':
            str(torrent_info.info_hash()
                ),  # original type: libtorrent.sha1_hash
            'num_pieces':
            torrent_info.num_pieces(),
            'creator':
            torrent_info.creator()
            if torrent_info.creator() else 'libtorrent v{}'.format(lt.version),
            'comment':
            torrent_info.comment(),
            'files': [{
                'path': file.path,
                'size': file.size,
                'size_fmt': Logic.size_fmt(file.size)
            } for file in torrent_info.files()],
            'magnet_uri':
            lt.make_magnet_uri(torrent_info),
        }
예제 #5
0
def atp(proto: conftest.Proto, magnet: bool,
        mkatp: conftest.MkAtp) -> lt.add_torrent_params:
    atp = mkatp(proto=proto)
    assert atp.ti is not None
    if magnet:
        atp = lt.parse_magnet_uri(lt.make_magnet_uri(atp.ti))
    return atp
예제 #6
0
def addTorrent(filepath, torrentpath, osfilename, filename):
    global torrentName, ses, torrentList  #, torrentHandleList
    fileStorage = lt.file_storage()
    lt.add_files(fileStorage, os.path.normpath(filepath + osfilename))
    lTorrent = lt.create_torrent(fileStorage)  #lTorrent = localTorrent
    torrentList.append(lTorrent)
    addTrackerList(lTorrent)

    lTorrent.set_creator('Hubzilla using Libtorrent %s' % lt.version)
    lTorrent.set_comment(
        "Filename:" +
        filename.encode('utf8', 'strict').decode('unicode_escape'))

    lt.set_piece_hashes(lTorrent, os.path.normpath(filepath))
    gTorrent = lTorrent.generate()  #gTorrent = generated Torrent

    ##write Torrent file to filesystem
    tFile = open(os.path.normpath(torrentpath + filename + ".torrent"), "wb")
    tFile.write(lt.bencode(gTorrent))
    tFile.close()

    handle = ses.add_torrent({
        'ti':
        lt.torrent_info(os.path.normpath(torrentpath + filename + ".torrent")),
        'save_path':
        os.path.normpath(filepath),
        'seed_mode':
        True
    })
    #torrentHandleList.append(handle)
    torrentName[str(handle.get_torrent_info().info_hash())] = filename

    mLink = lt.make_magnet_uri(lt.torrent_info(gTorrent))
    magnetLinks[str(handle.get_torrent_info().info_hash())] = mLink
    return mLink
예제 #7
0
 def test_torrent_handle(self) -> None:
     atp = lt.add_torrent_params()
     atp.info_hashes = lt.info_hash_t(
         lt.sha1_hash(bytes.fromhex(self.info_hash_sha1)))
     session = lt.session(lib.get_isolated_settings())
     with tempfile.TemporaryDirectory() as path:
         atp.save_path = path
         handle = session.add_torrent(atp)
         uri = lt.make_magnet_uri(handle)
     self.assertEqual(uri, f"magnet:?xt=urn:btih:{self.info_hash_sha1}")
def magnet_atp(protos: tuple[conftest.Proto, conftest.Proto],
               atp: lt.add_torrent_params) -> lt.add_torrent_params:
    magnet_proto, _ = protos
    assert atp.ti is not None
    magnet = lt.parse_magnet_uri(lt.make_magnet_uri(atp.ti))
    if not (magnet_proto & conftest.V1):
        magnet.info_hashes = lt.info_hash_t(magnet.info_hashes.v2)
    elif not (magnet_proto & conftest.V2):
        magnet.info_hashes = lt.info_hash_t(magnet.info_hashes.v1)
    return magnet
예제 #9
0
def mkmagnet(t):
    """get magnet from t (t is a torrent file) """
    info = lt.torrent_info(t)
    b32m = (lt.make_magnet_uri(info))
    mhash, dn = b32m.split('btih:')[1].split('&')
    mhex = binascii.hexlify(base64.b32decode(mhash)).decode('ascii')
    mgt = "magnet:?xt=urn:btih:{0}&{1}".format(mhex,dn)

    # I don't like this way, but the other give a wrong magnet link
    #mgt = os.popen("transmission-show -m {0}".format(t)).read()
    return(mgt)
예제 #10
0
def buildFromFile(ressource, tmpFile):
    """
		@brief Mainly use for .torrent
	"""

    if ressource.metadata.contentType == "application/x-bittorrent":
        tmpFile.rollover()
        task = Task(lt.make_magnet_uri(lt.torrent_info(tmpFile.name)),
                    nature=TaskNature.web_static_torrent,
                    is_dir=True)
        return task

    return None
예제 #11
0
    def convert_torrent_info(self, torrent_info):
        """from libtorrent torrent_info to python dictionary object"""
        import libtorrent as lt

        return {
            'name': torrent_info.name(),
            'num_files': torrent_info.num_files(),
            'total_size': torrent_info.total_size(),  # in byte
            'info_hash': str(torrent_info.info_hash()),  # original type: libtorrent.sha1_hash
            'num_pieces': torrent_info.num_pieces(),
            'creator': torrent_info.creator() if torrent_info.creator() else 'libtorrent v{}'.format(lt.version),
            'comment': torrent_info.comment(),
            'files': [{'path': file.path, 'size': file.size} for file in torrent_info.files()],
            'magnet_uri': lt.make_magnet_uri(torrent_info),
        }
예제 #12
0
	def dumpTorrent(self, torrent_file):
		size = os.path.getsize(torrent_file)
		if size < 0 or size > (40 * 1000000):
			return 'error'

		t = libtorrent.torrent_info(torrent_file)

		site = []
		site.append('File: {}'.format(torrent_file))

		nodes = t.nodes()
		if nodes:
			site.append('Nodes:')
			for node in nodes:
				site.append(" - "+formatText(node))

		trackers = t.trackers()
		if trackers:
			site.append('Trackers:')
			for tracker in trackers:
				site.append(" - "+formatText(tracker))

		magnet_uri = libtorrent.make_magnet_uri(t)

		site.append('name: {}'.format(formatText(t.name())))
		site.append('num_files: {}'.format(t.num_files()))
		site.append('info_hash: {}'.format(t.info_hash()))
		site.append('num_pieces: {}'.format(t.num_pieces()))
		site.append('piece_length: {}'.format(t.piece_length()))
		site.append('magnet_uri: {}'.format(magnet_uri))

		comment = t.comment()
		if comment:
			site.append('comment: {}'.format(formatText(comment)))

		creator = t.creator()
		if creator:
			site.append('creator: {}'.format(formatText(creator)))

		fs = t.files()

		site.append('Files:')
		for f in fs:
			site.append(' - {} ({})</li>'.format(path, formatSize(f.size)))

		return '\n'.join(site)
예제 #13
0
    def dumpTorrent(self, torrent_file):
        size = os.path.getsize(torrent_file)
        if size < 0 or size > (40 * 1000000):
            return 'error'

        t = libtorrent.torrent_info(torrent_file)

        site = []
        site.append('File: {}'.format(torrent_file))

        nodes = t.nodes()
        if nodes:
            site.append('Nodes:')
            for node in nodes:
                site.append(" - " + formatText(node))

        trackers = t.trackers()
        if trackers:
            site.append('Trackers:')
            for tracker in trackers:
                site.append(" - " + formatText(tracker))

        magnet_uri = libtorrent.make_magnet_uri(t)

        site.append('name: {}'.format(formatText(t.name())))
        site.append('num_files: {}'.format(t.num_files()))
        site.append('info_hash: {}'.format(t.info_hash()))
        site.append('num_pieces: {}'.format(t.num_pieces()))
        site.append('piece_length: {}'.format(t.piece_length()))
        site.append('magnet_uri: {}'.format(magnet_uri))

        comment = t.comment()
        if comment:
            site.append('comment: {}'.format(formatText(comment)))

        creator = t.creator()
        if creator:
            site.append('creator: {}'.format(formatText(creator)))

        fs = t.files()

        site.append('Files:')
        for f in fs:
            site.append(' - {} ({})</li>'.format(path, formatSize(f.size)))

        return '\n'.join(site)
예제 #14
0
    def properties(self):
        prop = [
            (_("link"), lt.make_magnet_uri(self.data)),
            (_("hash"), str(self.data.info_hash()).upper()),
            (_("location"), self.download_dir),
            (_("pieces"), self._status.pieces if self._status else []),
            (_("availability"), self.availability),
            (_("state"), self.state),
            ]
        if not self._info is None:
            comment =  self._info.comment()
            if comment:
                prop.append((_("comments"), comment))
            trackers = frozenset(self._info.trackers())
            if trackers:
                prop.append((_("trackers"), "\n".join(i.url for i in trackers).decode("utf8")))
            prop.append((_("files"), "\n".join(sorted(i.path for i in self._info.files())).decode("utf8")))

        return prop
예제 #15
0
    def convert_torrent_info(self, torrent_info):
        """from libtorrent torrent_info to python dictionary object"""
        try:
            import libtorrent as lt
        except ImportError as _e:
            raise ImportError("libtorrent package required") from _e

        return {
            "name": torrent_info.name(),
            "num_files": torrent_info.num_files(),
            "total_size": torrent_info.total_size(),  # in byte
            "total_size_fmt": size_fmt(torrent_info.total_size()),  # in byte
            "info_hash": str(torrent_info.info_hash()),  # original type: libtorrent.sha1_hash
            "num_pieces": torrent_info.num_pieces(),
            "creator": torrent_info.creator() if torrent_info.creator() else f"libtorrent v{lt.version}",
            "comment": torrent_info.comment(),
            "files": [
                {"path": file.path, "size": file.size, "size_fmt": size_fmt(file.size)} for file in torrent_info.files()
            ],
            "magnet_uri": lt.make_magnet_uri(torrent_info),
        }
예제 #16
0
    def properties(self):
        prop = [
            (_("link"), lt.make_magnet_uri(self.data)),
            (_("hash"), str(self.data.info_hash()).upper()),
            (_("location"), self.download_dir),
            (_("pieces"), self._status.pieces if self._status else []),
            (_("availability"), self.availability),
            (_("state"), self.state),
        ]
        if not self._info is None:
            comment = self._info.comment()
            if comment:
                prop.append((_("comments"), comment))
            trackers = frozenset(self._info.trackers())
            if trackers:
                prop.append(
                    (_("trackers"),
                     "\n".join(i.url for i in trackers).decode("utf8")))
            prop.append((_("files"), "\n".join(
                sorted(i.path for i in self._info.files())).decode("utf8")))

        return prop
예제 #17
0
 def get_magnet_link(self):
     return lt.make_magnet_uri(self.handle)
 def get_magnet_link(self):
     return lt.make_magnet_uri(self.handle)
예제 #19
0
def inputController(ses, ):
    global run
    while run:
        logFile.write("Input Controller started...\n")
        logFile.flush()
        inputString = input()

        command = inputString[0:inputString.find("]") + 1]
        param = inputString[inputString.find("]") +
                            1:len(inputString)].split(",")

        logFile.write("IC: Input command recievded ...\n")
        logFile.flush()

        if command == "[ADD_TRACKER]":
            logFile.write("IC: Add Tracker ...\n")
            logFile.flush()

            appendTrackerList(param)  # torrent nicht bekannt
            sys.stdout.flush()
        elif command == "[ADD_FILE]":
            logFile.write("IC: Add File ...\n")
            logFile.flush()

            #read parameters
            filename = str(param[1])
            filepath = str(param[0])

            fileStorage = lt.file_storage()
            lt.add_files(fileStorage,
                         os.path.normpath(filepath + "/" + filename))
            lTorrent = lt.create_torrent(fileStorage)  #lTorrent = localTorrent
            torrentList.append(lTorrent)
            addTrackerList(lTorrent)

            lTorrent.set_creator('Hubzilla using Libtorrent %s' % lt.version)
            lTorrent.set_comment("Filename:" + filename)
            lt.set_piece_hashes(lTorrent, os.path.normpath(filepath))
            gTorrent = lTorrent.generate()  #gTorrent = generated Torrent

            ##write Torrent file to filesystem
            tFile = open(
                os.path.normpath(filepath + "/" + filename + ".torrent"), "wb")
            tFile.write(lt.bencode(gTorrent))
            tFile.close()

            handle = ses.add_torrent({
                'ti':
                lt.torrent_info(
                    os.path.normpath(filepath + "/" + filename + ".torrent")),
                'name':
                filename,
                'save_path':
                os.path.normpath(filepath),
                'seed_mode':
                True
            })
            #torrentHandleList.append(handle)

            mLink = lt.make_magnet_uri(lt.torrent_info(gTorrent))
            logFile.write("IC: magnet uri:" + mLink + "\n")
            logFile.flush()

            print(mLink)
            sys.stdout.flush()

        else:
            pass
        time.sleep(1)
    logFile.write("SIGTERM: inputController ended...\n")
    logFile.flush()
예제 #20
0
f.close()

#ps = lt.proxy_settings()
#ps.type = lt.proxy_type.http
#ps.hostname = "hostname.de"
#ps.port = 1003

ses = lt.session()
ses.listen_on(6881, 6891)
#ses.set_proxy(ps)
#ses.set_web_seed_proxy(ps)

handle = ses.add_torrent({'ti': lt.torrent_info(torrent), 'save_path': workingPath,})
#handle.is_seed(1)
#h=lt.add_magnet_uri(ses,lt.make_magnet_uri(lt.torrent_info(torrent)),{'save_path':workingPath,'seed_mode':True})
print(lt.make_magnet_uri(lt.torrent_info(torrent)))
z=input('press anything to go')

print(handle.is_seed())
while 1:
    #print('1')
    try:
        s = handle.status()
        state_str = ['queued', 'checking', 'downloading metadata', \
                'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume']

        print('\r%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % \
        (s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state]))
        sys.stdout.flush()

        time.sleep(1)
    def __init__(self, parent, h):
        if not h.is_valid():
            Information(parent.win, "Invalid torrent handle.")
            return

        if not h.has_metadata():
            Information(parent.win, "Torrent contains no metadata.")
            return

        i = h.get_torrent_info()

        InnerWindow.__init__(self, parent.win)

        box = Box(self)
        box.size_hint_align = -1.0, -1.0
        box.size_hint_weight = 1.0, 1.0

        tname = Label(self)
        tname.size_hint_align = -1.0, 0.5
        tname.line_wrap = ELM_WRAP_CHAR
        tname.ellipsis = True
        tname.text = "{}".format(cgi.escape(i.name()))
        tname.show()
        box.pack_end(tname)

        for func in i.comment, i.creation_date, i.creator:
            try:
                w = func()
            except Exception as e:
                log.debug(e)
            else:
                if w:
                    f = Frame(self)
                    f.size_hint_align = -1.0, 0.0
                    f.text = func.__name__.replace("_", " ").capitalize()
                    l = Label(self)
                    l.ellipsis = True
                    l.text = cgi.escape(str(w))
                    l.show()
                    f.content = l
                    f.show()
                    box.pack_end(f)

        tpriv = Check(self)
        tpriv.size_hint_align = 0.0, 0.0
        tpriv.text = "Private"
        tpriv.tooltip_text_set("Whether this torrent is private.<br> \
            i.e., it should not be distributed on the trackerless network<br> \
            (the kademlia DHT).")
        tpriv.disabled = True
        tpriv.state = i.priv()

        magnet_uri = lt.make_magnet_uri(h)

        f = Frame(self)
        f.size_hint_align = -1.0, 0.0
        f.text = "Magnet URI"
        me_box = Box(self)
        me_box.horizontal = True
        me = Entry(self)
        me.size_hint_align = -1.0, 0.0
        me.size_hint_weight = 1.0, 0.0
        #me.editable = False
        me.entry = magnet_uri
        me_box.pack_end(me)
        me.show()
        me_btn = Button(self)
        me_btn.text = "Copy"
        if hasattr(me, "cnp_selection_set"):
            me_btn.callback_clicked_add(
                lambda x: me.top_widget.cnp_selection_set(
                    ELM_SEL_TYPE_CLIPBOARD, ELM_SEL_FORMAT_TEXT, me.text))
        else:
            import pyperclip
            me_btn.callback_clicked_add(lambda x: pyperclip.copy(magnet_uri))
        me_btn.show()
        me_box.pack_end(me_btn)
        me_box.show()
        f.content = me_box
        f.show()
        box.pack_end(f)

        fl_btn = Button(self)
        fl_btn.text = "Files ->"
        fl_btn.callback_clicked_add(self.file_list_cb, h)

        xbtn = Button(self)
        xbtn.text_set("Close")
        xbtn.callback_clicked_add(lambda x: self.delete())

        for w in tpriv, fl_btn, xbtn:
            w.show()
            box.pack_end(w)

        box.show()

        nf = self.nf = Naviframe(self)
        nf.item_simple_push(box)

        self.content_set(nf)
        self.activate()
예제 #22
0
 def test_torrent_info(self) -> None:
     ti = lt.torrent_info(lt.sha1_hash(bytes.fromhex(self.info_hash_sha1)))
     uri = lt.make_magnet_uri(ti)
     self.assertEqual(uri, f"magnet:?xt=urn:btih:{self.info_hash_sha1}")