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