示例#1
0
    def __init__(self):
        connection = database.create_connection()

        with connection:
            active_users = database.fetch_result(
                connection, Statements['SELECT_ALL_ACTIVITY_WITH_USERNAMES'])
            logger.debug(f'Active users fetched.')

        if self.active_users_cache is not None:
            return

        self.active_users_cache = {}

        if active_users is None:
            return

        if isinstance(active_users[0], str):
            active_users = {active_users}

        for active_user in active_users:
            user_id = active_user[0]
            chat_id = active_user[1]
            activity_timestamp = active_user[2]

            if chat_id not in self.active_users_cache:
                self.active_users_cache.update(
                    {chat_id: {
                        user_id: activity_timestamp
                    }})
            else:
                self.active_users_cache[chat_id].update(
                    {user_id: activity_timestamp})

        logger.info('Active users cache loaded.')
 def connect_to_db():
     """
     Method creates a connection to database
     :return: Connection object
     """
     database_path = os.path.expanduser(
         "~/Documents/LNUReader/ReaderDatabase.db")
     return db.create_connection(database_path)
示例#3
0
 def connect_to_db():
     """
     Method creates a connection to database
     :return: Connection object
     """
     path_to_db = os.path.expanduser("~/Documents/LNUReader")
     if not os.path.exists(path_to_db):
         os.makedirs(path_to_db)
     return db.create_connection(path_to_db + r'\ReaderDatabase.db')
示例#4
0
    def __init__(self, book):
        super().__init__()

        self.resize(250, 530)
        self.setWindowIcon(QIcon('../images/removeBook.ico'))
        self.setMinimumSize(250, 530)
        self.setMaximumSize(250, 530)

        self.book_key = book
        self.db_conn = db.create_connection(
            os.path.expanduser("~/Documents/LNUReader/ReaderDatabase.db"))

        self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint
                            | Qt.WindowTitleHint | Qt.WindowCloseButtonHint
                            | Qt.WindowStaysOnTopHint)

        # Main Widget
        self.mainQVBoxLayout = QVBoxLayout()
        self.mainQVBoxLayout.setContentsMargins(0, 10, 0, 0)

        # Categories
        self.categoriesQWidget = QWidget()
        self.categoriesQVBoxLayout = QVBoxLayout()
        self.categoriesQVBoxLayout.setContentsMargins(0, 20, 0, 0)
        self.categoriesQVBoxLayout.setSpacing(0)

        # Categories buttons
        self.categories = []
        self.favouritesQButton = QPushButton()

        # Buttons Menu
        self.buttonsMenu = QWidget()
        self.buttonsMenu.setObjectName('ButtonMenu')
        self.buttonsMenuQHBoxLayout = QHBoxLayout()
        self.buttonsMenuQHBoxLayout.setSpacing(0)
        self.buttonsMenuQHBoxLayout.setContentsMargins(0, 0, 0, 0)

        # Confirm and Decline Buttons
        self.acceptButton = QPushButton()
        self.acceptButton.setObjectName('FooterButton')
        self.acceptButton.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Fixed)
        self.acceptButton.clicked.connect(self.accept_additing)

        self.declineButton = QPushButton()
        self.declineButton.setObjectName('FooterButton')
        self.declineButton.setSizePolicy(QSizePolicy.Preferred,
                                         QSizePolicy.Fixed)
        self.declineButton.clicked.connect(self.decline_additing)

        self.currentActiveButton = None
        self.isAdded = False

        ColorsRegulator().set_colors(
            self, styles.Styles.set_add_to_ctg_dialog_style,
            night_styles.NightStyles.set_add_to_ctg_dialog_style)
        self.init_window()
示例#5
0
def move_to_main( coin_properties: CoinProperties, user, wallet_balance ):
    if wallet_balance <= 0:
        return

    if clientcommandprocessor.run_client_command( coin_properties.rpc_configuration, 'move', None, user, '', wallet_balance ):
        connection = database.create_connection()
        with connection:
            database.execute_query( connection, Statements[ 'INSERT_USER' ], (user,) )
            database.execute_query( connection, Statements[ 'UPDATE_USER_BALANCE' ], (user, coin_properties.ticker, str( wallet_balance ),) )
    else:
        raise Exception( f'Failed to move {user} balance {wallet_balance} to main account.' )
示例#6
0
def rain(update, coin_properties: CoinProperties):
    ticker = coin_properties.ticker
    arguments = update.message.text.split(' ')
    user = commonhelper.get_username(update)

    if len(arguments) < 2:
        raise BotUserError(messages.rain_error(ticker.lower()))

    amount_to_rain = arguments[1]
    total_balance, wallet_balance = commonhelper.get_user_balance(
        user, coin_properties)
    amount_to_rain = commonhelper.get_validated_amount(amount_to_rain, user,
                                                       total_balance)
    eligible_users = ActivityTracker().get_current_active_users(update, user)

    commonhelper.move_to_main(coin_properties, user, wallet_balance)

    if len(eligible_users) == 0:
        raise BotUserError('Found no active users except You... :\'(')

    eligible_users.append(
        Configuration.TELEGRAM_BOT_NAME)  # Give some to the bot
    amount_per_user = amount_to_rain / len(eligible_users)
    amount_per_user = round_down(amount_per_user, 8)
    amount_remainder = round_down(
        amount_to_rain - amount_per_user * len(eligible_users) +
        amount_per_user, 8)
    at_users = '|'
    users_balance_changes = []
    connection = database.create_connection()

    with connection:
        users_balance_changes.append((user, ticker, str(-amount_to_rain)))

        for eligible_user in eligible_users:
            if eligible_user is Configuration.TELEGRAM_BOT_NAME:
                users_balance_changes.append(
                    (eligible_user, ticker, str(amount_remainder)))
            else:
                users_balance_changes.append(
                    (eligible_user, ticker, str(amount_per_user)))
            at_users = at_users.__add__(' @' + eligible_user + ' |')

        database.execute_many(connection, Statements['UPDATE_USER_BALANCE'],
                              users_balance_changes)

    logger.info(
        f'rain amount ´{amount_to_rain}´ split between {len( eligible_users )} users.'
    )

    return f'@{user} has rained {amount_to_rain} {ticker} to ' \
           f'{len( eligible_users )} active users: {at_users}\n{amount_per_user} ' \
           f'{ticker} received per user.',
示例#7
0
def main():
    bot_configuration = BotConfiguration(Configuration)
    connection = database.create_connection()

    with connection:
        database.init_database(connection)
        database.execute_query(connection, Statements['INSERT_USER'],
                               (bot_configuration.telegram_bot_name, ))
        for coin in bot_configuration.coins:
            database.execute_query(connection, Statements['INSERT_COIN'], (
                coin.name,
                coin.ticker,
            ))

    activity_tracker = ActivityTracker()
    updater = Updater(token=bot_configuration.telegram_bot_token,
                      request_kwargs=None)
    dispatcher = updater.dispatcher

    for coin in bot_configuration.coins:
        dispatcher.add_handler(
            MessageHandler(~Filters.command, activity_tracker.track_activity))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}commands'.lower(),
                           Command(commands.commands, coin)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}start'.lower(),
                           Command(commands.help, coin)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}help'.lower(),
                           Command(commands.help, coin)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}balance'.lower(),
                           Command(commands.balance, coin)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}deposit'.lower(),
                           Command(commands.deposit, coin)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}withdraw'.lower(),
                           Command(commands.withdraw, coin)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}market'.lower(),
                           Command(commands.market, coin, activity_tracker)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}tip'.lower(),
                           Command(commands.tip, coin, activity_tracker)))
        dispatcher.add_handler(
            CommandHandler(f'{coin.ticker}rain'.lower(),
                           Command(commands.rain, coin, activity_tracker)))

    updater.start_polling()

    logger.info('Bot started.')
示例#8
0
def init_session():
    conn = create_connection(DATABASE)
    if conn is not None:
        drop_table('users')
        drop_table('astronauts')
        create_table(conn, sql_create_users_table)
        create_table(conn, sql_create_astronauts_table)
        add_astronauts_bulk(ASTRONAUTS)
    else:
        message = "Cannot create database connection!"
        LOG.error(message)
        raise Exception(message)

    conn.close()
示例#9
0
def get_user_balance( user, coin_properties: CoinProperties ):
    try:
        user_balance = clientcommandprocessor.run_client_command( coin_properties.rpc_configuration, 'getbalance', None, user )
        connection = database.create_connection()

        with connection:
            user_off_chain_balance = database.fetch_result( connection, Statements[ 'SELECT_USER_OFF_CHAIN_BALANCE' ], (user, coin_properties.ticker) )

        if user_off_chain_balance is None:
            user_off_chain_balance = 0

        user_off_chain_balance = round_down( user_off_chain_balance, 8 )
        total_balance = user_balance + user_off_chain_balance

        return total_balance, user_balance
    except BotUserError:
        raise BotUserError
示例#10
0
    def track_activity(self, bot, update):
        try:
            chat_id = update.message.chat_id
            now = datetime.now()
            current_time = datetime.timestamp(now)
            user = commonhelper.get_username(update)
            connection = database.create_connection()

            with connection:
                user_id = database.fetch_result(
                    connection,
                    Statements['SELECT_USER_ID_BY_TELEGRAM_USERNAME'],
                    (user, ))

                if user_id is None:
                    user_id = database.execute_query(connection,
                                                     Statements['INSERT_USER'],
                                                     (user, ))

                database.execute_query(connection,
                                       Statements['UPDATE_USER_ACTIVITY'], (
                                           user_id,
                                           chat_id,
                                           current_time,
                                       ))

            if chat_id not in self.active_users_cache:
                self.active_users_cache.update({chat_id: {user: current_time}})
            else:
                if user not in self.active_users_cache[chat_id]:
                    self.active_users_cache[chat_id].update(
                        {user: current_time})
                else:
                    self.active_users_cache[chat_id][user] = current_time

            logger.info(
                f'@{user} spoke @{chat_id} at {self.active_users_cache[ chat_id ][ user ]}.'
            )
        except BotUserError as e:
            logger.info(e)
示例#11
0
def tip(update, coin_properties: CoinProperties):
    ticker = coin_properties.ticker
    arguments = update.message.text.split(' ')

    if len(arguments) < 3:
        raise BotUserError(messages.tip_error(ticker.lower()))

    user = commonhelper.get_username(update)
    target_user = arguments[1]
    amount = arguments[2]

    if '@' not in target_user:
        raise BotUserError(f'That user ´{target_user}´ is not applicable.')

    target_user = target_user[1:]
    user_balance, wallet_balance = commonhelper.get_user_balance(
        user, coin_properties)
    amount = commonhelper.get_validated_amount(amount, user, user_balance)

    commonhelper.move_to_main(coin_properties, user, wallet_balance)

    if target_user == user:
        raise BotUserError('You can not tip Yourself.')

    users_balance_changes = [(user, ticker, str(-amount)),
                             (target_user, ticker, str(amount))]

    connection = database.create_connection()

    with connection:
        database.execute_query(connection, Statements['INSERT_USER'],
                               (target_user, ))
        database.execute_many(connection, Statements['UPDATE_USER_BALANCE'],
                              users_balance_changes)

    return f'@{user} tipped @{target_user} of {amount} {ticker}',
示例#12
0
    def __init__(self, book):
        super().__init__()

        self.setMinimumSize(700, 400)
        self.resize(1000, 600)

        self.book = book
        self.db_connection = db.create_connection(
            os.path.expanduser("~/Documents/LNUReader/ReaderDatabase.db"))

        self.mainLayout = QVBoxLayout()
        self.bookmarksTable = QTableWidget()
        self.notesTable = QTableWidget()

        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.bookmarksTable, '')
        self.tabWidget.addTab(self.notesTable, '')

        # Back Button
        self.backQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.backQButton,
                                         'design/images/back.png',
                                         'design/images/night/night_back.png')
        ColorsRegulator().set_colors(
            self.backQButton, styles.Styles.set_back_button_styles,
            night_styles.NightStyles.set_back_button_styles)
        self.backQButton.setIconSize(QSize(32, 32))
        self.backQButton.setFocusPolicy(Qt.NoFocus)
        self.backQButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.contextMenu = QMenu()
        self.openAct = self.contextMenu.addAction("")
        self.deleteAct = self.contextMenu.addAction("")
        ColorsRegulator().set_icon_color(
            self.openAct, 'design/images/pencil.png',
            'design/images/night/night_pencil.png')

        ColorsRegulator().set_icon_color(
            self.deleteAct, 'design/images/removeBook.png',
            'design/images/night/night_removeBook.png')
        ColorsRegulator().set_colors(
            self.contextMenu, styles.Styles.set_context_menu_styles,
            night_styles.NightStyles.set_context_menu_styles)

        self.openAct.triggered.connect(self.edit_obj)
        self.deleteAct.triggered.connect(self.delete_obj)
        QShortcut("Del", self).activated.connect(self.delete_obj)

        self.editNoteQDialog = QTwoFieldDialog()
        self.editNoteQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.editNoteQDialog.resize(600, 480)

        self.editBookmarkQDialog = QInputDialog()
        self.editBookmarkQDialog.setInputMode(QInputDialog.TextInput)
        self.editBookmarkQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.editBookmarkQDialog.resize(600, 480)
        ColorsRegulator().set_colors(
            self.editBookmarkQDialog, styles.Styles.set_dialog_styles,
            night_styles.NightStyles.set_dialog_styles)

        ColorsRegulator().set_colors(
            self, styles.Styles.set_content_window_style,
            night_styles.NightStyles.set_content_window_style)

        localize.set_content_localization(self)

        self.notesTable.itemDoubleClicked.connect(self.edit_note)

        # Bookmark / note delete confirmation dialog
        self.deleteDialog = ConfirmDialog()
        self.deleteDialog.setWindowIcon(QIcon('design/images/icon.ico'))

        self.main_init()
