def should_show(self):
        db = current.db
        user_record = utilities.get_user_records([self.user_id], "id", "id",
                                                 True)
        return user_record["atcoder_handle"] == ""


# ==============================================================================
Beispiel #2
0
    def get_data(self):
        cache_value = self.get_from_cache()
        if cache_value:
            return cache_value

        record = utilities.get_user_records([self.user_id], "id", "id", True)
        result = dict(institute=record["institute"],
                      friend_count=self.friend_count)
        self.set_to_cache(result)
        return result
Beispiel #3
0
    def should_show(self):
        db = current.db

        user_record = utilities.get_user_records([self.user_id], "id", "id",
                                                 True)
        if user_record.institute == "Other":
            # Don't show the card if the user's institute is Other
            return False

        self.friend_count = db(
            db.following.follower_id == self.user_id).count()
        return self.friend_count <= 3
Beispiel #4
0
 def should_show(self):
     cache_value = self.get_from_cache()
     if cache_value:
         self.handle_count = cache_value
     else:
         handle_count = 0
         db = current.db
         record = utilities.get_user_records([self.user_id], "id", "id",
                                             True)
         for site in current.SITES:
             if record[site.lower() + "_handle"]:
                 handle_count += 1
         self.handle_count = handle_count
         self.set_to_cache(self.handle_count)
     return self.handle_count < 3
Beispiel #5
0
def handle_details():
    atable = db.auth_user
    cftable = db.custom_friend
    ihtable = db.invalid_handle
    handle = request.vars.handle

    row = utilities.get_user_records([handle], "stopstalk_handle",
                                     "stopstalk_handle", True)
    if row is None:
        row = db(cftable.stopstalk_handle == handle).select().first()
        if row is None:
            # Invalid handle in the get params
            return dict()

    redis_cache_key = "handle_details_" + row.stopstalk_handle

    # Check if data is present in REDIS
    data = current.REDIS_CLIENT.get(redis_cache_key)
    if data:
        return data

    query = False
    for site in current.SITES:
        query |= ((ihtable.site == site) & \
                  (ihtable.handle == row[site.lower() + "_handle"]))
    ihandles = db(query).select()
    invalid_sites = set([])
    for record in ihandles:
        # For case sensitive check of handles
        if record.handle == row[record.site.lower() + "_handle"]:
            invalid_sites.add(record.site)

    response = {}
    for site in current.SITES:
        smallsite = site.lower()
        # 1. Pending submission retrieval
        if str(row[smallsite + "_lr"]) == current.INITIAL_DATE:
            response[smallsite] = "pending-retrieval"
        # 2. Check for invalid handles
        if site in invalid_sites:
            response[smallsite] = "invalid-handle"
        # 3. Check for empty handles
        if row[smallsite + "_handle"] == "":
            response[smallsite] = "not-provided"

    result = json.dumps(response, separators=JSON_DUMP_SEPARATORS)
    current.REDIS_CLIENT.set(redis_cache_key, result, ex=24 * 60 * 60)
    return result
Beispiel #6
0
    def get_html(self):
        submissions_data = self.get_data()

        card_content_table = TABLE(_class="bordered highlight")
        tbody = TBODY()

        for row in submissions_data:
            user_record = utilities.get_user_records([row[0]], "id", "id",
                                                     True)
            tr = TR(
                TD(
                    A(user_record.first_name + " " + user_record.last_name,
                      _href=URL("user",
                                "profile",
                                args=user_record.stopstalk_handle,
                                extension=False),
                      _target="_blank")))

            td = TD()
            for site in row[1]:
                if site == "total":
                    continue
                else:
                    td.append(
                        SPAN(IMG(_src=current.get_static_url(
                            "images/%s_small.png" % str(site).lower()),
                                 _class="parent-site-icon-very-small"),
                             " " + str(row[1][site]),
                             _style="padding-right: 10px;"))
            tr.append(td)
            tbody.append(tr)

        card_content_table.append(tbody)

        card_html = BaseCard.get_html(
            self,
            **dict(card_title=self.card_title,
                   card_content=card_content_table,
                   cta_links=self.get_cta_html(),
                   card_color_class="white",
                   card_text_color_class="black-text"))
        return card_html
