OSDN Git Service

コンフィグを用いた禁則文字置換を実装
[coroid/NicoBrowser.git] / src / nicobrowser / main / Main.java
index c12a527..e39c480 100644 (file)
@@ -1,12 +1,8 @@
 /*$Id$*/
 package nicobrowser.main;
 
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import nicobrowser.*;
 import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
@@ -17,28 +13,122 @@ import javax.persistence.EntityManagerFactory;
 import javax.persistence.EntityTransaction;
 import javax.persistence.Persistence;
 import javax.persistence.Query;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import nicobrowser.Config;
+import nicobrowser.GetFlvResult;
+import nicobrowser.Config.NicoFeed;
+import nicobrowser.NamePattern;
+import nicobrowser.NicoHttpClient;
+import nicobrowser.ProgressListener;
+import nicobrowser.VideoInfo;
 import nicobrowser.entity.NicoContent;
 import nicobrowser.entity.NicoContent.Status;
-import org.apache.http.HttpException;
+import nicobrowser.gui.config.ConfigFrame;
+import nicobrowser.update.DBUpdater;
+import nicobrowser.util.Util;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 
 public class Main {
 
-    public static void main(String[] args) {
-        System.out.println("Start");
-        new Main();
+    public static final String VERSION = "version 0.5.1";
+    private static Log log = LogFactory.getLog(Main.class);
+
+    public static void main(String[] args) throws IOException {
+        final boolean res = Config.createNewConfigFiles();
+
+        CommandLineParser parser = new PosixParser();
+        Options options = createOptions();
+
+        try {
+            // parse the command line arguments
+            CommandLine line = parser.parse(options, args);
+
+            if (line.hasOption("help")) {
+                new HelpFormatter().printHelp("java -jar NicoBrowser.jar [option]", options);
+                return;
+            } else if (line.hasOption("version")) {
+                System.out.println(VERSION);
+                return;
+            } else if (line.hasOption("property")) {
+                propertyOpen();
+                return;
+            }
+        } catch (ParseException exp) {
+            HelpFormatter formatter = new HelpFormatter();
+            formatter.printHelp("java -jar NicoBrowser.jar [option]", options);
+            return;
+        }
+
+        if (res) {
+            propertyOpen();
+            return;
+        }
+
+        DBUpdater updater = new DBUpdater();
+        if (args.length > 0 && "sync".equals(args[0])) {
+            updater.sync();
+            return;
+        } else if (args.length > 0 && "sync4".equals(args[0])) {
+            updater.sync_for_4();
+            return;
+        }
+        updater.update();
+
+        new Main().start();
+    }
+
+    private static Options createOptions() throws IllegalArgumentException {
+        Options options = new Options();
+        options.addOption("h", "help", false, "このメッセージを表示します");
+        options.addOption("p", "property", false, "コンフィグ設定画面を起動します");
+        options.addOption("v", "version", false, "バージョン情報を表示します");
+        return options;
+    }
+
+    private static void propertyOpen() {
+        SwingUtilities.invokeLater(new Runnable() {
+
+            public void run() {
+                ConfigFrame.setLookAndFeel();
+                JFrame frame = new ConfigFrame();
+                frame.setLocationByPlatform(true);
+                frame.setVisible(true);
+            }
+        });
     }
 
-    public Main() {
-        Config config = Config.getInstance();
-        List<NicoContent> dailyList = null;
+    public void start() {
+        log.info("program start");
+
+        final Config config = Config.getInstance();
+        List<NicoContent> dailyList = new ArrayList<NicoContent>();
         ArrayList<List<NicoContent>> myLists = new ArrayList<List<NicoContent>>();
         NicoHttpClient instance = null;
         try {
-            System.out.println("リストの取得");
-            instance = NicoHttpClient.getInstance();
-            //list = instance.loadMyList("4315046");
-            dailyList = instance.loadMyListDaily();
-            String[] mylists = config.getDownLoadMyList();
+            log.info("リストを取得します");
+            instance = new NicoHttpClient();
+            List<NicoFeed> feeds = config.getNicoFeeds();
+            for (NicoFeed f : feeds) {
+                List<NicoContent> list = instance.getContentsFromRss(f.getUrl());
+                int count = 0;
+                for (NicoContent l : list) {
+                    if (count >= f.getNumber()) {
+                        break;
+                    }
+                    dailyList.add(l);
+                    count++;
+                }
+            }
+            List<String> mylists = config.getDownLoadMyList();
             for (String l : mylists) {
                 List<NicoContent> list = instance.loadMyList(l);
                 myLists.add(list);
@@ -48,12 +138,13 @@ public class Main {
             return;
         }
 
-        System.out.println("DBとの突合せ");
+        log.info("今回取得したデータを過去の取得データと比較します");
+
         EntityManagerFactory factory;
         EntityManager manager;
 
         HashMap<String, String> map = new HashMap<String, String>();
-        map.put("toplink.jdbc.url", "jdbc:h2:" + config.getDbPath());
+        map.put("toplink.jdbc.url", "jdbc:h2:" + config.getDbFile());
         factory = Persistence.createEntityManagerFactory("NicoBrowserPU", map);
         manager = factory.createEntityManager();
 
@@ -64,9 +155,6 @@ public class Main {
             // ランキング上位のコンテンツ保存
             int num = 0;
             for (NicoContent c : dailyList) {
-                if (num >= config.getMaxDownloadNumber()) {
-                    break;
-                }
                 save(manager, c);
                 num++;
             }
@@ -86,37 +174,47 @@ public class Main {
             instance.login(config.getNicoMail(), config.getNicoPassword());
             Date prevDate = null;
             for (NicoContent c : results) {
-                if (c.getFailTimes() > config.getMaxRetry() + 1) {
+                if (c.getFailTimes() >= config.getMaxRetry()) {
                     continue;
                 }
                 if (prevDate != null) {
                     Date nowDate = Calendar.getInstance().getTime();
                     long sleep = nowDate.getTime() - prevDate.getTime();
-                    sleep = 5000 - sleep;
+                    sleep = config.getWaitTime() * 1000 - sleep;
                     if (sleep > 0) {
-                        System.out.print("" + sleep + "ms sleep");
-                        Thread.sleep(sleep);
+                        log.info("" + sleep / 1000 + "秒待機します。");
+                        try {
+                            Thread.sleep(sleep);
+                        } catch (InterruptedException e) {
+                            log.info("スリープ中断", e);
+                        }
                     }
                 }
                 prevDate = Calendar.getInstance().getTime();
-                System.out.print("FLVファイル取得: " + config.getSrcSaveDir() + File.separator + c.getFileName());
-                Status status;
+                File saveDir = new File(config.getSrcSaveDir());
+                NamePattern np = new NamePattern(config.getFileNamePattern(), config.getFileNameReplaceFrom(), config.
+                        getFileNameReplaceTo(), Util.getRegularFileName(c.getTitle()));
+                log.info("ファイルを取得します: " + c.getNicoId() + " " + c.getTitle());
                 try {
-                    status = instance.getFlvFile(c.getNicoId(),
-                            config.getSrcSaveDir() + File.separator + c.getFileName(), c.getStatus(),
-                            config.isExtMp4Use());
+                    VideoInfo vi = instance.getVideoInfo(c.getNicoId());
+                    GetFlvResult result = instance.getFlvFile(vi, saveDir, np, c.getStatus(), config.needLowFile(),
+                            ProgressListener.EMPTY_LISTENER);
+
+                    c.setFileName(FilenameUtils.getBaseName(result.getFile().toString()));
+                    c.setAuthor(result.getAuthor());
+                    Status status = result.getStatus();
                     c.setStatus(status);
                     if (status == Status.GET_INFO) {
                         c.setFailTimes(c.getFailTimes() + 1);
                     }
                 } catch (Exception ex) {
-                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                     c.setFailTimes(c.getFailTimes() + 1);
+                    log.error("ファイル取得に失敗しました: " + c.getNicoId() + ", 通算失敗回数: " + c.getFailTimes(), ex);
                 }
                 transaction.begin();
                 manager.persist(c);
                 transaction.commit();
-                System.out.println("...完了");
+                log.info("完了しました");
             }
         } catch (Exception ex) {
             ex.printStackTrace();
@@ -133,7 +231,7 @@ public class Main {
                 setParameter(1, c.getNicoId());
         List<NicoContent> resList = query.getResultList();
         if (resList.isEmpty()) {
-            System.out.println("NEW! " + c.getNicoId() + " : " + c.getFileName());
+            log.info("NEW! " + c.getNicoId() + " : " + c.getTitle());
             manager.persist(c);
         }
     }