def __init__(self, plugin=None, name=u'PresentationController',
        document_class=PresentationDocument):
        """
        This is the constructor for the presentationcontroller object. This
        provides an easy way for descendent plugins to populate common data.
        This method *must* be overridden, like so::

            class MyPresentationController(PresentationController):
                def __init__(self, plugin):
                    PresentationController.__init(
                        self, plugin, u'My Presenter App')

        ``plugin``
            Defaults to *None*. The presentationplugin object

        ``name``
            Name of the application, to appear in the application
        """
        self.supports = []
        self.alsosupports = []
        self.docs = []
        self.plugin = plugin
        self.name = name
        self.document_class = document_class
        self.settings_section = self.plugin.settingsSection
        self.available = None
        self.temp_folder = os.path.join(AppLocation.get_section_data_path(self.settings_section), name)
        self.thumbnail_folder = os.path.join(AppLocation.get_section_data_path(self.settings_section), u'thumbnails')
        self.thumbnail_prefix = u'slide'
        check_directory_exists(self.thumbnail_folder)
        check_directory_exists(self.temp_folder)
Ejemplo n.º 2
0
 def _performWizard(self):
     """
     Run the tasks in the wizard.
     """
     # Set plugin states
     self._incrementProgressBar(translate('OpenLP.FirstTimeWizard', 'Enabling selected plugins...'))
     self._setPluginStatus(self.songsCheckBox, u'songs/status')
     self._setPluginStatus(self.bibleCheckBox, u'bibles/status')
     # TODO Presentation plugin is not yet working on Mac OS X.
     # For now just ignore it.
     if sys.platform != 'darwin':
         self._setPluginStatus(self.presentationCheckBox, u'presentations/status')
     self._setPluginStatus(self.imageCheckBox, u'images/status')
     self._setPluginStatus(self.mediaCheckBox, u'media/status')
     self._setPluginStatus(self.remoteCheckBox, u'remotes/status')
     self._setPluginStatus(self.customCheckBox, u'custom/status')
     self._setPluginStatus(self.songUsageCheckBox, u'songusage/status')
     self._setPluginStatus(self.alertCheckBox, u'alerts/status')
     if self.webAccess:
         # Build directories for downloads
         songs_destination = os.path.join(
             unicode(gettempdir(), get_filesystem_encoding()), u'openlp')
         bibles_destination = AppLocation.get_section_data_path(u'bibles')
         themes_destination = AppLocation.get_section_data_path(u'themes')
         # Download songs
         for i in xrange(self.songsListWidget.count()):
             item = self.songsListWidget.item(i)
             if item.checkState() == QtCore.Qt.Checked:
                 filename = item.data(QtCore.Qt.UserRole)
                 self._incrementProgressBar(self.downloading % filename, 0)
                 self.previous_size = 0
                 destination = os.path.join(songs_destination, unicode(filename))
                 self.urlGetFile(u'%s%s' % (self.web, filename), destination)
         # Download Bibles
         bibles_iterator = QtGui.QTreeWidgetItemIterator(
             self.biblesTreeWidget)
         while bibles_iterator.value():
             item = bibles_iterator.value()
             if item.parent() and item.checkState(0) == QtCore.Qt.Checked:
                 bible = item.data(0, QtCore.Qt.UserRole)
                 self._incrementProgressBar(self.downloading % bible, 0)
                 self.previous_size = 0
                 self.urlGetFile(u'%s%s' % (self.web, bible), os.path.join(bibles_destination, bible))
             bibles_iterator += 1
         # Download themes
         for i in xrange(self.themesListWidget.count()):
             item = self.themesListWidget.item(i)
             if item.checkState() == QtCore.Qt.Checked:
                 theme = item.data(QtCore.Qt.UserRole)
                 self._incrementProgressBar(self.downloading % theme, 0)
                 self.previous_size = 0
                 self.urlGetFile(u'%s%s' % (self.web, theme), os.path.join(themes_destination, theme))
     # Set Default Display
     if self.displayComboBox.currentIndex() != -1:
         Settings().setValue(u'General/monitor', self.displayComboBox.currentIndex())
         self.screens.set_current_display(self.displayComboBox.currentIndex())
     # Set Global Theme
     if self.themeComboBox.currentIndex() != -1:
         Settings().setValue(u'themes/global theme', self.themeComboBox.currentText())
