summaryrefslogtreecommitdiffstats
path: root/idrop-web/grails-app/controllers/org/irods/mydrop/controller/FileController.groovy
blob: 714c505651ef70ad84594bd7b116debb766c3891 (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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
package org.irods.mydrop.controller


import grails.converters.*

import org.irods.jargon.core.connection.IRODSAccount
import org.irods.jargon.core.exception.CatNoAccessException
import org.irods.jargon.core.exception.DataNotFoundException
import org.irods.jargon.core.exception.JargonException
import org.irods.jargon.core.exception.NoResourceDefinedException
import org.irods.jargon.core.pub.CollectionAndDataObjectListAndSearchAO
import org.irods.jargon.core.pub.DataTransferOperations
import org.irods.jargon.core.pub.IRODSAccessObjectFactory
import org.irods.jargon.core.pub.Stream2StreamAO
import org.irods.jargon.core.pub.domain.DataObject
import org.irods.jargon.core.pub.io.IRODSFile
import org.irods.jargon.core.pub.io.IRODSFileFactory
import org.irods.jargon.core.pub.io.IRODSFileInputStream
import org.irods.jargon.datautils.uploads.UploadsService
import org.irods.jargon.datautils.uploads.UploadsServiceImpl
import org.springframework.web.multipart.MultipartFile


class FileController {

	IRODSAccessObjectFactory irodsAccessObjectFactory
	IRODSAccount irodsAccount
	static long MAX_UPLOAD = 3221225472  // shooting for 3GB max, make parm?

	/**
	 * Interceptor grabs IRODSAccount from the SecurityContextHolder
	 */
	def beforeInterceptor = [action:this.&auth]

	def auth() {
		if(!session["SPRING_SECURITY_CONTEXT"]) {
			redirect(controller:"login", action:"login")
			return false
		}
		irodsAccount = session["SPRING_SECURITY_CONTEXT"]
	}

	def afterInterceptor = {
		log.debug("closing the session")
		irodsAccessObjectFactory.closeSession()
	}


	/**
	 * This is the download action
	 */
	def index = {

		log.info("index action")
		String parseString = "/file/download"
		def parseStringLength = parseString.length()
		String fullPath = params.name
		if (fullPath == null || fullPath.isEmpty()) {
			log.error("null or missing path info")
			throw new JargonException("null or missing path info")
		}

		log.info("add path info is ${params.name}")
		def idx = fullPath.indexOf(parseString)
		log.debug("parsing out additional path info")
		if (idx == -1) {
			log.error("unable to parse addl path info for irods absolute path, path info was ${fullPath}")
			throw new JargonException("unable to parse addl path info for irods absolute path")
		}

		fullPath = fullPath.substring(idx + parseStringLength)
		log.info("iRODS path for file is: ${fullPath}")

		try {
			IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
			IRODSFileInputStream irodsFileInputStream = irodsFileFactory.instanceIRODSFileInputStream(fullPath)
			IRODSFile irodsFile = irodsFileFactory.instanceIRODSFile(fullPath)
			def length =  irodsFile.length()
			log.info("file length = ${length}")
			log.info("opened input stream")

			response.setContentType("application/octet-stream")
			response.setContentLength((int) length)
			response.setHeader("Content-disposition", "attachment;filename=\"${irodsFile.name}\"")

			//response.outputStream << irodsFileInputStream // Performing a binary stream copy

			Stream2StreamAO stream2Stream = irodsAccessObjectFactory.getStream2StreamAO(irodsAccount)
			def stats = stream2Stream
					.streamToStreamCopyUsingStandardIO(irodsFileInputStream, response.outputStream)
			log.info("transferStats:${stats}")

		} catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		}

	}

	/**
	 * Prepare a dialog to upload a file into the given collection
	 * 
	 */
	def prepareUploadDialog = {
		log.info("prepareUploadDialog")
		String irodsTargetCollection = params.irodsTargetCollection
		if (irodsTargetCollection == null || irodsTargetCollection.isEmpty()) {
			log.error("null or missing irodsTargetCollection")
		}

		log.info("looking up parent as: ${irodsTargetCollection}")

		/* here we could do any processing on irods, such as provisioning of metadata fields based on target
		 * for now, derive info about the target and normalize to a collection (could be a data object)
		 */

		CollectionAndDataObjectListAndSearchAO collectionAndDataObjectListAndSearchAO = irodsAccessObjectFactory.getCollectionAndDataObjectListAndSearchAO(irodsAccount)

		def targetObject = null
		try {
			targetObject = collectionAndDataObjectListAndSearchAO.getFullObjectForType(irodsTargetCollection)
		} catch (DataNotFoundException dnf) {
			log.error("no iRODS data found for: ${irodsTargetCollection}")
			throw new JargonException("No data found for ${irodsTargetCollection}")
		}

		if (targetObject instanceof DataObject) {
			log.info("substituting data object parent as path")
			DataObject dataObject = (DataObject) targetObject
			irodsTargetCollection = dataObject.collectionName
		}

		render(view:"uploadDialog", model:[irodsTargetCollection:irodsTargetCollection])
	}

	/**
	 * Prepare a quick upload dialog to upload a file to the default location using the quick upload service
	 *
	 */
	def prepareQuickUploadDialog = {
		log.info("prepareQuickUploadDialog")

		log.info("checking if uploads default directory needs to be created")

		/* here we could do any processing on irods, such as provisioning of metadata fields based on target
		 * for now, derive info about the target and normalize to a collection (could be a data object)
		 */

		UploadsService uploadsService = new UploadsServiceImpl(irodsAccessObjectFactory, irodsAccount)
		IRODSFile uploadsDir = uploadsService.getUploadsDirectory();

		render(view:"quickUploadDialog", model:[irodsTargetCollection:uploadsDir.absolutePath])
	}

	/**
	 * Process an actual call to upload data to iRODS as a multi-part file
	 */
	def upload = {
		log.info("upload action in file controller")
		MultipartFile f = request.getFile('file')
		def name = f.getOriginalFilename()

		log.info("f is ${f}")
		log.info("length of f is ${f.size}")
		log.info("max upload size is ${MAX_UPLOAD}")

		if (f.size > MAX_UPLOAD) {
			log.error("file size is too large, send error message to use bulk upload")
			def message = message(code:"error.use.bulk.upload")
			response.sendError(500,message)
			return
		} else if (f.size == 0) {
			log.error("file is zero length")
			def message = message(code:"error.zero.length.upload")
			response.sendError(500,message)
			return
		}

		log.info("name is : ${name}")
		def irodsCollectionPath = params.collectionParentName

		if (f == null || f.empty) {
			log.error("no file to upload")
			throw new JargonException("No file to upload")
		}

		if (irodsCollectionPath == null || irodsCollectionPath.empty) {
			log.error("no target iRODS collection given in upload request")
			throw new JargonException("No iRODS target collection given for upload")
		}

		InputStream fis = null
		log.info("building irodsFile for file name: ${name}")


		try {
			fis = new BufferedInputStream(f.getInputStream())
			IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
			IRODSFile targetFile = irodsFileFactory.instanceIRODSFile(irodsCollectionPath, name)
			targetFile.setResource(irodsAccount.defaultStorageResource)
			Stream2StreamAO stream2Stream = irodsAccessObjectFactory.getStream2StreamAO(irodsAccount)
			def transferStats = stream2Stream.transferStreamToFileUsingIOStreams(fis, targetFile, f.size, 0)
			log.info("transferStats:${transferStats}")
		} catch (NoResourceDefinedException nrd) {
			log.error("no resource defined exception", nrd)
			response.sendError(500, message(code:"message.no.resource"))
		} catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		} catch (Exception e) {
			log.error("exception in upload transfer", e)
			response.sendError(500, message(code:"message.error.in.upload"))
		} finally {
			// stream2Stream will close input and output streams
		}

		render "{\"name\":\"${name}\",\"type\":\"image/jpeg\",\"size\":\"1000\"}"
	}

	/**
	 * Delete the given file or folder
	 */
	def deleteFileOrFolder = {
		log.info("delete file or folder")
		String absPath = params['absPath']
		if (!absPath) {
			log.error "no absPath in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		absPath = absPath.trim()

		log.info("name for delete folder:${absPath}")
		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
		IRODSFile targetFile = irodsFileFactory.instanceIRODSFile(absPath)

		try {
			targetFile.deleteWithForceOption()
			log.info("file deleted")
			render(view:"deleteResult", model:[absPath:targetFile.parent])
		} catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		} catch (JargonException je) {
			log.error("exception on delete", je)
			response.sendError(500,je.message)
			return
		}
	}

	/**
	 * Process a bulk delete action based on data input from the browse details form
	 */
	def deleteBulkAction = {
		log.info("deleteBulkAction")

		log.info("params: ${params}")

		def filesToDelete = params['selectDetail']

		// if nothing selected, just jump out and return a message
		if (!filesToDelete) {
			log.info("no files to delete")
			render "OK"
			return
		}

		log.info("filesToDelete: ${filesToDelete}")

		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)

		if (filesToDelete instanceof Object[]) {
			log.debug "is array"
			filesToDelete.each{
				log.info "filesToDelete: ${it}"
				IRODSFile toDelete = irodsFileFactory.instanceIRODSFile(it)
				toDelete.delete()
				log.info("...delete successful")
			}

		} else {
			log.debug "not array"
			log.info "deleting: ${filesToDelete}..."
			IRODSFile toDelete = irodsFileFactory.instanceIRODSFile(filesToDelete)
			toDelete.delete()
			log.info("...delete successful")
		}

		render "OK"
	}


	/**
	 * Add a new iRODS folder
	 */
	def createFolder = {
		log.info("create folder")

		String parent = params['parent']
		if (!parent) {
			log.error "no parent in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		parent = parent.trim()

		String newFolderName = params['name']
		if (!newFolderName) {
			log.error "no name in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		newFolderName = newFolderName.trim()

		try {
			log.info("name for create folder:${newFolderName}")
			IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
			IRODSFile targetFile = irodsFileFactory.instanceIRODSFile(parent + "/" + newFolderName)

			if (targetFile.exists()) {
				log.error "no name in request"
				def message = message(code:"error.duplicate.file")
				response.sendError(500,message)
			}

			targetFile.mkdirs()
			log.info("file created:${targetFile.absolutePath}")
			render targetFile.getAbsolutePath()
		} catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		}

	}

	/**
	 * Rename an iRODS file or folder
	 */
	def renameFile = {
		log.info("renameFile()")

		String prevAbsPath = params['prevAbsPath']
		if (!prevAbsPath) {
			log.error "no prevAbsPath in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		prevAbsPath = prevAbsPath.trim()

		String newName = params['newName']
		if (!newName) {
			log.error "no newName in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		newName = newName.trim()

		log.info("rename to :${newName}")
		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
		IRODSFile prevFile = irodsFileFactory.instanceIRODSFile(prevAbsPath)

		IRODSFile newFile = irodsFileFactory.instanceIRODSFile(prevFile.getParentFile(), newName)

		// don't rename to self
		if (newFile.absolutePath == prevFile.absolutePath) {
			log.info("ignoring rename to self")
			render prevFile.absolutePath
			return
		}
		try {
			prevFile.renameTo(newFile)

			// return the parent, which will be reloaded
			render newFile.parent
		} catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		}

	}

	/**
	 * Move a file in iRODS
	 */
	def moveFile = {
		log.info("move file")
		String sourceAbsPath = params['sourceAbsPath']
		String targetAbsPath = params['targetAbsPath']

		if (!sourceAbsPath) {
			log.error "no source path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		if (!targetAbsPath) {
			log.error "no target path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		try {
			DataTransferOperations dataTransferOperations = irodsAccessObjectFactory.getDataTransferOperations(irodsAccount)
			log.info("moving ${sourceAbsPath} to ${targetAbsPath}")
			dataTransferOperations.move(sourceAbsPath, targetAbsPath)
		} catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		} catch (NoResourceDefinedException nrd) {
			log.error "no default resource found for move operation"
			def message = message(code:"message.no.resource")
			response.sendError(500,message)
		}

		render targetAbsPath
	}

	/**
	 * Do a check for access rights to a file at a given path, if it exists, is a data object, and the user has read access, return "OK", otherwise
	 * throw an appropriate exception
	 */
	def screenForDownloadRights = {
		log.info("screenForDownloadRights")

		String sourceAbsPath = params['absPath']
		if (!sourceAbsPath) {
			log.error "no source path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		log.info("getting file for path:${sourceAbsPath}")
		IRODSFile irodsFile = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount).instanceIRODSFile(sourceAbsPath)
		if (!irodsFile.exists()) {
			log.error "file does not exist"
			def message = message(code:"error.file.not.found")
			response.sendError(500,message)
		}

		if (!irodsFile.isFile()) {
			log.error "not a file"
			def message = message(code:"error.file.not.found")
			response.sendError(500,message)
		}

		if (!irodsFile.canRead()) {
			log.error "no access to file"
			def message = message(code:"error.no.access.permission")
			response.sendError(500,message)
		}

		render "OK"

	}

	/** 
	 * Copy a file in iRODS
	 */
	def copyFile = {
		log.info("copy file")
		String sourceAbsPath = params['sourceAbsPath']
		String targetAbsPath = params['targetAbsPath']

		if (!sourceAbsPath) {
			log.error "no source path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		if (!targetAbsPath) {
			log.error "no target path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		String defaultResource = irodsAccount.defaultStorageResource
		log.info("defaultResource:${defaultResource}")

		try {
			DataTransferOperations dataTransferOperations = irodsAccessObjectFactory.getDataTransferOperations(irodsAccount)
			log.info("copy ${sourceAbsPath} to ${targetAbsPath}")
			dataTransferOperations.copy(sourceAbsPath,defaultResource, targetAbsPath,null, null)
		} catch (NoResourceDefinedException nrd) {
			log.error "no default resource found for copy operation"
			def message = message(code:"message.no.resource")
			response.sendError(500,message)
		}  catch (CatNoAccessException e) {
			log.error("no access error", e)
			response.sendError(500, message(code:"message.no.access"))
		}


		render targetAbsPath

	}
}