Merged in the changes from the biblefixes branch.

bzr-revno: 494
This commit is contained in:
Raoul Snyman 2009-07-15 21:18:08 +02:00
commit 40a9c5a32c
9 changed files with 418 additions and 298 deletions

View File

@ -212,11 +212,12 @@ class SlideController(QtGui.QWidget):
self.ControllerLayout.addWidget(self.Toolbar) self.ControllerLayout.addWidget(self.Toolbar)
self.BaseToolbar.addServiceManagerItem(item, slideno) self.BaseToolbar.addServiceManagerItem(item, slideno)
class MasterPreview(QtCore.QObject): class MasterPreview(QtCore.QObject):
""" """
Class from which all Previews should extend allowing plugins to have their own Class from which all Previews should extend allowing plugins to
previews have their own previews
s """ """
def __init__(self, parent): def __init__(self, parent):
self.parent = parent self.parent = parent
QtCore.QObject.__init__(self) QtCore.QObject.__init__(self)
@ -369,28 +370,30 @@ class MasterToolbar(QtCore.QObject):
Display the slide number passed Display the slide number passed
""" """
log.debug(u'add Service Manager Item') log.debug(u'add Service Manager Item')
self.serviceitem = serviceitem
slide_pixmap = QtGui.QPixmap.fromImage(self.serviceitem.frames[0][u'image'])
slide_width = 300
slide_height = slide_width * slide_pixmap.height() / slide_pixmap.width()
self.PreviewListWidget.clear() self.PreviewListWidget.clear()
self.PreviewListWidget.setRowCount(0) self.PreviewListWidget.setRowCount(0)
self.serviceitem = serviceitem self.PreviewListWidget.setColumnWidth(0, slide_width)
framenumber = 0 for framenumber, frame in enumerate(self.serviceitem.frames):
for frame in self.serviceitem.frames:
self.PreviewListWidget.setRowCount(self.PreviewListWidget.rowCount() + 1) self.PreviewListWidget.setRowCount(self.PreviewListWidget.rowCount() + 1)
pixmap = QtGui.QPixmap.fromImage(frame[u'image']) pixmap = QtGui.QPixmap.fromImage(frame[u'image'])
item = QtGui.QTableWidgetItem() item = QtGui.QTableWidgetItem()
label = QtGui.QLabel() label = QtGui.QLabel()
label.setMargin(15) label.setMargin(8)
label.setScaledContents(True) label.setScaledContents(True)
width = 300
height = width * pixmap.height() / pixmap.width()
label.setPixmap(pixmap) label.setPixmap(pixmap)
self.PreviewListWidget.setCellWidget(framenumber, 0,label) self.PreviewListWidget.setCellWidget(framenumber, 0, label)
self.PreviewListWidget.setItem( framenumber, 0, item) self.PreviewListWidget.setItem(framenumber, 0, item)
self.PreviewListWidget.setRowHeight(framenumber, height) self.PreviewListWidget.setRowHeight(framenumber, slide_height)
self.PreviewListWidget.setColumnWidth(0, width) slide_width = self.PreviewListWidget.viewport().size().width()
framenumber += 1 self.PreviewListWidget.setColumnWidth(0, slide_width)
if slideno > self.PreviewListWidget.rowCount(): if slideno > self.PreviewListWidget.rowCount():
self.PreviewListWidget.selectRow(self.PreviewListWidget.rowCount()) self.PreviewListWidget.selectRow(self.PreviewListWidget.rowCount())
else: else:
self.PreviewListWidget.selectRow(slideno) self.PreviewListWidget.selectRow(slideno)
self.onSlideSelected() self.onSlideSelected()
self.serviceLoaded() self.serviceLoaded()
self.PreviewListWidget.setFocus()

View File

