Exemple #1
0
def new_post():
    title = request.form["title"]
    url = request.form["url"]
    text = request.form["text"]
    time = datetime.datetime.now()
    user = decode_auth_token(request.cookies.get('token'))
    if user is None:
        error = "ERROR: You must be logged to make a new post"
        return redirect("submit?error={0}".format(error))
    elif url != '' and text == '' and title != '' and not Contribution.exists(repository, url):
        contribution = Contribution(title, url, None, time, user, ContributionTypes.NEW.value, 0)
    elif text != '' and url == '' and title != '':
        contribution = Contribution(title, None, text, time, user, ContributionTypes.ASK.value, 0)
    elif text != '' and url != '':
        error = "ERROR: You can only fill URL or Text but not both"
        return redirect("submit?error={0}".format(error))
    elif url != '' and text == '' and Contribution.exists(repository, url):
        contribution_id = Contribution.get_contribution_id_by_URL(repository, url)
        return redirect("contribution?id={0}".format(contribution_id))
    elif text == '' and url == '' and title != '':
        error = "ERROR: You have to fill either URL or Text"
        return redirect("submit?error={0}".format(error))
    else:
        error = "ERROR: You must fill title"
        return redirect("submit?error={0}".format(error))
    contribution.save(repository)
    return redirect('')
Exemple #2
0
def create_new_ask():
    if 'Authorization' not in request.headers:
        return jsonify(''), 401
    username = decode_auth_token(request.headers['Authorization'])
    if username is None:
        return jsonify(''), 401
    json = request.get_json()
    ask = Contribution(title=json['title'], url=None, text=json['text'], time=datetime.datetime.now(),
                       username=username, kind=ContributionTypes.ASK.value)
    ask.save(repository)
    return jsonify(ask.toJSON())
Exemple #3
0
    def make_move(self):
        
        # Collect scores for player's contributions vs. quoter's context and filler

        contrs = Contribution(
                              self.trained_model, 
                              self.quote_context, 
                              self.quote_filler, 
                              self.player_name, 
                              self.data_set
                              )

        return contrs.humourise(contrs.score_contributions())
Exemple #4
0
def delete_contribution_api(contribution_id):
    if 'Authorization' not in request.headers:
        return jsonify('Unauthorized'), 401
    username = decode_auth_token(request.headers['Authorization'])
    if username is None:
        return jsonify('Unauthorized'), 401
    if not Contribution.exists_contribution(repository, contribution_id):
        return jsonify('Not Found'), 404
    contribution = Contribution.get_contribution(repository, contribution_id)
    if contribution.username != username:
        return jsonify('Forbidden'), 403
    Comment.delete_comments_from_contribution(repository, contribution_id)
    Contribution.delete_contribution(repository, contribution_id)
    return jsonify('Successful delete'), 204
Exemple #5
0
def main():
    result = constants.UNREVIEWED.get_all_values()
    vipo = constants.VIPO
    is_vipo = False

    already_voted_on = [
        contribution["url"] for contribution in
        constants.DB_UTEMPIAN.contributions.find({
            "status": "unreviewed",
            "voted_on": True
        })
    ]

    for row in result[1:]:
        contribution = Contribution(row)
        moderator = contribution.moderator
        score = contribution.score

        if ((moderator != "" and score != "")
                or contribution.url in already_voted_on):
            today = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            contribution.review_date = today

            try:
                post = Comment(contribution.url)
            except ContentDoesNotExistsException:
                constants.UNREVIEWED.delete_row(result.index(row) + 1)
                return

            if contribution.url in already_voted_on:
                contribution.moderator = "IGNORE"
                contribution.score = 0
                contribution.weight = 0
                constants.UNREVIEWED.delete_row(result.index(row) + 1)
                move_to_reviewed(contribution, post)
                continue

            if post.author in vipo:
                is_vipo = True

            category = contribution.category.strip()
            contribution.vote_status, contribution.weight = exponential_vote(
                float(score), category, contribution.url, is_vipo)

            if not moderator.upper() in [
                    "BANNED", "IGNORED", "IGNORE", "IRRELEVANT"
            ]:
                contribution.review_status = "Pending"

            constants.LOGGER.info(
                f"Moving {contribution.url} to reviewed sheet with voting % "
                f"{contribution.weight} and score {score}")

            constants.UNREVIEWED.delete_row(result.index(row) + 1)
            move_to_reviewed(contribution, post)

            if float(score) > constants.MINIMUM_SCORE:
                vote_contribution(contribution)
                add_comment(contribution)
            return
