Ejemplo n.º 1
0
def feedback():
    
    feedback = db.plugin_feedbacks_feedback
    form = SQLFORM(feedback)
    

    show_tab = ''
    if form.process(onvalidation=check_plugin_feedbacks_feedback_form).accepted:
        response.flash = T("Vielen Dank für Ihr Feedback.")
        session.plugin_feedbacks["sentFeedback"] = 1
        session.plugin_feedbacks["time"] = request.now
        if form.vars.feeling == "happy":
            show_tab = 'happy'
        else:
            show_tab = 'unhappy'
        
    likes = db(db.plugin_feedbacks_feedback.feeling == "happy").select(orderby=~db.plugin_feedbacks_feedback.commentdate)
    dislikes = db(db.plugin_feedbacks_feedback.feeling == "unhappy").select(orderby=~db.plugin_feedbacks_feedback.commentdate)
    
    for likerow in likes:
        likerow.commentdate = prettydate(likerow.commentdate,T)
    for dislikerow in dislikes:
        dislikerow.commentdate = prettydate(dislikerow.commentdate,T)
    
    test = datetime.datetime.now() - datetime.timedelta(minutes=15)
    records = db((db.plugin_feedbacks_feedback.senderip == form.vars.senderip) & (db.plugin_feedbacks_feedback.commentdate > test)).select()
    
    return dict(form=form, likes=likes, dislikes=dislikes, show_tab=show_tab)
Ejemplo n.º 2
0
def load_projects():
    """
    Description: Returns a list of projects to show on index.html. This is called from the JS.
    Returns: A JSON with a dictionary of all the builds and their database fields.
    Note: No HTML associated with page
    """

    # Find list of project names that match the user ID
    q = db(db.build.user_id == auth.user.id).select()
    project_list = []

    for i in q:
        # Find the status of the most recent experiment in builds corresponding to the project
        # for the overall project status. If no experiments, return "N/A" as status.
        try:
            status = db(db.experiment.build_id == i.id).select(
                orderby=~db.experiment.id)[0].status
        except IndexError:
            status = "N/A"

        # Find the project row that corresponds to the project associated with the build
        project = db(db.project.project_name == i.project).select()[0]

        # Add the project to the JSON file if it doesn't exist there already
        if not any(info['name'] == project.project_name
                   for info in project_list):
            project_list.append(
                dict(name=project.project_name,
                     id=project.id,
                     workspace=project.workspace,
                     time=str(prettydate(project.time_stamp, T)),
                     status=status))
    return project_list
Ejemplo n.º 3
0
def signedIn():
    #if user not signed in redirect to index/main page
    if not auth.user:
        redirect(URL('default', 'index'))

    form = SQLFORM(db.alarm)
    session.fromSignedIn = 1  #flag to indicate coming from signed in to create a new alarm

    #list = myReminders()
    list = db(db.alarm.phone_number == auth.user.phone).select()

    #list to hold prettydate(), time, and message
    remLists = []
    today = datetime.date.today()

    for alarm in list:
        # we only want to display future reminders
        if alarm.reminder_date >= today:
            a = prettydate(alarm.reminder_date, T)
            b = alarm.reminder_time
            c = alarm.reminder_message
            # place time and prettydate() into obj
            objAB = [a, b, c]
            #append to list
            remLists.append(objAB)

    return dict(form=form, list=list, remLists=remLists, today=today)
Ejemplo n.º 4
0
def signedIn():
    #if user not signed in redirect to index/main page
    if not auth.user:
        redirect(URL('default', 'index'))

    form = SQLFORM(db.alarm)
    session.fromSignedIn=1 #flag to indicate coming from signed in to create a new alarm

    #list = myReminders()
    list =  db(db.alarm.phone_number == auth.user.phone).select()

    #list to hold prettydate(), time, and message
    remLists = []
    today = datetime.date.today()

    for alarm in list:
        # we only want to display future reminders
        if alarm.reminder_date >= today:
            a = prettydate(alarm.reminder_date,T)
            b = alarm.reminder_time
            c = alarm.reminder_message
            # place time and prettydate() into obj
            objAB = [a,b,c]
            #append to list
            remLists.append(objAB)

    return dict(form=form,list=list,remLists=remLists,today=today)
Ejemplo n.º 5
0
def list():
    """
    Lists all entries by the current user for all tasks. For every task a
    separate panel is shown. All panels are collapsed by default, if no task id
    is given as argument. When a valid task id is given, the panel of that task
    is opened.

    /entry/list -> list all entries for all tasks, all task panels closed
    /entry/list/[task id] -> list all entries for all tasks, task with given
                             task id is opened
    """
    # check if a task number was given
    if request.args:
        try:
            task_to_be_viewed = int(request.args[0])
        except ValueError:
            task_to_be_viewed = ''
    else:
        task_to_be_viewed = ''
    # get all task that should be listed
    tasks_in_entries = db(db.Entries.Submitter == auth.user_id).select(orderby=db.Entries.Task, groupby=db.Entries.Task)
    task_div_list = []
    js_toggle_panels = ''
    for task in tasks_in_entries:
        # get current task from database based on id from Entries table
        current_task = db(db.Tasks.id == task.Task).select().first()
        # get all entries for current task sorted by submission time
        entries = db((db.Entries.Submitter == auth.user_id) & (db.Entries.Task == current_task.id)).select(orderby=~db.Entries.SubmissionTime)
        entry_rows = []
        entry_rows.append(TR(TD(T('Entry')), TD(T('Uploaded')), TD(T('Edit entry')), TD(T('Build entry')),
                             TD(T('Download source file')), TD(T('Download CodeBlocks project')), _class='table_header'))
        for entry in entries:
            # build table row of current entry for current task
            entry_text = T('Entry no. {}').format(entry.id)
            edit_entry_link = A(T('Edit entry'), _href=URL(c='default', f='codeeditor', args=(entry.Task, entry.id)))
            build_entry_link = A(T('Build entry'), _href=URL(f='build', args=(entry.Task, entry.id)))
            download_entry_source_link = A(T('Download source file'), _href=URL(f='download', args=(entry.Task, entry.id, 'source')))
            download_entry_project_link = A(T('Download CodeBlocks project'), _href=URL(f='download', args=(entry.Task, entry.id, 'project')))
            entry_rows.append(TR(TD(entry_text), TD(prettydate(entry.SubmissionTime,T)), TD(edit_entry_link),
                                 TD(build_entry_link), TD(download_entry_source_link), TD(download_entry_project_link),
                                 _id='entry_data-{}'.format(entry.id)))
        # build panel and its header
        task_panel_heading_id = 'task_heading-{}'.format(current_task.id)
        task_panel_body_id = 'task_body-{}'.format(current_task.id)
        entry_table = TABLE(*entry_rows, _class='table table-hover')
        current_task_table = DIV(entry_table, _class='panel-body', _id=task_panel_body_id)
        new_task_panel_header = H3(T('Task number {task_id}: {task_name}').format(task_id=current_task.id, task_name=current_task.Name),
                                   _class='panel-title')
        current_task_header = DIV(new_task_panel_header, _class='panel-heading', _id=task_panel_heading_id)
        task_div_list.append(DIV(current_task_header, current_task_table, _class='panel panel-default'))
        # create JavaScript to toggle panels by clicking on their header
        if not task_to_be_viewed or task_to_be_viewed != current_task.id:
            js_toggle_panels += '$("#{contentID}").hide();'.format(contentID=task_panel_body_id)
        js_toggle_panels += '$("#{titleID}").click(function(){{ $("#{contentID}").slideToggle(); }});'.format(titleID=task_panel_heading_id, contentID=task_panel_body_id)
    complete_entry_list = DIV(task_div_list)
    js_toggle_panels = SCRIPT(js_toggle_panels)
    return locals()
Ejemplo n.º 6
0
def index():
    response.title = 'Administración'
    response.subtitle = 'Listado'
    createargs = viewargs = None

    ### Config Grid
    fields = (Curso.titulo, Curso.precio, Curso.created_on)
    # Represent Columns
    Curso.created_on.represent = lambda v, r: SPAN(prettydate(v),
                                                   _title=v)
    # Readable&Writable
    Curso.created_on.readable = True

    # Pre Construct SQLFORM.grid
    if 'new' in request.args or 'edit' in request.args:
        response.subtitle = 'Nuevo' if 'new' in request.args else 'Edición'
        Curso.created_on.readable = False

    
    if 'view' in request.args:
        readable_signature(Curso)
        row = Curso(request.args(-1, cast=int))
        response.subtitle = 'Detalle > %s' % row.titulo
        
        f_cfecha = (CFecha.id, CFecha.fecha, CFecha.hora_inicio, CFecha.hora_fin)
        f_docente = (Inscripto.id, Inscripto.persona, Inscripto.docente)

        viewargs = dict(
            fecha = lambda: row.cfecha.select(*f_cfecha, orderby=CFecha.fecha),
            docente = lambda: row.inscripto.select(*f_docente).find(lambda r: r['docente'])
        )
        

    grid = SQLFORM.grid(Curso,
                        csv=False,
                        fields=fields,
                        viewargs=viewargs,
                        maxtextlength=200,
                        create=auth.has_membership('administrador'),
                        editable=auth.has_membership('administrador'),
                        deletable=auth.has_membership('administrador'),
                        ondelete=hide_record,
                        oncreate=curso_aux.oncreate,
                        onupdate=curso_aux.oncreate,
                        user_signature=True,
                        showbuttontext=False,
                        orderby=~Curso.created_on,
                        )

    # Post Construct SQLFORM.grid
    if 'view' in request.args:
        for i in grid.elements('.btn'):
            i.add_class('btn-xs btn-warning',)

    return dict(grid=grid)