@ -1,6 +1,10 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
""" """
OpenLP - Open Source Lyrics Projection OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under This program is free software; you can redistribute it and/or modify it under
@ -16,43 +20,34 @@ this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA Place, Suite 330, Boston, MA 02111-1307 USA
""" """
import os import os
import os.path
import logging import logging
from sqlalchemy import *
from sqlalchemy.sql import select
from sqlalchemy.orm import sessionmaker, mapper, scoped_session
from common import BibleCommon from common import BibleCommon
from openlp.core.utils import ConfigHelper from openlp.core.utils import ConfigHelper
from openlp.plugins.bibles.lib.tables import * from openlp.plugins.bibles.lib.models import *
from openlp.plugins.bibles.lib.classes import *
class BibleDBImpl(BibleCommon): class BibleDBImpl(BibleCommon):
global log global log
log=logging.getLogger(u'BibleDBImpl') log=logging.getLogger(u'BibleDBImpl')
log.info(u'BibleDBimpl loaded') log.info(u'BibleDBimpl loaded')
def __init__(self, biblepath , biblename, config): def __init__(self, biblepath, biblename, config):
# Connect to database # Connect to database
self.config = config self.config = config
self.biblefile = os.path.join(biblepath, biblename+u'.sqlite') self.biblefile = os.path.join(biblepath, biblename + u'.sqlite')
log.debug(u'Load bible %s on path %s', biblename, self.biblefile) log.debug(u'Load bible %s on path %s', biblename, self.biblefile)
db_type = self.config.get_config(u'db type', u'sqlite') db_type = self.config.get_config(u'db type', u'sqlite')
db_url = u''
if db_type == u'sqlite': if db_type == u'sqlite':
self.db = create_engine(u'sqlite:///' + self.biblefile) db_url = u'sqlite:///' + self.biblefile
else: else:
self.db_url = u'%s://%s:%s@%s/%s' % \ db_url = u'%s://%s:%s@%s/%s' % \
(db_type, self.config.get_config(u'db username'), (db_type, self.config.get_config(u'db username'),
self.config.get_config(u'db password'), self.config.get_config(u'db password'),
self.config.get_config(u'db hostname'), self.config.get_config(u'db hostname'),
self.config.get_config(u'db database')) self.config.get_config(u'db database'))
self.db.echo = False self.metadata, self.session = init_models(db_url)
metadata.bind = self.db self.metadata.create_all(checkfirst=True)
metadata.bind.echo = False
self.session = scoped_session(sessionmaker(autoflush=True, autocommit=False))
self.session.configure(bind=self.db)
metadata.create_all(self.db)
def create_tables(self): def create_tables(self):
log.debug( u'createTables') log.debug( u'createTables')
@ -63,122 +58,127 @@ class BibleDBImpl(BibleCommon):
def add_verse(self, bookid, chap, vse, text): def add_verse(self, bookid, chap, vse, text):
#log.debug(u'add_verse %s,%s,%s", bookid, chap, vse) #log.debug(u'add_verse %s,%s,%s", bookid, chap, vse)
metadata.bind.echo = False #metadata.bind.echo = False
session = self.session()
verse = Verse() verse = Verse()
verse.book_id = bookid verse.book_id = bookid
verse.chapter = chap verse.chapter = chap
verse.verse = vse verse.verse = vse
verse.text = text verse.text = text
session.add(verse) self.session.add(verse)
session.commit() self.session.commit()
def create_chapter(self, bookid, chap, textlist): def create_chapter(self, bookid, chap, textlist):
log.debug(u'create_chapter %s,%s', bookid, chap) log.debug(u'create_chapter %s,%s', bookid, chap)
#log.debug(u'Text %s ", textlist) #log.debug(u'Text %s ", textlist)
metadata.bind.echo = False #metadata.bind.echo = False
session = self.session()
#text list has book and chapter as first to elements of the array #text list has book and chapter as first to elements of the array
for v , t in textlist.iteritems(): for verse_number, verse_text in textlist.iteritems():
verse = Verse() verse = Verse()
verse.book_id = bookid verse.book_id = bookid
verse.chapter = chap verse.chapter = chap
verse.verse = v verse.verse = verse_number
verse.text = t verse.text = verse_text
session.add(verse) self.session.add(verse)
session.commit() self.session.commit()
def create_book(self, bookname, bookabbrev, testament = 1): def create_book(self, bookname, bookabbrev, testament=1):
log.debug(u'create_book %s,%s', bookname, bookabbrev) log.debug(u'create_book %s,%s', bookname, bookabbrev)
metadata.bind.echo = False #metadata.bind.echo = False
session = self.session()
book = Book() book = Book()
book.testament_id = testament book.testament_id = testament
book.name = bookname book.name = bookname
book.abbreviation = bookabbrev book.abbreviation = bookabbrev
session.add(book) self.session.add(book)
session.commit() self.session.commit()
return book return book
def save_meta(self, key, value): def save_meta(self, key, value):
log.debug(u'save_meta %s/%s', key, value) log.debug(u'save_meta %s/%s', key, value)
metadata.bind.echo = False #metadata.bind.echo = False
session = self.session() bmeta = BibleMeta()
bmeta= BibleMeta()
bmeta.key = key bmeta.key = key
bmeta.value = value bmeta.value = value
session.add(bmeta) self.session.add(bmeta)
session.commit() self.session.commit()
def get_meta(self, metakey): def get_meta(self, metakey):
log.debug(u'get meta %s', metakey) log.debug(u'get meta %s', metakey)
return self.session.query(BibleMeta).filter_by(key = metakey).first() return self.session.query(BibleMeta).filter_by(key=metakey).first()
def delete_meta(self, metakey): def delete_meta(self, metakey):
biblemeta = self.get_meta(metakey) biblemeta = self.get_meta(metakey)
try: try:
session.delete(biblemeta) self.session.delete(biblemeta)
session.commit() self.session.commit()
return True return True
except: except:
return False return False
def _load_testament(self, testament): def _load_testament(self, testament):
log.debug(u'load_testaments %s', testament) log.debug(u'load_testaments %s', testament)
metadata.bind.echo = False #metadata.bind.echo = False
session = self.session()
test = ONTestament() test = ONTestament()
test.name = testament test.name = testament
session.add(test) self.session.add(test)
session.commit() self.session.commit()
def get_bible_books(self): def get_bible_books(self):
log.debug(u'get_bible_books ') log.debug(u'get_bible_books')
return self.session.query(Book).order_by(Book.id).all() return self.session.query(Book).order_by(Book.id).all()
def get_max_bible_book_verses(self, bookname, chapter): def get_max_bible_book_verses(self, bookname, chapter):
log.debug(u'get_max_bible_book_verses %s,%s', bookname , chapter) log.debug(u'get_max_bible_book_verses %s, %s', bookname, chapter)
metadata.bind.echo = False #metadata.bind.echo = False
s = text (u'select max(verse.verse) from verse,book where chapter = :c and book_id = book.id and book.name = :b ') #s = text (u'select max(verse.verse) from verse,book where chapter = :c and book_id = book.id and book.name = :b ')
return self.db.execute(s, c=chapter, b=bookname).fetchone() #return self.db.execute(s, c=chapter, b=bookname).fetchone()
verse = self.session.query(Verse).join(Book).filter(Book.name==bookname).filter(Verse.chapter==chapter).order_by(Verse.verse.desc()).first()
return verse.verse
def get_max_bible_book_chapter(self, bookname): def get_max_bible_book_chapter(self, bookname):
log.debug(u'get_max_bible_book_chapter %s', bookname ) log.debug(u'get_max_bible_book_chapter %s', bookname)
metadata.bind.echo = False #metadata.bind.echo = False
s = text (u'select max(verse.chapter) from verse,book where book_id = book.id and book.name = :b') #s = text (u'select max(verse.chapter) from verse,book where book_id = book.id and book.name = :b')
return self.db.execute(s, b=bookname).fetchone() #return self.db.execute(s, b=bookname).fetchone()
verse = self.session.query(Verse).join(Book).filter(Book.name==bookname).order_by(Verse.chapter.desc()).first()
return verse.chapter
def get_bible_book(self, bookname): def get_bible_book(self, bookname):
log.debug(u'get_bible_book %s', bookname) log.debug(u'get_bible_book %s', bookname)
bk = self.session.query(Book).filter(Book.name.like(bookname + u'%')).first() bk = self.session.query(Book).filter(Book.name.like(bookname + u'%')).first()
if bk == None: if bk == None:
bk = self.session.query(Book).filter(Book.abbreviation.like(bookname+u'%')).first() bk = self.session.query(Book).filter(Book.abbreviation.like(bookname + u'%')).first()
return bk return bk
def get_bible_chapter(self, id, chapter): def get_bible_chapter(self, id, chapter):
log.debug(u'get_bible_chapter %s,%s', id, chapter ) log.debug(u'get_bible_chapter %s, %s', id, chapter)
metadata.bind.echo = False #metadata.bind.echo = False
return self.session.query(Verse).filter_by(chapter = chapter ).filter_by(book_id = id).first() return self.session.query(Verse).filter_by(chapter=chapter).filter_by(book_id=id).first()
def get_bible_text(self, bookname, chapter, sverse, everse): def get_bible_text(self, bookname, chapter, sverse, everse):
log.debug(u'get_bible_text %s,%s,%s,%s', bookname, chapter, sverse, everse) log.debug(u'get_bible_text %s, %s, %s, %s', bookname, chapter, sverse, everse)
metadata.bind.echo = False #metadata.bind.echo = False
bookname = bookname + u"%" #bookname = bookname + u"%"
s = text (u'select name,chapter,verse.verse, verse.text FROM verse , book where verse.book_id == book.id AND verse.chapter == :c AND (verse.verse between :v1 and :v2) and (book.name like :b)') #s = text (u'select name,chapter,verse.verse, verse.text FROM verse , book where verse.book_id == book.id AND verse.chapter == :c AND (verse.verse between :v1 and :v2) and (book.name like :b)')
return self.db.execute(s, c=chapter, v1=sverse , v2=everse, b=bookname).fetchall() #return self.db.execute(s, c=chapter, v1=sverse , v2=everse, b=bookname).fetchall()
verses = self.session.query(Verse).join(Book).filter(Book.name==bookname).filter(Verse.chapter==chapter).filter(Verse.verse>=sverse).filter(Verse.verse<=everse).order_by(Verse.verse).all()
return verses
def get_verses_from_text(self,versetext): def get_verses_from_text(self, versetext):
log.debug(u'get_verses_from_text %s',versetext) log.debug(u'get_verses_from_text %s',versetext)
metadata.bind.echo = False #metadata.bind.echo = False
versetext = "%"+versetext+"%" versetext = u'%%%s%%' % versetext
s = text (u'select book.name, verse.chapter, verse.verse, verse.text FROM verse , book where verse.book_id == book.id and verse.text like :t') #s = text (u'select book.name, verse.chapter, verse.verse, verse.text FROM verse , book where verse.book_id == book.id and verse.text like :t')
return self.db.execute(s, t=versetext).fetchall() #return self.db.execute(s, t=versetext).fetchall()
verses = self.session.query(Verse).filter(Verse.text.like(versetext)).all()
return verses
def dump_bible(self): def dump_bible(self):
log.debug( u'.........Dumping Bible Database') log.debug( u'.........Dumping Bible Database')
log.debug( '...............................Books ') log.debug( '...............................Books ')
s = text (u'select * FROM book ') #s = text (u'select * FROM book ')
log.debug( self.db.execute(s).fetchall()) books = self.session.query(Book).all()
log.debug(books)
log.debug( u'...............................Verses ') log.debug( u'...............................Verses ')
s = text (u'select * FROM verse ') #s = text (u'select * FROM verse ')
log.debug( self.db.execute(s).fetchall()) verses = self.session.query(Verse).all()
log.debug(verses)

