• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python seafile_api.get_fileserver_access_token函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中seaserv.seafile_api.get_fileserver_access_token函数的典型用法代码示例。如果您正苦于以下问题:Python get_fileserver_access_token函数的具体用法?Python get_fileserver_access_token怎么用?Python get_fileserver_access_token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_fileserver_access_token函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: extract_xmind_image

def extract_xmind_image(repo_id, path, size=XMIND_IMAGE_SIZE):

    # get inner path
    file_name = os.path.basename(path)
    file_id = seafile_api.get_file_id_by_path(repo_id, path)
    fileserver_token = seafile_api.get_fileserver_access_token(repo_id,
            file_id, 'view', '')
    inner_path = gen_inner_file_get_url(fileserver_token, file_name)

    # extract xmind image
    xmind_file = urllib2.urlopen(inner_path)
    xmind_file_str = StringIO(xmind_file.read())
    xmind_zip_file = zipfile.ZipFile(xmind_file_str, 'r')
    extracted_xmind_image = xmind_zip_file.read('Thumbnails/thumbnail.png')
    extracted_xmind_image_str = StringIO(extracted_xmind_image)

    # save origin xmind image to thumbnail folder
    thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size))
    if not os.path.exists(thumbnail_dir):
        os.makedirs(thumbnail_dir)
    local_xmind_image = os.path.join(thumbnail_dir, file_id)

    try:
        ret = _create_thumbnail_common(extracted_xmind_image_str, local_xmind_image, size)
        return ret
    except Exception as e:
        logger.error(e)
        return (False, 500)
开发者ID:haiwen,项目名称:seahub,代码行数:28,代码来源:utils.py


示例2: generate_thumbnail

def generate_thumbnail(request, repo_id, size, path):
    """ generate and save thumbnail if not exist
    """

    thumbnail_dir = os.path.join(THUMBNAIL_ROOT, str(size))
    if not os.path.exists(thumbnail_dir):
        os.makedirs(thumbnail_dir)

    file_id = get_file_id_by_path(repo_id, path)
    thumbnail_file = os.path.join(thumbnail_dir, file_id)

    if os.path.exists(thumbnail_file):
        return True

    token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view',
                                                    '', use_onetime = False)

    inner_path = gen_inner_file_get_url(token, os.path.basename(path))
    try:
        image_file = urllib2.urlopen(inner_path)
        f = StringIO(image_file.read())
        image = Image.open(f)
        if image.mode not in ["1", "L", "P", "RGB", "RGBA"]:
            image = image.convert("RGB")
        image.thumbnail((size, size), Image.ANTIALIAS)
        image.save(thumbnail_file, THUMBNAIL_EXTENSION)
        return True
    except Exception as e:
        logger.error(e)
        return False
开发者ID:penyatree,项目名称:seahub,代码行数:30,代码来源:utils.py


示例3: get_upload_url

def get_upload_url(request, repo_id):
    username = request.user.username
    if check_repo_access_permission(repo_id, request.user) == "rw":
        token = seafile_api.get_fileserver_access_token(repo_id, "dummy", "upload", username)
        return gen_file_upload_url(token, "upload")
    else:
        return ""
开发者ID:vikingliu,项目名称:seahub,代码行数:7,代码来源:repo.py


示例4: create_video_thumbnails

def create_video_thumbnails(repo, file_id, path, size, thumbnail_file, file_size):

    t1 = timeit.default_timer()
    token = seafile_api.get_fileserver_access_token(repo.id,
            file_id, 'view', '', use_onetime=False)

    if not token:
        return (False, 500)

    inner_path = gen_inner_file_get_url(token, os.path.basename(path))
    clip = VideoFileClip(inner_path)
    tmp_path = str(os.path.join(tempfile.gettempdir(), '%s.png' % file_id[:8]))

    clip.save_frame(tmp_path, t=THUMBNAIL_VIDEO_FRAME_TIME)
    t2 = timeit.default_timer()
    logger.debug('Create thumbnail of [%s](size: %s) takes: %s' % (path, file_size, (t2 - t1)))

    try:
        ret = _create_thumbnail_common(tmp_path, thumbnail_file, size)
        os.unlink(tmp_path)
        return ret
    except Exception as e:
        logger.error(e)
        os.unlink(tmp_path)
        return (False, 500)
