Exemple #1
0
def action_showdb():
  """
  Show the contents of the local database.
  """
  from src.database import Database
  from src.routes import app
  ctx = app.test_request_context()
  ctx.push()
  db = Database(app)
  db._show_contents()
Exemple #2
0
def action_initdb():
  """
  Clears the local database.
  """
  from src.database import Database
  from src.routes import app
  ctx = app.test_request_context()
  ctx.push()
  db = Database(app)
  db._drop_contents()
  print 'NOTICE: Successfully cleared local amphoros database.'
Exemple #3
0
    def delete_mail(self):
        '''
        This method deletes the e-mail from the database and calls the method to delete the e-mail from
        the server as well.

        :return:
        '''
        db = Database()
        db.delete_mail(self.em)
        CommunicationController.delete_mail(self.em)
        self.inbox.scheduled_mail_check("lolno")
 def from_mongo(cls, id):
     blog_data=Database.find_one(collection='blogs', query={'id':id})
     return cls(author=blog_data['author'],
                 title=blog_data['title'],
                 description=blog_data['description'],
                 id=blog_data['id']
                 )
 def setUp(self):
     self.db = Database()
     self.db.createUser("testUserRealName", IntegrationTest.TestUserName, "testUserPassword0$")
     self.game = Game()
     self.game.username = IntegrationTest.TestUserName
     self.game.loginWidget.loggedUsername = IntegrationTest.TestUserName
     self.game.showBoard(1)
 def __init__(self, **kwargs):
     super(OutboxLayout, self).__init__(**kwargs)
     self.counter = 0
     self.mails = []
     self.nRead = 0
     self.db = Database()
     Clock.schedule_once(self.scheduled_mail_check, 0)
     Clock.schedule_interval(self.scheduled_mail_check, 60)
 def _user_has_account(self):
     blog = Database.find_one('blogs', {'author': self.user})
     if blog is not None:
         #self.user_blog = blog #This would work however returning the object is better for this case
         self.user_blog = Blog.from_mongo(blog['id'])
         return True
     else:
         return False
 def from_mongo(cls, id):
     post_data = Database.find_one(collection='posts', query={'id': id})
     return cls(blog_id=post_data['blog_id'],
                title=post_data['title'],
                content=post_data['content'],
                author=post_data['author'],
                date=post_data['created_date'],
                id=post_data['id'])
class TestDatabase(TestCase):
    def setUp(self):
        self.database = Database(":memory:")

    def test_query(self):
        query = self.database.query("INSERT INTO commands VALUES (%(name)s, %(command)s, %(server)s)")
        self.assertEqual("INSERT INTO commands VALUES (:name, :command, :server)", query)

        self.database.sql_type = SQLType.postgres
        query = self.database.query("INSERT INTO commands VALUES (%(name)s, %(command)s, %(server)s)")
        self.assertEqual("INSERT INTO commands VALUES (%(name)s, %(command)s, %(server)s)", query)

    def test_table(self):
        table = self.database.table("commands")
        self.assertEqual("`commands`", table)

        self.database.sql_type = SQLType.postgres
        table = self.database.table("commands")
        self.assertEqual("\"commands\"", table)
Exemple #10
0
 def __init__(self, **kwargs):
     super(InboxLayout, self).__init__(**kwargs)
     self.counter = 0
     self.mails = []
     self.contacts = []
     self.nRead = 0
     self.db = Database()
     self.emailsPerPage = self.db.get_settings("nbr_mails")
     self.all_emails_text = "Show only not read e-mails"
     print type(self.all_emails_text)
     Clock.schedule_once(self.scheduled_mail_check, 0)
     Clock.schedule_interval(self.scheduled_mail_check, 60)
    def save_credentials(self, event):
        '''
        This method tries to connect to the server using the given information and (if successful)
        stores the gained data in the Inbox table of the database. This is used by the program to
        communicate with the server.

        :param event: no used, still passed by the callback
        :return:
        '''
        email = self.emailAddress.text
        password = self.password.text

        try:
            imapCon = imaplib.IMAP4_SSL(clunkyConfig[self.provider]["IMAP"]["host"])
            account = string.split(email, '@')[0]
            if(self.provider == 1):
                imapCon.login(account, password)
            else:
                imapCon.login(email, password)
            db = Database()
            db.create_inbox("test", "test", email, account, password,
                           clunkyConfig[self.provider]["IMAP"]["host"], clunkyConfig[self.provider]["SMTP"]["host"],
                           clunkyConfig[self.provider]["IMAP"]["port"], clunkyConfig[self.provider]["SMTP"]["port"],
                           clunkyConfig[self.provider]["IMAP"]["ssl"], clunkyConfig[self.provider]["SMTP"]["ssl"],
                           clunkyConfig[self.provider]["SMTP"]["auth"])
            db.close()
            imapCon.logout()
            self.parent.killMe()
            # we are still logged in, right?
        except imaplib.IMAP4.error as e:
            content = Button(text='Ein Fehler ist aufgetreten. \n Hier klicken, um es nocheinmal zu versuchen')
            popup = Popup(title='Error!', content=content,
                          size_hint=(None, None), size=(400, 400),
                          background="GUI/Icons/white_bg_400x400.png",
                          title_color=(0,0,0,1))
            content.bind(on_press=popup.dismiss)
            popup.open()
            print(e)
    def delete_mail(mail):
        '''
        This method takes an email-object, adds the flag "\\Deleted" and sends it to the server.
        The IMAP server then deletes the mail.

        :param mail: The mail to be deleted.
        :type: Mails
        :return:
        '''

        # open database connection and get credentials
        db = Database()
        inbox = db.get_inbox()
        try:
            # establish IMAP Connection
            imap_con = imaplib.IMAP4_SSL(inbox.imapServer, int(inbox.imapPort))

            if inbox.imapServer=="imap.web.de":
                emailAddress = inbox.account
            else:
                emailAddress = inbox.userMail

            password = inbox.password

            imap_con.login(emailAddress, password)
            imap_con.select('Inbox')

            search_query = '(HEADER message-id %s)' % mail.remoteID

            typ, data = imap_con.search(None, search_query)

            imap_con.store(data[0], '+FLAGS', '\\Deleted')
            imap_con.expunge()
            imap_con.close()
            db.close()
            imap_con.logout()
        except imaplib.IMAP4.error as e:
            print(e)
class IntegrationTest(unittest.TestCase):
    app = None

    TestUserName = "******"

    @classmethod
    def setUpClass(cls):
        global app
        app = QtGui.QApplication([])

    def setUp(self):
        self.db = Database()
        self.db.createUser("testUserRealName", IntegrationTest.TestUserName, "testUserPassword0$")
        self.game = Game()
        self.game.username = IntegrationTest.TestUserName
        self.game.loginWidget.loggedUsername = IntegrationTest.TestUserName
        self.game.showBoard(1)

    def tearDown(self):
        self.db.deleteAccount(IntegrationTest.TestUserName)
        self.game.board_widget.stopTimers()
        self.game.board_widget.statusBar.destroy()
        self.game.board_widget.exit()
        self.game.board_widget.destroy()
        self.game.destroy()

    @classmethod
    def tearDownClass(cls):
        app.quit()

    def testKillEnemiesOnBoardUpdateDb(self):
        self.assertTrue(self.db.hasUser(IntegrationTest.TestUserName))

        self.game.board_widget.level.clearEnemies()
        self.game.board_widget.setTileAt(2, 1, Tile.Balloom)
        self.game.board_widget.level.bomberman.curX = 1
        self.game.board_widget.level.bomberman.curY = 1
        self.game.board_widget.level.setBomberman()
        self.game.board_widget.level.setBomb()

        tempList = [2, 1, constant.DIRECTION_WEST, Tile.Balloom]
        self.game.board_widget.level.listEnemies.append(tempList)

        self.game.board_widget.level.numberEnemies = 1
        self.game.board_widget.level.listTypeEnemies[0] = 1
        self.game.board_widget.level.bomberman.rangeOfBombs = 3

        self.game.board_widget.detonateBomb()

        self.assertEqual(self.game.board_widget.tileAt(2, 1), Tile.Empty, "Bomb detonation did not kill enemy")
        self.assertEqual(0, self.game.board_widget.level.numberEnemies, "Enemy was not removed from map")

        self.assertEqual(self.db.getUserAccount(IntegrationTest.TestUserName)['cumulativeScore'], 100)
Exemple #14
0
class Bot:
    def __init__(self):
        self.__db = Database('database.db')
        self.__updater = Updater(
            token=env.telegram_bot_token)  # Токен API к Telegram
        self.__dispatcher = self.__updater.dispatcher
        self.__gsheet = GoogleSpreadsheetReader()
        handlers = self.get_handlers()

        self.__dispatcher.add_handler(CommandHandler('start', self.logger), -2)
        self.__dispatcher.add_handler(MessageHandler(Filters.all, self.logger),
                                      -2)
        self.__dispatcher.add_handler(
            CallbackQueryHandler(self.logger, pattern=''), -2)

        # https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.dispatcher.html
        self.__dispatcher.add_handler(
            MessageHandler(Filters.text, self.check_user_auth_handler), -1)
        self.__dispatcher.add_handler(
            CallbackQueryHandler(self.check_user_auth_handler, pattern=''), -1)

        self.__dispatcher.add_error_handler(self.error_handler)
        for handler in handlers:
            self.__dispatcher.add_handler(handler, 0)

    def logger(self, bot, update):
        user_id = self.get_chat_id_by_update(update)
        message = self.get_message_by_update(update)
        callback = self.get_callback_by_update(update)
        now = datetime.datetime.now(
            datetime.timezone.utc) + datetime.timedelta(hours=2)  # UTC + 2
        self.__db.execute(
            """
                INSERT INTO activity_log(user_id, callback, message, update_query, when_created)
                VALUES(?, ?, ?, ?, ?)
            """, user_id, callback, message, str(update),
            now.strftime('%Y-%m-%d %H:%M:%S'))

    def error_handler(self, bot, update, error):
        chat_id = self.get_chat_id_by_update(update)
        error_message = 'error: '
        try:
            raise error
        except Unauthorized:
            # remove update.message.chat_id from conversation list
            error_message += 'Unauthorized'
        except BadRequest:
            # handle malformed requests - read more below!
            error_message += 'BadRequest'
        except TimedOut:
            # handle slow connection problems
            error_message += 'TimedOut'
        except NetworkError:
            # handle other connection problems
            error_message += 'NetworkError'
        except ChatMigrated as e:
            # the chat_id of a group has changed, use e.new_chat_id instead
            error_message += str(e)
        except TelegramError:
            # handle all other telegram related errors
            error_message += 'TelegramError'

        bot.send_message(chat_id=chat_id, text=error_message)

    def get_db_user(self,
                    phone_number='',
                    first_name='',
                    last_name='',
                    user_id=''):
        result = self.__db.execute(
            """
                SELECT 
                    users.user_id,
                    users.phone_number,
                    users.first_name,
                    users.last_name
                FROM users
                WHERE 1=1
                    AND (
                        users.phone_number = ?
                        OR users.first_name = ?
                        OR users.last_name = ?
                        OR users.user_id = ?
                    )         
            """, phone_number, first_name, last_name, user_id).fetchall()

        if len(result):
            for row in result:
                return {
                    'user_id': row['user_id'],
                    'phone_number': row['phone_number'],
                    'first_name': row['first_name'],
                    'last_name': row['last_name']
                }

        return None

    def is_user_authenticated(self, user_id):
        result = self.__db.execute(
            """
                SELECT users.user_id
                FROM users
                WHERE 1=1
                    AND users.user_id = ?
                    AND users.when_authorized > date('now','-7 days')            
            """, user_id).fetchall()
        return len(result) != 0

    def get_message_by_update(self, update):
        try:
            message = update['message']['text']
        except Exception as e:
            message = ''

        return message

    def get_callback_by_update(self, update):
        try:
            callback = update['callback_query']['data']
        except Exception as e:
            callback = ''

        return callback

    def get_chat_id_by_update(self, update):
        try:
            chat_id = update['callback_query']['message']['chat']['id']
        except Exception as e:
            chat_id = update['message']['chat']['id']

        return chat_id

    def check_user_auth_handler(self, bot, update):
        user_id = chat_id = self.get_chat_id_by_update(update)

        db_user = self.get_db_user(user_id=user_id)
        user_is_authenticated = False if db_user is None else self.is_user_authenticated(
            user_id)

        if db_user is not None:
            spreadsheet_record = self.__gsheet.get_record_by_condition(
                'Name',
                db_user['first_name'] + ' ' + db_user['last_name'])  # By name

        if not user_is_authenticated or self.get_db_user(
                phone_number=spreadsheet_record['Phone number']) is None:
            bot.send_message(chat_id=chat_id,
                             text='Authentication required',
                             reply_markup=self.authenticate_keyboard())
            raise DispatcherHandlerStop

    def authenticate_keyboard(self):
        keyboard = [[
            KeyboardButton('Authenticate',
                           request_contact=True,
                           callback_data='authenticate')
        ]]

        return ReplyKeyboardMarkup(keyboard,
                                   resize_keyboard=True,
                                   one_time_keyboard=True)

    @send_typing_action
    def start_handler(self, bot, update):
        update.message.reply_text('Authentication required',
                                  reply_markup=self.authenticate_keyboard())

    def main_menu_handler(self, bot, update):
        query = update.callback_query
        bot.edit_message_text(chat_id=query.message.chat_id,
                              message_id=query.message.message_id,
                              text=self.main_menu_message(),
                              reply_markup=self.main_menu_keyboard())
        raise DispatcherHandlerStop

    def get_emoji(self, emoji):
        return config_global.emojis[emoji]

    def get_about_info(self):
        return env.about['info']

    def get_about_website(self):
        return env.about['website']

    '''
    how to avoid auth frauds: https://groosha.gitbooks.io/telegram-bot-lessons/content/chapter9.html
    +
    Compare user_id from contact with chat_id of user, who sent this contact
    '''

    @send_typing_action
    def authenticate_handler(self, bot, update):
        contact = update.message.contact
        chat_id = update.message.chat.id
        spreadsheet_record = self.__gsheet.get_record_by_condition(
            'Phone number', contact.phone_number)

        existing_user_by_phone_number = self.get_db_user(
            phone_number=contact.phone_number)

        # If phone number not found in spreadsheet or someone else is trying to access data of other user
        if spreadsheet_record is None or (
                existing_user_by_phone_number is not None
                and existing_user_by_phone_number['user_id'] != chat_id):
            bot.send_message(chat_id=chat_id, text='Access denied')
            raise DispatcherHandlerStop
        # Change phone number how-to: https://telegram.org/blog/telegram-me-change-number-and-pfs

        spreadsheet_record_full_name = str(spreadsheet_record['Name']).strip()
        try:
            spreadsheet_record_first_name, spreadsheet_record_last_name = spreadsheet_record_full_name.split(
            )
        except ValueError:
            bot.send_message(
                chat_id=chat_id,
                text=
                f'Invalid name format. Expected <Name Surname>, got <{spreadsheet_record_full_name}>'
            )
            raise DispatcherHandlerStop
        spreadsheet_record_phone_number = str(
            spreadsheet_record['Phone number']).strip()

        if spreadsheet_record_phone_number == contact.phone_number:
            if self.get_db_user(
                    first_name=spreadsheet_record_first_name,
                    last_name=spreadsheet_record_last_name) is None:
                self.__db.execute(
                    """
                        INSERT INTO users(first_name, last_name, phone_number, user_id)
                        VALUES(?, ?, ?, ?)
                    """, spreadsheet_record_first_name,
                    spreadsheet_record_last_name, contact.phone_number,
                    contact.user_id)
                bot.send_message(chat_id=chat_id,
                                 text='You have been registered')

            self.__db.execute(  # refresh user data
                """
                    UPDATE users
                    SET 
                        phone_number = ?,
                        when_authorized = datetime('now')
                    WHERE users.user_id = ?
                """, spreadsheet_record_phone_number, chat_id)
            '''
            bot.send_message(
                chat_id=chat_id,
                text=f'Received Contact: {contact}',
            )
            '''
            bot.send_message(chat_id=chat_id,
                             text=self.main_menu_message(),
                             reply_markup=self.main_menu_keyboard())
            self.main_menu_handler(bot, update)

            raise DispatcherHandlerStop

    def day_offs_menu_handler(self, bot, update):
        query = update.callback_query
        bot.edit_message_text(chat_id=query.message.chat_id,
                              message_id=query.message.message_id,
                              text=self.main_menu_message(),
                              reply_markup=self.day_offs_menu_keyboard())

    def day_offs_mine_handler(self, bot, update):
        db_user = self.get_db_user(
            user_id=update.callback_query.message.chat_id)
        spreadsheet_record = self.__gsheet.get_record_by_condition(
            'Phone number', db_user['phone_number'])

        text = f'You have {spreadsheet_record["Day-offs"]} day-offs left'

        query = update.callback_query
        bot.answer_callback_query(callback_query_id=query.id,
                                  text=text,
                                  show_alert=True)

    @send_typing_action
    def day_offs_paid_handler(self, bot, update):
        query = update.callback_query

        this_year_day_offs = env.paid_day_offs
        text = '*Paid day-offs:*\n' + '\n'.join([
            f'{holiday} - {this_year_day_offs[holiday]}'
            for holiday in this_year_day_offs
        ])

        bot.edit_message_text(chat_id=query.message.chat_id,
                              message_id=query.message.message_id,
                              text=text,
                              parse_mode='Markdown',
                              reply_markup=InlineKeyboardMarkup(
                                  build_menu(
                                      buttons=[self.get_main_menu_button()],
                                      n_cols=1)))

    @send_typing_action
    def help_handler(self, bot, update):
        query = update.callback_query
        text = env.help_text
        bot.edit_message_text(chat_id=query.message.chat_id,
                              message_id=query.message.message_id,
                              text=text,
                              parse_mode='Markdown',
                              reply_markup=InlineKeyboardMarkup(
                                  build_menu(
                                      buttons=[self.get_main_menu_button()],
                                      n_cols=1)))

    def salary_handler(self, bot, update):
        db_user = self.get_db_user(
            user_id=update.callback_query.message.chat_id)
        spreadsheet_record = self.__gsheet.get_record_by_condition(
            'Phone number', db_user['phone_number'])

        query = update.callback_query
        bot.answer_callback_query(callback_query_id=query.id,
                                  text=spreadsheet_record['Salary'],
                                  show_alert=True)

    def currency_handler(self, bot, update):
        query = update.callback_query

        try:
            today = datetime.datetime.today()
            today_exchange_rate = get_exchange_rate(47, today)  # EUR
            last_day_of_prev_month = today.replace(day=1) - datetime.timedelta(
                days=1)
            prev_month_exchange_rate = get_exchange_rate(
                47, last_day_of_prev_month)  # EUR
            text = f"{prev_month_exchange_rate} -> {today_exchange_rate}"
        except ConnectionError as e:
            text = "Could not connect to server. Try again later"
        except IndexError as e:
            text = "Error: unexpected API response. Please, contact responsible IT rep to fix this problem"
        except Exception as e:
            text = "Error. Please, contact responsible IT rep to fix this problem"

        bot.answer_callback_query(callback_query_id=query.id,
                                  text=text,
                                  show_alert=True)

    @send_typing_action
    def about_us_handler(self, bot, update):
        bot.send_photo(chat_id=update.callback_query.message.chat_id,
                       caption=self.get_about_info(),
                       photo=open('assets/logo.png', 'rb'),
                       reply_markup=InlineKeyboardMarkup(
                           build_menu(buttons=[self.get_website_link_button()],
                                      n_cols=1)))

    def main_menu_message(self):
        return 'Choose an option:'

    @send_typing_action
    def text_message_handler(self, bot, update):
        bot.send_message(chat_id=update.message.chat_id,
                         text="Direct messaging doesn't work yet")

    def main_menu_keyboard(self):
        header_buttons = [
            InlineKeyboardButton(self.get_emoji('palm_tree') + ' Day-offs',
                                 callback_data='day_offs_menu'),
        ]

        keyboard = [
            InlineKeyboardButton(self.get_emoji('euro_banknote') + ' Salary',
                                 callback_data='salary'),
            InlineKeyboardButton(self.get_emoji('chart_upwards') + ' Currency',
                                 callback_data='currency'),
            InlineKeyboardButton(self.get_emoji('about') + ' About us',
                                 callback_data='about_us'),
            InlineKeyboardButton(self.get_emoji('raised_hand') + ' Help',
                                 callback_data='help'),
        ]
        return InlineKeyboardMarkup(
            build_menu(buttons=keyboard,
                       header_buttons=header_buttons,
                       n_cols=2))

    def day_offs_menu_keyboard(self):
        keyboard = [
            InlineKeyboardButton(self.get_emoji('airplane') + ' My day-offs',
                                 callback_data='day_offs_mine'),
            InlineKeyboardButton(self.get_emoji('snowman') + ' Paid day-offs',
                                 callback_data='day_offs_paid'),
        ]
        return InlineKeyboardMarkup(
            build_menu(buttons=keyboard,
                       footer_buttons=[self.get_main_menu_button()],
                       n_cols=2))

    def get_main_menu_button(self):
        return InlineKeyboardButton(self.get_emoji('back') + ' Main menu',
                                    callback_data='main')

    def get_website_link_button(self):
        return InlineKeyboardButton('Website', url=self.get_about_website())

    def get_handlers(self):
        return [
            MessageHandler(Filters.text, self.text_message_handler),
            CommandHandler('start', self.start_handler),
            # CallbackQueryHandler(authenticate, pattern='authenticate'),
            MessageHandler(Filters.contact, self.authenticate_handler),
            CallbackQueryHandler(self.main_menu_handler, pattern='main'),
            CallbackQueryHandler(self.day_offs_menu_handler,
                                 pattern='day_offs_menu'),
            CallbackQueryHandler(self.day_offs_mine_handler,
                                 pattern='day_offs_mine'),
            CallbackQueryHandler(self.day_offs_paid_handler,
                                 pattern='day_offs_paid'),
            CallbackQueryHandler(self.salary_handler, pattern='salary'),
            CallbackQueryHandler(self.currency_handler, pattern='currency'),
            CallbackQueryHandler(self.about_us_handler, pattern='about_us'),
            CallbackQueryHandler(self.help_handler, pattern='help'),
        ]

    def idle(self):
        # Начинаем поиск обновлений
        self.__updater.start_polling(clean=True)
        # Останавливаем бота, если были нажаты Ctrl + C
        self.__updater.idle()
 def __init__(self, **kwargs):
     super(AddressLayout, self).__init__(**kwargs)
     self.contacts = []
     self.counter = 0
     self.db = Database()
     self.contsPerPage = self.db.get_settings("nbr_addresses")
Exemple #16
0
# joined_attrs = {
#     ('A', 'B'): ('id', 'id'), ('B', 'A'): ('id', 'id'),
#     ('C', 'B'): ('id', 'id2'), ('B', 'C'): ('id2', 'id'),
#     ('C', 'D'): ('id2', 'id'), ('D', 'C'): ('id', 'id2')
# }
#
# # A map of aliases and the relations they refer to
# alias_to_tables = {
#     'A': ['A'],
#     'B': ['B'],
#     'C': ['C'],
#     'D': ['D']
#     # e.g. 'J1': {"A", "B"} etc
# }

db = Database(False)

s = {}

s["aka_title"] = 1
s["char_name"] = 1
s["role_type"] = 1

s["comp_cast_type"] = 1
s["movie_link"] = 2
s["link_type"] = 1
s["cast_info"] = 4

s["complete_cast"] = 2
s["title"] = 9
s["aka_name"] = 2
Exemple #17
0
 def getPlayer(i):
     name = Database.getPlayerName(i)
     if name == 0:
         return None
     else:
         return Player(i, name)
Exemple #18
0
class DBManager():
    def __init__(self):
        self.database = Database()

    # adds user to the database after hashing the password
    # prevents an unsecured password from being entered in
    def add_user(self, first_name, last_name, email_address, password):
        hashedpw = self._hash_pw(password.encode('utf-8'))
        user = User(first_name, last_name, email_address, hashedpw)
        self.database._add_user(user)

    # adds a bill to the database from html
    def add_bill(self, date_added, electricity, gas, internet, city,
                 total_per_user, total, due_date):
        bill = Bills(date_added, electricity, gas, internet, city,
                     total_per_user, total, due_date)
        self.database._add_bill(bill)

    def check_email_availability(self, email):
        email = self.database._validate_user_email(email)
        return email

    # validates the users password against their email
    # by retrieving the hashed password, then checking
    # the password entered by the user
    def auth_user(self, email, password):
        try:
            hashedpassword = self.database._validate_user_password(email)
            check = bcrypt.checkpw(password.encode('utf-8'),
                                   hashedpassword.encode('utf-8'))
            if check is True:
                return True
            else:
                return False
        except AttributeError:
            return False

    # hashes the users password using bcrypt
    def _hash_pw(self, password):
        hashedpw = bcrypt.hashpw(password, bcrypt.gensalt())
        hashedpw = hashedpw.decode('utf-8')
        return hashedpw

    # retrieves bills from the database
    def _get_bills(self):
        bills = self.database._get_bills()
        return bills

    # retrieves billID from database
    def _get_billID(self, date_added):
        billID = self.database._get_billID(date_added)
        return billID

    # gets the users level from the database
    def _get_user_level(self, email):
        user_level = self.database._check_user_level(email)
        return user_level

    # gets users name
    def _get_name(self, email):
        user_name = self.database._get_users_name(email)
        return user_name

    def _get_user_count(self):
        count = self.database._count_users()
        return count
Exemple #19
0
 def getAll():
     return Database.find('email_subscriptions', {})
 def all_from_mongo():
     return [post for post in Database.find_all(collection='posts')]
Exemple #21
0
    def __init__(self, token, dm_id):
        self.db = Database('rolls.db')
        self.dm = dm_id

        self.bot = telepot.Bot(token)
        self.bot.message_loop(self.handle)
Exemple #22
0
import psycopg2
from src.database import Database
from src.instagram_bot import InstagramBot
import environ


env = environ.Env()
environ.Env.read_env(env_file='.env')

USERNAME = env.str('USERNAME')
PASSWORD = env.str('PASSWORD')
conn = psycopg2.connect(
    dbname=env.str('DBNAME'),
    user=env.str('DBUSER'),
    password=env.str('DBPASSWORD'),
    host=env.str('DBHOST'),
    port=env.str('DBPORT'))
cursor = conn.cursor()

db = Database(cursor, conn, USERNAME)
bot = InstagramBot(USERNAME, PASSWORD, USERNAME, db)
bot.run()
Exemple #23
0
def test_commit():
    with patch.object(sqlite3, 'connect', return_value=connection):
        db = Database(Mock())
        db.commit()

    connection.commit.assert_called_once()
Exemple #24
0
from flask import Flask, render_template, session, redirect, request, url_for, g
import requests
from src.database import Database
from src.twitter_utils import get_request_token, get_oauth_verifier_url, get_access_token
from src.user import User

app = Flask(__name__)
app.secret_key = 'JohnSnow'

Database.initialise(database="learning", host="localhost", user="******", password="******")


# Loads before every request
@app.before_request
def load_user():
    if 'screen_name' in session:
        g.user = User.load_db_by_screen_name(session['screen_name'])


@app.route('/')
def homepage():
    return render_template('home.html')


@app.route('/login/twitter')
def twitter_login():
    # Check to see if they are already logged in, and redirect to their profile
    if 'screen_name' in session:
        return redirect(url_for('profile'))

    # We need a request token 1st...
Exemple #25
0
 def retrieve_case(query):
     return Database.find(collection='previous_designs', query=query)
Exemple #26
0
 def save_to_mongo(self):
     Database.insert(collection='previous_designs', data=self.json())
Exemple #27
0
 def from_blog(_id):
     return [
         post for post in Database.find(collection="posts",
                                        query={"blog_id": _id})
     ]
import unittest
from src.database import Database
from src.user import User
db = Database('sqlite:///test.sqlite3')
user = User


class DatabaseTest(unittest.TestCase):
    def test_sqlite_orm_connection(self):
        self.assertTrue(db._get_connection())
        print('Connection Working')

    def test_orm_session_connection(self):
        self.assertTrue(db._get_session())
        print('Session Working')

    def test_database_add_user_using_orm(self):
        u1 = user('test', 'er', 'tester123', 'tester@email.', 'testersSecret')
        db.add_user(u1)
        self.assertTrue(db.get_user('tester123'))
        print('Adding User Working')


if __name__ == '__main__':
    unittest.main()
 def __init__(self, **kwargs):
     super(SettingsLayout, self).__init__(**kwargs)
     self.db = Database()
     Clock.schedule_once(self.initial_start, 0.5)
Exemple #30
0
 def save_to_mongo(self):
     Database.insert(collection='blogs', data=self.json())
Exemple #31
0
def get_db_stats() -> DatabaseStatsSchema:
    db = Database()
    matches = _get_stats("match", db)
    fighters = _get_stats("fighter", db)

    return DatabaseStatsSchema(matches=matches, fighters=fighters)
Exemple #32
0
 def get_by_author(cls, author):
     single_blog = Database.find_one(collection='blogs', query={'author': author})
     return cls(**single_blog)
Exemple #33
0
 def __init__(self):
     self.database = Database()
Exemple #34
0
 def __init__(self, **kwargs):
     super(WriteLayout, self).__init__(**kwargs)
     self.email = None
     self.db = Database()
     self.text_size = self.db.get_settings("font_size")
Exemple #35
0
 def delete(email):
     if email:
         Database.remove('email_subscriptions', {'email': email})
         return True
     return False
 def setUp(self):
     self.db = Database(True)
Exemple #37
0
 def get(self):
     db = Database()
     tm = db.get_telemetry()
     return tm.serialize()
Exemple #38
0
from flask import Flask, render_template, Response, request, jsonify, redirect
from werkzeug.utils import secure_filename
import json
import sys
import os

from src.database import Database

application = Flask(__name__)
application.config["UPLOAD_FOLDER"] = "src/static/assets"
user = None
db = Database()


@application.route("/", methods=["GET"])
def get_base():
    return redirect("/login")


@application.route("/login", methods=["GET"])
def get_login():
    global user

    user = None
    return render_template("login.html")


@application.route("/login-validation", methods=["GET"])
def validate_login():
    global user
Exemple #39
0
 def save_to_mongo(self):
     Database.insert(collection='posts', data=self.json())
Exemple #40
0
def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        g._database = Database()
    return g._database
 def from_blog(id):
     return [post for post in Database.find(collection='posts', query={'blog_id':id})] #Database.find(collection='posts', query={'blog_id':id}) returns a cursor
Exemple #42
0
 def from_mongo(cls, id):
     post_data = Database.find_one(collection='posts', query={'_id': id})
     return cls(**post_data)
 def setUp(self):
     self.database = Database(":memory:")
Exemple #44
0
 def from_blog(id):
     return [
         post for post in Database.find(collection='posts',
                                        query={'blog_id': id})
     ]
Exemple #45
0
 def get_data(cls):
     blog_data = Database.find(collection='blogs', query={})
     return blog_data
Exemple #46
0
def run() -> None:
    username = _get_environment_variable("USERNAME")
    oauth_token = _get_environment_variable("OAUTH_TOKEN")

    salty_db = Database(_get_environment_variable("DATABASE_PATH"))
    irc_bot = TwitchBot(username, oauth_token)

    current_match = None
    for message in irc_bot.listen():
        if isinstance(message, OpenBetMessage):
            logger.info(
                "New match. %s VS. %s. Tier: %s. Format: %s.",
                message.fighter_red,
                message.fighter_blue,
                message.tier,
                message.match_format,
            )
            salty_db.update_current_match(
                fighter_red=message.fighter_red,
                fighter_blue=message.fighter_blue,
                tier=message.tier,
                match_format=message.match_format,
            )
            if message.match_format != "exhibition":
                current_match = Match(message)
            else:
                current_match = None
        elif isinstance(message, OpenBetExhibitionMessage):
            logger.info(
                "New match. %s VS. %s. Format: exhibition",
                message.fighter_red,
                message.fighter_blue,
            )
            salty_db.update_current_match(
                fighter_red=message.fighter_red,
                fighter_blue=message.fighter_blue,
                match_format="exhibition",
            )
            current_match = None
        elif current_match:
            if isinstance(message, LockedBetMessage):
                success = current_match.update_locked(message)
                if success:
                    logger.info(
                        "Bets locked. %s ($%s). %s ($%s).",
                        message.fighter_red,
                        message.bet_red,
                        message.fighter_blue,
                        message.bet_blue,
                    )
            elif isinstance(message, WinMessage):
                success = current_match.update_winner(message)
                if success:
                    logger.info("Winner: %s.", message.winner)
                    try:
                        salty_db.new_match(current_match)
                    except ValueError:
                        logger.error(
                            "Failed to log current match. %s",
                            current_match.__dict__,
                            exc_info=True,
                        )
Exemple #47
0
class WriteLayout(Screen):

    """
    This method is used to handle the writing and sending of an e-mail.

    :param kwargs:
    """
    sendTo = ObjectProperty(None)
    subject = ObjectProperty(None)
    message = ObjectProperty(None)
    email = ObjectProperty()
    text_size = NumericProperty()

    def __init__(self, **kwargs):
        super(WriteLayout, self).__init__(**kwargs)
        self.email = None
        self.db = Database()
        self.text_size = self.db.get_settings("font_size")

    def on_email(self, instance, value):
        if self.email:
            self.display_email(value)
        else:
            self.sendTo.text = ""
            self.subject.text = ""
            self.message.text = ""

    def display_email(self, email):
        self.sendTo.text = email._from
        if len(email.subject) > 0:
            if not email.subject.startswith("Re:"):
                self.subject.text = "Re: " + email.subject
            else:
                self.subject.text = email.subject
        else:
            self.subject.text = ""
        self.message.text = self.format_reply_message(email) if len(email.message) > 0 else ""

    @staticmethod
    def format_reply_message(email):
        '''
        This method takes the message of the displayed e-mail and converts it to the usual Reply-Mail format.
        :return:
        '''
        if len(email.message) > 0:
            replyString = email.message.split("\n")
        else:
            replyString = ""
        if len(email._from) > 0:
            replyHeader = "\n>" + email._from + " wrote on " + email.date + ":\n>"
        else:
            replyHeader = ""
        return replyHeader +'\n>'.join(replyString)

    def send_mail(self):
        '''
        This method is used to get the information necessary to send an e-mail from the inbox,
        connects to the database and sends the information to the remote server. We have to differ
        between the offered providers.

        :return:
        '''
        WidgetManager.Instance().build_tree("a")

        if self.sendTo.text == "":
            content = GridLayout(cols=1)
            content.add_widget(Label(text="Please enter a message"))
            content.add_widget(Button(background_normal="GUI/Icons/iConfirm.png", size_hint=[None, None]))
            popup = Popup(title='Error!', content=content,
                          size_hint=(None, None), size=(400, 400),
                          background="GUI/Icons/white_bg_400x400.png",
                          title_color=(0,0,0,1))
            content.bind(on_release=popup.dismiss)
            popup.open()
        else:
            db = Database()
            inbox = db.get_inbox()
            if(inbox.smtpServer=="smtp.web.de"):
                dicti = {
                    'host': inbox.smtpServer,
                    'port': inbox.smtpPort,
                    'user': inbox.account,
                    'pw': inbox.password,
                    'ssl': inbox.smtpSSL
                }
            else:
                dicti = {
                    'host': inbox.smtpServer,
                    'port': inbox.smtpPort,
                    'user': inbox.userMail,
                    'pw': inbox.password,
                    'ssl': inbox.smtpSSL
                }
            try:
                test = SMTPSender(dicti)
                test.connect()
                test.send_mail(inbox.userMail, self.sendTo.text, self.subject.text, self.message.text, None)
                box = GridLayout(cols=1)
                anch1 = AnchorLayout(anchor_h="center")
                lbl = Label(text="Message successfully sent!", font_size=22, bold=True)
                anch1.add_widget(lbl)
                anch2 = AnchorLayout(anchor_h="center")
                butt = Button(background_normal="GUI/Icons/iConfirm.png", size_hint=[None, None])
                anch2.add_widget(butt)
                box.add_widget(anch1)
                box.add_widget(anch2)

                content = box
                popup = Popup(title='Success!', content=content,
                              size_hint=(None, None), size=(400, 400),
                              background="GUI/Icons/white_bg_400x400.png",
                              title_color=(0,0,0,1))
                content.bind(on_release=popup.dismiss)
                butt.bind(on_release=popup.dismiss)
                popup.open()
                self.message.text = ""
            except Exception as e:
                print e
                # probably make this Popup an own kv and class (reusable everytime something goes wrong?)
                content = GridLayout(cols=1)
                content.add_widget(Label(text="An error occurred.\nPlease try again"))
                butt = Button(background_normal="GUI/Icons/iConfirm.png", size_hint=[None, None])
                anch = AnchorLayout(align_h="center", size_hint=[None, None])
                anch.add_widget(butt)
                content.add_widget(anch)
                popup = Popup(title='Error!', content=content,
                              size_hint=(None, None), size=(400, 400),
                              background="GUI/Icons/white_bg_400x400.png",
                              title_color=(0,0,0,1))
                butt.bind(on_release=popup.dismiss)
                popup.open()