Ejemplo n.º 7
0
def ver_tarea():
    from gluon.tools import prettydate
    tarea_id = request.args(0, cast=int)
    tarea = db.tarea(tarea_id) or error()
    if not tarea.created_by == mi and not tarea.asignada_a == mi: error()
    meta = "Creada {} por {}, asignada a {}".format(
        prettydate(tarea.created_on, T), autor(tarea.created_by),
        autor(tarea.asignada_a))
    titulo = SPAN(tarea.titulo, " ",
                  I(tarea.estado, _class="label label-default"))
    contenido = DIV(H6(meta, _class="text-muted"), P(tarea.descripcion))
    return response.render("default/index.html",
                           dict(titulo=titulo, contenido=contenido))
Ejemplo n.º 8
0
def show_page():
    """
        Show the requested page
    """
    from gluon.tools import prettydate

    manager_toolbar = ManagerToolbar('page')
    if request.args(0) and request.args(0).isdigit():
        page = db.page(request.args(0))
    else:
        page = db(db.page.url == request.args(0)).select().first()
    #if the page has no content, we select the fisrt child (len < 8 to avoid having a page with just "<br />")
    if page and len(page.content) < 8:
        child = db(db.page.parent == page).select(orderby=db.page.rank
                                                  | db.page.title).first()
        if child:
            page = child
    if not page:
        if request.args(0) and request.args(0).lower() == 'images':
            redirect(URL('images'))
        else:
            page = db(db.page.is_index == True).select().first()

    disqus_shortname = None
    if page.allow_disqus and WEBSITE_PARAMETERS.disqus_shortname:
        disqus_shortname = WEBSITE_PARAMETERS.disqus_shortname
    pretty_date = prettydate(page.modified_on, T)
    header_component = db.page_component(page.header_component)
    left_sidebar_component = db.page_component(page.left_sidebar_component)
    right_sidebar_component = db.page_component(page.right_sidebar_component)
    left_footer_component = db.page_component(page.left_footer_component)
    middle_footer_component = db.page_component(page.middle_footer_component)
    right_footer_component = db.page_component(page.right_footer_component)
    central_component = db.page_component(page.central_component)
    return dict(page=page,
                header_component=header_component,
                left_sidebar_enabled=page.left_sidebar_enabled,
                right_sidebar_enabled=page.right_sidebar_enabled,
                left_sidebar_component=left_sidebar_component,
                right_sidebar_component=right_sidebar_component,
                left_footer_component=left_footer_component,
                middle_footer_component=middle_footer_component,
                right_footer_component=right_footer_component,
                central_component=central_component,
                manager_toolbar=manager_toolbar,
                pretty_date=pretty_date,
                disqus_shortname=disqus_shortname)
Ejemplo n.º 9
0
def show_page():
    """
        Show the requested page
    """
    from gluon.tools import prettydate

    manager_toolbar = ManagerToolbar('page')
    if request.args(0) and request.args(0).isdigit():
        page = db.page(request.args(0))
    else:
        page = db(db.page.url==request.args(0)).select().first()
    #if the page has no content, we select the fisrt child (len < 8 to avoid having a page with just "<br />")
    if page and len(page.content) < 8:
        child = db(db.page.parent==page).select(orderby=db.page.rank|db.page.title).first()
        if child:
            page=child
    if not page:
        if request.args(0) and request.args(0).lower() == 'images':
            redirect(URL('images'))
        else:
            page = db(db.page.is_index==True).select().first()

    disqus_shortname = None
    if page.allow_disqus and WEBSITE_PARAMETERS.disqus_shortname:
        disqus_shortname = WEBSITE_PARAMETERS.disqus_shortname
    pretty_date = prettydate(page.modified_on, T)
    header_component = db.page_component(page.header_component)
    left_sidebar_component = db.page_component(page.left_sidebar_component)
    right_sidebar_component = db.page_component(page.right_sidebar_component)
    left_footer_component = db.page_component(page.left_footer_component)
    middle_footer_component = db.page_component(page.middle_footer_component)
    right_footer_component = db.page_component(page.right_footer_component)
    central_component = db.page_component(page.central_component)
    return dict(page=page,
                header_component=header_component,
                left_sidebar_enabled=page.left_sidebar_enabled,
                right_sidebar_enabled=page.right_sidebar_enabled,
                left_sidebar_component=left_sidebar_component,
                right_sidebar_component=right_sidebar_component,
                left_footer_component=left_footer_component,
                middle_footer_component=middle_footer_component,
                right_footer_component=right_footer_component,
                central_component=central_component,
                manager_toolbar=manager_toolbar,
                pretty_date=pretty_date,
                disqus_shortname=disqus_shortname)
Ejemplo n.º 10
0
 def node(comment):
     if not comment.deleted:
         #return T('COMMENT')
         return LI(
             DIV(  ##T('posted by %(first_name)s %(last_name)s',comment.created_by),
                 # not sure why this doesn't work... db.auth record is not a mapping!?
                 DIV(comment.body, _class='body'),
                 DIV(
                     T('%s ', comment.created_by.first_name),
                     T('%s', comment.created_by.last_name),
                     # SPAN(' [local expertise]',_class='badge') if comment.claimed_expertise else '',
                     SPAN(' [', comment.feedback_type, ']', _class='badge')
                     if comment.feedback_type else '',
                     SPAN(' [', comment.intended_scope, ']', _class='badge')
                     if comment.intended_scope else '',
                     T(' - %s', prettydate(comment.created_on, T)),
                     SPAN(A(T('hide replies'), _class='toggle', _href='#'),
                          SPAN(' | ') if auth.user_id else '',
                          A(T('reply'), _class='reply', _href='#')
                          if auth.user_id else '',
                          SPAN(' | ')
                          if comment.created_by == auth.user_id else '',
                          A(T('delete'), _class='delete', _href='#')
                          if comment.created_by == auth.user_id else '',
                          _class='controls'),
                     _class='byline'),
                 _id='r%s' % comment.id),
             DIV(_class='reply'),
             # child messages (toggle hides/shows these)
             SUL(*[node(comment)
                   for comment in thread.get(comment.id, [])]))
     elif comment.id in thread:
         return LI(
             DIV(SPAN(T('[deleted comment]'), _class='body'),
                 ' ',
                 SPAN(A(T('hide replies'), _class='toggle', _href='#'),
                      _class='controls'),
                 _class='deleted'), DIV(_class='reply'),
             SUL(*[node(comment)
                   for comment in thread.get(comment.id, [])]))
     else:
         return None
Ejemplo n.º 11
0
def get_comments():
    response = check_response(request.vars,
        {'QuoteID': 'is_integer'})
    if response['status'] == 200:
        quoteid = request.vars.QuoteID
        comments = db((db.COMMENT.QuoteID==quoteid) & 
            (db.auth_user._id==db.COMMENT.created_by)).select(
            orderby=~db.COMMENT.created_on, limitby=(0,10))
        commentslist = []
        for q in comments:
            commentslist.append({
                'text': q.COMMENT.Text, 
                'user': q.auth_user.username, 
                'timestamp': str(prettydate(q.COMMENT.created_on,T)) })
        response['comments'] = sanitize_JSON(commentslist)
    else:
        status = response['status']
        response.pop('status', None)
        raise HTTP(status, json.dumps(response))
    response.pop('status', None)
    return json.dumps(response)
Ejemplo n.º 12
0
def show_page():
    """
        Show the requested page
    """
    from gluon.tools import prettydate

    manager_toolbar = ManagerToolbar("page")
    if request.args(0) and request.args(0).isdigit():
        page = db.page(request.args(0))
    else:
        page = db(db.page.url == request.args(0)).select().first()
    # if the page has no content, we select the fisrt child (len < 8 to avoid having a page with just "<br />")
    if page and len(page.content) < 8:
        child = db(db.page.parent == page).select(orderby=db.page.rank | db.page.title).first()
        if child:
            page = child
    if not page:
        if request.args(0) and request.args(0).lower() == "images":
            redirect(URL("images"))
        else:
            page = db(db.page.is_index == True).select().first()

    pretty_date = prettydate(page.modified_on, T)
    left_sidebar_component = db.page_component(page.left_sidebar_component)
    right_sidebar_component = db.page_component(page.right_sidebar_component)
    left_footer_component = db.page_component(page.left_footer_component)
    middle_footer_component = db.page_component(page.middle_footer_component)
    right_footer_component = db.page_component(page.right_footer_component)
    return dict(
        page=page,
        left_sidebar_enabled=page.left_sidebar_enabled,
        right_sidebar_enabled=page.right_sidebar_enabled,
        left_sidebar_component=left_sidebar_component,
        right_sidebar_component=right_sidebar_component,
        left_footer_component=left_footer_component,
        middle_footer_component=middle_footer_component,
        right_footer_component=right_footer_component,
        manager_toolbar=manager_toolbar,
        pretty_date=pretty_date,
    )
Ejemplo n.º 13
0
    def build_components(self):
        def remove_url(comment):
            base = self.base_url_remove_comment.copy()
            base["vars"].update({"__saved": comment["__saved"][0], "__idx": comment["__saved"][1]})
            return URL(**base)

        total = self.count_comments()

        components = []
        components.append(SPAN(self.T("Comments"), _class="nav-header"))
        components.append(self.form)
        if total:
            components.append(
                TAG["small"]("%d out of %d comments" % (5 if total > 5 else total, total), _class="comment-total")
            )
        components.append(self.script())
        last_comments = self.list_last_comments()
        if last_comments:
            comments = []
            for comment in last_comments:
                comments.append(
                    DIV(
                        DIV(
                            comment["comment"],
                            A(XML("&times"), _class="close", _href=remove_url(comment), cid=self.request.cid),
                            _class="comment-text",
                        ),
                        DIV(
                            TAG["small"]("%s : %s" % (self.T("by"), comment["by"]), _class="comment-by"),
                            TAG["small"](
                                "%s : %s" % (self.T("on"), prettydate(comment["on"], self.T)), _class="comment-on"
                            ),
                            _class="comment-help",
                        ),
                        _class="comment-row",
                    )
                )
            components.append(DIV(*comments, _class="comment-container"))
        return components
