This commit is contained in:
Andreas Preikschat 2011-01-12 17:45:51 +01:00
commit 28bcaf4313
10 changed files with 134 additions and 122 deletions

View File

@ -230,7 +230,7 @@ def open(filename):
return _open(filename)
def _fix_addersses(**kwargs):
def _fix_addresses(**kwargs):
for headername in (u'address', u'to', u'cc', u'bcc'):
try:
headervalue = kwargs[headername]
@ -260,7 +260,7 @@ def mailto_format(**kwargs):
"""
# @TODO: implement utf8 option
kwargs = _fix_addersses(**kwargs)
kwargs = _fix_addresses(**kwargs)
parts = []
for headername in (u'to', u'cc', u'bcc', u'subject', u'body', u'attach'):
if kwargs.has_key(headername):

View File

@ -59,7 +59,7 @@ class DisplayTagTab(SettingsTab):
# cPickle only accepts str not unicode strings
user_expands_string = str(unicode(user_expands).encode(u'utf8'))
if user_expands_string:
user_tags = cPickle.loads(user_expand_string)
user_tags = cPickle.loads(user_expands_string)
# If we have some user ones added them as well
for t in user_tags:
DisplayTags.add_html_tag(t)

View File

@ -371,9 +371,9 @@ class ServiceManager(QtGui.QWidget):
self.saveFile()
fileName = unicode(QtGui.QFileDialog.getOpenFileName(self.mainwindow,
translate('OpenLP.ServiceManager', 'Open File'),
SettingsManager.get_last_dir(self.mainwindow.serviceSettingsSection),
translate('OpenLP.ServiceManager',
'OpenLP Service Files (*.osz)')))
SettingsManager.get_last_dir(
self.mainwindow.serviceSettingsSection),
translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz)')))
if not fileName:
return False
SettingsManager.set_last_dir(self.mainwindow.serviceSettingsSection,
@ -461,9 +461,9 @@ class ServiceManager(QtGui.QWidget):
"""
fileName = unicode(QtGui.QFileDialog.getSaveFileName(self.mainwindow,
translate('OpenLP.ServiceManager', 'Save Service'),
SettingsManager.get_last_dir(self.mainwindow.serviceSettingsSection),
translate('OpenLP.ServiceManager',
'OpenLP Service Files (*.osz)')))
SettingsManager.get_last_dir(
self.mainwindow.serviceSettingsSection),
translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz)')))
if not fileName:
return False
if os.path.splitext(fileName)[1] == u'':
@ -482,7 +482,7 @@ class ServiceManager(QtGui.QWidget):
zip = None
fileTo = None
try:
zip = zipfile.ZipFile(unicode(fileName))
zip = zipfile.ZipFile(fileName)
for file in zip.namelist():
try:
ucsfile = file.decode(u'utf-8')
@ -951,7 +951,8 @@ class ServiceManager(QtGui.QWidget):
newItem.merge(item[u'service_item'])
item[u'service_item'] = newItem
self.repaintServiceList(itemcount + 1, 0)
self.mainwindow.liveController.replaceServiceManagerItem(newItem)
self.mainwindow.liveController.replaceServiceManagerItem(
newItem)
self.setModified(True)
def addServiceItem(self, item, rebuild=False, expand=None, replace=False):

View File

@ -592,7 +592,7 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
saveFrom = self.theme.background_filename
if not self.edit_mode and \
not self.thememanager.checkIfThemeExists(self.theme.theme_name):
return
return
self.accepted = True
self.thememanager.saveTheme(self.theme, saveFrom, saveTo)
return QtGui.QDialog.accept(self)

View File

