Remove Firebase implementation from engine (#2677)

This commit is contained in:
Collin Jackson 2016-05-12 14:03:00 -07:00
parent 43c108dae8
commit f2da7a1b71
8 changed files with 1 additions and 1012 deletions

4
DEPS
View File

@ -88,10 +88,6 @@ deps = {
'src/third_party/mesa/src':
Var('chromium_git') + '/chromium/deps/mesa.git' + '@' + '071d25db04c23821a12a8b260ab9d96a097402f0',
# TODO(jackson): Remove this once we're able to build Firebase on its own Travis instance
'src/third_party/firebase':
'https://github.com/collinjackson/firebase-sdk.git@master',
'src/third_party/gcm':
'https://github.com/flutter/flutter_gcm.git@master',
}

View File

@ -39,7 +39,7 @@ group("sky") {
# TODO(mpcomplete): This is temporary until we move GCM and Firebase
# out of the engine repo.
if (enable_firebase) {
deps += [ "//sky/services/firebase" ]
deps += [ "//third_party/firebase" ]
}
if (enable_gcm) {

View File

@ -25,7 +25,6 @@ dart_pkg("sky_services") {
":copy_sky_services_license",
"//sky/services/activity:interfaces",
"//sky/services/editing:interfaces",
"//sky/services/firebase:interfaces",
"//sky/services/media:interfaces",
"//sky/services/platform:interfaces",
"//sky/services/pointer:interfaces",

View File

@ -1,87 +0,0 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# TODO(jackson): move this to a separate repo. Doesn't belong in the main
# Flutter repo.
import("//mojo/public/tools/bindings/mojom.gni")
group("firebase") {
deps = [
":interfaces",
]
if (is_ios || is_android) {
deps += [ ":firebase_lib" ]
}
if (is_android) {
deps += [ ":interfaces_java" ]
}
}
mojom("interfaces") {
sources = [
"firebase.mojom",
]
}
if (is_android) {
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
android_library("firebase_lib") {
java_files = [
"src/org/domokit/firebase/FirebaseImpl.java",
]
deps = [
"//base:base_java",
"//mojo/java",
"//mojo/public/java:bindings",
"//mojo/public/java:system",
":interfaces_java",
"//third_party/firebase",
]
}
}
if (is_ios) {
source_set("firebase_lib") {
sources = [
"firebase.mojom",
"ios/firebase_impl.h",
"ios/firebase_impl.mm",
"//mojo/public/cpp/application/interface_factory.h",
"//third_party/firebase/Firebase.framework/Headers/Firebase.h",
]
include_dirs = [
"//third_party/firebase/Firebase.framework/Headers/",
]
libs = [
"Firebase.framework",
"CFNetwork.framework",
"SystemConfiguration.framework",
"Security.framework",
"icucore",
]
deps = [
"//base:base",
":interfaces",
]
all_dependent_configs = [ ":firebase_config" ]
}
config("firebase_config") {
firebase_dir = rebase_path("//third_party/firebase/", root_build_dir)
ldflags = [
"-F$firebase_dir",
"-ObjC",
]
}
}

View File

@ -1,68 +0,0 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
[DartPackage="sky_services"]
module firebase;
enum EventType {
EventTypeChildAdded, // 0, fired when a new child node is added to a location
EventTypeChildRemoved, // 1, fired when a child node is removed from a location
EventTypeChildChanged, // 2, fired when a child node at a location changes
EventTypeChildMoved, // 3, fired when a child node moves relative to the other child nodes at a location
EventTypeValue // 4, fired when any data changes at a location and, recursively, any children
};
struct DataSnapshot {
string key;
string jsonValue;
};
struct Error {
int32 code;
string message;
};
struct AuthData {
string uid;
string provider;
string token;
};
interface ValueEventListener {
OnCancelled(Error error);
OnDataChange(DataSnapshot snapshot);
};
interface ChildEventListener {
OnCancelled(Error error);
OnChildAdded(DataSnapshot snapshot, string? previousChildName);
OnChildChanged(DataSnapshot snapshot, string? previousChildName);
OnChildMoved(DataSnapshot snapshot, string? previousChildName);
OnChildRemoved(DataSnapshot snapshot);
};
[ServiceName="firebase::Firebase"]
interface Firebase {
InitWithUrl(string url);
AddValueEventListener(ValueEventListener listener);
AddChildEventListener(ChildEventListener listener);
ObserveSingleEventOfType(EventType eventType) => (DataSnapshot snapshot);
AuthWithCustomToken(string token) => (Error? error, AuthData? authData);
AuthAnonymously() => (Error? error, AuthData? authData);
AuthWithOAuthToken(string provider, string credentials) => (Error? error, AuthData? authData);
AuthWithPassword(string email, string password) => (Error? error, AuthData? authData);
Unauth() => (Error? error);
GetChild(string path, Firebase& child);
GetParent(Firebase& parent);
GetRoot(Firebase& root);
SetValue(string jsonValue, int32 priority, bool hasPriority) => (Error? error);
RemoveValue() => (Error? error);
Push(Firebase& child) => (string key);
SetPriority(int32 priority) => (Error? error);
CreateUser(string email, string password) => (Error? error, string? jsonValue);
ChangeEmail(string oldEmail, string password, string newEmail) => (Error? error);
ChangePassword(string newPassword, string email, string oldPassword) => (Error? error);
RemoveUser(string email, string password) => (Error? error);
ResetPassword(string email) => (Error? error);
};

View File

@ -1,102 +0,0 @@
// Copyright 2015 Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_SERVICES_FIREBASE_IOS_FIREBASEIMPL_H_
#define SKY_SERVICES_FIREBASE_IOS_FIREBASEIMPL_H_
#include "base/macros.h"
#include "mojo/public/cpp/application/interface_factory.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "sky/services/firebase/firebase.mojom.h"
#if __OBJC__
@class Firebase;
#else // __OBJC__
class Firebase;
#endif // __OBJC__
namespace sky {
namespace services {
namespace firebase {
class FirebaseImpl : public ::firebase::Firebase {
public:
explicit FirebaseImpl(mojo::InterfaceRequest<Firebase> request);
~FirebaseImpl() override;
void InitWithUrl(const mojo::String& url) override;
void AddValueEventListener(
::firebase::ValueEventListenerPtr listener) override;
void AddChildEventListener(
::firebase::ChildEventListenerPtr listener) override;
void ObserveSingleEventOfType(
::firebase::EventType eventType,
const ObserveSingleEventOfTypeCallback& callback) override;
void AuthWithCustomToken(
const mojo::String& token,
const AuthWithCustomTokenCallback& callback) override;
void AuthAnonymously(
const AuthAnonymouslyCallback& callback) override;
void AuthWithOAuthToken(
const mojo::String& provider,
const mojo::String& credentials,
const AuthWithOAuthTokenCallback& callback) override;
void AuthWithPassword(
const mojo::String& email,
const mojo::String& password,
const AuthWithPasswordCallback& callback) override;
void Unauth(const UnauthCallback& callback) override;
void GetChild(
const mojo::String& path,
mojo::InterfaceRequest<Firebase> child) override;
void GetParent(mojo::InterfaceRequest<Firebase> parent) override;
void GetRoot(mojo::InterfaceRequest<Firebase> root) override;
void RemoveValue(const RemoveValueCallback& callback) override;
void SetValue(
const mojo::String& jsonValue,
int32_t priority,
bool hasPriority,
const SetValueCallback& callback) override;
void Push(mojo::InterfaceRequest<Firebase> child,
const PushCallback& callback) override;
void SetPriority(int32_t priority,
const SetPriorityCallback& callback) override;
void CreateUser(const mojo::String& email,
const mojo::String& password,
const CreateUserCallback& callback) override;
void ChangeEmail(const mojo::String& oldEmail,
const mojo::String& password,
const mojo::String& newEmail,
const ChangeEmailCallback& callback) override;
void ChangePassword(
const mojo::String& newPassword,
const mojo::String& email,
const mojo::String& oldPassword,
const ChangePasswordCallback& callback) override;
void RemoveUser(const mojo::String& email,
const mojo::String& password,
const RemoveUserCallback& callback) override;
void ResetPassword(const mojo::String& email,
const ResetPasswordCallback& callback) override;
private:
mojo::StrongBinding<::firebase::Firebase> binding_;
::Firebase* client_;
std::vector<::firebase::ValueEventListenerPtr> value_event_listeners_;
std::vector<::firebase::ChildEventListenerPtr> child_event_listeners_;
DISALLOW_COPY_AND_ASSIGN(FirebaseImpl);
};
class FirebaseFactory
: public mojo::InterfaceFactory<::firebase::Firebase> {
public:
void Create(mojo::ApplicationConnection* connection,
mojo::InterfaceRequest<::firebase::Firebase> request) override;
};
} // namespace firebase
} // namespace services
} // namespace sky
#endif // SKY_SERVICES_FIREBASE_IOS_FIREBASEIMPL_H_

View File

@ -1,347 +0,0 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/services/firebase/ios/firebase_impl.h"
#include "base/logging.h"
#include "base/strings/sys_string_conversions.h"
#import <Firebase.h>
namespace sky {
namespace services {
namespace firebase {
::firebase::DataSnapshotPtr toMojoSnapshot(FDataSnapshot* snapshot) {
::firebase::DataSnapshotPtr mojoSnapshot(::firebase::DataSnapshot::New());
mojoSnapshot->key = base::SysNSStringToUTF8(snapshot.key);
NSDictionary *valueDictionary = @{@"value": snapshot.value};
NSData *data = [NSJSONSerialization dataWithJSONObject:valueDictionary
options:0
error:nil];
if (data != nil) {
NSString *jsonValue = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
mojoSnapshot->jsonValue = base::SysNSStringToUTF8(jsonValue);
}
return mojoSnapshot.Pass();
}
::firebase::ErrorPtr toMojoError(NSError* error) {
::firebase::ErrorPtr mojoError(::firebase::Error::New());
mojoError->code = error.code;
mojoError->message = base::SysNSStringToUTF8(error.description);
return mojoError.Pass();
}
::firebase::AuthDataPtr toMojoAuthData(FAuthData* authData) {
::firebase::AuthDataPtr mojoAuthData(::firebase::AuthData::New());
mojoAuthData->uid = base::SysNSStringToUTF8(authData.uid);
mojoAuthData->provider = base::SysNSStringToUTF8(authData.provider);
mojoAuthData->token = base::SysNSStringToUTF8(authData.token);
return mojoAuthData.Pass();
}
FirebaseImpl::FirebaseImpl(mojo::InterfaceRequest<::firebase::Firebase> request)
: binding_(this, request.Pass()) {}
FirebaseImpl::~FirebaseImpl() {
[client_ release];
}
void FirebaseImpl::InitWithUrl(const mojo::String& url) {
client_ = [[[::Firebase alloc] initWithUrl:@(url.data())] retain];
}
void FirebaseImpl::AddValueEventListener(::firebase::ValueEventListenerPtr ptr) {
::firebase::ValueEventListener *listener = ptr.get();
FirebaseHandle handle = [client_ observeEventType:FEventTypeValue
withBlock:^(FDataSnapshot *snapshot) {
listener->OnDataChange(toMojoSnapshot(snapshot));
} withCancelBlock:^(NSError *error) {
listener->OnCancelled(toMojoError(error));
}];
ptr.set_connection_error_handler([this, handle, listener]() {
[client_ removeObserverWithHandle:handle];
auto it = std::find_if(value_event_listeners_.begin(),
value_event_listeners_.end(),
[listener](const ::firebase::ValueEventListenerPtr& p) {
return (p.get() == listener);
});
DCHECK(it != value_event_listeners_.end());
value_event_listeners_.erase(it);
});
value_event_listeners_.emplace_back(ptr.Pass());
}
void FirebaseImpl::AddChildEventListener(::firebase::ChildEventListenerPtr ptr) {
::firebase::ChildEventListener *listener = ptr.get();
void (^cancelBlock)(NSError *) = ^(NSError *error) {
listener->OnCancelled(toMojoError(error));
};
void (^addedBlock)(FDataSnapshot *, NSString *) = ^(FDataSnapshot *snapshot, NSString *prevKey) {
listener->OnChildAdded(toMojoSnapshot(snapshot), base::SysNSStringToUTF8(prevKey));
};
FirebaseHandle addedHandle = [client_ observeEventType:FEventTypeChildAdded
andPreviousSiblingKeyWithBlock:addedBlock
withCancelBlock:cancelBlock];
void (^changedBlock)(FDataSnapshot *, NSString *) = ^(FDataSnapshot *snapshot, NSString *prevKey) {
listener->OnChildChanged(toMojoSnapshot(snapshot), base::SysNSStringToUTF8(prevKey));
};
FirebaseHandle changedHandle = [client_ observeEventType:FEventTypeChildChanged
andPreviousSiblingKeyWithBlock:changedBlock
withCancelBlock:cancelBlock];
void (^movedBlock)(FDataSnapshot *, NSString *) = ^(FDataSnapshot *snapshot, NSString *prevKey) {
listener->OnChildMoved(toMojoSnapshot(snapshot), base::SysNSStringToUTF8(prevKey));
};
FirebaseHandle movedHandle = [client_ observeEventType:FEventTypeChildMoved
andPreviousSiblingKeyWithBlock:movedBlock
withCancelBlock:cancelBlock];
void (^removedBlock)(FDataSnapshot *snapshot) = ^(FDataSnapshot *snapshot) {
listener->OnChildRemoved(toMojoSnapshot(snapshot));
};
FirebaseHandle removedHandle = [client_ observeEventType:FEventTypeChildRemoved
withBlock:removedBlock
withCancelBlock:cancelBlock];
ptr.set_connection_error_handler(
[this, addedHandle, changedHandle, movedHandle, removedHandle, listener]() {
[client_ removeObserverWithHandle:addedHandle];
[client_ removeObserverWithHandle:changedHandle];
[client_ removeObserverWithHandle:movedHandle];
[client_ removeObserverWithHandle:removedHandle];
auto it = std::find_if(child_event_listeners_.begin(),
child_event_listeners_.end(),
[listener](const ::firebase::ChildEventListenerPtr& p) {
return (p.get() == listener);
});
DCHECK(it != child_event_listeners_.end());
child_event_listeners_.erase(it);
}
);
child_event_listeners_.emplace_back(ptr.Pass());
}
void FirebaseImpl::ObserveSingleEventOfType(
::firebase::EventType eventType,
const ObserveSingleEventOfTypeCallback& callback) {
ObserveSingleEventOfTypeCallback *copyCallback =
new ObserveSingleEventOfTypeCallback(callback);
[client_ observeSingleEventOfType:static_cast<FEventType>(eventType)
withBlock:^(FDataSnapshot *snapshot) {
copyCallback->Run(toMojoSnapshot(snapshot));
delete copyCallback;
}];
}
void FirebaseImpl::AuthWithCustomToken(
const mojo::String& token,
const AuthWithCustomTokenCallback& callback) {
}
void FirebaseImpl::AuthAnonymously(
const AuthAnonymouslyCallback& callback) {
AuthAnonymouslyCallback *copyCallback =
new AuthAnonymouslyCallback(callback);
[client_ authAnonymouslyWithCompletionBlock:^(NSError *error, FAuthData *authData) {
copyCallback->Run(toMojoError(error), toMojoAuthData(authData));
delete copyCallback;
}];
}
void FirebaseImpl::AuthWithOAuthToken(
const mojo::String& provider,
const mojo::String& credentials,
const AuthWithOAuthTokenCallback& callback) {
AuthWithOAuthTokenCallback *copyCallback =
new AuthWithOAuthTokenCallback(callback);
[client_ authWithOAuthProvider:@(provider.data())
token:@(credentials.data())
withCompletionBlock:^(NSError *error, FAuthData *authData) {
copyCallback->Run(toMojoError(error), toMojoAuthData(authData));
delete copyCallback;
}];
}
void FirebaseImpl::AuthWithPassword(
const mojo::String& email,
const mojo::String& password,
const AuthWithPasswordCallback& callback) {
AuthWithPasswordCallback *copyCallback =
new AuthWithPasswordCallback(callback);
[client_ authUser:@(email.data())
password:@(password.data())
withCompletionBlock:^(NSError *error, FAuthData *authData) {
copyCallback->Run(toMojoError(error), toMojoAuthData(authData));
delete copyCallback;
}];
}
void FirebaseImpl::Unauth(const UnauthCallback& callback) {
[client_ unauth];
callback.Run(toMojoError(nullptr));
}
void FirebaseImpl::GetChild(
const mojo::String& path,
mojo::InterfaceRequest<Firebase> request) {
FirebaseImpl *child = new FirebaseImpl(request.Pass());
child->client_ = [[client_ childByAppendingPath:@(path.data())] retain];
}
void FirebaseImpl::GetParent(mojo::InterfaceRequest<Firebase> request) {
FirebaseImpl *parent = new FirebaseImpl(request.Pass());
parent->client_ = [[client_ parent] retain];
}
void FirebaseImpl::GetRoot(mojo::InterfaceRequest<::firebase::Firebase> request) {
FirebaseImpl *root = new FirebaseImpl(request.Pass());
root->client_ = [[client_ root] retain];
}
void FirebaseImpl::SetValue(const mojo::String& jsonValue,
int32_t priority,
bool hasPriority,
const SetValueCallback& callback) {
SetValueCallback *copyCallback =
new SetValueCallback(callback);
NSData *data = [@(jsonValue.data()) dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *valueDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
id value = [valueDictionary valueForKey:@"value"];
void (^completionBlock)(NSError *, ::Firebase* ref) = ^(NSError* error, ::Firebase* ref) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
};
if (valueDictionary != nil) {
if (hasPriority) {
[client_ setValue:value
andPriority:@(priority)
withCompletionBlock:completionBlock];
} else {
[client_ setValue:value withCompletionBlock:completionBlock];
}
} else {
completionBlock(error, client_);
}
}
void FirebaseImpl::RemoveValue(const RemoveValueCallback& callback) {
RemoveValueCallback *copyCallback =
new RemoveValueCallback(callback);
[client_ removeValueWithCompletionBlock:^(NSError *error, ::Firebase *ref) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
}];
}
void FirebaseImpl::Push(mojo::InterfaceRequest<Firebase> request,
const PushCallback& callback) {
FirebaseImpl *child = new FirebaseImpl(request.Pass());
child->client_ = [[client_ childByAutoId] retain];
callback.Run(base::SysNSStringToUTF8(child->client_.key));
}
void FirebaseImpl::SetPriority(int32_t priority,
const SetPriorityCallback& callback) {
SetPriorityCallback *copyCallback =
new SetPriorityCallback(callback);
[client_ setPriority:@(priority)
withCompletionBlock:^(NSError *error, ::Firebase *ref) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
}];
}
void FirebaseImpl::CreateUser(const mojo::String& email,
const mojo::String& password,
const CreateUserCallback& callback) {
CreateUserCallback *copyCallback =
new CreateUserCallback(callback);
[client_ createUser:@(email.data())
password:@(password.data())
withValueCompletionBlock:^(NSError *error, NSDictionary *valueDictionary) {
NSData *data = [NSJSONSerialization dataWithJSONObject:valueDictionary
options:0
error:nil];
if (data != nil) {
NSString *jsonValue = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
copyCallback->Run(toMojoError(error), base::SysNSStringToUTF8(jsonValue));
} else {
copyCallback->Run(toMojoError(error), nullptr);
}
delete copyCallback;
}];
}
void FirebaseImpl::ChangeEmail(const mojo::String& oldEmail,
const mojo::String& password,
const mojo::String& newEmail,
const ChangeEmailCallback& callback) {
ChangeEmailCallback *copyCallback =
new ChangeEmailCallback(callback);
[client_ changeEmailForUser:@(oldEmail.data())
password:@(password.data())
toNewEmail:@(newEmail.data())
withCompletionBlock:^(NSError *error) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
}];
}
void FirebaseImpl::ChangePassword(
const mojo::String& newPassword,
const mojo::String& email,
const mojo::String& oldPassword,
const ChangePasswordCallback& callback) {
ChangePasswordCallback *copyCallback =
new ChangePasswordCallback(callback);
[client_ changePasswordForUser:@(email.data())
fromOld:@(oldPassword.data())
toNew:@(newPassword.data())
withCompletionBlock:^(NSError *error) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
}];
}
void FirebaseImpl::RemoveUser(const mojo::String& email,
const mojo::String& password,
const RemoveUserCallback& callback) {
RemoveUserCallback *copyCallback =
new RemoveUserCallback(callback);
[client_ removeUser:@(email.data())
password:@(password.data())
withCompletionBlock:^(NSError *error) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
}];
}
void FirebaseImpl::ResetPassword(const mojo::String& email,
const ResetPasswordCallback& callback) {
ResetPasswordCallback *copyCallback =
new ResetPasswordCallback(callback);
[client_ resetPasswordForUser:@(email.data())
withCompletionBlock:^(NSError *error) {
copyCallback->Run(toMojoError(error));
delete copyCallback;
}];
}
void FirebaseFactory::Create(
mojo::ApplicationConnection* connection,
mojo::InterfaceRequest<::firebase::Firebase> request) {
new FirebaseImpl(request.Pass());
}
} // namespace firebase
} // namespace services
} // namespace sky

View File

@ -1,402 +0,0 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.firebase;
import android.content.Context;
import android.util.Log;
import com.firebase.client.AuthData;
import com.firebase.client.FirebaseError;
import com.firebase.client.Firebase.AuthResultHandler;
import com.firebase.client.Firebase.CompletionListener;
import com.firebase.client.Firebase.ResultHandler;
import com.firebase.client.Firebase.ValueResultHandler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import org.chromium.mojo.bindings.ConnectionErrorHandler;
import org.chromium.mojo.bindings.Interface.Binding;
import org.chromium.mojo.bindings.InterfaceRequest;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojom.firebase.DataSnapshot;
import org.chromium.mojom.firebase.EventType;
import org.chromium.mojom.firebase.Firebase;
import org.chromium.mojom.firebase.ValueEventListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FirebaseImpl implements org.chromium.mojom.firebase.Firebase {
private static final String TAG = "FirebaseImpl";
static private Context mContext;
private com.firebase.client.Firebase mClient;
public FirebaseImpl(Context context) {
if (context != mContext)
com.firebase.client.Firebase.setAndroidContext(context);
mContext = context;
}
public static Binding connectToService(Context context, Core core, MessagePipeHandle pipe) {
return Firebase.MANAGER.bind(new FirebaseImpl(context), pipe);
}
@Override
public void close() {}
@Override
public void onConnectionError(MojoException e) {}
@Override
public void initWithUrl(String url) {
mClient = new com.firebase.client.Firebase(url);
}
@Override
public void addValueEventListener(org.chromium.mojom.firebase.ValueEventListener listener) {
final org.chromium.mojom.firebase.ValueEventListener.Proxy proxy =
(org.chromium.mojom.firebase.ValueEventListener.Proxy)listener;
final com.firebase.client.ValueEventListener firebaseListener =
new com.firebase.client.ValueEventListener() {
@Override
public void onCancelled(FirebaseError error) {
proxy.onCancelled(toMojoError(error));
}
@Override
public void onDataChange(com.firebase.client.DataSnapshot snapshot) {
proxy.onDataChange(toMojoSnapshot(snapshot));
}
};
proxy.getProxyHandler().setErrorHandler(new ConnectionErrorHandler() {
@Override
public void onConnectionError(MojoException e) {
mClient.removeEventListener(firebaseListener);
}
});
mClient.addValueEventListener(firebaseListener);
}
@Override
public void addChildEventListener(org.chromium.mojom.firebase.ChildEventListener listener) {
final org.chromium.mojom.firebase.ChildEventListener.Proxy proxy =
(org.chromium.mojom.firebase.ChildEventListener.Proxy)listener;
final com.firebase.client.ChildEventListener firebaseListener =
new com.firebase.client.ChildEventListener() {
@Override
public void onCancelled(FirebaseError error) {
proxy.onCancelled(toMojoError(error));
}
@Override
public void onChildAdded(com.firebase.client.DataSnapshot snapshot, String previousChildName) {
proxy.onChildAdded(toMojoSnapshot(snapshot), previousChildName);
}
@Override
public void onChildChanged(com.firebase.client.DataSnapshot snapshot, String previousChildName) {
proxy.onChildChanged(toMojoSnapshot(snapshot), previousChildName);
}
@Override
public void onChildMoved(com.firebase.client.DataSnapshot snapshot, String previousChildName) {
proxy.onChildMoved(toMojoSnapshot(snapshot), previousChildName);
}
@Override
public void onChildRemoved(com.firebase.client.DataSnapshot snapshot) {
proxy.onChildRemoved(toMojoSnapshot(snapshot));
}
};
proxy.getProxyHandler().setErrorHandler(new ConnectionErrorHandler() {
@Override
public void onConnectionError(MojoException e) {
mClient.removeEventListener(firebaseListener);
}
});
mClient.addChildEventListener(firebaseListener);
}
@Override
public void observeSingleEventOfType(int eventType, final ObserveSingleEventOfTypeResponse response) {
mClient.addListenerForSingleValueEvent(new com.firebase.client.ValueEventListener() {
@Override
public void onDataChange(com.firebase.client.DataSnapshot snapshot) {
response.call(toMojoSnapshot(snapshot));
}
@Override
public void onCancelled(FirebaseError error) {
// No-op
}
});
}
@Override
public void authWithCustomToken(String token, final AuthWithCustomTokenResponse response) {
mClient.authWithCustomToken(token, new AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
response.call(null, toMojoAuthData(authData));
}
public void onAuthenticationError(FirebaseError error) {
response.call(toMojoError(error), null);
}
});
}
@Override
public void authAnonymously(final AuthAnonymouslyResponse response) {
mClient.authAnonymously(new AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
response.call(null, toMojoAuthData(authData));
}
public void onAuthenticationError(FirebaseError error) {
response.call(toMojoError(error), null);
}
});
}
@Override
public void authWithOAuthToken(String provider, String credentials, final AuthWithOAuthTokenResponse response) {
mClient.authWithOAuthToken(provider, credentials, new AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
response.call(null, toMojoAuthData(authData));
}
public void onAuthenticationError(FirebaseError error) {
response.call(toMojoError(error), null);
}
});
}
@Override
public void authWithPassword(String email, String password, final AuthWithPasswordResponse response) {
mClient.authWithPassword(email, password, new AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
response.call(null, toMojoAuthData(authData));
}
public void onAuthenticationError(FirebaseError error) {
response.call(toMojoError(error), null);
}
});
}
@Override
public void unauth(final UnauthResponse response) {
mClient.unauth(new CompletionListener() {
@Override
public void onComplete(FirebaseError error, com.firebase.client.Firebase ref) {
response.call(toMojoError(error));
}
});
}
@Override
public void getChild(String path, InterfaceRequest<Firebase> request) {
FirebaseImpl child = new FirebaseImpl(mContext);
child.mClient = mClient.child(path);
Firebase.MANAGER.bind(child, request);
}
@Override
public void getParent(InterfaceRequest<Firebase> request) {
FirebaseImpl parent = new FirebaseImpl(mContext);
parent.mClient = mClient.getParent();
Firebase.MANAGER.bind(parent, request);
}
@Override
public void getRoot(InterfaceRequest<Firebase> request) {
FirebaseImpl root = new FirebaseImpl(mContext);
root.mClient = mClient.getRoot();
Firebase.MANAGER.bind(root, request);
}
@Override
public void setValue(String jsonValue, int priority, boolean hasPriority, final SetValueResponse response) {
try {
JSONObject root = new JSONObject(jsonValue);
Object value = toMap(root).get("value");
mClient.setValue(value, hasPriority ? priority : null, new CompletionListener() {
@Override
public void onComplete(FirebaseError error, com.firebase.client.Firebase ref) {
response.call(toMojoError(error));
}
});
} catch(JSONException e) {
org.chromium.mojom.firebase.Error mojoError =
new org.chromium.mojom.firebase.Error();
mojoError.code = -1;
mojoError.message = "setValue JSONException";
Log.e(TAG, "setValue JSONException", e);
response.call(mojoError);
}
}
@Override
public void removeValue(final RemoveValueResponse response) {
mClient.removeValue(new CompletionListener() {
@Override
public void onComplete(FirebaseError error, com.firebase.client.Firebase ref) {
response.call(toMojoError(error));
}
});
}
@Override
public void push(InterfaceRequest<Firebase> request, final PushResponse response) {
FirebaseImpl child = new FirebaseImpl(mContext);
child.mClient = mClient.push();
Firebase.MANAGER.bind(child, request);
response.call(child.mClient.getKey());
}
@Override
public void setPriority(int priority, final SetPriorityResponse response) {
mClient.setPriority(priority, new CompletionListener() {
@Override
public void onComplete(FirebaseError error, com.firebase.client.Firebase ref) {
response.call(toMojoError(error));
}
});
}
@Override
public void createUser(String email, String password, final CreateUserResponse response) {
mClient.createUser(email, password, new ValueResultHandler<Map<String,Object>>() {
@Override
public void onError(FirebaseError error) {
response.call(toMojoError(error), null);
}
@Override
public void onSuccess(Map<String,Object> result) {
response.call(null, new JSONObject(result).toString());
}
});
}
@Override
public void changeEmail(String oldEmail, String password, String newExample, final ChangeEmailResponse response) {
mClient.changeEmail(oldEmail, password, newExample, new ResultHandler() {
@Override
public void onError(FirebaseError error) {
response.call(toMojoError(error));
}
@Override
public void onSuccess() {
response.call(null);
}
});
}
@Override
public void changePassword(String newPassword, String email, String oldPassword, final ChangePasswordResponse response) {
mClient.changePassword(newPassword, email, oldPassword, new ResultHandler() {
@Override
public void onError(FirebaseError error) {
response.call(toMojoError(error));
}
@Override
public void onSuccess() {
response.call(null);
}
});
}
@Override
public void removeUser(String email, String password, final RemoveUserResponse response) {
mClient.removeUser(email, password, new ResultHandler() {
@Override
public void onError(FirebaseError error) {
response.call(toMojoError(error));
}
@Override
public void onSuccess() {
response.call(null);
}
});
}
@Override
public void resetPassword(String email, final ResetPasswordResponse response) {
mClient.resetPassword(email, new ResultHandler() {
@Override
public void onError(FirebaseError error) {
response.call(toMojoError(error));
}
@Override
public void onSuccess() {
response.call(null);
}
});
}
DataSnapshot toMojoSnapshot(com.firebase.client.DataSnapshot snapshot) {
DataSnapshot mojoSnapshot = new DataSnapshot();
mojoSnapshot.key = snapshot.getKey();
Map<String, Object> jsonValue = new HashMap<String, Object>();
jsonValue.put("value", snapshot.getValue());
mojoSnapshot.jsonValue = new JSONObject(jsonValue).toString();
return mojoSnapshot;
}
org.chromium.mojom.firebase.Error toMojoError(FirebaseError error) {
if (error == null)
return null;
org.chromium.mojom.firebase.Error mojoError =
new org.chromium.mojom.firebase.Error();
mojoError.code = error.getCode();
mojoError.message = error.getMessage();
return mojoError;
}
org.chromium.mojom.firebase.AuthData toMojoAuthData(AuthData authData) {
org.chromium.mojom.firebase.AuthData mojoAuthData =
new org.chromium.mojom.firebase.AuthData();
mojoAuthData.uid = authData.getUid();
mojoAuthData.provider = authData.getProvider();
mojoAuthData.token = authData.getToken();
return mojoAuthData;
}
// public domain code from https://gist.github.com/codebutler/2339666
@SuppressWarnings({ "rawtypes", "unchecked" })
static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}