Exemplo n.º 1
0
def timelineitem(slug, itemid):
	obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0])
	if not obra:
		return abort(404)

	cacheid = "obratl%s-%s"%(obra['id'],itemid)
	timeline = fromcache(cacheid) or tocache(cacheid, wordpress.monitoramento.getObraTimeline(obra['id'], int(itemid) ))
	timeline = adjustCf(timeline)
	update = timeline[0]

	menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
	howto = fromcache('howtoobras') or tocache('howtoobras',wordpress.getPageByPath('howto-obras'))
	tos = fromcache('tosobras') or tocache('tosobras',wordpress.getPageByPath('tos-obras'))
	try:
		twitter_hash_cabecalho = twitts()
	except KeyError:
		twitter_hash_cabecalho = ""

	return render_template('timeline-item.html',
		menu=menus,
		obra=obra,
		howto=howto,
		tos=tos,
		update=update,
		twitter_hash_cabecalho=twitter_hash_cabecalho
	)
Exemplo n.º 2
0
def resultados(ano=2012):
    """Renders a wordpress page special"""
    cn = 'results-{0}'.format(ano)
    slideshow = fromcache(cn) or tocache(cn,wordpress.getRecentPosts(
        category_name='destaque-govpergunta-%s' % str(ano),
        post_status='publish',
        numberposts=4,
        thumbsizes=['slideshow']))

    categoria = 'resultados-gov-pergunta-%s' % str(ano)
    retorno = fromcache("contribs-{0}".format(ano)) or \
              tocache("contribs-{0}".format(ano) ,wordpress.wpgovp.getContribuicoes(principal='S',category=categoria))

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    questions = None
    for q in retorno:
        if isinstance(q, list):
            questions = q
    return render_template(
        'resultados.html',
        menu=menus,
        questions=questions,
        sidebar=wordpress.getSidebar,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        ano=ano,
        slideshow=slideshow,
        wp=wordpress
    )
Exemplo n.º 3
0
Arquivo: videos.py Projeto: clarete/gd
def canal(categoria_id):
    categories = fromcache("all_videos_categories") or tocache(
        "all_videos_categories", wordpress.wpgd.getVideosCategories())

    page = int(request.args.get('page') or 1)
    page -= 1
    # print "Carregando pagina", page

    # print categories
    nome_canal = ""
    for cat in categories:
        if int(cat['term_id']) == categoria_id:
            nome_canal = cat['name']
            break

    videos_json = {}
    allvideos = fromcache("all_videos_root") or tocache(
        "all_videos_root",
        treat_categories(wordpress.wpgd.getVideos(where='status=true'),
                         orderby='title'))
    for v in allvideos:
        videos_json[v['title']] = v['id']

    # print "Buscando", current_app.config['VIDEO_PAGINACAO'], "vídeos por página!"
    cacheid = "videos_canal_%s_page_%s" % (str(categoria_id), page)
    cacheidall = "videos_canal_%s" % str(categoria_id)
    pagging = int(current_app.config['VIDEO_PAGINACAO'])
    offset = page * pagging

    allvideos_cat = fromcache(cacheidall) or tocache(
        cacheidall,
        treat_categories(
            wordpress.wpgd.getVideosByCategory(category=categoria_id)))

    # print "PAGINACAO", len(allvideos_cat), page, pagging, offset
    page_total = int(round(Decimal(len(allvideos_cat)) / pagging))

    videos = fromcache(cacheid) or tocache(
        cacheid,
        paginate(
            treat_categories(wordpress.wpgd.getVideosByCategory(
                category=categoria_id, ),
                             orderby='date'), pagging, offset))

    hvideos = fromcache("h_videos_root") or tocache(
        "h_videos_root", treat_categories(
            wordpress.wpgd.getHighlightedVideos()))

    return render_template(
        'videos.html',
        videos=videos,
        titulos=videos_json,
        categories=categories,
        hvideos=hvideos,
        canal=nome_canal,
        canalclass="fa fa-th-large",
        page=page + 1,
        page_total=page_total,
        sidebar=wordpress.getSidebar,
    )
Exemplo n.º 4
0
def artigo_hierarquico(slug):
    """Renders a wordpress page special"""
    path = slug
    post_type = 'artigo-herarquico'
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    post = fromcache("artigo-%s" % slug) or tocache("artigo-%s" % slug, wordpress.getCustomPostByPath(post_type,path))

    # print '===================================================='
    # print post
    # print '===================================================='

    if not post['id']:
        return abort(404)

    total_artigos = []
    total_comentarios = []
    comentarios_separados = []
    add_filhos_and_comments_to_post(post_type, post, total_artigos, total_comentarios, comentarios_separados)

    HABILITAR_SANFONA="false"
    HABILITAR_ABAS="false"
    HABILITAR_COMENTARIO_MESTRE="false"
    HABILITAR_COMENTARIO_FILHOS="false"

    TEMPLATE = "artigo_hierarquico.html"
    for cf in post['custom_fields']:
        if cf['key'] == 'artigo_hierarquico_comentario_master' and cf['value'] == '1':
           HABILITAR_COMENTARIO_MESTRE = 'true'
        if cf['key'] == 'artigo_hierarquico_comentarios_filhos' and cf['value'] == '1':
           HABILITAR_COMENTARIO_FILHOS = 'true'
        if cf['key'] == 'artigo_hierarquico_sanfona' and cf['value'] == '1':
           HABILITAR_SANFONA = 'true'
        if cf['key'] == 'artigo_hierarquico_abas' and cf['value'] == '1':
           HABILITAR_ABAS = 'true'
           TEMPLATE = "artigo_hierarquico_aba.html"

    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )

    return render_template(
        TEMPLATE,
        post=post,
        wp=wordpress,
        total_artigos=sum(total_artigos),
        total_comentarios=sum(total_comentarios),
        todos_comentarios=comentarios_separados,
        sidebar=wordpress.getSidebar,
        HABILITAR_SANFONA=HABILITAR_SANFONA,
        HABILITAR_ABAS=HABILITAR_ABAS,
        HABILITAR_COMENTARIO_MESTRE=HABILITAR_COMENTARIO_MESTRE,
        HABILITAR_COMENTARIO_FILHOS=HABILITAR_COMENTARIO_FILHOS,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        show_comment_form=is_authenticated(),
        categoria_contribuicao_text=categoria_contribuicao_text
        ,menu=menus
    )
Exemplo n.º 5
0
def details(vid):
    video = fromcache("video_%s" % str(vid))

    if not video:
        # print "Video do wordpress...", vid
        video = tocache("video_%s" % str(vid), treat_categories(wordpress.wpgd.getVideo(vid))[0] )

    sources = fromcache("video_src_%s" % str(vid)) or tocache("video_src_%s" % str(vid),wordpress.wpgd.getVideoSources(vid))

    base_url = current_app.config['BASE_URL']
    base_url = base_url if base_url[-1:] != '/' else base_url[:-1] #corta a barra final
    video_sources = {}
    for s in sources:
        if(s['format'].find(';') > 0):
            f = s['format'][0:s['format'].find(';')]
        else:
            f = s['format']
        video_sources[f] = s['url']
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    return render_template('video.html', video=video, sources=video_sources
        ,menu=menus
        ,twitter_hash_cabecalho=twitter_hash_cabecalho
        ,base_url=base_url, sidebar=wordpress.getSidebar,)
Exemplo n.º 6
0
def timelineitem(slug, itemid):
    obra = fromcache("obra-" + slug) or tocache("obra-" + slug,
                                                _get_obras(slug)[0])
    if not obra:
        return abort(404)

    cacheid = "obratl%s-%s" % (obra['id'], itemid)
    timeline = fromcache(cacheid) or tocache(
        cacheid,
        wordpress.monitoramento.getObraTimeline(obra['id'], int(itemid)))
    timeline = adjustCf(timeline)
    update = timeline[0]

    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    howto = fromcache('howtoobras') or tocache(
        'howtoobras', wordpress.getPageByPath('howto-obras'))
    tos = fromcache('tosobras') or tocache(
        'tosobras', wordpress.getPageByPath('tos-obras'))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    return render_template('timeline-item.html',
                           menu=menus,
                           obra=obra,
                           howto=howto,
                           tos=tos,
                           update=update,
                           twitter_hash_cabecalho=twitter_hash_cabecalho)
Exemplo n.º 7
0
def resultados(ano=2012):
    """Renders a wordpress page special"""
    cn = 'results-{0}'.format(ano)
    slideshow = fromcache(cn) or tocache(
        cn,
        wordpress.getRecentPosts(
            category_name='destaque-govpergunta-%s' % str(ano),
            post_status='publish',
            numberposts=4,
            thumbsizes=['slideshow']))

    categoria = 'resultados-gov-pergunta-%s' % str(ano)
    retorno = fromcache("contribs-{0}".format(ano)) or \
              tocache("contribs-{0}".format(ano) ,wordpress.wpgovp.getContribuicoes(principal='S',category=categoria))

    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    questions = None
    for q in retorno:
        if isinstance(q, list):
            questions = q
    return render_template('resultados.html',
                           menu=menus,
                           questions=questions,
                           sidebar=wordpress.getSidebar,
                           twitter_hash_cabecalho=twitter_hash_cabecalho,
                           ano=ano,
                           slideshow=slideshow,
                           wp=wordpress)
Exemplo n.º 8
0
def index(page=0):
    sortby = request.values.get('sortby') or 'date'
    pagination, posts = fromcache('govescuta-posts-%s' % sortby) or \
                        tocache('govescuta-posts-%s' %sortby,
                                    wordpress.wpgove.getAudiencias(
                                            page=page,
                                            sortby=sortby,
                                            totalporpage='10'))
    how_to = fromcache('howtouse') or tocache('howtouse', wordpress.getPageByPath('how-to-use-governo-escuta'))

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = twitts()
    except:
        twitter_hash_cabecalho = ""

    return render_template(
        'govescuta.html',
        menu=menus,
        # sidebar=wordpress.getSidebar,
        pagination=pagination,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        audiences=posts,
        sortby=sortby,
        how_to=getattr(how_to, 'content', ''),)
Exemplo n.º 9
0
def news(page=0):
    """List posts in chronological order"""
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))

    pagination, posts = fromcache('pag_posts_%s' % page) or tocache(
        "pag_posts_%s" % page,
        wordpress.getPosts(page=page, thumbsizes=['newsbox', 'widenewsbox']))

    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)

    psearch = _format_postsearch(posts)
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    return render_template(
        'archive.html',
        sidebar=wordpress.getSidebar,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        # picday=picday,
        pagination=pagination,
        menu=menus,
        posts=psearch)
Exemplo n.º 10
0
def index(page=0):
    sortby = request.values.get('sortby') or 'date'
    pagination, posts = fromcache('govescuta-posts-%s' % sortby) or \
                        tocache('govescuta-posts-%s' %sortby,
                                    wordpress.wpgove.getAudiencias(
                                            page=page,
                                            sortby=sortby,
                                            totalporpage='10'))
    how_to = fromcache('howtouse') or tocache(
        'howtouse', wordpress.getPageByPath('how-to-use-governo-escuta'))

    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        twitter_hash_cabecalho = twitts()
    except:
        twitter_hash_cabecalho = ""

    return render_template(
        'govescuta.html',
        menu=menus,
        # sidebar=wordpress.getSidebar,
        pagination=pagination,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        audiences=posts,
        sortby=sortby,
        how_to=getattr(how_to, 'content', ''),
    )
Exemplo n.º 11
0
def tag(slug, page=0):
    """List posts of a given tag"""
    pagination, posts = fromcache(
        "pag_posts_tag_%s_%s" % (slug, page)) or tocache(
            "pag_posts_tag_%s_%s" %
            (slug, page), wordpress.getPostsByTag(tag=slug, page=page))
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))

    psearch = _format_postsearch(posts)
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    return render_template(
        'archive.html',
        sidebar=wordpress.getSidebar,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        # picday=picday,
        pagination=pagination,
        posts=psearch,
        menu=menus)
Exemplo n.º 12
0
def conselho():
    """Renders a wordpress page special"""
    path = 'conselho-comunicacao'
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    page = fromcache("page-%s" % path) or tocache(
        "page-%s" % path, wordpress.getPageByPath(path))
    cmts = fromcache("cmts-page-%s" % path) or tocache(
        "cmts-page-%s" % path,
        wordpress.getComments(
            status='approve', post_id=page.data['id'], number=1000))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    return render_template(
        'post.html',
        post=page,
        sidebar=wordpress.getSidebar,
        # picday=picday,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        comments=cmts,
        show_comment_form=is_authenticated(),
        categoria_contribuicao_text=categoria_contribuicao_text,
        menu=menus)