Beispiel #7
0
def update_details():
    """
        Update user details
    """

    form_fields = [
        "first_name", "last_name", "email", "institute", "country",
        "stopstalk_handle"
    ]

    for site in current.SITES:
        form_fields.append(site.lower() + "_handle")

    atable = db.auth_user
    stable = db.submission
    record = utilities.get_user_records([session.user_id], "id", "id", True)

    for field in form_fields:
        if record[field] is None:
            continue
        record[field] = record[field].encode("utf-8")

    # Do not allow to modify stopstalk_handle and email
    atable.stopstalk_handle.writable = False
    atable.stopstalk_handle.comment = T("StopStalk handle cannot be updated")

    atable.email.readable = True
    atable.email.writable = False
    atable.email.comment = T("Email cannot be updated")

    form = SQLFORM(db.auth_user, record, fields=form_fields, showid=False)

    if form.process(onvalidation=current.sanitize_fields).accepted:
        current.REDIS_CLIENT.delete(
            utilities.get_user_record_cache_key(session.user_id))
        session.flash = T("User details updated")

        updated_sites = utilities.handles_updated(record, form)
        if updated_sites != []:
            utilities.clear_profile_page_cache(record.stopstalk_handle)
            site_lrs = {}
            nrtable = db.next_retrieval
            submission_query = (stable.user_id == session.user_id)
            nrtable_record = db(
                nrtable.user_id == session.user_id).select().first()
            if nrtable_record is None:
                nid = nrtable.insert(user_id=session.user_id)
                nrtable_record = nrtable(nid)
            for site in updated_sites:
                site_lrs[site.lower() + "_lr"] = current.INITIAL_DATE
                nrtable_record.update({site.lower() + "_delay": 0})

            nrtable_record.update_record()

            pickle_file_path = "./applications/stopstalk/graph_data/" + \
                               str(session.user_id) + ".pickle"
            import os
            if os.path.exists(pickle_file_path):
                os.remove(pickle_file_path)

            # Reset the user only if any of the profile site handle is updated
            query = (atable.id == session.user_id)
            db(query).update(stopstalk_rating=0,
                             stopstalk_prev_rating=0,
                             per_day=0.0,
                             per_day_change="0.0",
                             authentic=False,
                             graph_data_retrieved=False,
                             **site_lrs)

            submission_query &= (stable.site.belongs(updated_sites))
            # Only delete the submission of those particular sites
            # whose site handles are updated
            db(submission_query).delete()

        session.auth.user = db.auth_user(session.user_id)
        current.REDIS_CLIENT.delete(
            CARD_CACHE_REDIS_KEYS["more_accounts_prefix"] +
            str(session.user_id))
        redirect(URL("default", "index"))
    elif form.errors:
        response.flash = T("Form has errors")

    return dict(form=form)
Beispiel #8
0
def get_friend_list():
    """
        Gets the friend list of a specific user and compares with the friend
        list of the logged in user.
    """

    profile_user_id = int(request.vars["user_id"])
    user_friends, _ = utilities.get_friends(session.user_id)
    profile_friends, _ = utilities.get_friends(profile_user_id)

    if not profile_friends:
        return dict(table='No friends added yet.')

    atable = db.auth_user
    cftable = db.custom_friend

    table = TABLE(_class="bordered centered")
    tbody = TBODY()

    user_records = utilities.get_user_records(profile_friends, "id", "id",
                                              False)

    for friend_id in profile_friends:
        row = user_records[friend_id]

        friend_name = " ".join(
            [row.first_name.capitalize(),
             row.last_name.capitalize()])
        profile_url = URL("user",
                          "profile",
                          args=[row.stopstalk_handle],
                          extension=False)

        if friend_id == session.user_id:
            tr = TR(TD(
                A(friend_name + " (You)", _href=profile_url,
                  _target="_blank")),
                    TD(),
                    _style="height: 87px")
            tbody.append(tr)
            continue

        friend_button_data = {
            "user-id": str(friend_id),
            "position": "left",
            "delay": "100"
        }

        if friend_id in user_friends:
            button_color, fa_icon = ("black", "fa-user-times")
            friend_button_data["tooltip"] = T("Unriend")
            friend_button_data["type"] = "unfriend"
        else:
            button_color, fa_icon = ("green", "fa-user-plus")
            friend_button_data["tooltip"] = T("Add Friend")
            friend_button_data["type"] = "add-friend"

        tr = TR(
            TD(A(friend_name, _href=profile_url, _target="_blank")),
            TD(
                BUTTON(
                    I(_class="fa fa-3x " + fa_icon),
                    _class="tooltipped btn-floating btn-large waves-effect " +
                    "waves-light friends-button " + button_color,
                    data=friend_button_data)))
        tbody.append(tr)

    table.append(tbody)

    return dict(table=table)