Ejemplo n.º 14
0
def workers():
    from gluon.tools import prettydate
    sdb = db
    sw, st, sr = (sdb.scheduler_worker, sdb.scheduler_task,sdb.scheduler_run)
    workers = sdb.executesql("select substring_index(worker_name,'#',1) node,group_names,count(id) from scheduler_worker group by node,group_names order by node,group_names")
    max = db.scheduler_task.id.max()
    latest_task_id = db((db.scheduler_task.task_name == 'task_evt_poll') & 
                        ((db.scheduler_task.status == 'COMPLETED') | (db.scheduler_task.times_run > 0))
                       ).select(max).first()[max]
    #latest_task_id=get_latest_task_id('task_evt_poll')
    latest_task=scheduler.task_status(latest_task_id) if  latest_task_id else None
    events_horizont_ts = json.loads(latest_task.args)[2] if latest_task else None
    events_horizont_dt = datetime.datetime.fromtimestamp(events_horizont_ts) if events_horizont_ts else None
    #events_horizont_ts = json.loads(latest_task.args)[2] if latest_task else None
    #events_horizont_dt = datetime.datetime.fromtimestamp(events_horizont_ts) if events_horizont_ts else None
    count = sdb(sdb.scheduler_worker.id>0).count()
    ticker,tasks,completed_tasks,workers_rows = (None,None,None,None)
    if auth.has_membership(role = 'advanced_scheduler_viewer'):
        ticker = sdb(sw.is_ticker == True).select().first()
        workers_rows = sdb(sw.id>0).select()
        tasks = sdb(st.status != 'COMPLETED').select(st.id,st.application_name,st.task_name,st.status,
                                            st.group_name,st.args,st.vars,st.start_time,
                                            st.times_run,st.times_failed,st.last_run_time,
                                            st.next_run_time,st.assigned_worker_name,
                                            limitby=(0,500),
                                            orderby=(~st.last_run_time,st.status))
        completed_tasks = sdb(st.status=='COMPLETED').select(st.id,st.application_name,st.task_name,st.status,
                                            st.group_name,st.args,st.vars,st.start_time,
                                            st.times_run,st.times_failed,st.last_run_time,
                                            st.next_run_time,st.assigned_worker_name,
                                            limitby=(0,50),
                                            orderby=(~st.last_run_time))
    return dict(workers=workers,ticker = ticker, count=count, tasks = tasks, completed_tasks = completed_tasks,
            events_horizont = dict (dt = events_horizont_dt, 
                                    ts = events_horizont_ts,
                                    pd = prettydate(events_horizont_dt)
                                   ),
            workers_rows = workers_rows
                )
Ejemplo n.º 15
0
def profesion():
    response.title = 'Administración'
    response.subtitle = 'grilla'
    createargs = viewargs = None

    ### Config Grid
    fields = (Profesion.nombre, Profesion.created_on)
    # Represent Columns
    Profesion.created_on.represent = lambda v, r: SPAN(prettydate(v),
                                                   _title=v)
    # Readable&Writable
    Profesion.created_on.readable = True

    grid = SQLFORM.grid(Profesion,
                        csv=False,
                        fields=fields,
                        maxtextlength=200,
                        ondelete=hide_record,
                        user_signature=True,
                        showbuttontext=False,
                        orderby=~Profesion.created_on,
                        )

    return dict(grid=grid)
Ejemplo n.º 16
0
 def node(comment):
     if not comment.deleted:
         #return T('COMMENT')
         return LI(
             DIV(##T('posted by %(first_name)s %(last_name)s',comment.created_by),
                 # not sure why this doesn't work... db.auth record is not a mapping!?
                 DIV( XML(markdown(comment.body or ''), sanitize=True),_class='body'),
                 DIV(T('%s ',comment.created_by.first_name),T('%s',comment.created_by.last_name), 
                     # SPAN(' [local expertise]',_class='badge') if comment.claimed_expertise else '',
                     SPAN(' ',comment.feedback_type,' ',_class='badge') if comment.feedback_type else '',
                     SPAN(' ',comment.intended_scope,' ',_class='badge') if comment.intended_scope else '',
                     T(' - %s',prettydate(comment.created_on,T)),
                     SPAN(
                         A(T('hide replies'),_class='toggle',_href='#'),
                         SPAN(' | ') if auth.user_id else '',
                         A(T('reply'),_class='reply',_href='#') if auth.user_id else '',
                         SPAN(' | ') if comment.created_by == auth.user_id else '',
                         A(T('delete'),_class='delete',_href='#') if comment.created_by == auth.user_id else '',
                     _class='controls'),
                 _class='byline'),
                 _id='r%s' % comment.id),
             DIV(_class='reply'),
             # child messages (toggle hides/shows these)
             SUL(*[node(comment) for comment in thread.get(comment.id,[])])
             )
     elif comment.id in thread:
         return LI(
             DIV(SPAN(T('[deleted comment]'),_class='body'),' ',
                 SPAN(
                     A(T('hide replies'),_class='toggle',_href='#'),
                 _class='controls'),
             _class='deleted'),
             DIV(_class='reply'),
             SUL(*[node(comment) for comment in thread.get(comment.id,[])]))
     else: 
         return None
Ejemplo n.º 17
0
                    db, 'auth_user.id', db.auth_user._format,
                    # orderby=db.auth_user.title
                )
            )
    ),
    Field(
        'direction', length=8, label=T('Direction'),
        requires=IS_IN_SET(['Sent', 'Received'])
    ),
    Field('is_read', 'boolean', label=T('Read?')),
    Field('msg_sender', length=100, label=T('Sender')),
    Field('msg_from', length=100, label=T('From')),
    Field('msg_recipient', length=100, label=T('Recipient')),
    Field('msg_to', length=100, label=T('To')),
    Field('msg_subject', length=100, label=T('Subject')),
    Field('msg_body', length=500, label=T('Body')),
    Field('msg_html', length=500, label=T('Body HTML')),
    # Field('msg_attachments', 'file'),

    auth.signature,
    singular = 'Message', plural = 'Messages',
    format = '%(msg_from)s: %(msg_subject)s',
)

db.message.is_read.represent = lambda is_read, row: (
    XML(DIV(I(_class="fa fa-envelope-o"), ' Read')) if is_read
    else XML(DIV(I(_class="fa fa-envelope"), ' Unread'))
)
db.message.created_on.represent = lambda create_on, row: prettydate(create_on, T)
db.message.modified_on.represent = lambda modified_on, row: prettydate(modified_on, T)
Ejemplo n.º 18
0
def pretty_date_function(date):
    pretty_d = prettydate(date, T)
    return pretty_d
Ejemplo n.º 19
0
def publicaciones():
    if not request.ajax: return ''
    from gluon.tools import prettydate
    from datetime import datetime

    if request.args:
            catslug_data = db(db.categoria.slug == request.args(0)).select(db.categoria.slug)
            for cat in catslug_data:
                    catslug = cat.slug
    else:
            catslug = 'noticias'


    publicaciones = DIV()

    # obteniendo los feeds categorizados bajo el slug solicitado desde la url

    ### 1 categoría por feed
    """
    for feedincat in db((db.categoria.slug == catslug) & (db.feed.categoria == db.categoria.id)
                            #& (db.feed_categoria.feed == db.feed.id)
                            #& (db.feed_categoria.is_active == True)
                            & (db.feed.is_active == True)
                            & (db.categoria.is_active == True)
                            ).select(db.feed.ALL):
    """

    feedincat_data = db((db.categoria.slug == catslug)
                                            & (db.feed.categoria == db.categoria.id)
                                            & (db.feed.is_active == True)
                                            & (db.categoria.is_active == True)
                                            ).select(db.feed.id,db.feed.title,db.feed.source)


    for feedincat in feedincat_data:

            # armando feed_bloque y la noticia de cada feed
            feedbox = DIV(DIV(A(feedincat.title,_href=feedincat.source,_target='_blank',_class='ui-widget-header-a'), _class = 'feed_titulo ui-widget-header ui-corner-all'), _class = 'feedbox feed_bloque  izq ui-widget ui-corner-all')

            for n in db(db.noticia.feed == feedincat.id).select(db.noticia.ALL, orderby =~ db.noticia.id, limitby=(0,4)):


                    try:
                        actualizado = datetime.strptime(str(n.updated),'%Y-%m-%d %H:%M:%S')
                    except:
                        actualizado = n.created_on

                    # armando la url que va en el rss
                    #localurl = 'http://' + request.env.http_host + URL(c = 'default', f = 'blog.html', args = [n.slug,n.id], extension='html')

                    # armando el título y enlace a la publicación; armando los bloques de publicación
                    feedbox.append(DIV(DIV(A(n.title.lower()+'...', _name = n.slug, 
                                             _href = URL(r = request, f = 'blog', args = [catslug,n.slug,n.id], extension=False), 
                                             _class = 'noticia_link ui-widget-content-a', _target='_blank',extension='html'),
                                             DIV(prettydate(actualizado,T),
                                                 _class='noticia_meta'),
                                                 _class = 'noticia_contenido ui-widget-content ui-corner-all'),
                                                 _class = 'noticia ui-widget ui-corner-all')
                        )


                    #entradas.append(dict(title =unicode(n.title,'utf8'), link = localurl, description = unicode('%s (%s)' % (n.description, n.feed.title),'utf8'), created_on = request.now))


            publicaciones.append(feedbox)

    response.js = XML('''function filtro(){
jQuery("#filtrando").keyup(function () {
    var filter = jQuery(this).val(), count = 0;

    jQuery(".feedbox .noticia, .feed_titulo").each(function () {
            if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
                    jQuery(this).addClass("hidden");
            } else {
                    jQuery(this).removeClass("hidden");
                    count++;
            }
    });
    jQuery("#filtrado").text(count);
});
}

jQuery(document).ready(filtro);
''')

    d = dict(publicaciones=publicaciones)
    return response.render(d)
