def subtest_good_friendship_stats(self):
        """
        Send a valid message-id from a registered crawler peer
        """
        print >>sys.stderr, time.asctime(),'-', "-"*80, "\ntest: good friendship stats"

        s = OLConnection(self.my_keypair, "localhost", self.hisport)

        t = time.time() - 100.0
        msg_dict = {'current time':int(t)}
        payload = bencode(msg_dict)
        self.send_crawler_request(s, CRAWLER_FRIENDSHIP_STATS, 0, 0, payload)

        error, payload = self.receive_crawler_reply(s, CRAWLER_FRIENDSHIP_STATS, 0)
        assert error == 0
        
        d = bdecode(payload)
        if DEBUG:
            print >>sys.stderr, time.asctime(),'-', "test: Got FRIENDSHIPSTATISTICS",`d`
        stats = d['stats']
        self.assert_(len(stats) == 1)
        record = d['stats'][0]
        self.assert_(record[0] == bin2str(self.his_permid))  # source_permid
        self.assert_(record[1] == bin2str(self.some_permid)) # target_permid
        self.assert_(record[2] == 0) # isForwarder

        time.sleep(1)
        s.close()
    def setUpPostSession(self):
        """ override TestAsServer """
        TestCrawler.setUpPostSession(self)

        self.some_keypair = EC.gen_params(EC.NID_sect233k1)
        self.some_keypair.gen_key()
        self.some_permid = str(self.some_keypair.pub().get_der())

        self.friendshipStatistics_db = FriendshipStatisticsDBHandler.getInstance(
        )
        self.friendshipStatistics_db.insertFriendshipStatistics(
            bin2str(self.his_permid),
            bin2str(self.some_permid),
            int(time.time()),
            0,
            commit=True)
        self.friendshipStatistics_db.insertFriendshipStatistics(
            bin2str(self.my_permid),
            bin2str(self.some_permid),
            int(time.time()),
            0,
            commit=True)

        # make sure that the OLConnection IS in the crawler_db
        crawler_db = CrawlerDBHandler.getInstance()
        crawler_db.temporarilyAddCrawler(self.my_permid)
Exemplo n.º 3
0
 def testInsertNewMetadataNoSubs(self):
     metadataDTO = MockMetadataDTO([])
     metadataDTO.sign(metadataDTO._keypair)
     self.underTest.insertMetadata(metadataDTO)
     
     testquery = "SELECT * FROM Metadata WHERE publisher_id=?" \
         + " AND infohash=?;" 
         
     channel = bin2str(metadataDTO.channel)
     infohash = bin2str(metadataDTO.infohash)
     results = self.db.fetchall(testquery, (channel,infohash))
     
     self.assertTrue(len(results) == 1)
     tupl = results[0] 
     self.assertTrue(tupl[0] is not None and isinstance(tupl[0], int))
     self.assertEquals(channel,tupl[1])
     self.assertEquals(infohash,tupl[2])
     self.assertEquals(metadataDTO.description, tupl[3])
     self.assertEquals(metadataDTO.timestamp, tupl[4])
     self.assertEquals(bin2str(metadataDTO.signature), tupl[5])
     
     subtitlesQuery = "SELECT * FROM Subtitles WHERE metadata_id_fk=?;"
     
     subtitles = self.db.fetchall(subtitlesQuery, (tupl[0],))
     self.assertEquals(0,len(subtitles))
Exemplo n.º 4
0
    def process_response(self, permid, d):

        mypermid = self.session.get_permid()

        self.friendshipStatistics_db.updateFriendshipResponseTime(
            bin2str(mypermid), bin2str(permid), int(time()))

        fs = self.frienddb.getFriendState(permid)

        # If the request to add has been approved
        if d['response'] == 1:
            if fs == FS_I_INVITED:
                self.frienddb.setFriendState(permid,
                                             commit=True,
                                             state=FS_MUTUAL)
            elif fs != FS_MUTUAL:
                # Unsollicited response, consider this an invite, if not already friend
                self.frienddb.setFriendState(permid,
                                             commit=True,
                                             state=FS_HE_INVITED)
        else:
            # He denied our friendship
            self.frienddb.setFriendState(permid,
                                         commit=True,
                                         state=FS_HE_DENIED)
