Example #1
0
def seguir(obraid):

	emailto = ""
	obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid, _get_obras(obraid=obraid)[0])

	if not obra:
		print "Não achou a obra!"
		return abort(404)

	slug = obra['slug']

	if request.form:

		if request.form.has_key('faceid'):
			has = UserFollow.query.filter_by(obra_id=obraid, facebook_id=request.form['faceid'])
			if has.count() <= 0:
				# return dumps({'status':'error','msg':'Você já é seguidor desta obra pelo Facebook'})
				follow = _make_follow(obraid)
				follow.facebook_id = request.form['faceid']
				emailto = "*****@*****.**" % follow.facebook_id

		if request.form.has_key('twitterid'):
			has = UserFollow.query.filter_by(obra_id=obraid, twitter_id=request.form['twitterid'])
			if has.count() <= 0:
				# return dumps({'status':'error','msg':'Você já é seguidor desta obra pelo Twitter'})
				follow = _make_follow(obraid)
				follow.twitter_id = request.form['twitterid']
				msg = u"A partir de agora você segue a obra %s!" % obra['title']
				_send_twitter_dm(follow.twitter_id, msg)

		if request.form.has_key('email'):
			has = UserFollow.query.filter_by(obra_id=obraid, email=request.form['email'])
			if has.count() <= 0:
				# return dumps({'status':'error','msg':'Você já é seguidor desta obra pelo Email'})
				follow = _make_follow(obraid)
				follow.email = request.form['email']
				emailto = follow.email

		dbsession.commit()

		if emailto:
			base_url = current_app.config['BASE_URL']
			base_url = base_url if base_url[-1:] != '/' else base_url[:-1] #corta a barra final
			_dados_email = {
				'titulo': obra['title'],
				'link'  : base_url + url_for('.obra',slug=slug),
				'descricao' : Markup(obra['content']).striptags(),
				'monitore_url': base_url + url_for('.index'),
				'siteurl': base_url,
			}
			sendmail(
			    current_app.config['SEGUIROBRA_SUBJECT'] % _dados_email,
			    emailto,
			    current_app.config['SEGUIROBRA_MSG'] % _dados_email
			)


		return dumps({'status':'ok'})
	else:
		return dumps({'status':'error'})
Example #2
0
def deseguir(obraid):
	obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid, _get_obras(obraid=obraid)[0])

	if not obra:
		print "Não achou a obra!"
		return abort(404)

	slug = obra['slug']

	if request.form:

		if request.form.has_key('faceid'):
			has = UserFollow.query.filter_by(obra_id=obraid, facebook_id=request.form['faceid'])
			if has.count() > 0:
				for f in has:
					has.delete()

		if request.form.has_key('twitterid'):
			has = UserFollow.query.filter_by(obra_id=obraid, twitter_id=request.form['twitterid'])
			if has.count() > 0:
				for f in has:
					has.delete()

		if request.form.has_key('email'):
			has = UserFollow.query.filter_by(obra_id=obraid, email=request.form['email'])
			if has.count() > 0:
				for f in has:
					has.delete()

		dbsession.commit()

		return dumps({'status':'ok', 'msg':u'Suas opções foram removidas. Obrigado por participar!'})
	else:
		return dumps({'status':'error'})
Example #3
0
def contribs_user():
    """Lists all contributions in the JSON format"""
    try:
        user = auth.authenticated_user()
    except auth.NobodyHome:
        return dumps([])
    return dumps([
        _format_contrib(i)
        for i in Contrib.query.filter_by().filter(Contrib.user == user)
    ])
Example #4
0
def contribs_user():
    """Lists all contributions in the JSON format"""
    try:
        user = auth.authenticated_user()
    except auth.NobodyHome:
        return dumps([])
    return dumps([
            _format_contrib(i)
                for i in Contrib.query
                    .filter_by()
                    .filter(Contrib.user==user)])
Example #5
0
def api_obraid(obraid):
	# obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0])
	obra = wordpress.getCustomPost(obraid, 'gdobra')
	if not obra:
		return Response(dumps({'status':'invalid_obraid'}),content_type="application/json")

	# timeline = wordpress.monitoramento.getObraTimeline(obra['id'], int(itemid) )
	# timeline = adjustCf(timeline)
	# update = timeline[0]

	return Response(dumps(obra),content_type="application/json")
