Beispiel #1
0
def main():
    session, term = getsession(), getterminal()
    session.activity = 'Viewing Userlist'

    colors = {'highlight': term.red,
              'lowlight': term.green, }

    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    # get and format userlist
    userlist = (
        u'{sp}{handle} {location} {lastcall}'
        .format(sp=u' ' * 4,
                handle=ur.handle.ljust(username_max_length),
                location=colors['lowlight'](
                    ur.location.ljust(location_max_length)),
                lastcall=timeago(ur.timeago))
        for ur in iter_userlist())

    echo(u'\r\n')

    # display users, using a command-prompt pager.
    prompt_pager(content=userlist,
                 line_no=line_no + 1,
                 colors={'highlight': term.red,
                         'lowlight': term.green,
                         },
                 width=80, breaker=None)
Beispiel #2
0
def main():
    session, term = getsession(), getterminal()
    session.activity = 'Viewing Userlist'

    colors = {
        'highlight': term.red,
        'lowlight': term.green,
    }

    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    # get and format userlist
    userlist = (u'{sp}{handle} {location} {lastcall}'.format(
        sp=u' ' * 4,
        handle=ur.handle.ljust(username_max_length),
        location=colors['lowlight'](ur.location.ljust(location_max_length)),
        lastcall=timeago(ur.timeago)) for ur in iter_userlist())

    echo(u'\r\n')

    # display users, using a command-prompt pager.
    prompt_pager(content=userlist,
                 line_no=line_no + 1,
                 colors={
                     'highlight': term.red,
                     'lowlight': term.green,
                 },
                 width=80,
                 breaker=None)
Beispiel #3
0
def main(last=10):
    """
    Script entry point.

    :param last: Number of last callers to display
    :type last: int
    """
    session, term = getsession(), getterminal()
    session.activity = u'Viewing last callers'

    colors = [term.green, term.bright_blue, term.bold,
              term.cyan, term.bold_black]

    # set syncterm font, if any
    if syncterm_font and term._kind.startswith('ansi'):
        echo(syncterm_setfont(syncterm_font))

    # display banner
    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    # get last callers
    last_callers = get_lastcallers(last=last)
    echo(u'\r\n\r\n')

    # format callers, header:
    callers_txt = [
        '{handle} {location} {num_calls} {timeago}'
        .format(
            handle=term.bold_underline(
                term.ljust('handle', username_max_length + 1)),
            location=term.underline(
                term.ljust('location', location_max_length)),
            num_calls=term.bold_underline(
                term.ljust('# calls', numcalls_max_length)),
            timeago=term.underline('time ago'))
    ]
    # content:
    callers_txt.extend([
        u'{handle} {location} {num_calls} {timeago}'
        .format(handle=lc.handle.ljust(username_max_length + 1),
                location=term.ljust(colors[idx % len(colors)](
                    lc.location or '-' * location_max_length),
                    location_max_length),
                num_calls='{0}'.format(
                    lc.num_calls).rjust(numcalls_max_length),
                timeago=colors[idx % len(colors)](
                    timeago(lc.timeago))
                ) for idx, lc in enumerate(last_callers)
    ])

    # display file contents, decoded, using a command-prompt pager.
    prompt_pager(content=callers_txt,
                 line_no=line_no + 2,
                 colors={'highlight': term.bright_green,
                         'lowlight': term.cyan, },
                 width=max(term.length(txt) for txt in callers_txt),
                 breaker=None)
