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 check_installed(self):
        """
        Check the viewer is installed.

        :return: True if program to open PDF-files was found, otherwise False.
        """
        log.debug('check_installed Pdf')
        self.mudrawbin = ''
        self.mutoolbin = ''
        self.gsbin = ''
        self.also_supports = []
        # Use the user defined program if given
        if Settings().value('presentations/enable_pdf_program'):
            pdf_program = Settings().value('presentations/pdf_program')
            program_type = self.check_binary(pdf_program)
            if program_type == 'gs':
                self.gsbin = pdf_program
            elif program_type == 'mudraw':
                self.mudrawbin = pdf_program
            elif program_type == 'mutool':
                self.mutoolbin = pdf_program
        else:
            # Fallback to autodetection
            application_path = AppLocation.get_directory(AppLocation.AppDir)
            if is_win():
                # for windows we only accept mudraw.exe or mutool.exe in the base folder
                application_path = AppLocation.get_directory(AppLocation.AppDir)
                if os.path.isfile(os.path.join(application_path, 'mudraw.exe')):
                    self.mudrawbin = os.path.join(application_path, 'mudraw.exe')
                elif os.path.isfile(os.path.join(application_path, 'mutool.exe')):
                    self.mutoolbin = os.path.join(application_path, 'mutool.exe')
            else:
                DEVNULL = open(os.devnull, 'wb')
                # First try to find mudraw
                self.mudrawbin = which('mudraw')
                # if mudraw isn't installed, try mutool
                if not self.mudrawbin:
                    self.mutoolbin = which('mutool')
                    # Check we got a working mutool
                    if not self.mutoolbin or self.check_binary(self.mutoolbin) != 'mutool':
                        self.gsbin = which('gs')
                # Last option: check if mudraw or mutool is placed in OpenLP base folder
                if not self.mudrawbin and not self.mutoolbin and not self.gsbin:
                    application_path = AppLocation.get_directory(AppLocation.AppDir)
                    if os.path.isfile(os.path.join(application_path, 'mudraw')):
                        self.mudrawbin = os.path.join(application_path, 'mudraw')
                    elif os.path.isfile(os.path.join(application_path, 'mutool')):
                        self.mutoolbin = os.path.join(application_path, 'mutool')
        if self.mudrawbin or self.mutoolbin:
            self.also_supports = ['xps', 'oxps']
            return True
        elif self.gsbin:
            return True
        else:
            return False
Ejemplo n.º 7
0
 def find_qm_files():
     """
     Find all available language files in this OpenLP install
     """
     log.debug('Translation files: %s', AppLocation.get_directory(
         AppLocation.LanguageDir))
     trans_dir = QtCore.QDir(AppLocation.get_directory(AppLocation.LanguageDir))
     file_names = trans_dir.entryList('*.qm', QtCore.QDir.Files, QtCore.QDir.Name)
     # Remove qm files from the list which start with "qt_".
     file_names = [file_ for file_ in file_names if not file_.startswith('qt_')]
     return list(map(trans_dir.filePath, file_names))
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):
     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.º 10
0
 def checkPreConditions(self):
     """
     Check to see if we have any presentation software available
     If Not do not install the plugin.
     """
     log.debug(u'checkPreConditions')
     controller_dir = os.path.join(
         AppLocation.get_directory(AppLocation.PluginsDir),
         u'presentations', u'lib')
     for filename in os.listdir(controller_dir):
         if filename.endswith(u'controller.py') and not filename == 'presentationcontroller.py':
             path = os.path.join(controller_dir, filename)
             if os.path.isfile(path):
                 modulename = u'openlp.plugins.presentations.lib.' + os.path.splitext(filename)[0]
                 log.debug(u'Importing controller %s', modulename)
                 try:
                     __import__(modulename, globals(), locals(), [])
                 except ImportError:
                     log.warn(u'Failed to import %s on path %s',
                         modulename, path)
     controller_classes = PresentationController.__subclasses__()
     for controller_class in controller_classes:
         controller = controller_class(self)
         self.registerControllers(controller)
     return bool(self.controllers)
