generated from demchenkoalex/react-native-module-template
-
Notifications
You must be signed in to change notification settings - Fork 30
/
utils.ts
225 lines (179 loc) · 6.6 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
import { decode } from 'html-entities'
import { Image } from 'react-native'
import { PreviewData, PreviewDataImage, Size } from './types'
export const getActualImageUrl = (baseUrl: string, imageUrl?: string) => {
let actualImageUrl = imageUrl?.trim()
if (!actualImageUrl || actualImageUrl.startsWith('data')) return
if (actualImageUrl.startsWith('//'))
actualImageUrl = `https:${actualImageUrl}`
if (!actualImageUrl.startsWith('http')) {
if (baseUrl.endsWith('/') && actualImageUrl.startsWith('/')) {
actualImageUrl = `${baseUrl.slice(0, -1)}${actualImageUrl}`
} else if (!baseUrl.endsWith('/') && !actualImageUrl.startsWith('/')) {
actualImageUrl = `${baseUrl}/${actualImageUrl}`
} else {
actualImageUrl = `${baseUrl}${actualImageUrl}`
}
}
return actualImageUrl
}
export const getHtmlEntitiesDecodedText = (text?: string) => {
const actualText = text?.trim()
if (!actualText) return
return decode(actualText)
}
export const getContent = (left: string, right: string, type: string) => {
const contents = {
[left.trim()]: right,
[right.trim()]: left,
}
return contents[type]?.trim()
}
export const getImageSize = (url: string) => {
return new Promise<Size>((resolve, reject) => {
Image.getSize(
url,
(width, height) => {
resolve({ height, width })
},
// type-coverage:ignore-next-line
(error) => reject(error)
)
})
}
// Functions below use functions from the same file and mocks are not working
/* istanbul ignore next */
export const getPreviewData = async (text: string, requestTimeout = 5000) => {
const previewData: PreviewData = {
description: undefined,
image: undefined,
link: undefined,
title: undefined,
}
try {
const textWithoutEmails = text.replace(REGEX_EMAIL, '').trim()
if (!textWithoutEmails) return previewData
const link = textWithoutEmails.match(REGEX_LINK)?.[0]
if (!link) return previewData
let url = link
if (!url.toLowerCase().startsWith('http')) {
url = 'https://' + url
}
// eslint-disable-next-line no-undef
let abortControllerTimeout: NodeJS.Timeout
const abortController = new AbortController()
const request = fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
},
signal: abortController.signal,
})
abortControllerTimeout = setTimeout(() => {
abortController.abort()
}, requestTimeout)
const response = await request
clearTimeout(abortControllerTimeout)
previewData.link = url
const contentType = response.headers.get('content-type') ?? ''
if (REGEX_IMAGE_CONTENT_TYPE.test(contentType)) {
const image = await getPreviewDataImage(url)
previewData.image = image
return previewData
}
const html = await response.text()
// Some pages return undefined
if (!html) return previewData
const head = html.substring(0, html.indexOf('<body'))
// Get page title
const title = REGEX_TITLE.exec(head)
previewData.title = getHtmlEntitiesDecodedText(title?.[1])
let matches: RegExpMatchArray | null
const meta: RegExpMatchArray[] = []
while ((matches = REGEX_META.exec(head)) !== null) {
meta.push([...matches])
}
const metaPreviewData = meta.reduce<{
description?: string
imageUrl?: string
title?: string
}>(
(acc, curr) => {
// Verify that we have property/name and content
// Note that if a page will specify property, name and content in the same meta, regex will fail
if (!curr[2] || !curr[3]) return acc
// Only take the first occurrence
// For description take the meta description tag into consideration
const description =
!acc.description &&
(getContent(curr[2], curr[3], 'og:description') ||
getContent(curr[2], curr[3], 'description'))
const ogImage =
!acc.imageUrl && getContent(curr[2], curr[3], 'og:image')
const ogTitle = !acc.title && getContent(curr[2], curr[3], 'og:title')
return {
description: description
? getHtmlEntitiesDecodedText(description)
: acc.description,
imageUrl: ogImage ? getActualImageUrl(url, ogImage) : acc.imageUrl,
title: ogTitle ? getHtmlEntitiesDecodedText(ogTitle) : acc.title,
}
},
{ title: previewData.title }
)
previewData.description = metaPreviewData.description
previewData.image = await getPreviewDataImage(metaPreviewData.imageUrl)
previewData.title = metaPreviewData.title
if (!previewData.image) {
let imageMatches: RegExpMatchArray | null
const tags: RegExpMatchArray[] = []
while ((imageMatches = REGEX_IMAGE_TAG.exec(html)) !== null) {
tags.push([...imageMatches])
}
let images: PreviewDataImage[] = []
for (const tag of tags
.filter((t) => !t[1].startsWith('data'))
.slice(0, 5)) {
const image = await getPreviewDataImage(getActualImageUrl(url, tag[1]))
if (!image) continue
images = [...images, image]
}
previewData.image = images.sort(
(a, b) => b.height * b.width - a.height * a.width
)[0]
}
return previewData
} catch {
return previewData
}
}
/* istanbul ignore next */
export const getPreviewDataImage = async (url?: string) => {
if (!url) return
try {
const { height, width } = await getImageSize(url)
const aspectRatio = width / (height || 1)
if (height > 100 && width > 100 && aspectRatio > 0.1 && aspectRatio < 10) {
const image: PreviewDataImage = { height, url, width }
return image
}
} catch {}
}
export const oneOf =
<T extends (...args: A) => any, U, A extends any[]>(
truthy: T | undefined,
falsy: U
) =>
(...args: Parameters<T>): ReturnType<T> | U => {
return truthy ? truthy(...args) : falsy
}
export const REGEX_EMAIL = /([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/g
export const REGEX_IMAGE_CONTENT_TYPE = /image\/*/g
// Consider empty line after img tag and take only the src field, space before to not match data-src for example
export const REGEX_IMAGE_TAG = /<img[\n\r]*.*? src=["'](.*?)["']/g
export const REGEX_LINK =
/((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/i
// Some pages write content before the name/property, some use single quotes instead of double
export const REGEX_META =
/<meta.*?(property|name)=["'](.*?)["'].*?content=["'](.*?)["'].*?>/g
export const REGEX_TITLE = /<title.*?>(.*?)<\/title>/g