Beispiel #1
0
async def process():
    printf(
        HTML(f"<ansiwhite>connecting to <b>{host}:{port}</b></ansiwhite>\n"))
    client_stream = await trio.open_tcp_stream(host, port)
    async with client_stream:
        async with trio.open_nursery() as nursery:
            nursery.start_soon(sender, client_stream)
            nursery.start_soon(receiver, client_stream)
Beispiel #2
0
 def c_import(self, args):
     hit, partial_hit, miss = self.core.detect_addons()
     if args == 'install' and len(hit) > 0:
         self.c_install(','.join(hit))
     else:
         printft(HTML(f'<ansigreen>Addons found:</ansigreen>'))
         for addon in hit:
             printft(addon)
         printft(HTML(f'\n<ansiyellow>Possible matches:</ansiyellow>'))
         for addon in partial_hit:
             printft(HTML(' <ansiwhite>or</ansiwhite> '.join(addon)))
         printft(HTML(f'\n<ansired>Unknown directories:</ansired>'))
         for addon in miss:
             printft(f'{addon}')
         printft(HTML(f'\nExecute <ansiwhite>import install</ansiwhite> command to install all detected addons.\n'
                      f'Possible matches need to be installed manually with the <ansiwhite>install</ansiwhite>'
                      f' command.'))
Beispiel #3
0
async def producer_handler(cphrsuit, websocket, username, chatroom, servaddr):
    footelem = HTML("<b>[" + chatroom + "]</b>" + " " + username.strip() + " - Sanctuary ZERO v04092020 running on '" + servaddr + "' - Hit Ctrl+C to EXIT")
    while True:
        with patch_stdout():
            mesgtext = await sess.prompt_async(lambda:"[" + obtntime() + "] " + formusnm(str(username)) + " > ", bottom_toolbar=footelem, validator=emtyfind(), refresh_interval=0.5)
        senddata = json.dumps({"username": username.strip(), "chatroom": chatroom, "mesgtext": mesgtext.strip()})
        senddata = cphrsuit.encrjson(senddata)
        await websocket.send(senddata)
Beispiel #4
0
 def get_cmd_prefix():
     has_focus = ctx.app.layout.current_buffer is ctx.cmd_buffer
     cls = style.COMMAND_FOCUSED
     if has_focus:
         text = f"<{cls}>> </{cls}>"
     else:
         text = "> "
     return HTML(text)
Beispiel #5
0
def sp(text):
  style = Style.from_dict({
    'user': '******',
    'tweet': '#b5a360',
    'timestamp': '#386577'
    })

  print_formatted_text(HTML(text), style=style)
Beispiel #6
0
 def run_command_line(self, text):
     try:
         cmd, args = self.parse_command_line(text)
         cmd(*args)
     except KeyboardInterrupt:
         raise
     except Exception as err:
         print_formatted_text(HTML('<red>Error:</red> {}'.format(err)))
Beispiel #7
0
 def handle_exception(self, e):
     if len(self.table_data) > 1:
         print(self.table.table)
     if getattr(sys, 'frozen', False):
         printft(HTML(f'\n<ansibrightred>{str(e)}</ansibrightred>'))
     else:
         sys.tracebacklimit = 1000
         traceback.print_exc()