Ejemplo n.º 20
0
    def _set(self):
        """Set the grid. """
        db = self.db
        request = self.request
        queries = list(self.queries) if self.queries else []
        queries.append((db.book.status == BOOK_STATUS_ACTIVE))
        queries.extend(self.filters())

        db.auth_user.name.represent = lambda v, row: A(
            v,
            _href=creator_url(row.creator, extension=False)
        )

        def book_name_rep(value, row):
            """db.book.name.represent."""
            # unused-argument (W0613): *Unused argument %%r*
            # pylint: disable=W0613
            book = Book.from_id(row.book.id)
            return A(
                formatted_name(book, include_publication_year=False),
                _href=book_url(book, extension=False)
            )
        db.book.name.represent = book_name_rep

        db.book.page_added_on.represent = lambda v, row: \
            str(prettydate(v, T=current.T)) if v is not None else 'n/a'

        fields = [
            db.book.id,
            db.book.name,
            db.book.book_type_id,
            db.book.number,
            db.book.of_number,
            db.book.publication_year,
            db.book.release_date,
            db.book.views,
            db.book.downloads,
            db.book.contributions_remaining,
            db.book.name_for_url,
            db.book.page_added_on,
            db.book.created_on,
            db.creator.id,
            db.auth_user.name,
            db.creator.paypal_email,
            db.creator.contributions_remaining,
            db.creator.torrent,
            db.creator.name_for_url,
        ]

        visible = [str(x) for x in self.visible_fields()]
        for f in fields:
            if str(f) in visible:
                self.show(f)
            else:
                self.hide(f)

        headers = {
            'auth_user.name': 'Cartoonist',
            'book.name': 'Title',
            'book.publication_year': 'Year',
            'book.released_date': 'Completed',
            'book.views': 'Views',
            'book.contributions_remaining': 'Remaining',
            'book.page_added_on': 'Added',
            'creator.contributions_remaining': 'Remaining',
        }

        links = []

        def add_link(body, header=''):
            """Add link to links list."""
            links.append({'header': header, 'body': body})

        if 'read' in self._buttons:
            add_link(read_link)

        if 'creator_torrent' in self._buttons:
            add_link(link_for_creator_torrent)

        if 'creator_contribute' in self._buttons:
            add_link(creator_contribute_button)

        if 'download' in self._buttons:
            add_link(download_link)

        if 'creator_follow' in self._buttons:
            add_link(link_for_creator_follow)

        if 'book_follow' in self._buttons:
            add_link(follow_link)

        if 'book_contribute' in self._buttons:
            add_link(book_contribute_button)

        sorter_icons = (
            SPAN(
                TAG.i(_class='icon zc-arrow-up size-08'),
                _class='grid_sort_marker'
            ),
            SPAN(
                TAG.i(_class='icon zc-arrow-down size-08'),
                _class='grid_sort_marker'
            ),
        )

        if not queries:
            queries.append(db.book)
        query = reduce(lambda x, y: x & y, queries) if queries else None

        grid_class = 'web2py_grid grid_view_{v} grid_key_{o}'.format(
            v=request.vars.view or 'tile',
            o=self.__class__.__name__.replace('Grid', '').lower()
        )

        kwargs = dict(
            fields=fields,
            field_id=db[self._attributes['table']].id,
            headers=headers,
            orderby=self.orderby(),
            groupby=self.groupby(),
            left=[
                db.creator.on(db.book.creator_id == db.creator.id),
                db.auth_user.on(
                    db.creator.auth_user_id == db.auth_user.id
                ),
            ],
            paginate=self.viewbys[self.viewby]['items_per_page'],
            details=False,
            editable=False,
            deletable=False,
            create=False,
            csv=False,
            searchable=False,
            maxtextlengths={
                'book.name': 50,
                'auth_user.name': 50,
            },
            links=links,
            sorter_icons=sorter_icons,
            editargs={'deletable': False},
            _class=grid_class,
        )
        if self.form_grid_args:
            kwargs.update(self.form_grid_args)

        grid_class = make_grid_class(
            export='none', search='none', ui='glyphicon')
        self.form_grid = grid_class.grid(query, **kwargs)
        self._paginate = kwargs['paginate']
        # Remove 'None' record count if applicable.
        for count, div in enumerate(self.form_grid[0]):
            if str(div) == '<div class="web2py_counter">None</div>':
                del self.form_grid[0][count]
                               IS_UPLOAD_FILENAME(extension='csv')),
          comment='* File has to be in .csv format, max size 200mb'),
    Field('assigned_to', 'reference auth_user'),
    Field('status', requires=IS_IN_SET(STATUSES), default=STATUSES[0]),
    Field('deadline', 'datetime', default=request.now + week * 4),
    auth.signature)

db.task.file.requires = IS_UPLOAD_FILENAME(extension='csv')
'''this query selects user ids from a members of VectorbiteAdmin'''
query = db((db.auth_user.id == db.auth_membership.user_id)
           & (db.auth_group.id == db.auth_membership.group_id)
           & (db.auth_group.role == 'VectorbiteAdmin'))
db.task.assigned_to.requires = IS_IN_DB(query, 'auth_user.id', '%(first_name)s'
                                        ' %(last_name)s')

db.task.created_on.represent = lambda v, row: prettydate(v)
db.task.deadline.represent = lambda v, row: SPAN(
    prettydate(v),
    _class='overdue' if v and v < datetime.datetime.today() else None)


def fullname(user_id):
    if user_id is None:
        return "Unknown"
    return "%(first_name)s %(last_name)s (id:%(id)s)" % db.auth_user(user_id)


def show_status(status, row=None):
    return SPAN(status, _class=status)

Ejemplo n.º 22
0
def analyze_task():
    task_id = request.args(0)
    if not task_id:
        return ''
    task = dbs(st.id == task_id).select().first()

    if not task:
        return ''

    q = sr.task_id == task_id

    first_run = dbs(q).select(sr.start_time, orderby=sr.start_time, limitby=(0,1)).first()

    last_run = dbs(q).select(sr.start_time, orderby=~sr.start_time, limitby=(0,1)).first()

    first_run_pretty = first_run and prettydate(first_run.start_time) or 'Never'
    last_run_pretty = last_run and prettydate(last_run.start_time) or 'Never'

    if not first_run:
        mode = 'no_runs'
        #we can rely on the data on the scheduler_task table because no scheduler_run were found
        q = st.id == task_id
        first_run_pretty = 'Never'
    else:
        mode = 'runs'
    last_run 
    if len(request.args) >= 2:
        if request.args(1) == 'byfunction':
            if mode == 'runs':
                q = sr.task_id.belongs(dbs(st.function_name == task.function_name)._select(st.id))
            else:
                q = st.function_name == task.function_name
        elif request.args(1) == 'bytaskname':
            if mode == 'runs':
                q = sr.task_id.belongs(dbs(st.task_name == task.task_name)._select(st.id))
            else:
                q = st.task_name == task.task_name
        elif request.args(1) == 'this':
            if mode == 'runs':
                q = sr.task_id == task_id
            else:
                q = st.id == task_id

    if len(request.args) == 4 and request.args(2) == 'byday':
            daysback = int(request.args(3))
            now = s.utc_time and request.utcnow or request.now
            day = now.date() - timed(days=daysback)
            if mode == 'runs':
                q = q & ((sr.start_time >= day) & (sr.start_time < day + timed(days=1)))
            else:
                q = q & ((st.last_run_time >= day) & (st.last_run_time < day + timed(days=1)))

    if mode == 'runs':
        gb_duration_rows, jgb_duration_series = gb_duration(q)
        jgb_duration_series = dumps(jgb_duration_series)
    else:
        #no duration can be calculated using the scheduler_task table only
        jgb_duration_series = dumps([])

    gb_status_rows, jgb_status_series = gb_status(q, mode)
    jgb_status_series = dumps(jgb_status_series)

    gb_when_rows, jgb_when_series = bydate(q, mode)
    jgb_when_series = dumps(jgb_when_series)

    if len(request.args) == 4 and request.args(2) == 'byday':
        gb_whend_rows, jgb_whend_series = byday(q, day, mode)
        jgb_whend_series = dumps(jgb_whend_series)
    else:
        jgb_whend_series = dumps([[]])

    return locals()
Ejemplo n.º 23
0
def publicaciones():
    if not request.ajax: return ''
    from gluon.tools import prettydate
    from datetime import datetime

    if request.args:
        catslug_data = db(db.categoria.slug == request.args(0)).select(
            db.categoria.slug)
        for cat in catslug_data:
            catslug = cat.slug
    else:
        catslug = 'noticias'

    publicaciones = DIV()

    # obteniendo los feeds categorizados bajo el slug solicitado desde la url

    ### 1 categoría por feed
    """
    for feedincat in db((db.categoria.slug == catslug) & (db.feed.categoria == db.categoria.id)
                            #& (db.feed_categoria.feed == db.feed.id)
                            #& (db.feed_categoria.is_active == True)
                            & (db.feed.is_active == True)
                            & (db.categoria.is_active == True)
                            ).select(db.feed.ALL):
    """

    feedincat_data = db((db.categoria.slug == catslug)
                        & (db.feed.categoria == db.categoria.id)
                        & (db.feed.is_active == True)
                        & (db.categoria.is_active == True)).select(
                            db.feed.id, db.feed.title, db.feed.source)

    for feedincat in feedincat_data:

        # armando feed_bloque y la noticia de cada feed
        feedbox = DIV(
            DIV(A(feedincat.title,
                  _href=feedincat.source,
                  _target='_blank',
                  _class='ui-widget-header-a'),
                _class='feed_titulo ui-widget-header ui-corner-all'),
            _class='feedbox feed_bloque  izq ui-widget ui-corner-all')

        for n in db(db.noticia.feed == feedincat.id).select(
                db.noticia.ALL, orderby=~db.noticia.id, limitby=(0, 4)):

            try:
                actualizado = datetime.strptime(str(n.updated),
                                                '%Y-%m-%d %H:%M:%S')
            except:
                actualizado = n.created_on

            # armando la url que va en el rss
            #localurl = 'http://' + request.env.http_host + URL(c = 'default', f = 'blog.html', args = [n.slug,n.id], extension='html')

            # armando el título y enlace a la publicación; armando los bloques de publicación
            feedbox.append(
                DIV(DIV(
                    A(n.title.lower() + '...',
                      _name=n.slug,
                      _href=URL(r=request,
                                f='blog',
                                args=[catslug, n.slug, n.id],
                                extension=False),
                      _class='noticia_link ui-widget-content-a',
                      _target='_blank',
                      extension='html'),
                    DIV(prettydate(actualizado, T), _class='noticia_meta'),
                    _class='noticia_contenido ui-widget-content ui-corner-all'
                ),
                    _class='noticia ui-widget ui-corner-all'))

            #entradas.append(dict(title =unicode(n.title,'utf8'), link = localurl, description = unicode('%s (%s)' % (n.description, n.feed.title),'utf8'), created_on = request.now))

        publicaciones.append(feedbox)

    response.js = XML('''function filtro(){
jQuery("#filtrando").keyup(function () {
    var filter = jQuery(this).val(), count = 0;

    jQuery(".feedbox .noticia, .feed_titulo").each(function () {
            if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
                    jQuery(this).addClass("hidden");
            } else {
                    jQuery(this).removeClass("hidden");
                    count++;
            }
    });
    jQuery("#filtrado").text(count);
});
}

jQuery(document).ready(filtro);
''')

    d = dict(publicaciones=publicaciones)
    return response.render(d)
