Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

refactor

ammarahm-ed65830c81ab2b
diff --git a/apps/mobile/patches/html-to-text+8.1.0.patch b/apps/mobile/patches/html-to-text+8.1.0.patch
new file mode 100644
index 000000000..418da0645
--- /dev/null
+++ b/apps/mobile/patches/html-to-text+8.1.0.patch
@@ -0,0 +1,49 @@
+diff --git a/node_modules/html-to-text/lib/formatter.js b/node_modules/html-to-text/lib/formatter.js
+index d6cb1e6..68d0337 100644
+--- a/node_modules/html-to-text/lib/formatter.js
++++ b/node_modules/html-to-text/lib/formatter.js
+@@ -1,4 +1,4 @@
+-const he = require('he');
++const {decode} = require('entities');
+
+ const { get, numberToLetterSequence, numberToRoman, splitClassesAndIds, trimCharacter } = require('./helper');
+
+@@ -146,7 +146,7 @@ function withBrackets (str, brackets) {
+ function formatImage (elem, walk, builder, formatOptions) {
+ const attribs = elem.attribs || {};
+ const alt = (attribs.alt)
+- ? he.decode(attribs.alt, builder.options.decodeOptions)
++ ? decode(attribs.alt, builder.options.decodeOptions)
+ : '';
+ const src = (!attribs.src)
+ ? ''
+@@ -176,7 +176,7 @@ function formatAnchor (elem, walk, builder, formatOptions) {
+ href = (formatOptions.baseUrl && href[0] === '/')
+ ? formatOptions.baseUrl + href
+ : href;
+- return he.decode(href, builder.options.decodeOptions);
++ return decode(href, builder.options.decodeOptions);
+ }
+ const href = getHref();
+ if (!href) {
+diff --git a/node_modules/html-to-text/lib/html-to-text.js b/node_modules/html-to-text/lib/html-to-text.js
+index 9ebda73..330a28c 100644
+--- a/node_modules/html-to-text/lib/html-to-text.js
++++ b/node_modules/html-to-text/lib/html-to-text.js
+@@ -1,6 +1,6 @@
+ const { hp2Builder } = require('@selderee/plugin-htmlparser2');
+ const merge = require('deepmerge');
+-const he = require('he');
++const {decode} = require("entities");
+ const htmlparser = require('htmlparser2');
+ const selderee = require('selderee');
+
+@@ -377,7 +377,7 @@ function recursiveWalk (walk, dom, builder) {
+ for (const elem of dom) {
+ switch (elem.type) {
+ case 'text': {
+- builder.addInline(he.decode(elem.data, options.decodeOptions));
++ builder.addInline(decode(elem.data, options.decodeOptions));
+ break;
+ }
+ case 'tag': {
diff --git a/apps/mobile/share/index.js b/apps/mobile/share/index.js
index b1c15dd2c..d1735514a 100644
--- a/apps/mobile/share/index.js
+++ b/apps/mobile/share/index.js
@@ -1,6 +1,6 @@
import Clipboard from '@react-native-clipboard/clipboard';
import absolutify from 'absolutify';
-import {getLinkPreview} from 'link-preview-js';
+import { getLinkPreview } from '../src/utils/linkpreview';
import React, {useEffect, useRef, useState} from 'react';
import {ScrollView} from 'react-native';
import {
@@ -67,27 +67,28 @@ function getBaseUrl(site) {
var url = site.split('/').slice(0, 3).join('/');
return url;
}
-
-async function absolutifyImgs(html, site) {
- let parser = require('jsdom-jscore-rn').html();
- parser.body.innerHTML = html;
+function absolutifyImgs(html, site) {
+ let {parse} = require('node-html-parser');
+ let parser = parse(html);
let images = parser.querySelectorAll('img');
for (var i = 0; i < images.length; i++) {
let img = images[i];
let url = getBaseUrl(site);
- if (img.src.startsWith('/')) {
- if (img.src.startsWith('//')) {
- img.src = img.src.replace('//', 'https://');
+ let src = img.getAttribute('src');
+ if (src.startsWith('/')) {
+ if (src.startsWith('//')) {
+ src = src.replace('//', 'https://');
} else {
- img.src = url + img.src;
+ src = url + src;
}
}
- if (img.src.startsWith('data:')) {
- img.src = '';
+ if (src.startsWith('data:')) {
+ src = '';
}
+ img.setAttribute('src', src);
}
- return parser.body.innerHTML;
+ return parser.outerHTML;
}
let defaultNote = {
@@ -197,7 +198,7 @@ const NotesnookShare = ({quicknote = false}) => {
_note.content.data = makeHtmlFromUrl(link);
try {
let preview = await getLinkPreview(link);
- _note.title = preview.siteName || preview.title;
+ _note.title = preview.title;
} catch (e) {
console.log(e);
}
@@ -290,7 +291,6 @@ const NotesnookShare = ({quicknote = false}) => {
await db.init();
await db.notes.init();
-
if (appendNote && !db.notes.note(appendNote.id)) {
useShareStore.getState().setAppendNote(null);
Alert.alert('The note you are trying to append to has been deleted.');
@@ -306,7 +306,7 @@ const NotesnookShare = ({quicknote = false}) => {
type: 'tiny'
},
id: appendNote.id,
- sessionId:Date.now()
+ sessionId: Date.now()
};
} else {
_note = {...note};
diff --git a/apps/mobile/src/services/Exporter.js b/apps/mobile/src/services/Exporter.js
index 874ebfd25..d1d04b528 100644
--- a/apps/mobile/src/services/Exporter.js
+++ b/apps/mobile/src/services/Exporter.js
@@ -1,14 +1,14 @@
-import { Platform } from 'react-native';
+import { decode } from 'entities';
+import {Platform} from 'react-native';
import RNHTMLtoPDF from 'react-native-html-to-pdf-lite';
import * as ScopedStorage from 'react-native-scoped-storage';
import RNFetchBlob from 'rn-fetch-blob';
import showdown from 'showdown';
-import { toTXT } from '../utils';
-import { db } from '../utils/database';
-import { sanitizeFilename } from '../utils/filename';
+import {toTXT} from '../utils';
+import {db} from '../utils/database';
+import {sanitizeFilename} from '../utils/filename';
import Storage from '../utils/storage';
-
const defaultStyle = `<style>
.img_size_one {
width:100%;
@@ -324,8 +324,7 @@ async function saveToPDF(note) {
Platform.OS === 'ios' && (await Storage.checkAndCreateDir('/exported/PDF/'));
let html = await db.notes.note(note).export('html');
- let he = require('he');
- html = he.decode(html);
+ html = decode(html);
let fileName = sanitizeFilename(note.title + Date.now(), {replacement: '_'});
let html3 = html;
if (html.indexOf('<head>') > -1) {
@@ -382,16 +381,7 @@ async function saveToMarkdown(note) {
path = file.uri;
}
-
- let converter = new showdown.Converter();
- converter.setFlavor('original');
- let jsdom = require('jsdom-jscore-rn');
- let dom = jsdom.html();
- let content = await db.notes.note(note.id).content();
- let markdown = converter.makeMarkdown(content, dom);
-
- markdown = await db.notes.note(note.id).export('md', markdown);
-
+ let markdown = await db.notes.note(note.id).export('md', markdown);
let fileName = sanitizeFilename(note.title + Date.now(), {replacement: '_'});
let fileUri;
diff --git a/apps/mobile/src/utils/linkpreview.ts b/apps/mobile/src/utils/linkpreview.ts
new file mode 100644
index 000000000..b48ae7e0a
--- /dev/null
+++ b/apps/mobile/src/utils/linkpreview.ts
@@ -0,0 +1,262 @@
+import {Image} from 'react-native';
+import {decode} 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);
+};
+
+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.js
index ea206fa88..6e828c3e2 100644
--- a/apps/mobile/src/views/Editor/tiny/toolbar/linkpreview.js
+++ b/apps/mobile/src/views/Editor/tiny/toolbar/linkpreview.js
@@ -1,4 +1,3 @@
-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';
@@ -11,8 +10,9 @@ import {SIZE} from '../../../../utils/SizeUtils';
import {INPUT_MODE, properties, reFocusEditor} from './constants';
import isEmail from 'validator/lib/isEmail';
import isURL from 'validator/lib/isURL';
-import isMobilePhone from "validator/lib/isMobilePhone";
-import { ToastEvent } from '../../../../services/EventManager';
+import isMobilePhone from 'validator/lib/isMobilePhone';
+import {ToastEvent} from '../../../../services/EventManager';
+import {getLinkPreview} from '../../../../utils/linkpreview';
let prevLink = {};
const LinkPreview = ({setMode, value, onSubmit}) => {
@@ -25,17 +25,14 @@ const LinkPreview = ({setMode, value, onSubmit}) => {
if (value && prevLink.value !== value) {
getLinkPreview(value)
.then(r => {
- if (r.contentType?.includes('text/html')) {
- prevLink = {
- value: value,
- name: r.siteName,
- title: r.title,
- description: r.description,
- image: r.images[0],
- favicon: r.favicons[0]
- };
- setLink(prevLink);
- }
+ prevLink = {
+ value: value,
+ name: r.siteName,
+ title: r.title,
+ description: r.description,
+ image: r.image
+ };
+ setLink(prevLink);
})
.catch(e => console.log);
}
@@ -92,8 +89,11 @@ const LinkPreview = ({setMode, value, onSubmit}) => {
};
const openLink = () => {
-
- if (value.startsWith("mailto:") || value.startsWith("tel:") || value.startsWith("sms:")) {
+ if (
+ value.startsWith('mailto:') ||
+ value.startsWith('tel:') ||
+ value.startsWith('sms:')
+ ) {
Linking.openURL(value).catch(console.log);
return;
}
@@ -117,9 +117,9 @@ const LinkPreview = ({setMode, value, onSubmit}) => {
});
} else {
ToastEvent.show({
- heading:"Url not valid",
- message:value,
- type:'error'
+ heading: 'Url not valid',
+ message: value,
+ type: 'error'
});
}
};
diff --git a/apps/mobile/src/views/Home/index.js b/apps/mobile/src/views/Home/index.js
index 673b90dae..b460111e8 100755
--- a/apps/mobile/src/views/Home/index.js
+++ b/apps/mobile/src/views/Home/index.js
@@ -1,19 +1,20 @@
-import React, { useCallback, useEffect } from 'react';
-import { ContainerBottomButton } from '../../components/Container/ContainerBottomButton';
-import { ContainerTopSection } from '../../components/Container/ContainerTopSection';
-import { Header } from '../../components/Header/index';
+import React, {useCallback, useEffect} from 'react';
+import {ContainerBottomButton} from '../../components/Container/ContainerBottomButton';
+import {ContainerTopSection} from '../../components/Container/ContainerTopSection';
+import {Header} from '../../components/Header/index';
import SelectionHeader from '../../components/SelectionHeader';
import SimpleList from '../../components/SimpleList';
-import { useNoteStore } from '../../provider/stores';
-import { DDS } from '../../services/DeviceDetection';
-import { eSendEvent } from '../../services/EventManager';
+import {useNoteStore} from '../../provider/stores';
+import {DDS} from '../../services/DeviceDetection';
+import {eSendEvent} from '../../services/EventManager';
import Navigation from '../../services/Navigation';
import SearchService from '../../services/SearchService';
-import { editing, InteractionManager, scrollRef } from '../../utils';
-import { db } from '../../utils/database';
-import { eOnLoadNote } from '../../utils/Events';
-import { tabBarRef } from '../../utils/Refs';
-import { getNote } from '../Editor/Functions';
+import {editing, InteractionManager, scrollRef} from '../../utils';
+import {db} from '../../utils/database';
+import {eOnLoadNote} from '../../utils/Events';
+import {getLinkPreview} from '../../utils/linkpreview';
+import {tabBarRef} from '../../utils/Refs';
+import {getNote} from '../Editor/Functions';
export const Home = ({navigation}) => {
const notes = useNoteStore(state => state.notes);
@@ -31,12 +32,12 @@ export const Home = ({navigation}) => {
Navigation.setHeaderState(
'Notes',
{
- menu: true,
+ menu: true
},
{
heading: 'Notes',
- id: 'notes_navigation',
- },
+ id: 'notes_navigation'
+ }
);
}, []);
@@ -74,16 +75,23 @@ export const Home = ({navigation}) => {
placeholder: 'Type a keyword to search in notes',
data: db?.notes?.all,
type: 'notes',
- title: 'Notes',
+ title: 'Notes'
});
};
const _onPressBottomButton = React.useCallback(async () => {
+ getLinkPreview('https://google.com')
+ .then(r => {
+ console.log(r);
+ })
+ .catch(console.log);
+ return;
+
if (!DDS.isTab) {
if (getNote()) {
- eSendEvent(eOnLoadNote, {type: 'new'});
- editing.currentlyEditing = true;
- editing.movedAway = false;
+ eSendEvent(eOnLoadNote, {type: 'new'});
+ editing.currentlyEditing = true;
+ editing.movedAway = false;
}
tabBarRef.current?.goToPage(1);
} else {
@@ -113,7 +121,7 @@ export const Home = ({navigation}) => {
loading={loading}
sortMenuButton={true}
headerProps={{
- heading: 'Notes',
+ heading: 'Notes'
}}
placeholderText={`Notes you write appear here`}
jumpToDialog={true}
@@ -122,7 +130,7 @@ export const Home = ({navigation}) => {
paragraph: 'You have not added any notes yet.',
button: 'Add your first note',
action: _onPressBottomButton,
- loading: 'Loading your notes.',
+ loading: 'Loading your notes.'
}}
/>