Example #1
0
File: wiki.py Project: qbi/seahub
def personal_wiki(request, page_name="home"):
    username = request.user.username
    wiki_exists = True
    try:
        content, repo, dirent = get_personal_wiki_page(username, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        # get available modules(wiki, etc)
        mods_available = get_available_mods_by_user(username)
        mods_enabled = get_enabled_mods_by_user(username)
        return render_to_response("wiki/personal_wiki.html", {
            "wiki_exists": wiki_exists,
            "mods_enabled": mods_enabled,
            "mods_available": mods_available,
        },
                                  context_instance=RequestContext(request))
    except WikiPageMissing:
        repo = get_personal_wiki_repo(username)
        filename = clean_page_name(page_name) + '.md'
        if not seaserv.post_empty_file(repo.id, "/", filename, username):
            return render_error(
                request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse('personal_wiki', args=[page_name]))
    else:
        url_prefix = reverse('personal_wiki', args=[])
        content = convert_wiki_link(content, url_prefix, repo.id, username)

        # fetch file latest contributor and last modified
        path = '/' + dirent.obj_name
        file_path_hash = hashlib.md5(urllib2.quote(
            path.encode('utf-8'))).hexdigest()[:12]
        contributors, last_modified, last_commit_id = get_file_contributors(\
            repo.id, path.encode('utf-8'), file_path_hash, dirent.obj_id)
        latest_contributor = contributors[0] if contributors else None

        # get available modules(wiki, etc)
        mods_available = get_available_mods_by_user(username)
        mods_enabled = get_enabled_mods_by_user(username)

        return render_to_response("wiki/personal_wiki.html", {
            "wiki_exists": wiki_exists,
            "content": content,
            "page": os.path.splitext(dirent.obj_name)[0],
            "last_modified": last_modified,
            "latest_contributor": latest_contributor,
            "path": path,
            "repo_id": repo.id,
            "search_repo_id": repo.id,
            "search_wiki": True,
            "mods_enabled": mods_enabled,
            "mods_available": mods_available,
        },
                                  context_instance=RequestContext(request))
Example #2
0
def personal_wiki(request, page_name="home"):
    username = request.user.username
    wiki_exists = True
    try:
        content, repo, dirent = get_personal_wiki_page(username, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        # get available modules(wiki, etc)
        mods_available = get_available_mods_by_user(username)
        mods_enabled = get_enabled_mods_by_user(username)
        return render_to_response("wiki/personal_wiki.html", {
                "wiki_exists": wiki_exists,
                "mods_enabled": mods_enabled,
                "mods_available": mods_available,
                }, context_instance=RequestContext(request))
    except WikiPageMissing:
        repo = get_personal_wiki_repo(username)
        filename = clean_page_name(page_name) + '.md'
        if not seaserv.post_empty_file(repo.id, "/", filename, username):
            return render_error(request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse('personal_wiki', args=[page_name]))
    else:
        url_prefix = reverse('personal_wiki', args=[])
        content = convert_wiki_link(content, url_prefix, repo.id, username)
        
        # fetch file latest contributor and last modified
        path = '/' + dirent.obj_name
        file_path_hash = hashlib.md5(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12]            
        contributors, last_modified, last_commit_id = get_file_contributors(\
            repo.id, path.encode('utf-8'), file_path_hash, dirent.obj_id)
        latest_contributor = contributors[0] if contributors else None

        # get available modules(wiki, etc)
        mods_available = get_available_mods_by_user(username)
        mods_enabled = get_enabled_mods_by_user(username)
        
        return render_to_response("wiki/personal_wiki.html", {
                "wiki_exists": wiki_exists,
                "content": content,
                "page": os.path.splitext(dirent.obj_name)[0],
                "last_modified": last_modified,
                "latest_contributor": latest_contributor,
                "path": path,
                "repo_id": repo.id,
                "search_repo_id": repo.id,
                "search_wiki": True,
                "mods_enabled": mods_enabled,
                "mods_available": mods_available,
                }, context_instance=RequestContext(request))
Example #3
0
def personal_wiki(request, page_name="home"):
    username = request.user.username
    wiki_exists = True
    try:
        content, repo, dirent = get_personal_wiki_page(username, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
        return render_to_response(
            "wiki/personal_wiki.html", {"wiki_exists": wiki_exists}, context_instance=RequestContext(request)
        )
    except WikiPageMissing:
        repo = get_personal_wiki_repo(username)
        filename = clean_page_name(page_name) + ".md"
        if not post_empty_file(repo.id, "/", filename, username):
            return render_error(request, _("Failed to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse("personal_wiki", args=[page_name]))
    else:
        url_prefix = reverse("personal_wiki", args=[])
        content = convert_wiki_link(content, url_prefix, repo.id, username)

        # fetch file latest contributor and last modified
        path = "/" + dirent.obj_name
        file_path_hash = md5_constructor(urllib2.quote(path.encode("utf-8"))).hexdigest()[:12]
        contributors, last_modified, last_commit_id = get_file_contributors(
            repo.id, path.encode("utf-8"), file_path_hash, dirent.obj_id
        )
        latest_contributor = contributors[0] if contributors else None

        return render_to_response(
            "wiki/personal_wiki.html",
            {
                "wiki_exists": wiki_exists,
                "content": content,
                "page": os.path.splitext(dirent.obj_name)[0],
                "last_modified": last_modified,
                "latest_contributor": latest_contributor,
                "path": path,
                "repo_id": repo.id,
            },
            context_instance=RequestContext(request),
        )
Example #4
0
def group_wiki(request, group, page_name="home"):
    is_staff = True if check_group_staff(group.id, request.user) else False
    username = request.user.username
    content = ''
    wiki_exists = True
    last_modified, latest_contributor = None, None
    try:
        content, repo_id, obj_id = get_wiki_page(request, group, page_name)
    except WikiDoesNotExist:
        wiki_exists = False
    except WikiPageMissing:
        '''create that page for user'''
        repo = find_wiki_repo(request, group)
        # No need to check whether repo is none, since repo is already created
        
        filename = normalize_page_name(page_name) + '.md'
        if not post_empty_file(repo.id, "/", filename, username):
            return render_error(request, _("Faied to create wiki page. Please retry later."))
        return HttpResponseRedirect(reverse('group_wiki', args=[group.id, page_name]))
    else:
        content = convert_wiki_link(content, group, repo_id, username)
        
        # fetch file latest contributor and last modified
        path = '/' + page_name + '.md'
        file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12]            
        contributors, last_modified, last_commit_id = get_file_contributors(\
            repo_id, path.encode('utf-8'), file_path_hash, obj_id)
        latest_contributor = contributors[0] if contributors else None

    return render_to_response("group/group_wiki.html", {
            "group_id": group.id,
            "group" : group,
            "is_staff": is_staff,
            "content": content,
            "page": page_name,
            "wiki_exists": wiki_exists,
            "last_modified": last_modified,
            "latest_contributor": latest_contributor,
            }, context_instance=RequestContext(request))
Example #5
0
def view_file(request, repo_id):
    """
    Steps to view file:
    1. Get repo id and file path.
    2. Check user's permission.
    3. Check whether this file can be viewed online.
    4.1 Get file content if file is text file.
    4.2 Prepare flash if file is document.
    4.3 Prepare or use pdfjs if file is pdf.
    4.4 Other file return it's raw path.
    """
    username = request.user.username
    # check arguments
    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    path = request.GET.get('p', '/')
    obj_id = get_file_id_by_path(repo_id, path)
    if not obj_id:
        return render_error(request, _(u'File does not exist'))

    # construct some varibles
    u_filename = os.path.basename(path)
    current_commit = get_commits(repo_id, 0, 1)[0]

    # Check whether user has permission to view file and get file raw path,
    # render error page if permission is deny.
    raw_path, user_perm = get_file_view_path_and_perm(request, repo_id,
                                                      obj_id, u_filename)
    if not user_perm:
        return render_permission_error(request, _(u'Unable to view file'))

    # get file type and extension
    filetype, fileext = get_file_type_and_ext(u_filename)

    img_prev = None
    img_next = None
    ret_dict = {'err': '', 'file_content': '', 'encoding': '', 'file_enc': '',
                'file_encoding_list': [], 'html_exists': False,
                'filetype': filetype}
    
    fsize = get_file_size(obj_id)

    exceeds_limit, err_msg = file_size_exceeds_preview_limit(fsize, filetype)
    if exceeds_limit:
        ret_dict['err'] = err_msg
    else:
        """Choose different approach when dealing with different type of file."""
        if is_textual_file(file_type=filetype):
            handle_textual_file(request, filetype, raw_path, ret_dict)
            if filetype == MARKDOWN:
                c = ret_dict['file_content']
                ret_dict['file_content'] = convert_md_link(c, repo_id, username)
        elif filetype == DOCUMENT:
            handle_document(raw_path, obj_id, fileext, ret_dict)
        elif filetype == PDF:
            handle_pdf(raw_path, obj_id, fileext, ret_dict)
        elif filetype == IMAGE:
            parent_dir = os.path.dirname(path)
            dirs = list_dir_by_path(current_commit.id, parent_dir)
            if not dirs:
                raise Http404

            img_list = []
            for dirent in dirs:
                if not stat.S_ISDIR(dirent.props.mode):
                    fltype, flext = get_file_type_and_ext(dirent.obj_name)
                    if fltype == 'Image':
                        img_list.append(dirent.obj_name)

            if len(img_list) > 1:
                img_list.sort(lambda x, y : cmp(x.lower(), y.lower()))
                cur_img_index = img_list.index(u_filename) 
                if cur_img_index != 0:
                    img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1])
                if cur_img_index != len(img_list) - 1:
                    img_next = os.path.join(parent_dir, img_list[cur_img_index + 1])
        else:
            pass

    # generate file path navigator
    zipped = gen_path_link(path, repo.name)

    # file shared link
    l = FileShare.objects.filter(repo_id=repo_id).filter(
        username=username).filter(path=path)
    fileshare = l[0] if len(l) > 0 else None
    http_or_https = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain
    if fileshare:
        file_shared_link = gen_shared_link(request, fileshare.token, 'f')
    else:
        file_shared_link = ''

    # my contacts used in shared link autocomplete
    contacts = Contact.objects.filter(user_email=username)

    """List repo groups"""
    # Get groups this repo is shared.    
    if request.user.org:
        org_id = request.user.org['org_id']
        repo_shared_groups = get_org_groups_by_repo(org_id, repo_id)
    else:
        repo_shared_groups = get_shared_groups_by_repo(repo_id)
    # Filter out groups that user in joined.
    groups = [ x for x in repo_shared_groups if is_group_user(x.id, username)]
    if len(groups) > 1:
        ctx = {}
        ctx['groups'] = groups
        repogrp_str = render_to_string("snippets/repo_group_list.html", ctx)
    else:
        repogrp_str = '' 
    
    file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12]            

    # fetch file contributors and latest contributor
    contributors, last_modified, last_commit_id = get_file_contributors(repo_id, path.encode('utf-8'), file_path_hash, obj_id)
    latest_contributor = contributors[0] if contributors else None

    # check whether file is starred
    is_starred = False
    org_id = -1
    if request.user.org:
        org_id = request.user.org['org_id']
    is_starred = is_file_starred(username, repo.id, path.encode('utf-8'), org_id)

    template = 'view_file_%s.html' % ret_dict['filetype'].lower()
    search_repo_id = None
    if not repo.encrypted:
        search_repo_id = repo.id
    return render_to_response(template, {
            'repo': repo,
            'obj_id': obj_id,
            'filename': u_filename,
            'path': path,
            'zipped': zipped,
            'current_commit': current_commit,
            'fileext': fileext,
            'raw_path': raw_path,
            'fileshare': fileshare,
            'protocol': http_or_https,
            'domain': domain,
            'file_shared_link': file_shared_link,
            'contacts': contacts,
            'err': ret_dict['err'],
            'file_content': ret_dict['file_content'],
            'file_enc': ret_dict['file_enc'],
            'encoding': ret_dict['encoding'],
            'file_encoding_list':ret_dict['file_encoding_list'],
            'html_exists': ret_dict['html_exists'],
            'html_detail': ret_dict.get('html_detail', {}),
            'filetype': ret_dict['filetype'],
            "applet_root": get_ccnetapplet_root(),
            'groups': groups,
            'use_pdfjs':USE_PDFJS,
            'contributors': contributors,
            'latest_contributor': latest_contributor,
            'last_modified': last_modified,
            'last_commit_id': last_commit_id,
            'repo_group_str': repogrp_str,
            'is_starred': is_starred,
            'user_perm': user_perm,
            'img_prev': img_prev,
            'img_next': img_next,
            'search_repo_id': search_repo_id,
            }, context_instance=RequestContext(request))
Example #6
0
def view_file(request, repo_id):
    """
    Steps to view file:
    1. Get repo id and file path.
    2. Check user's permission.
    3. Check whether this file can be viewed online.
    4.1 Get file content if file is text file.
    4.2 Prepare flash if file is document.
    4.3 Prepare or use pdfjs if file is pdf.
    4.4 Other file return it's raw path.
    """
    username = request.user.username
    # check arguments
    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    path = request.GET.get("p", "/")
    obj_id = get_file_id_by_path(repo_id, path)
    if not obj_id:
        return render_error(request, _(u"File does not exist"))

    # construct some varibles
    u_filename = os.path.basename(path)
    filename_utf8 = urllib2.quote(u_filename.encode("utf-8"))
    current_commit = get_commits(repo_id, 0, 1)[0]

    # Check whether user has permission to view file and get file raw path,
    # render error page if permission is deny.
    raw_path, user_perm = get_file_view_path_and_perm(request, repo_id, obj_id, u_filename)
    if not user_perm:
        return render_permission_error(request, _(u"Unable to view file"))

    # get file type and extension
    filetype, fileext = get_file_type_and_ext(u_filename)

    img_prev = None
    img_next = None
    ret_dict = {
        "err": "",
        "file_content": "",
        "encoding": "",
        "file_enc": "",
        "file_encoding_list": [],
        "swf_exists": False,
        "filetype": filetype,
    }

    # Check file size
    fsize = get_file_size(obj_id)
    if fsize > FILE_PREVIEW_MAX_SIZE:
        from django.template.defaultfilters import filesizeformat

        err = _(u"File size surpasses %s, can not be opened online.") % filesizeformat(FILE_PREVIEW_MAX_SIZE)
        ret_dict["err"] = err
    else:
        """Choose different approach when dealing with different type of file."""
        if is_textual_file(file_type=filetype):
            handle_textual_file(request, filetype, raw_path, ret_dict)
            if filetype == MARKDOWN:
                c = ret_dict["file_content"]
                ret_dict["file_content"] = convert_md_link(c, repo_id, username)
        elif filetype == DOCUMENT:
            handle_document(raw_path, obj_id, fileext, ret_dict)
        elif filetype == PDF:
            handle_pdf(raw_path, obj_id, fileext, ret_dict)
        elif filetype == IMAGE:
            parent_dir = os.path.dirname(path)
            dirs = list_dir_by_path(current_commit.id, parent_dir)
            if not dirs:
                raise Http404

            img_list = []
            for dirent in dirs:
                if not stat.S_ISDIR(dirent.props.mode):
                    fltype, flext = get_file_type_and_ext(dirent.obj_name)
                    if fltype == "Image":
                        img_list.append(dirent.obj_name)

            if len(img_list) > 1:
                img_list.sort(lambda x, y: cmp(x.lower(), y.lower()))
                cur_img_index = img_list.index(u_filename)
                if cur_img_index != 0:
                    img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1])
                if cur_img_index != len(img_list) - 1:
                    img_next = os.path.join(parent_dir, img_list[cur_img_index + 1])
        else:
            pass

    # generate file path navigator
    zipped = gen_path_link(path, repo.name)

    # file shared link
    l = FileShare.objects.filter(repo_id=repo_id).filter(username=username).filter(path=path)
    fileshare = l[0] if len(l) > 0 else None
    http_or_https = request.is_secure() and "https" or "http"
    domain = RequestSite(request).domain
    if fileshare:
        file_shared_link = gen_shared_link(request, fileshare.token, "f")
    else:
        file_shared_link = ""

    # my contacts used in shared link autocomplete
    contacts = Contact.objects.filter(user_email=username)

    """List repo groups"""
    # Get groups this repo is shared.
    if request.user.org:
        org_id = request.user.org["org_id"]
        repo_shared_groups = get_org_groups_by_repo(org_id, repo_id)
    else:
        repo_shared_groups = get_shared_groups_by_repo(repo_id)
    # Filter out groups that user in joined.
    groups = [x for x in repo_shared_groups if is_group_user(x.id, username)]
    if len(groups) > 1:
        ctx = {}
        ctx["groups"] = groups
        repogrp_str = render_to_string("snippets/repo_group_list.html", ctx)
    else:
        repogrp_str = ""

    file_path_hash = md5_constructor(urllib2.quote(path.encode("utf-8"))).hexdigest()[:12]

    # fetch file contributors and latest contributor
    contributors, last_modified, last_commit_id = get_file_contributors(
        repo_id, path.encode("utf-8"), file_path_hash, obj_id
    )
    latest_contributor = contributors[0] if contributors else None

    # check whether file is starred
    is_starred = False
    org_id = -1
    if request.user.org:
        org_id = request.user.org["org_id"]
    is_starred = is_file_starred(username, repo.id, path.encode("utf-8"), org_id)

    template = "view_file_%s.html" % ret_dict["filetype"].lower()
    return render_to_response(
        template,
        {
            "repo": repo,
            "obj_id": obj_id,
            "filename": u_filename,
            "path": path,
            "zipped": zipped,
            "current_commit": current_commit,
            "fileext": fileext,
            "raw_path": raw_path,
            "fileshare": fileshare,
            "protocol": http_or_https,
            "domain": domain,
            "file_shared_link": file_shared_link,
            "contacts": contacts,
            "err": ret_dict["err"],
            "file_content": ret_dict["file_content"],
            "file_enc": ret_dict["file_enc"],
            "encoding": ret_dict["encoding"],
            "file_encoding_list": ret_dict["file_encoding_list"],
            "swf_exists": ret_dict["swf_exists"],
            "filetype": ret_dict["filetype"],
            "applet_root": get_ccnetapplet_root(),
            "groups": groups,
            "DOCUMENT_CONVERTOR_ROOT": DOCUMENT_CONVERTOR_ROOT,
            "use_pdfjs": USE_PDFJS,
            "contributors": contributors,
            "latest_contributor": latest_contributor,
            "last_modified": last_modified,
            "last_commit_id": last_commit_id,
            "repo_group_str": repogrp_str,
            "is_starred": is_starred,
            "user_perm": user_perm,
            "img_prev": img_prev,
            "img_next": img_next,
        },
        context_instance=RequestContext(request),
    )