Exemple #6
0
def get_contribution():
    contribution_id = request.args.get('id')
    contribution = Contribution.get_contribution(repository, contribution_id)
    comments = Comment.get_comments_by_contribution(repository, contribution_id)
    contribution.n_comments = len(comments)
    username = decode_auth_token(request.cookies.get('token'))
    all_children = []
    comments_voted = []
    if username is not None:
        comments_voted = UserCommentVoted.get_voted(repository, username)
    for comment in comments:
        comment.voted = comment.id in [cv['comment_id'] for cv in comments_voted]
        children = Comment.get_comments_by_parent(repository, comment.id)
        all_children.extend(children)
        comment.children = children
    for child in all_children:
        child.voted = child.id in [cv['comment_id'] for cv in comments_voted]
        # TODO: Falta votar ultim child
    parents_comments = []
    for comment in comments:
        if comment.id not in [c.id for c in all_children]:
            parents_comments.append(comment)
    if username is not None:
        user = User.get(repository, username)
        contributions_voted = UserContributionVoted.get_voted(repository, username)
        voted = contribution.id in [cv['contribution_id'] for cv in contributions_voted]
        return render_template('contribution.html', contribution=contribution, comments=parents_comments, user=user,
                               voted=voted)
    return render_template('contribution.html', contribution=contribution, comments=parents_comments)
Exemple #7
0
def detect_all(contribname, sha, rules):
  print "Detecting for commit " + colored(sha, 'magenta')
  cachedir = '.'
  contributionso = {}
  features = set([])
  c = Contribution(contribname, loadfeatures=True, commitsha=sha, rules=rules)
  features.update(set(c.features.keys()))
  contributionso[c.rtitle] = {'features' : c.features}
  return contributionso
Exemple #8
0
 def all(cls):
     u2 = cls.users_for_extra()
     u1 = cls.users_for_query()
     us = list(u2) + list(u1)
     for i, u in enumerate(us):
         log('user no.{} {}'.format(i, u.login))
         cs = list(Contribution.all(u.login, u.repositories))
         u.contribution = sorted(cs, key=lambda c: c.count, reverse=True)
         u.star = sum([c.count for c in u.contribution])
     return us
Exemple #9
0
def return_newest_contributions():
    contributions = Contribution.get_contributions_new(repository)
    for c in contributions:
        aux = Comment.get_number_comments_by_contribution(repository, str(c['id']))
        c['n_comments'] = aux[0]['n_comments']
        aux = UserContributionVoted.get_votes_contribution(repository, str(c['id']))
        contribution_votes = []
        for aux_v in aux:
            contribution_votes.append(aux_v['username'])
        c['contribution_votes'] = contribution_votes
    return Response(json.dumps(contributions), mimetype='application/json')
Exemple #10
0
def create_new_comment(contribution_id):
    if 'Authorization' not in request.headers:
        return jsonify('Unauthorized'), 401
    username = decode_auth_token(request.headers['Authorization'])
    if username is None:
        return jsonify('Unauthorized'), 401
    if not Contribution.exists_contribution(repository, contribution_id):
        return jsonify('Not Found'), 404
    json = request.get_json()
    comment = Comment(username, datetime.datetime.now(), json['text'], contribution_id, None)
    comment.save(repository)
    return jsonify(comment.toJSON())
