001    package net.sourceforge.mp3dings.utils;
002    
003    /*
004     *  Mp3dings - manage mp3 meta-information
005     *  Copyright (C) 2003 Moritz Ringler
006     *  $Id: FilenamePatterns.java,v 1.7 2007/02/01 13:44:14 ringler Exp $
007     *
008     *  This program is free software; you can redistribute it and/or
009     *  modify it under the terms of the GNU General Public License
010     *  as published by the Free Software Foundation; either version 2
011     *  of the License, or (at your option) any later version.
012     *
013     *  This program is distributed in the hope that it will be useful,
014     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
015     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     *  GNU General Public License for more details.
017     *
018     *  You should have received a copy of the GNU General Public License
019     *  along with this program; if not, write to the Free Software
020     *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
021     */
022    import java.util.Arrays;
023    import java.util.Hashtable;
024    import java.util.Iterator;
025    import java.util.Set;
026    import java.util.logging.Logger;
027    import java.util.prefs.Preferences;
028    import java.util.regex.Matcher;
029    import java.util.regex.Pattern;
030    import de.mospace.lang.Array;
031    import net.sourceforge.mp3dings.Field;
032    
033    /**
034     * A set of patterns that can be used to retrieve information from an mp3
035     * filename.
036     *
037     * @author ringler
038     */
039    public class FilenamePatterns {
040        private static final Logger logger = Logger.getLogger(FilenamePatterns.class.getPackage().getName());
041        private Hashtable patterns = new Hashtable();
042        private Field currentField = null;
043        /** The default pattern for Artist (\1) and Title (\3)* */
044        public final static String DEFAULT_PATTERN =
045                "(\\p{L}(?:\\p{L}|[ '&])+\\p{L}) *- *(\\p{L}(?:\\p{L}|[ '])+\\p{L})";
046        /** The default pattern for Track (\1) * */
047        public final static String DEFAULT_TRACK_PATTERN = "(?:\\b|\\D)(\\d{1,2})(?:\\b|\\D)";
048    
049    
050        /** Constructs* */
051        public FilenamePatterns() { }
052    
053    
054        /**
055         * Description of the Method
056         *
057         * @param field Description of the Parameter
058         * @param p Description of the Parameter
059         * @param cgs Description of the Parameter
060         */
061        public void putPattern(Field field, Pattern p, String cgs) {
062            patterns.put(field, new String[]{p.toString(), cgs});
063        }
064    
065    
066        /**
067         * Description of the Method
068         *
069         * @param field Description of the Parameter
070         * @param p Description of the Parameter
071         * @param cgs Description of the Parameter
072         */
073        public void putPattern(Field field, String p, String cgs) {
074            patterns.put(field, new String[]{p, cgs});
075        }
076    
077    
078        /**
079         * Gets the fields attribute of the FilenamePatterns object
080         *
081         * @return The fields value
082         */
083        public Field[] getFields() {
084            Object[] keys = patterns.keySet().toArray();
085            Field[] fields = new Field[keys.length];
086            for (int i = 0; i < keys.length; i++) {
087                fields[i] = (Field) keys[i];
088            }
089            return (fields);
090        }
091    
092    
093        /**
094         * Gets the pattern attribute of the FilenamePatterns object
095         *
096         * @param field Description of the Parameter
097         * @return The pattern value
098         */
099        public String getPattern(Field field) {
100            try {
101                return ((String[]) patterns.get(field))[0];
102            } catch (Exception ex) {
103                return null;
104            }
105        }
106    
107    
108        /**
109         * Gets the cgString attribute of the FilenamePatterns object
110         *
111         * @param field Description of the Parameter
112         * @return The cgString value
113         */
114        public String getCgString(Field field) {
115            try {
116                return ((String[]) patterns.get(field))[1];
117            } catch (Exception ex) {
118                return null;
119            }
120        }
121    
122    
123        /** Description of the Method */
124        public void clear() {
125            patterns.clear();
126        }
127    
128    
129        /**
130         * Description of the Method
131         *
132         * @param filenames Description of the Parameter
133         * @param field Description of the Parameter
134         * @return Description of the Return Value
135         */
136        public Object[] apply(String[] filenames, Field field) {
137            currentField = field;
138            String[] pattern;
139            Object[] results = new Object[filenames.length];
140            Arrays.fill(results, null);
141            Pattern p;
142            Matcher m;
143            String match;
144            pattern = (String[]) patterns.get(field);
145            if (pattern == null) {
146                return results;
147            }
148            p = Pattern.compile(pattern[0]);
149            String name;
150            for (int i = 0; i < filenames.length; i++) {
151                name = filenames[i].replaceFirst("\\.mp3$", "");
152                m = p.matcher(name);
153                if (!m.find()) {
154                    results[i] = null;
155                    continue;
156                }
157                /*
158                 *  isolate first match
159                 */
160                match = filenames[i].substring(m.start(), m.end());
161                /*
162                 *  if replacement is null return match
163                 */
164                if (pattern[1] == null) {
165                    results[i] = field.valueOf(match);
166                    continue;
167                }
168                /*
169                 *  else reset matcher with the matching substring
170                 */
171                m.reset(match);
172                /*
173                 *  and perform the replacement operation
174                 *  this will return the String pattern[1] references to
175                 *  capturing groups replaced by the values from the input.
176                 */
177                try {
178                    match = m.replaceFirst(pattern[1]);
179                } catch (IndexOutOfBoundsException ex) {
180                    //If the replacement string refers to a capturing group that does not exist in the pattern
181                    logger.warning(ex.toString());
182                }
183                results[i] = field.valueOf(match);
184            }
185            return results;
186        }
187    
188    
189        /**
190         * Description of the Method
191         *
192         * @param filename Description of the Parameter
193         * @param field Description of the Parameter
194         * @return Description of the Return Value
195         */
196        public Object apply(String filename, Field field) {
197            currentField = field;
198            String[] pattern;
199            Matcher m;
200            pattern = (String[]) patterns.get(field);
201            if (pattern == null) {
202                return null;
203            }
204            m = Pattern.compile(pattern[0]).matcher(filename.replaceFirst("\\.mp3$", ""));
205            if (!m.find()) {
206                return null;
207            }
208    
209            /*
210             *  isolate first match
211             */
212            String match = filename.substring(m.start(), m.end());
213    
214            /*
215             *  if replacement is null return match
216             */
217            if (pattern[1] == null) {
218                return field.valueOf(match);
219            }
220    
221            /*
222             *  else reset matcher with the matching substring
223             */
224            m.reset(match);
225    
226            /*
227             *  and perform the replacement operation
228             *  this will return the String pattern[1] references to
229             *  capturing groups replaced by the values from the input.
230             */
231            try {
232                match = m.replaceFirst(pattern[1]);
233            } catch (IndexOutOfBoundsException ex) {
234                //If the replacement string refers to a capturing group that does not exist in the pattern
235                logger.warning(ex.toString());
236            }
237            return field.valueOf(match);
238        }
239    
240    
241        /**
242         * Recreates previously saved FilenamePatterns from the specified
243         * preferences node.
244         * This method must ensure that loading the patterns from the node will
245         * restore the exact same set of filename patterns that has been saved to it
246         * with {@link #save}.
247         *
248         * @param p Description of the Parameter
249         * @return A previously saved FilenamePatterns object if the preferences
250         *         node contains such an object or a default set of filename patterns
251         *         otherwise.
252         *
253         * @see #save
254         */
255        public static FilenamePatterns load(Preferences p) {
256            String fieldss = p.get("fields", "");
257            if (fieldss.equals("")) {
258                return mp3dingsDefault();
259            }
260            String[] fields = fieldss.split(",");
261            Field f;
262            FilenamePatterns fp = new FilenamePatterns();
263            String pattern;
264            String cgstr;
265            for (int i = 0; i < fields.length; i++) {
266                try {
267                    f = Field.forName(fields[i]);
268                    pattern = p.get(f.toString() + "p", null);
269                    cgstr = p.get(f.toString() + "c", null);
270                    if (pattern != null) {
271                        fp.putPattern(f, pattern, cgstr);
272                    }
273                } catch (Exception ex) {
274                    //This protects us against corrupt patterns
275                    //created or modified outside mp3dings
276                    logger.severe("Error loading filename pattern:");
277                    logger.severe(ex.getMessage());
278                    logger.severe("Pattern will be skipped");
279                    continue;
280                }
281            }
282            if(fp.patterns.size() == 0){
283                fp = mp3dingsDefault();
284            }
285            return fp;
286        }
287    
288    
289        /**
290         * Description of the Method
291         *
292         * @return Description of the Return Value
293         */
294        public static FilenamePatterns mp3dingsDefault() {
295            FilenamePatterns fp = new FilenamePatterns();
296            fp.putPattern(Field.ARTIST, DEFAULT_PATTERN, "$1");
297            fp.putPattern(Field.TITLE, DEFAULT_PATTERN, "$2");
298            fp.putPattern(Field.TRACK, DEFAULT_TRACK_PATTERN, "$1");
299            return fp;
300        }
301    
302    
303        /**
304         * Saves these FilenamePatterns to a Preferences node. This method
305         * must ensure that re-loading the patterns from the node will restore
306         * the exact same set of filename patterns.
307         *
308         * @param p Description of the Parameter
309         * @see #load
310         */
311        public void save(Preferences p) {
312            Set keySet = patterns.keySet();
313            Iterator it = keySet.iterator();
314            Field field;
315            String pattern;
316            String cgstr;
317            while (it.hasNext()) {
318                field = (Field) it.next();
319                pattern = getPattern(field);
320                if (pattern == null || pattern.equals("")) {
321                    it.remove();
322                    continue;
323                }
324                cgstr = getCgString(field);
325                String ckey = field.toString() + "c";
326                if (cgstr == null) {
327                    p.remove(ckey);
328                } else {
329                    p.put(ckey, cgstr);
330                }
331                p.put(field.toString() + "p", pattern);
332            }
333            p.put("fields", Array.join(keySet.toArray(), ','));
334        }
335    }