main.ts 9.85 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*******************************************************************************
 * Copyright 2003-2018 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 * contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 *
 * This file is part of CubicWeb.
 *
 * CubicWeb is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * CubicWeb is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

21
22
23
24
import {
  NO_DATA,
  MIME,
  Tag,
Laurent Wouters's avatar
Laurent Wouters committed
25
  DataSourceLinked,
26
  TabData,
Laurent Wouters's avatar
Laurent Wouters committed
27
28
  DataSourcePage,
  Link,
29
  DataSource,
30
31
  tryNegotiateData,
  MimeInfo
32
} from "../common/api";
Laurent Wouters's avatar
Laurent Wouters committed
33
/// <reference path="./register.d.ts"/>
34
35
36
37
38
39
40
41
42
43
44
45
46
47
let F = require("./register");
import "chrome";

/**
 * The data about the tabs
 */
let allTabs: { [index: number]: TabData } = {};

/**
 * Gets the data about a tab
 * @param id The identifier of a tab
 */
function getTabData(id: number): TabData {
  if (!allTabs.hasOwnProperty(id)) {
Laurent Wouters's avatar
Laurent Wouters committed
48
    allTabs[id] = new TabData();
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
  }
  return allTabs[id];
}

/**
 * Updates a tab
 * @param id The identifier of a tab
 */
function updateTab(tabId: number): void {
  updateIcon(tabId);
  chrome.tabs.sendMessage(tabId, getTabData(tabId));
}

/**
 * Updates the icon of a tab
 * @param id The identifier of a tab
 */
function updateIcon(tabId: number): void {
  let data = getTabData(tabId);
  chrome.browserAction.setIcon({
    path: data.isActive
      ? {
          48: "icons/app.png"
        }
      : {
          48: "icons/app_disabled.png"
        },
    tabId: tabId
  });
  chrome.browserAction.setBadgeBackgroundColor({
    color: [217, 0, 0, 255],
    tabId: tabId
  });
  chrome.browserAction.setBadgeText({
Laurent Wouters's avatar
Laurent Wouters committed
83
    text: data.mainSource.name,
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
    tabId: tabId
  });
}

/**
 * Toggle the activation state of a tab
 * @param tab The activated tab
 */
function toggleActive(tab: chrome.tabs.Tab): void {
  let data = getTabData(tab.id);
  data.isActive = !data.isActive;
  updateTab(tab.id);
}

/**
 * Listen for the activation/de-activation actions
 */
chrome.browserAction.onClicked.addListener(toggleActive);

/**
 * When a tab has been activated
 * @param tabId The identifier of a tab
 */
function onTabActivated(tabId: number): void {
  updateIcon(tabId);
}

// listen to tab URL changes
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  onTabActivated(tabId);
});
// listen to tab switching
chrome.tabs.onActivated.addListener(function(activeInfo) {
  onTabActivated(activeInfo.tabId);
});

/**
 * Parses the tags for a link
 * @param content The link description
 */
function parseLinkTags(content: string): Tag[] {
  let tags: Tag[] = [];
  let regexp = RegExp("([a-zA-Z_0-9]+)\\s*=\\s*('[^']*'|\"[^\"]*\")", "g");
  let match;
  while ((match = regexp.exec(content)) !== null) {
    tags.push({
      name: match[1],
      value: match[2].substring(1, match[2].length - 1)
    });
  }
  return tags;
}

/**
 * Parses the content of a link header
 * @param content The content to parse
 */
function parseLinks(content: string): Link[] {
  let links: Link[] = [];
  let regexp = RegExp(
    "<([^>]*)>(?:\\s*;\\s*([a-zA-Z_0-9]+)\\s*=\\s*('[^']*'|\"[^\"]*\"))*",
    "g"
  );
  let match;
  while ((match = regexp.exec(content)) !== null) {
149
150
    let tags = parseLinkTags(match[0]);
    let link = new Link(match[1], tags);
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    links.push(link);
  }
  return links;
}

/**
 * Get the value of a header
 * @param headers The headers
 * @param name The name of a header
 */
function getHeader(
  headers: chrome.webRequest.HttpHeader[],
  name: string
): string {
  for (var i = 0; i != headers.length; i++) {
    if (headers[i].name == name) {
      return headers[i].value;
    }
  }
  return null;
}

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
 * Set the value of a header
 * @param headers The headers
 * @param name The name of a header
 * @param value The value for the header
 */
function setHeader(
  headers: chrome.webRequest.HttpHeader[],
  name: string,
  value: string
): void {
  for (var i = 0; i != headers.length; i++) {
    if (headers[i].name == name) {
      headers[i].value = value;
    }
  }
  headers.push({ name: name, value: value });
}

192
/**
193
194
 * Gets all the links in the headers
 * @param headers The headers
195
 */
196
function getAllLinks(headers: chrome.webRequest.HttpHeader[]): Link[] {
197
  let linksContent = getHeader(headers, "Link");
Laurent Wouters's avatar
Laurent Wouters committed
198
  if (linksContent == null) return [];
199
200
201
202
203
204
205
206
  return parseLinks(linksContent);
}

/**
 * Detects the primary topic in the links
 * @param links The links in the header
 */
function detectTopicOnlinks(links: Link[]): string {
Laurent Wouters's avatar
Laurent Wouters committed
207
  return links
208
209
210
211
212
213
214
215
216
217
218
219
    .filter((link: Link) => link.refersToPrimaryTopic())
    .reduce((acc: string, link: Link) => (acc != null ? acc : link.url), null);
}

/**
 * Detects linked data in HTTP headers
 * @param links The links in the header
 */
