Ejemplo n.º 1
0
def publish_article(request):
    received_data = json.loads(request.body.decode('utf-8'))
    title = received_data['title']
    section = received_data['section']
    content = received_data['content']

    section = Section.objects.get(name=section)
    account = request.user.account

    if (section.creator != account):
        return JsonResponse(
            get_json_dict(err_code=-1, message="No Permission", data={}))

    new_article = Article(
        section=section,
        title=title,
        content=json.dumps(content),
    )
    images = [x["data"] for x in content if x["type"] == "image"]
    while len(images) < 3:
        images.append(None)
    new_article.image1_url = images[0]
    new_article.image2_url = images[1]
    new_article.image3_url = images[2]

    new_article.save()

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 2
0
def apply_for_task(request):

    request_data = json.loads(request.body.decode('utf-8'))

    task = Task.objects.get(id=request_data["task_id"])

    if task.state == "finished":
        return JsonResponse(
            get_json_dict(data={}, err_code=-1, message="报名已截止,不再接受报名"))

    now_time = timezone.now()

    if now_time > task.due_time:
        task.state = "finished"
        task.save()
        return JsonResponse(
            get_json_dict(data={}, err_code=-1, message="报名已截止,不再接受报名"))

    applications = task.applications.filter(applicant=request.user.account)

    if len(applications) > 0:
        return JsonResponse(
            get_json_dict(data={}, err_code=-1, message="你已经报过名了哦"))

    application = Application(
        applicant=request.user.account,
        task=task,
        application_text=request_data["application_text"])

    application.save()

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 3
0
def register(request):

    request_data = json.loads(request.body.decode('utf-8'))
    username = request_data['username']
    password = request_data['password']

    try:
        user = User.objects.get(username=username)
    except ObjectDoesNotExist as e:

        user = User(username=username)
        user.set_password(password)
        user.is_active = False
        user.save()
        account = Account(user=user)
        account.nickname = username
        account.save()
        account_confirm_code = AccountConfirmCode(
            account=account, code=generate_account_confirm_code())
        account_confirm_code.save()
    else:
        if user.is_active:
            return JsonResponse(
                get_json_dict(data={}, err_code=-1, message="您已注册过"))

        user.set_password(password)
        user.save()
        account_confirm_code = user.account.account_confirm_code
        account_confirm_code.code = generate_account_confirm_code()
        account_confirm_code.save()

    send_confirm_code_to_fdu_mailbox(username, account_confirm_code.code)

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 4
0
def feedback(request):
    request.POST = json.loads(request.body.decode('utf-8'))

    #Each feedback should be no longer than 500 letters, or it will be truncated.
    feedback_info = request.POST['feedback'].strip()[:500]
    if len(feedback_info) == 0:
        return JsonResponse(
            get_json_dict(data={}, err_code=-1, message="Empty Feedback"))
    else:
        feedback = Feedback(feedback=feedback_info)
        feedback.save()
        return JsonResponse(
            get_json_dict(data={}, err_code=0, message="Feedback Success"))
Ejemplo n.º 5
0
def change_password(request):
    received_data = json.loads(request.body.decode('utf-8'))
    old_password = received_data['old_password']
    new_password = received_data['new_password']

    user = authenticate(username=request.user.username, password=old_password)
    if user:
        user.set_password(new_password)
        user.save()
        login(request, user)
        return JsonResponse(get_json_dict(data={}))
    else:
        return JsonResponse(
            get_json_dict(err_code=-1, message="Invalid Password", data={}))
Ejemplo n.º 6
0
def get_article_list(request):
    """
    {
      'articles': [ARTICLE, ...]
    }
    """

    ONE_PAGE_SIZE = 10

    section = request.GET.get('section', "")
    page = int(request.GET.get('page', 0))

    json_dict = get_json_dict(data={})
    json_dict['data']['articles'] = []

    if section == "":
        articles = Article.objects.all().order_by(
            '-publish_time')[ONE_PAGE_SIZE * page:ONE_PAGE_SIZE * (page + 1)]
    else:
        articles = Article.objects.filter(section__name=section).order_by(
            '-publish_time')[ONE_PAGE_SIZE * page:ONE_PAGE_SIZE * (page + 1)]

    for article in articles:
        json_dict['data']['articles'].append(get_article_dict(article))

    return JsonResponse(json_dict)
