@meltwater/conversations-api-services 1.0.21 → 1.0.23

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.
@@ -0,0 +1,530 @@
1
+
2
+ import superagent from 'superagent';
3
+ import { loggerDebug, loggerError, loggerInfo } from '../../lib/logger.helpers.js';
4
+
5
+
6
+ const LINKEDIN_API = "https://api.linkedin.com/v2";
7
+ const LINKEDIN_API_VERSION = "2.0.0";
8
+
9
+ export async function like(token, externalId, socialAccountId, logger) {
10
+ let response;
11
+ let payload = { actor: socialAccountId, object: externalId };
12
+ let query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(externalId)}/likes`
13
+
14
+ try {
15
+ loggerDebug(logger,`Linkedin trying to Like `, {
16
+ query,
17
+ payload: JSON.stringify(payload),
18
+ });
19
+ response = await superagent
20
+ .post(query)
21
+ .timeout(5000) // 5 seconds
22
+ .set({
23
+ Authorization: `Bearer ${token}`,
24
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
25
+ 'LinkedIn-Version': '202311',
26
+ })
27
+ .send(payload);
28
+
29
+
30
+ loggerInfo(logger,
31
+ `Native Linkedin API Like Mutation Response`,
32
+ { response: JSON.stringify(response) }
33
+ );
34
+ } catch (err) {
35
+ loggerError(logger,`Linkedin Like or Unlike Exception`, err);
36
+ throw err;
37
+ }
38
+ return response.connection || response;
39
+ }
40
+
41
+ export async function unlike(token, externalId, socialAccountId, logger) {
42
+ let response;
43
+ let payload = { actor: socialAccountId, object: externalId };
44
+ let query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(
45
+ externalId
46
+ )}/likes/${fixedEncodeURIComponent(
47
+ payload.actor
48
+ )}?actor=${fixedEncodeURIComponent(payload.actor)}`;
49
+
50
+ try {
51
+ loggerDebug(logger,`Linkedin trying Delete Previous Like `, {
52
+ query,
53
+ payload: JSON.stringify(payload),
54
+ });
55
+ response = await superagent
56
+ .delete(query)
57
+ .timeout(5000)
58
+ .set({
59
+ Authorization: `Bearer ${token}`,
60
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
61
+ 'LinkedIn-Version': '202311',
62
+ });
63
+
64
+ loggerInfo(logger,
65
+ `Native Linkedin API UNLike Mutation Response`,
66
+ { response: JSON.stringify(response) }
67
+ );
68
+ } catch (err) {
69
+ loggerError(logger,`Linkedin Like or Unlike Exception`, err);
70
+ throw err;
71
+ }
72
+ return response.connection || response;
73
+ }
74
+
75
+ export async function deleteMessage(token, externalId, sourceId, inReplyToId, logger) {
76
+ const [, comment] = externalId.split(',');
77
+ const commentId = comment.split(')')[0];
78
+
79
+ let response;
80
+ const query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(
81
+ inReplyToId
82
+ )}/comments/${commentId}?actor=${fixedEncodeURIComponent(sourceId)}`;
83
+
84
+ try {
85
+
86
+ loggerDebug(logger,`Linkedin trying Delete `, {
87
+ query,
88
+ });
89
+ response = await superagent
90
+ .delete(query)
91
+ .timeout(5000)
92
+ .set({
93
+ Authorization: `Bearer ${token}`,
94
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
95
+ 'LinkedIn-Version': '202311',
96
+ });
97
+
98
+ loggerInfo(logger,
99
+ `Native Linkedin API Delete Comment Response`,
100
+ { response: JSON.stringify(response) }
101
+ );
102
+ } catch (err) {
103
+ loggerError(logger,`Linkedin Delete exception details`, {
104
+ err,
105
+ });
106
+ throw err;
107
+ }
108
+ return response;
109
+ }
110
+
111
+ export async function comment(token, mediaId,inReplyToId,socialAccountId, messageText, logger){
112
+ return publish(token,'qt', mediaId,inReplyToId,socialAccountId, messageText, logger)
113
+ }
114
+ export async function reply(token, mediaId,inReplyToId,socialAccountId, messageText, logger){
115
+ return publish(token,'re', mediaId,inReplyToId,socialAccountId, messageText, logger)
116
+ }
117
+
118
+ async function publish(token,discussionType, mediaId,inReplyToId,socialAccountId, messageText, logger) {
119
+ // for now this is needed to make the urns from the images api work until the docs are updated to reflect how to use these new ids.
120
+ if (mediaId) {
121
+ mediaId = mediaId.replace(
122
+ 'urn:li:image:',
123
+ 'urn:li:digitalmediaAsset:'
124
+ );
125
+ }
126
+
127
+ let body = {
128
+ actor: socialAccountId,
129
+ message: {
130
+ attributes: [],
131
+ text: messageText,
132
+ },
133
+ };
134
+ if (discussionType === 're') {
135
+ body.parentComment = inReplyToId;
136
+ }
137
+ if (mediaId) {
138
+ body.content = [
139
+ {
140
+ entity: {
141
+ digitalmediaAsset: mediaId,
142
+ },
143
+ type: 'IMAGE',
144
+ },
145
+ ];
146
+ }
147
+
148
+ let query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(inReplyToId)}/comments`;
149
+
150
+ // data-listener -> linkedin_api.client sendComment
151
+ let response;
152
+ let downloadUrl = '';
153
+ try {
154
+ response = await superagent
155
+ .post(query)
156
+ .timeout(5000)
157
+ .set({
158
+ Authorization: `Bearer ${token}`,
159
+ 'Content-Type': 'application/json',
160
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
161
+ 'LinkedIn-Version': '202311',
162
+ })
163
+ .send(body);
164
+
165
+ loggerInfo(logger,
166
+ `Native Linkedin API Publish Comment Response`,
167
+ { response: JSON.stringify(response) }
168
+ );
169
+ response = {
170
+ status: 200,
171
+ message: JSON.parse(response.text),
172
+ };
173
+
174
+
175
+ if (mediaId) {
176
+ loggerInfo(logger,
177
+ `mediaId`,
178
+ { mediaId }
179
+ );
180
+ downloadUrl = await getImageMedia(
181
+ mediaId,
182
+ token,
183
+ logger
184
+ );
185
+ loggerInfo(logger,
186
+ `downloadUrl`,
187
+ { downloadUrl }
188
+ );
189
+ }
190
+
191
+ } catch (err) {
192
+ loggerError(logger
193
+ `Exception in linkedin publish `,
194
+ err
195
+ );
196
+ throw err;
197
+ }
198
+
199
+ return {response, downloadUrl};
200
+ }
201
+
202
+ async function getImageMedia(mediaId, token, logger) {
203
+ let response = {};
204
+ if (mediaId && mediaId.includes('digitalmediaAsset')) {
205
+ mediaId = mediaId.replace(
206
+ 'urn:li:digitalmediaAsset:',
207
+ 'urn:li:image:'
208
+ );
209
+ }
210
+
211
+ try {
212
+ response = await superagent
213
+ .get(
214
+ LINKEDIN_API +
215
+ '/images/' +
216
+ fixedEncodeURIComponent(mediaId)
217
+ )
218
+ .timeout(5000) // 5 seconds
219
+ .set({
220
+ Authorization: `Bearer ${token}`,
221
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
222
+ 'LinkedIn-Version': '202311',
223
+ });
224
+ } catch (error) {
225
+ loggerError(logger,'Error in getImageMedia', error);
226
+ }
227
+
228
+ let { downloadUrl } = response.body || {};
229
+ if (downloadUrl) {
230
+ return { downloadUrl };
231
+ } else {
232
+ loggerError(logger,
233
+ `Invalid response getting Linkedin media for mediaId: ${mediaId} `,
234
+ { response: JSON.stringify(response) }
235
+ );
236
+ return {};
237
+ }
238
+ }
239
+
240
+ export async function getVideoMedia(mediaId, token, logger) {
241
+
242
+ let response = {};
243
+ let tempValue;
244
+
245
+ if (mediaId && mediaId.includes('digitalmediaMediaArtifact')) {
246
+ tempValue = mediaId.split('digitalmediaMediaArtifact:(')[1];
247
+ tempValue = tempValue.split(
248
+ ',urn:li:digitalmediaMediaArtifactClass'
249
+ )[0];
250
+ mediaId = tempValue;
251
+ }
252
+
253
+ if (mediaId && mediaId.includes('digitalmediaAsset')) {
254
+ mediaId = mediaId.replace(
255
+ 'urn:li:digitalmediaAsset:',
256
+ 'urn:li:video:'
257
+ );
258
+ }
259
+
260
+ try {
261
+ response = await superagent
262
+ .get(
263
+ LINKEDIN_API +
264
+ '/videos/' +
265
+ fixedEncodeURIComponent(mediaId)
266
+ )
267
+ .timeout(5000) // 5 seconds
268
+ .set({
269
+ Authorization: `Bearer ${token}`,
270
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
271
+ 'LinkedIn-Version': '202311',
272
+ });
273
+ } catch (error) {
274
+ loggerError(logger, 'Error in getVideoMedia', error);
275
+ }
276
+
277
+ let { thumbnail, downloadUrl } = response.body || {};
278
+ if (downloadUrl) {
279
+ return { thumbnail, downloadUrl };
280
+ } else {
281
+ loggerError(logger,
282
+ `Invalid response getting Linkedin media for mediaId: ${mediaId} `,
283
+ { response: JSON.stringify(response) }
284
+ );
285
+ return {};
286
+ }
287
+ }
288
+
289
+ export async function getMedia(token, mediaId, type, logger) {
290
+ // needed due to issue with polled data
291
+ if (type.includes('video') && mediaId.includes('image')) {
292
+ type = 'image/jpeg';
293
+ }
294
+
295
+ try {
296
+ if (type.includes('image')) {
297
+ const { downloadUrl } = await getImageMedia(
298
+ mediaId,
299
+ token,
300
+ logger
301
+ );
302
+
303
+ return {
304
+ downloadUrl,
305
+ };
306
+ } else if (type.includes('video')) {
307
+ const { thumbnail, downloadUrl } = await getVideoMedia(
308
+ mediaId,
309
+ token,
310
+ logger
311
+ );
312
+
313
+ return {
314
+ thumbnail,
315
+ downloadUrl,
316
+ };
317
+ }
318
+
319
+ return {};
320
+ } catch (error) {
321
+ loggerError(logger,'Error in getMedia', error);
322
+ }
323
+ }
324
+
325
+ export async function mediaUploadURL(
326
+ token,
327
+ socialAccountId,
328
+ logger
329
+ ) {
330
+ let query = `${LINKEDIN_API}/images?action=initializeUpload`;
331
+ let body = {
332
+ initializeUploadRequest: {
333
+ owner: socialAccountId,
334
+ },
335
+ };
336
+
337
+ let response;
338
+ try {
339
+ response = await superagent
340
+ .post(query)
341
+ .timeout(5000)
342
+ .set({
343
+ Authorization: `Bearer ${token}`,
344
+ 'Content-type': 'application/json',
345
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
346
+ 'LinkedIn-Version': '202311',
347
+ })
348
+ .send(body);
349
+
350
+ response = {
351
+ status: 200,
352
+ message: JSON.parse(response.text),
353
+ };
354
+ return response;
355
+ } catch (err) {
356
+ loggerError(logger,
357
+ `Exception linkedin media register `,
358
+ err
359
+ );
360
+ }
361
+ }
362
+
363
+ export async function getProfile(urn, token, logger) {
364
+ let [, , , id] = urn.split(':');
365
+
366
+ let profile;
367
+ try {
368
+ profile = await superagent
369
+ .get(`${LINKEDIN_API}/people/(id:${id})`)
370
+ .query({
371
+ projection:
372
+ '(id,localizedFirstName,localizedLastName,vanityName,profilePicture(displayImage~:playableStreams))',
373
+ })
374
+ .timeout(5000)
375
+ .set({
376
+ Authorization: `Bearer ${token}`,
377
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
378
+ 'LinkedIn-Version': '202311',
379
+ })
380
+ .then((result) => result.body);
381
+ } catch (error) {
382
+ loggerError(logger,
383
+ `Failed requesting LinkedIn API for profileId ${urn}`,
384
+ error
385
+ );
386
+ return;
387
+ }
388
+
389
+ loggerInfo( logger,
390
+ `Finished requesting LinkedIn API for profileId ${urn}`
391
+ );
392
+
393
+ return profile;
394
+ }
395
+
396
+ export async function getOrganization(urn, token, logger) {
397
+ let [, , , id] = urn.split(':');
398
+
399
+ let organization;
400
+ try {
401
+ organization = await superagent
402
+ .get(`${LINKEDIN_API}/organizations/${id}`)
403
+ .query({
404
+ projection:
405
+ '(id,localizedName,vanityName,logoV2(original~:playableStreams))',
406
+ })
407
+ .timeout(5000) // 5 seconds
408
+ .set({
409
+ Authorization: `Bearer ${token}`,
410
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
411
+ 'LinkedIn-Version': '202311',
412
+ })
413
+ .then((result) => result.body);
414
+ } catch (error) {
415
+ if (error.response.body.message.includes('ADMIN_ONLY')) {
416
+ return { id: 'private' };
417
+ }
418
+
419
+ loggerError(logger,
420
+ `Failed requesting LinkedIn API for organizationId ${urn}`,
421
+ error
422
+ );
423
+ }
424
+
425
+ loggerInfo(logger,
426
+ `Finished requesting LinkedIn API for organizationId ${urn}`
427
+ );
428
+
429
+ return organization;
430
+ }
431
+
432
+ async function getAllStats(externalId, token, logger) {
433
+ let response = {};
434
+ try {
435
+ response = await superagent
436
+ .get(
437
+ LINKEDIN_API +
438
+ '/socialMetadata/' +
439
+ fixedEncodeURIComponent(externalId)
440
+ )
441
+ .timeout(5000) // 5 seconds
442
+ .set({
443
+ Authorization: `Bearer ${token}`,
444
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
445
+ 'LinkedIn-Version': '202311',
446
+ });
447
+ } catch (error) {
448
+ loggerError(logger,'Error in getAllStats', error);
449
+ }
450
+
451
+ let { commentSummary, reactionSummaries } = response.body || {};
452
+ if (commentSummary && reactionSummaries) {
453
+ return { commentSummary, reactionSummaries };
454
+ } else {
455
+ loggerError( logger,
456
+ `Invalid response getting all Linkedin Stats for externalId: ${externalId}`,
457
+ { response: JSON.stringify(response) }
458
+ );
459
+ return {};
460
+ }
461
+ }
462
+
463
+ export async function getSocialStats(externalId, token, logger) {
464
+ try {
465
+ // get all stats (likes are not to be trusted) seems to only work
466
+ // for og posts.
467
+ const {
468
+ commentSummary,
469
+ reactionSummaries,
470
+ } = await getAllStats(externalId, token, logger);
471
+
472
+ return {
473
+ commentSummary,
474
+ reactionSummaries,
475
+ };
476
+ } catch (error) {
477
+ loggerError(logger,'Error in getSocialStats', error);
478
+ }
479
+ }
480
+
481
+ export async function likedByUser(
482
+ token,
483
+ externalId,
484
+ authorExternalId,
485
+ logger
486
+ ) {
487
+ let result;
488
+ try {
489
+ result = await superagent
490
+ .get(
491
+ `${LINKEDIN_API}/reactions/(actor:${fixedEncodeURIComponent(
492
+ authorExternalId
493
+ )},entity:${fixedEncodeURIComponent(externalId)})`
494
+ )
495
+ .set({
496
+ Authorization: `Bearer ${token}`,
497
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
498
+ 'LinkedIn-Version': '202311',
499
+ })
500
+ .then((result) => result.body);
501
+ } catch (error) {
502
+ loggerError(logger,'Error in getLikesByUser', error);
503
+ return false;
504
+ }
505
+ return true;
506
+ }
507
+
508
+ // query object is from AssetManager
509
+ export async function uploadMedia(query, logger) {
510
+ const { url, token, data } = query;
511
+ return await superagent
512
+ .put(url)
513
+ .set({
514
+ Accept: '*/*',
515
+ 'Content-Type': 'application/octet-stream',
516
+ Authorization: `Bearer ${token}`,
517
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
518
+ 'LinkedIn-Version': '202311',
519
+ })
520
+ .send(data)
521
+ .catch((err) => {
522
+ loggerError(logger,"Linkedin Error uploading Media",err);
523
+ throw err;
524
+ });
525
+ }
526
+
527
+
528
+ function fixedEncodeURIComponent(str) {
529
+ return encodeURIComponent(str).replace(/\(/g, '%28').replace(/\)/g, '%29');
530
+ }
@@ -18,6 +18,7 @@ import * as applicationTagFunctions from '../lib/applicationTags.helpers.js';
18
18
  import * as hiddenHelpers from '../lib/hidden.helpers.js';
19
19
  import * as FacebookNative from './http/facebook.native.js';
20
20
  import * as TiktokNative from './http/tiktok.native.js';
21
+ import * as LinkedinNative from './http/linkedin.native.js';
21
22
 
22
23
  const DocumentHelperFunctions = {
23
24
  ...messageHelpers,
@@ -32,6 +33,7 @@ const LinkedInHelpers = {
32
33
  export {
33
34
  FacebookNative,
34
35
  TiktokNative,
36
+ LinkedinNative,
35
37
  awsS3Client,
36
38
  assetManagerTvmRepository,
37
39
  CompanyApiClient,