Dateiverwaltung für die WebBox
ulrich
2018-03-05 ac72fe96abe90bee2d3ca5c1e2cab2cc5e9c1e39
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")) {
U 130               FileRef ref = new FileRef(fname, fileArray[i].isDirectory());
131               ref.setMimetype(bild.getMimeType(fileArray[i]));
132               files.add(ref);
133             }
3d0c6d 134           }
5bfd34 135         }
5dfab6 136       }
3d0c6d 137     }
7342b1 138     return files;
2121cc 139   }
U 140   
d14d78 141   
c509a0 142   public FileRef newFolder(String relPath, String folderName) {
eb2a2d 143     if (!relPath.startsWith(".")) {
U 144       logger.finer(relPath);
145       String targetPath = null;
146       if(relPath.startsWith(PUB_DIR_NAME)) {
147         targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
148       } else if(relPath.startsWith(HOME_DIR_NAME)) {
149         targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
150       } else {
151         // kann eigentlich nicht sein..
152       }
153       logger.finer(targetPath);
154       File targetDir = new File(getBase().getAbsolutePath(), targetPath);
155       targetDir.mkdirs();
156       return new FileRef(targetDir.getAbsolutePath(), true);
c509a0 157     } else {
eb2a2d 158       return null;
c509a0 159     }
5dfab6 160   }
U 161   
3ad4db 162   public String getCode(String relPath, String fileName) {
U 163     String code = null;
eb2a2d 164     if (!relPath.startsWith(".")) {
U 165       Object p = getRequest().getUserPrincipal();
166       if (p instanceof Principal) {
167         Reader reader = null;
3ad4db 168         try {
eb2a2d 169           File targetFile = new File(getTargetDir(relPath), fileName);
U 170
171           //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
172           reader = new FileReader(targetFile);
173           StringBuffer buf = new StringBuffer();
174           char[] readBuffer = new char[1024];
175           int charsRead = reader.read(readBuffer);
176           while (charsRead > -1) {
177             buf.append(readBuffer, 0, charsRead);
178             charsRead = reader.read(readBuffer);
179           }
180           code = buf.toString();
181         } catch (FileNotFoundException ex) {
182           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
3ad4db 183         } catch (IOException ex) {
U 184           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
eb2a2d 185         } finally {
U 186           try {
187             reader.close();
188           } catch (IOException ex) {
189             Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
190           }
3ad4db 191         }
eb2a2d 192
3ad4db 193       }
eb2a2d 194     }
3ad4db 195     return code;
U 196   }
197   
663ee9 198   public String renameFile(String relPath, String fname, String newName) {
eb2a2d 199     if (!relPath.startsWith(".")) {
U 200       File targetDir = getTargetDir(relPath);
201       File file = new File(targetDir, fname);
202       file.renameTo(new File(targetDir, newName));
203       return fname + " umbenannt zu " + newName;
204     } else {
205       return "Pfad nicht erlaubt.";
206     }
663ee9 207   }
U 208   
fc1897 209   public String deleteFiles(String relPath, List fileNames) {
U 210     String result = null;
211     try {
212       logger.fine(fileNames.toString());
eb2a2d 213       if (!relPath.startsWith(".")) {
U 214         File targetDir = getTargetDir(relPath);
215         for(int i=0; i < fileNames.size(); i++) {
216           Object o = fileNames.get(i);
217           if(o instanceof ArrayList) {
218             ArrayList al = (ArrayList) o;
219             logger.fine(al.get(0).toString());
220             File targetFile = new File(targetDir, al.get(0).toString());
221             logger.fine(targetFile.getAbsolutePath());
222             if(targetFile.isDirectory()) {
223               FileUtils.deleteDirectory(targetFile);
224             } else {
225               targetFile.delete();
226             }
5bfd34 227           }
fc1897 228         }
eb2a2d 229         result = "deleted";
fc1897 230       }
U 231     } catch (Throwable ex) {
232       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
233     }
234     return result;
235   }
236   
9e2964 237   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 238     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 239   }
U 240   
241   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 242     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 243   }
244   
245   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 246     String result = null;
U 247     try {
eb2a2d 248       if (!fromPath.startsWith(".")) {
U 249         File srcDir = getTargetDir(fromPath);
250         File targetDir = getTargetDir(toPath);
251         Iterator i = fileNames.iterator();
252         while(i.hasNext()) {
253           Object o = i.next();
254           if (o instanceof ArrayList) {
255             ArrayList al = (ArrayList) o;
256             File srcFile = new File(srcDir, al.get(0).toString());
257             if(srcFile.isDirectory()) {
258               if(operation == OP_MOVE) {
259                 FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
260               } else {
261                 FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
262               }
fab629 263             } else {
eb2a2d 264               if(operation == OP_MOVE) {
U 265                 FileUtils.moveFileToDirectory(srcFile, targetDir, false);
266               } else {
267                 FileUtils.copyFileToDirectory(srcFile, targetDir);              
268               }
fab629 269             }
5bfd34 270           }
U 271         }
272       }
273     } catch (IOException ex) {
274       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
275     }
276     return result;
9e2964 277   }
U 278   
47e9d4 279   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 280     FileRef savedFile = null;
281     logger.fine(relPath + " " + fileName);
eb2a2d 282     if (!relPath.startsWith(".")) {
U 283       //FileRef datenRef = getBase();
284       Object p = getRequest().getUserPrincipal();
285       if(p instanceof Principal) {
286         File targetFile = new File(getTargetDir(relPath), fileName);
287         if(targetFile.exists()) {
288           targetFile = getNewFileName(targetFile);
289         } else {
290           targetFile.getParentFile().mkdirs();
291         }
292         saveToFile(targetFile, contents);
47e9d4 293       }
U 294     }
295     return savedFile;
296   }
297   
298   private File getNewFileName(File file) {
299     File dir = file.getParentFile();
300     String targetName = file.getName();
301     logger.fine("targetName: " + targetName);
302     String ext = "";
303     int dotpos = targetName.indexOf(".");
304     if(dotpos > -1) {
305       ext = targetName.substring(dotpos);
306       targetName = targetName.substring(0, dotpos);
307     }
308     logger.fine("targetName: " + targetName + ", ext: " + ext);
309     int i = 1;
310     while(file.exists()) {
311       StringBuffer buf = new StringBuffer();
312       buf.append(targetName);
313       buf.append("-");
314       buf.append(i);
315       if(ext.length() > 0) {
316         buf.append(ext);
317       }
318       file = new File(dir, buf.toString());
319       i++;
320     }
321     logger.fine("new file: " + file.getName());
322     return file;
942d63 323   }  
47e9d4 324   
U 325   private FileRef saveToFile(File targetFile, String contents) {
ea7193 326     FileRef savedFile = null;
e5ff42 327     try {
47e9d4 328       targetFile.createNewFile();
U 329       FileWriter w = new FileWriter(targetFile);
942d63 330       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 331       w.write(contents);
U 332       w.flush();
333       w.close();
334       savedFile = new FileRef(
335               targetFile.getAbsolutePath(),
336               targetFile.isDirectory(),
337               targetFile.isHidden(),
338               targetFile.lastModified(),
339               targetFile.length());
e5ff42 340     } catch (IOException ex) {
47e9d4 341       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 342     }
343     return savedFile;
344   }
345   
346   public FileRef saveTextFile(String relPath, String fileName, String contents) {
347     FileRef savedFile = null;
348     logger.fine(relPath + " " + fileName);
eb2a2d 349     if (!relPath.startsWith(".")) {    
U 350       //FileRef datenRef = getBase();
351       Object p = getRequest().getUserPrincipal();
352       if(p instanceof Principal) {
353         File targetFile = new File(getTargetDir(relPath), fileName);
354         if(targetFile.exists()) {
355           /*
356             muss delete() sein?
357             pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
358             entsteht eine unerwuenschte Mischung aus altem und neuem 
359             Inhalt?
360           */
361           targetFile.delete();
362         } else {
363           targetFile.getParentFile().mkdirs();
364         }
365         saveToFile(targetFile, contents);
47e9d4 366       }
e5ff42 367     }
ea7193 368     return savedFile;
U 369   }
438b16 370   
U 371   public String bildVerkleinern(String relPath, String bildName) {
eb2a2d 372     if (!relPath.startsWith(".")) {
U 373       File dir = getTargetDir(relPath);
374       File original = new File(dir, bildName);
375       Bild bild = new Bild();
376       //for (int i = 0; i < Bild.GR.length; i++) {
377
438b16 378       //int gr = bild.getVariantenGroesse(i);
U 379       String ext = "";
380       String nurname = bildName;
381       int dotpos = bildName.indexOf(".");
382       if (dotpos > -1) {
383         ext = bildName.substring(dotpos);
384         nurname = bildName.substring(0, dotpos);
385       }
eb2a2d 386
bb9f8c 387           // 120, 240, 500, 700, 1200
U 388
389       
390       for (int i = 0; i < Bild.GR.length; i++) {
391         StringBuffer buf = new StringBuffer();
392         buf.append(nurname);
393         buf.append(bild.getVariantenName(i));
394         buf.append(ext);
395         File newImgFile = new File(dir, buf.toString());
396         try {
397           Thumbnails.of(original)
398                   .size(bild.getVariantenGroesse(i), bild.getVariantenGroesse(i))
399                   .keepAspectRatio(true)
8a8152 400                   .outputQuality(0.7)
bb9f8c 401                   .toFile(newImgFile);
U 402         } catch (IOException ex) {
403           logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
404         }
405       }
eb2a2d 406       return "ok";
U 407     } else {
408       return "Pfad micht erlaubt.";
409     }
438b16 410   }
6bd2c1 411   
bb9f8c 412   public String bildRotieren(String relPath, String bildName) {
U 413     if (!relPath.startsWith(".")) {
414       File dir = getTargetDir(relPath);
415       File original = new File(dir, bildName);
416
417       String ext = "";
418       String nurname = bildName;
419       int dotpos = bildName.indexOf(".");
420       if (dotpos > -1) {
421         ext = bildName.substring(dotpos);
422         nurname = bildName.substring(0, dotpos);
423       }
424
425       StringBuffer buf = new StringBuffer();
426       buf.append(nurname);
427       buf.append("-rot");
428       buf.append(ext);
429       File newImgFile = new File(dir, buf.toString());
430       
431       logger.fine("original: " + original.getAbsolutePath() + " newImgFile: " + newImgFile.getAbsolutePath());
432
433       try {
434         Thumbnails.of(original)
435                 .scale(1)
436                 .rotate(90)
437                 .toFile(newImgFile);
438       } catch (IOException ex) {
439         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
440       }
441
442
443       return "ok";
444     } else {
445       return "Pfad micht erlaubt.";
446     }
447   }
6bd2c1 448   public String extractZipfile(String relPath, String filename) {
eb2a2d 449     String result = null;
U 450     if (!relPath.startsWith(".")) {    
451       try {
452         File targetDir = getTargetDir(relPath);
453         File archive = new File(targetDir, filename);
454         if(extract(archive)) {
455           result = "ok";
456         } else {
457           result = "error while extracting";
458         }
459       } catch(Exception ex) {
460         result = ex.getLocalizedMessage();
461         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
6bd2c1 462       }
U 463     }
464     return result;
465   }
466   
467   /**
468      * extract a given ZIP archive to the folder respective archive resides in
469      * @param archive  the archive to extract
470      * @throws Exception
471      */
472     private boolean extract(File archive) throws Exception {
473         ZipFile zipfile = new ZipFile(archive);
474         Enumeration en = zipfile.entries();
475         while(en.hasMoreElements()) {
476             ZipEntry zipentry = (ZipEntry) en.nextElement();
477             unzip(zipfile, zipentry, archive.getParent());
478         }
479         zipfile.close();
480         return true;
481     }
482
483     /**
484      * unzip a given entry of a given zip file to a given location
485      * @param zipfile  the zip file to read an entry from
486      * @param zipentry  the zip entry to read
487      * @param destPath  the path to the destination location for the extracted content
488      * @throws IOException
489      */
490     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
491         byte buf[] = new byte[1024];
492         InputStream is = zipfile.getInputStream(zipentry);
493         String outFileName = destPath + File.separator + zipentry.getName();
494         File file = new File(outFileName);
495         if(!zipentry.isDirectory()) {
496             file.getParentFile().mkdirs();
497             if(!file.exists())
498                 file.createNewFile();
499             FileOutputStream fos = new FileOutputStream(file);
500             int i = is.read(buf, 0, 1024);
501             while(i > -1) {
502                 fos.write(buf, 0, i);
503                 i = is.read(buf, 0, 1024);
504             }
505             fos.close();
506             is.close();
507         } else {
508             file.mkdirs();
509         }
510     }
511
512   
438b16 513
5efd94 514   /* ---- Hilfsfunktionen ---- */
ea7193 515   
547755 516 }