Ejemplo n.º 1
0
def create_forum_thread(request):
    if not request.user.is_superuser:
        user_run_throttler = UserActionThrottler(request.user,
                                                 "forum-thread-create",
                                                 24 * 60 * 60, 10)
        if not user_run_throttler.increm():
            return ForumError.FORUM_THREAD_LIMIT_EXCEEDED

    title = request.POST["title"]

    if len(title) > 160:
        return ForumError.TITLE_TOO_LONG

    non_empty_url = False
    for character in title:
        if character.isalnum():
            non_empty_url = True
    if not non_empty_url:
        return ForumError.INVALID_TITLE

    forum = Forum.objects.get(id=int(request.POST["forumId"]))
    forum_thread = ForumThread.create(request.user, request.POST["title"],
                                      request.POST["message"], forum)

    state = State()
    forum_thread.publish_create_event()
    forum_thread.add_to_state(state)
    return state.to_response({"forumThreadId": forum_thread.id})
Ejemplo n.º 2
0
def private_chat_state(request):
    user1 = get_user_model().objects.get(id=int(request.POST["userId"]))
    user2 = request.user

    state = State()

    existing_chat = PrivateChat.get(user1=user1, user2=user2)

    if existing_chat:
        last_message_id = None
        if "lastMessageId" in request.POST:
            last_message_id = int(request.POST["lastMessageId"])
        existing_chat.add_to_state(state,
                                   message_count=20,
                                   last_message_id=last_message_id)
        return state.to_response({"privateChatId": existing_chat.id})

    create_throttle = UserActionThrottler(request.user, "create-private-chat",
                                          24 * 60 * 60, 10)

    if not request.user.is_superuser and not create_throttle.increm():
        return ChatError.NEW_PRIVATE_CHAT_LIMIT_EXCEEDED

    private_chat = PrivateChat.get_or_create(user1, user2)
    private_chat.add_to_state(state)

    return state.to_response({"privateChatId": private_chat.id})
Ejemplo n.º 3
0
def public_user_profile(request, profile_user):
    state = State()
    user_summary = get_public_user_class()(profile_user)
    state.add(user_summary)
    return state.to_response({
        "userId": profile_user.id,
    })
Ejemplo n.º 4
0
def latest_blog_state():
    blog_entries = BlogEntry.objects.filter(visible=True, discussion__isnull=False)\
                                    .order_by("-discussion__message_thread__last_activity")\
                                    .prefetch_related("article", "discussion", "discussion__message_thread")[:5]

    state = State()
    for blog_entry in blog_entries:
        blog_entry.add_to_state(state)
    return state
Ejemplo n.º 5
0
def documentation(request):
    state = State()

    documentation_entries = DocumentationEntry.objects.all().prefetch_related("article")
    for entry in documentation_entries:
        state.add(entry)
        state.add(entry.article)

    return state.to_response({"documentationEntryId": 1})
Ejemplo n.º 6
0
def questionnaire_state(request):
    questionnaire_id = int(request.POST["questionnaireId"])
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)

    if not request.user.is_superuser and not questionnaire.visible and questionnaire.owner_id != request.user.id:
        return BaseError.NOT_ALLOWED

    state = State()
    questionnaire.add_to_state(state, request.user)
    return state
Ejemplo n.º 7
0
def get_blogpost(request):
    try:
        blog_post = BlogEntry.objects.get(url_name=str(request.GET["entryUrlName"]))
        if not blog_post.visible and not request.user.is_superuser:
            return BaseError.NOT_ALLOWED
    except ObjectDoesNotExist:
        return BaseError.OBJECT_NOT_FOUND
    state = State()
    state.add(blog_post)
    state.add(blog_post.article)
    return state
Ejemplo n.º 8
0
 def view_func(request):
     ids = int_list(request.GET.getlist("ids[]"))
     if len(ids) > max_ids:
         # TODO: log this, may need to ban some asshole
         from establishment.errors.errors import BaseError
         return BaseError.TOO_MANY_OBJECTS
     state = State(request)
     for obj in cls.objects.get(id__in=ids):
         if not permission_filter or permission_filter(obj):
             state.add(obj)
     return state
Ejemplo n.º 9
0
def recognize(request):
    if not request.FILES or len(request.FILES) == 0:
        return StorageError.NO_FILES

    files = list(request.FILES.items())
    title = request.POST['title']

    state = State()
    for name, image in files:
        data = create_anpr(image, title)
        return state.to_response(extra={"success": True, "response": data})
