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})
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, })
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})
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})
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
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()
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})
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()
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()
def get_translations(request, article_id): article = Article.objects.get(id=article_id) if not request.user.is_superuser and article.author_created_id != request.user.id: return BaseError.NOT_ALLOWED translations = Article.objects.filter(base_article_id=article.id) return State.from_objects(translations, TermDefinition.objects.all())
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
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})
def set_article_owner(request, article_id): article = Article.objects.get(id=article_id) new_owner_id = int(request.POST["newOwner"]) article.author_created_id = new_owner_id article.save() return State.from_objects(article)
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
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
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
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})
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
def create_entry(request): if int(request.POST["articleId"]) != 0: article = Article.objects.get(id=int(request.POST["articleId"])) else: article = Article(author_created=request.user, name=request.POST["name"]) article.save() entry = DocumentationEntry.objects.create(parent_id=int(request.POST["parentId"]), name=request.POST["name"], url_name=request.POST["urlName"], parent_index=int(request.POST["parentIndex"]), article=article) entry.save() return State.from_objects(entry, entry.article)
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
def edit_translation(request): key_info = None if "editEntries" in request.POST.keys(): decoder = json.JSONDecoder() entries = decoder.decode(request.POST["editEntries"]) error = check_translation_entries(entries) if error is not None: return error edit_translation_entries(entries) elif "editKeys" in request.POST.keys(): decoder = json.JSONDecoder() change = decoder.decode(request.POST["editKeys"]) if change["type"] == "add": keys = [x.strip() for x in change["keys"].splitlines()] for key_value in keys: if not key_value: return LocalizationError.ONE_INVALID_TRANSLATION_KEY count_added = 0 for key_value in keys: if TranslationKey.objects.get_or_create(value=key_value)[1]: count_added += 1 key_info = { "added": count_added, "alreadyExists": len(keys) - count_added } elif change["type"] == "delete": key_id = int(change["keyId"]) key = TranslationKey.objects.get(id=key_id) if not key: return LocalizationError.TRANSLATION_KEY_NOT_FOUND key.delete() elif change["type"] == "rename": key_id = int(change["keyId"]) new_value = change["newValue"] key = TranslationKey.objects.get(id=key_id) if not key: return LocalizationError.TRANSLATION_KEY_NOT_FOUND if not new_value: return LocalizationError.INVALID_TRANSLATION_VALUE key.value = new_value key.save() return State.from_objects(TranslationEntry.objects.all(), TranslationKey.objects.all()).to_response({ "succes": True, "keyInfo": key_info })
def edit_entry(request): entry = DocumentationEntry.objects.get(id=request.POST["entryId"]) if int(request.POST["articleId"]) != 0: article = Article.objects.get(id=int(request.POST["articleId"])) else: article = Article(author_created=request.user, name=request.POST["name"]) article.save() entry.name = request.POST["name"] entry.url_name = request.POST["urlName"] entry.parent_index = int(request.POST["parentIndex"]) entry.article = article entry.save() return State.from_objects(entry, entry.article)
def create_message_from_request(self, request, stream_names=None): user = request.user content = request.POST["message"] virtual_id = request.POST.get("virtualId", None) if virtual_id and len(virtual_id) > 128: return None, ChatError.INVALID_MESSAGE_CONTENT message = self.create_message(user, content, virtual_id=virtual_id, stream_names=stream_names) return message, State.from_objects(message).to_response( extra={"messageId": message.id})
def edit_profile(request): save_user = False if "firstName" in request.POST and request.user.first_name != request.POST[ "firstName"]: request.user.first_name = request.POST["firstName"] save_user = True if "lastName" in request.POST and request.user.last_name != request.POST[ "lastName"]: request.user.last_name = request.POST["lastName"] save_user = True if "userName" in request.POST and request.user.username != request.POST[ "userName"]: request.user.username = request.POST["userName"] save_user = True if "displayName" in request.POST and request.user.display_name != request.POST[ "displayName"]: request.user.display_name = json.loads(request.POST["displayName"]) save_user = True if "receivesEmailAnnouncements" in request.POST: receives_email_announcements = json.loads( request.POST["receivesEmailAnnouncements"]) if request.user.receives_email_announcements != receives_email_announcements: request.user.receives_email_announcements = receives_email_announcements save_user = True if "customSettingsKey" in request.POST: # TODO: add ability to save multiple ones in the same request request.user.set_custom_setting(request.POST["customSettingsKey"], request.POST["customSettingsValue"]) if "localeLanguageId" in request.POST: request.user.locale_language_id = int(request.POST["localeLanguageId"]) save_user = True if save_user: try: request.user.full_clean() request.user.save() except ValidationError as e: return {"error": e.message_dict} request.user.publish_event("profileChanged", request.user) return State.from_objects([UserSummary(request.user) ]).to_response(extra={"success": True})
def public_user_profiles(request): if "usernamePrefix" in request.GET: username_prefix = request.GET["usernamePrefix"] precise_user = get_user_manager().filter( username__iexact=username_prefix) prefix_users = get_user_manager().filter( username__istartswith=username_prefix)[:10] users = list(precise_user) + list(prefix_users) else: user_ids = int_list(request.GET.getlist("ids[]")) if len(user_ids) > 512: # TODO: log this, may need to ban someone return AccountsError.TOO_MANY_PROFILES_REQUESTED users = get_user_manager().filter(id__in=user_ids) return State.from_objects(get_public_user_class().wrap_user_list(users))
def questionnaire_submit(request): questionnaire_id = int(request.POST["questionnaireId"]) questionnaire = Questionnaire.objects.get(id=questionnaire_id) if not request.user.is_superuser and not questionnaire.visible: return BaseError.NOT_ALLOWED instance = QuestionnaireInstance.objects.get(user=request.user, questionnaire=questionnaire) # if instance.date_submitted: # return BaseError.NOT_ALLOWED instance.date_submitted = timezone.now() instance.save() return State.from_objects(instance)
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
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
def questionnaire_answer(request): questionnaire_id = int(request.POST["questionnaireId"]) questionnaire = Questionnaire.objects.get(id=questionnaire_id) if not request.user.is_superuser and not questionnaire.visible: return BaseError.NOT_ALLOWED question = QuestionnaireQuestion.objects.get( id=int(request.POST["questionId"])) if question.questionnaire_id != questionnaire.id: return BaseError.NOT_ALLOWED instance = QuestionnaireInstance.objects.get(user=request.user, questionnaire=questionnaire) # if instance.date_submitted: # return BaseError.NOT_ALLOWED question_response, created = QuestionnaireQuestionResponse.objects.get_or_create( instance=instance, question=question) question_response.text = request.POST.get("text", None) if question.type == 2: # Single choice choice_id = request.POST.getlist("choiceIds[]", []) print(choice_id) if len(choice_id): choice_id = choice_id[0] question_choice = QuestionnaireQuestionOption.objects.get( id=choice_id) if question_choice.question_id != question.id: return BaseError.NOT_ALLOWED question_response.choices.set([question_choice]) else: question_response.choices.set([]) if question.type == 3: # Multiple choice choice_ids = request.POST.getlist("choiceIds[]", []) question_choices = QuestionnaireQuestionOption.objects.filter( id__in=choice_ids) if len(question_choices) != len(choice_ids): return BaseError.NOT_ALLOWED for question_choice in question_choices: if question_choice.question_id != question.id: return BaseError.NOT_ALLOWED question_response.choices.set(list(question_choices)) question_response.save() return State.from_objects(question_response)
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