예제 #1
0
    def gotChannelCastMessage(self, recv_msg, sender_permid, selversion):
        """ Receive and handle a ChannelCast message """
        # ChannelCast feature starts from eleventh version; hence, do not receive from lower version peers
        if selversion < OLPROTO_VER_ELEVENTH:
            if DEBUG:
                print >> sys.stderr, time.asctime(),'-', "Do not receive from lower version peer:", selversion
            return
                
        if DEBUG:
            print >> sys.stderr,time.asctime(),'-', 'channelcast: Received a msg from ', permid_for_user(sender_permid)
            print >> sys.stderr,time.asctime(),'-', " my_permid=", permid_for_user(self.my_permid)

        if not sender_permid or sender_permid == self.my_permid:
            if DEBUG:
                print >> sys.stderr, time.asctime(),'-', "channelcast: warning - got channelcastMsg from a None/Self peer", \
                        permid_for_user(sender_permid), recv_msg
            return False

        #if len(recv_msg) > self.max_length:
        #    if DEBUG:
        #        print >> sys.stderr, time.asctime(),'-', "channelcast: warning - got large channelCastHaveMsg", len(recv_msg)
        #    return False

        channelcast_data = {}

        try:
            channelcast_data = bdecode(recv_msg)
        except:
            print >> sys.stderr, time.asctime(),'-', "channelcast: warning, invalid bencoded data"
            return False

        # check message-structure
        if not validChannelCastMsg(channelcast_data):
            print >> sys.stderr, time.asctime(),'-', "channelcast: invalid channelcast_message"
            return False
        
        self.handleChannelCastMsg(sender_permid, channelcast_data)
        
        #Log RECV_MSG of uncompressed message
        if self.log:
            dns = self.dnsindb(sender_permid)
            if dns:
                ip,port = dns
                MSG_ID = "CHANNELCAST"
                msg = repr(channelcast_data)
                self.overlay_log('RECV_MSG', ip, port, show_permid(sender_permid), selversion, MSG_ID, msg)
 
        return True       
예제 #2
0
파일: votecast.py 프로젝트: csko/Tribler
    def handleVoteCastMsg(self, sender_permid, data):
        """ Handles VoteCast message """
        if DEBUG:
            print >>sys.stderr, "votecast: Processing VOTECAST msg from: ", show_permid_short(
                sender_permid
            ), "; data: ", repr(data)

        mod_ids = Set()
        for key, value in data.items():
            vote = {}
            vote["mod_id"] = bin2str(key)
            vote["voter_id"] = permid_for_user(sender_permid)
            vote["vote"] = value["vote"]
            vote["time_stamp"] = value["time_stamp"]
            self.votecastdb.addVote(vote)

            mod_ids.add(vote["mod_id"])

        # Arno, 2010-02-24: Generate event
        for mod_id in mod_ids:
            try:
                self.notifier.notify(NTFY_VOTECAST, NTFY_UPDATE, mod_id)
            except:
                print_exc()

        if DEBUG:
            print >>sys.stderr, "votecast: Processing VOTECAST msg from: ", show_permid_short(
                sender_permid
            ), "DONE; data:"
