EmbedHistoryListener.cpp 13.6 KB
Newer Older
1 2 3 4 5 6
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "EmbedHistoryListener.h"
#include "nsIURI.h"
7
#include "nsThreadUtils.h"
8 9 10
#include "mozilla/dom/Link.h"
#include "nsIEmbedLiteJSON.h"
#include "nsIObserverService.h"
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include "nsComponentManagerUtils.h"
#include "nsServiceManagerUtils.h"

#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIURI.h"

#include "mozilla/Services.h"

#define NS_LINK_VISITED_EVENT_TOPIC "link-visited"

// We copy Places here.
// Note that we don't yet observe this pref at runtime.
#define PREF_HISTORY_ENABLED "places.history.enabled"

// Time we wait to see if a pending visit is really a redirect
#define PENDING_REDIRECT_TIMEOUT 3000
28 29 30 31

using namespace mozilla;
using mozilla::dom::Link;

32 33 34 35 36 37 38 39
NS_IMPL_ISUPPORTS(EmbedHistoryListener, IHistory, nsIRunnable, nsITimerCallback)

EmbedHistoryListener* EmbedHistoryListener::sHistory = nullptr;

// Ease up porting from nsAndroidHistory.
namespace AndroidBridge {
  bool
  HasEnv() {
40 41
    // Disable for now. This not currently in use and causes crashing. JB#39908
    return false;
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  }
}

namespace embed {
  namespace GeckoAppShell {
    void
    MarkURIVisited(const nsAString &aUri)
    {
      nsString message;
      // Just simple property bag support still
      nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
      nsCOMPtr<nsIWritablePropertyBag2> root;
      json->CreateObject(getter_AddRefs(root));
      root->SetPropertyAsACString(NS_LITERAL_STRING("msg"), NS_LITERAL_CSTRING("markvisited"));
      root->SetPropertyAsAString(NS_LITERAL_STRING("uri"), aUri);

      json->CreateJSON(root, message);
      nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
      if (observerService) {
        observerService->NotifyObservers(nullptr, "em:history", message.get());
      }
    }

    void
    SetURITitle(const nsAString &aUri, const nsAString& aTitle)
    {
      nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
      nsString message;
      // Just simple property bag support still
      nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
      nsCOMPtr<nsIWritablePropertyBag2> root;
      json->CreateObject(getter_AddRefs(root));
      root->SetPropertyAsACString(NS_LITERAL_STRING("msg"), NS_LITERAL_CSTRING("settitle"));
      root->SetPropertyAsAString(NS_LITERAL_STRING("uri"), aUri);
      root->SetPropertyAsAString(NS_LITERAL_STRING("title"), aTitle);

      json->CreateJSON(root, message);
      if (observerService) {
        observerService->NotifyObservers(nullptr, "em:history", message.get());
      }
    }
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    void
    CheckURIVisited(const nsAString &aUri)
    {
      nsString message;
      // Just simple property bag support still
      nsCOMPtr<nsIEmbedLiteJSON> json = do_GetService("@mozilla.org/embedlite-json;1");
      nsCOMPtr<nsIWritablePropertyBag2> root;
      json->CreateObject(getter_AddRefs(root));
      root->SetPropertyAsACString(NS_LITERAL_STRING("msg"), NS_LITERAL_CSTRING("checkvisited"));
      root->SetPropertyAsAString(NS_LITERAL_STRING("uri"), aUri);

      json->CreateJSON(root, message);
      nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
      // Possible we can avoid json stuff for this case and send uri directly
      if (observerService) {
        observerService->NotifyObservers(nullptr, "em:history", message.get());
      }
    }
  }
}
104 105 106 107 108

/*static*/
EmbedHistoryListener*
EmbedHistoryListener::GetSingleton()
{
109 110 111 112
  if (!sHistory) {
    sHistory = new EmbedHistoryListener();
    NS_ENSURE_TRUE(sHistory, nullptr);
  }
113

114 115
  NS_ADDREF(sHistory);
  return sHistory;
116 117 118
}

EmbedHistoryListener::EmbedHistoryListener()
119
  : mHistoryEnabled(true)
120
{
121
  nsresult rv;
122
  nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
123 124 125 126 127

  if (observerService) {
    rv = observerService->AddObserver(this,
                                      "history:notifyVisited", false);
  }
128 129 130 131

  LoadPrefs();

  mTimer = do_CreateInstance(NS_TIMER_CONTRACTID);
132 133 134 135 136
}