Exemple #48
0
class DiscordBot(discord.Client):
    def __init__(self, pretix_cache: PretixCache):
        super().__init__(intents=discord.Intents(
            members=True, messages=True, reactions=True))

        self._pretix_cache = pretix_cache
        self._database = Database()
        self._i18n = I18n(self._database)

    async def on_ready(self):
        print(f'Discord bot ready as {self.user}.')

        await self.guilds[0].fetch_roles()

    async def on_member_join(self, member: discord.Member):
        discord_username = self._get_discord_username(member)
        user_info = self._database.get_user_info(discord_username)
        if user_info.state == UserState.NEW:
            message = await member.send(
                self._i18n.get_text(discord_username, 'welcome'))
            await message.add_reaction(Emojis.FLAG_DE)
            await message.add_reaction(Emojis.FLAG_US)

            user_info.next_state()
            user_info.last_message_id = message.id
            self._database.set_user_info(discord_username, user_info)

            self._log(discord_username, user_info, 'Joined.')

    async def on_raw_reaction_add(self, payload):
        user = await self.fetch_user(payload.user_id)
        emoji = payload.emoji.name
        message_id = payload.message_id
        discord_username = self._get_discord_username(user)
        if user.id == self.user.id:
            return
        user_info = self._database.get_user_info(discord_username)
        if message_id != user_info.last_message_id:
            return
        if user_info.state == UserState.LANGUAGE_REQUESTED:
            language, lang_suffix, welcome_filename = None, None, None
            if emoji == Emojis.FLAG_DE:
                language = UserLanguage.GERMAN
                lang_suffix = 'de'
                welcome_filename = 'Willkommen.pdf'
            elif emoji == Emojis.FLAG_US:
                language = UserLanguage.ENGLISH
                lang_suffix = 'en'
                welcome_filename = 'Welcome.pdf'
            if language is not None:
                user_info.next_state()
                user_info.language = language
                self._database.set_user_info(discord_username, user_info)

                await user.send(
                    self._i18n.get_text(discord_username, 'language-set'))

                files = [
                    discord.File(f'files/welcome_{lang_suffix}.pdf',
                                 filename=welcome_filename),
                    discord.File(f'files/coc_{lang_suffix}.pdf',
                                 filename='Code_of_Conduct.pdf')
                ]
                message = await user.send(self._i18n.get_text(
                    discord_username, 'welcome-coc'),
                                          files=files)
                await message.add_reaction(Emojis.YES)
                await message.add_reaction(Emojis.NO)

                user_info.state = UserState.COC_REQUESTED
                user_info.last_message_id = message.id
                self._database.set_user_info(discord_username, user_info)
        elif user_info.state == UserState.COC_REQUESTED:
            coc_accepted = None
            if emoji == Emojis.YES:
                coc_accepted = True
            elif emoji == Emojis.NO:
                coc_accepted = False

            if coc_accepted is not None:
                if coc_accepted:
                    user_info.next_state()
                    self._database.set_user_info(discord_username, user_info)
                    await user.send(
                        self._i18n.get_text(discord_username, 'coc-accepted'))

                    order = self._pretix_cache.get_order(discord_username)
                    if order is None:
                        await self._ask_master_program(discord_username, user,
                                                       user_info)
                    else:
                        message = await user.send(
                            self._i18n.get_text(discord_username,
                                                'order-found-confirm',
                                                product=order.product,
                                                programs=order.programs))
                        await message.add_reaction(Emojis.YES)
                        await message.add_reaction(Emojis.NO)
                        user_info.next_state()
                        user_info.last_message_id = message.id
                        self._database.set_user_info(discord_username,
                                                     user_info)
                else:
                    user_info.state = UserState.COC_DECLINED
                    self._database.set_user_info(discord_username, user_info)
                    await user.send(
                        self._i18n.get_text(discord_username, 'coc-declined'))

                    self._log(
                        discord_username, user_info,
                        'DECLINED CODE OF CONDUCT! Enabling message log.')
                    self._database.mark_coc_decliner(user.id)
        elif user_info.state == UserState.ORDER_CONFIRM:
            confirmed = None
            if emoji == Emojis.YES:
                confirmed = True
            elif emoji == Emojis.NO:
                confirmed = False
            if confirmed is not None:
                if confirmed:
                    user_info.next_state()
                    self._database.set_user_info(discord_username, user_info)

                    order = self._pretix_cache.get_order(discord_username)
                    if order.product == Products.MASTER:
                        await self._assign_roles(discord_username, user,
                                                 user_info, order.product,
                                                 order.programs, False)
                else:
                    await self._ask_master_program(discord_username, user,
                                                   user_info)
        elif user_info.state == UserState.MANUAL_MASTER_PROGRAM_ASKED:
            await self._handle_master_program_reaction(discord_username, user,
                                                       user_info, emoji)

    async def on_raw_reaction_remove(self, payload):
        user = await self.fetch_user(payload.user_id)
        emoji = payload.emoji.name
        message_id = payload.message_id
        discord_username = self._get_discord_username(user)
        if user.id == self.user.id:
            return
        user_info = self._database.get_user_info(discord_username)
        if message_id != user_info.last_message_id:
            return
        if user_info.state == UserState.MANUAL_MASTER_PROGRAM_ASKED:
            await self._handle_master_program_reaction(discord_username,
                                                       user,
                                                       user_info,
                                                       emoji,
                                                       remove=True)

    async def on_message(self, message: discord.Message):
        if self._database.is_coc_decliner(message.author.id):
            print(
                f'Message from CoC decliner ({message.author}): <{message.content}> ({message.id})'
            )

        if message.content == 'yikes':
            await self.on_member_join(message.author)

    async def _ask_master_program(self, discord_username: str,
                                  user: Union[discord.Member, discord.User],
                                  user_info: UserInfo):
        message = await user.send(
            self._i18n.get_text(discord_username, 'ask-master-program'))
        await message.add_reaction(Emojis.ONE)  # AS
        await message.add_reaction(Emojis.TWO)  # DSS
        await message.add_reaction(Emojis.THREE)  # CS
        await message.add_reaction(Emojis.FOUR)  # DKE
        await message.add_reaction(Emojis.FIVE)  # IT-Sec
        await message.add_reaction(Emojis.SIX)  # VC

        user_info.state = UserState.MANUAL_MASTER_PROGRAM_ASKED
        user_info.last_message_id = message.id
        self._database.set_user_info(discord_username, user_info)

    async def _handle_master_program_reaction(self,
                                              discord_username: str,
                                              user: Union[discord.User,
                                                          discord.Member],
                                              user_info: UserInfo,
                                              emoji: str,
                                              remove=False):
        program = None
        if emoji == Emojis.ONE:
            program = Programs.AUTONOMOUS_SYSTEMS
        elif emoji == Emojis.TWO:
            program = Programs.DISTRIBUTED_SOFTWARE_SYSTEMS
        elif emoji == Emojis.THREE:
            program = Programs.GENERAL
        elif emoji == Emojis.FOUR:
            program = Programs.INTERNET_AND_WEBBASED_SYSTEMS
        elif emoji == Emojis.FIVE:
            program = Programs.IT_SECURITY
        elif emoji == Emojis.SIX:
            program = Programs.VISUAL_COMPUTING
        if program is not None:
            if remove:
                await self._remove_master_roles(user, [program])
            else:
                await self._assign_roles(discord_username,
                                         user,
                                         user_info,
                                         Products.MASTER, [program],
                                         False,
                                         finished=False)

    async def _assign_roles(self,
                            discord_username: str,
                            user: Union[discord.User, discord.Member],
                            user_info: UserInfo,
                            product: Optional[Products],
                            programs: Optional[List[Programs]],
                            programming_course: bool,
                            finished=True):
        roles = []
        if product == Products.MASTER:
            roles.append(MASTER_ERSTI_ROLE_ID)
        if programs is not None:
            for program in programs:
                roles.append(PROGRAMS_MAP[program])
        if programming_course:
            roles.append(PROGRAMMING_COURSE_ROLE_ID)

        guild = self.guilds[0]
        member = await guild.fetch_member(user.id)
        await member.add_roles(*[DiscordRole(role_id) for role_id in roles],
                               atomic=True)

        self._log(
            discord_username, user_info,
            'Assigned roles according to product %s, programs %s and pc %s.' %
            (str(product), str(programs), str(programming_course)))

        if finished:
            user_info.state = UserState.FINISHED
            self._database.set_user_info(discord_username, user_info)
            await user.send(
                self._i18n.get_text(discord_username, 'roles-assigned'))

            self._log(discord_username, user_info, 'Finished.')

    async def _remove_master_roles(self, user: Union[discord.User,
                                                     discord.Member],
                                   programs: List[Programs]):
        roles = []
        if programs is not None:
            for program in programs:
                roles.append(PROGRAMS_MAP[program])

        guild = self.guilds[0]
        member = await guild.fetch_member(user.id)
        await member.remove_roles(*[DiscordRole(role_id) for role_id in roles],
                                  atomic=True)

    def _get_discord_username(self, user: Union[discord.Member, discord.User]):
        return user.name + '#' + user.discriminator

    def _log(self, discord_username: str, user_info: UserInfo, msg: str):
        print('%s, %s: %s' % (discord_username, str(user_info), msg))
