Code style fixes, mostly whitespace

This commit is contained in:
Laurent Bachelier 2013-08-04 20:00:19 +02:00
commit 23a71d847b
12 changed files with 84 additions and 73 deletions

View file

@ -32,6 +32,7 @@ from .collection import ArteLiveCollection
__all__ = ['IndexPage', 'VideoPage', 'ArteLivePage', 'ArteLiveCategorieVideoPage', 'ArteLiveVideoPage'] __all__ = ['IndexPage', 'VideoPage', 'ArteLivePage', 'ArteLiveCategorieVideoPage', 'ArteLiveVideoPage']
class ArteLiveVideoPage(BasePage): class ArteLiveVideoPage(BasePage):
def get_video(self, video=None, lang='fr', quality='hd'): def get_video(self, video=None, lang='fr', quality='hd'):
if not video: if not video:
@ -48,6 +49,7 @@ class ArteLiveVideoPage(BasePage):
video.url = urls.popitem()[1] video.url = urls.popitem()[1]
return video return video
class ArteLiveCategorieVideoPage(BasePage): class ArteLiveCategorieVideoPage(BasePage):
def iter_videos(self, lang='fr'): def iter_videos(self, lang='fr'):
videos = list() videos = list()
@ -79,7 +81,7 @@ class ArteLiveCategorieVideoPage(BasePage):
en = re.compile("<enclosure.*?/event/.*?/(.*?)-.*?/>", re.DOTALL) en = re.compile("<enclosure.*?/event/.*?/(.*?)-.*?/>", re.DOTALL)
pix = re.compile("(?<=<enclosure url=\")(.*?)(?=\" type=\"image/)", re.DOTALL) pix = re.compile("(?<=<enclosure url=\")(.*?)(?=\" type=\"image/)", re.DOTALL)
try: try:
ele['link'] = lk.search(chain).group(0) ele['link'] = lk.search(chain).group(0)
except: except:
return None return None
try: try:
@ -98,8 +100,8 @@ class ArteLiveCategorieVideoPage(BasePage):
ele['date'] = "No date" ele['date'] = "No date"
try: try:
s = (pt.search(chain).group(0)) s = (pt.search(chain).group(0))
s = HTMLParser.HTMLParser().unescape(s); s = HTMLParser.HTMLParser().unescape(s)
ele['pitch'] = HTMLParser.HTMLParser().unescape(s); ele['pitch'] = HTMLParser.HTMLParser().unescape(s)
except: except:
ele['pitch'] = "No description" ele['pitch'] = "No description"
try: try:
@ -113,18 +115,20 @@ class ArteLiveCategorieVideoPage(BasePage):
ele['pict'] = None ele['pict'] = None
return ele return ele
class ArteLivePage(BasePage): class ArteLivePage(BasePage):
def iter_resources(self): def iter_resources(self):
items = list() items = list()
for el in self.document.xpath('//ul[@id="categoryArray"]/li'): for el in self.document.xpath('//ul[@id="categoryArray"]/li'):
m = re.match(r'http://liveweb.arte.tv/*', el.find('a').attrib['href']) m = re.match(r'http://liveweb.arte.tv/*', el.find('a').attrib['href'])
if m: if m:
url = u'%s' %el.find('a').attrib['href'] url = u'%s' % el.find('a').attrib['href']
_id = url.split('/')[-2:-1][0] _id = url.split('/')[-2:-1][0]
item = ArteLiveCollection([u'live', u'%s'%_id], u'%s' %(el.find('a').text)) item = ArteLiveCollection([u'live', u'%s' % _id], u'%s' % (el.find('a').text))
items.append(item) items.append(item)
return items return items
class IndexPage(BasePage): class IndexPage(BasePage):
def iter_videos(self): def iter_videos(self):
videos = self.document.getroot().cssselect("div[class=video]") videos = self.document.getroot().cssselect("div[class=video]")

View file