View File

@ -97,7 +97,7 @@ class CWExtract(BibleCommon):
""" """
log.debug(u'get_bible_chapter %s,%s,%s,%s', version, bookid, bookname, chapter) log.debug(u'get_bible_chapter %s,%s,%s,%s', version, bookid, bookname, chapter)
bookname = bookname.replace(u' ', '') bookname = bookname.replace(u' ', '')
urlstring = u'http://bible.crosswalk.com/OnlineStudyBible/bible.cgi?word='+bookname+u'+'+unicode(chapter)+u'&version='+version urlstring = u'http://bible.crosswalk.com/OnlineStudyBible/bible.cgi?word=%s+%d&version=%s' % (bookname, chapter, version)
xml_string = self._get_web_text(urlstring, self.proxyurl) xml_string = self._get_web_text(urlstring, self.proxyurl)
#log.debug(u'Return data %s', xml_string) #log.debug(u'Return data %s', xml_string)
## Strip Book Title from Heading to return it to system ## Strip Book Title from Heading to return it to system
@ -207,7 +207,7 @@ class BibleHTTPImpl():
ev = CWExtract(self.proxyurl) ev = CWExtract(self.proxyurl)
else: else:
ev = BGExtract(self.proxyurl) ev = BGExtract(self.proxyurl)
return ev.get_bible_chapter(self.bibleid, bookid, bookname, chapter) return ev.get_bible_chapter(self.bibleid, bookid, bookname, chapter)
except: except Exception, e:
log.error(u'Error thrown = %s', sys.exc_info()[1]) log.error(u'Error thrown = %s', e.args[0])
print e