Ejemplo n.º 3
0
 def _perform_wizard(self):
     """
     Run the tasks in the wizard.
     """
     # Set plugin states
     self._increment_progress_bar(translate('OpenLP.FirstTimeWizard', 'Enabling selected plugins...'))
     self._set_plugin_status(self.songs_check_box, 'songs/status')
     self._set_plugin_status(self.bible_check_box, 'bibles/status')
     # TODO Presentation plugin is not yet working on Mac OS X.
     # For now just ignore it.
     if sys.platform != 'darwin':
         self._set_plugin_status(self.presentation_check_box, 'presentations/status')
     self._set_plugin_status(self.image_check_box, 'images/status')
     self._set_plugin_status(self.media_check_box, 'media/status')
     self._set_plugin_status(self.remote_check_box, 'remotes/status')
     self._set_plugin_status(self.custom_check_box, 'custom/status')
     self._set_plugin_status(self.song_usage_check_box, 'songusage/status')
     self._set_plugin_status(self.alert_check_box, 'alerts/status')
     if self.web_access:
         # Build directories for downloads
         songs_destination = os.path.join(gettempdir(), 'openlp')
         bibles_destination = AppLocation.get_section_data_path('bibles')
         themes_destination = AppLocation.get_section_data_path('themes')
         # Download songs
         for i in range(self.songs_list_widget.count()):
             item = self.songs_list_widget.item(i)
             if item.checkState() == QtCore.Qt.Checked:
                 filename = item.data(QtCore.Qt.UserRole)
                 self._increment_progress_bar(self.downloading % filename, 0)
                 self.previous_size = 0
                 destination = os.path.join(songs_destination, str(filename))
                 self.url_get_file('%s%s' % (self.web, filename), destination)
         # Download Bibles
         bibles_iterator = QtGui.QTreeWidgetItemIterator(
             self.bibles_tree_widget)
         while bibles_iterator.value():
             item = bibles_iterator.value()
             if item.parent() and item.checkState(0) == QtCore.Qt.Checked:
                 bible = item.data(0, QtCore.Qt.UserRole)
                 self._increment_progress_bar(self.downloading % bible, 0)
                 self.previous_size = 0
                 self.url_get_file('%s%s' % (self.web, bible), os.path.join(bibles_destination, bible))
             bibles_iterator += 1
         # Download themes
         for i in range(self.themes_list_widget.count()):
             item = self.themes_list_widget.item(i)
             if item.checkState() == QtCore.Qt.Checked:
                 theme = item.data(QtCore.Qt.UserRole)
                 self._increment_progress_bar(self.downloading % theme, 0)
                 self.previous_size = 0
                 self.url_get_file('%s%s' % (self.web, theme), os.path.join(themes_destination, theme))
     # Set Default Display
     if self.display_combo_box.currentIndex() != -1:
         Settings().setValue('core/monitor', self.display_combo_box.currentIndex())
         self.screens.set_current_display(self.display_combo_box.currentIndex())
     # Set Global Theme
     if self.theme_combo_box.currentIndex() != -1:
         Settings().setValue('themes/global theme', self.theme_combo_box.currentText())
Ejemplo n.º 4
0
 def _update_background_audio(self, song, item):
     song.media_files = []
     for i, bga in enumerate(item.background_audio):
         dest_file = os.path.join(
             AppLocation.get_section_data_path(self.plugin.name), 'audio', str(song.id), os.path.split(bga)[1])
         check_directory_exists(os.path.split(dest_file)[0])
         shutil.copyfile(os.path.join(AppLocation.get_section_data_path('servicemanager'), bga), dest_file)
         song.media_files.append(MediaFile.populate(weight=i, file_name=dest_file))
     self.plugin.manager.save_object(song, True)