Exemplo n.º 5
0
    def fmsg_send_callback(self, exc, permid, msgid):

        # If an exception arises
        if exc is None:
            self.delete_msg(permid, msgid)
        else:
            if DEBUG:
                print >> sys.stderr, 'friendship: Could not send to ', show_permid_short(
                    permid)
                print_exc()

        mypermid = self.session.get_permid()

        no_of_attempts = 0
        no_of_helpers = 10
        isForwarder = False
        if permid in self.currmsgs:
            msgid2rec = self.currmsgs[permid]
            for msgid in msgid2rec:
                msgrec = msgid2rec[msgid]
                no_of_attempts = msgrec['attempt']
                if msgrec['forwarded'] == True:
                    isForwarder = 1

        self.friendshipStatistics_db.insertOrUpdateFriendshipStatistics(
            bin2str(mypermid), bin2str(permid), int(time()), isForwarder,
            no_of_attempts, no_of_helpers)
 def fmsg_send_callback(self,exc,permid,msgid):
     
     # If an exception arises
     if exc is None:
         self.delete_msg(permid,msgid)
     else:
         if DEBUG:
             print >> sys.stderr, 'friendship: Could not send to ',show_permid_short(permid)  
             print_exc()
         
     mypermid = self.session.get_permid()
     
     no_of_attempts = 0
     no_of_helpers = 10
     isForwarder = False
     if permid in self.currmsgs:
         msgid2rec = self.currmsgs[permid]
         for msgid in msgid2rec:
             msgrec = msgid2rec[msgid]
             no_of_attempts = msgrec['attempt']
             if msgrec['forwarded'] == True:
                 isForwarder = 1
         
         
     self.friendshipStatistics_db.insertOrUpdateFriendshipStatistics( bin2str(mypermid), 
                                                                      bin2str(permid), 
                                                                      int(time()),
                                                                      isForwarder, 
                                                                      no_of_attempts ,
                                                                      no_of_helpers)
    def subtest_good_friendship_stats(self):
        """
        Send a valid message-id from a registered crawler peer
        """
        print >> sys.stderr, "-" * 80, "\ntest: good friendship stats"

        s = OLConnection(self.my_keypair, "localhost", self.hisport)

        t = time.time() - 100.0
        msg_dict = {'current time': int(t)}
        payload = bencode(msg_dict)
        self.send_crawler_request(s, CRAWLER_FRIENDSHIP_STATS, 0, 0, payload)

        error, payload = self.receive_crawler_reply(s,
                                                    CRAWLER_FRIENDSHIP_STATS,
                                                    0)
        assert error == 0

        d = bdecode(payload)
        if DEBUG:
            print >> sys.stderr, "test: Got FRIENDSHIPSTATISTICS", ` d `
        stats = d['stats']
        self.assert_(len(stats) == 1)
        record = d['stats'][0]
        self.assert_(record[0] == bin2str(self.his_permid))  # source_permid
        self.assert_(record[1] == bin2str(self.some_permid))  # target_permid
        self.assert_(record[2] == 0)  # isForwarder

        time.sleep(1)
        s.close()
    def setUpPostSession(self):
        """ override TestAsServer """
        TestCrawler.setUpPostSession(self)

        self.some_keypair = EC.gen_params(EC.NID_sect233k1)
        self.some_keypair.gen_key()
        self.some_permid = str(self.some_keypair.pub().get_der())

        self.friendshipStatistics_db = FriendshipStatisticsDBHandler.getInstance()
        self.friendshipStatistics_db.insertFriendshipStatistics( bin2str(self.his_permid), bin2str(self.some_permid), int(time.time()), 0, commit=True)        
        self.friendshipStatistics_db.insertFriendshipStatistics( bin2str(self.my_permid), bin2str(self.some_permid), int(time.time()), 0, commit=True)

        # make sure that the OLConnection IS in the crawler_db
        crawler_db = CrawlerDBHandler.getInstance()
        crawler_db.temporarilyAddCrawler(self.my_permid)
