import { Injectable } from '@angular/core'; import { Base64 } from '@yourcause/common'; import { I18nService } from '@yourcause/common/i18n'; import { LogService } from '@yourcause/common/logging'; import { NotifierService } from '@yourcause/common/notifier'; @Injectable({ providedIn: 'root' }) export class ImportExportService { constructor ( private logger: LogService, private i18n: I18nService, private notifier: NotifierService ) { } decodeExportString (exportString: string) { let fields: T[]; try { fields = JSON.parse(Base64.decode(exportString)); } catch (e) { this.logger.error(e); this.notifier.warning(this.i18n.translate( 'FORMS:notificationInvalidFileType', {}, 'The provided file was invalid, please obtain a valid file and try again.' )); } return fields; } handleImportFileClick () { return new Promise((res, rej) => { const input = document.createElement('input'); input.type = 'file'; input.hidden = true; input.addEventListener('change', (event: any) => { const [file] = event.target.files; const fileReader = new FileReader(); fileReader.addEventListener('loadend', async (loadEvent: any) => { const result = loadEvent.target.result; const decoded = this.decodeExportString(result); if (decoded) { res(decoded as any); } else { res(null); } }); fileReader.readAsText(file); }); input.addEventListener('cancel', () => { res(null); }); document.body.appendChild(input); input.click(); }); } }