Example #6
0
def api_obraid(obraid):
    # obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0])
    obra = wordpress.getCustomPost(obraid, 'gdobra')
    if not obra:
        return Response(dumps({'status': 'invalid_obraid'}),
                        content_type="application/json")

    # timeline = wordpress.monitoramento.getObraTimeline(obra['id'], int(itemid) )
    # timeline = adjustCf(timeline)
    # update = timeline[0]

    return Response(dumps(obra), content_type="application/json")
Example #7
0
def seguir(obraid):

	emailto = ""
	obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid, _get_obras(obraid=obraid)[0])

	if not obra:
		print "Não achou a obra!"
		return abort(404)

	slug = obra['slug']

	if request.form:
		follow = UserFollow()

		if authapi.is_authenticated():
			follow.user = authapi.authenticated_user()
			emailto = follow.user.email

		follow.obra_id = int(obraid)

		if request.form.has_key('faceid'):
			follow.facebook_id = request.form['faceid']

		if request.form.has_key('twitterid'):
			follow.twitter_id = request.form['twitterid']

		if request.form.has_key('email'):
			follow.email = request.form['email']
			emailto = follow.email

		dbsession.commit()

		if emailto:
			base_url = current_app.config['BASE_URL']
			base_url = base_url if base_url[-1:] != '/' else base_url[:-1] #corta a barra final
			_dados_email = {
				'titulo': obra['title'],
				'link'  : base_url + url_for('.obra',slug=slug),
				'descricao' : Markup(obra['content']).striptags(),
				'monitore_url': base_url + url_for('.index'),
				'siteurl': base_url,
			}
			sendmail(
			    current_app.config['SEGUIROBRA_SUBJECT'] % _dados_email,
			    emailto,
			    current_app.config['SEGUIROBRA_MSG'] % _dados_email
			)


		return dumps({'status':'ok'})
	else:
		return dumps({'status':'error'})
Example #8
0
def seguir(obraid):

    emailto = ""
    obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid,
                                                  _get_obras(obraid=obraid)[0])

    if not obra:
        print "Não achou a obra!"
        return abort(404)

    slug = obra['slug']

    if request.form:
        follow = UserFollow()

        if authapi.is_authenticated():
            follow.user = authapi.authenticated_user()
            emailto = follow.user.email

        follow.obra_id = int(obraid)

        if request.form.has_key('faceid'):
            follow.facebook_id = request.form['faceid']

        if request.form.has_key('twitterid'):
            follow.twitter_id = request.form['twitterid']

        if request.form.has_key('email'):
            follow.email = request.form['email']
            emailto = follow.email

        dbsession.commit()

        if emailto:
            base_url = current_app.config['BASE_URL']
            base_url = base_url if base_url[
                -1:] != '/' else base_url[:-1]  #corta a barra final
            _dados_email = {
                'titulo': obra['title'],
                'link': base_url + url_for('.obra', slug=slug),
                'descricao': Markup(obra['content']).striptags(),
                'monitore_url': base_url + url_for('.index'),
                'siteurl': base_url,
            }
            sendmail(current_app.config['SEGUIROBRA_SUBJECT'] % _dados_email,
                     emailto,
                     current_app.config['SEGUIROBRA_MSG'] % _dados_email)

        return dumps({'status': 'ok'})
    else:
        return dumps({'status': 'error'})
Example #9
0
def new_comment():
    """Posts new comments to the blog"""
    print "/new_comment/"
    if not is_authenticated():
        resp = make_response(dumps({
            'status': 'error',
            'msg': _(u'User not authenticated'),
            'redirectTo': url_for('auth.login')
        }))
        # if request.form['content']:
        #     resp.set_cookie('live_comment_save', request.form['content'].replace('\n','<br/>') )
        return resp

    try:
        nao_exibir_nome = request.form['nao_exibir_nome']
    except:
        nao_exibir_nome = ""

    try:
        post_id = request.form['comentar_em']
    except:
        post_id = request.form['post_id']

    try:
        wordpress.newComment(
            username=session['username'],
            password=session['password'],
            post_id=post_id,
            content=request.form['content'],
            nao_exibir_nome=nao_exibir_nome
        )
        removecache("comentarios%s" % str(post_id))
        return msg.ok(_(u'Thank you. Your comment was successfuly sent'))
    except xmlrpclib.Fault, err:
        return msg.error(_(err.faultString), code='CommentError')
