Example #1
0
 def authenticate(self, qr_reload):
     qr_callback = getattr(self, qr_reload, self.master_qr_code)
     with coordinator.mutex:
         self.bot: wxpy.Bot = wxpy.Bot(cache_path=os.path.join(efb_utils.get_data_path(self.channel_id), "wxpy.pkl"),
                                       qr_callback=qr_callback,
                                       logout_callback=self.exit_callback)
         self.bot.enable_puid(os.path.join(efb_utils.get_data_path(self.channel_id), "wxpy_puid.pkl"))
         self.done_reauth.set()
Example #2
0
 def authenticate(self, qr_reload):
     qr_callback = getattr(self, qr_reload, self.master_qr_code)
     with coordinator.mutex:
         self.bot: wxpy.Bot = wxpy.Bot(cache_path=str(efb_utils.get_data_path(self.channel_id) / "wxpy.pkl"),
                                       qr_callback=qr_callback,
                                       logout_callback=self.exit_callback)
         self.bot.enable_puid(
             efb_utils.get_data_path(self.channel_id) / "wxpy_puid.pkl",
             self.flag('puid_logs')
         )
         self.done_reauth.set()
         if hasattr(self, "slave_message"):
             self.slave_message.bot = self.bot
             self.slave_message.wechat_msg_register()
Example #3
0
    def __init__(self, instance_id: Optional[InstanceID] = None):
        super().__init__(instance_id)

        # load config
        self.yaml = YAML()
        conf_path = utils.get_config_path(self.middleware_id)
        if not conf_path.exists():
            conf_path.touch()
        self.config = self.yaml.load(conf_path)

        self.filters = [self.chat_id_based_filter]

        # Mapping
        self.FILTER_MAPPING = {
            "chat_name_contains": self.chat_name_contains_filter,
            "chat_name_matches": self.chat_name_matches_filter,
            "message_contains": self.message_contains_filter,
            "ews_mp": self.ews_mp_filter
        }

        # Chat ID based filter init
        shelve_path = str(
            utils.get_data_path(self.middleware_id) / "chat_id_filter.db")
        self.chat_id_filter_db = shelve.open(shelve_path)
        atexit.register(self.atexit)

        # load other filters
        if isinstance(self.config, Mapping):
            for i in self.config.keys():
                f = self.FILTER_MAPPING.get(i)
                if f:
                    self.filters.append(f)
    def __init__(self, master: str):
        # self.db = SqliteDatabase(str(base_path / 'ftdata.db'))
        base_path: str = utils.get_data_path(master)
        self.db: SqliteDatabase = SqliteDatabase(
            os.path.join(base_path, 'tgdata.db'))
        self.db.connect()

        class BaseModel(Model):
            class Meta:
                database = self.db

        class MsgLog(BaseModel):
            master_msg_id = TextField(unique=True, primary_key=True)
            master_msg_id_alt = TextField(null=True)
            slave_message_id = TextField()
            text = TextField()
            slave_origin_uid = TextField()
            slave_origin_display_name = TextField(null=True)
            slave_member_uid = TextField(null=True)
            slave_member_display_name = TextField(null=True)
            media_type = TextField(null=True)
            mime = TextField(null=True)
            file_id = TextField(null=True)
            msg_type = TextField()
            sent_to = TextField()
            time = DateTimeField(default=datetime.datetime.now, null=True)

        self.MsgLog = MsgLog
    def __init__(self, instance_id: InstanceID = None):
        super().__init__(instance_id)
        session_path = efb_utils.get_data_path(
            self.channel_id) / "session.pickle"
        try:
            data = pickle.load(session_path.open('rb'))
            self.client = EFMSClient(self, None, None, session_cookies=data)
        except FileNotFoundError:
            raise EFBException(
                self._("Session not found, please authorize your account.\n"
                       "To do so, run: efms-auth"))
        except FBchatUserError as e:
            message = str(e) + "\n" + \
                      self._("You may need to re-authorize your account.\n" +
                             "To do so, run: efms-auth")
            raise EFBException(message)

        self.load_config()
        self.chat_manager: EFMSChatManager = EFMSChatManager(self)
        self.flag: ExperimentalFlagsManager = ExperimentalFlagsManager(self)
        self.master_message: MasterMessageManager = MasterMessageManager(self)
        self.extra_functions: ExtraFunctionsManager = ExtraFunctionsManager(
            self)

        # Initialize list of chat from server
        self.get_chats()

        # Monkey patching
        Thread.__eq__ = lambda a, b: a.uid == b.uid
