data.ts 20.1 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/>.
 ******************************************************************************/

Laurent Wouters's avatar
Laurent Wouters committed
21
import { application } from "@logilab/libview";
22

Laurent Wouters's avatar
Laurent Wouters committed
23
24
25
26
/**
 * Metadata about a MIME type
 */
export class MimeInfo {
27
28
29
30
31
32
33
34
35
36
37
38
  constructor(
    mime: string,
    name: string,
    priority: number,
    fileExtension: string
  ) {
    this.mime = mime;
    this.name = name;
    this.priority = priority;
    this.fileExtension = fileExtension;
  }

Laurent Wouters's avatar
Laurent Wouters committed
39
40
41
42
43
44
45
46
47
48
49
50
  /**
   * The MIME type
   */
  mime: string;
  /**
   * The user-readable name
   */
  name: string;
  /**
   * The relative priority of using this MIME type (lower is better)
   */
  priority: number;
51
52
53
54
  /**
   * The associated file extension
   */
  fileExtension: string;
Laurent Wouters's avatar
Laurent Wouters committed
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
}

/**
 * A tag for a link
 */
export class Tag {
  name: string;
  value: string;
}

/**
 * A link for a related resource
 */
export class Link {
  constructor(url: string, tags: Tag[]) {
    this.url = url;
    this.tags = {};
    for (var i = 0; i != tags.length; i++) {
      this.tags[tags[i].name] = tags[i].value;
    }
  }
  /**
   * The link's target
   */
  url: string;
  /**
   * The various tags for this link
   */
  tags: { [tag: string]: string };
84
}
Laurent Wouters's avatar
Laurent Wouters committed
85

86
87
88
89
90
91
92
93
94
95
96
97
/**
 * Determines whether this link is appropriate as a linked data source
 * @param link The link to inspect
 */
export function refersToData(link: Link): boolean {
  return (
    link.tags.hasOwnProperty("rel") &&
    link.tags.hasOwnProperty("type") &&
    link.tags.rel == "alternate" &&
    MIME.hasOwnProperty(link.tags.type)
  );
}
98

99
100
101
102
103
104
/**
 * Determines whether this link refers to the primary topic on a page
 * @param link The link to inspect
 */
export function refersToPrimaryTopic(link: Link): boolean {
  return (
105
106
107
    (link.tags.hasOwnProperty("rev") &&
      "describedBy".toLocaleLowerCase() == link.tags.rev.toLocaleLowerCase()) ||
    (link.tags.hasOwnProperty("rel") && link.tags.rel == "bookmark")
108
  );
Laurent Wouters's avatar
Laurent Wouters committed
109
110
}

Laurent Wouters's avatar
Laurent Wouters committed
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
/**
 * Parses the tags for a link
 * @param content The link description
 */
export 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
 */
export function parseLinks(content: string): Link[] {
  if (content == undefined || content == null) return [];
  let links: Link[] = [];
  let regexp = RegExp(
    "<([^>]*)>(?:\\s*;\\s*([a-zA-Z_0-9]+)\\s*=\\s*('[^']*'|\"[^\"]*\"))*",
    "g"
  );
  let match;
  while ((match = regexp.exec(content)) !== null) {
    let tags = parseLinkTags(match[0]);
    let link = new Link(match[1], tags);
    links.push(link);
  }
  return links;
}

/**
 * Detects the primary topic in the links
 * @param links The links in the header
 */
export function detectTopicOnlinks(links: Link[]): string {
  return links
    .filter((link: Link) => refersToPrimaryTopic(link))
    .reduce((acc: string, link: Link) => (acc != null ? acc : link.url), null);
}

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

/**
 * Finds the relevant links in an HTML document
 * @param document The document to inspect
 * @param url The document URL
 * @param primaryTopic The detected primary topic, if any
 */