Example #10
0
def new_comment():
    """Posts new comments to the blog"""
    print "/new_comment/"
    if not is_authenticated():
        resp = make_response(
            dumps({
                'status': 'error',
                'msg': _(u'User not authenticated'),
                'redirectTo': url_for('auth.login')
            }))
        # if request.form['content']:
        #     resp.set_cookie('live_comment_save', request.form['content'].replace('\n','<br/>') )
        return resp

    try:
        nao_exibir_nome = request.form['nao_exibir_nome']
    except:
        nao_exibir_nome = ""

    try:
        post_id = request.form['comentar_em']
    except:
        post_id = request.form['post_id']

    try:
        wordpress.newComment(username=session['username'],
                             password=session['password'],
                             post_id=post_id,
                             content=request.form['content'],
                             nao_exibir_nome=nao_exibir_nome)
        removecache("comentarios%s" % str(post_id))
        return msg.ok(_(u'Thank you. Your comment was successfuly sent'))
    except xmlrpclib.Fault, err:
        return msg.error(_(err.faultString), code='CommentError')
Example #11
0
def contribs_all():
    """Lists all contributions in the JSON format"""
    r = fromcache("contribs_all_") or tocache(
        "contribs_all_",
        dumps(
            [_format_contrib(i)
             for i in Contrib.query.filter_by(status=True)]))
    return r
Example #12
0
def send(msg, data):
    """Sends messages to the socketio buzz
    """
    # This code will only run when no app is binded. Which means we
    # don't need to provide any socketio thing
    server = zmq.Context().socket(zmq.PUSH)
    server.connect(conf.SOCK_INCOMING_PULL)
    server.send(dumps({'message': msg, 'data': data}))
    server.close()
Example #13
0
File: sio.py Project: calcwb/gd
def send(msg, data):
    """Sends messages to the socketio buzz
    """
    # This code will only run when no app is binded. Which means we
    # don't need to provide any socketio thing
    server = zmq.Context().socket(zmq.PUSH)
    server.connect(conf.SOCK_INCOMING_PULL)
    server.send(dumps({ 'message': msg, 'data': data }))
    server.close()
Example #14
0
def contribs_choosen():
    """Lists all contributions in the JSON format"""
    contribs = {}
    for key in THEMES.keys():
        contribs[key] = {'name': THEMES[key], 'children': []}
        count = 11 if key == 'familia' else 10
        for data in wordpress.pairwise.getSortedByScore(0, count, key)[0]:
            cid = loads(data['data'])['id']

            # This is _nasty_. The team that carried about organizing
            # contribution approved something wrong. Yes, now we have
            # invalid data on our db. This was the better way I figured
            # out to fix it right now, but obviously something better
            # must be done when we have more time.
            if cid == 1213:
                continue
            contrib = Contrib.get(cid)
            final = _format_contrib(contrib)
            final['author'] = contrib.user.name
            final['score'] = data['score']
            final['votes'] = {
                'score': data['score'],
                'total': data['votes'],
                'won': data['won'],
                'lost': data['lost'],
            }

            final['children'] = []
            for subcontrib in contrib.children:
                subfinal = _format_contrib(subcontrib)
                subfinal['author'] = subcontrib.user.name
                final['children'].append(subfinal)

            for subcontrib in Contrib.query.filter_by(parent=contrib.id):
                subfinal = _format_contrib(subcontrib)
                subfinal['author'] = subcontrib.user.name
                final['children'].append(subfinal)
            contribs[key]['children'].append(final)
    return dumps(contribs)
