Exemplo n.º 1
0
    def get(self, request, repo_id, format=None):
        repo = get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND, 'Repo not found.')

        # generate download url for client
        ccnet_applet_root = get_ccnetapplet_root()
        relay_id = get_session_info().id
        addr, port = get_ccnet_server_addr_port()
        email = request.user.username
        token = seafserv_threaded_rpc.generate_repo_token(
            repo_id, request.user.username)
        repo_name = repo.name
        enc = 1 if repo.encrypted else ''
        magic = repo.magic if repo.encrypted else ''

        info_json = {
            'relay_id': relay_id,
            'relay_addr': addr,
            'relay_port': port,
            'email': email,
            'token': token,
            'repo_id': repo_id,
            'repo_name': repo_name,
            'encrypted': enc,
            'magic': magic,
        }
        return Response(info_json)
Exemplo n.º 2
0
    def get(self, request, repo_id, format=None):
        repo = get_repo(repo_id)
        if not repo:
            return api_error(status.HTTP_404_NOT_FOUND, 'Repo not found.')

        # generate download url for client
        ccnet_applet_root = get_ccnetapplet_root()
        relay_id = get_session_info().id
        addr, port = get_ccnet_server_addr_port ()
        email = request.user.username
        token = seafserv_threaded_rpc.generate_repo_token(repo_id,
                                                          request.user.username)
        repo_name = repo.name
        enc = 1 if repo.encrypted else ''
        magic = repo.magic if repo.encrypted else ''

        info_json = {
            'relay_id': relay_id,
            'relay_addr': addr,
            'relay_port': port,
            'email': email,
            'token': token,
            'repo_id': repo_id,
            'repo_name': repo_name,
            'encrypted': enc,
            'magic': magic,
            }
        return Response(info_json)
Exemplo n.º 3
0
    def get(self, request, repo_id, format=None):
        # check whether user can view repo
        repo = get_repo(repo_id)
        if not repo:
            return api_error('404')

        # if not can_access_repo(request, repo.id):
        #     return api_error('403')

        # check whether use is repo owner
        if validate_owner(request, repo_id):
            owner = "self"
        else:
            owner = "share"

        last_commit = get_commits(repo.id, 0, 1)[0].ctime
        repo.latest_modify = last_commit.ctime if last_commit else None

        # query repo infomation
        repo.size = seafserv_threaded_rpc.server_repo_size(repo_id)
        current_commit = get_commits(repo_id, 0, 1)[0]
        root_id = current_commit.root_id if current_commit else None

        # generate download url for client
        ccnet_applet_root = get_ccnetapplet_root()
        relay_id = get_session_info().id
        addr, port = get_ccnet_server_addr_port ()
        email = quote(request.user.username)
        token = get_repo_token_nonnull(repo_id, request.user.username)
        quote_repo_name = quote(repo.name.encode('utf-8'))
        enc = 1 if repo.encrypted else ''

        url = ccnet_applet_root + "/repo/download/"
        url += "?relay_id=%s&relay_addr=%s&relay_port=%s" % (relay_id, addr, port)
        url += "&email=%s&token=%s" % (email, token)
        url += "&repo_id=%s&repo_name=%s&encrypted=%s" % (repo_id, quote_repo_name, enc)
        
        repo_json = {
            "type":"repo",
            "id":repo.id,
            "owner":owner,
            "name":repo.name,
            "desc":repo.desc,
            "mtime":repo.lastest_modify,
            "size":repo.size,
            "encrypted":repo.encrypted,
            "root":root_id,
            "download_url": url,
            }

        return Response(repo_json)