export function findLinksInDocument(
  document: HTMLDocument,
  url: string,
  primaryTopic: string
): Link[] {
  let links: Link[] = [];
  let resource = primaryTopic;
  if (resource == null || resource == undefined || resource == "")
    resource = url;

  let elementsLink = document.head.getElementsByTagName("link");
  for (var i = 0; i != elementsLink.length; i++) {
    let element = elementsLink.item(i);
    let rel = element.getAttribute("rel");
    let type = element.type;
    let href = element.href;
    if (rel == "meta") {
      links.push(
        new Link(href, [
          { name: "type", value: type },
          { name: "rel", value: "alternate" }
        ])
      );
    } else if (rel == "bookmark") {
      links.push(new Link(href, [{ name: "rel", value: "bookmark" }]));
    }
  }

  let elementsA = document.body.getElementsByTagName("a");
  for (var i = 0; i != elementsA.length; i++) {
    let element = elementsA.item(i);
    if (element.href == null || element.href == undefined) continue;
    if (!element.href.startsWith(resource)) continue;
    let mimes = Object.keys(MIME).map((key: string) => MIME[key]);
    for (var j = 0; j != mimes.length; j++) {
      if (element.href.endsWith(mimes[j].fileExtension)) {
        links.push(
          new Link(element.href, [
            { name: "type", value: mimes[j].mime },
            { name: "rel", value: "alternate" }
          ])
        );
        break;
      }
    }
  }
  return links;
}

/**
 * A typed raw content
 */
export interface RawContent {
  /**
   * The MIME type
   */
  contentType: string;
  /**
   * The raw content
   */
  content: string;
}

/**
 * Content that can be observed for the detection of linked data
 */
export interface ObservableContent extends RawContent {
  /**
   * The URL of the content
   */
  url: string;
  /**
   * The value for the Link HTTP header
   */
  linkHeader: string;
}

/**
 * Gets some observable content at a target URI
 * @param target The target URI
 */
export function fetchObservableAt(target: string): Promise<ObservableContent> {
  let accept = Object.keys(MIME)
    .map(key => {
      return MIME[key];
    })
    .sort((x: MimeInfo, y: MimeInfo) => {
      return x.priority - y.priority;
    })
    .reduce((acc: string, mime: MimeInfo, index: number) => {
      if (acc.length == 0) return mime.mime;
      return acc + ", " + mime.mime + ";q=" + (1 - 0.1 * index).toString();
    }, "");
  accept += ", text/html;q=0.1";

  return new Promise<ObservableContent>(
    (
      resolve: (result: ObservableContent) => void,
      reject: (reason: any) => void
    ) => {
      let xmlHttp = new XMLHttpRequest();
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
          if (xmlHttp.status < 200 && xmlHttp.status >= 300)
            return reject("HTTP error: " + xmlHttp.status);
          let contentType = xmlHttp.getResponseHeader("Content-Type");
          let index = contentType.indexOf(";");
          if (index > 0) contentType = contentType.substring(0, index);
          resolve({
            contentType: contentType,
            content: xmlHttp.responseText,
            url: target,
            linkHeader: xmlHttp.getResponseHeader("Link")
          });
        }
      };
Laurent Wouters's avatar
Laurent Wouters committed
290
      xmlHttp.open("GET", target, true);
Laurent Wouters's avatar
Laurent Wouters committed
291
292
293
294
295
296
      xmlHttp.setRequestHeader("Accept", accept);
      xmlHttp.send();
    }
  );
}

Laurent Wouters's avatar
Laurent Wouters committed
297
298
299
300
/**
 * Map of known MIME types to badge names
 */
export const MIME: { [mime: string]: MimeInfo } = {
301
302
303
304
305
306
307
308
309
310
311
312
  "text/n3": new MimeInfo("text/n3", "N3", 5, ".n3"),
  "application/n-triples": new MimeInfo(
    "application/n-triples",
    "NT",
    6,
    ".nt"
  ),
  "application/n-quads": new MimeInfo("application/n-quads", "NQ", 7, ".nq"),
  "text/turtle": new MimeInfo("text/turtle", "TTL", 8, ".ttl"),
  "application/trig": new MimeInfo("application/trig", "TRIG", 9, ".trig"),
  "application/rdf+xml": new MimeInfo("application/rdf+xml", "RDF", 10, ".xml"),
  "application/ld+json": new MimeInfo("application/ld+json", "LD", 11, ".json")
Laurent Wouters's avatar
Laurent Wouters committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
};

/**
 * A source of data
 */
export interface DataSource {
  /**
   * A descriptor of the type of source
   */
  sourceType: string;
  /**
   * The human-readable source of this data
   */
  name: string;
  /**
   * The content's url
   */
  url: string;
  /**
   * MIME type for the content
   */
  contentType: string;
  /**
   * The relative priority of this source (lower is better)
   */
  priority: number;
}