Exemplo n.º 13
0
def post(pid):
    try:
        p = fromcache("post-%s" % str(pid)) or tocache("post-%s" % str(pid),wordpress.getPost(pid))
    except:
        return abort(404)
    """View that renders a post template"""
    recent_posts = fromcache("recent_posts") or tocache("recent_posts", wordpress.getRecentPosts(
        post_status='publish',
        numberposts=4))
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    cmts = fromcache("comentarios%s" % str(pid)) or tocache("comentarios%s" % str(pid),  wordpress.getComments(status='approve',post_id=pid))
    tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud())
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    # live_comment_ = request.cookies.get('live_comment_save')
    return render_template(
        'post.html',
        post=p,
        tags=tags,
        sidebar=wordpress.getSidebar,
        # live_comment_save=live_comment_,
        # picday=picday,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        menu=menus,
        comments=cmts,
        show_comment_form=is_authenticated(),
        recent_posts=recent_posts)
Exemplo n.º 14
0
def listing():

    page = int(request.args.get('page') or 1)
    page -= 1

    # page = wordpress.wpgd.getHighlightedVideos()
    hvideos = fromcache("h_videos_root") or tocache("h_videos_root",
        treat_categories(wordpress.wpgd.getHighlightedVideos()) )

    # print "========================================================"
    # print dir(request)
    # print request.url
    # print request.url_rule
    # print "========================================================"

    canalclass=""
    if 'populares' in str(request.url_rule):
        order = "views" #recents
        nome_canal = "Populares"
        canalclass="fa-star"
    else :
        order = "date"
        nome_canal = "Recentes"
        canalclass="fa fa-clock-o"

    order_by = "%s desc" % order

    videos_json = {}
    allvideos = fromcache("all_videos_root_") or \
                tocache("all_videos_root_" ,
                        treat_categories(wordpress.wpgd.getVideos(where='status=true'), orderby="date") )

    categories = fromcache("all_videos_categories") or \
        tocache("all_videos_categories",wordpress.wpgd.getVideosCategories())

    for v in allvideos:
        videos_json[v['title']] = v['id']

    # print "Buscando", current_app.config['VIDEO_PAGINACAO'], "vídeos por página!"
    cacheid = "videos_root_%s_page_%s" % (order,page)
    pagging = int(current_app.config['VIDEO_PAGINACAO'])
    offset = page * pagging
    page_total = int( round( Decimal( len(allvideos) ) / pagging ) )
    # print "PAGINACAO", len(allvideos), page, pagging, offset
    videos = fromcache(cacheid) or tocache(cacheid,
        paginate(treat_categories(wordpress.wpgd.getVideos(where='v.status=true'),orderby=order_by), pagging, offset) )

    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    return render_template('videos.html', videos=videos
        ,twitter_hash_cabecalho=twitter_hash_cabecalho
        ,menu=menus, titulos=videos_json, categories=categories, hvideos=hvideos
        ,canal=nome_canal, canalclass=canalclass, page=page+1, page_total=page_total,
        sidebar=wordpress.getSidebar,)
Exemplo n.º 15
0
def post_slug(slug):
    try:
        post = fromcache("post-%s" % slug) or tocache(
            "post-%s" % slug, wordpress.getPostByPath(slug))
        if not post['id']:
            abort(404)
    except:
        abort(404)

    print '=============================================================================='
    print post
    print '=============================================================================='

    pid = post['id']

    if 'the_date' not in post.keys():
        # post['the_date'] = post['date']['date'].value
        post['the_date'] = datetime.datetime.strptime(
            post['date']['date'].value, '%Y%m%dT%H:%M:%S')
    """View that renders a post template"""
    recent_posts = fromcache("recent_posts") or tocache(
        "recent_posts",
        wordpress.getRecentPosts(post_status='publish', numberposts=4))
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    # cmts = fromcache("comentarios_post_slug-%s"%slug) or tocache("comentarios_post_slug-%s"%slug, wordpress.getComments(status='approve',post_id=pid))
    tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud())
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    # live_comment_ = request.cookies.get('live_comment_save')
    # if live_comment_:
    #     live_comment_ = live_comment_.replace('<br/>','\n')

    resp = make_response(
        render_template(
            'post.html',
            post=post,
            tags=tags,
            # live_comment_save=live_comment_,
            sidebar=wordpress.getSidebar,
            # picday=picday,
            twitter_hash_cabecalho=twitter_hash_cabecalho,
            menu=menus,
            base_url=app.config['BASE_URL'],
            # comments=cmts,
            show_comment_form=is_authenticated(),
            recent_posts=recent_posts))
    # resp.set_cookie('live_comment_save', "" )
    return resp
Exemplo n.º 16
0
def adjustCf(obras):
    """#Trata o retorno dos custom_fields para facilitar a utilizacao"""
    r_obras = []
    for obra in obras:
        if obra['custom_fields']:
            custom_fields = {}
            for cf in obra['custom_fields']:
                valor = cf['value']
                #=== tratamento especial para alguns custom fields
                if cf['key'] == 'gdvideo':
                    vid = valor
                    video = fromcache("video_%s" % str(vid)) or tocache(
                        "video_%s" % str(vid),
                        treat_categories(wordpress.wpgd.getVideo(vid))[0])
                    sources = fromcache("video_src_%s" % str(vid)) or tocache(
                        "video_src_%s" % str(vid),
                        wordpress.wpgd.getVideoSources(vid))
                    # print "SOURCES===", sources

                    base_url = current_app.config['BASE_URL']
                    base_url = base_url if base_url[
                        -1:] != '/' else base_url[:-1]  #corta a barra final
                    video_sources = {}
                    for s in sources:
                        if (s['format'].find(';') > 0):
                            f = s['format'][0:s['format'].find(';')]
                        else:
                            f = s['format']
                        video_sources[f] = s['url']
                    video['sources'] = video_sources
                    # print "SOURCES===", video_sources
                    valor = video

                if cf['key'] in ('gdobra_municipio'):
                    #Deixa somente os nomes das empresas contratadas
                    valor = [x[1:-1] for x in re.findall('\".+?\"', valor)]

                if cf['key'] in ('gdobra_empresa_contratada'):
                    #Deixa somente os nomes das empresas contratadas
                    if '{' in valor:
                        valor = [x[1:-1] for x in re.findall('\".+?\"', valor)]
                    else:
                        valor = [valor]

                if cf['key'] == 'gdobra_coordenadas':
                    # print "LLLLLLLL", "[" + valor + "]"
                    valor = re.findall("([\+-].\d+.\d+,[\+-].\d+.\d+)", valor)

                custom_fields[cf['key']] = valor
            del obra['custom_fields']
            obra['custom_fields'] = custom_fields
        r_obras.append(obra)

    return r_obras