Ejemplo n.º 24
0
    def generate_comment_on(self, comment_on):
        """Generate on"""

        return prettydate(comment_on)
Ejemplo n.º 25
0
    def view(self):
        from gluon.tools import prettydate
        db = self.db
        auth = self.auth
        T = current.T
        request = current.request
        comment = self.define_comment()
        content = TABLE()
        value = None
        args = [self.tablename, self.table_id]
        if request.vars.comment_delete:
            db(comment.id == request.vars.comment_id).delete()
        elif request.vars.comment_update:
            db(comment.id == self.id).update(
                txtcontent=request.vars.txtcontent, created_on=request.now)
        elif self.id:
            value = comment(self.id).txtcontent
        elif request.vars.txtcontent:
            comment.insert(txtcontent=request.vars.txtcontent,
                           tablename=self.tablename,
                           table_id=self.table_id,
                           objects_id=self.objects_id,
                           procedures=self.procedures,
                           process=self.process,
                           auth_group=self.auth_groups)
        form = TABLE(TR(
            TD(TEXTAREA(_name='txtcontent', value=value),
               _id='table_comment_edit')),
                     _id='form_add_comment')
        ajax = "ajax('%s', ['txtcontent'], '%s_comment')" % (URL(
            r=request, c='plugin_comment', f='view', args=args,
            vars=self.vars), self.tablename)
        td = TD(
            INPUT(_type='button',
                  _name='submit',
                  _class='btn btn-primary',
                  _value=T('Add comment'),
                  _onclick=ajax))
        if value:
            self.vars['comment_id'] = self.id
            self.vars['comment_update'] = True
            ajax = "ajax('%s', ['txtcontent'], '%s_comment')" % (URL(
                r=request,
                c='plugin_comment',
                f='view',
                args=args,
                vars=self.vars), self.tablename)
            td.append(
                INPUT(_type='button',
                      _name='submit',
                      _class='btn btn-primary',
                      _value=T('Edit'),
                      _onclick=ajax))
            del self.vars['comment_update']
            self.vars['comment_delete'] = True
            ajax = "ajax('%s', [], '%s_comment')" % (URL(
                r=request,
                c='plugin_comment',
                f='view',
                args=args,
                vars=self.vars), self.tablename)
            td.append(
                INPUT(_type='button',
                      _name='submit',
                      _class='btn btn-danger',
                      _value=T('Delete'),
                      _onclick=ajax))
        from plugin_app import ColorBox
        td.append(
            DIV(SPAN(ColorBox(caption=T('Pencil'),
                              iframe='true',
                              source=URL(r=request,
                                         c='plugin_comment',
                                         f='draw.html',
                                         args=args,
                                         vars=self.vars),
                              reload=True,
                              width='850px',
                              height='380px'),
                     _id='button_cb',
                     _class='glyphicon glyphicon-pencil'),
                _class='btn btn-primary pencil'))
        form.append(TR(td))
        query = (comment.tablename == self.tablename) & (comment.table_id
                                                         == self.table_id)
        #if self.objects_id: query &= (comment.objects_id==self.objects_id)
        #if self.procedures: query &= (comment.procedures==self.procedures)
        #if self.process: query &= (comment.process==self.process)
        if self.auth_groups:
            query &= (comment.auth_group.contains(self.auth_groups, all=False))

        rows = db(query).select(orderby=~comment.created_on)
        for row in rows:
            user = self.db.auth_user(row.created_by)
            tr = TR(
                TD(row.created_on, ' (', prettydate(row.created_on, T), ')'),
                TD('%s %s' % (user.last_name, user.first_name), ':'))
            comment = row.txtcontent
            if (comment[:5] == 'data:'):
                comment = IMG(_src='%s' % comment,
                              _width='600',
                              _height='150',
                              _style='border: 1px solid #000;')
                tr.append(TD(''))
                content.append(tr)
                if self.auth.user_id == row.created_by:
                    self.vars['comment_id'] = row.id
                    comment = SPAN(ColorBox(
                        caption=comment,
                        iframe='true',
                        source=URL(r=request,
                                   c='plugin_comment',
                                   f='draw.html',
                                   args=args,
                                   vars=self.vars),
                        reload=True,
                        width='850px',
                        height='380px',
                        onCleanup="$('#savebutton').trigger('click');"),
                                   _id='button_cb')
                tr = TR(TD(comment, _colspan='3'))
                content.append(tr)
            else:
                comment = XML(comment)
                if self.auth.user_id == row.created_by:
                    self.vars['comment_id'] = row.id
                    ajax = "ajax('%s', [], '%s_comment')" % (URL(
                        r=request,
                        c='plugin_comment',
                        f='edit',
                        args=args,
                        vars=self.vars), self.tablename)
                    comment = SPAN(ColorBox(
                        caption=comment,
                        iframe='true',
                        source=URL(r=request,
                                   c='plugin_comment',
                                   f='edit.html',
                                   args=args,
                                   vars=self.vars),
                        reload=True,
                        width='800px',
                        height='600px',
                        onCleanup="$('#savebutton').trigger('click');"),
                                   _id='button_cb')
                    #tr.append(TD(A(comment,_href='#',_onclick=ajax)))
                    tr.append(TD(comment))
                else:
                    tr.append(TD(comment))
                content.append(tr)
        content = DIV(self.message,
                      content,
                      form,
                      _id='%s_comment' % self.tablename,
                      _class='object_comment')
        return XML(content)
Ejemplo n.º 26
0
db = current.globalenv['db']
auth = current.globalenv['auth']

# Notícias
db.define_table(
    'noticias',
    Field('titulo', length=128, notnull=True, unique=True),
    Field('resumo', length=128, notnull=True),
    Field('conteudo', 'text', length=5000, notnull=True),
    Field('permalink', notnull=True, unique=True),
    Field('foto', 'upload'),
    Field('thumbnail', 'upload'),
    Field('status'),
    auth.signature
)
db.noticias.modified_on.represent = lambda date, row: prettydate(date)