Ejemplo n.º 7
0
def quit_task(request):

    request_data = json.loads(request.body.decode('utf-8'))

    task = Task.objects.get(id=request_data["task_id"])

    applications = task.applications.filter(applicant=request.user.account)

    if len(applications) == 0:
        return JsonResponse(
            get_json_dict(data={}, err_code=-1, message="你还没有申请过"))

    application = applications.first()
    application.delete()

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 8
0
def upload_picture(request):
    """
    post form:
      picture: <image_file>
    response:
      {
        "err_code": 0,
        "message": "Success",
        "data": {
          "picture_url": "/statics/images/<username>/<time>_<md5>"
        }
      }
    """
    picture = request.FILES['picture']
    picture.name = "{timestamp}_{picture_name}".format(
        timestamp = int(round(time.time() * 1000)),
        picture_name = get_md5(picture.read())
    )

    picture_obj = Picture(picture=picture, user=request.user)
    picture_obj.save()

    json_dict = get_json_dict(data={})
    json_dict['data']['picture_url'] = picture_obj.picture.url
    return JsonResponse(json_dict)
Ejemplo n.º 9
0
def get_article_list(request):

    article_id_st = int(request.GET['id'])
    count = int(request.GET.get('count', 100))
    count = min(100, count)

    article_id_en = article_id_st + count

    articles = Article.objects.filter(id__gte=article_id_st, id__lt=article_id_en)

    json_dict = get_json_dict(data={"articles": []})

    for article in articles:
        if not hasattr(article, 'article_text'):
            article_text = ArticleText(article=article, text=__get_article_text(article))
            article_text.save()
        article_dict = {
            'id': article.id,
            'title': article.title,
            'text': article.article_text.text,
            'publish_time': article.publish_time.strftime("%Y-%m-%d %H:%M:%S")
        }
        json_dict['data']['articles'].append(article_dict)

    return JsonResponse(json_dict)
Ejemplo n.º 10
0
 def wrapper(request):
     if request.user.is_authenticated:
         return func(request)
     response = JsonResponse(
         get_json_dict(data={}, err_code=-1, message="Login Required"))
     response.status_code = 403
     return response
Ejemplo n.º 11
0
def get_mind_graph_article_list(request):

    l1_tag = request.GET['label1']
    l2_tag = request.GET['label2']
    l3_tag = request.GET['label3']

    try:
        time = timezone.datetime.strptime(request.GET[time],
                                          "%Y-%m-%d %H:%M:%S")
    except:
        time = timezone.now()

    days_interval = timedelta(days=3)

    articles = Article.objects.filter(article_tags__level1_tag=l1_tag,
                                      article_tags__level2_tag=l2_tag,
                                      article_tags__level3_tag=l3_tag,
                                      publish_time__lt=time,
                                      publish_time__gt=time -
                                      days_interval).order_by('-publish_time')

    json_dict_data = []

    for article in articles:
        json_dict_data.append(get_article_dict(article))

    return JsonResponse(get_json_dict(data={'articles': json_dict_data}))
Ejemplo n.º 12
0
def get_task_list(request):

    PAGE_SIZE = 20

    try:
        page = int(request.GET.get("page", 0))
    except:
        page = 0

    task_type = request.GET.get("task_type", "all")
    task_state = request.GET.get("task_state", "all")
    search_keyword = request.GET.get("search_keyword", "")

    st_task_index = PAGE_SIZE * page
    en_task_index = PAGE_SIZE * (page + 1)
    json_dict_data = {}

    json_dict_data["task_list"] = []

    tasks = Task.objects.all()
    if (task_type != "all"):
        tasks = tasks.filter(type=task_type)
    if (task_state != "all"):
        tasks = tasks.filter(state=task_state)
    if (search_keyword != ""):
        tasks = tasks.filter(title__contains=search_keyword)

    tasks = tasks.order_by("-create_time")[st_task_index:en_task_index]

    for task in tasks:
        json_dict_data["task_list"].append(get_task_dict(task))

    json_dict_data['task_count'] = Task.objects.count()

    return JsonResponse(get_json_dict(data=json_dict_data))
