<commit_before># -*- coding: utf-8 -*-

# Copyright(C) 2010  <NAME>
#
# This program 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, version 3 of the License.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from __future__ import with_statement

from datetime import datetime
from dateutil import tz
from logging import warning, debug

from weboob.capabilities.chat import ICapChat
from weboob.capabilities.messages import ICapMessages, ICapMessagesPost, Message, Thread
from weboob.capabilities.dating import ICapDating, StatusField
from weboob.capabilities.contact import ICapContact, Contact, ProfileNode
from weboob.tools.backend import BaseBackend
from weboob.tools.browser import BrowserUnavailable

from .captcha import CaptchaError
from .browser import AuMBrowser
from .exceptions import AdopteWait
from .optim.profiles_walker import ProfilesWalker
from .optim.visibility import Visibility


__all__ = ['AuMBackend']


class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapChat, ICapContact):
    NAME = 'aum'
    MAINTAINER = '<NAME>'
    EMAIL = '<EMAIL>'
    VERSION = '0.2'
    LICENSE = 'GPLv3'
    DESCRIPTION = u"“Adopte un mec” french dating website"
    CONFIG = {'username':      BaseBackend.ConfigField(description='Username on website'),
              'password':      BaseBackend.ConfigField(description='Password of account', is_masked=True),
              'register':      BaseBackend.ConfigField(default=False, description='Register as new account?'),
             }
    STORAGE = {'profiles_walker': {'viewed': []},
               'sluts': {},
              }
    BROWSER = AuMBrowser

    MAGIC_ID_BASKET = 1

    def create_default_browser(self):
        if self.config['register']:
            browser = None
            while not browser:
                try:
                    browser = self.create_browser(self.config['username'])
                    browser.register(password=   self.config['password'],
                                     sex=        0,
                                     birthday_d= 1,
                                     birthday_m= 1,
                                     birthday_y= 1970,
                                     zipcode=    75001,
                                     country=    'fr',
                                     godfather=  '')
                except CaptchaError:
                    debug('Unable to resolve captcha. Retrying...')
                    browser = None
            browser.password = self.config['password']
            return browser
        else:
            return self.create_browser(self.config['username'], self.config['password'])

    def get_status(self):
        with self.browser:
            try:
                return (
                        StatusField('myname', 'My name', self.browser.get_my_name()),
                        StatusField('score', 'Score', self.browser.score()),
                        StatusField('avcharms', 'Available charms', self.browser.nb_available_charms()),
                       )
            except AdopteWait:
                return (StatusField('notice', '', u'<h3>You are currently waiting 1am to be able to connect with this account</h3>', StatusField.FIELD_HTML|StatusField.FIELD_TEXT))

    def iter_threads(self):
        with self.browser:
            contacts = self.browser.get_threads_list()

        for contact in contacts:
            if not contact.get_id():
                continue
            thread = Thread(contact.get_id())
            thread.title = 'Discussion with %s' % contact.get_name()
            yield thread

    def get_thread(self, id, profiles=None):
        """
        Get a thread and its messages.

        The 'profiles' parameter is only used for internal calls.
        """
        thread = None
        if isinstance(id, Thread):
            thread = id
            id = thread.id

        if not thread:
            thread = Thread(id)
            full = False
        else:
            full = True

        with self.browser:
            mails = self.browser.get_thread_mails(id, full)
            my_name = self.browser.get_my_name()

        child = None
        msg = None
        slut = self._get_slut(id)
        if not profiles:
            profiles = {}
        for mail in mails:
            flags = 0
            if mail.date > slut['lastmsg']:
                flags |= Message.IS_UNREAD

                if not mail.profile_link in profiles:
                    with self.browser:
                        profiles[mail.profile_link] = self.browser.get_profile(mail.profile_link)
                mail.signature += u'\n%s' % profiles[mail.profile_link].get_profile_text()

            if mail.sender == my_name:
                if mail.new:
                    flags |= Message.IS_NOT_ACCUSED
                else:
                    flags |= Message.IS_ACCUSED

            if not thread.title:
                thread.title = mail.title

            msg = Message(thread=thread,
                          id=mail.message_id,
                          title=mail.title,
                          sender=mail.sender,
                          receiver=mail.name if mail.sender == my_name else my_name, # TODO: me
                          date=mail.date,
                          content=mail.content,
                          signature=mail.signature,
                          children=[],
                          flags=flags)
            if child:
                msg.children.append(child)
                child.parent = msg

            child = msg

        if full:
            # If we have get all the messages, replace NotLoaded with None as
            # parent.
            msg.parent = None
        thread.root = msg

        return thread

    def iter_unread_messages(self, thread=None):
        try:
            profiles = {}
            with self.browser:
                contacts = self.browser.get_threads_list()
            for contact in contacts:<commit_msg>set root message as NotLoaded if there are no messages and it's not a full request<commit_after># -*- coding: utf-8 -*-

# Copyright(C) 2010  <NAME>
#
# This program 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, version 3 of the License.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from __future__ import with_statement