View File

@ -1,6 +1,8 @@
""" """
OpenLP - Open Source Lyrics Projection OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under This program is free software; you can redistribute it and/or modify it under
@ -20,37 +22,69 @@ import os.path
import logging import logging
import chardet import chardet
import codecs import codecs
from openlp.plugins.bibles.lib.bibleDBimpl import BibleDBImpl
from openlp.core.lib import Receiver
from PyQt4 import QtCore from PyQt4 import QtCore
from openlp.plugins.bibles.lib.bibleDBimpl import BibleDBImpl
from openlp.core.lib import Receiver
class BibleOSISImpl(): class BibleOSISImpl():
"""
OSIS Bible format importer class.
"""
global log global log
log = logging.getLogger(u'BibleOSISImpl') log = logging.getLogger(u'BibleOSISImpl')
log.info(u'BibleOSISImpl loaded') log.info(u'BibleOSISImpl loaded')
def __init__(self, biblepath, bibledb): def __init__(self, biblepath, bibledb):
"""
Constructor to create and set up an instance of the
BibleOSISImpl class.
``biblepath``
This does not seem to be used.
``bibledb``
A reference to a Bible database object.
"""
self.bibledb = bibledb self.bibledb = bibledb
# books of the bible linked to bibleid {osis , name} # books of the bible linked to bibleid {osis , name}
self.booksOfBible = {} self.booksOfBible = {}
# books of the bible linked to bibleid {osis ,Abbrev } # books of the bible linked to bibleid {osis ,Abbrev }
self.abbrevOfBible = {} self.abbrevOfBible = {}
filepath = os.path.split(os.path.abspath(__file__))[0] filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(filepath, u'..', u'resources',u'osisbooks.csv')) filepath = os.path.abspath(os.path.join(
filepath, u'..', u'resources',u'osisbooks.csv'))
fbibles=open(filepath, u'r') fbibles=open(filepath, u'r')
for line in fbibles: for line in fbibles:
p = line.split(u',') p = line.split(u',')
self.booksOfBible[p[0]] = p[1].replace(u'\n', u'') self.booksOfBible[p[0]] = p[1].replace(u'\n', u'')
self.abbrevOfBible[p[0]] = p[2].replace(u'\n', u'') self.abbrevOfBible[p[0]] = p[2].replace(u'\n', u'')
self.loadbible = True self.loadbible = True
QtCore.QObject.connect(Receiver().get_receiver(),QtCore.SIGNAL(u'openlpstopimport'),self.stop_import) QtCore.QObject.connect(Receiver().get_receiver(),
QtCore.SIGNAL(u'openlpstopimport'), self.stop_import)
def stop_import(self): def stop_import(self):
"""
Stops the import of the Bible.
"""
self.loadbible = False self.loadbible = False
def load_data(self, osisfile_record, dialogobject=None): def load_data(self, osisfile_record, dialogobject=None):
osis = codecs.open(osisfile_record, u'r') """
Loads a Bible from file.
``osisfile_record``
The file to import from.
``dialogobject``
The Import dialog, so that we can increase the counter on
the progress bar.
"""
detect_file = open(osisfile_record, u'r')
details = chardet.detect(detect_file.read(2048))
detect_file.close()
osis = codecs.open(osisfile_record, u'r', details['encoding'])
book_ptr = None book_ptr = None
id = 0 id = 0
count = 0 count = 0
@ -110,8 +144,11 @@ class BibleOSISImpl():
if p[0] == u'Matt': if p[0] == u'Matt':
testament += 1 testament += 1
book_ptr = p[0] book_ptr = p[0]
book = self.bibledb.create_book(self.booksOfBible[p[0]] , self.abbrevOfBible[p[0]], testament) book = self.bibledb.create_book(
dialogobject.incrementProgressBar(self.booksOfBible[p[0]] ) self.booksOfBible[p[0]],
self.abbrevOfBible[p[0]], testament)
dialogobject.incrementProgressBar(
self.booksOfBible[p[0]])
Receiver().send_message(u'openlpprocessevents') Receiver().send_message(u'openlpprocessevents')
count = 0 count = 0
self.bibledb.add_verse(book.id, p[1], p[2], text) self.bibledb.add_verse(book.id, p[1], p[2], text)
@ -123,8 +160,18 @@ class BibleOSISImpl():
def remove_block(self, start_tag, end_tag, text): def remove_block(self, start_tag, end_tag, text):
""" """
removes a block of text between two tags Removes a block of text between two tags::
<tag attrib=xvf > Some not wanted text </tag>
<tag attrib="xvf">Some not wanted text</tag>
``start_tag``
The XML tag to look for.
``end_tag``
The ending XML tag.
``text``
The string of XML to search.
""" """
pos = text.find(start_tag) pos = text.find(start_tag)
while pos > -1: while pos > -1:
@ -138,8 +185,15 @@ class BibleOSISImpl():
def remove_tag(self, start_tag, text): def remove_tag(self, start_tag, text):
""" """
removes a single tag Removes a single tag::
<tag attrib1=fajkdf attrib2=fajkdf attrib2=fajkdf />
<tag attrib1="fajkdf" attrib2="fajkdf" attrib3="fajkdf" />
``start_tag``
The XML tag to remove.
``text``
The string of XML to search.
""" """
pos = text.find(start_tag) pos = text.find(start_tag)
while pos > -1: while pos > -1:

View File

