Skip to content

Commit

Permalink
Copying the link to an attachment should make sure that it is located…
Browse files Browse the repository at this point in the history
… in the same note folder -> Fixes BoostIO#1924
  • Loading branch information
ehhc committed May 29, 2018
1 parent ca0b03e commit 9c247bc
Show file tree
Hide file tree
Showing 21 changed files with 364 additions and 34 deletions.
29 changes: 18 additions & 11 deletions browser/components/CodeEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import convertModeName from 'browser/lib/convertModeName'
import eventEmitter from 'browser/main/lib/eventEmitter'
import iconv from 'iconv-lite'

const { ipcRenderer } = require('electron')
const {ipcRenderer} = require('electron')

CodeMirror.modeURL = '../node_modules/codemirror/mode/%N/%N.js'

const defaultEditorFontFamily = ['Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace']
const buildCMRulers = (rulers, enableRulers) =>
enableRulers ? rulers.map(ruler => ({ column: ruler })) : []
enableRulers ? rulers.map(ruler => ({column: ruler})) : []

export default class CodeEditor extends React.Component {
constructor (props) {
Expand Down Expand Up @@ -80,7 +80,7 @@ export default class CodeEditor extends React.Component {
}

componentDidMount () {
const { rulers, enableRulers } = this.props
const {rulers, enableRulers} = this.props
this.value = this.props.value

this.editor = CodeMirror(this.refs.root, {
Expand Down Expand Up @@ -174,7 +174,7 @@ export default class CodeEditor extends React.Component {

componentDidUpdate (prevProps, prevState) {
let needRefresh = false
const { rulers, enableRulers } = this.props
const {rulers, enableRulers} = this.props
if (prevProps.mode !== this.props.mode) {
this.setMode(this.props.mode)
}
Expand Down Expand Up @@ -274,6 +274,7 @@ export default class CodeEditor extends React.Component {

handlePaste (editor, e) {
const clipboardData = e.clipboardData
const {storageKey, noteKey} = this.props
const dataTransferItem = clipboardData.items[0]
const pastedTxt = clipboardData.getData('text')
const isURL = (str) => {
Expand All @@ -283,22 +284,28 @@ export default class CodeEditor extends React.Component {
const isInLinkTag = (editor) => {
const startCursor = editor.getCursor('start')
const prevChar = editor.getRange(
{ line: startCursor.line, ch: startCursor.ch - 2 },
{ line: startCursor.line, ch: startCursor.ch }
{line: startCursor.line, ch: startCursor.ch - 2},
{line: startCursor.line, ch: startCursor.ch}
)
const endCursor = editor.getCursor('end')
const nextChar = editor.getRange(
{ line: endCursor.line, ch: endCursor.ch },
{ line: endCursor.line, ch: endCursor.ch + 1 }
{line: endCursor.line, ch: endCursor.ch},
{line: endCursor.line, ch: endCursor.ch + 1}
)
return prevChar === '](' && nextChar === ')'
}
if (dataTransferItem.type.match('image')) {
const {storageKey, noteKey} = this.props
attachmentManagement.handlePastImageEvent(this, storageKey, noteKey, dataTransferItem)
} else if (this.props.fetchUrlTitle && isURL(pastedTxt) && !isInLinkTag(editor)) {
this.handlePasteUrl(e, editor, pastedTxt)
}
if (attachmentManagement.isAttachmentLink(pastedTxt)) {
attachmentManagement.handleAttachmentLinkPaste(storageKey, noteKey, pastedTxt)
.then((modifiedText) => {
this.editor.replaceSelection(modifiedText)
})
e.preventDefault()
}
}

handleScroll (e) {
Expand All @@ -322,7 +329,7 @@ export default class CodeEditor extends React.Component {
const cursor = editor.getCursor()
const LinkWithTitle = `[${parsedResponse.title}](${pastedTxt})`
const newValue = value.replace(taggedUrl, LinkWithTitle)
const newCursor = Object.assign({}, cursor, { ch: cursor.ch + newValue.length - value.length })
const newCursor = Object.assign({}, cursor, {ch: cursor.ch + newValue.length - value.length})
editor.setValue(newValue)
editor.setCursor(newCursor)
}).catch((e) => {
Expand Down Expand Up @@ -360,7 +367,7 @@ export default class CodeEditor extends React.Component {
}

render () {
const { className, fontSize } = this.props
const {className, fontSize} = this.props
let fontFamily = this.props.fontFamily
fontFamily = _.isString(fontFamily) && fontFamily.length > 0
? [fontFamily].concat(defaultEditorFontFamily)
Expand Down
77 changes: 73 additions & 4 deletions browser/main/lib/dataApi/attachmentManagement.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const mdurl = require('mdurl')
const fse = require('fs-extra')
const escapeStringRegexp = require('escape-string-regexp')
const sander = require('sander')
import i18n from 'browser/lib/i18n'

const STORAGE_FOLDER_PLACEHOLDER = ':storage'
const DESTINATION_FOLDER = 'attachments'
Expand Down Expand Up @@ -258,7 +259,7 @@ function deleteAttachmentsNotPresentInNote (markdownContent, storageKey, noteKey
if (fs.existsSync(attachmentFolder)) {
fs.readdir(attachmentFolder, (err, files) => {
if (err) {
console.error("Error reading directory '" + attachmentFolder + "'. Error:")
console.error('Error reading directory "' + attachmentFolder + '". Error:')
console.error(err)
return
}
Expand All @@ -267,17 +268,17 @@ function deleteAttachmentsNotPresentInNote (markdownContent, storageKey, noteKey
const absolutePathOfFile = path.join(targetStorage.path, DESTINATION_FOLDER, noteKey, file)
fs.unlink(absolutePathOfFile, (err) => {
if (err) {
console.error("Could not delete '%s'", absolutePathOfFile)
console.error('Could not delete "%s"', absolutePathOfFile)
console.error(err)
return
}
console.info("File '" + absolutePathOfFile + "' deleted because it was not included in the content of the note")
console.info('File "' + absolutePathOfFile + '" deleted because it was not included in the content of the note')
})
}
})
})
} else {
console.info("Attachment folder ('" + attachmentFolder + "') did not exist..")
console.info('Attachment folder ("' + attachmentFolder + '") did not exist..')
}
}

Expand Down Expand Up @@ -308,6 +309,71 @@ function cloneAttachments (oldNote, newNote) {
}
}

function generateFileNotFoundMarkdown () {
return '**' + i18n.__('⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠') + '**'
}

/**
* Determines whether a given text is a link to an boostnote attachment
* @param text Text that might contain a attachment link
* @return {Boolean} Result of the test
*/
function isAttachmentLink (text) {
if (text) {
return text.match(new RegExp('.*\\[.*\\]\\( *' + escapeStringRegexp(STORAGE_FOLDER_PLACEHOLDER) + escapeStringRegexp(path.sep) + '.*\\).*', 'gi')) != null
}
return false
}

/**
* @description Handles the paste of an attachment link. Copies the referenced attachment to the location belonging to the new note.
* Returns a modified version of the pasted text so that it matches the copied attachment (resp. the new location)
* @param storageKey StorageKey of the current note
* @param noteKey NoteKey of the currentNote
* @param linkText Text that was pasted
* @return {Promise<String>} Promise returning the modified text
*/
function handleAttachmentLinkPaste (storageKey, noteKey, linkText) {
if (storageKey != null && noteKey != null && linkText != null) {
const storagePath = findStorage.findStorage(storageKey).path
const attachments = getAttachmentsInContent(linkText) || []
const replaceInstructions = []
const copies = []
for (const attachment of attachments) {
const absPathOfAttachment = attachment.replace(new RegExp(STORAGE_FOLDER_PLACEHOLDER, 'g'), path.join(storagePath, DESTINATION_FOLDER))
copies.push(
sander.exists(absPathOfAttachment)
.then((fileExists) => {
if (!fileExists) {
const fileNotFoundRegexp = new RegExp('!?' + escapeStringRegexp('[') + '[\\w|\\d|\\s|\\.]*\\]\\(\\s*' + STORAGE_FOLDER_PLACEHOLDER + '[\\w|\\d|\\-|' + escapeStringRegexp(path.sep) + ']*' + escapeStringRegexp(path.basename(absPathOfAttachment)) + escapeStringRegexp(')'))
replaceInstructions.push({regexp: fileNotFoundRegexp, replacement: this.generateFileNotFoundMarkdown()})
return Promise.resolve()
}
return this.copyAttachment(absPathOfAttachment, storageKey, noteKey)
.then((fileName) => {
const replaceLinkRegExp = new RegExp(escapeStringRegexp('(') + ' *' + STORAGE_FOLDER_PLACEHOLDER + '[\\w|\\d|\\-|' + escapeStringRegexp(path.sep) + ']*' + escapeStringRegexp(path.basename(absPathOfAttachment)) + ' *' + escapeStringRegexp(')'))
replaceInstructions.push({
regexp: replaceLinkRegExp,
replacement: '(' + path.join(STORAGE_FOLDER_PLACEHOLDER, noteKey, fileName) + ')'
})
return Promise.resolve()
})
})
)
}
return Promise.all(copies).then(() => {
let modifiedLinkText = linkText
for (const replaceInstruction of replaceInstructions) {
modifiedLinkText = modifiedLinkText.replace(replaceInstruction.regexp, replaceInstruction.replacement)
}
return modifiedLinkText
})
} else {
console.log('One if the parameters was null -> Do nothing..')
return Promise.resolve(linkText)
}
}

module.exports = {
copyAttachment,
fixLocalURLS,
Expand All @@ -321,6 +387,9 @@ module.exports = {
deleteAttachmentsNotPresentInNote,
moveAttachments,
cloneAttachments,
isAttachmentLink,
handleAttachmentLinkPaste,
generateFileNotFoundMarkdown,
STORAGE_FOLDER_PLACEHOLDER,
DESTINATION_FOLDER
}
3 changes: 2 additions & 1 deletion locales/da.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,6 @@
"Sanitization": "Sanitization",
"Only allow secure html tags (recommended)": "Only allow secure html tags (recommended)",
"Allow styles": "Allow styles",
"Allow dangerous html tags": "Allow dangerous html tags"
"Allow dangerous html tags": "Allow dangerous html tags",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -205,5 +205,6 @@
"Unnamed": "Unbenannt",
"Rename": "Umbenennen",
"Folder Name": "Ordnername",
"No tags": "Keine Tags"
"No tags": "Keine Tags",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -174,5 +174,6 @@
"Only allow secure html tags (recommended)": "Only allow secure html tags (recommended)",
"Render newlines in Markdown paragraphs as <br>": "Render newlines in Markdown paragraphs as <br>",
"Allow styles": "Allow styles",
"Allow dangerous html tags": "Allow dangerous html tags"
"Allow dangerous html tags": "Allow dangerous html tags",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/es-ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,6 @@
"Sanitization": "Saneamiento",
"Only allow secure html tags (recommended)": "Solo permitir etiquetas html seguras (recomendado)",
"Allow styles": "Permitir estilos",
"Allow dangerous html tags": "Permitir etiquetas html peligrosas"
"Allow dangerous html tags": "Permitir etiquetas html peligrosas",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/fa.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,5 +153,6 @@
"Sanitization": "پاکسازی کردن",
"Only allow secure html tags (recommended)": "(فقط تگ های امن اچ تی ام ال مجاز اند.(پیشنهاد میشود",
"Allow styles": "حالت های مجاز",
"Allow dangerous html tags": "تگ های خطرناک اچ‌ تی ام ال مجاز اند"
"Allow dangerous html tags": "تگ های خطرناک اچ‌ تی ام ال مجاز اند",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,6 @@
"Sanitization": "Sanitization",
"Only allow secure html tags (recommended)": "Only allow secure html tags (recommended)",
"Allow styles": "Allow styles",
"Allow dangerous html tags": "Allow dangerous html tags"
"Allow dangerous html tags": "Allow dangerous html tags",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/hu.json
Original file line number Diff line number Diff line change
Expand Up @@ -174,5 +174,6 @@
"Only allow secure html tags (recommended)": "Csak a biztonságos html tag-ek engedélyezése (ajánlott)",
"Render newlines in Markdown paragraphs as <br>": "Az újsor karaktert <br> soremelésként jelenítse meg a Markdown jegyzetekben",
"Allow styles": "Stílusok engedélyezése",
"Allow dangerous html tags": "Veszélyes html tag-ek engedélyezése"
"Allow dangerous html tags": "Veszélyes html tag-ek engedélyezése",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
5 changes: 3 additions & 2 deletions locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,5 +153,6 @@
"Sanitization": "Bonifica",
"Only allow secure html tags (recommended)": "Consenti solo tag HTML sicuri (raccomandato)",
"Allow styles": "Consenti stili",
"Allow dangerous html tags": "Consenti tag HTML pericolosi"
}"
"Allow dangerous html tags": "Consenti tag HTML pericolosi",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,6 @@
"Sanitization": "サニタイズ",
"Only allow secure html tags (recommended)": "安全なHTMLタグのみ利用を許可する(推奨)",
"Allow styles": "スタイルを許可する",
"Allow dangerous html tags": "安全でないHTMLタグの利用を許可する"
"Allow dangerous html tags": "安全でないHTMLタグの利用を許可する",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -156,5 +156,6 @@
"Sanitization": "허용 태그 범위",
"Only allow secure html tags (recommended)": "안전한 HTML 태그만 허용 (추천)",
"Allow styles": "style 태그, 속성까지 허용",
"Allow dangerous html tags": "모든 위험한 태그 허용"
"Allow dangerous html tags": "모든 위험한 태그 허용",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/no.json
Original file line number Diff line number Diff line change
Expand Up @@ -149,5 +149,6 @@
"Sanitization": "Sanitization",
"Only allow secure html tags (recommended)": "Only allow secure html tags (recommended)",
"Allow styles": "Allow styles",
"Allow dangerous html tags": "Allow dangerous html tags"
"Allow dangerous html tags": "Allow dangerous html tags",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
3 changes: 2 additions & 1 deletion locales/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -149,5 +149,6 @@
"Sanitization": "Sanitization",
"Only allow secure html tags (recommended)": "Only allow secure html tags (recommended)",
"Allow styles": "Allow styles",
"Allow dangerous html tags": "Allow dangerous html tags"
"Allow dangerous html tags": "Allow dangerous html tags",
"⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠": "⚠ You have pasted a link referring an attachment that could not be found in the storage location of this note. Pasting links referring attachments is only supported if the source and destination location is the same storage. Please Drag&Drop the attachment instead! ⚠"
}
Loading

0 comments on commit 9c247bc

Please sign in to comment.