Exemplo n.º 1
0
def get_top_complaints(category, sinceid, slug_city):
    """

    Arguments:
    - `category`:
    - `slug_city`:
    """
    items = filter_with_category_and_city(
        category, slug_city, sorting_option="upvote_count"
    )
    l = []
    for item in items:
        comments = item.pop("comments")
        item["comments_count"] = len(comments)
        item = serialize_complaint(item)
        item["user"] = db.users.find_one({"_id": item["user"]})
        item["user"] = serialize_user(item["user"])
        l.append(item)

    if sinceid == "":
        l = (l[:12], 200)
    else:
        l = get_sinceid(sinceid, l)

    return l
Exemplo n.º 2
0
def get_near_complaints(lati, longi, category, sinceid, slug_city):
    """

    Arguments:
    - `category`:
    - `slug_city`:
    - `sinceid`:
    """
    l = []
    if category is "":
        category = "all"

    loc = [float(lati), float(longi)]
    if category is not 'all':
        items = db.complaint.find({"category": category,
                                   "location": {"$near": loc}})
    else:
        items = db.complaint.find({"location": {"$near": loc}})

    items = items[:50]      # limit 10 item

    for item in items:
        comments = item.pop("comments")
        item["comments_count"] = len(comments)
        item = serialize_complaint(item)
        item["user"] = db.users.find_one({"_id": item["user"]})
        item["user"] = serialize_user(item["user"])
        l.append(item)

    if sinceid == "":
        l = (l[:12], 200)
    else:
        l = get_sinceid(sinceid, l)

    return l
Exemplo n.º 3
0
    def get(self):
        users = db.users.find()
        serialized_users = []
        for user in users:
            temp_user = serialize_user(user)
            serialized_users.append(temp_user)

        return serialized_users, 200
Exemplo n.º 4
0
def register_user(session, email, password, first_name, last_name):
    """

    Arguments:
    - `session`:
    - `email`:
    - `password`:
    - `first_name`:
    - `last_name`:
    """

    name = first_name + " " + last_name
    password = bcrypt.hashpw(password, bcrypt.gensalt())

    default = "http://enforceapp.com/static/img/enforce-avatar-big.png"
    size = 75
    gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"

    gravatar_url += urllib.urlencode({"d": default, "s": str(size)})

    meta = db.metadata.find_one()
    user_count = int(meta["user_count"])
    user_count = str(user_count + 1)
    user_slug = make_slug(name) + "-" + user_count

    user = {
        "email": email,
        "first_name": first_name,
        "last_name": last_name,
        "avatar": gravatar_url,
        "name": name,
        "complaints": [],
        "upvotes": [],
        "downvotes": [],
        "password": password,
        "user_type": "member",
        "user_slug": user_slug,
        "fb": 0,
        "register_date": datetime.now(),
    }

    if not (email or password):
        return {"error": "email or password is not given"}, 404
    else:
        if check_mail(email):

            db.users.insert(user)
            user = cleanup_user_for_session(user)

            session["user"] = user
            session["logged_in"] = True
            user = serialize_user(user)

            db.metadata.update({"type": "statistics"}, {"$inc": {"user_count": 1}})

            return user, 201
        else:
            return {"error": "email address is not valid"}, 404
Exemplo n.º 5
0
def get_complaint_with_id(obj_id):
    """

    Arguments:
    - `obj_id`:
    """
    obj_id = ObjectId(unicode(obj_id))
    obj = db.complaint.find_one({"_id": obj_id})

    if not obj:
        return {"error": "object id not found"}, 404

    obj = serialize_complaint(obj)
    obj["user"] = db.users.find_one({"_id": obj["user"]})
    obj["user"] = serialize_user(obj["user"])

    for comment in obj["comments"]:
        comment["author"] = db.users.find_one({
            "_id": ObjectId(comment["author"])
        })
        comment["author"] = serialize_user(comment["author"])

    return obj, 200
Exemplo n.º 6
0
def get_complaint_with_slug(city, slug):
    """

    Arguments:
    - `city`:
    - `slug`:
    """
    path = "/" + city + "/" + slug
    obj = db.complaint.find_one({"slug_url": path})

    if not obj:
        return {"error": "city/slug combination not found"}, 404

    obj = serialize_complaint(obj)
    obj["user"] = db.users.find_one({"_id": obj["user"]})
    obj["user"] = serialize_user(obj["user"])

    for comment in obj["comments"]:
        comment["author"] = db.users.find_one({
            "_id": ObjectId(comment["author"])
        })
        comment["author"] = serialize_user(comment["author"])

    return obj, 200