Ejemplo n.º 13
0
def get_comments(request):

    task_id = int(request.GET.get('task_id'))

    page = int(request.GET.get('page', 0))

    PAGE_SIZE = 10

    index_st = PAGE_SIZE * page
    index_en = PAGE_SIZE * (page + 1)

    comments = Comment.objects.filter(task__id=task_id)[index_st:index_en]

    json_dict = get_json_dict(
        data={
            'comments': [],
            'comment_count': Comment.objects.filter(task__id=task_id).count()
        })

    i = index_st

    for comment in comments:

        json_dict['data']['comments'].append(get_comment_dict(comment))
        json_dict['data']['comments'][-1]['index'] = i
        i += 1

    return JsonResponse(json_dict)
Ejemplo n.º 14
0
def get_subscribed_sections(request):
    """
    USER: {
      id: <str>,
      nickname: <str>,
      gender: <str, 'M'/'F'>
    }
    SECTION: {
      name: <str>,
      creator: USER,
      description: <str>
    }
    {
      sections: [SECTION],
    }
    """

    json_dict = get_json_dict(data={})

    user = request.user
    sections = []
    default_sections = ["TechDaily"]
    if (user.is_authenticated):
        account = user.account
        for section in account.subscribed_sections.all():
            sections.append(section)
    if len(sections) == 0:
        for section in default_sections:
            sections.append(Section.objects.get(name=section))

    json_dict['data']['sections'] = []
    for section in sections:
        json_dict['data']['sections'].append(get_section_dict(section))

    return JsonResponse(json_dict)
Ejemplo n.º 15
0
def change_task(request):

    request_data = json.loads(request.body.decode('utf-8'))

    print(request_data)

    task = Task.objects.get(id=request_data["task_id"])

    if task.creator.user.id == request.user.id:

        task.title = request_data["title"]
        task.description = request_data["description"]
        task.requirement = request_data["requirement"]
        task.type = request_data["type"]
        task.due_time = request_data["due_time"]
        task.reward = request_data["reward"]

        task.save()

        now_time = timezone.now()
        task = Task.objects.get(id=task.id)
        if (task.due_time >= now_time):
            task.state = 'active'
        else:
            task.state = 'finished'

        task.save()

    else:
        return JsonResponse(get_permission_denied_json_dict())

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 16
0
def search_for_article(request):

    if settings.DEBUG:
        article_ids = [
            51540, 51541, 51542, 51543, 51544, 51545, 51546, 51547, 51548,
            51549, 51550, 51551, 51552, 51553, 51554, 51555, 51556, 51557,
            51558, 51559
        ]
    else:
        keyword = request.GET['keyword']
        try:
            page = int(request.GET['page'])
        except:
            page = 0

        search_engine = SearchEngine("10.144.5.124", "8983")
        article_ids = search_engine.query(keyword, page)

    json_dict = get_json_dict(data={})
    json_dict['data']['articles'] = []

    for article_id in article_ids:
        try:
            article = Article.objects.get(id=article_id)
            json_dict['data']['articles'].append(get_article_dict(article))
        except:
            pass

    return JsonResponse(json_dict)
Ejemplo n.º 17
0
def user_detail(request):
    account = request.user.account
    json_dict = get_json_dict(data={})

    json_dict['data'] = get_user_private_dict(account)

    return JsonResponse(json_dict)
Ejemplo n.º 18
0
def get_article_content(request):
    article_id = request.GET['id']

    article = Article.objects.get(id=article_id)
    json_dict = get_json_dict(data={})
    json_dict['data']['article'] = get_article_dict(article)

    return JsonResponse(json_dict)