function detectDataOnLinks(links: Link[]): DataSourceLinked[] {
  return links
    .filter((link: Link) => link.refersToData())
    .map((link: Link) => new DataSourceLinked(link));
220
221
222
223
}

/**
 * Detects linked data in page content
224
 * @param details The details
225
226
227
 * @param headers The HTTP headers
 */
function detectDataOnContent(
228
  details: chrome.webRequest.WebResponseHeadersDetails,
229
  headers: chrome.webRequest.HttpHeader[]
Laurent Wouters's avatar
Laurent Wouters committed
230
): DataSource {
231
232
233
  var contentType = getHeader(headers, "Content-Type");
  if (contentType == null) return NO_DATA;
  contentType = contentType.split(";")[0];
Laurent Wouters's avatar
Laurent Wouters committed
234
235
236
  return MIME.hasOwnProperty(contentType)
    ? new DataSourcePage(details.url, contentType)
    : NO_DATA;
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
/**
 * Gets whether based on the specified details a request's content should be pre-empted
 * @param details The details of an incoming request
 */
function shouldPreempt(
  details: chrome.webRequest.WebResponseHeadersDetails
): MimeInfo {
  let contentType = getHeader(details.responseHeaders, "Content-Type");
  contentType = contentType != null ? contentType.split(";")[0] : null;
  let mimes = Object.keys(MIME).map((key: string) => MIME[key]);
  for (var i = 0; i != mimes.length; i++) {
    if (
      mimes[i].mime == contentType ||
      details.url.endsWith(mimes[i].fileExtension)
    ) {
      return mimes[i];
    }
  }
  return null;
}

/**
 * Preempts the content of a request
 * @param details The details of an incoming request
 * @param mime The catpured MIME type
 */
function doPreempt(
  details: chrome.webRequest.WebResponseHeadersDetails,
  mime: MimeInfo
): chrome.webRequest.BlockingResponse {
  let headers = details.responseHeaders;
  setHeader(headers, "Content-Type", "text/plain");
  let data = getTabData(details.tabId);
  data.sources.push(new DataSourcePage(details.url, mime.mime));
  data.isActive = true; // activate by default
  data.selectMain();
  return { responseHeaders: headers };
}

278
279
280
281
282
283
/**
 * When headers are received for a tab
 * @param details The details
 */
function onHeadersReceived(
  details: chrome.webRequest.WebResponseHeadersDetails
284
): chrome.webRequest.BlockingResponse {
285
286
287
288
289
290
291
  if (
    details.tabId == -1 || // invalid tab
    details.frameId != 0 || // not the main top-level frame
    details.hasOwnProperty("initiator") || // requested initiated by something else
    (details.hasOwnProperty("originUrl") &&
      (details as any).originUrl != details.url) // not the original URL
  )
292
    return {};
293
  let data = getTabData(details.tabId);
Laurent Wouters's avatar
Laurent Wouters committed
294
  if (data.mainSource != NO_DATA)
295
    // already detected something
296
    return {};
Laurent Wouters's avatar
Laurent Wouters committed
297

298
299
300
301
  // try to detect the primary topic in HTTP headers' links
  let links = getAllLinks(details.responseHeaders);
  data.primaryTopic = detectTopicOnlinks(links);
  // determine if we shall preempt the content due to its type (raw RDF data)
302
303
304
305
306
  let mime = shouldPreempt(details);
  if (mime != null) {
    // preempts this request
    return doPreempt(details, mime);
  }
307
  // try to detect alternate sources of content
Laurent Wouters's avatar
Laurent Wouters committed
308
  data.sources.push(detectDataOnContent(details, details.responseHeaders));
309
  data.sources = data.sources.concat(detectDataOnLinks(links));
Laurent Wouters's avatar
Laurent Wouters committed
310
  data.selectMain();
311
  // if there are still nothing, try to probe with HTTP content negotiation
312
313
314
315
316
317
318
319
320
321
322
  if (data.mainSource == NO_DATA) {
    tryNegotiateData(details.url)
      .then((source: DataSourceLinked) => {
        data.sources.push(source);
        data.selectMain();
        updateTab(details.tabId);
      })
      .catch((reason: string) => {
        // do nothing
      });
  }
323
  updateIcon(details.tabId);
324
  return {};
325
326
327
328
329
330
331
332
333
334
}

/**
 * Event before a tab navigation occur
 * @param details The event details
 */
function onBeforeNavigate(
  details: chrome.webNavigation.WebNavigationFramedCallbackDetails
): void {
  if (details.tabId == -1 || details.frameId != 0) return;
Laurent Wouters's avatar
Laurent Wouters committed
335
  getTabData(details.tabId).clear();
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
  updateIcon(details.tabId);
}

/**
 * Event after tab navigation occurred
 * @param details the event details
 */
function onCompleted(
  details: chrome.webNavigation.WebNavigationFramedCallbackDetails
): void {
  if (details.tabId == -1 || details.frameId != 0) return;
  updateTab(details.tabId);
}

// listen to received headers
chrome.webRequest.onHeadersReceived.addListener(
  onHeadersReceived,
  { urls: ["<all_urls>"] },
354
  ["blocking", "responseHeaders"]
355
356
357
358
359
360
361
);
// listen to navigation
F.registerNavigations(onBeforeNavigate, onCompleted);

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  let data = getTabData(sender.tab.id);
  if (request.reqType == "links") {
362
363
364
365
    if (data.primaryTopic == null) {
      data.primaryTopic = detectTopicOnlinks(request.links);
    }
    data.sources = data.sources.concat(detectDataOnLinks(request.links));
Laurent Wouters's avatar
Laurent Wouters committed
366
    data.selectMain();
367
    updateTab(sender.tab.id);
368
369
  }
});