From 655635551dadd753a63efd9a855848d662493c5f Mon Sep 17 00:00:00 2001 From: Chen-I Lim Date: Wed, 3 Mar 2021 10:09:09 -0800 Subject: [PATCH] parseBlockArchive and tests --- webapp/src/blocks/archive.test.ts | 24 ++++++++++++++++++++ webapp/src/blocks/archive.ts | 37 +++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 webapp/src/blocks/archive.test.ts diff --git a/webapp/src/blocks/archive.test.ts b/webapp/src/blocks/archive.test.ts new file mode 100644 index 000000000..f4270056e --- /dev/null +++ b/webapp/src/blocks/archive.test.ts @@ -0,0 +1,24 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. +import {TestBlockFactory} from '../test/testBlockFactory' + +import {ArchiveUtils} from './archive' +import {IBlock} from './block' + +test('archive: archive and unarchive', async () => { + const blocks: IBlock[] = [] + + const board = TestBlockFactory.createBoard() + blocks.push(board) + blocks.push(TestBlockFactory.createBoardView(board)) + const card = TestBlockFactory.createCard(board) + blocks.push(card) + blocks.push(TestBlockFactory.createText(card)) + blocks.push(TestBlockFactory.createDivider(card)) + blocks.push(TestBlockFactory.createImage(card)) + + const archive = ArchiveUtils.buildBlockArchive(blocks) + const unarchivedBlocks = ArchiveUtils.parseBlockArchive(archive) + + expect(unarchivedBlocks).toEqual(blocks) +}) diff --git a/webapp/src/blocks/archive.ts b/webapp/src/blocks/archive.ts index 88a91ecee..8dd420bdc 100644 --- a/webapp/src/blocks/archive.ts +++ b/webapp/src/blocks/archive.ts @@ -39,6 +39,43 @@ class ArchiveUtils { return content } + + static parseBlockArchive(contents: string): IBlock[] { + const blocks: IBlock[] = [] + const allLineStrings = contents.split('\n') + if (allLineStrings.length >= 2) { + const headerString = allLineStrings[0] + const header = JSON.parse(headerString) as IArchiveHeader + if (header.date && header.version >= 1) { + const lineStrings = allLineStrings.slice(1) + let lineNum = 2 + for (const lineString of lineStrings) { + if (!lineString) { + // Ignore empty lines, e.g. last line + continue + } + const line = JSON.parse(lineString) as IArchiveLine + if (!line || !line.type || !line.data) { + throw new Error(`ERROR parsing line ${lineNum}`) + } + switch (line.type) { + case 'block': { + const blockLine = line as IBlockArchiveLine + const block = blockLine.data + blocks.push(block) + break + } + } + + lineNum += 1 + } + } else { + throw new Error('ERROR parsing header') + } + } + + return blocks + } } export {IArchiveHeader, IArchiveLine, IBlockArchiveLine, ArchiveUtils}