# Membros
db.define_table(
    'membros',
    Field('nome', length=64, notnull=True, unique=True),
    Field('foto', 'upload'),
    Field('email', notnull=True)
)
# Eventos
db.define_table(
    'eventos',
    Field('nome', length=128, notnull=True),
    Field('dia', 'date', notnull=True),
    Field('horario_inicio', 'time', label=current.T('Inicio'), notnull=True),
    Field('horario_fim', 'time', label=current.T('Término'), notnull=True),
Ejemplo n.º 27
0
    def node(comment):
        ##print("building node for comment id={0}...".format(comment.get('number', comment['id'])))
        # preload its comments (a separate API call)
        child_comments = [ ]
        if comment.get('comments') and comment.get('comments') > 0:
            get_children_url = comment['comments_url']
            resp = requests.get( get_children_url, headers=GH_GET_HEADERS)
            try:
                resp.raise_for_status()
                try:
                    child_comments = resp.json()
                except:
                    child_comments = resp.json
                print("found {0} child comments".format(len(child_comments)))
            except:
                # WE need logging in the web app!
                try:
                    import sys
                    sys.stderr.write('Error: got a {c} from {u}\n'.format(c=resp.status_code,
                                                                        u=get_children_url))
                except:
                    pass # well that sucks, we failed to even write to stderr

        metadata = parse_comment_metadata(comment['body'])
        ##print(metadata)

        # Examine the comment metadata (if any) to get the best display name
        # and URL for its author. Guests should appear here as the name and
        # email address they entered when creating a comment, rather than the
        # 'opentreeapi' bot user.
        #
        # Default values are what we can fetch from the issues API
        author_display_name = comment['user']['login']
        author_link = comment['user']['html_url']
        # Now let's try for something more friendly...
        if metadata:
            meta_author_info = metadata.get('Author', None)
            if meta_author_info:
                # Try to parse this fron a Markdown hyperlink. Typical values include:
                #   u'opentreeapi'
                #   u'11'
                #   u'[Jim Allman](https://github.com/jimallman)'
                #   u'[John Smith](mailto:[email protected])'
                regex = re.compile(r'\[(.*)\]\((.*)\)')
                markdown_fields = regex.findall(meta_author_info)
                if len(markdown_fields) > 0:
                    # look for parts of a markdown link
                    author_display_name, author_link = markdown_fields[0]
                else:
                    # it's not a markdown link, just a bare name or numeric userid
                    if meta_author_info.isdigit():
                        # ignore ugly userid (login is better)
                        pass
                    else:
                        author_display_name = meta_author_info

        # Is this node for an issue (thread starter) or a comment (reply)?
        issue_node = 'number' in comment

        # Is the current user logged in? If so, what is their GitHub ID (login)?
        current_user_id = auth.user and auth.user.github_login or None

        # Cook up some reasonably strong regular expressions to detect bare
        # URLs and wrap them in hyperlinks. Adapted from 
        # http://stackoverflow.com/questions/1071191/detect-urls-in-a-string-and-wrap-with-a-href-tag
        link_regex = re.compile(  r'''
                             (?x)( # verbose identify URLs within text
                      (http|https) # make sure we find a resource type
                               :// # ...needs to be followed by colon-slash-slash
                    (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx)
                              (/?| # could be just the domain name (maybe w/ slash)
                        [^ \n\r"]+ # or stuff then space, newline, tab, quote
                            [\w/]) # resource name ends in alphanumeric or slash
             (?=([\s\.,>)'"\]]|$)) # assert: followed by white or clause ending OR end of line
                                 ) # end of match group
                                   ''')
        # link_replace = r'<a href="\1" />\1</a>'
        # let's try this do-nothing version
        link_replace = r'\1'
        # NOTE the funky constructor required to use this below

        try:   # TODO: if not comment.deleted:
            markup = LI(
                    DIV(##T('posted by %(first_name)s %(last_name)s',comment.created_by),
                    # not sure why this doesn't work... db.auth record is not a mapping!?
                    ('title' in comment) and DIV( comment['title'], A(T('on GitHub'), _href=comment['html_url'], _target='_blank'), _class='topic-title') or '',
                    DIV( XML(markdown(get_visible_comment_body(comment['body'] or ''), extras={'link-patterns':None}, link_patterns=[(link_regex, link_replace)]).encode('utf-8'), sanitize=False),_class=(issue_node and 'body issue-body' or 'body comment-body')),
                    DIV(
                        A(T(author_display_name), _href=author_link, _target='_blank'),
                        # SPAN(' [local expertise]',_class='badge') if comment.claimed_expertise else '',
                        SPAN(' ',metadata.get('Feedback type'),' ',_class='badge') if metadata.get('Feedback type') else '',
                        SPAN(' ',metadata.get('Intended scope'),' ',_class='badge') if metadata.get('Intended scope') else '',
                        T(' - %s',prettydate(utc_to_local(datetime.strptime(comment['created_at'], GH_DATETIME_FORMAT)),T)),
                        SPAN(
                            issue_node and A(T(child_comments and 'Hide comments' or 'Show/add comments'),_class='toggle',_href='#') or '',
                            issue_node and comment['user']['login'] == current_user_id and SPAN(' | ') or '',
                            A(T('Delete'),_class='delete',_href='#') if comment['user']['login'] == current_user_id else '',
                        _class='controls'),
                    _class='byline'),
                    _id='r%s' % comment.get('number', comment['id']),
                    _class='msg-wrapper'),
                # child messages (toggle hides/shows these)
                issue_node and SUL(*[node(comment) for comment in child_comments], _style=("" if child_comments else "display: none;")) or '',
                issue_node and DIV(_class='reply', _style=("" if child_comments else "display: none;")) or '',
                _class=(issue_node and 'issue' or 'comment'))
            return markup
        except:
            import sys
            print "Unexpected error:", sys.exc_info()[0]
            raise
Ejemplo n.º 28
0
    Field('title', requires=IS_NOT_EMPTY()),
    Field('description', 'text',
        comment=XML(T("MARKMIN text syntax is accepted.").replace('MARKMIN', str(STRONG(A('MARKMIN', _href="http://web2py.com/books/default/chapter/29/05#markmin_markmin_syntax"))))),
        represent=lambda v, r: MARKMIN(v)
    ),
    Field('typology', 'reference issue_type', label=T('Type')),
    Field('priority', 'reference issue_priority'),
    Field('severity', 'reference issue_severity'),
    Field('weigth', 'integer', compute=IssueWeight.run),
    Field('status', 'reference issue_state', label=T('State')),
    Field('tags', 'list:string'),
#     Field('assigned_to', 'list:reference auth_group', comment="DEPRECATED"), # DEPRECATED
    Field('assignedto', 'reference auth_group', label=T("Assigned to"),
        default = auth.user_id
    ),
    Field('dead_line', 'date', represent=lambda v,r: prettydate(v)),
    Field('time_spent', 'integer', label=T("Time spent"), comment=T("in hours")),
    Field('closed', 'boolean', default=False),
    Field('closed_on', 'datetime', writable=False),
    Field('slugs', 'list:string', label=T("Wiki pages"),
        readable = False,
        represent=lambda v,r: SPAN(*map(lambda e: A(e, _href=URL('wiki', 'index', args=('issue_%s' % r.id +'_'+e,))), v))),
    auth.signature,
    format = '%(title)s',
)

db.issue.modified_on.represent=lambda v,r: prettydate(v)
db.issue.modified_on.label = T("Last modified")

IssueReferences(db.issue).assign()
Ejemplo n.º 29
0
def pdate(value):
    if isinstance(value, str):
        value = datetime.strptime(value, "%s %s" % (DATEFORMAT, TIMEFORMAT))
    return T(prettydate(value))
Ejemplo n.º 30
0
    'task',
    Field('title',
          'string',
          requires=IS_NOT_EMPTY() and IS_NOT_IN_DB(db, 'task.title')
          and IS_LENGTH(maxsize=15)),
    Field('description', 'text', requires=IS_NOT_EMPTY()),
    Field('status', 'integer', readable=False, writable=False, default=0),
    Field('pid', 'reference project', readable=False, writable=False),
    Field('duedat', 'date'), auth.signature)

db.task.duedat.requires = IS_DATE_IN_RANGE(format=T('%Y-%m-%d'),
                                           minimum=request.now.date(),
                                           maximum=datetime.date(2020, 1, 1))

db.define_table(
    'checklist', Field('description', 'text', requires=IS_NOT_EMPTY()),
    Field('status', 'integer', readable=False, writable=False, default=0),
    Field('pid', 'reference project', readable=False, writable=False),
    Field('tid', 'reference task', readable=False, writable=False),
    Field('due', 'datetime'), auth.signature)

db.define_table('tm', Field('title'),
                Field('assigned_to', 'reference auth_user'), auth.signature)

db.project.created_on.represent = lambda v, row: prettydate(v)

db.define_table('product', Field('name'), Field('colors', 'list:string'))
#db.product.colors.requires=IS_IN_SET(('red','blue','green'))  #imp

auth.enable_record_versioning(db)
Ejemplo n.º 31
0
    def node(comment):
        ##print("building node for comment id={0}...".format(comment.get('number', comment['id'])))
        # preload its comments (a separate API call)
        child_comments = [ ]
        if comment.get('comments') and comment.get('comments') > 0:
            get_children_url = comment['comments_url']
            resp = requests.get( get_children_url, headers=GH_GET_HEADERS)
            resp.raise_for_status()
            try:
                child_comments = resp.json()
            except:
                child_comments = resp.json
            print("found {0} child comments".format(len(child_comments)))

        metadata = parse_comment_metadata(comment['body'])
        ##print(metadata)

        # Examine the comment metadata (if any) to get the best display name
        # and URL for its author. Guests should appear here as the name and
        # email address they entered when creating a comment, rather than the
        # 'opentreeapi' bot user.
        #
        # Default values are what we can fetch from the issues API
        author_display_name = comment['user']['login']
        author_link = comment['user']['html_url']
        # Now let's try for something more friendly...
        if metadata:
            meta_author_info = metadata.get('Author', None)
            if meta_author_info:
                # Try to parse this fron a Markdown hyperlink. Typical values include:
                #   u'opentreeapi'
                #   u'11'
                #   u'[Jim Allman](https://github.com/jimallman)'
                #   u'[John Smith](mailto:[email protected])'
                regex = re.compile(r'\[(.*)\]\((.*)\)')
                markdown_fields = regex.findall(meta_author_info)
                if len(markdown_fields) > 0:
                    # look for parts of a markdown link
                    author_display_name, author_link = markdown_fields[0]
                else:
                    # it's not a markdown link, just a bare name or numeric userid
                    if meta_author_info.isdigit():
                        # ignore ugly userid (login is better)
                        pass
                    else:
                        author_display_name = meta_author_info

        # Is this node for an issue (thread starter) or a comment (reply)?
        issue_node = 'number' in comment

        # Is the current user logged in? If so, what is their GitHub ID (login)?
        current_user_id = auth.user and auth.user.github_login or None

        # Cook up some reasonably strong regular expressions to detect bare
        # URLs and wrap them in hyperlinks. Adapted from 
        # http://stackoverflow.com/questions/1071191/detect-urls-in-a-string-and-wrap-with-a-href-tag
        link_regex = re.compile(  r'''
                             (?x)( # verbose identify URLs within text
                      (http|https) # make sure we find a resource type
                               :// # ...needs to be followed by colon-slash-slash
                    (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx)
                              (/?| # could be just the domain name (maybe w/ slash)
                        [^ \n\r"]+ # or stuff then space, newline, tab, quote
                            [\w/]) # resource name ends in alphanumeric or slash
             (?=([\s\.,>)'"\]]|$)) # assert: followed by white or clause ending OR end of line
                                 ) # end of match group
                                   ''')
        # link_replace = r'<a href="\1" />\1</a>'
        # let's try this do-nothing version
        link_replace = r'\1'
        # NOTE the funky constructor required to use this below

        try:   # TODO: if not comment.deleted:
            markup = LI(
                    DIV(##T('posted by %(first_name)s %(last_name)s',comment.created_by),
                    # not sure why this doesn't work... db.auth record is not a mapping!?
                    ('title' in comment) and DIV( comment['title'], A(T('on GitHub'), _href=comment['html_url'], _target='_blank'), _class='topic-title') or '',
                    DIV( XML(markdown(get_visible_comment_body(comment['body'] or ''), extras={'link-patterns':None}, link_patterns=[(link_regex, link_replace)]).encode('utf-8'), sanitize=False),_class=(issue_node and 'body issue-body' or 'body comment-body')),
                    DIV(
                        A(T(author_display_name), _href=author_link, _target='_blank'),
                        # SPAN(' [local expertise]',_class='badge') if comment.claimed_expertise else '',
                        SPAN(' ',metadata.get('Feedback type'),' ',_class='badge') if metadata.get('Feedback type') else '',
                        SPAN(' ',metadata.get('Intended scope'),' ',_class='badge') if metadata.get('Intended scope') else '',
                        T(' - %s',prettydate(utc_to_local(datetime.strptime(comment['created_at'], GH_DATETIME_FORMAT)),T)),
                        SPAN(
                            issue_node and A(T(child_comments and 'Hide comments' or 'Show/add comments'),_class='toggle',_href='#') or '',
                            issue_node and comment['user']['login'] == current_user_id and SPAN(' | ') or '',
                            A(T('Delete'),_class='delete',_href='#') if comment['user']['login'] == current_user_id else '',
                        _class='controls'),
                    _class='byline'),
                    _id='r%s' % comment.get('number', comment['id']),
                    _class='msg-wrapper'),
                # child messages (toggle hides/shows these)
                issue_node and SUL(*[node(comment) for comment in child_comments], _style=("" if child_comments else "display: none;")) or '',
                issue_node and DIV(_class='reply', _style=("" if child_comments else "display: none;")) or '',
                _class=(issue_node and 'issue' or 'comment'))
            return markup
        except:
            import sys
            print "Unexpected error:", sys.exc_info()[0]
            raise
Ejemplo n.º 32
0
# this file is released under public domain and you can use without limitations

# -------------------------------------------------------------------------
# This is a sample controller
# - index is the default action of any application
# - user is required for authentication and authorization
# - download is for downloading files uploaded in the db (does streaming)
# -------------------------------------------------------------------------
from collections import OrderedDict
import json
import datetime
from gluon.tools import prettydate


db.logging.created_on.represent = db.application.created_on.represent = \
    lambda v, r: XML('<span title="%s">%s</span>' % (prettydate(getattr(r, 'created_on', None)),
                                                     getattr(r, 'created_on', None)))
db.application.modified_on.represent = lambda v, r: XML('<span title="%s">%s</span>' % (prettydate(
    getattr(r, 'modified_on', None)), getattr(r, 'modified_on', None)))

_role_to_permission = dict(app_managers="manage", contributors="contribute", admins="administrate", trainers="train",
                           masters=None)  # todo observers=observe


def test_email():
    response.view = os.path.join("templates", "email.html")
    return dict(summary="test", first_name="test", message="test", action_url="test", call_to_action="test")


def _disable_rbac_fields(*args):
    def _decorator(func):
Ejemplo n.º 33
0
    def node(comment):
        ##print("building node for comment id={0}...".format(comment.get('number', comment['id'])))
        # preload its comments (a separate API call)
        child_comments = [ ]
        if comment.get('comments') and comment.get('comments') > 0:
            get_children_url = comment['comments_url']
            resp = requests.get( get_children_url, headers=GH_GET_HEADERS, timeout=10)
            # N.B. Timeout is in seconds, and watches for *any* new data within that time (vs. whole response)
            try:
                resp.raise_for_status()
                try:
                    child_comments = resp.json()
                except:
                    child_comments = resp.json
            except:
                # WE need logging in the web app!
                try:
                    import sys
                    sys.stderr.write('Error: got a {c} from {u}\n'.format(c=resp.status_code,
                                                                        u=get_children_url))
                except:
                    pass # well that sucks, we failed to even write to stderr

        metadata = parse_comment_metadata(comment['body'])
        ##print(metadata)

        # Examine the comment metadata (if any) to get the best display name
        # and URL for its author. Guests should appear here as the name and
        # email address they entered when creating a comment, rather than the
        # GitHub app (bot).
        #
        # Default values are what we can fetch from the issues API
        author_display_name = comment['user']['login']
        author_link = comment['user']['html_url']
        # Now let's try for something more friendly...
        if metadata:
            meta_author_info = metadata.get('Author', None)
            if meta_author_info:
                # Try to parse this fron a Markdown hyperlink. Typical values include:
                #   u'opentreeapi'
                #   u'11'
                #   u'[Jim Allman](https://github.com/jimallman)'
                #   u'[John Smith](mailto:[email protected])'
                regex = re.compile(r'\[(.*)\]\((.*)\)')
                markdown_fields = regex.findall(meta_author_info)
                if len(markdown_fields) > 0:
                    # look for parts of a markdown link
                    author_display_name, author_link = markdown_fields[0]
                else:
                    # it's not a markdown link, just a bare name or numeric userid
                    if meta_author_info.isdigit():
                        # ignore ugly userid (login is better)
                        pass
                    else:
                        author_display_name = meta_author_info

        # Is this node for an issue (thread starter) or a comment (reply)?
        issue_node = 'number' in comment

        # Is the current user logged in? If so, what is their GitHub ID (login)?
        current_user_id = auth.user and auth.user.github_login or None

        # Cook up some reasonably strong regular expressions to detect bare
        # URLs and wrap them in hyperlinks. Adapted from 
        # http://stackoverflow.com/questions/1071191/detect-urls-in-a-string-and-wrap-with-a-href-tag
        link_regex = re.compile(  r'''
                             (?x)( # verbose identify URLs within text
                      (http|https) # make sure we find a resource type
                               :// # ...needs to be followed by colon-slash-slash
                    (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx)
                              (/?| # could be just the domain name (maybe w/ slash)
                        [^ \n\r"]+ # or stuff then space, newline, tab, quote
                            [\w/]) # resource name ends in alphanumeric or slash
             (?=([\s\.,>)'"\]]|$)) # assert: followed by white or clause ending OR end of line
                                 ) # end of match group
                                   ''')
        # link_replace = r'<a href="\1" />\1</a>'
        # let's try this do-nothing version
        link_replace = r'\1'
        # NOTE the funky constructor required to use this below

        # Define a consistent cleaner to sanitize user input. We need a few
        # elements that are common in our markdown but missing from the Bleach
        # whitelist.
        # N.B. HTML comments are stripped by default. Non-allowed tags will appear
        # "naked" in output, so we can identify any bad actors.
        common_feedback_tags = [u'p', u'br',
                                u'h1', u'h2', u'h3', u'h4', u'h5', u'h6',
                                ]
        ot_markdown_tags = list(set( bleach.sanitizer.ALLOWED_TAGS + common_feedback_tags))
        ot_cleaner = Cleaner(tags=ot_markdown_tags)

        try:   # TODO: if not comment.deleted:
            # N.B. some missing information (e.g. supporting URL) will appear here as a string like "None"
            supporting_reference_url = metadata.get('Supporting reference', None)
            has_supporting_reference_url = supporting_reference_url and (supporting_reference_url != u'None')
            # Prepare a sanitized rendering of this user-submitted markup
            rendered_comment_markdown = markdown(
                get_visible_comment_body(comment['body'] or ''),
                extras={'link-patterns':None},
                link_patterns=[(link_regex, link_replace)]).encode('utf-8')
            safe_comment_markup = XML(
                ot_cleaner.clean(rendered_comment_markdown),
                sanitize=False)  # gluon's sanitize will break on Unicode!
            markup = LI(
                    DIV(##T('posted by %(first_name)s %(last_name)s',comment.created_by),
                    # not sure why this doesn't work... db.auth record is not a mapping!?
                    ('title' in comment) and DIV( comment['title'], A(T('on GitHub'), _href=comment['html_url'], _target='_blank'), _class='topic-title') or '',
                    DIV( safe_comment_markup, _class=(issue_node and 'body issue-body' or 'body comment-body')),
                    DIV( A(T('Supporting reference (opens in a new window)'), _href=supporting_reference_url, _target='_blank'), _class='body issue-supporting-reference' ) if has_supporting_reference_url else '',
                    DIV(
                        A(T(author_display_name), _href=author_link, _target='_blank'),
                        # SPAN(' [local expertise]',_class='badge') if comment.claimed_expertise else '',
                        SPAN(' ',metadata.get('Feedback type'),' ',_class='badge') if metadata.get('Feedback type') else '',
                        T(' - %s',prettydate(utc_to_local(datetime.strptime(comment['created_at'], GH_DATETIME_FORMAT)),T)),
                        SPAN(
                            issue_node and A(T(child_comments and 'Hide comments' or 'Show/add comments'),_class='toggle',_href='#') or '',
                            issue_node and comment['user']['login'] == current_user_id and SPAN(' | ') or '',
                            A(T('Delete'),_class='delete',_href='#') if comment['user']['login'] == current_user_id else '',
                        _class='controls'),
                    _class='byline'),
                    _id='r%s' % comment.get('number', comment['id']),
                    _class='msg-wrapper'),
                # child messages (toggle hides/shows these)
                issue_node and SUL(*[node(comment) for comment in child_comments], _style=("" if child_comments else "display: none;")) or '',
                issue_node and DIV(_class='reply', _style=("" if child_comments else "display: none;")) or '',
                _class=(issue_node and 'issue' or 'comment'))
            return markup
        except:
            import sys
            print "Unexpected error:", sys.exc_info()[0]
            raise
