eventregistry 8.9.2 → 8.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/eventRegistry.js +2 -2
  3. package/dist/eventRegistry.js.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.js +13 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/queryArticles.js +6 -0
  8. package/dist/queryArticles.js.map +1 -1
  9. package/dist/queryEvents.js +6 -0
  10. package/dist/queryEvents.js.map +1 -1
  11. package/dist/queryMentions.d.ts +95 -0
  12. package/dist/queryMentions.js +579 -0
  13. package/dist/queryMentions.js.map +1 -0
  14. package/dist/topicPage.js +2 -2
  15. package/dist/topicPage.js.map +1 -1
  16. package/{src → dist}/types.d.ts +284 -195
  17. package/dist/types.js +3 -0
  18. package/dist/types.js.map +1 -0
  19. package/package.json +6 -5
  20. package/dist/correlations.d.ts +0 -50
  21. package/dist/correlations.js +0 -397
  22. package/dist/correlations.js.map +0 -1
  23. package/examples/autoSuggestionsExamples.ts +0 -46
  24. package/examples/countsExamples.ts +0 -34
  25. package/examples/dailySharesExamples.ts +0 -54
  26. package/examples/eventForTextExamples.ts +0 -32
  27. package/examples/feedOfNewArticlesExamples.ts +0 -82
  28. package/examples/feedOfNewEventsExamples.ts +0 -70
  29. package/examples/queryArticleExamples.ts +0 -42
  30. package/examples/queryArticlesExamples.ts +0 -242
  31. package/examples/queryEventExamples.ts +0 -99
  32. package/examples/queryEventsExamples.ts +0 -232
  33. package/examples/topicPageExamples.ts +0 -97
  34. package/examples/trendsExamples.ts +0 -34
  35. package/src/analytics.ts +0 -181
  36. package/src/base.ts +0 -198
  37. package/src/counts.ts +0 -119
  38. package/src/dailyShares.ts +0 -48
  39. package/src/eventForText.ts +0 -61
  40. package/src/eventRegistry.ts +0 -733
  41. package/src/index.ts +0 -111
  42. package/src/info.ts +0 -121
  43. package/src/query.ts +0 -257
  44. package/src/queryArticle.ts +0 -139
  45. package/src/queryArticles.ts +0 -603
  46. package/src/queryEvent.ts +0 -473
  47. package/src/queryEvents.ts +0 -684
  48. package/src/queryStory.ts +0 -152
  49. package/src/recent.ts +0 -63
  50. package/src/returnInfo.ts +0 -363
  51. package/src/topicPage.ts +0 -479
  52. package/src/trends.ts +0 -63
  53. package/test/index.d.ts +0 -18
  54. package/test/jasmine.json +0 -10
  55. package/test/spec/analytics.spec.ts +0 -150
  56. package/test/spec/autoSuggestions.spec.ts +0 -54
  57. package/test/spec/info.spec.ts +0 -84
  58. package/test/spec/invalidQueries.spec.ts +0 -147
  59. package/test/spec/queryArticle.spec.ts +0 -62
  60. package/test/spec/queryArticles.spec.ts +0 -541
  61. package/test/spec/queryArticlesComplex.spec.ts +0 -298
  62. package/test/spec/queryEvent.spec.ts +0 -194
  63. package/test/spec/queryEvents.spec.ts +0 -491
  64. package/test/spec/queryEventsComplex.spec.ts +0 -188
  65. package/test/spec/queryPaging.spec.ts +0 -318
  66. package/test/spec/returnInfo.spec.ts +0 -34
  67. package/test/spec/topicPage.spec.ts +0 -83
  68. package/test/spec/utils.ts +0 -436
  69. package/test/tsconfig.json +0 -31
  70. package/tsconfig.json +0 -32
  71. package/tslint.json +0 -25
