metamaps--metamaps/frontend/src/Metamaps/Import.js

428 lines
13 KiB
JavaScript
Raw Normal View History

/* global $ */
2016-03-27 11:43:30 +00:00
import parse from 'csv-parse'
import _ from 'lodash'
2016-09-22 09:36:47 +00:00
import Active from './Active'
2016-10-01 04:43:02 +00:00
import AutoLayout from './AutoLayout'
2016-10-03 00:32:37 +00:00
import DataModel from './DataModel'
2016-09-22 10:31:56 +00:00
import GlobalUI from './GlobalUI'
2016-09-22 09:36:47 +00:00
import Map from './Map'
2016-09-22 10:31:56 +00:00
import Synapse from './Synapse'
import Topic from './Topic'
2016-09-22 09:36:47 +00:00
const Import = {
// note that user is not imported
topicWhitelist: [
'id', 'name', 'metacode', 'x', 'y', 'description', 'link', 'permission'
],
synapseWhitelist: [
'topic1', 'topic2', 'category', 'direction', 'desc', 'description', 'permission'
],
2016-11-07 20:25:08 +00:00
cidMappings: {}, // to be filled by importId => cid mappings
2016-11-07 20:25:08 +00:00
handleTSV: function(text) {
2016-09-30 14:31:24 +00:00
const results = Import.parseTabbedString(text)
Import.handle(results)
},
2016-11-07 20:25:08 +00:00
handleCSV: function(text, parserOpts = {}) {
2016-09-30 14:31:24 +00:00
const self = Import
const topicsRegex = /("?Topics"?)([\s\S]*)/mi
const synapsesRegex = /("?Synapses"?)([\s\S]*)/mi
2016-10-01 04:43:02 +00:00
let topicsText = text.match(topicsRegex) || ''
if (topicsText) topicsText = topicsText[2].replace(synapsesRegex, '')
2016-10-01 04:43:02 +00:00
let synapsesText = text.match(synapsesRegex) || ''
if (synapsesText) synapsesText = synapsesText[2].replace(topicsRegex, '')
// merge default options and extra options passed in parserOpts argument
2016-11-07 20:25:08 +00:00
const csvParserOptions = Object.assign({
columns: true, // get headers
relax_column_count: true,
skip_empty_lines: true
}, parserOpts)
const topicsPromise = $.Deferred()
2016-11-07 20:25:08 +00:00
parse(topicsText, csvParserOptions, (err, data) => {
if (err) {
console.warn(err)
return topicsPromise.resolve([])
}
topicsPromise.resolve(data)
})
const synapsesPromise = $.Deferred()
2016-11-07 20:25:08 +00:00
parse(synapsesText, csvParserOptions, (err, data) => {
if (err) {
console.warn(err)
return synapsesPromise.resolve([])
}
synapsesPromise.resolve(data)
})
$.when(topicsPromise, synapsesPromise).done((topics, synapses) => {
2016-11-07 20:25:08 +00:00
self.handle({ topics, synapses })
})
},
2016-11-07 20:25:08 +00:00
handleJSON: function(text) {
2016-09-30 14:31:24 +00:00
const results = JSON.parse(text)
Import.handle(results)
},
handle: function(results) {
var self = Import
var topics = results.topics.map(topic => self.normalizeKeys(topic))
var synapses = results.synapses.map(synapse => self.normalizeKeys(synapse))
if (topics.length > 0 || synapses.length > 0) {
if (window.confirm('Are you sure you want to create ' + topics.length +
' new topics and ' + synapses.length + ' new synapses?')) {
self.importTopics(topics)
2016-11-07 20:25:08 +00:00
// window.setTimeout(() => self.importSynapses(synapses), 5000)
2016-10-27 06:03:18 +00:00
self.importSynapses(synapses)
2016-03-27 11:43:30 +00:00
} // if
} // if
},
2016-11-07 20:25:08 +00:00
parseTabbedString: function(text) {
var self = Import
// determine line ending and split lines
2016-03-27 11:43:30 +00:00
var delim = '\n'
if (text.indexOf('\r\n') !== -1) {
delim = '\r\n'
} else if (text.indexOf('\r') !== -1) {
delim = '\r'
} // if
var STATES = {
ABORT: -1,
UNKNOWN: 0,
TOPICS_NEED_HEADERS: 1,
SYNAPSES_NEED_HEADERS: 2,
TOPICS: 3,
2016-03-27 11:43:30 +00:00
SYNAPSES: 4
}
// state & lines determine parser behaviour
2016-03-27 11:43:30 +00:00
var state = STATES.UNKNOWN
var lines = text.split(delim)
var results = { topics: [], synapses: [] }
2016-03-27 11:43:30 +00:00
var topicHeaders = []
var synapseHeaders = []
2016-11-07 20:25:08 +00:00
lines.forEach(function(lineRaw, index) {
const line = lineRaw.split('\t')
var noblanks = line.filter(function(elt) {
2016-03-27 11:43:30 +00:00
return elt !== ''
})
switch (state) {
case STATES.UNKNOWN:
if (noblanks.length === 0) {
2016-03-27 11:43:30 +00:00
state = STATES.UNKNOWN
break
} else if (noblanks.length === 1 && self.simplify(line[0]) === 'topics') {
2016-03-27 11:43:30 +00:00
state = STATES.TOPICS_NEED_HEADERS
break
} else if (noblanks.length === 1 && self.simplify(line[0]) === 'synapses') {
2016-03-27 11:43:30 +00:00
state = STATES.SYNAPSES_NEED_HEADERS
break
}
2016-03-27 11:43:30 +00:00
state = STATES.TOPICS_NEED_HEADERS
// FALL THROUGH - if we're not sure what to do, pretend
// we're on the TOPICS_NEED_HEADERS state and parse some headers
case STATES.TOPICS_NEED_HEADERS: // eslint-disable-line no-fallthrough
if (noblanks.length < 2) {
2016-03-27 11:43:30 +00:00
self.abort('Not enough topic headers on line ' + index)
state = STATES.ABORT
}
2016-11-07 20:25:08 +00:00
topicHeaders = line.map(function(header, index) {
return self.normalizeKey(header)
2016-03-27 11:43:30 +00:00
})
state = STATES.TOPICS
break
case STATES.SYNAPSES_NEED_HEADERS:
if (noblanks.length < 2) {
2016-03-27 11:43:30 +00:00
self.abort('Not enough synapse headers on line ' + index)
state = STATES.ABORT
}
2016-11-07 20:25:08 +00:00
synapseHeaders = line.map(function(header, index) {
return self.normalizeKey(header)
2016-03-27 11:43:30 +00:00
})
state = STATES.SYNAPSES
break
case STATES.TOPICS:
if (noblanks.length === 0) {
2016-03-27 11:43:30 +00:00
state = STATES.UNKNOWN
} else if (noblanks.length === 1 && line[0].toLowerCase() === 'topics') {
2016-03-27 11:43:30 +00:00
state = STATES.TOPICS_NEED_HEADERS
} else if (noblanks.length === 1 && line[0].toLowerCase() === 'synapses') {
2016-03-27 11:43:30 +00:00
state = STATES.SYNAPSES_NEED_HEADERS
} else {
2016-03-27 11:43:30 +00:00
var topic = {}
2016-11-07 20:25:08 +00:00
line.forEach(function(field, index) {
2016-03-27 11:43:30 +00:00
var header = topicHeaders[index]
if (self.topicWhitelist.indexOf(header) === -1) return
topic[header] = field
if (['id', 'x', 'y'].indexOf(header) !== -1) {
2016-03-27 11:43:30 +00:00
topic[header] = parseInt(topic[header])
} // if
})
results.topics.push(topic)
}
2016-03-27 11:43:30 +00:00
break
case STATES.SYNAPSES:
if (noblanks.length === 0) {
2016-03-27 11:43:30 +00:00
state = STATES.UNKNOWN
} else if (noblanks.length === 1 && line[0].toLowerCase() === 'topics') {
2016-03-27 11:43:30 +00:00
state = STATES.TOPICS_NEED_HEADERS
} else if (noblanks.length === 1 && line[0].toLowerCase() === 'synapses') {
2016-03-27 11:43:30 +00:00
state = STATES.SYNAPSES_NEED_HEADERS
} else {
2016-03-27 11:43:30 +00:00
var synapse = {}
2016-11-07 20:25:08 +00:00
line.forEach(function(field, index) {
2016-03-27 11:43:30 +00:00
var header = synapseHeaders[index]
if (self.synapseWhitelist.indexOf(header) === -1) return
synapse[header] = field
if (['id', 'topic1', 'topic2'].indexOf(header) !== -1) {
2016-03-27 11:43:30 +00:00
synapse[header] = parseInt(synapse[header])
} // if
})
results.synapses.push(synapse)
}
2016-03-27 11:43:30 +00:00
break
case STATES.ABORT:
// FALL THROUGH
default: // eslint-disable-line no-fallthrough
2016-03-27 11:43:30 +00:00
self.abort('Invalid state while parsing import data. Check code.')
state = STATES.ABORT
}
2016-03-27 11:43:30 +00:00
})
if (state === STATES.ABORT) {
2016-03-27 11:43:30 +00:00
return false
} else {
2016-03-27 11:43:30 +00:00
return results
}
},
2016-11-07 20:25:08 +00:00
importTopics: function(parsedTopics) {
var self = Import
2016-10-26 12:34:22 +00:00
parsedTopics.forEach(topic => {
2016-10-01 04:57:19 +00:00
let coords = { x: topic.x, y: topic.y }
if (!coords.x || !coords.y) {
2016-10-03 00:32:37 +00:00
coords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings })
}
2016-10-01 04:57:19 +00:00
if (!topic.name && topic.link ||
topic.name && topic.link && !topic.metacode) {
self.handleURL(topic.link, {
coords,
name: topic.name,
permission: topic.permission,
2016-11-07 20:25:08 +00:00
importId: topic.id
2016-10-01 04:57:19 +00:00
})
return // "continue"
}
self.createTopicWithParameters(
topic.name, topic.metacode, topic.permission,
2016-10-01 04:57:19 +00:00
topic.desc, topic.link, coords.x, coords.y, topic.id
2016-03-27 11:43:30 +00:00
)
})
},
2016-11-07 20:25:08 +00:00
importSynapses: function(parsedSynapses) {
var self = Import
2016-11-07 20:25:08 +00:00
parsedSynapses.forEach(function(synapse) {
2016-03-27 11:43:30 +00:00
// only createSynapseWithParameters once both topics are persisted
// if there isn't a cidMapping, check by topic name instead
var topic1 = DataModel.Topics.get(self.cidMappings[synapse.topic1])
if (!topic1) topic1 = DataModel.Topics.findWhere({ name: synapse.topic1 })
var topic2 = DataModel.Topics.get(self.cidMappings[synapse.topic2])
if (!topic2) topic2 = DataModel.Topics.findWhere({ name: synapse.topic2 })
2016-03-31 01:25:14 +00:00
if (!topic1 || !topic2) {
console.error("One of the two topics doesn't exist!")
console.error(synapse)
return // next
2016-03-31 01:25:14 +00:00
}
2016-10-27 06:03:18 +00:00
const topic1Promise = $.Deferred()
if (topic1.id) {
topic1Promise.resolve()
} else {
topic1.on('sync', () => topic1Promise.resolve())
}
const topic2Promise = $.Deferred()
if (topic2.id) {
topic2Promise.resolve()
} else {
topic2.on('sync', () => topic2Promise.resolve())
}
$.when(topic1Promise, topic2Promise).done(() => {
self.createSynapseWithParameters(
synapse.desc, synapse.category, synapse.permission,
topic1, topic2
)
})
2016-03-27 11:43:30 +00:00
})
},
2016-11-07 20:25:08 +00:00
createTopicWithParameters: function(name, metacodeName, permission, desc,
link, xloc, yloc, importId, opts = {}) {
var self = Import
2016-09-22 09:36:47 +00:00
$(document).trigger(Map.events.editedByActiveMapper)
2016-11-07 20:25:08 +00:00
var metacode = DataModel.Metacodes.where({name: metacodeName})[0] || null
2016-07-03 05:31:04 +00:00
if (metacode === null) {
metacode = DataModel.Metacodes.where({ name: 'Wildcard' })[0]
2016-11-07 20:25:08 +00:00
console.warn("Couldn't find metacode " + metacodeName + ' so used Wildcard instead.')
2016-07-03 05:31:04 +00:00
}
2016-11-07 20:25:08 +00:00
const topicPermision = permission || Active.Map.get('permission')
var deferToMapId = permission === topicPermision ? Active.Map.get('id') : null
var topic = new DataModel.Topic({
name: name,
metacode_id: metacode.id,
2016-11-07 20:25:08 +00:00
permission: topicPermision,
defer_to_map_id: deferToMapId,
2016-10-13 08:48:46 +00:00
desc: desc || '',
link: link || '',
2016-09-22 09:36:47 +00:00
calculated_permission: Active.Map.get('permission')
2016-03-27 11:43:30 +00:00
})
DataModel.Topics.add(topic)
2016-11-07 20:25:08 +00:00
if (importId !== null && importId !== undefined) {
self.cidMappings[importId] = topic.cid
}
var mapping = new DataModel.Mapping({
2016-03-27 11:43:30 +00:00
xloc: xloc,
yloc: yloc,
mappable_id: topic.cid,
mappable_type: 'Topic'
})
DataModel.Mappings.add(mapping)
2016-02-07 09:51:01 +00:00
// this function also includes the creation of the topic in the database
2016-09-22 10:31:56 +00:00
Topic.renderTopic(mapping, topic, true, true, {
success: opts.success
})
2016-09-22 10:31:56 +00:00
GlobalUI.hideDiv('#instructions')
},
2016-11-07 20:25:08 +00:00
createSynapseWithParameters: function(desc, category, permission,
2016-03-27 11:43:30 +00:00
topic1, topic2) {
var node1 = topic1.get('node')
var node2 = topic2.get('node')
if (!topic1.id || !topic2.id) {
2016-03-27 11:43:30 +00:00
console.error('missing topic id when creating synapse')
return
} // if
var synapse = new DataModel.Synapse({
2016-10-13 08:48:46 +00:00
desc: desc || '',
category: category || 'from-to',
permission: permission,
topic1_id: topic1.id,
topic2_id: topic2.id
2016-03-27 11:43:30 +00:00
})
DataModel.Synapses.add(synapse)
var mapping = new DataModel.Mapping({
2016-03-27 11:43:30 +00:00
mappable_type: 'Synapse',
mappable_id: synapse.cid
})
DataModel.Mappings.add(mapping)
2016-03-27 11:43:30 +00:00
2016-09-22 10:31:56 +00:00
Synapse.renderSynapse(mapping, synapse, node1, node2, true)
},
2016-11-07 20:25:08 +00:00
handleURL: function(url, opts = {}) {
2016-10-01 04:57:19 +00:00
let coords = opts.coords
if (!coords || coords.x === undefined || coords.y === undefined) {
2016-10-03 00:32:37 +00:00
coords = AutoLayout.getNextCoord({ mappings: DataModel.Mappings })
2016-10-01 04:57:19 +00:00
}
const name = opts.name || 'Link'
const metacode = opts.metacode || 'Reference'
2016-11-07 20:25:08 +00:00
const importId = opts.importId || null // don't store a cidMapping
2016-10-01 04:57:19 +00:00
const permission = opts.permission || null // use default
const desc = opts.desc || url
Import.createTopicWithParameters(
name,
metacode,
permission,
desc,
url,
coords.x,
coords.y,
2016-11-07 20:25:08 +00:00
importId,
2016-10-01 04:57:19 +00:00
{
success: function(topic) {
if (topic.get('name') !== 'Link') return
$.get('/hacks/load_url_title', {
url
}, function success(data, textStatus) {
var selector = '#showcard #topic_' + topic.get('id') + ' .best_in_place'
if ($(selector).find('form').length > 0) {
$(selector).find('textarea, input').val(data.title)
} else {
$(selector).html(data.title)
}
topic.set('name', data.title)
topic.save()
})
}
}
)
},
/*
* helper functions
*/
2016-11-07 20:25:08 +00:00
abort: function(message) {
console.error(message)
},
2016-10-01 04:57:19 +00:00
// TODO investigate replacing with es6 (?) trim()
2016-11-07 20:25:08 +00:00
simplify: function(string) {
return string
.replace(/(^\s*|\s*$)/g, '')
.toLowerCase()
},
normalizeKey: function(key) {
let newKey = key.toLowerCase()
newKey = newKey.replace(/\s/g, '') // remove whitespace
if (newKey === 'url') newKey = 'link'
if (newKey === 'title') newKey = 'name'
if (newKey === 'label') newKey = 'desc'
if (newKey === 'description') newKey = 'desc'
if (newKey === 'direction') newKey = 'category'
return newKey
},
// thanks to http://stackoverflow.com/a/25290114/5332286
2016-10-01 04:57:19 +00:00
normalizeKeys: function(obj) {
return _.transform(obj, (result, val, key) => {
const newKey = Import.normalizeKey(key)
2016-10-01 04:57:19 +00:00
result[newKey] = val
})
2016-03-27 11:43:30 +00:00
}
}
export default Import