Ejemplo n.º 34
0
def show_page():
    """
    Show the requested page.
    You can call this controller either using the id or the url of the page.
    Calling this controller with the url of the page is better for SEO : 
    `http://your-website.com/default/show_page/my-pretty-page` is nicer than
    `http://your-website.com/default/show_page/42`

    A better solution would be to have urls like

    `http://your-website.com/my-pretty-page`
    instead of 
    `http://your-website.com/default/show_page/my-pretty-page`

    Here is an example of a custom routes.py file : 
    ###############################
    routes_in = (
      (r'/', r'/your-website/pages/show_page'),
      (r'/images', r'/your-website/images/images'),
      (r'/contact', r'/your-website/default/contact_form'),
      (r'/robots.txt', r'/your-website/static/robots.txt'),
      (r'/(?P<url>[\w_.-]+)', r'/your-website/pages/show_page/\g<url>'),
    )

    routes_out = [(x, y) for (y, x) in routes_in[:-1:]]
    routes_out += [
        (r'/your-website/pages/show_page/(?P<url>[\w_.-]+)', r'/\g<url>'),
    
    ###############################

    :request.args(0): page to show. This parameter can be either the id 
        or the url of the page
    :type container_id: int (if id) or str (if url).
    """
    from gluon.tools import prettydate

    # Create a Manager toolbar to Create/Update/Delete the files. See db.py model
    # for more informations on ManagerToolbar class
    manager_toolbar = ManagerToolbar('page')

    if request.args(0) and request.args(0).isdigit():
        # we passed the id of the page
        page = db.page(request.args(0))
    else:
        # we passed the url of the page
        page = db(db.page.url==request.args(0)).select().first()
    # if the page has no content, we select the fisrt child
    # before checking for a child, we check if the length of the page content is
    # more than 8 characterd to avoid having a page with just a "<br />" tag
    if page and len(page.content) < 8:
        child = db(db.page.parent==page).select(orderby=db.page.rank|db.page.title).first()
        if child:
            page=child
    if not page:
        if request.args(0) and request.args(0).lower() == 'images':
            redirect(URL('images'))
        else:
            page = db(db.page.is_index==True).select().first()

    # Disqus integration
    disqus_shortname = None
    if page.allow_disqus and WEBSITE_PARAMETERS.disqus_shortname:
        disqus_shortname = WEBSITE_PARAMETERS.disqus_shortname

    # Prettify the date "3 days ago" instead of 20130120 for example
    pretty_date = prettydate(page.modified_on, T)
    header_component = db.page_component(page.header_component)
    left_sidebar_component = db.page_component(page.left_sidebar_component)
    right_sidebar_component = db.page_component(page.right_sidebar_component)
    left_footer_component = db.page_component(page.left_footer_component)
    middle_footer_component = db.page_component(page.middle_footer_component)
    right_footer_component = db.page_component(page.right_footer_component)
    central_component = db.page_component(page.central_component)
    return dict(page=page,
                header_component=header_component,
                left_sidebar_enabled=page.left_sidebar_enabled,
                right_sidebar_enabled=page.right_sidebar_enabled,
                left_sidebar_component=left_sidebar_component,
                right_sidebar_component=right_sidebar_component,
                left_footer_component=left_footer_component,
                middle_footer_component=middle_footer_component,
                right_footer_component=right_footer_component,
                central_component=central_component,
                manager_toolbar=manager_toolbar,
                pretty_date=pretty_date,
                disqus_shortname=disqus_shortname)
Ejemplo n.º 35
0
def show_page():
    """
    Show the requested page.
    You can call this controller either using the id or the url of the page.
    Calling this controller with the url of the page is better for SEO : 
    `http://your-website.com/default/show_page/my-pretty-page` is nicer than
    `http://your-website.com/default/show_page/42`

    A better solution would be to have urls like

    `http://your-website.com/my-pretty-page`
    instead of 
    `http://your-website.com/default/show_page/my-pretty-page`

    Here is an example of a custom routes.py file : 
    ###############################
    routes_in = (
      (r'/', r'/your-website/pages/show_page'),
      (r'/images', r'/your-website/images/images'),
      (r'/contact', r'/your-website/default/contact_form'),
      (r'/robots.txt', r'/your-website/static/robots.txt'),
      (r'/(?P<url>[\w_.-]+)', r'/your-website/pages/show_page/\g<url>'),
    )

    routes_out = [(x, y) for (y, x) in routes_in[:-1:]]
    routes_out += [
        (r'/your-website/pages/show_page/(?P<url>[\w_.-]+)', r'/\g<url>'),
    
    ###############################

    :request.args(0): page to show. This parameter can be either the id 
        or the url of the page
    :type container_id: int (if id) or str (if url).
    """
    from gluon.tools import prettydate

    # Create a Manager toolbar to Create/Update/Delete the files. See db.py model
    # for more informations on ManagerToolbar class
    manager_toolbar = ManagerToolbar('page')

    if request.args(0) and request.args(0).isdigit():
        # we passed the id of the page
        page = db.page(request.args(0))
    else:
        # we passed the url of the page
        page = db(db.page.url == request.args(0)).select().first()
    # if the page has no content, we select the fisrt child
    # before checking for a child, we check if the length of the page content is
    # more than 8 characterd to avoid having a page with just a "<br />" tag
    if page and len(page.content) < 8:
        child = db(db.page.parent == page).select(orderby=db.page.rank
                                                  | db.page.title).first()
        if child:
            page = child
    if not page:
        if request.args(0) and request.args(0).lower() == 'images':
            redirect(URL('images'))
        else:
            page = db(db.page.is_index == True).select().first()

    # Disqus integration
    disqus_shortname = None
    if page.allow_disqus and WEBSITE_PARAMETERS.disqus_shortname:
        disqus_shortname = WEBSITE_PARAMETERS.disqus_shortname

    # Prettify the date "3 days ago" instead of 20130120 for example
    pretty_date = prettydate(page.modified_on, T)
    header_component = db.page_component(page.header_component)
    left_sidebar_component = db.page_component(page.left_sidebar_component)
    right_sidebar_component = db.page_component(page.right_sidebar_component)
    left_footer_component = db.page_component(page.left_footer_component)
    middle_footer_component = db.page_component(page.middle_footer_component)
    right_footer_component = db.page_component(page.right_footer_component)
    central_component = db.page_component(page.central_component)
    return dict(page=page,
                header_component=header_component,
                left_sidebar_enabled=page.left_sidebar_enabled,
                right_sidebar_enabled=page.right_sidebar_enabled,
                left_sidebar_component=left_sidebar_component,
                right_sidebar_component=right_sidebar_component,
                left_footer_component=left_footer_component,
                middle_footer_component=middle_footer_component,
                right_footer_component=right_footer_component,
                central_component=central_component,
                manager_toolbar=manager_toolbar,
                pretty_date=pretty_date,
                disqus_shortname=disqus_shortname)
Ejemplo n.º 36
0
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------
# AppConfig configuration made easy. Look inside private/appconfig.ini
# Auth is for authenticaiton and access control
# -------------------------------------------------------------------------
from gluon.contrib.appconfig import AppConfig
from gluon.tools import Auth

# import prettydate to concert datetime to min ago ot hours ago.
import datetime
d = datetime.datetime(2009, 7, 25, 14, 34, 56)
from gluon.tools import prettydate
pretty_d = prettydate(d, T)
# -------------------------------------------------------------------------
# This scaffolding model makes your app work on Google App Engine too
# File is released under public domain and you can use without limitations
# -------------------------------------------------------------------------

if request.global_settings.web2py_version < "2.15.5":
    raise HTTP(500, "Requires web2py 2.15.5 or newer")

# -------------------------------------------------------------------------
# if SSL/HTTPS is properly configured and you want all HTTP requests to
# be redirected to HTTPS, uncomment the line below:
# -------------------------------------------------------------------------
# request.requires_https()

# -------------------------------------------------------------------------
# once in production, remove reload=True to gain full speed
# -------------------------------------------------------------------------
Ejemplo n.º 37
0
def pdate(value):
    if isinstance(value, str):
        value = datetime.strptime(value, "%s %s" % (DATEFORMAT, TIMEFORMAT))
    return prettydate(value, T=T)
def analyze_task():
    session.forget(response)
    task_id = request.args(0)
    if not task_id:
        return ''
    task = dbs(st.id == task_id).select().first()

    if not task:
        return ''

    q = sr.task_id == task_id

    first_run = dbs(q).select(sr.start_time,
                              orderby=sr.start_time,
                              limitby=(0, 1)).first()

    last_run = dbs(q).select(sr.start_time,
                             orderby=~sr.start_time,
                             limitby=(0, 1)).first()

    first_run_pretty = first_run and prettydate(
        first_run.start_time) or 'Never'
    last_run_pretty = last_run and prettydate(last_run.start_time) or 'Never'

    if not first_run:
        mode = 'no_runs'
        #we can rely on the data on the scheduler_task table because no scheduler_run were found
        q = st.id == task_id
        first_run_pretty = 'Never'
    else:
        mode = 'runs'
    if len(request.args) >= 2:
        if request.args(1) == 'byfunction':
            if mode == 'runs':
                q = sr.task_id.belongs(
                    dbs(st.function_name == task.function_name)._select(st.id))
            else:
                q = st.function_name == task.function_name
        elif request.args(1) == 'bytaskname':
            if mode == 'runs':
                q = sr.task_id.belongs(
                    dbs(st.task_name == task.task_name)._select(st.id))
            else:
                q = st.task_name == task.task_name
        elif request.args(1) == 'this':
            if mode == 'runs':
                q = sr.task_id == task_id
            else:
                q = st.id == task_id

    if len(request.args) == 4 and request.args(2) == 'byday':
        daysback = int(request.args(3))
        now = s.utc_time and request.utcnow or request.now
        day = now.date() - timed(days=daysback)
        if mode == 'runs':
            q = q & ((sr.start_time >= day) &
                     (sr.start_time < day + timed(days=1)))
        else:
            q = q & ((st.last_run_time >= day) &
                     (st.last_run_time < day + timed(days=1)))

    if mode == 'runs':
        gb_duration_rows, jgb_duration_series = gb_duration(q)
        jgb_duration_series = dumps(jgb_duration_series)
    else:
        #no duration can be calculated using the scheduler_task table only
        jgb_duration_series = dumps([])

    gb_status_rows, jgb_status_series = gb_status(q, mode)
    jgb_status_series = dumps(jgb_status_series)

    gb_when_rows, jgb_when_series = bydate(q, mode)
    jgb_when_series = dumps(jgb_when_series)

    if len(request.args) == 4 and request.args(2) == 'byday':
        gb_whend_rows, jgb_whend_series = byday(q, day, mode)
        jgb_whend_series = dumps(jgb_whend_series)
    else:
        jgb_whend_series = dumps([[]])

    return locals()
Ejemplo n.º 39
0
    def generate_comment_on(self, comment_on):
        """Generate on"""

        return prettydate(comment_on)