Example #6
0
def wizard(profile, instance_id):
    data = {}
    config_path = efb_utils.get_config_path(TelegramChannel.channel_id)
    if Path(config_path).exists():
        with config_path.open() as f:
            data = yaml.full_load(f)

    data['api_id'] = int(input("API id: "))
    data['api_hash'] = input("API hash: ")
    data['proxy'] = {}
    data['proxy']['protocol'] = input("Proxy protocol (http or socks5): ")
    data['proxy']['host'] = input("Proxy host: ")
    data['proxy']['port'] = int(input("Proxy port: "))

    loop = asyncio.get_event_loop()
    data_path = efb_utils.get_data_path(TelegramChannel.channel_id)
    proxy = (data['proxy']['protocol'], data['proxy']['host'],
             data['proxy']['port'])
    client = TelegramClient(f'{data_path}/{instance_id}',
                            data['api_id'],
                            data['api_hash'],
                            loop=loop,
                            proxy=proxy)
    client.start()
    print(data)
    with open(config_path, 'w') as f:
        yaml.dump(data, f)
Example #7
0
    def __init__(self, channel: 'TelegramChannel'):
        base_path = utils.get_data_path(channel.channel_id)

        self.logger.debug("Loading database...")
        database.init(str(base_path / 'tgdata.db'))
        database.connect()
        self.logger.debug("Database loaded.")

        self.task_queue: 'Queue[Optional[Tuple[Callable, Sequence[Any], Dict[str, Any]]]]' = Queue(
        )
        self.worker_thread = Thread(target=self.task_worker,
                                    name="ETM database worker thread")
        self.worker_thread.start()

        self.logger.debug("Checking database migration...")
        if not ChatAssoc.table_exists():
            self._create()
        else:
            msg_log_columns = {i.name for i in database.get_columns("msglog")}
            slave_chat_info_columns = {
                i.name
                for i in database.get_columns("slavechatinfo")
            }
            if "file_id" not in msg_log_columns:
                self._migrate(0)
            elif "pickle" not in msg_log_columns:
                self._migrate(1)
            elif "slave_chat_group_id" not in slave_chat_info_columns:
                self._migrate(2)
        self.logger.debug("Database migration finished...")
Example #8
0
    def __init__(self, channel: EFBChannel):
        base_path = utils.get_data_path(channel.channel_id)

        database.init(str(base_path / 'tgdata.db'))
        database.connect()

        if not ChatAssoc.table_exists():
            self._create()
        elif "file_id" not in {i.name for i in database.get_columns("MsgLog")}:
            self._migrate(0)
Example #9
0
 def authenticate(self, qr_reload, first_start=False):
     self.master_qr_picture_id = None
     qr_callback = getattr(self, qr_reload, self.master_qr_code)
     if getattr(self, 'bot', None):  # if a bot exists
         self.bot.cleanup()
     with coordinator.mutex:
         self.bot: wxpy.Bot = wxpy.Bot(cache_path=str(efb_utils.get_data_path(self.channel_id) / "wxpy.pkl"),
                                       qr_callback=qr_callback,
                                       logout_callback=self.exit_callback,
                                       user_agent=self.flag('user_agent'),
                                       start_immediately=not first_start)
         self.bot.enable_puid(
             efb_utils.get_data_path(self.channel_id) / "wxpy_puid.pkl",
             self.flag('puid_logs')
         )
         self.done_reauth.set()
         if hasattr(self, "slave_message"):
             self.slave_message.bot = self.bot
             self.slave_message.wechat_msg_register()
 def __init__(self, profile: str, instance_id: str):
     coordinator.profile = profile
     self.profile = profile
     self.instance_id = instance_id
     self.channel_id = FBMessengerChannel.channel_id
     if instance_id:
         self.channel_id = ModuleID(self.channel_id + "#" + instance_id)
     self.config_path = utils.get_config_path(self.channel_id)
     self.session_path = utils.get_data_path(
         self.channel_id) / "session.pickle"
     self.yaml = YAML()
     if not self.config_path.exists():
         self.build_default_config()
     else:
         self.data = self.yaml.load(self.config_path.open())
