OSDN Git Service

置換文字設定を削除
[coroid/inqubus.git] / frontend / src / saccubus / worker / impl / download / Download.java
1 package saccubus.worker.impl.download;
2
3 import static saccubus.worker.impl.download.DownloadStatus.*;
4
5 import java.io.File;
6 import java.io.IOException;
7 import java.util.Date;
8 import java.util.EnumSet;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11 import nicobrowser.DownloadCommentType;
12 import nicobrowser.GetFlvResult;
13 import nicobrowser.NamePattern;
14 import nicobrowser.NicoHttpClient;
15 import nicobrowser.ProgressListener;
16 import nicobrowser.WayBackInfo;
17 import nicobrowser.entity.NicoContent.Status;
18 import saccubus.worker.Worker;
19 import saccubus.worker.WorkerListener;
20 import saccubus.worker.profile.CommentProfile;
21 import saccubus.worker.profile.GeneralProfile;
22 import saccubus.worker.profile.DownloadProfile;
23 import saccubus.worker.profile.ProxyProfile;
24
25 /**
26  * <p>タイトル: さきゅばす</p>
27  *
28  * <p>説明: ニコニコ動画の動画をコメントつきで保存</p>
29  *
30  * <p>著作権: Copyright (c) 2007 PSI</p>
31  *
32  * <p>会社名: </p>
33  *
34  * @author 未入力
35  * @version 1.0
36  */
37 public class Download extends Worker<DownloadResult, DownloadProgress> {
38
39     private static final Logger logger = LoggerFactory.getLogger(Download.class);
40     private static final Object timeLockObj = new Object();
41     private static volatile long lastStartTime = 0L;
42     private final DownloadProfile profile;
43     private final String videoId;
44     private final int waitDownload;
45
46     public Download(DownloadProfile profile, String videoId) {
47         this(profile, videoId, null, 30);
48     }
49
50     /**
51      * コンバータを構築します.
52      * @param videoId 対象となる動画のID.
53      * @param time
54      * @param profile
55      * @param listener
56      * @param flag
57      */
58     public Download(DownloadProfile profile, String videoId, WorkerListener<DownloadResult, DownloadProgress> listener,
59             int wait) {
60         super(listener);
61         this.videoId = videoId;
62         this.profile = profile;
63         this.waitDownload = wait;
64     }
65
66     @Override
67     public DownloadResult work() throws Exception {
68         waitAndGo();
69
70         publish(new DownloadProgress(PROCESS, 0.0, "ログイン中"));
71
72         NicoHttpClient client = null;
73         nicobrowser.VideoInfo vi = null;
74         NamePattern videoNamePattern = null;
75         WayBackInfo wbi = null;
76         if (needsLogin()) {
77             client = createClientAndLogin();
78             vi = client.getVideoInfo(videoId);
79
80             final String name = profile.getVideoProfile().getFileName();
81             videoNamePattern = new NamePattern(name, vi.getTitleInWatchPage());
82
83             if (needsBackLog()) {
84                 final String key = client.getWayBackKey(vi);
85                 wbi = new WayBackInfo(key, profile.getCommentProfile().getBackLogPoint());
86             }
87         }
88
89         checkStop();
90
91         File commentFile;
92         if (profile.getCommentProfile().isDownload()) {
93             final CommentProfile prof = profile.getCommentProfile();
94             final GeneralProfile gene = profile.getGeneralProfile();
95
96             final NamePattern pattern = new NamePattern(prof.getFileName(), vi.getTitleInWatchPage());
97             // TODO コメントファイルに{low}は使えないことをどこかに書くべきか
98             final String name = pattern.createFileName(videoId, true);
99             final File file = new File(profile.getCommentProfile().getDir(), name);
100
101             final EnumSet<DownloadCommentType> commentSet = EnumSet.of(DownloadCommentType.OWNER);
102             if (profile.getCommentProfile().isDisablePerMinComment()) {
103                 commentSet.add(DownloadCommentType.COMMENT_OLD);
104             } else {
105                 commentSet.add(DownloadCommentType.COMMENT);
106             }
107             commentFile = client.getCommentFile(vi, file.getPath(), commentSet, wbi, profile.getCommentProfile().
108                     getLengthRelatedCommentSize());
109         } else {
110             commentFile = profile.getCommentProfile().getLocalFile();
111         }
112
113         checkStop();
114
115         File videoFile;
116         GetFlvResult vf;
117         if (profile.getVideoProfile().isDownload()) {
118             vf = client.getFlvFile(vi, profile.getVideoProfile().getDir(), videoNamePattern,
119                     Status.GET_INFO, true, new ProgressListener() {
120
121                 @Override
122                 public void progress(long fileSize, long downloadSize) {
123                     final double vol = (double) downloadSize / (double) fileSize * 100.0;
124                     publish(new DownloadProgress(PROCESS, vol, String.format("ダウンロード%.2f%%", vol)));
125                 }
126             });
127
128             videoFile = vf.getFile();
129         } else {
130             videoFile = profile.getVideoProfile().getLocalFile();
131         }
132
133         return new DownloadResult(true, videoFile, commentFile);
134     }
135
136     /** @return 何かダウンロードするものがあればtrue. */
137     private static boolean needsDownload(DownloadProfile profile) {
138         return (profile.getVideoProfile().isDownload() || profile.getCommentProfile().isDownload());
139     }
140
141     /**
142      * HttpClientを生成し, ニコニコ動画サーバへログインします.
143      * @return 生成したHttpClientインスタンス.
144      * @throws IOException ログイン失敗.
145      * @throws InterruptedException ログイン失敗.
146      */
147     private NicoHttpClient createClientAndLogin() throws IOException, InterruptedException {
148         final NicoHttpClient client = createClient(profile.getProxyProfile());
149         if (profile.getLoginProfile().needsLogin()) {
150
151             final boolean hasLogin = client.login(profile.getLoginProfile().getMail(), profile.getLoginProfile().
152                     getPassword());
153             if (!hasLogin) {
154                 throw new IOException("login failed");
155             }
156         } else {
157             client.addCookie(profile.getLoginProfile().getCookies());
158         }
159
160         boolean hasLogin = client.challengeAuth();
161         if (!hasLogin) {
162             throw new IOException("invalid session(wrong id/pass or cookie parameter)");
163         }
164
165         return client;
166     }
167
168     private NicoHttpClient createClient(ProxyProfile proxy) {
169         if (proxy.use()) {
170             return new NicoHttpClient(proxy.getHost(), proxy.getPort());
171         } else {
172             return new NicoHttpClient();
173         }
174     }
175
176     /** @return ログインする必要があればtrue. */
177     private boolean needsLogin() {
178         return profile.getVideoProfile().isDownload() || profile.getCommentProfile().isDownload();
179     }
180
181     /** @return 過去ログ取得の必要があればtrue. */
182     private boolean needsBackLog() {
183         return profile.getCommentProfile().getBackLogPoint() >= 0L;
184     }
185
186     private void checkStop() throws InterruptedException {
187         if (Thread.interrupted()) {
188             throw new InterruptedException("中止要求を受け付けました");
189         }
190     }
191
192     /**
193      * ニコニコ動画サービスに連続アクセスするとはじかれるため, 前回のアクセス開始時刻から一定期間は
194      * 次のアクセスに行かないよう待機する必要があります.
195      * @throws InterruptedException 中断されました.
196      */
197     private void waitAndGo() throws InterruptedException {
198         synchronized (timeLockObj) {
199             final long now = new Date().getTime();
200             final long needSleep = (waitDownload * 1000L) - (now - lastStartTime);
201             if (needSleep > 0L) {
202                 publish(new DownloadProgress(DownloadStatus.PROCESS, -1.0, "過剰アクセス抑制待機 " + needSleep / 1000));
203                 Thread.sleep(needSleep);
204             }
205             lastStartTime = new Date().getTime();
206         }
207     }
208 }