Exemplo n.º 17
0
def embed(vid):
    video = fromcache("video_%s" % str(vid)) or tocache("video_%s" % str(vid), treat_categories(wordpress.wpgd.getVideo(vid))[0])
    sources = fromcache("video_src_%s" % str(vid)) or tocache("video_src_%s" % str(vid),wordpress.wpgd.getVideoSources(vid))
    video_sources = {}
    for s in sources:
        if(s['format'].find(';') > 0):
            f = s['format'][0:s['format'].find(';')]
        else:
            f = s['format']
        video_sources[f] = s['url']
    return render_template('videoembed.html', video=video, sources=video_sources)
Exemplo n.º 18
0
def index():
    # app.logger.error( " ######################################################################## BASE " )
    """Renders the index template"""
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        vote_url = app.config['VOTACAO_URL']
    except KeyError:
        vote_url = ""
    try:
        vote_root = app.config['VOTACAO_ROOT']
    except KeyError:
        vote_root = ""
    try:
        vote_altura = app.config['VOTACAO_ALTURA']
    except KeyError:
        vote_altura = ""

    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    # pagepri = fromcache('pagepri')      or tocache('pagepri', wordpress.getPageByPath('prioridades'))
    pagepq = fromcache('pagepq') or tocache('pagepq',
                                            wordpress.getPageByPath('por-que'))
    # pageproc = fromcache('pageproc')    or tocache('pageproc', wordpress.getPageByPath('processo'))
    pagevot = fromcache('pagevot') or tocache(
        'pagevot', wordpress.getPageByPath('votacao'))
    pagehow = fromcache('pagehow') or tocache(
        'pagehow', wordpress.getPageByPath('como-funciona'))
    pageseg = fromcache('pageseg') or tocache(
        'pageseg', wordpress.getPageByPath('seguranca-2'))
    # pagesobre = fromcache('pagesobre')  or tocache('pagesobre', wordpress.getPageByPath('sobre'))

    return render_template(
        'index.html',
        wp=wordpress,
        sidebar=wordpress.getSidebar,
        # page_about=pagesobre,
        # page_pri=pagepri,
        page_pq=pagepq,
        pagevot=pagevot,
        # page_pro=pageproc,
        page_como=pagehow,
        page_seg=pageseg,
        menu=menus,
        reforma_voted=request.cookies.get('reforma_voted') or False,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        VOTACAO_URL=vote_url,
        VOTACAO_ROOT=vote_root,
        VOTACAO_ALTURA=vote_altura,
    )
Exemplo n.º 19
0
def post_slug(slug):
    try:
        post = fromcache("post-%s" % slug) or tocache("post-%s" % slug, wordpress.getPostByPath(slug))
        if not post['id']:
            abort(404)
    except:
        abort(404)

    print '=============================================================================='
    print post
    print '=============================================================================='

    pid = post['id']

    if 'the_date' not in post.keys():
        # post['the_date'] = post['date']['date'].value
        post['the_date'] = datetime.datetime.strptime(post['date']['date'].value,'%Y%m%dT%H:%M:%S')

    """View that renders a post template"""
    recent_posts = fromcache("recent_posts") or tocache("recent_posts", wordpress.getRecentPosts(
        post_status='publish',
        numberposts=4))
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    # cmts = fromcache("comentarios_post_slug-%s"%slug) or tocache("comentarios_post_slug-%s"%slug, wordpress.getComments(status='approve',post_id=pid))
    tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud())
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    # live_comment_ = request.cookies.get('live_comment_save')
    # if live_comment_:
    #     live_comment_ = live_comment_.replace('<br/>','\n')

    resp = make_response(
     render_template(
        'post.html',
        post=post,
        tags=tags,
        # live_comment_save=live_comment_,
        sidebar=wordpress.getSidebar,
        # picday=picday,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        menu=menus,
        base_url=app.config['BASE_URL'],
        # comments=cmts,
        show_comment_form=is_authenticated(),
        recent_posts=recent_posts)
    )
    # resp.set_cookie('live_comment_save', "" )
    return resp
Exemplo n.º 20
0
def sobre_gd():
    pagesobre = fromcache('pagesobre')  or tocache('pagesobre', wordpress.getPageByPath('sobre'))
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'sobre.html', wp=wordpress,
        menu=menus,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        sidebar=wordpress.getSidebar,
        page_about=pagesobre
    )
Exemplo n.º 21
0
def addview(vid):
    video = fromcache("video_%s" % str(vid))
    if not video:
        video = tocache("video_%s" % str(vid), treat_categories(wordpress.wpgd.getVideo(vid))[0])

    if 'views' in video:
        video['views'] = int(video['views']) + 1
    else:
        video['views'] = 1

    removecache("video_%s" % str(vid))
    tocache("video_%s" % str(vid), video)
    wordpress.wpgd.setVideoViews(video['views'], vid);
    return "ok"
Exemplo n.º 22
0
def adjustCf(obras):
	"""#Trata o retorno dos custom_fields para facilitar a utilizacao"""
	r_obras = []
	for obra in obras:
		if obra['custom_fields']:
			custom_fields = {}
			for cf in obra['custom_fields']:
				valor = cf['value']
				#=== tratamento especial para alguns custom fields
				if cf['key'] == 'gdvideo':
					vid = valor
					video = fromcache("video_%s" % str(vid)) or tocache("video_%s" % str(vid), treat_categories(wordpress.wpgd.getVideo(vid))[0])
					sources = fromcache("video_src_%s" % str(vid)) or tocache("video_src_%s" % str(vid),wordpress.wpgd.getVideoSources(vid))
					# print "SOURCES===", sources

					base_url = current_app.config['BASE_URL']
					base_url = base_url if base_url[-1:] != '/' else base_url[:-1] #corta a barra final
					video_sources = {}
					for s in sources:
					    if(s['format'].find(';') > 0):
					        f = s['format'][0:s['format'].find(';')]
					    else:
					        f = s['format']
					    video_sources[f] = s['url']
					video['sources'] = video_sources
					# print "SOURCES===", video_sources
					valor = video


				if cf['key'] in ( 'gdobra_municipio' ):
					#Deixa somente os nomes das empresas contratadas
					valor = [ x[1:-1] for x in re.findall('\".+?\"',valor) ]

				if cf['key'] in ( 'gdobra_empresa_contratada' ):
					#Deixa somente os nomes das empresas contratadas
					if '{' in valor:
						valor = [ x[1:-1] for x in re.findall('\".+?\"',valor) ]
					else:
						valor = [valor]

				if cf['key'] == 'gdobra_coordenadas' :
					# print "LLLLLLLL", "[" + valor + "]"
					valor = re.findall("([\+-].\d+.\d+,[\+-].\d+.\d+)", valor)

				custom_fields[cf['key']] = valor
			del obra['custom_fields']
			obra['custom_fields'] = custom_fields
		r_obras.append(obra)

	return r_obras