开发者ID:haiwen,项目名称:seahub,代码行数:25,代码来源:utils.py


示例5: get_group_msgs

def get_group_msgs(groupid, page, username):

    # Show 15 group messages per page.
    paginator = Paginator(GroupMessage.objects.filter(group_id=groupid).order_by("-timestamp"), 15)

    # If page request (9999) is out of range, return None
    try:
        group_msgs = paginator.page(page)
    except (EmptyPage, InvalidPage):
        return None

    # Force evaluate queryset to fix some database error for mysql.
    group_msgs.object_list = list(group_msgs.object_list)

    attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list)

    msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list)
    reply_to_list = [r.reply_to_id for r in msg_replies]

    for msg in group_msgs.object_list:
        msg.reply_cnt = reply_to_list.count(msg.id)
        msg.replies = []
        for r in msg_replies:
            if msg.id == r.reply_to_id:
                msg.replies.append(r)
        msg.replies = msg.replies[-3:]

        for att in attachments:
            if att.group_message_id != msg.id:
                continue

            # Attachment name is file name or directory name.
            # If is top directory, use repo name instead.
            path = att.path
            if path == "/":
                repo = seafile_api.get_repo(att.repo_id)
                if not repo:
                    # TODO: what should we do here, tell user the repo
                    # is no longer exists?
                    continue
                att.name = repo.name
            else:
                path = path.rstrip("/")  # cut out last '/' if possible
                att.name = os.path.basename(path)

            # Load to discuss page if attachment is a image and from recommend.
            if att.attach_type == "file" and att.src == "recommend":
                att.filetype, att.fileext = get_file_type_and_ext(att.name)
                if att.filetype == IMAGE:
                    att.obj_id = seafile_api.get_file_id_by_path(att.repo_id, path)
                    if not att.obj_id:
                        att.err = "File does not exist"
                    else:
                        att.token = seafile_api.get_fileserver_access_token(att.repo_id, att.obj_id, "view", username)
                        att.img_url = gen_file_get_url(att.token, att.name)

            msg.attachment = att

    return group_msgs
开发者ID:rominf,项目名称:seahub,代码行数:59,代码来源:utils.py


示例6: get_onlyoffice_dict

def get_onlyoffice_dict(username, repo_id, file_path,
        file_id='', can_edit=False, can_download=True):

    repo = seafile_api.get_repo(repo_id)
    if repo.is_virtual:
        origin_repo_id = repo.origin_repo_id
        origin_file_path = posixpath.join(repo.origin_path, file_path.strip('/'))
        # for view history/trash/snapshot file
        if not file_id:
            file_id = seafile_api.get_file_id_by_path(origin_repo_id,
                    origin_file_path)
    else:
        origin_repo_id = repo_id
        origin_file_path = file_path
        if not file_id:
            file_id = seafile_api.get_file_id_by_path(repo_id,
                    file_path)

    dl_token = seafile_api.get_fileserver_access_token(repo_id,
            file_id, 'download', username, use_onetime=True)
    if not dl_token:
        return None

    filetype, fileext = get_file_type_and_ext(file_path)
    if fileext in ('xls', 'xlsx', 'ods', 'fods', 'csv'):
        document_type = 'spreadsheet'
    elif fileext in ('pptx', 'ppt', 'odp', 'fodp', 'ppsx', 'pps'):
        document_type = 'presentation'
    else:
        document_type = 'text'

    doc_info = json.dumps({'repo_id': repo_id, 'file_path': file_path, 'username': username})
    doc_key = hashlib.md5(force_bytes(origin_repo_id + origin_file_path + file_id)).hexdigest()[:20]
    cache.set("ONLYOFFICE_%s" % doc_key, doc_info, None)

    file_name = os.path.basename(file_path.rstrip('/'))
    doc_url = gen_file_get_url(dl_token, file_name)

    base_url = get_site_scheme_and_netloc()
    onlyoffice_editor_callback_url = reverse('onlyoffice_editor_callback')
    calllback_url = urlparse.urljoin(base_url, onlyoffice_editor_callback_url)

    return_dict = {
        'repo_id': repo_id,
        'path': file_path,
        'ONLYOFFICE_APIJS_URL': ONLYOFFICE_APIJS_URL,
        'file_type': fileext,
        'doc_key': doc_key,
        'doc_title': file_name,
        'doc_url': doc_url,
        'document_type': document_type,
        'callback_url': calllback_url,
        'can_edit': can_edit,
        'can_download': can_download,
        'username': username,
        'enable_watermark': ENABLE_WATERMARK and not can_edit,
    }

    return return_dict
开发者ID:haiwen,项目名称:seahub,代码行数:59,代码来源:utils.py


示例7: view_shared_upload_link

def view_shared_upload_link(request, token):
    assert token is not None  # Checked by URLconf

    uploadlink = UploadLinkShare.objects.get_valid_upload_link_by_token(token)
    if uploadlink is None:
        raise Http404

    if uploadlink.is_encrypted():
        if not check_share_link_access(request.user.username, token):
            d = {"token": token, "view_name": "view_shared_upload_link"}
            if request.method == "POST":
                post_values = request.POST.copy()
                post_values["enc_password"] = uploadlink.password
                form = SharedLinkPasswordForm(post_values)
                d["form"] = form
                if form.is_valid():
                    # set cache for non-anonymous user
                    if request.user.is_authenticated():
                        set_share_link_access(request.user.username, token)
                else:
                    return render_to_response(
                        "share_access_validation.html", d, context_instance=RequestContext(request)
                    )
            else:
                return render_to_response("share_access_validation.html", d, context_instance=RequestContext(request))

    username = uploadlink.username
    repo_id = uploadlink.repo_id
    path = uploadlink.path
    dir_name = os.path.basename(path[:-1])

    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    uploadlink.view_cnt = F("view_cnt") + 1
    uploadlink.save()

    no_quota = True if seaserv.check_quota(repo_id) < 0 else False

    token = seafile_api.get_fileserver_access_token(repo_id, "dummy", "upload", request.user.username)
    ajax_upload_url = gen_file_upload_url(token, "upload-aj")

    return render_to_response(
        "view_shared_upload_link.html",
        {
            "repo": repo,
            "token": token,
            "path": path,
            "username": username,
            "dir_name": dir_name,
            "max_upload_file_size": seaserv.MAX_UPLOAD_FILE_SIZE,
            "no_quota": no_quota,
            "ajax_upload_url": ajax_upload_url,
            "uploadlink": uploadlink,
        },
        context_instance=RequestContext(request),
    )
开发者ID:vikingliu,项目名称:seahub,代码行数:58,代码来源:repo.py


示例8: view_shared_upload_link

