afd5fc691685cef77de5c6a5832979cdb6db7a14
[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 com.oreilly.servlet.multipart.FilePart;
41
42 import mir.log.LoggerWrapper;
43 import mir.config.MirPropertiesConfiguration;
44 import mir.entity.Entity;
45 import mir.entity.EntityList;
46 import mir.media.MediaHelper;
47 import mir.media.MirMedia;
48 import mir.media.MirMediaException;
49 import mir.misc.FileHandler;
50 import mir.misc.FileHandlerException;
51 import mir.misc.FileHandlerUserException;
52 import mir.misc.StringUtil;
53 import mir.module.ModuleException;
54 import mir.storage.Database;
55 import mir.storage.StorageObjectExc;
56 import mir.storage.StorageObjectFailure;
57
58 import mircoders.storage.DatabaseMediaType;
59
60
61 /*
62  *  MediaRequest.java -
63  *    Takes an HTTPServletRequest from a mutltipart form and finds the files
64  *    uploaded via the com.oreilly.servlet.multipart package. Finally the
65  *    appropriate media objects are set.
66  *
67  * @author mh
68  * @version $Id: MediaRequest.java,v 1.13 2003/02/23 05:00:14 zapata Exp $
69  *
70  */
71
72 public class MediaRequest implements FileHandler
73 {
74   private String _user;
75   private EntityList _returnList = new EntityList();
76   private boolean _publish;
77   private LoggerWrapper logger;
78
79   public MediaRequest(String user, boolean publish) {
80     _user = user;
81     _publish = publish;
82     logger = new LoggerWrapper("Media.Request");
83   }
84
85   public EntityList getEntityList() {
86     return _returnList;
87   }
88
89   /*
90    * parses the files in the uploaded media and creates media Entity's out of
91    * them.  Produces them if the "produce" argument is true. The "publish"
92    * parameter determines if it should publish per default in the case where no
93    * is_published parameter (from the upload form) is supplied. (for backwards
94    * compatibility.)
95    */
96   public void setFile(FilePart filePart, int fileNum, HashMap mediaValues)
97     throws FileHandlerException, FileHandlerUserException {
98
99     String mediaId=null;
100     MirMedia mediaHandler;
101     Database mediaStorage = null;
102
103     try {
104       String fileName = filePart.getFileName();
105
106       //get the content-type from what the client browser
107       //sends us. (the "Oreilly method")
108       String contentType = filePart.getContentType();
109
110       //theLog.printInfo("FROM BROWSER: "+contentType);
111
112       //if the client browser sent us unknown (text/plain is default)
113       //or if we got application/octet-stream, it's possible that
114       //the browser is in error, better check against the file extension
115       if (contentType.equals("text/plain") ||
116           contentType.equals("application/octet-stream")) {
117         /**
118          * Fallback to finding the mime-type through the standard ServletApi
119          * ServletContext getMimeType() method.
120          *
121          * This is a way to get the content-type via the .extension,
122          * we could maybe use a magic method as an additional method of
123          * figuring out the content-type, by looking at the header (first
124          * few bytes) of the file. (like the file(1) command). We could
125          * also call the "file" command through Runtime. This is an
126          * option that I almost prefer as it is already implemented and
127          * exists with an up-to-date map on most modern Unix like systems.
128          * I haven't found a really nice implementation of the magic method
129          * in pure java yet.
130          *
131          * The first method we try thought is the "Oreilly method". It
132          * relies on the content-type that the client browser sends and
133          * that sometimes is application-octet stream with
134          * broken/mis-configured browsers.
135          *
136          * The map file we use for the extensions is the standard web-app
137          * deployment descriptor file (web.xml). See Mir's web.xml or see
138          * your Servlet containers (most likely Tomcat) documentation.
139          * So if you support a new media type you have to make sure that
140          * it is in this file -mh
141          */
142         ServletContext ctx = MirPropertiesConfiguration.getContext();
143         contentType = ctx.getMimeType(fileName);
144         if (contentType==null)
145           contentType = "text/plain"; // rfc1867 says this is the default
146       }
147       //theLog.printInfo("CONTENT TYPE IS: "+contentType);
148
149       if (contentType.equals("text/plain") ||
150           contentType.equals("application/octet-stream")) {
151         _throwBadContentType(fileName, contentType);
152       }
153
154       // call the routines that escape html
155       for (Iterator i=mediaValues.keySet().iterator(); i.hasNext(); ){
156         String k=(String)i.next();
157         String v=(String)mediaValues.get(k);
158
159         if (k.equals("description")) {
160           String tmp = StringUtil.deleteForbiddenTags(v);
161           mediaValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
162         } else {
163           //we don't want people fucking with the author/title, etc..
164           mediaValues.put(k,StringUtil.removeHTMLTags(v));
165         }
166
167       }
168
169       String mediaTitle = (String)mediaValues.get("media_title"+fileNum);
170       if ( (mediaTitle == null) || (mediaTitle.length() == 0)) {
171         //  uncomment the next line and comment out the exception throw
172         //  if you'd rather just assign missing media titles automatically
173         //  mediaTitle="media item "+fileNum;
174         throw new FileHandlerUserException("Missing field: media title "+mediaTitle+fileNum);
175       }
176
177       // TODO: need to add all the extra fields that can be present in the
178       // admin upload form. -mh
179       mediaValues.put("title", mediaTitle);
180       mediaValues.put("date", StringUtil.date2webdbDate(
181                                                     new GregorianCalendar()));
182       mediaValues.put("to_publisher", _user);
183       //mediaValues.put("to_media_folder", "7"); // op media_folder
184       mediaValues.put("is_produced", "0");
185
186       // icky backwards compatibility code -mh
187       if (_publish == true) {
188         mediaValues.put("is_published", "1");
189       } else {
190         if (!mediaValues.containsKey("is_published"))
191           mediaValues.put("is_published", "0");
192       }
193
194       // @todo this should probably be moved to DatabaseMediaType -mh
195       String[] cTypeSplit = StringUtil.split(contentType, "/");
196       String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
197
198       DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
199       EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
200
201       String mediaTypeId = null;
202
203       //if we didn't find an entry matching the
204       //content-type int the table.
205       if (mediaTypesList.size() == 0) {
206        _throwBadContentType(fileName, contentType);
207       }
208
209       Entity mediaType = null;
210       Entity mediaType2 = null;
211
212       // find out if we an exact content-type match if so take it.
213       // otherwise try to match majortype/*
214       // @todo this should probably be moved to DatabaseMediaType -mh
215       for(int j=0;j<mediaTypesList.size();j++) {
216         if(contentType.equals(
217               mediaTypesList.elementAt(j).getValue("mime_type")))
218           mediaType = mediaTypesList.elementAt(j);
219         else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
220                   cTypeSplit[0]+"/*") )
221           mediaType2= mediaTypesList.elementAt(j);
222       }
223
224       if ( (mediaType == null) && (mediaType2 == null) ) {
225         _throwBadContentType(fileName, contentType);
226       } else if( (mediaType == null) && (mediaType2 != null) ) {
227         mediaType = mediaType2;
228       }
229
230       //get the class names from the media_type table.
231       mediaTypeId = mediaType.getId();
232       // ############### @todo: merge these and the getURL call into one
233       // getURL helper call that just takes the Entity as a parameter
234       // along with media_type
235       try {
236         mediaHandler = MediaHelper.getHandler(mediaType);
237         mediaStorage = MediaHelper.getStorage(mediaType,
238                                             "mircoders.storage.Database");
239       }
240       catch (MirMediaException e) {
241         throw new FileHandlerException (e.getMessage());
242       }
243       mediaValues.put("to_media_type",mediaTypeId);
244
245       //load the classes via reflection
246       String MediaId;
247       Entity mediaEnt = null;
248       try {
249         mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
250       }
251       catch (Exception e) {
252         throw new FileHandlerException("Error in MediaRequest: "+e.toString());
253       }
254
255       mediaEnt.setStorage(mediaStorage);
256       mediaEnt.setValues(mediaValues);
257       mediaId = mediaEnt.insert();
258
259       //save and store the media data/metadata
260       try {
261         mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
262       }
263       catch (MirMediaException e) {
264         throw new FileHandlerException(e.getMessage());
265       }
266
267       _returnList.add(mediaEnt);
268     }
269     catch (StorageObjectFailure e) {
270       // first try to delete it.. don't catch exception as we've already..
271       try {
272         mediaStorage.delete(mediaId);
273       }
274       catch (Exception e2) {
275       }
276       throw new FileHandlerException("error in MediaRequest: "+e.toString());
277     }
278     catch (StorageObjectExc e) {
279       throw new FileHandlerException("error in MediaRequest: "+e.toString());
280     } //end try/catch block
281
282   } // method setFile()
283
284   private void _throwBadContentType (String fileName, String contentType)
285     throws FileHandlerUserException {
286
287     //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
288       //                    +contentType);
289     throw new FileHandlerUserException("The file you uploaded is of the "
290         +"following mime-type: "+contentType
291         +", we do not support this mime-type. "
292         +"Error One or more files of unrecognized type. Sorry");
293   }
294
295 }
296