Exemple #1
0
def entries(name):
    """
    This page presents a user's blog posts and file uploads,
    allowing visitors to download the files individually.
    """

    if get_user(name) is not None:
        session['theme'] = get_user(name).theme
        entries = [e for e in Entry.query.all()]
        entries.reverse()
        uploads = [dict(userid=f.userid, filename=f.filename, filetype=f.filetype) \
                   for f in Upload.query.all()]

        if request.method == "POST":
            title, text = request.form['title'], request.form['text']
            text = urlify(text)

            entry_instance = Entry(name, title, text)
            edb.session.add(entry_instance)
            edb.session.commit()

            flash('Post successful!')
            return redirect(url_for('entries', name=name))
        else:
            return render_template('entries.html', username=name,
                                   uploads=uploads, entries=entries, theme=session['theme'])
    else:
        display("User does not exist.")
        return redirect(url_for('login'))
Exemple #2
0
def create():
    """
	Allows a user to create a new account.
	"""
    error = None
    if request.method == 'POST':
        # Get submitted values from fields.
        username = request.form['username']
        password = request.form['password-a']

        # Check if there is a user by the same username in the database.
        user_instance = get_user(username)
        if user_instance is not None:
            error = 'Username is already taken.'
        elif password != request.form['password-b']:
            error = 'Passwords do not match.'
        else:
            # Add user to the database and log user in.
            user_instance = User(username, password)
            flash('Account created!')
            session['logged_in'] = username
            return redirect(url_for('files', name=username))

    display(error)
    return render_template('create.html')
Exemple #3
0
def get_profile(profile):
    tools.display(preset.message["retrieve_user"])
    user_data = tools.get_chrome_element(profile, preset.preferences)
    if not user_data:
        tools.display(preset.message["invalid_profile"])
        exit(1)
    return tools.get_user(user_data)
Exemple #4
0
def create():
	"""
	Allows a user to create a new account.
	"""
	error = None
	if request.method == 'POST':
		# Get submitted values from fields.
		username = request.form['username']
		password = request.form['password-a']

		# Check if there is a user by the same username in the database.
		user_instance = get_user(username)
		if user_instance is not None:
			error = 'Username is already taken.'
		elif password != request.form['password-b']:
			error = 'Passwords do not match.'
		else:
			# Add user to the database and log user in.
			user_instance = User(username, password)
			flash('Account created!')
			session['logged_in'] = username
			return redirect(url_for('files', name=username))

	display(error)
	return render_template('create.html')
Exemple #5
0
def change_theme(name):
    """
    This page will allow the user to change the appearance of their blog.
    """

    # Check if the user is logged in before allowing to change theme.
    error = valid_user(name)
    if error is None:
        if request.method == 'POST':
            new_theme = request.form['theme']
            user_instance = get_user(name)

            # Change the user's theme, change the theme in browser and
            # store the changed theme in the user database.
            user_instance.theme = session['theme'] = new_theme
            udb.session.commit()

            flash('Theme changed to %s.' % new_theme.lower())
            return redirect(url_for('change_theme', name=name))

        return render_template('theme.html', username=name, theme=session['theme'])

    # If an error occurs, display the error and
    # redirect to the appropriate page.
    display(error)
    if 'logged_in' in session:
        return redirect(url_for('upload', name=session['logged_in']))
    else:
        return redirect(url_for('login'))
Exemple #6
0
def login():
    """
    Allows a user to log in to their account.
    Note that the index page redirects here by default.
    """

    error = None
    if 'logged_in' not in session:
        session['theme'] = app.config['DEFAULT_THEME']

    if request.method == 'POST':
        username = request.form['username']

        # Check to see if the user exists.
        user_instance = get_user(username)
        if user_instance is None:
            error = 'Invalid username.'
        elif not user_instance.check_pw(request.form['password']):
            error = 'Invalid password.'
        else:
            session['logged_in'], session['posting_enabled'], session['theme'] = \
                username, user_instance.posting_enabled, user_instance.theme
            flash('Successfully logged in.')
            return redirect(url_for('entries', name=username))
    else:
        return render_template('login.html', theme=session['theme'])

    display(error)
    return render_template('login.html', theme=session['theme'])