Exemplo n.º 7
0
def update_user_city(session, user, current_city):
    """

    Arguments:
    - `session`:
    - `user`:
    - `city`:
    """
    userid = user["_id"]
    db.users.update({"_id": ObjectId(userid)}, {"$set": {"current_city": current_city}})
    user = db.users.find_one({"_id": ObjectId(userid)})
    user = cleanup_user_for_session(user)
    session["user"] = user
    session["logged_in"] = True
    user = serialize_user(user)
    return user, 202
Exemplo n.º 8
0
def get_all_complaints(category, slug_city):
    """

    Arguments:
    - `category`:
    - `slug_city`:
    """
    items = filter_with_category_and_city(category, slug_city)
    l = []
    for item in items:
        item["comments_count"] = len(item["comments"])
        item = serialize_complaint(item)
        item["user"] = db.users.find_one({"_id": item["user"]})
        item["user"] = serialize_user(item["user"])
        l.append(item)

    return l
Exemplo n.º 9
0
def update_profile_info(session, user, twitter, website):
    """

    Arguments:
    - `session`:
    - `user`:
    - `twitter`:
    - `website`:
    """
    userid = user["_id"]

    db.users.update({"_id": ObjectId(userid)}, {"$set": {"twitter": twitter, "website": website}})

    user = db.users.find_one({"_id": ObjectId(userid)})
    user = cleanup_user_for_session(user)
    session["user"] = user
    session["logged_in"] = True
    user = serialize_user(user)
    return user, 200
Exemplo n.º 10
0
def put_new_comment(session, complaint_id, text):
    """

    Arguments:
    - `session`:
    - `complaint_id`:
    - `text`:
    """
    user = session.get("user")

    obj_id = ObjectId(unicode(complaint_id))
    complaint_obj = db.complaint.find_one({"_id": obj_id})
    if not complaint_obj:
        return {'error': 'complaint not found'}, 404

    comment_data = {}
    comment_data["_id"] = ObjectId()
    comment_data["date"] = datetime.now()
    comment_data["author"] = user["_id"]
    comment_data["text"] = text
    comment_data["like"] = 0
    comment_data["dislike"] = 0

    db.complaint.update(
        {"_id": obj_id},
        {"$addToSet": {"comments": comment_data}}
    )

    db.metadata.update(
        {"type": "statistics"},
        {"$inc": {"comment_count": 1}}
    )

    comment_data["date"] = str(comment_data["date"])
    comment_data["_id"] = str(comment_data["_id"])
    comment_data["author"] = db.users.find_one(
        {"_id": ObjectId(comment_data["author"])}
    )
    comment_data["author"] = serialize_user(comment_data["author"])

    return comment_data, 201
Exemplo n.º 11
0
def login_user(session, email, password, client, android_id="", apple_id="", current_city=""):
    """

    Arguments:
    - `email`:
    - `password`:
    - `android_id`:
    - `apple_id`:
    - `session`:
    """

    user = db.users.find_one({"email": email})

    if not user:
        return {"error": "wrong password/email combination"}, 401

    pwd_hash = user["password"]
    if bcrypt.hashpw(password, pwd_hash) != pwd_hash:
        return {"error": "wrong password/email combination"}, 401
    else:
        if android_id:
            db.users.update({"_id": user["_id"]}, {"$addToSet": {"devices": {"android": android_id}}})
        elif apple_id:
            db.users.update({"_id": user["_id"]}, {"$addToSet": {"devices": {"apple": apple_id}}})

        if current_city:
            db.users.update({"_id": user["_id"]}, {"$set": {"current_city": current_city}})

        if client:
            db.users.update({"_id": user["_id"]}, {"$set": {"client": client}})

        user = db.users.find_one({"email": email})

        user = cleanup_user_for_session(user)
        session["user"] = user
        session["logged_in"] = True
        user = serialize_user(user)

        return user, 200
Exemplo n.º 12
0
def get_user_with_slug(slug):
    """

    Arguments:
    - `slug`:
    """
    user = db.users.find_one({"user_slug": slug})
    if not user:
        return {"error": "user not found with that slug"}, 404

    user = serialize_user(user)
    cmps = []
    for complaint in user["complaints"]:
        temp_cmp = db.complaint.find_one({"_id": ObjectId(complaint)})
        if temp_cmp:
            temp_cmp.pop("user")
            comments = temp_cmp.pop("comments")
            temp_cmp["comments_count"] = len(comments)
            temp_cmp = serialize_complaint(temp_cmp)
            cmps.append(temp_cmp)
    user["complaints"] = cmps
    user["complaints"] = sorted(user["complaints"], key=lambda k: k["date"], reverse=True)

    upvts = []
    for upvote in user["upvotes"]:
        temp_upvote = db.complaint.find_one({"_id": ObjectId(upvote)})
        if temp_upvote:
            temp_upvote.pop("user")
            comments = temp_upvote.pop("comments")
            temp_upvote["comments_count"] = len(comments)
            temp_upvote = serialize_complaint(temp_upvote)
            upvts.append(temp_upvote)
    user["upvotes"] = upvts
    user["upvotes"] = sorted(user["upvotes"], key=lambda k: k["date"], reverse=True)

    return user, 200