NS_IMETHODIMP
EmbedHistoryListener::RegisterVisitedCallback(nsIURI *aURI, Link *aContent)
{
137
  if (!aContent || !aURI)
138
    return NS_OK;
139

140 141 142 143 144 145 146 147
  // Silently return if URI is something we would never add to DB.
  bool canAdd;
  nsresult rv = CanAddURI(aURI, &canAdd);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!canAdd) {
    return NS_OK;
  }

148
  nsAutoCString uri;
149
  rv = aURI->GetSpec(uri);
150
  if (NS_FAILED(rv)) return rv;
151
  NS_ConvertUTF8toUTF16 uriString(uri);
152

153 154
  nsTArray<Link*>* list = mListeners.Get(uriString);
  if (! list) {
155
    list = new nsTArray<Link*>();
156
    mListeners.Put(uriString, list);
157 158 159
  }
  list->AppendElement(aContent);

160 161 162
  if (AndroidBridge::HasEnv()) {
    // widget::GeckoAppShell::CheckURIVisited
    embed::GeckoAppShell::CheckURIVisited(uriString);
163 164
  }
  return NS_OK;
165 166 167 168 169
}

NS_IMETHODIMP
EmbedHistoryListener::UnregisterVisitedCallback(nsIURI *aURI, Link *aContent)
{
170 171 172 173 174 175
  if (!aContent || !aURI)
    return NS_OK;

  nsAutoCString uri;
  nsresult rv = aURI->GetSpec(uri);
  if (NS_FAILED(rv)) return rv;
176
  NS_ConvertUTF8toUTF16 uriString(uri);
177

178 179
  nsTArray<Link*>* list = mListeners.Get(uriString);
  if (! list)
180
    return NS_OK;
181 182 183

  list->RemoveElement(aContent);
  if (list->IsEmpty()) {
184
    mListeners.Remove(uriString);
185 186 187
    delete list;
  }
  return NS_OK;
188 189
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
nsIEmbedAppService*
EmbedHistoryListener::GetService()
{
  if (!mService) {
    mService = do_GetService("@mozilla.org/embedlite-app-service;1");
  }
  return mService.get();
}

void
EmbedHistoryListener::AppendToRecentlyVisitedURIs(nsIURI* aURI) {
  if (mRecentlyVisitedURIs.Length() < RECENTLY_VISITED_URI_SIZE) {
    // Append a new element while the array is not full.
    mRecentlyVisitedURIs.AppendElement(aURI);
  } else {
    // Otherwise, replace the oldest member.
    mRecentlyVisitedURIsNextIndex %= RECENTLY_VISITED_URI_SIZE;
    mRecentlyVisitedURIs.ElementAt(mRecentlyVisitedURIsNextIndex) = aURI;
    mRecentlyVisitedURIsNextIndex++;
  }
}

bool
EmbedHistoryListener::ShouldRecordHistory()
{
  return mHistoryEnabled;
}

void
EmbedHistoryListener::LoadPrefs()
{
  nsresult rv;
  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
  if (NS_SUCCEEDED(rv)) {
    prefs->GetBoolPref(PREF_HISTORY_ENABLED, &mHistoryEnabled);
  }
}

inline bool
EmbedHistoryListener::IsRecentlyVisitedURI(nsIURI* aURI) {
  bool equals = false;
  RecentlyVisitedArray::index_type i;
  RecentlyVisitedArray::size_type length = mRecentlyVisitedURIs.Length();
  for (i = 0; i < length && !equals; ++i) {
    aURI->Equals(mRecentlyVisitedURIs.ElementAt(i), &equals);
  }
  return equals;
}

void
EmbedHistoryListener::AppendToEmbedURIs(nsIURI* aURI) {
  if (mEmbedURIs.Length() < EMBED_URI_SIZE) {
    // Append a new element while the array is not full.
    mEmbedURIs.AppendElement(aURI);
  } else {
    // Otherwise, replace the oldest member.
    mEmbedURIsNextIndex %= EMBED_URI_SIZE;
    mEmbedURIs.ElementAt(mEmbedURIsNextIndex) = aURI;
    mEmbedURIsNextIndex++;
  }
}

inline bool
EmbedHistoryListener::IsEmbedURI(nsIURI* aURI) {
  bool equals = false;
  EmbedArray::index_type i;
  EmbedArray::size_type length = mEmbedURIs.Length();
  for (i = 0; i < length && !equals; ++i) {
    aURI->Equals(mEmbedURIs.ElementAt(i), &equals);
  }
  return equals;
}

inline bool
EmbedHistoryListener::RemovePendingVisitURI(nsIURI* aURI) {
  // Remove the first pending URI that matches. Return a boolean to
  // let the caller know if we removed a URI or not.
  bool equals = false;
  PendingVisitArray::index_type i;
  for (i = 0; i < mPendingVisitURIs.Length(); ++i) {
    aURI->Equals(mPendingVisitURIs.ElementAt(i), &equals);
    if (equals) {
      mPendingVisitURIs.RemoveElementAt(i);
      return true;
    }
  }
  return false;
}

NS_IMETHODIMP
EmbedHistoryListener::Notify(nsITimer *timer)
{
  // Any pending visits left in the queue have exceeded our threshold for
  // redirects, so save them
  PendingVisitArray::index_type i;
  for (i = 0; i < mPendingVisitURIs.Length(); ++i) {
    SaveVisitURI(mPendingVisitURIs.ElementAt(i));
  }
  mPendingVisitURIs.Clear();

  return NS_OK;
}

void
EmbedHistoryListener::SaveVisitURI(nsIURI* aURI) {
  // Add the URI to our cache so we can take a fast path later
  AppendToRecentlyVisitedURIs(aURI);

  if (AndroidBridge::HasEnv()) {
    // Save this URI in our history
    nsAutoCString spec;
    (void)aURI->GetSpec(spec);
    // widget::GeckoAppShell::MarkURIVisited(NS_ConvertUTF8toUTF16(spec));
    embed::GeckoAppShell::MarkURIVisited(NS_ConvertUTF8toUTF16(spec));
  }

  // Finally, notify that we've been visited.
  nsCOMPtr<nsIObserverService> obsService = mozilla::services::GetObserverService();
  if (obsService) {
    obsService->NotifyObservers(aURI, NS_LINK_VISITED_EVENT_TOPIC, nullptr);
  }
}


314 315 316
NS_IMETHODIMP
EmbedHistoryListener::VisitURI(nsIURI *aURI, nsIURI *aLastVisitedURI, uint32_t aFlags)
{
317
  if (!aURI) {
318
    return NS_OK;
319
  }
320

321
  if (!(aFlags & VisitFlags::TOP_LEVEL)) {
322
    return NS_OK;
323
  }
324

325
  if (aFlags & VisitFlags::UNRECOVERABLE_ERROR) {
326
    return NS_OK;
327
  }
328

329 330 331 332 333
  // Silently return if URI is something we shouldn't add to DB.
  bool canAdd;
  nsresult rv = CanAddURI(aURI, &canAdd);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!canAdd) {
334
    return NS_OK;
335
  }
336

337 338 339 340 341 342 343 344 345
  if (aLastVisitedURI) {
    if (aFlags & VisitFlags::REDIRECT_SOURCE ||
        aFlags & VisitFlags::REDIRECT_PERMANENT ||
        aFlags & VisitFlags::REDIRECT_TEMPORARY) {
      // aLastVisitedURI redirected to aURI. We want to ignore aLastVisitedURI,
      // so remove the pending visit. We want to give aURI a chance to be saved,
      // so don't return early.
      RemovePendingVisitURI(aLastVisitedURI);
    }
346

347 348 349 350 351 352 353 354 355 356 357 358 359
    bool same;
    rv = aURI->Equals(aLastVisitedURI, &same);
    NS_ENSURE_SUCCESS(rv, rv);
    if (same && IsRecentlyVisitedURI(aURI)) {
      // Do not save refresh visits if we have visited this URI recently.
      return NS_OK;
    }

    // Since we have a last visited URI and we were not redirected, it is
    // safe to save the visit if it's still pending.
    if (RemovePendingVisitURI(aLastVisitedURI)) {
      SaveVisitURI(aLastVisitedURI);
    }
360 361
  }

362 363 364
  // Let's wait and see if this visit is not a redirect.
  mPendingVisitURIs.AppendElement(aURI);
  mTimer->InitWithCallback(this, PENDING_REDIRECT_TIMEOUT, nsITimer::TYPE_ONE_SHOT);
365

366
  return NS_OK;
367 368 369 370 371
}

