예제 #1
0
def _post_winning_submission(poll, submission_id):
    user = UserProfile.objects.get(username=poll.bot_name)
    submission = Submission.objects.get(id=submission_id)
    post = Post(user=user,
                category=poll.category,
                title="{}: {}".format(poll.stub, submission.title),
                url=submission.url,
                type='image',
                nsfw=True,
                crowd=submission.crowd)
    post.save()
    text = poll.winning_text.format(title=poll.title,
                                    stub=poll.stub,
                                    username=submission.user.username)

    comment = Comment(user=user, post=post, text=text, crowd=submission.crowd)
    comment.save()
    winning_user = UserProfile.objects.get(id=submission.user.id)
    winning_user.poll_votes += 1
    winning_user.save()
    submission.delete()
    # Notify the winner they won
    notify_users(user_ids=[winning_user.id],
                 from_user=UserProfile.objects.get(username=poll.bot_name),
                 text="Your {} submission won!".format(poll.title),
                 identifier=post.id,
                 type='comment',
                 level='info')
예제 #2
0
파일: views.py 프로젝트: incrowdio/incrowd
def _post_winning_submission(poll, submission_id):
    user = UserProfile.objects.get(username=poll.bot_name)
    submission = Submission.objects.get(id=submission_id)
    post = Post(user=user,
                category=poll.category,
                title="{}: {}".format(poll.stub, submission.title),
                url=submission.url,
                type='image',
                nsfw=True,
                crowd=submission.crowd)
    post.save()
    text = poll.winning_text.format(
        title=poll.title,
        stub=poll.stub,
        username=submission.user.username)

    comment = Comment(user=user,
                      post=post,
                      text=text,
                      crowd=submission.crowd)
    comment.save()
    winning_user = UserProfile.objects.get(id=submission.user.id)
    winning_user.poll_votes += 1
    winning_user.save()
    submission.delete()
    # Notify the winner they won
    notify_users(
        user_ids=[winning_user.id],
        from_user=UserProfile.objects.get(username=poll.bot_name),
        text="Your {} submission won!".format(poll.title),
        identifier=post.id,
        type='comment',
        level='info')