Ejemplo n.º 11
0
 def __init__(self, parent, **kwargs):
     log.debug(self.__class__.__name__)
     BibleDB.__init__(self, parent, **kwargs)
     self.filename = kwargs[u'filename']
     self.language_regex = re.compile(r'<language.*>(.*?)</language>')
     self.verse_regex = re.compile(
         r'<verse osisID="([a-zA-Z0-9 ]*).([0-9]*).([0-9]*)">(.*?)</verse>')
     self.note_regex = re.compile(r'<note(.*?)>(.*?)</note>')
     self.title_regex = re.compile(r'<title(.*?)>(.*?)</title>')
     self.milestone_regex = re.compile(r'<milestone(.*?)/>')
     self.fi_regex = re.compile(r'<FI>(.*?)<Fi>')
     self.rf_regex = re.compile(r'<RF>(.*?)<Rf>')
     self.lb_regex = re.compile(r'<lb(.*?)>')
     self.lg_regex = re.compile(r'<lg(.*?)>')
     self.l_regex = re.compile(r'<l (.*?)>')
     self.w_regex = re.compile(r'<w (.*?)>')
     self.q_regex = re.compile(r'<q(.*?)>')
     self.q1_regex = re.compile(r'<q(.*?)level="1"(.*?)>')
     self.q2_regex = re.compile(r'<q(.*?)level="2"(.*?)>')
     self.trans_regex = re.compile(r'<transChange(.*?)>(.*?)</transChange>')
     self.divine_name_regex = re.compile(
         r'<divineName(.*?)>(.*?)</divineName>')
     self.spaces_regex = re.compile(r'([ ]{2,})')
     filepath = os.path.join(
         AppLocation.get_directory(AppLocation.PluginsDir), u'bibles', u'resources', u'osisbooks.csv')
Ejemplo n.º 12
0
 def __init__(self):
     """
     Initialise the router
     """
     self.routes = [
         ('^/$', self.serve_file),
         ('^/(stage)$', self.serve_file),
         ('^/(main)$', self.serve_file),
         (r'^/files/(.*)$', self.serve_file),
         (r'^/api/poll$', self.poll),
         (r'^/stage/poll$', self.poll),
         (r'^/main/poll$', self.main_poll),
         (r'^/main/image$', self.main_image),
         (r'^/api/controller/(live|preview)/(.*)$', self.controller),
         (r'^/stage/controller/(live|preview)/(.*)$', self.controller),
         (r'^/api/service/(.*)$', self.service),
         (r'^/stage/service/(.*)$', self.service),
         (r'^/api/display/(hide|show|blank|theme|desktop)$', self.display),
         (r'^/api/alert$', self.alert),
         (r'^/api/plugin/(search)$', self.plugin_info),
         (r'^/api/(.*)/search$', self.search),
         (r'^/api/(.*)/live$', self.go_live),
         (r'^/api/(.*)/add$', self.add_to_service)
     ]
     self.translate()
     self.html_dir = os.path.join(AppLocation.get_directory(AppLocation.PluginsDir), 'remotes', 'html')
