class testMessageStore(unittest.TestCase):
    """Tests the message store. Note that the underlying store, e.g.,
    memcached, must be available before running these tests."""
    def setUp(self):
        self._ms = MessageStore('127.0.0.1', '11211')
        
    def testSetAndGet(self):
        self._ms.set(TEST_MESSAGE_ID, TEST_TIMESTAMP)
        self.assertEqual(TEST_TIMESTAMP, self._ms.get(TEST_MESSAGE_ID))

    def testGetEmpty(self):
        self.assertEquals(None, self._ms.get(TEST_MESSAGE_ID))
        pass
class testMessageStore(unittest.TestCase):
    """Tests the message store. Note that the underlying store, e.g.,
    memcached, must be available before running these tests."""
    def setUp(self):
        self._ms = MessageStore('127.0.0.1', '11211')

    def testSetAndGet(self):
        self._ms.set(TEST_MESSAGE_ID, TEST_TIMESTAMP)
        self.assertEqual(TEST_TIMESTAMP, self._ms.get(TEST_MESSAGE_ID))

    def testGetEmpty(self):
        self.assertEquals(None, self._ms.get(TEST_MESSAGE_ID))
        pass
示例#3
0
 def __init__(self, video_id=None, geometry='530x991+1913+0'):
     self.gui_root: Tk = Tk()
     self.geometry = geometry
     self.gui_root.geometry(self.geometry)
     self.gui: ChatPlayer = ChatPlayer(self.gui_root)
     self.previous_tick: float = 0
     self.scrubbing: bool = False
     self.search_open: bool = True
     self.search_focused: bool = False
     self.new_search: bool = False
     self.clock: Clock = Clock()
     self.clock.start()
     self.clock.pause()
     self.info: dict = {'title': 'Chat Player'}
     self.message_store: MessageStore = MessageStore([])
     self.duration: int = 0
     self.gui_root.bind_all('<Control-n>',
                            lambda _: self._configure_vid_info())
     self.gui_root.bind_all('<Control-w>', lambda _: self.exit())
     self.gui_root.bind_all('<Pause>', lambda _: self.exit())
     self.gui_root.bind_all(
         '<Escape>', lambda _: self.toggle_search()
         if self.search_open else None)
     if self.search_open:
         self.toggle_search()
     self._configure_vid_info(video_id)
示例#4
0
    def test_update(self):
        """
        Test for mastodon update processing
        """
        self.maxDiff = None
        with open(UPDATES_FILE) as f:
            data = f.read()
        f.close()
        j = json.loads(data)
        q = Queue()
        self.update_queue = Queue()
        tmp_db = MESSAGES_TEST_DB + '.bak'
        copyfile(MESSAGES_TEST_DB, tmp_db)
        self.message_store = MessageStore(tmp_db)
        m = mastodon_listener.MastodonListener(MASTODON_ID)
        m.jids = {'*****@*****.**'}
        if type(j) is list:
            for i in j:
                r = m.process_update(i)
                #self.update_queue.put(i)
                self.update_queue.put({
                    'mid': MASTODON_ID,
                    'status': r,
                    'm': m
                })
                q.put(r)
        else:
            r = m.process_update(j)
            self.update_queue.put({'mid': MASTODON_ID, 'status': r, 'm': m})
            q.put(r)

        with open(UPDATES_RSULT_FILE) as f:
            data = f.read()
        ju = json.loads(data)
        f.close()
        while not q.empty():
            m = q.get()
            u = ju.pop(0)
            # print(type(m))
            em = mastodon_listener.EncodedMessage()
            em.text = u['text']
            em.id = u['id']
            em.url = u['url']
            em.in_reply_to_id = u.get('in_reply_to_id')
            em.visibility = u['visibility']
            em.add_mentions(u['mentions'])
            ment = em.mentions
            self.assertEqual(m.to_dict(), em.to_dict())
示例#5
0
 def test_process_xmpp_thread(self):
     S=self
     message={
         'jid':'*****@*****.**',
         'to':'*****@*****.**',
         'body':"> @shura:\n> @[email protected]  @shura нормалды\nanswer"
     }
     class myMasto:
         def status_post(self, status, in_reply_to_id, visibility):
             print('status=', status)
             print('in_rely_to_id=', in_reply_to_id)
             print('visibility=',visibility)
             
             res=re.search(r'answer(.*)',status, flags=re.M|re.S)
             mentions_str=res.group(1)
             print(mentions_str)
             mentions=mentions_str.split(' ')
             mentions_ex=['\n','']
             S.assertEqual(mentions, mentions_ex)
             print(mentions)
             
             return {
                 'url':'url',
                 'id':'id',
             }
     m=myMasto()
     tmp_db=MESSAGES_TEST_DB+'.bak'
     copyfile(MESSAGES_TEST_DB, tmp_db)
     main.message_store=MessageStore(tmp_db)
     main.users_db = db.Db(USERS_TEST_DB)
     main.mastodon_listeners = {
         '*****@*****.**':m
     }
     main.process_xmpp_thread(message)
     new_message=main.message_store.get_message_by_id('id')
     print(new_message['mentions'])
     self.assertEqual(new_message['mentions'],'@[email protected] ' )
