AuM implements ICapAccount

This commit is contained in:
Romain Bignon 2010-10-26 20:59:24 +02:00
commit e709f40b8a
2 changed files with 103 additions and 58 deletions

View file

@ -26,8 +26,10 @@ from weboob.capabilities.chat import ICapChat
from weboob.capabilities.messages import ICapMessages, ICapMessagesPost, Message, Thread from weboob.capabilities.messages import ICapMessages, ICapMessagesPost, Message, Thread
from weboob.capabilities.dating import ICapDating, StatusField from weboob.capabilities.dating import ICapDating, StatusField
from weboob.capabilities.contact import ICapContact, Contact, ProfileNode from weboob.capabilities.contact import ICapContact, Contact, ProfileNode
from weboob.capabilities.account import ICapAccount, Account
from weboob.tools.backend import BaseBackend from weboob.tools.backend import BaseBackend
from weboob.tools.browser import BrowserUnavailable from weboob.tools.browser import BrowserUnavailable
from weboob.tools.value import Value, ValuesDict, ValueBool
from .captcha import CaptchaError from .captcha import CaptchaError
from .antispam import AntiSpam from .antispam import AntiSpam
@ -40,22 +42,16 @@ from .optim.visibility import Visibility
__all__ = ['AuMBackend'] __all__ = ['AuMBackend']
class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapChat, ICapContact): class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapChat, ICapContact, ICapAccount):
NAME = 'aum' NAME = 'aum'
MAINTAINER = 'Romain Bignon' MAINTAINER = 'Romain Bignon'
EMAIL = 'romain@weboob.org' EMAIL = 'romain@weboob.org'
VERSION = '0.3' VERSION = '0.3'
LICENSE = 'GPLv3' LICENSE = 'GPLv3'
DESCRIPTION = u"“Adopte un mec” french dating website" DESCRIPTION = u"“Adopte un mec” french dating website"
CONFIG = {'username': BaseBackend.ConfigField(description='Username on website'), CONFIG = ValuesDict(Value('username', label='Username'),
'password': BaseBackend.ConfigField(description='Password of account', is_masked=True), Value('password', label='Password', masked=True),
'register': BaseBackend.ConfigField(description='Register as new account?', default=False), ValueBool('antispam', label='Enable anti-spam', default=False))
'sex': BaseBackend.ConfigField(description='Sex of new the account owner', default='m',
choices=('m', 'f')),
'age': BaseBackend.ConfigField(description='Age of new the account owner', default=25),
'godfather': BaseBackend.ConfigField(description='Godfather of new the account owner', default=''),
'antispam': BaseBackend.ConfigField(description='Enable anti-spam', default=False),
}
STORAGE = {'profiles_walker': {'viewed': []}, STORAGE = {'profiles_walker': {'viewed': []},
'sluts': {}, 'sluts': {},
} }
@ -71,26 +67,6 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
self.antispam = None self.antispam = None
def create_default_browser(self): def create_default_browser(self):
if self.config['register']:
browser = None
birthday = datetime.datetime.now() - datetime.timedelta(int(self.config['age']) * 365)
while not browser:
try:
browser = self.create_browser(self.config['username'])
browser.register(password= self.config['password'],
sex= 0 if self.config['sex'] == 'm' else 1,
birthday_d= birthday.day,
birthday_m= birthday.month,
birthday_y= birthday.year,
zipcode= 75001,
country= 'fr',
godfather= self.config['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']) return self.create_browser(self.config['username'], self.config['password'])
def report_spam(self, id, suppr_id=None): def report_spam(self, id, suppr_id=None):
@ -99,6 +75,12 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
self.browser.report_fake(id) self.browser.report_fake(id)
pass pass
# ---- ICapDating methods ---------------------
def init_optimizations(self):
self.OPTIM_PROFILE_WALKER = ProfilesWalker(self.weboob.scheduler, self.storage, self.browser)
self.OPTIM_VISIBILITY = Visibility(self.weboob.scheduler, self.browser)
def get_status(self): def get_status(self):
with self.browser: with self.browser:
try: try:
@ -110,6 +92,11 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
except AdopteWait: 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)) 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))
# ---- ICapMessages methods ---------------------
def fill_thread(self, thread, fields):
return self.get_thread(thread)
def iter_threads(self): def iter_threads(self):
with self.browser: with self.browser:
contacts = self.browser.get_threads_list() contacts = self.browser.get_threads_list()
@ -281,10 +268,27 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
slut['lastmsg'] = slut['lastmsg'].replace(tzinfo=tz.tzutc()) slut['lastmsg'] = slut['lastmsg'].replace(tzinfo=tz.tzutc())
return slut return slut
# ---- ICapMessagesPost methods ---------------------
def post_message(self, message): def post_message(self, message):
with self.browser: with self.browser:
self.browser.post_mail(message.thread.id, message.content) self.browser.post_mail(message.thread.id, message.content)
# ---- ICapContact methods ---------------------
def fill_contact(self, contact, fields):
if 'profile' in fields:
contact = self.get_contact(contact)
if contact and 'photos' in fields:
for name, photo in contact.photos.iteritems():
with self.browser:
if photo.url:
data = self.browser.openurl(photo.url).read()
contact.set_photo(name, data=data)
if photo.thumbnail_url:
data = self.browser.openurl(photo.thumbnail_url).read()
contact.set_photo(name, thumbnail_data=data)
def get_contact(self, contact): def get_contact(self, contact):
with self.browser: with self.browser:
if isinstance(contact, Contact): if isinstance(contact, Contact):
@ -326,10 +330,6 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
return contact return contact
def init_optimizations(self):
self.OPTIM_PROFILE_WALKER = ProfilesWalker(self.weboob.scheduler, self.storage, self.browser)
self.OPTIM_VISIBILITY = Visibility(self.weboob.scheduler, self.browser)
def iter_contacts(self, status=Contact.STATUS_ALL, ids=None): def iter_contacts(self, status=Contact.STATUS_ALL, ids=None):
with self.browser: with self.browser:
for contact in self.browser.iter_contacts(): for contact in self.browser.iter_contacts():
@ -352,6 +352,8 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
c.set_photo(contact['cover'].split('/')[-1].replace('thumb0_', 'image'), thumbnail_url=contact['cover']) c.set_photo(contact['cover'].split('/')[-1].replace('thumb0_', 'image'), thumbnail_url=contact['cover'])
yield c yield c
# ---- ICapChat methods ---------------------
def iter_chat_messages(self, _id=None): def iter_chat_messages(self, _id=None):
with self.browser: with self.browser:
return self.browser.iter_chat_messages(_id) return self.browser.iter_chat_messages(_id)
@ -363,21 +365,56 @@ class AuMBackend(BaseBackend, ICapMessages, ICapMessagesPost, ICapDating, ICapCh
#def start_chat_polling(self): #def start_chat_polling(self):
#self._profile_walker = ProfilesWalker(self.weboob.scheduler, self.storage, self.browser) #self._profile_walker = ProfilesWalker(self.weboob.scheduler, self.storage, self.browser)
def fill_contact(self, contact, fields): # ---- ICapAccount methods ---------------------
if 'profile' in fields:
contact = self.get_contact(contact)
if contact and 'photos' in fields:
for name, photo in contact.photos.iteritems():
with self.browser:
if photo.url:
data = self.browser.openurl(photo.url).read()
contact.set_photo(name, data=data)
if photo.thumbnail_url:
data = self.browser.openurl(photo.thumbnail_url).read()
contact.set_photo(name, thumbnail_data=data)
def fill_thread(self, thread, fields): ACCOUNT_REGISTER_PROPERTIES = ValuesDict(
return self.get_thread(thread) Value('username', label='Email address', regexp='^[^ ]+@[^ ]+\.[^ ]+$'),
Value('password', label='Password', regexp='^[^ ]+$', masked=True),
Value('sex', label='Sex', choices={'0': 'Male', '1': 'Female'}),
Value('birthday', label='Birthday', regexp='^\d+/\d+/\d+$'),
Value('zipcode', label='Zipcode'),
Value('country', label='Country', choices={'fr': 'France', 'be': 'Belgique', 'ch': 'Suisse', 'ca': 'Canada'}, default='fr'),
Value('godfather',label='Godfather', regexp='^\d*$', default=''),
)
@classmethod
def register_account(klass, account):
"""
Register an account on website
This is a static method, it would be called even if the backend is
instancied.
@param account an Account object which describe the account to create
"""
browser = None
bday, bmonth, byear = account.properties['birthday'].value.split('/', 2)
while not browser:
try:
browser = klass.BROWSER(account.properties['username'].value)
browser.register(password= account.properties['password'].value,
sex= int(account.properties['sex'].value),
birthday_d= int(bday),
birthday_m= int(bmonth),
birthday_y= int(byear),
zipcode= account.properties['zipcode'].value,
country= account.properties['country'].value,
godfather= account.properties['godfather'].value)
except CaptchaError:
debug('Unable to resolve captcha. Retrying...')
browser = None
def get_account(self):
"""
Get the current account.
"""
raise NotImplementedError()
def update_account(self, account):
"""
Update the current account.
"""
raise NotImplementedError()
OBJECTS = {Thread: fill_thread, OBJECTS = {Thread: fill_thread,
Contact: fill_contact} Contact: fill_contact}

View file

@ -18,7 +18,9 @@
import re import re
from weboob.tools.mech import ClientForm
from weboob.tools.browser import BrowserIncorrectPassword from weboob.tools.browser import BrowserIncorrectPassword
from weboob.capabilities.account import AccountRegisterError
from .base import PageBase from .base import PageBase
from ..captcha import Captcha from ..captcha import Captcha
@ -31,9 +33,6 @@ class LoginPage(PageBase):
self.browser.submit() # submit current form self.browser.submit() # submit current form
class RegisterError(Exception):
pass
class RegisterPage(PageBase): class RegisterPage(PageBase):
def on_loaded(self): def on_loaded(self):
display_errors = False display_errors = False
@ -52,7 +51,7 @@ class RegisterPage(PageBase):
for m in re.finditer('"(\w+)": "(.*)",', child.data): for m in re.finditer('"(\w+)": "(.*)",', child.data):
errors.append(m.group(2)) errors.append(m.group(2))
raise RegisterError(u'Unable to register account: %s' % ', '.join(errors)) raise AccountRegisterError(u'Unable to register account: %s' % ', '.join(errors))
def register(self, password, sex, birthday_d, birthday_m, birthday_y, zipcode, country): def register(self, password, sex, birthday_d, birthday_m, birthday_y, zipcode, country):
""" """
@ -77,11 +76,20 @@ Form name=register (#1)
self.browser.select_form(name='register') self.browser.select_form(name='register')
self.browser.set_all_readonly(False) self.browser.set_all_readonly(False)
try:
self.browser['sex'] = [str(sex)] self.browser['sex'] = [str(sex)]
except ClientForm.ItemNotFoundError:
raise AccountRegisterError('Please give a right sex! (1 or 0)')
try:
self.browser['birthday0'] = [str(birthday_d)] self.browser['birthday0'] = [str(birthday_d)]
self.browser['birthday1'] = [str(birthday_m)] self.browser['birthday1'] = [str(birthday_m)]
self.browser['birthday2'] = [str(birthday_y)] self.browser['birthday2'] = [str(birthday_y)]
except ClientForm.ItemNotFoundError:
raise AccountRegisterError('Please give a right birthday date!')
try:
self.browser['country'] = [str(country)] self.browser['country'] = [str(country)]
except ClientForm.ItemNotFoundError:
raise AccountRegisterError('Please select a right country!')
self.browser['zip'] = str(zipcode) self.browser['zip'] = str(zipcode)
self.browser['email'] = self.browser.username self.browser['email'] = self.browser.username
self.browser['pass'] = password self.browser['pass'] = password