Beispiel #4
0
def list_results(questionnumber):
    term = getterminal()
    db = DBProxy(databasename)
    alternatives = {}
    questions = []
    results = []
    amount_of_alternatives = db['amount_of_alternatives']
    alternatives = db['alternatives']
    questions = db['questions']
    results = db['results']

    echo(term.clear())

    text = (term.white + questions[questionnumber] + u'\r\n' + term.blue +
            u'-' * len(questions[questionnumber]) + u'\r\n\r\n')

    # only display full statistics if the screen width is above 79 columns.
    if term.width > 79:
        text = text + (term.magenta + u'(alternatives)' + term.move_x(49) +
                       u'(votes)' + term.move_x(57) + u'(percentage)\r\n')
        totalvotes = 0.00
        for i in range(0, amount_of_alternatives[questionnumber]):
            totalvotes = totalvotes + results[(questionnumber, i)]
        for i in range(0, amount_of_alternatives[questionnumber]):
            if results[(questionnumber, i)] > 0:
                percentage = (results[(questionnumber, i)] / totalvotes) * 100
            else:
                percentage = 0
            staple = int(round(percentage / 5))
            text = text + u''.join(
                term.move_x(0) + term.white(alternatives[
                    (questionnumber, i)]) + term.move_x(49) +
                term.cyan(str(results[(questionnumber, i)])) + u'  ' +
                term.cyan + str(int(percentage)) + term.cyan(u'%') +
                term.move_x(57) + term.cyan(u'[') + term.green('#' * staple) +
                term.move_x(78) + term.cyan(']'))
            if i != amount_of_alternatives[questionnumber]:
                text = text + u'\r\n'
    else:
        for i in range(0, amount_of_alternatives[questionnumber]):
            text = text + (term.white(str(alternatives[(questionnumber, i)])) +
                           term.cyan(u' votes: ') + term.magenta(
                               str(results[(questionnumber, i)])) + u'\r\n')

    text = text.splitlines()
    prompt_pager(content=text,
                 line_no=0,
                 colors={
                     'highlight': term.cyan,
                     'lowlight': term.green,
                 },
                 width=term.width,
                 breaker=None,
                 end_prompt=False)
    echo(term.move_x(0) + term.bold_black(u'* = already voted\r\n'))
    waitprompt(term)
Beispiel #5
0
Datei: lc.py Projekt: tehmaze/x84
def main(last=10):
    """
    Script entry point.

    :param int last: Number of last callers to display
    """
    session, term = getsession(), getterminal()
    session.activity = u'Viewing last callers'

    colors = [term.green, term.bright_blue, term.bold,
              term.cyan, term.bold_black]

    # set syncterm font, if any
    if syncterm_font and term.kind.startswith('ansi'):
        echo(syncterm_setfont(syncterm_font))

    # display banner
    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    # get last callers
    last_callers = get_lastcallers(last=last)
    echo(u'\r\n\r\n')

    # format callers, header:
    callers_txt = [
        '{handle} {location} {num_calls} {timeago}'
        .format(
            handle=term.bold_underline(
                term.ljust('handle', username_max_length + 1)),
            location=term.underline(
                term.ljust('location', location_max_length)),
            num_calls=term.bold_underline(
                term.ljust('# calls', numcalls_max_length)),
            timeago=term.underline('time ago'))
    ]
    # content:
    callers_txt.extend([
        u'{handle} {location} {num_calls} {timeago}'
        .format(handle=lc.handle.ljust(username_max_length + 1),
                location=term.ljust(colors[idx % len(colors)](
                    lc.location or '-' * location_max_length),
                    location_max_length),
                num_calls='{0}'.format(
                    lc.num_calls).rjust(numcalls_max_length),
                timeago=colors[idx % len(colors)](
                    timeago(lc.timeago))
                ) for idx, lc in enumerate(last_callers)
    ])

    # display file contents, decoded, using a command-prompt pager.
    prompt_pager(content=callers_txt,
                 line_no=line_no + 2,
                 colors={'highlight': term.bright_green,
                         'lowlight': term.cyan, },
                 width=max(term.length(txt) for txt in callers_txt),
                 breaker=None)
