Рабочая версия

This commit is contained in:
LightAir
2018-05-30 22:20:54 +03:00
parent 8645a88b01
commit d896040f63
10 changed files with 107 additions and 52 deletions

View File

@@ -50,8 +50,9 @@ function items(items, channel) {
let item_values = []; let item_values = [];
item_values.push({_attr: {'turbo': 'true'}}); item_values.push({_attr: {'turbo': 'true'}});
item_values.push({link: item.url}); item_values.push({link: item.url});
item_values.push({'turbo:source': item.url});
ifTruePush(item.turboSource, item_values, {'turbo:source': item.turboSource});
ifTruePush(item.turboTopic, item_values, {'turbo:topic': item.turboTopic});
ifTruePush(item.date, item_values, {pubDate: new Date(item.date).toUTCString()}); ifTruePush(item.date, item_values, {pubDate: new Date(item.date).toUTCString()});
ifTruePush(item.author, item_values, {author: item.author}); ifTruePush(item.author, item_values, {author: item.author});
@@ -62,8 +63,10 @@ function items(items, channel) {
img = '<figure><img src="' + item.image_url + '" /></figure>'; img = '<figure><img src="' + item.image_url + '" /></figure>';
} }
if (item.menu) { if (Array.isArray(item.menu)) {
menu = '<menu>' + item.menu + '</menu>'; menu = '<menu>' + item.menu.map(function (item) {
return '<a href="' + item.link + '">' + item.text + '</a>';
}).join('') + '</menu>';
} }
let fullContent = '<header>' + img + ' <h1>' + item.title + '</h1>' + menu + '</header>' + item.content; let fullContent = '<header>' + img + ' <h1>' + item.title + '</h1>' + menu + '</header>' + item.content;
@@ -87,9 +90,9 @@ function generateXML(data) {
let channel = []; let channel = [];
channel.push({title: {_cdata: data.title}}); channel.push({title: {_cdata: data.title}});
channel.push({link: data.link || 'http://github.com/LightAir/turbo-rss'}); channel.push({link: data.link});
channel.push({description: {_cdata: data.description || data.title}}); channel.push({description: {_cdata: data.description || data.title}});
channel.push({language: 'ru'}); channel.push({language: data.language});
items(data.items, channel); items(data.items, channel);
@@ -114,27 +117,31 @@ function generateXML(data) {
* @param items * @param items
* @constructor * @constructor
*/ */
function YTurbo(options, items) { function TR(options, items) {
options = options || {}; options = options || {};
this.title = options.title || 'Untitled'; this.title = options.title || '';
this.link = options.link || '';
this.description = options.description || ''; this.description = options.description || '';
this.link = options.link; this.language = options.language || 'ru';
this.items = items || []; this.items = items || [];
this.item = function (data) { this.item = function (data) {
data = data || {}; data = data || {};
let item = { let item = {
title: data.title || 'No title', title: data.title || '',
description: data.description || '', description: data.description || '',
image_url: data.image_url, image_url: data.image_url,
url: data.url, url: data.url || data.link,
author: data.author, author: data.author,
date: data.date || data.pubDate, date: data.date || data.pubDate,
content: data.content, content: data.content,
menu: data.menu, menu: data.menu,
related: data.related, related: data.related,
relatedfinity: data.relatedfinity || false, relatedfinity: data.relatedfinity || false,
turboSource: data.turboSource || '',
turboTopic: data.turboTopic || ''
}; };
this.items.push(item); this.items.push(item);
@@ -146,4 +153,4 @@ function YTurbo(options, items) {
}; };
} }
module.exports = YTurbo; module.exports = TR;

View File

@@ -1,6 +1,6 @@
{ {
"name": "turbo-rss", "name": "turbo-rss",
"version": "1.0.7", "version": "1.0.8",
"description": "RSS based, feed generator for Yandex turbo", "description": "RSS based, feed generator for Yandex turbo",
"keywords": [ "keywords": [
"yandex", "yandex",
@@ -20,6 +20,7 @@
}, },
"contributors": [ "contributors": [
"LightAir <public@softroot.ru>", "LightAir <public@softroot.ru>",
"Ivan Pilyugin (aka Archer)",
"Dylan Greene <dylang@gmail.com>", "Dylan Greene <dylang@gmail.com>",
"Xavier Damman <xdamman@gmail.com>", "Xavier Damman <xdamman@gmail.com>",
"Michael R. Lange", "Michael R. Lange",

View File

@@ -1,5 +1,3 @@
## WIP
## turbo-rss ## turbo-rss
[![Maintainability](https://api.codeclimate.com/v1/badges/6525d2aabf20185b68b6/maintainability)](https://codeclimate.com/github/LightAir/turbo-rss/maintainability) [![Maintainability](https://api.codeclimate.com/v1/badges/6525d2aabf20185b68b6/maintainability)](https://codeclimate.com/github/LightAir/turbo-rss/maintainability)
@@ -8,9 +6,7 @@
[![npm](https://img.shields.io/badge/npm%20package-1.0.7-blue.svg?longCache=true&style=flat)](https://www.npmjs.com/package/turbo-rss) [![npm](https://img.shields.io/badge/npm%20package-1.0.7-blue.svg?longCache=true&style=flat)](https://www.npmjs.com/package/turbo-rss)
![license](https://img.shields.io/packagist/l/doctrine/orm.svg?longCache=true&style=flat) ![license](https://img.shields.io/packagist/l/doctrine/orm.svg?longCache=true&style=flat)
>Генератор RSS разметки для сервиса Турбо-страницы >Генератор RSS разметки для сервиса Турбо-страницы https://yandex.ru/support/webmaster/turbo/connection.html
>ПРЕДУПРЕЖДЕНИЕ! Работа в процессе
### Использование ### Использование
@@ -25,12 +21,11 @@ var feed = new TR(feedOptions);
##### `Опции канала` ##### `Опции канала`
* `title` **string** Название RSS-канала. * `title` **string** Название RSS-канала.
* `description` _optional_ **string** Описание канала одним предложением. Не используйте HTML-разметку.. * `link` **url string** Домен сайта, данные которого транслируются.
* `author` _optional_ **string** If included it is the name of the item's creator. **(Будет удалено)** * `description` _optional_ **string** Описание канала одним предложением. Не используйте HTML-разметку.
* `link` **url string** Домен сайта, данные которого транслируются.. * `language` _optional_ **string** Язык статьи по стандарту ISO 639-1. По умолчанию ru.
* `pubDate` _optional_ **Date object or date string** The publication date for content in the feed **(Будет удалено)**
*Будет добавлено в новых версиях turbo:analytics, turbo:adNetwork* *Будет добавлено в новых версиях turbo:analytics, turbo:adNetwork, на текущий момент можно добавить в интерфейсе Яндекс Вебмастер*
#### Добавление страницы в канал #### Добавление страницы в канал
```js ```js
@@ -40,22 +35,29 @@ feed.item(itemOptions);
##### itemOptions ##### itemOptions
* `title` **string** Заголовок страницы. * `title` **string** Заголовок страницы.
* `image_url` **url string** Адрес изображения, которое используется в качестве обложки. Изображение может быть в любом формате. * `image_url` _optional_ **url string** Адрес изображения, которое используется в качестве обложки. Изображение может быть в любом формате.
* `url` **url string** URL страницы сайта, для которой нужно сформировать Турбо-страницу. * `link` **url string** URL страницы сайта, для которой нужно сформировать Турбо-страницу.
* `author` _optional_ **string** Автор статьи, размещенной на странице. * `author` _optional_ **string** Автор статьи, размещенной на странице.
* `date` **string** Время публикации контента на сайте источника. * `date` или `pubDate` **string** Время публикации контента на сайте источника. Передается в формате RFC-822.
* `content` **string** Содержимое страницы * `content` **string** Содержимое страницы
* `related` _optional_ **array** Аффилированные ссылки `yandex:related` в конце статьи. * `menu` _optional_ **array** Внимание! Меню будет отображаться только в том случае, если в настройках на странице Яндекс Вебмастер -> Турбо-страницы -> Настройки, содержимое 'Меню Турбо-страниц' пустое!
* `related` _optional_ **array** Аффилированные ссылки `yandex:related` в конце статьи. Вы можете разместить ссылки на другие ресурсы или настроить отображение непрерывной ленты статей, реализованной, например с помощью AJAX.
* `relatedfinity` _optional_ **bool** Непрерывная лента статей * `relatedfinity` _optional_ **bool** Непрерывная лента статей
* `turboSource` _optional_ **string** URL страницы-источника, который можно передать в Яндекс.Метрику.
* `turboTopic` _optional_ **string** Заголовок страницы, который можно передать в Яндекс.Метрику.
*Будет добавлено в новых версиях turbo:source, turbo:topic, menu, pubDate как алиас date* ###### menu array
menu должен содержать массив объектов со следующими опциями:
* `link` **url string** ссылка
* `text` **string** текст ссылки. не должен содержать html
###### related array ###### related array
related должен содержать массив объектов со следующими опциями: related должен содержать массив объектов со следующими опциями:
* `link` **string** ссылка на статью' * `link` **url string** ссылка на статью
* `image_url` **string** ссылка на изображение к статье * `image_url` **url string** ссылка на изображение к статье
* `text` **string** текст ссылки * `text` **string** текст ссылки. Не должен содержать html
##### Получение XML ##### Получение XML
@@ -69,14 +71,12 @@ var xml = feed.xml();
```js ```js
var TR = require('turbo-rss'); var TR = require('turbo-rss');
/* lets create feed */
var feed = new TR({ var feed = new TR({
title: 'title', title: 'title',
description: 'description', description: 'description',
link: 'http://example.com', link: 'http://example.com',
}); });
/* loop over data and add to feed */
feed.item({ feed.item({
title: 'item title', title: 'item title',
image_url: 'http://example.com/example.png', image_url: 'http://example.com/example.png',
@@ -84,6 +84,13 @@ feed.item({
author: 'LightAir', author: 'LightAir',
date: 'May 27, 2012', date: 'May 27, 2012',
content: '<p>hello</p>', content: '<p>hello</p>',
menu: [{
link: 'http://example.com/',
text: 'Главная'
}, {
link: 'http://example.com/about',
text: 'О сайте'
}]
related: [{ related: [{
link: 'http://example.com/related/post1', link: 'http://example.com/related/post1',
image_url: 'http://example.com/i/img1.jpg', image_url: 'http://example.com/i/img1.jpg',
@@ -95,13 +102,12 @@ feed.item({
}] }]
}); });
// cache the xml to send to clients
var xml = feed.xml(); var xml = feed.xml();
``` ```
## Тестирование ## Тестирование
Для запуска тестов выполните `npm test`. На текущий момен покрытие тестами не 100% Для запуска тестов выполните `npm test`.
```sh ```sh
$ npm test $ npm test

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[Untitled]]></title><link>http://github.com/LightAir/turbo-rss</link><description><![CDATA[Untitled]]></description><language>ru</language></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title/><link></link><description/><language>ru</language></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link></link><turbo:source></turbo:source><turbo:content><![CDATA[<header> <h1>No title</h1></header>undefined]]></turbo:content></item></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link></link><turbo:content><![CDATA[<header> <h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[Untitled]]></title><link>http://github.com/LightAir/turbo-rss</link><description><![CDATA[Untitled]]></description><language>ru</language><item turbo="true"><link></link><turbo:source></turbo:source><turbo:content><![CDATA[<header> <h1>No title</h1></header>undefined]]></turbo:content></item></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title/><link></link><description/><language>ru</language><item turbo="true"><link></link><turbo:content><![CDATA[<header> <h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -0,0 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure> <h1>item title</h1><menu><a href="http://example.com/">Главная</a><a href="http://example.com/about">О сайте</a></menu></header><p>hello</p>]]></turbo:content><yandex:related type="infinity"><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item><item turbo="true"><link></link><turbo:content><![CDATA[<header> <h1></h1></header>undefined]]></turbo:content></item></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><turbo:source>http://example.com/article4?this&amp;that</turbo:source><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure> <h1>item title</h1><menu><a href="http://example.com/page1.html">Текст ссылки</a> <a href="http://example.com/page2.html">Текст ссылки</a></menu></header><p>hello</p>]]></turbo:content><yandex:related><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure> <h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss>

View File

@@ -1 +1 @@
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><turbo:source>http://example.com/article4?this&amp;that</turbo:source><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure> <h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related type="infinity"><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss> <rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><title><![CDATA[title]]></title><link>http://example.com/rss.xml</link><description><![CDATA[description]]></description><language>ru</language><item turbo="true"><link>http://example.com/article4?this&amp;that</link><pubDate>Sat, 26 May 2018 21:00:00 GMT</pubDate><author>LightAir</author><turbo:content><![CDATA[<header><figure><img src="http://example.com/example.png" /></figure> <h1>item title</h1></header><p>hello</p>]]></turbo:content><yandex:related type="infinity"><link url="http://example.com/related/post1" img="http://example.com/i/img1.jpg">related link text 1</link><link url="http://example.com/related/post2" img="http://example.com/i/img2.jpg">related link text 2</link></yandex:related></item></channel></rss>

View File

@@ -2,7 +2,7 @@
// use npm run test:browser to run tests in a browser // use npm run test:browser to run tests in a browser
const test = require('tape'); const test = require('tape');
const YTurbo = require('..'); const TR = require('..');
const includeFolder = require('include-folder'); const includeFolder = require('include-folder');
const expectedOutput = includeFolder(__dirname + '/expectedOutput', /.*\.xml$/); const expectedOutput = includeFolder(__dirname + '/expectedOutput', /.*\.xml$/);
@@ -11,7 +11,7 @@ require('mockdate').set('Wed, 10 Dec 2014 19:04:57 GMT');
test('empty feed', function (t) { test('empty feed', function (t) {
t.plan(2); t.plan(2);
let feed = new YTurbo(); let feed = new TR();
t.equal(feed.xml(), expectedOutput.default.trim()); t.equal(feed.xml(), expectedOutput.default.trim());
feed.item(); feed.item();
t.equal(feed.xml(), expectedOutput.defaultOneItem.trim()); t.equal(feed.xml(), expectedOutput.defaultOneItem.trim());
@@ -19,7 +19,7 @@ test('empty feed', function(t) {
test('default item', function (t) { test('default item', function (t) {
t.plan(1); t.plan(1);
let feed = new YTurbo({ let feed = new TR({
title: 'title', title: 'title',
description: 'description', description: 'description',
link: 'http://example.com/rss.xml', link: 'http://example.com/rss.xml',
@@ -33,7 +33,7 @@ test('default item', function(t) {
test('related item', function (t) { test('related item', function (t) {
t.plan(1); t.plan(1);
let feed = new YTurbo({ let feed = new TR({
title: 'title', title: 'title',
description: 'description', description: 'description',
link: 'http://example.com/rss.xml', link: 'http://example.com/rss.xml',
@@ -64,7 +64,7 @@ test('related item', function(t) {
test('related item', function (t) { test('related item', function (t) {
t.plan(1); t.plan(1);
let feed = new YTurbo({ let feed = new TR({
title: 'title', title: 'title',
description: 'description', description: 'description',
link: 'http://example.com/rss.xml', link: 'http://example.com/rss.xml',
@@ -92,3 +92,43 @@ test('related item', function(t) {
t.equal(feed.xml(), expectedOutput.relatedItemInfinity.trim()); t.equal(feed.xml(), expectedOutput.relatedItemInfinity.trim());
}); });
test('menu', function (t) {
t.plan(1);
let feed = new TR({
title: 'title',
description: 'description',
link: 'http://example.com/rss.xml',
site_url: 'http://example.com'
});
feed.item({
title: 'item title',
image_url: 'http://example.com/example.png',
url: 'http://example.com/article4?this&that',
author: 'LightAir',
date: 'May 27, 2018 00:00 AM',
content: '<p>hello</p>',
relatedfinity: true,
menu: [{
link: 'http://example.com/',
text: 'Главная',
}, {
link: 'http://example.com/about',
text: 'О сайте',
}],
related: [{
link: 'http://example.com/related/post1',
image_url: 'http://example.com/i/img1.jpg',
text: 'related link text 1'
}, {
link: 'http://example.com/related/post2',
image_url: 'http://example.com/i/img2.jpg',
text: 'related link text 2'
}]
});
feed.item({});
t.equal(feed.xml(), expectedOutput.menu.trim());
});