示例#13
0
def withdraw(update, coin_properties: CoinProperties):
    ticker = coin_properties.ticker
    arguments = update.message.text.split(' ')

    user = commonhelper.get_username(update)

    if len(arguments) < 3:
        raise BotUserError(messages.withdraw_error(ticker.lower()))

    address = arguments[1]
    address = commonhelper.get_validated_address(address, coin_properties)
    amount = arguments[2]
    total_balance, wallet_balance = commonhelper.get_user_balance(
        user, coin_properties)
    amount = commonhelper.get_validated_amount(amount, user, total_balance)
    configured_transaction_fee = round_down(coin_properties.withdrawal_fee, 8)

    if amount < coin_properties.minimum_withdraw:
        raise BotUserError(
            f'Minimum allowed withdrawal amount is {configured_transaction_fee}{ticker}.'
        )

    if arguments[2].lower is 'all':
        amount -= configured_transaction_fee
    elif amount + configured_transaction_fee > total_balance:
        raise BotUserError(
            f'Unable to withdraw {amount}{ticker}. '
            f'Amount combined with withdrawal fee {configured_transaction_fee}{ticker} exceeds the available balance: '
            f'{round_down( amount + configured_transaction_fee, 8 )}{ticker} > {round_down( total_balance, 8 )}{ticker}.'
        )

    commonhelper.move_to_main(coin_properties, user, wallet_balance)
    transaction_id = clientcommandprocessor.run_client_command(
        coin_properties.rpc_configuration, 'sendtoaddress', None, address,
        amount)
    real_transaction_fee = commonhelper.get_transaction_fee(
        coin_properties.rpc_configuration, transaction_id)

    users_balance_changes = [
        (user, ticker, str(-amount - configured_transaction_fee)),
        (Configuration.TELEGRAM_BOT_NAME, ticker,
         str(configured_transaction_fee + real_transaction_fee))
    ]

    try:
        connection = database.create_connection()
        with connection:
            database.execute_many(connection,
                                  Statements['UPDATE_USER_BALANCE'],
                                  users_balance_changes)
    except Exception as e:
        logger.error(e)
        return messages.GENERIC_ERROR

    blockchain_explorer: BlockchainExplorerConfiguration = coin_properties.blockchain_explorer

    if blockchain_explorer is not None:
        address = f'<a href="{blockchain_explorer.url}/{blockchain_explorer.address_prefix}/{address}">{address}</a>'
        transaction_id = f'<a href="{blockchain_explorer.url}/{blockchain_explorer.tx_prefix}/{transaction_id}">{transaction_id}</a>'

    return f'@{user} has successfully withdrawn {amount}{ticker} to address: {address}.<pre>\r\n</pre>TX:&#160;{transaction_id}. ' \
           f'Withdrawal fee of {configured_transaction_fee}{ticker} was applied.', 'HTML'
 def connect_to_db():
     path_to_db = os.path.expanduser("~/Documents/LNUReader")
     if not os.path.exists(path_to_db):
         os.makedirs(path_to_db)
     return db.create_connection(path_to_db + r'\ReaderDatabase.db')