<commit_before># This file is part of kytos-utils.
#
# Copyright (c) 2016 Kytos Team
#
# Authors:
#    <NAME> <<EMAIL>aldo AT ncc DOT unesp DOT br>
#
# kytos-utils is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# kytos-utils is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

from configparser import ConfigParser, NoOptionError
from datetime import datetime, timedelta
import os
import sys

class KytosConfig():
    def __init__(self):
        self.config_file = "~/.kytosrc"
        self.debug = False
        self.napps_uri = os.environ.get('NAPPS_API_URI')
        self.user = os.environ.get('NAPPS_USER')
        self.password = os.environ.get('NAPPS_PASSWORD')
        self.token = os.environ.get('NAPPS_TOKEN')

        self.config = ConfigParser()

        self.parse()

    def parse(self):
        try:
            self.config.readfp(open(os.path.expanduser(self.config_file)))
        except IOError as e:
            print("Config file not found.")
            print("Creating new config file.")
            print("For more information please run:")
            print(" $ kytos-napps --help")
            self.create()
            self.save_user(self.user)
            self.save_napps_uri(self.napps_uri)
            self.save_token(self.token)

        self.load_global()
        self.load_auth()

    def load_global(self):
        # Try to read global section
        try:
            self.debug = self.config.getboolean("global", "debug")
        except NoOptionError:
            pass

        try:
            self.napps_uri = self.config.get("global", "napps_uri")
        except NoOptionError:
            pass

    def load_auth(self):
        self.load_user()
        self.load_token()

    def load_user(self):
        try:
            self.user = self.config.get("auth", "user")
        except NoOptionError:
            pass

    def load_token(self):
        try:
            self.token = {'hash': self.config.get("token", "hash"),
                          'created_at': self.config.get("token", "created_at"),
                          'expiration_time': self.config.get("token",
                                                             "expiration_time")
            }
        except NoOptionError:
            pass

    def save_napps_uri(self, napps_uri):
        self.napps_uri = napps_uri
        if self.napps_uri:
           self.config.set("global", "napps_uri", napps_uri)
           self.save()

    def save_user(self, user):
        self.user = user
        if self.user:
            self.config.set("auth", "user", user)
            self.save()

    def token_expired(self):
        if self.token is None:
            return True
        now = datetime.now()
        date = datetime.now()
        date = date.strptime(self.token.get('created_at'),
                                            '%a, %d %b %Y %H:%M:%S GMT')
        time = timedelta(seconds=int(self.token.get('expiration_time')))

        return date + time <= now

    def save_token(self, token):
        self.token = token
        if self.token:
            self.config.set("token", "hash", token.get('hash'))
            self.config.set("token", "created_at", token.get('created_at'))
            self.config.set("token", "expiration_time",
                             str(token.get('expiration_time')))
            self.save()<commit_msg>Fixing some bugs with config sections<commit_after># This file is part of kytos-utils.
#
# Copyright (c) 2016 Kytos Team
#
# Authors:
#    <NAME> <beraldo AT ncc DOT unesp DOT br>
#
# kytos-utils is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# kytos-utils is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

from configparser import ConfigParser, NoOptionError, NoSectionError
from datetime import datetime, timedelta
import os
import sys

class KytosConfig():
    def __init__(self):
        self.config_file = "~/.kytosrc"
        self.debug = False
        self.napps_uri = os.environ.get('NAPPS_API_URI')
        self.user = os.environ.get('NAPPS_USER')
        self.password = os.environ.get('NAPPS_PASSWORD')
        self.token = os.environ.get('NAPPS_TOKEN')

        self.config = ConfigParser()

        self.parse()

    def parse(self):
        try:
            self.config.readfp(open(os.path.expanduser(self.config_file)))
        except IOError as e:
            print("Config file not found.")
            print("Creating new config file.")
            print("For more information please run:")
            print(" $ kytos-napps --help")
            self.create()
            self.save_user(self.user)
            self.save_napps_uri(self.napps_uri)
            self.save_token(self.token)

        self.load_global()
        self.load_auth()

    def load_global(self):
        # Try to read global section
        try:
            self.debug = self.config.getboolean("global", "debug")
        except NoOptionError:
            pass

        try:
            self.napps_uri = self.config.get("global", "napps_uri")
        except NoOptionError:
            pass

    def load_auth(self):
        self.load_user()
        self.load_token()

    def load_user(self):
        try:
            self.user = self.config.get("auth", "user")
        except NoOptionError:
            pass

    def load_token(self):
        try:
            self.token = {'hash': self.config.get("token", "hash"),
                          'created_at': self.config.get("token", "created_at"),
                          'expiration_time': self.config.get("token",
                                                             "expiration_time")
            }
        except NoSectionError:
            self.config.add_section('token')
        except NoOptionError:
            pass

    def save_napps_uri(self, napps_uri):
        self.napps_uri = napps_uri
        if self.napps_uri:
           self.config.set("global", "napps_uri", napps_uri)
           self.save()

    def save_user(self, user):
        self.user = user
        if self.user:
            self.config.set("auth", "user", user)
            self.save()

    def token_expired(self):
        if self.token is None:
            return True
        now = datetime.now()
        date = datetime.now()
        date = date.strptime(self.token.get('created_at'),
                                            '%a, %d %b %Y %H:%M:%S GMT')
        time = timedelta(seconds=int(self.token.get('expiration_time')))

        return date + time <= now

    def save_token(self, token):
        self.token = token
        if self.token:
            if not self.config.has_section('token'):
                self.config.add_section('token')
            self.config.set("token", "hash", token.get('hash'))
            self.config.set("token", "created_at", token.get('created_at'))
            self.config.set("token", "expiration_time",
                             str(token.get('expiration_time')))
            self.save()
{'fraction_non_alphanumeric': 0.11019944458470084, 'fraction_numerical': 0.0012623074981065387, 'mean_word_length': 2.0034116755117513, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4006506', 'n_tokens_mistral': 2293, 'n_tokens_neox': 2235, 'n_words': 602}