Exemple #1
0
    def test_dns_add_multiple(self):
        with pytest.raises(DnsError,
                           match='For dual alias, 2 subalias must be given'):
            RpiDns.new_dual_alias('only-one-alias', 'D:/test/dns/dual',
                                  '/home/test/dns/dual')

        RpiDns.new_dual_alias('text.test-multiple', 'D:/test/dns/dual-success',
                              '/home/test/dns/dual-success')
Exemple #2
0
def get_mail():
    """Gets the info for the raspberry mail (users pi and www-data)."""
    description = 'Raspberry Mail'
    files = {
        RpiDns.get('textdb.mail-pi'): 'raspberry_mail.txt',
        RpiDns.get('textdb.mail-www-data'): 'raspberry_mail2.txt'
    }
    return files, description
Exemple #3
0
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.debug('Starting database manager')
        self.con = sqlite3.connect(RpiDns.get('sqlite.menus_resi'))
        self.cur = self.con.cursor()

        self.cur.execute("""CREATE TABLE IF NOT EXISTS "menus" (
                         id INTEGER PRIMARY KEY NOT NULL,
                         origin VARCHAR NOT NULL,
                         day_month INTEGER NOT NULL,
                         month INTEGER NOT NULL,
                         year INTEGER NOT NULL,
                         day_week VARCHAR,
                         launch1 VARCHAR,
                         launch2 VARCHAR,
                         dinner1 VARCHAR,
                         dinner2 VARCHAR)""")

        self.cur.execute("""CREATE TABLE IF NOT EXISTS "links" (
                        'datetime' VARCHAR NOT NULL,
                        'link' VARCHAR PRIMARY KEY NOT NULL                        
                        )""")

        self.cur.execute("""CREATE TABLE IF NOT EXISTS "updates" (
                        'datetime' PRIMARY KEY     
                        )""")

        self.con.commit()
Exemple #4
0
class LoggingInfo:
    """Abstract class to store logs folders and file paths."""

    DEFAULT_LEVEL_WINDOWS = logging.DEBUG
    DEFAULT_LEVEL_LINUX = logging.DEBUG

    ROYAL = None
    WARNED = False

    LOGGING_FORMAT = '[%(asctime)s] %(levelname)-8s - %(name)s:%(lineno)s: %(message)s'
    TIME_FORMAT = '%H:%M:%S'

    today = datetime.datetime.today()

    LOGS_GENERAL_FOLDER = RpiDns.get('folder.logs')

    LOGS_YEAR_FOLDER = os.path.join(LOGS_GENERAL_FOLDER, str(today.year))
    LOGS_MONTH_FOLDER = os.path.join(LOGS_YEAR_FOLDER, str(today.month))
    LOGS_DAY_FOLDER = os.path.join(LOGS_MONTH_FOLDER, str(today.day))

    LOGS_APACHE_ACCESS = '/var/log/apache2/access.log'
    LOGS_APACHE_ERRROR = '/var/log/apache2/error.log'

    if os.path.isdir(LOGS_GENERAL_FOLDER) is False:
        os.mkdir(LOGS_GENERAL_FOLDER)

    if os.path.isdir(LOGS_YEAR_FOLDER) is False:
        os.mkdir(LOGS_YEAR_FOLDER)

    if os.path.isdir(LOGS_MONTH_FOLDER) is False:
        os.mkdir(LOGS_MONTH_FOLDER)

    if os.path.isdir(LOGS_DAY_FOLDER) is False:
        os.mkdir(LOGS_DAY_FOLDER)
Exemple #5
0
    def test_dns_add_one(self):
        assert RpiDns.len() >= 0

        RpiDns.new_alias('text.test_one', 'D:/test/dns')

        with pytest.raises(DnsError, match='already exists'):
            RpiDns.new_alias('text.test_one', 'D:/test/dns')

        with pytest.raises(DnsError, match='Not enough subalias'):
            RpiDns.new_alias('', 'D:/test/dns/not-enough-subalias')

        with pytest.raises(PlatformError, match='Invalid platform'):
            RpiDns.new_alias('rpi.text.test_one_independendant', 'D:/')
Exemple #6
0
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.path = RpiDns.get('json.claves')

        try:
            with open(self.path) as file_handler:
                self.dict = json.load(file_handler)
        except FileNotFoundError:
            self.logger.critical('Keys file not found (%r)', self.path)
            raise FileNotFoundError(f'Keys file not found ({self.path!r})')
Exemple #7
0
 def __init__(self):
     self.logger = logging.getLogger(__name__)
     self.path = RpiDns.get('textdb.config')
     self.config = {}
     self.load()
Exemple #8
0
def get_menus_database():
    """Gets the info for the menus database."""
    description = 'Menús Residencia Santiago'
    files = RpiDns.get('sqlite.menus_resi')
    return files, description
Exemple #9
0
def get_vcs_history():
    """Gets the info for the virtual campus scanner database."""
    description = 'Base de datos de links del Campus Virtual de la UVa'
    files = RpiDns.get('sqlite.vcs')
    return files, description
Exemple #10
0
    def test_dns_delete(self):
        with pytest.raises(DnsError, match='linux'):
            RpiDns.del_alias('text.test_one', error=False)

        RpiDns.del_alias('text.test-multiple')
Exemple #11
0
    def load(self):
        """Carga todos los usuarios."""

        self.logger.debug('Loading users')

        @dataclass
        class TempUser:
            username: str
            launcher: BaseLauncher
            is_active: bool
            email: str
            services: tuple
            is_superuser: bool
            is_staff: bool

        self.path = RpiDns.get('sqlite.django')

        if os.path.isfile(self.path) is False:
            self.logger.critical('User database not found (%r)', self.path)
            raise FileNotFoundError(f'User database not found ({self.path})')

        self.con = sqlite3.connect(self.path)
        self.cur = self.con.cursor()
        self.cur.execute(
            "select username, launcher, is_active, email, servicios, "
            "is_superuser, is_staff from 'usuarios_usuario'")

        content = self.cur.fetchall()
        self.con.close()

        content = [TempUser(*x) for x in content]

        for user in content:
            username = user.username
            is_active = user.is_active
            email = user.email
            is_superuser = user.is_superuser
            is_staff = user.is_staff

            # noinspection PyTypeChecker
            services = ServicesManager.eval(user.services)
            try:
                launcher = json.loads(user.launcher)
            except JSONDecodeError:
                launcher = {"type": 'Invalid'}

            if launcher["type"] == 'IFTTT':
                launcher = IftttLauncher(launcher["config"])
            elif launcher["type"] == "NotifyRun":
                launcher = NotifyRunLauncher(launcher["config"])
            elif launcher['type'] == "Telegram":
                launcher = TelegramLauncher(launcher['config'])
            else:
                launcher = InvalidLauncher()

            self.append(
                User(username, launcher, is_active, is_superuser, is_staff,
                     email, services))

        self.logger.debug('Users loaded')
        return self