Dateiverwaltung für die WebBox
ulrich
2017-03-10 41e9f0d04b3eb3df0f5f371aa0079c4cc248ca77
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   
7342b1 49   public static final String PUB_DIR_PATH = "www/";
U 50   public static final String HOME_DIR_PATH = "home/";
51   public static final String PUB_DIR_NAME = "Oeffentlich";
52   public static final String HOME_DIR_NAME = "Persoenlicher Ordner";
c7c502 53   
9e2964 54   public static final int OP_COPY = 1;
U 55   public static final int OP_MOVE = 2;
56   
ea7193 57   public String hallo() {
U 58     return "Hallo Welt!";
59   }
60   
7342b1 61   public List<FileRef> list(String relPath) {
f7d8bf 62     Bild bild = new Bild();
5dfab6 63     List<FileRef> files = new ArrayList();
7342b1 64     if(relPath.length() == 0) {
2121cc 65       FileRef namedPublicFolder = new FileRef(PUB_DIR_NAME, true);
5dfab6 66       logger.finer(namedPublicFolder.getAbsolutePath());
2121cc 67       FileRef namedHomeFolder = new FileRef(HOME_DIR_NAME, true);
5dfab6 68       logger.finer(namedHomeFolder.getAbsolutePath());
2121cc 69       files = new ArrayList();
7342b1 70       files.add(namedHomeFolder);
U 71       files.add(namedPublicFolder);
ea7193 72     } else {
2121cc 73       String path = getTargetDir(relPath).getAbsolutePath();
5bfd34 74       logger.fine("listing path: " + path);
U 75       File dir = new File(path);
76       if(dir.exists()) {
77         File[] fileArray = dir.listFiles();
78         for(int i = 0; i < fileArray.length; i++) {
79           logger.fine(fileArray[i].toURI().toString());
80           String fname = fileArray[i].toURI().toString().replace("file:/", "");
81           if(fileArray[i].isDirectory()) {
82             fname = fname.substring(0, fname.length() - 1);
83           }
84           logger.fine(fname);
f7d8bf 85           FileRef ref = new FileRef(fname, fileArray[i].isDirectory());
U 86           ref.setMimetype(bild.getMimeType(fileArray[i]));
87           files.add(ref);
5bfd34 88         }
5dfab6 89       }
c509a0 90     }    
7342b1 91     return files;
2121cc 92   }
U 93   
c509a0 94   public FileRef newFolder(String relPath, String folderName) {
U 95     logger.finer(relPath);
96     String targetPath = null;
97     if(relPath.startsWith(PUB_DIR_NAME)) {
98       targetPath = PUB_DIR_PATH + getUserName() + "/" + relPath.substring(PUB_DIR_NAME.length()) + "/" + folderName;
99     } else if(relPath.startsWith(HOME_DIR_NAME)) {
100       targetPath = HOME_DIR_PATH + getUserName() + "/" + relPath.substring(HOME_DIR_NAME.length()) + "/" + folderName;
101     } else {
102       // kann eigentlich nicht sein..
103     }
104     logger.finer(targetPath);
105     File targetDir = new File(getBase().getAbsolutePath(), targetPath);
106     targetDir.mkdirs();
107     return new FileRef(targetDir.getAbsolutePath(), true);
5dfab6 108   }
U 109   
3ad4db 110   public String getCode(String relPath, String fileName) {
U 111     String code = null;
112     
113     Object p = getRequest().getUserPrincipal();
114     if(p instanceof Principal) {
fab80c 115       Reader reader = null;
3ad4db 116       try {
U 117         File targetFile = new File(getTargetDir(relPath), fileName);
fab80c 118         
U 119         //reader = new InputStreamReader(new FileInputStream(targetFile), "UTF8");
120         
3ad4db 121         reader = new FileReader(targetFile);
U 122         StringBuffer buf = new StringBuffer();
123         char[] readBuffer = new char[1024];
124         int charsRead = reader.read(readBuffer);
125         while(charsRead > -1) {
126           buf.append(readBuffer, 0, charsRead);
127           charsRead = reader.read(readBuffer);
128         }
129         code = buf.toString();
130       } catch (FileNotFoundException ex) {
131         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
132       } catch (IOException ex) {
133         Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
134       } finally {
135         try {
136           reader.close();
137         } catch (IOException ex) {
138           Logger.getLogger(FileMgr.class.getName()).log(Level.SEVERE, null, ex);
139         }
140       }
141       
142     }    
143     
144     return code;
145   }
146   
663ee9 147   public String renameFile(String relPath, String fname, String newName) {
U 148     File targetDir = getTargetDir(relPath);
149     File file = new File(targetDir, fname);
150     file.renameTo(new File(targetDir, newName));
151     return fname + " umbenannt zu " + newName;
152   }
153   
fc1897 154   public String deleteFiles(String relPath, List fileNames) {
U 155     String result = null;
156     try {
157       logger.fine(fileNames.toString());
158       File targetDir = getTargetDir(relPath);
159       for(int i=0; i < fileNames.size(); i++) {
160         Object o = fileNames.get(i);
161         if(o instanceof ArrayList) {
162           ArrayList al = (ArrayList) o;
163           logger.fine(al.get(0).toString());
164           File targetFile = new File(targetDir, al.get(0).toString());
165           logger.fine(targetFile.getAbsolutePath());
5bfd34 166           if(targetFile.isDirectory()) {
U 167             FileUtils.deleteDirectory(targetFile);
168           } else {
169             targetFile.delete();
170           }
fc1897 171         }
U 172       }
173       result = "deleted";
174     } catch (Throwable ex) {
175       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
176     }
177     return result;
178   }
179   
9e2964 180   public String copyFiles(String fromPath, String toPath, List fileNames) {
fab629 181     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_COPY);
9e2964 182   }
U 183   
184   public String moveFiles(String fromPath, String toPath, List fileNames) {
fab629 185     return copyOrMoveFiles(fromPath, toPath, fileNames, OP_MOVE);
U 186   }
187   
188   private String copyOrMoveFiles(String fromPath, String toPath, List fileNames, int operation) {
5bfd34 189     String result = null;
U 190     try {
191       File srcDir = getTargetDir(fromPath);
192       File targetDir = getTargetDir(toPath);
193       Iterator i = fileNames.iterator();
194       while(i.hasNext()) {
195         Object o = i.next();
196         if (o instanceof ArrayList) {
197           ArrayList al = (ArrayList) o;
198           File srcFile = new File(srcDir, al.get(0).toString());
199           if(srcFile.isDirectory()) {
fab629 200             if(operation == OP_MOVE) {
U 201               FileUtils.moveDirectoryToDirectory(srcFile, targetDir, false);
202             } else {
203               FileUtils.copyDirectoryToDirectory(srcFile, targetDir);
204             }
5bfd34 205           } else {
fab629 206             if(operation == OP_MOVE) {
U 207               FileUtils.moveFileToDirectory(srcFile, targetDir, false);
208             } else {
209               FileUtils.copyFileToDirectory(srcFile, targetDir);              
210             }
5bfd34 211           }
U 212         }
213       }
214     } catch (IOException ex) {
215       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
216     }
217     return result;
9e2964 218   }
U 219   
47e9d4 220   public FileRef saveTextFileAs(String relPath, String fileName, String contents) {
U 221     FileRef savedFile = null;
222     logger.fine(relPath + " " + fileName);
223     //FileRef datenRef = getBase();
224     Object p = getRequest().getUserPrincipal();
225     if(p instanceof Principal) {
226       File targetFile = new File(getTargetDir(relPath), fileName);
227       if(targetFile.exists()) {
228         targetFile = getNewFileName(targetFile);
229       } else {
230         targetFile.getParentFile().mkdirs();
231       }
232       saveToFile(targetFile, contents);
233     }
234     return savedFile;
235   }
236   
237   private File getNewFileName(File file) {
238     File dir = file.getParentFile();
239     String targetName = file.getName();
240     logger.fine("targetName: " + targetName);
241     String ext = "";
242     int dotpos = targetName.indexOf(".");
243     if(dotpos > -1) {
244       ext = targetName.substring(dotpos);
245       targetName = targetName.substring(0, dotpos);
246     }
247     logger.fine("targetName: " + targetName + ", ext: " + ext);
248     int i = 1;
249     while(file.exists()) {
250       StringBuffer buf = new StringBuffer();
251       buf.append(targetName);
252       buf.append("-");
253       buf.append(i);
254       if(ext.length() > 0) {
255         buf.append(ext);
256       }
257       file = new File(dir, buf.toString());
258       i++;
259     }
260     logger.fine("new file: " + file.getName());
261     return file;
942d63 262   }  
47e9d4 263   
U 264   private FileRef saveToFile(File targetFile, String contents) {
ea7193 265     FileRef savedFile = null;
e5ff42 266     try {
47e9d4 267       targetFile.createNewFile();
U 268       FileWriter w = new FileWriter(targetFile);
942d63 269       //w.write(StringEscapeUtils.unescapeHtml(contents));
47e9d4 270       w.write(contents);
U 271       w.flush();
272       w.close();
273       savedFile = new FileRef(
274               targetFile.getAbsolutePath(),
275               targetFile.isDirectory(),
276               targetFile.isHidden(),
277               targetFile.lastModified(),
278               targetFile.length());
e5ff42 279     } catch (IOException ex) {
47e9d4 280       logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
U 281     }
282     return savedFile;
283   }
284   
285   public FileRef saveTextFile(String relPath, String fileName, String contents) {
286     FileRef savedFile = null;
287     logger.fine(relPath + " " + fileName);
288     //FileRef datenRef = getBase();
289     Object p = getRequest().getUserPrincipal();
290     if(p instanceof Principal) {
291       File targetFile = new File(getTargetDir(relPath), fileName);
292       if(targetFile.exists()) {
293         /*
294           muss delete() sein?
295           pruefen: ueberschreibt der FileWriter den alteen Inhalt oder 
296           entsteht eine unerwuenschte Mischung aus altem und neuem 
297           Inhalt?
298         */
299         targetFile.delete();
300       } else {
301         targetFile.getParentFile().mkdirs();
302       }
303       saveToFile(targetFile, contents);
e5ff42 304     }
ea7193 305     return savedFile;
U 306   }
438b16 307   
U 308   public String bildVerkleinern(String relPath, String bildName) {
309     File dir = getTargetDir(relPath);
310     File original = new File(dir, bildName);
311     Bild bild = new Bild();
312     //for (int i = 0; i < Bild.GR.length; i++) {
5efd94 313     
438b16 314       //int gr = bild.getVariantenGroesse(i);
U 315       
316       String ext = "";
317       String nurname = bildName;
318       int dotpos = bildName.indexOf(".");
319       if (dotpos > -1) {
320         ext = bildName.substring(dotpos);
321         nurname = bildName.substring(0, dotpos);
322       }
323         
324       Image image = Toolkit.getDefaultToolkit().getImage(original.getAbsolutePath());
325       MediaTracker mediaTracker = new MediaTracker(new Container());
326       mediaTracker.addImage(image, 0);
327       try {
328         mediaTracker.waitForID(0);
329
330         if(!mediaTracker.isErrorAny()) {
331           for(int i = 0; i < Bild.GR.length; i++) {
332             StringBuffer buf = new StringBuffer();
333             buf.append(nurname);
334             buf.append(bild.getVariantenName(i));
335             buf.append(ext);
336             File newImgFile = new File(dir, buf.toString());
337             if(!newImgFile.exists()) {
338               logger.fine(original.getAbsolutePath() + " " + newImgFile.getAbsolutePath());
339               bild.writeImageFile(image, bild.getVariantenGroesse(i), bild.getMimeType(original), original.getAbsolutePath(), newImgFile.getAbsolutePath());
340               //bild.writeImageFile(image, photo.getVariantenGroesse(i), photo.getMimetype(), photo.getAbsolutePath(basisPfad), photo.getVariantenName(basisPfad, i));
341             }
342           }
343         }
344       } catch(IOException | InterruptedException ex) {
345         logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
346       }
347
348     return "ok";
349   }
350
5efd94 351   /* ---- Hilfsfunktionen ---- */
ea7193 352   
5efd94 353   private File getTargetDir(String relPath) {
3c4b10 354     logger.fine(relPath);
5efd94 355     String targetPath = null;
U 356     if(relPath.startsWith(PUB_DIR_NAME)) {
9e2964 357       targetPath = PUB_DIR_PATH + getUserName() + relPath.substring(PUB_DIR_NAME.length());
5efd94 358     } else if(relPath.startsWith(HOME_DIR_NAME)) {
9e2964 359       targetPath = HOME_DIR_PATH + getUserName() + relPath.substring(HOME_DIR_NAME.length());
5efd94 360     } else {
U 361       // kann eigentlich nicht sein..
362     }
3c4b10 363     logger.fine(targetPath);
5efd94 364     File targetDir = new File(getBase().getAbsolutePath(), targetPath);
U 365     return targetDir;
366   }
9e2964 367   
5efd94 368   private FileRef getBase() {
U 369     FileRef base = null;
370     Object o = getServletContext().getAttribute(Initialiser.FILE_BASE);
3c4b10 371     if(o instanceof String) {
U 372       String baseStr = (String) o;
373       logger.fine(baseStr);
374       File file = new File(baseStr);
375       base = new FileRef(file.getAbsolutePath(), file.isDirectory());
5efd94 376     }
U 377     return base;
378   }
379   
380   private String getUserName() {
381     String userName = null;
382     Object p = getRequest().getUserPrincipal();
383     if(p instanceof Principal) {
384       userName = ((Principal) p).getName();
385     }
386     return userName;
547755 387   }    
U 388 }