Beispiel #8
0
def _source(args):
    """source reads commands from one or more source files.
    Each command must be on one line and the commands must be separated with
    newlines.
    The files may contain comments. The comment symbol is #
    """
    import shlex
    import html

    m = mocktraffic.MockTraffic()

    for filename in args.files:
        if filename.startswith('~'):
            filename = os.path.expanduser(filename)
        try:
            with open(filename) as f:
                for i, l in enumerate(f):
                    # Shell commands can be called from scripts. They start with '!'
                    if l.startswith('!'):
                        os.system(l[1:])
                        continue

                    # If recording commands, submit the command line.
                    # Don't record the "source" command itself.
                    if m.is_recording(
                    ) and not l.lstrip().startswith('source'):
                        m.record_command(l)

                    # With comments=True shlex will remove comments from the line
                    # when splitting. Comment symbol is #
                    s = shlex.split(l, comments=True)

                    # In verbose mode all commands are printed before execution.
                    if args.verbose and s:
                        print(HTML(f'<i>> {html.escape(l.strip())}</i>'))
                    cli.parse(s)
                    if cli.last_errno != 0:
                        print(
                            HTML(f'<ansired><i>{filename}</i>: '
                                 f'Error on line {i + 1}</ansired>'))
                        if not args.ignore_errors:
                            return
        except FileNotFoundError:
            print(f"No such file: '{filename}'")
        except PermissionError:
            print(f"Permission denied: '{filename}'")
Beispiel #9
0
 def c_force_update(self, args):
     if args:
         self.c_update(args, False, True, True)
     else:
         printft(
             HTML(
                 '<ansigreen>Usage:</ansigreen>\n\tThis command accepts a comma-separated list of links or addo'
                 'n names as an argument.'))
Beispiel #10
0
 def load_cli_owners_from_words(self, words: List[str]):
     if len(words) == 1:  # Reading seed from Environment Variable
         words = os.environ.get(words[0], default="").strip().split(" ")
     parsed_words = ' '.join(words)
     try:
         for index in range(100):  # Try first accounts of seed phrase
             account = get_account_from_words(parsed_words, index=index)
             if account.address in self.safe_cli_info.owners:
                 self.load_cli_owners(account.key)
         if not index:
             print_formatted_text(
                 HTML(
                     f'<ansired>Cannot generate any valid owner for this Safe</ansired>'
                 ))
     except ValidationError:
         print_formatted_text(
             HTML(f'<ansired>Cannot load owners from words</ansired>'))
Beispiel #11
0
def exec_channel_list():
    """加载所有频道列表"""
    name_list = RSS_CONFIG['RSS_URL_LIST']

    name_list.update(get_site_rss_channel_title_link_dict())

    nl = []
    num = 0
    for k, v in name_list.items():
        nl.append('[ ' + str(num) + ' ] ' + '<b>' + k + '</b>')
        num += 1

    name_keys = [item for item in name_list.keys()]

    terminal_config.PROMPT_MESSAGE_BASE.append(('', 'channel'))
    terminal_config.PROMPT_MESSAGE_BASE.append(('class:path', '>'))

    def bottom_toolbar():
        return [
            ('class:bottom-toolbar', '[ b ]返回'),
            ('class:bottom-toolbar', '  [ r + 编号 ]设置频道为已读'),
        ]

    while True:
        print_formatted_text(HTML("\r\n".join(nl)))

        num = -1
        try:
            user_input = prompt(terminal_config.PROMPT_MESSAGE_BASE,
                                style=terminal_config.STYLE,
                                bottom_toolbar=bottom_toolbar)
            num = int(user_input)
        except KeyboardInterrupt:
            print('bye bye !!!')
            exit()
            break
        except EOFError:
            print('bye bye !!!')
            exit()
            break
        except ValueError:
            pass

        if user_input == 'b':
            terminal_config.PROMPT_MESSAGE_BASE = terminal_config.PROMPT_MESSAGE_BASE[
                0:-2]
            break
        if num >= 0:
            name = name_keys[int(user_input)]
            url = name_list[name]
            exec_news_list(name, url)
            continue
        if re.match(r'r \d+', user_input) is not None:
            channel_name = name_keys[int(re.findall(r'\d+', user_input)[0])]
            channel_link = name_list[channel_name]
            terminal.exec_read_by_channel(channel_link)
            print('频道:', channel_name, '设置为已读成功')
            continue