/**
 * No data source
 */
export class DataSourceNone implements DataSource {
  constructor() {
    this.sourceType = "DataSourceNone";
347
    this.name = "No data";
Laurent Wouters's avatar
Laurent Wouters committed
348
349
350
351
352
353
354
355
356
357
358
    this.url = "";
    this.contentType = "";
    this.priority = Number.MAX_SAFE_INTEGER;
  }
  sourceType: string;
  name: string;
  url: string;
  contentType: string;
  priority: number;
}

Laurent Wouters's avatar
Laurent Wouters committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
 * A data source with inline content
 */
export class DataSourceInline implements DataSource {
  constructor(url: string, mime: MimeInfo, content: string) {
    this.sourceType = "DataSourceInline";
    this.name = "Inline content";
    this.url = url;
    this.contentType = mime.mime;
    this.priority = mime.priority;
    this.content = content;
  }
  sourceType: string;
  name: string;
  url: string;
  contentType: string;
  priority: number;
  /**
   * The inline content
   */
  content: string;
}

382
383
384
/**
 * The data about a page
 */
Laurent Wouters's avatar
Laurent Wouters committed
385
export class DataSourcePage implements DataSource {
386
  constructor(url: string, contentType: string) {
387
    let mime = MIME[contentType];
Laurent Wouters's avatar
Laurent Wouters committed
388
    this.sourceType = "DataSourcePage";
389
390
391
    this.name =
      "Page's content" +
      (mime != undefined && mime != null ? " (" + mime.name + ")" : "");
392
393
    this.url = url;
    this.contentType = contentType;
Laurent Wouters's avatar
Laurent Wouters committed
394
    this.priority = 1;
395
  }
Laurent Wouters's avatar
Laurent Wouters committed
396
397
  sourceType: string;
  name: string;
398
399
  url: string;
  contentType: string;
Laurent Wouters's avatar
Laurent Wouters committed
400
  priority: number;
401
402
403
404
405
}

/**
 * Get a promise to fetch the content of the current document
 */
Laurent Wouters's avatar
Laurent Wouters committed
406
function doFetchSourcePage(page: DataSourcePage): Promise<RawContent> {
407
  return new Promise(function(resolve, reject) {
408
409
410
411
412
413
414
415
416
417
418
419
420
421
    for (var i = 0; i != document.body.children.length; i++) {
      let child = document.body.children[i];
      if (child.tagName == "PRE") {
        let content = "";
        for (var j = 0; j != child.childNodes.length; j++) {
          content += (child.childNodes[j] as any).wholeText;
        }
        return resolve({
          contentType: page.contentType,
          content: content
        });
      }
    }
    return resolve({
422
      contentType: page.contentType,
423
      content: document.body.innerHTML
424
425
426
427
    });
  });
}

428
429
430
/**
 * A link for a related resource
 */
Laurent Wouters's avatar
Laurent Wouters committed
431
432
433
434
435
436
export class DataSourceLinked implements DataSource {
  constructor(link: Link) {
    let mime = MIME[link.tags.type];
    if (mime == null || mime == undefined) throw "Unrecognized link type";
    this.tags = link.tags;
    this.sourceType = "DataSourceLinked";
437
438
439
440
441
442
    this.name =
      "Linked content" +
      (mime != undefined && mime != null ? " (" + mime.name + ")" : "") +
      " (" +
      link.url +
      ")";
Laurent Wouters's avatar
Laurent Wouters committed
443
444
445
    this.url = link.url;
    this.contentType = mime.mime;
    this.priority = mime.priority;
446
447
448
449
450
  }
  /**
   * The various tags for this link
   */
  tags: { [tag: string]: string };
Laurent Wouters's avatar
Laurent Wouters committed
451
452
453
454
455
  sourceType: string;
  name: string;
  url: string;
  contentType: string;
  priority: number;
456
457
458
459
460
}

/**
 * Get a promise to fetch content at a URI
 */
