Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / android / download_controller_android_impl.cc
blob5d21117faeb170b3d8960ed1b171485aeaa73ee5
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/lazy_instance.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/synchronization/lock.h"
14 #include "base/time/time.h"
15 #include "content/browser/android/content_view_core_impl.h"
16 #include "content/browser/android/deferred_download_observer.h"
17 #include "content/browser/download/download_item_impl.h"
18 #include "content/browser/download/download_manager_impl.h"
19 #include "content/browser/loader/resource_dispatcher_host_impl.h"
20 #include "content/browser/renderer_host/render_process_host_impl.h"
21 #include "content/browser/renderer_host/render_view_host_delegate.h"
22 #include "content/browser/renderer_host/render_view_host_impl.h"
23 #include "content/browser/web_contents/web_contents_impl.h"
24 #include "content/public/browser/browser_context.h"
25 #include "content/public/browser/browser_thread.h"
26 #include "content/public/browser/download_url_parameters.h"
27 #include "content/public/browser/global_request_id.h"
28 #include "content/public/browser/resource_request_info.h"
29 #include "content/public/common/content_client.h"
30 #include "content/public/common/referrer.h"
31 #include "jni/DownloadController_jni.h"
32 #include "net/cookies/cookie_options.h"
33 #include "net/cookies/cookie_store.h"
34 #include "net/http/http_content_disposition.h"
35 #include "net/http/http_request_headers.h"
36 #include "net/http/http_response_headers.h"
37 #include "net/url_request/url_request.h"
38 #include "net/url_request/url_request_context.h"
40 using base::android::ConvertUTF8ToJavaString;
41 using base::android::ScopedJavaLocalRef;
43 namespace {
44 // Guards download_controller_
45 base::LazyInstance<base::Lock> g_download_controller_lock_;
47 content::WebContents* GetWebContents(int render_process_id,
48 int render_view_id) {
49 content::RenderViewHost* render_view_host =
50 content::RenderViewHost::FromID(render_process_id, render_view_id);
52 if (!render_view_host)
53 return nullptr;
55 return content::WebContents::FromRenderViewHost(render_view_host);
58 void CreateContextMenuDownload(int render_process_id,
59 int render_view_id,
60 const content::ContextMenuParams& params,
61 bool is_link,
62 const std::string& extra_headers,
63 bool granted) {
64 if (!granted)
65 return;
67 content::WebContents* web_contents =
68 GetWebContents(render_process_id, render_view_id);
69 if (!web_contents)
70 return;
72 const GURL& url = is_link ? params.link_url : params.src_url;
73 const GURL& referring_url =
74 params.frame_url.is_empty() ? params.page_url : params.frame_url;
75 content::DownloadManagerImpl* dlm =
76 static_cast<content::DownloadManagerImpl*>(
77 content::BrowserContext::GetDownloadManager(
78 web_contents->GetBrowserContext()));
79 scoped_ptr<content::DownloadUrlParameters> dl_params(
80 content::DownloadUrlParameters::FromWebContents(web_contents, url));
81 content::Referrer referrer = content::Referrer::SanitizeForRequest(
82 url,
83 content::Referrer(referring_url.GetAsReferrer(), params.referrer_policy));
84 dl_params->set_referrer(referrer);
85 if (is_link)
86 dl_params->set_referrer_encoding(params.frame_charset);
87 net::HttpRequestHeaders headers;
88 headers.AddHeadersFromString(extra_headers);
89 for (net::HttpRequestHeaders::Iterator it(headers); it.GetNext();)
90 dl_params->add_request_header(it.name(), it.value());
91 if (!is_link && extra_headers.empty())
92 dl_params->set_prefer_cache(true);
93 dl_params->set_prompt(false);
94 dlm->DownloadUrl(dl_params.Pass());
97 } // namespace
99 namespace content {
101 // JNI methods
102 static void Init(JNIEnv* env, jobject obj) {
103 DownloadControllerAndroidImpl::GetInstance()->Init(env, obj);
106 static void OnRequestFileAccessResult(
107 JNIEnv* env, jobject obj, jlong callback_id, jboolean granted) {
108 DCHECK_CURRENTLY_ON(BrowserThread::UI);
109 DCHECK(callback_id);
111 // Convert java long long int to c++ pointer, take ownership.
112 scoped_ptr<DownloadControllerAndroid::AcquireFileAccessPermissionCallback> cb(
113 reinterpret_cast<
114 DownloadControllerAndroid::AcquireFileAccessPermissionCallback*>(
115 callback_id));
116 cb->Run(granted);
119 struct DownloadControllerAndroidImpl::JavaObject {
120 ScopedJavaLocalRef<jobject> Controller(JNIEnv* env) {
121 return GetRealObject(env, obj);
123 jweak obj;
126 // static
127 bool DownloadControllerAndroidImpl::RegisterDownloadController(JNIEnv* env) {
128 return RegisterNativesImpl(env);
131 // static
132 DownloadControllerAndroid* DownloadControllerAndroid::Get() {
133 base::AutoLock lock(g_download_controller_lock_.Get());
134 if (!DownloadControllerAndroid::download_controller_)
135 download_controller_ = DownloadControllerAndroidImpl::GetInstance();
136 return DownloadControllerAndroid::download_controller_;
139 //static
140 void DownloadControllerAndroid::SetDownloadControllerAndroid(
141 DownloadControllerAndroid* download_controller) {
142 base::AutoLock lock(g_download_controller_lock_.Get());
143 DownloadControllerAndroid::download_controller_ = download_controller;
146 // static
147 DownloadControllerAndroidImpl* DownloadControllerAndroidImpl::GetInstance() {
148 return Singleton<DownloadControllerAndroidImpl>::get();
151 DownloadControllerAndroidImpl::DownloadControllerAndroidImpl()
152 : java_object_(NULL) {
155 DownloadControllerAndroidImpl::~DownloadControllerAndroidImpl() {
156 if (java_object_) {
157 JNIEnv* env = base::android::AttachCurrentThread();
158 env->DeleteWeakGlobalRef(java_object_->obj);
159 delete java_object_;
160 base::android::CheckException(env);
164 // Initialize references to Java object.
165 void DownloadControllerAndroidImpl::Init(JNIEnv* env, jobject obj) {
166 java_object_ = new JavaObject;
167 java_object_->obj = env->NewWeakGlobalRef(obj);
170 void DownloadControllerAndroidImpl::CancelDeferredDownload(
171 DeferredDownloadObserver* observer) {
172 for (auto iter = deferred_downloads_.begin();
173 iter != deferred_downloads_.end(); ++iter) {
174 if (*iter == observer) {
175 deferred_downloads_.erase(iter);
176 return;
181 void DownloadControllerAndroidImpl::AcquireFileAccessPermission(
182 int render_process_id,
183 int render_view_id,
184 const DownloadControllerAndroid::AcquireFileAccessPermissionCallback& cb) {
185 DCHECK_CURRENTLY_ON(BrowserThread::UI);
186 WebContents* web_contents = GetWebContents(render_process_id, render_view_id);
187 if (!web_contents) {
188 BrowserThread::PostTask(
189 BrowserThread::UI, FROM_HERE, base::Bind(cb, false));
190 return;
193 ScopedJavaLocalRef<jobject> view =
194 GetContentViewCoreFromWebContents(web_contents);
195 if (view.is_null()) {
196 BrowserThread::PostTask(
197 BrowserThread::UI, FROM_HERE, base::Bind(cb, false));
198 return;
201 if (HasFileAccessPermission(view)) {
202 BrowserThread::PostTask(
203 BrowserThread::UI, FROM_HERE, base::Bind(cb, true));
204 return;
207 JNIEnv* env = base::android::AttachCurrentThread();
208 // Make copy on the heap so we can pass the pointer through JNI.
209 intptr_t callback_id = reinterpret_cast<intptr_t>(
210 new DownloadControllerAndroid::AcquireFileAccessPermissionCallback(cb));
211 Java_DownloadController_requestFileAccess(
212 env, GetJavaObject()->Controller(env).obj(), view.obj(), callback_id);
215 bool DownloadControllerAndroidImpl::HasFileAccessPermission(
216 ScopedJavaLocalRef<jobject> j_content_view_core) {
217 DCHECK_CURRENTLY_ON(BrowserThread::UI);
218 DCHECK(!j_content_view_core.is_null());
220 JNIEnv* env = base::android::AttachCurrentThread();
221 return Java_DownloadController_hasFileAccess(
222 env, GetJavaObject()->Controller(env).obj(), j_content_view_core.obj());
225 void DownloadControllerAndroidImpl::CreateGETDownload(
226 int render_process_id, int render_view_id, int request_id) {
227 DCHECK_CURRENTLY_ON(BrowserThread::IO);
228 GlobalRequestID global_id(render_process_id, request_id);
230 // We are yielding the UI thread and render_view_host may go away by
231 // the time we come back. Pass along render_process_id and render_view_id
232 // to retrieve it later (if it still exists).
233 GetDownloadInfoCB cb = base::Bind(
234 &DownloadControllerAndroidImpl::StartAndroidDownload,
235 base::Unretained(this), render_process_id,
236 render_view_id);
238 PrepareDownloadInfo(
239 global_id,
240 base::Bind(&DownloadControllerAndroidImpl::StartDownloadOnUIThread,
241 base::Unretained(this), cb));
244 void DownloadControllerAndroidImpl::PrepareDownloadInfo(
245 const GlobalRequestID& global_id,
246 const GetDownloadInfoCB& callback) {
247 DCHECK_CURRENTLY_ON(BrowserThread::IO);
249 net::URLRequest* request =
250 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id);
251 if (!request) {
252 LOG(ERROR) << "Request to download not found.";
253 return;
256 DownloadInfoAndroid info_android(request);
258 net::CookieStore* cookie_store = request->context()->cookie_store();
259 if (cookie_store) {
260 net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();
261 if (cookie_monster) {
262 cookie_monster->GetAllCookiesForURLAsync(
263 request->url(),
264 base::Bind(&DownloadControllerAndroidImpl::CheckPolicyAndLoadCookies,
265 base::Unretained(this), info_android, callback,
266 global_id));
267 } else {
268 DoLoadCookies(info_android, callback, global_id);
270 } else {
271 // Can't get any cookies, start android download.
272 callback.Run(info_android);
276 void DownloadControllerAndroidImpl::CheckPolicyAndLoadCookies(
277 const DownloadInfoAndroid& info, const GetDownloadInfoCB& callback,
278 const GlobalRequestID& global_id, const net::CookieList& cookie_list) {
279 DCHECK_CURRENTLY_ON(BrowserThread::IO);
281 net::URLRequest* request =
282 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id);
283 if (!request) {
284 LOG(ERROR) << "Request to download not found.";
285 return;
288 if (request->context()->network_delegate()->CanGetCookies(
289 *request, cookie_list)) {
290 DoLoadCookies(info, callback, global_id);
291 } else {
292 callback.Run(info);
296 void DownloadControllerAndroidImpl::DoLoadCookies(
297 const DownloadInfoAndroid& info, const GetDownloadInfoCB& callback,
298 const GlobalRequestID& global_id) {
299 DCHECK_CURRENTLY_ON(BrowserThread::IO);
301 net::CookieOptions options;
302 options.set_include_httponly();
304 net::URLRequest* request =
305 ResourceDispatcherHostImpl::Get()->GetURLRequest(global_id);
306 if (!request) {
307 LOG(ERROR) << "Request to download not found.";
308 return;
311 request->context()->cookie_store()->GetCookiesWithOptionsAsync(
312 info.url, options,
313 base::Bind(&DownloadControllerAndroidImpl::OnCookieResponse,
314 base::Unretained(this), info, callback));
317 void DownloadControllerAndroidImpl::OnCookieResponse(
318 DownloadInfoAndroid download_info,
319 const GetDownloadInfoCB& callback,
320 const std::string& cookie) {
321 download_info.cookie = cookie;
323 // We have everything we need, start Android download.
324 callback.Run(download_info);
327 void DownloadControllerAndroidImpl::StartDownloadOnUIThread(
328 const GetDownloadInfoCB& callback,
329 const DownloadInfoAndroid& info) {
330 DCHECK_CURRENTLY_ON(BrowserThread::IO);
331 BrowserThread::PostTask(
332 BrowserThread::UI, FROM_HERE, base::Bind(callback, info));
335 void DownloadControllerAndroidImpl::StartAndroidDownload(
336 int render_process_id, int render_view_id,
337 const DownloadInfoAndroid& info) {
338 DCHECK_CURRENTLY_ON(BrowserThread::UI);
340 WebContents* web_contents = GetWebContents(render_process_id, render_view_id);
341 if (!web_contents) {
342 // The view went away. Can't proceed.
343 LOG(ERROR) << "Download failed on URL:" << info.url.spec();
344 return;
346 ScopedJavaLocalRef<jobject> view =
347 GetContentViewCoreFromWebContents(web_contents);
348 if (view.is_null()) {
349 // ContentViewCore might not have been created yet, pass a callback to
350 // DeferredDownloadTaskManager so that the download can restart when
351 // ContentViewCore is created.
352 deferred_downloads_.push_back(new DeferredDownloadObserver(
353 web_contents,
354 base::Bind(&DownloadControllerAndroidImpl::StartAndroidDownload,
355 base::Unretained(this), render_process_id, render_view_id,
356 info)));
357 return;
360 AcquireFileAccessPermission(
361 render_process_id, render_view_id,
362 base::Bind(&DownloadControllerAndroidImpl::StartAndroidDownloadInternal,
363 base::Unretained(this), render_process_id, render_view_id,
364 info));
367 void DownloadControllerAndroidImpl::StartAndroidDownloadInternal(
368 int render_process_id, int render_view_id,
369 const DownloadInfoAndroid& info, bool allowed) {
370 DCHECK_CURRENTLY_ON(BrowserThread::UI);
371 if (!allowed)
372 return;
374 // Call newHttpGetDownload
375 WebContents* web_contents = GetWebContents(render_process_id, render_view_id);
376 // The view went away. Can't proceed.
377 if (!web_contents)
378 return;
379 ScopedJavaLocalRef<jobject> view =
380 GetContentViewCoreFromWebContents(web_contents);
381 if (view.is_null())
382 return;
384 JNIEnv* env = base::android::AttachCurrentThread();
385 ScopedJavaLocalRef<jstring> jurl =
386 ConvertUTF8ToJavaString(env, info.url.spec());
387 ScopedJavaLocalRef<jstring> juser_agent =
388 ConvertUTF8ToJavaString(env, info.user_agent);
389 ScopedJavaLocalRef<jstring> jcontent_disposition =
390 ConvertUTF8ToJavaString(env, info.content_disposition);
391 ScopedJavaLocalRef<jstring> jmime_type =
392 ConvertUTF8ToJavaString(env, info.original_mime_type);
393 ScopedJavaLocalRef<jstring> jcookie =
394 ConvertUTF8ToJavaString(env, info.cookie);
395 ScopedJavaLocalRef<jstring> jreferer =
396 ConvertUTF8ToJavaString(env, info.referer);
398 // Try parsing the content disposition header to get a
399 // explicitly specified filename if available.
400 net::HttpContentDisposition header(info.content_disposition, "");
401 ScopedJavaLocalRef<jstring> jfilename =
402 ConvertUTF8ToJavaString(env, header.filename());
404 Java_DownloadController_newHttpGetDownload(
405 env, GetJavaObject()->Controller(env).obj(), view.obj(), jurl.obj(),
406 juser_agent.obj(), jcontent_disposition.obj(), jmime_type.obj(),
407 jcookie.obj(), jreferer.obj(), info.has_user_gesture, jfilename.obj(),
408 info.total_bytes);
411 void DownloadControllerAndroidImpl::OnDownloadStarted(
412 DownloadItem* download_item) {
413 DCHECK_CURRENTLY_ON(BrowserThread::UI);
414 if (!download_item->GetWebContents())
415 return;
417 JNIEnv* env = base::android::AttachCurrentThread();
419 // Register for updates to the DownloadItem.
420 download_item->AddObserver(this);
422 ScopedJavaLocalRef<jobject> view =
423 GetContentViewCoreFromWebContents(download_item->GetWebContents());
424 // The view went away. Can't proceed.
425 if (view.is_null())
426 return;
428 ScopedJavaLocalRef<jstring> jmime_type =
429 ConvertUTF8ToJavaString(env, download_item->GetMimeType());
430 ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
431 env, download_item->GetTargetFilePath().BaseName().value());
432 Java_DownloadController_onDownloadStarted(
433 env, GetJavaObject()->Controller(env).obj(), view.obj(), jfilename.obj(),
434 jmime_type.obj());
437 void DownloadControllerAndroidImpl::OnDownloadUpdated(DownloadItem* item) {
438 DCHECK_CURRENTLY_ON(BrowserThread::UI);
439 if (item->IsDangerous() && (item->GetState() != DownloadItem::CANCELLED))
440 OnDangerousDownload(item);
442 JNIEnv* env = base::android::AttachCurrentThread();
443 ScopedJavaLocalRef<jstring> jurl =
444 ConvertUTF8ToJavaString(env, item->GetURL().spec());
445 ScopedJavaLocalRef<jstring> jmime_type =
446 ConvertUTF8ToJavaString(env, item->GetMimeType());
447 ScopedJavaLocalRef<jstring> jpath =
448 ConvertUTF8ToJavaString(env, item->GetTargetFilePath().value());
449 ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
450 env, item->GetTargetFilePath().BaseName().value());
452 switch (item->GetState()) {
453 case DownloadItem::IN_PROGRESS: {
454 base::TimeDelta time_delta;
455 item->TimeRemaining(&time_delta);
456 Java_DownloadController_onDownloadUpdated(
457 env, GetJavaObject()->Controller(env).obj(),
458 base::android::GetApplicationContext(), jurl.obj(), jmime_type.obj(),
459 jfilename.obj(), jpath.obj(), item->GetReceivedBytes(), true,
460 item->GetId(), item->PercentComplete(), time_delta.InMilliseconds(),
461 item->HasUserGesture());
462 break;
464 case DownloadItem::COMPLETE:
465 // Multiple OnDownloadUpdated() notifications may be issued while the
466 // download is in the COMPLETE state. Only handle one.
467 item->RemoveObserver(this);
469 // Call onDownloadCompleted
470 Java_DownloadController_onDownloadCompleted(
471 env, GetJavaObject()->Controller(env).obj(),
472 base::android::GetApplicationContext(), jurl.obj(), jmime_type.obj(),
473 jfilename.obj(), jpath.obj(), item->GetReceivedBytes(), true,
474 item->GetId(), item->HasUserGesture());
475 break;
476 case DownloadItem::CANCELLED:
477 // TODO(shashishekhar): An interrupted download can be resumed. Android
478 // currently does not support resumable downloads. Add handling for
479 // interrupted case based on item->CanResume().
480 case DownloadItem::INTERRUPTED:
481 // Call onDownloadCompleted with success = false.
482 Java_DownloadController_onDownloadCompleted(
483 env, GetJavaObject()->Controller(env).obj(),
484 base::android::GetApplicationContext(), jurl.obj(), jmime_type.obj(),
485 jfilename.obj(), jpath.obj(), item->GetReceivedBytes(), false,
486 item->GetId(), item->HasUserGesture());
487 break;
488 case DownloadItem::MAX_DOWNLOAD_STATE:
489 NOTREACHED();
493 void DownloadControllerAndroidImpl::OnDangerousDownload(DownloadItem* item) {
494 JNIEnv* env = base::android::AttachCurrentThread();
495 ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString(
496 env, item->GetTargetFilePath().BaseName().value());
497 ScopedJavaLocalRef<jobject> view_core = GetContentViewCoreFromWebContents(
498 item->GetWebContents());
499 if (!view_core.is_null()) {
500 Java_DownloadController_onDangerousDownload(
501 env, GetJavaObject()->Controller(env).obj(), view_core.obj(),
502 jfilename.obj(), item->GetId());
506 ScopedJavaLocalRef<jobject>
507 DownloadControllerAndroidImpl::GetContentViewCoreFromWebContents(
508 WebContents* web_contents) {
509 if (!web_contents)
510 return ScopedJavaLocalRef<jobject>();
512 ContentViewCore* view_core = ContentViewCore::FromWebContents(web_contents);
513 return view_core ? view_core->GetJavaObject() :
514 ScopedJavaLocalRef<jobject>();
517 DownloadControllerAndroidImpl::JavaObject*
518 DownloadControllerAndroidImpl::GetJavaObject() {
519 if (!java_object_) {
520 // Initialize Java DownloadController by calling
521 // DownloadController.getInstance(), which will call Init()
522 // if Java DownloadController is not instantiated already.
523 JNIEnv* env = base::android::AttachCurrentThread();
524 Java_DownloadController_getInstance(env);
527 DCHECK(java_object_);
528 return java_object_;
531 void DownloadControllerAndroidImpl::StartContextMenuDownload(
532 const ContextMenuParams& params, WebContents* web_contents, bool is_link,
533 const std::string& extra_headers) {
534 int process_id = web_contents->GetRenderProcessHost()->GetID();
535 int routing_id = web_contents->GetRoutingID();
536 AcquireFileAccessPermission(
537 process_id, routing_id,
538 base::Bind(&CreateContextMenuDownload, process_id, routing_id, params,
539 is_link, extra_headers));
542 void DownloadControllerAndroidImpl::DangerousDownloadValidated(
543 WebContents* web_contents, int download_id, bool accept) {
544 if (!web_contents)
545 return;
546 DownloadManagerImpl* dlm = static_cast<DownloadManagerImpl*>(
547 BrowserContext::GetDownloadManager(web_contents->GetBrowserContext()));
548 DownloadItem* item = dlm->GetDownload(download_id);
549 if (!item)
550 return;
551 if (accept)
552 item->ValidateDangerousDownload();
553 else
554 item->Remove();
557 DownloadControllerAndroidImpl::DownloadInfoAndroid::DownloadInfoAndroid(
558 net::URLRequest* request)
559 : has_user_gesture(false) {
560 request->GetResponseHeaderByName("content-disposition", &content_disposition);
562 if (request->response_headers())
563 request->response_headers()->GetMimeType(&original_mime_type);
565 request->extra_request_headers().GetHeader(
566 net::HttpRequestHeaders::kUserAgent, &user_agent);
567 if (user_agent.empty())
568 user_agent = GetContentClient()->GetUserAgent();
569 GURL referer_url(request->referrer());
570 if (referer_url.is_valid())
571 referer = referer_url.spec();
572 if (!request->url_chain().empty()) {
573 original_url = request->url_chain().front();
574 url = request->url_chain().back();
577 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
578 if (info)
579 has_user_gesture = info->HasUserGesture();
582 DownloadControllerAndroidImpl::DownloadInfoAndroid::~DownloadInfoAndroid() {}
584 } // namespace content