Example #1
0
    def __init__(self, plugin=None, name='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, 'My Presenter App')

        :param plugin:  Defaults to *None*. The presentationplugin object
        :param name: Name of the application, to appear in the application
        :param document_class:
        """
        self.supports = []
        self.also_supports = []
        self.docs = []
        self.plugin = plugin
        self.name = name
        self.document_class = document_class
        self.settings_section = self.plugin.settings_section
        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), 'thumbnails')
        self.thumbnail_prefix = 'slide'
        check_directory_exists(self.thumbnail_folder)
        check_directory_exists(self.temp_folder)
    def __init__(self, plugin=None, name='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, 'My Presenter App')

        :param plugin:  Defaults to *None*. The presentationplugin object
        :param name: Name of the application, to appear in the application
        :param document_class:
        """
        self.supports = []
        self.also_supports = []
        self.docs = []
        self.plugin = plugin
        self.name = name
        self.document_class = document_class
        self.settings_section = self.plugin.settings_section
        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), 'thumbnails')
        self.thumbnail_prefix = 'slide'
        check_directory_exists(self.thumbnail_folder)
        check_directory_exists(self.temp_folder)
Example #3
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)
Example #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)
Example #5
0
 def _download_selected(self):
     """
     Download selected songs, bibles and themes. Returns False on download error
     """
     # 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')
     missed_files = []
     # 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, sha256 = 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))
             if not self.url_get_file('%s%s' % (self.songs_url, filename), destination, sha256):
                 missed_files.append('Song: {}'.format(filename))
     # 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, sha256 = item.data(0, QtCore.Qt.UserRole)
             self._increment_progress_bar(self.downloading % bible, 0)
             self.previous_size = 0
             if not self.url_get_file('%s%s' % (self.bibles_url, bible), os.path.join(bibles_destination, bible),
                                      sha256):
                 missed_files.append('Bible: {}'.format(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, sha256 = item.data(QtCore.Qt.UserRole)
             self._increment_progress_bar(self.downloading % theme, 0)
             self.previous_size = 0
             if not self.url_get_file('%s%s' % (self.themes_url, theme), os.path.join(themes_destination, theme),
                                      sha256):
                 missed_files.append('Theme: {}'.format(theme))
     if missed_files:
         file_list = ''
         for entry in missed_files:
             file_list += '{}<br \>'.format(entry)
         msg = QtGui.QMessageBox()
         msg.setIcon(QtGui.QMessageBox.Warning)
         msg.setWindowTitle(translate('OpenLP.FirstTimeWizard', 'Network Error'))
         msg.setText(translate('OpenLP.FirstTimeWizard', 'Unable to download some files'))
         msg.setInformativeText(translate('OpenLP.FirstTimeWizard',
                                          'The following files were not able to be '
                                          'downloaded:<br \>{}'.format(file_list)))
         msg.setStandardButtons(msg.Ok)
         ans = msg.exec_()
     return True
 def _download_selected(self):
     """
     Download selected songs, bibles and themes. Returns False on download error
     """
     # 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')
     missed_files = []
     # 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, sha256 = 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))
             if not self.url_get_file('%s%s' % (self.songs_url, filename), destination, sha256):
                 missed_files.append('Song: {}'.format(filename))
     # Download Bibles
     bibles_iterator = QtWidgets.QTreeWidgetItemIterator(self.bibles_tree_widget)
     while bibles_iterator.value():
         item = bibles_iterator.value()
         if item.parent() and item.checkState(0) == QtCore.Qt.Checked:
             bible, sha256 = item.data(0, QtCore.Qt.UserRole)
             self._increment_progress_bar(self.downloading % bible, 0)
             self.previous_size = 0
             if not self.url_get_file('%s%s' % (self.bibles_url, bible), os.path.join(bibles_destination, bible),
                                      sha256):
                 missed_files.append('Bible: {}'.format(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, sha256 = item.data(QtCore.Qt.UserRole)
             self._increment_progress_bar(self.downloading % theme, 0)
             self.previous_size = 0
             if not self.url_get_file('%s%s' % (self.themes_url, theme), os.path.join(themes_destination, theme),
                                      sha256):
                 missed_files.append('Theme: {}'.format(theme))
     if missed_files:
         file_list = ''
         for entry in missed_files:
             file_list += '{}<br \>'.format(entry)
         msg = QtWidgets.QMessageBox()
         msg.setIcon(QtWidgets.QMessageBox.Warning)
         msg.setWindowTitle(translate('OpenLP.FirstTimeWizard', 'Network Error'))
         msg.setText(translate('OpenLP.FirstTimeWizard', 'Unable to download some files'))
         msg.setInformativeText(translate('OpenLP.FirstTimeWizard',
                                          'The following files were not able to be '
                                          'downloaded:<br \>{}'.format(file_list)))
         msg.setStandardButtons(msg.Ok)
         ans = msg.exec()
     return True
Example #7
0
def delete_database(plugin_name, db_file_name=None):
    """
    Remove a database file from the system.

    :param plugin_name: The name of the plugin to remove the database for
    :param db_file_name: The database file name. Defaults to None resulting in the plugin_name being used.
    """
    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)
Example #8
0
def get_db_path(plugin_name, db_file_name=None):
    """
    Create a path to a database from the plugin name and database name

    :param plugin_name: Name of plugin
    :param db_file_name: File name of database
    :return: The path to the database as type str
    """
    if db_file_name is None:
        return 'sqlite:///%s/%s.sqlite' % (AppLocation.get_section_data_path(plugin_name), plugin_name)
    else:
        return 'sqlite:///%s/%s' % (AppLocation.get_section_data_path(plugin_name), db_file_name)
Example #9
0
File: db.py Project: jkunle/paul
def get_db_path(plugin_name, db_file_name=None):
    """
    Create a path to a database from the plugin name and database name

    :param plugin_name: Name of plugin
    :param db_file_name: File name of database
    :return: The path to the database as type str
    """
    if db_file_name is None:
        return 'sqlite:///%s/%s.sqlite' % (
            AppLocation.get_section_data_path(plugin_name), plugin_name)
    else:
        return 'sqlite:///%s/%s' % (
            AppLocation.get_section_data_path(plugin_name), db_file_name)
Example #10
0
File: db.py Project: jkunle/paul
def delete_database(plugin_name, db_file_name=None):
    """
    Remove a database file from the system.

    :param plugin_name: The name of the plugin to remove the database for
    :param db_file_name: The database file name. Defaults to None resulting in the plugin_name being used.
    """
    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)
Example #11
0
def get_db_path(plugin_name, db_file_name=None):
    """
    Create a path to a database from the plugin name and database name

    :param plugin_name: Name of plugin
    :param db_file_name: File name of database
    :return: The path to the database as type str
    """
    if db_file_name is None:
        return 'sqlite:///{path}/{plugin}.sqlite'.format(path=AppLocation.get_section_data_path(plugin_name),
                                                         plugin=plugin_name)
    else:
        return 'sqlite:///{path}/{name}'.format(path=AppLocation.get_section_data_path(plugin_name),
                                                name=db_file_name)
Example #12
0
def get_db_path(plugin_name, db_file_name=None):
    """
    Create a path to a database from the plugin name and database name

    :param plugin_name: Name of plugin
    :param db_file_name: File name of database
    :return: The path to the database as type str
    """
    if db_file_name is None:
        return 'sqlite:///{path}/{plugin}.sqlite'.format(
            path=AppLocation.get_section_data_path(plugin_name),
            plugin=plugin_name)
    else:
        return 'sqlite:///{path}/{name}'.format(
            path=AppLocation.get_section_data_path(plugin_name),
            name=db_file_name)
Example #13
0
 def on_clone_click(self):
     """
     Clone a Song
     """
     log.debug('on_clone_click')
     if check_item_selected(self.list_view, UiStrings().SelectEdit):
         self.edit_item = self.list_view.currentItem()
         item_id = self.edit_item.data(QtCore.Qt.UserRole)
         old_song = self.plugin.manager.get_object(Song, item_id)
         song_xml = self.open_lyrics.song_to_xml(old_song)
         new_song = self.open_lyrics.xml_to_song(song_xml)
         new_song.title = '%s <%s>' % \
                          (new_song.title, translate('SongsPlugin.MediaItem', 'copy', 'For song cloning'))
         # Copy audio files from the old to the new song
         if len(old_song.media_files) > 0:
             save_path = os.path.join(AppLocation.get_section_data_path(self.plugin.name), 'audio', str(new_song.id))
             check_directory_exists(save_path)
             for media_file in old_song.media_files:
                 new_media_file_name = os.path.join(save_path, os.path.basename(media_file.file_name))
                 shutil.copyfile(media_file.file_name, new_media_file_name)
                 new_media_file = MediaFile()
                 new_media_file.file_name = new_media_file_name
                 new_media_file.type = media_file.type
                 new_media_file.weight = media_file.weight
                 new_song.media_files.append(new_media_file)
         self.plugin.manager.save_object(new_song)
     self.on_song_list_load()
Example #14
0
 def serve_thumbnail(self, controller_name=None, dimensions=None, file_name=None):
     """
     Serve an image file. If not found return 404.
     """
     log.debug('serve thumbnail %s/thumbnails%s/%s' % (controller_name, dimensions, file_name))
     supported_controllers = ['presentations', 'images']
     # -1 means use the default dimension in ImageManager
     width = -1
     height = -1
     if dimensions:
         match = re.search('(\d+)x(\d+)', dimensions)
         if match:
             # let's make sure that the dimensions are within reason
             width = sorted([10, int(match.group(1)), 1000])[1]
             height = sorted([10, int(match.group(2)), 1000])[1]
     content = ''
     content_type = None
     if controller_name and file_name:
         if controller_name in supported_controllers:
             full_path = urllib.parse.unquote(file_name)
             if '..' not in full_path:  # no hacking please
                 full_path = os.path.normpath(os.path.join(AppLocation.get_section_data_path(controller_name),
                                                           'thumbnails/' + full_path))
                 if os.path.exists(full_path):
                     path, just_file_name = os.path.split(full_path)
                     self.image_manager.add_image(full_path, just_file_name, None, width, height)
                     ext, content_type = self.get_content_type(full_path)
                     image = self.image_manager.get_image(full_path, just_file_name, width, height)
                     content = image_to_byte(image, False)
     if len(content) == 0:
         return self.do_not_found()
     self.send_response(200)
     self.send_header('Content-type', content_type)
     self.end_headers()
     return content
Example #15
0
 def on_clone_click(self):
     """
     Clone a Song
     """
     log.debug('on_clone_click')
     if check_item_selected(self.list_view, UiStrings().SelectEdit):
         self.edit_item = self.list_view.currentItem()
         item_id = self.edit_item.data(QtCore.Qt.UserRole)
         old_song = self.plugin.manager.get_object(Song, item_id)
         song_xml = self.open_lyrics.song_to_xml(old_song)
         new_song = self.open_lyrics.xml_to_song(song_xml)
         new_song.title = '{title} <{text}>'.format(title=new_song.title,
                                                    text=translate('SongsPlugin.MediaItem',
                                                                   'copy', 'For song cloning'))
         # Copy audio files from the old to the new song
         if len(old_song.media_files) > 0:
             save_path = os.path.join(AppLocation.get_section_data_path(self.plugin.name), 'audio', str(new_song.id))
             check_directory_exists(save_path)
             for media_file in old_song.media_files:
                 new_media_file_name = os.path.join(save_path, os.path.basename(media_file.file_name))
                 shutil.copyfile(media_file.file_name, new_media_file_name)
                 new_media_file = MediaFile()
                 new_media_file.file_name = new_media_file_name
                 new_media_file.type = media_file.type
                 new_media_file.weight = media_file.weight
                 new_song.media_files.append(new_media_file)
         self.plugin.manager.save_object(new_song)
     self.on_song_list_load()
Example #16
0
    def add_from_command(self, path, file_name, image, display_title=None, notes=None):
        """
        Add a slide from a command.

        :param path: The title of the slide in the service item.
        :param file_name: The title of the slide in the service item.
        :param image: The command of/for the slide.
        :param display_title: Title to show in gui/webinterface, optional.
        :param notes: Notes to show in the webinteface, optional.
        """
        self.service_item_type = ServiceItemType.Command
        # If the item should have a display title but this frame doesn't have one, we make one up
        if self.is_capable(ItemCapabilities.HasDisplayTitle) and not display_title:
            display_title = translate('OpenLP.ServiceItem',
                                      '[slide {frame:d}]').format(frame=len(self._raw_frames) + 1)
        # Update image path to match servicemanager location if file was loaded from service
        if image and not self.has_original_files and self.name == 'presentations':
            file_location = os.path.join(path, file_name)
            file_location_hash = md5_hash(file_location.encode('utf-8'))
            image = os.path.join(AppLocation.get_section_data_path(self.name), 'thumbnails',
                                 file_location_hash, ntpath.basename(image))
        self._raw_frames.append({'title': file_name, 'image': image, 'path': path,
                                 'display_title': display_title, 'notes': notes})
        if self.is_capable(ItemCapabilities.HasThumbnails):
            self.image_manager.add_image(image, ImageSource.CommandPlugins, '#000000')
        self._new_item()
Example #17
0
 def build_loop_path(self):
     """
     Set up the loop path variables
     """
     self.path = AppLocation.get_section_data_path(self.settings_section)
     check_directory_exists(self.path)
     self.thumb_path = os.path.join(self.path, 'thumbnails')
     check_directory_exists(self.thumb_path)
Example #18
0
 def build_theme_path(self):
     """
     Set up the theme path variables
     """
     self.path = AppLocation.get_section_data_path(self.settings_section)
     check_directory_exists(self.path)
     self.thumb_path = os.path.join(self.path, 'thumbnails')
     check_directory_exists(self.thumb_path)
Example #19
0
 def initialise(self):
     """
     Initialize media item.
     """
     self.list_view.clear()
     self.service_path = os.path.join(AppLocation.get_section_data_path(self.settings_section), 'thumbnails')
     check_directory_exists(self.service_path)
     self.load_list(Settings().value(self.settings_section + '/media files'))
     self.rebuild_players()
Example #20
0
    def build_html(self, service_item, image_path=''):
        """
        Store the service_item and build the new HTML from it. Add the HTML to the display

        :param service_item: The Service item to be used
        :param image_path: Where the image resides.
        """
        self.web_loaded = False
        self.initial_fame = None
        self.service_item = service_item
        background = None
        # We have an image override so keep the image till the theme changes.
        if self.override:
            # We have an video override so allow it to be stopped.
            if 'video' in self.override:
                Registry().execute('video_background_replaced')
                self.override = {}
            # We have a different theme.
            elif self.override['theme'] != service_item.theme_data.background_filename:
                Registry().execute('live_theme_changed')
                self.override = {}
            else:
                # replace the background
                background = self.image_manager.get_image_bytes(self.override['image'], ImageSource.ImagePlugin)
        self.set_transparency(self.service_item.theme_data.background_type ==
                              BackgroundType.to_string(BackgroundType.Transparent))
        image_bytes = None
        if self.service_item.theme_data.background_type == 'image':
            if self.service_item.theme_data.background_filename:
                self.service_item.bg_image_bytes = self.image_manager.get_image_bytes(
                    self.service_item.theme_data.background_filename, ImageSource.Theme)
            if image_path:
                image_bytes = self.image_manager.get_image_bytes(image_path, ImageSource.ImagePlugin)
        created_html = build_html(self.service_item, self.screen, self.is_live, background, image_bytes,
                                  plugins=self.plugin_manager.plugins)
        self.web_view.setHtml(created_html)
        if service_item.foot_text:
            self.footer(service_item.foot_text)
        # if was hidden keep it hidden
        if self.hide_mode and self.is_live and not service_item.is_media():
            if Settings().value('core/auto unblank'):
                Registry().execute('slidecontroller_live_unblank')
            else:
                self.hide_display(self.hide_mode)
        if self.service_item.theme_data.background_type == 'video' and self.is_live:
            if self.service_item.theme_data.background_filename:
                service_item = ServiceItem()
                service_item.title = 'webkit'
                service_item.processor = 'webkit'
                path = os.path.join(AppLocation.get_section_data_path('themes'),
                                    self.service_item.theme_data.theme_name)
                service_item.add_from_command(path,
                                              self.service_item.theme_data.background_filename,
                                              ':/media/slidecontroller_multimedia.png')
                self.media_controller.video(DisplayControllerType.Live, service_item, video_behind_text=True)
        self._hide_mouse()
Example #21
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.service_path = os.path.join(AppLocation.get_section_data_path(self.settings_section), 'thumbnails')
     check_directory_exists(self.service_path)
     # Load images from the database
     self.load_full_list(
         self.manager.get_all_objects(ImageFilenames, order_by_ref=ImageFilenames.filename), initial_load=True)
Example #22
0
 def initialise(self):
     """
     Initialize media item.
     """
     self.list_view.clear()
     self.service_path = os.path.join(
         AppLocation.get_section_data_path(self.settings_section),
         'thumbnails')
     check_directory_exists(self.service_path)
     self.load_list(Settings().value(self.settings_section +
                                     '/media files'))
     self.rebuild_players()
Example #23
0
    def get_section_data_path_test(self):
        """
        Test the AppLocation.get_section_data_path() method
        """
        with patch('openlp.core.common.AppLocation.get_data_path') as mocked_get_data_path, \
                patch('openlp.core.common.applocation.check_directory_exists') as mocked_check_directory_exists:
            # GIVEN: A mocked out AppLocation.get_data_path()
            mocked_get_data_path.return_value = os.path.join('test', 'dir')
            mocked_check_directory_exists.return_value = True

            # WHEN: we call AppLocation.get_data_path()
            data_path = AppLocation.get_section_data_path('section')

            # THEN: check that all the correct methods were called, and the result is correct
            mocked_check_directory_exists.assert_called_with(os.path.join('test', 'dir', 'section'))
            self.assertEqual(os.path.join('test', 'dir', 'section'), data_path, 'Result should be "test/dir/section"')
Example #24
0
    def copy_media_file(self, song_id, filename):
        """
        This method copies the media file to the correct location and returns
        the new file location.

        :param song_id:
        :param 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):
            old_file, filename = filename, os.path.join(self.save_path, os.path.split(filename)[1])
            shutil.copyfile(old_file, filename)
        return filename
Example #25
0
    def copy_media_file(self, song_id, filename):
        """
        This method copies the media file to the correct location and returns
        the new file location.

        :param song_id:
        :param 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):
            old_file, filename = filename, os.path.join(self.save_path, os.path.split(filename)[1])
            shutil.copyfile(old_file, filename)
        return filename
Example #26
0
    def serve_thumbnail(self,
                        controller_name=None,
                        dimensions=None,
                        file_name=None):
        """
        Serve an image file. If not found return 404.

        :param file_name: file name to be served
        :param dimensions: image size
        :param controller_name: controller to be called
        """
        log.debug('serve thumbnail %s/thumbnails%s/%s' %
                  (controller_name, dimensions, file_name))
        supported_controllers = ['presentations', 'images']
        # -1 means use the default dimension in ImageManager
        width = -1
        height = -1
        if dimensions:
            match = re.search('(\d+)x(\d+)', dimensions)
            if match:
                # let's make sure that the dimensions are within reason
                width = sorted([10, int(match.group(1)), 1000])[1]
                height = sorted([10, int(match.group(2)), 1000])[1]
        content = ''
        content_type = None
        if controller_name and file_name:
            if controller_name in supported_controllers:
                full_path = urllib.parse.unquote(file_name)
                if '..' not in full_path:  # no hacking please
                    full_path = os.path.normpath(
                        os.path.join(
                            AppLocation.get_section_data_path(controller_name),
                            'thumbnails/' + full_path))
                    if os.path.exists(full_path):
                        path, just_file_name = os.path.split(full_path)
                        self.image_manager.add_image(full_path, just_file_name,
                                                     None, width, height)
                        ext, content_type = self.get_content_type(full_path)
                        image = self.image_manager.get_image(
                            full_path, just_file_name, width, height)
                        content = image_to_byte(image, False)
        if len(content) == 0:
            return self.do_not_found()
        self.send_response(200)
        self.send_header('Content-type', content_type)
        self.end_headers()
        return content
Example #27
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
Example #28
0
    def test_get_section_data_path(self):
        """
        Test the AppLocation.get_section_data_path() method
        """
        with patch('openlp.core.common.AppLocation.get_data_path') as mocked_get_data_path, \
                patch('openlp.core.common.applocation.check_directory_exists') as mocked_check_directory_exists:
            # GIVEN: A mocked out AppLocation.get_data_path()
            mocked_get_data_path.return_value = os.path.join('test', 'dir')
            mocked_check_directory_exists.return_value = True

            # WHEN: we call AppLocation.get_data_path()
            data_path = AppLocation.get_section_data_path('section')

            # THEN: check that all the correct methods were called, and the result is correct
            mocked_check_directory_exists.assert_called_with(
                os.path.join('test', 'dir', 'section'))
            self.assertEqual(os.path.join('test', 'dir', 'section'), data_path,
                             'Result should be "test/dir/section"')
Example #29
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
Example #30
0
    def __init__(self, parent, manager, bible_plugin):
        """
        Instantiate the wizard, and run any extra setup we need to.

        :param parent: The QWidget-derived parent of the wizard.
        :param manager: The Bible manager.
        :param 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')
    def __init__(self, parent, manager, bible_plugin):
        """
        Instantiate the wizard, and run any extra setup we need to.

        :param parent: The QWidget-derived parent of the wizard.
        :param manager: The Bible manager.
        :param 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')
Example #32
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.

    :param song_id: The ID of the song to delete.
    :param song_plugin: The song plugin instance.
    """
    save_path = ''
    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 OSError:
            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)
Example #33
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.

    :param song_id: The ID of the song to delete.
    :param song_plugin: The song plugin instance.
    """
    save_path = ''
    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 OSError:
            log.exception('Could not remove file: {name}'.format(name=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: {path}'.format(path=save_path))
    song_plugin.manager.delete_object(Song, song_id)
Example #34
0
    def add_from_command(self,
                         path,
                         file_name,
                         image,
                         display_title=None,
                         notes=None):
        """
        Add a slide from a command.

        :param path: The title of the slide in the service item.
        :param file_name: The title of the slide in the service item.
        :param image: The command of/for the slide.
        :param display_title: Title to show in gui/webinterface, optional.
        :param notes: Notes to show in the webinteface, optional.
        """
        self.service_item_type = ServiceItemType.Command
        # If the item should have a display title but this frame doesn't have one, we make one up
        if self.is_capable(
                ItemCapabilities.HasDisplayTitle) and not display_title:
            display_title = translate(
                'OpenLP.ServiceItem',
                '[slide {frame:d}]').format(frame=len(self._raw_frames) + 1)
        # Update image path to match servicemanager location if file was loaded from service
        if image and not self.has_original_files and self.name == 'presentations':
            file_location = os.path.join(path, file_name)
            file_location_hash = md5_hash(file_location.encode('utf-8'))
            image = os.path.join(AppLocation.get_section_data_path(self.name),
                                 'thumbnails', file_location_hash,
                                 ntpath.basename(image))
        self._raw_frames.append({
            'title': file_name,
            'image': image,
            'path': path,
            'display_title': display_title,
            'notes': notes
        })
        if self.is_capable(ItemCapabilities.HasThumbnails):
            self.image_manager.add_image(image, ImageSource.CommandPlugins,
                                         '#000000')
        self._new_item()
Example #35
0
    def build_html(self, service_item, image_path=''):
        """
        Store the service_item and build the new HTML from it. Add the HTML to the display

        :param service_item: The Service item to be used
        :param image_path: Where the image resides.
        """
        self.web_loaded = False
        self.initial_fame = None
        self.service_item = service_item
        background = None
        # We have an image override so keep the image till the theme changes.
        if self.override:
            # We have an video override so allow it to be stopped.
            if 'video' in self.override:
                Registry().execute('video_background_replaced')
                self.override = {}
            # We have a different theme.
            elif self.override[
                    'theme'] != service_item.theme_data.background_filename:
                Registry().execute('live_theme_changed')
                self.override = {}
            else:
                # replace the background
                background = self.image_manager.get_image_bytes(
                    self.override['image'], ImageSource.ImagePlugin)
        self.set_transparency(
            self.service_item.theme_data.background_type ==
            BackgroundType.to_string(BackgroundType.Transparent))
        image_bytes = None
        if self.service_item.theme_data.background_type == 'image':
            if self.service_item.theme_data.background_filename:
                self.service_item.bg_image_bytes = self.image_manager.get_image_bytes(
                    self.service_item.theme_data.background_filename,
                    ImageSource.Theme)
            if image_path:
                image_bytes = self.image_manager.get_image_bytes(
                    image_path, ImageSource.ImagePlugin)
        created_html = build_html(self.service_item,
                                  self.screen,
                                  self.is_live,
                                  background,
                                  image_bytes,
                                  plugins=self.plugin_manager.plugins)
        self.web_view.setHtml(created_html)
        if service_item.foot_text:
            self.footer(service_item.foot_text)
        # if was hidden keep it hidden
        if self.hide_mode and self.is_live and not service_item.is_media():
            if Settings().value('core/auto unblank'):
                Registry().execute('slidecontroller_live_unblank')
            else:
                self.hide_display(self.hide_mode)
        if self.service_item.theme_data.background_type == 'video' and self.is_live:
            if self.service_item.theme_data.background_filename:
                service_item = ServiceItem()
                service_item.title = 'webkit'
                service_item.processor = 'webkit'
                path = os.path.join(
                    AppLocation.get_section_data_path('themes'),
                    self.service_item.theme_data.theme_name)
                service_item.add_from_command(
                    path, self.service_item.theme_data.background_filename,
                    ':/media/slidecontroller_multimedia.png')
                self.media_controller.video(DisplayControllerType.Live,
                                            service_item,
                                            video_behind_text=True)
        self._hide_mouse()
Example #36
0
 def validateCurrentPage(self):
     """
     Validate the current page before moving on to the next page.
     """
     if self.currentPage() == self.welcome_page:
         return True
     elif self.currentPage() == self.select_page:
         if self.field("source_format") == BibleFormat.OSIS:
             if not self.field("osis_location"):
                 critical_error_message_box(UiStrings().NFSs, WizardStrings.YouSpecifyFile % WizardStrings.OSIS)
                 self.osis_file_edit.setFocus()
                 return False
         elif self.field("source_format") == BibleFormat.CSV:
             if not self.field("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.csv_books_edit.setFocus()
                 return False
             elif not self.field("csv_versefile"):
                 critical_error_message_box(
                     UiStrings().NFSs,
                     translate(
                         "BiblesPlugin.ImportWizardForm", "You need to specify a file of Bible verses to " "import."
                     ),
                 )
                 self.csv_verses_edit.setFocus()
                 return False
         elif self.field("source_format") == BibleFormat.OpenSong:
             if not self.field("opensong_file"):
                 critical_error_message_box(UiStrings().NFSs, WizardStrings.YouSpecifyFile % WizardStrings.OS)
                 self.open_song_file_edit.setFocus()
                 return False
         elif self.field("source_format") == BibleFormat.Zefania:
             if not self.field("zefania_file"):
                 critical_error_message_box(UiStrings().NFSs, WizardStrings.YouSpecifyFile % WizardStrings.ZEF)
                 self.zefania_file_edit.setFocus()
                 return False
         elif self.field("source_format") == BibleFormat.WebDownload:
             # If count is 0 the bible list has not yet been downloaded
             if self.web_translation_combo_box.count() == 0:
                 return False
             else:
                 self.version_name_edit.setText(self.web_translation_combo_box.currentText())
         return True
     elif self.currentPage() == self.license_details_page:
         license_version = self.field("license_version")
         license_copyright = self.field("license_copyright")
         path = AppLocation.get_section_data_path("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.version_name_edit.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.copyright_edit.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.version_name_edit.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.version_name_edit.setFocus()
             return False
         return True
     if self.currentPage() == self.progress_page:
         return True
Example #37
0
 def validateCurrentPage(self):
     """
     Validate the current page before moving on to the next page.
     """
     if self.currentPage() == self.welcome_page:
         return True
     elif self.currentPage() == self.select_page:
         if self.field('source_format') == BibleFormat.OSIS:
             if not self.field('osis_location'):
                 critical_error_message_box(
                     UiStrings().NFSs,
                     WizardStrings.YouSpecifyFile % WizardStrings.OSIS)
                 self.osis_file_edit.setFocus()
                 return False
         elif self.field('source_format') == BibleFormat.CSV:
             if not self.field('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.csv_books_edit.setFocus()
                 return False
             elif not self.field('csv_versefile'):
                 critical_error_message_box(
                     UiStrings().NFSs,
                     translate(
                         'BiblesPlugin.ImportWizardForm',
                         'You need to specify a file of Bible verses to '
                         'import.'))
                 self.csv_verses_edit.setFocus()
                 return False
         elif self.field('source_format') == BibleFormat.OpenSong:
             if not self.field('opensong_file'):
                 critical_error_message_box(
                     UiStrings().NFSs,
                     WizardStrings.YouSpecifyFile % WizardStrings.OS)
                 self.open_song_file_edit.setFocus()
                 return False
         elif self.field('source_format') == BibleFormat.Zefania:
             if not self.field('zefania_file'):
                 critical_error_message_box(
                     UiStrings().NFSs,
                     WizardStrings.YouSpecifyFile % WizardStrings.ZEF)
                 self.zefania_file_edit.setFocus()
                 return False
         elif self.field('source_format') == BibleFormat.WebDownload:
             # If count is 0 the bible list has not yet been downloaded
             if self.web_translation_combo_box.count() == 0:
                 return False
             else:
                 self.version_name_edit.setText(
                     self.web_translation_combo_box.currentText())
         return True
     elif self.currentPage() == self.license_details_page:
         license_version = self.field('license_version')
         license_copyright = self.field('license_copyright')
         path = AppLocation.get_section_data_path('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.version_name_edit.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.copyright_edit.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.version_name_edit.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.version_name_edit.setFocus()
             return False
         return True
     if self.currentPage() == self.progress_page:
         return True