Beispiel #6
0
def main():
    session, term = getsession(), getterminal()
    session.activity = 'Viewing Userlist'

    colors = {
        'highlight': term.red,
        'lowlight': term.green,
    }

    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    def make_header(fmt):
        return fmt.format(
            handle=term.bold('handle'.ljust(username_max_length)),
            location=term.bold('location'.ljust(location_max_length)),
            lastcall=term.bold('time ago').ljust(8))

    userlist_fmt = u'| {handle} | {location} | {lastcall} |'

    header = make_header(userlist_fmt)
    header_length = term.length(header)

    # for smaller screens, remove 'location' field.
    if header_length > term.width:
        userlist_fmt = u'| {handle} | {lastcall} |'
        header = make_header(userlist_fmt)
        header_length = term.length(header)

    userlist = [header] + ['-' * header_length]

    echo(u'Fetching ... ')
    for _ur in iter_userlist():
        location_txt = u''
        if 'location' in userlist_fmt:
            location_txt = colors['lowlight'](
                _ur.location.ljust(location_max_length))
        timeago_txt = timeago(_ur.timeago).ljust(8)
        handle_txt = _ur.handle.ljust(username_max_length)

        userlist.append(
            userlist_fmt.format(handle=handle_txt,
                                location=location_txt,
                                lastcall=timeago_txt))

    echo(term.move_x(0) + term.clear_eol + u'Processing ...' + term.move_x(0))

    # display users, using a command-prompt pager.
    prompt_pager(content=userlist,
                 line_no=line_no + 1,
                 colors={
                     'highlight': term.red,
                     'lowlight': term.green,
                 },
                 width=80,
                 breaker=None)
Beispiel #7
0
def query_question():
    term = getterminal()
    session = getsession()
    db = DBProxy(databasename)
    questions = []
    index = []
    uservotingdata = []
    questions = db['questions']
    index = db['index']

    # create a new database file if none exists
    if not session.user.handle in db:
        db[session.user.handle] = {}
    uservotingdata = db[session.user.handle]

    echo(term.clear() + term.blue(u'>>') +
         term.white(u'questions availible\r\n') +
         term.blue(u'-' * 21 + '\r\n\r\n'))

    text = ''
    for i in range(0, len(questions)):
        if (index[i], 0) in uservotingdata:
            text = text + term.green(u'*')
        text = text + u''.join(term.magenta + u'(' + term.cyan + str(i) +
                               term.magenta + u') ' + term.white +
                               questions[i] + u'\r\n')
    text = text.splitlines()
    prompt_pager(content=text,
                 line_no=0,
                 colors={
                     'highlight': term.cyan,
                     'lowlight': term.green,
                 },
                 width=term.width,
                 breaker=None,
                 end_prompt=False)
    echo(term.move_x(0) + term.bold_black(u'* = already voted\r\n\r\n'))

    while True:
        echo(
            term.move_x(0) + term.magenta(
                u'select one of the questions above or press enter to return: '
            ))
        le = LineEditor(10)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp is not None and inp.isnumeric() and int(inp) < len(questions):
            return int(inp)
        else:
            # -1 in this case means that no valid option was chosen.. break
            # loop.
            return -1
Beispiel #8
0
def main():
    session, term = getsession(), getterminal()
    session.activity = 'Viewing Userlist'

    colors = {'highlight': term.red,
              'lowlight': term.green, }

    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    def make_header(fmt):
        return fmt.format(
            handle=term.bold('handle'.ljust(username_max_length)),
            location=term.bold('location'.ljust(location_max_length)),
            lastcall=term.bold('time ago').ljust(8))

    userlist_fmt = u'| {handle} | {location} | {lastcall} |'

    header = make_header(userlist_fmt)
    header_length = term.length(header)

    # for smaller screens, remove 'location' field.
    if header_length > term.width:
        userlist_fmt = u'| {handle} | {lastcall} |'
        header = make_header(userlist_fmt)
        header_length = term.length(header)

    userlist = [header] + ['-' * header_length]

    for _ur in iter_userlist():
        location_txt = u''
        if 'location' in userlist_fmt:
            location_txt = colors['lowlight'](
                _ur.location.ljust(location_max_length))
        timeago_txt = timeago(_ur.timeago).ljust(8)
        handle_txt = _ur.handle.ljust(username_max_length)

        userlist.append(userlist_fmt.format(
            handle=handle_txt,
            location=location_txt,
            lastcall=timeago_txt))

    echo(u'\r\n')

    # display users, using a command-prompt pager.
    prompt_pager(content=userlist,
                 line_no=line_no + 1,
                 colors={'highlight': term.red,
                         'lowlight': term.green,
                         },
                 width=80, breaker=None)
