Skip to content

Commit

Permalink
1.1.1: Push for Seasons, refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
savely-krasovsky committed May 15, 2017
1 parent 7fbe931 commit 0cfd1e8
Showing 1 changed file with 133 additions and 75 deletions.
208 changes: 133 additions & 75 deletions push.js
Original file line number Diff line number Diff line change
@@ -1,90 +1,133 @@
/**
* Created by savely on 12.05.2017.
*/
const stream = require('stream');
const FeedParser = require('feedparser');

function hashCode(str){
let hash = 0;
if (str.length === 0) return hash;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}

module.exports = function () {
function fetch() {
const feedparser = new FeedParser();

// Загружаем RSS-файл
console.log('RSS downloading started...');
request
.get('http://retre.org/rssdd.xml')
.on('error', function(err) {
console.warn(err)
})
.pipe(feedparser);

// На всякий случай обрабатываем возможную ошибку парсинга
feedparser.on('error', function (error) {
console.warn(error.message);
});

// После парсинга RSS отобразим сообщение в лог
feedparser.on('end', function () {
console.log('RSS successfully parsed!');
});

// Читаем RSS блоками сверху вниз
feedparser.on('readable', function () {
let item;
while (item = feedparser.read()) {
if (item.categories[0] === '[MP4]') {
// Создаем временную переменную, потому что item может успеть
// сменится за время асинхронного запроса в базу данных
const temp = item;

// Используя регулярки сохраняем из RSS название на английском,
// а также номер сезона и серии
const title = /\((.+)\)\./.exec(temp.title)[1];
const num = /\(S(\d+)E(\d+)\)/.exec(temp.title);

// Делаем запрос в базу с фильтром по названию,
// чтобы узнать ID фильма. Узкое место:
// Мы предполагаем, что фильм с таким название только ОДИН
r.db('lostfilm').table('serials')
.filter({'title_orig': title})

.then(function (res) {
// Если пусто -- ничего не делаем.
// Скорее всего нужно обновить базу фильмов
if (res !== null) {
const series = {
title: title,
season: parseInt(num[1]),
episode: parseInt(num[2]),
id: res[0].id,
date: temp.date
};

return r.db('lostfilm').table('feed')
.insert(series);
const options = {
url: 'http://retre.org/rssdd.xml',
encoding: null
};

request.get(options)
.then(function (buffer) {
// Ответ возвращается нам сразу буфером, но...
const feed = new stream.PassThrough();
feed.end(buffer);

// feedparser требует Stream, так что стримим ему
feed.pipe(feedparser);

// Возвращаем промайз
return new Promise(function (resolve, reject) {
// На всякий случай обрабатываем возможную ошибку парсинга
feedparser.on('error', function (error) {
reject(error)
});

// После парсинга RSS отобразим сообщение в лог
feedparser.on('end', function () {
resolve('RSS successfully parsed!');
});

// Читаем RSS блоками сверху вниз
feedparser.on('readable', function () {
let item;
while (item = feedparser.read()) {
if (item.categories[0] === '[MP4]') {
// Создаем временную переменную, потому что item может успеть
// сменится за время асинхронного запроса в базу данных
const temp = item;

// Используя регулярки сохраняем из RSS название на английском,
// а также номер сезона и серии
const title = /\((.+)\)\./.exec(temp.title)[1];
const num = /\(S(\d+)E(\d+)\)/.exec(temp.title);

// Делаем запрос в базу с фильтром по названию,
// чтобы узнать ID фильма. Узкое место:
// Мы предполагаем, что фильм с таким название только ОДИН
r.db('lostfilm').table('serials')
.filter({'title_orig': title})

.then(function (res) {
// Если пусто -- ничего не делаем.
// Скорее всего нужно обновить базу фильмов
if (res !== null) {
let series = {};

if (parseInt(num[2]) !== 99)
series = {
title: title,
season: parseInt(num[1]),
episode: parseInt(num[2]),
id: res[0].id,
date: temp.date
};
else
series = {
title: title,
season: parseInt(num[1]),
episode: parseInt(num[2]),
id: res[0].id,
// Создаем фиктивную дату из хэша например Lost1016
date: new Date(hashCode(title + res[0].id + parseInt(num[1])))
};

return r.db('lostfilm').table('feed')
.insert(series);
}
})

.then(function (res) {
if (/Duplicate primary key/.exec(res.first_error))
console.log('Nothing new!');
else
console.log('New!');
})

.catch(function (error) {
reject(error);
});
}
})
}
});
});
})

.then(function (res) {
if (/Duplicate primary key/.exec(res.first_error))
console.log('Nothing new!');
else
console.log(series);
})
.then(function (res) {
console.log(res);
})

.catch(function (error) {
console.warn(error.message);
});
}
}
});
.catch(function (error) {
console.warn(error.message);
});
}

setInterval(fetch, 1000 * 60 * 3);

r.db('lostfilm').table('feed').changes()
.then(function (cursor) {
cursor.each(function(err, row) {
if (err) console.warn(err);
console.log(row);
if (err) reject(err);

if (row.new_val !== null) {
const id = row.new_val.id;
Expand All @@ -96,25 +139,40 @@ module.exports = function () {
})

.then(async function (res) {
for (let i in res) {
if (res.hasOwnProperty(i)) {
const serial = R.find(R.propEq('id', id))(res[i].favorites);
const text = '<b>' + serial.title + '</b>\n' +
'Вышла ' + row.new_val.episode + ' серия ' + row.new_val.season + ' сезона.\n' +
'Загрузить: /dl_' + id + '_' + row.new_val.season + '_' + row.new_val.episode;
console.log(await bot.sendMessage(res[i].id, text, parse_html));
res = {
users: res,
new: row.new_val,
serial: id
};

console.log(res);
for (let i in res.users) {
if (res.users.hasOwnProperty(i)) {
const serial = R.find(R.propEq('id', res.serial))(res.users[i].favorites);

let text = '';
if (res.new.episode !== 99)
text = '<b>' + serial.title + '</b>\n' +
'Вышла ' + res.new.episode + ' серия ' + res.new.season + ' сезона.\n' +
'Загрузить: /dl_' + res.serial + '_' + res.new.season + '_' + res.new.episode;
else
text = '<b>' + serial.title + '</b>\n' +
'Полностью вышел ' + res.new.season + ' сезон.\n' +
'Загрузить: /dl_' + res.serial + '_' + res.new.season;

console.log(await bot.sendMessage(res.users[i].id, text, parse_html));
}
}
})

.catch(function (error) {
console.warn(error.message);
});
throw new Error(error);
})
}
});
})

.catch(function (error) {
console.warn(error);
console.warn(error.message);
});
};

0 comments on commit 0cfd1e8

Please sign in to comment.