Beispiel #12
0
def sendTUI(pwd):
    os.system('clear')

    session = PromptSession(history=FileHistory(functions.HOME +
                                                '/.sendmail_mailinglist'))

    print_formatted_text(HTML(
        'Please enter your receiver (if you get suggested adresses, just press <wbg>→ </wbg>:'
    ),
                         style=style)
    receiver = session.prompt("> ",
                              validator=functions.validateEmail(),
                              auto_suggest=AutoSuggestFromHistory())
    print("Please enter your subject:")
    subject = input("> ")
    print_formatted_text(HTML(
        'Please enter your message content. If you have finished your text press <wbg>ALT</wbg> + <wbg>ENTER</wbg>:'
    ),
                         style=style)
    print("")

    text = prompt('> ',
                  multiline=True,
                  prompt_continuation=functions.prompt_continuation,
                  mouse_support=True)
    attachment = confirm("Do you want to add one attachment to the email?")
    if attachment:
        print_formatted_text(
            HTML(
                "Please enter the whole filepath to your attachment file. For example: <ansigreen>/home/lolo/documents/test.pdf</ansigreen>"
            ))
        filepath = prompt("> ",
                          validator=functions.validateFilePath(),
                          completer=PathCompleter())
    else:
        filepath = None

    send(addr_to=receiver,
         subject=subject,
         message=text,
         password=pwd,
         filename=filepath)

    os.system('clear')
    return
Beispiel #13
0
def job(args, competitions):
    sys.stdout.write('\r' + '─' * 80 + '\n')
    sys.stdout.flush()
    start_str = datetime.datetime.today().strftime(
        '%d %b %Y - %H:%M:%S').rjust(80 - len(' '.join(sys.argv[1:])))
    if not args.quiet:
        print(HTML(f'<teal>{" ".join(sys.argv[1:])}{start_str}</teal>\n'))
    try:
        spider = spiders[args.bookmaker](
            username=args.username,
            password=args.password,
            headless=args.notheadless,
            proxy=args.proxy,
            console_level=args.log,
        )
        for i, [country, league] in enumerate(competitions):
            with yaspin(text=f'scraping {country} - {league}') as sp:
                try:
                    start_time = time.time()
                    events, odds = spider.soccer.odds(country, league)
                    if args.db:
                        database.save_events_odds_in_db(
                            events, odds, args.bookmaker)
                    if args.json is not None:
                        database.save_events_odds_in_json(
                            events, odds, args.bookmaker, args.json)
                    sp.hide()
                    msg = f' {country} - {league}'
                    info = (f'{len(events)} events / {len(odds)} odds  '
                            f'{(time.time() - start_time):5.4}s '
                            f'[{1+i}/{len(competitions)}]')\
                        .rjust(79 - len(msg))
                    print(HTML(f'<seagreen>✔</seagreen>' + msg + info))
                except (IndexError, KeyError, ValueError) as e:
                    sp.hide()
                    msg = f' {country} - {league} [{type(e).__name__}]'
                    count = f'[{1+i}/{len(competitions)}]'.rjust(79 - len(msg))
                    print(HTML(f'<red>✘</red>' + msg + count))
                    e_msg = '\n  '.join(e.args)
                    print(f'  {e_msg}')
                sp.show()
    finally:
        print()
        spider.quit()
        del spider
Beispiel #14
0
async def chatroom(websocket, path):
    if not websocket in USERS:
        USERS[websocket] = ""
    try:
        async for mesgjson in websocket:
            if sepr in mesgjson and websocket in USERS:
                if (mesgjson.split(sepr)[0] == "CHKUSR") & (len(
                        mesgjson.split(sepr)) == 3):
                    result = str(chk_username_presence(mesgjson))
                    await websocket.send(result)
                    if (result == "True"):
                        await websocket.close()
                        USERS.pop(websocket)
                elif USERS[websocket] == "":
                    USERS[websocket] = [
                        mesgjson.split(sepr)[0],
                        mesgjson.split(sepr)[1]
                    ]
                    print_formatted_text(
                        HTML("[" + obtntime() + "] " +
                             "<b>USERJOINED</b> > <green>" +
                             mesgjson.split(sepr)[0] + "@" +
                             mesgjson.split(sepr)[1] + "</green>"))
                    await notify_mesej("SNCTRYZERO" + sepr + "USERJOINED" +
                                       sepr + mesgjson.split(sepr)[0] + sepr +
                                       mesgjson.split(sepr)[1] + sepr +
                                       str(getallus(mesgjson.split(sepr)[1])))
            else:
                if str(mesgjson) == "/list":
                    await send_chatroommembers_list(websocket)
                else:
                    print_formatted_text(
                        HTML("[" + obtntime() + "] " + "<b>SNCTRYZERO</b> > " +
                             helper_display.wrap_text(str(mesgjson))))
                    await notify_mesej(mesgjson)
    except ConnectionClosedError as EXPT:
        print_formatted_text(
            HTML("[" + obtntime() + "] " + "<b>USEREXITED</b> > <red>" +
                 USERS[websocket][0] + "@" + USERS[websocket][1] + "</red>"))
        userlist = getallus(USERS[websocket][1])
        userlist.remove(USERS[websocket][0])
        leftmesg = "SNCTRYZERO" + sepr + "USEREXITED" + sepr + USERS[
            websocket][0] + sepr + USERS[websocket][1] + sepr + str(userlist)
        USERS.pop(websocket)
        await notify_mesej(leftmesg)
Beispiel #15
0
    def change_threshold(self, threshold: int):
        if threshold == self.safe_cli_info.threshold:
            print_formatted_text(
                HTML(f'<ansired>Threshold is already {threshold}</ansired>'))
        elif threshold > len(self.safe_cli_info.owners):
            print_formatted_text(
                HTML(f'<ansired>Threshold={threshold} bigger than number '
                     f'of owners={len(self.safe_cli_info.owners)}</ansired>'))
        else:
            transaction = self.safe_contract.functions.changeThreshold(
                threshold).buildTransaction({
                    'from': self.address,
                    'gas': 0,
                    'gasPrice': 0
                })

            if self.execute_safe_internal_transaction(transaction['data']):
                self.safe_cli_info.threshold = threshold
Beispiel #16
0
 def show_cli_owners(self):
     if not self.accounts:
         print_formatted_text(
             HTML(f'<ansired>No accounts loaded</ansired>'))
     else:
         for account in self.accounts:
             print_formatted_text(
                 HTML(
                     f'<ansigreen><b>Account</b> {account.address} loaded</ansigreen>'
                 ))
         if self.default_sender:
             print_formatted_text(
                 HTML(
                     f'<ansigreen><b>Default sender:</b> {self.default_sender.address}'
                     f'</ansigreen>'))
         else:
             print_formatted_text(
                 HTML(f'<ansigreen>Not default sender set </ansigreen>'))
Beispiel #17
0
 def emit(self, record):
     try:
         record.msg = html.escape(
             record.msg.replace('{', '{{').replace('}', '}}'))
         msg = self.format(record)
         print_formatted_text(
             HTML(msg.format(level_msg_styles[record.levelno])), style=style)
     except Exception:
         self.handleError(record)
Beispiel #18
0
def display_qr(qr_read, verbose):
    """QR util method to display
    
    Args:
        qr_read ([Reg]): Data of the qr read
        verbose (Boolean): To display mor info
    """
    color = ColorSelected().theme.confirm
    print(color)
    print_ok_raw(f"Found {len(qr_read)} registries")
    for idx, reg in enumerate(qr_read):
        print_info(f"==== Reg {idx} ====")
        print_formatted_text(HTML(f"<{color}>Data:</{color}> {reg.data}"))
        if (verbose):
            print_formatted_text(HTML(f"<{color}>Type:</{color}> {reg.type}"))
            print_formatted_text(HTML(f"<{color}>Rect:</{color}> {reg.rect}"))
            print_formatted_text(
                HTML(f"<{color}>Polygon:</{color}> {reg.polygon}"))