@ -32,7 +32,7 @@ __all__ = ['LoginPage', 'IndexPage', 'AccountsPage', 'TransactionsPage', 'Unavai
class WikipediaARC4(object): class WikipediaARC4(object):
def __init__(self, key = None): def __init__(self, key=None):
self.state = range(256) self.state = range(256)
self.x = self.y = 0 self.x = self.y = 0
@ -54,6 +54,7 @@ class WikipediaARC4(object):
output[i] = chr((ord(input[i]) ^ self.state[(self.state[self.x] + self.state[self.y]) & 0xFF])) output[i] = chr((ord(input[i]) ^ self.state[(self.state[self.x] + self.state[self.y]) & 0xFF]))
return ''.join(output) return ''.join(output)
class RedirectPage(BasePage): class RedirectPage(BasePage):
""" """
var i = 'lyhrnu551jo42yfzx0jm0sqk'; var i = 'lyhrnu551jo42yfzx0jm0sqk';
@ -129,6 +130,7 @@ class RedirectPage(BasePage):
if redirect_url is not None: if redirect_url is not None:
self.browser.location(self.browser.request_class(self.browser.absurl(redirect_url), None, {'Referer': self.url})) self.browser.location(self.browser.request_class(self.browser.absurl(redirect_url), None, {'Referer': self.url}))
class UnavailablePage(BasePage): class UnavailablePage(BasePage):
def on_loaded(self): def on_loaded(self):
try: try:
@ -290,6 +292,7 @@ class TransactionsPage(BasePage):
COL_VALUE_DATE = 4 COL_VALUE_DATE = 4
COL_DEBIT = -2 COL_DEBIT = -2
COL_CREDIT = -1 COL_CREDIT = -1
def get_history(self): def get_history(self):
for tr in self.document.xpath('//table[@id="tbl1"]/tbody/tr'): for tr in self.document.xpath('//table[@id="tbl1"]/tbody/tr'):
tds = tr.findall('td') tds = tr.findall('td')

View file

@ -48,8 +48,8 @@ class Boursorama(BaseBrowser):
'.*/date_anniversaire.phtml.*': UpdateInfoPage, '.*/date_anniversaire.phtml.*': UpdateInfoPage,
} }
def __init__(self, device="weboob", enable_twofactors=False def __init__(self, device="weboob", enable_twofactors=False,
, *args, **kwargs): *args, **kwargs):
self.device = device self.device = device
self.enable_twofactors = enable_twofactors self.enable_twofactors = enable_twofactors
BaseBrowser.__init__(self, *args, **kwargs) BaseBrowser.__init__(self, *args, **kwargs)
@ -69,9 +69,9 @@ class Boursorama(BaseBrowser):
self.page.authenticate(self.device) self.page.authenticate(self.device)
else: else:
raise BrowserIncorrectAuthenticationCode( raise BrowserIncorrectAuthenticationCode(
"""Boursorama - activate the two factor authentication in boursorama config."""\ """Boursorama - activate the two factor authentication in boursorama config."""
""" You will receive SMS code but are limited in request per day (around 15)""" """ You will receive SMS code but are limited in request per day (around 15)"""
) )
def login_mobile(self): def login_mobile(self):
assert isinstance(self.username, basestring) assert isinstance(self.username, basestring)

View file

@ -125,6 +125,3 @@ class AuthenticationPage(BasePage):
def print_cookies(self): def print_cookies(self):
for c in self.browser._ua_handlers["_cookies"].cookiejar: for c in self.browser._ua_handlers["_cookies"].cookiejar:
print "%s : %s" % (c.name, c.value) print "%s : %s" % (c.name, c.value)

View file

