コード例 #1
0
def send_input(json_obj,
               pp,
               send_file=False,
               send_public=False,
               msg_receiver_s='',
               subj='',
               sent_msg_cont=''):

    # get aliases:
    only_return_book = False
    if msg_receiver_s != '' or subj != '':
        only_return_book = True

    addr_alia = iop.print_addr_book(json_obj, only_return_book)

    # 1. prompt for subject / or default
    # subj='' #iop.input_prompt(propmtstr='\n Enter message subject: ', confirm=True, soft_quite=True)
    # 2. prompt for receiver / check key or pass exist ...
    if msg_receiver_s == '':
        msg_receiver_s = iop.input_prompt(
            propmtstr=
            '\n Enter receiver address or alias - multiple after comas: ',
            confirm=False,
            soft_quite=True)

    if msg_receiver_s == 'q' or msg_receiver_s == '':
        print('Quitting message...')
        return '', '', '', ''

    # msg_receiver_s=msg_receiver_s.split(',')

    msg_receivers_list = msg_receiver_s  #[] #msg_receiver.strip().lower()
    # for msg_receiver in msg_receiver_s:

    # if msg_receiver in addr_alia.keys():
    # msg_receivers_list.append(msg_receiver.strip())

    # elif '@' in msg_receiver and send_public:
    # msg_receivers_list.append(msg_receiver.strip())

    # else : # if not full mail try match alias
    # print('Extracting alias address...')
    # tmp=0
    # for kk in addr_alia.keys():
    # if addr_alia[kk]==msg_receiver:
    # tmp=1
    # print('Matched alias '+msg_receiver+' to '+kk)
    # msg_receivers_list.append(kk)
    # break
    print(msg_receivers_list)

    if len(msg_receivers_list) == 0:
        print('...no proper address found - quitting message!...')
        return '', '', '', ''
    else:
        print('Sending to ' + str(msg_receivers_list))

    same_keys = True
    keytype = []
    key = []
    if send_public == False:

        pubkeys = iop.gpg_uids()
        # "outgoing_encryption_type","outgoing_encryption_key"
        for ijk, msg_receiver in enumerate(msg_receivers_list):
            if json_obj["outgoing_encryption_type"] == 'pgp':
                if json_obj["outgoing_encryption_key"] in str(pubkeys):
                    keytype.append('pgp')
                    key.append(json_obj["outgoing_encryption_key"])
                else:
                    print('Wrong key ' + json_obj["outgoing_encryption_key"] +
                          ' for address ' + msg_receiver)
                    print('Available keys: ' + str(pubkeys))
                    return '', '', '', ''

            elif json_obj[
                    "outgoing_encryption_type"] == 'aes256':  #msg_receiver in json_obj["address_book"].keys():
                keytype.append('aes256')
                key.append(json_obj["outgoing_encryption_key"])

            else:
                print(
                    'Address ' + msg_receiver +
                    ' missing key or password! First add the address to address book using command saveaddr and set proper password for message encryption and decryption.'
                )
                return '', '', '', ''

            if same_keys and ijk > 0:
                if keytype[ijk] != keytype[ijk - 1] or key[ijk] != key[ijk -
                                                                       1]:
                    same_keys = False
                    print(
                        '[!] Provided addresses have different keys/passwords - will send multiple messages if you continue...'
                    )

    msg_content = ''

    if send_public:
        subj = iop.input_prompt(propmtstr='\n Enter message subject: ',
                                confirm=True,
                                soft_quite=True)  # if empty - quit sending ...

    if send_file:
        msg_content = iop.select_file(tmppath='my_files')
    elif sent_msg_cont != '':
        msg_content = sent_msg_cont
    else:
        # 3. prompt for content -> save to attachment
        msg_content = iop.input_prompt(
            propmtstr='\n Enter message text/content: ',
            confirm=True,
            soft_quite=True)  # if empty - quit sending ...

    if msg_content in ['', 'q']:
        if msg_content == '':
            print('Quitting message - empty content...')
        else:
            print('Quitting message.')

        return '', '', '', ''

    str_new_id_send = str(0)
    new_id_send = 0
    try:
        new_id_send = int(json_obj["send_internal_id"]) + 1
        str_new_id_send = str(new_id_send)
    except:
        print()

    ret_list = []

    if send_public:

        fname = ''  #os.path.join('archive','sent','sent_'+str_new_id_send+'.txt')
        if send_file:
            fname = msg_content
        # else:
        # iop.save_file(fname,msg_content )
        ret_list.append([fname, subj, msg_receivers_list, msg_content])

    elif same_keys:

        ret_list.append([
            iop.encr_msg(msg_content,
                         keytype[0],
                         key[0],
                         internal_id_str=str_new_id_send), subj,
            msg_receivers_list, str_new_id_send
        ])
    else:
        print('msg_content', msg_content)

        for ijk in range(len(keytype)):
            ret_list.append([
                iop.encr_msg(msg_content,
                             keytype[ijk],
                             key[ijk],
                             internal_id_str=str_new_id_send), subj,
                msg_receivers_list[ijk], str_new_id_send
            ])
            new_id_send += 1
            str_new_id_send = str(new_id_send)

    json_obj["send_internal_id"] = str_new_id_send
    # iop.saving_encr_cred( json.dumps(json_obj), newest_file, pp)

    return ret_list
