Exemple #1
0
def code_search():
    """Searches files in specified folder for occurances substring.
    """
    H()
    sprint('Enter phrase or code snippet')
    term = display_manager.input_prompt()

    H()
    sprint(
        "Please enter the path to the folder you'd like to begin the search from."
    )
    root_dir = display_manager.input_prompt()

    try:
        H()
        sprint("Looking it up..")
        os.system("gnome-terminal -e \"grep -rnw '%s' -e '%s'\"" %
                  (root_dir, term))
    except KeyboardInterrupt as e:
        return
    except Exception as e:
        rollbar.report_exc_info()
        print(e)
        pass
    return
Exemple #2
0
def porter():
    """Sends an email to a specified email address.
    """
    uheader = '[' + user[0].upper() + ']'
    H()
    sprint("Enter payload\n")
    lines = []
    try:
        while True:
            lines.append(input(u"\u262F "))
    except EOFError:
        pass
    except KeyboardInterrupt:
        H()
        sprint("Aborted.")
    payload = "\n".join(lines)
    print('\n')
    H()
    sprint("Label the package")
    subject = display_manager.input_prompt()

    H()
    sprint("Who's the mark?")
    target = display_manager.input_prompt()

    try:
        fa = os.getenv('LUNADDR')
        if not target:  # Env vars
            ta = os.getenv('MYEMAIL')
        else:
            ta = target
        msg = MIMEMultipart()
        msg['From'] = fa
        msg['To'] = ta
        msg['Subject'] = subject
        body = payload
        msg.attach(MIMEText(body, 'plain'))
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(fa, os.getenv('EMAILPWD'))
        text = msg.as_string()
        server.sendmail(fa, ta, text)
        server.quit()
        H()
        sprint("Package sent.")
        delete_latest()
        return
    except:
        rollbar.report_exc_info()
        H()
        sprint('Package sending failed.')
        return
Exemple #3
0
def population_density():
    """Measures the population density of a specified area, given the population.
    """
    H()
    sprint("Please enter the number of people who live in this area.")
    population = display_manager.input_prompt().replace(',', '')
    H()
    sprint("Enter the size of the area in square kilometers.")
    area = display_manager.input_prompt().replace(',', '')
    H()
    sprint(
        "The population density of this area is %s people per square kilometer."
        % str(int(population) / int(area)))
Exemple #4
0
def find_related(key_word):
    """Finds articles in main database (intel, in this case) that contain keyword.
    """
    H()
    sprint('This might take a while so please be patient.')
    try:
        keyword = key_word
        found = []
        count = 0
        cycle = 0
        for file in intel.find():
            if ' ' + keyword.lower() + ' ' in file['payload'][0].lower():
                found.append([
                    file['payload'][0].lower().count(keyword.lower()),
                    file['title']
                ])
                count += file['payload'][0].lower().count(keyword.lower())
                cycle += 1
                if cycle == 1 or cycle == 100000:
                    logging.debug(
                        '<<<%s>>>...>' %
                        file['payload'][0].lower().count(keyword.lower()))
                    cycle = 0
    except KeyboardInterrupt:
        logging.warning('User aborted search for keyword "%s".' % key_word)
        H()
        sprint("I guess patience isn't your strong suit.")
        return

    if found:
        logging.debug('keyword "%s" appears %s times in current universe.' %
                      (key_word, str(count)))
        try:
            found.sort()
            found.reverse()
            for title in found:
                print('%s     (%s)' % (title[1].strip(), str(title[0])))
                time.sleep(0.02)
            return
        except KeyboardInterrupt:
            return

    else:
        H()
        sprint(
            "No mentions of %s exist locally, shall I do an internet sweep for requested data?"
            % key_word)
        response = display_manager.input_prompt()

        if 'yes' in response:
            logging.debug('relation seeker sent "%s" to informant.' % key_word)
            H()
            sprint('Doing that.')
            informant(key_word, False, 0, False, *['relation seeker'])
        else:
            controlCentre(*[response])
            return
Exemple #5
0
def start_over():
    H()
    sprint('Would you like to start over?')
    directive = display_manager.input_prompt()

    if 'yes' in directive:
        laFibonacci()
    else:
        H()
        sprint("Cool. It was nice reminding you who's the boss around here.")
        return
Exemple #6
0
def init_translator(*session):
    """Initialises and terminates translator mode.
    """
    if not session:
        H()
        sprint('translator activated.')
    raw_text = display_manager.input_prompt()

    if raw_text.lower() != 'exit':
        human_lang_translator(raw_text)
    else:
        H()
        sprint('translator terminated.')
Exemple #7
0
def wolfram(init=True):
    if init:
        H()
        sprint('Game face activated')

    command = display_manager.input_prompt()
    if command.lower() != 'exit':
        search_wolfram(command)
        wolfram(False)
    else:
        H()
        sprint('Normal operations resumed')

    return
Exemple #8
0
def ethan():
    inp = display_manager.input_prompt()

    if inp.startswith('open'):
        target = inp[5:]
        try:
            x = hades.find_one({'title': target})
            sprint(x['payload'])
        except Exception as e:
            rollbar.report_exc_info()
            H()
            sprint("No record found.")
    else:
        controlCentre(*[inp])
Exemple #9
0
def dictionaryHelper(dictionary):
    # todo: auto suggest from wordlist
    # print(dict_header, end='')
    # word = prompt('', history=FileHistory('wordlist.txt'), auto_suggest=AutoSuggestFromHistory())
    word = display_manager.input_prompt()

    if word != 'exit':
        try:
            H(dict_header)
            os.system('dict -d %s %s' % (dictionary, word))
            dictionaryHelper(dictionary)
        except Exception as e:
            rollbar.report_exc_info()
            H()
            sprint(e)
            return
    else:
        H()
        sprint('Dictionary closed.')
        return
Exemple #10
0
def main():
    try:
        global state_object
        state_object = {
            'value': 'initialise',
            'last_displayed': [],
            'index': 0
        }

        while state_object['value'] != 'exit':
            H()
            sprint('Enter a search critria')
            topic = display_manager.input_prompt()
            print('')
            list_urls(topic)

        logging.info('News crawler deactivated')
        return
    except Exception as e:
        logging.error('ERROR: %s' % e)
        state_object = {'value': 'exit', 'last_displayed': [], 'index': 0}
        return
Exemple #11
0
def dictionary():
    try:
        H(dict_header)
        print("Choose a dictionary database (enter the associated number)\n\n",
              "1. The Collaborative International Dictionary of English\n",
              "2. Wordnet (2006)\n", "3. The Devil's Dictionary (1881-1906)\n",
              "4. The Moby Thesaurus II by Grady Ward")
        dic = display_manager.input_prompt()
        mapper = {'1': 'gcide', '2': 'wn', '3': 'devil', '4': 'moby-thesaurus'}
        mapper2 = {
            '1': 'The Collaborative International Dictionary of English',
            '2': 'Wordnet (2006)',
            '3': "The Devil's Dictionary (1881-1906)",
            '4': 'The Moby Thesaurus II by Grady Ward'
        }
        H(dict_header)
        sprint("You are now in %s" % mapper2[dic])
        dictionaryHelper(mapper[dic])
    except KeyboardInterrupt:
        H()
        sprint('Aborted')
        return
Exemple #12
0
def find_external_resource():
    """Searches for links related to a specified subject. e.g., It can be used to search for pdf
       links that can then be curled through Luna's ghost terminal."""

    H()
    sprint("What do you need?")
    res = display_manager.input_prompt()

    try:
        # for anonymity edit google library to run through proxychains
        urls = search(res, stop=20)
        H()
        sprint("Take your pick.")
        for url in urls:
            print(url)
            time.sleep(0.03)
        return
    except Exception as e:
        logging.debug(str(e))
        H()
        sprint(random.choice(bad_connection_responses))
        return
Exemple #13
0
def usersTurn(n1=1, n2=1, depth=0):
    try:
        start = time.time()
        nextInt = n1 + n2
        try:
            userNext = display_manager.input_prompt()
            test = int(userNext)
        except Exception as e:
            logging.error(e)
            return

        end = time.time()
        gameOver = False

        if int(end - start) > 10:
            H()
            sprint('You took too long. Your max depth is %s.' % depth)
            start_over()

        if int(userNext) != nextInt:
            H()
            sprint('Cute. Max depth is %s.' % depth)
            gameOver = True

        if gameOver:
            start_over()
            # todo: save high score to file. Sustain if depth is lower.
        else:
            n1 = n2
            n2 = nextInt
            depth += 1
            lunasTurn(n1, n2, depth)
    except KeyboardInterrupt as e:
        H()
        sprint("Sequence terminated.")
        return
Exemple #14
0
def select_option(display_object, display_range, criteria=None):
    global state_object
    for i in range(display_range[0], display_range[1]):
        print(f'{i+1} {display_object[str(i)]}')

    # context management
    active_navigation_options = ['99']
    default_navigation_options = ['99', 'b', 'n', 'm', 'c']

    if (display_range[0] > 0):
        print('b back  ', end='')
        active_navigation_options.append('b')
    if (display_range[1] + 1 < len(display_object)):
        print('n next')
        active_navigation_options.append('n')
    print('\n99 exit | m main menu | c criteria selection')

    displayed_options = [*range(display_range[0] + 1, display_range[1] + 1)]
    logging.info('Got rows on current page: %s' % displayed_options)

    user_input = display_manager.input_prompt()
    print('')

    # selection logic
    if (user_input.isnumeric() and int(user_input) in displayed_options):
        index = int(
            user_input
        ) - 1  # displayed indexes are 1-based, their source object is 0-based
        logging.info('Selected row number: %s' % index)
        logging.info('Applying to object: %s' % display_object)
        state_object = {
            'value': display_object[f'{index}'],
            'last_displayed': display_range,
            'index': index
        }
        logging.info('State object: %s' % state_object)
        return

    # navigation logic
    if (user_input in default_navigation_options):
        if (user_input.lower() == 'n'):
            page_size = 10 if len(
                display_object) > 10 else len(display_object) - 1
            range_start = display_range[0] + page_size
            range_end = display_range[1] + page_size

            if range_end > len(display_object):
                range_end = len(display_object)

            if (user_input in default_navigation_options
                    and user_input not in active_navigation_options):
                range_start = 0
                range_end = 10 if len(display_object) > 10 else len(
                    display_object)

            logging.info(f'Requesting pages {range_start} to {range_end}')
            select_option(display_object, [range_start, range_end], criteria)

        if (user_input.lower() == 'b'):
            if (displayed_options[0] == 1):
                logging.info('Return to main menu requested')
                list_urls(criteria)
                return

            range_start = display_range[0] - 10 if display_range[0] > 10 else 0
            range_end = range_start + 10
            logging.info(f'Requesting pages {range_start} to {range_end + 5}')
            select_option(display_object, [range_start, range_end], criteria)

        if (user_input.lower() == 'm'):
            logging.info('Return to main menu requested')
            list_urls(criteria)
            return

        if (user_input.lower() == 'c'):
            logging.info('Return to criteria selection requested')
            main()
            return

        if (user_input == '99'):
            state_object = {
                'value': 'exit',
                'last_displayed': display_range,
                'index': 0
            }
            logging.info('Exiting with state: %s' % state_object)
            return
        return
Exemple #15
0
def directive(content, title, interm, *mode):
    """This fuction is informants() helper. It can save or show more data from the
       data displayed by informant. If user request is neither of these two actions
       it is sent to NLU and coordinated as necessary.
    """
    if mode and mode[0] == 'flesh':
        text_normaliser(content[interm:])

    action = display_manager.input_prompt()

    if (not mode) or (mode[0] != 'flesh') and ('more' in action):
        logging.info('Displaying the rest of document "%s".' % title)
        if 'displaystyle' not in content[interm:] and 'textstyle' not in content[interm:]:
            display_manager.output_prompt(); print(content[interm:])
            directive(content, title, interm, *['break'])
        else:
            display_manager.output_prompt(); output_controller(content[interm:], True)
            directive(content, title, interm, *['break'])

    elif action == 'save':
        try:
            insertion_res = persistence.insert_document('intelligence', title, content)
            logging.info(insertion_res)
            display_manager.output_prompt(); sprint("Saved.")
            return

        except ValueError as e:
            logging.error(e)
            display_manager.output_prompt(); sprint("Previous intell already exists. Update?[yes/no]")
            user_action = display_manager.input_prompt().lower()

            if user_action == 'yes':
                try:
                    old_entry = persistence.get_document('intelligence', title)
                    insertion_res = persistence.insert_document('archive', title, old_entry)
                    logging.info(insertion_res)
                    deletion_res = persistence.delete_document(title)
                    logging.info(deletion_res)
                    insertion_res = persistence.insert_document('intelligence', title, content)
                    logging.info(insertion_res)
                    display_manager.output_prompt(); sprint("Done.")
                    return

                except Exception as e:
                    rollbar.report_exc_info()
                    logging.error(str(e))
                    display_manager.output_prompt(); sprint('I ran into trouble. Check the logs.')
                    return
            else:
                if user_action == 'no':
                    display_manager.output_prompt(); sprint("Old entry sustained.")
                    return
        except Exception as e:
            rollbar.report_exc_info()
            logging.error(str(e))
            display_manager.output_prompt(); sprint('I ran into trouble. Check the logs.')
            return

    elif action.lower() == 'pin':
        result = persistence.update_doc_flags('intelligence', title, 'PIN_TO_START')
        logging.debug(result)
        if (result.startswith('Success')):
            display_manager.output_prompt(); sprint('Pinned.')
        else:
            display_manager.output_prompt(); sprint('I couldnt pin this article. Check the logs.')
        return

    else:
        logging.info(f"Returning '{action}' to caller")
        return action