Example #15
0
def contribs_choosen():
    """Lists all contributions in the JSON format"""
    contribs = {}
    for key in THEMES.keys():
        contribs[key] = {'name': THEMES[key], 'children': []}
        count = 11 if key == 'familia' else 10
        for data in wordpress.pairwise.getSortedByScore(0, count, key)[0]:
            cid = loads(data['data'])['id']

            # This is _nasty_. The team that carried about organizing
            # contribution approved something wrong. Yes, now we have
            # invalid data on our db. This was the better way I figured
            # out to fix it right now, but obviously something better
            # must be done when we have more time.
            if cid == 1213:
                continue
            contrib = Contrib.get(cid)
            final = _format_contrib(contrib)
            final['author'] = contrib.user.name
            final['score'] = data['score']
            final['votes'] = {
                'score': data['score'],
                'total': data['votes'],
                'won': data['won'],
                'lost': data['lost'],
            }

            final['children'] = []
            for subcontrib in contrib.children:
                subfinal = _format_contrib(subcontrib)
                subfinal['author'] = subcontrib.user.name
                final['children'].append(subfinal)

            for subcontrib in Contrib.query.filter_by(parent=contrib.id):
                subfinal = _format_contrib(subcontrib)
                subfinal['author'] = subcontrib.user.name
                final['children'].append(subfinal)
            contribs[key]['children'].append(final)
    return dumps(contribs)
Example #16
0
def buzz_stream(aid):
    """public_buzz, moderated_buzz, selected_buzz, last_published at once
    filtred by from_id, selected_ids, moderated_ids and last_published_id"""
    public_limit = int(request.values.get('public_limit'))
    public_ids = request.values.getlist('public_ids[]')
    moderated_ids = request.values.getlist('moderated_ids[]')
    selected_ids = request.values.getlist('selected_ids[]')
    last_published_id = int(request.values.get('last_published_id', 0))

    public = AudiencePosts.query.get(aid).get_public_buzz(0,public_limit,public_ids)
    moderated = AudiencePosts.query.get(aid).get_moderated_buzz(moderated_ids)
    selected = AudiencePosts.query.get(aid).get_selected_buzz(selected_ids)
    published = AudiencePosts.get(aid).get_last_published_notice()

    buzz = {'public': [notice.to_dict() for notice in public],
            'moderated': [notice.to_dict() for notice in moderated],
            'selected': [notice.to_dict() for notice in selected],
            'published': published and published.id != last_published_id \
            and published.to_dict() or None}
    # print "=================================================================================="
    # print dumps(buzz)
    # print "=================================================================================="
    return dumps(buzz)
Example #17
0
def buzz_stream(aid):
    """public_buzz, moderated_buzz, selected_buzz, last_published at once
    filtred by from_id, selected_ids, moderated_ids and last_published_id"""
    public_limit = int(request.values.get('public_limit'))
    public_ids = request.values.getlist('public_ids[]')
    moderated_ids = request.values.getlist('moderated_ids[]')
    selected_ids = request.values.getlist('selected_ids[]')
    last_published_id = int(request.values.get('last_published_id', 0))

    public = AudiencePosts.query.get(aid).get_public_buzz(
        0, public_limit, public_ids)
    moderated = AudiencePosts.query.get(aid).get_moderated_buzz(moderated_ids)
    selected = AudiencePosts.query.get(aid).get_selected_buzz(selected_ids)
    published = AudiencePosts.get(aid).get_last_published_notice()

    buzz = {'public': [notice.to_dict() for notice in public],
            'moderated': [notice.to_dict() for notice in moderated],
            'selected': [notice.to_dict() for notice in selected],
            'published': published and published.id != last_published_id \
            and published.to_dict() or None}
    # print "=================================================================================="
    # print dumps(buzz)
    # print "=================================================================================="
    return dumps(buzz)
Example #18
0
def all_buzz(aid):
    """Returns the last published notice of an audience"""
    public_all = AudiencePosts.query.get(aid).get_all_buzz()
    buzz = {'public_all': [notice.to_dict() for notice in public_all]}
    return dumps(buzz)
Example #19
0
def contribs_all():
    """Lists all contributions in the JSON format"""
    r = fromcache("contribs_all_") or  tocache("contribs_all_",dumps([
                                        _format_contrib(i)
                                            for i in Contrib.query.filter_by(status=True)]))
    return r
