A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
fix link preview
ammarahm-edd3480af3a7b5
diff --git a/apps/mobile/share/index.js b/apps/mobile/share/index.jsindex d1735514a..7429f89ca 100644--- a/apps/mobile/share/index.js+++ b/apps/mobile/share/index.js@@ -1,8 +1,7 @@import Clipboard from '@react-native-clipboard/clipboard';import absolutify from 'absolutify';-import { getLinkPreview } from '../src/utils/linkpreview';-import React, {useEffect, useRef, useState} from 'react';-import {ScrollView} from 'react-native';+import React, { useEffect, useRef, useState } from 'react';+import { ScrollView } from 'react-native';import {ActivityIndicator,Alert,@@ -16,23 +15,20 @@ import {useWindowDimensions,View} from 'react-native';-import Animated, {Easing, timing, useValue} from 'react-native-reanimated';-import {useSafeAreaInsets} from 'react-native-safe-area-context';+import Animated, { Easing, timing, useValue } from 'react-native-reanimated';+import { useSafeAreaInsets } from 'react-native-safe-area-context';import Icon from 'react-native-vector-icons/MaterialCommunityIcons';import WebView from 'react-native-webview';import ShareExtension from 'rn-extensions-share';-import {- eSendEvent,- eSubscribeEvent,- eUnSubscribeEvent-} from '../src/services/EventManager';-import {getElevation} from '../src/utils';-import {db} from '../src/utils/database';+import { eSendEvent, eSubscribeEvent, eUnSubscribeEvent } from '../src/services/EventManager';+import { getElevation } from '../src/utils';+import { db } from '../src/utils/database';import Storage from '../src/utils/storage';-import {sleep} from '../src/utils/TimeUtils';-import {Search} from './search';-import {useShareStore} from './store';+import { sleep } from '../src/utils/TimeUtils';+import { Search } from './search';+import { useShareStore } from './store';import isURL from 'validator/lib/isURL';+import { getLinkPreview } from 'link-preview-js';const AnimatedKAV = Animated.createAnimatedComponent(KeyboardAvoidingView);const AnimatedSAV = Animated.createAnimatedComponent(SafeAreaView);@@ -68,7 +64,7 @@ function getBaseUrl(site) {return url;}function absolutifyImgs(html, site) {- let {parse} = require('node-html-parser');+ let { parse } = require('node-html-parser');let parser = parse(html);let images = parser.querySelectorAll('img');@@ -118,12 +114,12 @@ const modes = {}};-const NotesnookShare = ({quicknote = false}) => {+const NotesnookShare = ({ quicknote = false }) => {const colors = useShareStore(state => state.colors);const accent = useShareStore(state => state.accent);const appendNote = useShareStore(state => state.appendNote);- const [note, setNote] = useState({...defaultNote});+ const [note, setNote] = useState({ ...defaultNote });const [loadingIntent, setLoadingIntent] = useState(true);const [loading, setLoading] = useState(false);const [floating, setFloating] = useState(false);@@ -133,14 +129,11 @@ const NotesnookShare = ({quicknote = false}) => {});const [mode, setMode] = useState(1);const keyboardHeight = useRef(0);- const {width, height} = useWindowDimensions();+ const { width, height } = useWindowDimensions();const webviewRef = useRef();const opacity = useValue(0);const translate = useValue(1000);- const insets =- Platform.OS === 'android'- ? {top: StatusBar.currentHeight}- : useSafeAreaInsets();+ const insets = Platform.OS === 'android' ? { top: StatusBar.currentHeight } : useSafeAreaInsets();const prevAnimation = useRef(null);const [showSearch, setShowSearch] = useState(false);@@ -174,14 +167,8 @@ const NotesnookShare = ({quicknote = false}) => {'keyboardWillChangeFrame',onKeyboardWillChangeFrame);- let keyboardDidShow = Keyboard.addListener(- 'keyboardDidShow',- onKeyboardDidShow- );- let keyboardDidHide = Keyboard.addListener(- 'keyboardDidHide',- onKeyboardDidHide- );+ let keyboardDidShow = Keyboard.addListener('keyboardDidShow', onKeyboardDidShow);+ let keyboardDidHide = Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);return () => {keyboardWillChangeFrame?.remove();keyboardDidShow?.remove();@@ -208,7 +195,7 @@ const NotesnookShare = ({quicknote = false}) => {const loadData = async () => {try {defaultNote.content.data = null;- setNote({...defaultNote});+ setNote({ ...defaultNote });const data = await ShareExtension.data();if (!data || data.length === 0) {setRawData({@@ -217,8 +204,8 @@ const NotesnookShare = ({quicknote = false}) => {setLoadingIntent(false);return;}- let note = {...defaultNote};- for (item of data) {+ let note = { ...defaultNote };+ for (let item of data) {if (item.type === 'text') {setRawData(item);if (isURL(item.value)) {@@ -228,7 +215,7 @@ const NotesnookShare = ({quicknote = false}) => {}}}- setNote({...note});+ setNote({ ...note });} catch (e) {}setLoadingIntent(false);};@@ -248,7 +235,7 @@ const NotesnookShare = ({quicknote = false}) => {const close = async () => {animate(0, 1000);await sleep(300);- setNote({...defaultNote});+ setNote({ ...defaultNote });setLoadingIntent(true);if (quicknote) {ShareExtension.openURL('ShareMedia://MainApp');@@ -268,7 +255,7 @@ const NotesnookShare = ({quicknote = false}) => {setTheme();`);}, 300);- let theme = {...colors};+ let theme = { ...colors };theme.factor = 1;postMessage(webviewRef, 'theme', JSON.stringify(theme));@@ -283,7 +270,7 @@ const NotesnookShare = ({quicknote = false}) => {}const onPress = async () => {- content = await getContent();+ let content = await getContent();if (!content || content === '') {return;}@@ -309,7 +296,7 @@ const NotesnookShare = ({quicknote = false}) => {sessionId: Date.now()};} else {- _note = {...note};+ _note = { ...note };_note.content.data = content;_note.sessionId = Date.now();}@@ -368,7 +355,7 @@ const NotesnookShare = ({quicknote = false}) => {html = await absolutifyImgs(html, rawData.value);setNote(note => {note.content.data = html;- return {...note};+ return { ...note };});} else {let html = isURL(rawData.value)@@ -376,7 +363,7 @@ const NotesnookShare = ({quicknote = false}) => {: makeHtmlFromPlainText(rawData.value);setNote(note => {note.content.data = html;- return {...note};+ return { ...note };});}} catch (e) {@@ -391,7 +378,7 @@ const NotesnookShare = ({quicknote = false}) => {let content = await getContent();setNote(note => {note.content.data = content + '\n' + makeHtmlFromPlainText(text);- return {...note};+ return { ...note };});}};@@ -404,7 +391,8 @@ const NotesnookShare = ({quicknote = false}) => {justifyContent: quicknote ? 'flex-start' : 'flex-end',opacity: Platform.OS !== 'ios' ? opacity : 1,alignSelf: 'center'- }}>+ }}+ >{quicknote && !showSearch ? (<Viewstyle={{@@ -417,7 +405,8 @@ const NotesnookShare = ({quicknote = false}) => {flexDirection: 'row',alignItems: 'center',justifyContent: 'space-between'- }}>+ }}+ ><Buttontype="action"icon="close"@@ -444,7 +433,8 @@ const NotesnookShare = ({quicknote = false}) => {color: colors.pri,fontSize: 17,fontFamily: 'OpenSans-Regular'- }}>+ }}+ >Quick note</Text>@@ -477,7 +467,8 @@ const NotesnookShare = ({quicknote = false}) => {width: '100%',height: '100%',position: 'absolute'- }}>+ }}+ ><Viewstyle={{width: '100%',@@ -513,17 +504,18 @@ const NotesnookShare = ({quicknote = false}) => {marginBottom: insets.top,transform: [{- translateY:- Platform.OS !== 'ios' ? translate : showSearch ? 1000 : 0+ translateY: Platform.OS !== 'ios' ? translate : showSearch ? 1000 : 0}]}}- behavior={Platform.OS === 'ios' ? 'padding' : null}>+ behavior={Platform.OS === 'ios' ? 'padding' : null}+ ><Viewstyle={{maxHeight: '100%',paddingHorizontal: 12- }}>+ }}+ ><ScrollViewhorizontalcontentContainerStyle={{@@ -535,7 +527,8 @@ const NotesnookShare = ({quicknote = false}) => {height: 45,borderRadius: 10,flexDirection: 'row'- }}>+ }}+ ><Buttoncolor={appendNote ? colors.nav : accent.color}onPress={() => {@@ -562,9 +555,7 @@ const NotesnookShare = ({quicknote = false}) => {icon="text-short"iconSize={18}iconColor={appendNote ? colors.light : colors.icon}- title={`${- appendNote ? appendNote.title.slice(0, 25) : 'Append to note'- }`}+ title={`${appendNote ? appendNote.title.slice(0, 25) : 'Append to note'}`}textColor={appendNote ? colors.light : colors.icon}type="rounded"style={{@@ -577,7 +568,8 @@ const NotesnookShare = ({quicknote = false}) => {<Viewstyle={{width: '100%'- }}>+ }}+ >{!quicknote ? (<Buttoncolor={accent.color}@@ -586,7 +578,6 @@ const NotesnookShare = ({quicknote = false}) => {icon="check"iconSize={25}type="action"- loading={loading}iconColor={colors.light}style={{position: 'absolute',@@ -606,14 +597,16 @@ const NotesnookShare = ({quicknote = false}) => {...getElevation(quicknote ? 1 : 5),backgroundColor: colors.bg,overflow: 'hidden'- }}>+ }}+ ><Viewstyle={{width: '100%',height: height * 0.25,paddingBottom: 15,borderRadius: 10- }}>+ }}+ ><WebViewonLoad={onLoad}ref={webviewRef}@@ -629,9 +622,7 @@ const NotesnookShare = ({quicknote = false}) => {bounces={false}allowFileAccess={true}scalesPageToFit={true}- allowingReadAccessToURL={- Platform.OS === 'android' ? true : null- }+ allowingReadAccessToURL={Platform.OS === 'android' ? true : null}onMessage={onMessage}onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}allowFileAccessFromFileURLs={true}@@ -641,7 +632,7 @@ const NotesnookShare = ({quicknote = false}) => {cacheEnabled={true}source={Platform.OS === 'ios'- ? {uri: sourceUri}+ ? { uri: sourceUri }: {uri: 'file:///android_asset/plaineditor.html',baseUrl: 'file:///android_asset/'@@ -659,13 +650,15 @@ const NotesnookShare = ({quicknote = false}) => {paddingHorizontal: 12,marginBottom: 10,flexWrap: 'wrap'- }}>+ }}+ >This shared note will be appended to{' '}<Textstyle={{color: accent.color,fontFamily: 'OpenSans-SemiBold'- }}>+ }}+ >"{appendNote.title}"</Text>{' '}. Click on "Create new note" to add to a new note instead.@@ -678,7 +671,8 @@ const NotesnookShare = ({quicknote = false}) => {paddingHorizontal: 12,paddingRight: 80,alignItems: 'center'- }}>+ }}+ >{rawData.value && isURL(rawData.value) ? (<Buttoncolor={mode == 2 ? colors.shade : colors.nav}@@ -689,7 +683,7 @@ const NotesnookShare = ({quicknote = false}) => {iconColor={mode == 2 ? accent.color : colors.icon}textColor={mode == 2 ? accent.color : colors.icon}type="rounded"- style={{paddingHorizontal: 12}}+ style={{ paddingHorizontal: 12 }}/>) : null}<Button@@ -701,7 +695,7 @@ const NotesnookShare = ({quicknote = false}) => {iconColor={mode == 1 ? accent.color : colors.icon}textColor={mode == 1 ? accent.color : colors.icon}type="rounded"- style={{paddingHorizontal: 12}}+ style={{ paddingHorizontal: 12 }}/></View></View>@@ -789,12 +783,11 @@ const Button = ({},types[type].style,style- ]}>+ ]}+ >{loading ? <ActivityIndicator color={iconColor} /> : null}- {icon && !loading ? (- <Icon name={icon} size={iconSize} color={iconColor || 'white'} />- ) : null}+ {icon && !loading ? <Icon name={icon} size={iconSize} color={iconColor || 'white'} /> : null}{title ? (<Text@@ -807,7 +800,8 @@ const Button = ({},textStyle,types[type].textStyle- ]}>+ ]}+ >{title}</Text>) : null}diff --git a/apps/mobile/src/utils/linkpreview.ts b/apps/mobile/src/utils/linkpreview.tsdeleted file mode 100644index c855654fc..000000000--- a/apps/mobile/src/utils/linkpreview.ts+++ /dev/null@@ -1,248 +0,0 @@-import { Image } from 'react-native';-import { decode, EntityLevel } from 'entities';-export interface PreviewData {- description?: string;- image?: PreviewDataImage;- link?: string;- title?: string;-}--export interface PreviewDataImage {- height: number;- url: string;- width: number;-}--export interface Size {- height: number;- width: number;-}--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, {- level: EntityLevel.HTML- });-};--export const getContent = (left: string, right: string, type: string) => {- const contents = {- [left.trim()]: right,- [right.trim()]: left- };-- return contents[type]?.trim();-};--const getDiffUrl = actualImageUrl => {- if (!actualImageUrl.startsWith('https://www.') || !actualImageUrl.startsWith('http://www.')) {- if (actualImageUrl.startsWith('http://')) {- actualImageUrl = actualImageUrl.replace('http://', 'http://www.');- } else {- actualImageUrl = actualImageUrl.replace('https://', 'https://www.');- }- }- return actualImageUrl;-};--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 => {- if (getDiffUrl(url) === url) {- reject(error);- } else {- let urlWithwww = getDiffUrl(url);- Image.getSize(- urlWithwww,- (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 getLinkPreview = async (text: string) => {- 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;- }- let abortControllerTimeout: NodeJS.Timeout = null;- const abort = new AbortController();- // Abort fetch request after 5 seconds.-- let 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: abort.signal- });- abortControllerTimeout = setTimeout(() => {- abort.abort();- }, 10000);- let 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;diff --git a/apps/mobile/src/views/Editor/tiny/toolbar/linkpreview.js b/apps/mobile/src/views/Editor/tiny/toolbar/linkpreview.jsindex fd7941d2c..5998916c7 100644--- a/apps/mobile/src/views/Editor/tiny/toolbar/linkpreview.js+++ b/apps/mobile/src/views/Editor/tiny/toolbar/linkpreview.js@@ -1,3 +1,4 @@+import { getLinkPreview } from 'link-preview-js';import React, { useEffect, useState } from 'react';import { Image, Linking, ScrollView, TouchableOpacity, View } from 'react-native';import Icon from 'react-native-vector-icons/MaterialCommunityIcons';@@ -12,7 +13,6 @@ import isEmail from 'validator/lib/isEmail';import isURL from 'validator/lib/isURL';import isMobilePhone from 'validator/lib/isMobilePhone';import { ToastEvent } from '../../../../services/EventManager';-import { getLinkPreview } from '../../../../utils/linkpreview';let prevLink = {};const LinkPreview = ({ setMode, value, onSubmit }) => {@@ -25,23 +25,24 @@ const LinkPreview = ({ setMode, value, onSubmit }) => {if (value && prevLink.value !== value) {getLinkPreview(value).then(r => {- prevLink = {- value: value,- name: r.siteName,- title: r.title,- description: r.description,- image: r.image- };- setLink(prevLink);+ if (r.contentType?.includes('text/html')) {+ prevLink = {+ value: value,+ name: r.siteName,+ title: r.title,+ description: r.description,+ image: r.images && r.images[0],+ favicon: r.favicons && r.favicons[0]+ };+ setLink(prevLink);+ }})- .catch(e => {- console.log(e);- });+ .catch(console.log);}}, [value]);- const renderImage = image => {- return image ? (+ const renderImage = (imageLink, faviconLink) => {+ return imageLink ? (<Imagestyle={{width: 35,@@ -54,8 +55,27 @@ const LinkPreview = ({ setMode, value, onSubmit }) => {marginRight: 5}}resizeMode="contain"- source={{ uri: image }}+ source={{ uri: imageLink }}/>+ ) : faviconLink ? (+ <View+ style={{+ borderColor: colors.nav,+ backgroundColor: colors.nav,+ borderWidth: 1,+ marginVertical: 5,+ borderRadius: 5+ }}+ >+ <Image+ style={{+ width: 35,+ height: 35+ }}+ resizeMode="center"+ source={{ uri: faviconLink }}+ />+ </View>) : (<Viewstyle={{@@ -64,7 +84,7 @@ const LinkPreview = ({ setMode, value, onSubmit }) => {marginVertical: 5,justifyContent: 'center',alignItems: 'center',- backgroundColor: colors.nav,+ backgroundColor: colors.shade,borderRadius: 5}}>@@ -91,8 +111,8 @@ const LinkPreview = ({ setMode, value, onSubmit }) => {if (isURL(value)) {openLinkInBrowser(value, colors)- .catch(e => {})- .then(async r => {+ .catch(console.log)+ .then(async () => {console.log('closed browser now');await reFocusEditor();});@@ -148,7 +168,7 @@ const LinkPreview = ({ setMode, value, onSubmit }) => {alignItems: 'center'}}>- {renderImage(link.image)}+ {renderImage(link.image, link.favicon)}{renderText(link.name, link.title, link.description)}<View