-
Notifications
You must be signed in to change notification settings - Fork 727
Crustdata linkedin enrichment #2678
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
ad329fa
crustdata linkedin scraper start
epipav e53c463
Merge branch 'main' into feature/crustdata-linkedin-scraper
epipav 3fb0180
update activity count requirement
epipav d4d06e3
Merge branch 'feature/crustdata-linkedin-scraper' of github.com:Crowd…
epipav c6c7b9e
review points
epipav 5c44fe2
add crustdata envs to required service envs on startup
epipav 773b750
better employment normalization check
epipav 0442a2b
formatting
epipav 020052a
add initialization for normalizeEmployment for possible edge cases
epipav 9d7f094
remove contributions from normalized object in crustdata
epipav a655e06
formatting
epipav 3f717a3
comments, crustdata getData better error handling
epipav e95edfc
increase page size to 500 when getting enrichable members
epipav 033f52c
better error handling
epipav bc48cb1
switch to realtime processing before deploy
epipav 5f2bdda
Merge branch 'main' into feature/crustdata-linkedin-scraper
epipav File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
324 changes: 324 additions & 0 deletions
324
services/apps/premium/members_enrichment_worker/src/sources/crustdata/service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,324 @@ | ||
| import axios from 'axios' | ||
|
|
||
| import { isEmail } from '@crowd/common' | ||
| import { Logger, LoggerBase } from '@crowd/logging' | ||
| import { | ||
| IMemberEnrichmentCache, | ||
| IMemberIdentity, | ||
| MemberAttributeName, | ||
| MemberEnrichmentSource, | ||
| MemberIdentityType, | ||
| OrganizationIdentityType, | ||
| OrganizationSource, | ||
| PlatformType, | ||
| } from '@crowd/types' | ||
|
|
||
| import { findMemberEnrichmentCacheForAllSources } from '../../activities/enrichment' | ||
| import { EnrichmentSourceServiceFactory } from '../../factory' | ||
| import { | ||
| IEnrichmentService, | ||
| IEnrichmentSourceInput, | ||
| IMemberEnrichmentAttributeSettings, | ||
| IMemberEnrichmentData, | ||
| IMemberEnrichmentDataNormalized, | ||
| } from '../../types' | ||
| import { normalizeAttributes, normalizeSocialIdentity } from '../../utils/common' | ||
|
|
||
| import { IMemberEnrichmentCrustdataRemainingCredits, IMemberEnrichmentDataCrustdata } from './types' | ||
|
|
||
| export default class EnrichmentServiceCrustdata extends LoggerBase implements IEnrichmentService { | ||
| public source: MemberEnrichmentSource = MemberEnrichmentSource.CRUSTDATA | ||
| public platform = `enrichment-${this.source}` | ||
|
|
||
| public alsoFindInputsInSourceCaches: MemberEnrichmentSource[] = [ | ||
| MemberEnrichmentSource.PROGAI, | ||
| MemberEnrichmentSource.CLEARBIT, | ||
| MemberEnrichmentSource.SERP, | ||
| ] | ||
|
|
||
| public enrichMembersWithActivityMoreThan = 1000 | ||
|
|
||
| public enrichableBySql = `("activitySummary".total_count > ${this.enrichMembersWithActivityMoreThan}) AND mi.verified AND mi.type = 'username' and mi.platform = 'linkedin'` | ||
|
|
||
| public cacheObsoleteAfterSeconds = 60 * 60 * 24 * 90 | ||
|
|
||
| public attributeSettings: IMemberEnrichmentAttributeSettings = { | ||
| [MemberAttributeName.AVATAR_URL]: { | ||
| fields: ['profile_picture_url'], | ||
| }, | ||
| [MemberAttributeName.JOB_TITLE]: { | ||
| fields: ['title'], | ||
| }, | ||
| [MemberAttributeName.BIO]: { | ||
| fields: ['summary', 'headline'], | ||
| }, | ||
| [MemberAttributeName.SKILLS]: { | ||
| fields: ['skills'], | ||
| transform: (skills: string) => skills.split(',').sort(), | ||
| }, | ||
| [MemberAttributeName.LANGUAGES]: { | ||
| fields: ['languages'], | ||
| transform: (languages: string[]) => languages.sort(), | ||
| }, | ||
| [MemberAttributeName.SCHOOLS]: { | ||
| fields: ['all_schools'], | ||
| transform: (schools: string[]) => schools.sort(), | ||
| }, | ||
| } | ||
|
|
||
| constructor(public readonly log: Logger) { | ||
| super(log) | ||
| } | ||
|
|
||
| async isEnrichableBySource(input: IEnrichmentSourceInput): Promise<boolean> { | ||
| const caches = await findMemberEnrichmentCacheForAllSources(input.memberId) | ||
|
|
||
| let hasEnrichableLinkedinInCache = false | ||
| for (const cache of caches) { | ||
| if (this.alsoFindInputsInSourceCaches.includes(cache.source)) { | ||
| const service = EnrichmentSourceServiceFactory.getEnrichmentSourceService( | ||
| cache.source, | ||
| this.log, | ||
| ) | ||
| const normalized = service.normalize(cache.data) as IMemberEnrichmentDataNormalized | ||
| if (normalized.identities.some((i) => i.platform === PlatformType.LINKEDIN)) { | ||
| hasEnrichableLinkedinInCache = true | ||
| break | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return ( | ||
| input.activityCount > this.enrichMembersWithActivityMoreThan && | ||
| (hasEnrichableLinkedinInCache || | ||
| (input.linkedin && input.linkedin.value && input.linkedin.verified)) | ||
| ) | ||
| } | ||
|
|
||
| async hasRemainingCredits(): Promise<boolean> { | ||
| try { | ||
| const config = { | ||
| method: 'get', | ||
| url: `${process.env['CROWD_ENRICHMENT_CRUSTDATA_URL']}/user/credits`, | ||
| headers: { | ||
| Authorization: `Token ${process.env['CROWD_ENRICHMENT_CRUSTDATA_API_KEY']}`, | ||
| }, | ||
| } | ||
|
|
||
| const response: IMemberEnrichmentCrustdataRemainingCredits = (await axios(config)).data | ||
|
|
||
| return response.credits > 5 | ||
| } catch (error) { | ||
| this.log.error('Error while checking Crustdata account usage', error) | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| async getData(input: IEnrichmentSourceInput): Promise<IMemberEnrichmentDataCrustdata[] | null> { | ||
| const profiles: IMemberEnrichmentDataCrustdata[] = [] | ||
| const caches = await findMemberEnrichmentCacheForAllSources(input.memberId) | ||
|
|
||
| const consumableIdentities = await this.findDistinctScrapableLinkedinIdentities(input, caches) | ||
|
|
||
| for (const identity of consumableIdentities) { | ||
| const data = await this.getDataUsingLinkedinHandle(identity.value) | ||
| if (data) { | ||
| profiles.push({ | ||
| ...data, | ||
| metadata: { | ||
| repeatedTimesInDifferentSources: identity.repeatedTimesInDifferentSources, | ||
| isFromVerifiedSource: identity.isFromVerifiedSource, | ||
| }, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| return profiles.length > 0 ? profiles : null | ||
| } | ||
|
|
||
| private async getDataUsingLinkedinHandle( | ||
| handle: string, | ||
| ): Promise<IMemberEnrichmentDataCrustdata> { | ||
| const url = `${process.env['CROWD_ENRICHMENT_CRUSTDATA_URL']}/screener/person/enrich` | ||
| const config = { | ||
| method: 'get', | ||
| url, | ||
| params: { | ||
| linkedin_profile_url: `https://linkedin.com/in/${handle}`, | ||
epipav marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| enrich_realtime: false, | ||
| }, | ||
| headers: { | ||
| Authorization: `Token ${process.env['CROWD_ENRICHMENT_CRUSTDATA_API_KEY']}`, | ||
| }, | ||
| } | ||
|
|
||
| const response: IMemberEnrichmentDataCrustdata[] = (await axios(config)).data | ||
|
|
||
| return response.length > 0 ? response[0] : null | ||
epipav marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private async findDistinctScrapableLinkedinIdentities( | ||
| input: IEnrichmentSourceInput, | ||
| caches: IMemberEnrichmentCache<IMemberEnrichmentData>[], | ||
| ): Promise< | ||
| (IMemberIdentity & { repeatedTimesInDifferentSources: number; isFromVerifiedSource: boolean })[] | ||
| > { | ||
| const consumableIdentities: (IMemberIdentity & { | ||
| repeatedTimesInDifferentSources: number | ||
| isFromVerifiedSource: boolean | ||
| })[] = [] | ||
| const linkedinUrlHashmap = new Map<string, number>() | ||
|
|
||
| for (const cache of caches) { | ||
| if (this.alsoFindInputsInSourceCaches.includes(cache.source)) { | ||
| const service = EnrichmentSourceServiceFactory.getEnrichmentSourceService( | ||
| cache.source, | ||
| this.log, | ||
| ) | ||
| const normalized = service.normalize(cache.data) as IMemberEnrichmentDataNormalized | ||
| if (normalized.identities.some((i) => i.platform === PlatformType.LINKEDIN)) { | ||
| const identity = normalized.identities.find((i) => i.platform === PlatformType.LINKEDIN) | ||
| if (!linkedinUrlHashmap.get(identity.value)) { | ||
| consumableIdentities.push({ | ||
| ...identity, | ||
| repeatedTimesInDifferentSources: 1, | ||
| isFromVerifiedSource: false, | ||
| }) | ||
| linkedinUrlHashmap.set(identity.value, 1) | ||
| } else { | ||
| const repeatedTimesInDifferentSources = linkedinUrlHashmap.get(identity.value) + 1 | ||
| linkedinUrlHashmap.set(identity.value, repeatedTimesInDifferentSources) | ||
| consumableIdentities.find( | ||
| (i) => i.value === identity.value, | ||
| ).repeatedTimesInDifferentSources = repeatedTimesInDifferentSources | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (input.linkedin && input.linkedin.value && input.linkedin.verified) { | ||
| if (!linkedinUrlHashmap.get(input.linkedin.value)) { | ||
| consumableIdentities.push({ | ||
| ...input.linkedin, | ||
| repeatedTimesInDifferentSources: 1, | ||
| isFromVerifiedSource: true, | ||
| }) | ||
| } else { | ||
| const repeatedTimesInDifferentSources = linkedinUrlHashmap.get(input.linkedin.value) + 1 | ||
| const identityFound = consumableIdentities.find((i) => i.value === input.linkedin.value) | ||
|
|
||
| identityFound.repeatedTimesInDifferentSources = repeatedTimesInDifferentSources | ||
| identityFound.isFromVerifiedSource = true | ||
| } | ||
| } | ||
| return consumableIdentities | ||
| } | ||
|
|
||
| normalize(profiles: IMemberEnrichmentDataCrustdata[]): IMemberEnrichmentDataNormalized[] { | ||
| const normalizedProfiles: IMemberEnrichmentDataNormalized[] = [] | ||
|
|
||
| for (const profile of profiles) { | ||
| const profileNormalized = this.normalizeOneResult(profile) | ||
| normalizedProfiles.push({ ...profileNormalized, metadata: profile.metadata }) | ||
| } | ||
|
|
||
| return normalizedProfiles.length > 0 ? normalizedProfiles : null | ||
| } | ||
|
|
||
| private normalizeOneResult( | ||
| data: IMemberEnrichmentDataCrustdata, | ||
| ): IMemberEnrichmentDataNormalized { | ||
| let normalized: IMemberEnrichmentDataNormalized = { | ||
| identities: [], | ||
| attributes: {}, | ||
| contributions: [], | ||
| memberOrganizations: [], | ||
| reach: {}, | ||
| } | ||
|
|
||
| normalized = this.normalizeIdentities(data, normalized) | ||
| normalized = normalizeAttributes(data, normalized, this.attributeSettings, this.platform) | ||
| normalized = this.normalizeEmployment(data, normalized) | ||
|
|
||
| if (data.num_of_connections) { | ||
| normalized.reach[this.platform] = data.num_of_connections | ||
| } | ||
|
|
||
| return normalized | ||
| } | ||
|
|
||
| private normalizeIdentities( | ||
| data: IMemberEnrichmentDataCrustdata, | ||
| normalized: IMemberEnrichmentDataNormalized, | ||
| ): IMemberEnrichmentDataNormalized { | ||
| if (!normalized.identities) { | ||
| normalized.identities = [] | ||
| } | ||
|
|
||
| if (!normalized.attributes) { | ||
| normalized.attributes = {} | ||
| } | ||
|
|
||
| if (data.name) { | ||
| normalized.displayName = data.name | ||
| } | ||
|
|
||
| if (data.email) { | ||
| for (const email of data.email.split(',').filter(isEmail)) { | ||
| normalized.identities.push({ | ||
| type: MemberIdentityType.EMAIL, | ||
| platform: this.platform, | ||
| value: email.trim(), | ||
| verified: false, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| if (data.twitter_handle) { | ||
| normalized = normalizeSocialIdentity( | ||
| { | ||
| handle: data.twitter_handle, | ||
| platform: PlatformType.TWITTER, | ||
| }, | ||
| MemberIdentityType.USERNAME, | ||
| true, | ||
| normalized, | ||
| ) | ||
| } | ||
|
|
||
| return normalized | ||
| } | ||
|
|
||
| private normalizeEmployment( | ||
| data: IMemberEnrichmentDataCrustdata, | ||
| normalized: IMemberEnrichmentDataNormalized, | ||
| ): IMemberEnrichmentDataNormalized { | ||
| const employmentInformation = (data.past_employers || []).concat(data.current_employers || []) | ||
| if (data.past_employers) { | ||
| for (const workExperience of employmentInformation) { | ||
| const identities = [] | ||
|
|
||
| if (workExperience.employer_linkedin_id) { | ||
| identities.push({ | ||
| platform: PlatformType.LINKEDIN, | ||
| value: `company:${workExperience.employer_linkedin_id}`, | ||
| type: OrganizationIdentityType.USERNAME, | ||
| verified: true, | ||
| }) | ||
| } | ||
|
|
||
| normalized.memberOrganizations.push({ | ||
| name: workExperience.employer_name, | ||
| source: OrganizationSource.ENRICHMENT_CRUSTDATA, | ||
| identities, | ||
| title: workExperience.employee_title, | ||
| startDate: workExperience.start_date, | ||
| endDate: workExperience.end_date, | ||
| organizationDescription: workExperience.employer_linkedin_description, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| return normalized | ||
| } | ||
epipav marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.