@@ -1,733 +0,0 @@
1
- import axios, { AxiosResponse, AxiosRequestConfig } from "axios";
2
- import * as fs from "fs";
3
- import * as _ from "lodash";
4
- import * as moment from "moment";
5
- import Semaphore from "semaphore-async-await";
6
- import * as winston from "winston";
7
- import { ConceptInfoFlags, ReturnInfo } from "./returnInfo";
8
- import { EventRegistryStatic } from "./types";
9
- import { QueryParamsBase, sleep } from "./base";
10
- import { QueryArticle } from "./queryArticle";
11
- import { QueryArticles } from "./queryArticles";
12
- import { QueryEvents } from "./queryEvents";
13
- import { QueryEvent } from "./queryEvent";
14
-
15
- /**
16
- * @class EventRegistry
17
- * Main class responsible for obtaining results form the Event Registry
18
- */
19
- export class EventRegistry {
20
- public logger: winston.Logger;
21
- public requestLogger: winston.Logger;
22
- private config: EventRegistryStatic.Config = {
23
- host: "http://eventregistry.org",
24
- hostAnalytics: "http://analytics.eventregistry.org",
25
- logging: false,
26
- minDelayBetweenRequests: 1,
27
- repeatFailedRequestCount: 2,
28
- verboseOutput: false,
29
- allowUseOfArchive: true,
30
- };
31
- private headers = {};
32
- private dailyAvailableRequests = -1;
33
- private remainingAvailableRequests = -1;
34
- private lastQueryTime = 0;
35
- private _logRequests = false;
36
- private readonly lock: Semaphore;
37
- private readonly stopStatusCodes = [
38
- 204,
39
- 400,
40
- 401,
41
- 403,
42
- 530,
43
- ];
44
- constructor(config: EventRegistryStatic.Config = {}) {
45
- this.lock = new Semaphore(1);
46
- if (!!config.apiKey && !!config.printHostInfo) {
47
- console.log("using user provided API key for making requests");
48
- }
49
- if (fs && fs.existsSync(this.config.settingsFName || "settings.json")) {
50
- const localConfig = JSON.parse(fs.readFileSync(this.config.settingsFName || "settings.json", "utf8"));
51
- _.extend(this.config, localConfig);
52
- if (!_.isNil(config.apiKey)) {
53
- if (!!config.printHostInfo) {
54
- console.log("found apiKey in settings file which will be used for making requests");
55
- }
56
- this.config.apiKey = config.apiKey;
57
- }
58
- } else {
59
- _.extend(this.config, config);
60
- }
61
- if (this.config.logging) {
62
- this.logger = winston.createLogger({
63
- level: "info",
64
- format: winston.format.json(),
65
- transports: [
66
- new winston.transports.File({
67
- filename: "logs/error.log",
68
- level: "error",
69
- }),
70
- new winston.transports.File({ filename: "logs/info.log" }),
71
- ],
72
- });
73
- }
74
-
75
- this._logRequests = this.config.logging;
76
- this.initRequestLogger();
77
-
78
- if (_.isNil(this.config.apiKey)) {
79
- console.info("No API key was provided. You will be allowed to perform only a very limited number of requests per day.");
80
- }
81
- if (!!config.printHostInfo) {
82
- console.log(`Event Registry host: ${config.host}`);
83
- console.log(`Text analytics host: ${config.hostAnalytics}`);
84
- }
85
- this.config.minDelayBetweenRequests *= 1000;
86
-
87
- axios.interceptors.response.use(undefined, (err) => {
88
- // If config does not exist or the retry option is not set, reject
89
- if (!err.config || !err.config.retry) {
90
- return Promise.reject(err);
91
- }
92
- if (_.includes(this.stopStatusCodes, err.response.status)) {
93
- return Promise.reject(err);
94
- }
95
- // Set the variable for keeping track of the retry count
96
- err.config.__retryCount = err.config.__retryCount || 0;
97
-
98
- // Check if we've maxed out the total number of retries
99
- if (err.config.__retryCount >= err.config.retry) {
100
- // Reject with the error
101
- return Promise.reject(err);
102
- }
103
- err.config.__retryCount += 1;
104
-
105
- return new Promise((resolve) => {
106
- setTimeout(() => resolve(), err.config.retryDelay || 1);
107
- }).then(() => axios(err.config));
108
- });
109
- }
110
-
111
- /**
112
- * Should all requests be logged to a file or not?
113
- */
114
- public setLogging(logging: boolean) {
115
- this._logRequests = logging;
116
- this.initRequestLogger();
117
- }
118
-
119
- public get verboseOutput() {
120
- return this.config.verboseOutput;
121
- }
122
-
123
- /**
124
- * Main method for executing the search queries.
125
- * @param query instance of Query class
126
- */
127
- public async execQuery(query, allowUseOfArchive?: boolean) {
128
- const params = query.getQueryParams();
129
- const request = await this.jsonRequest(query.path, params, allowUseOfArchive);
130
- if (!_.has(request, "data") && this.config.verboseOutput) {
131
- this.logger.error("Request did not return with the 'data' property.");
132
- }
133
- return _.get(request, "data", {});
134
- }
135
-
136
- public async jsonRequestAnalytics(path: string, parameters?, headers?, cookies? ): Promise<AxiosResponse> {
137
- let request;
138
- await this.lock.acquire();
139
- try {
140
- _.set(parameters, "apiKey", this.config.apiKey);
141
- const args = {
142
- url: path,
143
- method: "POST",
144
- baseURL: this.config.hostAnalytics,
145
- data: parameters,
146
- timeout: 600000,
147
- responseType: "json",
148
- maxRedirects: 5,
149
- } as AxiosRequestConfig;
150
- if (!!headers) {
151
- _.set(args, "headers", headers);
152
- }
153
- if (!!cookies) {
154
- const cookieString = Object.keys(cookies).map((key) => key + "=" + cookies[key]).join(";") + ";";
155
- _.set(args, "headers.Cookie", cookieString);
156
- }
157
- request = await axios.request(args);
158
- this.headers = _.get(request, "headers", {});
159
- if (_.get(request, "status") !== 200) {
160
- throw new Error(_.get(request, "statusText"));
161
- }
162
- const errorMessage = _.get(request, "data.error", "");
163
- if (errorMessage) {
164
- throw new Error(errorMessage);
165
- }
166
- } catch (error) {
167
- console.error("Event Registry Analytics exception while executing the request.");
168
- request = { data: {error} };
169
- if (this.config.verboseOutput) {
170
- if (error && error.stack && error.message) {
171
- console.error(error.message);
172
- } else {
173
- console.error(`${_.get(error, "response.status")}: ${_.get(error, "response.statusText")} => ${_.get(error, "response.data")}`);
174
- }
175
- }
176
- // try to print out the error that should be passed by in case the server is down or responds with errors
177
- if (this.config.logging) {
178
- this.logger.error(_.get(error, "errno", error));
179
- }
180
- } finally {
181
- this.lock.release();
182
- }
183
- return request;
184
- }
185
-
186
- /**
187
- * Make a request for json data
188
- * @param path url on er (e.g. "/api/v1/article")
189
- * @param parameters Optional parameters to be included in the request
190
- */
191
- public async jsonRequest(path: string, parameters?, allowUseOfArchive = this.config.allowUseOfArchive) {
192
- let request;
193
- const current = moment.utc().milliseconds();
194
- if (this.lastQueryTime && current - this.lastQueryTime < this.config.minDelayBetweenRequests) {
195
- await sleep(this.config.minDelayBetweenRequests - (current - this.lastQueryTime) );
196
- }
197
- await this.lock.acquire();
198
- if (this._logRequests) {
199
- if (!_.isEmpty(parameters)) {
200
- this.requestLogger.info("# " + JSON.stringify(parameters) + "\n");
201
- }
202
- this.requestLogger.info(path + "\n\n");
203
- }
204
- this.lastQueryTime = current;
205
- try {
206
- _.set(parameters, "apiKey", this.config.apiKey);
207
- if (!allowUseOfArchive) {
208
- _.set(parameters, "forceMaxDataTimeWindow", 31);
209
- }
210
- request = await axios.request({
211
- url: path,
212
- method: "POST",
213
- baseURL: this.config.host,
214
- data: parameters,
215
- timeout: 600000,
216
- responseType: "json",
217
- maxRedirects: 5,
218
- retry: this.config.repeatFailedRequestCount,
219
- } as any);
220
- this.headers = _.get(request, "headers", {});
221
- if (_.get(request, "status") !== 200) {
222
- throw new Error(_.get(request, "statusText"));
223
- }
224
- if (this.getLastHeader("warning")) {
225
- console.warn(`WARNING: ${this.getLastHeader("warning")}`);
226
- }
227
- this.dailyAvailableRequests = _.toNumber(this.getLastHeader("x-ratelimit-limit", "-1"));
228
- this.remainingAvailableRequests = _.toNumber(this.getLastHeader("x-ratelimit-remaining", "-1"));
229
- const errorMessage = _.get(request, "data.error", "");
230
- if (errorMessage) {
231
- throw new Error(errorMessage);
232
- }
233
- } catch (error) {
234
- console.error("Event Registry exception while executing the request.");
235
- request = { data: {error} };
236
- // try to print out the error that should be passed by in case the server is down or responds with errors
237
- if (this.config.verboseOutput) {
238
- if (error && error.stack && error.message) {
239
- console.error(error.message);
240
- } else {
241
- console.error(`${_.get(error, "response.status")}: ${_.get(error, "response.statusText")} => ${_.get(error, "response.data")}`);
242
- }
243
- }
244
- if (this.config.logging) {
245
- this.logger.error(_.get(error, "errno", error));
246
- }
247
- } finally {
248
- this.lock.release();
249
- }
250
- return request;
251
- }
252
-
253
- /**
254
- * get the number of requests that are still available for the user today. Information is only accessible after you make some query.
255
- */
256
- public getRemainingAvailableRequests() {
257
- return this.remainingAvailableRequests;
258
- }
259
-
260
- /**
261
- * get the total number of requests that the user can make in a day. Information is only accessible after you make some query.
262
- */
263
- public getDailyAvailableRequests() {
264
- return this.dailyAvailableRequests;
265
- }
266
-
267
- /**
268
- * Return the headers returned in the response object of the last executed request
269
- */
270
- public getLastHeaders() {
271
- return this.headers;
272
- }
273
-
274
- /**
275
- * Get a value of the header headerName that was set in the headers in the last response object
276
- */
277
- public getLastHeader(headerName: string, dfltVal?) {
278
- return _.get(this.headers, headerName, dfltVal);
279
- }
280
-
281
- /**
282
- * print some statistics about the last executed request
283
- */
284
- public printLastReqStats() {
285
- console.log(`Tokens used by the request: ${this.getLastHeader("req-tokens")}`);
286
- console.log(`Performed action: ${this.getLastHeader("req-action")}`);
287
- console.log(`Was archive used for the query: ${this.getLastReqArchiveUse() ? "Yes" : "No"}`);
288
- }
289
-
290
- /**
291
- * return true or false depending on whether the last request used the archive or not
292
- */
293
- public getLastReqArchiveUse() {
294
- return this.getLastHeader("req-archive", "0") === "1";
295
- }
296
-
297
- /**
298
- * Return the number of used and total available tokens. Can be used at any time (also before making queries)
299
- */
300
- public async getUsageInfo(): Promise<EventRegistryStatic.UsageInfo> {
301
- const request = await this.jsonRequest("/api/v1/usage");
302
- return request.data;
303
- }
304
-
305
- public async getServiceStatus(): Promise<EventRegistryStatic.UsageInfo> {
306
- const request = await this.jsonRequest("/api/v1/getServiceStatus");
307
- return request.data;
308
- }
309
-
310
- public getUrl(query: QueryArticles | QueryArticle | QueryEvents | QueryEvent) {
311
- if (!(query instanceof QueryParamsBase)) {
312
- if (this.config.verboseOutput) {
313
- console.warn("query parameter should be an instance of a class that has Query as a base class, such as QueryArticles or QueryEvents");
314
- }
315
- }
316
- const allParams = query.getQueryParams();
317
- return this.config.host + query.path + "?" + _.join(_.map(_.keys(allParams), (key) => key + "=" + allParams[key]), "&");
318
- }
319
-
320
- /**
321
- * Return a list of concepts that contain the given prefix.
322
- * Returned matching concepts are sorted based on their frequency of occurrence in news (from most to least frequent)
323
- * @param prefix input text that should be contained in the concept
324
- * @param args Object which contains a host of optional parameters
325
- */
326
- public async suggestConcepts(prefix: string, args: EventRegistryStatic.SuggestConceptsArguments = {}) {
327
- const { sources = [ "concepts" ] as EventRegistryStatic.ConceptType[], lang = "eng", conceptLang = "eng", page = 1, count = 20, returnInfo = new ReturnInfo(), ...otherParams } = args;
328
- if (page <= 0) {
329
- throw new RangeError("page parameter should be above 0");
330
- }
331
-
332
- let params = {
333
- prefix: prefix,
334
- source: sources,
335
- lang: lang,
336
- conceptLang: conceptLang,
337
- page: page,
338
- count: count,
339
- };
340
- params = _.extend({}, params, otherParams, returnInfo.getParams());
341
- const request = await this.jsonRequest("/api/v1/suggestConceptsFast", params);
342
- return request.data;
343
- }
344
-
345
- /**
346
- * Return a list of dmoz categories that contain the prefix
347
- * @param prefix input text that should be contained in the category name
348
- * @param args Object which contains a host of optional parameters
349
- */
350
- public async suggestCategories(prefix: string, args: EventRegistryStatic.SuggestCategoriesArguments = {}) {
351
- const {page = 1, count = 20, returnInfo = new ReturnInfo(), ...otherParams} = args;
352
- if (page <= 0) {
353
- throw new RangeError("page parameter should be above 0");
354
- }
355
- let params = {prefix, page, count};
356
- params = _.extend({}, params, otherParams, returnInfo.getParams());
357
- const request = await this.jsonRequest("/api/v1/suggestCategoriesFast", params);
358
- return request.data;
359
- }
360
-
361
- /**
362
- * Return a list of news sources that match the prefix
363
- * @param prefix input text that should be contained in the source name or uri
364
- * @param args Object which contains a host of optional parameters
365
- */
366
- public async suggestNewsSources(prefix: string, args: EventRegistryStatic.SuggestNewsSourcesArguments = {}) {
367
- const {page = 1, count = 20, dataType = ["news", "pr", "blog"], ...otherParams} = args;
368
- if (page <= 0) {
369
- throw new RangeError("page parameter should be above 0");
370
- }
371
- const request = await this.jsonRequest("/api/v1/suggestSourcesFast", {prefix, page, dataType, count, ...otherParams});
372
- return request.data;
373
- }
374
-
375
- /**
376
- * Return a list of news source groups that match the prefix
377
- * @param prefix input text that should be contained in the source group name or uri
378
- * @param args Object which contains a host of optional parameters
379
- */
380
- public async suggestSourceGroups(prefix: string, args: EventRegistryStatic.SuggestSourceGroupsArguments = {}) {
381
- const {page = 1, count = 20, ...otherParams} = args;
382
- if (page <= 0) {
383
- throw new RangeError("page parameter should be above 0");
384
- }
385
- const request = await this.jsonRequest("/api/v1/suggestSourceGroups", {prefix, page, count, ...otherParams});
386
- return request.data;
387
- }
388
-
389
- /**
390
- * Return a list of geo locations (cities or countries) that contain the prefix
391
- * @param prefix input text that should be contained in the location name
392
- * @param args Object which contains a host of optional parameters
393
- */
394
- public async suggestLocations(prefix: string, args: EventRegistryStatic.SuggestLocationsArguments = {}) {
395
- const {
396
- sources = ["place", "country"],
397
- lang = "eng",
398
- count = 20,
399
- countryUri = "",
400
- sortByDistanceTo,
401
- returnInfo = new ReturnInfo(),
402
- ...otherParams
403
- } = args;
404
- let params = {
405
- prefix: prefix,
406
- count: count,
407
- source: sources,
408
- lang: lang,
409
- countryUri: countryUri,
410
- };
411
- params = _.extend({}, params, otherParams, returnInfo.getParams());
412
- if (sortByDistanceTo) {
413
- if (!_.isArray(sortByDistanceTo)) {
414
- throw new Error("sortByDistanceTo has to contain a tuple with latitude and longitude of the location");
415
- }
416
-
417
- if (_.size(sortByDistanceTo) !== 2) {
418
- throw new Error("The sortByDistanceTo should contain two numbers");
419
- }
420
-
421
- params["closeToLat"] = sortByDistanceTo[0];
422
- params["closeToLon"] = sortByDistanceTo[1];
423
- }
424
- const request = await this.jsonRequest("/api/v1/suggestLocationsFast", params);
425
- return request.data;
426
- }
427
-
428
- /**
429
- * Return a list of geo locations (cities or places) that are close to the provided (lat, long) values
430
- * @param latitude latitude part of the coordinate
431
- * @param longitude longitude part of the coordinate
432
- * @param radiusKm radius in kilometers around the coordinates inside which the locations should be returned
433
- * @param args Object which contains a host of optional parameters
434
- */
435
- public async suggestLocationsAtCoordinate(latitude: number, longitude: number, radiusKm: number, args: EventRegistryStatic.SuggestLocationsAtCoordinateArguments = {}) {
436
- const {
437
- limitToCities = false,
438
- lang = "eng",
439
- count = 20,
440
- ignoreNonWiki = true,
441
- returnInfo = new ReturnInfo(),
442
- ...otherParams
443
- } = args;
444
- if (!_.isNumber(latitude)) {
445
- throw new Error("The 'latitude' should be a number");
446
- }
447
- if (!_.isNumber(longitude)) {
448
- throw new Error("The 'longitude' should be a number");
449
- }
450
- let params = {
451
- action: "getLocationsAtCoordinate",
452
- lat: latitude,
453
- lon: longitude,
454
- radius: radiusKm,
455
- limitToCities: limitToCities,
456
- count: count,
457
- lang: lang,
458
- };
459
- params = _.extend({}, params, otherParams, returnInfo.getParams());
460
- const request = await this.jsonRequest("/api/v1/suggestLocationsFast", params);
461
- return request.data;
462
- }
463
-
464
- /**
465
- * Return a list of news sources that are close to the provided (lat, long) values
466
- * @param latitude latitude part of the coordinate
467
- * @param longitude longitude part of the coordinate
468
- * @param radiusKm radius in kilometers around the coordinates inside which the news sources should be located
469
- * @param count number of returned suggestions
470
- */
471
- public async suggestSourcesAtCoordinate(latitude: number, longitude: number, radiusKm: number, count = 20, ...otherParams) {
472
- if (!_.isNumber(latitude)) {
473
- throw new Error("The 'latitude' should be a number");
474
- }
475
- if (!_.isNumber(longitude)) {
476
- throw new Error("The 'longitude' should be a number");
477
- }
478
- const params = {
479
- action: "getSourcesAtCoordinate",
480
- lat: latitude,
481
- lon: longitude,
482
- radius: radiusKm,
483
- count: count,
484
- ...otherParams
485
- };
486
- const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
487
- return request.data;
488
- }
489
-
490
- /**
491
- * Return a list of news sources that are close to the provided (lat, long) values
492
- * @param conceptUri concept that represents a geographic location for which we would like to obtain a list of sources located at the place
493
- * @param args Object which contains a host of optional parameters
494
- */
495
- public async suggestSourcesAtPlace(conceptUri: string, args: EventRegistryStatic.SuggestSourcesAtPlaceArguments = {}) {
496
- const { page = 1, count = 20, dataType = "news", ...otherParams } = args;
497
- const params = {
498
- action: "getSourcesAtPlace",
499
- conceptUri: conceptUri,
500
- page: page,
501
- count: count,
502
- dataType: dataType,
503
- ...otherParams
504
- };
505
- const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
506
- return request.data;
507
- }
508
-
509
- /**
510
- * Return a list of news sources that match the prefix
511
- * @param prefix: input text that should be contained in the author name and source url
512
- * @param page: page of results
513
- * @param count: number of returned suggestions
514
- */
515
- public async suggestAuthors(prefix: string, page = 1, count = 20, ...otherParams) {
516
- if (page <= 0) {
517
- throw new Error("Page parameter should be above 0.");
518
- }
519
- const params = {
520
- prefix,
521
- page,
522
- count,
523
- ...otherParams
524
- };
525
- const request = await this.jsonRequest("/api/v1/suggestAuthorsFast", params);
526
- return request.data;
527
- }
528
-
529
- /**
530
- * Return a list of concept classes that match the given prefix
531
- * @param prefix input text that should be contained in the category name
532
- * @param args Object which contains a host of optional parameters
533
- */
534
- public async suggestConceptClasses(prefix: string, args: EventRegistryStatic.SuggestConceptClassesArguments = {}) {
535
- const {
536
- lang = "eng",
537
- conceptLang = "eng",
538
- source = ["dbpedia", "custom"],
539
- page = 1,
540
- count = 20,
541
- returnInfo = new ReturnInfo(),
542
- ...otherParams
543
- } = args;
544
- if (page < 1) {
545
- throw new Error("page parameter should be above 0");
546
- }
547
- let params = { prefix, lang, conceptLang, source, page, count};
548
- params = _.extend({}, params, otherParams, returnInfo.getParams());
549
- const request = await this.jsonRequest("/api/v1/suggestConceptClasses", params);
550
- return request.data;
551
- }
552
-
553
- /**
554
- * return a concept uri that is the best match for the given concept label
555
- * if there are multiple matches for the given conceptLabel,
556
- * they are sorted based on their frequency of occurrence in news (most to least frequent)
557
- * @param conceptLabel partial or full name of the concept for which to return the concept uri
558
- * @param args Object which contains a host of optional parameters
559
- */
560
- public async getConceptUri(conceptLabel: string, args: EventRegistryStatic.GetConceptUriArguments = {}) {
561
- const { lang = "eng", sources = [ "concepts" ] as EventRegistryStatic.ConceptType[] } = args;
562
- const matches = await this.suggestConcepts(conceptLabel, { lang, sources });
563
- return _.get(_.first(matches), "uri", undefined);
564
- }
565
-
566
- /**
567
- * Return a location uri that is the best match for the given location label
568
- * @param locationLabel partial or full location name for which to return the location uri
569
- * @param args Object which contains a host of optional parameters
570
- */
571
- public async getLocationUri(locationLabel: string, args: EventRegistryStatic.GetLocationUriArguments = {}) {
572
- const { lang = "eng", sources = [ "place", "country" ] as any, countryUri, sortByDistanceTo } = args;
573
- const matches = await this.suggestLocations(locationLabel, { lang, sources, countryUri, sortByDistanceTo });
574
- return _.get(_.first(matches), "wikiUri", undefined);
575
- }
576
-
577
- /**
578
- * Return a category uri that is the best match for the given label
579
- * @param categoryLabel partial or full name of the category for which to return category uri
580
- */
581
- public async getCategoryUri(categoryLabel: string) {
582
- const matches = await this.suggestCategories(categoryLabel);
583
- return _.get(_.first(matches), "uri", undefined);
584
- }
585
-
586
- /**
587
- * Return the news source that best matches the source name
588
- * @param sourceName partial or full name of the source or source uri for which to return source uri
589
- * @param dataType: return the source uri that provides content of these data types
590
- */
591
- public async getNewsSourceUri(sourceName: string, dataType: EventRegistryStatic.DataType[] | EventRegistryStatic.DataType = ["news", "pr", "blog"]) {
592
- const matches = await this.suggestNewsSources(sourceName, { dataType });
593
- return _.get(_.first(matches), "uri", undefined);
594
- }
595
-
596
- /**
597
- * alternative (shorter) name for the method getNewsSourceUri()
598
- */
599
- public async getSourceUri(sourceName: string, dataType: EventRegistryStatic.DataType[] | EventRegistryStatic.DataType = ["news", "pr", "blog"]) {
600
- return await this.getNewsSourceUri(sourceName, dataType);
601
- }
602
-
603
- /**
604
- * Return the URI of the source group that best matches the name
605
- * @param sourceGroupName partial or full name of the source group
606
- */
607
- public async getSourceGroupUri(sourceGroupName: string) {
608
- const matches = await this.suggestSourceGroups(sourceGroupName);
609
- return _.get(_.first(matches), "uri", undefined);
610
- }
611
-
612
- /**
613
- * Return a uri of the concept class that is the best match for the given label
614
- * @param classLabel partial or full name of the concept class for which to return class uri
615
- * @param lang language in which the class label is specified
616
- */
617
- public async getConceptClassUri(classLabel: string, lang = "eng") {
618
- const matches = await this.suggestConceptClasses(classLabel, {lang});
619
- return _.get(_.first(matches), "uri", undefined);
620
- }
621
-
622
- /**
623
- * Return detailed information about a particular concept
624
- * @param conceptUri uri of the concept
625
- * @param returnInfo what details about the concept should be included in the returned information
626
- */
627
- public async getConceptInfo(conceptUri: string, returnInfo?: ReturnInfo) {
628
- if (!returnInfo) {
629
- const conceptInfo = new ConceptInfoFlags({ synonyms: true, image: true, description: true });
630
- returnInfo = new ReturnInfo({ conceptInfo });
631
- }
632
- let params = {
633
- uri: conceptUri,
634
- action: "getInfo",
635
- };
636
- params = _.extend({}, params, returnInfo.getParams());
637
- const request = await this.jsonRequest("/api/v1/concept/getInfo", params);
638
- return request.data;
639
- }
640
-
641
- /**
642
- * return author uri that is the best match for the given author name (and potentially source url)
643
- * if there are multiple matches for the given author name, they are sorted based on the number of articles they have written (from most to least frequent)
644
- * @param authorName: partial or full name of the author, potentially also containing the source url (e.g. "george brown nytimes")
645
- */
646
- public async getAuthorUri(authorName: string) {
647
- const matches = await this.suggestAuthors(authorName);
648
- return _.get(_.first(matches), "uri", undefined);
649
- }
650
-
651
- public static getUriFromUriWgt(uriWgtList: string[]) {
652
- if (!_.isArray(uriWgtList)) {
653
- throw new Error("uriWgtList has to be a list of strings that represent article uris");
654
- }
655
- return _.map(uriWgtList, (uriWgt) => _.first(_.split(uriWgt, ":")));
656
- }
657
-
658
- // Additional utility functions
659
-
660
- /**
661
- * If you have article urls and you want to query them in ER you first have to obtain their uris in the ER.
662
- * @param articleUrls a single article url or a list of article urls
663
- */
664
- public async getArticleUris(articleUrls: string | string[]) {
665
- if (!_.isArray(articleUrls) && !_.isString(articleUrls)) {
666
- throw new Error("Expected a single article url or a list of urls");
667
- }
668
- const request = await this.jsonRequest("/api/v1/articleMapper", { articleUrl: articleUrls});
669
- return request.data;
670
- }
671
-
672
- /**
673
- * Return information about the latest imported article
674
- */
675
- public async getSourceGroups() {
676
- const request = await this.jsonRequest("/api/v1/sourceGroup/getSourceGroups", { action: "getSourceGroups"});
677
- return request.data;
678
- }
679
-
680
- /**
681
- * Return info about the source group
682
- */
683
- public async getSourceGroup(sourceGroupUri: string) {
684
- const request = await this.jsonRequest("/api/v1/sourceGroup/getSourceGroupInfo", { action: "getSourceGroupInfo", uri: sourceGroupUri});
685
- return request.data;
686
- }
687
-
688
- private initRequestLogger() {
689
- if (this._logRequests && _.isUndefined(this.requestLogger)) {
690
- this.requestLogger = winston.createLogger({
691
- level: "info",
692
- format: winston.format.json(),
693
- transports: [
694
- new winston.transports.File({ filename: "logs/requests.log" }),
695
- ],
696
- });
697
- }
698
- }
699
- }
700
-
701
- /**
702
- * @class ArticleMapper
703
- * Create instance of article mapper it will map from article urls to article uris
704
- * the mappings can be remembered so it will not repeat requests for the same article urls
705
- */
706
- export class ArticleMapper {
707
- private er: EventRegistry;
708
- private articleUrlToUri = {};
709
- private rememberMappings = true;
710
-
711
- constructor(er: EventRegistry, rememberMapping = true) {
712
- this.er = er;
713
- this.rememberMappings = rememberMapping;
714
- }
715
-
716
- /**
717
- * Given the article url, return an array with 0, 1 or more article uris.
718
- * Not all returned article uris are necessarily valid anymore.
719
- * For news sources of lower importance we remove the duplicated articles and just keep the latest content
720
- * @param articleUrl string containing the article url
721
- */
722
- public async getArticleUri(articleUrl: string) {
723
- if (_.has(this.articleUrlToUri, articleUrl)) {
724
- return _.get(this.articleUrlToUri, articleUrl);
725
- }
726
- const response = await this.er.getArticleUris(articleUrl);
727
- const value = _.get(response, articleUrl, undefined);
728
- if (this.rememberMappings && value) {
729
- this.articleUrlToUri[articleUrl] = value;
730
- }
731
- return value;
732
- }
733
- }