예제 #3
0
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir",
                                   action="store",
                                   type="string",
                                   help="Use an alternate statedir")
    command_line_parser.add_option("--port",
                                   action="store",
                                   type="int",
                                   help="Listen at this port")
    command_line_parser.add_option("--nickname",
                                   action="store",
                                   type="string",
                                   help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    print "Press Ctrl-C to stop the metadata-injector"

    sscfg = SessionStartupConfig()
    if opt.statedir:
        sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port:
        sscfg.set_listen_port(opt.port)
    if opt.nickname:
        sscfg.set_nickname(opt.nickname)

    # set_moderationcast_promote_own() will ensure your moderations on
    # the RSS feed items are sent to any peer you connect to on the
    # overlay.

    sscfg.set_megacache(True)
    sscfg.set_overlay(True)
    # turn torrent collecting on. this will cause torrents to be distributed
    sscfg.set_torrent_collecting(True)
    sscfg.set_dialback(False)
    sscfg.set_internal_tracker(False)

    session = Session(sscfg)

    def on_incoming_torrent(subject, type_, infohash):
        print >> sys.stdout, "Incoming torrent:", infohash.encode("HEX")

    session.add_observer(on_incoming_torrent, NTFY_TORRENTS, [NTFY_INSERT])

    print >> sys.stderr, "permid: ", permid_for_user(session.get_permid())

    try:
        while True:
            x = sys.stdin.read()
    except:
        print_exc()

    session.shutdown()
    print "Shutting down..."
    time.sleep(5)
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir", action="store", type="string", help="Use an alternate statedir")
    command_line_parser.add_option("--port", action="store", type="int", help="Listen at this port")
    command_line_parser.add_option("--nickname", action="store", type="string", help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    print "Press Ctrl-C to stop the metadata-injector"

    sscfg = SessionStartupConfig()
    if opt.statedir: sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port: sscfg.set_listen_port(opt.port)
    if opt.nickname: sscfg.set_nickname(opt.nickname)
    
    # set_moderationcast_promote_own() will ensure your moderations on
    # the RSS feed items are sent to any peer you connect to on the
    # overlay.

    sscfg.set_megacache(True)
    sscfg.set_overlay(True)
    # turn torrent collecting on. this will cause torrents to be distributed
    sscfg.set_torrent_collecting(True)
    sscfg.set_dialback(False)
    sscfg.set_internal_tracker(False)

    session = Session(sscfg)

    def on_incoming_torrent(subject, type_, infohash):
        print >>sys.stdout, "Incoming torrent:", infohash.encode("HEX")
    session.add_observer(on_incoming_torrent, NTFY_TORRENTS, [NTFY_INSERT])

    print >>sys.stderr, "permid: ", permid_for_user(session.get_permid())    

    # 22/10/08. Boudewijn: connect to a specific peer
    # connect to a specific peer using the overlay
    # def after_connect(*args):
    #     print "CONNECTED", args
    # from Tribler.Core.Overlay.SecureOverlay import SecureOverlay
    # overlay = SecureOverlay.getInstance()
    # overlay.connect_dns(("130.161.158.24", 7762), after_connect)

    # condition variable would be prettier, but that don't listen to 
    # KeyboardInterrupt
    #time.sleep(sys.maxint/2048)
    try:
        while True:
            x = sys.stdin.read()
    except:
        print_exc()
    
    session.shutdown()
    print "Shutting down..."
    time.sleep(5)    
예제 #5
0
    def logMsg(self, msg_data, msg_permid, in_or_out, logfile):

        if in_or_out == 'in':
            permid_from = permid_for_user(msg_permid)

        elif in_or_out == 'out':
            permid_from = 'LOCAL'

        else:
            return

        timestamp = now()

        log = open(logfile, 'a')
        string = '%.1f %s %s' % (timestamp, in_or_out,
                                 permid_for_user(msg_permid))
        log.write(string + '\n')
        print >> sys.stderr, string

        data = msg_data.get('data', [])

        for permid in data:
            u = data[permid]['u']
            d = data[permid]['d']

            string = '%.1f %s %s %d %d' % (timestamp, permid_from,
                                           permid_for_user(permid), u, d)
            log.write(string + '\n')
            print >> sys.stderr, string

        totals = msg_data.get('totals', None)

        if totals != None:
            (u, d) = totals

            string = '%.1f TOT %s %d %d' % (timestamp, permid_from, u, d)
            log.write(string + '\n')
            print >> sys.stderr, string

        log.close()
예제 #6
0
    def logMsg(self, msg_data, msg_permid, in_or_out, logfile):
        
        if in_or_out == 'in':
            permid_from = permid_for_user(msg_permid) 
        
        elif in_or_out == 'out':
            permid_from = 'LOCAL'
            
        else:
            return
            
        timestamp = now()
            
        log = open(logfile, 'a')
        string = '%.1f %s %s' % (timestamp, in_or_out, permid_for_user(msg_permid))
        log.write(string + '\n')
        print >> sys.stderr, string
        
        data = msg_data.get('data', [])
        
        for permid in data:
            u = data[permid]['u']
            d = data[permid]['d']
            
            string = '%.1f %s %s %d %d' % (timestamp, permid_from, permid_for_user(permid), u, d)
            log.write(string + '\n')
            print >> sys.stderr, string
            
        totals = msg_data.get('totals', None)

        if totals != None:
            (u, d) = totals
            
            string = '%.1f TOT %s %d %d' % (timestamp, permid_from, u, d)
            log.write(string + '\n')
            print >> sys.stderr, string
            
            
        log.close()
예제 #7
0
 def handleVoteCastMsg(self, sender_permid, data):
     """ Handles VoteCast message """
     if DEBUG: 
         print >> sys.stderr, time.asctime(),'-', "Processing VOTECAST msg from: ", permid_for_user(sender_permid), "; data: ", repr(data)
 
     for value in data:
         vote = {}
         vote['mod_id'] = value[0]
         vote['voter_id'] = permid_for_user(sender_permid)
         vote['vote'] = value[1] 
         self.votecastdb.addVote(vote)
         
     if DEBUG:
         print >> sys.stderr,time.asctime(),'-', "Processing VOTECAST msg from: ", permid_for_user(sender_permid), "DONE; data:"
예제 #8
0
    def gotVoteCastMessage(self, recv_msg, sender_permid, selversion):
        """ Receives VoteCast message and handles it. """
        # VoteCast feature is renewed in eleventh version; hence, do not receive from lower version peers
        if selversion < OLPROTO_VER_ELEVENTH:
            if DEBUG:
                print >> sys.stderr, time.asctime(),'-', "Do not receive from lower version peer:", selversion
            return
                
        if DEBUG:
            print >> sys.stderr,time.asctime(),'-', 'votecast: Received a msg from ', permid_for_user(sender_permid)

        if not sender_permid or sender_permid == self.my_permid:
            if DEBUG:

                print >> sys.stderr, time.asctime(),'-', "votecast: error - got votecastMsg from a None peer", \
                        permid_for_user(sender_permid), recv_msg
            return False

        if self.max_length > 0 and len(recv_msg) > self.max_length:
            if DEBUG:
                print >> sys.stderr, time.asctime(),'-', "votecast: warning - got large voteCastHaveMsg; msg_size:", len(recv_msg)
            return False

        votecast_data = {}

        try:
            votecast_data = bdecode(recv_msg)
        except:
            print >> sys.stderr, time.asctime(),'-', "votecast: warning, invalid bencoded data"
            return False

        # check message-structure
        if not validVoteCastMsg(votecast_data):
            print >> sys.stderr, time.asctime(),'-', "votecast: warning, invalid votecast_message"
            return False
        
        self.handleVoteCastMsg(sender_permid, votecast_data)

        #Log RECV_MSG of uncompressed message
        if self.log:
            dns = self.dnsindb(sender_permid)
            if dns:
                ip,port = dns
                MSG_ID = "VOTECAST"
                msg = voteCastMsgToString(votecast_data)
                self.overlay_log('RECV_MSG', ip, port, show_permid(sender_permid), selversion, MSG_ID, msg)
 
        return True
예제 #9
0
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir", action="store", type="string", help="Use an alternate statedir")
    command_line_parser.add_option("--port", action="store", type="int", help="Listen at this port")
    command_line_parser.add_option("--nickname", action="store", type="string", help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    print "Press Ctrl-C to stop the metadata-injector"

    sscfg = SessionStartupConfig()
    if opt.statedir:
        sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port:
        sscfg.set_listen_port(opt.port)
    if opt.nickname:
        sscfg.set_nickname(opt.nickname)

    # set_moderationcast_promote_own() will ensure your moderations on
    # the RSS feed items are sent to any peer you connect to on the
    # overlay.

    sscfg.set_megacache(True)
    sscfg.set_overlay(True)
    # turn torrent collecting on. this will cause torrents to be distributed
    sscfg.set_torrent_collecting(True)
    sscfg.set_dialback(False)
    sscfg.set_internal_tracker(False)

    session = Session(sscfg)

    def on_incoming_torrent(subject, type_, infohash):
        print >> sys.stdout, "Incoming torrent:", infohash.encode("HEX")
    session.add_observer(on_incoming_torrent, NTFY_TORRENTS, [NTFY_INSERT])

    print >> sys.stderr, "permid: ", permid_for_user(session.get_permid())

    try:
        while True:
            x = sys.stdin.read()
    except:
        print_exc()

    session.shutdown()
    print "Shutting down..."
    time.sleep(5)
예제 #10
0
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir", action="store", type="string", help="Use an alternate statedir")
    command_line_parser.add_option("--port", action="store", type="int", help="Listen at this port")
    command_line_parser.add_option("--rss", action="store", type="string", help="Url where to fetch rss feed, or several seperated with ';'")
    command_line_parser.add_option("--nickname", action="store", type="string", help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    if not (opt.rss):
        print "Usage: python Tribler/Main/metadata-injector.py --help"
        print "Example: python Tribler/Main/metadata-injector.py --rss http://frayja.com/rss.php --nickname frayja"
        sys.exit()

    print "Press Ctrl-C to stop the metadata-injector"

    sscfg = SessionStartupConfig()
    if opt.statedir: sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port: sscfg.set_listen_port(opt.port)
    if opt.nickname: sscfg.set_nickname(opt.nickname)
    
    # Agressively promote own moderations:
    sscfg.set_moderationcast_promote_own(True)

    sscfg.set_megacache(True)
    sscfg.set_overlay(True)
    # turn torrent collecting on. this will cause torrents to be distributed
    sscfg.set_torrent_collecting(True)
    sscfg.set_dialback(False)
    sscfg.set_internal_tracker(False)

    session = Session(sscfg)
    
    print >>sys.stderr, time.asctime(),'-', "permid: ", permid_for_user(session.get_permid())    

    if opt.rss:
        
        moderation_cast_db = session.open_dbhandler(NTFY_MODERATIONCAST)
        torrent_feed_thread = TorrentFeedThread.getInstance()
        def on_torrent_callback(rss_url, infohash, torrent_data):
            """
            A torrent file is discovered through rss. Create a new
            moderation.
            """
            if "info" in torrent_data and "name" in torrent_data["info"]:
                print >>sys.stderr, time.asctime(),'-', "Creating moderation for %s" % torrent_data["info"]["name"]
            else:
                print >>sys.stderr, time.asctime(),'-', "Creating moderation"

            moderation = {}
            moderation['infohash'] = bin2str(infohash)
            torrenthash = sha.sha(bencode(data)).digest()
            moderation['torrenthash'] = bin2str(torrenthash)

            moderation_cast_db.addOwnModeration(moderation)

        torrent_feed_thread.register(session,120,1)
        for rss in opt.rss.split(";"):
            print >>sys.stderr, time.asctime(),'-', "Adding RSS: %s" % rss
            torrent_feed_thread.addURL(rss, on_torrent_callback=on_torrent_callback)


        # set_moderationcast_promote_own() will ensure your moderations on
        # the RSS feed items are sent to any peer you connect to on the
        # overlay.

        torrent_feed_thread.start()

    # 22/10/08. Boudewijn: connect to a specific peer
    # connect to a specific peer using the overlay
    # def after_connect(*args):
    #     print "CONNECTED", args
    # from Tribler.Core.Overlay.SecureOverlay import SecureOverlay
    # overlay = SecureOverlay.getInstance()
    # overlay.connect_dns(("130.161.158.24", 7762), after_connect)

    # condition variable would be prettier, but that don't listen to 
    # KeyboardInterrupt
    #time.sleep(sys.maxint/2048)
    try:
        while True:
            x = sys.stdin.read()
    except:
        print_exc()
    
    session.shutdown()
    print "Shutting down..."
    time.sleep(5)    
예제 #11
0
def dispersy_started(session, opt):
    myPermid = permid_for_user(session.get_permid())
    print >> sys.stderr, "permid: ", myPermid

    from Tribler.Main.vwxGUI.SearchGridManager import TorrentManager, LibraryManager, ChannelManager
    torrentManager = TorrentManager(None)
    libraryManager = LibraryManager(None)
    channelManager = ChannelManager()

    torrentManager.connect(session, libraryManager, channelManager)
    channelManager.connect(session, libraryManager, torrentManager)
    libraryManager.connect(session, torrentManager, channelManager)

    myChannelName = opt.channelname or opt.nickname or 'MetadataInjector-Channel'
    myChannelName = unicode(myChannelName)

    createdNewChannel = False
    myChannelId = channelManager.channelcast_db.getMyChannelId()
    if not myChannelId:
        print >> sys.stderr, "creating a new channel"
        channelManager.createChannel(myChannelName, u'')
        createdNewChannel = True

    else:
        print >> sys.stderr, "reusing previously created channel"
        myChannel = channelManager.getChannel(myChannelId)
        if myChannel.name != myChannelName:
            print >> sys.stderr, "renaming channel to", myChannelName
            channelManager.modifyChannel(myChannelId, {'name': myChannelName})

    # use dispersythread, this way we know our channel has been created
    @forceDispersyThread
    def createTorrentFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()

        torrentfeed = RssParser.getInstance()
        torrentfeed.register(session, myChannelId)
        torrentfeed.addCallback(myChannelId, channelManager.createTorrentFromDef)

        for rss in opt.rss.split(";"):
            torrentfeed.addURL(rss, myChannelId)

    if opt.rss:
        createTorrentFeed()

    # same here, using dispersythread to make sure channel has been created
    @forceDispersyThread
    def createDirFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()

        def on_torrent_callback(dirpath, infohash, torrent_data):
            torrentdef = TorrentDef.load_from_dict(torrent_data)
            channelsearch_manager.createTorrentFromDef(myChannelId, torrentdef)

            # save torrent to collectedtorrents
            filename = torrentManager.getCollectedFilenameFromDef(torrentdef)
            if not os.path.isfile(filename):
                torrentdef.save(filename)

        dirfeed = DirectoryFeedThread.getInstance()
        for dirpath in opt.dir.split(";"):
            dirfeed.addDir(dirpath, callback=on_torrent_callback)

    if opt.dir:
        createDirFeed()

    # same here, using dispersythread to make sure channel has been created
    @forceDispersyThread
    def createFileFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()
        community = channelManager._disp_get_community_from_channel_id(myChannelId)

        print >> sys.stderr, "Using community:", community._cid.encode('HEX')

        items = json.load(open(opt.file, 'rb'))
        for item in items:
            try:
                infohash = sha1(item['name']).digest()
            except:
                infohash = sha1(str(random.randint(0, 1000000))).digest()
            message = community._disp_create_torrent(infohash, long(time.time()), unicode(item['name']), ((u'fake.file', 10),), tuple(), update=False, forward=False)

            print >> sys.stderr, "Created a new torrent"

            latest_review = None
            for modification in item['modifications']:
                reviewmessage = community._disp_create_modification('description', unicode(modification['text']), long(time.time()), message, latest_review, update=False, forward=False)

                print >> sys.stderr, "Created a new modification"

                if modification['revert']:
                    community._disp_create_moderation('reverted', long(time.time()), 0, reviewmessage.packet_id, update=False, forward=False)

                    print >> sys.stderr, "Reverted the last modification"
                else:
                    latest_review = reviewmessage

    if opt.file and createdNewChannel:
        createFileFeed()
예제 #12
0
 def voteCastSendCallback(self, exc, target_permid, other=0):
     if DEBUG:
         if exc is None:
             print >> sys.stderr,time.asctime(),'-', "votecast: *** msg was sent successfully to peer", permid_for_user(target_permid)
         else:
             print >> sys.stderr, time.asctime(),'-', "votecast: *** warning - error in sending msg to", permid_for_user(target_permid), exc
def dispersy_started(session, opt):
    myPermid = permid_for_user(session.get_permid())
    print >> sys.stderr, "permid: ", myPermid

    from Tribler.Main.vwxGUI.SearchGridManager import TorrentManager, LibraryManager, ChannelManager
    torrentManager = TorrentManager(None)
    libraryManager = LibraryManager(None)
    channelManager = ChannelManager()

    torrentManager.connect(session, libraryManager, channelManager)
    channelManager.connect(session, libraryManager, torrentManager)
    libraryManager.connect(session, torrentManager, channelManager)

    myChannelName = opt.channelname or opt.nickname or 'MetadataInjector-Channel'
    myChannelName = unicode(myChannelName)

    createdNewChannel = False
    myChannelId = channelManager.channelcast_db.getMyChannelId()
    if not myChannelId:
        print >> sys.stderr, "creating a new channel"
        channelManager.createChannel(myChannelName, u'')
        createdNewChannel = True

    else:
        print >> sys.stderr, "reusing previously created channel"
        myChannel = channelManager.getChannel(myChannelId)
        if myChannel.name != myChannelName:
            print >> sys.stderr, "renaming channel to", myChannelName
            channelManager.modifyChannel(myChannelId, {'name': myChannelName})

    #use dispersythread, this way we know our channel has been created
    @forceDispersyThread
    def createTorrentFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()

        torrentfeed = RssParser.getInstance()
        torrentfeed.register(session, myChannelId)
        torrentfeed.addCallback(myChannelId,
                                channelManager.createTorrentFromDef)

        for rss in opt.rss.split(";"):
            torrentfeed.addURL(rss, myChannelId)

    if opt.rss:
        createTorrentFeed()

    #same here, using dispersythread to make sure channel has been created
    @forceDispersyThread
    def createDirFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()

        def on_torrent_callback(dirpath, infohash, torrent_data):
            torrentdef = TorrentDef.load_from_dict(torrent_data)
            channelsearch_manager.createTorrentFromDef(myChannelId, torrentdef)

            #save torrent to collectedtorrents
            filename = torrentManager.getCollectedFilenameFromDef(torrentdef)
            if not os.path.isfile(filename):
                torrentdef.save(filename)

        dirfeed = DirectoryFeedThread.getInstance()
        for dirpath in opt.dir.split(";"):
            dirfeed.addDir(dirpath, callback=on_torrent_callback)

    if opt.dir:
        createDirFeed()

    #same here, using dispersythread to make sure channel has been created
    @forceDispersyThread
    def createFileFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()
        community = channelManager._disp_get_community_from_channel_id(
            myChannelId)

        print >> sys.stderr, "Using community:", community._cid.encode('HEX')

        items = json.load(open(opt.file, 'rb'))
        for item in items:
            try:
                infohash = sha1(item['name']).digest()
            except:
                infohash = sha1(str(random.randint(0, 1000000))).digest()
            message = community._disp_create_torrent(infohash,
                                                     long(time.time()),
                                                     unicode(item['name']),
                                                     ((u'fake.file', 10), ),
                                                     tuple(),
                                                     update=False,
                                                     forward=False)

            print >> sys.stderr, "Created a new torrent"

            latest_review = None
            for modification in item['modifications']:
                reviewmessage = community._disp_create_modification(
                    'description',
                    unicode(modification['text']),
                    long(time.time()),
                    message,
                    latest_review,
                    update=False,
                    forward=False)

                print >> sys.stderr, "Created a new modification"

                if modification['revert']:
                    community._disp_create_moderation('reverted',
                                                      long(time.time()),
                                                      0,
                                                      reviewmessage.packet_id,
                                                      update=False,
                                                      forward=False)

                    print >> sys.stderr, "Reverted the last modification"
                else:
                    latest_review = reviewmessage

    if opt.file and createdNewChannel:
        createFileFeed()
예제 #14
0
def dispersy_started(session, opt):
    myPermid = permid_for_user(session.get_permid())
    print >>sys.stderr, "permid: ", myPermid
    
    from Tribler.Main.vwxGUI.SearchGridManager import TorrentManager, LibraryManager, ChannelManager
    torrentManager = TorrentManager(None)
    libraryManager = LibraryManager(None)
    channelManager = ChannelManager()
    
    torrentManager.connect(session, libraryManager, channelManager)
    channelManager.connect(session, torrentManager)
    libraryManager.connect(session, torrentManager)
    
    myChannelName = opt.channelname or opt.nickname or 'MetadataInjector-Channel'
    myChannelName = unicode(myChannelName)
    
    myChannelId = channelManager.channelcast_db.getMyChannelId()
    if not myChannelId:
        print >> sys.stderr, "creating a new channel"
        channelManager.createChannel(myChannelName, u'')
        
    else:
        print >> sys.stderr, "reusing previously created channel"
        
        myChannel = channelManager.getChannel(myChannelId)
        if myChannel.name != myChannelName:
            print >> sys.stderr, "renaming channel to",myChannelName
            channelManager.modifyChannel(myChannelId, {'name': myChannelName})

    #use dispersythread, this way we know our channel has been created
    @forceDispersyThread
    def createTorrentFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()

        torrentfeed = RssParser.getInstance()
        torrentfeed.register(session, myChannelId)
        torrentfeed.addCallback(myChannelId, channelManager.createTorrentFromDef)
        
        for rss in opt.rss.split(";"):
            torrentfeed.addURL(rss, myChannelId)
        
    if opt.rss:
        createTorrentFeed()
    
    #same here, using dispersythread to make sure channel has been created
    @forceDispersyThread
    def createDirFeed():
        myChannelId = channelManager.channelcast_db.getMyChannelId()
        
        def on_torrent_callback(dirpath, infohash, torrent_data):
            torrentdef = TorrentDef.load_from_dict(torrent_data)
            channelsearch_manager.createTorrentFromDef(myChannelId, torrentdef)
            
            #save torrent to collectedtorrents
            filename = torrentManager.getCollectedFilenameFromDef(torrentdef)
            if not os.path.isfile(filename): 
                torrentdef.save(filename)
        
        dirfeed = DirectoryFeedThread.getInstance()
        for dirpath in opt.dir.split(";"):
            dirfeed.addDir(dirpath, callback = on_torrent_callback)
            
    if opt.dir:
        createDirFeed()
예제 #15
0
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir", action="store", type="string", help="Use an alternate statedir")
    command_line_parser.add_option("--port", action="store", type="int", help="Listen at this port")
    command_line_parser.add_option("--rss", action="store", type="string", help="Url where to fetch rss feed, or several seperated with ';'")
    command_line_parser.add_option("--dir", action="store", type="string", help="Directory to watch for .torrent files, or several seperated with ';'")
    command_line_parser.add_option("--nickname", action="store", type="string", help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    if not (opt.rss or opt.dir):
        command_line_parser.print_help()
        print "\nExample: python Tribler/Main/metadata-injector.py --rss http://frayja.com/rss.php --nickname frayja"
        sys.exit()
    
    print "Press Ctrl-C to stop the metadata-injector"

    sscfg = SessionStartupConfig()
    if opt.statedir: sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port: sscfg.set_listen_port(opt.port)
    if opt.nickname: sscfg.set_nickname(opt.nickname)
    

    sscfg.set_megacache(True)
    sscfg.set_overlay(True)
    # turn torrent collecting on. this will cause torrents to be distributed
    sscfg.set_torrent_collecting(True)
    sscfg.set_dialback(False)
    sscfg.set_internal_tracker(False)

    session = Session(sscfg)
    
    print >>sys.stderr, "permid: ", permid_for_user(session.get_permid())    
    
    
    torrent_feed_thread = TorrentFeedThread.getInstance()
    torrent_feed_thread.register(session)
    dir_feed_thread = DirectoryFeedThread(torrent_feed_thread)
    
    if opt.rss:
        def on_torrent_callback(rss_url, infohash, torrent_data):
            """
            A torrent file is discovered through rss. Add it to our channel.
            """
            torrentdef = TorrentDef.load_from_dict(torrent_data)
            print >>sys.stderr,"*** Added a torrent to channel: %s" % torrentdef.get_name_as_unicode()
            
        for rss in opt.rss.split(";"):
            print >>sys.stderr, "Adding RSS: %s" % rss
            torrent_feed_thread.addURL(rss, callback=on_torrent_callback)
    
    if opt.dir:
        def on_torrent_callback(dirpath, infohash, torrent_data):
            torrentdef = TorrentDef.load_from_dict(torrent_data)
            print '*** Added a torrent to channel: %s' % torrentdef.get_name_as_unicode()
            
        for dirpath in opt.dir.split(";"):
            print >>sys.stderr, "Adding DIR: %s" % dirpath
            dir_feed_thread.addDir(dirpath, callback=on_torrent_callback)
    
    torrent_feed_thread.start()
    dir_feed_thread.start()

    # 22/10/08. Boudewijn: connect to a specific peer
    # connect to a specific peer using the overlay
    # def after_connect(*args):
    #     print "CONNECTED", args
    # from Tribler.Core.Overlay.SecureOverlay import SecureOverlay
    # overlay = SecureOverlay.getInstance()
    # overlay.connect_dns(("130.161.158.24", 7762), after_connect)

    # condition variable would be prettier, but that don't listen to 
    # KeyboardInterrupt
    #time.sleep(sys.maxint/2048)
    try:
        while True:
            x = sys.stdin.read()
    except:
        print_exc()
    
    torrent_feed_thread.shutdown()
    dir_feed_thread.shutdown()
    session.shutdown()
    print "Shutting down..."
    time.sleep(5)    
예제 #16
0
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir",
                                   action="store",
                                   type="string",
                                   help="Use an alternate statedir")
    command_line_parser.add_option("--port",
                                   action="store",
                                   type="int",
                                   help="Listen at this port")
    command_line_parser.add_option("--nickname",
                                   action="store",
                                   type="string",
                                   help="The moderator name")

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()

    print "Press Ctrl-C to stop the metadata-injector"

    sscfg = SessionStartupConfig()
    if opt.statedir: sscfg.set_state_dir(os.path.realpath(opt.statedir))
    if opt.port: sscfg.set_listen_port(opt.port)
    if opt.nickname: sscfg.set_nickname(opt.nickname)

    # set_moderationcast_promote_own() will ensure your moderations on
    # the RSS feed items are sent to any peer you connect to on the
    # overlay.

    sscfg.set_megacache(True)
    sscfg.set_overlay(True)
    # turn torrent collecting on. this will cause torrents to be distributed
    sscfg.set_torrent_collecting(True)
    sscfg.set_dialback(False)
    sscfg.set_internal_tracker(False)

    session = Session(sscfg)

    def on_incoming_torrent(subject, type_, infohash):
        print >> sys.stdout, "Incoming torrent:", infohash.encode("HEX")

    session.add_observer(on_incoming_torrent, NTFY_TORRENTS, [NTFY_INSERT])

    print >> sys.stderr, "permid: ", permid_for_user(session.get_permid())

    # 22/10/08. Boudewijn: connect to a specific peer
    # connect to a specific peer using the overlay
    # def after_connect(*args):
    #     print "CONNECTED", args
    # from Tribler.Core.Overlay.SecureOverlay import SecureOverlay
    # overlay = SecureOverlay.getInstance()
    # overlay.connect_dns(("130.161.158.24", 7762), after_connect)

    # condition variable would be prettier, but that don't listen to
    # KeyboardInterrupt
    #time.sleep(sys.maxint/2048)
    try:
        while True:
            x = sys.stdin.read()
    except:
        print_exc()

    session.shutdown()
    print "Shutting down..."
    time.sleep(5)