Example #11
0
    def reauth(self, command=False):
        # Remove wxpy.pkl if last edited earlier than 5 minutes ago.
        last_session = efb_utils.get_data_path(self.channel_id) / "wxpy.pkl"
        if (time.time() - last_session.stat().st_mtime) < (5 * 60):
            last_session.unlink()

        msg = self._("Preparing to log in...")
        qr_reload = self.flag("qr_reload")
        if command and qr_reload == "console_qr_code":
            msg += "\n" + self._("Please check your log to continue.")

        threading.Thread(target=self.authenticate,
                         args=(qr_reload, ),
                         name="EWS reauth thread").start()
        return msg
Example #12
0
    def __init__(self, channel: EFBChannel):
        base_path = utils.get_data_path(channel.channel_id)

        self.db = SqliteDatabase(str(base_path / 'tgdata.db'))

        self.db.connect()

        class BaseModel(Model):
            class Meta:
                database = self.db

        class ChatAssoc(BaseModel):
            master_uid = TextField()
            slave_uid = TextField()

        class MsgLog(BaseModel):
            master_msg_id = TextField(unique=True, primary_key=True)
            master_msg_id_alt = TextField(null=True)
            slave_message_id = TextField()
            text = TextField()
            slave_origin_uid = TextField()
            slave_origin_display_name = TextField(null=True)
            slave_member_uid = TextField(null=True)
            slave_member_display_name = TextField(null=True)
            media_type = TextField(null=True)
            mime = TextField(null=True)
            file_id = TextField(null=True)
            msg_type = TextField()
            sent_to = TextField()
            time = DateTimeField(default=datetime.datetime.now, null=True)

        class SlaveChatInfo(BaseModel):
            slave_channel_id = TextField()
            slave_channel_emoji = CharField()
            slave_chat_uid = TextField()
            slave_chat_name = TextField()
            slave_chat_alias = TextField(null=True)
            slave_chat_type = CharField()

        self.BaseModel = BaseModel
        self.ChatAssoc = ChatAssoc
        self.MsgLog = MsgLog
        self.SlaveChatInfo = SlaveChatInfo

        if not ChatAssoc.table_exists():
            self._create()
        elif "file_id" not in {i.name for i in self.db.get_columns("MsgLog")}:
            self._migrate(0)
 def __init__(self, instance_id: InstanceID = None):
     super().__init__(instance_id)
     self.load_config()
     self.loop = asyncio.get_event_loop()
     data_path = efb_utils.get_data_path(self.channel_id)
     proxy = (self.config['proxy']['protocol'],
              self.config['proxy']['host'], self.config['proxy']['port'])
     self.client: TelegramClient = TelegramClient(
         f'{data_path}/{instance_id}',
         self.config['api_id'],
         self.config['api_hash'],
         loop=self.loop,
         proxy=proxy).start()
     self.get_chat_cache: Dict[str, ChatID] = {}
     self.task = None
     self._main_thread_name = threading.current_thread().name
Example #14
0
    def __init__(self, channel: EFBChannel):
        base_path = utils.get_data_path(channel.channel_id)

        database.init(str(base_path / 'tgdata.db'))
        database.connect()

        self.task_queue: 'Queue[Optional[Tuple[Callable, Sequence[Any], Dict[str, Any]]]]' = Queue()
        self.worker_thread = Thread(target=self.task_worker)
        self.worker_thread.start()

        if not ChatAssoc.table_exists():
            self._create()
        else:
            msg_log_columns = {i.name for i in database.get_columns("MsgLog")}
            if "file_id" not in msg_log_columns:
                self._migrate(0)
            elif "pickle" not in msg_log_columns:
                self._migrate(1)
Example #15
0
def run(instance, profile):
    coordinator.profile = profile
    channel_id = FBMessengerChannel.channel_id
    if instance:
        channel_id += f"#{instance}"
    path = utils.get_data_path(channel_id)
    print(
        _("EFB Facebook Messenger Slave Session Updater\n"
          "============================================"))
    print()
    print(_("You are running EFMS {0}.").format(__version__))
    print()
    print(
        _("This will update and overwrite your EFMS token by\n"
          "log into your account again manually."))
    print()
    print(
        _("You usually need to do this when you want to log into\n"
          "a new account, or when the previous session is expired."))
    print()
    print(_("This session is written to\n" "{0}").format(path))
    print()
    print(_("To continue, press Enter/Return."))
    input()
    email = input(_("Email: "))
    password = getpass.getpass(_("Password: "******"Log in failed. Please check the information above and try again."
              ))
        exit(1)
    session_path = path / "session.pickle"
    with session_path.open('wb') as f:
        pickle.dump(client.getSession(), f)
    print(
        _("Your session has been successfully updated. It's stored at\n"
          "{0}").format(session_path))
    print(
        _("Your session cookies is as valuable as your account credential.\n"
          "Please keep them with equal care."))