Ejemplo n.º 19
0
def unsubscribe_section(request):
    received_data = json.loads(request.body.decode('utf-8'))
    section = received_data['section']
    section = Section.objects.get(name=section)

    section.subscribers.remove(request.user.account)

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 20
0
def get_score(request):

    account = request.user.account
    json_dict = get_json_dict(data={})
    json_dict["data"]["score"] = account.score
    json_dict["data"]["rank"] = Account.objects.filter(
        score__gt=account.score).count() + 1

    return JsonResponse(json_dict)
Ejemplo n.º 21
0
def get_user_public_detail(request):
    username = request.GET['username']

    account = Account.objects.get(user__username=username)

    json_dict = get_json_dict(data={})
    json_dict['data'] = get_user_public_dict(account)

    return JsonResponse(json_dict)
Ejemplo n.º 22
0
def get_hot_sections(request):
    json_dict = get_json_dict(data={})
    hot_sections = Section.objects.filter()[0:10]  # TODO - fake function

    json_dict['data']['sections'] = []

    for section in hot_sections:
        json_dict['data']['sections'].append(get_section_dict(section))

    return JsonResponse(json_dict)
Ejemplo n.º 23
0
 def get_user_login_success_response(user):
     expires = timezone.now() + timezone.timedelta(days=7)
     jwt_payload = get_user_private_dict(user.account)
     jwt_payload['expires'] = expires.strftime("%Y-%m-%d %H:%M:%S")
     jwt_token = jwt.encode(jwt_payload, PRIVATE_KEY,
                            algorithm="RS256").decode("utf-8")
     response = JsonResponse(
         get_json_dict(data={}, err_code=0, message="Login success"))
     response.set_cookie('jwt', jwt_token, max_age=604800)
     return response
Ejemplo n.º 24
0
def get_created_sections(request):
    json_dict = get_json_dict(data={})
    account = request.user.account

    json_dict['data']['sections'] = []

    for section in account.created_sections:
        json_dict['data']['sections'].append(get_section_dict(section))

    return JsonResponse(json_dict)
Ejemplo n.º 25
0
def get_task(request):

    task_id = request.GET.get("task_id")
    task = Task.objects.get(id=task_id)

    json_dict_data = {"task": get_task_dict(task)}

    json_dict = get_json_dict(data=json_dict_data)

    return JsonResponse(json_dict)
Ejemplo n.º 26
0
def change_detail(request):
    received_data = json.loads(request.body.decode('utf-8'))
    new_nickname = received_data['nickname']
    new_gender = received_data['gender']

    account = request.user.account
    account.nickname = new_nickname
    account.gender = new_gender
    account.save()

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 27
0
def create_new_section(request):
    received_data = json.loads(request.body.decode('utf-8'))
    name = received_data['name']
    description = received_data['description']
    account = request.user.account

    new_section = Section(creator=account, name=name, description=description)
    new_section.save()
    new_section.subscribers.add(account)

    return JsonResponse(get_json_dict(data={}))
Ejemplo n.º 28
0
def change_icon(request):
    picture = request.FILES['picture']

    picture.name = "{timestamp}_{picture_name}".format(
        timestamp=int(round(time.time() * 1000)),
        picture_name=get_md5(picture.read()))

    account = request.user.account
    account.icon = picture
    account.save()

    return JsonResponse(get_json_dict(data={'icon': account.icon.url}))
Ejemplo n.º 29
0
def search_for_sections(request):
    keyword = request.GET['keyword']

    sections = Section.objects.filter(name__contains=keyword)

    json_dict = get_json_dict(data={})
    json_dict['data']['sections'] = []

    for section in sections:
        json_dict['data']['sections'].append(get_section_dict(section))

    return JsonResponse(json_dict)
Ejemplo n.º 30
0
def finish_task(request):

    request_data = json.loads(request.body.decode('utf-8'))

    task = Task.objects.get(id=request_data['task_id'])

    if task.creator.user.id == request.user.id:
        task.state = 'finished'
        task.save()
        return JsonResponse(get_json_dict(data={}))
    else:
        return JsonResponse(get_permission_denied_json_dict())