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