Beispiel #9
0
def list_results(questionnumber):
    term = getterminal()
    db = DBProxy(databasename)
    alternatives = {}
    questions = []
    results = []
    amount_of_alternatives = db['amount_of_alternatives']
    alternatives = db['alternatives']
    questions = db['questions']
    results = db['results']

    echo(term.clear())

    text = (term.white + questions[questionnumber] + u'\r\n' + term.blue +
            u'-' * len(questions[questionnumber]) + u'\r\n\r\n')

    # only display full statistics if the screen width is above 79 columns.
    if term.width > 79:
        text = text + (term.magenta + u'(alternatives)' + term.move_x(49) +
                       u'(votes)' + term.move_x(57) + u'(percentage)\r\n')
        totalvotes = 0.00
        for i in range(0, amount_of_alternatives[questionnumber]):
            totalvotes = totalvotes + results[(questionnumber, i)]
        for i in range(0, amount_of_alternatives[questionnumber]):
            if results[(questionnumber, i)] > 0:
                percentage = (results[(questionnumber, i)] / totalvotes) * 100
            else:
                percentage = 0
            staple = int(round(percentage / 5))
            text = text + u''.join(term.move_x(0) + term.white(alternatives[(questionnumber, i)]) + term.move_x(49) +
                                   term.cyan(str(results[(questionnumber, i)])) + u'  ' + term.cyan + str(int(percentage)) +
                                   term.cyan(u'%') + term.move_x(57) + term.cyan(u'[') +
                                   term.green('#' * staple) + term.move_x(78) + term.cyan(']'))
            if i != amount_of_alternatives[questionnumber]:
                text = text + u'\r\n'
    else:
        for i in range(0, amount_of_alternatives[questionnumber]):
            text = text + (term.white(str(alternatives[(questionnumber, i)])) + term.cyan(u' votes: ') +
                           term.magenta(str(results[(questionnumber, i)])) + u'\r\n')

    text = text.splitlines()
    prompt_pager(content=text,
                 line_no=0,
                 colors={'highlight': term.cyan,
                         'lowlight': term.green,
                         },
                 width=term.width, breaker=None, end_prompt=False)
    echo(term.move_x(0) + term.bold_black(u'* = already voted\r\n'))
    waitprompt(term)
Beispiel #10
0
def query_question():
    term = getterminal()
    session = getsession()
    db = DBProxy(databasename)
    questions = []
    index = []
    uservotingdata = []
    questions = db['questions']
    index = db['index']

    # create a new database file if none exists
    if not session.user.handle in db:
        db[session.user.handle] = {}
    uservotingdata = db[session.user.handle]

    echo(term.clear() + term.blue(u'>>') + term.white(u'questions availible\r\n') +
         term.blue(u'-' * 21 + '\r\n\r\n'))

    text = ''
    for i in range(0, len(questions)):
        if (index[i], 0) in uservotingdata:
            text = text + term.green(u'*')
        text = text + u''.join(term.magenta + u'(' + term.cyan + str(i) + term.magenta + u') ' +
                              term.white + questions[i] + u'\r\n')
    text = text.splitlines()
    prompt_pager(content=text,
                 line_no=0,
                 colors={'highlight': term.cyan,
                         'lowlight': term.green,
                         },
                 width=term.width, breaker=None, end_prompt=False)
    echo(term.move_x(0) + term.bold_black(u'* = already voted\r\n\r\n'))

    while True:
        echo(term.move_x(
            0) + term.magenta(u'select one of the questions above or press enter to return: '))
        le = LineEditor(10)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp is not None and inp.isnumeric() and int(inp) < len(questions):
            return int(inp)
        else:
            # -1 in this case means that no valid option was chosen.. break
            # loop.
            return -1