예제 #3
0
def comment(request, screen_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            screen = Screen.objects.get(id=screen_id)
            new_comment = Comment(screen=screen, comment=form.cleaned_data['comment'], created_by_user=request.user)
            new_comment.save()
            return redirect(request.META['HTTP_REFERER'])
    elif request.method == 'GET':
        raise Http404
예제 #4
0
def update_folder_contents(children, source_node, destination_node):
    for item in children:
        if not item.is_file:
            update_folder_contents(item.children, source_node, destination_node)
        else:
            Comment.update(Q('root_target', 'eq', item._id), data={'node': destination_node})
            # update node record of commented files
            if item._id in source_node.commented_files:
                destination_node.commented_files[item._id] = source_node.commented_files[item._id]
                del source_node.commented_files[item._id]
                source_node.save()
                destination_node.save()
예제 #5
0
def comment(request, screen_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            screen = Screen.objects.get(id=screen_id)
            new_comment = Comment(screen=screen,
                                  comment=form.cleaned_data['comment'],
                                  created_by_user=request.user)
            new_comment.save()
            return redirect(request.META['HTTP_REFERER'])
    elif request.method == 'GET':
        raise Http404
예제 #6
0
파일: comment.py 프로젝트: GloriaaLi/osf.io
def update_folder_contents(children, source_node, destination_node):
    for item in children:
        if not item.is_file:
            update_folder_contents(item.children, source_node,
                                   destination_node)
        else:
            Comment.update(Q('root_target', 'eq', item._id),
                           data={'node': destination_node})
            # update node record of commented files
            if item._id in source_node.commented_files:
                destination_node.commented_files[
                    item._id] = source_node.commented_files[item._id]
                del source_node.commented_files[item._id]
                source_node.save()
                destination_node.save()
예제 #7
0
def saveComment(comment,uid1,wid1):
    c=Comment()
    co=comment
    w=website.objects.get(id=wid1)
    u=User.objects.get(id=uid1)
    c.coment=comment
    c.webid=w
    c.user_id=u
    pp=polarity_comment(co)
    c.polar=pp
    c.rating=comment_rating(pp)
    c.save()
예제 #8
0
def add_comment(**kwargs):

    auth = kwargs['auth']
    node = kwargs['node'] or kwargs['project']

    if not node.comment_level:
        raise HTTPError(http.BAD_REQUEST)

    if not node.can_comment(auth):
        raise HTTPError(http.FORBIDDEN)

    guid = request.json.get('target')
    target = resolve_target(node, guid)

    content = request.json.get('content').strip()
    content = sanitize(content)
    if not content:
        raise HTTPError(http.BAD_REQUEST)
    if len(content) > settings.COMMENT_MAXLENGTH:
        raise HTTPError(http.BAD_REQUEST)

    comment = Comment.create(
        auth=auth,
        node=node,
        target=target,
        user=auth.user,
        content=content,
    )
    comment.save()

    return {
        'comment': serialize_comment(comment, auth)
    }, http.CREATED
예제 #9
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            comment = Comment(content=form.comment.data,
                              user_id=current_user.id,
                              post_id=post.id)
            print(comment)
            db.session.add(comment)
            db.session.commit()
            flash('Your comment has been created!', 'success')

            return redirect(url_for('posts.post', id=id))

        flash('Login to write a comment!', 'primary')

        return redirect(url_for('users.login'))

    for error in form.errors:
        flash(error)

    return render_template('post.html',
                           title=post.title,
                           post=post,
                           form=form,
                           getLikeFun=getLikeFun,
                           getLikeIcon=getLikeIcon,
                           getCommentLikeFun=getCommentLikeFun,
                           getCommentLikeIcon=getCommentLikeIcon)
예제 #10
0
def update_file_guid_referent(self, node, event_type, payload, user=None):
    if event_type == 'addon_file_moved' or event_type == 'addon_file_renamed':
        source = payload['source']
        destination = payload['destination']
        source_node = Node.load(source['node']['_id'])
        destination_node = node
        file_guids = FileNode.resolve_class(source['provider'], FileNode.ANY).get_file_guids(
            materialized_path=source['materialized'] if source['provider'] != 'osfstorage' else source['path'],
            provider=source['provider'],
            node=source_node)

        if event_type == 'addon_file_renamed' and source['provider'] in settings.ADDONS_BASED_ON_IDS:
            return
        if event_type == 'addon_file_moved' and (source['provider'] == destination['provider'] and
                                                 source['provider'] in settings.ADDONS_BASED_ON_IDS) and source_node == destination_node:
            return

        for guid in file_guids:
            obj = Guid.load(guid)
            if source_node != destination_node and Comment.find(Q('root_target', 'eq', guid)).count() != 0:
                update_comment_node(guid, source_node, destination_node)

            if source['provider'] != destination['provider'] or source['provider'] != 'osfstorage':
                old_file = FileNode.load(obj.referent._id)
                obj.referent = create_new_file(obj, source, destination, destination_node)
                obj.save()
                if old_file and not TrashedFileNode.load(old_file._id):
                    old_file.delete()
예제 #11
0
    def get_unread_comments_count(self, obj):
        user = get_user_auth(self.context['request']).user
        node_comments = Comment.find_n_unread(user=user, node=obj, page='node')

        return {
            'node': node_comments
        }
예제 #12
0
파일: comment.py 프로젝트: msarahan/osf.io
def n_unread_comments(node, user):
    """Return the number of unread comments on a node for a user."""
    default_timestamp = datetime(1970, 1, 1, 12, 0, 0)
    view_timestamp = user.comments_viewed_timestamp.get(node._id, default_timestamp)
    return Comment.find(Q('node', 'eq', node) &
                        Q('user', 'ne', user) &
                        Q('date_created', 'gt', view_timestamp) &
                        Q('date_modified', 'gt', view_timestamp)).count()
예제 #13
0
파일: comment.py 프로젝트: sbt9uc/osf.io
def get_comment(cid, auth, owner=False):
    comment = Comment.load(cid)
    if comment is None:
        raise HTTPError(http.NOT_FOUND)
    if owner:
        if auth.user != comment.user:
            raise HTTPError(http.FORBIDDEN)
    return comment
예제 #14
0
파일: comment.py 프로젝트: sbt9uc/osf.io
def n_unread_comments(node, user):
    """Return the number of unread comments on a node for a user."""
    default_timestamp = datetime(1970, 1, 1, 12, 0, 0)
    view_timestamp = user.comments_viewed_timestamp.get(node._id, default_timestamp)
    return Comment.find(Q('node', 'eq', node) &
                        Q('user', 'ne', user) &
                        Q('date_created', 'gt', view_timestamp) &
                        Q('date_modified', 'gt', view_timestamp)).count()
예제 #15
0
파일: comment.py 프로젝트: dplorimer/osf
def get_comment(cid, auth, owner=False):
    comment = Comment.load(cid)
    if comment is None:
        raise HTTPError(http.NOT_FOUND)
    if owner:
        if auth.user != comment.user:
            raise HTTPError(http.FORBIDDEN)
    return comment
예제 #16
0
파일: comment.py 프로젝트: msarahan/osf.io
def add_comment(auth, node, **kwargs):

    if not node.comment_level:
        raise HTTPError(http.BAD_REQUEST)

    if not node.can_comment(auth):
        raise HTTPError(http.FORBIDDEN)

    guid = request.json.get('target')
    target = resolve_target(node, guid)

    content = request.json.get('content').strip()
    content = sanitize(content)
    if not content:
        raise HTTPError(http.BAD_REQUEST)
    if len(content) > settings.COMMENT_MAXLENGTH:
        raise HTTPError(http.BAD_REQUEST)

    comment = Comment.create(
        auth=auth,
        node=node,
        target=target,
        user=auth.user,
        content=content,
    )
    comment.save()

    context = dict(
        gravatar_url=auth.user.gravatar_url,
        content=content,
        target_user=target.user if is_reply(target) else None,
        parent_comment=target.content if is_reply(target) else "",
        url=node.absolute_url
    )
    time_now = datetime.utcnow().replace(tzinfo=pytz.utc)
    sent_subscribers = notify(
        uid=node._id,
        event="comments",
        user=auth.user,
        node=node,
        timestamp=time_now,
        **context
    )

    if is_reply(target):
        if target.user and target.user not in sent_subscribers:
            notify(
                uid=target.user._id,
                event='comment_replies',
                user=auth.user,
                node=node,
                timestamp=time_now,
                **context
            )

    return {
        'comment': serialize_comment(comment, auth)
    }, http.CREATED
예제 #17
0
    def get_unread_comments_count(self, obj):
        user = self.get_user_auth(self.context['request']).user
        node_comments = Comment.find_n_unread(user=user, node=obj, page='node')
        file_comments = self.get_unread_file_comments(obj)

        return {
            'total': node_comments + file_comments,
            'node': node_comments,
            'files': file_comments
        }
예제 #18
0
    def get_unread_comments_count(self, obj):
        user = self.get_user_auth(self.context['request']).user
        node_comments = Comment.find_n_unread(user=user, node=obj, page='node')
        file_comments = self.get_unread_file_comments(obj)

        return {
            'total': node_comments + file_comments,
            'node': node_comments,
            'files': file_comments
        }
예제 #19
0
파일: comment.py 프로젝트: mchelen/osf.io
def update_comment_root_target_file(self, node, event_type, payload, user=None):
    if event_type == 'addon_file_moved':
        source = payload['source']
        destination = payload['destination']
        source_node = Node.load(source['node']['_id'])
        destination_node = node

        if (source.get('provider') == destination.get('provider') == 'osfstorage') and source_node._id != destination_node._id:
            old_file = FileNode.load(source.get('path').strip('/'))
            new_file = FileNode.resolve_class(destination.get('provider'), FileNode.FILE).get_or_create(destination_node, destination.get('path'))

            Comment.update(Q('root_target', 'eq', old_file._id), data={'node': destination_node})

            # update node record of commented files
            if old_file._id in source_node.commented_files:
                destination_node.commented_files[new_file._id] = source_node.commented_files[old_file._id]
                del source_node.commented_files[old_file._id]
                source_node.save()
                destination_node.save()
예제 #20
0
파일: comment.py 프로젝트: pazthor/osf.io
def kwargs_to_comment(kwargs, owner=False):

    comment = Comment.load(kwargs.get('cid'))
    if comment is None:
        raise HTTPError(http.BAD_REQUEST)

    if owner:
        auth = kwargs['auth']
        if auth.user != comment.user:
            raise HTTPError(http.FORBIDDEN)

    return comment
예제 #21
0
 def get_unread_file_comments(self, obj):
     user = self.get_user_auth(self.context['request']).user
     n_unread = 0
     commented_files = File.find(Q('_id', 'in', obj.commented_files.keys()))
     for file_obj in commented_files:
         if obj.get_addon(file_obj.provider):
             try:
                 self.context['view'].get_file_object(obj, file_obj.path, file_obj.provider, check_object_permissions=False)
             except (exceptions.NotFound, exceptions.PermissionDenied):
                 continue
             n_unread += Comment.find_n_unread(user, obj, page='files', root_id=file_obj._id)
     return n_unread
예제 #22
0
파일: comment.py 프로젝트: akrit19/osf.io
def kwargs_to_comment(kwargs, owner=False):

    comment = Comment.load(kwargs.get('cid'))
    if comment is None:
        raise HTTPError(http.BAD_REQUEST)

    if owner:
        auth = kwargs['auth']
        if auth.user != comment.user:
            raise HTTPError(http.FORBIDDEN)

    return comment
예제 #23
0
def new_reply(post_id, comment_id):
    post = Post.query.get_or_404(post_id)
    parent = Comment.query.get_or_404(comment_id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(post_id=post.id,
                          author=current_user,
                          content=form.content.data,
                          parent=parent.id)
        save_comment(comment)
        flash('Your reply has been posted!', 'success')
        return redirect(url_for('posts.post', post_id=post.id))
    return redirect(url_for('posts.post', post_id=post.id))
예제 #24
0
def main():
    query = Comment.find(Q('root_target.1', 'ne', 'guid'))
    logger.info('Found {} comments whose root target is not a guid'.format(
        query.count()))
    migrated = 0
    for comment in query:
        root_target = comment.to_storage()['root_target']
        if root_target:
            logger.info('Root target for comment {}: {}'.format(
                comment._id, root_target))
            _id, collection = root_target
            if collection == 'storedfilenode':
                filenode = get_file_node(_id)
                if filenode:
                    guid = get_guid(filenode)
                    if guid:
                        logger.info('Setting root_target to Guid {}'.format(
                            guid._id))
                        comment.root_target = guid
                        comment.save()
                        migrated += 1
            else:
                logger.error('Unexpected root target: {}'.format(root_target))
        # If root_target is unset, look at the target field
        elif root_target is None:
            logger.info('Root target for comment {} is None'.format(
                comment._id))
            guid = comment.target
            if isinstance(guid.referent, (TrashedFileNode, StoredFileNode)):
                logger.info('Setting root_target to Guid {}'.format(guid._id))
                comment.root_target = guid
                comment.save()
                migrated += 1
            elif isinstance(guid.referent, Comment):
                logger.info(
                    'Comment {} has a comment target. It is a reply.'.format(
                        comment._id))
                found_root = False
                parent = guid.referent
                while not found_root:
                    if not isinstance(parent.target.referent, Comment):
                        found_root = True
                    else:
                        parent = parent.target.referent
                guid = parent.target
                logger.info('Setting root_target to Guid {}'.format(guid._id))
                comment.root_target = guid
                comment.save()
                migrated += 1

    logger.info('Successfully migrated {} comments'.format(migrated))
예제 #25
0
    def post(self, slug):
        context = self.get_context(slug)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)

            post = context.get('post')
            post.comments.append(comment)
            post.save()

            return redirect(url_for('posts.detail', slug=slug))

        return render_template('posts/detail.html', **context)
예제 #26
0
def post(post_id):
    post = Post.query.get_or_404(post_id)
    comments = Comment.query.order_by(Comment.timestamp.desc())
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(post_id=post.id,
                          author=current_user,
                          content=form.content.data)
        save_comment(comment)
        flash('Your comment has been posted!', 'success')
        return redirect(url_for('posts.post', post_id=post.id))
    return render_template('post.html',
                           post=post,
                           form=form,
                           comments=comments)
예제 #27
0
def comment(post_id):
    post = Post.query.get_or_404(post_id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(content=form.content.data,
                          date_posted=datetime.now(timezone('Asia/Kolkata')),
                          user_id=current_user.id,
                          post_id=post_id)
        db.session.add(comment)
        db.session.commit()
        flash('You have added a comment!', 'success')
        return redirect(url_for('post', post_id=post.id))
    return render_template('comment.html',
                           title=post.title,
                           post=post,
                           form=form)
예제 #28
0
def main():
    query = Comment.find(Q('root_target.1', 'ne', 'guid'))
    logger.info('Found {} comments whose root target is not a guid'.format(query.count()))
    migrated = 0
    for comment in query:
        root_target = comment.to_storage()['root_target']
        if root_target:
            logger.info('Root target for comment {}: {}'.format(comment._id, root_target))
            _id, collection = root_target
            if collection == 'storedfilenode':
                filenode = get_file_node(_id)
                if filenode:
                    guid = get_guid(filenode)
                    if guid:
                        logger.info('Setting root_target to Guid {}'.format(guid._id))
                        comment.root_target = guid
                        comment.save()
                        migrated += 1
            else:
                logger.error('Unexpected root target: {}'.format(root_target))
        # If root_target is unset, look at the target field
        elif root_target is None:
            logger.info('Root target for comment {} is None'.format(comment._id))
            guid = comment.target
            if isinstance(guid.referent, (TrashedFileNode, StoredFileNode)):
                logger.info('Setting root_target to Guid {}'.format(guid._id))
                comment.root_target = guid
                comment.save()
                migrated += 1
            elif isinstance(guid.referent, Comment):
                logger.info('Comment {} has a comment target. It is a reply.'.format(comment._id))
                found_root = False
                parent = guid.referent
                while not found_root:
                    if not isinstance(parent.target.referent, Comment):
                        found_root = True
                    else:
                        parent = parent.target.referent
                guid = parent.target
                logger.info('Setting root_target to Guid {}'.format(guid._id))
                comment.root_target = guid
                comment.save()
                migrated += 1

    logger.info('Successfully migrated {} comments'.format(migrated))
예제 #29
0
 def get_unread_file_comments(self, obj):
     user = self.get_user_auth(self.context['request']).user
     n_unread = 0
     commented_files = File.find(Q('_id', 'in', obj.commented_files.keys()))
     for file_obj in commented_files:
         if obj.get_addon(file_obj.provider):
             try:
                 get_file_object(node=obj,
                                 path=file_obj.path,
                                 provider=file_obj.provider,
                                 request=self.context['request'])
             except (exceptions.NotFound, exceptions.PermissionDenied):
                 continue
             n_unread += Comment.find_n_unread(user,
                                               obj,
                                               page='files',
                                               root_id=file_obj._id)
     return n_unread
예제 #30
0
def update_comment_targets_to_guids():
    comments = Comment.find()
    for comment in comments:
        # Skip comments on deleted files
        if not comment.target:
            continue
        if isinstance(comment.root_target, StoredFileNode):
            comment.root_target = comment.root_target.get_guid()
        elif comment.root_target:
            comment.root_target = Guid.load(comment.root_target._id)

        if isinstance(comment.target, StoredFileNode):
            comment.target = comment.target.get_guid()
        else:
            comment.target = Guid.load(comment.target._id)

        comment.save()
        logger.info("Migrated root_target and target for comment {0}".format(comment._id))
예제 #31
0
def update_comment_targets_to_guids():
    comments = Comment.find()
    for comment in comments:
        # Skip comments on deleted files
        if not comment.target:
            continue
        if isinstance(comment.root_target, StoredFileNode):
            comment.root_target = comment.root_target.get_guid()
        elif comment.root_target:
            comment.root_target = Guid.load(comment.root_target._id)

        if isinstance(comment.target, StoredFileNode):
            comment.target = comment.target.get_guid()
        else:
            comment.target = Guid.load(comment.target._id)

        comment.save()
        logger.info('Migrated root_target and target for comment {0}'.format(
            comment._id))
예제 #32
0
def comment_new(question_id, answer_id):

    ans = Answer.query.filter_by(id=answer_id).first()
    if not ans:
        flash("answer not found...")
        return redirect(
            url_for('main.question_detail', question_id=question_id) +
            "#answer")

    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(comment=form.comment.data,
                          author=current_user,
                          answer_id=answer_id)
        db.session.add(comment)
        db.session.commit()
        flash("done commenting...")
        return redirect(
            url_for('main.question_detail', question_id=question_id) +
            "#answer")

    return render_template('main/comment.html', form=form)
예제 #33
0
def update_file_guid_referent(self, node, event_type, payload, user=None):
    if event_type == 'addon_file_moved' or event_type == 'addon_file_renamed':
        source = payload['source']
        destination = payload['destination']
        source_node = Node.load(source['node']['_id'])
        destination_node = node
        file_guids = FileNode.resolve_class(
            source['provider'], FileNode.ANY).get_file_guids(
                materialized_path=source['materialized']
                if source['provider'] != 'osfstorage' else source['path'],
                provider=source['provider'],
                node=source_node)

        if event_type == 'addon_file_renamed' and source[
                'provider'] in settings.ADDONS_BASED_ON_IDS:
            return
        if event_type == 'addon_file_moved' and (
                source['provider'] == destination['provider']
                and source['provider'] in settings.ADDONS_BASED_ON_IDS
        ) and source_node == destination_node:
            return

        for guid in file_guids:
            obj = Guid.load(guid)
            if source_node != destination_node and Comment.find(
                    Q('root_target', 'eq', guid)).count() != 0:
                update_comment_node(guid, source_node, destination_node)

            if source['provider'] != destination['provider'] or source[
                    'provider'] != 'osfstorage':
                old_file = FileNode.load(obj.referent._id)
                obj.referent = create_new_file(obj, source, destination,
                                               destination_node)
                obj.save()
                if old_file and not TrashedFileNode.load(old_file._id):
                    old_file.delete()
예제 #34
0
 def get_unread_comments_count(self, obj):
     auth = self.get_user_auth(self.context['request'])
     user = auth.user
     return Comment.find_unread(user=user, node=obj)
예제 #35
0
def update_comment_node(root_target_id, source_node, destination_node):
    Comment.update(Q('root_target', 'eq', root_target_id), data={'node': destination_node})
    source_node.save()
    destination_node.save()
예제 #36
0
def update_comments():
    comments = Comment.find()
    for comment in comments:
        comment.root_target = comment.node
        comment.page = Comment.OVERVIEW
        comment.save()
예제 #37
0
def jurisdiction_comment(request):
    requestProcessor = HttpRequestProcessor(request)
    user = request.user
    data = {}
    dajax = Dajax()
    ajax = requestProcessor.getParameter('ajax')
    comments_changed = requestProcessor.getParameter('comments_changed')
    if comments_changed == 'yes':
        data['comments_changed'] = 'yes'
    else:
        data['comments_changed'] = 'no'
    if (ajax != None):
        if ajax == 'open_jurisdiction_comment':
            entity_id = requestProcessor.getParameter('entity_id')
            entity_name = requestProcessor.getParameter('entity_name')
            jid = requestProcessor.getParameter('jurisdiction_id')
            try:
                jurisdiction = Jurisdiction.objects.get(id = jid)
            except:
                jurisdiction = None
            comments = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id, parent_comment__isnull = True).order_by('-create_datetime')
  
            userviews = UserCommentView.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id, user = user)
            
            temp_comments = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).order_by('-create_datetime')
            last_comment = None
            if len(temp_comments) > 0 :
                last_comment = temp_comments[0]
            
            has_userview = False
            if len(userviews) > 0:
                userview = userviews[0]
                if userview.last_comment != None:
                    data['userview_last_comment'] = userview.last_comment.id
                    data['userview'] = userviews[0]
                    userview.comments_count = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).count()
                    userview.last_comment = last_comment
                    userview.view_datetime = datetime.datetime.now()
                    userview.save()
                    has_userview = True
            if has_userview == False:
                userview = None
                data['userview'] = userview
                data['userview_last_comment'] = 0
                userview = UserCommentView()
                userview.user = user
                userview.jurisdiction = jurisdiction
                userview.entity_name = entity_name
                userview.entity_id = entity_id
                userview.comments_count = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).count()
                userview.last_comment = last_comment
                userview.view_datetime = datetime.datetime.now()
                userview.save()
            
            af = AnswerReference.objects.get(id = entity_id)
            aa = ValidationUtil()
            data['answer'] = af
            data['answer_text'] = aa.get_formatted_value(af.value, af.question)
            data['jurisdiction'] = jurisdiction
            label = af.question.question
            if len(af.question.question) > 75:
                label = af.question.question[:78]+ '...'
            data['label'] = label
            
            data['commnets'] = comments
            
            others_afs = AnswerReference.objects.filter(jurisdiction = jurisdiction, question = af.question, approval_status='A').exclude(id = entity_id).order_by('-create_datetime')
            if len(others_afs) > 0 :
                old_answer = others_afs[0]
                if old_answer.id < af.id:
                    data['old_answer'] = old_answer
                    data['old_answer_text'] = aa.get_formatted_value(old_answer.value, old_answer.question)
                else:
                    data['old_answer'] = None
                    data['old_answer_text'] = ''
            else:
                data['old_answer'] = None
                data['old_answer_text'] = ''
  
            body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/jurisdiction_comment.html', data, '') 
            dajax.assign('#fancyboxformDiv','innerHTML', body)
            script = requestProcessor.decode_jinga_template(request,'website/jurisdictions/jurisdiction_comment.js', data, '')
            dajax.script(script)
            #script = requestProcessor.decode_jinga_template(request,'website/blocks/comments_list.js', data, '')
            #dajax.script(script)
            dajax.script('controller.showModalDialog("#fancyboxformDiv");')
        
        if ajax =='create_jurisdiction_comment':
            answer_id = requestProcessor.getParameter('answer_id')
            jid = requestProcessor.getParameter('jurisdiction_id')
            comment_type = 'JC'
            
            data['answer_id'] = answer_id
            data['jurisdiction_id'] = jid
            data['comment_type'] = comment_type
            data['parent_comment'] = ''
            body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/create_comment.html', data, '')
            script =  requestProcessor.decode_jinga_template(request,'website/jurisdictions/create_comment.js', data, '')
            dajax.assign('#secondDialogDiv','innerHTML', body) 
            dajax.script(script)
            dajax.script('controller.showSecondDialog("#secondDialogDiv");')
        
        if ajax =='comment_create_submit':
            entity_id = requestProcessor.getParameter('entity_id')
            entity_name = requestProcessor.getParameter('entity_name')
            jurisdiction_id = requestProcessor.getParameter('jurisdiction_id')
            comment_type = requestProcessor.getParameter('comment_type')
            comment_text = requestProcessor.getParameter('comment')
            parent_comment = requestProcessor.getParameter('parent_comment')
            try:
                jurisdiction = Jurisdiction.objects.get(id = jurisdiction_id)
            except:
                jurisdiction = None
                
            comment = Comment()
            comment.jurisdiction = jurisdiction
            comment.entity_name = entity_name
            comment.entity_id = entity_id
            comment.user = user
            comment.comment_type = comment_type
            comment.comment = comment_text
            if parent_comment != '':
                parent = Comment.objects.get(id = parent_comment)
                comment.parent_comment = parent
            comment.save()
            
            userviews = UserCommentView.objects.filter(user = user, jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id)
            userview = userviews[0]
            userview.last_comment = comment
            userview.comments_count = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).count()
            userview.view_datetime = datetime.datetime.now()
            userview.save()
            
            
            dajax.script('controller.closeSecondDialog();')
            dajax.script('controller.postRequest("/jurisdiction_comment/", {ajax: "open_jurisdiction_comment", jurisdiction_id:'+str(jurisdiction_id)+', entity_id: "'+str(entity_id)+'", entity_name: "'+str(entity_name)+'", comments_changed: "yes"});')

            data = {}
            data['action'] = 'refresh_ahj_qa'
            answer = AnswerReference.objects.get(id=entity_id) 
            validation_util_obj = ValidationUtil()                  
            body = validation_util_obj.get_question_answers_display_data(request, answer.jurisdiction, answer.question, data)      
            dajax.assign('#div_'+str(answer.question_id),'innerHTML', body)      
                
        if ajax =='reply_comment':
            cid = requestProcessor.getParameter('cid')
            comment = Comment.objects.get(id = cid)            
            data['comment'] = comment
            body = requestProcessor.decode_jinga_template(request,'website/blocks/reply_comment_form.html', data, '')
            script = requestProcessor.decode_jinga_template(request,'website/blocks/reply_comment_form.js', data, '')
            dajax.assign('#button-div-'+str(cid),'innerHTML', body) 
            dajax.script(script)
            
        
        if ajax == 'cancel_reply':
            cid = requestProcessor.getParameter('cid')
            body = '<a class="smallbutton" href="#" onClick="controller.postRequest(\'/jurisdiction_comment/\', {ajax: \'reply_comment\', cid: '+str(cid)+'});return false;">Reply</a><a class="smallbutton" href="#">Flag</a>'
            dajax.assign('#button-div-'+str(cid),'innerHTML', body) 
            
        if ajax == 'flag_comment':
            cid = requestProcessor.getParameter('cid')
            comment = Comment.objects.get(id = cid) 
            comment.approval_status = 'F'
            comment.save()
            
            af = AnswerReference.objects.get(id = comment.entity_id)
            to_mail = [django_settings.ADMIN_EMAIL_ADDRESS]
            data['comment'] = comment
            data['user'] = user
            data['question'] = af.question.question
 
            data['site_url'] = django_settings.SITE_URL
            data['requestProcessor'] = requestProcessor
            data['request'] = request
            send_email(data, to_mail)
            
            dajax.assign('#comment_'+str(cid), 'innerHTML', '<p>This comment had been flagged as inappropriate and is hidden pending review.</p>')
        
        if ajax == 'show_old_comments':
            entity_id = requestProcessor.getParameter('answer_id')
            entity_name = 'AnswerReference'
            jid = requestProcessor.getParameter('jurisdiction_id')
            try:
                jurisdiction = Jurisdiction.objects.get(id = jid)
            except:
                jurisdiction = None
            comments = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id, parent_comment__isnull = True).order_by('-create_datetime')
            
            userviews = UserCommentView.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id, user = user)
            
            temp_comments = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).order_by('-create_datetime')
            last_comment = None
            if len(temp_comments) > 0 :
                last_comment = temp_comments[0]
            if len(userviews) > 0:
                userview = userviews[0]
                data['userview'] = userview
                userview.comments_count = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).count()
                userview.last_comment = last_comment
                userview.view_datetime = datetime.datetime.now()
                userview.save()
            else:
                userview = None
                data['userview'] = userview
                userview = UserCommentView()
                userview.user = user
                userview.jurisdiction = jurisdiction
                userview.entity_name = entity_name
                userview.entity_id = entity_id
                userview.comments_count = Comment.objects.filter(jurisdiction = jurisdiction, entity_name = entity_name, entity_id = entity_id).count()
                userview.last_comment = last_comment
                userview.view_datetime = datetime.datetime.now()
                userview.save()
            data['commnets'] = comments
            
            body = requestProcessor.decode_jinga_template(request,'website/blocks/comments_list.html', data, '')
            dajax.assign('#old_list ul', 'innerHTML', body)
            dajax.assign('#show_commnet_div', 'innerHTML', '<a id="id_a_hide" href="#"><img src="/media/images/arrow_down.png" style="vertical-align:bottom;" alt="Hide old comments" >Hide old comments </a>')
            script = requestProcessor.decode_jinga_template(request,'website/jurisdictions/jurisdiction_comment.js', data, '')
            dajax.script(script)
            
        return HttpResponse(dajax.json())
    return
예제 #38
0
def update_comments():
    comments = Comment.find()
    for comment in comments:
        comment.root_target = comment.node
        comment.page = Comment.OVERVIEW
        comment.save()
예제 #39
0
def _view_project(node, auth, primary=False):
    """Build a JSON object containing everything needed to render
    project.view.mako.
    """
    user = auth.user

    parent = node.find_readable_antecedent(auth)
    if user:
        bookmark_collection = find_bookmark_collection(user)
        bookmark_collection_id = bookmark_collection._id
        in_bookmark_collection = bookmark_collection.pointing_at(
            node._primary_key) is not None
    else:
        in_bookmark_collection = False
        bookmark_collection_id = ''
    view_only_link = auth.private_key or request.args.get('view_only',
                                                          '').strip('/')
    anonymous = has_anonymous_link(node, auth)
    widgets, configs, js, css = _render_addon(node)
    redirect_url = node.url + '?view_only=None'

    disapproval_link = ''
    if (node.is_pending_registration and node.has_permission(user, ADMIN)):
        disapproval_link = node.root.registration_approval.stashed_urls.get(
            user._id, {}).get('reject', '')

    if (node.is_pending_embargo and node.has_permission(user, ADMIN)):
        disapproval_link = node.root.embargo.stashed_urls.get(user._id,
                                                              {}).get(
                                                                  'reject', '')

    # Before page load callback; skip if not primary call
    if primary:
        for addon in node.get_addons():
            messages = addon.before_page_load(node, user) or []
            for message in messages:
                status.push_status_message(message,
                                           kind='info',
                                           dismissible=False,
                                           trust=True)
    data = {
        'node': {
            'disapproval_link':
            disapproval_link,
            'id':
            node._primary_key,
            'title':
            node.title,
            'category':
            node.category_display,
            'category_short':
            node.category,
            'node_type':
            node.project_or_component,
            'description':
            node.description or '',
            'license':
            serialize_node_license_record(node.license),
            'url':
            node.url,
            'api_url':
            node.api_url,
            'absolute_url':
            node.absolute_url,
            'redirect_url':
            redirect_url,
            'display_absolute_url':
            node.display_absolute_url,
            'update_url':
            node.api_url_for('update_node'),
            'in_dashboard':
            in_bookmark_collection,
            'is_public':
            node.is_public,
            'is_archiving':
            node.archiving,
            'date_created':
            iso8601format(node.date_created),
            'date_modified':
            iso8601format(node.logs[-1].date) if node.logs else '',
            'tags': [tag._primary_key for tag in node.tags],
            'children':
            bool(node.nodes_active),
            'is_registration':
            node.is_registration,
            'is_pending_registration':
            node.is_pending_registration,
            'is_retracted':
            node.is_retracted,
            'is_pending_retraction':
            node.is_pending_retraction,
            'retracted_justification':
            getattr(node.retraction, 'justification', None),
            'embargo_end_date':
            node.embargo_end_date.strftime('%A, %b. %d, %Y')
            if node.embargo_end_date else False,
            'is_pending_embargo':
            node.is_pending_embargo,
            'is_embargoed':
            node.is_embargoed,
            'is_pending_embargo_termination':
            node.is_embargoed
            and (node.embargo_termination_approval
                 and node.embargo_termination_approval.is_pending_approval),
            'registered_from_url':
            node.registered_from.url if node.is_registration else '',
            'registered_date':
            iso8601format(node.registered_date)
            if node.is_registration else '',
            'root_id':
            node.root._id if node.root else None,
            'registered_meta':
            node.registered_meta,
            'registered_schemas':
            serialize_meta_schemas(node.registered_schema),
            'registration_count':
            node.registrations_all.count(),
            'is_fork':
            node.is_fork,
            'forked_from_id':
            node.forked_from._primary_key if node.is_fork else '',
            'forked_from_display_absolute_url':
            node.forked_from.display_absolute_url if node.is_fork else '',
            'forked_date':
            iso8601format(node.forked_date) if node.is_fork else '',
            'fork_count':
            node.forks.count(),
            'templated_count':
            node.templated_list.count(),
            'watched_count':
            node.watches.count(),
            'private_links': [x.to_json() for x in node.private_links_active],
            'link':
            view_only_link,
            'anonymous':
            anonymous,
            'points':
            len(node.get_points(deleted=False, folders=False)),
            'comment_level':
            node.comment_level,
            'has_comments':
            bool(Comment.find(Q('node', 'eq', node))),
            'has_children':
            bool(Comment.find(Q('node', 'eq', node))),
            'identifiers': {
                'doi': node.get_identifier_value('doi'),
                'ark': node.get_identifier_value('ark'),
            },
            'institutions':
            get_affiliated_institutions(node) if node else [],
            'alternative_citations':
            [citation.to_json() for citation in node.alternative_citations],
            'has_draft_registrations':
            node.has_active_draft_registrations,
            'contributors':
            [contributor._id for contributor in node.contributors],
            'is_preprint':
            node.is_preprint,
            'is_preprint_orphan':
            node.is_preprint_orphan,
            'preprint_file_id':
            node.preprint_file._id if node.preprint_file else None,
            'preprint_url':
            node.preprint_url
        },
        'parent_node': {
            'exists':
            parent is not None,
            'id':
            parent._primary_key if parent else '',
            'title':
            parent.title if parent else '',
            'category':
            parent.category_display if parent else '',
            'url':
            parent.url if parent else '',
            'api_url':
            parent.api_url if parent else '',
            'absolute_url':
            parent.absolute_url if parent else '',
            'registrations_url':
            parent.web_url_for('node_registrations') if parent else '',
            'is_public':
            parent.is_public if parent else '',
            'is_contributor':
            parent.is_contributor(user) if parent else '',
            'can_view':
            parent.can_view(auth) if parent else False
        },
        'user': {
            'is_contributor': node.is_contributor(user),
            'is_admin': node.has_permission(user, ADMIN),
            'is_admin_parent':
            parent.is_admin_parent(user) if parent else False,
            'can_edit': (node.can_edit(auth) and not node.is_registration),
            'has_read_permissions': node.has_permission(user, READ),
            'permissions': node.get_permissions(user) if user else [],
            'is_watching': user.is_watching(node) if user else False,
            'id': user._id if user else None,
            'username': user.username if user else None,
            'fullname': user.fullname if user else '',
            'can_comment': node.can_comment(auth),
            'show_wiki_widget': _should_show_wiki_widget(node, user),
            'dashboard_id': bookmark_collection_id,
            'institutions': get_affiliated_institutions(user) if user else [],
        },
        'badges':
        _get_badge(user),
        # TODO: Namespace with nested dicts
        'addons_enabled':
        node.get_addon_names(),
        'addons':
        configs,
        'addon_widgets':
        widgets,
        'addon_widget_js':
        js,
        'addon_widget_css':
        css,
        'node_categories': [{
            'value': key,
            'display_name': value
        } for key, value in settings.NODE_CATEGORY_MAP.iteritems()]
    }
    return data
예제 #40
0
파일: node.py 프로젝트: 545zhou/osf.io
def _view_project(node, auth, primary=False):
    """Build a JSON object containing everything needed to render
    project.view.mako.
    """
    user = auth.user

    parent = node.parent_node
    if user:
        bookmark_collection = find_bookmark_collection(user)
        bookmark_collection_id = bookmark_collection._id
        in_bookmark_collection = bookmark_collection.pointing_at(node._primary_key) is not None
    else:
        in_bookmark_collection = False
        bookmark_collection_id = ''
    view_only_link = auth.private_key or request.args.get('view_only', '').strip('/')
    anonymous = has_anonymous_link(node, auth)
    widgets, configs, js, css = _render_addon(node)
    redirect_url = node.url + '?view_only=None'

    disapproval_link = ''
    if (node.is_pending_registration and node.has_permission(user, ADMIN)):
        disapproval_link = node.root.registration_approval.stashed_urls.get(user._id, {}).get('reject', '')

    # Before page load callback; skip if not primary call
    if primary:
        for addon in node.get_addons():
            messages = addon.before_page_load(node, user) or []
            for message in messages:
                status.push_status_message(message, kind='info', dismissible=False, trust=True)
    data = {
        'node': {
            'disapproval_link': disapproval_link,
            'id': node._primary_key,
            'title': node.title,
            'category': node.category_display,
            'category_short': node.category,
            'node_type': node.project_or_component,
            'description': node.description or '',
            'license': serialize_node_license_record(node.license),
            'url': node.url,
            'api_url': node.api_url,
            'absolute_url': node.absolute_url,
            'redirect_url': redirect_url,
            'display_absolute_url': node.display_absolute_url,
            'update_url': node.api_url_for('update_node'),
            'in_dashboard': in_bookmark_collection,
            'is_public': node.is_public,
            'is_archiving': node.archiving,
            'date_created': iso8601format(node.date_created),
            'date_modified': iso8601format(node.logs[-1].date) if node.logs else '',
            'tags': [tag._primary_key for tag in node.tags],
            'children': bool(node.nodes_active),
            'is_registration': node.is_registration,
            'is_pending_registration': node.is_pending_registration,
            'is_retracted': node.is_retracted,
            'is_pending_retraction': node.is_pending_retraction,
            'retracted_justification': getattr(node.retraction, 'justification', None),
            'embargo_end_date': node.embargo_end_date.strftime("%A, %b. %d, %Y") if node.embargo_end_date else False,
            'is_pending_embargo': node.is_pending_embargo,
            'is_embargoed': node.is_embargoed,
            'is_pending_embargo_termination': node.is_embargoed and (
                node.embargo_termination_approval and
                node.embargo_termination_approval.is_pending_approval
            ),
            'registered_from_url': node.registered_from.url if node.is_registration else '',
            'registered_date': iso8601format(node.registered_date) if node.is_registration else '',
            'root_id': node.root._id if node.root else None,
            'registered_meta': node.registered_meta,
            'registered_schemas': serialize_meta_schemas(node.registered_schema),
            'registration_count': node.registrations_all.count(),
            'is_fork': node.is_fork,
            'forked_from_id': node.forked_from._primary_key if node.is_fork else '',
            'forked_from_display_absolute_url': node.forked_from.display_absolute_url if node.is_fork else '',
            'forked_date': iso8601format(node.forked_date) if node.is_fork else '',
            'fork_count': node.forks.count(),
            'templated_count': node.templated_list.count(),
            'watched_count': node.watches.count(),
            'private_links': [x.to_json() for x in node.private_links_active],
            'link': view_only_link,
            'anonymous': anonymous,
            'points': len(node.get_points(deleted=False, folders=False)),
            'piwik_site_id': node.piwik_site_id,
            'comment_level': node.comment_level,
            'has_comments': bool(Comment.find(Q('node', 'eq', node))),
            'has_children': bool(Comment.find(Q('node', 'eq', node))),
            'identifiers': {
                'doi': node.get_identifier_value('doi'),
                'ark': node.get_identifier_value('ark'),
            },
            'institution': {
                'name': node.primary_institution.name if node.primary_institution else None,
                'logo_path': node.primary_institution.logo_path if node.primary_institution else None,
                'id': node.primary_institution._id if node.primary_institution else None
            },
            'alternative_citations': [citation.to_json() for citation in node.alternative_citations],
            'has_draft_registrations': node.has_active_draft_registrations,
            'contributors': [contributor._id for contributor in node.contributors]
        },
        'parent_node': {
            'exists': parent is not None,
            'id': parent._primary_key if parent else '',
            'title': parent.title if parent else '',
            'category': parent.category_display if parent else '',
            'url': parent.url if parent else '',
            'api_url': parent.api_url if parent else '',
            'absolute_url': parent.absolute_url if parent else '',
            'registrations_url': parent.web_url_for('node_registrations') if parent else '',
            'is_public': parent.is_public if parent else '',
            'is_contributor': parent.is_contributor(user) if parent else '',
            'can_view': parent.can_view(auth) if parent else False
        },
        'user': {
            'is_contributor': node.is_contributor(user),
            'is_admin': node.has_permission(user, ADMIN),
            'is_admin_parent': parent.is_admin_parent(user) if parent else False,
            'can_edit': (node.can_edit(auth)
                         and not node.is_registration),
            'has_read_permissions': node.has_permission(user, READ),
            'permissions': node.get_permissions(user) if user else [],
            'is_watching': user.is_watching(node) if user else False,
            'piwik_token': user.piwik_token if user else '',
            'id': user._id if user else None,
            'username': user.username if user else None,
            'fullname': user.fullname if user else '',
            'can_comment': node.can_comment(auth),
            'show_wiki_widget': _should_show_wiki_widget(node, user),
            'dashboard_id': bookmark_collection_id,
            'institutions': get_affiliated_institutions(user) if user else [],
        },
        'badges': _get_badge(user),
        # TODO: Namespace with nested dicts
        'addons_enabled': node.get_addon_names(),
        'addons': configs,
        'addon_widgets': widgets,
        'addon_widget_js': js,
        'addon_widget_css': css,
        'node_categories': Node.CATEGORY_MAP
    }
    return data
예제 #41
0
def update_comment_node(root_target_id, source_node, destination_node):
    Comment.update(Q('root_target', 'eq', root_target_id),
                   data={'node': destination_node})
    source_node.save()
    destination_node.save()