Laurent Wouters's avatar
Laurent Wouters committed
461
function doFetchSourceLink(link: DataSourceLinked): Promise<RawContent> {
462
463
464
465
  return new Promise(function(resolve, reject) {
    let xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4) {
Laurent Wouters's avatar
Laurent Wouters committed
466
        if (xmlHttp.status < 200 && xmlHttp.status >= 300) {
467
468
469
470
471
472
473
474
475
476
          reject("HTTP error: " + xmlHttp.status);
        }
        let ct = xmlHttp.getResponseHeader("Content-Type");
        resolve({
          contentType: ct,
          content: xmlHttp.responseText
        });
      }
    };
    xmlHttp.open("GET", link.url, true);
Laurent Wouters's avatar
Laurent Wouters committed
477
    xmlHttp.setRequestHeader("Accept", link.contentType);
478
479
    xmlHttp.send();
  });
480
481
482
}

/**
Laurent Wouters's avatar
Laurent Wouters committed
483
 * Fetches this data
484
 */
Laurent Wouters's avatar
Laurent Wouters committed
485
486
487
488
489
export function fetchSource(source: DataSource): Promise<RawContent> {
  if (source == null || source == undefined) {
    return new Promise((resolve, reject) => reject("No data"));
  } else if (source.sourceType == "DataSourceNone") {
    return new Promise((resolve, reject) => reject("No data"));
Laurent Wouters's avatar
Laurent Wouters committed
490
491
492
493
494
  } else if (source.sourceType == "DataSourceInline") {
    let inline = source as DataSourceInline;
    return new Promise((resolve, reject) =>
      resolve({ contentType: inline.contentType, content: inline.content })
    );
Laurent Wouters's avatar
Laurent Wouters committed
495
496
497
498
  } else if (source.sourceType == "DataSourcePage") {
    return doFetchSourcePage(source as DataSourcePage);
  } else if (source.sourceType == "DataSourceLinked") {
    return doFetchSourceLink(source as DataSourceLinked);
499
  }
Laurent Wouters's avatar
Laurent Wouters committed
500
  return new Promise((resolve, reject) => reject("Unknown data source"));
501
502
}

503
/**
Laurent Wouters's avatar
Laurent Wouters committed
504
505
506
 * Compares two data sources
 * @param x The first data source
 * @param y The second data source
507
 */
Laurent Wouters's avatar
Laurent Wouters committed
508
509
function compareSources(x: DataSource, y: DataSource): number {
  return x.priority - y.priority;
510
511
}

512
513
514
/**
 * Constant when no data are available
 */
Laurent Wouters's avatar
Laurent Wouters committed
515
export const NO_DATA = new DataSourceNone();
516

517
/**
Laurent Wouters's avatar
Laurent Wouters committed
518
 * The observed data about a web resource
519
 */
Laurent Wouters's avatar
Laurent Wouters committed
520
export class ResourceObservedData {
521
  constructor() {
Laurent Wouters's avatar
Laurent Wouters committed
522
523
524
    this.url = "";
    this.sources = [];
    this.primaryTopic = "";
525
526
  }
  /**
Laurent Wouters's avatar
Laurent Wouters committed
527
   * The resource's url
528
   */
Laurent Wouters's avatar
Laurent Wouters committed
529
  url: string;
530
  /**
Laurent Wouters's avatar
Laurent Wouters committed
531
   * All the alternative data sources
532
   */
Laurent Wouters's avatar
Laurent Wouters committed
533
  sources: DataSource[];
534
  /**
Laurent Wouters's avatar
Laurent Wouters committed
535
   * The detected primary topic if any
536
   */
Laurent Wouters's avatar
Laurent Wouters committed
537
538
  primaryTopic: string;
}
539

Laurent Wouters's avatar
Laurent Wouters committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/**
 * Observes the content of an observable to get the observed data
 * @param observable An observable
 */