Exemplo n.º 23
0
Arquivo: videos.py Projeto: clarete/gd
def addview(vid):
    video = fromcache("video_%s" % str(vid))
    if not video:
        video = tocache("video_%s" % str(vid),
                        treat_categories(wordpress.wpgd.getVideo(vid))[0])

    if 'views' in video:
        video['views'] = int(video['views']) + 1
    else:
        video['views'] = 1

    removecache("video_%s" % str(vid))
    tocache("video_%s" % str(vid), video)
    wordpress.wpgd.setVideoViews(video['views'], vid)
    return "ok"
Exemplo n.º 24
0
def twitts():
    result = fromcache("twetts_cabecalho")
    if not result:
        t = Twython(conf.TWITTER_CONSUMER_KEY, conf.TWITTER_CONSUMER_SECRET, conf.TWITTER_ACCESS_TOKEN, conf.TWITTER_ACCESS_TOKEN_SECRET)
        result = t.search(q=conf.TWITTER_HASH_CABECALHO, result_type='mixed', count=25)
        tws = [status for status in result['statuses']]
        result = []
        for status in tws:
            status['classe'] = 'pessoa' + str(random.choice(range(1,10)))
            result.append(status)

        tocache("twetts_cabecalho", result)
    # print result
    # print len(result)
    return result
Exemplo n.º 25
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'})
Exemplo n.º 26
0
Arquivo: videos.py Projeto: clarete/gd
def embed(vid):
    video = fromcache("video_%s" % str(vid)) or tocache(
        "video_%s" % str(vid),
        treat_categories(wordpress.wpgd.getVideo(vid))[0])
    sources = fromcache("video_src_%s" % str(vid)) or tocache(
        "video_src_%s" % str(vid), wordpress.wpgd.getVideoSources(vid))
    video_sources = {}
    for s in sources:
        if (s['format'].find(';') > 0):
            f = s['format'][0:s['format'].find(';')]
        else:
            f = s['format']
        video_sources[f] = s['url']
    return render_template('videoembed.html',
                           video=video,
                           sources=video_sources)
Exemplo n.º 27
0
def login():
    """Renders the login form"""
    if authapi.is_authenticated():
        return redirect(url_for('.profile'))
    # signup_process = g.signup_process

    if 'twitter_token' in session:
        del session['twitter_token']

    next = request.args.get('next') or request.referrer
    if next and '/auth/' in next :
        next = ""
    print 'NEXT=', request.args.get('next')
    print 'NEXT=', next
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    resp = make_response(
     render_template('login.html', next=next,
        # signup_process=signup_process,
        menu=menus,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        sidebar=wordpress.getSidebar,
     )
    )
    resp.set_cookie('connect_type', '')
    return resp
Exemplo n.º 28
0
def login():
    """Renders the login form"""
    if authapi.is_authenticated():
        return redirect(url_for(".profile"))
    # signup_process = g.signup_process

    if "twitter_token" in session:
        del session["twitter_token"]

    next = request.args.get("next") or request.referrer
    if next and "/auth/" in next:
        next = ""
    print "NEXT=", request.args.get("next")
    print "NEXT=", next
    menus = fromcache("menuprincipal") or tocache(
        "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal")
    )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    resp = make_response(
        render_template(
            "login.html",
            next=next,
            # signup_process=signup_process,
            menu=menus,
            twitter_hash_cabecalho=twitter_hash_cabecalho,
            sidebar=wordpress.getSidebar,
        )
    )
    resp.set_cookie("connect_type", "")
    return resp
Exemplo n.º 29
0
def search(page=0):
    """Renders the search template"""

    query = request.values.get('s', '') or request.values.get('buscatop', '')
    #posttype = ['audiencia_govesc', 'clippinggd_clipping', 'equipegd_equipe', 'oquegd_oque', 'post']
    pagination, posts = wordpress.search(s=query, page=page, thumbsizes=['newsbox', 'widenewsbox'])
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)

    psearch = _format_postsearch(posts)
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    return render_template(
        'archive.html',
        sidebar=wordpress.getSidebar,
        # picday=picday,
        pagination=pagination,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        search_term=query,
        posts=psearch,
        menu=menus)
Exemplo n.º 30
0
def logout():
    """Logs the user out and returns """
    if not authapi.is_authenticated():
        return redirect(url_for("index"))
    authapi.logout()
    next = request.values.get("next")
    app = request.values.get("app")
    menus = fromcache("menuprincipal") or tocache(
        "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal")
    )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    if next:
        print "NEXTT=", next
        return redirect(next)
    else:
        return render_template(
            "logout.html",
            menu=menus,
            app=app,
            twitter_hash_cabecalho=twitter_hash_cabecalho,
            voltar=request.referrer or "/",
            sidebar=wordpress.getSidebar,
        )
Exemplo n.º 31
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'})
Exemplo n.º 32
0
def profile():
    """Shows the user profile form"""

    if not authapi.is_authenticated():
        return redirect(url_for("index"))

    data = authapi.authenticated_user().metadata()
    print "DATA FOR PROFILE", data

    profile = social(ProfileForm, default=data)
    passwd = ChangePasswordForm()
    menus = fromcache("menuprincipal") or tocache(
        "menuprincipal", wordpress.exapi.getMenuItens(menu_slug="menu-principal")
    )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        "profile.html",
        profile=profile,
        passwd=passwd,
        sidebar=wordpress.getSidebar,
        menu=menus,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
    )
