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"
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
;
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
);
55 bool DownloadControllerAndroidImpl::RegisterDownloadController(JNIEnv
* env
) {
56 return RegisterNativesImpl(env
);
60 DownloadControllerAndroid
* DownloadControllerAndroid::Get() {
61 return DownloadControllerAndroidImpl::GetInstance();
65 DownloadControllerAndroidImpl
* DownloadControllerAndroidImpl::GetInstance() {
66 return Singleton
<DownloadControllerAndroidImpl
>::get();
69 DownloadControllerAndroidImpl::DownloadControllerAndroidImpl()
70 : java_object_(NULL
) {
73 DownloadControllerAndroidImpl::~DownloadControllerAndroidImpl() {
75 JNIEnv
* env
= base::android::AttachCurrentThread();
76 env
->DeleteWeakGlobalRef(java_object_
->obj
);
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
);
99 void DownloadControllerAndroidImpl::CreateGETDownload(
100 int render_process_id
, int render_view_id
, int request_id
) {
101 DCHECK(BrowserThread::CurrentlyOn(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
,
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(BrowserThread::CurrentlyOn(BrowserThread::IO
));
123 net::URLRequest
* request
=
124 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id
);
126 LOG(ERROR
) << "Request to download not found.";
130 DownloadInfoAndroid
info_android(request
);
132 net::CookieStore
* cookie_store
= request
->context()->cookie_store();
134 net::CookieMonster
* cookie_monster
= cookie_store
->GetCookieMonster();
135 if (cookie_monster
) {
136 cookie_monster
->GetAllCookiesForURLAsync(
138 base::Bind(&DownloadControllerAndroidImpl::CheckPolicyAndLoadCookies
,
139 base::Unretained(this), info_android
, callback
,
142 DoLoadCookies(info_android
, callback
, global_id
);
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(BrowserThread::CurrentlyOn(BrowserThread::IO
));
155 net::URLRequest
* request
=
156 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id
);
158 LOG(ERROR
) << "Request to download not found.";
162 if (request
->context()->network_delegate()->CanGetCookies(
163 *request
, cookie_list
)) {
164 DoLoadCookies(info
, callback
, global_id
);
170 void DownloadControllerAndroidImpl::DoLoadCookies(
171 const DownloadInfoAndroid
& info
, const GetDownloadInfoCB
& callback
,
172 const GlobalRequestID
& global_id
) {
173 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
175 net::CookieOptions options
;
176 options
.set_include_httponly();
178 net::URLRequest
* request
=
179 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id
);
181 LOG(ERROR
) << "Request to download not found.";
185 request
->context()->cookie_store()->GetCookiesWithOptionsAsync(
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(BrowserThread::CurrentlyOn(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(BrowserThread::CurrentlyOn(BrowserThread::UI
));
213 JNIEnv
* env
= base::android::AttachCurrentThread();
215 // Call newHttpGetDownload
216 WebContents
* web_contents
= GetWebContents(render_process_id
, render_view_id
);
218 // The view went away. Can't proceed.
219 LOG(ERROR
) << "Download failed on URL:" << info
.url
.spec();
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(
230 base::Bind(&DownloadControllerAndroidImpl::StartAndroidDownload
,
231 base::Unretained(this), render_process_id
, render_view_id
,
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(),
261 void DownloadControllerAndroidImpl::OnDownloadStarted(
262 DownloadItem
* download_item
) {
263 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
264 if (!download_item
->GetWebContents())
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.
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(),
287 void DownloadControllerAndroidImpl::OnDownloadUpdated(DownloadItem
* item
) {
288 DCHECK(BrowserThread::CurrentlyOn(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());
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,
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,
337 case DownloadItem::MAX_DOWNLOAD_STATE
:
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
)
363 return render_view_host
->GetDelegate()->GetAsWebContents();
366 ScopedJavaLocalRef
<jobject
>
367 DownloadControllerAndroidImpl::GetContentViewCoreFromWebContents(
368 WebContents
* 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() {
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_
);
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(
402 content::Referrer(referring_url
.GetAsReferrer(),
403 params
.referrer_policy
));
404 dl_params
->set_referrer(referrer
);
406 dl_params
->set_referrer_encoding(params
.frame_charset
);
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
) {
417 DownloadManagerImpl
* dlm
= static_cast<DownloadManagerImpl
*>(
418 BrowserContext::GetDownloadManager(web_contents
->GetBrowserContext()));
419 DownloadItem
* item
= dlm
->GetDownload(download_id
);
423 item
->ValidateDangerousDownload();
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
);
449 has_user_gesture
= info
->HasUserGesture();
452 DownloadControllerAndroidImpl::DownloadInfoAndroid::~DownloadInfoAndroid() {}
454 } // namespace content