Exemplo n.º 13
0
def get_comments_from_complaint(complaint_id):
    """

    Arguments:
    - `complaint_id`:
    """
    complaint_obj = db.complaint.find_one({"_id": complaint_id})
    if not complaint_obj:
        return {'error': 'complaint not found'}, 404

    comments = []

    for comment in complaint_obj["comments"]:
        try:
            comment["date"] = str(comment["date"])
            comment["_id"] = str(comment["_id"])
            comment["author"] = db.users.find_one(
                {"_id": ObjectId(comment["author"])}
            )
            comment["author"] = serialize_user(comment["author"])
            comments.append(comment)
        except:
            pass
    return comments, 200
Exemplo n.º 14
0
def get_hot_complaints(category, sinceid, slug_city):
    """

    Arguments:
    - `session`:
    - `category`:
    - `sinceid`:
    - `city`:
    """
    current_time = datetime.now()
    l = []

    items = filter_with_category_and_city(category, slug_city)
    items = items[:50]      # limit 50 before sorting with scores
    for item in items:
        complaint_time = item["date"]
        delta = (current_time - complaint_time).days

        uc = item["upvote_count"]
        dc = item["downvote_count"]

        if delta == 0:
            item["score"] = 7 * (uc - dc)
            item["score"] += 2 * len(item["comments"])
        elif delta == 1:
            item["score"] = 6 * (uc - dc)
            item["score"] += len(item["comments"])
        elif delta == 2:
            item["score"] = 5 * (uc - dc)
            item["score"] += len(item["comments"])
        elif delta == 3:
            item["score"] = 4 * (uc - dc)
            item["score"] += len(item["comments"])
        elif delta > 3 and delta <= 15:
            item["score"] = (uc - dc)
            item["score"] += len(item["comments"])
        elif delta > 15 and delta <= 30:
            item["score"] = 0.8 * (uc - dc)
        elif delta > 30 and delta <= 60:
            item["score"] = 0.4 * (uc - dc)
        elif delta > 60 and delta <= 120:
            item["score"] = 0.2 * (uc - dc)
        else:
            item["score"] = 0.1 * (uc - dc)

        if int(item["downvote_count"]) >= int(item["upvote_count"]):
            item["score"] = 0

        comments = item.pop("comments")
        item["comments_count"] = len(comments)
        item = serialize_complaint(item)
        item["user"] = db.users.find_one({"_id": item["user"]})
        item["user"] = serialize_user(item["user"])
        l.append(item)

    sorted_l = sorted(l, key=lambda x: x["score"], reverse=True)

    if sinceid == "":
        sorted_l = (sorted_l[:12], 200)
    else:
        sorted_l = get_sinceid(sinceid, sorted_l)

    return sorted_l
Exemplo n.º 15
0
def post_new_complaint(session, location, title, pic_arr, category):
    """

    Arguments:
    - `session`:
    - `location`:
    - `title`:
    - `pic_arr`:
    - `category`:
    """
    user = session.get("user")
    address_info = get_city_and_address(location)
    city = address_info[0]
    address = address_info[1]

    slug_city = make_slug(city)
    slug_title = make_slug(title)

    number = db.metadata.find_one({"type": "statistics"})
    number = int(number["complaint_count"])
    number += 1

    slug_url = "/" + slug_city + "/" + slug_title + "-" + str(number)
    public_url = "/" + slug_city + "/" + slug_title + "-" + str(number)

    filename = byte_array_to_file(
        pic_arr, slug_city,
        slug_title + "-" + str(number)
    )

    new_complaint = {
        "_id": ObjectId(),
        "title": title,
        "user": ObjectId(user["_id"]),
        "pics": [filename],
        "slug_city": slug_city,
        "slug_url": slug_url,
        "public_url": public_url,
        "category": category,
        "comments": [],
        "upvoters": [ObjectId(user["_id"])],
        "downvoters": [],
        "upvote_count": 1,
        "downvote_count": 0,
        "location": location,
        "address": address,
        "city": city,
        "date": datetime.now()
    }

    user = session.get("user")
    db.complaint.insert(new_complaint)

    new_complaint = serialize_complaint(new_complaint)
    new_complaint["user"] = serialize_user(user)
    new_complaint["comments_count"] = 0

    db.metadata.update(
        {"type": "statistics"},
        {"$inc": {"complaint_count": 1}}
    )

    db.users.update(
        {"_id": ObjectId(user["_id"])},
        {
            "$addToSet": {
                "complaints": ObjectId(new_complaint["_id"]),
                "upvotes": ObjectId(new_complaint["_id"])
            }
        }
    )

    return new_complaint, 201
