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