Пример #1
0
def add_tag(session, pkgname, tag, user):
    """ Add a provided tag to the specified package. """

    tag = tag.lower()

    package = model.Package.by_name(session, pkgname)
    try:
        tagobj = model.Tag.get(session, package.id, tag)
        tagobj.like += 1
        user.score += 1
    except NoResultFound:

        # If no such tag exists, create a new one.  But first..
        if blacklisted(tag):
            raise ValueError("'%s' is not allowed." % tag)

        tagobj = model.Tag(package_id=package.id, label=tag)
        session.add(tagobj)
        session.flush()
        user.score += 2
    voteobj = model.Vote(user_id=user.id, tag_id=tagobj.id, like=True)
    session.add(user)
    session.add(voteobj)
    session.flush()

    fedmsg.publish('tag.create',
                   msg=dict(
                       tag=tagobj,
                       vote=voteobj,
                       user=user,
                   ))

    return 'Tag "%s" added to the package "%s"' % (tag, pkgname)
Пример #2
0
  def _post_put_hook(self, future):
    #After an update update the lesson's properties if this version is the parent lesson's latest version
    # use update_lesson(self)
    #order matters bellow 
    # create vote for lesson version if there isn't any already. and also check if it already has a lesson other wise create one.
    if not self.vote:
      self.vote = model.Vote(item=self.key).put()

    self._put_async()
Пример #3
0
    def put(self):
        """Exposed as `PUT /api/votes`.

       Takes a request payload that is a JSON object containing the Photo ID
       for which the currently logged in user is voting.

       {
         'photoId':0
       }

       Returns the following JSON response representing the Photo for which the
       User voted.

       {
         'id':0,
         'ownerUserId':0,
         'ownerDisplayName':'',
         'ownerProfileUrl':'',
         'ownerProfilePhoto':'',
         'themeId':0,
         'themeDisplayName':'',
         'numVotes':1,
         'voted':true,
         'created':0,
         'fullsizeUrl':'',
         'thumbnailUrl':'',
         'voteCtaUrl':'',
         'photoContentUrl':''
       }

       Issues the following errors along with corresponding HTTP response codes:
       401: 'Unauthorized request'.  No user was connected to disconnect.
       401: 'Access token expired'.  Retry with a new access token.
       500: 'Error writing app activity: ' + error from client library
    """
        try:
            user = self.get_user_from_session()
            vote = model.Vote()
            vote.from_json(self.request.body)
            vote.owner_user_id = user.key().id()
            voteExist = model.Vote.all().filter("owner_user_id =",
                                                user.key().id()).filter(
                                                    "photo_id =",
                                                    vote.photo_id).get()
            if voteExist is None:
                photo = model.Photo.get_by_id(vote.photo_id)
                if photo is not None:
                    vote.put()
                    photo.voted = True
                    self.add_photo_to_google_plus_activity(user, photo)
                    self.send_success(photo)
                    return
        except UserNotAuthorizedException as e:
            self.send_error(401, e.msg)
Пример #4
0
 def _create_proposal(self, mission_id, proposer_id, members_ids,
                      players_ids):
     players = db.session.query(model.Player).filter(
         model.Player.id.in_(members_ids)).all()
     voting = model.Voting()
     voting.votes = [model.Vote(voter_id=player) for player in players_ids]
     proposal = model.TroopProposal(members=players,
                                    proposer_id=proposer_id,
                                    mission_id=mission_id,
                                    voting=voting)
     db.session.add(proposal)
     db.session.add(voting)
     return proposal
Пример #5
0
    def _post_put_hook(self, future):
        #After an update update the lesson's properties if this version is the parent lesson's latest version
        # use update_lesson(self)
        #order matters bellow
        # create vote for lesson version if there isn't any already. and also check if it already has a lesson other wise create one.
        if not self.vote:
            vote = model.Vote(item=self.key).put()
            self.vote = vote
        if not self.lesson:
            lesson = model.Lesson().put()
            self.lesson = lesson
        if self.lesson and self.key == self.lesson.get().latest_version:
            self.update_lesson(
            )  #updates the lesson when the lesson version is updated

        self._put_async(
        )  #avoid using put() here because it will cause infinite loop