export function observeContent(
  observable: ObservableContent
): ResourceObservedData {
  if (MIME.hasOwnProperty(observable.contentType)) {
    // Linked-data content at this URI
    let links = parseLinks(observable.linkHeader);
    let primary = detectTopicOnlinks(links);
    let source =
      observable.content != null
        ? new DataSourceInline(
            observable.url,
            MIME[observable.contentType],
            observable.content
          )
        : new DataSourceLinked(
            new Link(observable.url, [
              { name: "rel", value: "alternate" },
              { name: "type", value: observable.contentType }
            ])
          );
    let observations: ResourceObservedData = {
565
      primaryTopic: primary == null ? observable.url : primary,
Laurent Wouters's avatar
Laurent Wouters committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
      url: observable.url,
      sources: [source]
    };
    return observations;
  } else {
    // no inline data, inspect the content
    let links = parseLinks(observable.linkHeader);
    let primary = detectTopicOnlinks(links);
    if (
      observable.contentType == "text/html" &&
      observable.content != null &&
      observable.content.length > 0
    ) {
      // parse the html to retrieve its header
Laurent Wouters's avatar
Laurent Wouters committed
580
581
582
583
      let parser = new DOMParser();
      let doc = parser.parseFromString(
        observable.content,
        observable.contentType
Laurent Wouters's avatar
Laurent Wouters committed
584
585
586
587
588
589
590
591
      );
      let otherLinks = findLinksInDocument(doc, observable.url, primary);
      links = links.concat(otherLinks);
      if (primary == null || primary == undefined || primary == "")
        primary = detectTopicOnlinks(links);
    }
    let sources = detectDataOnLinks(links);
    let observations: ResourceObservedData = {
592
593
      primaryTopic:
        primary == null || primary == undefined ? observable.url : primary,
Laurent Wouters's avatar
Laurent Wouters committed
594
595
596
597
598
599
600
      url: observable.url,
      sources: sources
    };
    return observations;
  }
}

Laurent Wouters's avatar
Laurent Wouters committed
601
602
603
604
605
606
607
608
609
/**
 * Gets whether data has been detected
 * @param observation The current observation
 */
export function hasDetectedData(observation: ResourceObservedData): boolean {
  let main = observation.sources.find(
    (source: DataSource) => source != NO_DATA
  );
  return main != undefined && main != null && main != NO_DATA;
610
611
}

612
/**
Laurent Wouters's avatar
Laurent Wouters committed
613
 * The user command for a specific resource for the linked data browser
614
 */
Laurent Wouters's avatar
Laurent Wouters committed
615
export class ResourceUserCommand {
Laurent Wouters's avatar
Laurent Wouters committed
616
  constructor() {
Laurent Wouters's avatar
Laurent Wouters committed
617
618
619
620
621
    this.isAutomatic = true;
    this.selectedSource = "";
    this.selectedTopic = "";
    this.selectedView = "";
    this.selectedLanguage = application.NO_LANGUAGE;
Laurent Wouters's avatar
Laurent Wouters committed
622
623
  }

624
  /**
Laurent Wouters's avatar
Laurent Wouters committed
625
   * Whether the command use the defaults
626
   */
Laurent Wouters's avatar
Laurent Wouters committed
627
  isAutomatic: boolean;
628
  /**
Laurent Wouters's avatar
Laurent Wouters committed
629
   * The identifier of the user-selected data source
630
   */
Laurent Wouters's avatar
Laurent Wouters committed
631
  selectedSource: string;
Laurent Wouters's avatar
Laurent Wouters committed
632
  /**
Laurent Wouters's avatar
Laurent Wouters committed
633
   * The URI of the user-selected topic, if any
Laurent Wouters's avatar
Laurent Wouters committed
634
   */
Laurent Wouters's avatar
Laurent Wouters committed
635
  selectedTopic: string;
636
  /**
Laurent Wouters's avatar
Laurent Wouters committed
637
   * The identifier of the user-selected view
638
   */
Laurent Wouters's avatar
Laurent Wouters committed
639
  selectedView: string;
640
  /**
Laurent Wouters's avatar
Laurent Wouters committed
641
   * The user-selected language
642
   */
Laurent Wouters's avatar
Laurent Wouters committed
643
644
  selectedLanguage: application.Language;
}
645

Laurent Wouters's avatar
Laurent Wouters committed
646
647
648
649
/**
 * The data about a resource for the linked data browser
 */
export class ResourceData {
650
  /**
Laurent Wouters's avatar
Laurent Wouters committed
651
   * The observed data
652
   */
Laurent Wouters's avatar
Laurent Wouters committed
653
  observations: ResourceObservedData;
Laurent Wouters's avatar
Laurent Wouters committed
654
  /**
Laurent Wouters's avatar
Laurent Wouters committed
655
   * The associated user command
Laurent Wouters's avatar
Laurent Wouters committed
656
   */
Laurent Wouters's avatar
Laurent Wouters committed
657
658
659
660
661
662
663
  command: ResourceUserCommand;
}