Exemplo n.º 16
0
def downvote_complaint(session, obj_id):
    """

    Arguments:
    - `session`:
    - `obj_id`:
    """

    obj_id = ObjectId(unicode(obj_id))
    obj = db.complaint.find_one({"_id": obj_id})
    if not obj:
        return {"error": "object id not found"}, 404

    upvoters = obj["upvoters"]
    downvoters = obj["downvoters"]

    user = session["user"]
    if not user:
        return {"error": "user not found in session"}, 404
    user_id = ObjectId(user["_id"])

    if user_id in upvoters:
        return {"error": "user upvoted this. can't downvote."}, 406
    elif user_id in downvoters:
        # remove users upvote
        db.complaint.update(
            {"_id": obj_id},
            {"$pull": {"downvoters": user_id}}
        )

        db.complaint.update(
            {"_id": obj_id}, {"$inc": {"downvote_count": -1}}
        )

        db.users.update(
            {"_id": user_id},
            {"$pull": {"downvotes": obj_id}}
        )

        obj = db.complaint.find_one({"_id": obj_id})
        comments = obj.pop("comments")
        obj["comments_count"] = len(comments)
        obj = serialize_complaint(obj)
        obj["user"] = db.users.find_one({"_id": obj["user"]})
        obj["user"] = serialize_user(obj["user"])
        return obj, 202

    db.complaint.update(
        {"_id": obj_id},
        {"$addToSet": {"downvoters": user_id}}
    )

    db.complaint.update(
        {"_id": obj_id}, {"$inc": {"downvote_count": 1}}
    )

    db.users.update(
        {"_id": user_id},
        {"$addToSet": {"downvotes": obj_id}}
    )

    obj = db.complaint.find_one({"_id": obj_id})
    comments = obj.pop("comments")
    obj["comments_count"] = len(comments)
    obj = serialize_complaint(obj)
    obj["user"] = db.users.find_one({"_id": obj["user"]})
    obj["user"] = serialize_user(obj["user"])
    return obj, 202
Exemplo n.º 17
0
def login_user_with_facebook(session, email, access_token, android_id="", apple_id="", current_city=""):
    """

    Arguments:
    - `session`:
    - `email`:
    - `access_token`:
    """
    url = "https://graph.facebook.com/me?access_token=" + access_token
    r = requests.get(url)
    if r.status_code != 200:
        return {"error": "access token is not valid"}, 401
    else:
        user = db.users.find_one({"email": email})

        if not user:
            json_data = r.json()

            if "username" in json_data:
                username = json_data["username"]
            else:
                username = json_data["id"]

            if "email" in json_data:
                email = json_data["email"]
            else:
                email = username + "@facebook.com"

            avatar_url = "https://graph.facebook.com/"
            avatar_url += username
            avatar_url += "/picture?type=square&width=75&height=75"

            meta = db.metadata.find_one()
            user_count = int(meta["user_count"])
            user_count = str(user_count + 1)
            user_slug = make_slug(json_data["name"]) + "-" + user_count

            try:
                db.users.insert(
                    {
                        "email": email,
                        "first_name": json_data["first_name"],
                        "last_name": json_data["last_name"],
                        "name": json_data["name"],
                        "devices": [],
                        "current_city": "",
                        "complaints": [],
                        "upvotes": [],
                        "downvotes": [],
                        "fbusername": username,
                        "avatar": avatar_url,
                        "user_type": "member",
                        "user_slug": user_slug,
                        "fb": 1,
                        "register_date": datetime.now(),
                    }
                )

                db.metadata.update({"type": "statistics"}, {"$inc": {"user_count": 1}})

                user = db.users.find_one({"email": email})
                user = cleanup_user_for_session(user)
                session["user"] = user
                session["logged_in"] = True
                user = serialize_user(user)
                return user, 200
            except:
                return {"error": "cont login with facebook"}, 400
        else:
            json_data = r.json()

            if user["fb"] == 0:
                if "username" in json_data:
                    username = json_data["username"]
                else:
                    username = json_data["id"]

                user["fbusername"] = username
                user["fb"] = 1
                db.users.save(user)

            if android_id:
                db.users.update({"_id": user["_id"]}, {"$addToSet": {"devices": {"android": android_id}}})
            elif apple_id:
                db.users.update({"_id": user["_id"]}, {"$addToSet": {"devices": {"apple": apple_id}}})

            if current_city:
                db.users.update({"_id": user["_id"]}, {"$set": {"current_city": current_city}})

            user = db.users.find_one({"email": email})

            user = cleanup_user_for_session(user)
            session["user"] = user
            session["logged_in"] = True
            user = serialize_user(user)
            return user, 200