示例#6
0
    def test_messages(self):
        tmp_db = MESSAGES_TEST_DB + '.bak'
        copyfile(MESSAGES_TEST_DB, tmp_db)
        message_store = MessageStore(tmp_db)
        mentions = set(['@[email protected]'])
        id = 104032314153599025
        message_store.update_mentions(id, mentions)
        toot = message_store.get_message_by_id(id)
        sample = set(['@[email protected]', '@[email protected]'])
        self.assertEqual(set(toot['mentions'].split(' ')), sample)
        mentions = set(['@[email protected]', '@[email protected]'])
        message_store.update_mentions(id, mentions)
        toot = message_store.get_message_by_id(id)
        sample.update(['@[email protected]'])
        self.assertEqual(set(toot['mentions'].split(' ')), sample)

        search_for = '''@[email protected]:
Захотелось прочитать книгу по Linux. А то юзаю как чайник.'''
        toot = message_store.find_message(search_for, '*****@*****.**')
        # print(toot)
        self.assertEqual(toot['id'], '104032564439980906')
        search_for = '''@[email protected]:
Когда-то очень давно, я записывал концерт Spititual Front на айпад.  
В смысле, стоял в зале и снимал.  
Сейчас понимаю, как тупо я выглядел.  
И меня мучает вопрос:
Интересно, а как музыкантов не бесит, что вместо того, чтобы наслаждаться музыкой, текстами, там... шоу, в конце концов, народ утыкается в смарты и просто "ксерокопирует" форму без содержания?
'''
        toot = message_store.find_message(search_for, '*****@*****.**')
        self.assertEqual(toot['id'], '104032809534204360')

        search_for = '''@Vladimir_Vladimirovich:
Судно "Академик Черский", способное достроить "Северный поток-2", которое по данным независимых СМИ шло в Находку, внезапно оказалось у берегов Дании. Наверное решили идти в Находку Северным морским путём.'''
        toot = message_store.find_message(search_for, '*****@*****.**')
        self.assertEqual(toot, None)

        search_for = '''С одной стороны я достаточно долго не любил тот же Озон и ко за то, что они были членами АКИТ и лоббировали снижение беспошлинных лимитов, и прочее. С другой стороны они в это же время выстроили классную логистику с оглядкой на Amazon и это реально УДОБНО и просто.'''
        toot = message_store.find_message(search_for, '*****@*****.**')
        self.assertEqual(toot['id'], '105237775817950579')

        search_for = '''С одной стороны я достаточно долго не любил тот же Озон и ко за то, что они были членами АКИТ и лоббировали снижение беспошлинных лимитов, и прочее. С другой стороны они в это же время выстроили классную логистику с оглядкой на Amazon и это реально УДОБНО и просто.'''
        toot = message_store.find_message(search_for, '*****@*****.**')
        self.assertEqual(toot['id'], '105237775810751372')
示例#7
0
        except mastodon_listener.NotFoundError:
            msg = XMPP.make_message(message['jid'],
                                    "Message not found",
                                    mtype='chat',
                                    mfrom=message['to'])
            msg.send()

        except Empty:
            pass
        await asyncio.sleep(.2)


if __name__ == '__main__':
    XMPP = gxmpp.Component(xmpp_jid, xmpp_password, xmpp_server, xmpp_port)
    users_db = db.Db(USERS_DB)
    message_store = MessageStore(MESSAGES_DB)
    users = users_db.get_users()  # {jid, mid, token}
    print(users)
    XMPP.add_users(users)
    XMPP.attach_queue(xmpp_queue)
    loop = asyncio.get_event_loop()
    XMPP.connected_event = asyncio.Event()
    callback = lambda _: XMPP.connected_event.set()
    XMPP.add_event_handler('session_start', callback)
    XMPP.add_event_handler('session_start', process_update)
    XMPP.add_event_handler('session_start', process_notification)
    XMPP.add_event_handler('session_start', process_xmpp)
    XMPP.register_plugin('xep_0030')  # Service Discovery
    XMPP.register_plugin('xep_0065',
                         {'auto_accept': True})  # SOCKS5 Bytestreams
 def __init__(self):
     self._messageStore = MessageStore(MSG_STORE_HOST, MSG_STORE_PORT)
     log("Using message store at %s:%s" % (MSG_STORE_HOST, MSG_STORE_PORT))
 def setUp(self):
     self._ms = MessageStore('127.0.0.1', '11211')
 def setUp(self):
     self._ms = MessageStore('127.0.0.1', '11211')
示例#11
0
        return False
    else:
        return True


######### PRINT CONST ########
print("######### CONFIG VARIABLES ########")
print('NODE_NAME: ', get_nodename())
print("IS_BEACON: ", IS_BEACON)
print("BLE_ENABLED: ", BLE_ENABLED)
print("BLE_NAME: ", BLE_NAME)
print("######### CONFIG VARIABLES ########")

########## MESSAGES ##########
MAX_MESSAGES_LENGTH = 30  # Max amount of messages we will retain before removing old ones
message_store = MessageStore(MAX_MESSAGES_LENGTH)
print('Current Messages: ', message_store.messages)

########## BLE ##########
if BLE_ENABLED:
    from BLEPeripheral import *
    from ble_advertising import advertising_payload

    ble = bluetooth.BLE()
    ble_peripheral = BLESPeripheral(ble, BLE_NAME)


    def on_ble_rx(value):
        try:
            print("[BLE] Received Message: ", value)
            payload = str(value, 'utf-8')