Beispiel #11
0
def display_message(session, term, msg_index, colors):
    """ Format message of index ``idx``. """
    color_handle = lambda handle: (colors["highlight"](handle) if handle == session.user.handle else handle)
    msg = get_msg(msg_index)
    txt_sent = msg.stime.replace(tzinfo=dateutil.tz.tzlocal()).astimezone(dateutil.tz.tzutc()).strftime(TIME_FMT)
    txt_sentago = colors["highlight"](timeago((datetime.datetime.now() - msg.stime).total_seconds()).strip())
    txt_to = color_handle(msg.recipient)
    txt_private = colors["highlight"](" (private)") if not "public" in msg.tags else u""
    txt_from = color_handle(msg.author)
    txt_tags = u", ".join((quote(tag, colors) for tag in msg.tags))
    txt_subject = colors["highlight"](msg.subject)
    txt_body = decode_pipe(msg.body)
    txt_breaker = ("-" if session.encoding == "ansi" else u"\u2500") * min(80, term.width)
    msg_txt = (
        u"\r\n{txt_breaker}\r\n"
        u"   from: {txt_from}\r\n"
        u"     to: {txt_to}{txt_private}\r\n"
        u"   sent: {txt_sent} ({txt_sentago} ago)\r\n"
        u"   tags: {txt_tags}\r\n"
        u"subject: {txt_subject}\r\n"
        u"\r\n"
        u"{txt_body}\r\n".format(
            txt_breaker=txt_breaker,
            txt_from=txt_from,
            txt_to=txt_to,
            txt_sent=txt_sent,
            txt_sentago=txt_sentago,
            txt_tags=txt_tags,
            txt_subject=txt_subject,
            txt_body=txt_body,
            txt_private=txt_private,
        )
    )

    do_mark_as_read(session, [msg_index])

    prompt_pager(
        content=msg_txt.splitlines(),
        line_no=0,
        width=min(80, term.width),
        colors=colors,
        breaker=u"- ",
        end_prompt=False,
        break_long_words=True,
    )
Beispiel #12
0
def main(quick=False):
    """
    Script entry point.

    :param quick: When True, returns early if this news has already been read.
    :type quick: bool
    """
    session, term = getsession(), getterminal()

    if not os.path.exists(news_file):
        log.warn('No news file, {0}'.format(news_file))
        echo(u'\r\n\r\n' + term.center(u'No news.').rstrip() + u'\r\n')
        return

    # return early if 'quick' is True and news is not new
    news_mtime = os.stat(news_file).st_mtime
    if quick and news_mtime < session.user.get('news_lastread', 0):
        return

    # set syncterm font, if any
    if syncterm_font and term._kind == 'ansi':
        echo(syncterm_setfont(syncterm_font))

    session.activity = 'Reading news'

    # display banner
    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    # retrieve news_file contents (decoded as utf8)
    news = decode_pipe(codecs.open(
        news_file, 'rb', news_file_encoding).read()
    ).splitlines()
    echo(u'\r\n\r\n')

    # display file contents, decoded, using a command-prompt pager.
    prompt_pager(content=news,
                 line_no=line_no + 2,
                 colors={'highlight': term.yellow,
                         'lowlight': term.green,
                         },
                 width=80)

    # update user's last-read time of news.
    session.user['news_lastread'] = time.time()
Beispiel #13
0
def main(quick=False):
    """
    Script entry point.

    :param bool quick: When True, returns early if this news has already
                       been read.
    """
    session, term = getsession(), getterminal()

    if not os.path.exists(news_file):
        log.warn('No news file, {0}'.format(news_file))
        echo(u'\r\n\r\n' + term.center(u'No news.').rstrip() + u'\r\n')
        return

    # return early if 'quick' is True and news is not new
    news_mtime = os.stat(news_file).st_mtime
    if quick and news_mtime < session.user.get('news_lastread', 0):
        return

    # set syncterm font, if any
    if syncterm_font and term.kind == 'ansi':
        echo(syncterm_setfont(syncterm_font))

    session.activity = 'Reading news'

    # display banner
    line_no = display_banner(filepattern=art_file, encoding=art_encoding)

    # retrieve news_file contents (decoded as utf8)
    news = decode_pipe(
        codecs.open(news_file, 'rb', news_file_encoding).read()).splitlines()
    echo(u'\r\n\r\n')

    # display file contents, decoded, using a command-prompt pager.
    prompt_pager(content=news,
                 line_no=line_no + 2,
                 colors={
                     'highlight': term.yellow,
                     'lowlight': term.green,
                 },
                 width=min(80, term.width))

    # update user's last-read time of news.
    session.user['news_lastread'] = time.time()