コード例 #2
0
def search_incoming(mail_from, mail_from_pswd, imap_addr, def_opt_init={}):

    mail = None
    try:
        mail = imaplib.IMAP4_SSL(imap_addr)
        mail.login(mail_from, mail_from_pswd)
        mail.select('inbox')
    except:
        err_track = traceback.format_exc()
        return {"Error": err_track}, []

    def_opt = {
        'date_before': 'any',
        'date_since': 'any',
        'from': 'any',
        'subject': 'any',
        'last_msg_limit': 5,
        'only_new': 'yes'
    }

    def_opt_set = {
        'date_before': ['*', 'any', 'all', '9912-12-12'],
        'date_since': ['*', 'any', 'all', '1912-12-12'],
        'from': ['*', 'any', 'all'],
        'subject': ['*', 'all', 'any']
    }

    def_opt_usr = def_opt.copy(
    )  #{'date_before':'2019-09-01','date_since':'any', 'from':'*', 'subject':'any', 'last_msg_limit':5, 'only_new':'no'} #def_opt

    ## tutaj prompter - user wybier i potwierdza dane ... 6 danych ...

    if def_opt_init != {}:
        for kk, vv in def_opt_usr.items():
            if kk in def_opt_init:
                def_opt_usr[kk] = def_opt_init[kk]  #overwrite with init value

    else:  # manual enter values

        # print('\nSet mail search params ... ') #,json_obj[kk])
        for kk in def_opt_usr.keys():

            opt = ''
            if kk in def_opt_set.keys():
                opt = ' Options: ' + str(def_opt_set[kk])

            tmpv = iop.input_prompt(
                '> Enter [' + str(kk) + '] current: [' + str(def_opt_usr[kk]) +
                '] ' + opt + ' OR end editing [e] : ', False, True)
            tmpv = tmpv.strip()

            if tmpv == 'e':
                break

            elif tmpv == '':
                continue

            elif kk == 'last_msg_limit':
                try:
                    tmpv = int(tmpv)
                except:
                    # print('Wrong mail search value - should be int number: '+tmpv)
                    continue

            def_opt_usr[kk] = tmpv  #propmtstr,confirm=False, soft_quite=False

    # print('Mail search params: ', def_opt_usr)

    total_str = ''

    if True:  #def_opt_usr!=def_opt:

        for kk, vv in def_opt_usr.items():

            if kk == 'only_new':  #,'only_new':['yes','no','y','n']
                if vv in ['yes', 'y']:
                    total_str += '(UNSEEN) '

            elif kk == 'last_msg_limit':  # def_opt_usr['last_msg_limit']
                continue

            elif vv not in def_opt_set[kk]:  # if not default option:

                if vv in ['*', 'any', 'all']:
                    continue

                if kk == 'date_since':

                    tmpdate = datetime.datetime.strptime(vv, '%Y-%m-%d')
                    tmpdate = tmpdate.strftime("%d-%b-%Y")

                    total_str += '(SENTSINCE {0})'.format(tmpdate) + ' '

                elif kk == 'date_before':

                    tmpdate = datetime.datetime.strptime(vv, '%Y-%m-%d')
                    tmpdate = tmpdate.strftime("%d-%b-%Y")

                    total_str += '(SENTBEFORE {0})'.format(tmpdate) + ' '

                elif kk == 'from':

                    total_str += '(FROM {0})'.format(vv.strip()) + ' '

                elif kk == 'subject':

                    total_str += '(SUBJECT "{0}")'.format(vv.strip()) + ' '

            # elif kk=='last_msg_limit':
            # if vv>1

    total_str = total_str.strip()
    if total_str == '':
        total_str = 'ALL'

    # now seelect top N msg ...
    # print('Search string: ['+total_str+']')
    ttype, data = mail.search(
        None, total_str
    )  #'(SENTSINCE {0})'.format(date), '(FROM {0})'.format(sender_email.strip())

    if ttype != 'OK':
        mail.close()
        mail.logout()
        return {}, []  #'no msg found'

    mail_ids = data[0]
    id_list = mail_ids.split()

    inter_indxi = [int(x) for x in id_list]
    # inter_indxi.sort(reverse = True)
    inter_indxi.sort()

    msg_to_process = {}

    # def_opt_usr['last_msg_limit']
    max_iter = def_opt_usr['last_msg_limit']
    if max_iter < 1 or max_iter > len(inter_indxi) or max_iter > 999:
        max_iter = min(999, len(inter_indxi))
        # print('Search [last_msg_limit]<1, setting max '+str(max_iter)+' messages')
        # max_iter=999

    # in here only return indexes for decryption!

    # print('... processing messages ... count ',str(len(inter_indxi)))

    iilist = []

    for i in inter_indxi:  #[25]

        if max_iter < 1:
            break

        # first fetch body structure to count attachments! and email size
        typ, dd = mail.fetch(str(i), 'BODYSTRUCTURE')

        att_count = 0
        msg_size = 0

        if len(dd) > 0:  #count att:
            # print('\n***'+str(email.message_from_bytes(dd[0] ))+'***\n')
            bstr = str(email.message_from_bytes(dd[0]))  #.lower()
            tmpstr = bstr.split("\"ATTACHMENT\"")  #'attachment')
            att_count += len(tmpstr) - 1
            # print('att_count',att_count)
            # exit()

        typ, dd = mail.fetch(str(i), '(RFC822.SIZE)')
        tmps = str(email.message_from_bytes(dd[0]))
        tmps = tmps.replace('(', '').replace(')', '')
        tmps = tmps.split()
        if len(tmps) > 2:
            if 'RFC822.SIZE' in tmps[1]:
                # print('size?',tmps[2])
                msg_size = tmps[2]
                if iop.is_int(msg_size):
                    msg_size = str(round(float(msg_size) / 1024 / 1024,
                                         1)) + ' MB'

        typ, dd = mail.fetch(
            str(i),
            '(BODY.PEEK[] FLAGS)')  # FIRST READ FLAGS TO RESTORE THEM !

        for response_part in dd:
            if isinstance(response_part, tuple):

                msg = email.message_from_string(
                    response_part[1].decode('utf-8'))
                mail_to = ''
                if msg["To"] != None:
                    mail_to = msg["To"]  #.split(',')
                # print(msg["Date"]+'|'+msg["From"]+'|'+msg["Subject"])

                tmpdate = email.utils.parsedate(msg["Date"])
                tmpdate = datetime.datetime.fromtimestamp(time.mktime(tmpdate))
                tmpdate = tmpdate.strftime('%Y-%m-%d')

                iilist.append(max_iter)
                tmpdict = {
                    "Date": tmpdate,
                    "From": msg["From"],
                    "To": mail_to,
                    "Subject": msg["Subject"],
                    "ID": str(i),
                    "Attachments": att_count,
                    "EmailSize": msg_size
                }
                msg_to_process[max_iter] = tmpdict  #.append(tmpdict)
                max_iter -= 1

    mail.close()
    mail.logout()

    return msg_to_process, iilist