Exemplo n.º 9
0
 def testUpdateExistingWithNewerNewSubs(self):
     metadataDTO = MockMetadataDTO(["nld", "ita"])
     metadataDTO.sign(metadataDTO._keypair)
     self.underTest.insertMetadata(metadataDTO)
     
     newerMetadataDTO = MockMetadataDTO(["nld","ita","eng"])
     newerMetadataDTO.channel = metadataDTO.channel
     newerMetadataDTO.infohash = metadataDTO.infohash
     newerMetadataDTO._keypair = metadataDTO._keypair
     newerMetadataDTO.timestamp = metadataDTO.timestamp +1 #newer 
     newerMetadataDTO.sign(newerMetadataDTO._keypair)
     
     
     self.underTest.insertMetadata(newerMetadataDTO)
     
     #assert the the older has been replaced
     testquery = "SELECT * FROM Metadata WHERE publisher_id=?" \
         + " AND infohash=?;" 
         
     channel = bin2str(metadataDTO.channel)
     infohash = bin2str(metadataDTO.infohash)
     results = self.db.fetchall(testquery, (channel,infohash))
     
     self.assertTrue(len(results) == 1)
     tupl = results[0] 
     self.assertTrue(tupl[0] is not None and isinstance(tupl[0], int))
     self.assertEquals(channel,tupl[1])
     self.assertEquals(infohash,tupl[2])
     self.assertEquals(newerMetadataDTO.description, tupl[3])
     self.assertEquals(newerMetadataDTO.timestamp, tupl[4])
     self.assertEquals(bin2str(newerMetadataDTO.signature), tupl[5])
     
     subtitlesQuery = "SELECT * FROM Subtitles WHERE metadata_id_fk=?;"
     
     subtitles = self.db.fetchall(subtitlesQuery, (tupl[0],))
     self.assertEquals(3,len(subtitles))
     
     for lang in ("ita", "nld","eng"):
         found = False
         foundSub = None
         for subtuple in subtitles:
             if subtuple[1] == lang:
                 found = True
                 foundSub = subtuple
                 break
             
         self.assertTrue(found)
         self.assertEquals(bin2str(newerMetadataDTO.getSubtitle(lang).checksum), foundSub[3])
Exemplo n.º 10
0
    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:"
 def test_channelcast(self):
     torrent_data = {'announce':"http://localhost", 'info':{'name':'Hello 123', 'files':[{'length':100, 'path':['license.txt']}]}}
     infohash = bin2str(sha(bencode(torrent_data['info'])).digest())
     self.channelcastdb.addOwnTorrent(infohash,torrent_data)
     
     s = OLConnection(self.my_keypair,'localhost',self.hisport)
     chcast = ChannelCastCore(None, s, self.session, None, log = '', dnsindb = None)
     
     # Good message
     chdata =  chcast.createChannelCastMessage()
     if chdata is None or len(chdata) ==0:
         print "test: no subscriptions for us.. hence do not send"       
     else:
         msg = CHANNELCAST + bencode(chdata)        
         print "test: channelcast msg created", repr(chdata)        
         s.send(msg)
     
     time.sleep(3)
     
     # Bad message
     if chdata is None or len(chdata)==0:
         pass
     else:
         pub_id, pub_name, infohash, torrenthash, name, timestamp, signature = chdata[0]
         chdata = [(pub_id, pub_name, infohash, torrenthash, name, 12343, signature)]
         msg = CHANNELCAST + bencode(chdata)        
         print "test: channelcast msg created", repr(chdata)        
         s.send(msg)
         time.sleep(20)
         # the other side should have closed the connection, as it is invalid message
     
         
     s.close()        