Beispiel #9
0
def custom_friend():
    """
        Controller to add a Custom Friend
    """

    atable = db.auth_user

    # The total referrals by the logged-in user
    query = (atable.referrer == session.handle) & \
            (atable.registration_key == "")

    # User should not enter his/her own
    # stopstalk handle as referrer handle
    query &= (atable.stopstalk_handle != session.handle)
    total_referrals = db(query).count()

    # Retrieve the total allowed custom users from auth_user table
    row = utilities.get_user_records([session.user_id], "id", "id", True)
    default_allowed = row.allowed_cu
    referrer = 0
    # If a valid referral is applied then award 1 extra CU
    if row.referrer and row.referrer != session.handle:
        query = (atable.stopstalk_handle == row.referrer) & \
                (atable.registration_key == "")
        referrer = db(query).count()

    # 3 custom friends allowed plus one for each 3 invites
    allowed_custom_friends = total_referrals / 3 + default_allowed + referrer

    # Custom users already created
    rows = db(db.custom_friend.user_id == session.user_id).select()

    table = TABLE(_class="bordered centered")
    tr = TR(TH(T("Name")), TH(T("StopStalk Handle")))

    tr.append(TH(T("Update")))
    table.append(THEAD(tr))

    tbody = TBODY()

    for row in rows:
        tr = TR()
        tr.append(
            TD(
                A(row.first_name + " " + row.last_name,
                  _href=URL("user", "profile", args=[row.stopstalk_handle]),
                  _target="_blank")))
        tr.append(TD(row.stopstalk_handle))

        tr.append(
            TD(
                FORM(INPUT(_class="btn yellow",
                           _style="color: black;",
                           _value=T("Update"),
                           _type="submit"),
                     _action=URL("user", "update_friend", args=[row.id]))))
        tbody.append(tr)

    table.append(tbody)
    if len(rows) >= allowed_custom_friends:
        return dict(form=None,
                    table=table,
                    allowed=allowed_custom_friends,
                    total_referrals=total_referrals)

    list_fields = [
        "first_name", "last_name", "institute", "country", "stopstalk_handle"
    ]

    for site in current.SITES:
        list_fields += [site.lower() + "_handle"]

    form = SQLFORM(db.custom_friend,
                   fields=list_fields,
                   hidden=dict(user_id=session.user_id))

    # Set the hidden field
    form.vars.user_id = session.user_id
    form.process(onvalidation=[
        current.sanitize_fields, utilities.prepend_custom_identifier
    ])

    if form.accepted:
        session.flash = T("Submissions will be added in some time")
        current.create_next_retrieval_record(form.vars, custom=True)
        redirect(URL("default", "dashboard"))

    return dict(form=form,
                table=table,
                allowed=allowed_custom_friends,
                total_referrals=total_referrals)
Beispiel #10
0
def submissions():
    """
        Retrieve submissions of a specific user
    """

    custom = False
    atable = db.auth_user
    cftable = db.custom_friend
    handle = None
    duplicates = []
    row = None

    if len(request.args) < 1:
        if auth.is_logged_in():
            user_id = session.user_id
            handle = session.handle
        else:
            redirect(URL("default", "index"))
    else:
        handle = request.args[0]
        row = utilities.get_user_records([handle], "stopstalk_handle",
                                         "stopstalk_handle", True)
        if row is None:
            query = (cftable.stopstalk_handle == handle)
            row = db(query).select().first()
            if row:
                custom = True
                user_id = row.id
                if row.duplicate_cu:
                    duplicates = [(row.id, row.duplicate_cu)]
                    user_id = row.duplicate_cu.id
            else:
                raise HTTP(404)
                return
        else:
            user_id = row.id

    if request.vars.page:
        page = request.vars.page
    else:
        page = "1"

    if int(page) > current.USER_PAGINATION_LIMIT and not auth.is_logged_in():
        session.flash = T("Please enter a valid page")
        redirect(URL("default", "index"))
        return

    stable = db.submission

    query = (stable.user_id == user_id)
    if custom:
        query = (stable.custom_user_id == user_id)

    PER_PAGE = current.PER_PAGE

    if request.extension == "json":
        total_submissions = db(query).count()
        if not auth.is_logged_in() and \
           total_submissions > current.USER_PAGINATION_LIMIT * PER_PAGE:
            total_submissions = current.USER_PAGINATION_LIMIT * PER_PAGE
        else:
            # User is logged in or total_submissions are less than our public
            # view limit of submissions
            pass
        page_count = total_submissions / PER_PAGE

        if total_submissions % PER_PAGE:
            page_count += 1

        return dict(page_count=page_count)

    offset = PER_PAGE * (int(page) - 1)
    all_submissions = db(query).select(orderby=~stable.time_stamp,
                                       limitby=(offset, offset + PER_PAGE))
    table = utilities.render_table(all_submissions, duplicates,
                                   session.user_id)

    if handle == session.handle:
        user = "******"
    else:
        user = row["first_name"]

    return dict(handle=handle,
                user=user,
                table=table,
                total_rows=len(all_submissions))