Ejemplo n.º 5
0
    def __init__(self, plugin_name, init_schema, db_file_name=None, upgrade_mod=None):
        """
        Runs the initialisation process that includes creating the connection to the database and the tables if they do
        not exist.

        ``plugin_name``
            The name to setup paths and settings section names

        ``init_schema``
            The init_schema function for this database

        ``upgrade_schema``
            The upgrade_schema function for this database

        ``db_file_name``
            The file name to use for this database. Defaults to None resulting in the plugin_name being used.
        """
        settings = Settings()
        settings.beginGroup(plugin_name)
        self.db_url = ''
        self.is_dirty = False
        self.session = None
        db_type = settings.value('db type')
        if db_type == 'sqlite':
            if db_file_name:
                self.db_url = 'sqlite:///%s/%s' % (AppLocation.get_section_data_path(plugin_name), db_file_name)
            else:
                self.db_url = 'sqlite:///%s/%s.sqlite' % (AppLocation.get_section_data_path(plugin_name), plugin_name)
        else:
            self.db_url = '%s://%s:%s@%s/%s' % (db_type,
                urlquote(settings.value('db username')),
                urlquote(settings.value('db password')),
                urlquote(settings.value('db hostname')),
                urlquote(settings.value('db database')))
            if db_type == 'mysql':
                db_encoding = settings.value('db encoding')
                self.db_url += '?charset=%s' % urlquote(db_encoding)
        settings.endGroup()
        if upgrade_mod:
            db_ver, up_ver = upgrade_db(self.db_url, upgrade_mod)
            if db_ver > up_ver:
                critical_error_message_box(
                    translate('OpenLP.Manager', 'Database Error'),
                    translate('OpenLP.Manager', 'The database being loaded was created in a more recent version of '
                        'OpenLP. The database is version %d, while OpenLP expects version %d. The database will not '
                        'be loaded.\n\nDatabase: %s') % (db_ver, up_ver, self.db_url)
                )
                return
        try:
            self.session = init_schema(self.db_url)
        except (SQLAlchemyError, DBAPIError):
            log.exception('Error loading database: %s', self.db_url)
            critical_error_message_box(
                translate('OpenLP.Manager', 'Database Error'),
                translate('OpenLP.Manager', 'OpenLP cannot load your database.\n\nDatabase: %s') % self.db_url
            )
Ejemplo n.º 6
0
def delete_database(plugin_name, db_file_name=None):
    """
    Remove a database file from the system.

    ``plugin_name``
        The name of the plugin to remove the database for

    ``db_file_name``
        The database file name. Defaults to None resulting in the plugin_name being used.
    """
    db_file_path = None
    if db_file_name:
        db_file_path = os.path.join(AppLocation.get_section_data_path(plugin_name), db_file_name)
    else:
        db_file_path = os.path.join(AppLocation.get_section_data_path(plugin_name), plugin_name)
    return delete_file(db_file_path)
Ejemplo n.º 7
0
 def initialise(self):
     self.list_view.clear()
     self.list_view.setIconSize(QtCore.QSize(88, 50))
     self.servicePath = os.path.join(AppLocation.get_section_data_path(self.settings_section), 'thumbnails')
     check_directory_exists(self.servicePath)
     self.load_list(Settings().value(self.settings_section + '/media files'))
     self.populateDisplayTypes()
Ejemplo n.º 8
0
 def onDeleteClick(self):
     """
     Remove a song from the list and database
     """
     if check_item_selected(self.listView, UiStrings().SelectDelete):
         items = self.listView.selectedIndexes()
         if QtGui.QMessageBox.question(self,
             UiStrings().ConfirmDelete,
             translate('SongsPlugin.MediaItem', 'Are you sure you want to delete the %n selected song(s)?', '',
             QtCore.QCoreApplication.CodecForTr, len(items)),
             QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No),
             QtGui.QMessageBox.Yes) == QtGui.QMessageBox.No:
             return
         self.application.set_busy_cursor()
         self.main_window.displayProgressBar(len(items))
         for item in items:
             item_id = item.data(QtCore.Qt.UserRole)
             media_files = self.plugin.manager.get_all_objects(MediaFile, MediaFile.song_id == item_id)
             for media_file in media_files:
                 try:
                     os.remove(media_file.file_name)
                 except:
                     log.exception('Could not remove file: %s', media_file.file_name)
             try:
                 save_path = os.path.join(AppLocation.get_section_data_path(self.plugin.name), 'audio', str(item_id))
                 if os.path.exists(save_path):
                     os.rmdir(save_path)
             except OSError:
                 log.exception(u'Could not remove directory: %s', save_path)
             self.plugin.manager.delete_object(Song, item_id)
             self.main_window.incrementProgressBar()
         self.main_window.finishedProgressBar()
         self.application.set_normal_cursor()
         self.onSearchTextButtonClicked()