Exemplo n.º 12
0
    def _updateChannelInternal(self, query_permid, query, hits):
        listOfAdditions = list()
        
        # a single read from the db is more efficient
        all_spam_channels = self.votecastdb.getPublishersWithNegVote(bin2str(self.session.get_permid()))
        for k,v in hits.items():
            #check if the record belongs to a channel who we have "reported spam" (negative vote)
            if bin2str(v['publisher_id']) in all_spam_channels:
                # if so, ignore the incoming record
                continue
            
            # make everything into "string" format, if "binary"
            hit = (bin2str(v['publisher_id']),v['publisher_name'],bin2str(v['infohash']),bin2str(v['torrenthash']),v['torrentname'],v['time_stamp'],bin2str(k))

            listOfAdditions.append(hit)

        # Arno, 2010-06-11: We're on the OverlayThread
        self._updateChannelcastDB(query_permid, query, hits, listOfAdditions)
 def log(self, permid, decoded_message):        
     lt = T.localtime(T.time())
     timestamp = "%04d-%02d-%02d %02d:%02d:%02d" % (lt[0], lt[1], lt[2], lt[3], lt[4], lt[5])
     ip = self.peer_db.getPeer(permid, "ip")
     #ip = "x.y.z.1"
     s = "%s\t%s\t%s\t%s\n"% (timestamp, bin2str(permid), ip, decoded_message)
     
     print dunno2unicode(s)
     self.logfile.write(dunno2unicode(s)) # bin2str(
     self.logfile.flush()
Exemplo n.º 14
0
    def saveFriendshipStatistics(self, permid, currentTime, stats):
        if stats:
            # 20/10/08. Boudewijn: A mistake in the code results in
            # only 7 items in the list instead of 8. We add one here
            # to get things working.
            for stat in stats:
                if len(stat) == 7:
                    stat.append(0)
                if len(stat) == 7 or len(stat) == 8:
                    stat.append(bin2str(permid))

            self.friendshipStatistics_db.saveFriendshipStatisticData(stats)
    def saveFriendshipStatistics(self,permid,currentTime,stats):
        if stats:
            # 20/10/08. Boudewijn: A mistake in the code results in
            # only 7 items in the list instead of 8. We add one here
            # to get things working.
            for stat in stats:
                if len(stat) == 7:
                    stat.append(0)
                if len(stat) == 7 or len(stat) == 8:
                    stat.append(bin2str(permid))

            self.friendshipStatistics_db.saveFriendshipStatisticData(stats)
Exemplo n.º 16
0
    def log(self, permid, decoded_message):
        lt = T.localtime(T.time())
        timestamp = "%04d-%02d-%02d %02d:%02d:%02d" % (lt[0], lt[1], lt[2],
                                                       lt[3], lt[4], lt[5])
        ip = self.peer_db.getPeer(permid, "ip")
        #ip = "x.y.z.1"
        s = "%s\t%s\t%s\t%s\n" % (timestamp, bin2str(permid), ip,
                                  decoded_message)

        print dunno2unicode(s)
        self.logfile.write(dunno2unicode(s))  # bin2str(
        self.logfile.flush()