Example #20
0
def page_json(path):
    """Returns a page data in the JSON format"""
    page = wordpress.getPageByPath(path)
    return dumps(page and page.data or None)
Example #21
0
def contribui(slug):

    obra = fromcache("obra-" + slug) or tocache("obra-" + slug,
                                                _get_obras(slug)[0])
    if not obra:
        return abort(404)

    r = {'status': 'ok', 'message': 'Sua contibuição foi aceita com sucesso'}
    user_recent = False
    if not authapi.is_authenticated():
        # r = {'status':'not_logged'}
        """
		Se não está autenticado, tenta achar o usuário pelo email, e
		acessar com a senha inserida no formulario.
		Se não, cadastra o camarada, com o nome e email informados, gerando
		uma senha para ele e enviando o email de boas vindas.
		"""
        email = request.form['email']

        if request.form['senha']:
            #Informou a senha do cadastro já existente
            # username = email
            # senha = request.form['senha']
            #Efetua o login
            print "Usuario e senha informado... logando!"
            username = request.values.get('email')
            senha = request.values.get('senha')
            print "tentando logar com", username, senha
            try:
                user = authapi.login(username, senha)
                r = {
                    'status': 'ok',
                    'message': 'Sua contibuição foi aceita com sucesso',
                    'refresh': True
                }
            except authapi.UserNotFound:
                r = {'status': 'nok', 'message': _(u'Wrong user or password')}
                return dumps(r)
            except authapi.UserAndPasswordMissmatch:
                r = {'status': 'nok', 'message': _(u'Wrong user or password')}
                return dumps(r)
        elif request.form['nome']:
            print "Nome informado... cadastrando..."
            #Informou a senha para cadastro
            nome = request.form['nome']
            telefone = request.form[
                'telefone'] if 'telefone' in request.form else ""
            novasenha = request.form[
                'newPassword'] if 'newPassword' in request.form else ""

            if not novasenha:
                # novasenha = "gabinetedigital"
                novasenha = ''.join(
                    random.choice(string.printable) for x in range(8))

            # print nome, '-', email, '-', novasenha

            try:
                user = authapi.create_user(nome, email, unicode(novasenha),
                                           email)
                r = {
                    'status':
                    'ok',
                    'message':
                    'Sua contibuição foi aceita com sucesso. Verifique seu email para confirmar o cadastro.'
                }
                user_recent = True
                send_welcome_email(user)
                send_password(user.email, novasenha)
            except authapi.UserExistsUnconfirmed, e:
                r = {
                    'status':
                    'nok',
                    'message':
                    u'Seu usuário precisa ser confirmado, veja seu email!'
                }
                return dumps(r)

            if telefone:
                user.set_meta('phone', telefone)
                dbsession.commit()
        else:
            r = {
                'status':
                'nok',
                'message':
                u'É necessário informar uma senha ou dados para cadastro.'
            }
Example #22
0
def api_obras():
	obras = fromcache("obras-monitoramento") or tocache("obras-monitoramento", _get_obras())
	return Response(dumps(obras),content_type="application/json")
Example #23
0
def selected_buzz(aid):
    """Returns the selected buzz of an audience in JSON format"""
    buzz = AudiencePosts.query.get(aid).get_selected_buzz()
    return dumps([notice.to_dict() for notice in buzz])
Example #24
0
			else:
				#Contribuição somente texto
				print "TEXTO <-------------"
				new_post_id = wordpress.wp.newPost(
					post_title    = request.form['titulo'],
					post_type     = "gdobra",
					post_parent   = ultimo_status['id'],
					post_author   = author_id, #int
					post_content  = request.form['conteudo'],
					post_status   = status,
					post_format   = "video" if request.files else "aside"
				)


	return dumps(r)

#=================================================================== ENVIO DE AVISOS DE ATUALIZAÇÕES

@monitoramento.route('/sendnews')
def sendnews():
	"""Método que faz o envio dos avisos para as pessoas que seguem as obras"""

	if "obra" in request.args:
		obraid = request.args['obra']
		obra = fromcache("obra-" + obraid) or tocache("obra-" + obraid, _get_obras(obraid=obraid)[0])
	elif "slug" in request.args:
		slug = request.args['slug']
		obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0])
		obraid = obra['id']
	else:
