Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ImageResolver.js « services « src - github.com/nextcloud/text.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fdad0b06293aa998b9186b5d675330b08a873d60 (plain)
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
226
227
228
229
230
231
/*
 * @copyright Copyright (c) 2022 Max <max@nextcloud.com>
 *
 * @author Max <max@nextcloud.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

import { generateUrl, generateRemoteUrl } from '@nextcloud/router'
import pathNormalize from 'path-normalize'

export default class ImageResolver {

	#session
	#user
	#shareToken
	#currentDirectory
	#attachmentDirectory

	constructor({ session, user, shareToken, currentDirectory, fileId }) {
		this.#session = session
		this.#user = user
		this.#shareToken = shareToken
		this.#currentDirectory = currentDirectory
		fileId ||= session?.documentId
		this.#attachmentDirectory = `.attachments.${fileId}`
	}

	/*
	 * Resolve a given src.
	 * @param { string } the original src in the node.
	 * @returns { Array<string> } - resolved urls to try.
	 *
	 * Currently returns either one or two urls.
	 */
	resolve(src) {
		if (this.#session && src.startsWith('text://')) {
			const imageFileName = getQueryVariable(src, 'imageFileName')
			return [this.#getAttachmentUrl(imageFileName)]
		}

		if (this.#session && src.startsWith(`.attachments.${this.#session?.documentId}/`)) {
			const imageFileName = decodeURIComponent(src.replace(`.attachments.${this.#session?.documentId}/`, '').split('?')[0])
			return [this.#getAttachmentUrl(imageFileName)]
		}

		if (isDirectUrl(src)) {
			return [src]
		}

		if (hasPreview(src)) { // && this.#mime !== 'image/gif') {
			return [this.#previewUrl(src)]
		}

		// if it starts with '.attachments.1234/'
		if (src.match(/^\.attachments\.\d+\//)) {
			const imageFileName = this.#relativePath(src)
				.replace(/\.attachments\.\d+\//, '')
			const attachmentUrl = this.#getAttachmentUrl(imageFileName)
			// try the webdav url and attachment API if the fails
			return [this.#davUrl(src), attachmentUrl]
		}

		return [this.#davUrl(src)]
	}

	#getAttachmentUrl(imageFileName) {
		if (!this.#session) {
			return this.#davUrl(
				`${this.#attachmentDirectory}/${imageFileName}`
			)
		}

		if (this.#user || !this.#shareToken) {
			return generateUrl('/apps/text/image?documentId={documentId}&sessionId={sessionId}&sessionToken={sessionToken}&imageFileName={imageFileName}', {
				...this.#textApiParams(),
				imageFileName,
			})
		}

		return generateUrl('/apps/text/image?documentId={documentId}&sessionId={sessionId}&sessionToken={sessionToken}&imageFileName={imageFileName}&shareToken={shareToken}', {
			...this.#textApiParams(),
			imageFileName,
			shareToken: this.#shareToken,
		})
	}

	#textApiParams() {
		if (this.#session) {
			return {
				documentId: this.#session.documentId,
				sessionId: this.#session.id,
				sessionToken: this.#session.token,
			}
		}

		return {}
	}

	#previewUrl(src) {
		const imageFileId = getQueryVariable(src, 'fileId')
		const path = this.#filePath(src)
		const fileQuery = `file=${encodeURIComponent(path)}`
		const query = fileQuery + '&x=1024&y=1024&a=true'

		if (this.#user && imageFileId) {
			return generateUrl(`/core/preview?fileId=${imageFileId}&${query}`)
		}

		if (this.#user) {
			return generateUrl(`/core/preview.png?${query}`)
		}

		if (this.#shareToken) {
			return generateUrl(`/apps/files_sharing/publicpreview/${this.#shareToken}?${query}`)
		}

		console.error('No way to authenticate image retrival - need to be logged in or provide a token')
		return src
	}

	#davUrl(src) {
		if (this.#user) {
			const uid = this.#user.uid
			const encoded = encodeURI(this.#filePath(src))
			return generateRemoteUrl(`dav/files/${uid}${encoded}`)
		}

		const path = this.#filePath(src).split('/')
		const basename = path.pop()
		const dirname = path.join('/')

		return generateUrl('/s/{token}/download?path={dirname}&files={basename}', {
			token: this.#shareToken,
			basename,
			dirname,
		})
	}

	/**
	 * Return the relativePath to a file specified in the url
	 *
	 * @param {string} src - url to extract path from
	 */
	#relativePath(src) {
		if (src.startsWith('text://')) {
			return [
				this.#attachmentDirectory,
				getQueryVariable(src, 'imageFileName'),
			].join('/')
		}

		return decodeURI(src.split('?')[0])
	}

	#filePath(src) {
		const f = [
			this.#currentDirectory,
			this.#relativePath(src),
		].join('/')

		return pathNormalize(f)
	}

}

/**
 * Check if a url can be loaded directly - i.e. is one of
 * - remote url
 * - data url
 * - preview url
 *
 * @param {string} src - the url to check
 */
function isDirectUrl(src) {
	return src.startsWith('http://')
		|| src.startsWith('https://')
		|| src.startsWith('data:')
		|| src.match(/^(\/index.php)?\/core\/preview/)
		|| src.match(/^(\/index.php)?\/apps\/files_sharing\/publicpreview\//)
}

/**
 * Check if the given url has a preview
 *
 * @param {string} src - the url to check
 */
function hasPreview(src) {
	return getQueryVariable(src, 'hasPreview') === 'true'
}

/**
 * Extract the value of a query variable from the given url
 *
 * @param {string} src - the url to extract query variable from
 * @param {string} variable - name of the variable to read out
 */
function getQueryVariable(src, variable) {
	const query = src.split('?')[1]

	if (typeof query === 'undefined') {
		return
	}

	const vars = query.split(/[&#]/)

	if (typeof vars === 'undefined') {
		return
	}

	for (let i = 0; i < vars.length; i++) {
		const pair = vars[i].split('=')
		if (decodeURIComponent(pair[0]) === variable) {
			return decodeURIComponent(pair[1])
		}
	}
}