Exemplo n.º 17
0
 def testInsertNewMetadataSubs(self):
     metadataDTO = MockMetadataDTO(["nld","ita"])
     metadataDTO.sign(metadataDTO._keypair)
     self.underTest.insertMetadata(metadataDTO)
     
     testquery = "SELECT * FROM Metadata WHERE publisher_id=?" \
         + " AND infohash=?;" 
     results = self.db.fetchall(testquery, (bin2str(metadataDTO.channel),bin2str(metadataDTO.infohash)))
     
     self.assertTrue(len(results) == 1)
     tupl = results[0] 
     self.assertTrue(tupl[0] is not None and isinstance(tupl[0], int))
     self.assertEquals(bin2str(metadataDTO.channel),tupl[1])
     self.assertEquals(bin2str(metadataDTO.infohash),tupl[2])
     self.assertEquals(metadataDTO.description, tupl[3])
     self.assertEquals(metadataDTO.timestamp, tupl[4])
     self.assertEquals(bin2str(metadataDTO.signature), tupl[5])
     
     subtitlesQuery = "SELECT * FROM Subtitles WHERE metadata_id_fk=?;"
     
     subtitles = self.db.fetchall(subtitlesQuery, (tupl[0],))
     self.assertEquals(2,len(subtitles))
     
     for lang in ("ita", "nld"):
         found = False
         foundSub = None
         for subtuple in subtitles:
             if subtuple[1] == lang:
                 found = True
                 foundSub = subtuple
                 break
             
         self.assertTrue(found)
         self.assertEquals(bin2str(metadataDTO.getSubtitle(lang).checksum), foundSub[3])
    def process_response(self,permid,d):

        mypermid = self.session.get_permid()
                     
                
        self.friendshipStatistics_db.updateFriendshipResponseTime( bin2str(mypermid), 
                                                                         bin2str(permid), 
                                                                         int(time()))

        
        fs = self.frienddb.getFriendState(permid)
         
        # If the request to add has been approved
        if d['response'] == 1:
            if fs == FS_I_INVITED:
                self.frienddb.setFriendState(permid, commit=True, state = FS_MUTUAL)
            elif fs != FS_MUTUAL:
                # Unsollicited response, consider this an invite, if not already friend
                self.frienddb.setFriendState(permid, commit=True, state = FS_HE_INVITED)
        else:
            # He denied our friendship
            self.frienddb.setFriendState(permid, commit=True, state = FS_HE_DENIED)
Exemplo n.º 19
0
 def subtest_votecast(self):
     print >>sys.stderr,time.asctime(),'-', "test: votecast-----------------------------"
     s = OLConnection(self.my_keypair,'localhost',self.hisport)
     vcast = VoteCastCore(None, s, self.session, None, log = '', dnsindb = None)
     
     #Send Good VoteCast message
     vdata = {self.hispermid:{'vote':-1,'time_stamp':12345345}}
     print >> sys.stderr, time.asctime(),'-', "Test Good VoteCast", `vdata`
     msg = VOTECAST+bencode(vdata)
     s.send(msg)
     resp = s.recv()
     #print >> sys.stderr, time.asctime(),'-', "printing resp", resp
     if len(resp) > 0:
         print >>sys.stderr,time.asctime(),'-', "test: votecast: got",getMessageName(resp[0])
     self.assert_(resp[0]==VOTECAST)
     print >>sys.stderr, time.asctime(),'-', "test: votecast: got msg", `bdecode(resp[1:])`
     vdata_rcvd = bdecode(resp[1:])
     self.assert_(validVoteCastMsg(vdata_rcvd)==True)
     s.close()
     
     #Now, send a bad ChannelCast messages
     # The other side should close the connection
     
     #Bad time_stamp: it can only int
     vdata = {bin2str(self.hispermid):{'vote':-1,'time_stamp':'halo'}}
     self.subtest_bad_votecast(vdata)
     
     #Bad Vote: Vote can only -1 or 2
     vdata = {bin2str(self.hispermid):{'vote':-15,'time_stamp':12345345}}
     self.subtest_bad_votecast(vdata)
     
     # Bad Message format ... Correct format is 'time_stamp'
     vdata = {bin2str(self.hispermid):{'vote':-15,'timestamp':12345345}}
     self.subtest_bad_votecast(vdata)
     
     print>>sys.stderr, time.asctime(),'-', "End of votecast test"