@ -51,7 +51,8 @@ class ThemeManager(QtGui.QWidget):
self.settingsSection = u'themes'
self.themeForm = ThemeForm(self)
self.fileRenameForm = FileRenameForm(self)
self.serviceComboBox = self.mainwindow.ServiceManagerContents.themeComboBox
self.serviceComboBox = \
self.mainwindow.ServiceManagerContents.themeComboBox
# start with the layout
self.layout = QtGui.QVBoxLayout(self)
self.layout.setSpacing(0)
@ -388,7 +389,8 @@ class ThemeManager(QtGui.QWidget):
files = QtGui.QFileDialog.getOpenFileNames(self,
translate('OpenLP.ThemeManager', 'Select Theme Import File'),
SettingsManager.get_last_dir(self.settingsSection),
translate('OpenLP.ThemeManager', 'Theme (*.*)'))
translate('OpenLP.ThemeManager', 'Theme v1 (*.theme);;'
'Theme v2 (*.otz);;All Files (*.*)'))
log.info(u'New Themes %s', unicode(files))
if files:
for file in files:
@ -637,7 +639,8 @@ class ThemeManager(QtGui.QWidget):
Flag to tell message lines per page need to be generated.
"""
log.debug(u'generateImage \n%s ', themeData)
return self.mainwindow.renderManager.generate_preview(themeData, forcePage)
return self.mainwindow.renderManager.generate_preview(
themeData, forcePage)
def getPreviewImage(self, theme):
"""

View File

@ -282,8 +282,44 @@ def split_filename(path):
else:
return os.path.split(path)
def get_web_page(url, header=None, update_openlp=False):
"""
Attempts to download the webpage at url and returns that page or None.
``url``
The URL to be downloaded.
``header``
An optional HTTP header to pass in the request to the web server.
``update_openlp``
Tells OpenLP to update itself if the page is successfully downloaded.
Defaults to False.
"""
# TODO: Add proxy usage. Get proxy info from OpenLP settings, add to a
# proxy_handler, build into an opener and install the opener into urllib2.
# http://docs.python.org/library/urllib2.html
if not url:
return None
req = urllib2.Request(url)
if header:
req.add_header(header[0], header[1])
page = None
log.debug(u'Downloading URL = %s' % url)
try:
page = urllib2.urlopen(req)
log.debug(u'Downloaded URL = %s' % page.geturl())
except urllib2.URLError:
log.exception(u'The web page could not be downloaded')
if not page:
return None
if update_openlp:
Receiver.send_message(u'openlp_process_events')
return page
from languagemanager import LanguageManager
from actions import ActionList
__all__ = [u'AppLocation', u'check_latest_version', u'add_actions',
u'get_filesystem_encoding', u'LanguageManager', u'ActionList']
u'get_filesystem_encoding', u'LanguageManager', u'ActionList',
u'get_web_page']

View File

