rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def do_forecasts(self, city):
def do_forecasts(self, line):
def do_forecasts(self, city): """ forecasts CITY
for backend, profile in self.weboob.do('get_profile', _id, backends=backend_name): if profile: print profile.get_profile_text().encode('utf-8')
for backend, contact in self.weboob.do('get_contact', _id, backends=backend_name): if contact: print 'Nickname:', contact.name if contact.status & contact.STATUS_ONLINE: s = 'online' elif contact.status & contact.STATUS_OFFLINE: s = 'offline' elif contact.status & contact.STATUS_AWAY: s = 'away' else: s = 'unknown' pri...
def command_profile(self, id): _id, backend_name = self.parse_id(id)
help_str = self.do_help(return_only=True)
app_cmds, weboob_cmds, undoc_cmds = self.get_commands_doc() help_str = '%s Commands:\n%s\n\n' % (self.APPNAME, '\n'.join(' %s' % cmd for cmd in sorted(app_cmds + undoc_cmds))) help_str +='Weboob Commands:\n%s\n' % '\n'.join(' %s' % cmd for cmd in weboob_cmds)
def __init__(self): cmd.Cmd.__init__(self) self.prompt = '%s> ' % self.APPNAME self.intro = '\n'.join(('Welcome to %s v%s' % (self.APPNAME, self.VERSION), '', '%s' % self.COPYRIGHT, 'This program is free software; you can redistribute it and/or modify', 'it under the terms of the GNU General Public License as published...
def do_help(self, arg=None, return_only=False): if return_only: stringio = StringIO() old_stdout = self.stdout self.stdout = stringio
def get_commands_doc(self): names = set(name for name in self.get_names() if name.startswith('do_')) application_cmds_doc = [] weboob_cmds_doc = [] cmds_undoc = [] for name in sorted(names): cmd = name[3:] if cmd in self.hidden_commands.union(['help']): continue elif getattr(self, name).__doc__: short_help = ' %s' %...
def do_help(self, arg=None, return_only=False): if return_only: stringio = StringIO() old_stdout = self.stdout self.stdout = stringio if arg: cmd_names = set(name[3:] for name in self.get_names() if name.startswith('do_')) if arg in cmd_names: command_help = self.get_command_help(arg) if command_help is None: logging.w...
names = set(name for name in self.get_names() if name.startswith('do_')) application_cmds_doc = [] weboob_cmds_doc = [] cmds_undoc = [] for name in sorted(names): cmd = name[3:] if cmd in self.hidden_commands.union(['help']): continue elif getattr(self, name).__doc__: short_help = ' %s' % self.get_command_help(cmd, ...
application_cmds_doc, weboob_cmds_doc, undoc_cmds_doc = self.get_commands_doc()
def do_help(self, arg=None, return_only=False): if return_only: stringio = StringIO() old_stdout = self.stdout self.stdout = stringio if arg: cmd_names = set(name[3:] for name in self.get_names() if name.startswith('do_')) if arg in cmd_names: command_help = self.get_command_help(arg) if command_help is None: logging.w...
self.print_topics(self.undoc_header, cmds_undoc, 15,80)
self.print_topics(self.undoc_header, undoc_cmds_doc, 15,80)
def do_help(self, arg=None, return_only=False): if return_only: stringio = StringIO() old_stdout = self.stdout self.stdout = stringio if arg: cmd_names = set(name[3:] for name in self.get_names() if name.startswith('do_')) if arg in cmd_names: command_help = self.get_command_help(arg) if command_help is None: logging.w...
if return_only: self.stdout = old_stdout return stringio.getvalue()
def do_help(self, arg=None, return_only=False): if return_only: stringio = StringIO() old_stdout = self.stdout self.stdout = stringio if arg: cmd_names = set(name[3:] for name in self.get_names() if name.startswith('do_')) if arg in cmd_names: command_help = self.get_command_help(arg) if command_help is None: logging.w...
if args[1] in ('enable', 'only'):
if args[1] == 'enable':
def complete_backends(self, text, line, begidx, endidx): choices = None commands = ['enable', 'disable', 'only', 'list'] available_backends_names = set(backend.name for backend in self.weboob.iter_backends()) enabled_backends_names = set(backend.name for backend in self.enabled_backends)
u = size[-2:] size = size = size[:-3].replace(',','.')
u = tr.getchildren()[1].getchildren()[0].text size = size = size.replace(',','.')
def iter_torrents(self):
if len(args) < nb_args or len(args) > nb_args and not varargs
if len(args) < nb_args or len(args) > nb_args and not varargs:
def f(x): return x.startswith('command_' + command)
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError), e:
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError, BadStatusLine), e:
def openurl(self, *args, **kwargs): """ Open an URL but do not create a Page object. """ if_fail = kwargs.pop('if_fail', 'raise') debug('Opening URL "%s", %s' % (args, kwargs)) try: return mechanize.Browser.open_novisit(self, *args, **kwargs) except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError)...
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError), e:
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError, BadStatusLine), e:
def submit(self, *args, **kwargs): """ Submit the selected form. """ try: self._change_location(mechanize.Browser.submit(self, *args, **kwargs)) except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError), e: self.page = None raise BrowserHTTPError(e) except (mechanize.BrowserStateError, BrowserRetry)...
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError), e:
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError, BadStatusLine), e:
def follow_link(self, *args, **kwargs): try: self._change_location(mechanize.Browser.follow_link(self, *args, **kwargs)) except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError), e: self.page = None raise BrowserHTTPError('%s (url="%s")' % (e, args and args[0] or 'None')) except (mechanize.BrowserS...
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError), e:
except (mechanize.response_seek_wrapper, urllib2.HTTPError, urllib2.URLError, BadStatusLine), e:
def location(self, *args, **kwargs): """ Change location of browser on an URL.
sub = self._complete_obj(backend, sub, fields)
sub = self._complete_obj(backend, fields, sub)
def _complete_iter(self, backend, count, fields, res): for i, sub in enumerate(res): if count and i == count: break sub = self._complete_obj(backend, sub, fields) yield sub
m = {'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024, }
m = {'B': 1, 'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024, }
def unit(self, n, u): m = {'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024, } #return float(n.replace(',', '')) * m.get(u, 1) return float(n*m[u])
size = td.find('font').text.split(',')[1] size = size.split(' ')[2] u = size[-3:].replace('i','') size = size[:-3]
size = td.find('font').text.split(',')[1].strip() u = size.split(' ')[1].split(u'\xa0')[1].replace('i','') size = size.split(' ')[1].split(u'\xa0')[0]
def iter_torrents(self):
self.set_default_formatter('table')
def do_list(self, line): """ list
self.set_default_formatter('table')
def do_backends(self, line): """ backends [CAPS ...]
def __init__(self, thread_id, id, title, sender, date=None, reply_id=''):
def __init__(self, thread_id, _id, title, sender, date=None, reply_id=u'', content=u'', signature=u''):
def __init__(self, thread_id, id, title, sender, date=None, reply_id=''): self.thread_id = unicode(thread_id) self.id = unicode(id) self.reply_id = unicode(reply_id) self.title = unicode(title) self.sender = unicode(sender)
self.id = unicode(id)
self._id = unicode(_id)
def __init__(self, thread_id, id, title, sender, date=None, reply_id=''): self.thread_id = unicode(thread_id) self.id = unicode(id) self.reply_id = unicode(reply_id) self.title = unicode(title) self.sender = unicode(sender)
self.content = u''
self.content = content
def __init__(self, thread_id, id, title, sender, date=None, reply_id=''): self.thread_id = unicode(thread_id) self.id = unicode(id) self.reply_id = unicode(reply_id) self.title = unicode(title) self.sender = unicode(sender)
return '%s.%s' % (self.id, self.thread_id)
return '%s.%s' % (self._id, self.thread_id)
def getFullID(self): return '%s.%s' % (self.id, self.thread_id)
return self.id
return self._id
def getID(self): return self.id
self.load_backends(ICapTravel)
def main(self, argv): self.load_backends(ICapTravel) return self.process_command(*argv[1:])
if cmd in self.commands_formatters: self.set_formatter(self.commands_formatters[cmd]) else: self.set_formatter(self.DEFAULT_FORMATTER)
try: formatter_name = self.commands_formatters[cmd] except KeyError: formatter_name = self.DEFAULT_FORMATTER self.set_formatter(formatter_name)
def onecmd(self, line): """ This REPL method is overrided to catch some particular exceptions. """ cmd, arg, ignored = self.parseline(line)
print 'Falling back to "%s".' % (name, self.DEFAULT_FORMATTER)
if self.DEFAULT_FORMATTER == name: self.DEFAULT_FORMATTER = ReplApplication.DEFAULT_FORMATTER print 'Falling back to "%s".' % (self.DEFAULT_FORMATTER)
def set_formatter(self, name): """ Set the current formatter from name.
content='Unable to send message to %s:\n\n\t%s' % (thread_id, e)))
content=content))
def command_post(self): msg = message_from_file(sys.stdin) reply_to = msg.get('In-Reply-To') if not reply_to: print >>sys.stderr, 'This is not a reply (no Reply-To field)' return 1
Browser.__init__(self, '', parser=Parser)
Browser.__init__(self, '', parser=Parser())
def __init__(self): Browser.__init__(self, '', parser=Parser)
if self.gotProfile(self.weboob.get_backend(contact.backend), contact):
self.loaded_profile = False missing_fields = self.gotProfile(self.weboob.get_backend(contact.backend), contact) if len(missing_fields) > 0:
def __init__(self, weboob, contact, parent=None): QWidget.__init__(self, parent) self.ui = Ui_Profile() self.ui.setupUi(self)
self.process_contact.do('fillobj', self.contact, ['photos', 'profile'], backends=self.contact.backend)
self.process_contact.do('fillobj', self.contact, missing_fields, backends=self.contact.backend)
def __init__(self, weboob, contact, parent=None): QWidget.__init__(self, parent) self.ui = Ui_Profile() self.ui.setupUi(self)
return
return [] missing_fields = set(['photos'])
def gotProfile(self, backend, contact): if not backend: return
if first and photo.data: img = QImage.fromData(photo.data)
if photo.data: data = photo.data try: missing_fields.remove('photos') except KeyError: pass elif photo.thumbnail_data: data = photo.thumbnail_data else: continue if first: img = QImage.fromData(data)
def gotProfile(self, backend, contact): if not backend: return
self.ui.descriptionEdit.setText('<h1>Description</h1><p>%s</p>' % ('<i>Receiving...</i>' if contact.summary is NotLoaded else contact.summary.replace('\n', '<br />')))
if contact.summary is NotLoaded: self.ui.descriptionEdit.setText('<h1>Description</h1><p><i>Receiving...</i></p>') missing_fields.add('summary') else: self.ui.descriptionEdit.setText('<h1>Description</h1><p>%s</p>' % contact.summary.replace('\n', '<br />'))
def gotProfile(self, backend, contact): if not backend: return
return True for head in contact.profile: if head.flags & head.HEAD: widget = self.ui.headFrame else: widget = self.ui.profileTab self.process_node(head, widget) return False
missing_fields.add('profile') elif not self.loaded_profile: self.loaded_profile = True for head in contact.profile: if head.flags & head.HEAD: widget = self.ui.headFrame else: widget = self.ui.profileTab self.process_node(head, widget) return missing_fields
def gotProfile(self, backend, contact): if not backend: return
self.setContact(contact) def setContact(self, contact):
def contactChanged(self, current): if not current: return
contact = Contact(contact['id'], contact['pseudo'], s) contact.status_msg = u'%s old' % contact['birthday'] contact.thumbnail_url = contact['cover'] yield contact
c = Contact(contact['id'], contact['pseudo'], s) c.status_msg = u'%s old' % contact['birthday'] c.thumbnail_url = contact['cover'] yield c
def iter_contacts(self, status=Contact.STATUS_ALL): with self.browser: for contact in self.browser.iter_contacts(): if contact['cat'] == 1: s = Contact.STATUS_ONLINE elif contact['cat'] == 3: s = Contact.STATUS_OFFLINE else: warning('Unknown AuM contact status: %s' % contact['cat'])
child = big.firstChild if hasattr(child, 'tagName') and child.tagName == u'b': self.name = child.firstChild.data break
for child in big.childNodes: if hasattr(child, 'tagName') and child.tagName == u'b': self.name = child.childNodes[1].data.strip() break
def on_loaded(self): self.items = []
return '%s.%s' % (self.id, self.thread_id)
return '%s.%s' % (self.thread_id, self.id)
def get_full_id(self): return '%s.%s' % (self.id, self.thread_id)
return '%s.%s' % (self.reply_id, self.thread_id)
return '%s.%s' % (self.thread_id, self.reply_id)
def get_full_reply_id(self): return '%s.%s' % (self.reply_id, self.thread_id)
Exception.__init__(self, u'These errors have been raised in backend threads:\n%s' % (
Exception.__init__(self, u'These errors have been raised in backend threads '\ '(use --debug option to print backtraces):\n%s' % (
def __init__(self, errors): Exception.__init__(self, u'These errors have been raised in backend threads:\n%s' % ( u'\n'.join((u' * %s: %s%s' % (backend, error, backtrace + '\n' if logging.root.level == logging.DEBUG else '')) for backend, error, backtrace in errors))) self.errors = copy(errors)
self.location('%s://%s' % (self.PROTOCOL, self.DOMAIN))
if self.DOMAIN is not None: self.location('%s://%s' % (self.PROTOCOL, self.DOMAIN))
def home(self): """ Go to the home page. """ self.location('%s://%s' % (self.PROTOCOL, self.DOMAIN))
print 'Total messages: %s' % tot
debug('Total messages: %s' % tot)
def test_new_messages(self): tot = 0 for thread in self.backend.iter_threads(): thread = self.backend.fillobj(thread, 'root') count = 0 for m in thread.iter_all_messages(): count += 1 debug('Count: %s' % count) tot += count
print 'Unread messages: %s' % count
debug('Unread messages: %s' % count)
def test_new_messages(self): tot = 0 for thread in self.backend.iter_threads(): thread = self.backend.fillobj(thread, 'root') count = 0 for m in thread.iter_all_messages(): count += 1 debug('Count: %s' % count) tot += count
content += '\n\t%s\n' % e
content += u'\n\t%s\n' % e
def process_incoming_mail(self, msg): to = self.get_email_address_ident(msg, 'To') reply_to = self.get_email_address_ident(msg, 'In-Reply-To') if not reply_to: print >>sys.stderr, 'This is not a reply (no Reply-To field)' return 1
content += '\n%s\n' % get_backtrace(e)
content += u'\n%s\n' % get_backtrace(e)
def process_incoming_mail(self, msg): to = self.get_email_address_ident(msg, 'To') reply_to = self.get_email_address_ident(msg, 'In-Reply-To') if not reply_to: print >>sys.stderr, 'This is not a reply (no Reply-To field)' return 1
c = Contact(contact['id'], contact['pseudo'], s, self.browser.id2url(contact['id']))
c = Contact(contact['id'], contact['pseudo'], s) c.url = self.browser.id2url(contact['id'])
def iter_contacts(self, status=Contact.STATUS_ALL, ids=None): with self.browser: for contact in self.browser.iter_contacts(): s = 0 if contact['cat'] == 1: s = Contact.STATUS_ONLINE elif contact['cat'] == 3: s = Contact.STATUS_OFFLINE elif contact['cat'] == 2: s = Contact.STATUS_AWAY else: self.logger.warning('Unknown ...
self._label = str(value)
self._label = unicode(value)
def label(self, value): self._label = str(value)
result += u'%sTo:%s %s\n' % (ReplApplication.BOLD, ReplApplication.NC, ', '.join(item['receivers'])) result += '\n%s' % item['content']
if item['receivers']: result += u'%sTo:%s %s\n' % (ReplApplication.BOLD, ReplApplication.NC, ', '.join(item['receivers'])) if item['flags'] & Message.IS_HTML: content = html2text(item['content']) else: content = item['content'] result += '\n%s' % content
def format_dict(self, item): result = u'%sTitle:%s %s\n' % (ReplApplication.BOLD, ReplApplication.NC, item['title']) result += u'%sDate:%s %s\n' % (ReplApplication.BOLD, ReplApplication.NC, item['date']) result += u'%sFrom:%s %s\n' % (ReplApplication.BOLD, ReplApplication.NC, item['sender']) result += u'%sTo:%s %s\n' %...
CONFIG = {'interval': 15,
CONFIG = {'interval': 300,
def run(self): if self.app.options.smtpd: if ':' in self.app.options.smtpd: host, port = self.app.options.smtpd.split(':', 1) else: host = '127.0.0.1' port = self.app.options.smtpd FakeSMTPD(self.app, host, int(port))
self.ui.photoLabel.setPixmap(None)
def display_photo(self): if self.displayed_photo_idx >= len(self.contact.photos): self.displayed_photo_idx = len(self.contact.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photoLabel.setPixmap(None) self.ui.photoUrlLabel.setText('') return
self.ui.photoLabel.setPixmap(None) self.ui.photoLabel.setText('<i>Loading...</i>')
def display_photo(self): if self.displayed_photo_idx >= len(self.contact.photos): self.displayed_photo_idx = len(self.contact.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photoLabel.setPixmap(None) self.ui.photoUrlLabel.setText('') return
if not photo.shown:
if photo.hidden:
def display_photo(self): if self.displayed_photo_idx >= len(self.contact.photos): self.displayed_photo_idx = len(self.contact.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photoLabel.setPixmap(None) self.ui.photoUrlLabel.setText('') return
seed = div.getchildren()[0].getchildren()[24].text leech = div.getchildren()[0].getchildren()[26].text
seed = div.getchildren()[1].getchildren()[7].text leech = div.getchildren()[1].getchildren()[9].text
def get_torrent(self, id): for div in self.document.getiterator('div'): if div.attrib.get('id','') == 'title': title = div.text elif div.attrib.get('class','') == 'download': url = div.getchildren()[0].attrib.get('href','') elif div.attrib.get('id','') == 'details': size = float(div.getchildren()[0].getchildren()[5].te...
if field.regexp and re.match(field.regexp, str(value)):
if field.regexp and not re.match(field.regexp, str(value)):
def __init__(self, weboob, name, config, storage): self.weboob = weboob self.name = name self.lock = RLock()
def _handle_app_options(self):
def _handle_options(self):
def _handle_app_options(self): if self.options.formatter: formatter_name = self.options.formatter else: formatter_name = 'multiline' self.formatter = load_formatter(formatter_name)
self.logger.debug('scheduled function "%s" is canceled' % e.function)
self.logger.debug('scheduled function "%s" is canceled' % e.function.__name__)
def cancel(self, ev): with self.mutex: try: e = self.queue.pop(ev) except KeyError: return False e.cancel() self.logger.debug('scheduled function "%s" is canceled' % e.function) return True
def load_buildtin():
def load_builtin():
def load_buildtin(): from .htmlparser import HTMLParser return HTMLParser
@pageaccess
def get_my_name(self): if time.time() - self.last_update > 60: self.home() return self.page.get_my_name()
'subject': title, 'body': message,
'subject': unicode(title).encode('utf-8'), 'body': unicode(message).encode('utf-8'),
def post_reply(self, thread, reply_id, title, message): content_type = id2contenttype(thread) thread_id = id2threadid(thread) reply_id = int(reply_id)
self.optims('Starting', 'start_optimization', self.config.get('optimizations').split(' '))
optimizations_str = self.config.get('optimizations').strip() if optimizations_str: optimizations = optimizations_str.split(' ') if optimizations: self.optims('Starting', 'start_optimization', optimizations)
def main(self, argv): self.load_config() self.load_backends(ICapDating, storage=self.create_storage(self.STORAGE_FILENAME))
self.service('Starting %s' % optim, 'start_optimization', optim)
self.service('Starting "%s"' % optim, 'start_optimization', optim)
def optims(self, action, function, optims): for optim in optims: try: self.service('Starting %s' % optim, 'start_optimization', optim) except weboob.core.CallErrors, errors: for backend, error, backtrace in errors: if isinstance(error, OptimizationNotFound): logging.error(u'Optimization "%s" not found' % optim)
regexp = re.compile("window.location='/thread.php\?id=(.*)'")
regexp = re.compile("window.location='/thread.php\?id=(\d+)'")
def get_id(self): tag = self.__get_element('thread_link')
print >>sys.stderr, 'Error: no enough arguments.'
print >>sys.stderr, 'Error: not enough arguments. %s' % str(e)
def onecmd(self, line): """ This REPL method is overrided to catch some particular exceptions. """ cmd, arg, ignored = self.parseline(line)
self.storage.set('profiles_walker', 'viewed', self.visited_profiles)
self.storage.set('profiles_walker', 'viewed', list(self.visited_profiles))
def save(self): self.storage.set('profiles_walker', 'viewed', self.visited_profiles) self.storage.save()
args = line.strip().split(' ', nb - 1) if req_n is not None and (len(args) < req_n or req_n < 2 and line == ''):
if line.strip() == '': args = [] else: args = line.strip().split(' ', nb - 1) if req_n is not None and (len(args) < req_n):
def parseargs(self, line, nb, req_n=None): args = line.strip().split(' ', nb - 1) if req_n is not None and (len(args) < req_n or req_n < 2 and line == ''): raise NotEnoughArguments('Command needs %d arguments' % req_n)
self.browser.post(thread_id, message)
self.browser.post_mail(thread_id, message)
def post_reply(self, thread_id, reply_id, title, message): with self.browser: self.browser.post(thread_id, message)
'timestamp': '',
'timestamp': timestamp,
def post_reply(self, thread, reply_id, title, message, is_html=False): content_type = id2contenttype(thread) thread_id = id2threadid(thread) reply_id = int(reply_id)
'referer': '%s://%s%s' % (self.PROTOCOL, self.DOMAIN, id2url(thread)),
'referer': thread_url,
def post_reply(self, thread, reply_id, title, message, is_html=False): content_type = id2contenttype(thread) thread_id = id2threadid(thread) reply_id = int(reply_id)
return self._play_default(media)
return self._play_default(media, player_name)
def _play_rtmp(self, media, player_name): """ Download data with rtmpdump and pipe them to a media player.
thread = self.browser.get_content(article.id)
def _iter_messages_of(self, what, thread_wanted, only_new): if not what in self.storage.get('seen', default={}): self.storage.set('seen', what, {})
self.storage.set('seen', what, seen) self.storage.save()
if seen: self.storage.set('seen', what, seen) self.storage.save()
def _iter_messages_of(self, what, thread_wanted, only_new): if not what in self.storage.get('seen', default={}): self.storage.set('seen', what, {})
debug('[%s] Went on %s' % (self.username, result.geturl()))
debug('[user_id=%s] Went on %s' % (self.username, result.geturl()))
def _change_location(self, result): """ This function is called when we have moved to a page, to load a Page object. """
if '_enabled' in params and not params['_enabled'] or \
if '_enabled' in params and not params['_enabled'].lower() in ('1', 'y', 'true', 'on', 'yes') or \
def load_backends(self, caps=None, names=None, modules=None, storage=None): loaded = {} if storage is None: storage = self.storage
u'\n'.join((u' * %s: %s%s' % (backend, repr(error), backtrace + '\n'
u'\n'.join((u' * %s: %s%s' % (backend, repr(error), backtrace.decode('utf-8') + '\n'
def __init__(self, errors): Exception.__init__(self, u'These errors have been raised in backend threads '\ '(use --debug option to print backtraces):\n%s' % ( u'\n'.join((u' * %s: %s%s' % (backend, repr(error), backtrace + '\n' if logging.root.level == logging.DEBUG else '')) for backend, error, backtrace in errors))) ...
OK_PATTERN = re.compile("Votre virement N.+ ([0-9]+) ") ERROR_PATTERN = re.compile('Votre virement n\'a pas pu')
OK_PATTERN = re.compile()
def confirm(self): self.browser.location("https://voscomptesenligne.labanquepostale.fr/voscomptes/canalXHTML/virementsafran/virementnational/4-virementNational.ea")
text = to_unicode(p.text)
text = to_unicode(p.text).strip()
def get_transfer_id(self): p = self.document.xpath("//form/div/p")[0] text = to_unicode(p.text)
match = self.OK_PATTERN.search(text)
match = re.search("Votre virement N.+ ([0-9]+) ", text)
def get_transfer_id(self): p = self.document.xpath("//form/div/p")[0] text = to_unicode(p.text)
match = self.ERROR_PATTERN.search(text) if match and p.find('br'): errmsg = to_unicode(p.find('br').tail).strip() raise TransferError('Unable to process transfer: %s' % errmsg)
if text.startswith(u"Votre virement n'a pas pu"): if p.find('br'): errmsg = to_unicode(p.find('br').tail).strip() raise TransferError('Unable to process transfer: %s' % errmsg) else: self.browser.logger.warning('Unable to find the error reason')
def get_transfer_id(self): p = self.document.xpath("//form/div/p")[0] text = to_unicode(p.text)
class WebkitGtkFormatter(TableFormatter):
class WebkitGtkFormatter(HTMLTableFormatter):
def __init__(self): gtk.Window.__init__(self) self.connect('destroy', gtk.main_quit) self.set_default_size(800, 600) self.web_view = webkit.WebView() sw = gtk.ScrolledWindow() sw.add(self.web_view) self.add(sw) self.show_all()
TableFormatter.__init__(self, return_only=True, result_funcname='get_html_string')
HTMLTableFormatter.__init__(self, return_only=True)
def __init__(self): TableFormatter.__init__(self, return_only=True, result_funcname='get_html_string')
table_string = TableFormatter.flush(self)
table_string = HTMLTableFormatter.flush(self)
def flush(self): table_string = TableFormatter.flush(self) js_filepaths = [] js_filepaths.append(get_javascript('jquery')) js_filepaths.append(get_javascript('tablesorter')) scripts = ['<script type="text/javascript" src="%s"></script>' % js_filepath for js_filepath in js_filepaths] html_string_params = dict(table=tabl...
def balance_set(self, value):
def balance(self, value):
def balance_set(self, value): self._balance = float(value)
def coming_set(self, value):
def coming(self, value):
def coming_set(self, value): self._coming = float(value)
return video
if video: return video
def _get_video(self, _id): if self.interactive: try: video = self.videos[int(_id)] except (KeyError,ValueError): pass else: return video _id, backend_name = self.parse_id(_id) backend_names = (backend_name,) if backend_name is not None else self.enabled_backends for backend, video in self.do('get_video', _id, backends=...
torrent.description += '%s\n\n%s\n' % (title, body)
if torrent.description is NotLoaded: torrent.description = u'' torrent.description += u'%s\n\n%s\n' % (title, body)
def get_torrent(self, id): table = self.document.getroot().cssselect('div.thin') if not table: warning('No div.thin found') return None
self.storage.load(self.STORAGE)
self.storage.load(deepcopy(self.STORAGE))
def __init__(self, weboob, name, config, storage): self.weboob = weboob self.name = name self.lock = RLock()
except ClientForm.ControlNotFoundError:
except ControlNotFoundError: self.browser.controls.append(ClientForm.TextControl('text', 'numero', {'value': ''})) self.browser.controls.append(ClientForm.TextControl('text', 'code', {'value': ''}))
def login(self, login, password): self.browser.select_form(nr=0) try: self.browser['numero'] = login self.browser['code'] = password except ControlNotFoundError: try: self.browser['userLogin'] = login self.browser['userPassword'] = password except ClientForm.ControlNotFoundError: self.browser.controls.append(ClientForm...
return self.weboob.do(self.complete, self.options.count, self.selected_fields, function, *args, **kwargs)
return self.weboob.do(self._complete, self.options.count, self.selected_fields, function, *args, **kwargs)
def do(self, function, *args, **kwargs): """ Call Weboob.do(), after having filled the yielded object, if selected fields are given by user. """
m = {'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024, }
m = {'bytes': 1, 'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024, }
def unit(self, n, u): m = {'KB': 1024, 'MB': 1024*1024, 'GB': 1024*1024*1024, 'TB': 1024*1024*1024*1024, } return float(n*m[u])
content = content.encode('iso-8859-15', 'replace')
content = content.encode('Windows-1252', 'replace')
def post(self, content): if isinstance(content, unicode): content = content.encode('iso-8859-15', 'replace')
if self.klass.BROWSER and self.klass.BROWSER.DOMAIN:
if self.klass.BROWSER and hasattr(self.klass.BROWSER, 'DOMAIN') and self.klass.BROWSER.DOMAIN:
def website(self): if self.klass.BROWSER and self.klass.BROWSER.DOMAIN: return '%s://%s' % (self.klass.BROWSER.PROTOCOL, self.klass.BROWSER.DOMAIN) else: return None
('Configuration', ', '.join('%s=%s' % (key, ('*****' if key in backend.config and backend.config[key].is_masked else value)) for key, value in params.iteritems())),
('Configuration', ', '.join( '%s=%s' % (key, ('*****' if key in backend.config and backend.config[key].is_masked \ else value)) \ for key, value in params.iteritems())),
def do_list(self, line): """ list
app_options = OptionGroup(option_parser, '%s Options' % self.APPNAME.capitalize())
app_options = OptionGroup(self._parser, '%s Options' % self.APPNAME.capitalize())
def __init__(self, option_parser=None): self.weboob = self.create_weboob() self.config = None self.options = None if option_parser is None: self._parser = OptionParser(self.SYNOPSIS, version=self._get_optparse_version()) else: self._parser = option_parser if self.DESCRIPTION: self._parser.description = self.DESCRIPTION...
with self.mutex: self.errors.append((b, e))
self._store_error(b, e)
def _caller(self, b, function, args, kwargs): debug('Hello from timer %s' % b) with b: try: # Call method on backend try: if callable(function): r = function(b, *args, **kwargs) else: r = getattr(b, function)(*args, **kwargs) except Exception, e: with self.mutex: # TODO save backtrace and/or print it here (with debug) ...
with self.mutex: self.responses.append((b,e)) self.response_event.set()
self._store_result(b, e)
def _caller(self, b, function, args, kwargs): debug('Hello from timer %s' % b) with b: try: # Call method on backend try: if callable(function): r = function(b, *args, **kwargs) else: r = getattr(b, function)(*args, **kwargs) except Exception, e: with self.mutex: # TODO save backtrace and/or print it here (with debug) ...
with self.mutex: self.responses.append((b,r)) self.response_event.set()
self._store_result(b, r)
def _caller(self, b, function, args, kwargs): debug('Hello from timer %s' % b) with b: try: # Call method on backend try: if callable(function): r = function(b, *args, **kwargs) else: r = getattr(b, function)(*args, **kwargs) except Exception, e: with self.mutex: # TODO save backtrace and/or print it here (with debug) ...
def parse(self, data):
def parse(self, data, encoding):
def parse(self, data): self.feed(data.read()) return self
if self.document.docinfo.doctype == '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
if self.document.docinfo.doctype == '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" ' \
def on_loaded(self): if self.document.docinfo.doctype == '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">': self.browser.follow_link(url_regex="releve", tag="a")
logging.error(u'Cannot start application: no configured backend was found.\nHere is a list of all available backends:') from weboob.applications.weboobcfg import WeboobCfg
print 'Cannot start application: no configured backend was found.' try: from weboob.applications.weboobcfg import WeboobCfg except ImportError: print 'Please edit ~/.weboob/backends to add backends' return print '\nHere is a list of all available backends:'
def load_backends(self, caps=None, names=None, *args, **kwargs): loaded_backends = BaseApplication.load_backends(self, caps, names, *args, **kwargs) if not loaded_backends: logging.error(u'Cannot start application: no configured backend was found.\nHere is a list of all available backends:') from weboob.applications.we...