-
Notifications
You must be signed in to change notification settings - Fork 27
/
yourei_search.js
178 lines (153 loc) · 5.59 KB
/
yourei_search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
const reload = require('require-reload')(require);
const request = require('request-promise');
const cheerio = require('cheerio');
const { Navigation, NavigationChapter } = require('monochrome-bot');
const constants = reload('./constants.js');
const trimEmbed = reload('./util/trim_embed.js');
const { highlight } = reload('./util/sentence_highlighter.js');
const { throwPublicErrorInfo, throwPublicErrorFatal } = reload('./util/errors.js');
const YOUREI_BASE_URL = 'http://yourei.jp';
const SENTENCES_PER_FETCH = 20;
const EXAMPLES_PER_PAGE = 4;
const SENTENCES_EMOTE = '🇸';
const FULLTEXT_EMOTE = '🇫';
const USAGE_EMOTE = '🇺';
function getExampleSentences($) {
return $('#sentence-example-list').find('li').map((idx, item) => {
if (idx === SENTENCES_PER_FETCH) return undefined;
const sentence = $(item)
.children()
.not('.next-sentence-preview')
.find('rt')
.replaceWith('')
.end();
return {
short: sentence.filter('.the-sentence').text(), // The main sentence containing the word
full: sentence.not('.sentence-source-title').text(), // Preceding or following sentences
source: sentence.filter('.sentence-source-title').text(), // From where the sentence is quoted
};
}).toArray();
}
function getExampleSentenceCount($) {
return $('#num-examples').text();
}
function getUsageExamples($) {
return $('#ingrams').find('li').map((idx, item) => $(item).text()).toArray();
}
function getUsageFrequencies($) {
return $('#next-freq-ngrams').find('a').map((idx, item) => $(item).text()).toArray();
}
function getNextPageURI($) {
return encodeURI(`${YOUREI_BASE_URL}${$('#sentence-next-pagenation-link').attr('href')}`);
}
async function scrapeWebPage(keyword) {
const targetURI = encodeURI(`${YOUREI_BASE_URL}/${keyword}`);
const options = {
uri: targetURI,
transform: body => cheerio.load(body),
};
return request(options)
.then($ => ({
data: {
sentences: getExampleSentences($),
usageFrequencies: getUsageFrequencies($),
usageExamples: getUsageExamples($),
},
meta: {
count: getExampleSentenceCount($),
keyword,
},
links: {
next: getNextPageURI($),
self: targetURI,
},
}))
.catch(error => throwPublicErrorFatal(
'用例.jp',
'Sorry, yourei.jp isn\'t responding. Please try again later.',
'Error fetching from yourei.jp',
error,
));
}
function formatSentenceData(sentences, keyword, showFullSentences = false) {
return sentences.map((sentence) => {
const highlighted = highlight(
showFullSentences ? sentence.full : sentence.short,
showFullSentences ? sentence.short : keyword,
);
return {
name: highlighted,
value: `-- ${sentence.source}`,
inline: false,
};
});
}
function createNavigationChapterForSentences(scrapeResult, authorName, showFullSentences) {
const pages = [];
const {
data: { sentences },
meta: { count, keyword },
links: { self, next },
} = scrapeResult;
const fields = formatSentenceData(sentences, keyword, showFullSentences).reverse();
let pageNumber = 1;
const pageCount = Math.ceil(sentences.length / EXAMPLES_PER_PAGE);
while (fields.length !== 0) {
const embed = {
title: `${keyword} - 用例.jp Search Results ${showFullSentences ? '(whole context)' : ''} (page ${pageNumber} of ${pageCount})`,
description: `Showing ${sentences.length} from ${count} sentences found. Visit [用例.jp](${next}) to see more sentences.`,
url: self,
fields: [],
color: constants.EMBED_NEUTRAL_COLOR,
footer: {
icon_url: constants.FOOTER_ICON_URI,
text: `${authorName} can use the reaction buttons below to see more information!`,
},
};
for (let i = 0; i < EXAMPLES_PER_PAGE; i += 1) {
embed.fields.push(fields.pop());
}
pages.push(trimEmbed({ embed }));
pageNumber += 1;
}
return NavigationChapter.fromContent(pages);
}
function createNavigationChapterForUsage(scrapeResult, authorName) {
const { meta: { keyword } } = scrapeResult;
const frequencyField = {
name: 'Most frequent usage:',
value: scrapeResult.data.usageFrequencies.join('\n'),
inline: false,
};
const usageExampleField = {
name: 'Usage examples:',
value: scrapeResult.data.usageExamples.join('・'),
inline: false,
};
const embed = {
title: `${keyword} - 用例.jp Search Results`,
url: scrapeResult.links.self,
color: constants.EMBED_NEUTRAL_COLOR,
fields: [frequencyField, usageExampleField],
footer: {
icon_url: constants.FOOTER_ICON_URI,
text: `${authorName} can use the reaction buttons below to see more information!`,
},
};
return NavigationChapter.fromContent([trimEmbed({ embed })]);
}
async function createNavigationForExamples(authorName, authorId, keyword, msg, navigationManager) {
const searchResults = await scrapeWebPage(keyword);
if (searchResults.data.sentences.length === 0) {
return throwPublicErrorInfo('用例.jp', `I didn't find any results for **${keyword}**.`, 'No results');
}
const chapters = {};
chapters[SENTENCES_EMOTE] = createNavigationChapterForSentences(searchResults, authorName, false);
chapters[FULLTEXT_EMOTE] = createNavigationChapterForSentences(searchResults, authorName, true);
chapters[USAGE_EMOTE] = createNavigationChapterForUsage(searchResults, authorName);
const navigation = new Navigation(authorId, true, SENTENCES_EMOTE, chapters);
return navigationManager.show(navigation, constants.NAVIGATION_EXPIRATION_TIME, msg.channel, msg);
}
module.exports = {
createNavigationForExamples,
};