Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const parseFile = async (html) => {
- const file = html.find('#file')[0].files[0]
- const packId = html.find('#packId')[0].value
- var reader = new FileReader()
- const pack = game.packs.get(packId)
- const nameRegex = /([A-Za-z \!\"\'\-]+)\s\[([A-Za-z ]+)\]/
- reader.onload = async (e) => {
- const contents = parseCSV(e.target.result)
- for (const row of contents) {
- try {
- const [category, label, nameTag, track, details] = row
- if (nameTag === '') continue
- let categoryFolder = pack.folders.contents.filter(
- (f) => f.name === category.trim(),
- )[0]
- if (!categoryFolder) {
- categoryFolder = await Folder.create(
- { name: category.trim(), type: 'Item' },
- { pack: packId },
- )
- }
- let labelFolder = pack.folders.contents.filter(
- (f) => f.name === label.trim(),
- )[0]
- if (!labelFolder) {
- labelFolder = await Folder.create(
- { name: label.trim(), type: 'Item', folder: categoryFolder },
- { pack: packId },
- )
- }
- const [_match, name, tag] = nameTag.match(nameRegex)
- itemData = {
- name: name.trim(),
- type: 'aspect',
- system: {
- track: { max: track },
- details,
- type: tag,
- },
- folder: labelFolder._id,
- }
- await Item.create(itemData, { pack: packId, keepId: true })
- } catch (e) {
- ui.notifications.warn(`Import failed for ${row.join(',')}`)
- console.log(e, row)
- continue
- }
- }
- ui.notifications.info('Complete')
- }
- reader.readAsText(file)
- }
- function parseCSV(str) {
- const arr = []
- let quote = false
- for (let row = 0, col = 0, c = 0; c < str.length; c++) {
- let cc = str[c],
- nc = str[c + 1]
- arr[row] = arr[row] || []
- arr[row][col] = arr[row][col] || ''
- if (cc == '"' && quote && nc == '"') {
- arr[row][col] += cc
- ++c
- continue
- }
- if (cc == '"') {
- quote = !quote
- continue
- }
- if (cc == ',' && !quote) {
- ++col
- continue
- }
- if (cc == '\r' && nc == '\n' && !quote) {
- ++row
- col = 0
- ++c
- continue
- }
- if (cc == '\n' && !quote) {
- ++row
- col = 0
- continue
- }
- if (cc == '\r' && !quote) {
- ++row
- col = 0
- continue
- }
- arr[row][col] += cc
- }
- return arr
- }
- await new Promise((resolve) => {
- new Dialog({
- title: 'Import CSV File to RollTable',
- content: `<form>
- <div class="form-group">
- <label style="max-width:100px">File</label>
- <div class="form-fields">
- <input id="file" type="file"/>
- </div>
- </div>
- <div class="form-group">
- <label style="max-width: 100px">Pack ID</label>
- <div class="form-fields">
- <input id="packId" type="text" placeholder="world.wildsea" />
- </div>
- </div>
- </form>`,
- buttons: {
- roll: {
- icon: '<i class="fas fa-file-import"></i>',
- label: 'Import',
- callback: (html) => resolve(parseFile(html)),
- },
- },
- close: () => resolve(null),
- }).render(true)
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement