Esempio n. 1
0
def set_password(user):
    """
    Prompt for user.password, minimum length.
    """
    # pylint: disable=R0914
    #        Too many local variables
    from x84.bbs import getterminal, echo, ini, LineEditor
    term = getterminal()
    hidden_ch = u'x'
    prompt_password = u'password: '******'   again: '
    msg_empty = u'ENtER A PASSWORd!'
    msg_tooshort = u'TOO ShORt, MUSt bE At lEASt %s.'
    msg_unmatched = u'VERifY MUSt MAtCH!'
    width = ini.CFG.getint('nua', 'max_pass')
    min_pass = ini.CFG.getint('nua', 'min_pass')
    while True:
        echo(u'\r\n\r\n' + term.clear_eol + term.normal + prompt_password)
        led = LineEditor(width)
        led.hidden = hidden_ch
        password = led.read()
        if password == u'' or password is None:
            warning(msg_empty)
        elif len(password) < min_pass:
            warning(msg_tooshort % min_pass)
        else:
            echo(u'\r\n\r\n' + term.clear_eol + term.normal + prompt_verify)
            led = LineEditor(width)
            led.hidden = hidden_ch
            verify = led.read()
            if password != verify:
                warning(msg_unmatched)
                continue
            user.password = password
            return
Esempio n. 2
0
def add_question():
    term = getterminal()
    db = DBProxy(databasename)
    questions = []
    amount_of_alternatives = []
    index = {}
    alternatives = {}
    results = {}
    index = db['index']
    questions = db['questions']
    alternatives = db['alternatives']
    results = db['results']
    amount_of_alternatives = db['amount_of_alternatives']
    amount_of_questions = len(questions)

    echo(term.clear + term.white + u'\r\nQuestion: ')
    le = LineEditor(65)
    new_question = le.read()
    if new_question == '' or new_question == None:
        return

    echo(
        term.bold_black(u'\r\n\r\nLeave a blank line when you are finished..'))
    new_amount = 0
    while True:
        echo(term.normal + term.white + u'\r\nchoice ' + term.red +
             str(new_amount) + term.white + u': ')
        le = LineEditor(48)
        alternatives[(amount_of_questions, new_amount)] = le.read()
        if alternatives[(amount_of_questions,
                         new_amount)] == '' or alternatives[(
                             amount_of_questions, new_amount)] == None:
            break
        else:
            results[(amount_of_questions, new_amount)] = 0
            new_amount = new_amount + 1

    if new_amount > 0:
        echo(term.white(u'\r\n\r\nSave this voting question?'))
        answer = ynprompt()
        if answer == 1:
            questions.append(new_question)
            amount_of_alternatives.append(new_amount)

            indexcounter = db['indexcounter']
            indexcounter = indexcounter + 1
            index.append(str(indexcounter))

            db['indexcounter'] = indexcounter
            db['index'] = index
            db['questions'] = questions
            db['amount_of_alternatives'] = amount_of_alternatives
            db['results'] = results
            db['amount_of_questions'] = amount_of_questions
            db['alternatives'] = alternatives

            waitprompt(term)
Esempio n. 3
0
File: vote.py Progetto: tehmaze/x84
def add_question():
    term = getterminal()

    db = DBProxy(databasename)
    questions = []
    amount_of_alternatives = []
    index = {}
    alternatives = {}
    results = {}
    index = db['index']
    questions = db['questions']
    alternatives = db['alternatives']
    results = db['results']
    amount_of_alternatives = db['amount_of_alternatives']
    amount_of_questions = len(questions)

    echo(term.clear + term.white + '\r\nQuestion: ')
    le = LineEditor(65)
    new_question = le.read()
    if new_question == '':
        return

    echo(
        term.bold_black + '\r\n\r\nLeave a blank line when you are finished..')
    new_amount = 0
    while True:
        echo(term.normal + term.white + '\r\nchoice ' +
             term.red + str(new_amount) + term.white + ': ')
        le = LineEditor(48)
        alternatives[(amount_of_questions, new_amount)] = le.read()
        if alternatives[(amount_of_questions, new_amount)] == '':
            break
        else:
            results[(amount_of_questions, new_amount)] = 0
            new_amount = new_amount + 1

    if new_amount > 0:
        echo(term.normal + term.white + '\r\n\r\nSave this voting question?')
        answer = ynprompt()
        if answer == 1:
            questions.append(new_question)
            amount_of_alternatives.append(new_amount)

            indexcounter = db['indexcounter']
            indexcounter = indexcounter + 1
            index.append(str(indexcounter))

            db['indexcounter'] = indexcounter
            db['index'] = index
            db['questions'] = questions
            db['amount_of_alternatives'] = amount_of_alternatives
            db['results'] = results
            db['amount_of_questions'] = amount_of_questions
            db['alternatives'] = alternatives

            waitprompt()
Esempio n. 4
0
File: ol.py Progetto: donfanning/x84
def saysomething(dumb=True):
    """
    Prompt user to post oneliner, also prompt user to post
    to bbs-scene.org if configured, returning background Thread.
    """
    import time
    from x84.bbs import getsession, getterminal, echo, LineEditor, ini
    session, term = getsession(), getterminal()
    prompt_say = u'SAY WhAt ?! '
    # heard_msg = u'YOUR MESSAGE hAS bEEN VOiCEd.'

    yloc = term.height - 3
    xloc = max(0, ((term.width / 2) - (MAX_INPUT / 2)))
    if dumb:
        echo(u'\r\n\r\n' + term.bold_blue(prompt_say))
    else:
        echo(term.move(yloc, xloc) or u'\r\n\r\n')
        echo(term.bold_blue(prompt_say))
    ole = LineEditor(MAX_INPUT)
    ole.highlight = term.green_reverse
    oneliner = ole.read()
    if oneliner is None or 0 == len(oneliner.strip()):
        if not dumb:
            # clear input line,
            echo(term.normal + term.move(yloc, 0) + term.clear_eol)
        return None

    session.user['lastliner'] = time.time()
    # post local-onlyw hen bbs-scene.org is not configured
    if not ini.CFG.has_section('bbs-scene'):
        add_oneline(oneliner.strip())
        return None
    return post_bbs_scene(oneliner, dumb)
Esempio n. 5
0
def upload_files(term, protocol='xmodem1k'):
    """ Upload files. """
    echo(term.clear)
    while True:
        echo(u'Filename (empty to quit):\r\n')
        led = LineEditor(width=term.width - 1)
        led.refresh()
        inp = led.read()
        led = None
        if inp:
            for illegal in (os.path.sep, u'..', u'~',):
                if illegal in inp:
                    echo(term.bold_red(u'\r\nIllegal filename.\r\n'))
                    term.inkey()
                    return

            echo(term.bold(
                u'\r\nBegin your {0} sending program now.\r\n'
                .format(protocol)))

            upload_filename = os.path.join(UPLOADS_DIR, inp)
            try:
                upload = open(upload_filename, 'wb')
            except IOError as err:
                echo(term.bold_red('u\r\nIOError: {err}\r\n'.format(err=err)))
            else:
                if not recv_modem(upload, protocol):
                    echo(term.bold_red(u'Upload failed!\r\n'))
                    os.unlink(upload_filename)
                else:
                    echo(term.bold_green(u'Transfer succeeded.\r\n'))
            term.inkey()
        else:
            return