Ejemplo n.º 9
0
 def initialise(self):
     log.debug('initialise')
     self.list_view.clear()
     self.list_view.setIconSize(QtCore.QSize(88, 50))
     self.list_view.setIndentation(self.list_view.default_indentation)
     self.list_view.allow_internal_dnd = True
     self.servicePath = os.path.join(AppLocation.get_section_data_path(self.settings_section), 'thumbnails')
     check_directory_exists(self.servicePath)
     # Load images from the database
     self.load_full_list(
         self.manager.get_all_objects(ImageFilenames, order_by_ref=ImageFilenames.filename), initial_load=True)
Ejemplo n.º 10
0
 def get_section_data_path_test(self):
     """
     Test the AppLocation.get_section_data_path() method
     """
     with patch(u'openlp.core.utils.AppLocation.get_data_path') as mocked_get_data_path, \
          patch(u'openlp.core.utils.check_directory_exists') as mocked_check_directory_exists:
         # GIVEN: A mocked out AppLocation.get_data_path()
         mocked_get_data_path.return_value = u'test/dir'
         mocked_check_directory_exists.return_value = True
         # WHEN: we call AppLocation.get_data_path()
         data_path = AppLocation.get_section_data_path(u'section')
         # THEN: check that all the correct methods were called, and the result is correct
         mocked_check_directory_exists.assert_called_with(u'test/dir/section')
         assert data_path == u'test/dir/section', u'Result should be "test/dir/section"'
Ejemplo n.º 11
0
    def copyMediaFile(self, song_id, filename):
        """
        This method copies the media file to the correct location and returns
        the new file location.

        ``filename``
            The file to copy.
        """
        if not hasattr(self, 'save_path'):
            self.save_path = os.path.join(AppLocation.get_section_data_path(self.import_wizard.plugin.name),
                'audio', str(song_id))
        check_directory_exists(self.save_path)
        if not filename.startswith(self.save_path):
            oldfile, filename = filename, os.path.join(self.save_path, os.path.split(filename)[1])
            shutil.copyfile(oldfile, filename)
        return filename
Ejemplo n.º 12
0
    def __init__(self, parent):
        """
        Finds all the bibles defined for the system and creates an interface
        object for each bible containing connection information. Throws
        Exception if no Bibles are found.

        Init confirms the bible exists and stores the database path.
        """
        log.debug('Bible Initialising')
        self.parent = parent
        self.settings_section = 'bibles'
        self.web = 'Web'
        self.db_cache = None
        self.path = AppLocation.get_section_data_path(self.settings_section)
        self.proxy_name = Settings().value(self.settings_section + '/proxy name')
        self.suffix = '.sqlite'
        self.import_wizard = None
        self.reload_bibles()
        self.media = None
Ejemplo n.º 13
0
    def __init__(self, parent, manager, bibleplugin):
        """
        Instantiate the wizard, and run any extra setup we need to.

        ``parent``
            The QWidget-derived parent of the wizard.

        ``manager``
            The Bible manager.

        ``bibleplugin``
            The Bible plugin.
        """
        self.manager = manager
        self.mediaItem = bibleplugin.mediaItem
        self.suffix = u'.sqlite'
        self.settingsSection = u'bibles'
        self.path = AppLocation.get_section_data_path(self.settingsSection)
        self.temp_dir = os.path.join(unicode(gettempdir(), get_filesystem_encoding()), u'openlp')
        self.files = self.manager.old_bible_databases
        self.success = {}
        self.newbibles = {}
        OpenLPWizard.__init__(self, parent, bibleplugin, u'bibleUpgradeWizard', u':/wizards/wizard_importbible.bmp')
