def __init__(self, loglevel=None): config = ClientConfig(encryption_enabled=True, pickle_key=cfg.pickle_key, store_name=cfg.store_name, store_sync_tokens=True) if not os.path.exists(cfg.store_path): os.makedirs(cfg.store_path) self.http_session = aiohttp.ClientSession( headers={'User-Agent': self.user_agent}) self.client = AsyncClient( cfg.server, cfg.user, cfg.device_id, config=config, store_path=cfg.store_path ) logger_group.level = getattr( logbook, loglevel) if loglevel else logbook.CRITICAL logbook.StreamHandler(sys.stdout).push_application() self.logger = logbook.Logger('bot') logger_group.add_logger(self.logger) self.mli = MessageLinksInfo(self.http_session) self._register_commands() self.client.add_response_callback(self._sync_cb, SyncResponse) self.client.add_response_callback( self._key_query_cb, KeysQueryResponse) self.client.add_event_callback(self._invite_cb, InviteMemberEvent)
def test_sync_token_restoring(self, client): user = client.user_id device_id = client.device_id path = client.store_path del client config = ClientConfig(store_sync_tokens=True) client = Client(user, device_id, path, config=config) client.receive_response(self.login_response) assert not client.next_batch assert not client.loaded_sync_token client.receive_response(self.sync_response) assert client.next_batch client = Client(user, device_id, path, config=config) client.receive_response(self.login_response) assert client.loaded_sync_token
async def main(): # By setting `store_sync_tokens` to true, we'll save sync tokens to our # store every time we sync, thereby preventing reading old, previously read # events on each new sync. # For more info, check out https://matrix-nio.readthedocs.io/en/latest/nio.html#asyncclient config = ClientConfig(store_sync_tokens=True) client = CustomEncryptedClient( ALICE_HOMESERVER, ALICE_USER_ID, store_path=STORE_FOLDER, config=config, ssl=False, proxy="http://localhost:8080", ) try: await run_client(client) except (asyncio.CancelledError, KeyboardInterrupt): await client.close()
async def run(self): client_config = ClientConfig(store_sync_tokens=True) self.client = AsyncClient(homeserver=self.config["main"]["base_url"], user=self.config["main"]["user_id"], device_id=self.config["main"]["device_id"], store_path=self.config["main"]["store_path"], config=client_config) self.client.add_event_callback(self.on_invite, InviteEvent) self.client.add_event_callback(self.on_room_message, RoomMessageText) print("Logging in...") status = await self.client.login( self.config["main"]["password"], device_name=self.config["main"]["device_name"]) if not self.client.logged_in: print("Error logging in.") return print(f"Logged in as user {self.client.user_id}") await self.client.sync_forever(timeout=30000, full_state=True)
async def main(imagePath): # By setting `store_sync_tokens` to true, we'll save sync tokens to our # store every time we sync, thereby preventing reading old, previously read # events on each new sync. # For more info, check out https://matrix-nio.readthedocs.io/en/latest/nio.html#asyncclient config = ClientConfig( store_sync_tokens=True ) # path = os.path.dirname(os.path.abspath(__file__)) # path = os.path.join(path, "Morty_Smith.jpg") # a, n = await client.upload( # lambda *_ : path, "image/jpg", "Morty_Smith.jpg" # ) # print(a.content_uri) # # thumbObj = await client.thumbnail("https://alice.pdxinfosec.org",a.content_uri,width=500,height=500, method=ResizingMethod.crop) # # tubmb_uri = thumbObj.transport_response.real_url # # tubmb_uri = str(tubmb_uri) # # print(tubmb_uri) # b = await client.room_send( # room_id="!pmoszSetEtIHfZScMY:alice.pdxinfosec.org", # message_type="m.room.message", # content={ # "msgtype": "m.image", # "body": "Morty_Smith.jpg", # "url" : a.content_uri # } # ) client = CustomEncryptedClient(ALICE_HOMESERVER, ALICE_USER_ID, store_path=STORE_FOLDER, config=config) # ssl=False, # proxy="http://localhost:8080", try: await run_client(client, imagePath) except (asyncio.CancelledError, KeyboardInterrupt): await client.close()
def __init__( self, server_name, pan_store, pan_conf, homeserver, queue=None, user_id="", device_id="", store_path="", config=None, ssl=None, proxy=None, store_class=None, ): config = config or ClientConfig( store=store_class or SqliteStore, store_name="pan.db" ) super().__init__(homeserver, user_id, device_id, store_path, config, ssl, proxy) index_dir = os.path.join(store_path, server_name, user_id) try: os.makedirs(index_dir) except OSError: pass self.server_name = server_name self.pan_store = pan_store self.pan_conf = pan_conf if INDEXING_ENABLED: logger.info("Indexing enabled.") from pantalaimon.index import IndexStore self.index = IndexStore(self.user_id, index_dir) else: logger.info("Indexing disabled.") self.index = None self.task = None self.queue = queue # Those two events are mainly used for testing. self.new_fetch_task = asyncio.Event() self.fetch_loop_event = asyncio.Event() self.room_members_fetched = defaultdict(bool) self.send_semaphores = defaultdict(asyncio.Semaphore) self.send_decision_queues = dict() # type: asyncio.Queue self.last_sync_token = None self.history_fetcher_task = None self.history_fetch_queue = asyncio.Queue() self.add_to_device_callback(self.key_verification_cb, KeyVerificationEvent) self.add_to_device_callback( self.key_request_cb, (RoomKeyRequest, RoomKeyRequestCancellation) ) self.add_event_callback(self.undecrypted_event_cb, MegolmEvent) if INDEXING_ENABLED: self.add_event_callback( self.store_message_cb, ( RoomMessageText, RoomMessageMedia, RoomEncryptedMedia, RoomTopicEvent, RoomNameEvent, ), ) self.add_response_callback(self.keys_query_cb, KeysQueryResponse) self.add_response_callback(self.sync_tasks, SyncResponse)
async def main(args): cfgparser = configparser.ConfigParser() with open(args.config) as fh: cfgparser.read_file(fh) cfg = cfgparser['DEFAULT'] room = cfg['room'] payload = { 'service': args.service, 'host': args.host, 'type': args.type.upper(), 'state': args.state.upper(), 'output': args.output, 'msg': args.message, } device = {} device_state = os.path.join(cfg['state'], 'device.json') try: with open(device_state) as fh: device = json.load(fh) except FileNotFoundError: pass ensure_dir(cfg['state']) ensure_dir(os.path.join(cfg['state'], 'nio')) ensure_dir(os.path.join(cfg['state'], 'nio', cfg['user_id'])) client = AsyncClient(cfg['homeserver'], cfg['user_id'], device_id=device.get('device_id'), store_path=os.path.join(cfg['state'], 'nio', cfg['user_id']), config=ClientConfig(store_sync_tokens=True)) if device: client.access_token = device['access_token'] client.user_id = device['user_id'] client.load_store() else: resp = await client.login_raw({ 'type': 'org.matrix.login.jwt', 'token': cfg['token'], }) if (isinstance(resp, LoginResponse)): write_state(device_state, resp) else: print(f"Failed to log in: {resp}", file=sys.stderr) sys.exit(1) await client.sync(timeout=args.timeout * 1000, full_state=True) in_rooms = client.rooms.keys() room_id = (await client.room_resolve_alias(room)).room_id if not room_id in in_rooms: await client.join(room_id) for unwanted in [r for r in in_rooms if r != room_id]: await client.room_leave(room) if client.should_upload_keys: await client.keys_upload() if client.should_query_keys: await client.keys_query() if client.should_claim_keys: await client.keys_claim(client.get_users_for_key_claiming()) await client.sync(timeout=args.timeout * 1000, full_state=True) ps_l = [] if payload['msg']: ps_l.append(payload['msg']) if payload['output']: ps_l.append(payload['output']) ps = '\n'.join(ps_l) await client.room_send( room_id, 'm.room.message', { 'msgtype': 'm.text', 'body': '{type}: {service} on {host} is {state}\n{msg}'.format(**payload), 'format': 'org.matrix.custom.html', 'formatted_body': '<span style="background-color: #{color};"><span data-mx-bg-color="#{color}"><strong>{type}</strong>:</span></span> <span data-mx-bg-color="#ffffff">Service <strong>{service}</strong> on <strong>{host}</strong> is <strong>{state}</strong>:<br />{ps}</span>' .format(**payload, bgcolor=state_colors_back.get(payload['state'].lower(), '222288'), ps=ps, color=state_colors.get(payload['state'].lower(), '1111ff')), }, ignore_unverified_devices=True) await client.sync(timeout=args.timeout * 1000, full_state=True) await client.close()
def client_no_e2e(tempdir): config = ClientConfig(encryption_enabled=False) return Client("ephemeral", "DEVICEID", tempdir, config)