Beispiel #14
0
def display_message(session, term, msg_index, colors):
    """ Format message of index ``idx``. """
    color_handle = lambda handle: (colors['highlight'](handle) if handle ==
                                   session.user.handle else handle)
    msg = get_msg(msg_index)
    txt_sent = msg.stime.replace(tzinfo=dateutil.tz.tzlocal()).astimezone(
        dateutil.tz.tzutc()).strftime(TIME_FMT)
    txt_sentago = colors['highlight'](timeago(
        (datetime.datetime.now() - msg.stime).total_seconds()).strip())
    txt_to = color_handle(msg.recipient)
    txt_private = (colors['highlight'](' (private)')
                   if not 'public' in msg.tags else u'')
    txt_from = color_handle(msg.author)
    txt_tags = u', '.join((quote(tag, colors) for tag in msg.tags))
    txt_subject = colors['highlight'](msg.subject)
    txt_body = decode_pipe(msg.body)
    txt_breaker = ('-' if session.encoding == 'ansi' else u'\u2500') * min(
        80, term.width)
    msg_txt = (u'\r\n{txt_breaker}\r\n'
               u'   from: {txt_from}\r\n'
               u'     to: {txt_to}{txt_private}\r\n'
               u'   sent: {txt_sent} ({txt_sentago} ago)\r\n'
               u'   tags: {txt_tags}\r\n'
               u'subject: {txt_subject}\r\n'
               u'\r\n'
               u'{txt_body}\r\n'.format(txt_breaker=txt_breaker,
                                        txt_from=txt_from,
                                        txt_to=txt_to,
                                        txt_sent=txt_sent,
                                        txt_sentago=txt_sentago,
                                        txt_tags=txt_tags,
                                        txt_subject=txt_subject,
                                        txt_body=txt_body,
                                        txt_private=txt_private))

    do_mark_as_read(session, [msg_index])

    prompt_pager(content=msg_txt.splitlines(),
                 line_no=0,
                 width=min(80, term.width),
                 colors=colors,
                 breaker=u'- ',
                 end_prompt=False,
                 break_long_words=True)
Beispiel #15
0
def main():
    """ Script entry point. """

    term, session = getterminal(), getsession()
    # colors
    prompt_lowlight = getattr(term, PROMPT_LOWLIGHT_COLOR)
    prompt_highlight = getattr(term, PROMPT_HIGHLIGHT_COLOR)
    lightbar_border = getattr(term, LIGHTBAR_BORDER_COLOR)
    lightbar_lowlight = getattr(term, LIGHTBAR_LOWLIGHT_COLOR)
    lightbar_highlight = getattr(term, LIGHTBAR_HIGHLIGHT_COLOR)
    header_highlight = getattr(term, HEADER_HIGHLIGHT_COLOR)
    header_lowlight = getattr(term, HEADER_LOWLIGHT_COLOR)
    text_highlight = getattr(term, TEXT_HIGHLIGHT_COLOR)
    text_lowlight = getattr(term, TEXT_LOWLIGHT_COLOR)


    def error_message(message):
        """
        Display the given error message.

        :param str message: The error message to display
        """

        echo(term.bright_red(message))
        term.inkey(timeout=3)

    def get_sign(force=False):
        """
        Return the user's sign or let them choose one using a Lightbar.

        :param bool force: If True, does not retrive the user's sign from the db
        :rtype: :class:`str`
        """

        database = DBProxy('astrology', table='users')

        if not force and session.user.handle in database:
            return database[session.user.handle]

        lbar = Lightbar(width=15, height=14, xloc=max(term.width / 2 - 7, 0),
                        yloc=max(term.height / 2 - 7, 0),
                        colors={'border': lightbar_border,
                                'highlight': lightbar_highlight,
                                'lowlight': lightbar_lowlight},
                        glyphs={'top-left': u'+', 'top-right': u'+',
                                'top-horiz': u'-', 'bot-horiz': u'-',
                                'bot-left': u'+', 'bot-right': u'+',
                                'left-vert': u'|', 'right-vert': u'|'})

        def refresh():
            """ Refresh the lightbar. """
            echo(u''.join((term.normal, term.clear)))
            contents = ((key, key) for key in SIGNS)
            lbar.update(contents)
            echo(u''.join([lbar.border(), lbar.refresh()]))

        refresh()

        while not lbar.selected and not lbar.quit:
            event, data = session.read_events(['refresh', 'input'])

            if event == 'refresh':
                refresh()
            elif event == 'input':
                session.buffer_input(data, pushback=True)
                echo(lbar.process_keystroke(term.inkey()))

        if lbar.quit:
            return

        sign, _ = lbar.selection
        database[session.user.handle] = sign

        return sign

    def get_horoscope(sign):
        """
        Retrieve the horoscope for the user's selected astrological sign.

        :param str sign: The user's astrological sign
        :rtype: :class:`str`
        """

        database = DBProxy('astrology', table='horoscope')
        nowdate = date.today()

        if 'horoscope' not in database:
            database['horoscope'] = {'date': None}

        if database['horoscope']['date'] != nowdate:
            req = None
            echo(u''.join((term.normal, u'\r\n', prompt_lowlight,
                           u'Retrieving horoscope... ', term.normal)))

            try:
                req = requests.get(
                    'http://www.api.littleastro.com/restserver/index.php'
                    '/api/horoscope/readings/format/json')
            except requests.exceptions.RequestException:
                return error_message(u'Error retrieving horoscope.')

            response = None

            try:
                response = json.loads(req.text)
            except TypeError:
                return error_message(u'Error parsing response.')

            with database:
                try:
                    for element in response:
                        horoscope = {'daily': element['Daily_Horoscope'],
                                     'weekly': element['Weekly_Horoscope'],
                                     'monthly': element['Monthly_Horoscope']}
                        database[element['Sign']] = horoscope
                except KeyError:
                    return error_message(u'Invalid response.')

            database['horoscope'] = {'date': nowdate}

        return database[sign]

    def input_prompt():
        """
        Quit on input or allow the user to change their astrological sign.
        """

        echo(u''.join((term.normal, u'\r\n\r\n',
                       term.move_x(max(term.width / 2 - 40, 0)),
                       prompt_lowlight(u'Press '),
                       prompt_highlight(u'!'),
                       prompt_lowlight(u' to change your sign or '),
                       prompt_highlight(u'any other key'),
                       prompt_lowlight(u' to continue'))))
        inp = getch()

        if inp == u'!':
            get_sign(force=True)
            main()

    sign = get_sign()

    if not sign:
        return

    horoscope = get_horoscope(sign)

    if not horoscope:
        return

    daily = u'{period} {horoscope}' \
            .format(period=text_highlight(u'Today:'),
                    horoscope=text_lowlight(horoscope['daily']))
    weekly = u'{period} {horoscope}' \
             .format(period=text_highlight(u'This week:'),
                     horoscope=text_lowlight(horoscope['weekly']))
    monthly = u'{period} {horoscope}' \
              .format(period=text_highlight(u'This month:'),
                      horoscope=text_lowlight(horoscope['monthly']))
    echo(u''.join((term.normal, term.clear)))
    output = u''.join((u'\r\n',
                       header_highlight(u''.join((sign[0].upper(), sign[1:]))),
                       u'\r\n',
                       header_lowlight(u'-' * len(sign)),
                       u'\r\n\r\n',))

    wrapwidth = min(80, term.width - 1)

    for line in term.wrap(daily, wrapwidth):
        output += text_lowlight(line) + u'\r\n'

    output += u'\r\n'

    for line in term.wrap(weekly, wrapwidth):
        output += text_lowlight(line) + u'\r\n'

    output += u'\r\n'

    for line in term.wrap(monthly, wrapwidth):
        output += text_lowlight(line) + u'\r\n'

    wrapped = output.splitlines()

    prompt_pager(wrapped, end_prompt=False, width=min(term.width - 1, 80),
                 colors={'highlight': prompt_highlight,
                         'lowlight': prompt_lowlight})
    input_prompt()