@ -23,20 +23,22 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
"""
The :mod:`http` module enables OpenLP to retrieve scripture from bible
websites.
"""
import logging
import os
import re
import sqlite3
import socket
import urllib
import urllib2
from HTMLParser import HTMLParseError
from BeautifulSoup import BeautifulSoup, NavigableString
from openlp.core.lib import Receiver, translate
from openlp.core.utils import AppLocation
from openlp.core.utils import AppLocation, get_web_page
from openlp.plugins.bibles.lib import SearchResults
from openlp.plugins.bibles.lib.db import BibleDB, Book
@ -204,29 +206,11 @@ class BGExtract(object):
url_params = urllib.urlencode(
{u'search': u'%s %s' % (bookname, chapter),
u'version': u'%s' % version})
page = None
try:
page = urllib2.urlopen(
u'http://www.biblegateway.com/passage/?%s' % url_params)
log.debug(u'BibleGateway url = %s' % page.geturl())
Receiver.send_message(u'openlp_process_events')
except urllib2.URLError:
log.exception(u'The web bible page could not be downloaded.')
send_error_message(u'download')
finally:
if not page:
return None
cleaner = [(re.compile('&nbsp;|<br />|\'\+\''), lambda match: '')]
soup = None
try:
soup = BeautifulSoup(page, markupMassage=cleaner)
except HTMLParseError:
log.exception(u'BeautifulSoup could not parse the bible page.')
Receiver.send_message(u'bibles_download_error')
send_error_message(u'parse')
finally:
if not soup:
return None
soup = get_soup_for_bible_ref(
u'http://www.biblegateway.com/passage/?%s' % url_params, cleaner)
if not soup:
return None
Receiver.send_message(u'openlp_process_events')
footnotes = soup.findAll(u'sup', u'footnote')
if footnotes:
@ -280,35 +264,16 @@ class BSExtract(object):
log.debug(u'get_bible_chapter %s,%s,%s', version, bookname, chapter)
chapter_url = u'http://m.bibleserver.com/text/%s/%s%s' % \
(version, bookname, chapter)
log.debug(u'URL: %s', chapter_url)
page = None
try:
page = urllib2.urlopen(chapter_url)
Receiver.send_message(u'openlp_process_events')
except urllib2.URLError:
log.exception(u'The web bible page could not be downloaded.')
send_error_message(u'download')
finally:
if not page:
return None
soup = None
try:
soup = BeautifulSoup(page)
except HTMLParseError:
log.exception(u'BeautifulSoup could not parse the bible page.')
send_error_message(u'parse')
header = (u'Accept-Language', u'en')
soup = get_soup_for_bible_ref(chapter_url, header)
if not soup:
return None
Receiver.send_message(u'openlp_process_events')
content = None
try:
content = soup.find(u'div', u'content').find(u'div').findAll(u'div')
except:
content = soup.find(u'div', u'content').find(u'div').findAll(u'div')
if not content:
log.exception(u'No verses found in the Bibleserver response.')
send_error_message(u'parse')
finally:
if not content:
return None
return None
verse_number = re.compile(r'v(\d{1,2})(\d{3})(\d{3}) verse')
verses = {}
for verse in content:
@ -344,21 +309,8 @@ class CWExtract(object):
urlbookname = bookname.replace(u' ', u'-')
chapter_url = u'http://www.biblestudytools.com/%s/%s/%s.html' % \
(version, urlbookname.lower(), chapter)
log.debug(u'URL: %s', chapter_url)
page = None
try:
page = urllib2.urlopen(chapter_url)
Receiver.send_message(u'openlp_process_events')
except urllib2.URLError:
log.exception(u'The web bible page could not be downloaded.')
send_error_message(u'download')
return None
soup = None
try:
soup = BeautifulSoup(page)
except HTMLParseError:
log.exception(u'BeautifulSoup could not parse the bible page.')
send_error_message(u'parse')
soup = get_soup_for_bible_ref(chapter_url)
if not soup:
return None
Receiver.send_message(u'openlp_process_events')
htmlverses = soup.findAll(u'span', u'versetext')
@ -416,6 +368,8 @@ class HTTPBible(BibleDB):
BibleDB.__init__(self, parent, **kwargs)
self.download_source = kwargs[u'download_source']
self.download_name = kwargs[u'download_name']
# TODO: Clean up proxy stuff. We probably want one global proxy per
# connection type (HTTP and HTTPS) at most.
self.proxy_server = None
self.proxy_username = None
self.proxy_password = None
@ -471,7 +425,7 @@ class HTTPBible(BibleDB):
book = reference[0]
db_book = self.get_book(book)
if not db_book:
book_details = self.lookup_book(book)
book_details = HTTPBooks.get_book(book)
if not book_details:
Receiver.send_message(u'openlp_error_message', {
u'title': translate('BiblesPlugin', 'No Book Found'),
@ -511,12 +465,12 @@ class HTTPBible(BibleDB):
log.debug(u'get_chapter %s, %s', book, chapter)
log.debug(u'source = %s', self.download_source)
if self.download_source.lower() == u'crosswalk':
ev = CWExtract(self.proxy_server)
handler = CWExtract(self.proxy_server)
elif self.download_source.lower() == u'biblegateway':
ev = BGExtract(self.proxy_server)
handler = BGExtract(self.proxy_server)
elif self.download_source.lower() == u'bibleserver':
ev = BSExtract(self.proxy_server)
return ev.get_bible_chapter(self.download_name, book, chapter)
handler = BSExtract(self.proxy_server)
return handler.get_bible_chapter(self.download_name, book, chapter)
def get_books(self):
"""
@ -525,12 +479,6 @@ class HTTPBible(BibleDB):
return [Book.populate(name=book['name'])
for book in HTTPBooks.get_books()]
def lookup_book(self, book):
"""
Look up the name of a book.
"""
return HTTPBooks.get_book(book)
def get_chapter_count(self, book):
"""
Return the number of chapters in a particular book.
@ -549,8 +497,41 @@ class HTTPBible(BibleDB):
"""
return HTTPBooks.get_verse_count(book, chapter)
def get_soup_for_bible_ref(reference_url, header=None, cleaner=None):
"""
Gets a webpage and returns a parsed and optionally cleaned soup or None.
``reference_url``
The URL to obtain the soup from.
``header``
An optional HTTP header to pass to the bible web server.
``cleaner``
An optional regex to use during webpage parsing.
"""
if not reference_url:
return None
page = get_web_page(reference_url, header, True)
if not page:
send_error_message(u'download')
return None
soup = None
try:
if cleaner:
soup = BeautifulSoup(page, markupMassage=cleaner)
else:
soup = BeautifulSoup(page)
except HTMLParseError:
log.exception(u'BeautifulSoup could not parse the bible page.')
if not soup:
send_error_message(u'parse')
return None
Receiver.send_message(u'openlp_process_events')
return soup
def send_error_message(reason):
if reason == u'downoad':
if reason == u'download':
Receiver.send_message(u'openlp_error_message', {
u'title': translate('BiblePlugin.HTTPBible', 'Download Error'),
u'message': translate('BiblePlugin.HTTPBible', 'There was a '
@ -563,5 +544,5 @@ def send_error_message(reason):
u'title': translate('BiblePlugin.HTTPBible', 'Parse Error'),
u'message': translate('BiblePlugin.HTTPBible', 'There was a '
'problem extracting your verse selection. If this error continues '
'continues to occur consider reporting a bug.')
'to occur consider reporting a bug.')
})

View File

@ -25,7 +25,6 @@
###############################################################################
import logging
import time
from PyQt4 import QtCore, QtGui
@ -137,9 +136,6 @@ class BibleMediaItem(MediaManagerItem):
self.quickSearchButton.setObjectName(u'quickSearchButton')
self.quickSearchButtonLayout.addWidget(self.quickSearchButton)
self.quickLayout.addRow(self.quickSearchButtonLayout)
self.quickMessage = QtGui.QLabel(self.quickTab)
self.quickMessage.setObjectName(u'quickMessage')
self.quickLayout.addRow(self.quickMessage)
self.searchTabWidget.addTab(self.quickTab,
translate('BiblesPlugin.MediaItem', 'Quick'))
# Add the Advanced Search tab.
@ -231,9 +227,6 @@ class BibleMediaItem(MediaManagerItem):
self.advancedSearchButtonLayout.addWidget(self.advancedSearchButton)
self.advancedLayout.addLayout(
self.advancedSearchButtonLayout, 7, 0, 1, 3)
self.advancedMessage = QtGui.QLabel(self.advancedTab)
self.advancedMessage.setObjectName(u'advancedMessage')
self.advancedLayout.addWidget(self.advancedMessage, 8, 0, 1, 3)
self.searchTabWidget.addTab(self.advancedTab,
translate('BiblesPlugin.MediaItem', 'Advanced'))
# Add the search tab widget to the page layout.
@ -347,13 +340,6 @@ class BibleMediaItem(MediaManagerItem):
self.configUpdated()
log.debug(u'bible manager initialise complete')
def setQuickMessage(self, text):
self.quickMessage.setText(text)
self.advancedMessage.setText(text)
Receiver.send_message(u'openlp_process_events')
# Minor delay to get the events processed.
time.sleep(0.1)
def onListViewResize(self, width, height):
listViewGeometry = self.listView.geometry()
self.SearchProgress.setGeometry(listViewGeometry.x(),
@ -432,11 +418,13 @@ class BibleMediaItem(MediaManagerItem):
verse_count = self.parent.manager.get_verse_count(bible, book, 1)
if verse_count == 0:
self.advancedSearchButton.setEnabled(False)
self.advancedMessage.setText(
translate('BiblesPlugin.MediaItem', 'Bible not fully loaded.'))
Receiver.send_message(u'openlp_error_message', {
u'title': translate('BiblePlugin.MediaItem', 'Error'),
u'message': translate('BiblePlugin.MediaItem',
'Bible not fully loaded')
})
else:
self.advancedSearchButton.setEnabled(True)
self.advancedMessage.setText(u'')
self.adjustComboBox(1, self.chapter_count, self.advancedFromChapter)
self.adjustComboBox(1, self.chapter_count, self.advancedToChapter)
self.adjustComboBox(1, verse_count, self.advancedFromVerse)
@ -606,6 +594,7 @@ class BibleMediaItem(MediaManagerItem):
second_bible, text)
else:
# We are doing a 'Text Search'.
Receiver.send_message(u'cursor_busy')
bibles = self.parent.manager.get_bibles()
self.search_results = self.parent.manager.verse_search(bible,
second_bible, text)
@ -636,6 +625,7 @@ class BibleMediaItem(MediaManagerItem):
elif self.search_results:
self.displayResults(bible, second_bible)
self.quickSearchButton.setEnabled(True)
Receiver.send_message(u'cursor_normal')
def displayResults(self, bible, second_bible=u''):
"""

View File

@ -169,7 +169,7 @@ class ImpressController(PresentationController):
try:
return Dispatch(u'com.sun.star.ServiceManager')
except pywintypes.com_error:
log.warn(u'Failed to get COM service manager. '
log.exception(u'Failed to get COM service manager. '
u'Impress Controller has been disabled')
return None
@ -257,7 +257,6 @@ class ImpressDocument(PresentationDocument):
except:
log.exception(u'Failed to load presentation %s' % url)
return False
self.presentation = self.document.getPresentation()
self.presentation.Display = \
self.controller.plugin.renderManager.screens.current_display + 1
@ -327,8 +326,7 @@ class ImpressDocument(PresentationDocument):
self.presentation = None
self.document.dispose()
except:
#We tried!
pass
log.exception("Closing presentation failed")
self.document = None
self.controller.remove_doc(self)
@ -339,13 +337,14 @@ class ImpressDocument(PresentationDocument):
log.debug(u'is loaded OpenOffice')
#print "is_loaded "
if self.presentation is None or self.document is None:
#print "no present or document"
log.debug("is_loaded: no presentation or document")
return False
try:
if self.document.getPresentation() is None:
#print "no getPresentation"
log.debug("getPresentation failed to find a presentation")
return False
except:
log.exception("getPresentation failed to find a presentation")
return False
return True

View File

@ -23,7 +23,7 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
import logging
import os
from PyQt4 import QtCore
@ -31,6 +31,8 @@ from PyQt4 import QtCore
from openlp.core.lib import Receiver
from songimport import SongImport
log = logging.getLogger(__name__)
if os.name == u'nt':
from win32com.client import Dispatch
PAGE_BEFORE = 4
@ -116,7 +118,7 @@ class OooImport(SongImport):
+ u'socket,host=localhost,port=2002;' \
+ u'urp;StarOffice.ComponentContext')
except:
pass
log.exception("Failed to resolve uno connection")
self.start_ooo_process()
loop += 1
manager = ctx.ServiceManager
@ -143,7 +145,7 @@ class OooImport(SongImport):
process.waitForStarted()
self.process_started = True
except:
pass
log.exception("start_ooo_process failed")
def open_ooo_file(self, filepath):
"""
@ -167,7 +169,7 @@ class OooImport(SongImport):
self.import_wizard.incrementProgressBar(
u'Processing file ' + filepath, 0)
except:
pass
log.exception("open_ooo_file failed")
return
def close_ooo_file(self):
@ -232,4 +234,4 @@ class OooImport(SongImport):
text += paratext + u'\n'
songs = SongImport.process_songs_text(self.manager, text)
for song in songs:
song.finish()
song.finish()