Skip to content
Browse files

Removing FB from FfAA to pull in as separate github repo.

  • Loading branch information...
1 parent f6df662 commit 627a7ab4ae34719563a15de3753b5d49d862dd2e @jubishop committed Sep 11, 2009
View
161 fb/FBAPI.as
@@ -1,161 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-package fb {
- import com.adobe.crypto.MD5;
- import com.adobe.serialization.json.JSON;
-
- import fb.FBConnect;
- import fb.FBEvent;
- import fb.net.FBPost;
- import fb.net.JSONLoader;
- import fb.util.Output;
- import fb.util.StringUtil;
-
- import flash.events.Event;
- import flash.events.EventDispatcher;
- import flash.filesystem.File;
- import flash.net.URLLoader;
- import flash.net.URLLoaderDataFormat;
- import flash.net.URLRequest;
- import flash.net.URLRequestMethod;
- import flash.net.URLVariables;
- import mx.utils.ObjectUtil;
- import mx.controls.HTML;
-
- public class FBAPI {
- private static const restURL:String =
- "http://api.facebook.com/restserver.php";
-
- private static var auth_token:String;
- private static var session_key:String;
- private static var uid:String;
- private static var expires:String;
-
- private static var htmlWindow:HTML = new HTML();
-
- private static var datePrefix:String = (new Date()).time.toString();
- private static var callCount:int = 0;
-
- // Simple way of accessing our restserver.php
- // method: Method to call (like friends.get)
- // args: Key=>Value set of args to include.
- // Note that v, format, api_key, call_id, and session_key
- // are all auto-included for you.
- // So for many api calls you don't need any args at all.
- // The method returns an EventDispatcher that will then
- // dispatch an FBEvent.SUCCESS upon return from the server
- // with .data being the json-decoded results.
- // For example to call friends.get:
- // FBAPI.callMethod("friends.get").addEventListener(FBEvent.SUCCESS,
- // function(event:FBEvent):void {
- // trace("All friend ids are: " + event.data.join(","))
- // });
- // Or if I wanted to tag photo 4145 with user 1681, and I didn't
- // care to check the result (since it's just "1"):
- // FBAPI.callMethod("photos.addTag", {pid:4145, tag_uid:1681, x:40, y:20});
- public static function callMethod(method:String,
- callArgs:Object = null):JSONLoader {
- if (!FBConnect.api_key || !FBConnect.session)
- return null;
-
- Output.log("FBAPI calling: " + method, callArgs);
-
- var urlArgs:URLVariables = flattenArgs(method, callArgs);
-
- var loader:JSONLoader = new JSONLoader();
-
- var request:URLRequest = new URLRequest(restURL);
- request.contentType = "application/x-www-form-urlencoded";
- request.method = URLRequestMethod.GET;
- request.data = urlArgs;
- loader.dataFormat = URLLoaderDataFormat.TEXT;
- loader.load(request);
-
- return loader;
- }
-
- // This will upload a photo for you.
- // Demonstration of its use is coming soon.
- public static function uploadPhoto(photo:File,
- callArgs:Object = null):JSONLoader {
- if (!FBConnect.api_key || !FBConnect.session)
- return null;
-
- var urlArgs:URLVariables = flattenArgs("photos.upload", callArgs);
- var post:FBPost= new FBPost();
- for (var urlArg:String in urlArgs)
- post.writePostData(urlArg, urlArgs[urlArg]);
- post.writeFileData(photo);
- post.close();
-
- var loader:JSONLoader = new JSONLoader();
-
- var request:URLRequest = new URLRequest(restURL);
- request.method = URLRequestMethod.POST;
- request.contentType = "multipart/form-data; boundary="+FBPost.boundary;
- request.data = post.data;
- loader.dataFormat = URLLoaderDataFormat.TEXT;
- loader.load(request);
-
- return loader;
- }
-
- // Utility function splits out fql.multiquery to it's parts
- public static function multiqueryByKey(data:Object):Object {
- var resultsByKey:Object = new Object();
- for each (var result:Object in data)
- resultsByKey[result.name] = result.fql_result_set;
- return resultsByKey;
- }
-
- // Utility function takes the method and callArgs
- // And builds a URLVariables with them and
- // all the other default cruft required.
- private static function flattenArgs(method:String,
- callArgs:Object = null):URLVariables {
- callCount++;
-
- var urlArgs:URLVariables = new URLVariables();
- if (callArgs)
- for (var key:String in callArgs)
- if (!ObjectUtil.isSimple(callArgs[key]))
- urlArgs[key] = JSON.encode(callArgs[key]);
- else if (callArgs[key] is Array)
- urlArgs[key] = callArgs[key].join(",");
- else
- urlArgs[key] = callArgs[key];
-
- urlArgs['v'] = '1.0';
- urlArgs['format'] = 'JSON';
- urlArgs['method'] = method;
- urlArgs['api_key'] = FBConnect.api_key;
- urlArgs['call_id'] = datePrefix + callCount;
- urlArgs['ss'] = true;
- urlArgs['session_key'] = FBConnect.session.key;
-
- var argsArray:Array = new Array();
- for (var arg:String in urlArgs) {
- var val:* = urlArgs[arg];
- argsArray.push(arg + "=" + val);
- }
- argsArray.sort();
- var hashString:String = argsArray.join("") + FBConnect.session.secret;
- urlArgs['sig'] = MD5.hash(StringUtil.toUTF8(hashString));
-
- return urlArgs;
- }
- }
-}
View
350 fb/FBConnect.as
@@ -1,350 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb {
- import com.adobe.serialization.json.JSON;
-
- import fb.FBAPI;
- import fb.FBEvent;
- import fb.FBSession;
- import fb.display.FBAuthDialog;
- import fb.display.FBDialog;
- import fb.display.FBPermDialog;
- import fb.display.FBPagePermDialog;
- import fb.net.JSONLoader;
- import fb.net.RedirectTester;
- import fb.util.Output;
-
- import flash.events.Event;
- import flash.events.EventDispatcher;
- import flash.net.SharedObject;
-
- public class FBConnect {
- // Enum constants
- public static const Connected:String = "Connected";
- public static const NotLoggedIn:String = "NotLoggedIn";
-
- // Path to check for logged in status
- private static const LoggedInPath:String = FBDialog.FacebookURL +
- "/extern/desktop_login_status.php";
-
- // Universal dispatcher of authorization changes
- public static var dispatcher:EventDispatcher = new EventDispatcher();
-
- // Publicly accessible globals about session states
- public static var api_key:String;
- [Bindable] public static var session:FBSession;
-
- // List of extra session params passed to requireSession()
- private static var extraSessionParams:Object;
-
- // Permissions
- private static var permissions:Array = new Array();
- private static var validating_permissions:Array;
-
- // Page Adminning
- private static var adminnedPages:Array = new Array();
- private static var requesting_page:String;
-
- // Local filestorage (desktop "cookie")
- private static var sharedObject:SharedObject;
-
- // Status getter/setter. Setter triggers event.
- private static var _status:String = NotLoggedIn;
- public static function get status():String { return _status; }
- public static function set status(new_status:String):void {
- if (new_status != Connected &&
- new_status != NotLoggedIn) {
- return;
- }
- _status = new_status;
-
- dispatcher.dispatchEvent(new FBEvent(FBEvent.STATUS_CHANGED));
- }
-
- // Must be called to start things off.
- public static function init(new_api_key:String):void {
- Output.log("FBConnect init beginning...");
- api_key = new_api_key;
-
- _status = NotLoggedIn;
- session = null;
-
- // If we have stored session data, let's pull it in
- sharedObject = SharedObject.getLocal(api_key);
- if (sharedObject.data["session_key"]) {
- session = new FBSession();
- session.key = sharedObject.data["session_key"];
- session.uid = sharedObject.data["uid"];
- session.expires = sharedObject.data["expires"];
- session.secret = sharedObject.data["secret"];
- Output.log("Loaded session from cache: ",
- session.key, session.uid, session.expires, session.secret);
- }
- }
-
- /**********************************
- * PAGE ADMINISTRATION
- **********************************/
- // Can we admin the given page id?
- public static function canAdminPage(page_id:Number):Boolean {
- return (adminnedPages.indexOf(page_id) != -1);
- }
-
- // Call this to require that we admin a page
- public static function requestPageAdministration(page_id:String):void {
- if (!FBConnect.session.uid) return;
- if (requesting_page) return;
-
- // Check to see whether we already got these
- dispatcher.dispatchEvent(new FBEvent(FBEvent.ALERT,
- "Verifying Page Administration"));
- requesting_page = page_id;
- FBAPI.callMethod("fql.multiquery", {queries:{
- allPages:"select page_id " +
- "from page_admin where uid = " + FBConnect.session.uid,
- grantedPages:"select uid, publish_stream " +
- "from permissions where uid in (select page_id from #allPages)"
- }}).addEventListener(FBEvent.SUCCESS, gotAdminInfo);
- }
-
- // Callback on page admin data
- public static function gotAdminInfo(event:FBEvent):void {
- var resultsByKey:Object = FBAPI.multiqueryByKey(event.data);
-
- // Rebuild list of pages we know we can publish to
- adminnedPages = new Array();
- for each (var grantedPage:Object in resultsByKey.grantedPages)
- if (grantedPage.publish_stream == 1)
- adminnedPages.push(grantedPage.uid);
-
- // If we found out we can in fact administer this page
- // then just fire the event to say so.
- if (canAdminPage(Number(requesting_page))) {
- dispatcher.dispatchEvent(new FBEvent(FBEvent.RESOLVED));
- dispatcher.dispatchEvent(new FBEvent(FBEvent.PAGE_PERMISSION_CHANGED));
- }
- // Ok we're gonna need some dialog action to get this permission
- else {
- var dialog:FBPagePermDialog = new FBPagePermDialog();
- dialog.ext_perm = "publish_stream";
- dialog.page_id = requesting_page;
- dialog.addEventListener(FBEvent.CLOSED, adminDialogClosed);
- dialog.show();
- }
- }
-
- private static function adminDialogClosed(event:FBEvent):void {
- // Loop thru and add all those permissions we've gotten
- if (event.data) adminnedPages.push(event.data);
-
- requesting_page = null;
- dispatcher.dispatchEvent(new FBEvent(FBEvent.PAGE_PERMISSION_CHANGED));
- }
-
- /**********************************
- * EXTENDED PERMISSIONS
- **********************************/
- // Simply informs if we have had this permission granted
- public static function hasPermission(permission_name:String):Boolean {
- return (permissions.indexOf(permission_name) != -1);
- }
-
- // Call this to require/validate a permission
- public static function requirePermissions(permission_names:Array):void {
- if (!FBConnect.session.uid) return;
- if (validating_permissions) return;
-
- // Ask about all these first, to see if we're already auth'd
- dispatcher.dispatchEvent(new FBEvent(FBEvent.ALERT,
- "Checking Extended Permissions"));
- validating_permissions = permission_names;
- FBAPI.callMethod("fql.query", {query:
- "select " + permission_names.join(", ") + " " +
- "from permissions where uid = " + FBConnect.session.uid
- }).addEventListener(FBEvent.SUCCESS, gotPermissionInfo);
- }
-
- // Callback from restserver of whether we have permission
- private static function gotPermissionInfo(event:FBEvent):void {
- var permissions_array:Array = event.data as Array;
- var permissions_granted:Object = permissions_array[0];
-
- // Update our cache of what we know about these permissions
- for (var permission_granted:String in permissions_granted) {
- if (permissions_granted[permission_granted] == 1 &&
- permissions.indexOf(permission_granted) == -1)
- permissions.push(permission_granted);
- else if (permissions_granted[permission_granted] == 0 &&
- permissions.indexOf(permission_granted) != -1)
- permissions.splice(permissions.indexOf(permission_granted), 1);
- }
-
- // Check to see if we need more
- var permissions_needed:Array = new Array();
- for each (var validating_permission:String in validating_permissions)
- if (!hasPermission(validating_permission))
- permissions_needed.push(validating_permission);
-
- if (permissions_needed.length == 0) {
- validating_permissions = null;
- dispatcher.dispatchEvent(new FBEvent(FBEvent.PERMISSION_CHANGED));
- } else {
- dispatcher.dispatchEvent(new FBEvent(FBEvent.ALERT,
- "Confirming Logged In Status"));
- // Confirm we are logged in before trying the perm dialog
- var redirectTester:RedirectTester = new RedirectTester(
- LoggedInPath + "?next=" + FBDialog.NextPath + "&api_key=" + api_key,
- FBDialog.NextPath, 'result=logged_in');
- redirectTester.addEventListener(FBEvent.FAILURE,
- function(event:FBEvent):void {
- unauthenticated();
- });
- redirectTester.addEventListener(FBEvent.SUCCESS,
- function(event:FBEvent):void {
- confirmedLoggedIn(unescape(event.target.location),
- permissions_needed);
- });
- }
- }
-
- // Callback when desktop_login_status has confirmed our login
- // We confirm our uid and proceed with PermDialog or we bail
- private static function confirmedLoggedIn(url:String,
- permissions_needed:Array):void {
- var uid_pattern:RegExp = /uid=(\d+)/;
- var uid:Number = Number(uid_pattern.exec(url)[1]);
- if (uid != session.uid) {
- unauthenticated();
- } else {
- var dialog:FBPermDialog = new FBPermDialog();
- dialog.ext_perm = permissions_needed.join(",");
- dialog.addEventListener(FBEvent.CLOSED, permissionsDialogClosed);
- dialog.show();
- }
- }
-
- // Callback when permissions dialog has closed
- private static function permissionsDialogClosed(event:FBEvent):void {
- // Loop thru and add all those permissions we've gotten
- if (event.data && event.data is Array) {
- var validated_permissions:Array = event.data as Array;
- for each (var validated_permission:String in validated_permissions) {
- permissions.push(validated_permission);
- }
- }
- validating_permissions = null;
-
- dispatcher.dispatchEvent(new FBEvent(FBEvent.PERMISSION_CHANGED));
- }
-
- /**********************************
- * AUTHORIZATION
- **********************************/
- // Our session key may have been deauthorized by the user
- // This method allows us to confirm it's still valid
- private static function validateSession():void {
- if (!api_key || !session) return;
-
- dispatcher.dispatchEvent(new FBEvent(FBEvent.ALERT,
- "Validating Session Key"));
- var loggedIn:JSONLoader =
- FBAPI.callMethod("users.isAppUser");
- loggedIn.retry = false; // Only try once here, we're watching failure...
- loggedIn.addEventListener(FBEvent.SUCCESS, gotLoggedInUser);
- loggedIn.addEventListener(FBEvent.FAILURE, noLoggedInUser);
- }
-
- // This will require we get a session key.
- // And validate if we already have one.
- public static function requireSession(extra_params:Object = null):void {
- if (!api_key) return;
-
- extraSessionParams = extra_params;
-
- if (session) {
- validateSession();
- } else {
- var dialog:FBAuthDialog = new FBAuthDialog(extraSessionParams);
- dialog.addEventListener(FBEvent.CLOSED, loginDialogClosed);
- dialog.show();
- }
- }
-
- // Callback from restserver if session key causes error
- private static function noLoggedInUser(event:FBEvent = null):void {
- session = null;
- SharedObject.getLocal(api_key).data["session_key"] = null;
- requireSession(extraSessionParams);
- }
-
- // Callback from restserver of whether session key is valid
- private static function gotLoggedInUser(event:FBEvent):void {
- if (event.data) status = Connected;
- else noLoggedInUser();
- }
-
- // Callback when authorization dialog has closed
- private static function loginDialogClosed(event:FBEvent):void {
- var dialog:FBAuthDialog = event.target as FBAuthDialog;
- if (event.data) {
- var session_pattern:RegExp = /\{.+?\}/;
- var session_json:String = session_pattern.exec(
- unescape(dialog.htmlWindow.location))[0];
- var session_obj:Object = JSON.decode(session_json);
-
- session = new FBSession();
- session.key = session_obj.session_key;
- session.secret = session_obj.secret;
- session.expires = session_obj.expires;
- session.uid = session_obj.uid;
-
- sharedObject.data["session_key"] = session.key;
- sharedObject.data["uid"] = session.uid;
- sharedObject.data["expires"] = session.expires;
- sharedObject.data["secret"] = session.secret;
-
- status = Connected;
- } else {
- status = NotLoggedIn;
- }
- }
-
- // This will log us out if we have a session
- public static function logout():void {
- if (!api_key) return;
-
- if (status == Connected) {
- var expiration:JSONLoader = FBAPI.callMethod("auth.expireSession");
- expiration.addEventListener(FBEvent.SUCCESS, loggedOutUser);
- expiration.addEventListener(FBEvent.FAILURE, loggedOutUser);
- } else loggedOutUser();
- }
-
- // Callback from restserver of when session is dead
- private static function loggedOutUser(event:FBEvent = null):void {
- session = null;
- status = NotLoggedIn;
- }
-
- // Called internally when we've discovered we're unauthenticated
- private static function unauthenticated():void {
- validating_permissions = null;
- session = null;
- SharedObject.getLocal(api_key).data["session_key"] = null;
- status = NotLoggedIn;
- }
- }
-}
View
48 fb/FBEvent.as
@@ -1,48 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb {
- import flash.events.Event;
-
- public class FBEvent extends Event {
- public static const SUCCESS:String = "success";
- public static const RETRY:String = "retry";
- public static const FAILURE:String = "failure";
- public static const SHOWING:String = "fb_showing";
- public static const SHOWN:String = "fb_shown";
- public static const CLOSED:String = "fb_closed";
- public static const CLOSING:String = "fb_closing";
- public static const STATUS_CHANGED:String = "fb_statusChanged";
- public static const PERMISSION_CHANGED:String = "fb_permissionChanged";
- public static const PAGE_PERMISSION_CHANGED:String =
- "fb_pagePermissionChanged";
- public static const ALERT:String = "fb_alert";
- public static const ERROR:String = "fb_error";
- public static const RESOLVED:String = "fb_resolved";
- public static const DISABLE:String = "fb_disable";
- public static const ENABLE:String = "fb_enable";
- public static const DATA_RECEIVED:String = "fb_dataReceived";
- public static const FETCHING_DATA:String = "fb_fetchingData";
- public static const DELETED:String = "fb_deleted";
-
- private var _data:*;
-
- public function FBEvent(type:String, new_data:*= null) {
- _data = new_data;
- super(type, true, true);
- }
- public function get data():* { return _data; }
- }
-}
View
23 fb/FBSession.as
@@ -1,23 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb {
- public class FBSession {
- public var key:String;
- public var secret:String;
- public var expires:int;
- [Bindable] public var uid:int;
- }
-}
View
57 fb/display/FBAuthDialog.as
@@ -1,57 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-// FBDialog extension specifically for login and tos
-// Please see FBDialog for more details.
-package fb.display {
- import fb.display.FBDialog;
- import fb.util.Output;
-
- import flash.events.Event;
-
- public class FBAuthDialog extends FBDialog {
- private static const FailurePath:String = FBDialog.FacebookURL +
- "/connect/login_failure.html";
-
- public function FBAuthDialog(extra_params:Object) {
- title = "Facebook Connect Authorization";
- location = "/login.php";
- extraParams["next"] = NextPath;
- extraParams["return_session"] = true;
- extraParams["cancel_url"] = FailurePath;
- for (var param:String in extra_params) {
- extraParams[param] = extra_params[param];
- }
- }
-
- override protected function htmlLocationChange(event:Event):void {
- super.htmlLocationChange(event);
-
- if (!htmlWindow || htmlWindow.location == '' ||
- htmlWindow.location == location || closed) return;
-
- Output.log("Authorization location: " + htmlWindow.location);
-
- if (htmlWindow.location.indexOf(NextPath) == 0)
- hide(true);
- else if (htmlWindow.location.indexOf(FailurePath) == 0)
- hide(false);
- // Sometimes we get kicked to home.php, which is basically failure
- else if (htmlWindow.location.indexOf("home.php") != -1)
- hide(false);
- else transition();
- }
- }
-}
View
194 fb/display/FBDialog.mxml
@@ -1,194 +0,0 @@
-<!--
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- -->
-<!-- This internal dialog class is built to frame in
- Facebook authorization pages.
- It's functionally abstract.
- FBAuthDialog and FBPermDialog are concrete implementations.
- It has no internal graphical elements
- other than an HTML element and a loading animation.
- Although it could be extended for other purposes.
- It has a hide() and show() function.
- It dispatches SHOWING, SHOWN, CLOSING, CLOSED.
- It autoresizes to the content it's displaying. -->
-<display:WindowBase xmlns:mx="http://www.adobe.com/2006/mxml"
- xmlns:display="fb.display.*"
- width="510"
- styleName="fbDialog"
- creationComplete="creationComplete(event)"
- close="hide()" >
-
- <mx:Style source="../styles/fb_style.css" />
-
- <mx:Canvas width="100%"
- height="100%" >
- <mx:HTML id="htmlWindow"
- visible="false"
- width="100%"
- locationChange="htmlLocationChange(event)"
- updateComplete="htmlComplete(event)" />
- <mx:HBox id="loadingAnimation"
- visible="false"
- styleName="dialogLoadingIndicator" >
- <mx:Label styleName="statusText"
- text="Connecting to Facebook" />
- <display:LoadAnimation width="20"
- height="100%" />
- </mx:HBox>
- </mx:Canvas>
- <mx:Script><![CDATA[
- import fb.FBConnect;
- import fb.FBEvent;
-
- import flash.events.Event;
- import flash.events.TimerEvent;
-
- import mx.controls.HTML;
- import mx.events.FlexEvent;
-
- private static const MINIMUM_HEIGHT:int = 8;
-
- public static const FacebookURL:String =
- "http://www.facebook.com";
- public static const NextPath:String = FacebookURL +
- "/connect/login_success.html";
-
- private static var result:* = false;
-
- private static const TimeoutDelay:int = 20000;
- private static var reloadTimer:Timer = new Timer(TimeoutDelay);
-
- protected var location:String;
- protected var extraParams:Object = {
- v:"1.0",
- fbconnect:true,
- nochrome:true,
- connect_display:"popup",
- display:"popup"
- };
-
- // Called when initialized
- private function creationComplete(event:FlexEvent):void {
- // Make sure to listen to timer
- reloadTimer.addEventListener(TimerEvent.TIMER, timedOut);
- }
-
- // Shows the dialog in the center of the app.
- // You should probably set location before calling this.
- // And perhaps extraParams as well.
- public function show():void {
- // If any listener to SHOWING calls preventDefault()
- // Then we stop.
- var showingEvent:FBEvent = new FBEvent(FBEvent.SHOWING);
- dispatchEvent(showingEvent);
- if (showingEvent.isDefaultPrevented()) return;
-
- // Pop us up onto the screen and center ourself
- open();
-
- // We wait to set our html location until after addPopUp
- // to ensure all our graphical elements are initialized.
- setHTMLWindowLocation();
-
- dispatchEvent(new FBEvent(FBEvent.SHOWN));
- }
-
- public function hide(a_result:* = false):void {
- if (!visible) return;
-
- // If any listener to CLOSING calls preventDefault()
- // Then we don't close.
- var closingEvent:FBEvent = new FBEvent(FBEvent.CLOSING);
- dispatchEvent(closingEvent);
- if (closingEvent.isDefaultPrevented()) return;
-
- // No need to keep loading whatever we're loading
- htmlWindow.cancelLoad();
-
- // Cache away our result
- result = a_result;
-
- // No longer care about timeouts
- reloadTimer.stop();
-
- // Remove ourselves from display
- close();
-
- // Dispatch that we're closed
- dispatchEvent(new FBEvent(FBEvent.CLOSED, result));
-
- // Clear out our location
- htmlWindow.location = '';
- }
-
- private function timedOut(event:TimerEvent):void {
- htmlWindow.reload();
- }
-
- protected function setHTMLWindowLocation():void {
- // Build our full url location
- var full_location:String = FacebookURL + location +
- "?api_key=" + FBConnect.api_key;
- for (var key:String in extraParams) {
- full_location += "&" + key + "=" + extraParams[key];
- }
- htmlWindow.location = full_location;
- }
-
- // We listen to location changes to track success / failure.
- // Intended to be overridden by subclasses
- // The subclass should determine if the Dialog's job is done
- // And then call hide() handing it a result parameter.
- // hide() will then dispatch that result with an FBEvent.CLOSED
- protected function htmlLocationChange(event:Event):void {
- if (!htmlWindow || htmlWindow.location == '' || closed) return;
-
- // If an htmlLocationChange doesn't fire eventually
- // then we'll reload
- reloadTimer.start();
- }
-
- // Called when the size of our html has changed, so we resize/recenter
- private function htmlComplete(event:Event):void {
- // We got data, so stop thinking we're timed out.
- reloadTimer.stop();
-
- if (!htmlWindow || htmlWindow.location == '' || closed) return;
-
- if (htmlWindow.loaded) showHTML();
- }
-
- // Utility to call when html is ready and we need to
- // recenter and make ourselves look proper with html
- protected function showHTML():void {
- if (closed || !nativeWindow) return
- if (htmlWindow.contentHeight < MINIMUM_HEIGHT)
- transition();
- else {
- loadingAnimation.visible = false;
- htmlWindow.visible = true;
- height = htmlWindow.contentHeight;
- }
- }
-
- // Utility to call when transitioning between pages.
- // Recenters self and shows the loading animation
- protected function transition():void {
- if (closed) return;
- htmlWindow.visible = false;
- loadingAnimation.visible = true;
- }
- ]]></mx:Script>
-</display:WindowBase>
View
39 fb/display/FBPagePermDialog.as
@@ -1,39 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-// FBDialog extension specifically for authorize
-// Please see FBDialog for more details.
-package fb.display {
- import fb.display.FBDialog;
- import fb.util.Output;
-
- import flash.events.Event;
-
- public class FBPagePermDialog extends FBPermDialog {
- public function get page_id():String {
- return extraParams["profile_selector_ids"];
- }
- public function set page_id(new_page_id:String):void {
- extraParams["profile_selector_ids"] = new_page_id;
- }
-
- override public function hide(a_result:* = false):void {
- // If we're hiding with a value, override that
- // value and insert our page_id
- if (a_result) super.hide(Number(page_id));
- else super.hide(false);
- }
- }
-}
View
58 fb/display/FBPermDialog.as
@@ -1,58 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-// FBDialog extension specifically for authorizing page adminning
-// Please see FBDialog for more details.
-package fb.display {
- import fb.display.FBDialog;
- import fb.util.Output;
-
- import flash.events.Event;
-
- public class FBPermDialog extends FBDialog {
- public function FBPermDialog() {
- title = "Facebook Connect Extended Permissions";
- location = "/connect/prompt_permissions.php";
- extraParams["next"] = NextPath + "?xxRESULTTOKENxx";
- extraParams["extern"] = 1;
- }
-
- public function get ext_perm():String { return extraParams["ext_perm"]; }
- public function set ext_perm(new_ext_perm:String):void {
- extraParams["ext_perm"] = new_ext_perm;
- }
-
- override protected function htmlLocationChange(event:Event):void {
- super.htmlLocationChange(event);
-
- if (!htmlWindow || htmlWindow.location == '' ||
- htmlWindow.location == location || closed) return;
-
- Output.log("Permission location: " + htmlWindow.location);
-
- // We check and pull out the string of those that were authorized
- if (htmlWindow.location.indexOf(NextPath) == 0) {
- var unescaped_location:String = unescape(htmlWindow.location);
- var results:String =
- unescaped_location.substring(unescaped_location.indexOf("?") + 1);
- hide(results.split(","));
- }
- // If this is not our base url then we're off track somehow
- else if (htmlWindow.location.indexOf(location) == -1)
- hide(false);
- else transition();
- }
- }
-}
View
75 fb/display/LoadAnimation.as
@@ -1,75 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-// Creates the "Loading" Animation used on Facebook to indicate
-// network activity.
-package fb.display {
- import fb.util.MathUtil;
-
- import flash.events.Event;
-
- import mx.containers.Canvas;
-
- public class LoadAnimation extends Canvas {
-
- public var fadeDuration:Number = 800;
- private var totalElapsed:Number = 0;
-
- public function LoadAnimation() {
- addEventListener(Event.ENTER_FRAME, update);
- }
-
- override public function set visible(to:Boolean):void {
- if (super.visible == to) return;
- super.visible = to;
-
- if (visible) {
- addEventListener(Event.ENTER_FRAME, update);
- } else {
- removeEventListener(Event.ENTER_FRAME, update);
- }
- }
-
- private function update(evt:Event):void {
- totalElapsed += 20;
-
- var cycle:Number;
- graphics.clear();
-
- var fullHeight:Number = Math.floor(height);
- var restHeight:Number = Math.floor(fullHeight * 0.3);
-
- var shapeWidth:Number = Math.round((width/3) * 0.6);
- var shapeGap:Number = Math.round((width/3) * 0.4);
-
- var dH:Number = fullHeight - restHeight;
-
- for (var i:int=0; i<3; i++) {
- cycle = (totalElapsed + (3-i) * fadeDuration*0.13) % fadeDuration;
- cycle = MathUtil.invCos(1 - MathUtil.clamp(cycle/(0.6*fadeDuration)));
-
- graphics.lineStyle(1, 0x576EA4, cycle*0.7+0.3, true);
- graphics.beginFill(0xB1BAD3, cycle*0.7+0.3);
- graphics.drawRoundRect(0.5 + i * (shapeGap + shapeWidth),
- 0.5 + 0.5 * (dH - cycle*dH),
- shapeWidth,
- restHeight + cycle * dH,
- 2);
- graphics.endFill();
- }
- }
-
- }
-}
View
36 fb/display/WindowBase.as
@@ -1,36 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.display {
- import fb.util.FlexUtil;
-
- import flash.events.Event;
-
- import mx.core.Window;
-
- public class WindowBase extends Window {
- public function WindowBase() {
- alwaysInFront = true;
- showStatusBar = false;
- resizable = minimizable = maximizable = false;
- addEventListener(Event.ADDED, added);
- }
-
- private function added(event:Event):void {
- if (event.target == this) return;
- FlexUtil.simplify(event.target);
- }
- }
-}
View
110 fb/net/FBPost.as
@@ -1,110 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.net {
- import flash.filesystem.File;
- import flash.utils.ByteArray;
- import flash.utils.Endian;
-
- // Utility class builds our form-data;
- public class FBPost {
- public static const boundary:String = "-----";
- private var postData:ByteArray = new ByteArray();
-
- public function FBPost() {
- postData.endian = Endian.BIG_ENDIAN;
- }
-
- public function writePostData(name:String, value:String):void {
- var bytes:String;
-
- writeBoundary();
- writeLineBreak();
-
- bytes = 'Content-Disposition: form-data; name="' + name + '"';
-
- for (var i:Number=0; i < bytes.length; i++) {
- postData.writeByte( bytes.charCodeAt(i) );
- }
-
- writeLineBreak();
- writeLineBreak();
-
- postData.writeUTFBytes(value);
-
- writeLineBreak();
- }
-
- public function writeFileData(file:File):void {
- var bytes:String;
-
- writeBoundary();
- writeLineBreak();
-
- bytes = 'Content-Disposition: form-data; filename="';
- for (var i:Number=0; i < bytes.length; i++) {
- postData.writeByte(bytes.charCodeAt(i));
- }
- postData.writeUTFBytes(file.name);
-
- writeQuotationMark();
- writeLineBreak();
-
- bytes = 'Content-Type: image/jpg';
- for (i=0; i < bytes.length; i++) {
- postData.writeByte(bytes.charCodeAt(i));
- }
-
- writeLineBreak();
- writeLineBreak();
-
- file.data.position = 0;
- postData.writeBytes(file.data, 0, file.data.length);
-
- writeLineBreak();
- }
-
- public function get data():ByteArray {
- postData.position = 0;
- return postData;
- }
-
- public function close():void {
- writeBoundary();
- writeDoubleDash();
- }
-
- protected function writeLineBreak():void {
- postData.writeShort(0x0d0a);
- }
-
- protected function writeQuotationMark():void {
- postData.writeByte(0x22);
- }
-
- protected function writeDoubleDash():void {
- postData.writeShort(0x2d2d);
- }
-
- protected function writeBoundary():void {
- writeDoubleDash();
-
- for (var i:Number=0; i < boundary.length; i++) {
- postData.writeByte(boundary.charCodeAt(i));
- }
- }
-
- }
-}
View
113 fb/net/JSONLoader.as
@@ -1,113 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.net {
- import air.net.URLMonitor;
-
- import com.adobe.serialization.json.JSON;
-
- import fb.FBConnect;
- import fb.FBEvent;
- import fb.util.Output;
-
- import flash.events.Event;
- import flash.events.IOErrorEvent;
- import flash.events.SecurityErrorEvent;
- import flash.events.StatusEvent;
- import flash.net.URLLoader;
- import flash.net.URLRequest;
-
- // Simple URLLoader extender will wrap the result from
- // it's own COMPLETE in a JSON.decode then dispatch a
- // FBEvent.SUCCESS with the JSON data.
- public class JSONLoader extends URLLoader {
- public var retry:Boolean = true;
-
- private static const MaxAttempts:int = 3;
- private var attempts:int = 0;
-
- private var request:URLRequest;
- private var urlMonitor:URLMonitor;
-
- public function JSONLoader(new_request:URLRequest = null,
- new_retry:Boolean = true) {
- request = new_request;
- retry = new_retry;
- addEventListener(Event.COMPLETE, success);
- addEventListener(IOErrorEvent.IO_ERROR, error);
- addEventListener(SecurityErrorEvent.SECURITY_ERROR, error);
- }
-
- private function error(event:Event):void {
- Output.error("JSON Error: " + urlMonitor.available);
- dispatchEvent(new FBEvent(FBEvent.RETRY));
- if (attempts++ < MaxAttempts) reload();
- else if (!urlMonitor.available) {
- attempts = 0;
- urlMonitor.start();
- }
- }
-
- private function statusChanged(event:StatusEvent):void {
- Output.error("JSON Status changed: " + urlMonitor.available);
- if (urlMonitor.available) reload();
- }
-
- public function reload():void {
- if (!retry) return;
- Output.error("Reloading JSON: " + request.url);
- load(request);
- }
-
- override public function load(new_request:URLRequest):void {
- if (++attempts > MaxAttempts) return;
- Output.log("JSON Loading: " + new_request.url);
- if (new_request) request = new_request;
- if (!urlMonitor) {
- urlMonitor = new URLMonitor(request);
- urlMonitor.addEventListener(StatusEvent.STATUS, statusChanged);
- }
- super.load(new_request);
- }
-
- private function success(event:Event):void {
- if (event.target.data.indexOf("<") != 0) {
- var eventData:* = JSON.decode(event.target.data);
- if (eventData.constructor == Object && eventData.error_code) {
- Output.error("Server Error", eventData);
- FBConnect.dispatcher.dispatchEvent(new FBEvent(FBEvent.ERROR,
- {text:"Server Error (Click To Retry)",
- callback:function():void { attempts = 0; reload(); },
- hide:true}));
- dispatchEvent(new FBEvent(FBEvent.FAILURE, eventData));
- urlMonitor.start();
- }
- else {
- Output.log("JSON Loaded: ", eventData);
- urlMonitor.stop();
- dispatchEvent(new FBEvent(FBEvent.SUCCESS, eventData));
- }
- } else {
- Output.error("Server XML returned", event.target.data);
- FBConnect.dispatcher.dispatchEvent(new FBEvent(FBEvent.ERROR,
- {text:"Server XML (Click To Retry)",
- callback:function():void { attempts = 0; reload(); },
- hide:true}));
- dispatchEvent(new FBEvent(FBEvent.FAILURE));
- urlMonitor.start();
- }
- }
- }
-}
View
61 fb/net/RedirectTester.as
@@ -1,61 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.net {
- import fb.FBEvent;
- import fb.util.Output;
-
- import flash.events.Event;
- import flash.events.EventDispatcher;
-
- import mx.controls.HTML;
- import mx.core.Application;
-
- public class RedirectTester extends EventDispatcher {
- private var origURL:String;
- private var nextURL:String;
- private var success:String;
-
- private var html:HTML = new HTML();
-
- public function RedirectTester(new_orig_url:String,
- new_next_url:String,
- new_success:String) {
- origURL = new_orig_url;
- nextURL = new_next_url;
- success = new_success;
-
- html.visible = html.includeInLayout = false;
- Application.application.addChild(html);
- html.addEventListener(Event.LOCATION_CHANGE, locationChange);
- html.location = origURL;
- }
-
- private function locationChange(event:Event):void {
- Output.log("Redirect url: " + location);
- if (location == '' || location == origURL) return;
- if (location.indexOf(nextURL) == -1) return;
- if (location.indexOf(success) == -1)
- dispatchEvent(new FBEvent(FBEvent.FAILURE));
- else
- dispatchEvent(new FBEvent(FBEvent.SUCCESS));
- html.location = '';
- }
-
- public function get location():String {
- return html.location;
- }
- }
-}
View
14 fb/styles/fb_style.css
@@ -1,14 +0,0 @@
-.dialogLoadingIndicator {
- horizontalCenter:0;
- verticalCenter:0;
-}
-
-.fbDialog {
- background-color: #ffffff;
-}
-
-.statusText {
- color: #333333;
- font-family: "Lucida Grande", "Segoe UI", "Tahoma", "Verdana", "Arial", "_sans";
- font-weight: bold;
-}
View
109 fb/util/FlexUtil.as
@@ -1,109 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.util {
- import fb.util.Output;
-
- import flash.display.DisplayObject;
- import flash.display.InteractiveObject;
- import flash.filesystem.File;
-
- import mx.controls.TextArea;
- import mx.core.Container;
- import mx.core.ScrollPolicy;
-
- public class FlexUtil {
- public static function getStyle(obj:*, ... styles):* {
- if (!styles || styles.length == 0) return null;
- for (var i:int = 0; i < styles.length-1; i++)
- if (obj.getStyle(styles[i]))
- return obj.getStyle(styles[i]);
- return styles[styles.length-1];
- }
-
- public static function getUserPath(file:String):File {
- if (File.desktopDirectory && File.desktopDirectory.exists)
- return File.desktopDirectory.resolvePath(file);
- if (File.userDirectory && File.userDirectory.exists)
- return File.userDirectory.resolvePath(file);
- return File.applicationStorageDirectory.resolvePath(file);
- }
-
- public static function simplify(obj:*):void {
- // Automagic scrollbars and masks in flex cause so much pain
- // and trouble, that we're going to remove them for all
- // containers added to our application. Take that, flex!
- if (obj is Container) {
- var container:Container = obj as Container;
- container.clipContent = false;
- container.horizontalScrollPolicy =
- container.verticalScrollPolicy = ScrollPolicy.OFF;
-
- for (var i:int = 0; i < container.numChildren; i++)
- simplify(container.getChildAt(i));
- }
-
- // We don't want tab enabled for anything but text
- if (obj is InteractiveObject && !(obj is TextArea))
- (obj as InteractiveObject).tabEnabled = false;
- }
-
- // Checks the values of other, and merges them
- // into orig only if not ==.
- public static function merge(orig:*, other:*):* {
- // If either is null, then go w/ the other
- if (other == null) return orig;
- if (orig == null) return other;
-
- // If orig is primitive, then check against it
- if (orig is Number ||
- orig is Boolean ||
- orig is String) {
- if (orig != other) return other;
- else return orig;
- }
-
- // If other is primitive and orig wasn't,
- // then go with other.
- if (other is Number ||
- other is Boolean ||
- other is String)
- return other;
-
-
- // If different types, go with other
- if (orig.constructor != other.constructor) return other;
-
- // Merge arrays, destructively favoring other
- if (orig is Array && other is Array) {
- for (var i:int = 0; i < Math.min(orig.length, other.length); i++)
- orig[i] = merge(orig[i], other[i]);
- if (other.length < orig.length)
- orig.splice(other.length, orig.length - other.length);
- else if (other.length > orig.length)
- orig.push.apply(orig, other.slice(orig.length));
- return orig;
- }
-
- // Merge the pieces, additively
- var entry:*;
- for (entry in orig)
- orig[entry] = merge(orig[entry], other[entry]);
- for (entry in other) if (!orig[entry])
- orig[entry] = other[entry];
- return orig;
- }
- }
-}
View
65 fb/util/MathUtil.as
@@ -1,65 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.util {
- public final class MathUtil {
- // returns bounded n to the min and max
- public static function clamp(n:Number, min:Number=0, max:Number=1):Number {
- if (n < min) {
- return min;
- }
- if (n > max) {
- return max;
- }
- return n;
- }
-
- public static function invCos(x:Number):Number {
- return 1 - (0.5 * (Math.cos(x*Math.PI) + 1));
- }
-
- public static function and(... bools):Boolean {
- for each (var b:Boolean in bools) if (!b) return false;
- return true;
- }
-
- public static function or(... bools):Boolean {
- for each (var b:Boolean in bools) if (b) return true;
- return false;
- }
-
- public static function xor(... bools):Boolean {
- var foundTruth:Boolean = false;
- for each (var b:Boolean in bools) if (b) {
- if (foundTruth) return false;
- foundTruth = true;
- }
- return foundTruth;
- }
-
- // returns an ordinal number
- public static function ordinal(n:int):String {
- if (n > 3 && n < 21) {
- return n + 'th';
- }
- switch (n % 10) {
- case 1: return n + 'st';
- case 2: return n + 'nd';
- case 3: return n + 'rd';
- default: return n + 'th';
- }
- }
- }
-}
View
113 fb/util/Output.as
@@ -1,113 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.util {
- import flash.filesystem.File;
- import flash.filesystem.FileMode;
- import flash.filesystem.FileStream;
- import flash.utils.getTimer;
-
- import mx.controls.Alert;
-
- import fb.util.FlexUtil;
-
- public class Output {
- private static var prod:Boolean = false;
- private static var verbose:Boolean = true;
- private static var debugFile:File = FlexUtil.getUserPath("air_debug.txt");
- private static var debugStream:FileStream = new FileStream();
- private static var loggedItems:Array = new Array();
-
- // Trace
- public static function log(... rest):void {
- if (prod || !verbose) return;
- loggedItems.push("Log Time: " + getTimer());
- for each (var item:* in rest)
- loggedItems.push(item);
- }
-
- // Trace no matter what
- public static function bug(... rest):void {
- if (prod) return;
- loggedItems.push("Bug Time: " + getTimer());
- for each (var item:* in rest) {
- loggedItems.push(item);
- trace(pretty(item));
- }
- }
-
- // Trace error no matter what
- public static function error(... rest):void {
- if (prod) return;
- loggedItems.push("Error Time: " + getTimer());
- for each (var item:* in rest) {
- loggedItems.push(item);
- trace(pretty(item));
- }
- }
-
- public static function logDump():void {
- if (prod) return;
- debugStream.open(debugFile, FileMode.WRITE);
- for each (var item:* in loggedItems)
- debugStream.writeUTFBytes(pretty(item));
- debugStream.close();
- }
-
- // Assert the thing which is not profane
- public static function assert(assertion:Boolean, ... rest):void {
- if (prod) return;
- if (!assertion) for each (var item:* in rest) error(item);
- }
-
- // Alert
- public static function alert(item:*):void {
- if (prod) return;
- Alert.show(pretty(item));
- }
-
- // Take an object and turn it into a pretty json-encoded string
- public static function pretty(item:*, preTab:String = ""):String {
- if (prod) return '';
- if (item is Array) {
- var i:int = 0;
- var a:String = "[\n";
- for each (var entry:* in item) {
- a += preTab + " " + i + " - " + pretty(entry, preTab + " ");
- i++;
- }
- a += preTab + "]\n";
- return a;
- }
-
- if (item is String)
- return "\"" + item + "\"\n";
- if (item is Boolean ||
- item is Number)
- return String(item) + "\n";
-
- if (item is Object) {
- var o:String = "{\n";
- for (var key:String in item) {
- o += preTab + " " + key + ":" + pretty(item[key], preTab + " ");
- }
- o += preTab + "}\n";
- return o;
- }
-
- return String(item) + "\n";
- }
- }
-}
View
144 fb/util/StringUtil.as
@@ -1,144 +0,0 @@
-/*
- Copyright Facebook Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-package fb.util {
- public final class StringUtil {
-
- public static var UrlRegExp:RegExp =
- new RegExp('(?:(?:ht|f)tps?):\\/\\/([^\\s<\\)\\]"\']*[^\\s<\\.\\)\\]"\':])', 'gi');
-
- // Simple util builds an html link out of a string and a url
- public static function linkify(str:String, url:String,
- bold:Boolean=true,
- color:String='3b5998'):String {
- if (empty(str)) return '';
- var link:String = '<a href="' + url + '">' + str + '</a>';
- if (bold) {
- link = '<b>' + link + '</b>';
- }
- return colorize(link, color);
- }
-
- // Wrap some text in a font color tag
- public static function colorize(str:String, color:String):String {
- if (empty(str)) return '';
- return '<font color="#' + color + '">' + str + '</font>';
- }
-
- // Take a word and a total and phrase it with optional plurality
- public static function pluralize(word:String, amount:int):String {
- if (empty(word)) return '';
- return amount + " " + word + (amount == 1 ? '' : 's');
- }
-
- // Find all the links in text and linkify them
- public static function htmlize(str:String):String {
- if (empty(str)) return '';
- // hearts
- str = str.replace(/<3\b/g, '&hearts;');
- // html encode
- str = replaceAll(str, ['&', '<', '>', '\'', '"'],
- ['&amp;', '&lt;', '&gt;', '&apos;', '&quot;']);
- // post fix
- // Note also that the <3 conversion is done as a post-fixup hack,
- // so that there is a way to literally put '&hearts;'
- str = replaceAll(str, ['\r\n', '\n', '&amp;hearts;'],
- ['<br />', '<br />', '♥']);
- // linkify
- str = str.replace(UrlRegExp, function():String {
- var str:String = arguments[1];
- if (str.charAt(str.length-1) == '/') {
- str = str.substring(0, str.length-1);
- }
- return linkify(str, arguments[0], false);
- });
- return str;
- }
-
- public static function replaceAll(str:String, pre:*, post:*):String {
- if (empty(str)) return '';
- if (pre is String) {
- return str.split(pre).join(post);
- } else if (pre is Array) {
- var preA:Array = pre as Array;
- var postA:Array = post as Array;
- for (var i:int = 0; i < preA.length; i++) {
- str = str.split(preA[i]).join(postA[i]);
- }
- }
- return str;
- }
-
- public static function empty(str:*):Boolean {
- return (!str || str == '');
- }
-
- // Encode a string as utf-8. Helpful before MD5 since PHP and other
- // languages encode strings in utf-8 before hashing them.
- // This assumes the input is valid utf-16 (most AS3 strings are)
- public static function toUTF8(input:String):String {
- var output:String = "";
- var i:Number = -1;
- var x:Number, y:Number;
-
- while (++i < input.length) {
- // Decode utf-16 surrogate pairs
- x = input.charCodeAt(i);
- y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
- if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
- x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
- i++;
- }
-
- // Encode output as utf-8
- if (x <= 0x7F) {
- output += String.fromCharCode(x);
- } else if (x <= 0x7FF) {
- output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
- 0x80 | ( x & 0x3F));
- } else if (x <= 0xFFFF) {
- output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
- 0x80 | ((x >>> 6 ) & 0x3F),
- 0x80 | ( x & 0x3F));
- } else if (x <= 0x1FFFFF) {
- output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
- 0x80 | ((x >>> 12) & 0x3F),
- 0x80 | ((x >>> 6 ) & 0x3F),
- 0x80 | ( x & 0x3F));
- }
- }
-
- return output;
- }
-
- // Gets the low-order bits of a 64-bit decimal number represented in the
- // input string. Because ActionScript Numbers are only accurate up to 53
- // bits when calculating, avoids dealing with any Numbers with more than
- // 32 bits of significance.
- public static function lowOrder64(input:String):int {
- var j:Number = 1;
- var result:int = 0;
- for (var i:int = input.length - 1; i >= 0; i--) {
- var digitValue:Number = int(input.charAt(i)) * j;
- var digitBin:String = digitValue.toString(2);
- if (digitBin.length > 32)
- digitBin = digitBin.substr(digitBin.length - 32, 32);
- result += parseInt(digitBin, 2);
- j *= 10;
- }
- return result;
- }
- }
-}

0 comments on commit 627a7ab

Please sign in to comment.
Something went wrong with that request. Please try again.