Exemplo n.º 33
0
Arquivo: webapp.py Projeto: calcwb/gd
def login():
    """Renders the login form"""
    if authapi.is_authenticated():
        return redirect(url_for('.profile'))
    # signup_process = g.signup_process

    if 'twitter_token' in session:
        del session['twitter_token']

    next = request.args.get('next') or request.referrer
    if next and '/auth/' in next :
        next = ""
    print 'NEXT=', request.args.get('next')
    print 'NEXT=', next
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    resp = make_response(
     render_template('login.html', next=next,
        # signup_process=signup_process,
        menu=menus,
        twitter_hash_cabecalho=twitter_hash_cabecalho
     )
    )
    resp.set_cookie('connect_type', '')
    return resp
Exemplo n.º 34
0
def sobre_gd():
    pagesobre = fromcache('pagesobre') or tocache(
        'pagesobre', wordpress.getPageByPath('sobre'))
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template('sobre.html',
                           wp=wordpress,
                           menu=menus,
                           twitter_hash_cabecalho=twitter_hash_cabecalho,
                           sidebar=wordpress.getSidebar,
                           page_about=pagesobre)
Exemplo n.º 35
0
def search(page=0):
    """Renders the search template"""

    query = request.values.get('s', '') or request.values.get('buscatop', '')
    #posttype = ['audiencia_govesc', 'clippinggd_clipping', 'equipegd_equipe', 'oquegd_oque', 'post']
    pagination, posts = wordpress.search(s=query,
                                         page=page,
                                         thumbsizes=['newsbox', 'widenewsbox'])
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)

    psearch = _format_postsearch(posts)
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    return render_template(
        'archive.html',
        sidebar=wordpress.getSidebar,
        # picday=picday,
        pagination=pagination,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        search_term=query,
        posts=psearch,
        menu=menus)
Exemplo n.º 36
0
def index():
    # app.logger.error( " ######################################################################## BASE " )
    """Renders the index template"""
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        vote_url = app.config['VOTACAO_URL']
    except KeyError:
        vote_url = ""
    try:
        vote_root = app.config['VOTACAO_ROOT']
    except KeyError:
        vote_root = ""
    try:
        vote_altura = app.config['VOTACAO_ALTURA']
    except KeyError:
        vote_altura = ""

    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    # pagepri = fromcache('pagepri')      or tocache('pagepri', wordpress.getPageByPath('prioridades'))
    pagepq = fromcache('pagepq')        or tocache('pagepq', wordpress.getPageByPath('por-que'))
    # pageproc = fromcache('pageproc')    or tocache('pageproc', wordpress.getPageByPath('processo'))
    pagevot = fromcache('pagevot')    or tocache('pagevot', wordpress.getPageByPath('votacao'))
    pagehow = fromcache('pagehow')      or tocache('pagehow', wordpress.getPageByPath('como-funciona'))
    pageseg = fromcache('pageseg')      or tocache('pageseg', wordpress.getPageByPath('seguranca-2'))
    # pagesobre = fromcache('pagesobre')  or tocache('pagesobre', wordpress.getPageByPath('sobre'))

    return render_template(
        'index.html', wp=wordpress,
        sidebar=wordpress.getSidebar,
        # page_about=pagesobre,
        # page_pri=pagepri,
        page_pq=pagepq,
        pagevot=pagevot,
        # page_pro=pageproc,
        page_como=pagehow,
        page_seg=pageseg,
        menu=menus,
        reforma_voted=request.cookies.get('reforma_voted') or False,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        VOTACAO_URL=vote_url,
        VOTACAO_ROOT=vote_root,
        VOTACAO_ALTURA=vote_altura,
    )
Exemplo n.º 37
0
Arquivo: webapp.py Projeto: calcwb/gd
def lost_password():
    """Renders the lost password form"""
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template('lost_password.html', menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho)
Exemplo n.º 38
0
def error502(e):
    return render_template(
        '502.html',
        menu=fromcache('menuprincipal')
        or tocache('menuprincipal',
                   wordpress.exapi.getMenuItens(menu_slug='menu-principal')),
        sidebar=wordpress.getSidebar,
    ), 502
Exemplo n.º 39
0
Arquivo: videos.py Projeto: calcwb/gd
def nextpage(pagina):
    paginacao = int(current_app.config['VIDEO_PAGINACAO'])
    offset = pagina * paginacao
    print "OFFSET:", offset
    videos = fromcache("videos_%s" % str(offset)) or tocache("videos_%s" % str(offset), wordpress.wpgd.getVideos(
        where='status=true', orderby='date DESC', limit=paginacao, 
        offset=offset))
    return render_template('videos_pagina.html', videos=videos)
Exemplo n.º 40
0
def lost_password():
    """Renders the lost password form"""
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template('lost_password.html', menu=menus, sidebar=wordpress.getSidebar, twitter_hash_cabecalho=twitter_hash_cabecalho)
Exemplo n.º 41
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
Exemplo n.º 42
0
def resultado_detalhe(postid):
    """Renders a contribution detail"""
    principal = fromcache("res-detalhe-{0}".format(postid)) or \
                tocache("res-detalhe-{0}".format(postid),wordpress.wpgovp.getContribuicoes(principal='S',postID=postid))
    # print "PRINCIPAL +++++++++++++++++++++", principal[1][0]
    retorno = fromcache("contribs-detalhe-{0}".format(postid)) or \
              tocache("contribs-detalhe-{0}".format(postid),wordpress.wpgovp.getContribuicoes(principal='N',postID=postid))
    # print "RETORNO +++++++++++++++++++++", retorno
    comts = fromcache("com-res-detalhe-{0}".format(postid)) or \
            tocache("com-res-detalhe-{0}".format(postid),wordpress.getComments(status='approve',post_id=postid))
    qtd = retorno[0]
    detalhes = retorno[1]
    return render_template('resultados-detalhes.html',
                           agregadas=detalhes,
                           qtd_agregadas=qtd,
                           principal=principal[1][0],
                           comments=comts,
                           postid=postid)
