merge do_caps() and do_backends() into do() (optional keyword params 'backends' and 'caps')

This commit is contained in:
Romain Bignon 2010-07-17 13:33:27 +02:00
commit fc4badf88e
13 changed files with 53 additions and 103 deletions

View file

@ -46,7 +46,7 @@ class Chatoob(ConsoleApplication):
@ConsoleApplication.command('list online contacts') @ConsoleApplication.command('list online contacts')
def command_list(self): def command_list(self):
for backend, contact in self.weboob.do_caps(ICapContact, 'iter_contacts', status=Contact.STATUS_ONLINE): for backend, contact in self.weboob.do('iter_contacts', status=Contact.STATUS_ONLINE, caps=ICapContact):
self.format(contact, backend.name) self.format(contact, backend.name)
@ConsoleApplication.command('get messages') @ConsoleApplication.command('get messages')

View file

@ -60,7 +60,7 @@ class HaveSex(PromptApplication):
_id, backend_name = self.parse_id(id) _id, backend_name = self.parse_id(id)
found = 0 found = 0
for backend, profile in self.weboob.do_backends(backend_name, 'get_profile', _id): for backend, profile in self.weboob.do('get_profile', _id, backends=backend_name):
if profile: if profile:
print profile.get_profile_text().encode('utf-8') print profile.get_profile_text().encode('utf-8')
found = 1 found = 1

View file

@ -74,10 +74,7 @@ class MessagesManager(QWidget):
self.process = QtDo(self.weboob, self._gotMessage) self.process = QtDo(self.weboob, self._gotMessage)
if self.backend: self.process.do(self.backend.name, command, backends=self.backend, caps=ICapMessages)
self.process.do_backends(self.backend.name, command)
else:
self.process.do_caps(ICapMessages, command)
def _gotMessage(self, backend, message): def _gotMessage(self, backend, message):
if message is None: if message is None:

View file

@ -76,7 +76,7 @@ class ContactThread(QWidget):
command = 'iter_messages' command = 'iter_messages'
self.process_msg = QtDo(self.weboob, self.gotMessage) self.process_msg = QtDo(self.weboob, self.gotMessage)
self.process_msg.do_backends(self.contact.backend, command, thread=self.contact.id) self.process_msg.do(command, thread=self.contact.id, backends=self.contact.backend)
def gotMessage(self, backend, message): def gotMessage(self, backend, message):
if not message: if not message:
@ -101,7 +101,7 @@ class ContactThread(QWidget):
self.ui.textEdit.setEnabled(False) self.ui.textEdit.setEnabled(False)
self.ui.sendButton.setEnabled(False) self.ui.sendButton.setEnabled(False)
self.process_reply = QtDo(self.weboob, self._postReply_cb, self._postReply_eb) self.process_reply = QtDo(self.weboob, self._postReply_cb, self._postReply_eb)
self.process_reply.do_backends(self.contact.backend, 'post_reply', self.contact.id, 0, '', text) self.process_reply.do('post_reply', self.contact.id, 0, '', text, backends=self.contact.backend)
def _postReply_cb(self, backend, ignored): def _postReply_cb(self, backend, ignored):
self.ui.textEdit.clear() self.ui.textEdit.clear()
@ -128,6 +128,8 @@ class ContactProfile(QWidget):
self.contact = contact self.contact = contact
self.ui.nicknameLabel.setText('<h1>%s</h1>' % contact.name) self.ui.nicknameLabel.setText('<h1>%s</h1>' % contact.name)
self.ui.statusLabel.setText('%s' % contact.status_msg)
self.ui.descriptionEdit.setText('<h1>Description</h1><p>%s</p>' % contact.summary)
class IGroup(object): class IGroup(object):
def __init__(self, weboob, id, name): def __init__(self, weboob, id, name):
@ -148,7 +150,7 @@ class MetaGroup(IGroup):
status = Contact.STATUS_ALL status = Contact.STATUS_ALL
self.process = QtDo(self.weboob, lambda b, d: self.cb(cb, b, d)) self.process = QtDo(self.weboob, lambda b, d: self.cb(cb, b, d))
self.process.do_caps(ICapContact, 'iter_contacts', status) self.process.do('iter_contacts', status, caps=ICapContact)
def cb(self, cb, backend, contact): def cb(self, cb, backend, contact):
if contact: if contact:
@ -233,6 +235,9 @@ class ContactsWidget(QWidget):
self.contact = current.data(Qt.UserRole).toPyObject() self.contact = current.data(Qt.UserRole).toPyObject()
if not self.contact:
return
self.ui.tabWidget.addTab(ContactProfile(self.weboob, self.contact), self.tr('Profile')) self.ui.tabWidget.addTab(ContactProfile(self.weboob, self.contact), self.tr('Profile'))
if self.contact.backend.has_caps(ICapMessages): if self.contact.backend.has_caps(ICapMessages):
self.ui.tabWidget.addTab(ContactThread(self.weboob, self.contact), self.tr('Messages')) self.ui.tabWidget.addTab(ContactThread(self.weboob, self.contact), self.tr('Messages'))

