-
Notifications
You must be signed in to change notification settings - Fork 5
/
database.js
121 lines (94 loc) · 2.52 KB
/
database.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
// Imports
var http = require('http');
var difflib = require('difflib');
var jsdom = require('jsdom');
// 'Class' Imports
var Card = require('./card.js');
// Define Export
var exports = module.exports = {};
// Constants
const URL = "yugioh.wikia.com";
const SEARCH = "/api/v1/Search/List?query=";
const SEARCH_LIMIT = "&limit=";
const IGNORE_REGEX = /(\((.*?)\)|^Card (.*?):|List of)/i
const MATCH_RATIO = 0.8;
// Private methods
function request(path, callback) {
var options = {
host: URL,
port: 80,
path: path,
};
http.get(options, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
}).on('end', function() {
callback(body);
}).on('error', function (err) {
console.log("Error: " + err.message);
});
});
}
function search(name, limit, callback) {
request(SEARCH + encodeURIComponent(name) + SEARCH_LIMIT + encodeURIComponent(limit), function(res) {
var data = JSON.parse(res);
var sequenceMatcher = new difflib.SequenceMatcher(null, "", "");
sequenceMatcher.setSeq2(name.toLowerCase());
if(!data.items) {
return;
}
data.items.some(function(item) {
if(IGNORE_REGEX.test(item.title)) {
if (global.config.debug) {
console.log("Failed test: " + name + " --> " + item.title);
}
return false;
}
sequenceMatcher.setSeq1(item.title.toLowerCase());
if (sequenceMatcher.ratio() < MATCH_RATIO) {
if (global.config.debug) {
console.log("Failed match: " + name + " --> " + item.title);
}
return false;
}
callback(item);
return true;
});
});
}
function parseCardData(url, callback) {
var card = new Card();
jsdom.env(
url,
['http://code.jquery.com/jquery.js'],
function(err, window) {
if (err) {
console.log(err.message);
return;
}
var $ = window.$;
var table = $('.cardtable');
if (!table.length) {
if (global.config.debug) {
console.log("No cardtable found for page: " + url);
}
return;
}
table.find('.cardtablerow').each(function() {
var row = $(this);
card.parse(row.find('.cardtablerowheader').html(), row.find('.cardtablerowdata').html());
});
card.parse("text", table.find('.navbox-list').first().html().replace("<br>", "\n").trim());
card.set("image", table.find('.cardtable-cardimage').find('img').attr('src'));
callback(card);
}
);
}
// Public methods
exports.lookup = function (name, callback) {
search(name, 5, function(data) {
parseCardData(data.url, callback);
});
}