Ejemplo n.º 13
0
 def define_config(self):
     """
     Define the configuration of the server.
     """
     if Settings().value(self.settings_section + '/https enabled'):
         port = Settings().value(self.settings_section + '/https port')
         address = Settings().value(self.settings_section + '/ip address')
         local_data = AppLocation.get_directory(AppLocation.DataDir)
         cherrypy.config.update({'server.socket_host': str(address),
                                 'server.socket_port': port,
                                 'server.ssl_certificate': os.path.join(local_data, 'remotes', 'openlp.crt'),
                                 'server.ssl_private_key': os.path.join(local_data, 'remotes', 'openlp.key')})
     else:
         port = Settings().value(self.settings_section + '/port')
         address = Settings().value(self.settings_section + '/ip address')
         cherrypy.config.update({'server.socket_host': str(address)})
         cherrypy.config.update({'server.socket_port': port})
     cherrypy.config.update({'environment': 'embedded'})
     cherrypy.config.update({'engine.autoreload_on': False})
     directory_config = {'/': {'tools.staticdir.on': True,
                             'tools.staticdir.dir': self.router.html_dir,
                             'tools.basic_auth.on': Settings().value('remotes/authentication enabled'),
                             'tools.basic_auth.realm': 'OpenLP Remote Login',
                             'tools.basic_auth.users': fetch_password,
                             'tools.basic_auth.encrypt': make_sha_hash},
                      '/files': {'tools.staticdir.on': True,
                                  'tools.staticdir.dir': self.router.html_dir,
                                  'tools.basic_auth.on': False},
                      '/stage': {'tools.staticdir.on': True,
                                  'tools.staticdir.dir': self.router.html_dir,
                                  'tools.basic_auth.on': False},
                      '/main': {'tools.staticdir.on': True,
                                  'tools.staticdir.dir': self.router.html_dir,
                                  'tools.basic_auth.on': False}}
     return directory_config
Ejemplo n.º 14
0
 def check_available_media_players(self):
     """
     Check to see if we have any media Player's available.
     """
     log.debug('_check_available_media_players')
     controller_dir = os.path.join(AppLocation.get_directory(AppLocation.AppDir), 'core', 'ui', 'media')
     for filename in os.listdir(controller_dir):
         if filename.endswith('player.py') and not filename == 'mediaplayer.py':
             path = os.path.join(controller_dir, filename)
             if os.path.isfile(path):
                 modulename = 'openlp.core.ui.media.' + os.path.splitext(filename)[0]
                 log.debug('Importing controller %s', modulename)
                 try:
                     __import__(modulename, globals(), locals(), [])
                 # On some platforms importing vlc.py might cause
                 # also OSError exceptions. (e.g. Mac OS X)
                 except (ImportError, OSError):
                     log.warn('Failed to import %s on path %s', modulename, path)
     player_classes = MediaPlayer.__subclasses__()
     for player_class in player_classes:
         player = player_class(self)
         self.register_players(player)
     if not self.media_players:
         return False
     savedPlayers, overriddenPlayer = get_media_players()
     invalid_media_players = [mediaPlayer for mediaPlayer in savedPlayers
         if not mediaPlayer in self.media_players or not self.media_players[mediaPlayer].check_available()]
     if invalid_media_players:
         for invalidPlayer in invalid_media_players:
             savedPlayers.remove(invalidPlayer)
         set_media_players(savedPlayers, overriddenPlayer)
     self._set_active_players()
     self._generate_extensions_lists()
     return True
Ejemplo n.º 15
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.º 16
0
    def check_installed(self):
        """
        Check the viewer is installed.

        :return: True if program to open PDF-files was found, otherwise False.
        """
        log.debug('check_installed Pdf')
        self.mudrawbin = ''
        self.gsbin = ''
        self.also_supports = []
        # Use the user defined program if given
        if Settings().value('presentations/enable_pdf_program'):
            pdf_program = Settings().value('presentations/pdf_program')
            program_type = self.check_binary(pdf_program)
            if program_type == 'gs':
                self.gsbin = pdf_program
            elif program_type == 'mudraw':
                self.mudrawbin = pdf_program
        else:
            # Fallback to autodetection
            application_path = AppLocation.get_directory(AppLocation.AppDir)
            if is_win():
                # for windows we only accept mudraw.exe in the base folder
                application_path = AppLocation.get_directory(AppLocation.AppDir)
                if os.path.isfile(os.path.join(application_path, 'mudraw.exe')):
                    self.mudrawbin = os.path.join(application_path, 'mudraw.exe')
            else:
                DEVNULL = open(os.devnull, 'wb')
                # First try to find mupdf
                self.mudrawbin = which('mudraw')
                # if mupdf isn't installed, fallback to ghostscript
                if not self.mudrawbin:
                    self.gsbin = which('gs')
                # Last option: check if mudraw is placed in OpenLP base folder
                if not self.mudrawbin and not self.gsbin:
                    application_path = AppLocation.get_directory(AppLocation.AppDir)
                    if os.path.isfile(os.path.join(application_path, 'mudraw')):
                        self.mudrawbin = os.path.join(application_path, 'mudraw')
        if self.mudrawbin:
            self.also_supports = ['xps', 'oxps']
            return True
        elif self.gsbin:
            return True
        else:
            return False