Exemple #49
0
    def send_mail(self):
        '''
        This method is used to get the information necessary to send an e-mail from the inbox,
        connects to the database and sends the information to the remote server. We have to differ
        between the offered providers.

        :return:
        '''
        WidgetManager.Instance().build_tree("a")

        if self.sendTo.text == "":
            content = GridLayout(cols=1)
            content.add_widget(Label(text="Please enter a message"))
            content.add_widget(Button(background_normal="GUI/Icons/iConfirm.png", size_hint=[None, None]))
            popup = Popup(title='Error!', content=content,
                          size_hint=(None, None), size=(400, 400),
                          background="GUI/Icons/white_bg_400x400.png",
                          title_color=(0,0,0,1))
            content.bind(on_release=popup.dismiss)
            popup.open()
        else:
            db = Database()
            inbox = db.get_inbox()
            if(inbox.smtpServer=="smtp.web.de"):
                dicti = {
                    'host': inbox.smtpServer,
                    'port': inbox.smtpPort,
                    'user': inbox.account,
                    'pw': inbox.password,
                    'ssl': inbox.smtpSSL
                }
            else:
                dicti = {
                    'host': inbox.smtpServer,
                    'port': inbox.smtpPort,
                    'user': inbox.userMail,
                    'pw': inbox.password,
                    'ssl': inbox.smtpSSL
                }
            try:
                test = SMTPSender(dicti)
                test.connect()
                test.send_mail(inbox.userMail, self.sendTo.text, self.subject.text, self.message.text, None)
                box = GridLayout(cols=1)
                anch1 = AnchorLayout(anchor_h="center")
                lbl = Label(text="Message successfully sent!", font_size=22, bold=True)
                anch1.add_widget(lbl)
                anch2 = AnchorLayout(anchor_h="center")
                butt = Button(background_normal="GUI/Icons/iConfirm.png", size_hint=[None, None])
                anch2.add_widget(butt)
                box.add_widget(anch1)
                box.add_widget(anch2)

                content = box
                popup = Popup(title='Success!', content=content,
                              size_hint=(None, None), size=(400, 400),
                              background="GUI/Icons/white_bg_400x400.png",
                              title_color=(0,0,0,1))
                content.bind(on_release=popup.dismiss)
                butt.bind(on_release=popup.dismiss)
                popup.open()
                self.message.text = ""
            except Exception as e:
                print e
                # probably make this Popup an own kv and class (reusable everytime something goes wrong?)
                content = GridLayout(cols=1)
                content.add_widget(Label(text="An error occurred.\nPlease try again"))
                butt = Button(background_normal="GUI/Icons/iConfirm.png", size_hint=[None, None])
                anch = AnchorLayout(align_h="center", size_hint=[None, None])
                anch.add_widget(butt)
                content.add_widget(anch)
                popup = Popup(title='Error!', content=content,
                              size_hint=(None, None), size=(400, 400),
                              background="GUI/Icons/white_bg_400x400.png",
                              title_color=(0,0,0,1))
                butt.bind(on_release=popup.dismiss)
                popup.open()
 def save_to_mongo(self):
     Database.insert(collection="blogs",
                     data=self.json())
class TestDatabase(unittest.TestCase):
    TestRealName = "Test User"
    TestValidUsername1 = "testUser1"
    TestValidUsername2 = "testUser2"
    TestValidRealname = "testRealName"
    TestInvalidUsernameEmpty = ""
    TestInvalidUsernameTooShort = "user1"
    TestValidPassword = "******"
    TestInvalidPasswordTooShort = "De@1"
    TestInvalidPasswordNoSpecial = "testPassword0"
    TestInvalidPasswordNoDigit = "testPassword$"
    TestInvalidPasswordNoUpper = "testpassword$0"
    TestInvalidPasswordNoLower = "TESTPASSWORD$0"

    def setUp(self):
        self.db = Database(True)

    def testCreateUser(self):
        self.assertFalse(self.db.hasUser(TestDatabase.TestValidUsername1))
        self.createTestUser1()
        self.assertTrue(self.db.hasUser(TestDatabase.TestValidUsername1))

    def testUpdateUserAccountWithExistingUsername(self):
        self.createTestUser1()
        self.createTestUser2()
        self.assertFalse(self.db.updateUserAccount(TestDatabase.TestValidUsername1, TestDatabase.TestValidUsername2, TestDatabase.TestValidRealname, TestDatabase.TestValidPassword))

    def testUpdateUserAccountWithValidCredentials(self):
        self.createTestUser1()
        self.assertFalse(self.db.hasUser(TestDatabase.TestValidUsername2))
        self.assertTrue(self.db.updateUserAccount(TestDatabase.TestValidUsername1, TestDatabase.TestValidUsername2, TestDatabase.TestValidRealname, TestDatabase.TestValidPassword))
        self.assertTrue(self.db.hasUser(TestDatabase.TestValidUsername2))

    def testIsValidUsername(self):
        self.assertTrue(self.db.isValidUsername(TestDatabase.TestValidUsername1))
        self.assertFalse(self.db.isValidUsername(TestDatabase.TestInvalidUsernameEmpty))
        self.assertFalse(self.db.isValidUsername(TestDatabase.TestInvalidUsernameTooShort))

    def testIsValidPassword(self):
        self.assertTrue(self.db.isValidPassword(TestDatabase.TestValidPassword))
        self.assertFalse(self.db.isValidPassword(TestDatabase.TestInvalidPasswordTooShort))
        self.assertFalse(self.db.isValidPassword(TestDatabase.TestInvalidPasswordNoSpecial))
        self.assertFalse(self.db.isValidPassword(TestDatabase.TestInvalidPasswordNoDigit))
        self.assertFalse(self.db.isValidPassword(TestDatabase.TestInvalidPasswordNoLower))
        self.assertFalse(self.db.isValidPassword(TestDatabase.TestInvalidPasswordNoUpper))

    def testGetTopTenUsers(self):
        self.db.createUserAccountsForDemo()
        users = self.db.getTopTenUsers()

        iter = users.__iter__()
        self.assertEqual(iter.__next__()['username'], "Demo05")
        self.assertEqual(iter.__next__()['username'], "Demo06")
        self.assertEqual(iter.__next__()['username'], "Demo07")
        self.assertEqual(iter.__next__()['username'], "Demo04")
        self.assertEqual(iter.__next__()['username'], "Demo03")
        self.assertEqual(iter.__next__()['username'], "Demo10")
        self.assertEqual(iter.__next__()['username'], "Demo09")
        self.assertEqual(iter.__next__()['username'], "Demo01")
        self.assertEqual(iter.__next__()['username'], "Demo02")
        self.assertEqual(iter.__next__()['username'], "Demo08")

    def testGetHighestUnlockedLevel(self):
        self.db.createUserAccountsForDemo()
        self.assertEqual(self.db.getHighestUnlockedLevel("Demo01"), 11)
        self.assertEqual(self.db.getHighestUnlockedLevel("Demo05"), 15)

        self.createTestUser1()
        self.assertEqual(self.db.getHighestUnlockedLevel(TestDatabase.TestValidUsername1), 1)

    def testUpdateUserScore(self):
        self.db.createUserAccountsForDemo()
        self.assertEqual(self.db.getUserAccount("Demo05")['cumulativeScore'], 16000)
        self.db.updateUserScore("Demo05", 0)
        self.assertEqual(self.db.getUserAccount("Demo05")['cumulativeScore'], 16000)
        self.db.updateUserScore("Demo05", 1000)
        self.assertEqual(self.db.getUserAccount("Demo05")['cumulativeScore'], 17000)

    def testUpdateNumGamesPlayed(self):
        self.createTestUser1()
        self.assertEqual(self.db.getUserAccount(TestDatabase.TestValidUsername1)['numGamesPlayed'], 0)
        self.db.incrementNumOfGamesPlayed(TestDatabase.TestValidUsername1)
        self.assertEqual(self.db.getUserAccount(TestDatabase.TestValidUsername1)['numGamesPlayed'], 1)

    def createTestUser1(self):
        self.db.createUser(TestDatabase.TestRealName, TestDatabase.TestValidUsername1, TestDatabase.TestInvalidPasswordNoSpecial)

    def createTestUser2(self):
        self.db.createUser(TestDatabase.TestRealName, TestDatabase.TestValidUsername2, TestDatabase.TestInvalidPasswordNoSpecial)
    def from_mongo(cls, _id):
        blog_data = Database.find_one(collection="blogs",
                                      query={"_id": _id})

        return cls(**blog_data)