Пример #6
0
def admin_vote_update(vote_id=0):
    if vote_id:
        vote_db = model.Vote.get_by_id(vote_id)
    else:
        vote_db = model.Vote()

    if not vote_db:
        flask.abort(404)

    form = VoteUpdateAdminForm(obj=vote_db)

    user_dbs, user_cursor = model.User.get_dbs(limit=-1)
    post_dbs, post_cursor = model.Post.get_dbs(limit=-1)
    form.user_key.choices = [(c.key.urlsafe(), c.name) for c in user_dbs]
    form.post_key.choices = [(c.key.urlsafe(), c.title) for c in post_dbs]
    if flask.request.method == 'GET' and not form.errors:
        form.user_key.data = vote_db.user_key.urlsafe(
        ) if vote_db.user_key else None
        form.post_key.data = vote_db.post_key.urlsafe(
        ) if vote_db.post_key else None

    if form.validate_on_submit():
        form.user_key.data = ndb.Key(
            urlsafe=form.user_key.data) if form.user_key.data else None
        form.post_key.data = ndb.Key(
            urlsafe=form.post_key.data) if form.post_key.data else None
        form.populate_obj(vote_db)
        vote_db.put()
        return flask.redirect(
            flask.url_for('admin_vote_list', order='-modified'))

    return flask.render_template(
        'vote/admin_vote_update.html',
        title='%s' % '%sVote' % ('' if vote_id else 'New '),
        html_class='admin-vote-update',
        form=form,
        vote_db=vote_db,
        back_url_for='admin_vote_list',
        api_url=flask.url_for(
            'api.admin.vote',
            vote_key=vote_db.key.urlsafe() if vote_db.key else ''),
    )
Пример #7
0
 def _handle_troop_voting_results(self, mission, **kwargs):
     voting = mission.troop_proposals[-1].voting
     voting.result = sum([v.result
                          for v in voting.votes]) > len(voting.votes) // 2
     if voting.result:
         mission.troop_members = mission.troop_proposals[-1].members
         mission.voting = model.Voting()
         mission.voting.votes = [
             model.Vote(voter=player) for player in mission.troop_members
         ]
         db.session.add(mission.voting)
         mission.next()
         return actions.MissionUpdated(mission.game_id, mission.to_dict())
     else:
         if len(mission.troop_proposals) >= self.rules['proposals_to_lose']:
             mission._stage = model.RoundStage.mission_results
             mission.resistance_won = False
             return actions.GameUpdated(mission.game.to_dict(),
                                        mission.game.host_id)
         mission._stage = model.RoundStage.proposal_request
         return self.update_mission(mission, **kwargs)
Пример #8
0
        voteobj = model.Vote.get(session, user_id=user.id, tag_id=tagobj.id)
        if voteobj.like == vote:
            return 'Your vote on the tag "%s" for the package "%s" did ' \
                   'not change' % (tag, pkgname)
        else:
            if voteobj.like:
                tagobj.like -= 1
                tagobj.dislike += 1
            else:
                tagobj.dislike -= 1
                tagobj.like += 1
            voteobj.like = vote
    except NoResultFound:
        # otherwise, create it
        verb = 'added'
        voteobj = model.Vote(user_id=user.id, tag_id=tagobj.id, like=vote)
        if vote:
            tagobj.like += 1
        else:
            tagobj.dislike += 1
        user.score += 0.5

    session.add(user)
    session.add(tagobj)
    session.add(voteobj)
    session.flush()

    fedmsg.publish('tag.update',
                   msg=dict(
                       tag=tagobj,
                       vote=voteobj,
Пример #9
0
def save():
    response = None
    with app.app_context():
        if 'RECAPTCHA_SECRET' in os.environ:
            recaptcha_secret = os.environ['RECAPTCHA_SECRET']
            recaptcha_response = request.form['g-recaptcha-response']
            remote_ip = request.remote_addr
            verification = requests.post(
                'https://www.google.com/recaptcha/api/siteverify',
                data=dict(secret=recaptcha_secret,
                          response=recaptcha_response,
                          remoteip=remote_ip)).json()
            if not verification['success']:
                return make_response(redirect(url_for('index')))

        receipt = model.Receipt.query.filter_by(
            user_id=session['me']['id']).first()

        current_testers_text = os.getenv('TESTERS', '')
        current_testers = re.split(r'\W', current_testers_text)
        user_is_tester = session['me']['name'] in current_testers

        if receipt is not None:
            if request.cookies['receipt_id'] is None:
                return render_template('done.html', nocookie=True)

            receipt_id_text = request.cookies['receipt_id']
            receipt_id_bytes = binascii.unhexlify(
                receipt_id_text.replace('-', ''))
            userhash = hashlib.sha256(session['me']['id'].encode('utf8') +
                                      receipt_id_bytes).hexdigest()
            if model.Vote.query.filter_by(user_hash=userhash).count() == 0:
                return render_template('done.html', tamper=True)
            response = make_response(
                render_template('done.html',
                                voted=True,
                                receipt_id=receipt_id_text,
                                request=request,
                                user_is_tester=user_is_tester))
        else:
            receipt_id = uuid.uuid4()
            receipt_id_text = str(receipt_id)
            userhash = hashlib.sha256(session['me']['id'].encode('utf8') +
                                      receipt_id.bytes).hexdigest()
            response = make_response(
                render_template('done.html',
                                voted=True,
                                receipt_id=receipt_id_text,
                                request=request,
                                user_is_tester=user_is_tester))
            response.set_cookie('receipt_id', value=receipt_id_text)
            rct = model.Receipt()
            rct.user_id = session['me']['id']
            model.db.session.add(rct)

        v = model.Vote.query.filter_by(user_hash=userhash).first()
        if v is None:
            v = model.Vote()
            v.user_hash = userhash
        v.datestamp = datetime.datetime.utcnow()
        model.db.session.add(v)
        # response = 'userid=' + session['me']['id'] + '\n'
        for a in v.answers:
            model.db.session.delete(a)
        for field, value in sorted(request.form.items(), key=questions_sort):
            if value is None or value == '':
                continue
            if field in ('cmd_save', 'g-recaptcha-response'):
                continue
            if not field.startswith('q_'):
                continue
            a = model.Answer.query.filter_by(code=field, vote=v).first()
            if a is None:
                a = model.Answer()
                a.code = field
                a.vote = v
            if len(value) >= 512:
                value = value[:511] + '\u2026'
            a.answer_value = value
            a.vote = v
            model.db.session.add(a)
        try:
            model.db.session.commit()
        except sqlalchemy.exc.OperationalError as e:
            response = make_response(render_template('done.html', error=True))
    if response is None:
        response = make_response(render_template('done.html'))
    return response
Пример #10
0
 def _post_put_hook(self, future):
   if not self.vote:
     self.vote = model.Vote(item=self.key).put()
     self._put_async() #AVOID USING put() because it will cause infinite loop
Пример #11
0
def load_votes(session):
	"""Parsing the votes json files to add Vote, HouseVote, and 
	SenateVote objects onto their respective tables in the database 
	using the path files created by create_congress_list and 
	parse_congress_list.
	"""
	# test_list = ['data/congress/108/votes/2004/h177/data.json', 
	# 			 'data/congress/112/votes/2011/s153/data.json', 
	# 			 'data/congress/112/votes/2011/h183/data.json', 
	# 			 'data/congress/110/votes/2007/h1118/data.json', 
	# 			 'data/congress/110/votes/2007/h774/data.json', 
	# 			 'data/congress/110/votes/2008/h34/data.json', 
	# 			 'data/congress/107/votes/2001/h335/data.json', 
	# 			 'data/congress/109/votes/2006/h328/data.json', 
	# 			 'data/congress/111/votes/2010/h392/data.json', 
	# 			 'data/congress/111/votes/2009/s209/data.json', 
	# 			 'data/congress/106/votes/1999/h319/data.json', 
	# 			 'data/congress/108/votes/2003/h173/data.json', 
	# 			 'data/congress/110/votes/2008/s52/data.json', 
	# 			 'data/congress/112/votes/2011/h344/data.json', 
	# 			 'data/congress/113/votes/2013/h66/data.json', 
	# 			 'data/congress/113/votes/2013/s178/data.json', 
	# 			 'data/congress/112/votes/2011/h783/data.json', 
	# 			 'data/congress/107/votes/2002/h87/data.json', 
	# 			 'data/congress/110/votes/2007/h778/data.json', 
	# 			 'data/congress/110/votes/2007/h336/data.json', 
	# 			 'data/congress/108/votes/2003/h497/data.json', 
	# 			 'data/congress/109/votes/2005/h513/data.json', 
	# 			 'data/congress/110/votes/2007/s113/data.json', 
	# 			 'data/congress/113/votes/2013/h53/data.json', 
	# 			 'data/congress/111/votes/2010/h326/data.json', 
	# 			 'data/congress/111/votes/2009/h498/data.json', 
	# 			 'data/congress/109/votes/2005/s36/data.json', 
	# 			 'data/congress/111/votes/2010/s191/data.json', 
	# 			 'data/congress/110/votes/2007/h735/data.json', 
	# 			 'data/congress/107/votes/2002/h20/data.json'] #TEST

	# starting a counter to commit regularly throughout the process
	counter = 0
	# for vote in test_list: #TEST

	for vote in cpaths['votes']:
		counter += 2
		# open the file
		v = open(vote)
		# load as a json object to access values
		vote_dict = json.load(v)

		# skip votes related to types of bills not being stored
		votes_to_skip = ['hconres', 'hjres', 'hres', 'sconres', 'sjres', 'sres']
		
		# iterate over votes to add associated information to the database
		if vote_dict.get('bill') and vote_dict['bill']['type'] not in votes_to_skip:
			# creating the bill_id
			vote_bill = str(vote_dict['bill']['type'])
			vote_bill_number = str(vote_dict['bill']['number'])
			vote_bill_congress = str(vote_dict['congress'])
			vote_bill_id = vote_bill + vote_bill_number + '-' + vote_bill_congress
			
			# changing the date into a datetime object
			vote_date = datetime.datetime.strptime(vote_dict['date'][0:10], "%Y-%m-%d")

			# assign variables to be added as part of the Vote object
			vote_id = vote_dict['vote_id']
			vote_category = vote_dict['category']
			vote_result = vote_dict['result']

			creat Vote object
			Vote = model.Vote(vote_id=vote_id,
							  bill_id=vote_bill_id,
							  date=vote_date,
							  vote_category=vote_category,
							  vote_result=vote_result)
			session.add(Vote)

			# creating HouseVote and SenateVote objects (connecting 
			# Legislators with the value of their vote--House votes 
			# reference the GovTrack id, Senate votes reference the LIS ID)

			# a dictionary where the keys are the type of vote (Yea/Nay/etc)
			vote_types = vote_dict['votes'].keys() 
			
			# add each member's vote as a HouseVote or SenateVote object
			for vote_type in vote_types:
				legislator_ids = []
				voters = vote_dict['votes'][vote_type]

				# add each legislator's id to the list to be added as 
				# part of the object
				for voter in voters:
					try:
						legislator_ids.append(voter['id'])
					except:
						print vote_bill_id
				
				# add object attributes as HouseVote or SenateVote objects
				for legislator in legislator_ids:
					# commented code below was used when all votes were on a single table
					# if vote_id[0] == 'h':
					# 	reference_id='bioguide_id'
					# elif vote_id[0] == 's':
					# 	reference_id='lis_id'

					# LegislatorBillVote = model.LegislatorBillVote(vote_id=vote_id,
					# 											  bill_id=vote_bill_id,
					# 											  vote_value=vote_type,
					# 											  reference_id=reference_id,
					# 											  legislator_id=legislator)
							
					if vote_id[0] == 'h':
						LegislatorBillVote = model.HouseVote(vote_id=vote_id,
										  				bioguide_id=legislator,
														bill_id=vote_bill_id,
														vote_value=vote_type)
						session.add(LegislatorBillVote)
					if vote_id[0] == 's':
						LegislatorBillVote = model.SenateVote(vote_id=vote_id,
										  				lis_id=legislator,
														bill_id=vote_bill_id,
														vote_value=vote_type)
					session.add(LegislatorBillVote)
			if counter % 500:
				session.commit()
		session.commit()
Пример #12
0
 def vote(self, twid, vote):
     if vote in model.VoteEnum:
         newVote = model.Vote(twid, vote)
         db.session.add(newVote)
         db.session.commit()