Ejemplo n.º 10
0
def get_article_state(article):
    article_edits = ArticleEdit.objects.filter(article=article)

    state = State()
    state.add(article)
    state.add_all(article_edits)

    # TODO: Language should be loaded in PublicState
    from establishment.content.models import Language
    state.add_all(Language.objects.all())
    return state
Ejemplo n.º 11
0
def full_article(request):
    article = Article.objects.get(id=int(request.GET["articleId"]))

    # Permission checking to access all edits for this article
    if not request.user.is_superuser and article.author_created != request.user:
        return BaseError.NOT_ALLOWED

    state = State()

    article.add_to_state(state, True)

    return state
Ejemplo n.º 12
0
def group_chat_state(request):
    group_chat = GroupChat.objects.get(id=int(request.GET["chatId"]))

    state = State(request)

    last_message_id = request.GET.get("lastMessageId", None)
    if last_message_id:
        last_message_id = int(last_message_id)

    group_chat.add_to_state(state, last_message_id)

    return state.to_response()
Ejemplo n.º 13
0
def translate(request):
    if not request.FILES or len(request.FILES) == 0:
        return StorageError.NO_FILES

    files = list(request.FILES.items())
    title = request.POST['title']

    state = State()
    for name, image in files:
        public_storage_file = create_translation(request.user, image, title)
        public_storage_file.add_to_state(state)
    return state.to_response(extra={"success": True})
Ejemplo n.º 14
0
def latest_forum_state():
    state = State()

    forum_threads = ForumThread.objects.filter(hidden=False)\
                                       .order_by("-message_thread__last_activity")\
                                       .prefetch_related("message_thread", "parent", "content", "content__reaction_collection")[:5]

    for forum_thread in forum_threads:
        state.add(forum_thread)
        state.add(forum_thread.parent)

    return state
Ejemplo n.º 15
0
def private_chat_list(request):
    # TODO: superuser shoud be able to specify a user
    private_chats = PrivateChat.objects.filter(
        Q(user1=request.user) | Q(user2=request.user))
    if "onlyUnread" in request.GET:
        private_chats = private_chats.filter(
            first_unread_message__has_key=str(request.user.id))
    private_chats = private_chats.prefetch_related("message_thread")
    state = State()
    # TODO: it's very expensive to have num_private_chat DB hits for messages, optimize this
    for private_chat in private_chats:
        private_chat.add_to_state(state, message_count=20)
    return state
Ejemplo n.º 16
0
def fetch_article(request):
    article_ids = request.GET.getlist("ids[]")
    article_ids = [int(x) for x in article_ids]
    if len(article_ids) > 128:
        return ContentError.REQUESTED_TOO_MANY_ARTICLES
    articles = Article.objects.filter(id__in=article_ids)

    state = State()

    for article in articles:
        if article.is_available_to(request.user):
            state.add(article)

    return state.to_response()
Ejemplo n.º 17
0
def forum_thread_state(request):
    forum_thread = ForumThread.objects.get(
        id=int(request.POST["forumThreadId"]))
    if forum_thread.hidden and not request.user.is_superuser:
        return BaseError.NOT_ALLOWED

    forum_view_throttler = ActionThrottler(
        request.visitor.unique() + "-forum-thread-" + str(forum_thread.id) +
        "-view", 60 * 60 * 24, 1)
    if forum_view_throttler.increm():
        forum_thread.increment_num_views()

    state = State(request)
    forum_thread.add_to_state(state, request)
    return state.to_response()
Ejemplo n.º 18
0
def questionnaire_all_answers(request):
    questionnaire_id = int(request.GET["questionnaireId"])
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)

    if not request.user.is_superuser and questionnaire.owner_id != request.user.id:
        return BaseError.NOT_ALLOWED

    state = State()
    questionnaire.add_to_state(state)

    answers = QuestionnaireInstance.objects.filter(
        questionnaire=questionnaire).prefetch_related(
            "question_answers__choices")
    for answer in answers:
        answer.add_to_state(state)

    return state
Ejemplo n.º 19
0
def change_user_group(request):
    group_id = int(request.POST["groupId"])
    group = UserGroup.get_group_by_id(group_id)
    if not request.user.is_superuser and group.owner_id != request.user.id:
        return BaseError.NOT_ALLOWED

    state = State()
    user_id = int(request.POST["userId"])
    action = request.POST["action"]
    if action == "remove":
        UserGroupMember.objects.filter(user_id=user_id,
                                       group_id=group_id).delete()
    elif action == "add":
        group_member, created = UserGroupMember.objects.get_or_create(
            user_id=user_id, group_id=group_id)
        state.add(group_member)
    return state
