news.service.ts 13.6 KB
Newer Older
Thibault Ehrhart's avatar
Thibault Ehrhart committed
1
import { Injectable } from '@angular/core';
2
import { HttpClient } from '@angular/common/http';
Thibault Ehrhart's avatar
Thibault Ehrhart committed
3 4 5 6 7 8 9 10 11 12 13 14
import { Observable, Observer } from 'rxjs/Rx';
import 'rxjs/add/observable/fromPromise';
import { of } from 'rxjs/observable/of';
import { map, catchError } from 'rxjs/operators';

import { environment } from '../../../environments/environment';

declare var require: any;
const { Client } = require('virtuoso-sparql-client');

export interface NewsContext {
  id?: string;
15
  subjects?: Array<string> | string;
Thibault Ehrhart's avatar
Thibault Ehrhart committed
16 17 18 19 20
  genres?: Array<string> | string;
  date?: string;
  location?: string;
  keywords?: string;
  annotations?: Array<any>;
21
  schema?: string;
22
  schemaProperties?: Array<any>;
23 24
  language?: string;
  hasMedias?: boolean;
Thibault Ehrhart's avatar
Thibault Ehrhart committed
25 26 27 28 29
}

@Injectable()
export class NewsService {

30
  constructor(private http: HttpClient) {}
Thibault Ehrhart's avatar
Thibault Ehrhart committed
31

32
  getAnnotations(classRef: string = null, term: string = null): Observable<any> {
Thibault Ehrhart's avatar
Thibault Ehrhart committed
33 34
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');
35
    let query = `
Thibault Ehrhart's avatar
Thibault Ehrhart committed
36 37
      ${this.getPrefixes()}
      SELECT DISTINCT ?anchorOf ?classRef ?identRef
38
      FROM <http://asrael.eurecom.fr/agencefrancepresse/news>
Thibault Ehrhart's avatar
Thibault Ehrhart committed
39
      WHERE {
40
        ?s a nif:Phrase .
Thibault Ehrhart's avatar
Thibault Ehrhart committed
41 42 43 44
        ?s nif:referenceContext ?refContext .
        ?s nif:anchorOf ?anchorOf .
        ?s itsrdf:taClassRef ?classRef .
        ?s itsrdf:taIdentRef ?identRef .
45 46 47 48
        `
        + (term ? `FILTER (CONTAINS(LCASE(?anchorOf), LCASE(${JSON.stringify(term)})))` : ``)
        + (classRef ? `FILTER (?classRef = <${classRef}>)` : ``)
        + `
Thibault Ehrhart's avatar
Thibault Ehrhart committed
49
      }
50 51 52 53 54 55
      LIMIT 20
    `;

    console.debug(query);

    return Observable.fromPromise(client.query(query));
Thibault Ehrhart's avatar
Thibault Ehrhart committed
56 57 58 59 60 61 62 63
  }

  getLocations(): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');
    return Observable.fromPromise(client.query(`
      ${this.getPrefixes()}
      SELECT DISTINCT ?country
64
      FROM <http://asrael.eurecom.fr/agencefrancepresse/news>
Thibault Ehrhart's avatar
Thibault Ehrhart committed
65
      WHERE {
66
        ?s a rnews:Article .
Thibault Ehrhart's avatar
Thibault Ehrhart committed
67 68 69 70 71 72 73 74
        ?s schema:contentLocation ?location .
        ?location schema:address ?address .
        ?address schema:addressCountry ?country .
        ?address schema:addressLocality ?locality .
      }
      ORDER BY ASC(?country)
    `));
  }
75

Thibault Ehrhart's avatar
Thibault Ehrhart committed
76 77 78 79 80 81 82 83
  getSubjectCodes(): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');
    return Observable.fromPromise(client.query(`
      ${this.getPrefixes()}
      SELECT DISTINCT ?sc ?prefLabel
      WHERE {
        {
84
          SELECT DISTINCT ?subject WHERE {
85
            GRAPH <http://asrael.eurecom.fr/agencefrancepresse/news> { ?s a rnews:Article . }
86
            ?s dc:subject ?subject .
Thibault Ehrhart's avatar
Thibault Ehrhart committed
87 88 89 90 91 92 93
          }
        }
        {
          GRAPH <http://asrael.eurecom.fr/iptc/subjectcodes> { ?sc a skos:Concept . }
          ?sc skos:inScheme <http://cv.iptc.org/newscodes/subjectcode/> .
          ?sc skos:prefLabel ?prefLabel .
          FILTER (LANG(?prefLabel) = "" || LANG(?prefLabel) = "en-gb")
94
          FILTER (?sc = ?subject)
Thibault Ehrhart's avatar
Thibault Ehrhart committed
95 96 97 98 99 100
        }
      }
      ORDER BY ASC(?prefLabel)
    `));
  }

101 102 103 104 105 106 107
  getLanguages(): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');
    return Observable.fromPromise(client.query(`
      ${this.getPrefixes()}
      SELECT DISTINCT ?lang
      WHERE {
108
        GRAPH <http://asrael.eurecom.fr/agencefrancepresse/news> { ?s a rnews:Article . }
109 110 111 112 113 114
        ?s rnews:inLanguage ?lang .
      }
      GROUP BY ?lang
    `));
  }

Thibault Ehrhart's avatar
Thibault Ehrhart committed
115 116 117 118 119 120 121 122
  getPrefixes() {
    return `
      PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
      PREFIX schema: <http://schema.org/>
      PREFIX rnews: <http://iptc.org/std/rNews/2011-10-07#>
      PREFIX asrael: <http://asrael.eurecom.fr/asrael#>
      PREFIX nif: <http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#>
      PREFIX itsrdf: <http://www.w3.org/2005/11/its/rdf#>
123
      PREFIX wdt: <http://www.wikidata.org/prop/direct/>
Thibault Ehrhart's avatar
Thibault Ehrhart committed
124 125 126 127 128 129 130 131 132 133
    `;
  }

  getNewsByUri(uri: string): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');

    // Generate query
    let query = `
      ${this.getPrefixes()}
134
      SELECT DISTINCT ?s ?dateCreated ?dateModified ?datePublished ?description ?genre ?genreLabel (GROUP_CONCAT(?subject; separator="|") AS ?subjects) (GROUP_CONCAT(?subjectLabel; separator="|") AS ?subjectsLabels) ?dateline ?headline ?identifier ?language ?slug (GROUP_CONCAT(?associatedMedia; separator="|") AS ?associatedMedias) ?country ?locality ?context
Thibault Ehrhart's avatar
Thibault Ehrhart committed
135
      FROM <http://asrael.eurecom.fr/agencefrancepresse/news>
Thibault Ehrhart's avatar
Thibault Ehrhart committed
136
      WHERE {
137
        ?s a rnews:Article .
Thibault Ehrhart's avatar
Thibault Ehrhart committed
138 139 140 141 142
        VALUES ?s { <${uri}> }
        OPTIONAL { ?s rnews:dateCreated ?dateCreated . }
        OPTIONAL { ?s rnews:dateModified ?dateModified . }
        OPTIONAL { ?s rnews:datePublished ?datePublished . }
        OPTIONAL {
143
          ?s rnews:articleBody ?description .
Thibault Ehrhart's avatar
Thibault Ehrhart committed
144
        }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        OPTIONAL {
          ?s rnews:genre ?genre .
          OPTIONAL {
            ?genre skos:prefLabel ?genreLabel .
            FILTER (LANG(?genreLabel) = "en-gb")
          }
        }
        OPTIONAL {
          ?s dc:subject ?subject .
          OPTIONAL {
            ?subject skos:prefLabel ?subjectLabel .
            FILTER (LANG(?subjectLabel) = "en-gb")
          }
        }
        OPTIONAL { ?s rnews:dateline ?dateline . }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
160 161 162 163
        OPTIONAL { ?s rnews:headline ?headline . }
        OPTIONAL { ?s rnews:identifier ?identifier . }
        OPTIONAL { ?s rnews:inLanguage ?language . }
        OPTIONAL { ?s rnews:slug ?slug . }
164
        OPTIONAL { ?s rnews:associatedMedia ?associatedMedia . }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
165 166 167 168 169 170 171 172
        OPTIONAL {
          ?s schema:contentLocation ?location .
          OPTIONAL {
            ?location schema:address ?address .
            OPTIONAL { ?address schema:addressCountry ?country . }
            OPTIONAL { ?address schema:addressLocality ?locality }
          }
        }
173
        OPTIONAL { ?s asrael:context ?context . }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
      }
      LIMIT 1
    `;

    console.debug(query);

    let obs = Observable.create((observer: Observer<JSON>) => {
      client.query(query).then((data: any) => {
        let bindings = data.results.bindings;
        bindings.forEach((binding: any) => {
            // Normalize objects
            for (let k in binding) {
              binding[k] = binding[k].value;
            }

189
            // Subjects
Thibault Ehrhart's avatar
Thibault Ehrhart committed
190 191 192 193 194 195 196
            if (binding.subjects) {
              binding.subjects = binding.subjects.split('|');
            }
            if (binding.subjectsLabels) {
              binding.subjectsLabels = binding.subjectsLabels.split('|');
            }

197 198 199 200
            // Associated medias
            if (binding.associatedMedias) {
              binding.associatedMedias = binding.associatedMedias.split('|');
            }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214
        });

        observer.next(bindings);
        observer.complete();
      });
    });

    return obs;
  }

  getNews(context: NewsContext): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');

