)self;
62 |
63 | [bannerView loadRequest:request];
64 | return bannerView;
65 | @}
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/Firebase.Analytics/Analytics.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 |
12 | namespace Firebase.Analytics
13 | {
14 |
15 | [ForeignInclude(Language.Java, "android.os.Bundle", "com.google.firebase.analytics.FirebaseAnalytics")]
16 | [Require("Cocoapods.Podfile.Target", "pod 'FirebaseAnalytics'")]
17 | extern(mobile)
18 | internal static class AnalyticsService
19 | {
20 | static bool _initialized;
21 | extern(android) static Java.Object _handle;
22 |
23 | [Foreign(Language.Java)]
24 | extern(android)
25 | public static void LogEvent(string name, string[] keys, string[] vals, int len)
26 | @{
27 | @{_handle:Set(FirebaseAnalytics.getInstance(com.fuse.Activity.getRootActivity()))};
28 | Bundle bundle = new Bundle();
29 |
30 | for (int i = 0; i < len; i++) {
31 | bundle.putString(keys.get(i), vals.get(i));
32 | }
33 | ((FirebaseAnalytics)@{_handle}).logEvent(name, bundle);
34 | @}
35 |
36 |
37 | [Require("Source.Import","FirebaseAnalytics/FirebaseAnalytics.h")]
38 | [Require("Xcode.Framework", "AdSupport.framework")]
39 | [Foreign(Language.ObjC)]
40 | extern(iOS)
41 | public static void LogEvent(string name, string[] keys, string[] vals, int len)
42 | @{
43 | NSDictionary *param = [NSDictionary dictionaryWithObjects:[vals copyArray] forKeys:[keys copyArray]];
44 | [FIRAnalytics logEventWithName:name parameters:param];
45 | @}
46 | }
47 |
48 | extern(!mobile)
49 | internal static class AnalyticsService
50 | {
51 | public static void Init() {}
52 | public static void LogEvent(string name, string[] keys, string[] vals, int len) {
53 | debug_log "LogEvent: " + name;
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/Firebase.Analytics/Firebase.Analytics.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase/Firebase.unoproj"
4 | ],
5 | "Packages": [
6 | "Fuse",
7 | "FuseJS",
8 | "Fuse.Scripting"
9 | ],
10 | "Includes": [
11 | "*",
12 | "android_const.js:Bundle",
13 | "kfirevent.js:Bundle",
14 | "kfirparameter.js:Bundle"
15 | ]
16 | }
17 |
--------------------------------------------------------------------------------
/src/Firebase.Analytics/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Threading;
4 | using Uno.Text;
5 | using Uno.Platform;
6 | using Uno.Compiler.ExportTargetInterop;
7 | using Uno.Collections;
8 | using Fuse;
9 | using Fuse.Scripting;
10 | using Fuse.Reactive;
11 | using Firebase.Analytics;
12 |
13 | namespace Firebase.Analytics.JS
14 | {
15 | /**
16 | */
17 | [UXGlobalModule]
18 | public sealed class AnalyticsModule : NativeModule
19 | {
20 | static readonly AnalyticsModule _instance;
21 |
22 | public AnalyticsModule()
23 | {
24 | if(_instance != null) return;
25 | Uno.UX.Resource.SetGlobalKey(_instance = this, "Firebase/Analytics");
26 |
27 | Firebase.Core.Init();
28 | AddMember(new NativeFunction("logEvent", LogEvent));
29 | }
30 |
31 | static object LogEvent(Context context, object[] args)
32 | {
33 | var n = (string)args[0];
34 | var p = (Fuse.Scripting.Object)args[1];
35 | var keys = p.Keys;
36 | string[] objs = new string[keys.Length];
37 | for (int i=0; i < keys.Length; i++) {
38 | objs[i] = p[keys[i]].ToString();
39 | }
40 | AnalyticsService.LogEvent(n, keys, objs, keys.Length);
41 | return null;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/Firebase.Analytics/kfirparameter.js:
--------------------------------------------------------------------------------
1 | var kFIRParameter = {};
2 | module.exports = kFIRParameter;
3 |
4 | /// @file FIRParameterNames.h
5 | ///
6 | /// Predefined event parameter names.
7 | ///
8 | /// Params supply information that contextualize Events. You can associate up to 25 unique Params
9 | /// with each Event type. Some Params are suggested below for certain common Events, but you are
10 | /// not limited to these. You may supply extra Params for suggested Events or custom Params for
11 | /// Custom events. Param names can be up to 24 characters long, may only contain alphanumeric
12 | /// characters and underscores ("_"), and must start with an alphabetic character. Param values can
13 | /// be up to 36 characters long. The "firebase_" prefix is reserved and should not be used.
14 |
15 | /// Game achievement ID (NSString).
16 | ///
17 | /// NSDictionary *params = @{
18 | /// kFIRParameterAchievementID : "10_matches_won",
19 | /// // ...
20 | /// };
21 | ///
22 | kFIRParameter.AchievementID = "achievement_id";
23 |
24 | /// Character used in game (NSString).
25 | ///
26 | /// NSDictionary *params = @{
27 | /// kFIRParameterCharacter : "beat_boss",
28 | /// // ...
29 | /// };
30 | ///
31 | kFIRParameter.Character = "character";
32 |
33 | /// Type of content selected (NSString).
34 | ///
35 | /// NSDictionary *params = @{
36 | /// kFIRParameterContentType : "news article",
37 | /// // ...
38 | /// };
39 | ///
40 | kFIRParameter.ContentType = "content_type";
41 |
42 | /// Coupon code for a purchasable item (NSString).
43 | ///
44 | /// NSDictionary *params = @{
45 | /// kFIRParameterCoupon : "zz123",
46 | /// // ...
47 | /// };
48 | ///
49 | kFIRParameter.Coupon = "coupon";
50 |
51 | /// Purchase currency in 3-letter
52 | /// ISO_4217 format (NSString).
53 | ///
54 | /// NSDictionary *params = @{
55 | /// kFIRParameterCurrency : "USD",
56 | /// // ...
57 | /// };
58 | ///
59 | kFIRParameter.Currency = "currency";
60 |
61 | /// Flight or Travel destination (NSString).
62 | ///
63 | /// NSDictionary *params = @{
64 | /// kFIRParameterDestination : "Mountain View, CA",
65 | /// // ...
66 | /// };
67 | ///
68 | kFIRParameter.Destination = "destination";
69 |
70 | /// The arrival date, check-out date or rental end date for the item. This should be in
71 | /// YYYY-MM-DD format (NSString).
72 | ///
73 | /// NSDictionary *params = @{
74 | /// kFIRParameterEndDate : "2015-09-14",
75 | /// // ...
76 | /// };
77 | ///
78 | kFIRParameter.EndDate = "end_date";
79 |
80 | /// Flight number for travel events (NSString).
81 | ///
82 | /// NSDictionary *params = @{
83 | /// kFIRParameterFlightNumber : "ZZ800",
84 | /// // ...
85 | /// };
86 | ///
87 | kFIRParameter.FlightNumber = "flight_number";
88 |
89 | /// Group/clan/guild ID (NSString).
90 | ///
91 | /// NSDictionary *params = @{
92 | /// kFIRParameterGroupID : "g1",
93 | /// // ...
94 | /// };
95 | ///
96 | kFIRParameter.GroupID = "group_id";
97 |
98 | /// Item category (NSString).
99 | ///
100 | /// NSDictionary *params = @{
101 | /// kFIRParameterItemCategory : "t-shirts",
102 | /// // ...
103 | /// };
104 | ///
105 | kFIRParameter.ItemCategory = "item_category";
106 |
107 | /// Item ID (NSString).
108 | ///
109 | /// NSDictionary *params = @{
110 | /// kFIRParameterItemID : "p7654",
111 | /// // ...
112 | /// };
113 | ///
114 | kFIRParameter.ItemID = "item_id";
115 |
116 | /// The Google Place ID (NSString) that
117 | /// corresponds to the associated item. Alternatively, you can supply your own custom Location ID.
118 | ///
119 | /// NSDictionary *params = @{
120 | /// kFIRParameterItemLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ",
121 | /// // ...
122 | /// };
123 | ///
124 | kFIRParameter.ItemLocationID = "item_location_id";
125 |
126 | /// Item name (NSString).
127 | ///
128 | /// NSDictionary *params = @{
129 | /// kFIRParameterItemName : "abc",
130 | /// // ...
131 | /// };
132 | ///
133 | kFIRParameter.ItemName = "item_name";
134 |
135 | /// Level in game (signed 64-bit integer as NSNumber).
136 | ///
137 | /// NSDictionary *params = @{
138 | /// kFIRParameterLevel : @(42),
139 | /// // ...
140 | /// };
141 | ///
142 | kFIRParameter.Level = "level";
143 |
144 | /// Location (NSString). The Google Place ID
145 | /// that corresponds to the associated event. Alternatively, you can supply your own custom
146 | /// Location ID.
147 | ///
148 | /// NSDictionary *params = @{
149 | /// kFIRParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ",
150 | /// // ...
151 | /// };
152 | ///
153 | kFIRParameter.Location = "location";
154 |
155 | /// Number of nights staying at hotel (signed 64-bit integer as NSNumber).
156 | ///
157 | /// NSDictionary *params = @{
158 | /// kFIRParameterNumberOfNights : @(3),
159 | /// // ...
160 | /// };
161 | ///
162 | kFIRParameter.NumberOfNights = "number_of_nights";
163 |
164 | /// Number of passengers traveling (signed 64-bit integer as NSNumber).
165 | ///
166 | /// NSDictionary *params = @{
167 | /// kFIRParameterNumberOfPassengers : @(11),
168 | /// // ...
169 | /// };
170 | ///
171 | kFIRParameter.NumberOfPassengers = "number_of_passengers";
172 |
173 | /// Number of rooms for travel events (signed 64-bit integer as NSNumber).
174 | ///
175 | /// NSDictionary *params = @{
176 | /// kFIRParameterNumberOfRooms : @(2),
177 | /// // ...
178 | /// };
179 | ///
180 | kFIRParameter.NumberOfRooms = "number_of_rooms";
181 |
182 | /// Flight or Travel origin (NSString).
183 | ///
184 | /// NSDictionary *params = @{
185 | /// kFIRParameterOrigin : "Mountain View, CA",
186 | /// // ...
187 | /// };
188 | ///
189 | kFIRParameter.Origin = "origin";
190 |
191 | /// Purchase price (double as NSNumber).
192 | ///
193 | /// NSDictionary *params = @{
194 | /// kFIRParameterPrice : @(1.0),
195 | /// kFIRParameterCurrency : "USD", // e.g. $1.00 USD
196 | /// // ...
197 | /// };
198 | ///
199 | kFIRParameter.Price = "price";
200 |
201 | /// Purchase quantity (signed 64-bit integer as NSNumber).
202 | ///
203 | /// NSDictionary *params = @{
204 | /// kFIRParameterQuantity : @(1),
205 | /// // ...
206 | /// };
207 | ///
208 | kFIRParameter.Quantity = "quantity";
209 |
210 | /// Score in game (signed 64-bit integer as NSNumber).
211 | ///
212 | /// NSDictionary *params = @{
213 | /// kFIRParameterScore : @(4200),
214 | /// // ...
215 | /// };
216 | ///
217 | kFIRParameter.Score = "score";
218 |
219 | /// The search string/keywords used (NSString).
220 | ///
221 | /// NSDictionary *params = @{
222 | /// kFIRParameterSearchTerm : "periodic table",
223 | /// // ...
224 | /// };
225 | ///
226 | kFIRParameter.SearchTerm = "search_term";
227 |
228 | /// Shipping cost (double as NSNumber).
229 | ///
230 | /// NSDictionary *params = @{
231 | /// kFIRParameterShipping : @(9.50),
232 | /// kFIRParameterCurrency : "USD", // e.g. $9.50 USD
233 | /// // ...
234 | /// };
235 | ///
236 | kFIRParameter.Shipping = "shipping";
237 |
238 | /// Sign up method (NSString).
239 | ///
240 | /// NSDictionary *params = @{
241 | /// kFIRParameterSignUpMethod : "google",
242 | /// // ...
243 | /// };
244 | ///
245 | kFIRParameter.SignUpMethod = "sign_up_method";
246 |
247 | /// The departure date, check-in date or rental start date for the item. This should be in
248 | /// YYYY-MM-DD format (NSString).
249 | ///
250 | /// NSDictionary *params = @{
251 | /// kFIRParameterStartDate : "2015-09-14",
252 | /// // ...
253 | /// };
254 | ///
255 | kFIRParameter.StartDate = "start_date";
256 |
257 | /// Tax amount (double as NSNumber).
258 | ///
259 | /// NSDictionary *params = @{
260 | /// kFIRParameterTax : @(1.0),
261 | /// kFIRParameterCurrency : "USD", // e.g. $1.00 USD
262 | /// // ...
263 | /// };
264 | ///
265 | kFIRParameter.Tax = "tax";
266 |
267 | /// A single ID for a ecommerce group transaction (NSString).
268 | ///
269 | /// NSDictionary *params = @{
270 | /// kFIRParameterTransactionID : "ab7236dd9823",
271 | /// // ...
272 | /// };
273 | ///
274 | kFIRParameter.TransactionID = "transaction_id";
275 |
276 | /// Travel class (NSString).
277 | ///
278 | /// NSDictionary *params = @{
279 | /// kFIRParameterTravelClass : "business",
280 | /// // ...
281 | /// };
282 | ///
283 | kFIRParameter.TravelClass = "travel_class";
284 |
285 | /// A context-specific numeric value which is accumulated automatically for each event type. This is
286 | /// a general purpose parameter that is useful for accumulating a key metric that pertains to an
287 | /// event. Examples include revenue, distance, time and points. Value should be specified as signed
288 | /// 64-bit integer or double as NSNumber. Notes: Currency-related values should be supplied using
289 | /// double as NSNumber and must be accompanied by a {@link kFIRParameterCurrency} parameter. The
290 | /// valid range of accumulated values is [-9,223,372,036,854.77, 9,223,372,036,854.77].
291 | ///
292 | /// NSDictionary *params = @{
293 | /// kFIRParameterValue : @(3.99),
294 | /// kFIRParameterCurrency : "USD", // e.g. $3.99 USD
295 | /// // ...
296 | /// };
297 | ///
298 | kFIRParameter.Value = "value";
299 |
300 | /// Name of virtual currency type (NSString).
301 | ///
302 | /// NSDictionary *params = @{
303 | /// kFIRParameterVirtualCurrencyName : "virtual_currency_name",
304 | /// // ...
305 | /// };
306 | ///
307 | kFIRParameter.VirtualCurrencyName = "virtual_currency_name";
308 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Email/Authentication.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Email
14 | {
15 | public class EmailService : Firebase.Authentication.AuthProvider
16 | {
17 | static bool _initd = false;
18 |
19 | internal static void Init()
20 | {
21 | if (_initd) return;
22 | var es = new EmailService();
23 | Firebase.Authentication.AuthService.RegisterAuthProvider(es);
24 | _initd = true;
25 | }
26 |
27 | public override AuthProviderName Name { get { return AuthProviderName.Email; } }
28 |
29 | public override void Start() {}
30 |
31 | public override void SignOut() {}
32 |
33 | public override Promise ReAuthenticate(string email, string password)
34 | {
35 | return new ReAuthenticate(email, password);
36 | }
37 | }
38 |
39 | extern(!mobile)
40 | internal class ReAuthenticate : Promise
41 | {
42 | public ReAuthenticate(string email, string password) {}
43 | public void Reject(string reason) { }
44 | }
45 |
46 | extern(!mobile)
47 | internal class CreateUser : Promise
48 | {
49 | public CreateUser(string email, string password) { }
50 | public void Reject(string reason) { }
51 | }
52 |
53 | extern(!mobile)
54 | internal class SignInUser : Promise
55 | {
56 | public SignInUser(string email, string password) { }
57 | public void Reject(string reason) { }
58 | }
59 |
60 | extern(!mobile)
61 | internal class UpdateEmail : Promise
62 | {
63 | public UpdateEmail(string email) {}
64 | void Reject(string reason) { Reject(new Exception(reason)); }
65 | }
66 |
67 | extern(!mobile)
68 | internal class UpdatePassword : Promise
69 | {
70 | public UpdatePassword(string password) {}
71 | void Reject(string reason) { Reject(new Exception(reason)); }
72 | }
73 |
74 | extern(!mobile)
75 | internal class SendVerificationEmail : Promise
76 | {
77 | public SendVerificationEmail() {}
78 | void Reject(string reason) { Reject(new Exception(reason)); }
79 | }
80 |
81 | extern(!mobile)
82 | internal class SendPasswordResetEmail : Promise
83 | {
84 | public SendPasswordResetEmail(string email) {}
85 | void Reject(string reason) { Reject(new Exception(reason)); }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Email/Firebase.Authentication.Email.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase.Authentication/Firebase.Authentication.unoproj"
4 | ],
5 | "Packages": [
6 | "Fuse",
7 | "FuseJS",
8 | "Fuse.Scripting"
9 | ],
10 | "Includes": [
11 | "*"
12 | ]
13 | }
14 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Email/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Threading;
4 | using Uno.Text;
5 | using Uno.Platform;
6 | using Uno.Compiler.ExportTargetInterop;
7 | using Uno.Collections;
8 | using Fuse;
9 | using Fuse.Scripting;
10 | using Fuse.Reactive;
11 |
12 | namespace Firebase.Authentication.Email.JS
13 | {
14 | /**
15 | */
16 | [UXGlobalModule]
17 | public sealed class EmailModule : NativeModule
18 | {
19 | // static NativeEvent _onReceivedMessage;
20 | static readonly EmailModule _instance;
21 |
22 | public EmailModule()
23 | {
24 | if(_instance != null) return;
25 | Uno.UX.Resource.SetGlobalKey(_instance = this, "Firebase/Authentication/Email");
26 |
27 | Firebase.Authentication.Email.EmailService.Init();
28 |
29 | AddMember(new NativePromise("createWithEmailAndPassword", CreateWithEmailAndPassword));
30 | AddMember(new NativePromise("signInWithEmailAndPassword", SignInWithEmailAndPassword));
31 | AddMember(new NativePromise("updateEmail", UpdateEmail));
32 | AddMember(new NativePromise("updatePassword", UpdatePassword));
33 | AddMember(new NativePromise("sendVerificationEmail", SendVerificationEmail));
34 | AddMember(new NativePromise("sendPasswordResetEmail", SendPasswordResetEmail));
35 |
36 | }
37 |
38 | Future CreateWithEmailAndPassword(object[] args)
39 | {
40 | var email = (string)args[0];
41 | var password = (string)args[1];
42 | return new Firebase.Authentication.Email.CreateUser(email, password);
43 | }
44 |
45 | Future SignInWithEmailAndPassword(object[] args)
46 | {
47 | var email = (string)args[0];
48 | var password = (string)args[1];
49 | return new Firebase.Authentication.Email.SignInUser(email, password);
50 | }
51 |
52 | Future UpdateEmail(object[] args)
53 | {
54 | var email = (string)args[0];
55 | return new Firebase.Authentication.Email.UpdateEmail(email);
56 | }
57 |
58 | Future UpdatePassword(object[] args)
59 | {
60 | var password = (string)args[0];
61 | return new Firebase.Authentication.Email.UpdatePassword(password);
62 | }
63 |
64 | Future SendVerificationEmail(object[] args)
65 | {
66 | return new Firebase.Authentication.Email.SendVerificationEmail();
67 | }
68 |
69 | Future SendPasswordResetEmail(object[] args)
70 | {
71 | var email = (string)args[0];
72 | return new Firebase.Authentication.Email.SendPasswordResetEmail(email);
73 | }
74 |
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Email/iOSImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Email
14 | {
15 | [Require("Source.Include", "Firebase/Firebase.h")]
16 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
17 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
18 | extern(iOS)
19 | class CreateUser : Promise
20 | {
21 | [Foreign(Language.ObjC)]
22 | public CreateUser(string email, string password)
23 | @{
24 | [[FIRAuth auth]
25 | createUserWithEmail:email
26 | password:password
27 | completion:^(FIRAuthDataResult * _Nullable authResult, NSError* error) {
28 | if (error)
29 | @{CreateUser:Of(_this).Reject(int):Call(error.code)};
30 | else
31 | @{CreateUser:Of(_this).Resolve(string):Call(@"success")};
32 | }];
33 | @}
34 |
35 | void Resolve(string message)
36 | {
37 | AuthService.AnnounceSignIn(AuthProviderName.Email);
38 | base.Resolve(message);
39 | }
40 |
41 | void Reject(int errorCode)
42 | {
43 | Reject(new Exception(Errors.CreateUserWithEmailBaseErrorMessage(errorCode)));
44 | }
45 | }
46 |
47 | [Require("Source.Include", "Firebase/Firebase.h")]
48 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
49 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
50 | extern(iOS)
51 | class SignInUser : Promise
52 | {
53 | [Foreign(Language.ObjC)]
54 | public SignInUser(string email, string password)
55 | @{
56 | [[FIRAuth auth]
57 | signInWithEmail:email
58 | password:password
59 | completion:^(FIRAuthDataResult * _Nullable authResult, NSError* error) {
60 | if (error)
61 | @{SignInUser:Of(_this).Reject(int):Call(error.code)};
62 | else
63 | @{SignInUser:Of(_this).Resolve(string):Call(@"success")};
64 | }];
65 | @}
66 |
67 | void Resolve(string message)
68 | {
69 | AuthService.AnnounceSignIn(AuthProviderName.Email);
70 | base.Resolve(message);
71 | }
72 |
73 | void Reject(int errorCode)
74 | {
75 | Reject(new Exception(Errors.SignInWithEmailBaseErrorMessage(errorCode)));
76 | }
77 | }
78 |
79 | [Require("Source.Include", "Firebase/Firebase.h")]
80 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
81 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
82 | [Require("Source.Include", "@{Firebase.Authentication.User:Include}")]
83 | extern(iOS)
84 | class ReAuthenticate : Promise
85 | {
86 | [Foreign(Language.ObjC)]
87 | public ReAuthenticate(string email, string password)
88 | @{
89 | if (email == NULL && password == NULL)
90 | {
91 | @{ReAuthenticate:Of(_this).Reject(string):Call(@"ReAuthenticate requires that at least one of email or password are provided")};
92 | return;
93 | }
94 |
95 | FIRUser* user = (FIRUser*)@{User.GetCurrent():Call()};
96 |
97 | FIRAuthCredential *credential =
98 | [FIREmailPasswordAuthProvider credentialWithEmail:email password:password];
99 |
100 | [user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {
101 | if (error)
102 | @{ReAuthenticate:Of(_this).Reject(int):Call(error.code)};
103 | else
104 | @{ReAuthenticate:Of(_this).Resolve(string):Call(@"success")};
105 | }];
106 |
107 | @}
108 |
109 | void Reject(string reason)
110 | {
111 | Reject(new Exception(reason));
112 | }
113 |
114 | void Reject(int errorCode)
115 | {
116 | Reject(new Exception(Errors.SignInWithEmailBaseErrorMessage(errorCode)));
117 | }
118 | }
119 |
120 | [Require("Source.Include", "Firebase/Firebase.h")]
121 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
122 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
123 | [Require("Source.Include", "@{Firebase.Authentication.User:Include}")]
124 | extern(iOS)
125 | internal class UpdateEmail : Promise
126 | {
127 | [Foreign(Language.ObjC)]
128 | public UpdateEmail(string email)
129 | @{
130 | [[FIRAuth auth].currentUser updateEmail:email completion:^(NSError *_Nullable error) {
131 | if (error)
132 | @{UpdateEmail:Of(_this).Reject(int):Call(error.code)};
133 | else
134 | @{UpdateEmail:Of(_this).Resolve(string):Call(@"Success")};
135 | }];
136 | @}
137 |
138 | void Reject(string reason)
139 | {
140 | Reject(new Exception(reason));
141 | }
142 |
143 | void Reject(int errorCode)
144 | {
145 | Reject(new Exception(Errors.SignInWithEmailBaseErrorMessage(errorCode)));
146 | }
147 | }
148 |
149 | [Require("Source.Include", "Firebase/Firebase.h")]
150 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
151 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
152 | [Require("Source.Include", "@{Firebase.Authentication.User:Include}")]
153 | extern(iOS)
154 | internal class UpdatePassword : Promise
155 | {
156 | [Foreign(Language.ObjC)]
157 | public UpdatePassword(string password)
158 | @{
159 | [[FIRAuth auth].currentUser updatePassword:password completion:^(NSError *_Nullable error) {
160 | if (error)
161 | @{UpdatePassword:Of(_this).Reject(int):Call(error.code)};
162 | else
163 | @{UpdatePassword:Of(_this).Resolve(string):Call(@"Success")};
164 | }];
165 | @}
166 |
167 | void Reject(string reason)
168 | {
169 | Reject(new Exception(reason));
170 | }
171 |
172 | void Reject(int errorCode)
173 | {
174 | Reject(new Exception(Errors.SignInWithEmailBaseErrorMessage(errorCode)));
175 | }
176 | }
177 |
178 | [Require("Source.Include", "Firebase/Firebase.h")]
179 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
180 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
181 | [Require("Source.Include", "@{Firebase.Authentication.User:Include}")]
182 | extern(iOS)
183 | internal class SendVerificationEmail : Promise
184 | {
185 | [Foreign(Language.ObjC)]
186 | public SendVerificationEmail()
187 | @{
188 | [[FIRAuth auth].currentUser sendEmailVerificationWithCompletion:^(NSError *_Nullable error) {
189 | if (error)
190 | @{SendVerificationEmail:Of(_this).Reject(int):Call(error.code)};
191 | else
192 | @{SendVerificationEmail:Of(_this).Resolve(string):Call(@"Success")};
193 | }];
194 | @}
195 |
196 | void Reject(string reason)
197 | {
198 | Reject(new Exception(reason));
199 | }
200 |
201 | void Reject(int errorCode)
202 | {
203 | Reject(new Exception(Errors.SignInWithEmailBaseErrorMessage(errorCode)));
204 | }
205 | }
206 |
207 | [Require("Source.Include", "Firebase/Firebase.h")]
208 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
209 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
210 | [Require("Source.Include", "@{Firebase.Authentication.User:Include}")]
211 | extern(iOS)
212 | internal class SendPasswordResetEmail : Promise
213 | {
214 | [Foreign(Language.ObjC)]
215 | public SendPasswordResetEmail(string email)
216 | @{
217 | [[FIRAuth auth] sendPasswordResetWithEmail:email completion:^(NSError *_Nullable error) {
218 | if(error)
219 | @{SendPasswordResetEmail:Of(_this).Reject(int):Call(error.code)};
220 | else
221 | @{SendPasswordResetEmail:Of(_this).Resolve(string):Call(@"Success")};
222 | }];
223 | @}
224 |
225 | void Reject(string reason)
226 | {
227 | Reject(new Exception(reason));
228 | }
229 |
230 | void Reject(int errorCode)
231 | {
232 | Reject(new Exception(Errors.SignInWithEmailBaseErrorMessage(errorCode)));
233 | }
234 | }
235 | }
236 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/AndroidImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Facebook
14 | {
15 |
16 | [ForeignInclude(Language.Java,
17 | "com.facebook.AccessToken",
18 | "com.facebook.CallbackManager",
19 | "com.facebook.FacebookCallback",
20 | "com.facebook.FacebookException",
21 | "com.facebook.FacebookSdk",
22 | "com.facebook.login.LoginManager",
23 | "com.facebook.login.LoginResult",
24 | "com.facebook.login.widget.LoginButton",
25 | "com.google.android.gms.tasks.OnCompleteListener",
26 | "com.google.android.gms.tasks.Task",
27 | "com.google.firebase.auth.AuthCredential",
28 | "com.google.firebase.auth.AuthResult",
29 | "com.google.firebase.auth.FacebookAuthProvider",
30 | "com.google.firebase.auth.FirebaseAuth",
31 | "com.google.firebase.auth.FirebaseUser")]
32 | extern(android)
33 | class ReAuthenticate : Promise
34 | {
35 | static ReAuthenticate()
36 | {
37 | FacebookService.Init();
38 | }
39 |
40 | [Foreign(Language.Java)]
41 | public ReAuthenticate()
42 | @{
43 | final FirebaseUser user = (FirebaseUser)@{Firebase.Authentication.User.GetCurrent():Call()};
44 | AccessToken token = AccessToken.getCurrentAccessToken();
45 |
46 | AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
47 | @{Firebase.Authentication.Facebook.JS.FacebookModule.Auth(string):Call(token.getToken())};
48 | FirebaseAuth.getInstance().signInWithCredential(credential)
49 | .addOnCompleteListener(com.fuse.Activity.getRootActivity(), new OnCompleteListener() {
50 | public void onComplete(Task task) {
51 | if (!task.isSuccessful())
52 | @{ReAuthenticate:Of(_this).Resolve(string):Call("success")};
53 | else
54 | @{ReAuthenticate:Of(_this).Reject(string):Call("failed reauthentication")};
55 | }});
56 | @}
57 |
58 | void Reject(string reason) { Reject(new Exception(reason)); }
59 | }
60 |
61 | [Require("Gradle.Dependency.Compile", "com.facebook.android:facebook-android-sdk:4.16.+")]
62 | [Require("Android.ResStrings.Declaration", "@(Project.Facebook.AppID)")]
63 | [Require("AndroidManifest.ApplicationElement", "")]
64 | [ForeignInclude(Language.Java,
65 | "com.facebook.AccessToken",
66 | "com.facebook.CallbackManager",
67 | "com.facebook.FacebookCallback",
68 | "com.facebook.FacebookException",
69 | "com.facebook.FacebookSdk",
70 | "com.facebook.login.LoginManager",
71 | "com.facebook.login.LoginResult",
72 | "com.facebook.login.widget.LoginButton",
73 | "com.google.android.gms.tasks.OnCompleteListener",
74 | "com.google.android.gms.tasks.Task",
75 | "com.google.firebase.auth.AuthCredential",
76 | "com.google.firebase.auth.AuthResult",
77 | "com.google.firebase.auth.FacebookAuthProvider",
78 | "com.google.firebase.auth.FirebaseAuth",
79 | "com.google.firebase.auth.FirebaseUser",
80 | "android.os.Handler")]
81 | extern(android)
82 | public class AndroidFacebookButton : LeafView
83 | {
84 | static AndroidFacebookButton()
85 | {
86 | FacebookService.Init();
87 | }
88 |
89 | public AndroidFacebookButton() : base(Create())
90 | {
91 | EncueAutoSignIn();
92 | }
93 |
94 | [Foreign(Language.Java)]
95 | void EncueAutoSignIn()
96 | @{
97 | // if the button has retained credentials use them to log in
98 | // at startup. The delay is as firebase is known to pull these
99 | // detail asyncronously so as not to block the ui thread.
100 | // This wait is cludgy but was recommended on a StackOverflow
101 | // thread. cest la vie
102 | final Handler handler = new Handler();
103 | handler.postDelayed(new Runnable() {
104 | public void run() {
105 | AccessToken token = AccessToken.getCurrentAccessToken();
106 | if (token!=null)
107 | {
108 | @{OnAuth(Java.Object):Call(token)};
109 | }
110 | }}, 500);
111 | @}
112 |
113 | [Foreign(Language.Java)]
114 | static Java.Object Create()
115 | @{
116 | LoginButton loginButton = new LoginButton(com.fuse.Activity.getRootActivity());
117 | loginButton.setReadPermissions("email", "public_profile");
118 | loginButton.registerCallback(
119 | (CallbackManager)@{FacebookService.CallbackManager},
120 | new FacebookCallback() {
121 | public void onSuccess(LoginResult loginResult) {
122 | @{OnAuth(Java.Object):Call(loginResult.getAccessToken())};
123 | }
124 |
125 | public void onCancel() {
126 | @{OnFailure(string):Call("Facebook Auth Stage Cancelled")};
127 | }
128 |
129 | public void onError(FacebookException error) {
130 | String reason = "Facebook Auth Stage Errored (" + error.getClass().getName() + "):\n" + error.getMessage();
131 | @{OnFailure(string):Call(reason)};
132 | }
133 | });
134 | return loginButton;
135 | @}
136 |
137 | [Foreign(Language.Java)]
138 | static void OnAuth(Java.Object loginToken)
139 | @{
140 | final AccessToken token = (AccessToken)loginToken;
141 | AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
142 | @{Firebase.Authentication.Facebook.JS.FacebookModule.Auth(string):Call(token.getToken())};
143 | FirebaseAuth.getInstance().signInWithCredential(credential)
144 | .addOnCompleteListener(com.fuse.Activity.getRootActivity(), new OnCompleteListener() {
145 | public void onComplete(Task task) {
146 | if (task.isSuccessful())
147 | @{OnSuccess(string):Call("Success")};
148 | else
149 | @{OnFailure(string):Call("Authentication against Firebase failed")};
150 | }});
151 | @}
152 |
153 | static void OnSuccess(string message)
154 | {
155 | AuthService.AnnounceSignIn(AuthProviderName.Facebook);
156 | }
157 |
158 | static void OnFailure(string reason)
159 | {
160 | AuthService.SignalError(-1, reason);
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/AndroidImpl.uxl:
--------------------------------------------------------------------------------
1 |
2 |
7 | ]]>
8 |
9 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/Authentication.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Facebook
14 | {
15 | [ForeignInclude(Language.Java, "com.facebook.FacebookSdk", "com.facebook.CallbackManager", "com.facebook.login.LoginManager")]
16 | [extern(iOS) Require("Cocoapods.Podfile.Target", "pod 'FBSDKCoreKit'")]
17 | [extern(iOS) Require("Cocoapods.Podfile.Target", "pod 'FBSDKShareKit'")]
18 | [extern(iOS) Require("Cocoapods.Podfile.Target", "pod 'FBSDKLoginKit'")]
19 | [extern(iOS) Require("AppDelegate.SourceFile.Declaration", "#include ")]
20 | [extern(iOS) Require("Source.Include", "Firebase/Firebase.h")]
21 | [extern(iOS) Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
22 | [extern(iOS) Require("Source.Include", "FBSDKCoreKit/FBSDKCoreKit.h")]
23 | [extern(iOS) Require("Source.Include", "FBSDKLoginKit/FBSDKLoginKit.h")]
24 | public class FacebookService : Firebase.Authentication.AuthProvider
25 | {
26 | static bool _initd = false;
27 | extern(android) internal static Java.Object CallbackManager;
28 | extern(iOS) internal static ObjC.Object LoginManager;
29 |
30 | public override AuthProviderName Name { get { return AuthProviderName.Facebook; } }
31 |
32 | internal static void Init()
33 | {
34 | if (_initd) return;
35 | var fs = new FacebookService();
36 | Firebase.Authentication.AuthService.RegisterAuthProvider(fs);
37 | _initd = true;
38 | }
39 |
40 | extern(!mobile)
41 | public override void Start() {}
42 |
43 | extern(android)
44 | public override void Start()
45 | {
46 | Android.ActivityUtils.Results += ForwardActivityResults;
47 | StartGoogle();
48 | }
49 |
50 | [Foreign(Language.Java)]
51 | extern(android)
52 | public void StartGoogle()
53 | @{
54 | FacebookSdk.sdkInitialize(com.fuse.Activity.getRootActivity());
55 | @{CallbackManager:Set(CallbackManager.Factory.create())};
56 | @}
57 |
58 | [Foreign(Language.ObjC)]
59 | extern(iOS)
60 | public override void Start()
61 | @{
62 | FBSDKLoginManager* lm = [[FBSDKLoginManager alloc] init];
63 | @{LoginManager:Set(lm)};
64 | @}
65 |
66 | public override void SignOut()
67 | {
68 | if defined(mobile)
69 | SignOutInner();
70 | }
71 |
72 | [Foreign(Language.Java)]
73 | extern(android)
74 | public void SignOutInner()
75 | @{
76 | LoginManager lm = LoginManager.getInstance();
77 | if (lm!=null)
78 | lm.logOut();
79 | @}
80 |
81 | [Foreign(Language.ObjC)]
82 | extern(iOS)
83 | public void SignOutInner()
84 | @{
85 | [@{LoginManager:Get()} logOut];
86 | @}
87 |
88 | public override Promise ReAuthenticate(string ignored0, string ignored1)
89 | {
90 | return new ReAuthenticate();
91 | }
92 |
93 | [Foreign(Language.Java)]
94 | extern(android)
95 | void ForwardActivityResults(int requestCode, int resultCode, Java.Object data)
96 | @{
97 | ((CallbackManager)@{CallbackManager}).onActivityResult(requestCode, resultCode, (android.content.Intent)data);
98 | @}
99 |
100 | [Foreign(Language.ObjC)]
101 | extern(iOS)
102 | static void LogForeground()
103 | @{
104 | [FBSDKAppEvents activateApp];
105 | @}
106 | }
107 |
108 | extern(!mobile)
109 | class ReAuthenticate : Promise
110 | {
111 | public void Reject(string reason) { }
112 | public void Resolve() { }
113 | }
114 |
115 | public class FacebookButton : Panel
116 | {
117 | protected override IView CreateNativeView()
118 | {
119 | if defined(Android)
120 | {
121 | return new AndroidFacebookButton();
122 | }
123 | else if defined(iOS)
124 | {
125 | return new iOSFacebookButton();
126 | }
127 | else
128 | {
129 | return base.CreateNativeView();
130 | }
131 | }
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/FacebookAuthentication.uno:
--------------------------------------------------------------------------------
1 | using Fuse;
2 | using Fuse.Platform;
3 | using Uno;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Firebase.Authentication;
6 |
7 |
8 | namespace Firebase.Authentication.Facebook.JS
9 | {
10 |
11 | [extern(Android) ForeignInclude(Language.Java,
12 | "com.fuse.Activity",
13 | "android.content.Intent",
14 | "com.facebook.*",
15 | "com.facebook.login.*",
16 | "com.facebook.appevents.AppEventsLogger",
17 | "com.google.android.gms.tasks.OnCompleteListener",
18 | "com.google.android.gms.tasks.Task",
19 | "com.google.firebase.auth.*")]
20 |
21 | [extern(iOS) Require("Cocoapods.Podfile.Target", "pod 'FBSDKCoreKit'")]
22 | [extern(iOS) Require("Cocoapods.Podfile.Target", "pod 'FBSDKShareKit'")]
23 | [extern(iOS) Require("Cocoapods.Podfile.Target", "pod 'FBSDKLoginKit'")]
24 | [extern(iOS) Require("AppDelegate.SourceFile.Declaration", "#include ")]
25 | [extern(iOS) Require("Source.Include", "Firebase/Firebase.h")]
26 | [extern(iOS) Require("Source.Include", "Firebase/Firebase.h")]
27 | [extern(iOS) Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
28 | [extern(iOS) Require("Source.Include", "FBSDKCoreKit/FBSDKCoreKit.h")]
29 | [extern(iOS) Require("Source.Include", "FBSDKLoginKit/FBSDKLoginKit.h")]
30 | [extern(iOS) Require("Source.Include", "@{Firebase.Authentication.Facebook.JS.FacebookModule:Include}")]
31 | [extern(iOS) Require("Source.Include", "@{FacebookService:Include}")]
32 |
33 | public class FacebookAuthentication
34 | {
35 |
36 | public FacebookAuthentication()
37 | {
38 |
39 | }
40 |
41 | [Foreign(Language.ObjC)]
42 | public extern(iOS) void Login()
43 | @{
44 | FBSDKLoginManager* login = [[FBSDKLoginManager alloc] init];
45 | [login
46 | logInWithReadPermissions: @[@"public_profile"]
47 | fromViewController: [[[UIApplication sharedApplication] keyWindow] rootViewController]
48 | handler: ^(FBSDKLoginManagerLoginResult* result, NSError* error)
49 | {
50 | if (error)
51 | {
52 | NSString * message = @"Facebook SignIn Failed. Error code: ";
53 | NSString *errorMessage = [NSString stringWithFormat:@"%@ %ld", message, error.code];
54 | @{OnFailure(string):Call(errorMessage)};
55 | @{Firebase.Authentication.Facebook.JS.FacebookModule.OnFailed(string):Call(errorMessage)};
56 | return;
57 | }
58 | if (result.isCancelled)
59 | {
60 | NSString *error = @"Facebook Auth Stage Cancelled";
61 | @{OnFailure(string):Call(error)};
62 | @{Firebase.Authentication.Facebook.JS.FacebookModule.OnFailed(string):Call(error)};
63 | return;
64 | }
65 | @{OnAuth(ObjC.Object):Call(result)};
66 | }
67 | ];
68 | @}
69 |
70 | extern(Android) Java.Object _callbackManager;
71 | [Foreign(Language.Java)]
72 | public extern(Android) void Login()
73 | @{
74 | FacebookSdk.sdkInitialize(Activity.getRootActivity());
75 | final CallbackManager callbackManager = CallbackManager.Factory.create();
76 | @{FacebookAuthentication:Of(_this)._callbackManager:Set(callbackManager)};
77 | Activity.subscribeToResults(new Activity.ResultListener() {
78 | @Override
79 | public boolean onResult(int requestCode, int resultCode, Intent data) {
80 | return callbackManager.onActivityResult(requestCode, resultCode, data);
81 | }
82 | });
83 | CallbackManager callbackManagerFrom = (CallbackManager)@{FacebookAuthentication:Of(_this)._callbackManager:Get()};
84 | LoginManager.getInstance().registerCallback(callbackManagerFrom,
85 | new FacebookCallback()
86 | {
87 | public void onSuccess(LoginResult loginResult) {
88 | @{OnAuth(Java.Object):Call(loginResult.getAccessToken())};
89 | }
90 |
91 | public void onCancel() {
92 | @{OnFailure(string):Call("Facebook Auth Stage Cancelled")};
93 | @{Firebase.Authentication.Facebook.JS.FacebookModule.OnFailed(string):Call("Facebook Auth Stage Cancelled")};
94 | }
95 |
96 | public void onError(FacebookException error) {
97 | String reason = "Facebook Auth Stage Errored (" + error.getClass().getName() + "):\n" + error.getMessage();
98 | @{OnFailure(string):Call(reason)};
99 | @{Firebase.Authentication.Facebook.JS.FacebookModule.OnFailed(string):Call(reason)};
100 | }
101 | }
102 | );
103 | LoginManager.getInstance().logInWithReadPermissions(Activity.getRootActivity(), java.util.Arrays.asList("public_profile"));
104 | @}
105 |
106 | extern(Mobile)
107 | static void OnSuccess(string message)
108 | {
109 | AuthService.AnnounceSignIn(AuthProviderName.Facebook);
110 | }
111 |
112 | extern(Mobile)
113 | static void OnFailure(string reason)
114 | {
115 | AuthService.SignalError(-1, reason);
116 | }
117 |
118 | [Foreign(Language.Java)]
119 | static extern(Android) void OnAuth(Java.Object result)
120 | @{
121 | final AccessToken token = (AccessToken)result;
122 | AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
123 | @{Firebase.Authentication.Facebook.JS.FacebookModule.Auth(string):Call(token.getToken())};
124 | FirebaseAuth.getInstance().signInWithCredential(credential)
125 | .addOnCompleteListener(com.fuse.Activity.getRootActivity(), new OnCompleteListener() {
126 | public void onComplete(Task task) {
127 | if (task.isSuccessful())
128 | @{OnSuccess(string):Call("Success")};
129 | else
130 | @{OnFailure(string):Call("Authentication against Firebase failed")};
131 | }});
132 | @}
133 |
134 | [Foreign(Language.ObjC)]
135 | static extern(iOS) void OnAuth(ObjC.Object result)
136 | @{
137 | FBSDKLoginManagerLoginResult *accessToken = (FBSDKLoginManagerLoginResult *)result;
138 | NSString *tokenStr = accessToken.token.tokenString;
139 |
140 | if (tokenStr==NULL)
141 | {
142 | @{OnFailure(string):Call(@"Authentication against Firebase failed")};
143 | return;
144 | }
145 |
146 | @{Firebase.Authentication.Facebook.JS.FacebookModule.Auth(string):Call(tokenStr)};
147 | FIRAuthCredential* credential = [FIRFacebookAuthProvider credentialWithAccessToken:tokenStr];
148 |
149 | // auth againsts firebase
150 | [[FIRAuth auth] signInWithCredential:credential
151 | completion:^(FIRUser* fuser, NSError* ferror) {
152 | if (ferror)
153 | @{OnFailure(string):Call(@"Authentication against Firebase failed")};
154 | else
155 | @{OnSuccess(string):Call(@"success")};
156 | }];
157 | @}
158 |
159 | }
160 | }
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/Firebase.Authentication.Facebook.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase/Firebase.unoproj",
4 | "../Firebase.Authentication/Firebase.Authentication.unoproj"
5 | ],
6 | "Packages": [
7 | "Fuse",
8 | "FuseJS",
9 | "Fuse.Scripting",
10 | "Android.ActivityUtils"
11 | ],
12 | "Android": {
13 | "SDK": {
14 | "MinVersion": "15"
15 | }
16 | },
17 | "Includes": [
18 | "*",
19 | "iOSFacebookCallbacks.h:ObjCHeader:iOS",
20 | "iOSFacebookCallbacks.mm:ObjCSource:iOS"
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Threading;
4 | using Uno.Text;
5 | using Uno.Platform;
6 | using Uno.Compiler.ExportTargetInterop;
7 | using Uno.Collections;
8 | using Fuse;
9 | using Fuse.Scripting;
10 | using Fuse.Reactive;
11 |
12 | namespace Firebase.Authentication.Facebook.JS
13 | {
14 | /**
15 | */
16 | [UXGlobalModule]
17 | public sealed class FacebookModule : NativeModule
18 | {
19 | static readonly FacebookModule _instance;
20 | static NativeEvent _onAuth, _onError;
21 | readonly FacebookAuthentication _facebookAuthentication;
22 |
23 | public FacebookModule()
24 | {
25 | if(_instance != null) return;
26 | Uno.UX.Resource.SetGlobalKey(_instance = this, "Firebase/Authentication/Facebook");
27 | _facebookAuthentication = new FacebookAuthentication();
28 | _onAuth = new NativeEvent("onAuth");
29 | AddMember(_onAuth);
30 | _onError = new NativeEvent("onFailed");
31 | AddMember(_onError);
32 | AddMember(new NativeFunction("doFacebookLogin", (NativeCallback)DoFacebookLogin));
33 | Firebase.Authentication.Facebook.FacebookService.Init();
34 | }
35 |
36 | static void Auth(string token)
37 | {
38 | var worker = _onAuth.Context == null ? null : _onAuth.Context.ThreadWorker;
39 | _onAuth.RaiseAsync(worker, token);
40 | }
41 |
42 | static void OnFailed(string err)
43 | {
44 | var worker = _onError.Context == null ? null : _onError.Context.ThreadWorker;
45 | _onError.RaiseAsync(worker, err);
46 | }
47 |
48 | object DoFacebookLogin(Context context, object[] args)
49 | {
50 | if defined(iOS || Android)
51 | {
52 | _facebookAuthentication.Login();
53 | }
54 | else{ }
55 | return null;
56 | }
57 | }
58 |
59 | }
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/iOSFacebookCallbacks.h:
--------------------------------------------------------------------------------
1 | #import
2 | #include
3 |
4 | @interface FireFacebookCallbacks : NSObject
5 | @end
6 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/iOSFacebookCallbacks.mm:
--------------------------------------------------------------------------------
1 | #import
2 | #include
3 | #include <@{Firebase.Authentication.Facebook.iOSFacebookButton:Include}>
4 | #include <@{ObjC.Object:Include}>
5 |
6 | @implementation FireFacebookCallbacks : NSObject
7 |
8 | - (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {
9 | @{Firebase.Authentication.Facebook.iOSFacebookButton.OnFBAuth(ObjC.Object):Call(error)};
10 | }
11 | - (BOOL) loginButtonWillLogin:(FBSDKLoginButton *)loginButton {
12 | return YES;
13 | }
14 | - (void) loginButtonDidLogOut:(FBSDKLoginButton *)loginButton {
15 | }
16 |
17 | @end
18 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/iOSImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.iOS;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Facebook
14 | {
15 | [Require("Source.Include", "Firebase/Firebase.h")]
16 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
17 | [Require("Source.Include", "FBSDKCoreKit/FBSDKCoreKit.h")]
18 | [Require("Source.Include", "FBSDKLoginKit/FBSDKLoginKit.h")]
19 | [Require("Source.Include", "@{FacebookService:Include}")]
20 | extern(iOS)
21 | class ReAuthenticate : Promise
22 | {
23 | [Foreign(Language.ObjC)]
24 | public ReAuthenticate()
25 | @{
26 | FIRUser *user = [FIRAuth auth].currentUser;
27 |
28 | FIRAuthCredential* credential =
29 | [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
30 |
31 | [user reauthenticateWithCredential:credential completion:^(NSError* _Nullable error) {
32 | if (error)
33 | @{ReAuthenticate:Of(_this).Reject(int):Call(error.code)};
34 | else
35 | @{ReAuthenticate:Of(_this).Resolve(string):Call(@"success")};
36 | }];
37 | @}
38 |
39 | void Reject(int errorCode)
40 | {
41 | var reason = Errors.ReauthenticateWithCredentialBaseErrorMessage(errorCode);
42 | Reject(new Exception(reason));
43 | }
44 | }
45 |
46 | [Require("Source.Include", "Firebase/Firebase.h")]
47 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
48 | [Require("Source.Include", "FBSDKCoreKit/FBSDKCoreKit.h")]
49 | [Require("Source.Include", "FBSDKLoginKit/FBSDKLoginKit.h")]
50 | [Require("Source.Include", "@{Firebase.Authentication.Facebook.JS.FacebookModule:Include}")]
51 | [Require("Source.Include", "@{FacebookService:Include}")]
52 | [Require("Source.Include", "iOSFacebookCallbacks.h")]
53 |
54 | extern(iOS)
55 | public class iOSFacebookButton : LeafView
56 | {
57 | static internal ObjC.Object _iosDelegate;
58 | static bool _initd = false;
59 |
60 | static iOSFacebookButton()
61 | {
62 | FacebookService.Init();
63 | }
64 |
65 | public iOSFacebookButton() : base(Create()) { }
66 |
67 | [Foreign(Language.ObjC)]
68 | static ObjC.Object Create()
69 | @{
70 | FireFacebookCallbacks* fireCB;
71 | if (!@{_initd:Get()})
72 | {
73 | fireCB = [[FireFacebookCallbacks alloc] init];
74 | @{_iosDelegate:Set(fireCB)};
75 | @{_initd:Set(true)};
76 | } else {
77 | fireCB = @{_iosDelegate:Get()};
78 | }
79 |
80 | FBSDKLoginButton* loginButton = [[FBSDKLoginButton alloc] init];
81 | loginButton.delegate = (id)fireCB;
82 | loginButton.readPermissions = @[@"public_profile", @"email", @"user_friends"];
83 |
84 | if ([FBSDKAccessToken currentAccessToken].tokenString != nil)
85 | @{OnFBAuth(ObjC.Object):Call(nil)};
86 |
87 | return loginButton;
88 | @}
89 |
90 | [Foreign(Language.ObjC)]
91 | static void OnFBAuth(ObjC.Object err)
92 | @{
93 | NSError* error = (NSError*)err;
94 |
95 | if (error == nil) {
96 | NSString* tokenStr = [FBSDKAccessToken currentAccessToken].tokenString;
97 |
98 | if (tokenStr==NULL)
99 | {
100 | @{OnAborted():Call()};
101 | return;
102 | }
103 |
104 | @{Firebase.Authentication.Facebook.JS.FacebookModule.Auth(string):Call(tokenStr)};
105 | FIRAuthCredential* credential = [FIRFacebookAuthProvider credentialWithAccessToken:tokenStr];
106 |
107 | // auth againsts firebase
108 | [[FIRAuth auth] signInWithCredential:credential
109 | completion:^(FIRUser* fuser, NSError* ferror) {
110 | if (ferror)
111 | @{OnFirebaseFailure(int):Call(ferror.code)};
112 | else
113 | @{OnSuccess(string):Call(@"success")};
114 |
115 | }];
116 | } else {
117 | @{OnFacebookFailure(int):Call(error.code)};
118 | }
119 | @}
120 |
121 | static void OnSuccess(string message)
122 | {
123 | AuthService.AnnounceSignIn(AuthProviderName.Facebook);
124 | }
125 |
126 | static void OnAborted()
127 | {
128 | var message = "Facebook signin aborted";
129 | AuthService.SignalError(-1, message);
130 | }
131 |
132 | static void OnFacebookFailure(int code)
133 | {
134 | var message = "Facebook SignIn Failed";
135 | AuthService.SignalError(code, message);
136 | }
137 |
138 | static void OnFirebaseFailure(int code)
139 | {
140 | var message = Errors.SignInWithCredentialBaseErrorMessage(code);
141 | AuthService.SignalError(code, message);
142 | }
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Facebook/iOSImpl.uxl:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | FacebookAppID
7 | @(Project.Facebook.AppID)
8 | FacebookDisplayName
9 | @(Project.Facebook.DisplayName || BundleIdentifier)
10 | LSApplicationQueriesSchemes
11 |
12 | fbapi
13 | fb-messenger-api
14 | fbauth2
15 | fbshareextension
16 |
17 | ]]>
18 |
19 |
20 |
23 |
24 |
31 |
32 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/AndroidImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Google
14 | {
15 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.content.Intent",
16 | "com.google.android.gms.auth.api.Auth",
17 | "com.google.android.gms.auth.api.signin.GoogleSignInAccount",
18 | "com.google.android.gms.auth.api.signin.GoogleSignInOptions",
19 | "com.google.android.gms.auth.api.signin.GoogleSignInResult",
20 | "com.google.android.gms.common.ConnectionResult",
21 | "com.google.android.gms.common.api.GoogleApiClient",
22 | "com.google.android.gms.common.api.ResultCallback",
23 | "com.google.android.gms.common.api.Status",
24 | "com.google.android.gms.tasks.OnCompleteListener",
25 | "com.google.android.gms.tasks.Task",
26 | "com.google.firebase.auth.AuthCredential",
27 | "com.google.firebase.auth.AuthResult",
28 | "com.google.firebase.auth.FirebaseAuth",
29 | "com.google.firebase.auth.FirebaseUser",
30 | "com.google.firebase.auth.GoogleAuthProvider")]
31 | extern(android)
32 | class ReAuthenticate : Promise
33 | {
34 | static ReAuthenticate()
35 | {
36 | GoogleService.Init();
37 | }
38 |
39 | public ReAuthenticate()
40 | {
41 | var intent = MakeIntent();
42 | Android.ActivityUtils.StartActivity(intent, onResult);
43 | }
44 |
45 | [Foreign(Language.Java)]
46 | Java.Object MakeIntent()
47 | @{
48 | final GoogleApiClient client = (GoogleApiClient)@{GoogleService._mGoogleApiClient};
49 | return Auth.GoogleSignInApi.getSignInIntent(client);
50 | @}
51 |
52 | [Foreign(Language.Java)]
53 | void onResult(int resultCode, Java.Object intent, object info)
54 | @{
55 | final Intent data = (Intent)intent;
56 | GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
57 | if (!result.isSuccess()) {
58 | @{ReAuthenticate:Of(_this).Reject(string):Call("SignIn Failed: Google re-authentication failed")};
59 | return;
60 | }
61 | // kick off next step
62 | GoogleSignInAccount account = result.getSignInAccount();
63 | AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
64 | @{Firebase.Authentication.Google.JS.GoogleModule.Auth(string,string):Call(account.getIdToken(),null)};
65 | FirebaseAuth.getInstance().signInWithCredential(credential)
66 | .addOnCompleteListener(com.fuse.Activity.getRootActivity(), new OnCompleteListener() {
67 | public void onComplete(Task task) {
68 | if (task.isSuccessful())
69 | @{ReAuthenticate:Of(_this).Resolve(string):Call("success")};
70 | else
71 | @{ReAuthenticate:Of(_this).Reject(string):Call("SignIn Failed: GoogleSignIn re-authentication succeeded however the re-authentication against firebase failed.")};
72 | }});
73 | @}
74 |
75 | void Reject(string reason) { Reject(new Exception(reason)); }
76 | }
77 |
78 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.content.Intent",
79 | "com.google.android.gms.auth.api.Auth",
80 | "com.google.android.gms.auth.api.signin.GoogleSignInAccount",
81 | "com.google.android.gms.auth.api.signin.GoogleSignInOptions",
82 | "com.google.android.gms.auth.api.signin.GoogleSignInResult",
83 | "com.google.android.gms.common.ConnectionResult",
84 | "com.google.android.gms.common.api.GoogleApiClient",
85 | "com.google.android.gms.common.api.ResultCallback",
86 | "com.google.android.gms.common.api.Status",
87 | "com.google.android.gms.tasks.OnCompleteListener",
88 | "com.google.android.gms.tasks.Task",
89 | "com.google.firebase.auth.AuthCredential",
90 | "com.google.firebase.auth.AuthResult",
91 | "com.google.firebase.auth.FirebaseAuth",
92 | "com.google.firebase.auth.FirebaseUser",
93 | "com.google.firebase.auth.GoogleAuthProvider",
94 | "com.google.android.gms.common.SignInButton")]
95 | extern(android) public class AndroidGoogleButton : LeafView
96 | {
97 |
98 | static AndroidGoogleButton()
99 | {
100 | GoogleService.Init();
101 | }
102 |
103 | public AndroidGoogleButton() : base(Create()) { }
104 |
105 |
106 | [Foreign(Language.Java)]
107 | static Java.Object Create()
108 | @{
109 | SignInButton button = new SignInButton(com.fuse.Activity.getRootActivity());
110 | button.setOnClickListener(new android.view.View.OnClickListener() {
111 | public void onClick(android.view.View v) {
112 | @{SignInUser():Call()};
113 | }
114 | });
115 | return button;
116 | @}
117 |
118 | static void SignInUser()
119 | {
120 | var intent = MakeIntent();
121 | Android.ActivityUtils.StartActivity(intent, onResult);
122 | }
123 |
124 | [Foreign(Language.Java)]
125 | static Java.Object MakeIntent()
126 | @{
127 | final GoogleApiClient client = (GoogleApiClient)@{GoogleService._mGoogleApiClient};
128 | return Auth.GoogleSignInApi.getSignInIntent(client);
129 | @}
130 |
131 | [Foreign(Language.Java)]
132 | static void onResult(int resultCode, Java.Object intent, object info)
133 | @{
134 | final Intent data = (Intent)intent;
135 | GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
136 | if (!result.isSuccess()) {
137 | @{OnFailure(string):Call("SignIn Failed: GoogleSignIn failed: " + result.getStatus().getStatusCode())};
138 | return;
139 | }
140 | // kick off next step
141 | GoogleSignInAccount account = result.getSignInAccount();
142 | AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
143 | @{Firebase.Authentication.Google.JS.GoogleModule.Auth(string,string):Call(account.getIdToken(),null)};
144 | FirebaseAuth.getInstance().signInWithCredential(credential)
145 | .addOnCompleteListener(com.fuse.Activity.getRootActivity(), new OnCompleteListener() {
146 | public void onComplete(Task task) {
147 | if (task.isSuccessful())
148 | @{OnSuccess(string):Call("success")};
149 | else
150 | @{OnFailure(string):Call("SignIn Failed: GoogleSignIn succeeded however following authenticate against firebase failed.")};
151 | }});
152 | @}
153 |
154 | static void OnSuccess(string message)
155 | {
156 | AuthService.AnnounceSignIn(AuthProviderName.Google);
157 | }
158 |
159 | static void OnFailure(string reason)
160 | {
161 | AuthService.SignalError(-1, reason);
162 | }
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/Authentication.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 | using Firebase.Authentication;
13 |
14 | namespace Firebase.Authentication.Google
15 | {
16 |
17 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.content.Intent",
18 | "com.google.android.gms.auth.api.Auth",
19 | "com.google.android.gms.auth.api.signin.GoogleSignInAccount",
20 | "com.google.android.gms.auth.api.signin.GoogleSignInOptions",
21 | "com.google.android.gms.auth.api.signin.GoogleSignInResult",
22 | "com.google.android.gms.common.ConnectionResult",
23 | "com.google.android.gms.common.api.GoogleApiClient",
24 | "com.google.android.gms.common.api.ResultCallback",
25 | "com.google.android.gms.common.api.Status",
26 | "com.google.android.gms.tasks.OnCompleteListener",
27 | "com.google.android.gms.tasks.Task",
28 | "com.google.firebase.auth.AuthCredential",
29 | "com.google.firebase.auth.AuthResult",
30 | "com.google.firebase.auth.FirebaseAuth",
31 | "com.google.firebase.auth.FirebaseUser",
32 | "com.google.firebase.auth.GoogleAuthProvider")]
33 | [Require("Gradle.Dependency.Compile", "com.google.firebase:firebase-auth:12.0.1")]
34 | [Require("Gradle.Dependency.Compile", "com.google.android.gms:play-services-auth:12.0.1")]
35 | [Require("Cocoapods.Podfile.Target", "pod 'GoogleSignIn'")]
36 | [Require("AppDelegate.HeaderFile.Declaration", "#include ")]
37 | [Require("AppDelegate.SourceFile.Declaration", "#include ")]
38 | [extern(iOS) Require("Source.Include", "GoogleSignIn/GoogleSignIn.h")]
39 | [extern(iOS) Require("Source.Include", "Firebase/Firebase.h")]
40 | [extern(iOS) Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
41 | [extern(iOS) Require("Source.Include", "iOSCallbacks.h")]
42 | public class GoogleService : Firebase.Authentication.AuthProvider
43 | {
44 | static bool _initd = false;
45 |
46 | extern(mobile) static string _requestID = extern"uString::Ansi(\"@(Project.Google.RequestID:Or(''))\")";
47 |
48 | extern(ios) static internal ObjC.Object _iosDelegate;
49 | extern(android) static internal Java.Object _mGoogleApiClient;
50 | extern(android) static Java.Object _gso;
51 |
52 | public override AuthProviderName Name { get { return AuthProviderName.Google; } }
53 |
54 | internal static void Init()
55 | {
56 | if (_initd) return;
57 | var gs = new GoogleService();
58 | Firebase.Authentication.AuthService.RegisterAuthProvider(gs);
59 | _initd = true;
60 | }
61 |
62 | extern(!mobile)
63 | public override void Start() {}
64 |
65 | extern(android)
66 | public override void Start()
67 | {
68 | _gso = MakeSignInOptions();
69 | _mGoogleApiClient = MakeClient(_gso);
70 | }
71 |
72 | public override void SignOut()
73 | {
74 | if defined(mobile)
75 | SignOutInner();
76 | }
77 |
78 | [Foreign(Language.Java)]
79 | extern(android)
80 | public void SignOutInner()
81 | @{
82 | Auth.GoogleSignInApi.signOut((GoogleApiClient)@{_mGoogleApiClient}).setResultCallback(
83 | new ResultCallback() {
84 | public void onResult(Status status) {
85 | // Left here for future expansion
86 | }});
87 | @}
88 |
89 | [Foreign(Language.ObjC)]
90 | extern(iOS)
91 | public void SignOutInner()
92 | @{
93 | [[GIDSignIn sharedInstance] signOut];
94 | @}
95 |
96 | [Foreign(Language.ObjC)]
97 | extern(iOS)
98 | public override void Start()
99 | @{
100 | FireGoogCallbacks* fireCB = [[FireGoogCallbacks alloc] init];
101 | @{_iosDelegate:Set(fireCB)};
102 | [GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;
103 | [GIDSignIn sharedInstance].delegate = (id)fireCB;
104 | [GIDSignIn sharedInstance].uiDelegate = (id)fireCB;
105 | @}
106 |
107 |
108 | [Foreign(Language.Java)]
109 | extern(android)
110 | static Java.Object MakeSignInOptions()
111 | @{
112 | return new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
113 | .requestIdToken(@{_requestID})
114 | .requestEmail()
115 | .build();
116 | @}
117 |
118 | [Foreign(Language.Java)]
119 | extern(android)
120 | static Java.Object MakeClient(Java.Object gso)
121 | @{
122 | final GoogleSignInOptions signInOptions = (GoogleSignInOptions)gso;
123 |
124 | GoogleApiClient.OnConnectionFailedListener l = new GoogleApiClient.OnConnectionFailedListener() {
125 | public void onConnectionFailed(ConnectionResult connectionResult) {
126 | String m = "An unresolvable error has occurred and Google APIs (including Sign-In) will not be available.";
127 | @{ConnectionFailed(string):Call(m)};
128 | }
129 | };
130 |
131 | return new GoogleApiClient.Builder(com.fuse.Activity.getRootActivity())
132 | .enableAutoManage(com.fuse.Activity.getRootActivity(), l)
133 | .addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions)
134 | .build();
135 | @}
136 |
137 | static void ConnectionFailed(string message)
138 | {
139 | throw new Exception(message);
140 | }
141 |
142 | public override Promise ReAuthenticate(string email, string password)
143 | {
144 | return new ReAuthenticate();
145 | }
146 | }
147 |
148 | extern(!mobile)
149 | class SignInUser : Promise
150 | {
151 | public void Reject(string reason) { }
152 | }
153 |
154 | extern(!mobile)
155 | class ReAuthenticate : Promise
156 | {
157 | public ReAuthenticate() { }
158 | public void Reject(string reason) { }
159 | }
160 |
161 | public class GoogleButton : Panel
162 | {
163 | protected override IView CreateNativeView()
164 | {
165 | if defined(Android)
166 | {
167 | return new AndroidGoogleButton();
168 | }
169 | else if defined(iOS)
170 | {
171 | return new iOSGoogleButton();
172 | }
173 | else
174 | {
175 | return base.CreateNativeView();
176 | }
177 | }
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/Firebase.Authentication.Google.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase/Firebase.unoproj",
4 | "../Firebase.Authentication/Firebase.Authentication.unoproj"
5 | ],
6 | "Packages": [
7 | "Fuse",
8 | "FuseJS",
9 | "Fuse.Scripting",
10 | "Android.ActivityUtils"
11 | ],
12 | "Includes": [
13 | "*",
14 | "iOSCallbacks.h:ObjCHeader:iOS",
15 | "iOSCallbacks.mm:ObjCSource:iOS"
16 | ]
17 | }
18 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Threading;
4 | using Uno.Text;
5 | using Uno.Platform;
6 | using Uno.Compiler.ExportTargetInterop;
7 | using Uno.Collections;
8 | using Fuse;
9 | using Fuse.Scripting;
10 | using Fuse.Reactive;
11 |
12 | namespace Firebase.Authentication.Google.JS
13 | {
14 | /**
15 | */
16 | [UXGlobalModule]
17 | public sealed class GoogleModule : NativeModule
18 | {
19 | static readonly GoogleModule _instance;
20 | static NativeEvent _onAuth;
21 |
22 | public GoogleModule()
23 | {
24 | if(_instance != null) return;
25 | Uno.UX.Resource.SetGlobalKey(_instance = this, "Firebase/Authentication/Google");
26 |
27 | _onAuth = new NativeEvent("onAuth");
28 | AddMember(_onAuth);
29 | Firebase.Authentication.Google.GoogleService.Init();
30 | }
31 |
32 | static void Auth(string idToken, string accessToken)
33 | {
34 | var worker = _onAuth.Context == null ? null : _onAuth.Context.ThreadWorker;
35 | _onAuth.RaiseAsync(worker, idToken, accessToken);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/iOSCallbacks.h:
--------------------------------------------------------------------------------
1 |
2 | #import
3 | #include
4 |
5 | @interface FireGoogCallbacks : NSObject
6 | @end
7 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/iOSCallbacks.mm:
--------------------------------------------------------------------------------
1 |
2 | #import
3 | #include
4 | #include <@{Firebase.Authentication.Google.iOSGoogleButton:Include}>
5 | #include <@{Firebase.Authentication.AuthService:Include}>
6 | #include <@{Firebase.Authentication.Google.JS.GoogleModule:Include}>
7 |
8 | #include
9 |
10 | @implementation FireGoogCallbacks : NSObject
11 |
12 | - (void)signIn:(GIDSignIn *)signIn
13 | didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
14 | if (error == nil) {
15 | GIDAuthentication* authentication = user.authentication;
16 | @{Firebase.Authentication.Google.JS.GoogleModule.Auth(string,string):Call(authentication.idToken,authentication.accessToken)};
17 | }
18 | @{Firebase.Authentication.Google.iOSGoogleButton.Callback(ObjC.Object,ObjC.Object):Call((@{ObjC.Object})user, (@{ObjC.Object})error)};
19 | }
20 |
21 | - (void)signIn:(GIDSignIn *)signIn
22 | didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error {
23 | @{Firebase.Authentication.AuthService.SignedOut():Call()};
24 | }
25 |
26 |
27 | - (void) signIn:(GIDSignIn *)signIn presentViewController:(UIViewController *)viewController {
28 | // If implemented, this method will be invoked when sign in needs to
29 | // display a view controller. The view controller should be displayed
30 | // modally (via UIViewController's presentViewController method, and
31 | // not pushed unto a navigation controller's stack.
32 | UIViewController* vc = (UIViewController*)[UIApplication sharedApplication].delegate;
33 | [vc presentViewController:viewController animated:YES completion:nil];
34 | }
35 |
36 | - (void) signIn:(GIDSignIn *)signIn dismissViewController:(UIViewController *)viewController {
37 | // If implemented, this method will be invoked when sign in needs to
38 | // dismiss a view controller. Typically, this should be implemented
39 | // by calling dismissViewController on the passed view controller.
40 | UIViewController* vc = (UIViewController*)[UIApplication sharedApplication].delegate;
41 | [vc dismissViewControllerAnimated:YES completion: NULL ];
42 | }
43 |
44 | @end
45 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/iOSDelegateMethods.uxl:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
11 |
12 |
17 |
18 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication.Google/iOSImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.iOS;
10 | using Uno.Threading;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.Google
14 | {
15 | [Require("AppDelegate.SourceFile.Declaration", "#include ")]
16 | [Require("Source.Include", "GoogleSignIn/GoogleSignIn.h")]
17 | [Require("Source.Include", "Firebase/Firebase.h")]
18 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
19 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Auth'")]
20 | [Require("Source.Include", "@{Firebase.Authentication.User:Include}")]
21 | [Require("Source.Include", "@{Firebase.Authentication.Google.iOSGoogleButton:Include}")]
22 | extern(iOS)
23 | class ReAuthenticate : Promise
24 | {
25 | [Foreign(Language.ObjC)]
26 | public ReAuthenticate()
27 | @{
28 | FIRUser *user = [FIRAuth auth].currentUser;
29 | GIDGoogleUser* guser = [GIDSignIn sharedInstance].currentUser;
30 | GIDAuthentication* authentication = guser.authentication;
31 |
32 | FIRAuthCredential* credential =
33 | [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
34 | accessToken:authentication.accessToken];
35 |
36 | [user reauthenticateWithCredential:credential completion:^(NSError* _Nullable error) {
37 | if (error)
38 | @{ReAuthenticate:Of(_this).Reject(int):Call(error.code)};
39 | else
40 | @{ReAuthenticate:Of(_this).Resolve(string):Call(@"success")};
41 | }];
42 | @}
43 |
44 | void Reject(int errorCode)
45 | {
46 | var reason = Errors.ReauthenticateWithCredentialBaseErrorMessage(errorCode);
47 | Reject(new Exception(reason));
48 | }
49 | }
50 |
51 | [Require("AppDelegate.SourceFile.Declaration", "#include ")]
52 | [Require("AppDelegate.SourceFile.Declaration", "#include <@{Firebase.Authentication.Google.iOSGoogleButton:Include}>")]
53 | [Require("Source.Include", "GoogleSignIn/GoogleSignIn.h")]
54 | [Require("Source.Include", "Firebase/Firebase.h")]
55 | [Require("Source.Include", "FirebaseAuth/FirebaseAuth.h")]
56 | extern(iOS) public class iOSGoogleButton : LeafView
57 | {
58 | public iOSGoogleButton() : base(Create()) { }
59 |
60 |
61 | [Foreign(Language.ObjC)]
62 | [Require("Entity","Firebase.Authentication.Google.JS.GoogleModule.Auth(string,string)")]
63 |
64 | static ObjC.Object Create()
65 | @{
66 | [[GIDSignIn sharedInstance] signInSilently];
67 | return [[GIDSignInButton alloc] init];
68 | @}
69 |
70 | [Foreign(Language.ObjC)]
71 | static void Callback(ObjC.Object usr, ObjC.Object err)
72 | @{
73 | GIDGoogleUser* user = (GIDGoogleUser*)usr;
74 | NSError* error = (NSError*)err;
75 |
76 | if (error == nil) {
77 | GIDAuthentication* authentication = user.authentication;
78 |
79 | FIRAuthCredential* credential =
80 | [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
81 | accessToken:authentication.accessToken];
82 |
83 | // auth againsts firebase
84 | [[FIRAuth auth] signInWithCredential:credential
85 | completion:^(FIRUser* fuser, NSError* ferror) {
86 | if (ferror)
87 | @{OnFirebaseFailure(int):Call(ferror.code)};
88 | else
89 | @{OnSuccess(string):Call(@"success")};
90 |
91 | }];
92 | } else {
93 | @{OnGoogleFailure(int):Call(error.code)};
94 | }
95 | @}
96 |
97 | static void OnSuccess(string message)
98 | {
99 | AuthService.AnnounceSignIn(AuthProviderName.Google);
100 | }
101 |
102 | static void OnGoogleFailure(int code)
103 | {
104 | var message = "Google SignIn Failed";
105 | AuthService.SignalError(code, message);
106 | }
107 |
108 | static void OnFirebaseFailure(int code)
109 | {
110 | var message = Errors.SignInWithCredentialBaseErrorMessage(code);
111 | AuthService.SignalError(code, message);
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication/AndroidImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 |
12 | namespace Firebase.Authentication
13 | {
14 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.net.Uri",
15 | "com.google.android.gms.tasks.OnCompleteListener",
16 | "com.google.android.gms.tasks.Task",
17 | "com.google.firebase.auth.AuthResult",
18 | "com.google.firebase.auth.FirebaseAuth",
19 | "com.google.firebase.auth.FirebaseUser",
20 | "com.google.firebase.auth.UserInfo",
21 | "org.json.JSONArray",
22 | "org.json.JSONObject",
23 | "org.json.JSONException")]
24 | extern(android)
25 | internal static class User
26 | {
27 | [Foreign(Language.Java)]
28 | internal static Java.Object GetCurrent()
29 | @{
30 | return FirebaseAuth.getInstance().getCurrentUser();
31 | @}
32 |
33 | [Foreign(Language.Java)]
34 | internal static string GetUid(Java.Object obj)
35 | @{
36 | FirebaseUser user = (FirebaseUser)obj;
37 | String r = user.getUid();
38 | return r;
39 | @}
40 |
41 | [Foreign(Language.Java)]
42 | internal static string GetName(Java.Object obj)
43 | @{
44 | FirebaseUser user = (FirebaseUser)obj;
45 | String r = user.getDisplayName();
46 | return r;
47 | @}
48 |
49 | [Foreign(Language.Java)]
50 | internal static string GetEmail(Java.Object obj)
51 | @{
52 | FirebaseUser user = (FirebaseUser)obj;
53 | String r = user.getEmail();
54 | return r;
55 | @}
56 |
57 | [Foreign(Language.Java)]
58 | internal static string GetPhotoUrl(Java.Object obj)
59 | @{
60 | FirebaseUser user = (FirebaseUser)obj;
61 | Uri uri = user.getPhotoUrl();
62 | return (uri==null) ? null : uri.toString();
63 | @}
64 |
65 | [Foreign(Language.Java)]
66 | internal static string GetProviderData(Java.Object obj)
67 | @{
68 | FirebaseUser user = (FirebaseUser)obj;
69 | JSONArray providers = new JSONArray();
70 | for (UserInfo profile : user.getProviderData()) {
71 | JSONObject provider = new JSONObject();
72 | try {
73 | provider.put("getProviderId", profile.getProviderId());
74 | provider.put("getDisplayName", profile.getDisplayName());
75 | provider.put("getEmail", profile.getEmail());
76 | provider.put("getUid", profile.getUid());
77 | providers.put(provider);
78 | } catch (JSONException e) {
79 | //
80 | }
81 | }
82 | return providers.toString();
83 | @}
84 |
85 | [Foreign(Language.Java)]
86 | internal static bool IsEmailVerified(Java.Object obj)
87 | @{
88 | FirebaseUser user = (FirebaseUser)obj;
89 | return user.isEmailVerified();
90 | @}
91 | }
92 |
93 |
94 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.net.Uri",
95 | "com.google.android.gms.tasks.OnCompleteListener",
96 | "com.google.android.gms.tasks.Task",
97 | "com.google.firebase.auth.AuthResult",
98 | "com.google.firebase.auth.GetTokenResult",
99 | "com.google.firebase.auth.FirebaseAuth",
100 | "com.google.firebase.auth.FirebaseUser",
101 | "com.google.firebase.auth.UserProfileChangeRequest")]
102 | extern(android)
103 | internal class GetToken : Promise
104 | {
105 | [Foreign(Language.Java)]
106 | public GetToken()
107 | @{
108 | final FirebaseUser user = (FirebaseUser)@{User.GetCurrent():Call()};
109 | user.getToken(true).addOnCompleteListener(new OnCompleteListener() {
110 | public void onComplete(Task task)
111 | {
112 | if (task.isSuccessful()) {
113 | String token = task.getResult().getToken();
114 | @{UpdateProfile:Of(_this).Resolve(string):Call(token)};
115 | } else {
116 | @{UpdateProfile:Of(_this).Reject(string):Call("failed getting token for user")};
117 | }
118 | }
119 | });
120 | @}
121 |
122 | void Reject(string reason) { Reject(new Exception(reason)); }
123 | }
124 |
125 |
126 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.net.Uri",
127 | "com.google.android.gms.tasks.OnCompleteListener",
128 | "com.google.android.gms.tasks.Task",
129 | "com.google.firebase.auth.AuthResult",
130 | "com.google.firebase.auth.FirebaseAuth",
131 | "com.google.firebase.auth.FirebaseUser",
132 | "com.google.firebase.auth.UserProfileChangeRequest")]
133 | extern(android)
134 | internal class UpdateProfile : Promise
135 | {
136 | [Foreign(Language.Java)]
137 | public UpdateProfile(string displayName, string photoUri)
138 | @{
139 | if (displayName == null && photoUri == null)
140 | {
141 | @{UpdateProfile:Of(_this).Reject(string):Call("UpdateProfile requires that at least one of displayName or photoUri are provided")};
142 | return;
143 | }
144 |
145 | final FirebaseUser user = (FirebaseUser)@{User.GetCurrent():Call()};
146 |
147 | UserProfileChangeRequest.Builder builder = new UserProfileChangeRequest.Builder();
148 | if (displayName!=null)
149 | builder.setDisplayName(displayName);
150 | if (photoUri!=null)
151 | builder.setPhotoUri(Uri.parse(photoUri));
152 | UserProfileChangeRequest profileUpdates = builder.build();
153 |
154 | user.updateProfile(profileUpdates)
155 | .addOnCompleteListener(new OnCompleteListener() {
156 | public void onComplete(Task task)
157 | {
158 | if (task.isSuccessful())
159 | @{UpdateProfile:Of(_this).Resolve(string):Call("success")};
160 | else
161 | @{UpdateProfile:Of(_this).Reject(string):Call("Firebase failed to update profile")};
162 | }
163 | });
164 | @}
165 | void Reject(string reason) { Reject(new Exception(reason)); }
166 | }
167 |
168 |
169 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.net.Uri",
170 | "com.google.android.gms.tasks.OnCompleteListener",
171 | "com.google.android.gms.tasks.Task",
172 | "com.google.firebase.auth.AuthResult",
173 | "com.google.firebase.auth.FirebaseAuth",
174 | "com.google.firebase.auth.FirebaseUser")]
175 | extern(android)
176 | internal class UpdateEmail : Promise
177 | {
178 | [Foreign(Language.Java)]
179 | public UpdateEmail(string email)
180 | @{
181 | if (email == null)
182 | {
183 | @{UpdateEmail:Of(_this).Reject(string):Call("UpdateEmail requires that an email address is provided")};
184 | return;
185 | }
186 |
187 | final FirebaseUser user = (FirebaseUser)@{User.GetCurrent():Call()};
188 |
189 | user.updateEmail(email)
190 | .addOnCompleteListener(new OnCompleteListener() {
191 | public void onComplete(Task task) {
192 | if (task.isSuccessful())
193 | @{UpdateEmail:Of(_this).Resolve(string):Call("success")};
194 | else
195 | @{UpdateEmail:Of(_this).Reject(string):Call("Firebase failed to update email user's address")};
196 | }
197 | });
198 | @}
199 |
200 | void Reject(string reason) { Reject(new Exception(reason)); }
201 | }
202 |
203 |
204 |
205 |
206 |
207 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.net.Uri",
208 | "com.google.android.gms.tasks.OnCompleteListener",
209 | "com.google.android.gms.tasks.Task",
210 | "com.google.firebase.auth.AuthResult",
211 | "com.google.firebase.auth.FirebaseAuth",
212 | "com.google.firebase.auth.FirebaseUser")]
213 | extern(android)
214 | internal class DeleteUser : Promise
215 | {
216 |
217 | [Foreign(Language.Java)]
218 | public DeleteUser()
219 | @{
220 | final FirebaseUser user = (FirebaseUser)@{User.GetCurrent():Call()};
221 | final String email = user.getEmail();
222 |
223 | user.delete()
224 | .addOnCompleteListener(new OnCompleteListener() {
225 | public void onComplete(Task task) {
226 | if (task.isSuccessful())
227 | @{DeleteUser:Of(_this).Resolve(string):Call("User with email " + email + " deleted")};
228 | else
229 | @{DeleteUser:Of(_this).Reject(string):Call("Firebase failed to delete user")};
230 | }
231 | });
232 | @}
233 |
234 | void Reject(string reason) { Reject(new Exception(reason)); }
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication/Firebase.Authentication.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase/Firebase.unoproj"
4 | ],
5 | "Packages": [
6 | "Fuse",
7 | "FuseJS",
8 | "Fuse.Scripting"
9 | ],
10 | "InternalsVisibleTo": [
11 | "Firebase.Authentication.Email",
12 | "Firebase.Authentication.Google",
13 | "Firebase.Authentication.Facebook",
14 | "Firebase.Authentication.Twitter",
15 | "Firebase.Authentication.Github"
16 | ],
17 | "Includes": [
18 | "*"
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Threading;
4 | using Uno.Text;
5 | using Uno.Platform;
6 | using Uno.Compiler.ExportTargetInterop;
7 | using Uno.Collections;
8 | using Fuse;
9 | using Fuse.Scripting;
10 | using Fuse.Reactive;
11 | using Firebase.Authentication;
12 |
13 | namespace Firebase.Authentication.JS
14 | {
15 | /**
16 | */
17 | [UXGlobalModule]
18 | public sealed class AuthModule : NativeEventEmitterModule
19 | {
20 | static readonly AuthModule _instance;
21 | static NativeEvent _onSignInChanged;
22 | static NativeEvent _onError;
23 |
24 | public AuthModule() : base(true,"error","signedInStateChanged")
25 | {
26 | if(_instance != null) return;
27 |
28 | Uno.UX.Resource.SetGlobalKey(_instance = this, "Firebase/Authentication/User");
29 |
30 | AuthService.Init();
31 |
32 | // properties
33 | AddMember(new NativeProperty("isSignedIn", GetSignedIn));
34 | AddMember(new NativeProperty("uid", GetUid));
35 | AddMember(new NativeProperty("name", GetName));
36 | AddMember(new NativeProperty("email", GetEmail));
37 | AddMember(new NativeProperty("photoUrl", GetPhotoUrl));
38 | AddMember(new NativeProperty("providerData", GetProviderData));
39 | AddMember(new NativeProperty("isEmailVerified", IsEmailVerified));
40 |
41 | // events
42 | _onSignInChanged = new NativeEvent("signedInStateChanged");
43 | _onError = new NativeEvent("onError");
44 |
45 | On("error", _onError);
46 | On("signedInStateChanged", _onSignInChanged);
47 |
48 | AddMember(_onSignInChanged);
49 | AddMember(_onError);
50 |
51 | // functions/promises
52 | AddMember(new NativeFunction("signOut", SignOut));
53 |
54 | AddMember(new NativePromise("updateProfile", UpdateProfile, null));
55 | AddMember(new NativePromise("updateEmail", UpdateEmail, null));
56 |
57 | AddMember(new NativePromise("delete", DeleteUser, null));
58 | AddMember(new NativePromise("reauthenticate", ReAuthenticate, null));
59 |
60 | AddMember(new NativePromise("getToken", GetToken, null));
61 |
62 | AuthService.UserChanged += OnUser;
63 | AuthService.OnError += OnError;
64 | }
65 |
66 | // properties
67 | static bool GetSignedIn()
68 | {
69 | return Firebase.Authentication.User.GetCurrent()!=null;
70 | }
71 |
72 | static string GetUid()
73 | {
74 | if (GetSignedIn())
75 | return User.GetUid(User.GetCurrent());
76 | else
77 | return "";
78 | }
79 |
80 | static string GetName()
81 | {
82 | if (GetSignedIn())
83 | return User.GetName(User.GetCurrent());
84 | else
85 | return "";
86 | }
87 |
88 | static string GetEmail()
89 | {
90 | if (GetSignedIn())
91 | return User.GetEmail(User.GetCurrent());
92 | else
93 | return "";
94 | }
95 |
96 | static string GetPhotoUrl()
97 | {
98 | if (GetSignedIn())
99 | return User.GetPhotoUrl(User.GetCurrent());
100 | else
101 | return "";
102 | }
103 |
104 | static string GetProviderData()
105 | {
106 | if (GetSignedIn())
107 | return User.GetProviderData(User.GetCurrent());
108 | else
109 | return "";
110 | }
111 |
112 | static bool IsEmailVerified()
113 | {
114 | if(GetSignedIn())
115 | return User.IsEmailVerified(User.GetCurrent());
116 | else
117 | return false;
118 | }
119 |
120 | // events
121 | static void OnUser()
122 | {
123 | var isSignedIn = GetSignedIn();
124 | var worker = _onSignInChanged.Context == null ? null : _onSignInChanged.Context.ThreadWorker;
125 | _onSignInChanged.RaiseAsync(worker, isSignedIn);
126 | _instance.Emit("signedInStateChanged", isSignedIn);
127 | }
128 |
129 | static void OnError(int errorCode, string message)
130 | {
131 | var worker = _onError.Context == null ? null : _onError.Context.ThreadWorker;
132 | _onError.RaiseAsync(worker, message, errorCode);
133 | _instance.Emit("error", message, errorCode);
134 | }
135 |
136 |
137 |
138 | // functions
139 | static Future GetToken(object[] arg)
140 | {
141 | return new GetToken();
142 | }
143 |
144 | static Future UpdateProfile(object[] args)
145 | {
146 | var displayName = (string)args[0];
147 | var photoUri = (string)args[1];
148 | return new UpdateProfile(displayName, photoUri);
149 | }
150 |
151 | // static object UpdateUser(Context context, object[] args)
152 | // {
153 | // return null;
154 | // }
155 |
156 | static Future UpdateEmail(object[] args)
157 | {
158 | var email = (string)args[0];
159 | return new UpdateEmail(email);
160 | }
161 |
162 | static Future DeleteUser(object[] args)
163 | {
164 | return new DeleteUser();
165 | }
166 |
167 | static object SignOut(Context context, object[] args)
168 | {
169 | AuthService.SignOut();
170 | return null;
171 | }
172 |
173 | Future ReAuthenticate(object[] args)
174 | {
175 | var email = (args.Length>0) ? (string)args[0] : null;
176 | var password = (args.Length>1) ? (string)args[1] : null;
177 | return AuthService.ReAuthenticate(email, password);
178 | }
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication/UpdateUser.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 |
12 | namespace Firebase.Authentication
13 | {
14 | internal class UpdateUser : Promise
15 | {
16 | UpdateProfile _pendingProfile;
17 | UpdateEmail _pendingEmail;
18 | bool _emailSucceeded = true;
19 | bool _profileSucceeded = true;
20 | List _failReasons = new List();
21 |
22 | public UpdateUser(string displayName, string email, string photoUrl)
23 | {
24 | if (email != null)
25 | {
26 | _pendingEmail = new UpdateEmail(email);
27 | _pendingEmail.Then(EmailSuccess, EmailFailed);
28 | }
29 |
30 | if (displayName!=null || photoUrl!=null)
31 | {
32 | _pendingProfile = new UpdateProfile((displayName==null ? User.GetName(User.GetCurrent()) : displayName),
33 | (photoUrl==null ? User.GetPhotoUrl(User.GetCurrent()) : photoUrl));
34 | _pendingProfile.Then(ProfileSuccess, ProfileFailed);
35 | }
36 | }
37 |
38 | void Continue()
39 | {
40 | if (_pendingProfile == null && _pendingEmail == null)
41 | {
42 | if (_emailSucceeded && _profileSucceeded)
43 | {
44 | Resolve("succeeded");
45 | return;
46 | }
47 |
48 | var message = "Update failed with the following issues:";
49 |
50 | Reject(new Exception(message));
51 | }
52 | }
53 |
54 | void EmailSuccess(string message)
55 | {
56 | _pendingEmail = null;
57 | Continue();
58 | }
59 |
60 | void EmailFailed(Exception e)
61 | {
62 | _pendingEmail = null;
63 | _emailSucceeded = false;
64 | Continue();
65 | }
66 |
67 | void ProfileSuccess(string message)
68 | {
69 | _pendingProfile = null;
70 | Continue();
71 | }
72 |
73 | void ProfileFailed(Exception e)
74 | {
75 | _pendingProfile = null;
76 | _profileSucceeded = false;
77 | Continue();
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/Firebase.Authentication/todo.md:
--------------------------------------------------------------------------------
1 | - Add current provider √
2 | - Add announce signin √
3 | - Make announce logout any currently logged in provider √
4 | - Check for signin before signing out :|
5 | - Is reauth just sent to everyone? no you have to target it
6 | - make reauth use current provider √
7 | - remove 'Allo' :D
8 | - hookup errors in example
9 | - remove debug-log
10 |
--------------------------------------------------------------------------------
/src/Firebase.Database/Firebase.Database.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase/Firebase.unoproj",
4 | "../../Fuse.JSON/JSON.unoproj"
5 | ],
6 | "Packages": [
7 | "Fuse",
8 | "FuseJS"
9 | ],
10 | "Includes": [
11 | "*"
12 | ]
13 | }
14 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/Android/Assets/DefaultIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fuse-compound/Fuse.Firebase/ceea6d5495c4973d6635bf68a9ce48f169332704/src/Firebase.Notifications.Android/Android/Assets/DefaultIcon.png
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/Android/Impl.cpp.uxl:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 | ]]>
10 |
11 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | ]]>
27 |
28 |
29 |
30 |
31 |
33 |
35 |
37 |
39 |
41 |
43 |
44 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/Android/Impl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.Graphics;
3 | using Uno.Collections;
4 | using Fuse;
5 | using Fuse.Controls;
6 | using Fuse.Triggers;
7 | using Fuse.Resources;
8 |
9 | using Fuse.Platform;
10 | using Uno.Compiler.ExportTargetInterop;
11 | using Uno.Compiler.ExportTargetInterop.Android;
12 |
13 | namespace Firebase.Notifications
14 | {
15 | [ForeignInclude(Language.Java,
16 | "java.io.IOException",
17 | "android.app.Activity",
18 | "android.content.Intent",
19 | "android.os.AsyncTask",
20 | "android.content.res.Resources",
21 | "android.content.res.AssetManager",
22 | "android.content.res.AssetFileDescriptor",
23 | "android.os.Bundle",
24 | "com.fuse.firebase.Notifications.PushNotificationReceiver",
25 | "com.google.firebase.messaging.RemoteMessage")]
26 | [Require("Gradle.Dependency.Compile", "com.google.firebase:firebase-messaging:12.0.1")]
27 | extern(Android)
28 | internal class AndroidImpl
29 | {
30 | public static event EventHandler RegistrationSucceeded;
31 | public static event EventHandler RegistrationFailed;
32 | public static event EventHandler> ReceivedNotification;
33 |
34 | static bool _init = false;
35 | static List _cachedMessages = new List();
36 |
37 | internal static void Init()
38 | {
39 | if (!_init)
40 | {
41 | JInit();
42 | _init = true;
43 | Lifecycle.EnteringInteractive += OnEnteringInteractive;
44 | Lifecycle.ExitedInteractive += OnExitedInteractive;
45 | }
46 | }
47 |
48 | [Foreign(Language.Java)]
49 | static void JInit()
50 | @{
51 | // Set up vars and hook into fuse intent listeners
52 | com.fuse.Activity.subscribeToIntents(
53 | new com.fuse.Activity.IntentListener() {
54 | public void onIntent (Intent newIntent) {
55 | String jsonStr = com.fuse.firebase.Notifications.PushNotificationReceiver.ToJsonString(newIntent);
56 | @{OnRecieve(string,bool):Call(jsonStr, false)};
57 | }
58 | },
59 | PushNotificationReceiver.ACTION);
60 | String id = com.google.firebase.iid.FirebaseInstanceId.getInstance().getToken();
61 | @{getRegistrationIdSuccess(string):Call(id)};
62 | @}
63 |
64 |
65 | [Foreign(Language.Java), ForeignFixedName]
66 | static void RegistrationIDUpdated(string regid)
67 | @{
68 | @{getRegistrationIdSuccess(string):Call(regid)};
69 | @}
70 |
71 | static void getRegistrationIdSuccess(string regid)
72 | {
73 | var x = RegistrationSucceeded;
74 | if (x!=null)
75 | x(null, regid);
76 | }
77 |
78 | static void getRegistrationIdError(string message)
79 | {
80 | var x = RegistrationFailed;
81 | if (x!=null)
82 | x(null, message);
83 | }
84 |
85 | //----------------------------------------------------------------------
86 |
87 | static void OnEnteringInteractive(ApplicationState newState)
88 | {
89 | NoteInteractivity(true);
90 | var x = ReceivedNotification;
91 | if (x!=null)
92 | {
93 | foreach (var message in _cachedMessages)
94 | x(null, new KeyValuePair(message, true));
95 | }
96 | _cachedMessages.Clear();
97 | }
98 |
99 |
100 | static void OnExitedInteractive(ApplicationState newState)
101 | {
102 | NoteInteractivity(false);
103 | }
104 |
105 | //----------------------------------------------------------------------
106 |
107 | [Foreign(Language.Java), ForeignFixedName]
108 | static void OnRecieve2(string message, bool fromNotificationBar)
109 | @{
110 | @{OnRecieve(string,bool):Call(message, fromNotificationBar)};
111 | @}
112 |
113 | static void OnRecieve(string message, bool fromNotificationBar)
114 | {
115 | if (Lifecycle.State == ApplicationState.Interactive)
116 | {
117 | var x = ReceivedNotification;
118 | if (x!=null)
119 | x(null, new KeyValuePair(message, fromNotificationBar));
120 | }
121 | else
122 | {
123 | _cachedMessages.Add(message);
124 | }
125 | }
126 |
127 | //----------------------------------------------------------------------
128 |
129 | [Foreign(Language.Java)]
130 | static void NoteInteractivity(bool isItInteractive)
131 | @{
132 | PushNotificationReceiver.InForeground = isItInteractive;
133 | java.util.ArrayList maps = PushNotificationReceiver._cachedBundles;
134 | if (isItInteractive && maps!=null && maps.size()>0) {
135 | for (RemoteMessage remoteMessage : maps)
136 | @{OnRecieve(string,bool):Call(PushNotificationReceiver.ToJsonString(remoteMessage), true)};
137 | maps.clear();
138 | }
139 | @}
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/Android/PushNotificationIDService.java:
--------------------------------------------------------------------------------
1 | package com.fuse.firebase.Notifications;
2 |
3 | import com.google.firebase.iid.FirebaseInstanceId;
4 | import com.google.firebase.iid.FirebaseInstanceIdService;
5 |
6 | public class PushNotificationIDService extends FirebaseInstanceIdService
7 | {
8 | @Override
9 | public void onTokenRefresh()
10 | {
11 | String refreshedToken = FirebaseInstanceId.getInstance().getToken();
12 | com.foreign.Firebase.Notifications.AndroidImpl.RegistrationIDUpdated(refreshedToken);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/Common.uno:
--------------------------------------------------------------------------------
1 | using Uno.Compiler.ExportTargetInterop;
2 | using Uno;
3 | using Uno.Graphics;
4 | using Uno.Platform;
5 | using Uno.Collections;
6 | using Fuse;
7 | using Fuse.Controls;
8 | using Uno.Threading;
9 |
10 | namespace Firebase.Notifications
11 | {
12 | [Require("Entity","Firebase.Core.Init()")]
13 | [ForeignInclude(Language.Java,
14 | "android.util.Log",
15 | "com.google.firebase.iid.FirebaseInstanceId")]
16 | [extern(iOS) Require("Source.Include", "Firebase/Firebase.h")]
17 | public static class NotificationService
18 | {
19 | extern(!Android)
20 | static NotificationService()
21 | {
22 | OnRegistrationFailed(null, "Firebase Notifications are not yet available on this platform");
23 | }
24 |
25 | extern(Android)
26 | static NotificationService()
27 | {
28 | // Firebase.Core.Init();
29 | AndroidImpl.ReceivedNotification += OnReceived;
30 | AndroidImpl.RegistrationFailed += OnRegistrationFailed;
31 | AndroidImpl.RegistrationSucceeded += OnRegistrationSucceeded;
32 | AndroidImpl.Init();
33 | }
34 |
35 | public static void OnReceived(object sender, KeyValuePair notification)
36 | {
37 | var x = _receivedNotification;
38 | if (x!=null)
39 | x(null, notification);
40 | else
41 | _pendingNotifications.Add(notification);
42 | }
43 |
44 | public static void OnRegistrationFailed(object sender, string message)
45 | {
46 | var x = _registrationFailed;
47 | if (x!=null)
48 | {
49 | x(null, message);
50 | }
51 | else
52 | {
53 | _pendingSuccess = null;
54 | _pendingFailure = message;
55 | }
56 | }
57 |
58 | public static void OnRegistrationSucceeded(object sender, string message)
59 | {
60 | var x = _registrationSucceeded;
61 | if (x!=null)
62 | {
63 | x(null, message);
64 | }
65 | else
66 | {
67 | _pendingFailure = null;
68 | _pendingSuccess = message;
69 | }
70 | }
71 |
72 | static event EventHandler _registrationSucceeded;
73 | static event EventHandler _registrationFailed;
74 | static event EventHandler> _receivedNotification;
75 | static string _pendingSuccess;
76 | static string _pendingFailure;
77 | static List> _pendingNotifications = new List>();
78 |
79 | internal static event EventHandler> ReceivedNotification
80 | {
81 | add
82 | {
83 | _receivedNotification += value;
84 | foreach (var n in _pendingNotifications)
85 | value(null, n);
86 | _pendingNotifications.Clear();
87 | }
88 | remove {
89 | _receivedNotification -= value;
90 | }
91 | }
92 |
93 | // NOTE: We dont clean the _pendingSuccess or _pendingFailure fields
94 | // As each consumer of PushNotifications will need to know these details.
95 |
96 | internal static event EventHandler RegistrationSucceeded
97 | {
98 | add
99 | {
100 | _registrationSucceeded += value;
101 | if (_pendingSuccess!=null)
102 | {
103 | value(null, _pendingSuccess);
104 | }
105 | }
106 | remove {
107 | _registrationSucceeded -= value;
108 | }
109 | }
110 |
111 | internal static event EventHandler RegistrationFailed
112 | {
113 | add
114 | {
115 | _registrationFailed += value;
116 | if (_pendingFailure!=null)
117 | {
118 | value(null, _pendingFailure);
119 | }
120 | }
121 | remove {
122 | _registrationFailed -= value;
123 | }
124 | }
125 |
126 | [Foreign(Language.ObjC)]
127 | public extern(iOS) static void ClearBadgeNumber()
128 | @{
129 | // [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
130 | @}
131 |
132 | public extern(!iOS) static void ClearBadgeNumber() { }
133 |
134 | [Foreign(Language.ObjC)]
135 | public extern(iOS) static void ClearAllNotifications()
136 | @{
137 | // [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
138 | // [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
139 | @}
140 |
141 | [Foreign(Language.Java)]
142 | public extern(Android) static void ClearAllNotifications()
143 | @{
144 | android.app.Activity activity = com.fuse.Activity.getRootActivity();
145 | android.app.NotificationManager nMgr = (android.app.NotificationManager)activity.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
146 | nMgr.cancelAll();
147 | @}
148 |
149 | public extern(!iOS && !Android) static void ClearAllNotifications() { }
150 |
151 | [Foreign(Language.ObjC)]
152 | public extern(iOS) static String GetFCMToken()
153 | @{
154 | NSString *fcmToken = [[FIRInstanceID instanceID] token];
155 | return fcmToken;
156 | @}
157 |
158 | [Foreign(Language.Java)]
159 | public extern(Android) static String GetFCMToken()
160 | @{
161 | String refreshedToken = FirebaseInstanceId.getInstance().getToken();
162 | Log.d("TOKEN", "Refreshed token: " + refreshedToken);
163 | return refreshedToken;
164 | @}
165 |
166 | public extern(!iOS && !Android) static String GetFCMToken() { return ""; }
167 |
168 |
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/Firebase.Notifications.Android.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Copyright": "Copyright (c) Fusetools AS 2017",
3 | "Description": "Support for Push Notifications On Mobile",
4 | "Publisher": "Fusetools AS",
5 | "Version": "1.0.0-rc2",
6 | "Package": {
7 | "ProjectUrl": "https://fusetools.com"
8 | },
9 | "Packages": [
10 | "Uno.Collections",
11 | "Uno.Threading",
12 | "Fuse.Controls",
13 | "Fuse.Elements",
14 | "Fuse.Reactive",
15 | "Fuse.Scripting",
16 | "Fuse.Common",
17 | "Fuse.Platform"
18 | ],
19 | "Projects": [
20 | "../Firebase/Firebase.unoproj"
21 | ],
22 | "Includes": [
23 | "Common.uno:Source",
24 | "JS.uno:Source",
25 | "Android/Impl.uno:Source",
26 | "iOSImpl.uno:Source",
27 | "Android/Impl.cpp.uxl:Extensions",
28 | "Android/PushNotificationReceiver.java:Java:android",
29 | "Android/PushNotificationIDService.java:Java:android",
30 | "iOSFirebaseNotificationCallbacks.h:ObjCHeader:iOS",
31 | "iOSFirebaseNotificationCallbacks.mm:ObjCSource:iOS",
32 | "Android/Assets/DefaultIcon.png:File"
33 | ]
34 | }
35 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Platform;
4 | using Uno.Collections;
5 | using Uno.Compiler.ExportTargetInterop;
6 | using Fuse;
7 | using Fuse.Scripting;
8 | using Fuse.Reactive;
9 |
10 | namespace Firebase.Notifications
11 | {
12 | /**
13 | @scriptmodule Firebase/Notifications
14 |
15 | Handles push notification from Firebase
16 |
17 | @include Docs/Guide.md
18 |
19 | ## Remarks
20 |
21 | This module is an @EventEmitter, so the methods from @EventEmitter can be used to listen to events.
22 |
23 | You need to add a reference to `Firebase.Notifications` in your project file to use this feature.
24 | */
25 | [UXGlobalModule]
26 | public sealed class NotificationModule : NativeEventEmitterModule
27 | {
28 | static readonly NotificationModule _instance;
29 | readonly iOSImpl _iOSImpl;
30 | static NativeEvent _onRegistrationSucceedediOS;
31 |
32 | public NotificationModule()
33 | : base(true,
34 | "receivedMessage",
35 | "registrationSucceeded")
36 | {
37 | if (_instance != null) return;
38 | Resource.SetGlobalKey(_instance = this, "Firebase/Notifications");
39 |
40 | _iOSImpl = new iOSImpl();
41 |
42 | // Old-style events for backwards compatibility
43 | var onReceivedMessage = new NativeEvent("onReceivedMessage");
44 | var onRegistrationFailed = new NativeEvent("onRegistrationFailed");
45 | var onRegistrationSucceeded = new NativeEvent("onRegistrationSucceeded");
46 |
47 | On("receivedMessage", onReceivedMessage);
48 | // Note: If we decide to remove these old-style events in the future, the
49 | // "error" event will no longer have a listener by default, meaning that the
50 | // module will then throw an exception on "error" (as per the way
51 | // EventEmitter works), unlike the current behaviour. To retain the current
52 | // behaviour we might then want to add a dummy listener to the "error"
53 | // event.
54 | On("error", onRegistrationFailed);
55 | On("registrationSucceeded", onRegistrationSucceeded);
56 |
57 | AddMember(onReceivedMessage);
58 | AddMember(onRegistrationSucceeded);
59 | AddMember(onRegistrationFailed);
60 | AddMember(new NativeFunction("clearBadgeNumber", ClearBadgeNumber));
61 | AddMember(new NativeFunction("clearAllNotifications", ClearAllNotifications));
62 | AddMember(new NativeFunction("getFCMToken", GetFCMToken));
63 | _onRegistrationSucceedediOS = new NativeEvent("onRegistrationSucceedediOS");
64 | AddMember(_onRegistrationSucceedediOS);
65 |
66 | Firebase.Notifications.NotificationService.ReceivedNotification += OnReceivedNotification;
67 | Firebase.Notifications.NotificationService.RegistrationSucceeded += OnRegistrationSucceeded;
68 | Firebase.Notifications.NotificationService.RegistrationFailed += OnRegistrationFailed;
69 | }
70 |
71 | /**
72 | @scriptevent receivedMessage
73 | @param message The content of the notification as json
74 |
75 | Triggered when your app receives a notification.
76 | */
77 | void OnReceivedNotification(object sender, KeyValuePairmessage)
78 | {
79 | Emit("receivedMessage", message.Key, message.Value);
80 | }
81 |
82 | /**
83 | @scriptevent registrationSucceeded
84 | @param message The registration key from the backend
85 |
86 | Triggered when your app registers with the APNS or GCM backend.
87 | */
88 | void OnRegistrationSucceeded(object sender, string message)
89 | {
90 | Emit("registrationSucceeded", message);
91 | }
92 |
93 | static void OnRegistrationSucceedediOS(string message) {
94 | //_onRegistrationSucceedediOS.RaiseAsync(message);
95 | // App is getting crash sometimes at this function and now we are getting FCM token via GetFCMToken(), so we can put it in comment
96 | }
97 |
98 | /**
99 | @scriptevent error
100 | @param message A backend specific reason for the failure.
101 |
102 | Called if your app fails to register with the backend.
103 | */
104 | void OnRegistrationFailed(object sender, string message)
105 | {
106 | EmitError(message);
107 | }
108 |
109 | /**
110 | @scriptmethod clearBadgeNumber
111 |
112 | Clears the badge number shown on the iOS home screen.
113 |
114 | Has no effects on other platforms.
115 | */
116 | public object ClearBadgeNumber(Context context, object[] args)
117 | {
118 | Firebase.Notifications.NotificationService.ClearBadgeNumber();
119 | return null;
120 | }
121 |
122 | /**
123 | @scriptmethod clearAllNotifications
124 |
125 | Cancels all previously shown notifications.
126 | */
127 | public object ClearAllNotifications(Context context, object[] args)
128 | {
129 | Firebase.Notifications.NotificationService.ClearAllNotifications();
130 | return null;
131 | }
132 |
133 | public object GetFCMToken(Context context, object[] args)
134 | {
135 | var token = Firebase.Notifications.NotificationService.GetFCMToken();
136 | if (token != null) {
137 | Emit("registrationSucceeded", token);
138 | }
139 | return null;
140 | }
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/iOSFirebaseNotificationCallbacks.h:
--------------------------------------------------------------------------------
1 | #import
2 | #include
3 |
4 | @interface FireNotificationCallbacks : NSObject
5 | @end
6 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/iOSFirebaseNotificationCallbacks.mm:
--------------------------------------------------------------------------------
1 | #import
2 | #include <@{Firebase.Notifications.NotificationModule:Include}>
3 | #include <@{ObjC.Object:Include}>
4 | #include
5 |
6 | @implementation FireNotificationCallbacks : NSObject
7 |
8 |
9 | - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
10 | NSLog(@"FCM registration token: %@", fcmToken);
11 |
12 | @{Firebase.Notifications.NotificationModule.OnRegistrationSucceedediOS(string):Call(fcmToken)};
13 | }
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/src/Firebase.Notifications.Android/iOSImpl.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Uno.Threading;
8 |
9 | namespace Firebase.Notifications
10 | {
11 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Messaging'")]
12 | [extern(iOS) Require("Source.Include", "iOSFirebaseNotificationCallbacks.h")]
13 | [extern(iOS) Require("Source.Include", "Firebase/Firebase.h")]
14 |
15 | public class iOSImpl
16 | {
17 | extern(ios) static internal ObjC.Object _iosDelegate;
18 |
19 | public iOSImpl() {
20 | Start();
21 | }
22 |
23 | extern(!iOS)
24 | public void Start() { }
25 |
26 | [Foreign(Language.ObjC)]
27 | extern(iOS)
28 | public void Start()
29 | @{
30 | FireNotificationCallbacks* fireCB = [[FireNotificationCallbacks alloc] init];
31 | @{_iosDelegate:Set(fireCB)};
32 | [FIRMessaging messaging].delegate = (id)fireCB;
33 | @}
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/Firebase.Storage/Firebase.Storage.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Projects": [
3 | "../Firebase/Firebase.unoproj"
4 | ],
5 | "Packages": [
6 | "Fuse",
7 | "FuseJS"
8 | ],
9 | "Includes": [
10 | "*"
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/src/Firebase.Storage/JS.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Threading;
4 | using Uno.Text;
5 | using Uno.Platform;
6 | using Uno.Compiler.ExportTargetInterop;
7 | using Uno.Collections;
8 | using Fuse;
9 | using Fuse.Scripting;
10 | using Fuse.Reactive;
11 |
12 | namespace Firebase.Storage.JS
13 | {
14 | [UXGlobalModule]
15 | public sealed class StorageModule : NativeModule
16 | {
17 | static readonly StorageModule _instance;
18 | public StorageModule()
19 | {
20 | if(_instance != null) return;
21 | Uno.UX.Resource.SetGlobalKey(_instance = this, "Firebase/Storage");
22 | Firebase.Storage.StorageService.Init();
23 | AddMember(new NativePromise("upload", Upload, null));
24 | }
25 |
26 | static Future Upload(object[] args)
27 | {
28 | var storagepath = args[0].ToString();
29 | var filepath = args[1].ToString();
30 | return new Upload(storagepath, filepath);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/Firebase.Storage/Storage.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 | using Uno.Threading;
11 |
12 | namespace Firebase.Storage
13 | {
14 | [ForeignInclude(Language.Java,
15 | "com.google.firebase.storage.FirebaseStorage",
16 | "com.google.firebase.storage.OnProgressListener",
17 | "com.google.firebase.storage.StorageReference",
18 | "com.google.firebase.storage.UploadTask")]
19 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Storage'")]
20 | [Require("Gradle.Dependency.Compile", "com.google.firebase:firebase-storage:12.0.1")]
21 | [extern(iOS) Require("Source.Import","FirebaseStorage/FirebaseStorage.h")]
22 | extern(mobile)
23 | static class StorageService
24 | {
25 | static bool _initialized;
26 | extern(android) static Java.Object _handle;
27 | extern(ios) public static ObjC.Object _handle;
28 |
29 | public static void Init()
30 | {
31 | if (!_initialized)
32 | {
33 | Firebase.Core.Init();
34 | if defined(android) AndroidInit();
35 | if defined(ios) iOSInit();
36 | _initialized = true;
37 | }
38 | }
39 |
40 | [Foreign(Language.ObjC)]
41 | extern(iOS)
42 | public static void iOSInit()
43 | @{
44 | [FIRStorage storage];
45 | @{_handle:Set([[FIRStorage storage] reference])};
46 | @}
47 |
48 |
49 | [Foreign(Language.Java)]
50 | extern(android)
51 | public static void AndroidInit()
52 | @{
53 | @{_handle:Set(FirebaseStorage.getInstance().getReference())};
54 | @}
55 | }
56 |
57 | extern(!mobile)
58 | static class StorageService
59 | {
60 | public static void Init() {}
61 | }
62 |
63 | extern(!mobile)
64 | internal class Upload : Promise
65 | {
66 | public Upload(string storagepath, string filepath)
67 | {
68 | Reject(new Exception("Not implemented on desktop"));
69 | }
70 | }
71 |
72 | [Require("Entity", "StorageService")]
73 | [Require("Source.Include","@{StorageService:Include}")]
74 | [extern(iOS) Require("Source.Import","FirebaseStorage/FirebaseStorage.h")]
75 | extern(iOS)
76 | internal class Upload : Promise
77 | {
78 | [Foreign(Language.ObjC)]
79 | public Upload(string storagepath, string filepath)
80 | @{
81 | FIRStorageReference *ref = @{StorageService._handle:Get()};
82 | FIRStorageReference *refChild = [ref child:storagepath];
83 | NSURL *localFile = [NSURL fileURLWithPath:filepath];
84 | dispatch_async(dispatch_get_main_queue(), ^(void){
85 | FIRStorageUploadTask *uploadTask = [refChild putFile:localFile metadata:nil completion:^(FIRStorageMetadata *metadata, NSError *errorUploading) {
86 | if (errorUploading != nil) {
87 | NSString *erstrupload = [NSString stringWithFormat:@"Firebase Storage Upload Error: %@", errorUploading.localizedDescription];
88 | @{Upload:Of(_this).Reject(string):Call(erstrupload)};
89 | } else {
90 | [refChild downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
91 | if (error != nil) {
92 | NSString *erstr = [NSString stringWithFormat:@"Firebase Storage URL Error: %@", error.localizedDescription];
93 | @{Upload:Of(_this).Reject(string):Call(erstr)};
94 | } else {
95 | NSURL *downloadURL = URL;
96 | @{Upload:Of(_this).Resolve(string):Call([downloadURL absoluteString])};
97 | }
98 | }];
99 | }
100 | }];
101 | });
102 | @}
103 | void Reject(string reason) { Reject(new Exception(reason)); }
104 | }
105 |
106 | [ForeignInclude(Language.Java,
107 | "com.google.android.gms.tasks.OnFailureListener",
108 | "com.google.android.gms.tasks.OnSuccessListener",
109 | "com.google.firebase.storage.FirebaseStorage",
110 | "com.google.firebase.storage.OnProgressListener",
111 | "com.google.firebase.storage.StorageReference",
112 | "com.google.firebase.storage.UploadTask",
113 | "java.io.File",
114 | "android.net.Uri")]
115 | extern(Android)
116 | internal class Upload : Promise
117 | {
118 | [Foreign(Language.Java)]
119 | public Upload(string storagepath, string filepath)
120 | @{
121 | StorageReference ref = (StorageReference)@{StorageService._handle:Get()};
122 | Uri file = Uri.fromFile(new File(filepath));
123 | StorageReference childRef = ref.child(storagepath);
124 |
125 | childRef.putFile(file).addOnFailureListener(new OnFailureListener() {
126 | @Override
127 | public void onFailure(Exception exception) {
128 | @{Upload:Of(_this).Reject(string):Call(exception.toString())};
129 | }
130 | }).addOnSuccessListener(new OnSuccessListener() {
131 | @Override
132 | public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
133 | @{Upload:Of(_this).Resolve(string):Call(taskSnapshot.getDownloadUrl().toString())};
134 | }
135 | });
136 | @}
137 | void Reject(string reason) { Reject(new Exception(reason)); }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/Firebase/BundleFiles.java:
--------------------------------------------------------------------------------
1 | package com.fuse.firebase;
2 |
3 | import android.content.Context;
4 | import android.content.res.AssetManager;
5 | import android.util.Log;
6 |
7 | import java.io.BufferedReader;
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.io.InputStreamReader;
11 | import java.util.HashMap;
12 |
13 | public class BundleFiles
14 | {
15 | private static HashMap> bundled = null;
16 |
17 | private static void PopulateBundleInfo(Context context)
18 | {
19 | if (bundled != null) return;
20 |
21 | bundled = new HashMap<>();
22 | BufferedReader reader = null;
23 | try
24 | {
25 | reader = new BufferedReader(new InputStreamReader(context.getAssets().open("bundle"), "UTF-8"));
26 | String mLine;
27 | while ((mLine = reader.readLine()) != null) {
28 | String[] split = mLine.split(":");
29 | if (split.length>1) {
30 | String pkg = split[0];
31 | HashMap bundle = new HashMap<>();
32 | for (int i = 1; i < split.length ; i+=2) {
33 | String bdlName = split[i];
34 | String fileName = split[i+1];
35 | bundle.put(bdlName, fileName);
36 | }
37 | bundled.put(pkg, bundle);
38 | }
39 | }
40 | }
41 | catch (IOException e)
42 | {
43 | Log.e("@(Project.Name)", "Could not read bundle file index");
44 | }
45 | finally
46 | {
47 | if (reader != null)
48 | {
49 | try
50 | {
51 | reader.close();
52 | } catch (IOException e) {
53 | Log.e("@(Project.Name)", "Could not close bundle file index");
54 | }
55 | }
56 | }
57 | }
58 |
59 | public static String GetPathToBundled(Context context, String packageName, String name)
60 | {
61 | PopulateBundleInfo(context);
62 | HashMap pkg = bundled.get(packageName);
63 | if (pkg!=null)
64 | return pkg.get(name);
65 | else
66 | return null;
67 | }
68 |
69 | public static InputStream OpenBundledFile(Context context, String packageName, String name)
70 | {
71 | String bdlPath = GetPathToBundled(context, packageName, name);
72 | if (bdlPath==null) return null;
73 | AssetManager am = context.getAssets();
74 | try
75 | {
76 | return am.open(bdlPath);
77 | }
78 | catch (IOException e)
79 | {
80 | return null;
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/Firebase/Core.uno:
--------------------------------------------------------------------------------
1 | using Uno;
2 | using Uno.UX;
3 | using Uno.Collections;
4 | using Uno.Compiler.ExportTargetInterop;
5 | using Fuse;
6 | using Fuse.Triggers;
7 | using Fuse.Controls;
8 | using Fuse.Controls.Native;
9 | using Fuse.Controls.Native.Android;
10 |
11 | namespace Firebase
12 | {
13 | extern(!mobile)
14 | public class Core
15 | {
16 | static public void Init()
17 | {
18 |
19 | }
20 | }
21 |
22 | [Require("Cocoapods.Podfile.Target", "pod 'Firebase/Core'")]
23 | [Require("Source.Include", "Firebase/Firebase.h")]
24 | extern(iOS)
25 | public class Core
26 | {
27 | [Foreign(Language.ObjC)]
28 | static public void Init()
29 | {
30 | @{
31 | if ([FIRApp defaultApp] == nil) {
32 | NSLog(@"Firebase Configuring...");
33 | [FIRApp configure];
34 | NSLog(@"Firebase Configure Ready!");
35 | }
36 | @}
37 | }
38 | }
39 |
40 | [ForeignInclude(Language.Java, "java.util.ArrayList", "java.util.List", "android.graphics.Color")]
41 | [Require("Gradle.Dependency.ClassPath", "com.google.gms:google-services:4.0.0")]
42 | [Require("Gradle.AllProjects.Repository", "maven {url 'https://maven.google.com'}")]
43 | [Require("Gradle.Dependency.Compile", "com.google.firebase:firebase-core:12.0.1")]
44 | [Require("Gradle.BuildFile.End", "apply plugin: 'com.google.gms.google-services'")]
45 | extern(Android)
46 | public class Core
47 | {
48 | [Foreign(Language.Java)]
49 | static public void Init()
50 | @{
51 |
52 | @}
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/Firebase/Firebase.unoproj:
--------------------------------------------------------------------------------
1 | {
2 | "Packages": [
3 | "Fuse",
4 | "FuseJS",
5 | ],
6 | "Includes": [
7 | "Core.uno",
8 | "iOSHelpers.m:ObjCSource:iOS",
9 | "BundleFiles.java:Java:android"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/src/Firebase/iOSHelpers.m:
--------------------------------------------------------------------------------
1 | #import
2 | @import Firebase;
3 |
4 | // This is an odd file. It exists because if you use `@import` in .mm files
5 | // then XCode will complain that module support is not enabled, even if you
6 | // explicitly enable it (and other surrounding options) in you 'Build Settings'
7 | //
8 | // To work around this we have this one objc file that simply exists to make sure
9 | // that the module is linked properly. The other .mm files can then stick to using
10 | // #include without any extra complications
11 |
--------------------------------------------------------------------------------