OSDN Git Service

jarからファイルを取り出すのにgetSystemResourceが使えなかったため, getSystemResourceAsStreamに変更.
[coroid/NicoBrowser.git] / src / nicobrowser / Config.java
1 /*$Id$*/
2 package nicobrowser;
3
4 import java.io.BufferedInputStream;
5 import java.io.BufferedReader;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.net.URISyntaxException;
12 import java.net.URL;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.Properties;
16 import org.apache.commons.io.FileUtils;
17 import org.apache.commons.logging.Log;
18 import org.apache.commons.logging.LogFactory;
19
20 public final class Config {
21
22     /**
23      * feedurl.txtから取得した情報を格納する.
24      */
25     public static class NicoFeed {
26
27         private final String url;
28         private final int number;
29
30         public NicoFeed(String url, int number) {
31             this.url = url;
32             this.number = number;
33         }
34
35         /** @return 上位いくつまでダウンロード対象とするか. */
36         public int getNumber() {
37             return number;
38         }
39
40         /** @return フィードのURL. */
41         public String getUrl() {
42             return url;
43         }
44
45         @Override
46         public String toString() {
47             return getUrl() + ", " + getNumber();
48         }
49     }
50     private static Log log = LogFactory.getLog(Config.class);
51     private static Config instance;
52     private final Properties properties;
53     private static final String APPLICATION_NAME = "nicobrowser";
54     private static final String CONFIG_NAME = APPLICATION_NAME + ".properties";
55     private static final String FEEDURL_NAME = "feedurl.txt";
56     private static final File APP_HOME = new File(System.getProperty("user.home", "."), "." + APPLICATION_NAME);
57     private static final File CONFIG_FILE = new File(APP_HOME, CONFIG_NAME);
58     private static final File FEEDURL_FILE = new File(APP_HOME, FEEDURL_NAME);
59     private static final String P_PATH_DB = "path.db";
60     private static final String P_PATH_SAVEFILE = "path.savefile";
61     private static final String P_FILE_ENCODING = "encoding";
62     private static final String P_NICOVIDEO_MAIL = "nicovideo.mail";
63     private static final String P_NICOVIDEO_PASSWORD = "nicovideo.password";
64     private static final String P_DOWNLOAD_RETRY = "download.retry";
65     private static final String P_DOWNLOAD_MYLIST = "download.mylist";
66
67     /**
68      * プログラム実行に必要なコンフィグファイルを作成する.
69      * @return 今回コンフィグを作成したのであればtrue. 既に存在していたため, ファイル作成を行わなかった場合にはfalse.
70      * @throws java.io.IOException ファイル作成に失敗した.
71      */
72     public static boolean createNewConfigFiles() throws IOException {
73         boolean result = false;
74         if (!CONFIG_FILE.exists()) {
75             createNewConfigFile(CONFIG_FILE);
76             result = true;
77             log.info("コンフィグファイルを作成しました: " + CONFIG_FILE.getCanonicalPath());
78         }
79         if (!FEEDURL_FILE.exists()) {
80             InputStream resource = null;
81             try {
82                 resource = ClassLoader.getSystemResourceAsStream("resources/" + FEEDURL_NAME);
83                 createNewFeedFile(resource, FEEDURL_FILE);
84                 result = true;
85                 log.info("FEED URLファイルを作成しました: " + FEEDURL_FILE.getCanonicalPath());
86             } finally {
87                 if (resource != null) {
88                     resource.close();
89                 }
90             }
91         }
92         return result;
93     }
94
95     private static void createNewConfigFile(File file) throws IOException {
96         ArrayList<CharSequence> props = new ArrayList<CharSequence>();
97
98         StringBuilder dbpath = new StringBuilder(P_PATH_DB + "=");
99         File dbDir = new File(APP_HOME, "db");
100         dbDir.mkdirs();
101         //Windowsのパス区切りバックスペースをエスケープするための処理も入れている.
102         dbpath.append(dbDir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
103         props.add(dbpath);
104
105         StringBuilder savepath = new StringBuilder(P_PATH_SAVEFILE + "=");
106         File saveDir = new File(APP_HOME, "flv");
107         saveDir.mkdirs();
108         savepath.append(saveDir.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
109         props.add(savepath);
110
111         props.add(P_FILE_ENCODING + "=" + System.getProperty("file.encoding"));
112
113         props.add(P_NICOVIDEO_MAIL + "=set.your@mail.address");
114         props.add(P_NICOVIDEO_PASSWORD + "=set_your_password");
115         props.add(P_DOWNLOAD_RETRY + "=3");
116         props.add(P_DOWNLOAD_MYLIST + "=");
117
118         FileUtils.writeLines(file, props);
119     }
120
121     private static void createNewFeedFile(InputStream resource, File dest) throws IOException {
122         List<String> list = new ArrayList<String>();
123         BufferedReader br = new BufferedReader(new InputStreamReader(resource, "UTF-8"));
124         while (true) {
125             String text = br.readLine();
126             if (text == null) {
127                 break;
128             }
129             list.add(text);
130         }
131         FileUtils.writeLines(dest, list);
132     }
133
134     private Config() {
135         properties = new Properties();
136         FileInputStream fis = null;
137         try {
138             fis = new FileInputStream(CONFIG_FILE);
139             properties.load(fis);
140         } catch (IOException ex) {
141             log.fatal("コンフィグの読み込みに失敗: " + CONFIG_FILE);
142             throw new RuntimeException(ex);
143         } finally {
144             if (fis != null) {
145                 try {
146                     fis.close();
147                 } catch (IOException ex) {
148                     log.warn("", ex);
149                 }
150             }
151         }
152
153         try {
154             List urls = FileUtils.readLines(FEEDURL_FILE);
155         } catch (IOException ex) {
156             log.fatal("コンフィグの読み込みに失敗: " + CONFIG_FILE);
157             throw new RuntimeException(ex);
158         }
159     }
160
161     public static Config getInstance() {
162         if (instance == null) {
163             instance = new Config();
164         }
165         return instance;
166     }
167
168     /**
169      * @return ニコニコ動画ログインID.
170      */
171     public String getNicoMail() {
172         return properties.getProperty(P_NICOVIDEO_MAIL);
173     }
174
175     /**
176      * @return ニコニコ動画ログインパスワード.
177      */
178     public String getNicoPassword() {
179         return properties.getProperty(P_NICOVIDEO_PASSWORD);
180     }
181
182     /** @return DBパス */
183     public String getDbFile() {
184         return new File(properties.getProperty(P_PATH_DB), "nicodb").getAbsolutePath();
185     }
186
187     /** @return 保存先の指定. */
188     public String getSrcSaveDir() {
189         return properties.getProperty(P_PATH_SAVEFILE);
190     }
191
192     /** @return feedurl.txtの文字エンコーディング. */
193     public String getEncoding() {
194         String res = properties.getProperty(P_FILE_ENCODING, System.getProperty("file.encoding"));
195         return res;
196     }
197 //    /**
198 //     * video/mp4のストリーム保存時、ファイルの拡張子に
199 //     * .mp4を使用する(true)か、使用しない(.flv)か.
200 //     * @return mp4拡張子を使用する場合true.
201 //     */
202 //    public boolean isExtMp4Use() {
203 //        String res = properties.getProperty("download.ext.mp4");
204 //        if ("false".equalsIgnoreCase(res)) {
205 //            return false;
206 //        }
207 //        return true;
208 //    }
209 //
210
211     /**
212      * 失敗したダウンロードファイルの最大リトライ回数を取得する.
213      * @return リトライ回数.
214      */
215     public int getMaxRetry() {
216         String res = properties.getProperty(P_DOWNLOAD_RETRY);
217         return Integer.parseInt(res);
218     }
219 //
220 //    /**
221 //     * 上位何位までの動画をダウンロードするか.
222 //     * @return ダウンロードするファイルの最下位.
223 //     */
224 //    public int getMaxDownloadNumber() {
225 //        String res = properties.getProperty("download.number");
226 //        return Integer.parseInt(res);
227 //    }
228 //
229
230     public List<String> getDownLoadMyList() {
231         List<String> list = new ArrayList<String>();
232         String res = properties.getProperty(P_DOWNLOAD_MYLIST);
233         String[] nums = res.split(",");
234         for (int i = 0; i < nums.length; i++) {
235             String text = nums[i].trim();
236             if (!text.isEmpty()) {
237                 list.add(text);
238             }
239         }
240         return list;
241     }
242
243     public List<NicoFeed> getNicoFeeds() {
244         List<NicoFeed> list = new ArrayList<NicoFeed>();
245         try {
246             List lines = FileUtils.readLines(FEEDURL_FILE, getEncoding());
247             for (Object line : lines) {
248                 final String str = line.toString();
249                 if (str.isEmpty() || str.startsWith("#")) {
250                     // 空行, コメント行はスキップ.
251                     continue;
252                 }
253
254                 String[] values = str.split(",");
255                 NicoFeed feed = new NicoFeed(values[0].trim(), Integer.parseInt(values[1].trim()));
256                 list.add(feed);
257             }
258         } catch (IOException ex) {
259             log.error("ファイルが見つかりません: " + FEEDURL_FILE);
260         }
261         return list;
262     }
263 }