215 216 217 218 219 220
    // Subjects filter
    let subjectsFilter = '';
    if (typeof context.subjects === 'string') {
      context.subjects = [context.subjects];
    }
    if (Array.isArray(context.subjects) && context.subjects.length > 0) {
221
      subjectsFilter = '?s dc:subject ?subject . VALUES ?subject { ' + context.subjects.map(uri => '<' + uri + '>').join(' ') + ' }';
222 223
    }

Thibault Ehrhart's avatar
Thibault Ehrhart committed
224 225 226 227 228 229
    // Genres filter
    let genresFilter = '';
    if (typeof context.genres === 'string') {
      context.genres = [context.genres];
    }
    if (Array.isArray(context.genres) && context.genres.length > 0) {
230
      genresFilter = '?s rnews:genre ?genre . FILTER (?genre NOT IN(' + context.genres.map(genre => `<http://cv.iptc.org/newscodes/genre/${genre}>`) + '))';
Thibault Ehrhart's avatar
Thibault Ehrhart committed
231 232 233 234 235 236 237 238 239
    }

    // Date filter
    let dateFilter = context.date ? 'FILTER(?dateCreated >= "' + context.date + 'T00:00:00Z"^^xsd:dateTime && ?dateCreated <= "' + context.date + 'T23:59:59Z"^^xsd:dateTime)' : '';

    // Location filter
    let locationFilter = context.location ? 'FILTER(IF(BOUND(?country), contains(?country, "' + context.location + '"), true))' : '';

    // Keywords filter
Thibault Ehrhart's avatar
Thibault Ehrhart committed
240 241 242
    let keywordsFilter = context.keywords ? 'FILTER(CONTAINS(?description, ' + JSON.stringify(context.keywords) + ')) ' : '';

    // Schema filter
243 244 245
    let schemaFilter = '';
    if (context.schemaProperties) {
      context.schemaProperties.forEach(prop => {
Thibault Ehrhart's avatar
Thibault Ehrhart committed
246
        if (prop.value.length > 0) {
247
          schemaFilter += `?s wdt:${prop.name} ?wdt_${prop.name} . FILTER(?wdt_${prop.name} >= ${JSON.stringify(prop.value)}^^xsd:float) `
Thibault Ehrhart's avatar
Thibault Ehrhart committed
248
        }
249 250
      })
    }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
251

252 253 254
    // Language filter
    const languageFilter = context.language ? '?s rnews:inLanguage ' + JSON.stringify(context.language) + ' .': '';

Thibault Ehrhart's avatar
Thibault Ehrhart committed
255 256 257 258 259
    // Annotations filter
    let annotationsFilter = '';
    console.log('context=',context);
    if (context.annotations) {
      annotationsFilter += `
260
        OPTIONAL { ?s asrael:context ?context . }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
      `;
      let i = 0;
      for (let k in context.annotations) {
        annotationsFilter += `
          {
            SELECT ?refContext_${i} WHERE {
              GRAPH <http://asrael.eurecom.fr/agencefrancepresse/news> { ?sp a nif:Phrase . }
              ?sp nif:referenceContext ?refContext_${i} .
              ?sp itsrdf:taIdentRef ?identRef_${i} .
              FILTER (?identRef_${i} = <${context.annotations[k]}>)
            }
          }
          FILTER (?context = ?refContext_${i})
        `;
        i++;
      }
    }

279 280 281
    // Has medias
    const hasMediasFilter = context.hasMedias ? 'FILTER EXISTS { ?s rnews:associatedMedia ?associatedMedia }' : '';