def view_shared_upload_link(request, token):
    assert token is not None    # Checked by URLconf

    uploadlink = UploadLinkShare.objects.get_valid_upload_link_by_token(token)
    if uploadlink is None:
        raise Http404

    if uploadlink.is_encrypted():
        if not check_share_link_access(request.user.username, token):
            d = {'token': token, 'view_name': 'view_shared_upload_link', }
            if request.method == 'POST':
                post_values = request.POST.copy()
                post_values['enc_password'] = uploadlink.password
                form = SharedLinkPasswordForm(post_values)
                d['form'] = form
                if form.is_valid():
                    # set cache for non-anonymous user
                    if request.user.is_authenticated():
                        set_share_link_access(request.user.username, token)
                else:
                    return render_to_response('share_access_validation.html', d,
                                              context_instance=RequestContext(request))
            else:
                return render_to_response('share_access_validation.html', d,
                                          context_instance=RequestContext(request))

    username = uploadlink.username
    repo_id = uploadlink.repo_id
    path = uploadlink.path
    dir_name = os.path.basename(path[:-1])

    repo = get_repo(repo_id)
    if not repo:
        raise Http404

    uploadlink.view_cnt = F('view_cnt') + 1
    uploadlink.save()

    no_quota = True if seaserv.check_quota(repo_id) < 0 else False

    token = seafile_api.get_fileserver_access_token(repo_id, 'dummy',
                                                    'upload', request.user.username)
    ajax_upload_url = gen_file_upload_url(token, 'upload-aj')

    return render_to_response('view_shared_upload_link.html', {
            'repo': repo,
            'token': token,
            'path': path,
            'username': username,
            'dir_name': dir_name,
            'max_upload_file_size': seaserv.MAX_UPLOAD_FILE_SIZE,
            'no_quota': no_quota,
            'ajax_upload_url': ajax_upload_url,
            'uploadlink': uploadlink,
            'enable_upload_folder': ENABLE_UPLOAD_FOLDER,
            }, context_instance=RequestContext(request))
开发者ID:e1th0r,项目名称:seahub,代码行数:56,代码来源:repo.py


示例9: post

    def post(self, request):
        """ Save file.
        """

        # 在默认情况下,所有的编辑参与者退出编辑5分钟之后,毕升Office会触发回存逻辑;
        # 或者在所以用户退出编辑之后,如果有用户再打开预览,也会触发回存。

        # {u'action': u'saveBack',
        #  u'data': {u'changesUrl': u'2bd816895cb7a72dffa4810d2ba5c474/changes.zip',
        #            u'delta': 10,
        #            u'docId': u'2bd816895cb7a72dffa4810d2ba5c474',
        #            u'docURL': u'/s3/draft/...',
        #            u'modifyBy': [{u'avatar': u'http://192.168.1.113:8000/media/avatars/default.png',
        #                           u'nickName': u'lian',
        #                           u'oid': u'[email protected]',
        #                           u'privilege': None,
        #                           u'uid': u'[email protected]'}],
        #            u'unchanged': False},
        #  u'docId': u'2bd816895cb7a72dffa4810d2ba5c474'}

        post_data = json.loads(request.body)

        # check action from bisheng server
        action = post_data.get('action')
        if action != 'saveBack':
            return Response()

        # ger file basic info
        doc_id = post_data.get('docId')
        file_info = cache.get('BISHENG_OFFICE_' + doc_id)

        username = file_info.get('username')
        repo_id = file_info.get('repo_id')
        file_path = file_info.get('file_path')

        # get content of new editted file
        data = post_data.get('data')
        file_url = urlparse.urljoin(BISHENG_OFFICE_HOST_DOMAIN, data.get('docURL'))
        files = {
            'file': requests.get(file_url).content,
            'file_name': os.path.basename(file_path),
            'target_file': file_path,
        }

        # prepare update token for seafhttp
        fake_obj_id = {'online_office_update': True,}
        update_token = seafile_api.get_fileserver_access_token(
            repo_id, json.dumps(fake_obj_id), 'update', username)

        # update file
        update_url = gen_inner_file_upload_url('update-api', update_token)
        requests.post(update_url, files=files)

        return Response()
开发者ID:haiwen,项目名称:seahub,代码行数:54,代码来源:views.py