class AddressLayout(Screen):
    grid = ObjectProperty()
    pageCount = StringProperty()

    def __init__(self, **kwargs):
        super(AddressLayout, self).__init__(**kwargs)
        self.contacts = []
        self.counter = 0
        self.db = Database()
        self.contsPerPage = self.db.get_settings("nbr_addresses")

    def on_grid(self, instance, value):
        '''
        This method is an observer for the attribute self.grid.
        Since kivy is a young framework it can occur that the object grid is not properly set during the
        __init__ cycle. This method observes the object and triggers, if something changes. Usually the change
        is the correct instance of the spoken to GridLayout.

        :param instance:
        :param value:
        :return:
        '''

        # this only indicates the object is loaded properly
        # better set observer to datamodel as well
        self.get_contacts_from_db()

    def display_contacts(self):
        '''
        This method calculates how many contacts shall be added to the GridLayout, calculates the
        page indicator and calls the actual adding of the contact objects.

        :return:
        '''
        self.grid.clear_widgets()
        self.add_contacts(self.contacts[self.counter*self.contsPerPage:(self.counter+1)*self.contsPerPage])
        a = self.counter * self.contsPerPage
        a1 = a if self.counter == 0 else self.counter * self.contsPerPage + 1
        b = (self.counter + 1) * self.contsPerPage
        b1 = b if b < len(self.contacts) else len(self.contacts)
        c = len(self.contacts)
        self.pageCount = "%d - %d/%d" %(a1, b1, c)

    # see comments above add_emails in InboxLayout.py
    def add_contacts(self, contacts):
        '''
        This method adds the contacts given by the parameter "contacts" to the GridLayout.

        :param contacts: The contacts to be added to the Overview.
        :type [Contacts]: List of contacts
        :return:
        '''
        # counter = 0
        for v in contacts:
            if (contacts.index(v) % 2) != 0:
                item = ContactItem(v)
            else:
                item = ContactItem(v, colour=1)
            self.grid.add_widget(item)

    def get_contacts_from_db(self):
        '''
        This method gets all contacts from the database, stores them in the object-attribute "contacts"
        and calls the method to display all contacts stored in the attribute.

        :return:
        '''
        contacts = self.db.get_contacts()
        self.contacts = contacts
        self.display_contacts()

    def add_new_contact(self):
        '''
        This method is called when the user clicks the "Add contact" button in the bottom center.
        It opens up the necessary popup to fill in name and e-mail address of the new contact.

        :return:
        '''
        p = AddContactPopup(self.db, self)
        p.open()

    def delete_contact(self, contact):
        '''
        This method can be called from the contact item object of a certain contact object. The respective
        contact gets deleted from the database and the view is updated to the new data.

        :param contact:
        :return:
        '''
        self.db.delete_contact(contact)
        self.contacts.remove(contact)
        self.grid.clear_widgets()
        self.get_contacts_from_db()

    def previous_page(self):
        '''
        This method is used to switch through the pages of contacts.
        It turns one step backwards.

        :return:
        '''
        if self.counter > 0:
            self.counter -= 1
        else:
            self.counter = 0
        self.get_contacts_from_db()

    def next_page(self):
        '''
        This method is used to switch through the pages of contacts.
        It turns one step forward.

        :return:
        '''
        if ((self.counter+1) * self.contsPerPage) < len(self.contacts):
            self.counter += 1
        self.get_contacts_from_db()
Exemple #54
0
from src.config import config
from src.database import Database

database = Database(config)
database.migrate()
Exemple #55
0
class InboxLayout(Screen):

    """
    This class is the corresponding controller for the Inbox View.
    It manages the synchronisation with the server and the database.

    :param kwargs:
    """
    grid = ObjectProperty()
    pageCount = StringProperty()
    all_emails_text = StringProperty()

    def __init__(self, **kwargs):
        super(InboxLayout, self).__init__(**kwargs)
        self.counter = 0
        self.mails = []
        self.contacts = []
        self.nRead = 0
        self.db = Database()
        self.emailsPerPage = self.db.get_settings("nbr_mails")
        self.all_emails_text = "Show only not read e-mails"
        print type(self.all_emails_text)
        Clock.schedule_once(self.scheduled_mail_check, 0)
        Clock.schedule_interval(self.scheduled_mail_check, 60)

    def scheduled_mail_check(self, _):
        '''
        This method is called every 60 seconds to get new emails from the server and synchronize the view
        with the database.

        :param _: I have no idea what is going on here. Somehow I needed it, somehow I didn't.
        :return:
        '''
        CommunicationController.getEmailsFromServer()
        if self.nRead:
            self.mails = self.db.get_not_read_mails()
        else:
            self.mails = self.db.get_all_mails()
        self.display_emails()

    #the kivy properties don't always load properly
    #this method observes the property and triggers when it changes
    def on_grid(self, instance, value):
        '''
        This method is used to compensate the slowness of the framework. It is called when the grid attribute
        changes.

        :param instance: not used, but gets passed
        :param value: not used, but gets passed
        :return:
        '''
        self.display_emails()

    def get_emails_from_db(self):
        '''
        This method loads the emails from the database and returns them.
        A correct way of sorting the emails will come in the future.

        :return: emails: All e-mails found in the database.
        :rtype: [Emails]: List of Emails
        '''
        emails = self.db.get_all_mails()
        return emails

    def get_contacts_from_db(self):
        '''
        This method loads the contacts from the database and returns them.

        :return: contacts: All contacts found in the database.
        :rtype: [Contacts]: List of Contacts
        '''
        contacts = self.db.get_contacts()
        return contacts

    def display_emails(self):
        '''
        This method calculates the number of e-mails to be displayed, calls the add_emails method using
        that calculation and passes the right e-mails which ought to be displayed.
        Also the labeling for the page number is called.

        :return:
        '''
        self.grid.clear_widgets()
        currentMails = self.mails[self.counter*self.emailsPerPage:(self.counter+1)*self.emailsPerPage]
        self.add_emails(currentMails)
        self.set_page_count()
        WidgetManager.Instance().build_tree("a")

    # Parameter emails is a list of email objects as defined below
    def add_emails(self, emails):
        '''
        This method takes a list of emails and displays them in the Inbox View.

        :param emails: The emails to be displayed.
        :type [Emails]: A list of Emails
        :return:
        '''
        for v in emails:
            if (emails.index(v) % 2) != 0:
                item = EmailItem(v, self)
            else:
                item = EmailItem(v, self, colour=1)
            self.grid.add_widget(item)

    def previous_page(self):
        '''
        This method is used to switch through the available pages.
        It turns the counter one step backwards and refreshes the View.

        :return:
        '''
        if self.counter > 0:
            self.counter -= 1
        else:
            self.counter = 0
        self.display_emails()

    def next_page(self):
        '''
        This method is used to switch through the available pages.
        It turns the counter one step forward and refreshes the View.

        :return:
        '''
        if ((self.counter+1) * self.emailsPerPage) < (len(self.mails)):
            self.counter += 1
        self.display_emails()

    def set_page_count(self):
        '''
        This method is used to calculate how many e-mails are being display and how many are available.

        :return:
        '''
        a = self.emailsPerPage * self.counter + 1
        a1 = a if self.counter >= 1 else self.emailsPerPage * self.counter
        b = self.emailsPerPage * (self.counter + 1)
        c = len(self.mails)
        b1 = b if b < c else c
        self.pageCount = "%d - %d / %d" %(a1,b1,c)

    def toggle_selection(self):
        '''
        This methos is used to toggle between All and only Not-Read e-mails.

        :return:
        '''
        if self.nRead == 1:
            self.all_emails_text = "Show only not read e-mails"
            self.nRead = 0
        else:
            self.nRead = 1
            self.all_emails_text = "Show all e-mails"
        print self.all_emails_text
        self.scheduled_mail_check("lolno")
