<commit_before>#!/usr/bin/python

import argparse
import getpass
import logging
import re
import requests
import sys
import urllib

try:
    import configparser
except ImportError:
    # Python 2
    import ConfigParser as configparser


def get_wan_ip(wan_ip_url):
    return requests.get(wan_ip_url).content.rstrip()


class Client(object):
    PROTECTED_HOSTNAMES = ['ftp', 'headers', 'localhost', 'mail', 'pop',
                           'smtp', 'www', 'www.headers']

    def __init__(self, host, wan_ip_url=None, verify_ssl=True, verbose=False):
        self.host = re.sub('/$', '', host)
        self.log = logging.getLogger()
        self.verify_ssl = verify_ssl
        self.verbose = verbose
        self.timeout = 2

        self.session = requests.session()
        self.authenticated = False

        if self.verbose:
            try:
                import http.client as http_client
            except ImportError:
                # Python 2
                import httplib as http_client
            http_client.HTTPConnection.debuglevel = 1
            logging.basicConfig()
            logging.getLogger().setLevel(logging.DEBUG)
            requests_log = logging.getLogger("requests.packages.urllib3")
            requests_log.setLevel(logging.DEBUG)
            requests_log.propagate = True

    def __request(self, request_type, command, data={}, args={}):
        url = self.__make_cmd_url(command, args)
        request = getattr(self.session, request_type)
        response = request(url, data=data, timeout=self.timeout,
                           verify=self.verify_ssl, allow_redirects=False)
        return response

    def __post(self, command, data={}, args={}):
        return self.__request('post', command, data, args)

    def __get(self, command, data={}, args={}):
        return self.__request('get', command, data, args)

    def __make_cmd_url(self, command, args=None):
        if args:
            return '{}/{}?{}'.format(self.host, command,
                                     urllib.urlencode(args))
        return '{}/{}'.format(self.host, command)

    def authenticate(self, username, password):
        login_data = {'referer': '/',
                      'username': username,
                      'password': password}
        response = self.__post('CMD_LOGIN', data=login_data)

        if ('X-DirectAdmin' in response.headers
                and response.headers['X-DirectAdmin'] == 'unauthorized'):
            raise RuntimeError('Invalid credentials (authentication failed).')
        self.authenticated = True

    def get_current_ip(self, domain, name):
        assert self.authenticated, 'Not authenticated'
        record = self.get_current_record(domain, name) or [None]
        return record[-1]

    def get_current_record(self, domain, name):
        assert self.authenticated, 'Not authenticated'
        response = self.__get('CMD_API_DNS_CONTROL', args={'domain': domain})
        assert response.status_code == 200, \
            'Invalid HTTP status code {}'.response.status_code

        current_records = re.findall('^{}.*$'.format(name),
                                     response.content,
                                     re.MULTILINE)
        if not len(current_records):
            return None

        current_record = re.sub('[\s]+', ' ', current_records[0]).split(' ')
        return current_record

    def delete_record(self, domain, name, addr):
        assert self.authenticated, 'Not authenticated'
        assert name not in self.PROTECTED_HOSTNAMES, \
            'Cannot change protected host name {}'.format(name)
        response = self.__get('CMD_API_DNS_CONTROL',
                              args={'domain': domain,
                                    'action': 'select',
                                    'arecs0': ('name={}&value={}'
                                               .format(name, addr))})
        response = self.session.get(delete_record_url,
                                    allow_redirects=False)
        assert response.status_code == 200, \
            'Invalid HTTP status code {}'.response.status_code

    def add_record(self, domain, name, addr):
        assert self.authenticated, 'Not authenticated'
        assert name not in self.PROTECTED_HOSTNAMES, \
            'Cannot change protected host name {}'.format(name)
        old_addr = self.get_current_ip(domain, name)
        if old_addr:
            self.delete_record(domain, name, old_addr)
        add_record_url = ('{}/CMD_API_DNS_CONTROL?domain={}&'
                          'action=add&type=A&name={}&value={}'
                          .format(self.host, domain, name, addr))
        response = self.session.get(add_record_url,
                                    allow_redirects=False)
        assert response.status_code == 200, \
            'Invalid HTTP status code {}'.response.status_code
        self.log.info('Record updated ({}.{} now points to {}'
                      .format(domain, name, addr))


def __parser():
    parser = argparse.ArgumentParser(
        prog='dadns', add_help=False,
        description=('Update a DDNS record on a DirectAdmin hosted domain'))
    parser.add_argument('--help',
                        action='help', default=argparse.SUPPRESS,
                        help='show this help message and exit')
    group1 = parser.add_argument_group(title='File-based configuration')<commit_msg>Fix issue 1<commit_after>#!/usr/bin/python

import argparse
import getpass
import logging
import re
import requests
import sys
import urllib

try:
    import configparser
except ImportError:
    # Python 2
    import ConfigParser as configparser