示例10: get

    def get(self, request, repo_id):
        """ get info of a single file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if path[0] != '/':
            path = '/' + path

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'file/folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if stat.S_ISDIR(dirent.mode):
            is_file = False
        else:
            is_file = True

        username = request.user.username
        if is_file and request.GET.get('dl', '0') == '1':

            token = seafile_api.get_fileserver_access_token(repo_id,
                dirent.obj_id, 'download', username, use_onetime=True)
            dl_url = gen_file_get_url(token, dirent.obj_name)
            send_file_access_msg(request, repo, path, 'web')
            return Response({'download_url': dl_url})

        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
开发者ID:RaphaelWimmer,项目名称:seahub,代码行数:49,代码来源:library_dirents.py


示例11: get

    def get(self, request, repo_id):
        """ get info of a single file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = normalize_file_path(path)

        try:
            dirent = seafile_api.get_dirent_by_path(repo_id, path)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not dirent:
            error_msg = 'File or folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if stat.S_ISDIR(dirent.mode):
            is_file = False
        else:
            is_file = True

        username = request.user.username
        if is_file and request.GET.get('dl', '0') == '1':

            token = seafile_api.get_fileserver_access_token(
                repo_id, dirent.obj_id, 'download', username,
                use_onetime=settings.FILESERVER_TOKEN_ONCE_ONLY)

            if not token:
                error_msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

            dl_url = gen_file_get_url(token, dirent.obj_name)
            send_file_access_msg(request, repo, path, 'web')
            return Response({'download_url': dl_url})

        dirent_info = get_dirent_info(dirent)

        return Response(dirent_info)
开发者ID:haiwen,项目名称:seahub,代码行数:47,代码来源:library_dirents.py


示例12: repl

    def repl(matchobj):
        if matchobj.group(2):  # return origin string in backquotes
            return matchobj.group(2)

        page_alias = page_name = matchobj.group(1).strip()
        if len(page_name.split("|")) > 1:
            page_alias = page_name.split("|")[0]
            page_name = page_name.split("|")[1]

        filetype, fileext = get_file_type_and_ext(page_name)
        if fileext == "":
            # convert page_name that extension is missing to a markdown page
            try:
                dirent = get_wiki_dirent(repo_id, page_name)
                a_tag = """<a href="%s">%s</a>"""
                return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + "/"), page_alias)
            except (WikiDoesNotExist, WikiPageMissing):
                a_tag = """<a href="%s" class="wiki-page-missing">%s</a>"""
                return a_tag % (smart_str(url_prefix + normalize_page_name(page_name) + "/"), page_alias)
        elif filetype == IMAGE:
            # load image to wiki page
            path = "/" + page_name
            filename = os.path.basename(path)
            obj_id = seaserv.get_file_id_by_path(repo_id, path)
            if not obj_id:
                # Replace '/' in page_name to '-', since wiki name can not
                # contain '/'.
                return """<a href="%s" class="wiki-page-missing">%s</a>""" % (
                    url_prefix + "/" + page_name.replace("/", "-"),
                    page_name,
                )

            token = seafile_api.get_fileserver_access_token(repo_id, obj_id, "view", username)
            ret = '<img src="%s" alt="%s" class="wiki-image" />' % (gen_file_get_url(token, filename), filename)
            return smart_str(ret)
        else:
            from seahub.base.templatetags.seahub_tags import file_icon_filter
            from django.conf import settings

            # convert other types of filelinks to clickable links
            path = "/" + page_name
            icon = file_icon_filter(page_name)
            s = reverse("view_lib_file", args=[repo_id, path])
            a_tag = """<img src="%simg/file/%s" alt="%s" class="file-icon vam" /> <a href="%s" class="vam" target="_blank">%s</a>"""
            ret = a_tag % (settings.MEDIA_URL, icon, icon, smart_str(s), page_name)
            return smart_str(ret)
开发者ID:XuTuKe,项目名称:seahub,代码行数:46,代码来源:utils.py


示例13: get

    def get(self, request, token):
        """ Get file upload url according to upload link token.

        Permission checking:
        1. anyone has the upload link token can perform this action;
        """

        try:
            uls = UploadLinkShare.objects.get(token=token)
        except UploadLinkShare.DoesNotExist:
            error_msg = 'token %s not found.' % token
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # currently not support encrypted upload link
        if uls.is_encrypted():
            error_msg = 'Upload link %s is encrypted.' % token
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        repo_id = uls.repo_id
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        path = uls.path
        dir_id = seafile_api.get_dir_id_by_path(repo_id, path)
        if not dir_id:
            error_msg = 'Folder %s not found.' % path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if repo.encrypted or \
                seafile_api.check_permission_by_path(repo_id, '/', uls.username) != 'rw':
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        token = seafile_api.get_fileserver_access_token(repo_id,
                dir_id, 'upload-link', uls.username, use_onetime=False)

        if not token:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        result = {}
        result['upload_link'] = gen_file_upload_url(token, 'upload-api')
        return Response(result)