NS_IMETHODIMP
EmbedHistoryListener::SetURITitle(nsIURI *aURI, const nsAString& aTitle)
{
372 373 374 375 376
  // Silently return if URI is something we shouldn't add to DB.
  bool canAdd;
  nsresult rv = CanAddURI(aURI, &canAdd);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!canAdd) {
377
    return NS_OK;
378
  }
379

380 381 382 383 384 385 386 387 388 389 390
  if (IsEmbedURI(aURI)) {
    return NS_OK;
  }

  if (AndroidBridge::HasEnv()) {
    nsAutoCString uri;
    nsresult rv = aURI->GetSpec(uri);
    if (NS_FAILED(rv)) return rv;
    NS_ConvertUTF8toUTF16 uriString(uri);
    // widget::GeckoAppShell::SetURITitle(uriString, aTitle);
    embed::GeckoAppShell::SetURITitle(uriString, aTitle);
391 392 393
  }
  return NS_OK;
}
394

395 396 397
NS_IMETHODIMP
EmbedHistoryListener::Observe(nsISupports *aSubject,
                              const char *aTopic,
398
                              const char16_t *aData)
399 400
{
  if (!strcmp(aTopic, "history:notifyVisited")) {
401
    sHistory->mPendingLinkURIs.Push(nsDependentString(aData));
402 403 404
    NS_DispatchToMainThread(sHistory);
  }
  return NS_OK;
405 406 407 408 409
}

