Ejemplo n.º 1
0
def get_or_create_invitation_link(org_id):
    """Invitation link for an org. Users will be redirected to WeChat QR page.
    Mainly used in docs.seafile.com.
    """
    org_id = int(org_id)
    expires = 3 * 24 * 60 * 60

    def get_token_by_org_id(org_id):
        return cache.get('org_associate_%d' % org_id, None)

    def set_token_by_org_id(org_id, token):
        cache.set('org_associate_%d' % org_id, token, expires)

    def get_org_id_by_token(token):
        return cache.get('org_associate_%s' % token, -1)

    def set_org_id_by_token(token, org_id):
        cache.set('org_associate_%s' % token, org_id, expires)

    token = get_token_by_org_id(org_id)
    cached_org_id = get_org_id_by_token(token)

    if token and org_id == cached_org_id:
        return '%s/weixin/oauth-login/?next=%s' % (get_service_url().rstrip(
            '/'), reverse('org_associate', args=[token]))

    token = gen_token(32)
    set_token_by_org_id(org_id, token)
    set_org_id_by_token(token, org_id)

    link = '%s/weixin/oauth-login/?next=%s' % (
        get_service_url().rstrip('/'), reverse('org_associate', args=[token]))
    return link
Ejemplo n.º 2
0
Archivo: repo.py Proyecto: xiez/seahub
def view_lib_as_wiki(request, repo_id, path):

    if not path.startswith('/'):
        path = '/' + path

    repo = seafile_api.get_repo(repo_id)

    is_dir = None
    file_id = seafile_api.get_file_id_by_path(repo.id, path)
    if file_id:
        is_dir = False

    dir_id = seafile_api.get_dir_id_by_path(repo.id, path)
    if dir_id:
        is_dir = True

    user_perm = check_folder_permission(request, repo.id, '/')
    if user_perm is None:
        return render_error(request, _(u'Permission denied'))

    if user_perm == 'rw':
        user_can_write = True
    else:
        user_can_write = False

    return render(
        request, 'view_lib_as_wiki.html', {
            'repo_id': repo_id,
            'service_url': get_service_url().rstrip('/'),
            'initial_path': path,
            'is_dir': is_dir,
            'repo_name': repo.name,
            'permission': user_can_write
        })
Ejemplo n.º 3
0
def _get_saml_client():
    acs_url = get_service_url().rstrip('/') + '/saml/acs/'
    metadata = _get_metadata()

    saml_settings = {
        'metadata': metadata,
        'service': {
            'sp': {
                'endpoints': {
                    'assertion_consumer_service': [
                        (acs_url, BINDING_HTTP_REDIRECT),
                        (acs_url, BINDING_HTTP_POST)
                    ],
                },
                'allow_unsolicited': True,
                'authn_requests_signed': False,
                'logout_requests_signed': True,
                'want_assertions_signed': False,
                'want_response_signed': False,
            },
        },
    }

    if 'ENTITY_ID' in SAML_LOGIN_SETTINGS:
        saml_settings['entityid'] = settings.SAML_LOGIN_SETTINGS['ENTITY_ID']

    if 'NAME_ID_FORMAT' in SAML_LOGIN_SETTINGS:
        saml_settings['service']['sp']['name_id_format'] = SAML_LOGIN_SETTINGS['NAME_ID_FORMAT']

    spConfig = Saml2Config()
    spConfig.load(saml_settings)
    spConfig.allow_unknown_attributes = True
    saml_client = Saml2Client(config=spConfig)
    return saml_client
Ejemplo n.º 4
0
def get_subdomain(domain):
    service_url_netloc = urlparse(get_service_url()).netloc
    domain_remaining = domain.replace(service_url_netloc, '')

    if domain_remaining == '':
        return None
    elif domain_remaining[-1] == '.':
        return domain_remaining[:-1]
    else:
        logger.warning('Invalid domain: %s, service_url: %s' %
                       (domain, service_url_netloc))
        return None
Ejemplo n.º 5
0
    def post(self, request):

        if not request.user.admin_permissions.can_config_system():
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        favicon_file = request.FILES.get('favicon', None)
        if not favicon_file:
            error_msg = 'Favicon can not be found.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        file_type, ext = get_file_type_and_ext(favicon_file.name)
        if file_type != IMAGE:
            error_msg = file_type_error_msg(ext, PREVIEW_FILEEXT.get(IMAGE))
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if favicon_file.size > 1024 * 1024 * 20:  # 20mb
            error_msg = file_size_error_msg(favicon_file.size,
                                            20 * 1024 * 1024)
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if not os.path.exists(SEAHUB_DATA_ROOT):
            os.makedirs(SEAHUB_DATA_ROOT)

        custom_dir = os.path.join(SEAHUB_DATA_ROOT,
                                  os.path.dirname(CUSTOM_FAVICON_PATH))

        if not os.path.exists(custom_dir):
            os.makedirs(custom_dir)

        try:
            custom_favicon_file = os.path.join(SEAHUB_DATA_ROOT,
                                               CUSTOM_FAVICON_PATH)

            # save favicon file to custom dir
            with open(custom_favicon_file, 'wb') as fd:
                fd.write(favicon_file.read())

            custom_symlink = os.path.join(MEDIA_ROOT,
                                          os.path.dirname(CUSTOM_FAVICON_PATH))

            # create symlink for custom dir
            if not os.path.exists(custom_symlink):
                os.symlink(custom_dir, custom_symlink)

        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({
            'favicon_path':
            get_service_url() + MEDIA_URL + CUSTOM_FAVICON_PATH
        })
Ejemplo n.º 6
0
    def post(self, request):

        if not request.user.admin_permissions.can_config_system():
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        logo_file = request.FILES.get('logo', None)
        if not logo_file:
            error_msg = 'Logo can not be found.'
            logger.error(error_msg)
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        file_type, ext = get_file_type_and_ext(logo_file.name)
        if file_type != IMAGE:
            error_msg = file_type_error_msg(ext, PREVIEW_FILEEXT.get(IMAGE))
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if logo_file.size > 1024 * 1024 * 20:  # 20mb
            error_msg = file_size_error_msg(logo_file.size, 20 * 1024 * 1024)
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if not os.path.exists(SEAHUB_DATA_ROOT):
            os.makedirs(SEAHUB_DATA_ROOT)

        custom_dir = os.path.join(SEAHUB_DATA_ROOT,
                                  os.path.dirname(CUSTOM_LOGO_PATH))
        if not os.path.exists(custom_dir):
            os.makedirs(custom_dir)

        try:
            # save logo file to custom dir
            custom_logo_file = os.path.join(SEAHUB_DATA_ROOT, CUSTOM_LOGO_PATH)
            image = Image.open(logo_file)
            image.save(custom_logo_file)

            # create symlink for custom dir
            custom_symlink = os.path.join(MEDIA_ROOT,
                                          os.path.dirname(CUSTOM_LOGO_PATH))
            if not os.path.exists(custom_symlink):
                os.symlink(custom_dir, custom_symlink)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response(
            {'logo_path': get_service_url() + MEDIA_URL + CUSTOM_LOGO_PATH})
Ejemplo n.º 7
0
    def post(self, request):
        image_file = request.FILES.get('login_bg_image', None)
        if not image_file:
            error_msg = 'Image can not be found.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if not os.path.exists(SEAHUB_DATA_ROOT):
            os.makedirs(SEAHUB_DATA_ROOT)

        file_type, ext = get_file_type_and_ext(image_file.name)
        if file_type != IMAGE:
            error_msg = file_type_error_msg(ext, PREVIEW_FILEEXT.get('Image'))
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if image_file.size > 1024 * 1024 * 20:  # 20mb
            error_msg = file_size_error_msg(image_file.size, 20 * 1024 * 1024)
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        custom_login_bg_image_path = get_custom_login_bg_image_path()
        custom_dir = os.path.join(SEAHUB_DATA_ROOT,
                                  os.path.dirname(custom_login_bg_image_path))
        if not os.path.exists(custom_dir):
            os.makedirs(custom_dir)

        try:
            custom_login_bg_image_file = os.path.join(
                SEAHUB_DATA_ROOT, custom_login_bg_image_path)
            # save login background image file to custom dir
            with open(custom_login_bg_image_file, 'wb') as fd:
                fd.write(image_file.read())

            custom_symlink = os.path.join(
                MEDIA_ROOT, os.path.dirname(custom_login_bg_image_path))
            # create symlink for custom dir
            if not os.path.exists(custom_symlink):
                os.symlink(custom_dir, custom_symlink)

        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({
            'login_bg_image_path':
            get_service_url() + MEDIA_URL + CUSTOM_LOGIN_BG_PATH
        })
Ejemplo n.º 8
0
def api_avatar_url(user, size=AVATAR_DEFAULT_SIZE):
    service_url = get_service_url()
    service_url = service_url.rstrip('/')

    # when store avatars in the media directory
    if not AVATAR_FILE_STORAGE:
        # urlparse('https://192.157.12.3:89/demo')
        # ParseResult(scheme='https', netloc='192.157.12.3:89', path='/demo', params='', query='', fragment='')
        parse_result = urlparse(service_url)
        service_url = '%s://%s' % (parse_result[0], parse_result[1])

    avatar = get_primary_avatar(user, size=size)
    if avatar:
        url = avatar.avatar_url(size)
        date_uploaded = avatar.date_uploaded
        # /media/avatars/6/9/5011f01afac2a506b9544c5ce21a0a/resized/32/109af9901c0fd38ab39d018f5cd4baf6.png
        return service_url + url, False, date_uploaded
    else:
        # /media/avatars/default.png
        return service_url + get_default_avatar_url(), True, None
Ejemplo n.º 9
0
    def test_update_favicon(self):

        custom_symlink = os.path.join(MEDIA_ROOT, os.path.dirname(CUSTOM_FAVICON_PATH))
        if os.path.exists(custom_symlink):
            os.remove(custom_symlink)

        assert not os.path.exists(custom_symlink)

        # update user avatar
        logo_url = reverse('api-v2.1-admin-favicon')
        logo_url = urljoin(BASE_URL, logo_url)
        logo_file = os.path.join(os.getcwd(), 'media/img/seafile-logo.png')

        with open(logo_file, 'rb') as f:
            resp = self.client.post(logo_url, {'favicon': f})

        assert resp.status_code == 200
        json_resp = json.loads(resp.content)
        assert json_resp['favicon_path'] == get_service_url() + MEDIA_URL + CUSTOM_FAVICON_PATH
        assert os.path.exists(custom_symlink)
        assert os.path.islink(custom_symlink)
Ejemplo n.º 10
0
    def test_update_logo(self):

        custom_symlink = os.path.join(MEDIA_ROOT, os.path.dirname(CUSTOM_LOGIN_BG_PATH))
        if os.path.exists(custom_symlink):
            os.remove(custom_symlink)

        assert not os.path.exists(custom_symlink)

        # update user avatar
        image_url = reverse('api-v2.1-admin-login-background-image')
        image_url = urljoin(BASE_URL, image_url)
        image_file = os.path.join(os.getcwd(), 'media/img/seafile-logo.png')

        with open(image_file, 'rb') as f:
            resp = self.client.post(image_url, {'login_bg_image': f})
        json_resp = json.loads(resp.content)

        assert 200 == resp.status_code
        assert json_resp['login_bg_image_path'] == get_service_url() + MEDIA_URL + CUSTOM_LOGIN_BG_PATH
        assert os.path.exists(custom_symlink)
        assert os.path.islink(custom_symlink)
Ejemplo n.º 11
0
def slug(request, slug, file_path="home.md"):
    """Show wiki page.
    """
    # get wiki object or 404
    wiki = get_object_or_404(Wiki, slug=slug)
    file_path = "/" + file_path

    # perm check
    req_user = request.user.username

    if not req_user:
        return redirect('auth_login')

    if not wiki.check_access_wiki(request):
        return render_permission_error(request, _(u'Permission denied.'))

    file_type, ext = get_file_type_and_ext(posixpath.basename(file_path))
    if file_type == IMAGE:
        file_url = reverse('view_lib_file', args=[wiki.repo_id, file_path])
        return HttpResponseRedirect(file_url + "?raw=1")

    if not req_user:
        user_can_write = False
    elif req_user == wiki.username or check_folder_permission(
            request, wiki.repo_id, '/') == 'rw':
        user_can_write = True
    else:
        user_can_write = False

    return render(
        request, "wiki/wiki.html", {
            "wiki": wiki,
            "page_name": file_path,
            "user_can_write": user_can_write,
            "file_path": file_path,
            "repo_id": wiki.repo_id,
            "search_repo_id": wiki.repo_id,
            "search_wiki": True,
            "service_url": get_service_url().rstrip('/')
        })
Ejemplo n.º 12
0
def view_lib_as_wiki(request, repo_id, path):

    if not path.startswith('/'):
        path = '/' + path

    repo = seafile_api.get_repo(repo_id)

    is_dir = None
    file_id = seafile_api.get_file_id_by_path(repo.id, path)
    if file_id:
        is_dir = False

    dir_id = seafile_api.get_dir_id_by_path(repo.id, path)
    if dir_id:
        is_dir = True

    user_perm = check_folder_permission(request, repo.id, '/')
    if user_perm is None:
        return render_error(request, _('Permission denied'))

    if user_perm == 'rw':
        user_can_write = True
    else:
        user_can_write = False

    return render(
        request, 'view_lib_as_wiki.html', {
            'seafile_collab_server': SEAFILE_COLLAB_SERVER,
            'repo_id': repo_id,
            'service_url': get_service_url().rstrip('/'),
            'initial_path': path,
            'is_dir': is_dir,
            'repo_name': repo.name,
            'permission': user_can_write,
            'share_link_expire_days_min': SHARE_LINK_EXPIRE_DAYS_MIN,
            'share_link_expire_days_max': SHARE_LINK_EXPIRE_DAYS_MAX,
        })
Ejemplo n.º 13
0
def view_lib_as_wiki(request, repo_id, path):

    if not path.startswith('/'):
        path = '/' + path

    repo = seafile_api.get_repo(repo_id)

    is_dir = None
    file_id = seafile_api.get_file_id_by_path(repo.id, path)
    if file_id:
        is_dir = False

    dir_id = seafile_api.get_dir_id_by_path(repo.id, path)
    if dir_id:
        is_dir = True

    user_perm = check_folder_permission(request, repo.id, '/')
    if user_perm is None:
        return render_error(request, _(u'Permission denied'))

    if user_perm == 'rw':
        user_can_write = True
    else:
        user_can_write = False

    return render(request, 'view_lib_as_wiki.html', {
        'seafile_collab_server': SEAFILE_COLLAB_SERVER,
        'repo_id': repo_id,
        'service_url': get_service_url().rstrip('/'),
        'initial_path': path,
        'is_dir': is_dir,
        'repo_name': repo.name,
        'permission': user_can_write,
        'share_link_expire_days_min': SHARE_LINK_EXPIRE_DAYS_MIN,
        'share_link_expire_days_max': SHARE_LINK_EXPIRE_DAYS_MAX,
        })
Ejemplo n.º 14
0
def gen_smart_link(dirent_uuid, dirent_name):

    service_url = get_service_url()
    service_url = service_url.rstrip('/')
    return '%s/smart-link/%s/%s' % (service_url, dirent_uuid, dirent_name)
Ejemplo n.º 15
0
logger = logging.getLogger(__name__)

email_templates = (u'''Hi, ${to_email}
You've got ${count} new message on ${site_name}.

Go check out at ${url}
''',
u'''Hi, ${to_email}
You've got ${count} new messages on ${site_name}.

Go check out at ${url}
''')

site_name = settings.SITE_NAME
subjects = (u'New message on %s' % site_name, u'New messages on %s' % site_name)
url = get_service_url().rstrip('/') + reverse('message_list')

class Command(BaseCommand):
    help = 'Send Email notifications to user if he/she has a unread user message.'

    def handle(self, *args, **options):
        logger.debug('Start sending user message...')
        self.do_action()
        logger.debug('Finish sending user message.\n')

    def do_action(self):
        now = datetime.now()

        if not UserMsgLastCheck.objects.all():
            logger.debug('No last check time found, get all unread msgs.')
            unread_msgs = UserMessage.objects.filter(ifread=0)
Ejemplo n.º 16
0
def get_thumbnail_src(repo_id, obj_id, size):
    return posixpath.join(get_service_url(), "thumbnail", repo_id,
                          obj_id, size) + "/"
Ejemplo n.º 17
0
def org_register(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """Allow a new user to register an organization account. A new
    organization will be created associate with that user.

    Arguments:
    - `request`:
    """
    login_bg_image_path = get_login_bg_image_path()
    redirect_to = request.GET.get(redirect_field_name)

    if request.method == 'POST':
        form = OrgRegistrationForm(request.POST)

        if ORG_AUTO_URL_PREFIX:
            # generate url prefix automatically
            url_prefix = gen_org_url_prefix(3)
            if url_prefix is None:
                messages.error(request, "Failed to create organization account, please try again later.")
                return render(request, 'organizations/org_register.html', {
                    'form': form,
                    'login_bg_image_path': login_bg_image_path,
                    'org_auto_url_prefix': ORG_AUTO_URL_PREFIX,
                })

        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            org_name = form.cleaned_data['org_name']

            new_user = User.objects.create_user(email, password,
                                                is_staff=False, is_active=True)
            create_org(org_name, url_prefix, new_user.username)
            new_org = get_org_by_url_prefix(url_prefix)
            org_created.send(sender=None, org=new_org)

            if name:
                Profile.objects.add_or_update(new_user.username, name)

            # login the user
            new_user.backend = settings.AUTHENTICATION_BACKENDS[0]
            login(request, new_user)

            if not redirect_to:
                return HttpResponseRedirect(reverse('dtable'))
            else:
                return HttpResponseRedirect(redirect_to)
    else:
        form = OrgRegistrationForm()

    service_url = get_service_url()
    up = urlparse(service_url)
    service_url_scheme = up.scheme
    service_url_remaining = up.netloc + up.path

    return render(request, 'organizations/org_register.html', {
        'form': form,
        'login_bg_image_path': login_bg_image_path,
        'service_url_scheme': service_url_scheme,
        'service_url_remaining': service_url_remaining,
        'org_auto_url_prefix': ORG_AUTO_URL_PREFIX,
        'redirect_to': redirect_to or reverse('dtable'),
    })
Ejemplo n.º 18
0
def get_thumbnail_src(repo_id, obj_id, size):
    return posixpath.join(get_service_url(), "thumbnail", repo_id, obj_id,
                          size) + "/"
Ejemplo n.º 19
0
def base(request):
    """
    Add seahub base configure to the context.

    """
    try:
        org = request.user.org
    except AttributeError:
        org = None

    # extra repo id from request path, use in search
    repo_id_patt = r".*/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})/.*"
    m = re.match(repo_id_patt, request.get_full_path())
    search_repo_id = m.group(1) if m is not None else None
    file_server_root = config.FILE_SERVER_ROOT
    if not file_server_root.endswith('/'):
        file_server_root += '/'

    logo_path = LOGO_PATH
    favicon_path = FAVICON_PATH
    login_bg_path = LOGIN_BG_IMAGE_PATH

    # filter ajax/api request out
    avatar_url = ''
    username = request.user.username
    if (not request.is_ajax()) and ("api2/" not in request.path) and \
            ("api/v2.1/" not in request.path):

        # get logo path
        custom_logo_file = os.path.join(MEDIA_ROOT, CUSTOM_LOGO_PATH)
        if os.path.exists(custom_logo_file):
            logo_path = CUSTOM_LOGO_PATH

        # get favicon path
        custom_favicon_file = os.path.join(MEDIA_ROOT, CUSTOM_FAVICON_PATH)
        if os.path.exists(custom_favicon_file):
            favicon_path = CUSTOM_FAVICON_PATH

        # get login bg path
        custom_login_bg_file = os.path.join(MEDIA_ROOT, CUSTOM_LOGIN_BG_PATH)
        if os.path.exists(custom_login_bg_file):
            login_bg_path = CUSTOM_LOGIN_BG_PATH

        avatar_url, is_default, date_uploaded = api_avatar_url(username, 72)

    result = {
        'seafile_version': SEAFILE_VERSION,
        'site_title': config.SITE_TITLE,
        'branding_css': BRANDING_CSS,
        'enable_branding_css': config.ENABLE_BRANDING_CSS,
        'favicon_path': favicon_path,
        'login_bg_path': login_bg_path,
        'logo_path': logo_path,
        'logo_width': LOGO_WIDTH,
        'logo_height': LOGO_HEIGHT,
        'cloud_mode': request.cloud_mode,
        'org': org,
        'site_name': get_site_name(),
        'enable_signup': config.ENABLE_SIGNUP,
        'max_file_name': MAX_FILE_NAME,
        'has_file_search': HAS_FILE_SEARCH,
        'show_repo_download_button': SHOW_REPO_DOWNLOAD_BUTTON,
        'share_link_password_min_length':
        config.SHARE_LINK_PASSWORD_MIN_LENGTH,
        'repo_password_min_length': config.REPO_PASSWORD_MIN_LENGTH,
        'events_enabled': EVENTS_ENABLED,
        'sysadmin_extra_enabled': ENABLE_SYSADMIN_EXTRA,
        'multi_tenancy': MULTI_TENANCY,
        'multi_institution': getattr(dj_settings, 'MULTI_INSTITUTION', False),
        'search_repo_id': search_repo_id,
        'SITE_ROOT': SITE_ROOT,
        'CSRF_COOKIE_NAME': dj_settings.CSRF_COOKIE_NAME,
        'constance_enabled': dj_settings.CONSTANCE_ENABLED,
        'FILE_SERVER_ROOT': file_server_root,
        'LOGIN_URL': dj_settings.LOGIN_URL,
        'enable_thumbnail': ENABLE_THUMBNAIL,
        'thumbnail_size_for_original': THUMBNAIL_SIZE_FOR_ORIGINAL,
        'enable_guest_invitation': ENABLE_GUEST_INVITATION,
        'enable_terms_and_conditions': config.ENABLE_TERMS_AND_CONDITIONS,
        'show_logout_icon': SHOW_LOGOUT_ICON,
        'is_pro': True if is_pro_version() else False,
        'is_docs': ENABLE_SEAFILE_DOCS,
        'enable_upload_folder': dj_settings.ENABLE_UPLOAD_FOLDER,
        'enable_resumable_fileupload': dj_settings.ENABLE_RESUMABLE_FILEUPLOAD,
        'service_url': get_service_url().rstrip('/'),
        'enable_file_scan': ENABLE_FILE_SCAN,
        'enable_work_weixin': ENABLE_WORK_WEIXIN,
        'avatar_url': avatar_url if avatar_url else '',
    }

    if request.user.is_staff:
        result['is_default_admin'] = request.user.admin_role == DEFAULT_ADMIN
        result[
            'enable_share_link_report_abuse'] = ENABLE_SHARE_LINK_REPORT_ABUSE

    return result
Ejemplo n.º 20
0
def get_thumbnail_src(repo_id, obj_id, size):
    return os.path.join(get_service_url(), "thumbnail", repo_id, obj_id, size, "")
Ejemplo n.º 21
0
    def do_action(self):
        now = datetime.datetime.now()

        try:
            cmd_last_check = CommandsLastCheck.objects.get(command_type=self.label)
            logger.debug('Last check time is %s' % cmd_last_check.last_check)

            unseen_notices = UserNotification.objects.get_all_notifications(
                seen=False, time_since=cmd_last_check.last_check)

            logger.debug('Update last check time to %s' % now)
            cmd_last_check.last_check = now
            cmd_last_check.save()
        except CommandsLastCheck.DoesNotExist:
            logger.debug('No last check time found, get all unread notices.')
            unseen_notices = UserNotification.objects.get_all_notifications(
                seen=False)

            logger.debug('Create new last check time: %s' % now)
            CommandsLastCheck(command_type=self.label, last_check=now).save()

        email_ctx = {}
        for notice in unseen_notices:
            if notice.to_user in email_ctx:
                email_ctx[notice.to_user] += 1
            else:
                email_ctx[notice.to_user] = 1

        for to_user, count in email_ctx.items():
            notices = []
            for notice in unseen_notices:
                if notice.to_user != to_user:
                    continue

                if notice.is_priv_file_share_msg():
                    notice = self.format_priv_file_share_msg(notice)

                elif notice.is_user_message():
                    notice = self.format_user_message(notice)

                elif notice.is_group_msg():
                    notice = self.format_group_message(notice)

                elif notice.is_grpmsg_reply():
                    notice = self.format_grpmsg_reply(notice)

                elif notice.is_repo_share_msg():
                    notice = self.format_repo_share_msg(notice)

                elif notice.is_file_uploaded_msg():
                    notice = self.format_file_uploaded_msg(notice)

                elif notice.is_group_join_request():
                    notice = self.format_group_join_request(notice)

                notices.append(notice)

            if not notices:
                continue

            subject = subjects[1] if count > 1 else subjects[0]
            c = { 
                'to_user': to_user,
                'notice_count': count,
                'notices': notices,
                'avatar_url': self.get_avatar_url(to_user),
                'service_url': get_service_url(),
                }   

            try:
                send_html_email(subject, 'notifications/notice_email.html', c,
                                None, [to_user])

                logger.info('Successfully sent email to %s' % to_user)
            except Exception as e:
                logger.error('Failed to send email to %s, error detail: %s' % (to_user, e))
Ejemplo n.º 22
0
def construct_org_url(url_prefix, path):
    service_url = get_service_url()
    p = urlparse(service_url)
    scheme = p.scheme
    netloc = p.netloc
    return "%s://%s.%s%s" % (scheme, url_prefix, netloc, path)
Ejemplo n.º 23
0
    def do_action(self):
        now = datetime.datetime.now()

        try:
            cmd_last_check = CommandsLastCheck.objects.get(command_type=self.label)
            logger.debug('Last check time is %s' % cmd_last_check.last_check)

            unseen_notices = UserNotification.objects.get_all_notifications(
                seen=False, time_since=cmd_last_check.last_check)

            logger.debug('Update last check time to %s' % now)
            cmd_last_check.last_check = now
            cmd_last_check.save()
        except CommandsLastCheck.DoesNotExist:
            logger.debug('No last check time found, get all unread notices.')
            unseen_notices = UserNotification.objects.get_all_notifications(
                seen=False)

            logger.debug('Create new last check time: %s' % now)
            CommandsLastCheck(command_type=self.label, last_check=now).save()

        email_ctx = {}
        for notice in unseen_notices:
            if notice.to_user in email_ctx:
                email_ctx[notice.to_user] += 1
            else:
                email_ctx[notice.to_user] = 1

        for to_user, count in email_ctx.items():
            # save current language
            cur_language = translation.get_language()

            # get and active user language
            user_language = self.get_user_language(to_user)
            translation.activate(user_language)
            logger.info('Set language code to %s', user_language)

            notices = []
            for notice in unseen_notices:
                if notice.to_user != to_user:
                    continue

                if notice.is_priv_file_share_msg():
                    notice = self.format_priv_file_share_msg(notice)

                elif notice.is_user_message():
                    notice = self.format_user_message(notice)

                elif notice.is_group_msg():
                    notice = self.format_group_message(notice)

                elif notice.is_grpmsg_reply():
                    notice = self.format_grpmsg_reply(notice)

                elif notice.is_repo_share_msg():
                    notice = self.format_repo_share_msg(notice)

                elif notice.is_file_uploaded_msg():
                    notice = self.format_file_uploaded_msg(notice)

                elif notice.is_group_join_request():
                    notice = self.format_group_join_request(notice)

                notices.append(notice)

            if not notices:
                continue

            c = { 
                'to_user': to_user,
                'notice_count': count,
                'notices': notices,
                'avatar_url': self.get_avatar_url(to_user),
                'service_url': get_service_url(),
                }   

            try:
                send_html_email(_('New notice on %s') % settings.SITE_NAME,
                                'notifications/notice_email.html', c,
                                None, [to_user])

                logger.info('Successfully sent email to %s' % to_user)
            except Exception as e:
                logger.error('Failed to send email to %s, error detail: %s' % (to_user, e))

            # restore current language
            translation.activate(cur_language)
Ejemplo n.º 24
0
logger = logging.getLogger(__name__)

email_templates = (u'''Hi, ${to_email}
You've got ${count} new message on ${site_name}.

Go check out at ${url}
''', u'''Hi, ${to_email}
You've got ${count} new messages on ${site_name}.

Go check out at ${url}
''')

site_name = settings.SITE_NAME
subjects = (u'New message on %s' % site_name,
            u'New messages on %s' % site_name)
url = get_service_url().rstrip('/') + reverse('message_list')


class Command(BaseCommand):
    help = 'Send Email notifications to user if he/she has a unread user message.'

    def handle(self, *args, **options):
        logger.debug('Start sending user message...')
        self.do_action()
        logger.debug('Finish sending user message.\n')

    def do_action(self):
        now = datetime.now()

        if not UserMsgLastCheck.objects.all():
            logger.debug('No last check time found, get all unread msgs.')
Ejemplo n.º 25
0
def gen_share_dtable_link(token):
    service_url = get_service_url()
    assert service_url is not None
    service_url = service_url.rstrip('/')
    return '%s/dtable/links/%s' % (service_url, token)
Ejemplo n.º 26
0
def gen_dtable_external_link(token):
    service_url = get_service_url()
    assert service_url is not None
    service_url = service_url.rstrip().rstrip('/')
    return '%s/dtable/external-links/%s/' % (service_url, token)
Ejemplo n.º 27
0
def gen_smart_link(dirent_uuid):

    service_url = get_service_url()
    service_url = service_url.rstrip('/')
    return '%s/smart-link/%s/' % (service_url, dirent_uuid)
Ejemplo n.º 28
0
 def get_full_url(self):
     service_url = get_service_url().rstrip('/')
     if self.is_file_share_link():
         return '%s/f/%s/' % (service_url, self.token)
     else:
         return '%s/d/%s/' % (service_url, self.token)
Ejemplo n.º 29
0
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.utils import api_error
from seahub.constants import PERMISSION_READ_WRITE
from seahub.dtable.models import DTables, Workspaces, DTableExternalLinks
from seahub.dtable.utils import check_dtable_permission, FILE_TYPE, check_dtable_admin_permission
from seahub.utils import get_service_url, gen_inner_file_get_url
from seaserv import seafile_api

logger = logging.getLogger(__name__)
TMP_PATH = '/tmp/dtable_for_copy/'
service_url = get_service_url().strip()


def clear_tmp_files_and_dirs(uuid):
    # delete tmp files/dirs
    path = os.path.join(TMP_PATH, uuid)
    if os.path.exists(path):
        shutil.rmtree(path)


def _trans_url(url, workspace_id, dtable_uuid):
    if url.startswith(service_url):
        return re.sub(r'\d+/asset/[-\w]{36}',
                      str(workspace_id) + '/asset/' + str(dtable_uuid), url)
    return url