Exemple #7
0
def upload_video(upload_dict: dict) -> None:
    upload_way_dict = {'bd': BDUpload,
                       's3': S3Upload}
    upload_way = upload_way_dict.get(config['upload_by'])
    uploader = upload_way()
    user_config = get_user(upload_dict['User'])
    result = uploader.upload_item(f"{upload_dict['Path']}", upload_dict['Title'])
    if not result:
        raise RuntimeError('Upload error')
    if config['upload_by'] == 'bd':
        share_url = uploader.share_item(upload_dict['Title'])
        if config['enable_mongodb']:
            data = {"Title": upload_dict['Origin_Title'],
                    "Date": upload_dict['Date'],
                    "Link": share_url,
                    "ASS": upload_dict['ASS']}
            insert_video(upload_dict['User'], data)
    elif config['upload_by'] == 's3':
        if config['enable_mongodb']:
            share_url = f"gets3/{quote(upload_dict['Title'])}"
            data = {"Title": upload_dict['Origin_Title'],
                    "Date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    "Link": share_url,
                    "ASS": upload_dict['ASS']}
            insert_video(upload_dict['User'], data)
    else:
        raise RuntimeError(f'Upload {upload_dict["Title"]} failed')
    pub = Publisher()
    data = {'Msg': f"[下载提示] {upload_dict['Title']} 已上传, 请查看https://matsuri.design/",
            'User': user_config['user']}
    pub.do_publish(data, 'bot')
def call_bot(video_dict: dict) -> None:
    user_config = get_user(video_dict['User'])
    if user_config['bot_notice']:
        try:
            group_id = user_config['group_id']
        except KeyError:
            group_id = config['group_id']
        bot(video_dict['Msg'], group_id)
 async def main(self) -> None:
     user_config = get_user(self.video_dict['User'])
     if not user_config['record']:
         return None
     ddir = get_ddir(user_config)
     self.video_dict['Origin_Title'] = self.video_dict['Title']
     self.video_dict['Title'] = AdjustFileName(
         self.video_dict['Title']).adjust(ddir)
     await self.ws_interaction()
     self.upload_record(ddir)
Exemple #10
0
def dispatch():

    user = tools.get_user()


    if user.cmd:
        user.interactive = False
        return apprunner.run(user)
    else:
        user.interactive = True
        return shell.prompt(user)
Exemple #11
0
def call_bot(video_dict: dict) -> None:
    user_config = get_user(video_dict['User'])
    if user_config['bot_notice']:
        bot_config = dict()
        config_item = ['group_id', 'bot_host', 'bot_token']
        for item in config_item:
            if item in user_config:
                bot_config[item] = user_config[item]
            else:
                bot_config[item] = config[item]
        msg = filter_at(video_dict['User'], video_dict['Msg'])
        bot(msg, bot_config)