Ejemplo n.º 20
0
def add_entry(request):
    title = request.POST.get("title", "Unnamed entry" + str(datetime.datetime.now()))
    url_name = request.POST.get("urlName", slugify(title))
    is_visible = json.loads(request.POST.get("isVisible", "false"))

    article = Article(author_created=request.user, name=title)

    if "content" in request.POST:
        article.markup = request.POST["content"]

    with transaction.atomic():
        article.save()
        entry = BlogEntry.objects.create(url_name=url_name, article=article, visible=is_visible)

    state = State()
    entry.add_to_state(state)
    return state.to_response({"blogEntryId": entry.id})
Ejemplo n.º 21
0
def get_blog_state(request):
    blog_posts = BlogEntry.objects.order_by("-article__date_created").prefetch_related("article")

    if not request.user.is_superuser:
        blog_posts = blog_posts.filter(visible=True)

    if request.is_ajax() and "lastDate" in request.GET:
        last_date = datetime.datetime.fromtimestamp(float(request.GET["lastDate"]))
        blog_posts = blog_posts.filter(article__date_created__lt=last_date)

    blog_posts = blog_posts[:(BLOG_FETCH_CHUNK + 1)]

    state = State()

    for blog_post in blog_posts[:BLOG_FETCH_CHUNK]:
        blog_post.add_to_state(state)

    return state, (len(blog_posts) <= BLOG_FETCH_CHUNK)
Ejemplo n.º 22
0
def private_chat_post(request):
    if not request.user.is_superuser:
        # TODO: this needs multiple throttlers
        user_run_throttler = UserActionThrottler(request.user, "post-message",
                                                 60, 60)
        if not user_run_throttler.increm():
            return ChatError.MESSAGE_LIMIT_EXCEEDED

    private_chat_id = int(request.POST["privateChatId"])
    content = request.POST["message"]

    try:
        private_chat = PrivateChat.objects.get(id=private_chat_id)
    except Exception as e:
        # TODO: log this
        return BaseError.OBJECT_NOT_FOUND

    can_post, error = private_chat.can_post(request.user, content)
    if not can_post:
        # TODO: log this
        return error

    message_instance, json_response = private_chat.create_message_from_request(
        request)

    state = State()
    state.add(private_chat)
    state.add(private_chat.message_thread)
    state.add(message_instance)

    private_chat.user_posted(request.user, message_instance)

    private_chat.publish_event("privateMessage", {},
                               extra={
                                   "messageId": message_instance.id,
                                   "privateChatId": private_chat.id,
                                   "state": state
                               },
                               stream_names=private_chat.get_user_streams())

    return json_response
Ejemplo n.º 23
0
    def handle(self, *args, **options):
        state = State()
        context_dict = {}
        from collections import OrderedDict
        global_constants = OrderedDict()

        for collector in settings.PUBLIC_STATE_COLLECTORS:
            if isinstance(collector, str):
                collector = import_module_attribute(collector)
            collector(state, global_constants, context_dict)

        global_constants["PUBLIC_STATE"] = state

        context_dict["all_constants"] = mark_safe("\n".join([
            self.serialize_constant(key, value)
            for key, value in global_constants.items()
        ]))
        context_dict["constants"] = global_constants

        for template_path, output_path in settings.PUBLIC_STATE_PATHS:
            self.generate_template(template_path, output_path, context_dict)
Ejemplo n.º 24
0
def index(request):
    return State()
Ejemplo n.º 25
0
def user_state(request):
    state = State()
    state.add_all(TextTranslation.objects.filter(user=request.user))
    return state.to_response(extra={"success": True})
Ejemplo n.º 26
0
def index(request):
    state = State()
    state.add_all(TextTranslation.objects.filter(user=request.user))
    return state
Ejemplo n.º 27
0
def main_forum_view(request):
    main_forum = Forum.objects.get(id=1)
    state = State(request)
    main_forum.add_to_state(state)
    return state.to_response(extra={"forumId": main_forum.id})
Ejemplo n.º 28
0
def forum_state(request):
    forum = Forum.objects.get(id=int(request.POST["forumId"]))
    state = State(request)
    forum.add_to_state(state)
    return state.to_response()