-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
317 lines (295 loc) · 7.65 KB
/
main.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
const matcher = {
https: 'https(.*?)"',
dictionary: "{(.*?)}",
tuple: "((.*?))",
array: "[(.*?)]",
src: ' src="(.*?)" ',
video: "<iframe*(.*?) src='*(.*?)' ",
custom: (_r) => _r,
};
function regexIno(content, pattern = new RegExp(matcher.dictionary, "g")) {
let match;
const matchArr = [];
while ((match = pattern.exec(content))) {
match = match[1]?.trim();
if (match) matchArr.push(match);
}
return matchArr;
}
//get all post each categories
function urlJsonSearchPostsCategories({
category = "",
postId = "",
query = "",
blogUrl,
blogId,
}) {
return `${blogUrl ? `${blogUrl}/feeds` : `https://www.blogger.com/feeds/${blogId}`
}/posts/default/${postId}${category ? `-/${category}` : ""
}?alt=json&${query}`;
}
//fet llop
export default class UseBlogger {
blogUrl = ""; // if blogUrl not req blogId
blogId = ""; //if blogId not req blogeUrl
save;
isBrowser = false;
data = [];
category = "";
postId = "";
query = "";
variables = [];
unselected = [];
selected = [];
uncategory = [];
_callback;
constructor(props = {}) {
const { blogId, isBrowser, save, blogUrl = "" } = props;
this.blogId = blogId;
this.isBrowser = isBrowser;
this.save = save;
this.blogUrl = blogUrl;
}
categories(_categories = []) {
this.category = _categories?.join("/") || "";
return this;
}
uncategories(_categories = []) {
this.uncategory = _categories;
return this;
}
labels(_categories = []) {
this.categories(_categories);
return this;
}
unlabels(_categories = []) {
this.uncategories(_categories);
return this;
}
post(postId = "") {
this.postId = postId;
return this;
}
//fn query
search(text = "") {
this.query += `q=${text}&`;
return this;
}
limit(n = 3) {
this.query += `max-results=${n}&`;
return this;
}
select(_select = []) {
this.selected = _select;
}
unselect(_select = []) {
this.unselected = _select;
}
skip(n = 1) {
this.query += `start-index=${n}&`;
return this;
}
orderby(value = "published") {
//or updated
this.query += `orderby=${value}&`;
return this;
}
//
callback(cb) {
this._callback = cb;
return this;
}
setData(data) {
this.data = data;
return this;
}
getData() {
return this.data;
}
published(dateMin, dateMax) {
if (dateMin) this.query += `published-min=${dateMin}&`;
if (dateMax) this.query += `published-max=${dateMax}&`;
return this;
}
updated(dateMin, dateMax) {
if (dateMin) this.query += `updated-min=${dateMin}&`;
if (dateMax) this.query += `updated-max=${dateMax}&`;
return this;
}
async load(variables) {
try {
const { category, postId, query, blogUrl, blogId } = this;
if (!this.data?.length) {
const url = urlJsonSearchPostsCategories({
category,
postId,
query,
blogUrl,
blogId,
});
const response = await fetch(url);
if (!response.ok) {
throw new Error("Network response was not ok");
}
if (this.save) this.save(data);
this.data = await response.json();
}
const resault = this.postId
? getPost(this.data?.entry, variables)
: getPosts(this.data, variables);
if (typeof this._callback === "function") {
this._callback(resault);
}
//selected variable
if (this.selected.length) {
resault.data = resault?.data
.filter((obj) =>
this.selected.every((prop) => obj.hasOwnProperty(prop))
)
.map(
(obj) =>
this.selected.reduce((acc, prop) => {
acc[prop] = obj[prop];
return acc;
}, {}) || []
);
}
//unselected variable
//this.unselected.length && resault?.data?.forEach(key => this.unselected[key] && delete resault.data[key]);
if (this.unselected.length) {
resault.data = resault?.data.reduce((acc, obj) => {
const filteredObj = {};
for (const key in obj) {
if (!this.unselected.includes(key)) {
filteredObj[key] = obj[key];
}
}
if (Object.keys(filteredObj).length > 0) {
acc.push(filteredObj);
}
return acc;
}, []);
}
return resault;
} catch (error) {
console.error("There was a problem with the fetch request:", error);
}
}
//clone load
async exec(variables) {
return await this.load(variables);
}
}
function getPost(entry, variables = []) {
const {
id: { $t: _id },
content: { $t: _content },
media$thumbnail, //: thumbnail,//{ url: thumbnail },
published: { $t: published },
updated: { $t: updated },
title: { $t: name },
category,
link,
} = entry;
_content = _content.replace(/ /gi, "");
//get videos array
const _videos = new RegExp(matcher.video, "g").exec(_content) || [];
const videos = _videos[2] || "";
//get image
const images =
regexIno(_content, new RegExp(matcher.src, "g"))?.map((img = "") => img) ||
[];
const content = _content.replace(/(<([^>]+)>)/gi, "");
function getVariable({ key, type = "string", regex }) {
let _res =
regexIno(_content, new RegExp(regex || `${key}*[:=]*(.*?)[;<]`, "g")) ||
[];
if (type === "full") return _res;
let res = _res[0];
if (type === "number")
return res?.match(/\d+(\.\d+)?/g)?.map((_r) => +_r)[0] || 0;
if (type === "array") return res?.split(",")?.filter((_r) => _r !== "");
return res;
}
const vars = [];
variables?.forEach(({ key, type, regex, asArray, as }) => {
const _var = getVariable({ key, type, regex });
const asOrKey = as || key;
if (_var) {
if (asArray) {
vars[asArray] = {
...(vars[asArray] || {}),
[asOrKey]: _var,
};
} else {
vars[asOrKey] = _var;
}
}
});
//
const categories = category?.map((cat) => cat.term) || [];
const thumbnail = media$thumbnail?.url;
const id = _id.split("post-")[1];
const data = {
id,
name,
thumbnail,
published,
videos,
link,
images,
text: content,
html: _content,
categories,
category: categories[0],
updated,
entry,
...vars,
};
if (categories && categories.indexOf("$") !== -1) {
return { $: data };
}
return { data };
}
function getPosts(dataPosts = [], variables) {
const posts = [];
const fnk = [];
dataPosts.feed?.entry?.forEach((entry) => {
const post = getPost(entry, variables);
if (post.$) fnk.push(post.$);
else posts.push(post.data);
});
return { data: posts, $: fnk };
}
/*
const smallStringToNum = (smallStr) => {
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
let result = 0;
let multiplier = 1;
for (let i = smallStr.length - 1; i >= 0; i--) {
const char = smallStr[i];
const digit = alphabet.indexOf(char);
result += digit * multiplier;
multiplier *= 36;
}
return result;
};
const convertNum = (strOrNum) => {
let num;
if (typeof strOrNum === 'number') {
num = strOrNum;
} else if (typeof strOrNum === 'string') {
// Try to convert the string to a number
num = Number(strOrNum);
if (isNaN(num)) {
throw new Error('Input must be a number or a string that can be converted to a number');
}
} else {
throw new Error('Input must be a number or a string');
}
return numToSmallString(num);
};
console.log(convertNum(8277077996046083588)); // Output: "4w5ue5ld5pmc"
console.log(convertNum("4w5ue5ld5pmc")); // Output: 8277077996046083588
console.log(convertNum("8277077996046083588")); // Output: "4w5ue5ld5pmc"
*/