Exemple #12
0
def upload_record(upload_dict: dict) -> None:
    user_config = get_user(upload_dict['User'])
    uploader = BDUpload()
    result = uploader.upload_item(upload_dict['Path'], upload_dict['Title'])
    if not result:
        raise RuntimeError('Upload error')
    if config['upload_by'] == 'bd':
        share_url = uploader.share_item(upload_dict['Title'])
        if config['enable_mongodb']:
            data = {"Title": upload_dict['Origin_Title'],
                    "Date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    "Record": share_url}
            insert_video(upload_dict['User'], data)
            pub = Publisher()
            data = {'Msg': f"[同传提示] {upload_dict['Title']} 已记录, 请查看https://matsuri.design/",
                    'User': user_config['user']}
            pub.do_publish(data, 'bot')
def upload_video(upload_dict: dict) -> None:
    upload_way_dict = {'bd': BDUpload, 's3': S3Upload}
    upload_way = upload_way_dict.get(config['upload_by'])
    uploader = upload_way()
    user_config = get_user(upload_dict['User'])
    result = uploader.upload_item(f"{upload_dict['Path']}",
                                  upload_dict['Filename'])
    if not result:
        raise RuntimeError('Upload error')
    if config['upload_by'] == 'bd':
        share_url = uploader.share_item(upload_dict['Filename'])
        if config['enable_mongodb']:
            data = {
                "Title": upload_dict['Origin_Title'],
                "Date": upload_dict['Date'],
                "Link": share_url,
                "ASS": upload_dict['ASS'],
                "Txt": upload_dict['Txt']
            }
            insert_video(upload_dict['User'], data)
    elif config['upload_by'] == 's3':
        if config['enable_mongodb']:
            share_url = f'https://matsuri.design/{config["s3_bucket"]}/{quote(upload_dict["Filename"])}'
            m3u8_url = f'https://matsuri.design/{config["s3_bucket"]}/{quote(upload_dict["Title"]) + ".m3u8"}'
            data = {
                "Title": upload_dict['Origin_Title'],
                "Date": upload_dict['Date'],
                "Link": share_url,
                "ASS": upload_dict['ASS'],
                "Txt": upload_dict['Txt'],
                "M3U8": m3u8_url
            }
            insert_video(upload_dict['User'], data)
    else:
        raise RuntimeError(f'Upload {upload_dict["Filename"]} failed')
    pub = Publisher()
    data = {
        'Msg':
        f"[下载提示] {upload_dict['Title']} 已上传, 请查看https://matsuri.design/",
        'User': user_config['user']
    }
    pub.do_publish(data, 'bot')
Exemple #14
0
def process_video(video_dict):
    """
    处理直播视频,包含bot的发送,视频下载,视频上传和存入数据库
    :param video_dict: 含有直播视频数据的dict
    :return: None
    """
    user_config: dict = get_user(video_dict['User'])
    if not user_config['download']:
        return None
    ddir: str = get_ddir(user_config)
    check_ddir_is_exist(ddir)
    logger.info(f'{video_dict["Provide"]} Found A Live, starting downloader')
    except_bili(video_dict['User'], video_dict['Provide'])
    video_dict['Origin_Title'] = video_dict['Title']
    video_dict['Title'] = AdjustFileName(video_dict['Title']).adjust(ddir)
    video_dict['Start_timestamp'] = get_timestamp()
    video_dict['Title'] = download_video(video_dict, ddir)
    video_dict['End_timestamp'] = get_timestamp()
    send_bot(video_dict['Title'], user_config['user'])
    send_upload(video_dict, f'{ddir}/{video_dict["Title"]}')
def process_video(video_dict):
    """
    处理直播视频,包含bot的发送,视频下载,视频上传和存入数据库
    :param video_dict: 含有直播视频数据的dict
    :return: None
    """
    user_config: dict = get_user(video_dict['User'])
    if not user_config['download']:
        return None
    ddir: str = get_ddir(user_config)
    check_ddir_is_exist(ddir)
    logger.info(f'{video_dict["Provide"]} Found A Live, starting downloader')
    video_dict['Origin_Title'] = video_dict['Title']
    video_dict['Title'] = AdjustFileName(video_dict['Title']).adjust(ddir)
    video_dict['Start_timestamp'] = int(datetime.now().timestamp() * 1000)
    if video_dict["Provide"] == 'Youtube':
        result: str = downloader(r"https://www.youtube.com/watch?v=" + video_dict['Ref'], video_dict['Title'],
                                 config['proxy'], ddir, user_config, config['youtube_quality'])
    else:
        result: str = downloader(video_dict['Ref'], video_dict['Title'], config['proxy'], ddir, user_config)
    pub = Publisher()
    if result:
        video_dict['End_timestamp'] = int(datetime.now().timestamp() * 1000)
        data = {'Msg': f"[下载提示] {result} 已下载完成,等待上传",
                'User': user_config['user']}
        logger.warning(data)
        pub.do_publish(data, 'bot')
    if config['enable_upload']:
        upload_dict = {
            'Title': result,
            'Target': video_dict['Target'],
            'Date': video_dict['Date'],
            'Path': f'{ddir}/{result}',
            'User': video_dict['User'],
            'Origin_Title': video_dict['Origin_Title'],
            'ASS': get_ass(video_dict)
        }
        pub.do_publish(upload_dict, 'upload')
        pub.do_publish(video_dict['Target'], 'cq')
Exemple #16
0
def login():
	"""
	Allows a user to log in to their account.
	Note that the index page redirects here by default.
	"""
	error = None
	if request.method == 'POST':
		username = request.form['username']

		# Check to see if the user exists.
		user_instance = get_user(username)
		if user_instance is None:
			error = 'Invalid username.'
		elif not user_instance.check_pw(request.form['password']):
			error = 'Invalid password.'
		else:
			session['logged_in'] = username
			flash('Successfully logged in.')
			return redirect(url_for('files', name=username))

	display(error)
	return render_template('login.html')
Exemple #17
0
def login():
    """
	Allows a user to log in to their account.
	Note that the index page redirects here by default.
	"""
    error = None
    if request.method == 'POST':
        username = request.form['username']

        # Check to see if the user exists.
        user_instance = get_user(username)
        if user_instance is None:
            error = 'Invalid username.'
        elif not user_instance.check_pw(request.form['password']):
            error = 'Invalid password.'
        else:
            session['logged_in'] = username
            flash('Successfully logged in.')
            return redirect(url_for('files', name=username))

    display(error)
    return render_template('login.html')
Exemple #18
0
def create():
    """
    Allows a user to create a new account.
    """
    error = None
    if 'logged_in' not in session:
        session['theme'] = app.config['DEFAULT_THEME']

    if request.method == 'POST':
        # Get submitted values from fields.
        username, password = request.form['username'], request.form['password-a']

        # Check if there is a user by the same username in the database.
        user_instance = get_user(username)
        if user_instance is not None:
            error = 'Username is already taken.'
        elif re.search(r'[^_a-zA-Z0-9]', username):
            error = 'Username must only contain letters, numbers, and underscores.'
        elif password == '':
            error = 'Please enter a password.'
        elif password != request.form['password-b']:
            error = 'Passwords do not match.'
        else:
            # Add user to the database and log user in.
            user_instance = User(username, password)
            user_instance.theme = app.config['DEFAULT_THEME']
            udb.session.add(user_instance)
            udb.session.commit()

            flash('Account created!')
            session['logged_in'], session['posting_enabled'], session['theme'] = \
                username, user_instance.posting_enabled, user_instance.theme
            return redirect(url_for('entries', name=username))

    display(error)
    return render_template('create.html', theme=session['theme'])
        source_files.append(file)
        print('{0:>1}: {1:>40}'.format(len(source_files), file))

csvpath = ''
while not ((csvpath in source_files) or
           (csvpath.isdigit() and 0 < int(csvpath) <= len(source_files))):
    csvpath = input(
        "\nenter filename 'filename.csv' for source file or its number from list above\n"
    )
if csvpath.isdigit():
    csvpath = source_files[int(csvpath) - 1]

raw_data = tools.csv_parser(csvpath)
table = tools.packer(raw_data)
users = [
    User(handler, num + 1, tools.get_user(num, table))
    for num in range(len(table['staffid']))
]

if not tools.approving(handler, csvpath, users):
    sys.exit(0)

auth = tools.authentication()
session, login = auth['session'], auth['login']

print('')

if handler == 'upload':
    for u in users:
        u.check(session)
        if u.get_verify_status():