Example #25
0
def last_published(aid):
    """Returns the last published notice of an audience"""
    notice = AudiencePosts.get(aid).get_last_published_notice()
    return dumps(notice and notice.to_dict() or None)
Example #26
0
def selected_buzz(aid):
    """Returns the selected buzz of an audience in JSON format"""
    buzz = AudiencePosts.query.get(aid).get_selected_buzz()
    return dumps([notice.to_dict() for notice in buzz])
Example #27
0
def public_buzz(aid):
    """Returns the public buzz of an audience in JSON format"""
    buzz = AudiencePosts.query.get(aid).get_public_buzz(0, 10)
    return dumps([notice.to_dict() for notice in buzz])
Example #28
0
def public_buzz(aid):
    """Returns the public buzz of an audience in JSON format"""
    buzz = AudiencePosts.query.get(aid).get_public_buzz(0, 10)
    return dumps([notice.to_dict() for notice in buzz])
Example #29
0
def vote(obraid, slug, plus):
    """
	O controle do voto é como segue:
	 - obraid = É o id do item da timeline (post-filho) que está sendo votado
	 - slug   = É um md5 criado através do slug do post-filho
	 - plus   = É um md5 criado através do obraid juntamente com:
	            ->  1 se for para somar voto
	            -> -1 se for para dominuir voto
	"""

    ret = {}

    post = wordpress.getCustomPost(obraid, 'gdobra')

    # print "Post", post['id'], post['post_type']

    post_slug = md5(post['slug']).hexdigest()
    slugok = True if post_slug == slug else False
    # print "SLUG===", slug, type(post_slug), post['slug'], type(post['slug'])

    md5_plus = md5(obraid + '1').hexdigest()
    md5_down = md5(obraid + '-1').hexdigest()
    vote_plus = True if md5_plus == plus else False
    vote_down = True if md5_down == plus else False

    # print "PLUS===", plus, md5_plus
    # print "DOWN===", plus, md5_down

    # print "Votando", slugok, vote_plus, vote_down

    item = "gdobra_"
    itemup = item + "voto_up"
    itemdown = item + "voto_down"
    itemscore = item + "voto_score"
    itemvoted = item + "users_voted"

    if 'custom_fields' in post:
        cfs = post['custom_fields']

        # print "Custom Fields", [ f['value'] for f in cfs if f['key'] == itemvoted]

        score = [int(f['value']) for f in cfs if f['key'] == itemscore]
        votosup = [int(f['value']) for f in cfs if f['key'] == itemup]
        votosdown = [int(f['value']) for f in cfs if f['key'] == itemdown]
        users_voted = [f['value'] for f in cfs if f['key'] == itemvoted]

        score = score[0] if score else 0
        votosup = votosup[0] if votosup else 0
        votosdown = votosdown[0] if votosdown else 0
        users_voted = users_voted[0] if users_voted else ""

        if vote_plus:
            score += 1
            votosup += 1
        else:
            score -= 1
            votosdown += 1

        ret['score'] = score

        feito = ""
        newcfs = []
        for cf in cfs:
            if cf['key'] == itemscore:
                cf['value'] = score
                feito += ",%s" % itemscore
                newcfs.append(cf)
            if cf['key'] == itemup:
                cf['value'] = votosup
                feito += ",%s" % itemup
                newcfs.append(cf)
            if cf['key'] == itemdown:
                cf['value'] = votosdown
                feito += ",%s" % itemdown
                newcfs.append(cf)
        if itemscore not in feito:
            newcfs.append({'key': itemscore, 'value': score})
        if itemup not in feito:
            newcfs.append({'key': itemup, 'value': votosup})
        if itemdown not in feito:
            newcfs.append({'key': itemdown, 'value': votosdown})

        # print "Custom Fields OK", newcfs

        #Grava o usuário que votou
        users_voted = users_voted + authapi.authenticated_user().username + ","
        newcfs.append({'key': itemvoted, 'value': users_voted})

        # edit_post_id = wordpress.wp.editPost(
        # 	post_id=post['id'],
        # 	custom_fields = cfs
        # )
        edit_post_id = wordpress.exapi.setPostCustomFields(post['id'], newcfs)

    return dumps(ret)
