Exemple #1
0
def upload_blobs(repo, file, path):
    """
     utils to check file type and upload blob

     return: git blob
    """
    if allowed_file(file):
        return upload_blob(repo, path + '/' + file, True)
    else:
        return upload_blob(repo, path + '/' + file)
def edit_save_image(dir_path):
    if request.method == 'POST':
        file = request.files.get('image')
        if file and allowed_file(file.filename):
            filename = file.filename
            filename = secure_filename(filename)
            if not os.path.exists(UPLOAD_FOLDER):
                os.makedirs(UPLOAD_FOLDER)

            file_path = os.path.join(UPLOAD_FOLDER + '/' + dir_path, filename)
            file.save(file_path)
            return jsonify({'data': '/temp/' + dir_path + '/' + filename})
        return jsonify({'data': None})
def index():
    """
    Initialize the github folders.
    """
    auth = initialize()
    if auth and auth[0]:
        init = auth[1]
        repo = init.get('repo')

        # get the posts location in github
        posts_folder = get_post_folder()
        if posts_folder:
            folders = get_contents(repo, posts_folder)
        else:
            return redirect('/configure')

        contents = get_content_from_folder(repo, folders)
        display_pages = {}

        for key, value in contents.items():
            files = value['files']
            for file in files:
                temp = {}
                if not allowed_file(file.path):
                    text = decode_content(file.content, True)
                    display_content = get_file_contents(text)[0]
                    temp = get_article_data(display_content)

                    if temp.get('title'):
                        temp['path'] = value['path']
                        display_pages[temp['title']] = temp
                    else:
                        print(key, value)

        return render_template('index.html', pages=display_pages)
    elif not auth:
        return render_template('index.html')
    else:
        return redirect(url_for('core.' + auth[1]))