Example #16
0
    def __init__(self, instance_id: str = None):
        super().__init__(instance_id)

        storage_path = utils.get_data_path(self.middleware_id)
        config_path = utils.get_config_path(self.middleware_id)
        if not os.path.exists(storage_path):
            os.makedirs(storage_path)
        if not os.path.exists(config_path):
            raise EFBException("Filter middleware is not configured.")
        else:
            config = yaml.safe_load(open(config_path, encoding="UTF-8"))
            self.config_version = 0
            self.match_mode = config.get("match_mode")  # fuzz and exact
            if self.match_mode is None:
                self.match_mode = "fuzz"

        self.logger = logging.getLogger("xzsk2.filter")
        hdlr = logging.FileHandler('./xzsk2.filter.log', encoding="UTF-8")
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        self.logger.setLevel(logging.ERROR)
 def init_client_manager(self):
     self.Helper = Helper(self, efb_utils.get_data_path(self.channel_id),
                          self.hostname, self.port)
     self.Helper.start_polling()
Example #18
0
    def __init__(self, instance_id: str = None):
        super().__init__(instance_id)
        storage_path = utils.get_data_path(self.middleware_id)
        config_path = utils.get_config_path(self.middleware_id)
        if not os.path.exists(storage_path):
            os.makedirs(storage_path)
        if not os.path.exists(config_path):
            # raise EFBException(self._("GnuPG middleware is not configured."))
            pass
        else:
            pass
            # config = yaml.load(open(config_path))
            # # self.key = config['key']
            # # self.always_trust = config.get('always_trust', self.always_trust)
            # # self.binary = config.get('binary', self.binary)
            # # self.password = config.get('password', self.password)
            # # self.server = config.get('server', self.server)
            # self.apikey = config.get('apikey', self.apikey).strip()

        # self.mappings_path = os.path.join(storage_path, "keymap.pkl")
        # if os.path.exists(self.mappings_path):
        #     self.mappings = pickle.load(open(self.mappings_path, 'rb'))

        self.chat = efbchat.SystemChat(
            middleware=self,
            # channel_name=self.middleware_name,
            module_name=self.middleware_name,
            # channel_id=self.middleware_id,
            module_id=self.middleware_id,
            channel_emoji="🤖",
            uid="__trysh.trysh__",
            # chat_name=self.middleware_name,
        )  # EFBChat()
        self.chat.channel_name = self.middleware_name
        self.chat.module_name = self.middleware_name
        self.chat.channel_id = self.middleware_id
        self.chat.module_id = self.middleware_id
        self.chat.channel_emoji = "🤖"
        self.chat.uid = "__trysh.trysh__"
        self.chat.chat_name = self.middleware_name
        # self.chat.chat_type = ChatType.System

        # self.chatMember = efbchat.ChatMember(
        #     chat=self.chat,
        #     middleware=self,
        #     # channel_name=self.middleware_name,
        #     # module_name=self.middleware_name,
        #     # channel_id=self.middleware_id,
        #     # module_id=self.middleware_id,
        #     # channel_emoji="🤖",
        #     uid="__trysh.trysh__",
        #     # chat_name=self.middleware_name,
        # )  # EFBChat()

        self.chat.channel_name = self.middleware_name
        self.chat.module_name = self.middleware_name
        self.chat.channel_id = self.middleware_id
        self.chat.module_id = self.middleware_id
        self.chat.channel_emoji = "🤖"
        self.chat.uid = "__trysh.trysh__"
        self.chat.chat_name = self.middleware_name

        self.logger = logging.getLogger("trysh.trysh")
        self.logger.log(99, f"trysh init ok v:{version}")
        # self.logger.setLevel(99)

        self.t1: threading.Thread = None
        self.t2: threading.Thread = None
        self.t1q: queue.Queue = None
        self.t2q: queue.Queue = queue.Queue()