Example #30
0
def page_json(path):
    """Returns a page data in the JSON format"""
    page = wordpress.getPageByPath(path)
    return dumps(page and page.data or None)
Example #31
0
def all_buzz(aid):
    """Returns the last published notice of an audience"""
    public_all = AudiencePosts.query.get(aid).get_all_buzz()
    buzz = {'public_all': [notice.to_dict() for notice in public_all]}
    return dumps(buzz)
Example #32
0
def last_published(aid):
    """Returns the last published notice of an audience"""
    notice = AudiencePosts.get(aid).get_last_published_notice()
    return dumps(notice and notice.to_dict() or None)
Example #33
0
 def public_json(self):
     """Returns the same content as `public_dict()', but in JSON
     format"""
     return dumps(self.public_dict())
Example #34
0
def vote(obraid, slug, plus):
	"""
	O controle do voto é como segue:
	 - obraid = É o id do item da timeline (post-filho) que está sendo votado
	 - slug   = É um md5 criado através do slug do post-filho
	 - plus   = É um md5 criado através do obraid juntamente com:
	            ->  1 se for para somar voto
	            -> -1 se for para dominuir voto
	"""

	ret = {}

	post = wordpress.getCustomPost(obraid, 'gdobra')

	# print "Post", post['id'], post['post_type']

	post_slug = md5(post['slug']).hexdigest()
	slugok = True if post_slug == slug else False
	# print "SLUG===", slug, type(post_slug), post['slug'], type(post['slug'])

	md5_plus = md5(obraid + '1').hexdigest()
	md5_down = md5(obraid + '-1').hexdigest()
	vote_plus = True if md5_plus == plus else False
	vote_down = True if md5_down == plus else False

	# print "PLUS===", plus, md5_plus
	# print "DOWN===", plus, md5_down

	# print "Votando", slugok, vote_plus, vote_down

	item      = "gdobra_"
	itemup    = item+"voto_up"
	itemdown  = item+"voto_down"
	itemscore = item+"voto_score"
	itemvoted = item+"users_voted"

	if 'custom_fields' in post:
		cfs = post['custom_fields']

		# print "Custom Fields", [ f['value'] for f in cfs if f['key'] == itemvoted]

		score = [ int(f['value']) for f in cfs if f['key'] == itemscore]
		votosup = [ int(f['value']) for f in cfs if f['key'] == itemup]
		votosdown = [ int(f['value']) for f in cfs if f['key'] == itemdown]
		users_voted = [ f['value'] for f in cfs if f['key'] == itemvoted]

		score = score[0] if score else 0
		votosup = votosup[0] if votosup else 0
		votosdown = votosdown[0] if votosdown else 0
		users_voted = users_voted[0] if users_voted else ""

		if vote_plus:
			score += 1
			votosup += 1
		else:
			score -= 1
			votosdown += 1

		ret['score'] = score

		feito = ""
		newcfs = []
		for cf in cfs :
			if cf['key'] == itemscore:
				cf['value'] = score
				feito+=",%s" % itemscore
				newcfs.append(cf)
			if cf['key'] == itemup:
				cf['value'] = votosup
				feito+=",%s" % itemup
				newcfs.append(cf)
			if cf['key'] == itemdown:
				cf['value'] = votosdown
				feito+=",%s" % itemdown
				newcfs.append(cf)
		if itemscore not in feito:
			newcfs.append({'key':itemscore, 'value':score})
		if itemup not in feito:
			newcfs.append({'key':itemup, 'value':votosup})
		if itemdown not in feito:
			newcfs.append({'key':itemdown, 'value':votosdown})

		# print "Custom Fields OK", newcfs

		#Grava o usuário que votou
		users_voted = users_voted + authapi.authenticated_user().username + ","
		newcfs.append({'key':itemvoted, 'value':users_voted})

		# edit_post_id = wordpress.wp.editPost(
		# 	post_id=post['id'],
		# 	custom_fields = cfs
		# )
		edit_post_id = wordpress.exapi.setPostCustomFields(post['id'], newcfs)

	return dumps(ret)
