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