def edit_page():
    if request.method == 'GET':
        clear_temp_static(True)
        path = request.args.get('path', None)
        folder_path = path.split('/')[-1]
        if path:
            get_repo = initialize()
            if get_repo[0]:
                init = get_repo[1]
                repo = init.get('repo')
                file_contents = get_contents(repo, path)
                for file in file_contents:
                    if not allowed_file(file.path):

                        # text =  decode_content(file.content, True)
                        text = file.decoded_content
                        display_content = get_file_contents(text)
                        file_meta = get_article_data(display_content[0])
                        add_image_desc = re.sub('!\[\]\(.', '![](temp/{}'.format(folder_path), display_content[1])
                        # TODO: fix it in proper way (workround found to remove the extra spaces)
                        remove_extra_lines = add_image_desc.replace('\r\n\r\n  \r\n\r\n', '\r\n') \
                            .replace('\r\n\r\n', '\r\n').replace('\r\n', '\n')

                        markdown = md2.markdown(add_image_desc, extras=['fenced-code-blocks'])
                        fix_front_quotes = re.sub('<blockquote>\n', '<blockquote>', markdown)
                        fixed_quotes = re.sub('\n</blockquote>\n', '</blockquote>', fix_front_quotes)
                        # breakpoint()
                        description = re.sub('\n', '<br/>', \
                                             fixed_quotes \
                                             .replace('\n\n', '\n').replace('</li>\n', '</li>') \
                                             .replace('\n<li>', '<li>').replace('<p><em>', '<em>') \
                                             .replace('</em></p>', '</em>').replace('\n  \n', '')
                                             )
                        # breakpoint()
                    else:
                        file_path = os.path.join(UPLOAD_FOLDER + '/{}'.format(folder_path), file.name)
                        os.makedirs(os.path.dirname(file_path), exist_ok=True)
                        # file_path = os.path.join(UPLOAD_FOLDER, file.name)
                        with open(file_path, 'wb') as f:
                            f.write(decode_content(file.content))
                form = CreateForm(data=file_meta)
                return render_template('edit.html', form=form, description=description, path=path)
            else:
                return redirect(url_for('core.' + get_repo[1]))
        else:
            return render_template('edit.html', content=None)

    if request.method == 'POST':
        # breakpoint()
        get_repo = initialize()
        if get_repo[0]:
            init = get_repo[1]
            repo = init.get('repo')
            tree = init.get('tree')
            branch = init.get('branch')
            master_ref = init.get('master_ref')

            form = request.form
            path = form.get('path')
            title_text = form.get('title')
            category_text = form.get('category')
            folder_text = form.get('folder')
            created_date = form.get('date')
            file_path = path.split('/')[-1]
            # get file content
            description = form.get('description')
            is_draft = form.get('draft')

            # find image
            current_image = re.findall('temp/.*?\.[jpg|jpeg|png|gif]+', description)

            previous_image = new_images = remove_images = []
            if current_image:
                try:
                    previous_image = os.listdir(UPLOAD_FOLDER + '/' + file_path)
                except:
                    previous_image = []
                # go thorugh all the image take the list of added and removed images
                new_images = [image.split('/')[-1] for image in current_image if
                              image.split('/')[-1] not in previous_image]
                remove_images = [image for image in previous_image if
                                 'temp/' + file_path + '/' + image not in current_image]

            # get content current folder
            content_folder = get_content_type(path)

            updated_image = re.sub('\(/temp|temp/[a-z0-9\-]+', '(.', description)

            # recheck the image added to temp folder
            updated_desc = re.sub('\(\(./', '(./', updated_image)

            # update the file
            current_time = datetime.now().strftime("%d-%b-%Y")

            title = 'title: ' + title_text + '\n'
            category = 'category: ' + category_text + '\n'
            author = 'author: ' + 'arunkumar' + '\n'
            date = 'date: ' + '{}'.format(created_date) + '\n'
            updated = 'updated: ' + '{}'.format(current_time) + '\n'
            folder = 'folder: ' + folder_text + '\n'

            file_meta = '---\n' + title + category + author + date + updated + folder + '---\n'

            content = file_meta + updated_desc

            commit_message = 'Updated {} at {}'.format(file_path, current_time)

            file = repo.get_contents('{}/index.md'.format(path))

            """
             find the content folder location and check for
             saving type(draft or post)

             if draft
               i)  content_folder is draft leave to the flow
               ii) contet_folder is post:
                     update the folder meta_data for content
                     and create new draft content
             if post
               i) content_folder is post leave the flow
               ii) content_folder is draft:
                   check file_meta_data folder
                   folder is empty --> create new content
                   folder is not empty --> update the path leave the flow
            """
            if is_draft and content_folder == 'drafts' or not is_draft and content_folder == 'posts':
                # leave the flow
                if current_image:
                    github_remove_images(remove_images, path, repo)
                    github_upload_images(new_images, UPLOAD_FOLDER, path, repo, tree, branch, master_ref)

            elif is_draft and content_folder == 'posts':
                # Update the folder path and create new draft content
                content = re.sub('folder:', 'folder:{}'.format(path), content)
                # create element tree
                blob = create_git_blob(repo, content, 'utf-8|base64')

                draft_folder = get_post_folder(draft)

                git_dir = file_path

                git_path = draft_folder + git_dir

                index_element = create_input_git_tree(git_path + '/index.md', '100644', 'blob', blob.sha)

                element_tree = [index_element]

                # create git tree
                git_tree = create_git_tree(repo, element_tree, tree)
                # create git commit

                parent = repo.get_git_commit(branch.commit.sha)

                git_commit = create_git_commit(repo, 'new draft post added in {}'.format(git_dir), git_tree, parent)
                # update the head commit
                update_commit(master_ref, git_commit.sha)

                github_upload_images(new_images, UPLOAD_FOLDER, git_path)

                # upload current image
                github_upload_images(previous_image, UPLOAD_FOLDER + '/' + file_path, git_path)
                return redirect('/drafts')

            elif not is_draft and not folder_text:
                # create new post content
                blob = create_git_blob(repo, content, 'utf-8|base64')
                posts_folder = get_post_folder(is_draft)
                git_dir = file_path
                git_path = posts_folder + git_dir

                index_element = create_input_git_tree(git_path + '/index.md', '100644', 'blob', blob.sha)

                element_tree = [index_element]

                # create git tree
                git_tree = create_git_tree(repo, element_tree, tree)
                # create git commit
                parent = repo.get_git_commit(branch.commit.sha)
                git_commit = create_git_commit(repo, 'new draft post added in {}'.format(git_dir), git_tree, parent)
                # update the head commit
                update_commit(master_ref, git_commit.sha)

                github_upload_images(new_images, UPLOAD_FOLDER, path)
                github_upload_images(previous_image, UPLOAD_FOLDER + '/' + file_path, git_path)

                return redirect(root_url)

            elif not is_draft and folder_text:
                # leave the flow and update the path
                path = folder_text
                file = repo.get_contents('{}/index.md'.format(path))
                # update the folder text to empty
                content = re.sub('folder: [a-z]+/[a-z]+/[a-zA-z0-9\-]+', 'folder:', content)
                github_remove_images(remove_images, path, repo)
                github_upload_images(new_images, UPLOAD_FOLDER, path)

            update_file(repo, path + '/index.md', commit_message, content, file.sha)
            clear_temp_static(True)
            # TODO exception handling and send the form again with data
            return redirect(root_url)
        else:
            return redirect(url_for('core.' + get_repo[1]))