continued refactor of saving packaged files

This commit is contained in:
Phill Ridout 2017-12-30 08:08:10 +00:00
parent 4b1965520c
commit a1ea35c4e7

View File

@ -37,6 +37,7 @@ from openlp.core.common import ThemeLevel, delete_file
from openlp.core.common.actions import ActionList, CategoryOrder from openlp.core.common.actions import ActionList, CategoryOrder
from openlp.core.common.applocation import AppLocation from openlp.core.common.applocation import AppLocation
from openlp.core.common.i18n import UiStrings, format_time, translate from openlp.core.common.i18n import UiStrings, format_time, translate
from openlp.core.common.json import OpenLPJsonDecoder, OpenLPJsonEncoder
from openlp.core.common.mixins import LogMixin, RegistryProperties from openlp.core.common.mixins import LogMixin, RegistryProperties
from openlp.core.common.path import Path, create_paths, str_to_path from openlp.core.common.path import Path, create_paths, str_to_path
from openlp.core.common.registry import Registry, RegistryBase from openlp.core.common.registry import Registry, RegistryBase
@ -515,13 +516,11 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
if path_from in write_list or path_from in missing_list: if path_from in write_list or path_from in missing_list:
continue continue
if not os.path.exists(path_from): if not os.path.exists(path_from):
missing_list.append(path_from) missing_list.append(Path(path_from))
else: else:
write_list.append(path_from) write_list.append(Path(path_from))
return write_list, missing_list return write_list, missing_list
def save_file(self): def save_file(self):
""" """
Save the current service file. Save the current service file.
@ -531,16 +530,15 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
into the zip file. into the zip file.
""" """
file_path = self.file_name() file_path = self.file_name()
service_file_name = '{name}.osj'.format(name=file_path.suffix)
self.log_debug('ServiceManager.save_file - {name}'.format(name=file_path)) self.log_debug('ServiceManager.save_file - {name}'.format(name=file_path))
Settings().setValue(self.main_window.service_manager_settings_section + '/last directory', file_path.parent) service_file_name = '{name}.osj'.format(name=file_path.suffix)
service = self.create_basic_service()
self.application.set_busy_cursor() self.application.set_busy_cursor()
# Number of items + 1 to zip it
self.main_window.display_progress_bar(len(self.service_items) + 1) service = self.create_basic_service()
# Get list of missing files, and list of files to write # Get list of missing files, and list of files to write
audio_files = []
write_list, missing_list = self.get_write_file_list() write_list, missing_list = self.get_write_file_list()
@ -550,12 +548,11 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
message = translate('OpenLP.ServiceManager', message = translate('OpenLP.ServiceManager',
'The following file(s) in the service are missing: {name}\n\n' 'The following file(s) in the service are missing: {name}\n\n'
'These files will be removed if you continue to save.' 'These files will be removed if you continue to save.'
).format(name="\n\t".join(missing_list)) ).format(name='\n\t'.join(missing_list))
answer = QtWidgets.QMessageBox.critical(self, title, message, answer = QtWidgets.QMessageBox.critical(self, title, message,
QtWidgets.QMessageBox.StandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.StandardButtons(QtWidgets.QMessageBox.Ok |
QtWidgets.QMessageBox.Cancel)) QtWidgets.QMessageBox.Cancel))
if answer == QtWidgets.QMessageBox.Cancel: if answer == QtWidgets.QMessageBox.Cancel:
self.main_window.finished_progress_bar()
return False return False
# Check if item contains a missing file. # Check if item contains a missing file.
for item in list(self.service_items): for item in list(self.service_items):
@ -563,25 +560,24 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
item['service_item'].remove_invalid_frames(missing_list) item['service_item'].remove_invalid_frames(missing_list)
if item['service_item'].missing_frames(): if item['service_item'].missing_frames():
self.service_items.remove(item) self.service_items.remove(item)
else: continue
service_item = item['service_item'].get_service_repr(self._save_lite) service_item = item['service_item'].get_service_repr(self._save_lite)
if service_item['header']['background_audio']: for audio_path in service_item['header']['background_audio']:
for i, file_name in enumerate(service_item['header']['background_audio']): write_list.append(audio_path)
new_file = os.path.join('audio', item['service_item'].unique_identifier, str(file_name)) # Add the service item to the service.
audio_files.append((file_name, new_file)) service.append({'serviceitem': service_item})
service_item['header']['background_audio'][i] = new_file
# Add the service item to the service.
service.append({'serviceitem': service_item})
self.repaint_service_list(-1, -1) self.repaint_service_list(-1, -1)
total_size = 0 service_content = json.dumps(service, cls=OpenLPJsonEncoder)
total_size = len(bytes(service_content, encoding='utf-8'))
for file_item in write_list: for file_item in write_list:
file_size = os.path.getsize(file_item) file_size = os.path.getsize(file_item)
total_size += file_size total_size += file_size
self.log_debug('ServiceManager.save_file - ZIP contents size is %i bytes' % total_size) self.log_debug('ServiceManager.save_file - ZIP contents size is %i bytes' % total_size)
service_content = json.dumps(service)
# Number of items + 1 to zip it
self.main_window.display_progress_bar(total_size)
self.main_window.increment_progress_bar() #self.main_window.increment_progress_bar()
try: try:
with NamedTemporaryFile() as temp_file, \ with NamedTemporaryFile() as temp_file, \
zipfile.ZipFile(temp_file, 'w') as zip_file: zipfile.ZipFile(temp_file, 'w') as zip_file:
@ -590,17 +586,10 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
# Finally add all the listed media files. # Finally add all the listed media files.
for write_from in write_list: for write_from in write_list:
zip_file.write(write_from, write_from) zip_file.write(write_from, write_from)
for audio_from, audio_to in audio_files: with suppress(FileNotFoundError):
audio_from = str(audio_from) file_path.unlink()
audio_to = str(audio_to) os.link(temp_file.name, file_path)
if audio_from.startswith('audio'): Settings().setValue(self.main_window.service_manager_settings_section + '/last directory', file_path.parent)
# When items are saved, they get new unique_identifier. Let's copy the file to the new location.
# Unused files can be ignored, OpenLP automatically cleans up the service manager dir on exit.
audio_from = os.path.join(self.service_path, audio_from)
zip_file.write(audio_from, audio_to)
with suppress(FileNotFoundError):
file_path.unlink()
os.link(temp_file.name, file_path)
except (PermissionError, OSError) as error: except (PermissionError, OSError) as error:
self.log_exception('Failed to save service to disk: {name}'.format(name=temp_file.name)) self.log_exception('Failed to save service to disk: {name}'.format(name=temp_file.name))
self.main_window.error_message( self.main_window.error_message(
@ -767,7 +756,7 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi
if 'p_file' in locals(): if 'p_file' in locals():
file_to = open(p_file, 'r') file_to = open(p_file, 'r')
if p_file.endswith('osj'): if p_file.endswith('osj'):
items = json.load(file_to) items = json.load(file_to, cls=OpenLPJsonDecoder)
else: else:
critical_error_message_box(message=translate('OpenLP.ServiceManager', critical_error_message_box(message=translate('OpenLP.ServiceManager',
'The service file you are trying to open is in an old ' 'The service file you are trying to open is in an old '