-
Notifications
You must be signed in to change notification settings - Fork 456
/
index.js
277 lines (259 loc) · 11.6 KB
/
index.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
/**
* Author: Ruo
* Create: 2018-08-20
* Description: 我的关注 视频自动推送 功能
*/
import _ from 'lodash';
import {Feature} from 'Libs/feature';
import {getURL, __, toDuration, createNotification, fetchFromHelper} from 'Utils';
import apis from './apis';
export {DynamicCheckUI} from './UI/index.js';
const MAX_LIST_NUMBERS = 50;
export class DynamicCheck extends Feature {
constructor() {
super({
name: 'dynamicCheck',
kind: 'popup',
permissions: ['login', 'notifications'],
settings: { // 指该feature的配置
on: true, // 指feature是否执行launch function
title: __('dynamicCheck_name'), // 在option页面中配置项目的显示名称
type: 'checkbox', // 指该feature配置子选项的类型,此处为复选框
description: __('dynamicCheck_description'),
hasUI: true,
options: [ // 子选项
{
title: __('dynamicCheck_options_notification'),
key: 'notification',
on: false,
},
{
title: __('dynamicCheck_options_bvToggle'),
key: 'bvToggle',
on: true,
},
{
title: __('dynamicCheck_options_dynamicCheckBox'),
key: 'dynamicCheckBox',
on: true,
description: __('dynamicCheck_options_dynamicCheckBox_description', [MAX_LIST_NUMBERS]),
},
],
subPage: {
type: 'checkbox',
title: __('dynamicCheck_subPage_title'),
description: __('dynamicCheck_subPage_description'),
options: [
{key: 'video', title: __('dynamicCheck_subPage_options_video'), on: true, value: 8},
{key: 'smallVideo', title: __('dynamicCheck_subPage_options_smallVideo'), on: false, value: 16},
{key: 'cv', title: __('dynamicCheck_subPage_options_cv'), on: false, value: 64},
{key: 'bangumi', title: __('dynamicCheck_subPage_options_bangumi'), on: false, value: 512},
],
},
},
});
this.hasLaunched = false;
}
get userId() {
return new Promise((resolve, reject) => {
chrome.cookies.get({
url: 'http://www.bilibili.com/',
name: 'DedeUserID',
}, (cookie) => {
if (cookie && cookie.expirationDate > (new Date()).getTime() / 1000) {
resolve(cookie.value);
} else {
reject();
}
});
});
}
get typeList() {
const options = this.settings.subPage.options;
const typeList = _.compact(options.map((option) => option.on ? option.value : null));
return typeList;
}
launch = () => {
this.currentList = [];
this.lastList = [];
this.lastCounter = 0;
this.lastCheckDynamicID = undefined;
this.lastDynamicID = this.store;
chrome.alarms.create('dynamicCheck', {periodInMinutes: 1});
this.initCurrentList();
this.hasLaunched = true;
};
pause = () => {
this.currentList = [];
this.oldList = [];
this.lastList = [];
this.lastCounter = 0;
this.lastCheckDynamicID = undefined;
chrome.alarms.clear('dynamicCheck');
this.hasLaunched = false;
};
addListener = () => {
chrome.alarms.onAlarm.addListener((alarm) => {
switch (alarm.name) {
case 'dynamicCheck':
this.lastCheckDynamicID && this.checkNew();
break;
}
return true;
});
chrome.notifications.onButtonClicked.addListener((notificationId, index) => {
if (this.currentList[notificationId] && index === 0) {
chrome.notifications.clear(notificationId);
chrome.tabs.create({url: this.currentList[notificationId]});
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.command === 'getDynamicList') {
sendResponse({feedList: this.currentList, lastCounter: this.lastCounter});
} else if (message.command === 'updateLastDynamicId') {
if (this.lastList.length > 0) {
this.store = this.lastList[0].desc.dynamic_id_str;
this.lastCheckDynamicID = this.store;
this.oldList = this.lastList.concat(this.oldList).slice(0, MAX_LIST_NUMBERS);
this.lastList = [];
this.lastCounter = 0;
}
}
return true;
});
};
permissionHandleLogin = (value) => {
if (value) {
!this.hasLaunched && this.launch();
} else {
this.pause();
}
};
initCurrentList() {
if (this.typeList.length === 0) {
return;
}
this.getFeed(this.typeList).then(({code, data, message}) => {
if (code === 0) {
const newList = data.cards.slice(0, MAX_LIST_NUMBERS);
this.currentList = _.map(newList, (card) => {
try {
card.card = typeof card.card === 'string' ? JSON.parse(card.card) : card.card;
if (card.card.duration) {
card.card.duration = toDuration(card.card.duration);
}
return card;
} catch (e) {
console.warn(e);
}
});
this.oldList = this.currentList.slice(0);
if (this.currentList.length > 0) {
if (!this.store) {
this.lastCheckDynamicID = this.currentList[0].desc.dynamic_id_str;
this.store = this.lastCheckDynamicID;
} else {
this.lastCheckDynamicID = this.store;
this.checkNew();
}
}
} else {
console.warn(message);
}
});
}
// 检查未读推送
checkNew = () => {
this.userId.then((userId) => {
if (this.typeList.length === 0) {
return new Promise.reject(false);
}
const dynamic_id = this.lastCheckDynamicID ? `&update_num_dy_id=${this.lastCheckDynamicID}` : '';
return fetchFromHelper(`${apis.dynamic_num}?uid=${userId}&type_list=${this.typeList.join(',')}${dynamic_id}&requestFrom=bilibili-helper1.2.31`)
.then(response => response.json())
.then(({code, data: {new_num, update_num}, message}) => {
if (code !== 0) {
return Promise.reject(message);
} else {
return new_num || update_num;
}
})
.then((new_num) => {
if (!new_num) {
return;
}
this.getFeed(this.typeList).then(({code, data, message}) => {
if (code !== 0) {
return console.warn(message);
}
// 处理刚获取到的推送列表
const newList = _.compact(data.cards.slice(0, new_num).map((card) => {
try {
// 过滤重复项目
const sameCard = this.currentList.find((last) => this.isSameCard(last, card));
if (sameCard) {
return;
}
card.card = typeof card.card === 'string' ? JSON.parse(card.card) : card.card;
if (card.card.duration) {
card.card.duration = toDuration(card.card.duration);
}
return card;
} catch (e) {
console.warn(e);
}
}));
if (newList.length > 0) { // 如果新的推送列表不为空
this.lastCheckDynamicID = newList[0].desc.dynamic_id_str; // 记录新推送列表第一项的id为offset
this.lastList = newList.concat(this.lastList); // 更新最近推送列表,连接到上一次的列表上,
this.currentList = this.lastList.concat(this.oldList).slice(0, MAX_LIST_NUMBERS); // 更新用于显示在菜单的推送列表
this.lastCounter += new_num;
chrome.browserAction.setBadgeText({text: String(this.lastCounter)}); // 设置扩展菜单按钮上的Badge\( ̄︶ ̄)/
this.sendNotification(newList);
}
});
});
});
};
isSameCard = (lastCard, newCard) => lastCard.desc.dynamic_id_str === newCard.desc.dynamic_id_str;
// 处理推送数据 - 不缓存到本地( ̄. ̄)
getFeed = (typeList, offsetID) => {
return this.userId.then((userId) => {
const url = offsetID ? `${apis.dynamic_history}?uid=${userId}&type_list=${this.typeList}&offset_dynamic_id=${offsetID}` : `${apis.dynamic_new}?uid=${userId}&type_list=${typeList}&requestFrom=bilibili-helper1.2.31`;
return fetchFromHelper(url).then(response => response.json());
});
};
createLinkByType = (type, data) => {
switch (type) {
case 8:
return 'https://www.bilibili.com/video/av' + data.stat.aid;
case 16:
return 'https://vc.bilibili.com/video/' + data.item.id;
case 64:
return 'https://www.bilibili.com/read/cv' + data.id;
case 512:
return data.url;
}
};
// 弹出推送通知窗口
sendNotification = (newFeedList) => {
const notificationState = _.find(this.settings.options, {key: 'notification'});
const notifyList = newFeedList.slice(0, 3); // 由于目前会累积没查看的推送,一段时候没查后会累积很多,导致集中推送,故改为只推最近三条
notificationState && notificationState.on && _.map(notifyList, ({card, desc}) => {
const cardData = card;
const picture = cardData.pic || (cardData.item && cardData.item.cover.default) || cardData.banner_url || cardData.cover;
const name = (cardData.owner && cardData.owner.name) || (cardData.user && cardData.user.name) || (cardData.author && cardData.author.name);
const topic = cardData.title || (cardData.item && cardData.item.description) || cardData.new_desc || '';
const link = this.createLinkByType(desc.type, cardData);
createNotification('bilibili-helper-dynamic-check' + Math.random(), {
type: 'basic',
iconUrl: picture || getURL('/statics/imgs/cat.svg'),
title: __('extensionNotificationTitle'),
message: `${name ? name + ': ' : ''}${topic}`,
buttons: [{title: __('extensionNotificationWatch')}],
}, (notificationId) => {
this.currentList[notificationId] = link;
});
});
};
};