onix-gen-funstory
Version:
onix generator
399 lines (398 loc) • 19.8 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = require("fs");
var path = __importStar(require("path"));
var xml2js = __importStar(require("xml2js"));
var moment_1 = __importDefault(require("moment"));
var readFile = fs_1.promises.readFile;
exports.xml2jsParser = function (text) { return __awaiter(void 0, void 0, void 0, function () {
var parser;
return __generator(this, function (_a) {
parser = new xml2js.Parser();
return [2 /*return*/, new Promise(function (resolve, reject) {
parser.parseString(text, function (err, result) {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
})];
});
}); };
var ONIXGenerator = /** @class */ (function () {
function ONIXGenerator(initOption) {
this.initOption = {
senderName: 'Funstory',
contactName: 'Funstory',
emailAddress: 'email@email.com',
cityOfPublication: 'BeiJing',
countryOfManufacture: 'CN',
publisherName: 'Funstory',
websiteLink: 'https://funstory.ai',
};
if (initOption) {
this.initOption = initOption;
}
this.tempObj = '';
}
ONIXGenerator.prototype.init = function (initOption) {
return __awaiter(this, void 0, void 0, function () {
var onixTmp, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (initOption) {
this.initOption = initOption;
}
return [4 /*yield*/, readFile(path.join(__dirname, "./onixTmp.xml"))];
case 1:
onixTmp = _b.sent();
// ONIX模板xml2js
_a = this;
return [4 /*yield*/, exports.xml2jsParser(onixTmp.toString('utf8'))];
case 2:
// ONIX模板xml2js
_a.tempObj = _b.sent();
return [2 /*return*/];
}
});
});
};
ONIXGenerator.prototype.getTemp = function () {
return this.tempObj;
};
ONIXGenerator.prototype.genONIX = function (bookinfo) {
if (this.tempObj === '') {
throw new Error('please run init() first');
}
var onixObj = __assign({}, this.tempObj);
onixObj.ONIXMessage.Header[0].Sender[0].SenderName = this.initOption.senderName;
onixObj.ONIXMessage.Header[0].Sender[0].ContactName = this.initOption.contactName;
onixObj.ONIXMessage.Header[0].Sender[0].EmailAddress = this.initOption.emailAddress;
// onixObj.ONIXMessage.Product[0].DescriptiveDetail[0]
// .CountryOfManufacture = this.initOption.countryOfManufacture;
onixObj.ONIXMessage.Product[0].PublishingDetail[0]
.Publisher[0].PublisherName = this.initOption.publisherName;
onixObj.ONIXMessage.Product[0].PublishingDetail[0]
.Publisher[0].Website[0].WebsiteLink = this.initOption.websiteLink;
onixObj.ONIXMessage.Product[0].PublishingDetail[0]
.CityOfPublication = this.initOption.cityOfPublication;
onixObj.ONIXMessage.Product[0].PublishingDetail[0]
.CountryOfPublication = this.initOption.countryOfManufacture;
onixObj.ONIXMessage.Product[0].ProductSupply[0]
.SupplyDetail[0].Supplier[0].SupplierName = this.initOption.publisherName;
// ISBN
var isbnNum = bookinfo.isbn;
onixObj.ONIXMessage.Product[0].RecordReference = isbnNum;
onixObj.ONIXMessage.Product[0].ProductIdentifier[0].IDValue = isbnNum;
// 书名
var bookTitle = bookinfo.bookName;
var volumeNum = bookinfo.volume;
var subTitle = bookinfo.subTitle;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].TitleDetail[0]
.TitleElement[0].TitleText = "" + bookTitle;
// 副标题
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].TitleDetail[0]
.TitleElement[0].Subtitle = subTitle ? subTitle : "Book " + volumeNum;
// 第几卷(系列号)
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Collection[0]
.CollectionSequence[0].CollectionSequenceNumber = volumeNum;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Collection[0]
.TitleDetail[0].TitleElement[0].TitleText = "Book " + volumeNum;
// 作者
var bookAuthor = bookinfo.author.split(' ');
var familyName1 = bookAuthor.shift() || '';
var familyName = familyName1[0] ? "" + familyName1[0].toUpperCase() + familyName1.slice(1) : '';
var authorName1 = bookAuthor.join('');
var authorName = authorName1[0] ? "" + authorName1[0].toUpperCase() + authorName1.slice(1) : '';
// onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Contributor[0].KeyNames = bookAuthor;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Contributor[0].PersonName = familyName + " " + authorName;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Contributor[0].PersonNameInverted = authorName + ", " + familyName;
// 译者
var bookTranslator = bookinfo.translator.split(' ');
if (bookTranslator.length > 0) {
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Contributor[1].PersonName = bookTranslator[0] + " " + bookTranslator[1];
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Contributor[1].PersonNameInverted = bookTranslator[1] + ", " + bookTranslator[0];
}
var bookPageCount = bookinfo.pageCount;
if (bookPageCount) {
// onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Extent = [{}];
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Extent[0].ExtentType = '00';
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Extent[0].ExtentValue = bookPageCount;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Extent[0].ExtentUnit = '03';
}
else {
delete onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Extent;
}
// 小说类型 详见https://bisg.org/page/Fiction ['FIC008000', 'FIC009000', 'FIC028000']
var aBISACEdition = bookinfo.subjectCode;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Subject[0].SubjectCode = aBISACEdition;
// 关键词
var bookKeywords = bookinfo.keywords;
if (bookKeywords.length > 0) {
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Subject[1] = {};
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0].Subject[1].SubjectSchemeIdentifier = 20;
onixObj.ONIXMessage.Product[0].DescriptiveDetail[0]
.Subject[1].SubjectHeadingText = bookKeywords.join('; ');
}
// 小说简介
var description = bookinfo.description.replace(/(\r|\n)+/g, '').trim();
onixObj.ONIXMessage.Product[0].CollateralDetail[0].TextContent[0].Text[0]._ = description;
var nowdate = moment_1.default();
var publicationDate = bookinfo.publicationDate ? moment_1.default(bookinfo.publicationDate) : nowdate;
var preOrderDate = bookinfo.preOrderDate ? moment_1.default(bookinfo.preOrderDate) : undefined;
var publicationDateTime = parseInt(publicationDate.format('x'), 10);
var nowDateTime = parseInt(nowdate.format('x'), 10);
// 是否未发布 根据发布日期是否大于当前日期对比
var noPublushed = publicationDateTime > nowDateTime;
// 发送日期
onixObj.ONIXMessage.Header[0].SentDateTime = nowdate.format('YYYYMMDDTHHmm');
// 出版日期
onixObj.ONIXMessage.Product[0].PublishingDetail[0].PublishingDate[0] = {
PublishingDateRole: ['01'],
Date: [{
$: { dateformat: '00' },
_: publicationDate.format('YYYYMMDD'),
}],
};
// 解禁日期
onixObj.ONIXMessage.Product[0].PublishingDetail[0].PublishingDate[1] = {
PublishingDateRole: ['02'],
Date: [{
$: { dateformat: '00' },
_: publicationDate.format('YYYYMMDD'),
}],
};
// 上市日期
onixObj.ONIXMessage.Product[0].ProductSupply[0].
MarketPublishingDetail[0].MarketDate[0].Date[0]._ = publicationDate.format('YYYYMMDD');
// 是否可用 10 Not yet available, 20 Available
onixObj.ONIXMessage.Product[0].ProductSupply[0].SupplyDetail[0]
.ProductAvailability[0] = noPublushed ? '10' : '20';
// 出版状态 04 Active, 02 Forthcoming
onixObj.ONIXMessage.Product[0].PublishingDetail[0].PublishingStatus[0] = noPublushed ? '02' : '04';
onixObj.ONIXMessage.Product[0].ProductSupply[0].MarketPublishingDetail[0].MarketPublishingStatus[0] = noPublushed ? '02' : '04';
// 预售信息
if (preOrderDate && (parseInt(preOrderDate.format('x'), 10) < publicationDateTime)) {
// 预售日期
onixObj.ONIXMessage.Product[0].PublishingDetail[0].PublishingDate[2] = {
PublishingDateRole: ['09'],
Date: [{
$: { dateformat: '00' },
_: preOrderDate.format('YYYYMMDD'),
}],
};
}
// if (noPublushed) {
// onixObj.ONIXMessage.Product[0].ProductSupply[0].SupplyDetail[0].SupplyDate = [];
// onixObj.ONIXMessage.Product[0].ProductSupply[0].SupplyDetail[0].SupplyDate[0] = {
// SupplyDateRole: '02',
// Date: [{
// $: { dateformat: '00' },
// _: publicationDate.format('YYYYMMDD'),
// }],
// };
// onixObj.ONIXMessage.Product[0].ProductSupply[0].SupplyDetail[0].SupplyDate[1] = {
// SupplyDateRole: '08',
// Date: [{
// $: { dateformat: '00' },
// _: publicationDate.format('YYYYMMDD'),
// }],
// };
// }
var salesRestriction = bookinfo.salesRestriction || 'KINDLE_ONLY';
switch (salesRestriction) {
case 'KINDLE_ONLY':
onixObj.ONIXMessage.Product[0].PublishingDetail[0].SalesRestriction = [];
onixObj.ONIXMessage.Product[0].PublishingDetail[0].SalesRestriction[0] = {
SalesRestrictionType: ['04'],
SalesOutlet: [
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['AMZ']
}],
SalesOutletName: ['Amazon eBookBase']
},
],
};
break;
case 'TOP_FIVE':
onixObj.ONIXMessage.Product[0].PublishingDetail[0].SalesRestriction = [];
onixObj.ONIXMessage.Product[0].PublishingDetail[0].SalesRestriction[0] = {
SalesRestrictionType: ['04'],
SalesOutlet: [
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['AMZ']
}],
SalesOutletName: ['Amazon eBookBase']
},
// {
// SalesOutletIdentifier: [{
// SalesOutletIDType: ['03'],
// IDValue: ['BNO']
// }],
// SalesOutletName: ['Barnes And Noble']
// },
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['GOO']
}],
SalesOutletName: ['Google Books']
},
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['APC']
}],
SalesOutletName: ['iBookstore']
},
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['KBO']
}],
SalesOutletName: ['Kobo']
},
],
};
break;
default:
onixObj.ONIXMessage.Product[0].PublishingDetail[0].SalesRestriction = [];
onixObj.ONIXMessage.Product[0].PublishingDetail[0].SalesRestriction[0] = {
SalesRestrictionType: ['04'],
SalesOutlet: [
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['AMZ']
}],
SalesOutletName: ['Amazon eBookBase']
},
// {
// SalesOutletIdentifier: [{
// SalesOutletIDType: ['03'],
// IDValue: ['BNO']
// }],
// SalesOutletName: ['Barnes And Noble']
// },
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['GOO']
}],
SalesOutletName: ['Google Books']
},
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['APC']
}],
SalesOutletName: ['iBookstore']
},
{
SalesOutletIdentifier: [{
SalesOutletIDType: ['03'],
IDValue: ['KBO']
}],
SalesOutletName: ['Kobo']
},
],
};
break;
}
// 地区及当地价格
var priceInfo = bookinfo.price;
onixObj.ONIXMessage.Product[0].ProductSupply[0]
.SupplyDetail[0].Price = priceInfo.map(function (price) { return ({
PriceType: '01',
PriceStatus: '01',
PriceAmount: price.priceAmount,
CurrencyCode: price.currencyCode,
Territory: [
(price.countriesIncluded.length === 1 && price.countriesIncluded[0] === 'WORLD') ? ({
RegionsIncluded: price.countriesIncluded[0],
CountriesExcluded: 'CN',
}) : ({
CountriesIncluded: price.countriesIncluded.join(' '),
})
]
}); });
// 返回ONIX xml
// 下架ONIX
if (bookinfo.takedown) {
onixObj.ONIXMessage.Product[0].NotificationType[0] = '04';
onixObj.ONIXMessage.Product[0].ProductSupply[0].SupplyDetail[0]
.ProductAvailability[0] = '51';
onixObj.ONIXMessage.Product[0].PublishingDetail[0].PublishingStatus[0] = '07';
onixObj.ONIXMessage.Product[0].ProductSupply[0].MarketPublishingDetail[0]
.MarketPublishingStatus[0] = '07';
}
var js2xmlBuilder2 = new xml2js.Builder({ renderOpts: { pretty: true } });
return js2xmlBuilder2.buildObject(onixObj);
};
return ONIXGenerator;
}());
exports.ONIXGenerator = ONIXGenerator;