Dateiverwaltung für die WebBox
ulrich
2018-03-04 6720b65e8c3d886cf91c011e45578f70f0207973
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)
398                   .toFile(newImgFile);
399         } catch (IOException ex) {
400           logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
401         }
402       }
403       /*
438b16 404       Image image = Toolkit.getDefaultToolkit().getImage(original.getAbsolutePath());
U 405       MediaTracker mediaTracker = new MediaTracker(new Container());
406       mediaTracker.addImage(image, 0);
407       try {
408         mediaTracker.waitForID(0);
409
eb2a2d 410         if (!mediaTracker.isErrorAny()) {
U 411           for (int i = 0; i < Bild.GR.length; i++) {
438b16 412             StringBuffer buf = new StringBuffer();
U 413             buf.append(nurname);
414             buf.append(bild.getVariantenName(i));
415             buf.append(ext);
416             File newImgFile = new File(dir, buf.toString());
eb2a2d 417             if (!newImgFile.exists()) {
438b16 418               logger.fine(original.getAbsolutePath() + " " + newImgFile.getAbsolutePath());
a44b26 419               bild.writeImageFile(image, bild.getVariantenGroesse(i), bild.getMimeType(original), newImgFile.getAbsolutePath());
438b16 420               //bild.writeImageFile(image, photo.getVariantenGroesse(i), photo.getMimetype(), photo.getAbsolutePath(basisPfad), photo.getVariantenName(basisPfad, i));
U 421             }
422           }
423         }
eb2a2d 424       } catch (IOException | InterruptedException ex) {
438b16 425         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 426       }
bb9f8c 427       */
eb2a2d 428       return "ok";
U 429     } else {
430       return "Pfad micht erlaubt.";
431     }
438b16 432   }
6bd2c1 433   
bb9f8c 434   public String bildRotieren(String relPath, String bildName) {
U 435     if (!relPath.startsWith(".")) {
436       File dir = getTargetDir(relPath);
437       File original = new File(dir, bildName);
438
439       String ext = "";
440       String nurname = bildName;
441       int dotpos = bildName.indexOf(".");
442       if (dotpos > -1) {
443         ext = bildName.substring(dotpos);
444         nurname = bildName.substring(0, dotpos);
445       }
446
447       StringBuffer buf = new StringBuffer();
448       buf.append(nurname);
449       buf.append("-rot");
450       buf.append(ext);
451       File newImgFile = new File(dir, buf.toString());
452       
453       logger.fine("original: " + original.getAbsolutePath() + " newImgFile: " + newImgFile.getAbsolutePath());
454
455       try {
456         Thumbnails.of(original)
457                 .scale(1)
458                 .rotate(90)
459                 .toFile(newImgFile);
460       } catch (IOException ex) {
461         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
462       }
463
464
465       return "ok";
466     } else {
467       return "Pfad micht erlaubt.";
468     }
469   }
6bd2c1 470   public String extractZipfile(String relPath, String filename) {
eb2a2d 471     String result = null;
U 472     if (!relPath.startsWith(".")) {    
473       try {
474         File targetDir = getTargetDir(relPath);
475         File archive = new File(targetDir, filename);
476         if(extract(archive)) {
477           result = "ok";
478         } else {
479           result = "error while extracting";
480         }
481       } catch(Exception ex) {
482         result = ex.getLocalizedMessage();
483         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
6bd2c1 484       }
U 485     }
486     return result;
487   }
488   
489   /**
490      * extract a given ZIP archive to the folder respective archive resides in
491      * @param archive  the archive to extract
492      * @throws Exception
493      */
494     private boolean extract(File archive) throws Exception {
495         ZipFile zipfile = new ZipFile(archive);
496         Enumeration en = zipfile.entries();
497         while(en.hasMoreElements()) {
498             ZipEntry zipentry = (ZipEntry) en.nextElement();
499             unzip(zipfile, zipentry, archive.getParent());
500         }
501         zipfile.close();
502         return true;
503     }
504
505     /**
506      * unzip a given entry of a given zip file to a given location
507      * @param zipfile  the zip file to read an entry from
508      * @param zipentry  the zip entry to read
509      * @param destPath  the path to the destination location for the extracted content
510      * @throws IOException
511      */
512     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
513         byte buf[] = new byte[1024];
514         InputStream is = zipfile.getInputStream(zipentry);
515         String outFileName = destPath + File.separator + zipentry.getName();
516         File file = new File(outFileName);
517         if(!zipentry.isDirectory()) {
518             file.getParentFile().mkdirs();
519             if(!file.exists())
520                 file.createNewFile();
521             FileOutputStream fos = new FileOutputStream(file);
522             int i = is.read(buf, 0, 1024);
523             while(i > -1) {
524                 fos.write(buf, 0, i);
525                 i = is.read(buf, 0, 1024);
526             }
527             fos.close();
528             is.close();
529         } else {
530             file.mkdirs();
531         }
532     }
533
534   
438b16 535
5efd94 536   /* ---- Hilfsfunktionen ---- */
ea7193 537   
547755 538 }