Exemplo n.º 20
0
    def test_channelcast(self):
        torrent_data = {
            'announce': "http://localhost",
            'info': {
                'name': 'Hello 123',
                'files': [{
                    'length': 100,
                    'path': ['license.txt']
                }]
            }
        }
        infohash = bin2str(sha(bencode(torrent_data['info'])).digest())
        self.channelcastdb.addOwnTorrent(infohash, torrent_data)

        s = OLConnection(self.my_keypair, 'localhost', self.hisport)
        chcast = ChannelCastCore(None,
                                 s,
                                 self.session,
                                 None,
                                 log='',
                                 dnsindb=None)

        # Good message
        chdata = chcast.createChannelCastMessage()
        if chdata is None or len(chdata) == 0:
            print "test: no subscriptions for us.. hence do not send"
        else:
            msg = CHANNELCAST + bencode(chdata)
            print "test: channelcast msg created", repr(chdata)
            s.send(msg)

        time.sleep(3)

        # Bad message
        if chdata is None or len(chdata) == 0:
            pass
        else:
            pub_id, pub_name, infohash, torrenthash, name, timestamp, signature = chdata[
                0]
            chdata = [(pub_id, pub_name, infohash, torrenthash, name, 12343,
                       signature)]
            msg = CHANNELCAST + bencode(chdata)
            print "test: channelcast msg created", repr(chdata)
            s.send(msg)
            time.sleep(20)
            # the other side should have closed the connection, as it is invalid message

        s.close()
Exemplo n.º 21
0
 def subtest_channel_permid_query(self,nickname):
     print >>sys.stderr,time.asctime(),'-', "test: chquery permid-----------------------------"
     s = OLConnection(self.my_keypair,'localhost',self.hisport)
     data = {}
     uq = u'CHANNEL p '+ bin2str(self.hispermid)
     data['q'] = uq.encode("UTF-8")
     data['id'] = 'b' * 20
     msg = QUERY + bencode(data)
     s.send(msg)
     resp = s.recv()
     #print >> sys.stderr, time.asctime(),'-', "printing resp", resp
     if len(resp) > 0:
         print >>sys.stderr,time.asctime(),'-', "test: chquery: got",getMessageName(resp[0])
     self.assert_(resp[0]==QUERY_REPLY)
     self.check_chquery_reply(resp[1:],nickname)
     print >>sys.stderr,time.asctime(),'-', "test:",`bdecode(resp[1:])`
     s.close()
Exemplo n.º 22
0
    def test_channel_subscription(self):
        self.votecastdb.unsubscribe(bin2str(self.mypermid))
        self.assertEqual(
            self.votecastdb.getVote(bin2str(self.mypermid),
                                    bin2str(self.hispermid)), None)
        print >> sys.stderr, self.votecastdb.getAll()

        self.votecastdb.spam(bin2str(self.mypermid))
        self.assertEqual(
            self.votecastdb.getVote(bin2str(self.mypermid),
                                    bin2str(self.hispermid)), -1)
        print >> sys.stderr, self.votecastdb.getAll()

        self.votecastdb.subscribe(bin2str(self.mypermid))
        self.assertEqual(
            self.votecastdb.getVote(bin2str(self.mypermid),
                                    bin2str(self.hispermid)), 2)
        print >> sys.stderr, self.votecastdb.getAll()

        self.votecastdb.unsubscribe(bin2str(self.mypermid))
        self.assertEqual(
            self.votecastdb.getVote(bin2str(self.mypermid),
                                    bin2str(self.hispermid)), 0)
        print >> sys.stderr, self.votecastdb.getAll()

        self.votecastdb.spam(bin2str(self.mypermid))
        self.assertEqual(
            self.votecastdb.getVote(bin2str(self.mypermid),
                                    bin2str(self.hispermid)), -1)
        print >> sys.stderr, self.votecastdb.getAll()
