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