code cleaning, new config
[mir.git] / source / mircoders / media / MediaRequest.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.media;
33
34 import java.util.GregorianCalendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37
38 import javax.servlet.ServletContext;
39
40 import mir.config.MirPropertiesConfiguration;
41 import mir.entity.Entity;
42 import mir.entity.EntityList;
43 import mir.media.MediaHelper;
44 import mir.media.MirMedia;
45 import mir.media.MirMediaException;
46 import mir.misc.FileHandler;
47 import mir.misc.FileHandlerException;
48 import mir.misc.FileHandlerUserException;
49 import mir.misc.StringUtil;
50 import mir.module.ModuleException;
51 import mir.storage.Database;
52 import mir.storage.StorageObjectExc;
53 import mir.storage.StorageObjectFailure;
54 import mircoders.producer.ProducerMedia;
55 import mircoders.storage.DatabaseMediaType;
56
57 import com.oreilly.servlet.multipart.FilePart;
58
59 /*
60  *  MediaRequest.java -
61  *    Takes an HTTPServletRequest from a mutltipart form and finds the files
62  *    uploaded via the com.oreilly.servlet.multipart package. Finally the
63  *    appropriate media objects are set.
64  *
65  * @author mh
66  * @version $Id: MediaRequest.java,v 1.12 2003/01/25 17:50:35 idfx Exp $
67  *
68  */
69
70 public class MediaRequest implements FileHandler
71 {
72
73   String _user;
74   EntityList _returnList = new EntityList();
75   boolean _produce, _publish;
76
77   public MediaRequest(String user, boolean produce, boolean publish) {
78     _user = user;
79     _produce = produce;
80     _publish = publish;
81   }
82
83   public EntityList getEntityList() {
84     return _returnList;
85   }
86
87   /*
88    * parses the files in the uploaded media and creates media Entity's out of
89    * them.  Produces them if the "produce" argument is true. The "publish"
90    * parameter determines if it should publish per default in the case where no
91    * is_published parameter (from the upload form) is supplied. (for backwards
92    * compatibility.)
93    */
94   public void setFile(FilePart filePart, int fileNum, HashMap mediaValues)
95     throws FileHandlerException, FileHandlerUserException {
96
97     String mediaId=null;
98     MirMedia mediaHandler;
99     Database mediaStorage = null;
100     ProducerMedia mediaProducer = null;
101
102     try {
103       String fileName = filePart.getFileName();
104
105       //get the content-type from what the client browser
106       //sends us. (the "Oreilly method")
107       String contentType = filePart.getContentType();
108
109       //theLog.printInfo("FROM BROWSER: "+contentType);
110
111       //if the client browser sent us unknown (text/plain is default)
112       //or if we got application/octet-stream, it's possible that
113       //the browser is in error, better check against the file extension
114       if (contentType.equals("text/plain") ||
115           contentType.equals("application/octet-stream")) {
116         /**
117          * Fallback to finding the mime-type through the standard ServletApi
118          * ServletContext getMimeType() method.
119          *
120          * This is a way to get the content-type via the .extension,
121          * we could maybe use a magic method as an additional method of
122          * figuring out the content-type, by looking at the header (first
123          * few bytes) of the file. (like the file(1) command). We could
124          * also call the "file" command through Runtime. This is an
125          * option that I almost prefer as it is already implemented and
126          * exists with an up-to-date map on most modern Unix like systems.
127          * I haven't found a really nice implementation of the magic method
128          * in pure java yet.
129          *
130          * The first method we try thought is the "Oreilly method". It
131          * relies on the content-type that the client browser sends and
132          * that sometimes is application-octet stream with
133          * broken/mis-configured browsers.
134          *
135          * The map file we use for the extensions is the standard web-app
136          * deployment descriptor file (web.xml). See Mir's web.xml or see
137          * your Servlet containers (most likely Tomcat) documentation.
138          * So if you support a new media type you have to make sure that
139          * it is in this file -mh
140          */
141         ServletContext ctx = MirPropertiesConfiguration.getContext();
142         contentType = ctx.getMimeType(fileName);
143         if (contentType==null)
144           contentType = "text/plain"; // rfc1867 says this is the default
145       }
146       //theLog.printInfo("CONTENT TYPE IS: "+contentType);
147
148       if (contentType.equals("text/plain") ||
149           contentType.equals("application/octet-stream")) {
150         _throwBadContentType(fileName, contentType);
151       }
152
153       // call the routines that escape html
154       for (Iterator i=mediaValues.keySet().iterator(); i.hasNext(); ){
155         String k=(String)i.next();
156         String v=(String)mediaValues.get(k);
157         
158         if (k.equals("description")) {
159           String tmp = StringUtil.deleteForbiddenTags(v);
160           mediaValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
161         } else {
162           //we don't want people fucking with the author/title, etc..
163           mediaValues.put(k,StringUtil.removeHTMLTags(v));
164         }
165         
166       }
167
168       String mediaTitle = (String)mediaValues.get("media_title"+fileNum);
169       if ( (mediaTitle == null) || (mediaTitle.length() == 0)) {
170         //  uncomment the next line and comment out the exception throw
171         //  if you'd rather just assign missing media titles automatically
172         //  mediaTitle="media item "+fileNum;
173         throw new FileHandlerUserException("Missing field: media title "+mediaTitle+fileNum);
174       }
175
176       // TODO: need to add all the extra fields that can be present in the
177       // admin upload form. -mh
178       mediaValues.put("title", mediaTitle);
179       mediaValues.put("date", StringUtil.date2webdbDate(
180                                                     new GregorianCalendar()));
181       mediaValues.put("to_publisher", _user);
182       //mediaValues.put("to_media_folder", "7"); // op media_folder
183       mediaValues.put("is_produced", "0");
184
185       // icky backwards compatibility code -mh
186       if (_publish == true) {
187         mediaValues.put("is_published", "1");
188       } else {
189         if (!mediaValues.containsKey("is_published"))
190           mediaValues.put("is_published", "0");
191       }
192
193       // @todo this should probably be moved to DatabaseMediaType -mh
194       String[] cTypeSplit = StringUtil.split(contentType, "/");
195       String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
196
197       DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
198       EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
199
200       String mediaTypeId = null;
201
202       //if we didn't find an entry matching the
203       //content-type int the table.
204       if (mediaTypesList.size() == 0) {
205        _throwBadContentType(fileName, contentType);
206       }
207
208       Entity mediaType = null;
209       Entity mediaType2 = null;
210
211       // find out if we an exact content-type match if so take it.
212       // otherwise try to match majortype/*
213       // @todo this should probably be moved to DatabaseMediaType -mh
214       for(int j=0;j<mediaTypesList.size();j++) {
215         if(contentType.equals(
216               mediaTypesList.elementAt(j).getValue("mime_type")))
217           mediaType = mediaTypesList.elementAt(j);
218         else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
219                   cTypeSplit[0]+"/*") )
220           mediaType2= mediaTypesList.elementAt(j);
221       }
222
223       if ( (mediaType == null) && (mediaType2 == null) ) {
224         _throwBadContentType(fileName, contentType);
225       } else if( (mediaType == null) && (mediaType2 != null) ) {
226         mediaType = mediaType2;
227       }
228
229       //get the class names from the media_type table.
230       mediaTypeId = mediaType.getId();
231       // ############### @todo: merge these and the getURL call into one
232       // getURL helper call that just takes the Entity as a parameter
233       // along with media_type
234       try {
235         mediaHandler = MediaHelper.getHandler(mediaType);
236         mediaStorage = MediaHelper.getStorage(mediaType,
237                                             "mircoders.storage.Database");
238       }
239       catch (MirMediaException e) {
240         throw new FileHandlerException (e.getMessage());
241       }
242       mediaValues.put("to_media_type",mediaTypeId);
243
244       //load the classes via reflection
245       String MediaId;
246       Entity mediaEnt = null;
247       try {
248         mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
249         if (_produce == true) {
250           Class prodCls = Class.forName("mircoders.producer.Producer"+
251                                         mediaType.getValue("tablename"));
252           mediaProducer = (ProducerMedia)prodCls.newInstance();
253         }
254       } catch (Exception e) {
255         throw new FileHandlerException("Error in MediaRequest: "+e.toString());
256       }
257
258       mediaEnt.setStorage(mediaStorage);
259       mediaEnt.setValues(mediaValues);
260       mediaId = mediaEnt.insert();
261
262       //save and store the media data/metadata
263       try {
264         mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
265       }
266       catch (MirMediaException e) {
267         e.printStackTrace(System.out);
268         throw new FileHandlerException(e.getMessage());
269       }
270       try {
271         if (_produce == true )
272           mediaProducer.handle(null, null, false, false, mediaId);
273       } catch (ModuleException e) {
274         // first try to delete it.. don't catch exception as we've already..
275         try { mediaStorage.delete(mediaId); } catch (Exception e2) {}
276         throw new FileHandlerException("error in MediaRequest: "+e.toString());
277       }
278
279       _returnList.add(mediaEnt);
280     }
281     catch (StorageObjectFailure e) {
282       // first try to delete it.. don't catch exception as we've already..
283       try { mediaStorage.delete(mediaId); } catch (Exception e2) {}
284       throw new FileHandlerException("error in MediaRequest: "+e.toString());
285     } catch (StorageObjectExc e) {
286       throw new FileHandlerException("error in MediaRequest: "+e.toString());
287     } //end try/catch block
288
289   } // method setFile()
290
291   private void _throwBadContentType (String fileName, String contentType)
292     throws FileHandlerUserException {
293
294     //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
295       //                    +contentType);
296     throw new FileHandlerUserException("The file you uploaded is of the "
297         +"following mime-type: "+contentType
298         +", we do not support this mime-type. "
299         +"Error One or more files of unrecognized type. Sorry");
300   }
301
302 }
303