Beispiel #19
0
    def change_threshold(self, threshold: int):
        if threshold == self.safe_cli_info.threshold:
            print_formatted_text(
                HTML(f"<ansired>Threshold is already {threshold}</ansired>"))
        elif threshold > len(self.safe_cli_info.owners):
            print_formatted_text(
                HTML(f"<ansired>Threshold={threshold} bigger than number "
                     f"of owners={len(self.safe_cli_info.owners)}</ansired>"))
        else:
            transaction = self.safe_contract.functions.changeThreshold(
                threshold).buildTransaction({
                    "from": self.address,
                    "gas": 0,
                    "gasPrice": 0
                })

            if self.execute_safe_internal_transaction(transaction["data"]):
                self.safe_cli_info.threshold = threshold
 def c_set_wa_wow_account(self, args):
     if args:
         args = args.strip()
         if os.path.isfile(
                 Path(f'WTF/Account/{args}/SavedVariables/WeakAuras.lua')):
             printft(
                 HTML(
                     f'WoW account name set to: <ansiwhite>{args}</ansiwhite>'
                 ))
             self.core.config['WAAccountName'] = args
             self.core.save_config()
         else:
             printft('Incorrect WoW account name.')
     else:
         printft(
             HTML(
                 '<ansigreen>Usage:</ansigreen>\n\tThis command accepts the WoW account name as an argument.'
             ))
Beispiel #21
0
def download(opts):
    while True:
        # Clear screen.
        system("cls")

        # Get the URL from the user.
        url = input_formatted(
            HTML("""
            <b>Paste in your link and hit enter.</b>

            Playlists links are supported!
            Searching is also supported! Just prefix your query with:
                - <b>'ytsearch:'</b>, for <ansired>YouTube</ansired>
                - <b>'scsearch:'</b>, for <orange>Soundcloud</orange> (MP3 only!)

            <ansired>You can also exit back to the main menu using <b>'Q'</b> or <b>'X'</b>.</ansired>

            """

                 # noqa
                 ))
        if url.upper() in ("Q", "X"):
            break

        # Set some opts that should always be set this way. #
        # Prefer FFMPEG.
        opts["prefer_ffmpeg"] = True
        # Points towards the FFMPEG we downloaded.
        opts["ffmpeg_location"] = join(ffmpeg_dir_path, "bin")
        # Restrict to safe filenames.
        opts["restrict_filenames"] = True
        # Sets our logger for any information from youtube-dl.
        opts["logger"] = logger
        # Sets our hook that is called whenever youtube-dl makes any progress downloading a file.
        opts["progress_hooks"] = [ytdl_hook]

        # Create a root Tkinter window that we will instantly hide.
        root = Tk()
        # Hide the window.
        root.withdraw()
        # Ask for a save directory.
        opts["outtmpl"] = join(
            askdirectory(mustexist=True, initialdir=current_dir),
            "%(title)s.%(ext)s")
        # Destroy the hidden root window once we are done with it.
        root.destroy()

        with ytdl.YoutubeDL(opts) as ydl:
            try:
                print()
                ydl.download([url])
                break
            except ytdl.utils.DownloadError:
                # Wait a little so they can read the above.
                sleep(5)
                # Reset menu.
                continue
Beispiel #22
0
 def enable_module(self, module_address: str):
     if module_address in self.safe_cli_info.modules:
         print_formatted_text(HTML(f'<ansired>Module {module_address} is already enabled</ansired>'))
     else:
         transaction = self.safe_contract.functions.enableModule(
             module_address
         ).buildTransaction({'from': self.address, 'gas': 0, 'gasPrice': 0})
         if self.execute_safe_internal_transaction(transaction['data']):
             self.safe_cli_info.modules = self.safe.retrieve_modules()
Beispiel #23
0
 def reveal_shard(self, shard_name: str) -> None:
     self._ensure_shards(shards_expected=True)
     shard = self.shards[shard_name]
     words = shard.encrypted_mnemonic
     print_formatted_text(
         HTML("Encrypted SLIP39 phrase for shard <i>{}</i>:\n".format(
             shard_name)))
     print_formatted_text("\n".join(textwrap.wrap(words, 80)), "\n")
     self.interface.get_line_then_clear()
Beispiel #24
0
 async def set_server_client_drop_probability(self):
     """
     set_server_client_drop_probability handles the "scprob" command.
     """
     print(
         HTML(
             f"Current probability is <ansired>{self._droppers[1].prob}</ansired>."
         ))
     self._droppers[1].prob = await self._prompt_probability()
Beispiel #25
0
def process_status(process, max_puid_len=10, group_by='group'):
    state = process['statename']
    uid = '{{uid:{}}}'.format(max_puid_len).format(uid=process['uid'])
    desc = process_description(process)
    text = '{p}{uid} <{lstate}>{state:8}</{lstate}> {description}' \
           .format(p=('' if group_by in (None, 'process') else '  '),
                   uid=uid, state=state, lstate=state.lower(),
                   description=desc)
    return HTML(text)
Beispiel #26
0
 def c_force_update(self, args):
     if args:
         self.c_update(args, False, True, True)
     else:
         # noinspection PyTypeChecker
         answer = confirm(HTML('<ansibrightred>Execute a forced update of all addons and overwrite ALL local '
                               'changes?</ansibrightred>'))
         if answer:
             self.c_update(False, False, True, True)
Beispiel #27
0
def no_contrib_action(user_knowledge, user_name):
    if not user_knowledge:
        name = user_name
        print_formatted_text(HTML("<ansiyellow>Sadly, " \
                                  f"<i>[[{name}-Bot]]</i> has made no " \
                                  "contributions</ansiyellow>"))
        return prompt("Ask someone else? [y/n] ").lower() == "y"
    else:
        return "skip"
Beispiel #28
0
 def print(self):
     # displays the matrix
     width = self.columnWidth()
     print("_" * (self.cols * (width + 1) + 1))
     for row in self.allRows():
         printRow = "|"
         for element in row:
             printRow += str(element).center(width) + "|"
         print_formatted_text(HTML('<u>' + printRow + '</u>'))
Beispiel #29
0
def servenow(netpdata="127.0.0.1", chatport="9696"):
    try:
        start_server = websockets.serve(chatroom, netpdata, int(chatport))
        asyncio.get_event_loop().run_until_complete(start_server)
        print_formatted_text(
            HTML(
                "[" + obtntime() + "] " +
                "<b>SNCTRYZERO</b> > <green>SNCTRYZERO was started up on 'ws://"
                + str(netpdata) + ":" + str(chatport) + "/'</green>"))
        asyncio.get_event_loop().run_forever()
    except KeyboardInterrupt:
        print("")
        print_formatted_text(
            HTML(
                "[" + obtntime() + "] " +
                "<b>SNCTRYZERO</b> > <red><b>SNCTRYZERO was shut down</b></red>"
            ))
        sys.exit()
Beispiel #30
0
 def update(self, status):
     counters = status.ImageCounters
     self.set_items_completed(self.acq_counter,
                              counters.LastImageAcquired + 1)
     self.set_items_completed(self.base_counter,
                              counters.LastBaseImageReady + 1)
     self.set_items_completed(self.img_counter, counters.LastImageReady + 1)
     if self.save_counter:
         self.set_items_completed(self.save_counter,
                                  counters.LastImageSaved + 1)
     acq = status.AcquisitionStatus
     if status.Error != Lima.Core.CtControl.NoError:
         error = ErrorMap[status.Error]
         print_formatted_text(
             HTML(f'<red>Acquisition error: </red> <b>{error}</b>'))
     elif acq == AcqFault:
         print_formatted_text(HTML(f'<orange>Acquisition fault</orange>'))
     return acq == AcqRunning and status.Error == Lima.Core.CtControl.NoError