Thibault Ehrhart's avatar
Thibault Ehrhart committed
282 283 284 285 286 287 288
    // Offset/limit
    let offset = 0;
    let limit = 100;

    // Generate query
    let query = `
      ${this.getPrefixes()}
289 290
      SELECT DISTINCT *
      FROM <http://asrael.eurecom.fr/agencefrancepresse/news>
Thibault Ehrhart's avatar
Thibault Ehrhart committed
291
      WHERE {
292
        ?s a rnews:Article .
Thibault Ehrhart's avatar
Thibault Ehrhart committed
293
        OPTIONAL { ?s rnews:dateCreated ?dateCreated . }
294
        OPTIONAL { ?s rnews:articleBody ?description . }
Thibault Ehrhart's avatar
Thibault Ehrhart committed
295
        OPTIONAL { ?s rnews:headline ?headline . }
296
        OPTIONAL { ?s asrael:context ?context . }
297 298
        OPTIONAL { ?s schema:contentLocation/schema:address/schema:addressCountry ?country . }
        OPTIONAL { ?s schema:contentLocation/schema:address/schema:addressLocality ?locality . }
299
        FILTER (BOUND(?headline) || STRLEN(?headline) > 0)
300
        ${keywordsFilter}
301
        ${subjectsFilter}
Thibault Ehrhart's avatar
Thibault Ehrhart committed
302 303 304
        ${genresFilter}
        ${dateFilter}
        ${locationFilter}
305
        ${schemaFilter}
306
        ${languageFilter}
Thibault Ehrhart's avatar
Thibault Ehrhart committed
307
        ${annotationsFilter}
308
        ${hasMediasFilter}
Thibault Ehrhart's avatar
Thibault Ehrhart committed
309 310 311 312 313 314 315 316 317 318 319
      }
      ORDER BY DESC(?dateCreated)
      OFFSET ${offset}
      LIMIT ${limit}
    `;

    console.debug(query);

    return Observable.fromPromise(client.query(query));
  }

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  getNewsWikiProps(newsURI: string): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');

    let query = `
      ${this.getPrefixes()}
      SELECT DISTINCT *
      FROM <http://asrael.eurecom.fr/agencefrancepresse/news>
      WHERE {
        <${newsURI}> ?p ?o .
        FILTER(STRSTARTS(STR(?p), STR(wdt:)))
      }
    `;

    console.debug(query);

    return Observable.fromPromise(client.query(query));
  }

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  getAnnotationsByContext(context: string): Observable<any> {
    let client = new Client(environment.virtuosoAddress);
    client.setOptions('application/json');

    // Generate query
    let query = `
      ${this.getPrefixes()}
      SELECT ?refContext ?anchorOf ?classRef ?identRef ?beginIndex ?endIndex
      FROM <http://asrael.eurecom.fr/agencefrancepresse/news>
      WHERE {
        ?sp a nif:Phrase .
        ?sp nif:referenceContext ?refContext .
        VALUES ?refContext { <${context}> }
        ?sp nif:anchorOf ?anchorOf .
        ?sp nif:beginIndex ?beginIndex .
        ?sp nif:endIndex ?endIndex .
        ?sp itsrdf:taClassRef ?classRef .
        ?sp itsrdf:taIdentRef ?identRef .
      }
    `;

    console.debug(query);

    let obs = Observable.create((observer: Observer<JSON>) => {
      client.query(query).then((data: any) => {
        let bindings = data.results.bindings;
        bindings.forEach((binding: any) => {
            // Normalize objects
            for (let k in binding) {
              binding[k] = binding[k].value;
            }
        });

        observer.next(bindings);
        observer.complete();
      });
    });

    return obs;
  }

380
  getSources(identifier: string): Observable<any> {
Thibault Ehrhart's avatar
Thibault Ehrhart committed
381
    return this.http.get('assets/data/limsi/' + identifier.replace(/:/g, '_') + '.json');
382 383
  }

384 385 386 387
  getSchemas(): Observable<any> {
    return this.http.get('assets/schemas.json');
  }

388 389 390 391
  getClusters(): Observable<any> {
    return this.http.get('assets/clusters.json');
  }

392 393
  static getAnnotationColor(annotationType: string) {
    switch (annotationType) {
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
      case 'http://adel.eurecom.fr/Stanford/Person':
      case 'http://adel.eurecom.fr/Stanford/PERSON':
        return 'person';
      case 'http://adel.eurecom.fr/Stanford/Location':
      case 'http://adel.eurecom.fr/Stanford/LOCATION':
        return 'location';
      case 'http://adel.eurecom.fr/Stanford/Misc':
      case 'http://adel.eurecom.fr/Stanford/MISC':
        return 'misc';
      case 'http://adel.eurecom.fr/Stanford/Organization':
      case 'http://adel.eurecom.fr/Stanford/ORGANIZATION':
        return 'organization';
      case 'http://adel.eurecom.fr/Stanford/Thing':
      case 'http://adel.eurecom.fr/Stanford/THING':
        return 'thing';
      case 'http://adel.eurecom.fr/Stanford/Event':
      case 'http://adel.eurecom.fr/Stanford/EVENT':
        return 'event';
      case 'http://adel.eurecom.fr/Stanford/Product':
      case 'http://adel.eurecom.fr/Stanford/PRODUCT':
        return 'product';
415 416 417 418
    }
    return 'default';
  }

Thibault Ehrhart's avatar
Thibault Ehrhart committed
419
}