Ejemplo n.º 17
0
 def get_cursor():
     """
     Return the cursor object. Instantiate one if it doesn't exist yet.
     """
     if BiblesResourcesDB.cursor is None:
         filepath = os.path.join(AppLocation.get_directory(AppLocation.PluginsDir),
             u'bibles', u'resources', u'bibles_resources.sqlite')
         conn = sqlite3.connect(filepath)
         BiblesResourcesDB.cursor = conn.cursor()
     return BiblesResourcesDB.cursor
Ejemplo n.º 18
0
 def get_directory_for_app_dir_test(self):
     """
     Test the AppLocation.get_directory() method for AppLocation.AppDir
     """
     with patch(u'openlp.core.utils._get_frozen_path') as mocked_get_frozen_path:
         mocked_get_frozen_path.return_value = u'app/dir'
         # WHEN: We call AppLocation.get_directory
         directory = AppLocation.get_directory(AppLocation.AppDir)
         # THEN:
         assert directory == u'app/dir', u'Directory should be "app/dir"'
Ejemplo n.º 19
0
 def __init__(self, plugin):
     """
     Initialise the httpserver, and start the server.
     """
     log.debug(u'Initialise httpserver')
     self.plugin = plugin
     self.html_dir = os.path.join(AppLocation.get_directory(AppLocation.PluginsDir), u'remotes', u'html')
     self.connections = []
     self.current_item = None
     self.current_slide = None
     self.start_tcp()
Ejemplo n.º 20
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.º 21
0
 def __init__(self):
     """
     The constructor for the plugin manager. Passes the controllers on to
     the plugins for them to interact with via their ServiceItems.
     """
     log.info('Plugin manager Initialising')
     Registry().register('plugin_manager', self)
     Registry().register_function('bootstrap_initialise', self.bootstrap_initialise)
     self.base_path = os.path.abspath(AppLocation.get_directory(AppLocation.PluginsDir))
     log.debug('Base path %s ', self.base_path)
     self.plugins = []
     log.info('Plugin manager Initialised')
Ejemplo n.º 22
0
 def start_process(self):
     """
     Loads the PPTVIEWLIB library.
     """
     if self.process:
         return
     log.debug('start PPTView')
     dll_path = os.path.join(AppLocation.get_directory(AppLocation.AppDir),
                             'plugins', 'presentations', 'lib', 'pptviewlib', 'pptviewlib.dll')
     self.process = cdll.LoadLibrary(dll_path)
     if log.isEnabledFor(logging.DEBUG):
         self.process.SetDebug(1)
Ejemplo n.º 23
0
 def start_process(self):
     """
     Loads the PPTVIEWLIB library.
     """
     if self.process:
         return
     log.debug('start PPTView')
     dll_path = os.path.join(AppLocation.get_directory(AppLocation.AppDir),
                             'plugins', 'presentations', 'lib', 'pptviewlib', 'pptviewlib.dll')
     self.process = cdll.LoadLibrary(dll_path)
     if log.isEnabledFor(logging.DEBUG):
         self.process.SetDebug(1)