Example #35
0
                        'O arquivo enviado não é permitido. Use apenas arquivos PNG ou JPG.'
                    }

            else:
                #Contribuição somente texto
                print "TEXTO <-------------"
                new_post_id = wordpress.wp.newPost(
                    post_title=request.form['titulo'],
                    post_type="gdobra",
                    post_parent=ultimo_status['id'],
                    post_author=author_id,  #int
                    post_content=request.form['conteudo'],
                    post_status=status,
                    post_format="video" if request.files else "aside")

    return dumps(r)


#=================================================================== ENVIO DE AVISOS DE ATUALIZAÇÕES


@monitoramento.route('/sendnews')
def sendnews():
    """Método que faz o envio dos avisos para as pessoas que seguem as obras"""

    if "obra" in request.args:
        obraid = request.args['obra']
        obra = fromcache("obra-" + obraid) or tocache(
            "obra-" + obraid,
            _get_obras(obraid=obraid)[0])
    elif "slug" in request.args:
Example #36
0
def contribui(slug):

	obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0])
	if not obra:
		return abort(404)

	r = {'status':'ok', 'message':'Sua contibuição foi aceita com sucesso'}
	user_recent = False
	if not authapi.is_authenticated():
		# r = {'status':'not_logged'}
		"""
		Se não está autenticado, tenta achar o usuário pelo email, e
		acessar com a senha inserida no formulario.
		Se não, cadastra o camarada, com o nome e email informados, gerando
		uma senha para ele e enviando o email de boas vindas.
		"""
		email = request.form['email']

		if request.form['senha']:
			#Informou a senha do cadastro já existente
			# username = email
			# senha = request.form['senha']
			#Efetua o login
			print "Usuario e senha informado... logando!"
			username = request.values.get('email')
			senha = request.values.get('senha')
			print "tentando logar com", username, senha
			try:
				user = authapi.login(username, senha)
				r = {'status':'ok', 'message':'Sua contibuição foi aceita com sucesso', 'refresh': True}
			except authapi.UserNotFound:
				r = {'status':'nok', 'message':_(u'Wrong user or password')}
				return dumps(r)
			except authapi.UserAndPasswordMissmatch:
				r = {'status':'nok', 'message':_(u'Wrong user or password')}
				return dumps(r)
		elif request.form['nome']:
			print "Nome informado... cadastrando..."
			#Informou a senha para cadastro
			nome = request.form['nome']
			telefone = request.form['telefone'] if 'telefone' in request.form else ""
			novasenha = request.form['newPassword'] if 'newPassword' in request.form else ""

			if not novasenha:
				# novasenha = "gabinetedigital"
				novasenha = ''.join(random.choice(string.printable) for x in range(8))

			# print nome, '-', email, '-', novasenha

			try:
				user = authapi.create_user(nome, email, unicode(novasenha), email)
				r = {'status':'ok', 'message':'Sua contibuição foi aceita com sucesso. Verifique seu email para confirmar o cadastro.'}
				user_recent = True
				send_welcome_email(user)
				send_password(user.email, novasenha)
			except authapi.UserExistsUnconfirmed, e:
				r = {'status':'nok', 'message':u'Seu usuário precisa ser confirmado, veja seu email!'}
				return dumps(r)

			if telefone:
				user.set_meta('phone', telefone)
				dbsession.commit()
		else:
			r = {'status':'nok', 'message':u'É necessário informar uma senha ou dados para cadastro.'}
Example #37
0
File: sio.py Project: calcwb/gd
 def send(self, message, data):
     """Sends a message to all connected clients"""
     self.app.server.send(dumps({ 'message': message, 'data': data }))
Example #38
0
 def send(self, message, data):
     """Sends a message to all connected clients"""
     self.app.server.send(dumps({'message': message, 'data': data}))
Example #39
0
def api_obras():
    obras = fromcache("obras-monitoramento") or tocache(
        "obras-monitoramento", _get_obras())
    return Response(dumps(obras), content_type="application/json")