Exemplo n.º 23
0
    def fmsg_connect_callback(self, exc, dns, permid, selversion, type=None):
        """ Callback function for the overlay connect function """
        # Called by OverlayThread

        if exc is None:
            if selversion < OLPROTO_VER_SEVENTH:
                self.remove_msgs_for_ltv7_peer(permid)
                return

            # Reached him
            sendlist = self.get_msgs_as_sendlist(targetpermid=permid)
            if DEBUG:
                print >> sys.stderr, 'friendship: fmsg_connect_callback: sendlist len', len(
                    sendlist)
                #print_stack()

            for i in range(0, len(sendlist)):
                tuple = sendlist[i]

                permid, msgid, msg = tuple
                send_callback = lambda exc, permid: self.fmsg_send_callback(
                    exc, permid, msgid)

                if DEBUG:
                    print >> sys.stderr, "friendship: fmsg_connect_callback: Sending", ` msg `, msgid

                mypermid = self.session.get_permid()

                commit = (i == len(sendlist) - 1)
                isForwarder = 0
                no_of_helpers = 0
                #                if type == F_REQUEST_MSG:
                #                    print
                #                elif type == F_RESPONSE_MSG:
                #                    print
                #Set forwarder to True and also no of helpers to 10
                if type == F_FORWARD_MSG:
                    isForwarder = 1
                    no_of_helpers = 10

                no_of_attempts = 0
                if permid in self.currmsgs:
                    msgid2rec = self.currmsgs[permid]
                    if msgid in msgid2rec:
                        msgrec = msgid2rec[msgid]
                        no_of_attempts = msgrec['attempt']


#                insertFriendshipStatistics(self, my_permid, target_permid, current_time, isForwarder = 0, no_of_attempts = 0, no_of_helpers = 0, commit = True):

                self.friendshipStatistics_db.insertOrUpdateFriendshipStatistics(
                    bin2str(mypermid),
                    bin2str(permid),
                    int(time()),
                    isForwarder,
                    no_of_attempts,
                    no_of_helpers,
                    commit=commit)

                self.overlay_bridge.send(permid, FRIENDSHIP + bencode(msg),
                                         send_callback)

        else:
            if DEBUG:
                peer = self.peerdb.getPeer(permid)
                if peer is None:
                    print >> sys.stderr, 'friendship: Could not connect to peer', show_permid_short(
                        permid), peer
                else:
                    print >> sys.stderr, 'friendship: Could not connect to peer', show_permid_short(
                        permid), peer['name']
                print >> sys.stderr, exc

            mypermid = self.session.get_permid()

            isForwarder = 0
            no_of_helpers = 0
            if type == F_FORWARD_MSG:
                isForwarder = 1
                no_of_helpers = 10

            no_of_attempts = 0
            if permid in self.currmsgs:
                msgid2rec = self.currmsgs[permid]
                for msgid in msgid2rec:
                    msgrec = msgid2rec[msgid]
                    no_of_attempts = msgrec['attempt']

            self.friendshipStatistics_db.insertOrUpdateFriendshipStatistics(
                bin2str(mypermid), bin2str(permid), int(time()), isForwarder,
                no_of_attempts, no_of_helpers)
    def fmsg_connect_callback(self,exc,dns,permid,selversion, type = None):
        """ Callback function for the overlay connect function """
        # Called by OverlayThread

        if exc is None:
            if selversion < OLPROTO_VER_SEVENTH:
                self.remove_msgs_for_ltv7_peer(permid)
                return
            
            # Reached him
            sendlist = self.get_msgs_as_sendlist(targetpermid=permid)
            if DEBUG:
                print >> sys.stderr, 'friendship: fmsg_connect_callback: sendlist len',len(sendlist)
                #print_stack()
            
            for i in range(0,len(sendlist)):
                tuple = sendlist[i]
                
                permid,msgid,msg = tuple
                send_callback = lambda exc,permid:self.fmsg_send_callback(exc,permid,msgid)
                
                if DEBUG:
                    print >>sys.stderr,"friendship: fmsg_connect_callback: Sending",`msg`,msgid
                
                mypermid = self.session.get_permid()
                
                commit = (i == len(sendlist)-1)
                isForwarder = 0
                no_of_helpers = 0
#                if type == F_REQUEST_MSG:
#                    print
#                elif type == F_RESPONSE_MSG:
#                    print
                #Set forwarder to True and also no of helpers to 10
                if type == F_FORWARD_MSG:
                    isForwarder = 1
                    no_of_helpers = 10
                    
                  
                no_of_attempts = 0
                if permid in self.currmsgs:
                    msgid2rec = self.currmsgs[permid]
                    if msgid in msgid2rec:
                        msgrec = msgid2rec[msgid]
                        no_of_attempts = msgrec['attempt']
                
