favor DCHECK_CURRENTLY_ON for better logs in content/browser/[a-d]*
[chromium-blink-merge.git] / content / browser / android / download_controller_android_impl.cc
blob353e2611b3e3a6c2aff05471ffcc3430aa4df300
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/android/download_controller_android_impl.h"
7 #include "base/android/jni_android.h"
8 #include "base/android/jni_string.h"
9 #include "base/bind.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/time/time.h"
13 #include "content/browser/android/content_view_core_impl.h"
14 #include "content/browser/android/deferred_download_observer.h"
15 #include "content/browser/download/download_item_impl.h"
16 #include "content/browser/download/download_manager_impl.h"
17 #include "content/browser/loader/resource_dispatcher_host_impl.h"
18 #include "content/browser/renderer_host/render_process_host_impl.h"
19 #include "content/browser/renderer_host/render_view_host_delegate.h"
20 #include "content/browser/renderer_host/render_view_host_impl.h"
21 #include "content/browser/web_contents/web_contents_impl.h"
22 #include "content/public/browser/browser_context.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "content/public/browser/download_url_parameters.h"
25 #include "content/public/browser/global_request_id.h"
26 #include "content/public/browser/resource_request_info.h"
27 #include "content/public/common/referrer.h"
28 #include "jni/DownloadController_jni.h"
29 #include "net/cookies/cookie_options.h"
30 #include "net/cookies/cookie_store.h"
31 #include "net/http/http_content_disposition.h"
32 #include "net/http/http_request_headers.h"
33 #include "net/http/http_response_headers.h"
34 #include "net/url_request/url_request.h"
35 #include "net/url_request/url_request_context.h"
37 using base::android::ConvertUTF8ToJavaString;
38 using base::android::ScopedJavaLocalRef;
40 namespace content {
42 // JNI methods
43 static void Init(JNIEnv* env, jobject obj) {
44 DownloadControllerAndroidImpl::GetInstance()->Init(env, obj);
47 struct DownloadControllerAndroidImpl::JavaObject {
48 ScopedJavaLocalRef<jobject> Controller(JNIEnv* env) {
49 return GetRealObject(env, obj);
51 jweak obj;
54 // static
55 bool DownloadControllerAndroidImpl::RegisterDownloadController(JNIEnv* env) {
56 return RegisterNativesImpl(env);
59 // static
60 DownloadControllerAndroid* DownloadControllerAndroid::Get() {
61 return DownloadControllerAndroidImpl::GetInstance();
64 // static
65 DownloadControllerAndroidImpl* DownloadControllerAndroidImpl::GetInstance() {
66 return Singleton<DownloadControllerAndroidImpl>::get();
69 DownloadControllerAndroidImpl::DownloadControllerAndroidImpl()
70 : java_object_(NULL) {
73 DownloadControllerAndroidImpl::~DownloadControllerAndroidImpl() {
74 if (java_object_) {
75 JNIEnv* env = base::android::AttachCurrentThread();
76 env->DeleteWeakGlobalRef(java_object_->obj);
77 delete java_object_;
78 base::android::CheckException(env);
82 // Initialize references to Java object.
83 void DownloadControllerAndroidImpl::Init(JNIEnv* env, jobject obj) {
84 java_object_ = new JavaObject;
85 java_object_->obj = env->NewWeakGlobalRef(obj);
88 void DownloadControllerAndroidImpl::CancelDeferredDownload(
89 DeferredDownloadObserver* observer) {
90 for (auto iter = deferred_downloads_.begin();
91 iter != deferred_downloads_.end(); ++iter) {
92 if (*iter == observer) {
93 deferred_downloads_.erase(iter);
94 return;
99 void DownloadControllerAndroidImpl::CreateGETDownload(
100 int render_process_id, int render_view_id, int request_id) {
101 DCHECK_CURRENTLY_ON(BrowserThread::IO);
102 GlobalRequestID global_id(render_process_id, request_id);
104 // We are yielding the UI thread and render_view_host may go away by
105 // the time we come back. Pass along render_process_id and render_view_id
106 // to retrieve it later (if it still exists).
107 GetDownloadInfoCB cb = base::Bind(
108 &DownloadControllerAndroidImpl::StartAndroidDownload,
109 base::Unretained(this), render_process_id,
110 render_view_id);
112 PrepareDownloadInfo(
113 global_id,
114 base::Bind(&DownloadControllerAndroidImpl::StartDownloadOnUIThread,
115 base::Unretained(this), cb));
118 void DownloadControllerAndroidImpl::PrepareDownloadInfo(
119 const GlobalRequestID& global_id,
120 const GetDownloadInfoCB& callback) {
121 DCHECK_CURRENTLY_ON(BrowserThread::IO);
123 net::URLRequest* request =
124 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id);
125 if (!request) {
126 LOG(ERROR) << "Request to download not found.";
127 return;
130 DownloadInfoAndroid info_android(request);
132 net::CookieStore* cookie_store = request->context()->cookie_store();
133 if (cookie_store) {
134 net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();
135 if (cookie_monster) {
136 cookie_monster->GetAllCookiesForURLAsync(
137 request->url(),
138 base::Bind(&DownloadControllerAndroidImpl::CheckPolicyAndLoadCookies,
139 base::Unretained(this), info_android, callback,
140 global_id));
141 } else {
142 DoLoadCookies(info_android, callback, global_id);
144 } else {
145 // Can't get any cookies, start android download.
146 callback.Run(info_android);
150 void DownloadControllerAndroidImpl::CheckPolicyAndLoadCookies(
151 const DownloadInfoAndroid& info, const GetDownloadInfoCB& callback,
152 const GlobalRequestID& global_id, const net::CookieList& cookie_list) {
153 DCHECK_CURRENTLY_ON(BrowserThread::IO);
155 net::URLRequest* request =
156 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id);
157 if (!request) {
158 LOG(ERROR) << "Request to download not found.";
159 return;
162 if (request->context()->network_delegate()->CanGetCookies(
163 *request, cookie_list)) {
164 DoLoadCookies(info, callback, global_id);
165 } else {
166 callback.Run(info);
170 void DownloadControllerAndroidImpl::DoLoadCookies(
171 const DownloadInfoAndroid& info, const GetDownloadInfoCB& callback,
172 const GlobalRequestID& global_id) {
173 DCHECK_CURRENTLY_ON(BrowserThread::IO);
175 net::CookieOptions options;
176 options.set_include_httponly();
178 net::URLRequest* request =
179 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id);
180 if (!request) {
181 LOG(ERROR) << "Request to download not found.";
182 return;
185 request->context()->cookie_store()->GetCookiesWithOptionsAsync(
186 info.url, options,
187 base::Bind(&DownloadControllerAndroidImpl::OnCookieResponse,
188 base::Unretained(this), info, callback));
191 void DownloadControllerAndroidImpl::OnCookieResponse(
192 DownloadInfoAndroid download_info,
193 const GetDownloadInfoCB& callback,
194 const std::string& cookie) {
195 download_info.cookie = cookie;
197 // We have everything we need, start Android download.
198 callback.Run(download_info);
201 void DownloadControllerAndroidImpl::StartDownloadOnUIThread(
202 const GetDownloadInfoCB& callback,
203 const DownloadInfoAndroid& info) {
204 DCHECK_CURRENTLY_ON(BrowserThread::IO);
205 BrowserThread::PostTask(
206 BrowserThread::UI, FROM_HERE, base::Bind(callback, info));
209 void DownloadControllerAndroidImpl::StartAndroidDownload(
210 int render_process_id, int render_view_id,
211 const DownloadInfoAndroid& info) {
212 DCHECK_CURRENTLY_ON(BrowserThread::UI);
213 JNIEnv* env = base::android::AttachCurrentThread();
215 // Call newHttpGetDownload
216 WebContents* web_contents = GetWebContents(render_process_id, render_view_id);
217 if (!web_contents) {
218 // The view went away. Can't proceed.
219 LOG(ERROR) << "Download failed on URL:" << info.url.spec();
220 return;
222 ScopedJavaLocalRef<jobject> view =
223 GetContentViewCoreFromWebContents(web_contents);
224 if (view.is_null()) {
225 // ContentViewCore might not have been created yet, pass a callback to
226 // DeferredDownloadTaskManager so that the download can restart when
227 // ContentViewCore is created.
228 deferred_downloads_.push_back(new DeferredDownloadObserver(
229 web_contents,
230 base::Bind(&DownloadControllerAndroidImpl::StartAndroidDownload,
231 base::Unretained(this), render_process_id, render_view_id,
232 info)));
233 return;
235 ScopedJavaLocalRef<jstring> jurl =
236 ConvertUTF8ToJavaString(env, info.url.spec());
237 ScopedJavaLocalRef<jstring> juser_agent =
238 ConvertUTF8ToJavaString(env, info.user_agent);
239 ScopedJavaLocalRef<jstring> jcontent_disposition =
240 ConvertUTF8ToJavaString(env, info.content_disposition);
241 ScopedJavaLocalRef<jstring> jmime_type =
242 ConvertUTF8ToJavaString(env, info.original_mime_type);
243 ScopedJavaLocalRef<jstring> jcookie =
244 ConvertUTF8ToJavaString(env, info.cookie);
245 ScopedJavaLocalRef<jstring> jreferer =
246 ConvertUTF8ToJavaString(env, info.referer);
248 // Try parsing the content disposition header to get a
249 // explicitly specified filename if available.
250 net::HttpContentDisposition header(info.content_disposition, "");
251 ScopedJavaLocalRef<jstring> jfilename =
252 ConvertUTF8ToJavaString(env, header.filename());
254 Java_DownloadController_newHttpGetDownload(
255 env, GetJavaObject()->Controller(env).obj(), view.obj(), jurl.obj(),
256 juser_agent.obj(), jcontent_disposition.obj(), jmime_type.obj(),
257 jcookie.obj(), jreferer.obj(), info.has_user_gesture, jfilename.obj(),
258 info.total_bytes);
261 void DownloadControllerAndroidImpl::OnDownloadStarted(
262 DownloadItem* download_item) {
263 DCHECK_CURRENTLY_ON(BrowserThread::UI);
264 if (!download_item->GetWebContents())
265 return;
267 JNIEnv* env = base::android::AttachCurrentThread();
269 // Register for updates to the DownloadItem.
270 download_item->AddObserver(this);
272 ScopedJavaLocalRef<jobject> view =
273 GetContentViewCoreFromWebContents(download_item->GetWebContents());
274 // The view went away. Can't proceed.
275 if (view.is_null())
276 return;
278 ScopedJavaLocalRef<jstring> jmime_type =
279 ConvertUTF8ToJavaString(env, download_item->GetMimeType());
280 ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
281 env, download_item->GetTargetFilePath().BaseName().value());
282 Java_DownloadController_onDownloadStarted(
283 env, GetJavaObject()->Controller(env).obj(), view.obj(), jfilename.obj(),
284 jmime_type.obj());
287 void DownloadControllerAndroidImpl::OnDownloadUpdated(DownloadItem* item) {
288 DCHECK_CURRENTLY_ON(BrowserThread::UI);
289 if (item->IsDangerous() && (item->GetState() != DownloadItem::CANCELLED))
290 OnDangerousDownload(item);
292 JNIEnv* env = base::android::AttachCurrentThread();
293 ScopedJavaLocalRef<jstring> jurl =
294 ConvertUTF8ToJavaString(env, item->GetURL().spec());
295 ScopedJavaLocalRef<jstring> jmime_type =
296 ConvertUTF8ToJavaString(env, item->GetMimeType());
297 ScopedJavaLocalRef<jstring> jpath =
298 ConvertUTF8ToJavaString(env, item->GetTargetFilePath().value());
299 ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
300 env, item->GetTargetFilePath().BaseName().value());
302 switch (item->GetState()) {
303 case DownloadItem::IN_PROGRESS: {
304 base::TimeDelta time_delta;
305 item->TimeRemaining(&time_delta);
306 Java_DownloadController_onDownloadUpdated(
307 env, GetJavaObject()->Controller(env).obj(),
308 base::android::GetApplicationContext(), jurl.obj(), jmime_type.obj(),
309 jfilename.obj(), jpath.obj(), item->GetReceivedBytes(), true,
310 item->GetId(), item->PercentComplete(), time_delta.InMilliseconds());
311 break;
313 case DownloadItem::COMPLETE:
314 // Multiple OnDownloadUpdated() notifications may be issued while the
315 // download is in the COMPLETE state. Only handle one.
316 item->RemoveObserver(this);
318 // Call onDownloadCompleted
319 Java_DownloadController_onDownloadCompleted(
320 env, GetJavaObject()->Controller(env).obj(),
321 base::android::GetApplicationContext(), jurl.obj(), jmime_type.obj(),
322 jfilename.obj(), jpath.obj(), item->GetReceivedBytes(), true,
323 item->GetId());
324 break;
325 case DownloadItem::CANCELLED:
326 // TODO(shashishekhar): An interrupted download can be resumed. Android
327 // currently does not support resumable downloads. Add handling for
328 // interrupted case based on item->CanResume().
329 case DownloadItem::INTERRUPTED:
330 // Call onDownloadCompleted with success = false.
331 Java_DownloadController_onDownloadCompleted(
332 env, GetJavaObject()->Controller(env).obj(),
333 base::android::GetApplicationContext(), jurl.obj(), jmime_type.obj(),
334 jfilename.obj(), jpath.obj(), item->GetReceivedBytes(), false,
335 item->GetId());
336 break;
337 case DownloadItem::MAX_DOWNLOAD_STATE:
338 NOTREACHED();
342 void DownloadControllerAndroidImpl::OnDangerousDownload(DownloadItem* item) {
343 JNIEnv* env = base::android::AttachCurrentThread();
344 ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
345 env, item->GetTargetFilePath().BaseName().value());
346 ScopedJavaLocalRef<jobject> view_core = GetContentViewCoreFromWebContents(
347 item->GetWebContents());
348 if (!view_core.is_null()) {
349 Java_DownloadController_onDangerousDownload(
350 env, GetJavaObject()->Controller(env).obj(), view_core.obj(),
351 jfilename.obj(), item->GetId());
355 WebContents* DownloadControllerAndroidImpl::GetWebContents(
356 int render_process_id, int render_view_id) {
357 RenderViewHost* render_view_host =
358 RenderViewHost::FromID(render_process_id, render_view_id);
360 if (!render_view_host)
361 return NULL;
363 return render_view_host->GetDelegate()->GetAsWebContents();
366 ScopedJavaLocalRef<jobject>
367 DownloadControllerAndroidImpl::GetContentViewCoreFromWebContents(
368 WebContents* web_contents) {
369 if (!web_contents)
370 return ScopedJavaLocalRef<jobject>();
372 ContentViewCore* view_core = ContentViewCore::FromWebContents(web_contents);
373 return view_core ? view_core->GetJavaObject() :
374 ScopedJavaLocalRef<jobject>();
377 DownloadControllerAndroidImpl::JavaObject*
378 DownloadControllerAndroidImpl::GetJavaObject() {
379 if (!java_object_) {
380 // Initialize Java DownloadController by calling
381 // DownloadController.getInstance(), which will call Init()
382 // if Java DownloadController is not instantiated already.
383 JNIEnv* env = base::android::AttachCurrentThread();
384 Java_DownloadController_getInstance(env);
387 DCHECK(java_object_);
388 return java_object_;
391 void DownloadControllerAndroidImpl::StartContextMenuDownload(
392 const ContextMenuParams& params, WebContents* web_contents, bool is_link) {
393 const GURL& url = is_link ? params.link_url : params.src_url;
394 const GURL& referring_url = params.frame_url.is_empty() ?
395 params.page_url : params.frame_url;
396 DownloadManagerImpl* dlm = static_cast<DownloadManagerImpl*>(
397 BrowserContext::GetDownloadManager(web_contents->GetBrowserContext()));
398 scoped_ptr<DownloadUrlParameters> dl_params(
399 DownloadUrlParameters::FromWebContents(web_contents, url));
400 content::Referrer referrer = content::Referrer::SanitizeForRequest(
401 url,
402 content::Referrer(referring_url.GetAsReferrer(),
403 params.referrer_policy));
404 dl_params->set_referrer(referrer);
405 if (is_link)
406 dl_params->set_referrer_encoding(params.frame_charset);
407 else
408 dl_params->set_prefer_cache(true);
409 dl_params->set_prompt(false);
410 dlm->DownloadUrl(dl_params.Pass());
413 void DownloadControllerAndroidImpl::DangerousDownloadValidated(
414 WebContents* web_contents, int download_id, bool accept) {
415 if (!web_contents)
416 return;
417 DownloadManagerImpl* dlm = static_cast<DownloadManagerImpl*>(
418 BrowserContext::GetDownloadManager(web_contents->GetBrowserContext()));
419 DownloadItem* item = dlm->GetDownload(download_id);
420 if (!item)
421 return;
422 if (accept)
423 item->ValidateDangerousDownload();
424 else
425 item->Remove();
428 DownloadControllerAndroidImpl::DownloadInfoAndroid::DownloadInfoAndroid(
429 net::URLRequest* request)
430 : has_user_gesture(false) {
431 request->GetResponseHeaderByName("content-disposition", &content_disposition);
433 if (request->response_headers())
434 request->response_headers()->GetMimeType(&original_mime_type);
436 request->extra_request_headers().GetHeader(
437 net::HttpRequestHeaders::kUserAgent, &user_agent);
438 GURL referer_url(request->referrer());
439 if (referer_url.is_valid())
440 referer = referer_url.spec();
441 if (!request->url_chain().empty()) {
442 original_url = request->url_chain().front();
443 url = request->url_chain().back();
446 const content::ResourceRequestInfo* info =
447 content::ResourceRequestInfo::ForRequest(request);
448 if (info)
449 has_user_gesture = info->HasUserGesture();
452 DownloadControllerAndroidImpl::DownloadInfoAndroid::~DownloadInfoAndroid() {}
454 } // namespace content