Exemplo n.º 43
0
def canal(categoria_id):
    categories = fromcache("all_videos_categories") or tocache("all_videos_categories",wordpress.wpgd.getVideosCategories())

    page = int(request.args.get('page') or 1)
    page -= 1
    # print "Carregando pagina", page

    # print categories
    nome_canal = ""
    for cat in categories:
        if int(cat['term_id']) == categoria_id:
            nome_canal = cat['name']
            break

    videos_json = {}
    allvideos = fromcache("all_videos_root") or tocache("all_videos_root",
        treat_categories(wordpress.wpgd.getVideos(where='status=true'), orderby='title') )
    for v in allvideos:
        videos_json[v['title']] = v['id']


    # print "Buscando", current_app.config['VIDEO_PAGINACAO'], "vídeos por página!"
    cacheid = "videos_canal_%s_page_%s" % (str(categoria_id),page)
    cacheidall = "videos_canal_%s" % str(categoria_id)
    pagging = int(current_app.config['VIDEO_PAGINACAO'])
    offset = page * pagging

    allvideos_cat = fromcache(cacheidall) or tocache(cacheidall,
             treat_categories(wordpress.wpgd.getVideosByCategory(category=categoria_id)) )

    # print "PAGINACAO", len(allvideos_cat), page, pagging, offset
    page_total = int( round( Decimal( len(allvideos_cat) ) / pagging ) )

    videos = fromcache(cacheid) or tocache(cacheid,
             paginate(treat_categories(wordpress.wpgd.getVideosByCategory(category=categoria_id,
                ), orderby='date'), pagging, offset) )

    hvideos = fromcache("h_videos_root") or tocache("h_videos_root",
        treat_categories(wordpress.wpgd.getHighlightedVideos()) )

    return render_template('videos.html', videos=videos, titulos=videos_json,
        categories=categories, hvideos=hvideos, canal=nome_canal, canalclass="fa fa-th-large",
        page=page+1, page_total=page_total,
        sidebar=wordpress.getSidebar,)
Exemplo n.º 44
0
def gallery():
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'gallerys.html',
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        menu=menus,
    )
Exemplo n.º 45
0
Arquivo: videos.py Projeto: calcwb/gd
def listing():
    videos_json = {}
    allvideos = fromcache("all_videos_root") or tocache("all_videos_root",wordpress.wpgd.getVideos(
        where='status=true', orderby='title'))

    for v in allvideos:
        videos_json[v['title']] = v['id']

    print "Buscando", current_app.config['VIDEO_PAGINACAO'], "vídeos por página!"
    videos = fromcache("videos_root") or tocache("videos_root",wordpress.wpgd.getVideos(
        where='status=true', orderby='date DESC', limit=current_app.config['VIDEO_PAGINACAO']))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    return render_template('videos.html', videos=videos
        ,twitter_hash_cabecalho=twitter_hash_cabecalho
        ,menu=menus, titulos=videos_json)
Exemplo n.º 46
0
def resultado_detalhe(postid):
    """Renders a contribution detail"""
    principal = fromcache("res-detalhe-{0}".format(postid)) or \
                tocache("res-detalhe-{0}".format(postid),wordpress.wpgovp.getContribuicoes(principal='S',postID=postid))
    # print "PRINCIPAL +++++++++++++++++++++", principal[1][0]
    retorno = fromcache("contribs-detalhe-{0}".format(postid)) or \
              tocache("contribs-detalhe-{0}".format(postid),wordpress.wpgovp.getContribuicoes(principal='N',postID=postid))
    # print "RETORNO +++++++++++++++++++++", retorno
    comts = fromcache("com-res-detalhe-{0}".format(postid)) or \
            tocache("com-res-detalhe-{0}".format(postid),wordpress.getComments(status='approve',post_id=postid))
    qtd = retorno[0]
    detalhes = retorno[1]
    return render_template(
        'resultados-detalhes.html',
        agregadas=detalhes,
        qtd_agregadas=qtd,
        principal=principal[1][0],
        comments=comts,
        postid=postid
    )
Exemplo n.º 47
0
def tag(slug, page=0):
    """List posts of a given tag"""
    pagination, posts = fromcache("pag_posts_tag_%s_%s" % (slug,page)) or tocache("pag_posts_tag_%s_%s" % (slug,page), wordpress.getPostsByTag(tag=slug, page=page) )
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )

    psearch = _format_postsearch(posts)
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    return render_template(
        'archive.html',
        sidebar=wordpress.getSidebar,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        # picday=picday,
        pagination=pagination,
        posts=psearch
        ,menu=menus)
Exemplo n.º 48
0
def resultados_gd():
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'resultados-capa.html', wp=wordpress,
        menu=menus,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        sidebar=wordpress.getSidebar
    )
Exemplo n.º 49
0
def obra(slug):
	obra = fromcache("obra-" + slug) or tocache("obra-" + slug, _get_obras(slug)[0])
	if not obra:
		return abort(404)

	cacheid = "obratl-%s"%slug
	timeline = fromcache(cacheid) or tocache(cacheid,wordpress.monitoramento.getObraTimeline(obra['id']))
	timeline = adjustCf(timeline)
	statuses = [ s for s in timeline if s['format'] == 'status' ]

	cacheid = "page-more-"+slug
	more = fromcache(cacheid) or tocache(cacheid,wordpress.getPageByPath('more-'+slug))
	if more:
		more = more.content

	menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
	try:
		twitter_hash_cabecalho = twitts()
	except KeyError:
		twitter_hash_cabecalho = ""

	tos = fromcache('tosobras') or tocache('tosobras',wordpress.getPageByPath('tos-obras'))
	howto = fromcache('howtoobras') or tocache('howtoobras',wordpress.getPageByPath('howto-obras'))
	return render_template('obra.html',
		menu=menus,
		obra=obra,
		tos=tos,
		howto=howto,
		more=more,
		timeline=timeline,
		statuses=statuses,
		twitter_hash_cabecalho=twitter_hash_cabecalho
	)
Exemplo n.º 50
0
def gallery():
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'gallerys.html',
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        menu=menus,
    )
Exemplo n.º 51
0
def resultados_gd():
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template('resultados-capa.html',
                           wp=wordpress,
                           menu=menus,
                           twitter_hash_cabecalho=twitter_hash_cabecalho,
                           sidebar=wordpress.getSidebar)
Exemplo n.º 52
0
def twitts(hashtag=None, count=25):
    result = None
    if not hashtag:
        result = fromcache("twetts_cabecalho")
    if not result:
        t = get_twitter_connection()
        if not hashtag:
            hashtag = conf.TWITTER_HASH_CABECALHO
        result = t.search(hashtag, result_type='mixed', count=count)
        # pdb.set_trace()
        # tws = [status for status in result['statuses']]
        result = []
        for status in result:
            # print status
            status['classe'] = 'pessoa' + str(random.choice(range(1, 10)))
            status['created_at'] = convert_todatetime(status.created_at)
            result.append(status)

        tocache("twetts_cabecalho", result)
    # print result
    # print len(result)
    return result