NS_IMETHODIMP
EmbedHistoryListener::NotifyVisited(nsIURI *aURI)
{
410 411 412
  if (aURI && sHistory) {
    nsAutoCString spec;
    (void)aURI->GetSpec(spec);
413
    sHistory->mPendingLinkURIs.Push(NS_ConvertUTF8toUTF16(spec));
414 415 416
    NS_DispatchToMainThread(sHistory);
  }
  return NS_OK;
417 418 419 420 421
}

NS_IMETHODIMP
EmbedHistoryListener::Run()
{
422 423
  while (! mPendingLinkURIs.IsEmpty()) {
    nsString uriString = mPendingLinkURIs.Pop();
424 425 426 427 428 429 430
    nsTArray<Link*>* list = sHistory->mListeners.Get(uriString);
    if (list) {
      for (unsigned int i = 0; i < list->Length(); i++) {
        list->ElementAt(i)->SetLinkState(eLinkState_Visited);
      }
      // as per the IHistory interface contract, remove the
      // Link pointers once they have been notified
431
      mListeners.Remove(uriString);
432
      delete list;
433
    }
434
  }
435 436 437
  return NS_OK;
}

438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
// Filter out unwanted URIs such as "chrome:", "mailbox:", etc.
//
// The model is if we don't know differently then add which basically means
// we are suppose to try all the things we know not to allow in and then if
// we don't bail go on and allow it in.
//
// Logic ported from nsNavHistory::CanAddURI.

NS_IMETHODIMP
EmbedHistoryListener::CanAddURI(nsIURI* aURI, bool* canAdd)
{
  NS_ASSERTION(NS_IsMainThread(), "This can only be called on the main thread");
  NS_ENSURE_ARG(aURI);
  NS_ENSURE_ARG_POINTER(canAdd);

  // See if we're disabled.
  if (!ShouldRecordHistory()) {
    *canAdd = false;
    return NS_OK;
  }

  nsAutoCString scheme;
  nsresult rv = aURI->GetScheme(scheme);
  NS_ENSURE_SUCCESS(rv, rv);

  // first check the most common cases (HTTP, HTTPS) to allow in to avoid most
  // of the work
  if (scheme.EqualsLiteral("http")) {
    *canAdd = true;
    return NS_OK;
  }
  if (scheme.EqualsLiteral("https")) {
    *canAdd = true;
    return NS_OK;
  }

  // now check for all bad things
  if (scheme.EqualsLiteral("about") ||
      scheme.EqualsLiteral("imap") ||
      scheme.EqualsLiteral("news") ||
      scheme.EqualsLiteral("mailbox") ||
      scheme.EqualsLiteral("moz-anno") ||
      scheme.EqualsLiteral("view-source") ||
      scheme.EqualsLiteral("chrome") ||
      scheme.EqualsLiteral("resource") ||
      scheme.EqualsLiteral("data") ||
      scheme.EqualsLiteral("wyciwyg") ||
      scheme.EqualsLiteral("javascript") ||
      scheme.EqualsLiteral("blob")) {
    *canAdd = false;
    return NS_OK;
  }
  *canAdd = true;
492
  return NS_OK;
493
}