Ejemplo n.º 14
0
def delete_song(song_id, song_plugin):
    """
    Deletes a song from the database. Media files associated to the song
    are removed prior to the deletion of the song.

    ``song_id``
        The ID of the song to delete.

    ``song_plugin``
        The song plugin instance.
    """
    media_files = song_plugin.manager.get_all_objects(MediaFile, MediaFile.song_id == song_id)
    for media_file in media_files:
        try:
            os.remove(media_file.file_name)
        except:
            log.exception('Could not remove file: %s', media_file.file_name)
    try:
        save_path = os.path.join(AppLocation.get_section_data_path(song_plugin.name), 'audio', str(song_id))
        if os.path.exists(save_path):
            os.rmdir(save_path)
    except OSError:
        log.exception('Could not remove directory: %s', save_path)
    song_plugin.manager.delete_object(Song, song_id)
Ejemplo n.º 15
0
    def __init__(self, parent, manager, bible_plugin):
        """
        Instantiate the wizard, and run any extra setup we need to.

        ``parent``
            The QWidget-derived parent of the wizard.

        ``manager``
            The Bible manager.

        ``bible_plugin``
            The Bible plugin.
        """
        self.manager = manager
        self.media_item = bible_plugin.media_item
        self.suffix = '.sqlite'
        self.settings_section = 'bibles'
        self.path = AppLocation.get_section_data_path(self.settings_section)
        self.temp_dir = os.path.join(gettempdir(), 'openlp')
        self.files = self.manager.old_bible_databases
        self.success = {}
        self.new_bibles = {}
        super(BibleUpgradeForm, self).__init__(
            parent, bible_plugin, 'bibleUpgradeWizard', ':/wizards/wizard_importbible.bmp')
Ejemplo n.º 16
0
 def validateCurrentPage(self):
     """
     Validate the current page before moving on to the next page.
     """
     if self.currentPage() == self.welcomePage:
         return True
     elif self.currentPage() == self.selectPage:
         if self.field(u'source_format') == BibleFormat.OSIS:
             if not self.field(u'osis_location'):
                 critical_error_message_box(UiStrings().NFSs, WizardStrings.YouSpecifyFile % WizardStrings.OSIS)
                 self.osisFileEdit.setFocus()
                 return False
         elif self.field(u'source_format') == BibleFormat.CSV:
             if not self.field(u'csv_booksfile'):
                 critical_error_message_box(UiStrings().NFSs, translate('BiblesPlugin.ImportWizardForm',
                     'You need to specify a file with books of the Bible to use in the import.'))
                 self.csvBooksEdit.setFocus()
                 return False
             elif not self.field(u'csv_versefile'):
                 critical_error_message_box(UiStrings().NFSs,
                     translate('BiblesPlugin.ImportWizardForm',
                         'You need to specify a file of Bible verses to import.'))
                 self.csvVersesEdit.setFocus()
                 return False
         elif self.field(u'source_format') == BibleFormat.OpenSong:
             if not self.field(u'opensong_file'):
                 critical_error_message_box(UiStrings().NFSs, WizardStrings.YouSpecifyFile % WizardStrings.OS)
                 self.openSongFileEdit.setFocus()
                 return False
         elif self.field(u'source_format') == BibleFormat.WebDownload:
             self.versionNameEdit.setText(self.webTranslationComboBox.currentText())
             return True
         elif self.field(u'source_format') == BibleFormat.OpenLP1:
             if not self.field(u'openlp1_location'):
                 critical_error_message_box(UiStrings().NFSs, WizardStrings.YouSpecifyFile % UiStrings().OLPV1)
                 self.openlp1FileEdit.setFocus()
                 return False
         return True
     elif self.currentPage() == self.licenseDetailsPage:
         license_version = self.field(u'license_version')
         license_copyright = self.field(u'license_copyright')
         path = AppLocation.get_section_data_path(u'bibles')
         if not license_version:
             critical_error_message_box(UiStrings().EmptyField,
                 translate('BiblesPlugin.ImportWizardForm', 'You need to specify a version name for your Bible.'))
             self.versionNameEdit.setFocus()
             return False
         elif not license_copyright:
             critical_error_message_box(UiStrings().EmptyField,
                 translate('BiblesPlugin.ImportWizardForm', 'You need to set a copyright for your Bible. '
                     'Bibles in the Public Domain need to be marked as such.'))
             self.copyrightEdit.setFocus()
             return False
         elif self.manager.exists(license_version):
             critical_error_message_box(translate('BiblesPlugin.ImportWizardForm', 'Bible Exists'),
                 translate('BiblesPlugin.ImportWizardForm',
                     'This Bible already exists. Please import a different Bible or first delete the existing one.'))
             self.versionNameEdit.setFocus()
             return False
         elif os.path.exists(os.path.join(path, clean_filename(
             license_version))):
             critical_error_message_box(
                 translate('BiblesPlugin.ImportWizardForm', 'Bible Exists'),
                 translate('BiblesPlugin.ImportWizardForm', 'This Bible already exists. Please import '
                     'a different Bible or first delete the existing one.'))
             self.versionNameEdit.setFocus()
             return False
         return True
     if self.currentPage() == self.progressPage:
         return True