Esempio n. 6
0
def upload_files(term, protocol='xmodem1k'):
    """ Upload files. """
    echo(term.clear)
    while True:
        echo(u'Filename (empty to quit):\r\n')
        led = LineEditor(width=term.width - 1)
        led.refresh()
        inp = led.read()
        led = None
        if inp:
            for illegal in (os.path.sep, u'..', u'~',):
                if illegal in inp:
                    echo(term.bold_red(u'\r\nIllegal filename.\r\n'))
                    term.inkey()
                    return

            echo(term.bold(
                u'\r\nBegin your {0} sending program now.\r\n'
                .format(protocol)))

            upload_filename = os.path.join(UPLOADS_DIR, inp)
            try:
                upload = open(upload_filename, 'wb')
            except IOError as err:
                echo(term.bold_red('u\r\nIOError: {err}\r\n'.format(err=err)))
            else:
                if not recv_modem(upload, protocol):
                    echo(term.bold_red(u'Upload failed!\r\n'))
                    os.unlink(upload_filename)
                else:
                    echo(term.bold_green(u'Transfer succeeded.\r\n'))
            term.inkey()
        else:
            return
Esempio n. 7
0
def try_pass(user):
    """
    Prompt for password and authenticate, returns True if succesfull.
    """
    # pylint: disable=R0914
    #         Too many local variables
    from x84.bbs import getsession, getterminal, ini, LineEditor, echo
    session, term = getsession(), getterminal()
    prompt_pass = u'\r\n\r\n  pass: '******'\r\n\r\n  ' + term.yellow_reverse(u"Encrypting ..")
    badpass_msg = (u'\r\n\r\n' + term.red_reverse +
                   u"'%s' login failed." + term.normal)
    max_pass = int(ini.CFG.get('nua', 'max_pass'))
    # prompt for password, disable input tap during, mask input with 'x',
    # and authenticate against user record, performing a script change to
    # topscript if sucessful.
    # pylint: disable=W0212
    #         Access to a protected member _tap_input of a client class
    echo(prompt_pass)
    chk = session._tap_input  # <-- save
    session._tap_input = False
    lne = LineEditor(max_pass)
    lne.hidden = u'x'
    password = lne.read()
    session._tap_input = chk  # restore -->
    if password is not None and 0 != len(password):
        echo(status_auth)
        if user.auth(password):
            return True
    denied(badpass_msg % (user.handle,))
    return False
Esempio n. 8
0
def saysomething(dumb=True):
    """
    Prompt user to post oneliner, also prompt user to post
    to bbs-scene.org if configured, returning background Thread.
    """
    import time
    from x84.bbs import getsession, getterminal, echo, LineEditor, ini
    session, term = getsession(), getterminal()
    prompt_say = u'SAY WhAt ?! '
    # heard_msg = u'YOUR MESSAGE hAS bEEN VOiCEd.'

    yloc = term.height - 3
    xloc = max(0, ((term.width / 2) - (MAX_INPUT / 2)))
    if dumb:
        echo(u'\r\n\r\n' + term.bold_blue(prompt_say))
    else:
        echo(term.move(yloc, xloc) or u'\r\n\r\n')
        echo(term.bold_blue(prompt_say))
    ole = LineEditor(MAX_INPUT)
    ole.highlight = term.green_reverse
    oneliner = ole.read()
    if oneliner is None or 0 == len(oneliner.strip()):
        if not dumb:
            # clear input line,
            echo(term.normal + term.move(yloc, 0) + term.clear_eol)
        return None

    session.user['lastliner'] = time.time()
    # post local-onlyw hen bbs-scene.org is not configured
    if not ini.CFG.has_section('bbs-scene'):
        add_oneline(oneliner.strip())
        return None
    return post_bbs_scene(oneliner, dumb)
Esempio n. 9
0
def try_pass(user):
    """
    Prompt for password and authenticate, returns True if succesfull.
    """
    # pylint: disable=R0914
    #         Too many local variables
    from x84.bbs import getsession, getterminal, ini, LineEditor, echo
    session, term = getsession(), getterminal()
    prompt_pass = u'pass: '******'\r\n\r\n  ' + term.yellow_reverse(u"Encrypting ..")
    badpass_msg = (u'\r\n\r\n' + term.red_reverse + u"'%s' login failed." +
                   term.normal)
    max_pass = int(ini.CFG.get('nua', 'max_pass'))
    # prompt for password, disable input tap during, mask input with 'x',
    # and authenticate against user record, performing a script change to
    # topscript if sucessful.
    # pylint: disable=W0212
    #         Access to a protected member _tap_input of a client class
    echo(term.move(term.height, max_pass + 10) + prompt_pass)
    chk = session._tap_input  # <-- save
    session._tap_input = False
    lne = LineEditor(max_pass)
    lne.hidden = u'x'
    password = lne.read()
    session._tap_input = chk  # restore -->
    if password is not None and 0 != len(password):
        echo(status_auth)
        if user.auth(password):
            return True
    denied(badpass_msg % (user.handle, ))
    return False
Esempio n. 10
0
def locate_user(term, point):
    """ Prompt for search pattern and return discovered User. """
    _color1, _color2, _color3 = [
        getattr(term, _color)
        for _color in (color_lowlight, color_highlight, color_field_edit)
    ]

    # show help
    width = term.width - (point.x * 2)
    help_txt = (u'Enter username or glob pattern.  Press escape to cancel.')
    y_offset = 0
    for y_offset, txt in enumerate(term.wrap(help_txt, width=width)):
        echo(term.move(point.y + y_offset, point.x))
        echo(_color1(txt) + term.clear_eol)
    point_prompt = Point(y=point.y + y_offset + 2, x=point.x)

    editor = LineEditor(nua.username_max_length, colors={'highlight': _color3})
    while True:
        # prompt for handle
        echo(term.move(*point_prompt))
        echo(u'handle: ' + term.clear_eol)
        inp = editor.read()

        point = Point(y=point_prompt.y + 2, x=point.x)
        if inp is None:
            # canceled (escape)
            return
        elif u'*' in inp or u'?' in inp:
            # a glob pattern, fetch all usernames
            handles = fnmatch.filter(list_users(), inp)
            if len(handles) == 0:
                echo(u''.join((term.move(*point),
                               u'No matches for {0}.'.format(_color2(inp)),
                               term.clear_eos)))
            elif len(handles) == 1:
                return get_user(handles[0])
            else:
                matches_text = (
                    u'{0} accounts matched, chose one: {1}.'.format(
                        _color2(str(len(handles))),
                        u', '.join(_color2(handle) for handle in handles)))
                echo(term.move(*point))
                for y_offset, txt in enumerate(
                        term.wrap(matches_text, width=width)):
                    echo(term.move(point.y + y_offset, point.x))
                    echo(txt + term.clear_eol)
                    if point.y + y_offset > term.height - 3:
                        # we simply cannot display anymore
                        break
                echo(term.clear_eos)
        else:
            handle = find_user(inp)
            if handle is not None:
                return get_user(handle)
            echo(u''.join(
                (term.move(*point),
                 u'No matches for {0}.'.format(_color2(inp)), term.clear_eos)))