Beispiel #16
0
def vote(questionnumber):
    term = getterminal()
    session = getsession()
    db = DBProxy(databasename)
    questions = []
    amount_of_alternatives = []
    alternatives = {}
    results = {}
    index = []
    questions = db['questions']
    alternatives = db['alternatives']
    results = db['results']
    amount_of_alternatives = db['amount_of_alternatives']
    index = db['index']

    echo(term.clear() + term.white + questions[questionnumber] + u'\r\n' +
         term.blue(u'-' * len(questions[questionnumber])) + u'\r\n\r\n')
    text = ''
    for i in range(0, amount_of_alternatives[questionnumber]):
        text = text + (term.magenta + u'(' + term.cyan + str(i) + term.magenta + u') ' +
                       term.white + alternatives[(questionnumber, i)] + u'\r\n')

    text = text.splitlines()
    prompt_pager(content=text,
                 line_no=0,
                 colors={'highlight': term.cyan,
                         'lowlight': term.green,
                         },
                 width=term.width, breaker=None, end_prompt=False)
    echo(term.move_x(0) + term.magenta(u'(') + term.cyan(str(amount_of_alternatives[questionnumber])) +
         term.magenta(u') ') + term.bold_black(u'Add your own answer..\r\n\r\n'))

    while True:
        echo(term.move_x(0) + term.magenta(u'Your choice: '))
        le = LineEditor(10)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp is not None and inp.isnumeric() and int(
                inp) <= amount_of_alternatives[questionnumber]:

            # create database for user if the user hasn't made any votes
            if session.user.handle not in db:
                db[session.user.handle] = {}

            uservotingdata = {}
            uservotingdata = db[session.user.handle]

            # if user wants to create an own alternative..
            if int(inp) == amount_of_alternatives[questionnumber]:
                echo(term.clear + term.red + u'\r\nPress enter to abort. ' +
                     term.move(0, 0) + term.white(u'Your answer: '))
                le = LineEditor(48)
                new_alternative = le.read()
                if new_alternative == '' or new_alternative == None:
                    return
                results[(questionnumber, int(inp))] = 0  # init..
                # init..
                alternatives[(questionnumber, int(inp))] = new_alternative
                amount_of_alternatives[
                    questionnumber] = amount_of_alternatives[questionnumber] + 1
                db['alternatives'] = alternatives
                db['amount_of_alternatives'] = amount_of_alternatives

            # if the user has voted on this question before..
            if (index[questionnumber], 0) in uservotingdata:
                temp2 = uservotingdata[(index[questionnumber], 0)]
                results[(questionnumber, temp2)] = results[
                    (questionnumber, temp2)] - 1  # remove the old vote
                results[(questionnumber, int(inp))] = results[
                    (questionnumber, int(inp))] + 1
                uservotingdata[(index[questionnumber], 0)] = int(inp)
            else:
                uservotingdata[(index[questionnumber], 0)] = int(inp)
                results[(questionnumber, int(inp))] = results[
                    (questionnumber, int(inp))] + 1

            uservotingdata[(index[questionnumber], 0)] = int(inp)

            echo(term.green(u'\r\nyour vote has been noted, thanks..'))
            term.inkey(2)
            db['results'] = results
            db[session.user.handle] = uservotingdata
            list_results(questionnumber)
            return