from src.models.Ship import Ship
from src.database import Database



ship1 = Ship(35, 200, 210, 30, 35, 10, 35000, 0, 0.7, 0.8, 0)

motion = ship1.calculate_motions()
res = ship1.calculate_resistance()
stab = ship1.calculate_stability()


print("Resistance is  " + str(round(ship1.total_resistance/1000)) + "  kN")
print("Max. vertical acceleration is  "+ str(round(ship1.max_vert_acceleration, 4)) + "  m/s/s")
print("KM is  " + str(round(ship1.km)) + "  m")

Database.initialize()
ship1.save_to_mongo()

# next thing is to code html for adding ships
class SettingsLayout(Screen):

    txt_colourblind = ObjectProperty()
    txt_nbr_mails = ObjectProperty()
    txt_nbr_addresses = ObjectProperty()
    txt_font_size = ObjectProperty()

    def __init__(self, **kwargs):
        super(SettingsLayout, self).__init__(**kwargs)
        self.db = Database()
        Clock.schedule_once(self.initial_start, 0.5)

    def initial_start(self, _):
        self.txt_colourblind.text = str(self.db.get_settings("colourblind_mode"))
        self.txt_font_size.text = str(self.db.get_settings("font_size"))
        self.txt_nbr_addresses.text = str(self.db.get_settings("nbr_addresses"))
        self.txt_nbr_mails.text = str(self.db.get_settings("nbr_mails"))

    def save_settings(self):
        # save the changes made
        print "Saving changes"
        self.db.edit_settings("colourblind_mode", int(self.txt_colourblind.text))
        self.db.edit_settings("nbr_mails", int(self.txt_nbr_mails.text))
        self.db.edit_settings("nbr_addresses", int(self.txt_nbr_addresses.text))
        self.db.edit_settings("font_size", int(self.txt_font_size.text))
        self.restart_program()

    def discard_changes(self):
        # set everything to the database state
        print "Reset settings"
        self.txt_colourblind.text = str(self.db.get_settings("colourblind_mode"))
        self.txt_font_size.text = str(self.db.get_settings("font_size"))
        self.txt_nbr_addresses.text = str(self.db.get_settings("nbr_addresses"))
        self.txt_nbr_mails.text = str(self.db.get_settings("nbr_mails"))

    def reset_program(self):
        # reset the entire database
        print "Reset database"
        self.db.reset_database()
        self.restart_program()

    @staticmethod
    def restart_program():
        # any cleanup has to be done before calling this method
        # it does not return
        python = sys.executable
        os.execl(python, python, * sys.argv)
Exemple #58
0
class App:
    """
        Application for filling and testing the database
    """
    def __init__(self):
        # Connect to the database
        self.database = Database(DB_NAME, DB_USER, DB_HOST, DB_PWD)
        self.database.connect_database()
        self.database.select_database()

        # Attributes for generating data
        self.vat_rates = VAT_RATES
        self.orders_lines = list()
        self.statutes_history = list()

    def init_db_structure(self, sql_file):
        """
            Reset or create the DB structure based on an SQL file
        """
        self.database.read_sql_file(sql_file)

    def insert_data_db(self):
        """
            Insert the random data in the database
        """
        self.database.insert_customers(Customer.customers)
        self.database.insert_restaurants(Restaurant.restaurants)
        self.database.insert_roles(Role.roles)
        self.database.insert_employees(Employee.employees)
        self.database.insert_ingredients(Ingredient.ingredients)
        self.database.insert_sizes(Size.sizes)
        self.database.insert_categories(Category.categories)
        self.database.insert_vat_rates(self.vat_rates)
        self.database.insert_pizzas(Pizza.pizzas)
        self.database.insert_stock(Stock.stocks)
        self.database.insert_recipes(Recipe.recipes_lines)
        self.database.insert_status(Status.status)
        self.database.insert_payments(Payment.payments)
        self.database.insert_payments_status(PaymentStatus.payments_status)
        self.database.insert_orders(Order.orders)
        self.database.insert_orders_lines(OrderLine.orders_lines)
        self.database.insert_status_history(StatusHistory.status_history)

    def random_data(self):
        """
            Create random data for the database
        """
        self.generate_simple('customers', CUSTOMERS_COUNT, Customer)
        self.generate_simple('pizzeria', RESTAURANTS_COUNT, Restaurant)
        self.generate_simple('roles', len(ROLES), Role, ROLES)
        self.generate_complex_while('employees for each restaurant',
                                    (EMPLOYEES_COUNT_MIN, EMPLOYEES_COUNT_MAX),
                                    Restaurant.restaurants,
                                    Employee,
                                    Role.roles)
        self.generate_simple('ingredients', INGREDIENTS_COUNT, Ingredient, INGREDIENTS_UNITS)
        self.generate_simple('sizes', SIZES_COUNT, Size)
        self.generate_simple('categories', CATEGORIES_COUNT, Category)
        self.generate_simple('pizzas', PIZZA_COUNT, Pizza, Category.categories, self.vat_rates)
        self.generate_complex('stock for each restaurant',
                              (Restaurant.restaurants, Ingredient.ingredients),
                              Stock)
        self.generate_complex('recipes for each pizza',
                              (Pizza.pizzas, Ingredient.ingredients),
                              Recipe,
                              random_choice=True)
        self.generate_simple('status for the orders', len(STATUS), Status, STATUS)
        self.generate_simple('payments types', PAYMENTS_TYPE_COUNT, Payment)
        self.generate_simple('payments status', PAYMENTS_STATUS_COUNT, PaymentStatus)
        self.generate_complex_while('order for each customer',
                                    (ORDERS_COUNT_MIN, ORDERS_COUNT_MAX),
                                    Customer.customers,
                                    Order,
                                    Restaurant.restaurants,
                                    Status.status,
                                    Payment.payments,
                                    PaymentStatus.payments_status)
        self.random_status_history()
        self.generate_complex_while('orders lines for each order',
                                    (ORDERS_LINES_COUNT_MIN, ORDERS_LINES_COUNT_MAX),
                                    Order.orders,
                                    OrderLine,
                                    Pizza.pizzas,
                                    Size.sizes)

    @staticmethod
    def generate_simple(data_name, count, klass, *args):
        """
            Generate data with a simple loop
        """
        progress_bar = f'Create {data_name}'
        progress_bar = FillingCirclesBar(progress_bar, max=count)
        i = 0
        while i < count:
            i += 1
            klass(LANG_CODE, *args)
            progress_bar.next()
        progress_bar.finish()

    @staticmethod
    def generate_complex(data_name, lists, klass, *args, random_choice=False):
        """
            Generate data with a double for loop
        """
        parents, children = lists
        progress_bar = f'Create {data_name}'
        progress_bar = FillingCirclesBar(progress_bar, max=len(parents))
        for parent in parents:
            for child in children:
                if random_choice:
                    if choice([True, False]):
                        klass(parent, child, *args)
                else:
                    klass(parent, child, *args)
            progress_bar.next()
        progress_bar.finish()

    @staticmethod
    def generate_complex_while(data_name, count, parents, klass, *args):
        """
            Generate data with a for and a while loops
        """
        count_min, count_max = count
        progress_bar = f'Create {data_name}'
        progress_bar = FillingCirclesBar(progress_bar, max=len(parents))
        for parent in parents:
            child_count = randrange(count_min, count_max)
            i = 0
            while i < child_count:
                i += 1
                klass(LANG_CODE, parent, *args)
            progress_bar.next()
        progress_bar.finish()

    @staticmethod
    def random_status_history():
        """
            Create random history for status
        """
        progress_bar = 'Create status histories for the orders'
        progress_bar = FillingCirclesBar(progress_bar, max=len(Order.orders))
        for i, order in enumerate(Order.orders):
            history_count = randrange(0, (len(STATUS) - 1))
            j = 0
            while j < history_count:
                j += 1
                StatusHistory(order)
                Order.orders[i].random_date()
                Order.orders[i].random_status(Status.status)
            progress_bar.next()
        progress_bar.finish()
from src.menu import Menu
from src.models.blog import Blog
from src.models.post import Post
from src.database import Database

__author__ = 'ibininja'

Database.initialize()

#post = Post(blog_id="125",
#            title="Healthy Banana",
#           content="This is the content of Healthy Banana name published articles....",
#            author="Mohamed")
#post.save_to_mongo()

#posts = Post.from_blog('125')
#for post in posts:
#    print(post)

#posts = Post.from_mongo('3782101c9d3d4e5eae511d8f3180f8d5')
#print(posts)

#This below is to test Blog
# blog = Blog(author="Ibrahim",
#             title="Sample Title",
#             description="Sample Description")
# blog.new_post()
# blog.save_to_mongo()
# from_database= Blog.from_mongo(blog.id)
# print(blog.get_posts())
Exemple #60
0
def initialize_database():
    Database.initialize()