Esempio n. 11
0
File: vote.py Progetto: hick/x84
def main():
    session = getsession()
    session.activity = u'hanging out in voting script'
    term = getterminal()
    echo(term.clear())

    db = DBProxy(databasename)  
    if not 'questions' in db:
        generate_database()

    while True: 
        echo(term.clear()) # clears the screen and displays the vote art header
        for line in showart(os.path.join(os.path.dirname(__file__),'art','vote.ans'),'topaz'):
            echo(term.cyan+term.move_x((term.width/2)-40)+line)

        if 'sysop' in session.user.groups:
            spacing = 1
        else:
            spacing = 7
            echo(' ')
        echo(term.magenta+'\n ('+term.cyan+'r'+term.magenta+')'+term.white+'esults'+' '*spacing)
        echo(term.magenta+'('+term.cyan+'v'+term.magenta+')'+term.white+'ote on a question'+' '*spacing)
        echo(term.magenta+'('+term.cyan+'a'+term.magenta+')'+term.white+'dd a new question'+' '*spacing)
        if 'sysop' in session.user.groups:
            echo(term.magenta+'('+term.cyan+'d'+term.magenta+')'+term.white+'elete a question'+' '*spacing)
        echo(term.magenta+'('+term.cyan+'q'+term.magenta+')'+term.white+'uit')
        echo(term.magenta+'\r\n\r\n\r\nx/84 voting booth command: ')  
        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        inp = inp.lower() # makes the input indifferent to wheter you used lower case when typing in a command or not..

        if 'sysop' in session.user.groups and inp == 'd':
            while 1:
                questionnumber = query_question()
                if questionnumber == 999:
                    break
                delete_question(questionnumber)
        elif inp == 'r':
            while 1:
                questionnumber = query_question()
                if questionnumber == 999:
                    break
                list_results(questionnumber)
        elif inp == 'v':
            while 1:
                questionnumber = query_question()
                if questionnumber == 999:
                    break
                vote(questionnumber)
        elif inp == 'a':
            add_question()
        elif inp == 'q':
            return
        else:
            echo(term.red+'\r\nNo such command. Try again.\r\n') # if no valid key is pressed then do some ami/x esthetics.
            waitprompt()
Esempio n. 12
0
def prompt_recipient(msg):
    """ Prompt for recipient of message. """
    # pylint: disable=R0914
    #         Too many local variables
    from x84.bbs import getterminal, LineEditor, echo, ini, list_users
    from x84.bbs import Selector
    import difflib
    term = getterminal()
    echo(u"ENtER %s, OR '%s' tO AddRESS All. %s to exit" % (
        term.bold_yellow(u'hANdlE'),
        term.bold_yellow(u'None'),
        term.bold_yellow_underline('Escape'),))
    echo(u'\r\n\r\n')
    max_user = ini.CFG.getint('nua', 'max_user')
    lne = LineEditor(max_user, msg.recipient or u'None')
    lne.highlight = term.yellow_reverse
    echo(term.clear_eol + u'   RECiPiENt: ')
    recipient = lne.read()
    if recipient is None or lne.quit:
        return False
    userlist = list_users()
    if recipient in userlist:
        msg.recipient = recipient
        return True
    elif len(recipient) != 0 and recipient != 'None':
        for match in difflib.get_close_matches(recipient, userlist):
            blurb = u'did YOU MEAN: %s ?' % (match,)
            inp = Selector(yloc=term.height - 1,
                           xloc=term.width - 22,
                           width=20, left=u'YES', right=u'NO')
            echo(u''.join((
                u'\r\n',
                term.move(inp.yloc, inp.xloc - len(blurb)),
                term.clear_eol,
                term.bold_yellow(blurb))))
            selection = inp.read()
            echo(term.move(inp.yloc, 0) + term.clear_eol)
            if selection == u'YES':
                msg.recipient = match
                return True
            if selection is None or inp.quit:
                return False
    else:
        blurb = u' NO RECiPiENT; POSt tO PUbliC? '
        inp = Selector(yloc=term.height - 1,
                       xloc=term.width - 22,
                       width=20, left=u'YES', right=u'NO')
        echo(u''.join((
            u'\r\n',
            term.move(inp.yloc, inp.xloc - len(blurb)),
            term.clear_eol,
            term.bold_yellow(blurb))))
        selection = inp.read()
        echo(term.move(inp.yloc, 0) + term.clear_eol)
        if selection == u'YES':
            msg.recipient = None
            return True
Esempio n. 13
0
def locate_user(term, point):
    """ Prompt for search pattern and return discovered User. """
    _color1, _color2, _color3 = [
        getattr(term, _color) for _color in (
            color_lowlight, color_highlight, color_field_edit)]

    # show help
    width = term.width - (point.x * 2)
    help_txt = (u'Enter username or glob pattern.  Press escape to cancel.')
    y_offset = 0
    for y_offset, txt in enumerate(term.wrap(help_txt, width=width)):
        echo(term.move(point.y + y_offset, point.x))
        echo(_color1(txt) + term.clear_eol)
    point_prompt = Point(y=point.y + y_offset + 2, x=point.x)

    editor = LineEditor(nua.username_max_length, colors={'highlight': _color3})
    while True:
        # prompt for handle
        echo(term.move(*point_prompt))
        echo(u'handle: ' + term.clear_eol)
        inp = editor.read()

        point = Point(y=point_prompt.y + 2, x=point.x)
        if inp is None:
            # canceled (escape)
            return
        elif u'*' in inp or u'?' in inp:
            # a glob pattern, fetch all usernames
            handles = fnmatch.filter(list_users(), inp)
            if len(handles) == 0:
                echo(u''.join((term.move(*point),
                               u'No matches for {0}.'.format(_color2(inp)),
                               term.clear_eos)))
            elif len(handles) == 1:
                return get_user(handles[0])
            else:
                matches_text = (
                    u'{0} accounts matched, chose one: {1}.'.format(
                        _color2(str(len(handles))), u', '.join(
                            _color2(handle) for handle in handles)))
                echo(term.move(*point))
                for y_offset, txt in enumerate(
                        term.wrap(matches_text, width=width)):
                    echo(term.move(point.y + y_offset, point.x))
                    echo(txt + term.clear_eol)
                    if point.y + y_offset > term.height - 3:
                        # we simply cannot display anymore
                        break
                echo(term.clear_eos)
        else:
            handle = find_user(inp)
            if handle is not None:
                return get_user(handle)
            echo(u''.join((term.move(*point),
                           u'No matches for {0}.'.format(_color2(inp)),
                           term.clear_eos)))