Exemple #11
0
def vote_contribution_api(contribution_id):
    if 'Authorization' not in request.headers:
        return jsonify('Unauthorized'), 401
    username = decode_auth_token(request.headers['Authorization'])
    if username is None:
        return jsonify('Unauthorized'), 401
    if not Contribution.exists_contribution(repository, contribution_id):
        return jsonify('Not Found'), 404
    contribution = Contribution.get_contribution(repository, contribution_id)
    if contribution.username == username:
        return jsonify('Forbidden'), 403
    contribution_voted = UserContributionVoted(username, contribution_id)
    if request.method == 'POST':
        if UserContributionVoted.exists(repository, contribution_id, username):
            return jsonify('Conflict'), 409
        contribution_voted.save(repository)
    elif request.method == 'DELETE':
        if not UserContributionVoted.exists(repository, contribution_id, username):
            return jsonify('Not Found'), 404
        contribution_voted.delete(repository)
    return return_asked_contribution(contribution_id)
Exemple #12
0
def create_new_new():
    if 'Authorization' not in request.headers:
        return jsonify('Unauthorized'), 401
    username = decode_auth_token(request.headers['Authorization'])
    if username is None:
        return jsonify(''), 401
    json = request.get_json()
    new = Contribution(title=json['title'], url=json['url'], text=None, time=datetime.datetime.now(),
                       username=username, kind=ContributionTypes.NEW.value)
    if Contribution.exists(repository, new.url):
        new = Contribution.get_contribution_by_url(repository, new.url)
        return jsonify(new.toJSON()), 409
    new.save(repository)
    return jsonify(new.toJSON())
Exemple #13
0
def new():
    contributions = Contribution.get_contributions_new(repository)
    username = decode_auth_token(request.cookies.get('token'))
    for c in contributions:
        aux = Comment.get_number_comments_by_contribution(repository, str(c['id']))
        c['n_comments'] = aux[0]['n_comments']
    if username is not None:
        user = User.get(repository, username)
        contributions_voted = UserContributionVoted.get_voted(repository, username)
        for c in contributions:
            c.voted = c['id'] in [cv['contribution_id'] for cv in contributions_voted]
        return render_template('home.html', contributions=contributions, user=user)
    return render_template('home.html', contributions=contributions)
Exemple #14
0
def return_asked_contribution(contribution_id):
    if not Contribution.exists_contribution(repository, contribution_id):
        return jsonify('Not Found'), 404
    contribution_to_show = Contribution.get_contribution(repository, contribution_id)
    contribution = {
        "id": contribution_to_show.id,
        "title": contribution_to_show.title,
        "url": contribution_to_show.url,
        "text": contribution_to_show.text,
        "time": contribution_to_show.time,
        "user": contribution_to_show.username,
        "kind": contribution_to_show.kind,
        "n_votes": contribution_to_show.n_votes,
        "comments": get_contribution_comments(contribution_id)
    }
    votes = UserContributionVoted.get_votes_contribution(repository, contribution_id)
    contribution_votes = []
    for vote in votes:
        contribution_votes.append(vote['username'])
    contribution['contribution_votes'] = contribution_votes
    contribution['n_comments'] = Comment.get_number_comments_by_contribution(repository, contribution_id)[0][
        'n_comments']
    return jsonify(contribution)
Exemple #15
0
def return_news():
    contributions = Contribution.get_news_home(repository)
    news_to_show = []
    for c in contributions:
        aux = Comment.get_number_comments_by_contribution(repository, str(c['id']))
        c['n_comments'] = aux[0]['n_comments']
        aux = UserContributionVoted.get_votes_contribution(repository, str(c['id']))
        contribution_votes = []
        for aux_v in aux:
            contribution_votes.append(aux_v['username'])
        c['contribution_votes'] = contribution_votes
        new_attributes = {
            "id": c['id'],
            "title": c['title'],
            "url": c['url'],
            "time": c['time'],
            "user": c['user'],
            "n_votes": c['n_votes'],
            "n_comments": c['n_comments'],
            "contribution_votes": c['contribution_votes']
        }
        news_to_show.append(new_attributes)
    return Response(json.dumps(news_to_show), mimetype='application/json')
Exemple #16
0
def __group_by_year(conts: Set[Contribution]) -> Dict[datetime.date, int]:
    mapped = map(
        lambda c: Contribution(datetime.date(c.date.year, 1, 1), c.commits),
        conts)
    return __group(mapped)