/**
 * Selects the main resource among the provided one
 * @param resource The current data about a resource
 */
664
export function selectDataSources(resource: ResourceData): DataSource[] {
Laurent Wouters's avatar
Laurent Wouters committed
665
666
667
668
669
  if (
    resource.command.isAutomatic ||
    resource.command.selectedSource == null ||
    resource.command.selectedSource == ""
  ) {
670
    return selectDataSourcesAuto(resource);
Laurent Wouters's avatar
Laurent Wouters committed
671
672
673
674
  } else {
    let source = resource.observations.sources.find(
      (source: DataSource) => source.url == resource.command.selectedSource
    );
675
676
    if (source != null) return [source];
    return selectDataSourcesAuto(resource);
Laurent Wouters's avatar
Laurent Wouters committed
677
678
679
  }
}

680
681
682
683
684
685
686
687
688
689
690
691
/**
 * Automatically selects the main resource among the provided one
 * @param resource The current data about a resource
 */
function selectDataSourcesAuto(resource: ResourceData): DataSource[] {
  return resource.observations.sources
    .filter((source: DataSource) => {
      return source != NO_DATA;
    })
    .sort(compareSources);
}

Laurent Wouters's avatar
Laurent Wouters committed
692
693
694
695
696
697
698
699
700
701
702
703
704
/**
 * Selects the relevant primay topic
 * @param resource The current data about a resource
 */
export function selectPrimaryTopic(resource: ResourceData): string {
  if (
    resource.command.isAutomatic ||
    resource.command.selectedTopic == null ||
    resource.command.selectedTopic == ""
  ) {
    return resource.observations.primaryTopic;
  } else {
    return resource.command.selectedTopic;
Laurent Wouters's avatar
Laurent Wouters committed
705
  }
Laurent Wouters's avatar
Laurent Wouters committed
706
}
Laurent Wouters's avatar
Laurent Wouters committed
707

708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/**
 * Tries to negotiate data content at the specified URL
 */
export function tryNegotiateData(target: string): Promise<DataSourceLinked> {
  let accept = Object.keys(MIME)
    .map(key => {
      return MIME[key];
    })
    .sort((x: MimeInfo, y: MimeInfo) => {
      return x.priority - y.priority;
    })
    .reduce((acc: string, mime: MimeInfo, index: number) => {
      if (acc.length == 0) return mime.mime;
      return acc + ", " + mime.mime + ";q=" + (1 - 0.1 * index).toString();
    }, "");

  return new Promise(function(resolve, reject) {
    let xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status < 200 && xmlHttp.status >= 300)
          return reject("HTTP error: " + xmlHttp.status);
        let contentType = xmlHttp.getResponseHeader("Content-Type");
        let index = contentType.indexOf(";");
        if (index > 0) contentType = contentType.substring(0, index);
        if (!MIME.hasOwnProperty(contentType)) return reject("Nothing found");
        let link = new Link(target, [
          { name: "type", value: contentType },
          { name: "rel", value: "alternate" }
        ]);
        resolve(new DataSourceLinked(link));
      }
    };
    xmlHttp.open("HEAD", target, true);
    xmlHttp.setRequestHeader("Accept", accept);
    xmlHttp.send();
  });
}
746
747

/**
Laurent Wouters's avatar
Laurent Wouters committed
748
 * A registry for observed data
749
 */
Laurent Wouters's avatar
Laurent Wouters committed
750
751
export interface ObservedResourceRegistry {
  [index: number]: ResourceObservedData;
752
753
754
}

/**
Laurent Wouters's avatar
Laurent Wouters committed
755
 * Gets the observed data for a tab
756
757
758
 * @param registry The registry of tab data
 * @param id The identifier of a tab
 */
Laurent Wouters's avatar
Laurent Wouters committed
759
760
761
762
export function resolveObservationsForTab(
  registry: ObservedResourceRegistry,
  id: number
): ResourceObservedData {
763
  if (!registry.hasOwnProperty(id)) {
Laurent Wouters's avatar
Laurent Wouters committed
764
    registry[id] = new ResourceObservedData();
765
766
767
  }
  return registry[id];
}