#                insertFriendshipStatistics(self, my_permid, target_permid, current_time, isForwarder = 0, no_of_attempts = 0, no_of_helpers = 0, commit = True):
                
                self.friendshipStatistics_db.insertOrUpdateFriendshipStatistics( bin2str(mypermid), 
                                                                         bin2str(permid), 
                                                                         int(time()),
                                                                         isForwarder, 
                                                                         no_of_attempts ,
                                                                         no_of_helpers, 
                                                                         commit=commit)
                
                self.overlay_bridge.send(permid, FRIENDSHIP + bencode(msg), send_callback)
                
                
        else:
            if DEBUG:
                peer = self.peerdb.getPeer(permid)
                if peer is None:
                    print >>sys.stderr, 'friendship: Could not connect to peer', show_permid_short(permid),peer
                else:
                    print >>sys.stderr, 'friendship: Could not connect to peer', show_permid_short(permid),peer['name']
                print >>sys.stderr,exc
            
            mypermid = self.session.get_permid()
            
            isForwarder = 0
            no_of_helpers = 0
            if type == F_FORWARD_MSG:
                isForwarder = 1
                no_of_helpers = 10
                    
                 
            no_of_attempts = 0
            if permid in self.currmsgs:
                msgid2rec = self.currmsgs[permid]
                for msgid in msgid2rec:
                    msgrec = msgid2rec[msgid]
                    no_of_attempts = msgrec['attempt']
                
                
            self.friendshipStatistics_db.insertOrUpdateFriendshipStatistics( bin2str(mypermid), 
                                                                         bin2str(permid), 
                                                                         int(time()),
                                                                         isForwarder, 
                                                                         no_of_attempts ,
                                                                         no_of_helpers)
Exemplo n.º 25
0
    def subtest_voting(self):
        self.votecast_db.unsubscribe(bin2str(self.mypermid))
        self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),None)
        #print >> sys.stderr, time.asctime(),'-', self.votecast_db.getAll()

        self.votecast_db.spam(bin2str(self.mypermid))
        self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1)
        #print >> sys.stderr, time.asctime(),'-', self.votecast_db.getAll()
                
        self.votecast_db.subscribe(bin2str(self.mypermid))
        self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),2)
        #print >> sys.stderr, time.asctime(),'-', self.votecast_db.getAll()
        
        self.votecast_db.unsubscribe(bin2str(self.mypermid))
        self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),None)
        #print >> sys.stderr, time.asctime(),'-', self.votecast_db.getAll()
        
        self.votecast_db.spam(bin2str(self.mypermid))
        self.assertEqual(self.votecast_db.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1)
Exemplo n.º 26
0
 def usercallback(infohash,metadata,filename):
     if tmp_hits.has_key(infohash):
         hit = tmp_hits[infohash]
         if self.channelcastdb.addTorrent(hit):
             self.hits.append(hit)
     else:
         print >> sys.stderr, "channelcast: updatechannel: could not find infohash", bin2str(infohash)
    def test_channel_subscription(self):
        self.votecastdb.unsubscribe(bin2str(self.mypermid))
        self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),None)
        print >> sys.stderr, self.votecastdb.getAll()

        self.votecastdb.spam(bin2str(self.mypermid))
        self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1)
        print >> sys.stderr, self.votecastdb.getAll()
                
        self.votecastdb.subscribe(bin2str(self.mypermid))
        self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),2)
        print >> sys.stderr, self.votecastdb.getAll()
        
        self.votecastdb.unsubscribe(bin2str(self.mypermid))
        self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),0)
        print >> sys.stderr, self.votecastdb.getAll()
        
        self.votecastdb.spam(bin2str(self.mypermid))
        self.assertEqual(self.votecastdb.getVote(bin2str(self.mypermid),bin2str(self.hispermid)),-1)
        print >> sys.stderr, self.votecastdb.getAll()