@ -1,67 +0,0 @@
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
"""
from sqlalchemy.orm import mapper, relation
from openlp.plugins.bibles.lib.tables import *
class BaseModel(object):
"""
BaseModel provides a base object with a set of generic functions
"""
@classmethod
def populate(cls, **kwargs):
"""
Creates an instance of a class and populates it, returning the instance
"""
me = cls()
keys = kwargs.keys()
for key in keys:
me.__setattr__(key, kwargs[key])
return me
class BibleMeta(BaseModel):
"""
Bible Meta Data
"""
pass
class ONTestament(BaseModel):
"""
Bible Testaments
"""
pass
class Book(BaseModel):
"""
Song model
"""
pass
class Verse(BaseModel):
"""
Topic model
"""
pass
mapper(BibleMeta, meta_table)
mapper(ONTestament, testament_table,
properties={'books': relation(Book, backref='testament')})
mapper(Book, book_table,
properties={'verses': relation(Verse, backref='book')})
mapper(Verse, verse_table)

View File

@ -2,7 +2,9 @@
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 # vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
""" """
OpenLP - Open Source Lyrics Projection OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under This program is free software; you can redistribute it and/or modify it under
@ -18,7 +20,7 @@ this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA Place, Suite 330, Boston, MA 02111-1307 USA
""" """
import logging import logging
import os, os.path import os
import sys import sys
from common import SearchResults from common import SearchResults
@ -26,72 +28,93 @@ from bibleOSISimpl import BibleOSISImpl
from bibleCSVimpl import BibleCSVImpl from bibleCSVimpl import BibleCSVImpl
from bibleDBimpl import BibleDBImpl from bibleDBimpl import BibleDBImpl
from bibleHTTPimpl import BibleHTTPImpl from bibleHTTPimpl import BibleHTTPImpl
from openlp.plugins.bibles.lib.tables import * from openlp.plugins.bibles.lib.tables import *
from openlp.plugins.bibles.lib.classes import * from openlp.plugins.bibles.lib.classes import *
class BibleManager(): class BibleMode(object):
Full = 1
Partial = 2
class BibleManager(object):
"""
The Bible manager which holds and manages all the Bibles.
"""
global log global log
log=logging.getLogger(u'BibleManager') log=logging.getLogger(u'BibleManager')
log.info(u'Bible manager loaded') log.info(u'Bible manager loaded')
def __init__(self, config): def __init__(self, config):
""" """
Finds all the bibles defined for the system Finds all the bibles defined for the system and creates an
Creates an Interface Object for each bible containing connection information interface object for each bible containing connection
Throws Exception if no Bibles are found. information. Throws Exception if no Bibles are found.
Init confirms the bible exists and stores the database path. Init confirms the bible exists and stores the database path.
``config``
The plugin's configuration object.
""" """
self.config = config self.config = config
log.debug(u'Bible Initialising') log.debug(u'Bible Initialising')
self.bible_db_cache = None # dict of bible database classes # dict of bible database objects
self.bible_http_cache = None # dict of bible http readers self.bible_db_cache = None
# dict of bible http readers
self.bible_http_cache = None
self.biblePath = self.config.get_data_path() self.biblePath = self.config.get_data_path()
self.proxyname = self.config.get_config(u'proxy name') #get proxy name for screen #get proxy name for screen
self.proxyname = self.config.get_config(u'proxy name')
self.bibleSuffix = u'sqlite' self.bibleSuffix = u'sqlite'
self.dialogobject = None self.dialogobject = None
self.reload_bibles() self.reload_bibles()
def reload_bibles(self): def reload_bibles(self):
log.debug(u'Reload bibles') log.debug(u'Reload bibles')
files = self.config.get_files(self.bibleSuffix) files = self.config.get_files(self.bibleSuffix)
log.debug(u'Bible Files %s', files ) log.debug(u'Bible Files %s', files )
self.bible_db_cache = {} self.bible_db_cache = {}
self.bible_http_cache = {} self.bible_http_cache = {}
# books of the bible with testaments
self.book_testaments = {} # books of the bible with testaments self.book_testaments = {}
self.book_abbreviations = {} # books of the bible with abbreviation # books of the bible with abbreviation
self.book_abbreviations = {}
self.web_bibles_present = False self.web_bibles_present = False
for f in files: for f in files:
nme = f.split(u'.') nme = f.split(u'.')
bname = nme[0] bname = nme[0]
self.bible_db_cache[bname] = BibleDBImpl(self.biblePath, bname, self.config) self.bible_db_cache[bname] = BibleDBImpl(self.biblePath,
biblesource = self.bible_db_cache[bname].get_meta(u'WEB') # look to see if lazy load bible exists and get create getter. bname, self.config)
# look to see if lazy load bible exists and get create getter.
biblesource = self.bible_db_cache[bname].get_meta(u'WEB')
if biblesource: if biblesource:
self.web_bibles_present = True self.web_bibles_present = True
nhttp = BibleHTTPImpl() nhttp = BibleHTTPImpl()
nhttp.set_bible_source(biblesource.value) # tell The Server where to get the verses from. # tell The Server where to get the verses from.
nhttp.set_bible_source(biblesource.value)
self.bible_http_cache [bname] = nhttp self.bible_http_cache [bname] = nhttp
meta = self.bible_db_cache[bname].get_meta(u'proxy') # look to see if lazy load bible exists and get create getter. # look to see if lazy load bible exists and get create getter.
meta = self.bible_db_cache[bname].get_meta(u'proxy')
proxy = None proxy = None
if meta != None: if meta != None:
proxy = meta.value proxy = meta.value
nhttp.set_proxy(proxy) # tell The Server where to get the verses from. # tell The Server where to get the verses from.
bibleid = self.bible_db_cache[bname].get_meta(u'bibleid').value # look to see if lazy load bible exists and get create getter. nhttp.set_proxy(proxy)
nhttp.set_bibleid(bibleid) # tell The Server where to get the verses from. # look to see if lazy load bible exists and get create getter.
bibleid = self.bible_db_cache[bname].get_meta(u'bibleid').value
# tell The Server where to get the verses from.
nhttp.set_bibleid(bibleid)
else: else:
self.bible_http_cache [bname] = None # makes the Full / partial code easier. # makes the Full / partial code easier.
self.bible_http_cache [bname] = None
if self.web_bibles_present: if self.web_bibles_present:
self.book_testaments = {} # books of the bible linked to bibleid {osis , name} # books of the bible linked to bibleid {osis, name}
self.book_abbreviations = {} # books of the bible linked to bibleid {osis ,Abbrev } self.book_testaments = {}
# books of the bible linked to bibleid {osis, abbrev}
self.book_abbreviations = {}
filepath = os.path.split(os.path.abspath(__file__))[0] filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(filepath, u'..', u'resources',u'httpbooks.csv')) filepath = os.path.abspath(os.path.join(
fbibles=open(filepath, 'r') filepath, u'..', u'resources',u'httpbooks.csv'))
fbibles = open(filepath, u'r')
for line in fbibles: for line in fbibles:
p = line.split(u',') p = line.split(u',')
self.book_abbreviations[p[0]] = p[1].replace(u'\n', '') self.book_abbreviations[p[0]] = p[1].replace(u'\n', '')
@ -99,31 +122,64 @@ class BibleManager():
log.debug(u'Bible Initialised') log.debug(u'Bible Initialised')
def process_dialog(self, dialogobject): def process_dialog(self, dialogobject):
"""
Sets the reference to the dialog with the progress bar on it.
``dialogobject``
The reference to the dialog.
"""
self.dialogobject = dialogobject self.dialogobject = dialogobject
def register_http_bible(self, biblename, biblesource, bibleid, proxyurl=None, proxyid=None, proxypass=None): def register_http_bible(self, biblename, biblesource, bibleid,
proxyurl=None, proxyid=None, proxypass=None):
""" """
Return a list of bibles from a given URL. Return a list of bibles from a given URL. The selected Bible
The selected Bible can then be registered and LazyLoaded into a database can then be registered and LazyLoaded into a database.
"""
log.debug(u'register_HTTP_bible %s,%s,%s,%s,%s,%s', biblename, biblesource, bibleid, proxyurl, proxyid, proxypass)
if self._is_new_bible(biblename):
nbible = BibleDBImpl(self.biblePath, biblename, self.config) # Create new Bible
nbible.create_tables() # Create Database
self.bible_db_cache[biblename] = nbible
``biblename``
The name of the bible to register.
``biblesource``
Where this Bible stores it's verses.
``bibleid``
The identifier for a Bible.
``proxyurl``
Defaults to *None*. An optional URL to a proxy server.
``proxyid``
Defaults to *None*. A username for logging into the proxy
server.
``proxypass``
Defaults to *None*. The password to accompany the username.
"""
log.debug(u'register_HTTP_bible %s, %s, %s, %s, %s, %s',
biblename, biblesource, bibleid, proxyurl, proxyid, proxypass)
if self._is_new_bible(biblename):
# Create new Bible
nbible = BibleDBImpl(self.biblePath, biblename, self.config)
# Create Database
nbible.create_tables()
self.bible_db_cache[biblename] = nbible
nhttp = BibleHTTPImpl() nhttp = BibleHTTPImpl()
nhttp.set_bible_source(biblesource) nhttp.set_bible_source(biblesource)
self.bible_http_cache [biblename] = nhttp self.bible_http_cache [biblename] = nhttp
nbible.save_meta(u'WEB', biblesource) # register a lazy loading interest # register a lazy loading interest
nbible.save_meta(u'bibleid', bibleid) # store the we id of the bible nbible.save_meta(u'WEB', biblesource)
# store the web id of the bible
nbible.save_meta(u'bibleid', bibleid)
if proxyurl != None and proxyurl != "": if proxyurl != None and proxyurl != "":
nbible.save_meta(u'proxy', proxyurl) # store the proxy URL # store the proxy URL
nbible.save_meta(u'proxy', proxyurl)
nhttp.set_proxy(proxyurl) nhttp.set_proxy(proxyurl)
if proxyid != None and proxyid != "": if proxyid != None and proxyid != "":
nbible.save_meta(u'proxyid', proxyid) # store the proxy userid # store the proxy userid
nbible.save_meta(u'proxyid', proxyid)
if proxypass != None and proxypass != "": if proxypass != None and proxypass != "":
nbible.save_meta(u'proxypass', proxypass) # store the proxy password # store the proxy password
nbible.save_meta(u'proxypass', proxypass)
return True return True
else: else:
log.debug(u'register_http_file_bible %s not created already exists', biblename) log.debug(u'register_http_file_bible %s not created already exists', biblename)
@ -165,21 +221,26 @@ class BibleManager():
log.debug(u'register_OSIS_file_bible %s , %s not created already exists', biblename, osisfile) log.debug(u'register_OSIS_file_bible %s , %s not created already exists', biblename, osisfile)
return False return False
def get_bibles(self, mode=u'full'): def get_bibles(self, mode=BibleMode.Full):
"""
Returns a list of Books of the bible. When ``mode`` is set to
``BibleMode.Full`` this method returns all the Bibles for the
Advanced Search, and when the mode is ``BibleMode.Partial``
this method returns all the bibles for the Quick Search.
``mode``
Defaults to ``BibleMode.Full``. The Bible mode.
"""
log.debug(u'get_bibles') log.debug(u'get_bibles')
""" bible_list = []
Returns a list of Books of the bible for bible_name, bible_object in self.bible_db_cache.iteritems():
Mode "Full" - Returns all the bibles for the Queck seearch if mode == BibleMode.Full:
Mode "Partial" - Returns CSV and OSIS bbles for the Advanced Search bible_list.append(bible_name)
"""
r=[]
for b , o in self.bible_db_cache.iteritems():
if mode == u'full':
r.append(b)
else: else:
if self.bible_http_cache [b] == None: # we do not have an http bible if self.bible_http_cache[bible_name] is None:
r.append(b) # we do not have an http bible
return r bible_list.append(bible_name)
return bible_list
def get_bible_books(self,bible): def get_bible_books(self,bible):
""" """
@ -192,7 +253,7 @@ class BibleManager():
""" """
Returns the number of Chapters for a given book Returns the number of Chapters for a given book
""" """
log.debug(u'get_book_chapter_count %s,%s', bible, book) log.debug(u'get_book_chapter_count %s, %s', bible, book)
return self.bible_db_cache[bible].get_max_bible_book_chapter(book) return self.bible_db_cache[bible].get_max_bible_book_chapter(book)
def get_book_verse_count(self, bible, book, chapter): def get_book_verse_count(self, bible, book, chapter):
@ -227,7 +288,7 @@ class BibleManager():
log.debug(u'get_meta %s,%s', bible, key) log.debug(u'get_meta %s,%s', bible, key)
return self.bible_db_cache[bible].get_meta(key) return self.bible_db_cache[bible].get_meta(key)
def get_verse_text(self, bible, bookname, schapter, echapter, sverse, everse = 0 ): def get_verse_text(self, bible, bookname, schapter, echapter, sverse, everse=0):
""" """
Returns a list of verses for a given Book, Chapter and ranges of verses. Returns a list of verses for a given Book, Chapter and ranges of verses.
If the end verse(everse) is less then the start verse(sverse) If the end verse(everse) is less then the start verse(sverse)
@ -237,7 +298,7 @@ class BibleManager():
""" """
text = [] text = []
log.debug(u'get_verse_text %s,%s,%s,%s,%s,%s', bible, bookname, schapter, echapter, sverse, everse) log.debug(u'get_verse_text %s,%s,%s,%s,%s,%s', bible, bookname, schapter, echapter, sverse, everse)
if not self.bible_http_cache [bible] == None: if not self.bible_http_cache[bible] == None:
# check to see if book/chapter exists # check to see if book/chapter exists
book= self.bible_db_cache[bible].get_bible_book(bookname) book= self.bible_db_cache[bible].get_bible_book(bookname)
if book == None: if book == None:

View File

@ -2,7 +2,9 @@
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 # vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
""" """
OpenLP - Open Source Lyrics Projection OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008-2009 Martin Thompson, Tim Bentley Portions copyright (c) 2008-2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under This program is free software; you can redistribute it and/or modify it under
@ -21,8 +23,10 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import ServiceItem, MediaManagerItem, Receiver, translate, contextMenuAction, contextMenuSeparator from openlp.core.lib import translate, ServiceItem, MediaManagerItem, \
Receiver, contextMenuAction, contextMenuSeparator
from openlp.plugins.bibles.forms import BibleImportForm from openlp.plugins.bibles.forms import BibleImportForm
from openlp.plugins.bibles.lib.manager import BibleMode
class BibleList(QtGui.QListWidget): class BibleList(QtGui.QListWidget):
@ -255,12 +259,12 @@ class BibleMediaItem(MediaManagerItem):
log.debug(u'Loading Bibles') log.debug(u'Loading Bibles')
self.QuickVersionComboBox.clear() self.QuickVersionComboBox.clear()
self.AdvancedVersionComboBox.clear() self.AdvancedVersionComboBox.clear()
bibles = self.parent.biblemanager.get_bibles(u'full') bibles = self.parent.biblemanager.get_bibles(BibleMode.Full)
# load bibles into the combo boxes # load bibles into the combo boxes
for bible in bibles: for bible in bibles:
self.QuickVersionComboBox.addItem(bible) self.QuickVersionComboBox.addItem(bible)
# Without HTT # Without HTTP
bibles = self.parent.biblemanager.get_bibles(u'partial') bibles = self.parent.biblemanager.get_bibles(BibleMode.Partial)
first = True first = True
# load bibles into the combo boxes # load bibles into the combo boxes
for bible in bibles: for bible in bibles:
@ -344,12 +348,12 @@ class BibleMediaItem(MediaManagerItem):
bitem = self.ListView.item(item.row()) bitem = self.ListView.item(item.row())
text = unicode((bitem.data(QtCore.Qt.UserRole)).toString()) text = unicode((bitem.data(QtCore.Qt.UserRole)).toString())
verse = text[:text.find(u'(')] verse = text[:text.find(u'(')]
bible = text[text.find(u'(') + 1:text.find(u')')] bible = text[text.find(u'(') + 1:-1]
self.searchByReference(bible, verse) self.searchByReference(bible, verse)
book = self.search_results[0][0] book = self.search_results[0].book.name
chapter = unicode(self.search_results[0][1]) chapter = unicode(self.search_results[0].chapter)
verse = unicode(self.search_results[0][2]) verse = unicode(self.search_results[0].verse)
text = self.search_results[0][3] text = self.search_results[0].text
#Paragraph style force new line per verse #Paragraph style force new line per verse
if self.parent.bibles_tab.paragraph_style: if self.parent.bibles_tab.paragraph_style:
text = text + u'\n\n' text = text + u'\n\n'
@ -406,8 +410,8 @@ class BibleMediaItem(MediaManagerItem):
def initialiseChapterVerse(self, bible, book): def initialiseChapterVerse(self, bible, book):
log.debug(u'initialiseChapterVerse %s , %s', bible, book) log.debug(u'initialiseChapterVerse %s , %s', bible, book)
self.chapters_from = self.parent.biblemanager.get_book_chapter_count(bible, book)[0] self.chapters_from = self.parent.biblemanager.get_book_chapter_count(bible, book)
self.verses = self.parent.biblemanager.get_book_verse_count(bible, book, 1)[0] self.verses = self.parent.biblemanager.get_book_verse_count(bible, book, 1)
self.adjustComboBox(1, self.chapters_from, self.AdvancedFromChapter) self.adjustComboBox(1, self.chapters_from, self.AdvancedFromChapter)
self.adjustComboBox(1, self.chapters_from, self.AdvancedToChapter) self.adjustComboBox(1, self.chapters_from, self.AdvancedToChapter)
self.adjustComboBox(1, self.verses, self.AdvancedFromVerse) self.adjustComboBox(1, self.verses, self.AdvancedFromVerse)
@ -420,10 +424,16 @@ class BibleMediaItem(MediaManagerItem):
combo.addItem(unicode(i)) combo.addItem(unicode(i))
def displayResults(self, bible): def displayResults(self, bible):
for book, chap, vse , txt in self.search_results: for verse in self.search_results:
bible_text = unicode(u' %s %d:%d (%s)'%(book , chap,vse, bible)) #bible_text = unicode(u' %s %d:%d (%s)'%(book , chap,vse, bible))
#bible_verse = QtGui.QListWidgetItem(bible_text)
#bible_verse.setData(QtCore.Qt.UserRole, QtCore.QVariant(bible_text))
#self.ListView.addItem(bible_verse)
bible_text = u' %s %d:%d (%s)' % (verse.book.name,
verse.chapter, verse.verse, bible)
bible_verse = QtGui.QListWidgetItem(bible_text) bible_verse = QtGui.QListWidgetItem(bible_text)
bible_verse.setData(QtCore.Qt.UserRole, QtCore.QVariant(bible_text)) bible_verse.setData(QtCore.Qt.UserRole,
QtCore.QVariant(bible_text))
self.ListView.addItem(bible_verse) self.ListView.addItem(bible_verse)
def searchByReference(self, bible, search): def searchByReference(self, bible, search):

View File

@ -0,0 +1,111 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
"""
import string
from sqlalchemy import Column, Table, MetaData, ForeignKey, types, \
create_engine
from sqlalchemy.orm import mapper, relation, sessionmaker, scoped_session
class BaseModel(object):
"""
BaseModel provides a base object with a set of generic functions
"""
@classmethod
def populate(cls, **kwargs):
"""
Creates an instance of a class and populates it, returning the instance
"""
me = cls()
keys = kwargs.keys()
for key in keys:
me.__setattr__(key, kwargs[key])
return me
class BibleMeta(BaseModel):
"""
Bible Meta Data
"""
pass
class ONTestament(BaseModel):
"""
Bible Testaments
"""
pass
class Book(BaseModel):
"""
Song model
"""
pass
class Verse(BaseModel):
"""
Topic model
"""
pass
def init_models(db_url):
engine = create_engine(db_url)
metadata.bind = engine
session = scoped_session(sessionmaker(autoflush=True,
autocommit=False,
bind=engine))
# Don't think this is needed...
#metadata.bind.echo = False
#Define the tables and indexes
return metadata, session
metadata = MetaData()
meta_table = Table(u'metadata', metadata,
Column(u'key', types.Unicode(255), primary_key=True, index=True),
Column(u'value', types.Unicode(255)),
)
testament_table = Table(u'testament', metadata,
Column(u'id', types.Integer, primary_key=True),
Column(u'name', types.Unicode(50)),
)
book_table = Table(u'book', metadata,
Column(u'id', types.Integer, primary_key=True),
Column(u'testament_id', types.Integer, ForeignKey(u'testament.id')),
Column(u'name', types.Unicode(50), index=True),
Column(u'abbreviation', types.Unicode(5), index=True),
)
verse_table = Table(u'verse', metadata,
Column(u'id', types.Integer, primary_key=True, index=True),
Column(u'book_id', types.Integer, ForeignKey(u'book.id'), index=True),
Column(u'chapter', types.Integer, index=True),
Column(u'verse', types.Integer, index=True),
Column(u'text', types.UnicodeText, index=True),
)
mapper(BibleMeta, meta_table)
mapper(ONTestament, testament_table,
properties={'books': relation(Book, backref='testament')})
mapper(Book, book_table,
properties={'verses': relation(Verse, backref='book')})
mapper(Verse, verse_table)

