"use strict";
require("core-js/modules/es.object.keys.js");
require("core-js/modules/es.symbol.js");
require("core-js/modules/es.array.filter.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
require("core-js/modules/es.object.get-own-property-descriptors.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/es.weak-map.js");
require("core-js/modules/web.dom-collections.iterator.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.transformNewForm = transformNewForm;
exports.workToFormState = workToFormState;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteral"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
require("core-js/modules/es.date.to-json.js");
require("core-js/modules/web.url.to-json.js");
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.array.map.js");
require("core-js/modules/es.array.splice.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/web.dom-collections.for-each.js");
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _isEmpty2 = _interopRequireDefault(require("lodash/isEmpty"));
var _map2 = _interopRequireDefault(require("lodash/map"));
var auth = _interopRequireWildcard(require("../../helpers/auth"));
var entityRoutes = _interopRequireWildcard(require("./entity"));
var middleware = _interopRequireWildcard(require("../../helpers/middleware"));
var search = _interopRequireWildcard(require("../../../common/helpers/search"));
var utils = _interopRequireWildcard(require("../../helpers/utils"));
var _entityRouteUtils = require("../../helpers/entityRouteUtils");
var _error = require("../../../common/helpers/error");
var _privilegesUtils = require("../../../common/helpers/privileges-utils");
var _types = require("../../../client/entity-editor/relationship-editor/types");
var _props = require("../../helpers/props");
var _express = _interopRequireDefault(require("express"));
var _log = _interopRequireDefault(require("log"));
var _utils2 = require("../../../common/helpers/utils");
var _target = _interopRequireDefault(require("../../templates/target"));
var _excluded = ["languageId"],
_excluded2 = ["type"];
var _templateObject;
/*
* Copyright (C) 2015 Ben Ockmore
* 2015-2016 Sean Burke
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
/** ****************************
*********** Helpers ************
*******************************/
function transformNewForm(data) {
var aliases = entityRoutes.constructAliases(data.aliasEditor, data.nameSection);
var identifiers = entityRoutes.constructIdentifiers(data.identifierEditor);
var relationships = entityRoutes.constructRelationships(data.relationshipSection);
var languages = (0, _map2.default)(data.workSection.languages, function (language) {
return language.value;
});
return {
aliases: aliases,
annotation: data.annotationSection.content,
disambiguation: data.nameSection.disambiguation,
identifiers: identifiers,
languages: languages,
note: data.submissionSection.note,
relationships: relationships,
typeId: data.workSection.type
};
}
var createOrEditHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('work', transformNewForm, 'typeId');
var mergeHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('work', transformNewForm, 'typeId', true);
var ENTITY_EDITOR = _privilegesUtils.PrivilegeType.ENTITY_EDITOR;
/** ****************************
*********** Routes *************
*******************************/
var router = _express.default.Router();
// Creation
router.get('/create', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadLanguages, middleware.loadWorkTypes, middleware.loadRelationshipTypes, function (req, res, next) {
var _req$app$locals$orm = req.app.locals.orm,
Author = _req$app$locals$orm.Author,
Edition = _req$app$locals$orm.Edition;
var relationshipTypeId;
var initialRelationshipIndex = 0;
var propsPromise = (0, _entityRouteUtils.generateEntityProps)('work', req, res, {});
if (req.query.author) {
propsPromise.author = Author.forge({
bbid: req.query.author
}).fetch({
require: false,
withRelated: 'defaultAlias'
}).then(function (data) {
return data && utils.entityToOption(data.toJSON());
});
}
if (req.query.edition) {
propsPromise.edition = Edition.forge({
bbid: req.query.edition
}).fetch({
require: false,
withRelated: 'defaultAlias'
}).then(function (data) {
return data && utils.entityToOption(data.toJSON());
});
}
function render(_x) {
return _render.apply(this, arguments);
}
function _render() {
_render = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(props) {
var _req$query$name, _req$query;
var nameSection, editorMarkup, markup, updatedProps;
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (props.author) {
// add initial ralationship with relationshipTypeId = 8 (<Work> is written by <Author>)
relationshipTypeId = _types.RelationshipTypes.AuthorWroteWork;
(0, _entityRouteUtils.addInitialRelationship)(props, relationshipTypeId, initialRelationshipIndex++, props.author);
}
if (props.edition) {
// add initial ralationship with relationshipTypeId = 10 (<Work> is contained in <Edition>)
relationshipTypeId = _types.RelationshipTypes.EditionContainsWork;
(0, _entityRouteUtils.addInitialRelationship)(props, relationshipTypeId, initialRelationshipIndex++, props.edition);
}
nameSection = {
disambiguation: '',
exactMatches: null,
language: null,
name: (_req$query$name = (_req$query = req.query) === null || _req$query === void 0 ? void 0 : _req$query.name) !== null && _req$query$name !== void 0 ? _req$query$name : '',
searchResults: null,
sortName: ''
};
if (!nameSection.name) {
_context.next = 16;
break;
}
_context.prev = 4;
_context.next = 7;
return search.autocomplete(req.app.locals.orm, nameSection.name, 'Work');
case 7:
nameSection.searchResults = _context.sent;
_context.next = 10;
return search.checkIfExists(req.app.locals.orm, nameSection.name, 'Work');
case 10:
nameSection.exactMatches = _context.sent;
_context.next = 16;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](4);
_log.default.debug(_context.t0);
case 16:
props.initialState.nameSection = nameSection;
editorMarkup = (0, _entityRouteUtils.entityEditorMarkup)(props);
markup = editorMarkup.markup;
updatedProps = editorMarkup.props;
return _context.abrupt("return", res.send((0, _target.default)({
markup: markup,
props: (0, _props.escapeProps)(updatedProps),
script: '/js/entity-editor.js',
title: props.heading
})));
case 21:
case "end":
return _context.stop();
}
}
}, _callee, null, [[4, 13]]);
}));
return _render.apply(this, arguments);
}
(0, _utils2.makePromiseFromObject)(propsPromise).then(render).catch(next);
});
router.post('/create', entityRoutes.displayPreview, auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadLanguages, middleware.loadWorkTypes, middleware.loadRelationshipTypes, /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(req, res, next) {
var _entity$workSection;
var WorkType, entity, propsPromise, render;
return _regenerator.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
render = function _render2(props) {
var editorMarkup = (0, _entityRouteUtils.entityEditorMarkup)(props);
var markup = editorMarkup.markup;
var updatedProps = editorMarkup.props;
return res.send((0, _target.default)({
markup: markup,
props: (0, _props.escapeProps)(updatedProps),
script: '/js/entity-editor.js',
title: props.heading
}));
};
WorkType = req.app.locals.orm.WorkType;
_context2.next = 4;
return utils.parseInitialState(req, 'work');
case 4:
entity = _context2.sent;
if (!((_entity$workSection = entity.workSection) !== null && _entity$workSection !== void 0 && _entity$workSection.type)) {
_context2.next = 9;
break;
}
_context2.next = 8;
return utils.getIdByField(WorkType, 'label', entity.workSection.type);
case 8:
entity.workSection.type = _context2.sent;
case 9:
if (!entity.workSection) {
_context2.next = 13;
break;
}
_context2.next = 12;
return utils.parseLanguages(entity.workSection, req.app.locals.orm);
case 12:
entity.workSection = _context2.sent;
case 13:
propsPromise = (0, _entityRouteUtils.generateEntityProps)('work', req, res, {}, function () {
return entity;
});
(0, _utils2.makePromiseFromObject)(propsPromise).then(render).catch(next);
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
}());
router.post('/create/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), createOrEditHandler);
/* If the route specifies a BBID, make sure it does not redirect to another bbid then load the corresponding entity */
router.param('bbid', middleware.redirectedBbid);
router.param('bbid', middleware.makeEntityLoader('Work', ['workType', 'languageSet.languages'], 'Work not found'));
function _setWorkTitle(res) {
res.locals.title = utils.createEntityPageTitle(res.locals.entity, 'Work', utils.template(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["Work \u201C", "\u201D"])), 'name'));
}
router.get('/:bbid', middleware.loadEntityRelationships, middleware.loadWikipediaExtract, function (req, res) {
_setWorkTitle(res);
entityRoutes.displayEntity(req, res);
});
router.get('/:bbid/delete', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), function (req, res, next) {
if (!res.locals.entity.dataId) {
return next(new _error.ConflictError('This entity has already been deleted'));
}
_setWorkTitle(res);
return entityRoutes.displayDeleteEntity(req, res);
});
router.post('/:bbid/delete/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), function (req, res) {
var orm = req.app.locals.orm;
var WorkHeader = orm.WorkHeader,
WorkRevision = orm.WorkRevision;
return entityRoutes.handleDelete(orm, req, res, WorkHeader, WorkRevision);
});
router.get('/:bbid/revisions', function (req, res, next) {
var WorkRevision = req.app.locals.orm.WorkRevision;
_setWorkTitle(res);
entityRoutes.displayRevisions(req, res, next, WorkRevision);
});
router.get('/:bbid/revisions/revisions', function (req, res, next) {
var WorkRevision = req.app.locals.orm.WorkRevision;
_setWorkTitle(res);
entityRoutes.updateDisplayedRevisions(req, res, next, WorkRevision);
});
function workToFormState(work) {
/** The front-end expects a language id rather than the language object. */
var aliases = work.aliasSet ? work.aliasSet.aliases.map(function (_ref2) {
var languageId = _ref2.languageId,
rest = (0, _objectWithoutProperties2.default)(_ref2, _excluded);
return _objectSpread(_objectSpread({}, rest), {}, {
language: languageId
});
}) : [];
var defaultAliasIndex = entityRoutes.getDefaultAliasIndex(work.aliasSet);
var defaultAliasList = aliases.splice(defaultAliasIndex, 1);
var aliasEditor = {};
aliases.forEach(function (alias) {
aliasEditor[alias.id] = alias;
});
var buttonBar = {
aliasEditorVisible: false,
identifierEditorVisible: false
};
var nameSection = (0, _isEmpty2.default)(defaultAliasList) ? {
language: null,
name: '',
sortName: ''
} : defaultAliasList[0];
nameSection.disambiguation = work.disambiguation && work.disambiguation.comment;
var identifiers = work.identifierSet ? work.identifierSet.identifiers.map(function (_ref3) {
var type = _ref3.type,
rest = (0, _objectWithoutProperties2.default)(_ref3, _excluded2);
return _objectSpread({
type: type.id
}, rest);
}) : [];
var identifierEditor = {};
identifiers.forEach(function (identifier) {
identifierEditor[identifier.id] = identifier;
});
var workSection = {
languages: work.languageSet ? work.languageSet.languages.map(function (_ref4) {
var id = _ref4.id,
name = _ref4.name;
return {
label: name,
value: id
};
}) : [],
type: work.workType && work.workType.id
};
var relationshipSection = {
canEdit: true,
lastRelationships: null,
relationshipEditorProps: null,
relationshipEditorVisible: false,
relationships: {}
};
work.relationships.forEach(function (relationship) {
return relationshipSection.relationships["n".concat(relationship.id)] = {
attributeSetId: relationship.attributeSetId,
attributes: relationship.attributeSet ? relationship.attributeSet.relationshipAttributes : [],
relationshipType: relationship.type,
rowID: "n".concat(relationship.id),
sourceEntity: relationship.source,
targetEntity: relationship.target
};
});
var optionalSections = {};
if (work.annotation) {
optionalSections.annotationSection = work.annotation;
}
return _objectSpread({
aliasEditor: aliasEditor,
buttonBar: buttonBar,
identifierEditor: identifierEditor,
nameSection: nameSection,
relationshipSection: relationshipSection,
workSection: workSection
}, optionalSections);
}
router.get('/:bbid/edit', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadWorkTypes, middleware.loadLanguages, middleware.loadEntityRelationships, middleware.loadRelationshipTypes, function (req, res) {
var _entityEditorMarkup = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('work', req, res, {}, workToFormState)),
markup = _entityEditorMarkup.markup,
props = _entityEditorMarkup.props;
return res.send((0, _target.default)({
markup: markup,
props: (0, _props.escapeProps)(props),
script: '/js/entity-editor.js',
title: props.heading
}));
});
router.post('/:bbid/edit/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), createOrEditHandler);
router.post('/:bbid/merge/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), mergeHandler);
var _default = router;
exports.default = _default;
//# sourceMappingURL=work.js.map