View file

@ -48,6 +48,7 @@ class MainWindow(QtMainWindow):
self.ui.tabWidget.addTab(MessagesManager(self.weboob), self.tr('Messages')) self.ui.tabWidget.addTab(MessagesManager(self.weboob), self.tr('Messages'))
self.ui.tabWidget.addTab(ContactsWidget(self.weboob), self.tr('Contacts')) self.ui.tabWidget.addTab(ContactsWidget(self.weboob), self.tr('Contacts'))
self.ui.tabWidget.addTab(QWidget(), self.tr('Calendar')) self.ui.tabWidget.addTab(QWidget(), self.tr('Calendar'))
self.ui.tabWidget.addTab(QWidget(), self.tr('Optimizations'))
self.connect(self.ui.actionBackends, SIGNAL("triggered()"), self.backendsConfig) self.connect(self.ui.actionBackends, SIGNAL("triggered()"), self.backendsConfig)
self.connect(self.ui.tabWidget, SIGNAL('currentChanged(int)'), self.tabChanged) self.connect(self.ui.tabWidget, SIGNAL('currentChanged(int)'), self.tabChanged)

View file

@ -18,7 +18,6 @@
from __future__ import with_statement from __future__ import with_statement
from PyQt4.QtGui import QWidget, QHBoxLayout, QVBoxLayout, QFrame, QLabel, QImage, QPixmap from PyQt4.QtGui import QWidget, QHBoxLayout, QVBoxLayout, QFrame, QLabel, QImage, QPixmap
from PyQt4.QtCore import SIGNAL
from weboob.capabilities.dating import StatusField from weboob.capabilities.dating import StatusField
from weboob.tools.application.qt import QtDo from weboob.tools.application.qt import QtDo
@ -60,7 +59,7 @@ class Account(QFrame):
self.process = QtDo(self.weboob, self.updateStats_cb) self.process = QtDo(self.weboob, self.updateStats_cb)
self.process.body = u'' self.process.body = u''
self.process.in_p = False self.process.in_p = False
self.process.do_backends(self.backend, 'get_status') self.process.do('get_status', backends=self.backend)
def updateStats_cb(self, backend, field): def updateStats_cb(self, backend, field):
if not field: if not field:

View file

@ -43,7 +43,7 @@
</widget> </widget>
</item> </item>
<item> <item>
<widget class="QFrame" name="frame_3"> <widget class="QFrame" name="headFrame">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred"> <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch> <horstretch>0</horstretch>
@ -78,7 +78,7 @@
</widget> </widget>
</item> </item>
<item> <item>
<widget class="QFrame" name="frame_2"> <widget class="QFrame" name="bodyFrame">
<property name="frameShape"> <property name="frameShape">
<enum>QFrame::NoFrame</enum> <enum>QFrame::NoFrame</enum>
</property> </property>
@ -87,7 +87,11 @@
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout"> <layout class="QHBoxLayout" name="horizontalLayout">
<item> <item>
<widget class="QTextEdit" name="textEdit"/> <widget class="QTextEdit" name="descriptionEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item> </item>
</layout> </layout>
</widget> </widget>