@ -94,7 +94,7 @@ class AccountsPage(CDNBasePage):
for line in data: for line in data:
a = Account() a = Account()
a.id = line[self.COL_ID].replace(' ','') a.id = line[self.COL_ID].replace(' ', '')
fp = StringIO(unicode(line[self.COL_LABEL]).encode(self.browser.ENCODING)) fp = StringIO(unicode(line[self.COL_LABEL]).encode(self.browser.ENCODING))
a.label = self.parser.tocleanstring(self.parser.parse(fp, self.browser.ENCODING).xpath('//div[@class="libelleCompteTDB"]')[0]) a.label = self.parser.tocleanstring(self.parser.parse(fp, self.browser.ENCODING).xpath('//div[@class="libelleCompteTDB"]')[0])
a.balance = Decimal(FrenchTransaction.clean_amount(line[self.COL_BALANCE])) a.balance = Decimal(FrenchTransaction.clean_amount(line[self.COL_BALANCE]))
@ -128,6 +128,7 @@ class ProAccountsPage(AccountsPage):
COL_BALANCE = 1 COL_BALANCE = 1
ARGS = ['Banque', 'Agence', 'classement', 'Serie', 'SSCompte', 'Devise', 'CodeDeviseCCB', 'LibelleCompte', 'IntituleCompte', 'Indiceclassement', 'IndiceCompte', 'NomClassement'] ARGS = ['Banque', 'Agence', 'classement', 'Serie', 'SSCompte', 'Devise', 'CodeDeviseCCB', 'LibelleCompte', 'IntituleCompte', 'Indiceclassement', 'IndiceCompte', 'NomClassement']
def params_from_js(self, text): def params_from_js(self, text):
l = [] l = []
for sub in re.findall("'([^']*)'", text): for sub in re.findall("'([^']*)'", text):
@ -141,7 +142,6 @@ class ProAccountsPage(AccountsPage):
return url, args return url, args
def get_list(self): def get_list(self):
for tr in self.document.xpath('//table[@class="datas"]//tr'): for tr in self.document.xpath('//table[@class="datas"]//tr'):
if tr.attrib.get('class', '') == 'entete': if tr.attrib.get('class', '') == 'entete':
@ -255,6 +255,7 @@ class TransactionsPage(CDNBasePage):
yield t yield t
class ProTransactionsPage(TransactionsPage): class ProTransactionsPage(TransactionsPage):
def get_next_args(self, args): def get_next_args(self, args):
txt = self.get_from_js('myPage.setPiedPage(oNavSuivantPrec_1(', ')') txt = self.get_from_js('myPage.setPiedPage(oNavSuivantPrec_1(', ')')

View file