Ejemplo n.º 17
0
    def save_song(self, preview=False):
        """
        Get all the data from the widgets on the form, and then save it to the
        database. The form has been validated and all reference items
        (Authors, Books and Topics) have been saved before this function is
        called.

        ``preview``
            Should be ``True`` if the song is also previewed (boolean).
        """
        # The Song() assignment. No database calls should be made while a
        # Song() is in a partially complete state.
        if not self.song:
            self.song = Song()
        self.song.title = self.title_edit.text()
        self.song.alternate_title = self.alternative_edit.text()
        self.song.copyright = self.copyright_edit.text()
        # Values will be set when cleaning the song.
        self.song.search_title = ''
        self.song.search_lyrics = ''
        self.song.verse_order = ''
        self.song.comments = self.comments_edit.toPlainText()
        ordertext = self.verse_order_edit.text()
        order = []
        for item in ordertext.split():
            verse_tag = VerseType.tags[VerseType.from_translated_tag(item[0])]
            verse_num = item[1:].lower()
            order.append('%s%s' % (verse_tag, verse_num))
        self.song.verse_order = ' '.join(order)
        self.song.ccli_number = self.ccli_number_edit.text()
        self.song.song_number = self.song_book_number_edit.text()
        book_name = self.song_book_combo_box.currentText()
        if book_name:
            self.song.book = self.manager.get_object_filtered(Book,
                Book.name == book_name)
        else:
            self.song.book = None
        theme_name = self.theme_combo_box.currentText()
        if theme_name:
            self.song.theme_name = theme_name
        else:
            self.song.theme_name = None
        self._process_lyrics()
        self.song.authors = []
        for row in range(self.authors_list_view.count()):
            item = self.authors_list_view.item(row)
            authorId = (item.data(QtCore.Qt.UserRole))
            author = self.manager.get_object(Author, authorId)
            if author is not None:
                self.song.authors.append(author)
        self.song.topics = []
        for row in range(self.topics_list_view.count()):
            item = self.topics_list_view.item(row)
            topicId = (item.data(QtCore.Qt.UserRole))
            topic = self.manager.get_object(Topic, topicId)
            if topic is not None:
                self.song.topics.append(topic)
        # Save the song here because we need a valid id for the audio files.
        clean_song(self.manager, self.song)
        self.manager.save_object(self.song)
        audio_files = [a.file_name for a in self.song.media_files]
        log.debug(audio_files)
        save_path = os.path.join(AppLocation.get_section_data_path(self.media_item.plugin.name), 'audio',
            str(self.song.id))
        check_directory_exists(save_path)
        self.song.media_files = []
        files = []
        for row in range(self.audio_list_widget.count()):
            item = self.audio_list_widget.item(row)
            filename = item.data(QtCore.Qt.UserRole)
            if not filename.startswith(save_path):
                oldfile, filename = filename, os.path.join(save_path, os.path.split(filename)[1])
                shutil.copyfile(oldfile, filename)
            files.append(filename)
            media_file = MediaFile()
            media_file.file_name = filename
            media_file.type = 'audio'
            media_file.weight = row
            self.song.media_files.append(media_file)
        for audio in audio_files:
            if audio not in files:
                try:
                    os.remove(audio)
                except:
                    log.exception('Could not remove file: %s', audio)
        if not files:
            try:
                os.rmdir(save_path)
            except OSError:
                log.exception('Could not remove directory: %s', save_path)
        clean_song(self.manager, self.song)
        self.manager.save_object(self.song)
        self.media_item.auto_select_id = self.song.id