Exemplo n.º 4
0
Arquivo: repo.py Projeto: genba/seahub
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page
    """
    username = request.user.username
    path = get_path_from_request(request)
    user_perm = check_repo_access_permission(repo.id, username)
    if user_perm is None:
        return render_to_response('repo_access_deny.html', {
            'repo': repo,
        },
                                  context_instance=RequestContext(request))

    server_crypto = False
    if repo.encrypted:
        try:
            server_crypto = UserOptions.objects.is_server_crypto(username)
        except CryptoOptionNotSetError:
            return render_to_response('options/set_user_options.html', {},
                                      context_instance=RequestContext(request))

        if (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
                and not is_password_set(repo.id, username):
            return render_to_response('decrypt_repo_form.html', {
                    'repo': repo,
                    'next': get_next_url_from_request(request) or \
                        reverse('repo', args=[repo.id])
                    }, context_instance=RequestContext(request))

    # query context args
    applet_root = get_ccnetapplet_root()
    httpserver_root = get_httpserver_root()
    max_upload_file_size = MAX_UPLOAD_FILE_SIZE

    protocol = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain

    contacts = Contact.objects.get_contacts_by_user(username)
    accessible_repos = [
        repo
    ] if repo.encrypted else get_unencry_rw_repos_by_user(username)

    head_commit = get_commit(repo.head_cmmt_id)
    if not head_commit:
        raise Http404
    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    search_repo_id = None if repo.encrypted else repo.id
    repo_owner = seafile_api.get_repo_owner(repo.id)
    is_repo_owner = True if repo_owner == username else False

    more_start = None
    file_list, dir_list, dirent_more = get_repo_dirents(request,
                                                        repo.id,
                                                        head_commit,
                                                        path,
                                                        offset=0,
                                                        limit=100)
    if dirent_more:
        more_start = 100
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html",
                                          {'groups': repo_groups})
    else:
        repo_group_str = ''
    upload_url = get_upload_url(request, repo.id)

    if repo.encrypted and repo.enc_version == 2 and not server_crypto:
        ajax_upload_url = get_blks_upload_url(request, repo.id)
        ajax_update_url = get_blks_update_url(request, repo.id)
    else:
        ajax_upload_url = get_ajax_upload_url(request, repo.id)
        ajax_update_url = get_ajax_update_url(request, repo.id)
    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_dir_share_link(fileshare)

    joined_groups = get_personal_groups_by_user(request.user.username)

    return render_to_response('repo.html', {
        'repo': repo,
        'user_perm': user_perm,
        'repo_owner': repo_owner,
        'is_repo_owner': is_repo_owner,
        'current_commit': head_commit,
        'password_set': True,
        'repo_size': repo_size,
        'dir_list': dir_list,
        'file_list': file_list,
        'dirent_more': dirent_more,
        'more_start': more_start,
        'path': path,
        'zipped': zipped,
        'accessible_repos': accessible_repos,
        'applet_root': applet_root,
        'groups': repo_groups,
        'joined_groups': joined_groups,
        'repo_group_str': repo_group_str,
        'no_quota': no_quota,
        'max_upload_file_size': max_upload_file_size,
        'upload_url': upload_url,
        'ajax_upload_url': ajax_upload_url,
        'ajax_update_url': ajax_update_url,
        'httpserver_root': httpserver_root,
        'protocol': protocol,
        'domain': domain,
        'contacts': contacts,
        'fileshare': fileshare,
        'dir_shared_link': dir_shared_link,
        'search_repo_id': search_repo_id,
        'ENABLE_SUB_LIBRARY': ENABLE_SUB_LIBRARY,
        'server_crypto': server_crypto,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 5
0
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page
    """
    username = request.user.username
    path = get_path_from_request(request)
    user_perm = check_repo_access_permission(repo.id, username)
    if user_perm is None:
        return render_to_response("repo_access_deny.html", {"repo": repo}, context_instance=RequestContext(request))

    if (
        repo.encrypted
        and (repo.enc_version == 1 or (repo.enc_version == 2 and SERVER_CRYPTO))
        and not is_password_set(repo.id, username)
    ):
        return render_to_response(
            "decrypt_repo_form.html",
            {"repo": repo, "next": get_next_url_from_request(request) or reverse("repo", args=[repo.id])},
            context_instance=RequestContext(request),
        )

    # query context args
    applet_root = get_ccnetapplet_root()
    httpserver_root = get_httpserver_root()
    max_upload_file_size = MAX_UPLOAD_FILE_SIZE

    protocol = request.is_secure() and "https" or "http"
    domain = RequestSite(request).domain

    contacts = Contact.objects.get_contacts_by_user(username)
    accessible_repos = [repo] if repo.encrypted else get_unencry_rw_repos_by_user(username)

    head_commit = get_commit(repo.head_cmmt_id)
    if not head_commit:
        raise Http404
    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    search_repo_id = None if repo.encrypted else repo.id
    repo_owner = seafile_api.get_repo_owner(repo.id)
    is_repo_owner = True if repo_owner == username else False

    more_start = None
    file_list, dir_list, dirent_more = get_repo_dirents(request, repo.id, head_commit, path, offset=0, limit=100)
    if dirent_more:
        more_start = 100
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html", {"groups": repo_groups})
    else:
        repo_group_str = ""
    upload_url = get_upload_url(request, repo.id)

    if repo.encrypted and repo.enc_version == 2 and not SERVER_CRYPTO:
        ajax_upload_url = get_blks_upload_url(request, repo.id)
        ajax_update_url = get_blks_update_url(request, repo.id)
    else:
        ajax_upload_url = get_ajax_upload_url(request, repo.id)
        ajax_update_url = get_ajax_update_url(request, repo.id)
    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_dir_share_link(fileshare)

    joined_groups = get_personal_groups_by_user(request.user.username)

    return render_to_response(
        "repo.html",
        {
            "repo": repo,
            "user_perm": user_perm,
            "repo_owner": repo_owner,
            "is_repo_owner": is_repo_owner,
            "current_commit": head_commit,
            "password_set": True,
            "repo_size": repo_size,
            "dir_list": dir_list,
            "file_list": file_list,
            "dirent_more": dirent_more,
            "more_start": more_start,
            "path": path,
            "zipped": zipped,
            "accessible_repos": accessible_repos,
            "applet_root": applet_root,
            "groups": repo_groups,
            "joined_groups": joined_groups,
            "repo_group_str": repo_group_str,
            "no_quota": no_quota,
            "max_upload_file_size": max_upload_file_size,
            "upload_url": upload_url,
            "ajax_upload_url": ajax_upload_url,
            "ajax_update_url": ajax_update_url,
            "httpserver_root": httpserver_root,
            "protocol": protocol,
            "domain": domain,
            "contacts": contacts,
            "fileshare": fileshare,
            "dir_shared_link": dir_shared_link,
            "search_repo_id": search_repo_id,
            "ENABLE_SUB_LIBRARY": ENABLE_SUB_LIBRARY,
        },
        context_instance=RequestContext(request),
    )
