Dateiverwaltung für die WebBox
ulrich
2018-03-31 0a2df2254edd25d4f2e499f27c5f0630e60f2614
commit | author | age
8931b7 1 /*
U 2     Dateiverwaltung - File management in your browser
3     Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU Affero General Public License as
7     published by the Free Software Foundation, either version 3 of the
8     License, or (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU Affero General Public License for more details.
14
15     You should have received a copy of the GNU Affero General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
c7c502 19 package de.uhilger.filecms.api;
U 20
6e70be 21 import de.uhilger.filecms.data.FileRef;
d14d78 22 import de.uhilger.filecms.pub.AbstractComparator;
U 23 import de.uhilger.filecms.pub.FileNameComparator;
bb9f8c 24 import de.uhilger.wbx.Bild;
8e51b7 25 import java.io.File;
3ad4db 26 import java.io.FileNotFoundException;
6bd2c1 27 import java.io.FileOutputStream;
3ad4db 28 import java.io.FileReader;
e5ff42 29 import java.io.FileWriter;
U 30 import java.io.IOException;
6bd2c1 31 import java.io.InputStream;
fab80c 32 import java.io.Reader;
e5ff42 33 import java.security.Principal;
7342b1 34 import java.util.ArrayList;
d14d78 35 import java.util.Arrays;
6bd2c1 36 import java.util.Enumeration;
5bfd34 37 import java.util.Iterator;
7342b1 38 import java.util.List;
e5ff42 39 import java.util.logging.Level;
8e51b7 40 import java.util.logging.Logger;
6bd2c1 41 import java.util.zip.ZipEntry;
U 42 import java.util.zip.ZipFile;
bb9f8c 43 import net.coobird.thumbnailator.Thumbnails;
5bfd34 44 import org.apache.commons.io.FileUtils;
c7c502 45
U 46 /**
fafe1b 47  * Methoden zur Verwaltung von Dateien
c7c502 48  */
8931b7 49 public class FileMgr extends Api {
8e51b7 50   private static final Logger logger = Logger.getLogger(FileMgr.class.getName());
c7c502 51   
972e94 52   
9e2964 53   public static final int OP_COPY = 1;
U 54   public static final int OP_MOVE = 2;
55   
ea7193 56   public String hallo() {
U 57     return "Hallo Welt!";
58   }
59   
1f550a 60   /**
U 61    * Inhalte der WebBox listen. Hier wird nur der relative Pfad 
62    * ausgehend von www oder home ausgegeben sowie zudem ausgehend 
63    * von $daten und $basis, sofern der Benutzer die Rolle wbxAdmin hat.
64    * 
65    * Andere Inhalte werden nicht ausgegeben.
66    * 
67    * @param relPath
68    * @return 
69    */
7342b1 70   public List<FileRef> list(String relPath) {
d14d78 71     return listInt(relPath, "name", AbstractComparator.ORDER_ASC);
U 72   }
73   
74   public List<FileRef> listOrdered(String relPath, String orderBy, String order) {
75     return listInt(relPath, orderBy, order);
76   }
77   
78   /**
79    * Inhalte der WebBox listen. Hier wird nur der relative Pfad 
80    * ausgehend von www oder home ausgegeben sowie zudem ausgehend 
81    * von $daten und $basis, sofern der Benutzer die Rolle wbxAdmin hat.
82    * 
83    * Andere Inhalte werden nicht ausgegeben.
84    * 
85    * @param relPath
86    * @param orderBy 'name'
87    * @param order AbstractComparator.ORDER_ASC oder AbstractComparator.ORDER_DESC
88    * @return 
89    */
90   private List<FileRef> listInt(String relPath, String orderBy, String order) {
f7d8bf 91     Bild bild = new Bild();
5dfab6 92     List<FileRef> files = new ArrayList();
ac72fe 93     if (!relPath.startsWith(".") && !relPath.contains("WEB-INF") && !relPath.contains("META-INF")) {
3d0c6d 94       if (relPath.length() == 0) {
U 95         FileRef namedPublicFolder = new FileRef(PUB_DIR_NAME, true);
96         logger.finer(namedPublicFolder.getAbsolutePath());
97         FileRef namedHomeFolder = new FileRef(HOME_DIR_NAME, true);
98         logger.finer(namedHomeFolder.getAbsolutePath());
99         FileRef namedDavFolder = new FileRef(DAV_DIR_NAME, true);
100         logger.finer(namedDavFolder.getAbsolutePath());
101         files = new ArrayList();
102         files.add(namedHomeFolder);
103         files.add(namedPublicFolder);
104         files.add(namedDavFolder);
105         if (getRequest().isUserInRole(WBX_ADMIN_ROLE)) {
106           FileRef namedBaseFolder = new FileRef(WBX_BASE, true);
107           FileRef namedDataFolder = new FileRef(WBX_DATA, true);
108           files.add(namedBaseFolder);
109           files.add(namedDataFolder);
d14d78 110         }
3d0c6d 111       } else {
U 112         String path = getTargetDir(relPath).getAbsolutePath();
113         logger.fine("listing path: " + path);
114         File dir = new File(path);
115         if (dir.exists()) {
116           File[] fileArray = dir.listFiles();
117           if (orderBy != null && orderBy.equalsIgnoreCase("name")) {
118             Arrays.sort(fileArray, new FileNameComparator(order));
119           } else {
120             Arrays.sort(fileArray, new FileNameComparator(AbstractComparator.ORDER_ASC));
5bfd34 121           }
3d0c6d 122           for (int i = 0; i < fileArray.length; i++) {
U 123             logger.fine(fileArray[i].toURI().toString());
124             String fname = fileArray[i].toURI().toString().replace("file:/", "");
125             if (fileArray[i].isDirectory()) {
126               fname = fname.substring(0, fname.length() - 1);
127             }
128             logger.fine(fname);
ac72fe 129             if(!fname.contains("WEB-INF") && !fname.contains("META-INF")) {
c5eaaa 130               long fLen = fileArray[i].length();
U 131               long lastMod = fileArray[i].lastModified();
132               FileRef ref = new FileRef(fname, fileArray[i].isDirectory(), fileArray[i].isHidden(), lastMod, fLen);
ac72fe 133               ref.setMimetype(bild.getMimeType(fileArray[i]));
U 134               files.add(ref);
135             }
3d0c6d 136           }
5bfd34 137         }
5dfab6 138       }
3d0c6d 139     }
7342b1 140     return files;
2121cc 141   }
U 142   
d14d78 143   
c509a0 144   public FileRef newFolder(String relPath, String folderName) {
eb2a2d 145     if (!relPath.startsWith(".")) {
U 146       logger.finer(relPath);
147       String targetPath = null;
148       if(relPath.startsWith(PUB_DIR_NAME)) {
149         targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
150       } else if(relPath.startsWith(HOME_DIR_NAME)) {
151         targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
152       } else {
153         // kann eigentlich nicht sein..
154       }
155       logger.finer(targetPath);
156       File targetDir = new File(getBase().getAbsolutePath(), targetPath);
157       targetDir.mkdirs();
158       return new FileRef(targetDir.getAbsolutePath(), true);
c509a0 159     } else {
eb2a2d 160       return null;
c509a0 161     }
5dfab6 162   }
U 163   
3ad4db 164   public String getCode(String relPath, String fileName) {
U 165     String code = null;
eb2a2d 166     if (!relPath.startsWith(".")) {
U 167       Object p = getRequest().getUserPrincipal();
168       if (p instanceof Principal) {
169         Reader reader = null;
3ad4db 170         try {
eb2a2d 171           File targetFile = new File(getTargetDir(relPath), fileName);
U 172
173           //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
174           reader = new FileReader(targetFile);
175           StringBuffer buf = new StringBuffer();
176           char[] readBuffer = new char[1024];
177           int charsRead = reader.read(readBuffer);
178           while (charsRead > -1) {
179             buf.append(readBuffer, 0, charsRead);
180             charsRead = reader.read(readBuffer);
181           }
182           code = buf.toString();
183         } catch (FileNotFoundException ex) {
184           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
3ad4db 185         } catch (IOException ex) {
U 186           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
eb2a2d 187         } finally {
U 188           try {
189             reader.close();
190           } catch (IOException ex) {
191             Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
192           }
3ad4db 193         }
eb2a2d 194
3ad4db 195       }
eb2a2d 196     }
3ad4db 197     return code;
U 198   }
199   
663ee9 200   public String renameFile(String relPath, String fname, String newName) {
eb2a2d 201     if (!relPath.startsWith(".")) {
U 202       File targetDir = getTargetDir(relPath);
203       File file = new File(targetDir, fname);
204       file.renameTo(new File(targetDir, newName));
205       return fname + " umbenannt zu " + newName;
206     } else {
207       return "Pfad nicht erlaubt.";
208     }
663ee9 209   }
U 210   
fc1897 211   public String deleteFiles(String relPath, List fileNames) {
U 212     String result = null;
213     try {
214       logger.fine(fileNames.toString());
eb2a2d 215       if (!relPath.startsWith(".")) {
U 216         File targetDir = getTargetDir(relPath);
217         for(int i=0; i < fileNames.size(); i++) {
218           Object o = fileNames.get(i);
219           if(o instanceof ArrayList) {
220             ArrayList al = (ArrayList) o;
221             logger.fine(al.get(0).toString());
222             File targetFile = new File(targetDir, al.get(0).toString());
223             logger.fine(targetFile.getAbsolutePath());
224             if(targetFile.isDirectory()) {
225               FileUtils.deleteDirectory(targetFile);
226             } else {
227               targetFile.delete();
228             }
5bfd34 229           }
fc1897 230         }
eb2a2d 231         result = "deleted";
fc1897 232       }
U 233     } catch (Throwable ex) {
234       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
235     }
236     return result;
237   }
238   
9e2964 239   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 240     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 241   }
U 242   
243   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 244     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 245   }
246   
247   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 248     String result = null;
U 249     try {
eb2a2d 250       if (!fromPath.startsWith(".")) {
U 251         File srcDir = getTargetDir(fromPath);
252         File targetDir = getTargetDir(toPath);
253         Iterator i = fileNames.iterator();
254         while(i.hasNext()) {
255           Object o = i.next();
256           if (o instanceof ArrayList) {
257             ArrayList al = (ArrayList) o;
258             File srcFile = new File(srcDir, al.get(0).toString());
259             if(srcFile.isDirectory()) {
260               if(operation == OP_MOVE) {
261                 FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
262               } else {
263                 FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
264               }
fab629 265             } else {
eb2a2d 266               if(operation == OP_MOVE) {
U 267                 FileUtils.moveFileToDirectory(srcFile, targetDir, false);
268               } else {
269                 FileUtils.copyFileToDirectory(srcFile, targetDir);              
270               }
fab629 271             }
5bfd34 272           }
U 273         }
274       }
275     } catch (IOException ex) {
276       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
277     }
278     return result;
9e2964 279   }
U 280   
47e9d4 281   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 282     FileRef savedFile = null;
283     logger.fine(relPath + " " + fileName);
eb2a2d 284     if (!relPath.startsWith(".")) {
U 285       //FileRef datenRef = getBase();
286       Object p = getRequest().getUserPrincipal();
287       if(p instanceof Principal) {
288         File targetFile = new File(getTargetDir(relPath), fileName);
289         if(targetFile.exists()) {
290           targetFile = getNewFileName(targetFile);
291         } else {
292           targetFile.getParentFile().mkdirs();
293         }
294         saveToFile(targetFile, contents);
47e9d4 295       }
U 296     }
297     return savedFile;
298   }
299   
300   private File getNewFileName(File file) {
301     File dir = file.getParentFile();
302     String targetName = file.getName();
303     logger.fine("targetName: " + targetName);
304     String ext = "";
305     int dotpos = targetName.indexOf(".");
306     if(dotpos > -1) {
307       ext = targetName.substring(dotpos);
308       targetName = targetName.substring(0, dotpos);
309     }
310     logger.fine("targetName: " + targetName + ", ext: " + ext);
311     int i = 1;
312     while(file.exists()) {
313       StringBuffer buf = new StringBuffer();
314       buf.append(targetName);
315       buf.append("-");
316       buf.append(i);
317       if(ext.length() > 0) {
318         buf.append(ext);
319       }
320       file = new File(dir, buf.toString());
321       i++;
322     }
323     logger.fine("new file: " + file.getName());
324     return file;
942d63 325   }  
47e9d4 326   
U 327   private FileRef saveToFile(File targetFile, String contents) {
ea7193 328     FileRef savedFile = null;
e5ff42 329     try {
47e9d4 330       targetFile.createNewFile();
U 331       FileWriter w = new FileWriter(targetFile);
942d63 332       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 333       w.write(contents);
U 334       w.flush();
335       w.close();
336       savedFile = new FileRef(
337               targetFile.getAbsolutePath(),
338               targetFile.isDirectory(),
339               targetFile.isHidden(),
340               targetFile.lastModified(),
341               targetFile.length());
e5ff42 342     } catch (IOException ex) {
47e9d4 343       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 344     }
345     return savedFile;
346   }
347   
348   public FileRef saveTextFile(String relPath, String fileName, String contents) {
349     FileRef savedFile = null;
350     logger.fine(relPath + " " + fileName);
eb2a2d 351     if (!relPath.startsWith(".")) {    
U 352       //FileRef datenRef = getBase();
353       Object p = getRequest().getUserPrincipal();
354       if(p instanceof Principal) {
355         File targetFile = new File(getTargetDir(relPath), fileName);
356         if(targetFile.exists()) {
357           /*
358             muss delete() sein?
359             pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
360             entsteht eine unerwuenschte Mischung aus altem und neuem 
361             Inhalt?
362           */
363           targetFile.delete();
364         } else {
365           targetFile.getParentFile().mkdirs();
366         }
367         saveToFile(targetFile, contents);
47e9d4 368       }
e5ff42 369     }
ea7193 370     return savedFile;
U 371   }
438b16 372   
U 373   public String bildVerkleinern(String relPath, String bildName) {
eb2a2d 374     if (!relPath.startsWith(".")) {
U 375       File dir = getTargetDir(relPath);
376       File original = new File(dir, bildName);
377       Bild bild = new Bild();
378       //for (int i = 0; i < Bild.GR.length; i++) {
379
438b16 380       //int gr = bild.getVariantenGroesse(i);
U 381       String ext = "";
382       String nurname = bildName;
383       int dotpos = bildName.indexOf(".");
384       if (dotpos > -1) {
385         ext = bildName.substring(dotpos);
386         nurname = bildName.substring(0, dotpos);
387       }
eb2a2d 388
bb9f8c 389           // 120, 240, 500, 700, 1200
U 390
391       
392       for (int i = 0; i < Bild.GR.length; i++) {
393         StringBuffer buf = new StringBuffer();
394         buf.append(nurname);
395         buf.append(bild.getVariantenName(i));
396         buf.append(ext);
397         File newImgFile = new File(dir, buf.toString());
398         try {
399           Thumbnails.of(original)
400                   .size(bild.getVariantenGroesse(i), bild.getVariantenGroesse(i))
401                   .keepAspectRatio(true)
8a8152 402                   .outputQuality(0.7)
bb9f8c 403                   .toFile(newImgFile);
U 404         } catch (IOException ex) {
405           logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
406         }
407       }
eb2a2d 408       return "ok";
U 409     } else {
410       return "Pfad micht erlaubt.";
411     }
438b16 412   }
6bd2c1 413   
bb9f8c 414   public String bildRotieren(String relPath, String bildName) {
U 415     if (!relPath.startsWith(".")) {
416       File dir = getTargetDir(relPath);
417       File original = new File(dir, bildName);
418
419       String ext = "";
420       String nurname = bildName;
421       int dotpos = bildName.indexOf(".");
422       if (dotpos > -1) {
423         ext = bildName.substring(dotpos);
424         nurname = bildName.substring(0, dotpos);
425       }
426
427       StringBuffer buf = new StringBuffer();
428       buf.append(nurname);
429       buf.append("-rot");
430       buf.append(ext);
431       File newImgFile = new File(dir, buf.toString());
432       
433       logger.fine("original: " + original.getAbsolutePath() + " newImgFile: " + newImgFile.getAbsolutePath());
434
435       try {
436         Thumbnails.of(original)
437                 .scale(1)
438                 .rotate(90)
439                 .toFile(newImgFile);
440       } catch (IOException ex) {
441         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
442       }
443
444
445       return "ok";
446     } else {
447       return "Pfad micht erlaubt.";
448     }
449   }
6bd2c1 450   public String extractZipfile(String relPath, String filename) {
eb2a2d 451     String result = null;
U 452     if (!relPath.startsWith(".")) {    
453       try {
454         File targetDir = getTargetDir(relPath);
455         File archive = new File(targetDir, filename);
456         if(extract(archive)) {
457           result = "ok";
458         } else {
459           result = "error while extracting";
460         }
461       } catch(Exception ex) {
462         result = ex.getLocalizedMessage();
463         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
6bd2c1 464       }
U 465     }
466     return result;
467   }
468   
469   /**
470      * extract a given ZIP archive to the folder respective archive resides in
471      * @param archive  the archive to extract
472      * @throws Exception
473      */
474     private boolean extract(File archive) throws Exception {
475         ZipFile zipfile = new ZipFile(archive);
476         Enumeration en = zipfile.entries();
477         while(en.hasMoreElements()) {
478             ZipEntry zipentry = (ZipEntry) en.nextElement();
479             unzip(zipfile, zipentry, archive.getParent());
480         }
481         zipfile.close();
482         return true;
483     }
484
485     /**
486      * unzip a given entry of a given zip file to a given location
487      * @param zipfile  the zip file to read an entry from
488      * @param zipentry  the zip entry to read
489      * @param destPath  the path to the destination location for the extracted content
490      * @throws IOException
491      */
492     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
493         byte buf[] = new byte[1024];
494         InputStream is = zipfile.getInputStream(zipentry);
495         String outFileName = destPath + File.separator + zipentry.getName();
496         File file = new File(outFileName);
497         if(!zipentry.isDirectory()) {
498             file.getParentFile().mkdirs();
499             if(!file.exists())
500                 file.createNewFile();
501             FileOutputStream fos = new FileOutputStream(file);
502             int i = is.read(buf, 0, 1024);
503             while(i > -1) {
504                 fos.write(buf, 0, i);
505                 i = is.read(buf, 0, 1024);
506             }
507             fos.close();
508             is.close();
509         } else {
510             file.mkdirs();
511         }
512     }
513
514   
438b16 515
5efd94 516   /* ---- Hilfsfunktionen ---- */
ea7193 517   
547755 518 }