~sircmpwn/names.sr.ht

ref: 4befa4e5942b52045dc9ef9bcd3473389db71d61 names.sr.ht/names/opensrs.py -rw-r--r-- 5.6 KiB
4befa4e5Drew DeVault Add tables for remaining TLDs with special reqs 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# Based on https://github.com/fatbox/OpenSRS-py
from collections import namedtuple
import enum
import hashlib
import requests
from srht.config import cfg
from xml.etree.ElementTree import fromstring, tostring, SubElement, Element

_OPENSRS_XML_HEADER = "<?xml version='1.0' encoding='UTF-8' standalone='no' ?><!DOCTYPE OPS_envelope SYSTEM 'ops.dtd'>"
_OPENSRS_VERSION = '0.9'

_opensrs_key = cfg("names.sr.ht", "opensrs-key")
_opensrs_username = cfg("names.sr.ht", "opensrs-username")
_opensrs_upstream = cfg("names.sr.ht", "opensrs-upstream")

def _xml_to_data(elm, is_list=False):
    """
    This converts an element that has a bunch of 'item' tags
    as children into a Python data structure.
    If is_list is true it is assumed that the child items all
    have numeric indices and should be treated as a list, else
    they are treated as a dict
    """
    if is_list:
        data = []
    else:
        data = {}

    for child in elm:
        if child.tag == 'item':
            if len(child) > 0:
                if child[0].tag == 'dt_assoc':
                    new_data = _xml_to_data(child[0])
                elif child[0].tag == 'dt_array':
                    new_data = _xml_to_data(child[0], is_list=True)
            else:
                new_data = str(child.text)

            key = child.get('key')
            if is_list:
                data.insert(int(key), new_data)
            else:
                data[key] = new_data

    return data

def _data_to_xml(elm, key, data):
    """
    data_to_xml adds a item sub element to elm and then sets the
    text if its not a list or dict, otherwise it recurses
    """
    item = SubElement(elm, 'item', { 'key': key })
    if isinstance(data, dict):
        _data_to_dt_assoc(item, data)
    elif isinstance(data, list):
        _data_to_dt_array(item, data)
    else:
        item.text = str(data)
    return item

def _data_to_dt_array(elm, list):
    """
    Adds an list of data in the format that opensrs requires,
    uses data_to_xml to recurse
    """
    _dt_array = SubElement(elm, 'dt_array')
    key = 0
    for ent in list:
        _data_to_xml(_dt_array, str(key), ent)
        key += 1

def _data_to_dt_assoc(elm, data):
    """
    Adds an associative array of data in the format that opensrs
    requires, uses data_to_xml to recurse
    """
    _dt_assoc = SubElement(elm, 'dt_assoc')
    for key in data.keys():
        _data_to_xml(_dt_assoc, key, data[key])

def _post(action, obj, attrs, extra_items=None):
    env = Element("OPS_envelope")

    header = SubElement(env, 'header')
    version = SubElement(header, 'version')
    version.text = _OPENSRS_VERSION

    body = SubElement(env, 'body')
    data_block = SubElement(body, 'data_block')

    params = {
        'protocol': 'XCP',
        'action': action,
        'object': obj,
        'attributes': attrs,
    }

    if isinstance(extra_items, dict):
        params.update(extra_items)

    _data_to_dt_assoc(data_block, params)
    data = f"{_OPENSRS_XML_HEADER}{tostring(env)}"

    # wut
    checksum = hashlib.md5((data + _opensrs_key).encode()).hexdigest()
    checksum = hashlib.md5((checksum + _opensrs_key).encode()).hexdigest()

    r = requests.post(_opensrs_upstream, data=data.encode(), headers={
        'Content-Type': 'text/xml',
        'X-Username': _opensrs_username,
        'X-Signature': checksum,
    })

    if r.status_code != 200:
        raise Exception(f"Unexpected response from OpenSRS\n{r.text}")

    dom = fromstring(r.text)
    data_block = dom.find('body/data_block/dt_assoc')
    if data_block is None:
        raise Exception("Unexpected response from OpenSRS\n{r.text}")

    print(r.text)
    return _xml_to_data(data_block)

class DomainStatus(enum.Enum):
    available = 210
    taken = 211

def lookup_domain(domain):
    """
    Returns True if this domain is available.
    """
    # TODO: Deal with premium domains
    r = _post("lookup", "domain", attrs={
        "domain": domain,
    })
    print(r)
    return DomainStatus(int(r["response_code"]))

PricingInfo = namedtuple('PricingInfo', ['cents'])

class RegistrationType(enum.Enum):
    new = "new"
    renewal = "renewal"
    transfer = "trade"

def get_price(domain, reg_type=RegistrationType.new):
    """
    Returns price for this domain in cents.
    """
    # TODO: Should we support the period parameter?
    r = _post("get_price", "domain", attrs={
        "domain": domain,
        "reg_type": reg_type.value,
    })
    print(r)
    return int(float(r["attributes"]["price"]) * 100)

def check_transfer(domain):
    """
    Checks if this domain can be transferred into OpenSRS. Returns a tuple
    of the transferability (bool) and the email address the transfer request
    must be acknowledged at.
    """
    r = _post("check_transfer", "domain attributes", attrs={
        "domain": domain,
        "get_request_address": "1",
    })
    print(r)
    return (r["attributes"]["transferrable"] == '1',
            r["attributes"].get("request_address"))

Suggestion = namedtuple("Suggestion", ["domain", "status"])

def name_suggest(search_string, maximum=20):
    """
    """
    # TODO: Ask OpenSRS to add suggestions for more gTLDs
    r = _post("name_suggest", "domain", attrs={
        "lookup": search_string,
        "maximum": str(maximum),
        "searchstring": search_string,
        "services": ["lookup", "suggestion"],
        "tlds": [".COM", ".NET", ".ORG", ".INFO"],
    })
    print(r)
    to_suggestion = lambda i: Suggestion(i["domain"],
            DomainStatus.available if i["status"] == "available"
            else DomainStatus.taken)
    return [to_suggestion(i) for i in r["attributes"]["lookup"]["items"]]