from datetime import datetime
from dateutil import tz
from logging import warning, debug

from weboob.capabilities.base import NotLoaded
from weboob.capabilities.chat import ICapChat
from weboob.capabilities.messages import ICapMessages, ICapMessagesPost, Message, Thread
from weboob.capabilities.dating import ICapDating, StatusField
from weboob.capabilities.contact import ICapContact, Contact, ProfileNode
from weboob.tools.backend import BaseBackend
from weboob.tools.browser import BrowserUnavailable

from .captcha import CaptchaError
from .browser import AuMBrowser
from .exceptions import AdopteWait
from .optim.profiles_walker import ProfilesWalker
from .optim.visibility import Visibility


__all__ = ['AuMBackend']


class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapChat, ICapContact):
    NAME = 'aum'
    MAINTAINER = '<NAME>'
    EMAIL = '<EMAIL>'
    VERSION = '0.2'
    LICENSE = 'GPLv3'
    DESCRIPTION = u"“Adopte un mec” french dating website"
    CONFIG = {'username':      BaseBackend.ConfigField(description='Username on website'),
              'password':      BaseBackend.ConfigField(description='Password of account', is_masked=True),
              'register':      BaseBackend.ConfigField(default=False, description='Register as new account?'),
             }
    STORAGE = {'profiles_walker': {'viewed': []},
               'sluts': {},
              }
    BROWSER = AuMBrowser

    MAGIC_ID_BASKET = 1

    def create_default_browser(self):
        if self.config['register']:
            browser = None
            while not browser:
                try:
                    browser = self.create_browser(self.config['username'])
                    browser.register(password=   self.config['password'],
                                     sex=        0,
                                     birthday_d= 1,
                                     birthday_m= 1,
                                     birthday_y= 1970,
                                     zipcode=    75001,
                                     country=    'fr',
                                     godfather=  '')
                except CaptchaError:
                    debug('Unable to resolve captcha. Retrying...')
                    browser = None
            browser.password = self.config['password']
            return browser
        else:
            return self.create_browser(self.config['username'], self.config['password'])

    def get_status(self):
        with self.browser:
            try:
                return (
                        StatusField('myname', 'My name', self.browser.get_my_name()),
                        StatusField('score', 'Score', self.browser.score()),
                        StatusField('avcharms', 'Available charms', self.browser.nb_available_charms()),
                       )
            except AdopteWait:
                return (StatusField('notice', '', u'<h3>You are currently waiting 1am to be able to connect with this account</h3>', StatusField.FIELD_HTML|StatusField.FIELD_TEXT))

    def iter_threads(self):
        with self.browser:
            contacts = self.browser.get_threads_list()

        for contact in contacts:
            if not contact.get_id():
                continue
            thread = Thread(contact.get_id())
            thread.title = 'Discussion with %s' % contact.get_name()
            yield thread

    def get_thread(self, id, profiles=None):
        """
        Get a thread and its messages.

        The 'profiles' parameter is only used for internal calls.
        """
        thread = None
        if isinstance(id, Thread):
            thread = id
            id = thread.id

        if not thread:
            thread = Thread(id)
            full = False
        else:
            full = True

        with self.browser:
            mails = self.browser.get_thread_mails(id, full)
            my_name = self.browser.get_my_name()

        child = None
        msg = None
        slut = self._get_slut(id)
        if not profiles:
            profiles = {}
        for mail in mails:
            flags = 0
            if mail.date > slut['lastmsg']:
                flags |= Message.IS_UNREAD

                if not mail.profile_link in profiles:
                    with self.browser:
                        profiles[mail.profile_link] = self.browser.get_profile(mail.profile_link)
                mail.signature += u'\n%s' % profiles[mail.profile_link].get_profile_text()

            if mail.sender == my_name:
                if mail.new:
                    flags |= Message.IS_NOT_ACCUSED
                else:
                    flags |= Message.IS_ACCUSED

            if not thread.title:
                thread.title = mail.title

            msg = Message(thread=thread,
                          id=mail.message_id,
                          title=mail.title,
                          sender=mail.sender,
                          receiver=mail.name if mail.sender == my_name else my_name, # TODO: me
                          date=mail.date,
                          content=mail.content,
                          signature=mail.signature,
                          children=[],
                          flags=flags)
            if child:
                msg.children.append(child)
                child.parent = msg

            child = msg

        if full and msg:
            # If we have get all the messages, replace NotLoaded with None as
            # parent.
            msg.parent = None
        if not full and not msg:
            # Perhaps there are hidden messages
            msg = NotLoaded

        thread.root = msg

        return thread

    def iter_unread_messages(self, thread=None):
        try:
            profiles = {}
            with self.browser:
                contacts = self.browser.get_threads_list()
            for contact in contacts:
{'fraction_non_alphanumeric': 0.08073505045940654, 'fraction_numerical': 0.006025003765627353, 'mean_word_length': 1.7033794788273615, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 2, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5371784', 'n_tokens_mistral': 3434, 'n_tokens_neox': 3273, 'n_words': 997}