Ejemplo n.º 24
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.º 25
0
    def gs_get_resolution(self, size):
        """
        Only used when using ghostscript
        Ghostscript can't scale automatically while keeping aspect like mupdf, so we need
        to get the ratio between the screen size and the PDF to scale

        :param size: Size struct containing the screen size.
        :return: The resolution dpi to be used.
        """
        # Use a postscript script to get size of the pdf. It is assumed that all pages have same size
        gs_resolution_script = AppLocation.get_directory(
            AppLocation.PluginsDir
        ) + '/presentations/lib/ghostscript_get_resolution.ps'
        # Run the script on the pdf to get the size
        runlog = []
        try:
            runlog = check_output([
                self.controller.gsbin, '-dNOPAUSE', '-dNODISPLAY', '-dBATCH',
                '-sFile=' + self.file_path, gs_resolution_script
            ],
                                  startupinfo=self.startupinfo)
        except CalledProcessError as e:
            log.debug(' '.join(e.cmd))
            log.debug(e.output)
        # Extract the pdf resolution from output, the format is " Size: x: <width>, y: <height>"
        width = 0.0
        height = 0.0
        for line in runlog.splitlines():
            try:
                width = float(
                    re.search('.*Size: x: (\d+\.?\d*), y: \d+.*',
                              line.decode()).group(1))
                height = float(
                    re.search('.*Size: x: \d+\.?\d*, y: (\d+\.?\d*).*',
                              line.decode()).group(1))
                break
            except AttributeError:
                continue
        # Calculate the ratio from pdf to screen
        if width > 0 and height > 0:
            width_ratio = size.width() / width
            height_ratio = size.height() / height
            # return the resolution that should be used. 72 is default.
            if width_ratio > height_ratio:
                return int(height_ratio * 72)
            else:
                return int(width_ratio * 72)
        else:
            return 72
Ejemplo n.º 26
0
    def get_files_no_section_no_extension_test(self):
        """
        Test the AppLocation.get_files() method with no parameters passed.
        """
        with patch('openlp.core.utils.AppLocation.get_data_path') as mocked_get_data_path, \
                patch('openlp.core.utils.applocation.os.listdir') as mocked_listdir:
            # GIVEN: Our mocked modules/methods.
            mocked_get_data_path.return_value = 'test/dir'
            mocked_listdir.return_value = copy.deepcopy(FILE_LIST)

            # When: Get the list of files.
            result = AppLocation.get_files()

            # Then: check if the file lists are identical.
            assert result == FILE_LIST,  'The file lists should be identical.'
Ejemplo n.º 27
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.º 28
0
 def get_directory_for_plugins_dir_test(self):
     """
     Test the AppLocation.get_directory() method for AppLocation.PluginsDir
     """
     with patch(u'openlp.core.utils._get_frozen_path') as mocked_get_frozen_path, \
          patch(u'openlp.core.utils.os.path.abspath') as mocked_abspath, \
          patch(u'openlp.core.utils.os.path.split') as mocked_split, \
          patch(u'openlp.core.utils.sys') as mocked_sys:
         mocked_abspath.return_value = u'plugins/dir'
         mocked_split.return_value = [u'openlp']
         mocked_get_frozen_path.return_value = u'plugins/dir'
         mocked_sys.frozen = 1
         mocked_sys.argv = ['openlp']
         # WHEN: We call AppLocation.get_directory
         directory = AppLocation.get_directory(AppLocation.PluginsDir)
         # THEN:
         assert directory == u'plugins/dir', u'Directory should be "plugins/dir"'
