OSDN Git Service

バージョン, 更新履歴を更新
[coroid/NicoBrowser.git] / src / nicobrowser / main / Main.java
1 /*$Id$*/
2 package nicobrowser.main;
3
4 import java.io.File;
5 import java.util.ArrayList;
6 import java.util.Calendar;
7 import java.util.Date;
8 import java.util.HashMap;
9 import java.util.List;
10 import javax.persistence.EntityManager;
11 import javax.persistence.EntityManagerFactory;
12 import javax.persistence.EntityTransaction;
13 import javax.persistence.Persistence;
14 import javax.persistence.Query;
15 import javax.swing.JFrame;
16 import javax.swing.SwingUtilities;
17 import nicobrowser.config.Config;
18 import nicobrowser.GetFlvResult;
19 import nicobrowser.NamePattern;
20 import nicobrowser.NicoHttpClient;
21 import nicobrowser.ProgressListener;
22 import nicobrowser.VideoInfo;
23 import nicobrowser.config.NicoFeed;
24 import nicobrowser.entity.NicoContent;
25 import nicobrowser.entity.NicoContent.Status;
26 import nicobrowser.gui.config.ConfigFrame;
27 import nicobrowser.update.DBUpdater;
28 import org.apache.commons.cli.CommandLine;
29 import org.apache.commons.cli.CommandLineParser;
30 import org.apache.commons.cli.HelpFormatter;
31 import org.apache.commons.cli.Options;
32 import org.apache.commons.cli.ParseException;
33 import org.apache.commons.cli.PosixParser;
34 import org.apache.commons.io.FilenameUtils;
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37
38 public class Main {
39
40     public static final String VERSION = "version 0.9.2";
41     private static Log log = LogFactory.getLog(Main.class);
42
43     public static void main(String[] args) throws Exception {
44         final boolean res = Config.createNewConfigFiles();
45
46         CommandLineParser parser = new PosixParser();
47         Options options = createOptions();
48
49         try {
50             // parse the command line arguments
51             CommandLine line = parser.parse(options, args);
52
53             if (line.hasOption("help")) {
54                 new HelpFormatter().printHelp("java -jar NicoBrowser.jar [option]", options);
55                 return;
56             } else if (line.hasOption("version")) {
57                 System.out.println(VERSION);
58                 return;
59             } else if (line.hasOption("property")) {
60                 propertyOpen();
61                 return;
62             }
63         } catch (ParseException exp) {
64             HelpFormatter formatter = new HelpFormatter();
65             formatter.printHelp("java -jar NicoBrowser.jar [option]", options);
66             return;
67         }
68
69         if (res) {
70             propertyOpen();
71             return;
72         }
73
74         DBUpdater updater = new DBUpdater();
75         if (args.length > 0 && "sync".equals(args[0])) {
76             updater.sync();
77             return;
78         } else if (args.length > 0 && "sync4".equals(args[0])) {
79             updater.sync_for_4();
80             return;
81         }
82         updater.update();
83
84         new Main().start();
85     }
86
87     private static Options createOptions() throws IllegalArgumentException {
88         Options options = new Options();
89         options.addOption("h", "help", false, "このメッセージを表示します");
90         options.addOption("p", "property", false, "コンフィグ設定画面を起動します");
91         options.addOption("v", "version", false, "バージョン情報を表示します");
92         return options;
93     }
94
95     private static void propertyOpen() {
96         SwingUtilities.invokeLater(new Runnable() {
97
98             public void run() {
99                 ConfigFrame.setLookAndFeel();
100                 JFrame frame = new ConfigFrame();
101                 frame.setLocationByPlatform(true);
102                 frame.setVisible(true);
103             }
104         });
105     }
106
107     public void start() {
108         log.info("program start");
109
110         final Config config = Config.getInstance();
111         List<NicoContent> dailyList = new ArrayList<NicoContent>();
112         ArrayList<List<NicoContent>> myLists = new ArrayList<List<NicoContent>>();
113         NicoHttpClient instance = null;
114         try {
115             log.info("リストを取得します");
116             instance = new NicoHttpClient();
117             List<NicoFeed> feeds = config.getNicoFeeds();
118             for (NicoFeed f : feeds) {
119                 List<NicoContent> list = instance.getContentsFromRss(f.getUrl());
120                 int count = 0;
121                 for (NicoContent l : list) {
122                     if (count >= f.getNumber()) {
123                         break;
124                     }
125                     dailyList.add(l);
126                     count++;
127                 }
128             }
129             List<String> mylists = config.getDownLoadMyList();
130             for (String l : mylists) {
131                 List<NicoContent> list = instance.loadMyList(l);
132                 myLists.add(list);
133             }
134         } catch (Exception e) {
135             e.printStackTrace();
136             return;
137         }
138
139         log.info("今回取得したデータを過去の取得データと比較します");
140
141         EntityManagerFactory factory;
142         EntityManager manager;
143
144         HashMap<String, String> map = new HashMap<String, String>();
145         map.put("toplink.jdbc.url", "jdbc:h2:" + config.getDbFile());
146         factory = Persistence.createEntityManagerFactory("NicoBrowserPU", map);
147         manager = factory.createEntityManager();
148
149         EntityTransaction transaction = manager.getTransaction();
150
151         transaction.begin();
152         try {
153             // ランキング上位のコンテンツ保存
154             int num = 0;
155             for (NicoContent c : dailyList) {
156                 save(manager, c);
157                 num++;
158             }
159
160             // マイリストに登録したコンテンツ保存
161             for (List<NicoContent> l : myLists) {
162                 for (NicoContent c : l) {
163                     save(manager, c);
164                 }
165             }
166
167             transaction.commit();
168
169             Query query = manager.createQuery("SELECT cont FROM NicoContent AS cont " + "WHERE ?1 <> cont.status").
170                     setParameter(1, NicoContent.Status.GET_FILE);
171             List<NicoContent> results = query.getResultList();
172             instance.login(config.getNicoMail(), config.getNicoPassword());
173             Date prevDate = null;
174             for (NicoContent c : results) {
175                 if (c.getFailTimes() >= config.getMaxRetry()) {
176                     continue;
177                 }
178                 if (prevDate != null) {
179                     Date nowDate = Calendar.getInstance().getTime();
180                     long sleep = nowDate.getTime() - prevDate.getTime();
181                     sleep = config.getWaitTime() * 1000 - sleep;
182                     if (sleep > 0) {
183                         log.info("" + sleep / 1000 + "秒待機します。");
184                         try {
185                             Thread.sleep(sleep);
186                         } catch (InterruptedException e) {
187                             log.info("スリープ中断", e);
188                         }
189                     }
190                 }
191                 prevDate = Calendar.getInstance().getTime();
192                 File saveDir = new File(config.getSrcSaveDir());
193                 NamePattern np = new NamePattern(config.getFileNamePattern(), config.getFileNameReplaceFrom(), config.
194                         getFileNameReplaceTo(), c.getTitle());
195                 log.info("ファイルを取得します: " + c.getNicoId() + " " + c.getTitle());
196                 try {
197                     VideoInfo vi = instance.getVideoInfo(c.getNicoId());
198                     GetFlvResult result = instance.getFlvFile(vi, saveDir, np, c.getStatus(), config.needLowFile(),
199                             ProgressListener.EMPTY_LISTENER);
200
201                     c.setFileName(FilenameUtils.getBaseName(result.getFile().toString()));
202                     c.setAuthor(result.getAuthor());
203                     Status status = result.getStatus();
204                     c.setStatus(status);
205                     if (status == Status.GET_INFO) {
206                         c.setFailTimes(c.getFailTimes() + 1);
207                     }
208                 } catch (Exception ex) {
209                     c.setFailTimes(c.getFailTimes() + 1);
210                     log.error("ファイル取得に失敗しました: " + c.getNicoId() + ", 通算失敗回数: " + c.getFailTimes(), ex);
211                 }
212                 transaction.begin();
213                 manager.persist(c);
214                 transaction.commit();
215                 log.info("完了しました");
216             }
217         } catch (Exception ex) {
218             ex.printStackTrace();
219             transaction.rollback();
220         } finally {
221             manager.close();
222             factory.close();
223         }
224
225     }
226
227     private void save(EntityManager manager, NicoContent c) {
228         Query query = manager.createQuery("SELECT cont FROM NicoContent AS cont " + "WHERE ?1 = cont.nicoId").
229                 setParameter(1, c.getNicoId());
230         List<NicoContent> resList = query.getResultList();
231         if (resList.isEmpty()) {
232             log.info("NEW! " + c.getNicoId() + " : " + c.getTitle());
233             manager.persist(c);
234         }
235     }
236 }