开发者ID:haiwen,项目名称:seahub,代码行数:45,代码来源:upload_links.py


示例14: repo_download_dir

def repo_download_dir(request, repo_id):
    repo = get_repo(repo_id)
    if not repo:
        return render_error(request, _(u'Library does not exist'))

    path = request.GET.get('p', '/')
    if path[-1] != '/':         # Normalize dir path
        path += '/'

    if not seafile_api.get_dir_id_by_path(repo.id, path):
        return render_error(request, _('"%s" does not exist.') % path)

    if len(path) > 1:
        dirname = os.path.basename(path.rstrip('/')) # Here use `rstrip` to cut out last '/' in path
    else:
        dirname = repo.name

    allow_download = True if check_folder_permission(request, repo_id, '/') else False

    if allow_download:

        dir_id = seafile_api.get_dir_id_by_commit_and_path(repo.id,
            repo.head_cmmt_id, path)
        try:
            total_size = seafile_api.get_dir_size(repo.store_id,
                repo.version, dir_id)
        except Exception, e:
            logger.error(str(e))
            return render_error(request, _(u'Internal Error'))

        if total_size > MAX_DOWNLOAD_DIR_SIZE:
            return render_error(request, _(u'Unable to download directory "%s": size is too large.') % dirname)

        is_windows = 0
        if is_windows_operating_system(request):
            is_windows = 1

        fake_obj_id = {
            'obj_id': dir_id,
            'dir_name': dirname,
            'is_windows': is_windows
        }

        token = seafile_api.get_fileserver_access_token(
                repo_id, json.dumps(fake_obj_id), 'download-dir', request.user.username)
开发者ID:pinguo-liuhongwei,项目名称:seahub,代码行数:45,代码来源:__init__.py


示例15: allow_generate_thumbnail

def allow_generate_thumbnail(request, repo_id, path):
    """check if thumbnail is allowed
    """

    # get file type
    obj_name = os.path.basename(path)
    file_type, file_ext = get_file_type_and_ext(obj_name)

    # get file size
    file_id = get_file_id_by_path(repo_id, path)
    if not file_id:
        return False

    repo = get_repo(repo_id)
    file_size = get_file_size(repo.store_id, repo.version, file_id)

    if repo.encrypted or file_type != IMAGE or not ENABLE_THUMBNAIL:
        return False

    # check image compressed size limit
    if file_size < THUMBNAIL_IMAGE_COMPRESSED_SIZE_LIMIT * 1024**2:
        return True

    # get image memory cost
    token = seafile_api.get_fileserver_access_token(repo_id, file_id, 'view',
                                                    '', use_onetime = True)

    inner_path = gen_inner_file_get_url(token, obj_name)
    try:
        image_file = urllib2.urlopen(inner_path)
        f = StringIO(image_file.read())
        image = Image.open(f)
        width, height = image.size

        # check image memory cost size limit
        # use RGBA as default mode(4x8-bit pixels, true colour with transparency mask)
        # every pixel will cost 4 byte in RGBA mode
        image_memory_cost = width * height * 4 / 1024 / 1024
        if image_memory_cost < THUMBNAIL_IMAGE_ORIGINAL_SIZE_LIMIT:
            return True

    except Exception as e:
        logger.error(e)
        return False
开发者ID:hangshisitu,项目名称:seahub,代码行数:44,代码来源:utils.py