コード例 #3
0
        print('Initial consolidation run:')
        # run through all addresse with nonzero balances
        wallet_consolidation(CLI_STR, json_conf, FEE)

    while deamon_warning not in zxc:  # and citer>0:

        if selected_mode == 'wallet':
            wallet_mode_limits = {}
            wallet_mode_limits["tx_amount_limit"] = '999999'
            wallet_mode_limits[
                "tx_time_limit_hours"] = '1'  # no limits when wallet mode!
            # print()
            time.sleep(0.5)

            user_cmd = iop.input_prompt("\nEnter your command:",
                                        confirm=False,
                                        soft_quite=True)  #input()
            user_cmd = iop.clear_whites(user_cmd)

            if user_cmd.lower() in ['confirm', 'confirmed'
                                    ] and toconfstr != '':
                user_cmd = toconfstr

            elif toconfstr != '':
                print('Cancelled previous operation')
                toconfstr = ''
                user_cmd = ''

            if user_cmd != '':

                if 'consolidate' in COMMANDS and user_cmd.lower() in [
コード例 #4
0
def external_addr_book(internal_addr_list,
                       cur_path,
                       pp,
                       CLI_STR,
                       print_only=False):

    json_conf = get_addr_book(cur_path, pp)  #json.loads('{}')

    if print_only:
        return print_cur_addr_book(json_conf)

    act = ["add", "del"]
    print("Actions: " + str(act))

    while True:

        change = False

        print(print_cur_addr_book(json_conf))
        sela = iop.optional_input('Select action or quit [q]: ',
                                  options_list=act,
                                  soft_quite=True)

        if sela in ['', 'q']:
            break

        elif sela == "add":
            newa = ''
            while True:
                newa = iop.input_prompt('Enter new address: ',
                                        confirm=False,
                                        soft_quite=True)

                if newa in ['', 'q']:
                    break

                isv, isz = wallet_commands.isaddrvalid(CLI_STR, newa)
                if isv:
                    break
                else:
                    print('Addresss not valid - enter correct address...')

            if newa in ['', 'q']:
                continue

            addrnick = ''
            while True:
                addrnick = iop.input_prompt(
                    'Enter unique address owner nick/name: ',
                    confirm=True,
                    soft_quite=True)

                # print('internal_addr_list',internal_addr_list)
                # print('internal_addr_list.keys()',internal_addr_list.keys())

                if len(addrnick) < 1:
                    print("Minimum 1 character required...")

                elif addrnick in internal_addr_list.values():
                    print(
                        "This name is already taken [internal wallet alias], enter a different one..."
                    )

                elif addrnick in json_conf:
                    print(
                        "This name is already taken, enter a different one...")
                else:
                    break

            if addrnick != '' and newa != '':
                json_conf[addrnick] = newa
                change = True

        elif sela == "del":

            addrnick = iop.optional_input(
                'Enter address owner nick/name from the book to DELETE it: ',
                options_list=json_conf.keys(),
                soft_quite=True)
            if addrnick != '':
                del json_conf[addrnick]
                change = True

        if change:
            iop.saving_encr_cred(json.dumps(json_conf), cur_path, pp)
コード例 #5
0
def read_app_settings(selected_mode, init_pass=''):

    if not os.path.exists('tmp'):
        os.mkdir('tmp')

    set_name = [
        'email_addr', "email_password", "imap_addr", "smtp_addr",
        "tx_amount_limit", "tx_time_limit_hours", "outgoing_encryption_type",
        "outgoing_encryption_key", "incoming_encryption_type",
        "incoming_encryption_key", "incoming_mail_sender_email",
        "incoming_mail_title", "wallet_secret_key", "gpg_password",
        "incoming_tx_notification", "staking_summary_notification",
        "wallet_encryption", "active_consolidation_address"
    ]

    # set_name=['email_addr',"email_password","imap_addr","smtp_addr","tx_amount_limit","tx_time_limit_hours","outgoing_encryption_type","outgoing_encryption_key","incoming_encryption_type","incoming_encryption_key","incoming_mail_sender_email","incoming_mail_title","wallet_secret_key","gpg_password","incoming_tx_notification","staking_summary_notification"]

    set_value = [
        "my@email", "*****", "imap.gmail.com", "smtp.gmail.com", "1", "24",
        "aes256,pgp", "keyin", "aes256,pgp", "keyout", "optional", "optional",
        "optional", "semioptional", "off", "off", "", ""
    ]

    musthave = [
        'email_addr', "email_password", "imap_addr", "smtp_addr",
        "tx_amount_limit", "tx_time_limit_hours", "outgoing_encryption_type",
        "outgoing_encryption_key", "incoming_encryption_type",
        "incoming_encryption_key"
    ]

    DEAMON_DEFAULTS = {}
    for ij, sn in enumerate(set_name):
        DEAMON_DEFAULTS[sn] = set_value[ij].replace("optional", "").replace(
            "semioptional", "")

    json_conf = ''

    newest_date, newest_file, filed = iop.get_config_file()
    pswd = ''

    # print(newest_date, newest_file, filed)
    # exit()

    if newest_file != '':
        # print('read file - edit in options then exit and force enter again ... ')

        try_decr = True
        decr_str = ''

        while try_decr:

            pp = init_pass
            if pp == '':
                pp = iop.ask_password(newest_file)

            try:
                str_rep = iop.decrypt_cred(pp, newest_file)
                if 'failed' in str_rep:
                    print(
                        "Your password didn't match the config file ... Try another password or quit [q]"
                    )
                    if init_pass != '':
                        print('Wrong password for config file ' + newest_file)
                        exit()
                    continue
                else:
                    decr_str = str_rep.split(iop.lorem_ipsum())
                    if len(decr_str) < 2:
                        print(
                            "Your password didn't match the config file ... Try another password or quit [q]"
                        )
                        if init_pass != '':
                            print('Wrong password for config file ' +
                                  newest_file)
                            exit()
                        continue

                    decr_str = decr_str[1]
                    try_decr = False
                    pswd = pp
            except:
                err_track = traceback.format_exc()
                print(err_track)
                if init_pass != '':
                    print('Wrong password for config file ' + newest_file)
                    exit()

                print(
                    "Your password didn't match the config file ... Try another password or quit [q]"
                )
                init_pass = ''

        if try_decr == False:
            json_conf = json.loads(json.dumps(DEAMON_DEFAULTS))
            json_conf_tmp = json.loads(decr_str)
            for jct, vv in json_conf_tmp.items():
                # print(jct,jct in hidden_par)

                if jct in json_conf:  # and jct not in ["consumer_key",	"consumer_secret"]:
                    json_conf[jct] = vv
                    if jct in musthave:
                        musthave.remove(jct)

            if len(musthave) > 0:
                print('Elements missing in config file ', str(musthave))
                exit()
    else:

        pp = iop.ask_password()
        pswd = pp

        json_obj = json.loads(json.dumps(DEAMON_DEFAULTS))
        print('\nCreating new generic config ... ')

        if selected_mode == 'deamon':

            outuids = []
            inuids = []
            for kk in set_name:  #json_obj.keys():

                if "encryption_type" in kk:
                    json_obj[kk] = iop.optional_input('> Enter ' + str(kk) +
                                                      ' : ', ['aes256', 'pgp'],
                                                      soft_quite=False)
                    if json_obj[kk] == 'pgp':
                        musthave.append("gpg_password")
                        if "outgoing" in kk:
                            outuids = iop.gpg_uids(False, True)
                        else:
                            inuids = iop.gpg_uids(True, True)

                elif kk == "outgoing_encryption_key" and json_obj[
                        "outgoing_encryption_type"] == 'pgp':
                    json_obj[kk] = iop.optional_input('> Enter ' + str(kk) +
                                                      ' : ',
                                                      outuids,
                                                      soft_quite=False)
                elif kk == "incoming_encryption_key" and json_obj[
                        "incoming_encryption_type"] == 'pgp':
                    json_obj[kk] = iop.optional_input('> Enter ' + str(kk) +
                                                      ' : ',
                                                      inuids,
                                                      soft_quite=False)
                # check must have fields are not empty !!!
                elif kk in musthave:
                    strtmp = ''

                    while strtmp == '':
                        strtmp = iop.input_prompt('> Enter ' + str(kk) + ' : ',
                                                  True, True)
                        if strtmp == '':
                            print('This value cannot be empty - try again...')
                        elif kk == "tx_amount_limit" and not iop.is_float(
                                strtmp):
                            print('This value must be numeric - try again...')
                        elif kk == "tx_time_limit_hours" and not iop.is_int(
                                strtmp):
                            print('This value must be integer - try again...')

                        else:
                            json_obj[kk] = strtmp
                else:
                    json_obj[kk] = iop.input_prompt(
                        '> Enter value for ' + str(kk) +
                        ' or hit enter for empty: ', True, True)

            print('Creating done, accepted values:\n' + str(json_obj))

        newest_file = list(filed.keys())
        newest_file = newest_file[0]

        json_conf = json.dumps(json_obj)
        iop.saving_encr_cred(json_conf, newest_file, pswd)

        # encr_str=iop.lorem_ipsum()
        # iop.createtmpfile(encr_str)

    return json_conf, pswd
コード例 #6
0
def edit_app_settings(json_conf, pswd):

    set_name = [
        'email_addr', "email_password", "imap_addr", "smtp_addr",
        "tx_amount_limit", "tx_time_limit_hours", "outgoing_encryption_type",
        "outgoing_encryption_key", "incoming_encryption_type",
        "incoming_encryption_key", "incoming_mail_sender_email",
        "incoming_mail_title", "wallet_secret_key", "gpg_password",
        "incoming_tx_notification", "staking_summary_notification",
        "wallet_encryption", "active_consolidation_address"
    ]

    set_name_alia = alias_mapping(set_name)

    newest_date, newest_file, filed = iop.get_config_file()

    toedit = ''

    while True:
        print_current_settings(set_name, json_conf, set_name_alia)

        toedit = iop.optional_input(
            'Enter alias to edit value or quite [q] or quite and save [S]: ',
            options_list=list(set_name_alia.values()) + ['S'],
            soft_quite=True)
        if toedit == 'S':
            iop.saving_encr_cred(json.dumps(json_conf), newest_file, pswd)
            print(
                'App settings changed - exiting. Please start the app again.')
            exit()
        elif toedit in ['q', '']:
            print('\n! Exit editing without saving, current setup:')
            print_current_settings(set_name, json_conf, set_name_alia)
            break

        nameii = [
            key for (key, value) in set_name_alia.items() if value == toedit
        ]
        print('Editing ' + nameii[0] + ', current value = ' +
              json_conf[nameii[0]])
        newvv = ''
        if "encryption_type" in nameii[0]:
            newvv = iop.optional_input('Enter new value [aes256/pgp]: ',
                                       options_list=['aes256', 'pgp'],
                                       soft_quite=True)

        elif nameii[0] in [
                "incoming_tx_notification", "staking_summary_notification"
        ]:
            # "incoming_tx_notification","staking_summary_notification"
            newvv = iop.optional_input('Select status for [' + nameii[0] +
                                       '] or quit [q]: ',
                                       options_list=['on', 'off'],
                                       soft_quite=True)
        elif nameii[0] == "wallet_encryption":
            newvv = iop.input_prompt(
                'Enter wallet encryption password (min. length 16, max. 32): ',
                confirm=True,
                soft_quite=True)
            while (len(newvv) < 16 or '"' in newvv
                   or "'" in newvv) and newvv.lower() not in ['q', '']:
                if len(newvv) < 16:
                    print('Password [' + newvv + '] length is ' +
                          str(len(newvv)) + ' < 16, try again or quit...')
                else:
                    print(
                        'Password [' + newvv +
                        '] contains forbidden character [",\'], try again or quit...'
                    )

                newvv = iop.input_prompt(
                    'Enter wallet encryption password (min. length 16, max. 32): ',
                    confirm=True,
                    soft_quite=True)

            if newvv.lower() in ['q', '']:
                newvv = ''

        else:
            newvv = iop.input_prompt('Enter new value (enter for empty): ',
                                     confirm=True,
                                     soft_quite=True)

            while nameii[0] in [
                    "outgoing_encryption_key", "incoming_encryption_key",
                    "gpg_password"
            ] and ('"' in newvv or "'" in newvv):
                print(
                    'Password  or key [' + newvv +
                    '] contains forbidden character [",\'], try again or quit...'
                )
                newvv = iop.input_prompt('Enter new value (enter for empty): ',
                                         confirm=True,
                                         soft_quite=True)

        json_conf[nameii[0]] = newvv