def get_wan_ip(wan_ip_url):
    return requests.get(wan_ip_url).content.rstrip()


class Client(object):
    PROTECTED_HOSTNAMES = ['ftp', 'headers', 'localhost', 'mail', 'pop',
                           'smtp', 'www', 'www.headers']

    def __init__(self, host, wan_ip_url=None, verify_ssl=True, verbose=False):
        self.host = re.sub('/$', '', host)
        self.log = logging.getLogger()
        self.verify_ssl = verify_ssl
        self.verbose = verbose
        self.timeout = 2

        self.session = requests.session()
        self.authenticated = False

        if self.verbose:
            try:
                import http.client as http_client
            except ImportError:
                # Python 2
                import httplib as http_client
            http_client.HTTPConnection.debuglevel = 1
            logging.basicConfig()
            logging.getLogger().setLevel(logging.DEBUG)
            requests_log = logging.getLogger("requests.packages.urllib3")
            requests_log.setLevel(logging.DEBUG)
            requests_log.propagate = True

    def __request(self, request_type, command, data={}, args={}):
        url = self.__make_cmd_url(command, args)
        request = getattr(self.session, request_type)
        response = request(url, data=data, timeout=self.timeout,
                           verify=self.verify_ssl, allow_redirects=False)
        return response

    def __post(self, command, data={}, args={}):
        return self.__request('post', command, data, args)

    def __get(self, command, data={}, args={}):
        return self.__request('get', command, data, args)

    def __make_cmd_url(self, command, args=None):
        if args:
            return '{}/{}?{}'.format(self.host, command,
                                     urllib.urlencode(args))
        return '{}/{}'.format(self.host, command)

    def authenticate(self, username, password):
        login_data = {'referer': '/',
                      'username': username,
                      'password': password}
        response = self.__post('CMD_LOGIN', data=login_data)

        if ('X-DirectAdmin' in response.headers
                and response.headers['X-DirectAdmin'] == 'unauthorized'):
            raise RuntimeError('Invalid credentials (authentication failed).')
        self.authenticated = True

    def get_current_ip(self, domain, name):
        assert self.authenticated, 'Not authenticated'
        record = self.get_current_record(domain, name) or [None]
        return record[-1]

    def get_current_record(self, domain, name):
        assert self.authenticated, 'Not authenticated'
        response = self.__get('CMD_API_DNS_CONTROL', args={'domain': domain})
        assert response.status_code == 200, \
            'Invalid HTTP status code {}'.response.status_code

        current_records = re.findall('^{}.*$'.format(name),
                                     response.content,
                                     re.MULTILINE)
        if not len(current_records):
            return None

        current_record = re.sub('[\s]+', ' ', current_records[0]).split(' ')
        return current_record

    def delete_record(self, domain, name):
        assert self.authenticated, 'Not authenticated'
        assert name not in self.PROTECTED_HOSTNAMES, \
            'Cannot change protected host name {}'.format(name)
        response = self.__get('CMD_API_DNS_CONTROL',
                              args={'domain': domain,
                                    'action': 'select',
                                    'arecs0': ('name={}'
                                               .format(name))})
        delete_record_url = ('{}/CMD_API_DNS_CONTROL?domain={}&'
                          'action=delete&type=A&name={}'
                          .format(self.host, domain, name))
	response = self.session.get(delete_record_url,
                                    allow_redirects=False)
        assert response.status_code == 200, \
            'Invalid HTTP status code {}'.response.status_code

    def add_record(self, domain, name, addr):
        assert self.authenticated, 'Not authenticated'
        assert name not in self.PROTECTED_HOSTNAMES, \
            'Cannot change protected host name {}'.format(name)
        old_addr = self.get_current_ip(domain, name)
        if old_addr:
            self.delete_record(domain, name)
        add_record_url = ('{}/CMD_API_DNS_CONTROL?domain={}&'
                          'action=add&type=A&name={}&value={}'
                          .format(self.host, domain, name, addr))
        response = self.session.get(add_record_url,
                                    allow_redirects=False)
        assert response.status_code == 200, \
            'Invalid HTTP status code {}'.response.status_code
        self.log.info('Record updated ({}.{} now points to {}'
                      .format(domain, name, addr))


def __parser():
    parser = argparse.ArgumentParser(
        prog='dadns', add_help=False,
        description=('Update a DDNS record on a DirectAdmin hosted domain'))
    parser.add_argument('--help',
                        action='help', default=argparse.SUPPRESS,
                        help='show this help message and exit')
    group1 = parser.add_argument_group(title='File-based configuration')
{'fraction_non_alphanumeric': 0.11302054919076196, 'fraction_numerical': 0.0033642480450991087, 'mean_word_length': 2.0612301697745616, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6901215', 'n_tokens_mistral': 3030, 'n_tokens_neox': 2894, 'n_words': 682}