示例16: get

    def get(self, request):

        # argument check
        req_from = request.GET.get('from', 'web')
        if req_from not in ('web', 'api'):
            error_msg = 'from invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # recourse check
        try:
            repo_id = seafile_api.get_system_default_repo_id()
            repo = seafile_api.get_repo(repo_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        parent_dir = request.GET.get('path', '/')
        parent_dir = normalize_dir_path(parent_dir)
        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        token = seafile_api.get_fileserver_access_token(repo_id,
                'dummy', 'upload', 'system', use_onetime=False)

        if not token:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if req_from == 'api':
            url = gen_file_upload_url(token, 'upload-api')
        else:
            url = gen_file_upload_url(token, 'upload-aj')

        result = {}
        result['upload_link'] = url
        return Response(result)
开发者ID:haiwen,项目名称:seahub,代码行数:43,代码来源:system_library.py


示例17: _download_dir_from_share_link

def _download_dir_from_share_link(request, fileshare, repo, real_path):
    # check whether owner's traffic over the limit
    if user_traffic_over_limit(fileshare.username):
        return render_error(
            request,
            _(u'Unable to access file: share link traffic is used up.'))

    shared_by = fileshare.username
    if real_path == '/':
        dirname = repo.name
    else:
        dirname = os.path.basename(real_path.rstrip('/'))

    dir_id = seafile_api.get_dir_id_by_path(repo.id, real_path)
    if not dir_id:
        return render_error(request,
                            _(u'Unable to download: folder not found.'))

    try:
        total_size = seaserv.seafserv_threaded_rpc.get_dir_size(
            repo.store_id, repo.version, dir_id)
    except Exception as e:
        logger.error(str(e))
        return render_error(request, _(u'Internal Error'))

    if total_size > seaserv.MAX_DOWNLOAD_DIR_SIZE:
        return render_error(
            request,
            _(u'Unable to download directory "%s": size is too large.') %
            dirname)

    token = seafile_api.get_fileserver_access_token(
        repo.id, dir_id, 'download-dir', request.user.username)

    try:
        seaserv.send_message(
            'seahub.stats', 'dir-download\t%s\t%s\t%s\t%s' %
            (repo.id, shared_by, dir_id, total_size))
    except Exception as e:
        logger.error('Error when sending dir-download message: %s' % str(e))

    return HttpResponseRedirect(gen_file_get_url(token, dirname))
开发者ID:soloice,项目名称:seahub,代码行数:42,代码来源:repo.py


示例18: create_psd_thumbnails

def create_psd_thumbnails(repo, file_id, path, size, thumbnail_file, file_size):
    try:
        from psd_tools import PSDImage
    except ImportError:
        logger.error("Could not find psd_tools installed. "
                     "Please install by 'pip install psd_tools'")
        return (False, 500)

    token = seafile_api.get_fileserver_access_token(
        repo.id, file_id, 'view', '', use_onetime=False)
    if not token:
        return (False, 500)

    tmp_img_path = str(os.path.join(tempfile.gettempdir(), '%s.png' % file_id))
    t1 = timeit.default_timer()

    inner_path = gen_inner_file_get_url(token, os.path.basename(path))
    tmp_file = os.path.join(tempfile.gettempdir(), file_id)
    urlretrieve(inner_path, tmp_file)
    psd = PSDImage.load(tmp_file)

    merged_image = psd.as_PIL()
    merged_image.save(tmp_img_path)
    os.unlink(tmp_file)     # remove origin psd file

    t2 = timeit.default_timer()
    logger.debug('Extract psd image [%s](size: %s) takes: %s' % (path, file_size, (t2 - t1)))

    try:
        ret = _create_thumbnail_common(tmp_img_path, thumbnail_file, size)
        os.unlink(tmp_img_path)
        return ret
    except Exception as e:
        logger.error(e)
        os.unlink(tmp_img_path)
        return (False, 500)
开发者ID:haiwen,项目名称:seahub,代码行数:36,代码来源:utils.py


示例19: get

    def get(self, request, token):
        """ Get FileServer url of the shared folder.

        Permission checking:
        1. only admin can perform this action.
        """

        try:
            uploadlink = UploadLinkShare.objects.get(token=token)
        except UploadLinkShare.DoesNotExist:
            error_msg = 'Upload link %s not found.' % token
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_id = uploadlink.repo_id
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library not found.'
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        path = uploadlink.path
        obj_id = seafile_api.get_dir_id_by_path(repo_id, path)
        if not obj_id:
            error_msg = 'Folder not found.'
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        upload_token = seafile_api.get_fileserver_access_token(repo_id,
                obj_id, 'upload-link', uploadlink.username, use_onetime=False)

        if not upload_token:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        result = {}
        result['upload_link'] = gen_file_upload_url(upload_token, 'upload-api')

        return Response(result)
开发者ID:haiwen,项目名称:seahub,代码行数:36,代码来源:upload_links.py


示例20: group_discuss

def group_discuss(request, group):
    if group.is_pub:
        raise Http404

    username = request.user.username
    form = MessageForm()

    # remove user notifications
    UserNotification.objects.seen_group_msg_notices(username, group.id)

    # Get all group members.
    members = get_group_members(group.id)

    """group messages"""
    # Show 15 group messages per page.
    paginator = Paginator(GroupMessage.objects.filter(group_id=group.id).order_by("-timestamp"), 15)

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        group_msgs = paginator.page(page)
    except (EmptyPage, InvalidPage):
        group_msgs = paginator.page(paginator.num_pages)

    group_msgs.page_range = paginator.get_page_range(group_msgs.number)

    # Force evaluate queryset to fix some database error for mysql.
    group_msgs.object_list = list(group_msgs.object_list)

    msg_attachments = MessageAttachment.objects.filter(group_message__in=group_msgs.object_list)

    msg_replies = MessageReply.objects.filter(reply_to__in=group_msgs.object_list)
    reply_to_list = [r.reply_to_id for r in msg_replies]

    for msg in group_msgs.object_list:
        msg.reply_cnt = reply_to_list.count(msg.id)
        msg.replies = []
        for r in msg_replies:
            if msg.id == r.reply_to_id:
                msg.replies.append(r)
        msg.replies = msg.replies[-3:]

        msg.attachments = []
        for att in msg_attachments:
            if att.group_message_id != msg.id:
                continue

            # Attachment name is file name or directory name.
            # If is top directory, use repo name instead.
            path = att.path
            if path == "/":
                repo = get_repo(att.repo_id)
                if not repo:
                    # TODO: what should we do here, tell user the repo
                    # is no longer exists?
                    continue
                att.name = repo.name
            else:
                path = path.rstrip("/")  # cut out last '/' if possible
                att.name = os.path.basename(path)

            # Load to discuss page if attachment is a image and from recommend.
            if att.attach_type == "file" and att.src == "recommend":
                att.filetype, att.fileext = get_file_type_and_ext(att.name)
                if att.filetype == IMAGE:
                    att.obj_id = get_file_id_by_path(att.repo_id, path)
                    if not att.obj_id:
                        att.err = _(u"File does not exist")
                    else:
                        att.token = seafile_api.get_fileserver_access_token(att.repo_id, att.obj_id, "view", username)
                        att.img_url = gen_file_get_url(att.token, att.name)

            msg.attachments.append(att)

    # get available modules(wiki, etc)
    mods_available = get_available_mods_by_group(group.id)
    mods_enabled = get_enabled_mods_by_group(group.id)

    return render_to_response(
        "group/group_discuss.html",
        {
            "group": group,
            "is_staff": group.is_staff,
            "group_msgs": group_msgs,
            "form": form,
            "mods_enabled": mods_enabled,
            "mods_available": mods_available,
        },
        context_instance=RequestContext(request),
    )
开发者ID:octomike,项目名称:seahub,代码行数:95,代码来源:views.py



注:本文中的seaserv.seafile_api.get_fileserver_access_token函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python seafile_api.get_org_repo_owner函数代码示例发布时间:2022-05-27
下一篇:
Python seafile_api.get_file_id_by_path函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap