# Path: mbot/state.py
# class StateMachine:
# 
#     """Simple state machine object (only in-memory now)
# 
#     """
# 
#     _states = {
#         'connections': ConnectionManager,
#         'dialogs': DialogManager,
#         'groups': GroupManager,
#         'users': UserManager,
#         'jobs': JobManager,
#     }
# 
#     def __init__(self, bot, engine="memory", state_path=None):
#         self.engine = engine
#         self.bot = bot
#         self.state_path = state_path
#         # history of command
#         self.command_history = {}
# 
#         self.states = {}
#         self.user_states = {}
# 
#         for key, manager in self._states.items():
#             setattr(self, key, manager(states=self.states,
#                                        user_states=self.user_states,
#                                        engine=engine,
#                                        name=key,
#                                        scope=key,
#                                        bot=bot))
# 
#         # stored user based command history
#         self.commands = {}
# 
#         # raw event history
#         self.events = []
# 
#     def add_new_messages(self, messages):
#         self.events += messages
# 
#     def save(self):
#         return self.bot.storage.save_state(self)
# 
#     def get_last_command(self, user):
#         if user not in self.command_history:
#             self.command_history[user] = []
#             return
#         if not self.command_history[user]:
#             return
#         return self.command_history[user][-1]
# 
#     def save_command_from_history(self, user, index, name):
#         """Story command under new shortcut
#         """
# 
#         cmd = self.command_history[user][index]
# 
#         self.commands[user][name] = cmd
# 
#     def save_last_command(self, user, name):
#         """Story command under new shortcut
#         """
# 
#         if user not in self.commands:
# 
#             self.commands[user] = {}
# 
#         self.commands[user][name] = self.get_last_command(user)
# 
#     def get_command(self, user, name):
#         if user in self.commands:
#             if name in self.commands[user]:
#                 return self.commands[user][name]
#             return False
#         return None
# 
#     def save_command(self, user, func, args=(), kwargs={}):
#         """Store callables with arguments
#         """
# 
#         if user not in self.command_history:
#             self.command_history[user] = []
# 
#         self.command_history[user].append((func, args, kwargs))
# 
#         self.save()
# 
#     def run_command(self, name, user=None, msg=None):
#         """Run command stored in user space"""
# 
#         func, args, kwargs = self.get_command(user or msg.user, name)
# 
#         if msg:
#             msg.reply("Loading command *%s*." % name)
#             if isinstance(args[1], Event):
#                 args[1].backend = msg.backend
# 
#         LOG.info("%s %s %s " % (func, args, kwargs))
# 
#         if isinstance(args[1], Event):
#             args[1].bot = self.bot
# 
#         func(*args, **kwargs)
# 
#     def __repr__(self):
#         return "<command_history:%s>" % self.command_history
# 
# Path: mbot/utils/packages.py
# def install_package(package, upgrade=True,
#                     target=None):
#     """Install a package on PyPi. Accepts pip compatible package strings.
#     Return boolean if install successful.
#     """
#     # Not using 'import pip; pip.main([])' because it breaks the logger
#     with INSTALL_LOCK:
#         if check_package_exists(package, target):
#             return True
# 
#         _LOGGER.info('Attempting install of %s', package)
#         args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
#         if upgrade:
#             args.append('--upgrade')
#         if target:
#             args += ['--target', os.path.abspath(target)]
# 
#         try:
#             return subprocess.call(args) == 0
#         except subprocess.SubprocessError:
#             _LOGGER.exception('Unable to install pacakge %s', package)
#             return False


import logging
import dill as pickle
import io
            import boto3
from mbot.state import StateMachine
from mbot.utils.packages import install_package

    def decrypt_data(self, data):
        return self.bot.fernet.decrypt(data)

    def save_state(self, state):
        """Save state"""

        with open(state.state_path, 'wb') as f:

            data = pickle.dumps(state, pickle.HIGHEST_PROTOCOL)

            if self.encrypt:
                data = self.encrypt_data(data)

            pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

    def restore_state(self, path):
        """Returns loaded state"""

        try:
            with open(path, 'rb') as f:
                if self.encrypt:
                    state = pickle.loads(self.decrypt_data(pickle.load(f)))
                else:
                    state = pickle.load(f)

                LOG.debug("Restoring state successs")
        except Exception as e:
            LOG.debug("Restoring state from %s failed with %s" % (
                path, e))

# Path: mbot/state.py
# class StateMachine:
# 
#     """Simple state machine object (only in-memory now)
# 
#     """
# 
#     _states = {
#         'connections': ConnectionManager,
#         'dialogs': DialogManager,
#         'groups': GroupManager,
#         'users': UserManager,
#         'jobs': JobManager,
#     }
# 
#     def __init__(self, bot, engine="memory", state_path=None):
#         self.engine = engine
#         self.bot = bot
#         self.state_path = state_path
#         # history of command
#         self.command_history = {}
# 
#         self.states = {}
#         self.user_states = {}
# 
#         for key, manager in self._states.items():
#             setattr(self, key, manager(states=self.states,
#                                        user_states=self.user_states,
#                                        engine=engine,
#                                        name=key,
#                                        scope=key,
#                                        bot=bot))
# 
#         # stored user based command history
#         self.commands = {}
# 
#         # raw event history
#         self.events = []
# 
#     def add_new_messages(self, messages):
#         self.events += messages
# 
#     def save(self):
#         return self.bot.storage.save_state(self)
# 
#     def get_last_command(self, user):
#         if user not in self.command_history:
#             self.command_history[user] = []
#             return
#         if not self.command_history[user]:
#             return
#         return self.command_history[user][-1]
# 
#     def save_command_from_history(self, user, index, name):
#         """Story command under new shortcut
#         """
# 
#         cmd = self.command_history[user][index]
# 
#         self.commands[user][name] = cmd
# 
#     def save_last_command(self, user, name):
#         """Story command under new shortcut
#         """
# 
#         if user not in self.commands:
# 
#             self.commands[user] = {}
# 
#         self.commands[user][name] = self.get_last_command(user)
# 
#     def get_command(self, user, name):
#         if user in self.commands:
#             if name in self.commands[user]:
#                 return self.commands[user][name]
#             return False
#         return None
# 
#     def save_command(self, user, func, args=(), kwargs={}):
#         """Store callables with arguments
#         """
# 
#         if user not in self.command_history:
#             self.command_history[user] = []
# 
#         self.command_history[user].append((func, args, kwargs))
# 
#         self.save()
# 
#     def run_command(self, name, user=None, msg=None):
#         """Run command stored in user space"""
# 
#         func, args, kwargs = self.get_command(user or msg.user, name)
# 
#         if msg:
#             msg.reply("Loading command *%s*." % name)
#             if isinstance(args[1], Event):
#                 args[1].backend = msg.backend
# 
#         LOG.info("%s %s %s " % (func, args, kwargs))
# 
#         if isinstance(args[1], Event):
#             args[1].bot = self.bot
# 
#         func(*args, **kwargs)
# 
#     def __repr__(self):
#         return "<command_history:%s>" % self.command_history
# 
# Path: mbot/utils/packages.py
# def install_package(package, upgrade=True,
#                     target=None):
#     """Install a package on PyPi. Accepts pip compatible package strings.
#     Return boolean if install successful.
#     """
#     # Not using 'import pip; pip.main([])' because it breaks the logger
#     with INSTALL_LOCK:
#         if check_package_exists(package, target):
#             return True
# 
#         _LOGGER.info('Attempting install of %s', package)
#         args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
#         if upgrade:
#             args.append('--upgrade')
#         if target:
#             args += ['--target', os.path.abspath(target)]
# 
#         try:
#             return subprocess.call(args) == 0
#         except subprocess.SubprocessError:
#             _LOGGER.exception('Unable to install pacakge %s', package)
#             return False


# Path: mbot/storage.py
import logging
import dill as pickle
import io
            import boto3
from mbot.state import StateMachine
from mbot.utils.packages import install_package


    def decrypt_data(self, data):
        return self.bot.fernet.decrypt(data)

    def save_state(self, state):
        """Save state"""

        with open(state.state_path, 'wb') as f:

            data = pickle.dumps(state, pickle.HIGHEST_PROTOCOL)

            if self.encrypt:
                data = self.encrypt_data(data)

            pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

    def restore_state(self, path):
        """Returns loaded state"""

        try:
            with open(path, 'rb') as f:
                if self.encrypt:
                    state = pickle.loads(self.decrypt_data(pickle.load(f)))
                else:
                    state = pickle.load(f)

                LOG.debug("Restoring state successs")
        except Exception as e:
            LOG.debug("Restoring state from %s failed with %s" % (
                path, e))

            state = StateMachine(self.bot, state_path=path)