View file

@ -80,10 +80,7 @@ class MainWindow(QtMainWindow):
backend_name = str(self.ui.backendEdit.itemData(self.ui.backendEdit.currentIndex()).toString()) backend_name = str(self.ui.backendEdit.itemData(self.ui.backendEdit.currentIndex()).toString())
self.process = QtDo(self.weboob, self.addVideo) self.process = QtDo(self.weboob, self.addVideo)
if backend_name: self.process.do('iter_search_results', pattern, self.ui.sortbyEdit.currentIndex(), nsfw=True, backends=backend_name)
self.process.do_backends(backend_name, 'iter_search_results', pattern, self.ui.sortbyEdit.currentIndex(), nsfw=True)
else:
self.process.do('iter_search_results', pattern, self.ui.sortbyEdit.currentIndex(), nsfw=True)
def addVideo(self, backend, video): def addVideo(self, backend, video):
if not backend: if not backend:

View file

@ -40,7 +40,7 @@ class Weboorrents(ConsoleApplication):
_id, backend_name = self.parse_id(id) _id, backend_name = self.parse_id(id)
found = 0 found = 0
for backend, torrent in self.weboob.do_backends(backend_name, 'get_torrent', _id): for backend, torrent in self.weboob.do('get_torrent', _id, backends=backend_name):
if torrent: if torrent:
self.format(torrent, backend.name) self.format(torrent, backend.name)
found = 1 found = 1
@ -52,7 +52,7 @@ class Weboorrents(ConsoleApplication):
def command_getfile(self, id, dest): def command_getfile(self, id, dest):
_id, backend_name = self.parse_id(id) _id, backend_name = self.parse_id(id)
for backend, buf in self.weboob.do_backends(backend_name, 'get_torrent_file', _id): for backend, buf in self.weboob.do('get_torrent_file', _id, backends=backend_name):
if buf: if buf:
if dest == '-': if dest == '-':
print buf print buf

View file

@ -54,11 +54,12 @@ class ICapDating(ICap):
OPTIM_PROFILE_WALKER = None OPTIM_PROFILE_WALKER = None
OPTIM_VISIBILITY = None OPTIM_VISIBILITY = None
OPTIM_PRIORITY_CONNECTION = None
def init_optimizations(self): def init_optimizations(self):
raise NotImplementedError() raise NotImplementedError()
def get_optim(self, optim): def _get_optim(self, optim):
optim = optim.upper() optim = optim.upper()
if not hasattr(self, 'OPTIM_%s' % optim): if not hasattr(self, 'OPTIM_%s' % optim):
raise OptimizationNotFound() raise OptimizationNotFound()
@ -66,15 +67,18 @@ class ICapDating(ICap):
return getattr(self, 'OPTIM_%s' % optim) return getattr(self, 'OPTIM_%s' % optim)
def start_optimization(self, optim): def start_optimization(self, optim):
optim = self.get_optim(optim) optim = self._get_optim(optim)
if not optim: if not optim:
return False return False
return optim.start() return optim.start()
def stop_optimization(self, optim): def stop_optimization(self, optim):
optim = self.get_optim(optim) optim = self._get_optim(optim)
if not optim: if not optim:
return False return False
return optim.stop() return optim.stop()
def list_optimizations(self):
pass

View file

@ -108,43 +108,30 @@ class Weboob(object):
**kwargs. **kwargs.
@param function backend's method name, or callable object @param function backend's method name, or callable object
@param backends list of backends to iterate on
@param caps iterate on backends with this caps
@return an iterator of results @return an iterator of results
""" """
backends = list(self.iter_backends()) backends = self.backend_instances.values()
return BackendsCall(backends, function, *args, **kwargs) if 'backends' in kwargs and kwargs['backends']:
if isinstance(kwargs['backends'], BaseBackend):
backends = [kwargs.pop('backends')]
elif isinstance(kwargs['backends'], (str,unicode)) and kwargs['backends']:
backends = self.backend_instances[kwargs.pop('backends')]
elif isinstance(kwargs['backends'], (list,tuple)):
backends = []
for backend in kwargs.pop('backends'):
if isinstance(backend, (str,unicode)):
try:
backends.append(self.backend_instances[backend])
except ValueError:
pass
else:
backends.append(backend)
def do_caps(self, caps, function, *args, **kwargs): if 'caps' in kwargs:
""" backends = [backend for backend in backends if backend.has_caps(kwargs.pop('caps'))]
Do calls on loaded backends with the specified capabilities, in
separated threads.
See also documentation of the 'do' method.
@param caps list of caps or cap to select backends
@param function backend's method name, or callable object
@return an iterator of results
"""
backends = list(self.iter_backends(caps))
return BackendsCall(backends, function, *args, **kwargs)
def do_backends(self, backends, function, *args, **kwargs):
if backends is None:
backends = list(self.iter_backends())
elif isinstance(backends, BaseBackend):
backends = [backends]
elif isinstance(backends, (str,unicode)):
backends = [backend for backend in self.iter_backends() if backend.name == backends]
elif isinstance(backends, (list,tuple)):
old_backends = backends
backends = []
for backend in old_backends:
if isinstance(backend, (str,unicode)):
try:
backends.append(self.backends[self.backends.index(backend)])
except ValueError:
pass
else:
backends.append(backend)
return BackendsCall(backends, function, *args, **kwargs) return BackendsCall(backends, function, *args, **kwargs)
def schedule(self, interval, function, *args): def schedule(self, interval, function, *args):

View file

@ -284,33 +284,3 @@ class ConsoleApplication(BaseApplication):
except Exception, e: except Exception, e:
logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e)) logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
yield backend, result yield backend, result
def do_caps(self, caps, function, *args, **kwargs):
"""
Call Weboob.do_caps(), after having filled the yielded object, if selected fields are given by user.
"""
for i, (backend, result) in enumerate(self.weboob.do_caps(caps, function, *args, **kwargs)):
if self.options.count and i == self.options.count:
break
fields = set(self.selected_fields) - set('*')
if fields:
try:
backend.browser.fillobj(result, fields)
except Exception, e:
logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
yield backend, result
def do_backends(self, backends, function, *args, **kwargs):
"""
Call Weboob.do_backends(), after having filled the yielded object, if selected fields are given by user.
"""
for i, (backend, result) in enumerate(self.weboob.do_backends(backends, function, *args, **kwargs)):
if self.options.count and i == self.options.count:
break
fields = set(self.selected_fields) - set('*')
if fields:
try:
backend.browser.fillobj(result, fields)
except Exception, e:
logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
yield backend, result

View file

@ -99,23 +99,9 @@ class QtDo(QObject):
self.connect(self, SIGNAL('cb'), self.local_cb) self.connect(self, SIGNAL('cb'), self.local_cb)
self.connect(self, SIGNAL('eb'), self.local_eb) self.connect(self, SIGNAL('eb'), self.local_eb)
def run_thread(func):
def inner(self, *args, **kwargs):
self.process = func(self, *args, **kwargs)
self.process.callback_thread(self.thread_cb, self.thread_eb)
return inner
@run_thread
def do(self, *args, **kwargs): def do(self, *args, **kwargs):
return self.weboob.do(*args, **kwargs) self.process = self.weboob.do(*args, **kwargs)
self.process.callback_thread(self.thread_cb, self.thread_eb)
@run_thread
def do_caps(self, *args, **kwargs):
return self.weboob.do_caps(*args, **kwargs)
@run_thread
def do_backends(self, *args, **kwargs):
return self.weboob.do_backends(*args, **kwargs)
def default_eb(self, backend, error, backtrace): def default_eb(self, backend, error, backtrace):
# TODO display a messagebox # TODO display a messagebox