forked from kanghj/wordnews_chrome_extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent-share.js
242 lines (210 loc) · 8.14 KB
/
content-share.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
// Shared functions and configurations for learning and annotation mode
var websiteSettingENUM = {cnn: 1, chinadaily: 2, bbc: 3};
var websiteSettingLookupTable = ['none', 'cnn.com', 'chinadaily.com.cn', 'bbc.co']; //none is just a buffer
var userSettings = {
websiteSetting: [],
userId: "",
score: 0,
rank: 0,
learnLanguage: "",
annotationLanguage: ""
};
//This variable stores the result of the current website
//e.g. "cnn.com", "bbc.com"
var website;
//According to https://docs.google.com/spreadsheets/d/1OHxJHR1XdkLxQRxPyvbnf0k9tWe-CHrcsnNbJGKVVT8/edit#gid=0
var rankAccess = {
FREE: 0,
VIEW_MACHINE_TRANSLATION: 1,
TAKE_QUIZ : 2,
VIEW_HUMAN_ANNOTATION: 3 ,
VOTE_TRANSLATIONS: 4,
INPUT_OWN_TRANSLATION: 5
};
var eventLogger = {};
if (typeof chrome != 'undefined') {
console.log('Chrome, initializating with chrome storage.');
//Send message to background to notify new page
chrome.runtime.sendMessage(
{ type: "new_page", currentURL: window.location.href },
function(response) {
//Respone will be a copy of user settings
//Save a local copy of the user settings in content-share.js
for (var key in response) {
userSettings[key] = response[key];
}
}
);
} else {
console.log('Not chrome, waiting for manual initialization.');
}
// Common function to
function updateScoreAndRank(score, rank) {
userSettings.score = score;
userSettings.rank = rank;
chrome.runtime.sendMessage(
{ type: "update_score_rank",
score: score,
rank: rank
},
function(response) {
console.log("Score and rank updated");
console.log('Score :' + score + " Rank: " + rank)
}
);
}
const USER_RANK_INSUFFICIENT = -1;
const USER_NOT_LOGGED_IN = -2
const USER_HAS_ACCESS = 0;
function checkRankAndLogin(requiredRank) {
var NOT_LOGIN = false;
//TODO: How to even check is it login?
if (requiredRank > userSettings.rank) {
console.log('rank in setting ' + userSettings.rank)
return USER_RANK_INSUFFICIENT;
} else if (userSettings.rank >= 4 && NOT_LOGIN) { //IF not login return, -2 to prompt for login
return USER_NOT_LOGGED_IN;
}
return USER_HAS_ACCESS; //No problem with rank and login
}
function getURLPostfix(url) {
var index = url.search('//');
var noHTTPString = url.substr(index + 2); // this will get the string with http://
index = noHTTPString.search('/');
return noHTTPString.substr(index + 1);
}
function getParagraphs() {
var paragraphs = []
//If website is cnn
if (document.URL.indexOf('cnn.com') !== -1) {
paragraphs = $('.zn-body__paragraph').get();
paragraphFormatTag = '.zn-body__paragraph';
website = "cnn";
}
//if website is bbc
else if (document.URL.indexOf('bbc.com') !== -1){
// for most pages like http://www.bbc.com/sport/formula1/37506181
article = document.getElementById('responsive-story-page');
// for pages like http://www.bbc.com/future/story/20161003-would-it-be-ethical-to-implant-false-memories-in-therapy
mainContent = document.getElementsByClassName('primary-content-lining');
if (article!=null) {
paragraphs = article.getElementsByTagName('p');
} else if (mainContent.length>0) {
paragraphs = mainContent[0].getElementsByTagName('p');
} else {
paragraphs = document.getElementsByTagName('p');
}
paragraphFormatTag = 'p';
website = "bbc";
}
else { //TODO: Other webpages could be other tags instead of <p>
paragraphs = document.getElementsByTagName('p');
paragraphFormatTag = 'p';
website = "other";
}
return paragraphs;
}
//Window event to check whether window is focused
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
console.log("Blured");
//Loop through the all the events and add no focus event
for (var key in eventLogCont) {
newEvent(key, "no focus");
}
break;
case "focus": //Update the chrome UI
console.log("Focused")
chrome.runtime.sendMessage(
{type: "active", value: true},
function (response) {
//Respone will be a copy of user settings
//Save a local copy of the user settings in content-share.js
for (var key in response) {
userSettings[key] = response[key];
}
});
break;
}
}
$(this).data("prevType", e.type);
})
chrome.storage.onChanged.addListener( function(changes, namespace){
if (namespace == "sync") {
for (key in changes) {
var storageChange = changes[key];
userSettings[key] = storageChange.newValue;
//console.log('Storage key "%s" in namespace "%s" changed. ' +
// 'Old value was "%s", new value is "%s".',
// key,
// namespace,
// storageChange.oldValue,
// storageChange.newValue);
}
}
})
//This is temporary variable to use for checking the differences of mode and when to reload the page
var currentMode = "disable";
//Listener to handle event messages from background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
// If it is not app settings update
//TODO: refine/improve on this condition/logic
//If request mode is disable or current mode is disable and current mode is different from request mode
if (request.mode == "disable" || ((currentMode != "disable") && (currentMode != request.mode)) ) {
//Need to clear both annotation and learn
//TODO: Need ways to disable the functionality of annotation and learn without restarting
window.location.reload();
}
if (request.mode == "annotate") {
annotationLanguage = request.ann_lang;
//wordDisplay = request.wordDisplay;
//console.log("annotate mode lang:" + annotationLanguage);
beginAnnotation(request.user_id);
}
else if (request.mode == "learn") {
//Set the respective variables
learnLanguage = request.learn_lang;
translationType = request.translationType;
quizType = request.quizType;
wordDisplay = request.wordDisplay;
wordsLearn = request.wordsLearn;
if ( 'action' in request ) {
// there is a user click in one of the social button
if ( request.action == "send_fb_recommend" ) {
fb_send_recommend();
}
}
else {
beginTranslating();
}
}
//Set the mode
currentMode = request.mode;
//TODO: This doesn't makes any sense unless the request only send ann_lang in the parameter
if ('ann_lang' in request) {
annotationLanguage = request.ann_lang;
console.log("update lang to " + annotationLanguage);
}
});
//Common function to call ajax post for /log
function sendLog (data) {
$.ajax({
type: "post",
beforeSend : function (request) {
request.setRequestHeader("Accept", "application/json");
},
url: hostUrl + '/log',
dataType: "json",
data: data,
success: function (result) {
console.log("log successful.", result);
},
error: function (error) {
console.log("log error.");
}
})
}