utils.py 4.89 KB
Newer Older
putro's avatar
putro committed
1 2 3 4 5 6 7 8 9
import os
import sys
import re
import getpass


class InputError(Exception):
    pass

putro's avatar
putro committed
10

11
def download(file, config):
putro's avatar
putro committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    """ Download remailer stats file """
    print "downloading %s....... please wait" % file
    from urllib2 import Request, urlopen, URLError, HTTPError
    url = config['stats']['stats_url'] + file
    req = Request(url)
    try:
        response = urlopen(req)
    except HTTPError, e:
        print 'Error - The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
        pressKey()
    except URLError, e:
        print 'Error - We failed to reach a server.'
        print 'Reason: ', e.reason
        pressKey()
    else:
        the_page = response.read()
        w = open(os.path.dirname(sys.argv[0]) + "/" + file, "w")
        w.write(the_page)
        w.close()
        pass


def pressKey():
    """ wait user to press RETURN """
    raw_input("press RETURN to continue\n")

putro's avatar
putro committed
39

putro's avatar
putro committed
40 41 42 43 44 45 46
def validateEmail(email):
    """ check if the recipient is a valid email address"""
    if re.match(r'[\w\-][\w\-\.]*@[\w\-][\w\-\.]+[a-zA-Z]{1,4}', email):
        return True
    else:
        return False

putro's avatar
putro committed
47

putro's avatar
putro committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
def validateChoice(choice, list):
    try:
        i = (int(choice))
    except ValueError:
        print "Invalid input, enter a number...."
        return False
    if i < 1:
        print "enter a number greater than 1...."
        return False
    if i > len(list):
        print "error, there are only %s choices" % len(list)
        return False
    else:
        return True


def askPassphrase():
    """ Ask passphrase for nym secret key if not set in config"""
    pwd = getpass.getpass("insert passphrase for nym secret key: ")
    return pwd

putro's avatar
putro committed
69

putro's avatar
putro committed
70 71 72 73
def askSomething(question):
    usr_input = raw_input(question)
    return usr_input

putro's avatar
putro committed
74

putro's avatar
putro committed
75 76 77 78 79 80 81 82 83 84 85 86
def askYesNo(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is one of "yes" or "no".
    """
    valid = {"yes":True,   "y":True,  "ye":True,
             "no":False,     "n":False}
putro's avatar
putro committed
87
    if default is None:
putro's avatar
putro committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
putro's avatar
putro committed
104
            sys.stdout.write("Please respond with 'yes' or 'no' "
putro's avatar
putro committed
105 106
                             "(or 'y' or 'n').\n")

putro's avatar
putro committed
107

putro's avatar
putro committed
108 109 110 111 112 113
def printList(list):
    counter = 1
    for i in list:
        print counter, "-", i
        counter += 1

putro's avatar
putro committed
114

putro's avatar
putro committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128
def chooseList(list):
    printList(list)
    usr_input = ''
    while usr_input not in range(1, len(list) + 1):
        try:
            usr_input = input("Enter your choice (1-%s): " % len(list))
        except:
            print "\nError - you have to enter a number !!!!"
    return list[usr_input - 1]


def selectServer(config):
    servers = config['options']['nymservers']
    for idx, val in enumerate(servers):
putro's avatar
putro committed
129
        print idx + 1, val
putro's avatar
putro committed
130 131 132 133 134 135 136 137 138 139 140 141 142

    while True:
        choice = raw_input("Enter the nymserver you want to use: ")
        if validateChoice(choice, servers):
            break

    server = servers[int(choice) - 1]
    return server


def chooseSubjType(config):
    subject_types = config['options']['subj_types']
    for idx, val in enumerate(subject_types):
putro's avatar
putro committed
143
        print idx + 1, "-", val
putro's avatar
putro committed
144 145 146 147 148 149 150 151 152

    while True:
        choice = raw_input("Enter what kind of subject you want: ")
        if validateChoice(choice, subject_types):
            break

    subj_type = subject_types[int(choice) - 1]
    return subj_type

putro's avatar
putro committed
153

putro's avatar
putro committed
154 155 156 157
def getDomain(email):
    domain = email.split("@")[1]
    return domain

putro's avatar
putro committed
158

putro's avatar
putro committed
159 160 161 162 163 164 165 166 167
def isGpg(message):
    m = re.compile('^-----BEGIN PGP MESSAGE-----')
    line = message.split("\n", 1)[0]
    print line
    pressKey()
    if m.match(line):
        return True
    else:
        return False
168

putro's avatar
putro committed
169

170 171
def isAscii(text):
    return all(ord(c) < 128 for c in text)
172

putro's avatar
putro committed
173

174
def editMessage():
putro's avatar
putro committed
175
    import tempfile, os
176 177
    from subprocess import call

putro's avatar
putro committed
178
    EDITOR = os.environ.get('EDITOR', 'vim')
179

putro's avatar
putro committed
180
    initial_message = ""   # if you want to set up the file somehow
181 182 183 184 185 186 187

    with tempfile.NamedTemporaryFile(suffix=".tmp") as tempfile:
        tempfile.write(initial_message)
        tempfile.flush()
        call([EDITOR, tempfile.name])

        f = open(tempfile.name, "r")
putro's avatar
putro committed
188
        data = f.read()
189 190 191 192 193 194 195 196 197 198
        f.close()

    return data


def X_is_running():
    from subprocess import Popen, PIPE
    p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
    p.communicate()
    return p.returncode == 0