@ -23,54 +23,53 @@ import time
import re import re
from weboob.tools.browser import BasePage, BrowserUnavailable from weboob.tools.browser import BasePage, BrowserUnavailable
from weboob.tools.captcha.virtkeyboard import VirtKeyboard,VirtKeyboardError from weboob.tools.captcha.virtkeyboard import VirtKeyboard, VirtKeyboardError
__all__ = ['LoginPage', 'ConfirmPage', 'InfoMessagePage'] __all__ = ['LoginPage', 'ConfirmPage', 'InfoMessagePage']
class HelloBankVirtKeyboard(VirtKeyboard): class HelloBankVirtKeyboard(VirtKeyboard):
symbols={'0':'4d1e060efb694ee60e4bd062d800401c', symbols = {'0': '4d1e060efb694ee60e4bd062d800401c',
'1':'509134b5c09980e282cdd5867815e9e3', '1': '509134b5c09980e282cdd5867815e9e3',
'2':'4cd09c9c44405e00b12e0371e2f972ae', '2': '4cd09c9c44405e00b12e0371e2f972ae',
'3':'227d854efc5623292eda4ca2f9bfc4d7', '3': '227d854efc5623292eda4ca2f9bfc4d7',
'4':'be8d23e7f5fce646193b7b520ff80443', '4': 'be8d23e7f5fce646193b7b520ff80443',
'5':'5fe450b35c946c3a983f1df6e5b41fd1', '5': '5fe450b35c946c3a983f1df6e5b41fd1',
'6':'113a6f63714f5094c7f0b25caaa66f78', '6': '113a6f63714f5094c7f0b25caaa66f78',
'7':'de0e93ba880a8a052aea79237f08f3f8', '7': 'de0e93ba880a8a052aea79237f08f3f8',
'8':'3d70474c05c240b606556c89baca0568', '8': '3d70474c05c240b606556c89baca0568',
'9':'040954a5e5e93ec2fb03ac0cfe592ac2' '9': '040954a5e5e93ec2fb03ac0cfe592ac2'
} }
url = "/NSImgBDGrille?timestamp=%d"
url="/NSImgBDGrille?timestamp=%d" color = 17
color=17 def __init__(self, basepage):
def __init__(self,basepage):
coords = {} coords = {}
coords["01"] = (31,28,49,49) coords["01"] = (31, 28, 49, 49)
coords["02"] = (108,28,126,49) coords["02"] = (108, 28, 126, 49)
coords["03"] = (185,28,203,49) coords["03"] = (185, 28, 203, 49)
coords["04"] = (262,28,280,49) coords["04"] = (262, 28, 280, 49)
coords["05"] = (339,28,357,49) coords["05"] = (339, 28, 357, 49)
coords["06"] = (31,100,49,121) coords["06"] = (31, 100, 49, 121)
coords["07"] = (108,100,126,121) coords["07"] = (108, 100, 126, 121)
coords["08"] = (185,100,203,121) coords["08"] = (185, 100, 203, 121)
coords["09"] = (262,100,280,121) coords["09"] = (262, 100, 280, 121)
coords["10"] = (339,100,357,121) coords["10"] = (339, 100, 357, 121)
VirtKeyboard.__init__(self,basepage.browser.openurl(self.url % time.time()),coords,self.color) VirtKeyboard.__init__(self, basepage.browser.openurl(self.url % time.time()), coords, self.color)
self.check_symbols(self.symbols,basepage.browser.responses_dirname) self.check_symbols(self.symbols, basepage.browser.responses_dirname)
def get_symbol_code(self,md5sum): def get_symbol_code(self, md5sum):
code=VirtKeyboard.get_symbol_code(self,md5sum) code = VirtKeyboard.get_symbol_code(self, md5sum)
return code return code
def get_string_code(self,string): def get_string_code(self, string):
code='' code = ''
for c in string: for c in string:
code+=self.get_symbol_code(self.symbols[c]) code += self.get_symbol_code(self.symbols[c])
return code return code
@ -85,9 +84,9 @@ class LoginPage(BasePage):
def login(self, login, password): def login(self, login, password):
try: try:
vk=HelloBankVirtKeyboard(self) vk = HelloBankVirtKeyboard(self)
except VirtKeyboardError as err: except VirtKeyboardError as err:
self.logger.error("Error: %s"%err) self.logger.error("Error: %s" % err)
return False return False
self.browser.select_form('logincanalnet') self.browser.select_form('logincanalnet')
@ -114,4 +113,3 @@ class ConfirmPage(BasePage):
class InfoMessagePage(BasePage): class InfoMessagePage(BasePage):
def on_loaded(self): def on_loaded(self):
pass pass

View file

@ -88,7 +88,7 @@ class TransactionsFormatter(IFormatter):
else: else:
try: try:
_type = self.TYPES[obj.type] _type = self.TYPES[obj.type]
except (IndexError,AttributeError): except (IndexError, AttributeError):
_type = '' _type = ''
label = obj.label label = obj.label
@ -115,6 +115,7 @@ class TransferFormatter(IFormatter):
result += u'Reason: %s\n' % obj.reason result += u'Reason: %s\n' % obj.reason
return result return result
class InvestmentFormatter(IFormatter): class InvestmentFormatter(IFormatter):
MANDATORY_FIELDS = ('label', 'quantity', 'unitvalue') MANDATORY_FIELDS = ('label', 'quantity', 'unitvalue')
@ -134,7 +135,7 @@ class InvestmentFormatter(IFormatter):
self.tot_diff += diff self.tot_diff += diff
self.tot_valuation += obj.valuation self.tot_valuation += obj.valuation
return u' %s %s %s %s %s %s' %\ return u' %s %s %s %s %s %s' % \
(self.colored('%-30s' % label[:30], 'red'), (self.colored('%-30s' % label[:30], 'red'),
self.colored('%-10s' % obj.code[:8], 'yellow') if not empty(obj.code) else ' ' * 10, self.colored('%-10s' % obj.code[:8], 'yellow') if not empty(obj.code) else ' ' * 10,
self.colored('%6d' % obj.quantity, 'yellow'), self.colored('%6d' % obj.quantity, 'yellow'),
@ -145,7 +146,7 @@ class InvestmentFormatter(IFormatter):
def flush(self): def flush(self):
self.output('-------------------------------+--------+----------+-----------+-----------+--------') self.output('-------------------------------+--------+----------+-----------+-----------+--------')
self.output(u' Total %s %s' %\ self.output(u' Total %s %s' %
(self.colored('%8.2f' % self.tot_valuation, 'yellow'), (self.colored('%8.2f' % self.tot_valuation, 'yellow'),
self.colored('%8.2f' % self.tot_diff, 'green' if self.tot_diff >=0 else 'red') self.colored('%8.2f' % self.tot_diff, 'green' if self.tot_diff >=0 else 'red')
)) ))

View file

@ -17,7 +17,9 @@
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>. # along with weboob. If not, see <http://www.gnu.org/licenses/>.
import urllib, sys, codecs import urllib
import sys
import codecs
from PyQt4.QtCore import Qt, SIGNAL from PyQt4.QtCore import Qt, SIGNAL
from PyQt4.QtGui import QFrame, QImage, QPixmap, QFileDialog from PyQt4.QtGui import QFrame, QImage, QPixmap, QFileDialog
@ -85,11 +87,11 @@ class Recipe(QFrame):
if not empty(self.recipe.picture_url): if not empty(self.recipe.picture_url):
data = urllib.urlopen(self.recipe.picture_url).read() data = urllib.urlopen(self.recipe.picture_url).read()
img = QImage.fromData(data) img = QImage.fromData(data)
self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToWidth(250,Qt.SmoothTransformation)) self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToWidth(250, Qt.SmoothTransformation))
def export(self): def export(self):
fileDial = QFileDialog(self, 'Export "%s" recipe' % fileDial = QFileDialog(self, 'Export "%s" recipe' %
self.recipe.title, '%s.kreml' % self.recipe.title.replace('/',','), 'Krecipe file (*.kreml);;all files (*)') self.recipe.title, '%s.kreml' % self.recipe.title.replace('/', ','), 'Krecipe file (*.kreml);;all files (*)')
fileDial.setAcceptMode(QFileDialog.AcceptSave) fileDial.setAcceptMode(QFileDialog.AcceptSave)
fileDial.setLabelText(QFileDialog.Accept, 'Export recipe') fileDial.setLabelText(QFileDialog.Accept, 'Export recipe')
fileDial.setLabelText(QFileDialog.FileName, 'Recipe file name') fileDial.setLabelText(QFileDialog.FileName, 'Recipe file name')

View file

@ -26,18 +26,20 @@ from weboob.capabilities.job import ICapJob
from .ui.main_window_ui import Ui_MainWindow from .ui.main_window_ui import Ui_MainWindow
class JobListWidgetItem(QListWidgetItem): class JobListWidgetItem(QListWidgetItem):
def __init__(self, job, *args, **kwargs): def __init__(self, job, *args, **kwargs):
QListWidgetItem.__init__(self, *args, **kwargs) QListWidgetItem.__init__(self, *args, **kwargs)
self.job = job self.job = job
def __lt__(self, other): def __lt__(self, other):
return self.job.publication_date < other.job.publication_date return self.job.publication_date < other.job.publication_date
def setAttrs(self, storage): def setAttrs(self, storage):
text = u'%s - %s' % (self.job.backend, self.job.title) text = u'%s - %s' % (self.job.backend, self.job.title)
self.setText(text) self.setText(text)
class MainWindow(QtMainWindow): class MainWindow(QtMainWindow):
def __init__(self, config, storage, weboob, parent=None): def __init__(self, config, storage, weboob, parent=None):
QtMainWindow.__init__(self, parent) QtMainWindow.__init__(self, parent)
@ -129,4 +131,3 @@ class MainWindow(QtMainWindow):
self.ui.jobFrame.show() self.ui.jobFrame.show()
else: else:
self.ui.jobFrame.hide() self.ui.jobFrame.hide()