Exemple #17
0
def contribution(row, status):
    """
    Convert row to dictionary, only selecting values we want.
    """
    contribution = Contribution(row)
    url = contribution.url

    if url == "":
        return

    if contribution.staff_pick.lower() == "yes":
        staff_picked = True
    else:
        staff_picked = False

    try:
        review_date = parse(contribution.review_date)
    except Exception:
        review_date = datetime(1970, 1, 1)

    if ((datetime.now() - review_date).seconds > 561600
            and status != "unreviewed"):
        return

    total_payout = 0

    # Check if post deleted
    try:
        comment = Comment(url)
    except Exception:
        return

    if contribution.review_status == "Pending":
        for reply in comment.get_replies():
            if reply.author == contribution.moderator:
                review_date = reply["created"]
                comment_url = reply.permlink
                break
        else:
            review_date = datetime(1970, 1, 1)
            comment_url = ""
    else:
        comment_url = ""

    # Calculate total (pending) payout of contribution
    if comment.time_elapsed() > timedelta(days=7):
        total_payout = Amount(comment.json()["total_payout_value"]).amount
    else:
        total_payout = Amount(comment.json()["pending_payout_value"]).amount

    # Get votes, comments and author
    votes = comment.json()["net_votes"]
    comments = comment.json()["children"]
    author = comment.author

    # Add status for unvoted and pending
    if contribution.vote_status == "Unvoted":
        status = "unvoted"
    elif contribution.vote_status == "Pending":
        status = "pending"

    try:
        utopian_vote = Vote(f"{comment.authorperm}|utopian-io").sbd
    except Exception:
        voted_on = False
        utopian_vote = 0

    if utopian_vote:
        voted_on = True
    else:
        voted_on = False

    # Check for when contribution not reviewed
    if contribution.score == "":
        score = None
    else:
        try:
            score = float(contribution.score)
        except Exception:
            score = None

    # Create contribution dictionary and return it
    new_contribution = {
        "moderator": contribution.moderator.strip(),
        "author": author,
        "review_date": review_date,
        "url": url,
        "repository": contribution.repository,
        "category": contribution.category,
        "staff_picked": staff_picked,
        "picked_by": contribution.picked_by,
        "status": status,
        "score": score,
        "voted_on": voted_on,
        "total_payout": total_payout,
        "total_votes": votes,
        "total_comments": comments,
        "utopian_vote": utopian_vote,
        "created": comment["created"],
        "title": comment.title,
        "review_status": contribution.review_status.lower(),
        "comment_url": comment_url
    }

    return new_contribution
Exemple #18
0
 def handle_starttag(self, tag, attrs):
     if tag == 'rect':
         dic = dict(attrs)
         self.contributions.append(
             Contribution(datetime.strptime(dic['data-date'], "%Y-%m-%d"), int(dic['data-count'])))
Exemple #19
0
    if time_ago < 60:
        return str(int(round(time_ago))) + " seconds"

    time_ago = time_ago / 60
    if time_ago < 60:
        return str(int(round(time_ago))) + " minutes"

    time_ago = time_ago / 60
    if time_ago / 60 < 24:
        return str(int(round(time_ago))) + " hours"

    time_ago = time_ago / 24
    if time_ago < 12:
        return str(int(round(time_ago))) + " months"

    time_ago = time_ago / 12
    return str(int(round(time_ago))) + " years"


if __name__ == '__main__':
    repository = Persistence(os.environ['DB_PATH'], logging.getLogger(__name__))
    repository.init_db(
        [User.get_table_creation(), Contribution.get_table_creation(), UserContributionVoted.get_table_creation(),
         Comment.get_table_creation(), UserCommentVoted.get_table_creation()])

    basicConfig(filename=os.environ['LOG'], level=INFO)

    app.config.update(TEMPLATES_AUTO_RELOAD=True)
    app.run(host=str(os.environ['HOST']), port=int(os.environ['PORT']), threaded=True)
Exemple #20
0
def delete_contribution():
    contribution_id = request.form['con_id']
    Comment.delete_comments_from_contribution(repository, contribution_id)
    Contribution.delete_contribution(repository, contribution_id)
    return redirect('')