Dateiverwaltung für die WebBox
ulrich
2018-03-03 3d0c6d50d341c393890f54704543810563ea5eda
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.Bild;
U 22 import de.uhilger.filecms.data.FileRef;
d14d78 23 import de.uhilger.filecms.pub.AbstractComparator;
U 24 import de.uhilger.filecms.pub.FileNameComparator;
438b16 25 import java.awt.Container;
U 26 import java.awt.Image;
27 import java.awt.MediaTracker;
28 import java.awt.Toolkit;
8e51b7 29 import java.io.File;
3ad4db 30 import java.io.FileNotFoundException;
6bd2c1 31 import java.io.FileOutputStream;
3ad4db 32 import java.io.FileReader;
e5ff42 33 import java.io.FileWriter;
U 34 import java.io.IOException;
6bd2c1 35 import java.io.InputStream;
fab80c 36 import java.io.Reader;
e5ff42 37 import java.security.Principal;
7342b1 38 import java.util.ArrayList;
d14d78 39 import java.util.Arrays;
6bd2c1 40 import java.util.Enumeration;
5bfd34 41 import java.util.Iterator;
7342b1 42 import java.util.List;
e5ff42 43 import java.util.logging.Level;
8e51b7 44 import java.util.logging.Logger;
6bd2c1 45 import java.util.zip.ZipEntry;
U 46 import java.util.zip.ZipFile;
5bfd34 47 import org.apache.commons.io.FileUtils;
c7c502 48
U 49 /**
fafe1b 50  * Methoden zur Verwaltung von Dateien
c7c502 51  */
8931b7 52 public class FileMgr extends Api {
8e51b7 53   private static final Logger logger = Logger.getLogger(FileMgr.class.getName());
c7c502 54   
972e94 55   
9e2964 56   public static final int OP_COPY = 1;
U 57   public static final int OP_MOVE = 2;
58   
ea7193 59   public String hallo() {
U 60     return "Hallo Welt!";
61   }
62   
1f550a 63   /**
U 64    * Inhalte der WebBox listen. Hier wird nur der relative Pfad 
65    * ausgehend von www oder home ausgegeben sowie zudem ausgehend 
66    * von $daten und $basis, sofern der Benutzer die Rolle wbxAdmin hat.
67    * 
68    * Andere Inhalte werden nicht ausgegeben.
69    * 
70    * @param relPath
71    * @return 
72    */
7342b1 73   public List<FileRef> list(String relPath) {
d14d78 74     return listInt(relPath, "name", AbstractComparator.ORDER_ASC);
U 75   }
76   
77   public List<FileRef> listOrdered(String relPath, String orderBy, String order) {
78     return listInt(relPath, orderBy, order);
79   }
80   
81   /**
82    * Inhalte der WebBox listen. Hier wird nur der relative Pfad 
83    * ausgehend von www oder home ausgegeben sowie zudem ausgehend 
84    * von $daten und $basis, sofern der Benutzer die Rolle wbxAdmin hat.
85    * 
86    * Andere Inhalte werden nicht ausgegeben.
87    * 
88    * @param relPath
89    * @param orderBy 'name'
90    * @param order AbstractComparator.ORDER_ASC oder AbstractComparator.ORDER_DESC
91    * @return 
92    */
93   private List<FileRef> listInt(String relPath, String orderBy, String order) {
f7d8bf 94     Bild bild = new Bild();
5dfab6 95     List<FileRef> files = new ArrayList();
3d0c6d 96     if (!relPath.startsWith(".")) {
U 97       if (relPath.length() == 0) {
98         FileRef namedPublicFolder = new FileRef(PUB_DIR_NAME, true);
99         logger.finer(namedPublicFolder.getAbsolutePath());
100         FileRef namedHomeFolder = new FileRef(HOME_DIR_NAME, true);
101         logger.finer(namedHomeFolder.getAbsolutePath());
102         FileRef namedDavFolder = new FileRef(DAV_DIR_NAME, true);
103         logger.finer(namedDavFolder.getAbsolutePath());
104         files = new ArrayList();
105         files.add(namedHomeFolder);
106         files.add(namedPublicFolder);
107         files.add(namedDavFolder);
108         if (getRequest().isUserInRole(WBX_ADMIN_ROLE)) {
109           FileRef namedBaseFolder = new FileRef(WBX_BASE, true);
110           FileRef namedDataFolder = new FileRef(WBX_DATA, true);
111           files.add(namedBaseFolder);
112           files.add(namedDataFolder);
d14d78 113         }
3d0c6d 114       } else {
U 115         String path = getTargetDir(relPath).getAbsolutePath();
116         logger.fine("listing path: " + path);
117         File dir = new File(path);
118         if (dir.exists()) {
119           File[] fileArray = dir.listFiles();
120           if (orderBy != null && orderBy.equalsIgnoreCase("name")) {
121             Arrays.sort(fileArray, new FileNameComparator(order));
122           } else {
123             Arrays.sort(fileArray, new FileNameComparator(AbstractComparator.ORDER_ASC));
5bfd34 124           }
3d0c6d 125           for (int i = 0; i < fileArray.length; i++) {
U 126             logger.fine(fileArray[i].toURI().toString());
127             String fname = fileArray[i].toURI().toString().replace("file:/", "");
128             if (fileArray[i].isDirectory()) {
129               fname = fname.substring(0, fname.length() - 1);
130             }
131             logger.fine(fname);
132             FileRef ref = new FileRef(fname, fileArray[i].isDirectory());
133             ref.setMimetype(bild.getMimeType(fileArray[i]));
134             files.add(ref);
135           }
5bfd34 136         }
5dfab6 137       }
3d0c6d 138     }
7342b1 139     return files;
2121cc 140   }
U 141   
d14d78 142   
c509a0 143   public FileRef newFolder(String relPath, String folderName) {
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);
5dfab6 157   }
U 158   
3ad4db 159   public String getCode(String relPath, String fileName) {
U 160     String code = null;
161     
162     Object p = getRequest().getUserPrincipal();
163     if(p instanceof Principal) {
fab80c 164       Reader reader = null;
3ad4db 165       try {
U 166         File targetFile = new File(getTargetDir(relPath), fileName);
fab80c 167         
U 168         //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
169         
3ad4db 170         reader = new FileReader(targetFile);
U 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);
181       } catch (IOException ex) {
182         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
183       } finally {
184         try {
185           reader.close();
186         } catch (IOException ex) {
187           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
188         }
189       }
190       
191     }    
192     
193     return code;
194   }
195   
663ee9 196   public String renameFile(String relPath, String fname, String newName) {
U 197     File targetDir = getTargetDir(relPath);
198     File file = new File(targetDir, fname);
199     file.renameTo(new File(targetDir, newName));
200     return fname + " umbenannt zu " + newName;
201   }
202   
fc1897 203   public String deleteFiles(String relPath, List fileNames) {
U 204     String result = null;
205     try {
206       logger.fine(fileNames.toString());
207       File targetDir = getTargetDir(relPath);
208       for(int i=0; i < fileNames.size(); i++) {
209         Object o = fileNames.get(i);
210         if(o instanceof ArrayList) {
211           ArrayList al = (ArrayList) o;
212           logger.fine(al.get(0).toString());
213           File targetFile = new File(targetDir, al.get(0).toString());
214           logger.fine(targetFile.getAbsolutePath());
5bfd34 215           if(targetFile.isDirectory()) {
U 216             FileUtils.deleteDirectory(targetFile);
217           } else {
218             targetFile.delete();
219           }
fc1897 220         }
U 221       }
222       result = "deleted";
223     } catch (Throwable ex) {
224       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
225     }
226     return result;
227   }
228   
9e2964 229   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 230     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 231   }
U 232   
233   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 234     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 235   }
236   
237   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 238     String result = null;
U 239     try {
240       File srcDir = getTargetDir(fromPath);
241       File targetDir = getTargetDir(toPath);
242       Iterator i = fileNames.iterator();
243       while(i.hasNext()) {
244         Object o = i.next();
245         if (o instanceof ArrayList) {
246           ArrayList al = (ArrayList) o;
247           File srcFile = new File(srcDir, al.get(0).toString());
248           if(srcFile.isDirectory()) {
fab629 249             if(operation == OP_MOVE) {
U 250               FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
251             } else {
252               FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
253             }
5bfd34 254           } else {
fab629 255             if(operation == OP_MOVE) {
U 256               FileUtils.moveFileToDirectory(srcFile, targetDir, false);
257             } else {
258               FileUtils.copyFileToDirectory(srcFile, targetDir);              
259             }
5bfd34 260           }
U 261         }
262       }
263     } catch (IOException ex) {
264       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
265     }
266     return result;
9e2964 267   }
U 268   
47e9d4 269   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 270     FileRef savedFile = null;
271     logger.fine(relPath + " " + fileName);
272     //FileRef datenRef = getBase();
273     Object p = getRequest().getUserPrincipal();
274     if(p instanceof Principal) {
275       File targetFile = new File(getTargetDir(relPath), fileName);
276       if(targetFile.exists()) {
277         targetFile = getNewFileName(targetFile);
278       } else {
279         targetFile.getParentFile().mkdirs();
280       }
281       saveToFile(targetFile, contents);
282     }
283     return savedFile;
284   }
285   
286   private File getNewFileName(File file) {
287     File dir = file.getParentFile();
288     String targetName = file.getName();
289     logger.fine("targetName: " + targetName);
290     String ext = "";
291     int dotpos = targetName.indexOf(".");
292     if(dotpos > -1) {
293       ext = targetName.substring(dotpos);
294       targetName = targetName.substring(0, dotpos);
295     }
296     logger.fine("targetName: " + targetName + ", ext: " + ext);
297     int i = 1;
298     while(file.exists()) {
299       StringBuffer buf = new StringBuffer();
300       buf.append(targetName);
301       buf.append("-");
302       buf.append(i);
303       if(ext.length() > 0) {
304         buf.append(ext);
305       }
306       file = new File(dir, buf.toString());
307       i++;
308     }
309     logger.fine("new file: " + file.getName());
310     return file;
942d63 311   }  
47e9d4 312   
U 313   private FileRef saveToFile(File targetFile, String contents) {
ea7193 314     FileRef savedFile = null;
e5ff42 315     try {
47e9d4 316       targetFile.createNewFile();
U 317       FileWriter w = new FileWriter(targetFile);
942d63 318       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 319       w.write(contents);
U 320       w.flush();
321       w.close();
322       savedFile = new FileRef(
323               targetFile.getAbsolutePath(),
324               targetFile.isDirectory(),
325               targetFile.isHidden(),
326               targetFile.lastModified(),
327               targetFile.length());
e5ff42 328     } catch (IOException ex) {
47e9d4 329       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 330     }
331     return savedFile;
332   }
333   
334   public FileRef saveTextFile(String relPath, String fileName, String contents) {
335     FileRef savedFile = null;
336     logger.fine(relPath + " " + fileName);
337     //FileRef datenRef = getBase();
338     Object p = getRequest().getUserPrincipal();
339     if(p instanceof Principal) {
340       File targetFile = new File(getTargetDir(relPath), fileName);
341       if(targetFile.exists()) {
342         /*
343           muss delete() sein?
344           pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
345           entsteht eine unerwuenschte Mischung aus altem und neuem 
346           Inhalt?
347         */
348         targetFile.delete();
349       } else {
350         targetFile.getParentFile().mkdirs();
351       }
352       saveToFile(targetFile, contents);
e5ff42 353     }
ea7193 354     return savedFile;
U 355   }
438b16 356   
U 357   public String bildVerkleinern(String relPath, String bildName) {
358     File dir = getTargetDir(relPath);
359     File original = new File(dir, bildName);
360     Bild bild = new Bild();
361     //for (int i = 0; i < Bild.GR.length; i++) {
5efd94 362     
438b16 363       //int gr = bild.getVariantenGroesse(i);
U 364       
365       String ext = "";
366       String nurname = bildName;
367       int dotpos = bildName.indexOf(".");
368       if (dotpos > -1) {
369         ext = bildName.substring(dotpos);
370         nurname = bildName.substring(0, dotpos);
371       }
372         
373       Image image = Toolkit.getDefaultToolkit().getImage(original.getAbsolutePath());
374       MediaTracker mediaTracker = new MediaTracker(new Container());
375       mediaTracker.addImage(image, 0);
376       try {
377         mediaTracker.waitForID(0);
378
379         if(!mediaTracker.isErrorAny()) {
380           for(int i = 0; i < Bild.GR.length; i++) {
381             StringBuffer buf = new StringBuffer();
382             buf.append(nurname);
383             buf.append(bild.getVariantenName(i));
384             buf.append(ext);
385             File newImgFile = new File(dir, buf.toString());
386             if(!newImgFile.exists()) {
387               logger.fine(original.getAbsolutePath() + " " + newImgFile.getAbsolutePath());
a44b26 388               bild.writeImageFile(image, bild.getVariantenGroesse(i), bild.getMimeType(original), newImgFile.getAbsolutePath());
438b16 389               //bild.writeImageFile(image, photo.getVariantenGroesse(i), photo.getMimetype(), photo.getAbsolutePath(basisPfad), photo.getVariantenName(basisPfad, i));
U 390             }
391           }
392         }
393       } catch(IOException | InterruptedException ex) {
394         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
395       }
396
397     return "ok";
398   }
6bd2c1 399   
U 400   public String extractZipfile(String relPath, String filename) {
401     String result;
402     try {
403       File targetDir = getTargetDir(relPath);
404       File archive = new File(targetDir, filename);
405       if(extract(archive)) {
406         result = "ok";
407       } else {
408         result = "error while extracting";
409       }
410     } catch(Exception ex) {
411       result = ex.getLocalizedMessage();
412       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
413     }
414     return result;
415   }
416   
417   /**
418      * extract a given ZIP archive to the folder respective archive resides in
419      * @param archive  the archive to extract
420      * @throws Exception
421      */
422     private boolean extract(File archive) throws Exception {
423         ZipFile zipfile = new ZipFile(archive);
424         Enumeration en = zipfile.entries();
425         while(en.hasMoreElements()) {
426             ZipEntry zipentry = (ZipEntry) en.nextElement();
427             unzip(zipfile, zipentry, archive.getParent());
428         }
429         zipfile.close();
430         return true;
431     }
432
433     /**
434      * unzip a given entry of a given zip file to a given location
435      * @param zipfile  the zip file to read an entry from
436      * @param zipentry  the zip entry to read
437      * @param destPath  the path to the destination location for the extracted content
438      * @throws IOException
439      */
440     private void unzip(ZipFile zipfile, ZipEntry zipentry, String destPath) throws IOException {
441         byte buf[] = new byte[1024];
442         InputStream is = zipfile.getInputStream(zipentry);
443         String outFileName = destPath + File.separator + zipentry.getName();
444         File file = new File(outFileName);
445         if(!zipentry.isDirectory()) {
446             file.getParentFile().mkdirs();
447             if(!file.exists())
448                 file.createNewFile();
449             FileOutputStream fos = new FileOutputStream(file);
450             int i = is.read(buf, 0, 1024);
451             while(i > -1) {
452                 fos.write(buf, 0, i);
453                 i = is.read(buf, 0, 1024);
454             }
455             fos.close();
456             is.close();
457         } else {
458             file.mkdirs();
459         }
460     }
461
462   
438b16 463
5efd94 464   /* ---- Hilfsfunktionen ---- */
ea7193 465   
547755 466 }