View file

@ -18,7 +18,6 @@
# along with weboob. If not, see <http://www.gnu.org/licenses/>. # along with weboob. If not, see <http://www.gnu.org/licenses/>.
import sys import sys
from weboob.capabilities.torrent import ICapTorrent, MagnetOnly from weboob.capabilities.torrent import ICapTorrent, MagnetOnly
@ -56,7 +55,7 @@ class TorrentInfoFormatter(IFormatter):
for f in obj.files: for f in obj.files:
result += ' * %s\n' % f result += ' * %s\n' % f
result += '\n%sDescription%s\n' % (self.BOLD, self.NC) result += '\n%sDescription%s\n' % (self.BOLD, self.NC)
result += '%s'%obj.description result += '%s' % obj.description
return result return result
@ -71,6 +70,7 @@ class TorrentListFormatter(PrettyFormatter):
(5, 'green', None), (5, 'green', None),
(10, 'green', 'bold'), (10, 'green', 'bold'),
) )
def _get_color(self, nb): def _get_color(self, nb):
if empty(nb): if empty(nb):
return self.colored('N/A', 'red') return self.colored('N/A', 'red')
@ -115,7 +115,7 @@ class Weboorrents(ReplApplication):
Get information about a torrent. Get information about a torrent.
""" """
torrent = self.get_object(id, 'get_torrent', ('description','files')) torrent = self.get_object(id, 'get_torrent', ('description', 'files'))
if not torrent: if not torrent:
print >>sys.stderr, 'Torrent not found: %s' % id print >>sys.stderr, 'Torrent not found: %s' % id
return 3 return 3

View file

@ -19,8 +19,12 @@
from .base import IBaseCap, CapBaseObject, StringField, IntField, Field, empty from .base import IBaseCap, CapBaseObject, StringField, IntField, Field, empty
import lxml.etree as ET import lxml.etree as ET
import base64, re, urllib
import base64
import re
import urllib
__all__ = ['Recipe', 'ICapRecipe'] __all__ = ['Recipe', 'ICapRecipe']
@ -42,6 +46,7 @@ class Comment():
result += 'comment: %s' % self.text result += 'comment: %s' % self.text
return result return result
class Recipe(CapBaseObject): class Recipe(CapBaseObject):
""" """
Recipe object. Recipe object.
@ -108,7 +113,7 @@ class Recipe(CapBaseObject):
datab64 = base64.encodestring(data)[:-1] datab64 = base64.encodestring(data)[:-1]
pictures = ET.SubElement(desc, 'pictures') pictures = ET.SubElement(desc, 'pictures')
pic = ET.SubElement(pictures, 'pic', {'format' : 'JPEG', 'id' : '1'}) pic = ET.SubElement(pictures, 'pic', {'format': 'JPEG', 'id': '1'})
pic.text = ET.CDATA(datab64) pic.text = ET.CDATA(datab64)
if not empty(self.ingredients): if not empty(self.ingredients):

View file

@ -18,8 +18,6 @@
# along with weboob. If not, see <http://www.gnu.org/licenses/>. # along with weboob. If not, see <http://www.gnu.org/licenses/>.
import os import os
import shutil import shutil
@ -39,6 +37,7 @@ __all__ = ['Weboob']
class VersionsMismatchError(ConfigError): class VersionsMismatchError(ConfigError):
pass pass
class Weboob(object): class Weboob(object):
""" """
The main class of Weboob, used to manage backends and call methods. The main class of Weboob, used to manage backends and call methods.