Ejemplo n.º 29
0
 def get_data_path_with_custom_location_test(self):
     """
     Test the AppLocation.get_data_path() method when a custom location is set in the settings
     """
     with patch(u'openlp.core.utils.Settings') as mocked_class,\
          patch(u'openlp.core.utils.os') as mocked_os:
         # GIVEN: A mocked out Settings class which returns a custom data location
         mocked_settings = mocked_class.return_value
         mocked_settings.contains.return_value = True
         mocked_settings.value.return_value.toString.return_value = u'custom/dir'
         mocked_os.path.normpath.return_value = u'custom/dir'
         # WHEN: we call AppLocation.get_data_path()
         data_path = AppLocation.get_data_path()
         # THEN: the mocked Settings methods were called and the value returned was our set up value
         mocked_settings.contains.assert_called_with(u'advanced/data path')
         mocked_settings.value.assert_called_with(u'advanced/data path')
         assert data_path == u'custom/dir', u'Result should be "custom/dir"'
Ejemplo n.º 30
0
    def get_files_test(self):
        """
        Test the AppLocation.get_files() method with all parameters passed.
        """
        with patch('openlp.core.utils.AppLocation.get_data_path') as mocked_get_data_path, \
                patch('openlp.core.utils.applocation.os.listdir') as mocked_listdir:
            # GIVEN: Our mocked modules/methods.
            mocked_get_data_path.return_value = 'test/dir'
            mocked_listdir.return_value = copy.deepcopy(FILE_LIST)

            # When: Get the list of files.
            result = AppLocation.get_files('section', '.mp3')

            # Then: Check if the section parameter was used correctly.
            mocked_listdir.assert_called_with('test/dir/section')

            # Then: check if the file lists are identical.
            assert result == ['file5.mp3', 'file6.mp3'],  'The file lists should be identical.'
Ejemplo n.º 31
0
    def get_translator(language):
        """
        Set up a translator to use in this instance of OpenLP

        ``language``
            The language to load into the translator
        """
        if LanguageManager.auto_language:
            language = QtCore.QLocale.system().name()
        lang_path = AppLocation.get_directory(AppLocation.LanguageDir)
        app_translator = QtCore.QTranslator()
        app_translator.load(language, lang_path)
        # A translator for buttons and other default strings provided by Qt.
        if sys.platform != 'win32' and sys.platform != 'darwin':
            lang_path = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)
        default_translator = QtCore.QTranslator()
        default_translator.load('qt_%s' % language, lang_path)
        return app_translator, default_translator
Ejemplo n.º 32
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.º 33
0
    def gs_get_resolution(self, size):
        """
        Only used when using ghostscript
        Ghostscript can't scale automatically while keeping aspect like mupdf, so we need
        to get the ratio between the screen size and the PDF to scale

        :param size: Size struct containing the screen size.
        :return: The resolution dpi to be used.
        """
        # Use a postscript script to get size of the pdf. It is assumed that all pages have same size
        gs_resolution_script = AppLocation.get_directory(
            AppLocation.PluginsDir) + '/presentations/lib/ghostscript_get_resolution.ps'
        # Run the script on the pdf to get the size
        runlog = []
        try:
            runlog = check_output([self.controller.gsbin, '-dNOPAUSE', '-dNODISPLAY', '-dBATCH',
                                   '-sFile=' + self.file_path, gs_resolution_script],
                                  startupinfo=self.startupinfo)
        except CalledProcessError as e:
            log.debug(' '.join(e.cmd))
            log.debug(e.output)
        # Extract the pdf resolution from output, the format is " Size: x: <width>, y: <height>"
        width = 0.0
        height = 0.0
        for line in runlog.splitlines():
            try:
                width = float(re.search('.*Size: x: (\d+\.?\d*), y: \d+.*', line.decode()).group(1))
                height = float(re.search('.*Size: x: \d+\.?\d*, y: (\d+\.?\d*).*', line.decode()).group(1))
                break
            except AttributeError:
                continue
        # Calculate the ratio from pdf to screen
        if width > 0 and height > 0:
            width_ratio = size.width() / width
            height_ratio = size.height() / height
            # return the resolution that should be used. 72 is default.
            if width_ratio > height_ratio:
                return int(height_ratio * 72)
            else:
                return int(width_ratio * 72)
        else:
            return 72