OSDN Git Service

コンフィグにファイル命名規則を追加
[coroid/NicoBrowser.git] / src / nicobrowser / Config.java
1 /*$Id$*/
2 package nicobrowser;
3
4 import java.io.BufferedReader;
5 import java.io.File;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.List;
12 import org.apache.commons.configuration.Configuration;
13 import org.apache.commons.configuration.ConfigurationException;
14 import org.apache.commons.configuration.PropertiesConfiguration;
15 import org.apache.commons.io.FileUtils;
16 import org.apache.commons.logging.Log;
17 import org.apache.commons.logging.LogFactory;
18
19 public final class Config {
20
21     /**
22      * feedurl.txtから取得した情報を格納する.
23      */
24     public static class NicoFeed {
25
26         private final String url;
27         private final int number;
28
29         public NicoFeed(String url, int number) {
30             this.url = url;
31             this.number = number;
32         }
33
34         /** @return 上位いくつまでダウンロード対象とするか. */
35         public int getNumber() {
36             return number;
37         }
38
39         /** @return フィードのURL. */
40         public String getUrl() {
41             return url;
42         }
43
44         @Override
45         public String toString() {
46             return getUrl() + ", " + getNumber();
47         }
48     }
49     private static Log log = LogFactory.getLog(Config.class);
50     private static Config instance;
51     private final PropertiesConfiguration properties;
52     private static final String APPLICATION_NAME = "nicobrowser";
53     private static final String CONFIG_NAME = APPLICATION_NAME + ".properties";
54     private static final String FEEDURL_NAME = "feedurl.txt";
55     private static final File APP_HOME = new File(System.getProperty("user.home", "."), "." + APPLICATION_NAME);
56     private static final File CONFIG_FILE = new File(APP_HOME, CONFIG_NAME);
57     private static final File FEEDURL_FILE = new File(APP_HOME, FEEDURL_NAME);
58     public static final String P_PATH_DB = "path.db";
59     public static final String P_PATH_SAVEFILE = "path.savefile";
60     public static final String P_SAVEFILE_PATTERN = "savefile.pattern";
61     public static final String P_FILE_ENCODING = "encoding";
62     public static final String P_NICOVIDEO_MAIL = "nicovideo.mail";
63     public static final String P_NICOVIDEO_PASSWORD = "nicovideo.password";
64     public static final String P_DOWNLOAD_RETRY = "download.retry";
65     public static final String P_DOWNLOAD_WAIT = "download.wait";
66     public static final String P_DOWNLOAD_LOW = "download.low";
67     public static final String P_DOWNLOAD_MYLIST = "download.mylist";
68     private static final int DEFAULT_MAX_RETRY = 3;
69     private static final int DEFAULT_WAIT_TIME = 15;
70     private static final boolean DEFAULT_LOW_FILE = true;
71
72     /**
73      * プログラム実行に必要なコンフィグファイルを作成する.
74      * @return 今回コンフィグを作成したのであればtrue. 既に存在していたため, ファイル作成を行わなかった場合にはfalse.
75      * @throws java.io.IOException ファイル作成に失敗した.
76      */
77     public static boolean createNewConfigFiles() throws IOException {
78         boolean result = false;
79         if (!CONFIG_FILE.exists()) {
80             createNewConfigFile(CONFIG_FILE);
81             result = true;
82             log.info("コンフィグファイルを作成しました: " + CONFIG_FILE.getCanonicalPath());
83         }
84         if (!FEEDURL_FILE.exists()) {
85             InputStream resource = null;
86             try {
87                 resource = ClassLoader.getSystemResourceAsStream("resources/" + FEEDURL_NAME);
88                 createNewFeedFile(resource, FEEDURL_FILE);
89                 result = true;
90                 log.info("FEED URLファイルを作成しました: " + FEEDURL_FILE.getCanonicalPath());
91             } finally {
92                 if (resource != null) {
93                     resource.close();
94                 }
95             }
96         }
97         return result;
98     }
99
100     /**
101      * 新しいプロパティを設定する. 新しいプロパティに値がない場合, 現在のままとなる.
102      * @param p 新規プロパティ.
103      * @throws IOException
104      */
105     public void updateConfigFile(Configuration p) throws IOException {
106         updatePropertyValue(p, P_NICOVIDEO_MAIL);
107         updatePropertyValue(p, P_NICOVIDEO_PASSWORD);
108         updatePropertyValue(p, P_FILE_ENCODING);
109
110         updatePropertyValue(p, P_PATH_DB);
111         updatePropertyValue(p, P_PATH_SAVEFILE);
112         updatePropertyValue(p, P_SAVEFILE_PATTERN);
113
114         updatePropertyValue(p, P_DOWNLOAD_RETRY);
115         updatePropertyValue(p, P_DOWNLOAD_WAIT);
116         updatePropertyValue(p, P_DOWNLOAD_LOW);
117
118         updatePropertyValueArray(p, P_DOWNLOAD_MYLIST);
119
120         try {
121             properties.save();
122         } catch (ConfigurationException ex) {
123             throw new IOException(ex);
124         }
125     }
126
127     /**
128      * 新しいプロパティを設定する. 新しいプロパティに値がない場合, 現在のままとなる.
129      * @param newProp 新規プロパティ.
130      * @param key 設定するプロパティキー.
131      */
132     private void updatePropertyValue(Configuration newProp, String key) {
133         String value = newProp.getString(key, properties.getString(key));
134         properties.setProperty(key, value);
135     }
136
137     private void updatePropertyValueArray(Configuration newProp, String key) {
138         String[] values = newProp.getStringArray(key);
139         if (values.length < 1) {
140             values = properties.getStringArray(key);
141         }
142         properties.setProperty(key, values);
143     }
144
145     private static void createNewConfigFile(File file) throws IOException {
146         ArrayList<CharSequence> props = new ArrayList<CharSequence>();
147
148         StringBuilder dbpath = new StringBuilder(P_PATH_DB + "=");
149         File dbDir = new File(APP_HOME, "db");
150         dbDir.mkdirs();
151         //Windowsのパス区切りバックスペースをエスケープするための処理も入れている.
152         dbpath.append(dbDir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
153         props.add(dbpath);
154
155         StringBuilder savepath = new StringBuilder(P_PATH_SAVEFILE + "=");
156         File saveDir = new File(APP_HOME, "flv");
157         saveDir.mkdirs();
158         savepath.append(saveDir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
159         props.add(savepath);
160
161         props.add(P_SAVEFILE_PATTERN + "={title}");
162
163         props.add(P_FILE_ENCODING + "=" + System.getProperty("file.encoding"));
164
165         props.add(P_NICOVIDEO_MAIL + "=");
166         props.add(P_NICOVIDEO_PASSWORD + "=");
167         props.add(P_DOWNLOAD_RETRY + "=" + DEFAULT_MAX_RETRY);
168         props.add(P_DOWNLOAD_WAIT + "=" + DEFAULT_WAIT_TIME);
169         props.add(P_DOWNLOAD_LOW + "=" + DEFAULT_LOW_FILE);
170         props.add(P_DOWNLOAD_MYLIST + "=");
171
172         FileUtils.writeLines(file, props);
173     }
174
175     private static void createNewFeedFile(InputStream resource, File dest) throws IOException {
176         List<String> list = new ArrayList<String>();
177         BufferedReader br = new BufferedReader(new InputStreamReader(resource, "UTF-8"));
178         while (true) {
179             String text = br.readLine();
180             if (text == null) {
181                 break;
182             }
183             list.add(text);
184         }
185         FileUtils.writeLines(dest, list);
186     }
187
188     private Config() {
189         try {
190             properties = new PropertiesConfiguration(CONFIG_FILE);
191         } catch (Exception ex) {
192             log.fatal("コンフィグの読み込みに失敗: " + CONFIG_FILE);
193             throw new RuntimeException(ex);
194         }
195
196         try {
197             List urls = FileUtils.readLines(FEEDURL_FILE);
198         } catch (IOException ex) {
199             log.fatal("コンフィグの読み込みに失敗: " + CONFIG_FILE);
200             throw new RuntimeException(ex);
201         }
202     }
203
204     public static Config getInstance() {
205         if (instance == null) {
206             instance = new Config();
207         }
208         return instance;
209     }
210
211     /**
212      * @return ニコニコ動画ログインID.
213      */
214     public String getNicoMail() {
215         return properties.getString(P_NICOVIDEO_MAIL);
216     }
217
218     /**
219      * @return ニコニコ動画ログインパスワード.
220      */
221     public String getNicoPassword() {
222         return properties.getString(P_NICOVIDEO_PASSWORD);
223     }
224
225     /** @return DBパス. コンフィグで設定した値(保存ディレクトリ)でなく, DBファイルのパスが変えることに注意. */
226     public String getDbFile() {
227         return new File(properties.getString(P_PATH_DB), "nicodb").getAbsolutePath();
228     }
229
230     /** @return 保存先の指定. */
231     public String getSrcSaveDir() {
232         return properties.getString(P_PATH_SAVEFILE);
233     }
234
235     /**@return 保存ファイル名の命名規則. */
236     public String fileNamePattern() {
237         return properties.getString(P_SAVEFILE_PATTERN, "{title}");
238     }
239
240     /** @return feedurl.txtの文字エンコーディング. */
241     public String getEncoding() {
242         String res = properties.getString(P_FILE_ENCODING, System.getProperty("file.encoding"));
243         return res;
244     }
245
246     /**
247      * 失敗したダウンロードファイルの最大リトライ回数を取得する.
248      * @return リトライ回数.
249      */
250     public int getMaxRetry() {
251         return properties.getInt(P_DOWNLOAD_RETRY, DEFAULT_MAX_RETRY);
252     }
253
254     /**
255      * 前回ダウンロード開始から最低何秒後から次回ダウンロードを開始するか.
256      * @return 待ち時間(秒).
257      */
258     public int getWaitTime() {
259         return properties.getInt(P_DOWNLOAD_WAIT, DEFAULT_WAIT_TIME);
260     }
261
262     /**
263      * エコノミー動画をダウンロードする必要があるか.
264      * @return エコノミー動画もダウンロード対称にする場合はtrue.
265      */
266     public boolean needLowFile() {
267         return properties.getBoolean(P_DOWNLOAD_LOW, DEFAULT_LOW_FILE);
268     }
269
270     public List<String> getDownLoadMyList() {
271         String[] res = properties.getStringArray(P_DOWNLOAD_MYLIST);
272         return Arrays.asList(res);
273     }
274
275     public List<NicoFeed> getNicoFeeds() {
276         List<NicoFeed> list = new ArrayList<NicoFeed>();
277         try {
278             List lines = FileUtils.readLines(FEEDURL_FILE, getEncoding());
279             for (Object line : lines) {
280                 final String str = line.toString();
281                 if (str.isEmpty() || str.startsWith("#")) {
282                     // 空行, コメント行はスキップ.
283                     continue;
284                 }
285
286                 String[] values = str.split(",");
287                 NicoFeed feed = new NicoFeed(values[0].trim(), Integer.parseInt(values[1].trim()));
288                 list.add(feed);
289             }
290         } catch (IOException ex) {
291             log.error("ファイルが見つかりません: " + FEEDURL_FILE);
292         }
293         return list;
294     }
295
296     public static File getConfigfile() {
297         return CONFIG_FILE;
298     }
299
300     public static File getFeedUrlFile() {
301         return FEEDURL_FILE;
302     }
303
304     public static File getAppHome() {
305         return APP_HOME;
306     }
307 }