View File

@ -1,52 +0,0 @@
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
"""
OpenLP - Open Source Lyrics Projection
Copyright (c) 2008 Raoul Snyman
Portions copyright (c) 2008 - 2009 Martin Thompson, Tim Bentley
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
"""
import string
from sqlalchemy import *
from sqlalchemy import Column, Table, MetaData, ForeignKey, schema
metadata = MetaData()
#Define the tables and indexes
meta_table = Table(u'metadata', metadata,
Column(u'key', String(255), primary_key=True),
Column(u'value', String(255)),
)
testament_table = Table(u'testament', metadata,
Column(u'id', Integer, primary_key=True),
Column(u'name', String(30)),
)
book_table = Table(u'book', metadata,
Column(u'id', Integer, primary_key=True),
Column(u'testament_id', Integer, schema.ForeignKey(u'testament.id')),
Column(u'name', String(30)),
Column(u'abbreviation', String(5)),
)
Index(u'idx_name', book_table.c.name, book_table.c.id)
Index(u'idx_abbrev', book_table.c.abbreviation, book_table.c.id)
verse_table = Table(u'verse', metadata,
Column(u'id', Integer, primary_key=True),
Column(u'book_id', Integer , schema.ForeignKey(u'book.id')),
Column(u'chapter', Integer),
Column(u'verse', Integer),
Column(u'text', Text),
)
Index(u'idx_chapter_verse_book', verse_table.c.chapter, verse_table.c.verse, verse_table.c.book_id, verse_table.c.id)
Index(u'idx_chapter_verse_text', verse_table.c.text, verse_table.c.verse, verse_table.c.book_id, verse_table.c.id)