Exemplo n.º 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)
    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))
Exemplo n.º 7
0
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page

    """
    username = request.user.username
    user_perm = check_repo_access_permission(repo.id, username)
    if user_perm is None:
        return render_to_response('repo_access_deny.html', {
                'repo': repo,
                }, context_instance=RequestContext(request))

    if repo.encrypted and not is_password_set(repo.id, username):
        return render_to_response('decrypt_repo_form.html', {
                'repo': repo,
                'next': get_next_url_from_request(request) or \
                    reverse('repo', args=[repo.id])
                }, context_instance=RequestContext(request))

    # query context args
    applet_root = get_ccnetapplet_root()
    httpserver_root = get_httpserver_root()
    max_upload_file_size = MAX_UPLOAD_FILE_SIZE
    
    protocol = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain
    path = get_path_from_request(request)

    contacts = Contact.objects.get_contacts_by_user(username)
    accessible_repos = [repo] if repo.encrypted else get_unencry_rw_repos_by_user(username)

    head_commit = get_commit(repo.head_cmmt_id)
    if not head_commit:
        raise Http404
    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    history_limit = seaserv.get_repo_history_limit(repo.id)
    search_repo_id = None if repo.encrypted else repo.id
    
    is_repo_owner = seafile_api.is_repo_owner(username, repo.id)
    file_list, dir_list = get_repo_dirents(request, repo.id, head_commit, path)
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html",
                                          {'groups': repo_groups})
    else:
        repo_group_str = ''
    upload_url = get_upload_url(request, repo.id)
    update_url = get_update_url(request, repo.id)
    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_shared_link(request, fileshare)

    return render_to_response('repo.html', {
            'repo': repo,
            'user_perm': user_perm,
            'is_repo_owner': is_repo_owner,
            'current_commit': head_commit,
            'password_set': True,
            'repo_size': repo_size,
            'dir_list': dir_list,
            'file_list': file_list,
            'path': path,
            'zipped': zipped,
            'accessible_repos': accessible_repos,
            'applet_root': applet_root,
            'groups': repo_groups,
            'repo_group_str': repo_group_str,
            'no_quota': no_quota,
            'max_upload_file_size': max_upload_file_size,
            'upload_url': upload_url,
            'update_url': update_url,
            'httpserver_root': httpserver_root,
            'protocol': protocol,
            'domain': domain,
            'contacts': contacts,
            'fileshare': fileshare,
            'dir_shared_link': dir_shared_link,
            'history_limit': history_limit,
            'search_repo_id': search_repo_id,
            }, context_instance=RequestContext(request))
Exemplo n.º 8
0
 def get_applet_root(self):
     return get_ccnetapplet_root()
Exemplo n.º 9
0
def render_repo(request, repo):
    """Steps to show repo page:
    If user has permission to view repo
      If repo is encrypt and password is not set on server
        return decrypt repo page
      If repo is not encrypt or password is set on server
        Show repo direntries based on requested path
    If user does not have permission to view repo
      return permission deny page
    """
    username = request.user.username
    path = get_path_from_request(request)
    user_perm = check_repo_access_permission(repo.id, username)
    if user_perm is None:
        return render_to_response('repo_access_deny.html', {
                'repo': repo,
                }, context_instance=RequestContext(request))

    server_crypto = False
    if repo.encrypted:
        try:
            server_crypto = UserOptions.objects.is_server_crypto(username)
        except CryptoOptionNotSetError:
            return render_to_response('options/set_user_options.html', {
                    }, context_instance=RequestContext(request))
            
        if (repo.enc_version == 1 or (repo.enc_version == 2 and server_crypto)) \
                and not is_password_set(repo.id, username):
            return render_to_response('decrypt_repo_form.html', {
                    'repo': repo,
                    'next': get_next_url_from_request(request) or \
                        reverse('repo', args=[repo.id])
                    }, context_instance=RequestContext(request))

    # query context args
    applet_root = get_ccnetapplet_root()
    httpserver_root = get_httpserver_root()
    max_upload_file_size = MAX_UPLOAD_FILE_SIZE
    
    protocol = request.is_secure() and 'https' or 'http'
    domain = RequestSite(request).domain

    contacts = Contact.objects.get_contacts_by_user(username)
    accessible_repos = [repo] if repo.encrypted else get_unencry_rw_repos_by_user(username)
    joined_groups = get_personal_groups_by_user(request.user.username)

    head_commit = get_commit(repo.head_cmmt_id)
    if not head_commit:
        raise Http404
    repo_size = get_repo_size(repo.id)
    no_quota = is_no_quota(repo.id)
    search_repo_id = None if repo.encrypted else repo.id
    repo_owner = seafile_api.get_repo_owner(repo.id)
    is_repo_owner = True if repo_owner == username else False
    
    more_start = None
    file_list, dir_list, dirent_more = get_repo_dirents(request, repo.id, head_commit, path, offset=0, limit=100)
    if dirent_more:
        more_start = 100
    zipped = get_nav_path(path, repo.name)
    repo_groups = get_shared_groups_by_repo_and_user(repo.id, username)
    if len(repo_groups) > 1:
        repo_group_str = render_to_string("snippets/repo_group_list.html",
                                          {'groups': repo_groups})
    else:
        repo_group_str = ''
    upload_url = get_upload_url(request, repo.id)

    if repo.encrypted and repo.enc_version == 2 and not server_crypto:
        ajax_upload_url = get_blks_upload_url(request, repo.id)
        ajax_update_url = get_blks_update_url(request, repo.id)
    else:
        ajax_upload_url = get_ajax_upload_url(request, repo.id)
        ajax_update_url = get_ajax_update_url(request, repo.id)
    fileshare = get_fileshare(repo.id, username, path)
    dir_shared_link = get_dir_share_link(fileshare)
    uploadlink = get_uploadlink(repo.id, username, path)
    dir_shared_upload_link = get_dir_shared_upload_link(uploadlink)

    return render_to_response('repo.html', {
            'repo': repo,
            'user_perm': user_perm,
            'repo_owner': repo_owner,
            'is_repo_owner': is_repo_owner,
            'current_commit': head_commit,
            'password_set': True,
            'repo_size': repo_size,
            'dir_list': dir_list,
            'file_list': file_list,
            'dirent_more': dirent_more,
            'more_start': more_start,
            'path': path,
            'zipped': zipped,
            'accessible_repos': accessible_repos,
            'applet_root': applet_root,
            'groups': repo_groups,
            'joined_groups': joined_groups,
            'repo_group_str': repo_group_str,
            'no_quota': no_quota,
            'max_upload_file_size': max_upload_file_size,
            'upload_url': upload_url,
            'ajax_upload_url': ajax_upload_url,
            'ajax_update_url': ajax_update_url,
            'httpserver_root': httpserver_root,
            'protocol': protocol,
            'domain': domain,
            'contacts': contacts,
            'fileshare': fileshare,
            'dir_shared_link': dir_shared_link,
            'uploadlink': uploadlink,
            'dir_shared_upload_link': dir_shared_upload_link,
            'search_repo_id': search_repo_id,
            'ENABLE_SUB_LIBRARY': ENABLE_SUB_LIBRARY,
            'server_crypto': server_crypto,
            }, context_instance=RequestContext(request))
Exemplo n.º 10
0
 def get_applet_root(self):
     return get_ccnetapplet_root()
Exemplo n.º 11
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),
    )