Esempio n. 14
0
def prompt_recipient(msg):
    """ Prompt for recipient of message. """
    # pylint: disable=R0914
    #         Too many local variables
    from x84.bbs import getterminal, LineEditor, echo, ini, list_users
    from x84.bbs import Selector
    import difflib
    term = getterminal()
    echo(u"ENtER %s, OR '%s' tO AddRESS All. %s to exit" % (
        term.bold_yellow(u'hANdlE'),
        term.bold_yellow(u'None'),
        term.bold_yellow_underline('Escape'),
    ))
    echo(u'\r\n\r\n')
    max_user = ini.CFG.getint('nua', 'max_user')
    lne = LineEditor(max_user, msg.recipient or u'None')
    lne.highlight = term.yellow_reverse
    echo(term.clear_eol + u'   RECiPiENt: ')
    recipient = lne.read()
    if recipient is None or lne.quit:
        return False
    userlist = list_users()
    if recipient in userlist:
        msg.recipient = recipient
        return True
    elif len(recipient) != 0 and recipient != 'None':
        for match in difflib.get_close_matches(recipient, userlist):
            blurb = u'did YOU MEAN: %s ?' % (match, )
            inp = Selector(yloc=term.height - 1,
                           xloc=term.width - 22,
                           width=20,
                           left=u'YES',
                           right=u'NO')
            echo(u''.join((u'\r\n', term.move(inp.yloc, inp.xloc - len(blurb)),
                           term.clear_eol, term.bold_yellow(blurb))))
            selection = inp.read()
            echo(term.move(inp.yloc, 0) + term.clear_eol)
            if selection == u'YES':
                msg.recipient = match
                return True
            if selection is None or inp.quit:
                return False
    else:
        blurb = u' NO RECiPiENT; POSt tO PUbliC? '
        inp = Selector(yloc=term.height - 1,
                       xloc=term.width - 22,
                       width=20,
                       left=u'YES',
                       right=u'NO')
        echo(u''.join((u'\r\n', term.move(inp.yloc, inp.xloc - len(blurb)),
                       term.clear_eol, term.bold_yellow(blurb))))
        selection = inp.read()
        echo(term.move(inp.yloc, 0) + term.clear_eol)
        if selection == u'YES':
            msg.recipient = None
            return True
Esempio n. 15
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
Esempio n. 16
0
def prompt_subject(msg):
    """ Prompt for subject of message. """
    from x84.bbs import getterminal, LineEditor, echo, ini
    term = getterminal()
    max_subject = int(ini.CFG.getint('msg', 'max_subject'))
    lne = LineEditor(max_subject, msg.subject)
    lne.highlight = term.yellow_reverse
    echo(u'\r\n\r\n     SUBjECt: ')
    subject = lne.read()
    if subject is None or 0 == len(subject):
        return False
    msg.subject = subject
    return True
Esempio n. 17
0
def prompt_subject(msg):
    """ Prompt for subject of message. """
    from x84.bbs import getterminal, LineEditor, echo, ini
    term = getterminal()
    max_subject = int(ini.CFG.getint('msg', 'max_subject'))
    lne = LineEditor(max_subject, msg.subject)
    lne.highlight = term.yellow_reverse
    echo(u'\r\n\r\n     SUBjECt: ')
    subject = lne.read()
    if subject is None or 0 == len(subject):
        return False
    msg.subject = subject
    return True
Esempio n. 18
0
 def on_nicknameinuse(self, connection, event):
     """ Nick is being used; pick another one. """
     # pylint:disable=W0613
     self.session.send_event('route', (self.session.sid, 'irc-connected'))
     self.connected = True
     echo(u''.join([self.term.normal, self.term.clear,
                    u'Your nickname is in use or illegal. Pick a new one '
                    u'(blank to quit):\r\n']))
     led = LineEditor(width=MAX_NICK)
     newnick = led.read()
     echo(u'\r\n')
     if not newnick:
         self.session.send_event('route', (self.session.sid, 'irc-quit'))
         return
     connection.nick(newnick)
Esempio n. 19
0
 def on_nicknameinuse(self, connection, event):
     """ Nick is being used; pick another one. """
     # pylint: disable=W0613
     self.session.buffer_event('irc-connected')
     self.connected = True
     echo(u''.join([self.term.normal, u'\r\n',
                    u'Your nickname is in use or illegal. Pick a new one '
                    u'(blank to quit):\r\n']))
     led = LineEditor(width=MAX_NICK)
     newnick = led.read()
     echo(u'\r\n')
     if not newnick:
         self.session.buffer_event('irc-quit', 'canceled')
         return
     connection.nick(newnick)
Esempio n. 20
0
File: vote.py Progetto: tehmaze/x84
def query_question():
    term = getterminal()
    session = getsession()
    db = DBProxy(databasename)
    questions = []
    index = []
    uservotingdata = []
    questions = db['questions']
    index = db['index']
    counter = 0

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

    echo(term.clear() + term.blue + '>>' + term.white + 'questions availible\r\n' +
         term.blue + '---------------------\r\n\r\n' + term.white)
    for i in range(0, len(questions)):
        if (index[i], 0) in uservotingdata:
            # prints out a star to show that the user already voted on this
            # question
            echo(term.green + '*')
        echo(term.magenta + '(' + term.cyan + str(i) + term.magenta + ') ' +
             term.white + questions[i] + '\r\n')

        # if the list of questions is longer than the screen height, display a
        # press enter prompt
        counter = counter + 1
        if counter > term.height - 7:
            counter = 0
            waitprompt()
            echo(term.move_x(0) + term.clear_eol + term.move_up)

    echo(term.bold_black + '* = already voted\r\n\r\n' + term.normal)

    while True:
        echo(
            term.magenta + '\rselect one of the questions above or press enter to return: ')
        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp.isnumeric() and int(inp) < len(questions):
            return int(inp)
        else:
            # 999 in this case means that no valid option was chosen.. break
            # loop.
            return 999
Esempio n. 21
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
Esempio n. 22
0
def query_question():
    term = getterminal()
    session = getsession()
    db = DBProxy(databasename)
    questions = []
    index = []
    uservotingdata = []
    questions = db['questions']
    index = db['index']
    counter = 0

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

    echo(term.clear() + term.blue + '>>' + term.white +
         'questions availible\r\n' + term.blue +
         '---------------------\r\n\r\n' + term.white)
    for i in range(0, len(questions)):
        if (index[i], 0) in uservotingdata:
            echo(
                term.green + '*'
            )  # prints out a star to show that the user already voted on this question
        echo(term.magenta + '(' + term.cyan + str(i) + term.magenta + ') ' +
             term.white + questions[i] + '\r\n')

        counter = counter + 1  # if the list of questions is longer than the screen height, display a press enter prompt
        if counter > term.height - 7:
            counter = 0
            waitprompt()
            echo(term.move_x(0) + term.clear_eol + term.move_up)

    echo(term.bold_black + '* = already voted\r\n\r\n' + term.normal)

    while 1:
        echo(term.magenta +
             '\rselect one of the questions above or press enter to return: ')
        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp.isnumeric() and int(inp) < len(questions):
            return int(inp)
        else:
            return 999  # 999 in this case means that no valid option was chosen.. break loop.
Esempio n. 23
0
def main():
    term = getterminal()
    session = getsession()
    banner()

    while True:
        session.activity = 'Viewing automsg'
        inp = term.inkey()
        if inp.lower() in (u'n', 'q') or inp.code == term.KEY_ENTER:
            return

        if inp.lower() == u'y':
            session.activity = 'Writing automsg'
            echo(term.move(12, 31))
            echo(term.bold_white(session.user.handle))
            echo((u' ' * 7))

            echo(term.move(21, 0) + term.clear_eol)
            for row in range(1, 4):
                echo(term.move(15 + row, 5))
                echo(u' ' * 57)

            msg = []
            for row in range(1, 4):
                echo(term.move(15 + row, 5))
                le = LineEditor(70)
                le.colors['highlight'] = term.white
                msg.append(le.read())

            ask(u'submit your text as a public message? ')

            while True:
                inp = term.inkey()
                if inp.lower() == u'n':
                    return
                if inp == 'y' or inp == 'Y':
                    echo(term.move(21, 0) + term.clear_eol)
                    with codecs.open(get_datafile_path(), 'w', 'utf-8') as fo:
                        fo.write('\n'.join([session.user.handle] + msg))
                        fo.close()
                    return
Esempio n. 24
0
File: automsg.py Progetto: hick/x84
def main():
    term = getterminal()
    session = getsession()
    banner()

    while True:
        session.activity = 'Viewing automsg'
        inp = term.inkey()
        if inp.lower() in (u'n', 'q') or inp.code == term.KEY_ENTER:
            return

        if inp.lower() == u'y':
            session.activity = 'Writing automsg'
            echo(term.move(12, 31))
            echo(term.bold_white(session.user.handle))
            echo((u' ' * 7))

            echo(term.move(21, 0) + term.clear_eol)
            for row in range (1, 4):
                echo(term.move(15 + row, 5))
                echo(u' ' * 57)

            msg = []
            for row in range (1, 4):
                echo(term.move(15 + row, 5))
                le = LineEditor(70)
                le.colors['highlight'] = term.white
                msg.append(le.read())

            ask(u'submit your text as a public message? ')

            while 1:
                inp = term.inkey()
                if inp.lower() == u'n':
                    return
                if inp == 'y' or inp == 'Y':
                    echo(term.move(21, 0) + term.clear_eol)
                    with codecs.open(get_datafile_path(), 'w', 'utf-8') as fo:
                        fo.write('\n'.join([session.user.handle] + msg))
                        fo.close()
                    return
Esempio n. 25
0
def delete_question(questionnumber):
    term = getterminal()
    db = DBProxy(databasename)
    alternatives = {}
    questions = []
    results = {}
    amount_of_alternatives = []
    questions = db['questions']
    results = db['results']
    amount_of_alternatives = db['amount_of_alternatives']
    alternatives = db['alternatives']
    index = db['index']

    echo(term.clear + term.white(u'Delete the ') + term.magenta(u'(') + term.cyan(u'e') + term.magenta(u')') +
         term.white(u'ntire question or delete single ') + term.magenta(u'(') + term.cyan(u'a') + term.magenta(u')') +
         term.white(u'lternatives?') + u'\r\n\r\n' + term.magenta(u'command: '))

    le = LineEditor(10)
    le.colors['highlight'] = term.cyan
    inp = le.read()
    # makes the input indifferent to wheter you used lower case when typing in
    # a command or not..
    inp = (inp or u'').lower()

    if inp == u'a':  # delete answer alternative..
        echo(term.clear)
        echo(term.white + questions[questionnumber] + term.move_x(max(0, term.width - 12)) +
             u' index: ' + str(index[questionnumber]) + u'\r\n\r\n')
        for i in range(0, amount_of_alternatives[questionnumber]):
            echo(term.cyan(str(i) + u'. ') +
                 term.white(alternatives[(questionnumber, i)]) + u'\r\n')

        echo(term.magenta(u'\r\nSelect a number. Enter to abort: '))

        le = LineEditor(10)
        le.colors['highlight'] = term.cyan
        inp2 = le.read()

        if inp2 is not None and inp2.isnumeric() and int(
                inp2) < amount_of_alternatives[questionnumber]:
            if int(inp2) + 1 < amount_of_alternatives[questionnumber]:
                for i in range(
                        int(inp2), amount_of_alternatives[questionnumber] - 1):
                    alternatives[(questionnumber, i)] = alternatives[
                        (questionnumber, i + 1)]
                    results[(questionnumber, i)] = results[
                        (questionnumber, i + 1)]
        else:
            return
        amount_of_alternatives[questionnumber] -= 1

    elif inp == u'e':  # delete entire question..
        if questionnumber + 1 < len(questions):
            for i in range(questionnumber, len(questions) - 1):
                questions[i] = questions[i + 1]
                amount_of_alternatives[i] = amount_of_alternatives[i + 1]
                index[(i)] = index[(i + 1)]
                for i2 in range(0, amount_of_alternatives[i + 1]):
                    alternatives[(i, i2)] = alternatives[(i + 1, i2)]
                    results[(i, i2)] = results[(i + 1, i2)]
        del questions[-1]
        del amount_of_alternatives[-1]
        del index[-1]
    else:
        return

    db['index'] = index
    db['questions'] = questions
    db['amount_of_alternatives'] = amount_of_alternatives
    db['results'] = results
    db['alternatives'] = alternatives
    return
Esempio n. 26
0
def add_bbs():
    """
    Prompt user for details and to add bbs to list.
    """
    # pylint: disable=R0914,R0915
    #        Too many local variables
    #        Too many statements
    from x84.bbs import getsession, getterminal, echo, LineEditor, DBProxy, ini
    from x84.bbs import getch
    session, term = getsession(), getterminal()
    echo(term.move(term.height, 0))
    empty_msg = u'\r\n\r\nVAlUE iS NOt OPtiONAl.'
    cancel_msg = u"\r\n\r\nENtER 'quit' tO CANCEl."
    saved_msg = u'\r\n\r\nSAVED AS RECORd id %s.'
    logger = logging.getLogger()
    bbs = dict()
    for bkey in DB_KEYS:
        if bkey == 'timestamp':
            value = time.strftime('%Y-%m-%d %H:%M:%S')
            bbs[bkey] = value
            continue
        elif bkey == 'ansi':
            # todo: upload ansi with xmodem .. lol !?
            value = u''
            continue
        splice = len(bkey) - (len(bkey) / 3)
        prefix = (u'\r\n\r\n  ' +
                  (term.bold_red('* ') if bkey in XML_REQNOTNULL else u'') +
                  term.bold_blue(bkey[:splice]) +
                  term.bold_black(bkey[splice:]) + term.bold_white(': '))
        led = LineEditor(40)  # !?
        led.highlight = term.green_reverse
        while True:
            echo(prefix)
            value = led.read()
            if value is not None and (value.strip().lower() == 'quit'):
                return
            if bkey in XML_REQNOTNULL:
                if value is None or 0 == len(value.strip()):
                    echo(term.bold_red(empty_msg))
                    echo(u'\r\n' + cancel_msg)
                    continue
            if bkey in ('port') and value is None or 0 == len(value):
                value = u'23'
            # TODO: telnet connect test, of course !
            bbs[bkey] = value
            break
    key = max([int(_key) for _key in DBProxy('bbslist').keys()] or [0]) + 1
    DBProxy('bbslist')[key] = bbs
    DBProxy('bbslist', 'comments')[key] = list()
    DBProxy('bbslist', 'ratings')[key] = list()
    echo('\r\n\r\n' + saved_msg % (key) + '\r\n')
    session.send_event('global', (
        'bbslist_update',
        None,
    ))
    session.buffer_event('bbslist_update')
    if ini.CFG.has_section('bbs-scene'):
        # post to bbs-scene.org
        posturl = 'http://bbs-scene.org/api/bbslist.xml'
        usernm = ini.CFG.get('bbs-scene', 'user')
        passwd = ini.CFG.get('bbs-scene', 'pass')
        data = {
            'name': bbs['bbsname'],
            'sysop': bbs['sysop'],
            'software': bbs['software'],
            'address': bbs['address'],
            'port': bbs['port'],
            'location': bbs['location'],
            'notes': bbs['notes'],
        }
        req = requests.post(posturl, auth=(usernm, passwd), data=data)
        if req.status_code != 200:
            echo(u'\r\n\r\nrequest failed,\r\n')
            echo(u'%r' % (req.content, ))
            echo(u'\r\n\r\n(code : %s).\r\n' % (req.status_code, ))
            echo(u'\r\nPress any key ..')
            logger.warn('bbs post failed: %s' % (posturl, ))
            getch()
            return
        logger.info('bbs-scene.org api (%d): %r/%r', req.status_code,
                    session.user.handle, bbs)
        # spawn a thread to re-fetch bbs entries,
        thread = FetchUpdates()
        thread.start()
        wait_for(thread)
        return chk_thread(thread)
Esempio n. 27
0
def main():
    session, term = getsession(), getterminal()
    session.activity = 'reading news from ycombinator.com'
    echo(term.clear + term.yellow + 'firing up hACKER nEWS! *')

    feed = feedparser.parse('https://news.ycombinator.com/rss')
    article = []
    link = []
    dirty = True
    offset = 0
    wrappedarticle = []               # if the article header needs wrapping..
    # the amount of rows that a description is estimated to use.
    amount = term.height / 5

    echo(u'*')

    # buffers the articles titels, summarys and links.
    for post in feed.entries:
        article.append(post.title)
        link.append(post.link)

    while True:
        if dirty == True:
            echo(term.normal)
            for i in range(1, term.height - 1):
                echo(term.move(i, 0) + term.clear_eol)
            echo(term.move(2, 0))

            for i in range(0, amount):
                if len(article) > i + offset:
                    echo(term.magenta + str(i + offset) + '. ')
                    if len(article[i + offset]) > 79 - 4:
                        wrappedarticle = wrap(
                            article[
                                i +
                                offset],
                            79 -
                            4,
                            break_long_words=True)
                        for i2 in range(0, len(wrappedarticle)):
                            echo(term.cyan + wrappedarticle[i2] + '\r\n')
                    else:
                        echo(term.cyan + article[i + offset] + '\r\n')
                    echo(
                        term.white +
                        link[
                            i +
                            offset] +
                        '\r\n\r\n' +
                        term.normal)
            echo(term.normal + term.move(term.height, 0) + term.on_blue + term.clear_eol + '(' + term.bold('up/down') +
                 term.on_blue + ') next/previous  (' + term.bold('q/escape') + term.on_blue + ') quits  (' +
                 term.bold('enter') + term.on_blue + ') select' + term.move(term.height, term.width - 20) + term.cyan +
                 term.move(0, 0) + term.clear_eol + term.cyan + '** hacker news on ycombinator.com **' + term.normal)

        keypressed = getch()
        dirty = True

        if keypressed == 'q' or keypressed == 'Q' or keypressed == term.KEY_ESCAPE:
            break
        elif keypressed == term.KEY_DOWN:
            if (offset + amount) < len(article):
                offset = offset + amount
            else:
                # checks wheter the article has fewer lines than the screen or
                # not..
                if len(article) < amount:
                    offset = 0
        elif keypressed == term.KEY_UP:
            if offset > amount:
                offset = offset - amount
            else:
                offset = 0
        elif keypressed == term.KEY_ENTER:
            echo(
                term.move(
                    term.height,
                    0) +
                term.clear_eol +
                term.white +
                'choose your article no#: ')
            le = LineEditor(10)
            le.colors['highlight'] = term.cyan
            inp = le.read()
            if inp.isnumeric() and int(inp) < len(article):
                echo(
                    term.clear +
                    term.yellow +
                    'fetching the latest news just for you..' +
                    term.normal)
                choosenurl = link[int(inp)]
                h = html2text.HTML2Text()
                h.ignore_links = True
                h.ignore_images = True
                h.escape_all = True
                h.body_width = 79
                req = urllib2.Request(
                    choosenurl, headers={
                        'User-Agent': 'Mozilla'})  # identify as mozilla
                try:
                    text = urllib2.urlopen(req, timeout=10).read()
                except socket.timeout as e:
                    echo(
                        term.clear() +
                        term.yellow +
                        'request timed out.. try again.')
                    waitprompt()
                except urllib2.URLError as e:
                    echo(
                        term.clear() +
                        term.yellow +
                        'faulty http link.. try again.')
                    waitprompt()
                else:
                    text = unicode(h.handle(text.decode(errors='ignore')))
                    articlereader(text.split('\n'))
        else:
            dirty = False
Esempio n. 28
0
def add_bbs():
    """
    Prompt user for details and to add bbs to list.
    """
    # pylint: disable=R0914,R0915
    #        Too many local variables
    #        Too many statements
    from x84.bbs import getsession, getterminal, echo, LineEditor, DBProxy, ini
    from x84.bbs import getch
    session, term = getsession(), getterminal()
    echo(term.move(term.height, 0))
    empty_msg = u'\r\n\r\nVAlUE iS NOt OPtiONAl.'
    cancel_msg = u"\r\n\r\nENtER 'quit' tO CANCEl."
    saved_msg = u'\r\n\r\nSAVED AS RECORd id %s.'
    logger = logging.getLogger()
    bbs = dict()
    for bkey in DB_KEYS:
        if bkey == 'timestamp':
            value = time.strftime('%Y-%m-%d %H:%M:%S')
            bbs[bkey] = value
            continue
        elif bkey == 'ansi':
            # todo: upload ansi with xmodem .. lol !?
            value = u''
            continue
        splice = len(bkey) - (len(bkey) / 3)
        prefix = (u'\r\n\r\n  '
                  + (term.bold_red('* ') if bkey in XML_REQNOTNULL else u'')
                  + term.bold_blue(bkey[:splice])
                  + term.bold_black(bkey[splice:])
                  + term.bold_white(': '))
        led = LineEditor(40)  # !?
        led.highlight = term.green_reverse
        while True:
            echo(prefix)
            value = led.read()
            if value is not None and (value.strip().lower() == 'quit'):
                return
            if bkey in XML_REQNOTNULL:
                if value is None or 0 == len(value.strip()):
                    echo(term.bold_red(empty_msg))
                    echo(u'\r\n' + cancel_msg)
                    continue
            if bkey in ('port') and value is None or 0 == len(value):
                value = u'23'
            # TODO: telnet connect test, of course !
            bbs[bkey] = value
            break
    key = max([int(_key) for _key in DBProxy('bbslist').keys()] or [0]) + 1
    DBProxy('bbslist')[key] = bbs
    DBProxy('bbslist', 'comments')[key] = list()
    DBProxy('bbslist', 'ratings')[key] = list()
    echo('\r\n\r\n' + saved_msg % (key) + '\r\n')
    session.send_event('global', ('bbslist_update', None,))
    session.buffer_event('bbslist_update')
    if ini.CFG.has_section('bbs-scene'):
        # post to bbs-scene.org
        posturl = 'http://bbs-scene.org/api/bbslist.xml'
        usernm = ini.CFG.get('bbs-scene', 'user')
        passwd = ini.CFG.get('bbs-scene', 'pass')
        data = {'name': bbs['bbsname'],
                'sysop': bbs['sysop'],
                'software': bbs['software'],
                'address': bbs['address'],
                'port': bbs['port'],
                'location': bbs['location'],
                'notes': bbs['notes'],
                }
        req = requests.post(posturl, auth=(usernm, passwd), data=data)
        if req.status_code != 200:
            echo(u'\r\n\r\nrequest failed,\r\n')
            echo(u'%r' % (req.content,))
            echo(u'\r\n\r\n(code : %s).\r\n' % (req.status_code,))
            echo(u'\r\nPress any key ..')
            logger.warn('bbs post failed: %s' % (posturl,))
            getch()
            return
        logger.info('bbs-scene.org api (%d): %r/%r',
                    req.status_code, session.user.handle, bbs)
        # spawn a thread to re-fetch bbs entries,
        thread = FetchUpdates()
        thread.start()
        wait_for(thread)
        return chk_thread(thread)
Esempio n. 29
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] + '\r\n\r\n')
    for i in range(0, amount_of_alternatives[questionnumber]):
        echo(term.magenta + '(' + term.cyan + str(i) + term.magenta + ') ' +
             term.white + alternatives[(questionnumber, i)] + '\r\n')
    echo(term.magenta + '(' + term.cyan +
         str(amount_of_alternatives[questionnumber]) + term.magenta + ')' +
         term.bold_black + ' Add your own answer..\r\n\r\n')

    while 1:
        echo(term.normal + term.magenta + '\rYour choice:: ')
        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp.isnumeric(
        ) and int(inp) <= amount_of_alternatives[questionnumber]:

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

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

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

            if (
                    index[questionnumber], 0
            ) in uservotingdata:  # if the user has voted on this question before..
                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 + '\r\nyour vote has been noted, thanks..')
            getch(1)
            db['results'] = results
            db[session.user.handle] = uservotingdata
            list_results(questionnumber)
            return
Esempio n. 30
0
def main():
    session = getsession()
    session.activity = u'hanging out in voting script'
    term = getterminal()
    echo(term.clear())

    db = DBProxy(databasename)
    if not 'questions' in db:
        generate_database()

    while True:
        echo(
            term.clear())  # clears the screen and displays the vote art header
        for line in showart(
                os.path.join(os.path.dirname(__file__), 'art', 'vote.ans'),
                'topaz'):
            echo(term.cyan + term.move_x((term.width / 2) - 40) + line)

        if 'sysop' in session.user.groups:
            spacing = 1
        else:
            spacing = 7
            echo(' ')
        echo(term.magenta + '\n (' + term.cyan + 'r' + term.magenta + ')' +
             term.white + 'esults' + ' ' * spacing)
        echo(term.magenta + '(' + term.cyan + 'v' + term.magenta + ')' +
             term.white + 'ote on a question' + ' ' * spacing)
        echo(term.magenta + '(' + term.cyan + 'a' + term.magenta + ')' +
             term.white + 'dd a new question' + ' ' * spacing)
        if 'sysop' in session.user.groups:
            echo(term.magenta + '(' + term.cyan + 'd' + term.magenta + ')' +
                 term.white + 'elete a question' + ' ' * spacing)
        echo(term.magenta + '(' + term.cyan + 'q' + term.magenta + ')' +
             term.white + 'uit')
        echo(term.magenta + '\r\n\r\n\r\nx/84 voting booth command: ')
        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        inp = inp.lower(
        )  # makes the input indifferent to wheter you used lower case when typing in a command or not..

        if 'sysop' in session.user.groups and inp == 'd':
            while 1:
                questionnumber = query_question()
                if questionnumber == 999:
                    break
                delete_question(questionnumber)
        elif inp == 'r':
            while 1:
                questionnumber = query_question()
                if questionnumber == 999:
                    break
                list_results(questionnumber)
        elif inp == 'v':
            while 1:
                questionnumber = query_question()
                if questionnumber == 999:
                    break
                vote(questionnumber)
        elif inp == 'a':
            add_question()
        elif inp == 'q':
            return
        else:
            echo(term.red + '\r\nNo such command. Try again.\r\n'
                 )  # if no valid key is pressed then do some ami/x esthetics.
            waitprompt()
Esempio n. 31
0
File: vote.py Progetto: tehmaze/x84
def delete_question(questionnumber):
    term = getterminal()
    db = DBProxy(databasename)

    alternatives = {}
    questions = []
    results = {}
    amount_of_alternatives = []
    questions = db['questions']
    results = db['results']
    amount_of_alternatives = db['amount_of_alternatives']
    alternatives = db['alternatives']
    index = db['index']

    echo(term.clear + term.white + 'Delete the ' + term.magenta + '(' + term.cyan + 'e' + term.magenta + ')' + term.white +
         'ntire question or delete single ' + term.magenta + '(' + term.cyan + 'a' + term.magenta + ')' + term.white + 'lternatives?' +
         '\r\n\r\n' + term.magenta + 'command:: ')

    le = LineEditor(30)
    le.colors['highlight'] = term.cyan
    inp = le.read()
    # makes the input indifferent to wheter you used lower case when typing in
    # a command or not..
    inp = inp.lower()

    if inp == 'a':  # delete answer alternative..
        echo(term.clear)
        echo(term.white + questions[questionnumber] + term.move_x(max(0,
                                                                      term.width - 12)) + ' index: ' + str(index[questionnumber]) + '\r\n\r\n')
        for i in range(0, amount_of_alternatives[questionnumber]):
            echo(term.cyan + str(i) + '. ' + term.white +
                 alternatives[(questionnumber, i)] + '\r\n')

        echo(term.magenta + '\r\nSelect a number. Enter to abort: ')

        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp2 = le.read()

        if inp2.isnumeric() and int(
                inp2) < amount_of_alternatives[questionnumber]:
            if int(inp2) + 1 < amount_of_alternatives[questionnumber]:
                for i in range(
                        int(inp2), amount_of_alternatives[questionnumber] - 1):
                    alternatives[(questionnumber, i)] = alternatives[
                        (questionnumber, i + 1)]
                    results[(questionnumber, i)] = results[
                        (questionnumber, i + 1)]
        else:
            return
        amount_of_alternatives[questionnumber] -= 1

    elif inp == 'e':  # delete entire question..
        if questionnumber + 1 < len(questions):
            for i in range(questionnumber, len(questions) - 1):
                questions[i] = questions[i + 1]
                amount_of_alternatives[i] = amount_of_alternatives[i + 1]
                index[(i)] = index[(i + 1)]
                for i2 in range(0, amount_of_alternatives[i + 1]):
                    alternatives[(i, i2)] = alternatives[(i + 1, i2)]
                    results[(i, i2)] = results[(i + 1, i2)]
        del questions[-1]
        del amount_of_alternatives[-1]
        del index[-1]
    else:
        return

    db['index'] = index
    db['questions'] = questions
    db['amount_of_alternatives'] = amount_of_alternatives
    db['results'] = results
    db['alternatives'] = alternatives
    return
Esempio n. 32
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
Esempio n. 33
0
File: vote.py Progetto: tehmaze/x84
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] + '\r\n\r\n')
    for i in range(0, amount_of_alternatives[questionnumber]):
        echo(term.magenta + '(' + term.cyan + str(i) + term.magenta + ') ' +
             term.white + alternatives[(questionnumber, i)] + '\r\n')
    echo(term.magenta + '(' + term.cyan + str(amount_of_alternatives[
         questionnumber]) + term.magenta + ')' + term.bold_black + ' Add your own answer..\r\n\r\n')

    while True:
        echo(term.normal + term.magenta + '\rYour choice:: ')
        le = LineEditor(30)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        if inp.isnumeric() and int(
                inp) <= amount_of_alternatives[questionnumber]:

            # create database for user if the user hasn't made any votes
            if not session.user.handle 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 + '\r\nPress enter to abort.' +
                     term.move(0, 0) + term.white + ' Your answer: ')
                le = LineEditor(48)
                new_alternative = le.read()
                if new_alternative == '':
                    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 + '\r\nyour vote has been noted, thanks..')
            getch(1)
            db['results'] = results
            db[session.user.handle] = uservotingdata
            list_results(questionnumber)
            return
Esempio n. 34
0
def main():
    session = getsession()
    session.activity = u'hanging out in voting script'
    term = getterminal()
    echo(syncterm_setfont('topaz'))

    db = DBProxy(databasename)
    if 'questions' not in db:
        generate_database()

    while True:
        # clears the screen and displays the vote art header
        echo(term.clear())
        for line in showart(
                os.path.join(os.path.dirname(__file__), 'art', 'vote.ans'), 'cp437'):
            echo(term.cyan + term.move_x(max(0, (term.width / 2) - 40)) + line)

        if 'sysop' in session.user.groups:
            spacing = 1
        else:
            spacing = 7
            echo(' ')
        echo(term.magenta(u'\n (') + term.cyan(u'r') + term.magenta(u')') +
             term.white(u'esults') + ' ' * spacing +
             term.magenta(u'(') + term.cyan(u'v') + term.magenta(u')') +
             term.white(u'ote on a question') + u' ' * spacing +
             term.magenta(u'(') + term.cyan(u'a') + term.magenta(u')') +
             term.white(u'dd a new question') + u' ' * spacing)
        if 'sysop' in session.user.groups:
            echo(term.magenta(u'(') + term.cyan(u'd') + term.magenta(u')') +
                 term.white(u'elete a question') + u' ' * spacing)
        echo(term.magenta(u'(') + term.cyan(u'q') + term.magenta(u')') + term.white(u'uit') +
             term.magenta(u'\r\n\r\nx/84 voting booth command: '))
        le = LineEditor(10)
        le.colors['highlight'] = term.cyan
        inp = le.read()
        # makes the input indifferent to wheter you used lower case when typing
        # in a command or not..
        inp = (inp or u'').lower()

        if 'sysop' in session.user.groups and inp == u'd':
            while True:
                questionnumber = query_question()
                if questionnumber == -1:
                    break
                delete_question(questionnumber)
        elif inp == u'r':
            while True:
                questionnumber = query_question()
                if questionnumber == -1:
                    break
                list_results(questionnumber)
        elif inp == u'v':
            while True:
                questionnumber = query_question()
                if questionnumber == -1:
                    break
                vote(questionnumber)
        elif inp == u'a':
            add_question()
        elif inp == u'q':
            return
        else:
            # if no valid key is pressed then do some ami/x esthetics.
            echo(term.red(u'\r\nNo such command. Try again.\r\n'))
            waitprompt(term)