Exemplo n.º 53
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'})
Exemplo n.º 54
0
Arquivo: videos.py Projeto: clarete/gd
def details(vid):
    video = fromcache("video_%s" % str(vid))

    if not video:
        # print "Video do wordpress...", vid
        video = tocache("video_%s" % str(vid),
                        treat_categories(wordpress.wpgd.getVideo(vid))[0])

    sources = fromcache("video_src_%s" % str(vid)) or tocache(
        "video_src_%s" % str(vid), wordpress.wpgd.getVideoSources(vid))

    base_url = current_app.config['BASE_URL']
    base_url = base_url if base_url[
        -1:] != '/' else base_url[:-1]  #corta a barra final
    video_sources = {}
    for s in sources:
        if (s['format'].find(';') > 0):
            f = s['format'][0:s['format'].find(';')]
        else:
            f = s['format']
        video_sources[f] = s['url']
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""

    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    return render_template(
        'video.html',
        video=video,
        sources=video_sources,
        menu=menus,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        base_url=base_url,
        sidebar=wordpress.getSidebar,
    )
Exemplo n.º 55
0
def timelineplus(obra_slug, statusid):
    cacheid = "obratl-%s" % obra_slug
    obra = fromcache("obra-" + obra_slug) or tocache("obra-" + obra_slug,
                                                     _get_obras(obra_slug)[0])
    timeline = fromcache(cacheid) or tocache(
        cacheid, wordpress.monitoramento.getObraTimeline(obra['id']))
    timeline = adjustCf(timeline)
    # import pdb

    updates = []
    # pdb.set_trace()
    inrange = False
    for resp in timeline:
        # print statusid, resp['id'], resp['format']
        if int(resp['id']) == statusid and resp['format'] == 'status':
            inrange = True
        elif resp['format'] == 'status' and inrange:
            inrange = False
            # break
        if inrange:
            # print "Added!"
            updates.append(resp)

    return render_template('timeline_part.html', timeline=updates, obra=obra)
Exemplo n.º 56
0
def post(pid):
    try:
        p = fromcache("post-%s" % str(pid)) or tocache("post-%s" % str(pid),
                                                       wordpress.getPost(pid))
    except:
        return abort(404)
    """View that renders a post template"""
    recent_posts = fromcache("recent_posts") or tocache(
        "recent_posts",
        wordpress.getRecentPosts(post_status='publish', numberposts=4))
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    cmts = fromcache("comentarios%s" % str(pid)) or tocache(
        "comentarios%s" % str(pid),
        wordpress.getComments(status='approve', post_id=pid))
    tags = fromcache("tags") or tocache("tags", wordpress.getTagCloud())
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    # live_comment_ = request.cookies.get('live_comment_save')
    return render_template(
        'post.html',
        post=p,
        tags=tags,
        sidebar=wordpress.getSidebar,
        # live_comment_save=live_comment_,
        # picday=picday,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        menu=menus,
        comments=cmts,
        show_comment_form=is_authenticated(),
        recent_posts=recent_posts)
Exemplo n.º 57
0
def profile():
    """Shows the user profile form"""

    if not authapi.is_authenticated():
        return redirect(url_for('index'))

    data = authapi.authenticated_user().metadata()
    print "DATA FOR PROFILE", data

    profile = social(ProfileForm, default=data)
    passwd = ChangePasswordForm()
    menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
    try:
        twitter_hash_cabecalho = utils.twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'profile.html', profile=profile, passwd=passwd, sidebar=wordpress.getSidebar, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho)
Exemplo n.º 58
0
def pages(path):
    """Renders a wordpress page"""
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)
    menus = fromcache('menuprincipal') or tocache(
        'menuprincipal',
        wordpress.exapi.getMenuItens(menu_slug='menu-principal'))
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'page.html',
        page=wordpress.getPageByPath(path),
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        sidebar=wordpress.getSidebar,
        # picday=picday
        menu=menus)
Exemplo n.º 59
0
def archive(m, page=0):
    """List posts of the archive given yyyymm format"""
    pagination, posts = fromcache(
        "archive-%s-%s" % (str(m), str(page))) or tocache(
            "archive-%s-%s" %
            (str(m), str(page)), wordpress.getArchivePosts(m=m, page=page))
    #Retorna a ultima foto inserida neste album.
    # picday = wordpress.wpgd.getLastFromGallery(conf.GALLERIA_FOTO_DO_DIA_ID)

    psearch = _format_postsearch(posts)
    try:
        twitter_hash_cabecalho = twitts()
    except KeyError:
        twitter_hash_cabecalho = ""
    return render_template(
        'archive.html',
        sidebar=wordpress.getSidebar,
        # picday=picday,
        twitter_hash_cabecalho=twitter_hash_cabecalho,
        pagination=pagination,
        posts=psearch)
Exemplo n.º 60
0
def logon():
    """Logs the user in and returns the user object in
    JSON format"""
    username = request.values.get('username')
    password = request.values.get('password')
    gonext = True
    if username and password:
        try:
            user = authapi.login(username, password)
        except authapi.UserNotFound:
            flash(_(u'Wrong user or password'), 'alert-error')
            gonext = False
        except authapi.UserAndPasswordMissmatch:
            flash(_(u'Wrong user or password'), 'alert-error')
            gonext = False
        # else:
            # msg.ok({ 'user': user })
            # flash(_(u'Login successfuly!'), 'alert-success')
    else:
        flash(_(u'Username or password missing'), 'alert-error')
        gonext = False
    formcad = social(SignupForm)

    next = request.values.get('next',default="")
    if next is not None and gonext:
        return redirect(next)
    else:
        menus = fromcache('menuprincipal') or tocache('menuprincipal', wordpress.exapi.getMenuItens(menu_slug='menu-principal') )
        try:
            twitter_hash_cabecalho = utils.twitts()
        except KeyError:
            twitter_hash_cabecalho = ""
        # if request.referrer:
        #     return redirect(request.referrer)
        # else:
        #     return render_template('login.html', form=formcad, next=next)
        return render_template('login.html', form=formcad, next=next, sidebar=wordpress.getSidebar, menu=menus, twitter_hash_cabecalho=twitter_hash_cabecalho)