コード例 #1
0
 def update_stake_db(self, tx_account, new_stake, txid):
     to_exec = """UPDATE db
             SET staked=%s, lasttxid=%s
             WHERE snowflake
             LIKE %s"""
     self.cursor.execute(to_exec, (new_stake, txid, tx_account))
     self.connection.commit()
     output.success("Successfully updated user's staked amount!")
コード例 #2
0
ファイル: bot.py プロジェクト: Nadro-J/tipbot-v2
async def on_ready():
    output.info("Loading {} extension(s)...".format(len(startup_extensions)))
    for extension in startup_extensions:
        try:
            bot.load_extension("cogs.{}".format(extension.replace(".py", "")))
            loaded_extensions.append(extension)
        except Exception as e:
            exc = '{}: {}'.format(type(e).__name__, e)
            output.error('Failed to load extension {}\n\t->{}'.format(extension, exc))
    output.success('Successfully loaded the following extension(s): {}'.format(', '.join(loaded_extensions)))
    output.info('You can now invite the bot to a server using the following link: https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(bot.user.id))
コード例 #3
0
ファイル: bot.py プロジェクト: Sieres/PIVX-Discord-Bot
async def on_ready():
    output.info("Loading {} extension(s)...".format(len(startup_extensions)))

    for extension in startup_extensions:
        try:
            bot.load_extension("cogs.{}".format(extension.replace(".py", "")))
            loaded_extensions.append(extension)

        except Exception as e:
            exc = '{}: {}'.format(type(e).__name__, e)
            output.error('Failed to load extension {}\n\t->{}'.format(extension, exc))
    output.success('Successfully loaded the following extension(s); {}'.format(loaded_extensions))
コード例 #4
0
 def check_for_user(self, tx_account):
     to_exec = """SELECT snowflake
     FROM db
     WHERE snowflake
     LIKE %s"""
     self.cursor.execute(to_exec, (str(tx_account)))
     result_set = self.cursor.fetchone()
     if result_set == None:
         output.info("User does not exist in db, adding...")
         self.make_user(tx_account)
     output.success("User exists in db, proceeding...")
     return result_set
コード例 #5
0
 def remove_tx_db(self, tx_account, tx_amount, txid, tx_category):
     to_exec = """DELETE FROM unconfirmed
     WHERE account = %s
     AND amount = %s
     AND txid = %s
     LIMIT 1"""
     self.cursor.execute(to_exec,
                         (str(tx_account), str(tx_amount), str(txid)))
     self.connection.commit()
     output.success(
         "Tx has been removed, adding to user's balance/staked...")
     self.check_for_user(tx_account)
     self.get_db(tx_account, tx_amount, txid, tx_category)
コード例 #6
0
 def make_user(self, tx_account):
     to_exec = "INSERT INTO db(snowflake, balance) VALUES(%s,%s)"
     self.cursor.execute(to_exec, (str(tx_account), '0'))
     self.connection.commit()
     output.success("Successfully added user to db, proceeding...")
コード例 #7
0
def main():
    args = parse_arguments()

    # loads applicative configuration
    config = ConfigurationManager(args.env)

    HOST = config.active_configuration['HOST']
    CERTIFICATE_PATH = config.active_configuration['CERTIFICATE_PATH']
    PRIVATE_KEY_PATH = config.active_configuration['PRIVATE_KEY_PATH']

    app = Flask(__name__)
    auth = HTTPBasicAuth()

    global base_directory
    base_directory = args.directory

    # Deal with Favicon requests
    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'images/favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    ############################################
    # File Browsing and Download Functionality #
    ############################################
    @app.route('/', defaults={'path': None})
    @app.route('/<path:path>')
    @auth.login_required
    def home(path):
        # If there is a path parameter and it is valid
        if path and is_valid_subpath(path, base_directory):
            # Take off the trailing '/'
            path = os.path.normpath(path)
            requested_path = os.path.join(base_directory, path)

            # If directory
            if os.path.isdir(requested_path):
                back = get_parent_directory(requested_path, base_directory)
                is_subdirectory = True

            # If file
            elif os.path.isfile(requested_path):

                # Check if the view flag is set
                if request.args.get('view') is None:
                    send_as_attachment = True
                else:
                    send_as_attachment = False

                # Check if file extension
                (filename, extension) = os.path.splitext(requested_path)
                if extension == '':
                    mimetype = 'text/plain'
                else:
                    mimetype = None

                try:
                    return send_file(requested_path,
                                     mimetype=mimetype,
                                     as_attachment=send_as_attachment)
                except PermissionError:
                    abort(403, 'Read Permission Denied: ' + requested_path)

        else:
            # Root home configuration
            is_subdirectory = False
            requested_path = base_directory
            back = ''

        if os.path.exists(requested_path):
            # Read the files
            try:
                directory_files = process_files(os.scandir(requested_path),
                                                base_directory)
            except PermissionError:
                abort(403, 'Read Permission Denied: ' + requested_path)

            return render_template('home.html',
                                   files=directory_files,
                                   back=back,
                                   directory=requested_path,
                                   is_subdirectory=is_subdirectory,
                                   version=version)
        else:
            return redirect('/')

    #############################
    # File Upload Functionality #
    #############################
    @app.route('/upload', methods=['POST'])
    @auth.login_required
    def upload():
        if request.method == 'POST':

            # No file part - needs to check before accessing the files['file']
            if 'file' not in request.files:
                return redirect(request.referrer)

            path = request.form['path']
            # Prevent file upload to paths outside of base directory
            if not is_valid_upload_path(path, base_directory):
                return redirect(request.referrer)

            for file in request.files.getlist('file'):

                # No filename attached
                if file.filename == '':
                    return redirect(request.referrer)

                # Assuming all is good, process and save out the file
                # TODO:
                # - Add support for overwriting
                if file:
                    filename = secure_filename(file.filename)
                    full_path = os.path.join(path, filename)
                    try:
                        file.save(full_path)
                    except PermissionError:
                        abort(403, 'Write Permission Denied: ' + full_path)
                    finally:
                        parse_generate(full_path)
                        write_server_log("File parsing started!")

            return redirect(request.referrer)

    # Password functionality is without username
    users = {'': generate_password_hash(args.password)}

    @auth.verify_password
    def verify_password(username, password):
        if args.password:
            if username in users:
                return check_password_hash(users.get(username), password)
            return False
        else:
            return True

    # Inform user before server goes up
    success('Serving {}...'.format(args.directory, args.port))

    def handler(signal, frame):
        print()
        error('Exiting!')

    signal.signal(signal.SIGINT, handler)

    ssl_context = None
    if args.ssl:
        ssl_context = (CERTIFICATE_PATH, PRIVATE_KEY_PATH)

    run_simple(HOST, int(args.port), app, ssl_context=ssl_context)