FacebookManager = Core.class() function FacebookManager:init(appLoginID, permissions) --helper function for debugging purposes self.fbData = {} --require "json" -- require this somewhere in your main or app setup logic -- print a table's contents - handy for testing data returned by requestComplete event function self:print_r( t ) local print_r_cache={} local function sub_print_r(t,indent) if (print_r_cache[tostring(t)]) then print(indent.."*"..tostring(t)) else print_r_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if (type(val)=="table") then print(indent.."["..pos.."] => "..tostring(t).." {") sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) print(indent..string.rep(" ",string.len(pos)+6).."}") elseif (type(val)=="string") then print(indent.."["..pos..'] => "'..val..'"') else print(indent.."["..pos.."] => "..tostring(val)) end end else print(indent..tostring(t)) end end end if (type(t)=="table") then print(tostring(t).." {") sub_print_r(t," ") print("}") else sub_print_r(t," ") end print() end local a,b,c,d,e=application:getDeviceInfo() local platform = ((a == "Windows" or a == "Mac OS") and "Desktop") if platform == "Desktop" then print("Facebook plugin NOT available.") else print("Platform: "..a) -- proteted call to detemine if facebook is available if pcall(require, "facebook") then require "facebook" print "require facebook: SUCCESS" --set default value facebook._session = false self.appLoginID = appLoginID -- used to deterine if session is valid after facebook login function facebook:isSessionValid() return self._session end if not permissions then print("default permissions") ------------------------------------------------------------------------ --public_profile - implicit but still call from Android / iOS app ----------------------------------------------------------------------- -- id, name, first_name, last_name, age_range, link, gender, locale, picture -- timezone, updated_time, verified -- -- user_friends permission ----------------------------- -- used to get app friends self.basicGetPermissions = {"public_profile", "user_friends"} -------------------- -- publish_actions -------------------- --Provides access to publish Posts, Open Graph actions, achievements, scores and other activity on behalf of a --person using your app. Because this permission lets you publish on behalf of a user please read the Platform --Policies to ensure you understand how to properly use this permission. --Your app does not need to request the publish_actions permission in order to use the -- * Feed Dialog, -- * the Requests Dialog or -- * the Send Dialog ----------- --Review ----------- --If your app requests this permission Facebook WILL have to REVIEW how your app uses it. --When requesting this permission via App Review, please make sure your instructions are easily reproducible by our --team. --Common Usage for this permission -- CAN: Let people explicitly publish content from your app to Facebook from within a custom composer. -- CAN: Seamlessly publish Open Graph stories for people when the user is aware and has appropriate controls. -- DO NOT: Automatically publish stories without the person being aware or having control. -- DO NOT: Publishing via dialogs or social plugins does not require this permission. -- Do not request review of this permission if you're only using Share dialog, -- Feed Dialog, Message Dialog etc, or Social Plugins (e.g. the Like Button.) -- DO NOT: Pre-fill the user message parameter of posts with content a person didn’t create, -- even if the person can edit or remove the content before sharing. self.basicPostPermissions = {"publish_actions"} -- self.permissions = self.basicGetPermissions self.permissions = self.basicPostPermissions else self.permissions = permissions end -------------------------------- -- OPEN URL?? -------------------------------- -- function self:_openURL(e) -- print("open url: "..e.url) -- end -- facebook:addEventListener(Event.OPEN_URL, self._openURL, self) -------------------------------- -- LOGIN/AUTH EVENT LISTENERS -------------------------------- function self:_logInComplete() facebook._session = true print("=FB LOGIN COMPLETE============================================") --Attempts to extend the access token. The access token expires after a certain amount of time and when --you call this method it will be refreshed if it is still active and only after some time has passed since --the last refresh. To ensure that you keep the access token fresh for active users, call this method in your --Application.RESUME event. self._accessToken = facebook:getAccessToken() self._expirationDate = facebook:getExpirationDate() self.fbData["accessToken"] = self._accessToken self.fbData["expirationDate"] = self._expirationDate ----------------------------------------------- -- TESTING -- uncomment to test function ----------------------------------------------- self:getProfile() --self:getInvitableFriends() --self:getAppFriends() --self:sendAppRequests() --self:sendToFeed() --self:share() --self:postPhoto("gfx/store-icon-verb-smash.png", {message = "An example photo"}) --self:postScore(10000) --self:getScores() --????self:requestOAuth() --????self:inviteFriends("Speedy Gram", "my friend", "Play this asome English grammar game.") end facebook:addEventListener(Event.LOGIN_COMPLETE, self._logInComplete, self) function self:_logInError(e) print("login error"..e.error) end facebook:addEventListener(Event.LOGIN_ERROR, self._logInError, self) function self:_logOutComplete() print("logged out complete") end facebook:addEventListener(Event.LOGOUT_COMPLETE, self._logOutComplete, self) function self:_logOutError() print("logged out error") end -- Event.LOGOUT_ERROR is not in autocomplete for ZeroBrane Studio facebook:addEventListener(Event.LOGOUT_ERROR, self._logOutError, self) -------------------------------- -- REQUEST EVENT LISTENERS -------------------------------- function self:_requestComplete(e) print ("REQUEST COMPLETE: "..e.type) -- make sure that you require "json" somewhere in your project, or uncomment line 7 above for testing -- purposes local lastResponse = json.decode(e.response) if type(lastResponse) == "table" then print("Facebook request returned a table.") if (lastResponse.error) then print("Facebook error message: "..lastResponse.error.message) end if (lastResponse.id) then self.fbData["userId"] = lastResponse.id end if (lastResponse.data and e.type == "me/friends") then local data = lastResponse.data self.fbData.userAppFriends = data self:print_r(self.fbData.userAppFriends) end if (lastResponse.data and e.type == "me/invitable_friends") then print("INVITABLE FRIENDS: ") local data = lastResponse.data self.fbData["invitableFriends"] = data end if (lastResponse.name) then self.fbData["userFullName"] = lastResponse.name end if (lastResponse.first_name) then self.fbData["userFirstName"] = lastResponse.first_name end if (lastResponse.last_name) then self.fbData["userLastName"] = lastResponse.last_name end -- application id is returned so build string local response = self.appLoginID.."/scores" if e.type==response then self.fbData["score"] = lastResponse.data end self:print_r(self.fbData) else -- something else was returned print("Something else was returned e.response") end end facebook:addEventListener(Event.REQUEST_COMPLETE, self._requestComplete, self) function self:_requestError(e) print("request error: ", e.type, e.error) end facebook:addEventListener(Event.REQUEST_ERROR, self._requestError, self ) -------------------------------- -- DIALOGUE EVENT LISTENERS -------------------------------- function self:_dialogueError(e) print("dialog error: "..e.type, e.error) if e.type == "apprequests" then print("appRequest error.") elseif e.type == "feed" then print("Feed error.") end end facebook:addEventListener(Event.DIALOG_ERROR, self._dialogueError, self) function self:_dialogueCancel(e) print("dialog cancel") end facebook:addEventListener("dialogCancel", self._dialogueCancel, self) function self:_dialogueComplete(e) print("dialog complete") end facebook:addEventListener(Event.DIALOG_COMPLETE, self._dialogueComplete, self) --log into facebook self:logIn(self.appLoginID, self.permissions) else print("failed to require facebook") end end function self:destroy() self:logOut() facebook:removeEventListener(Event.LOGOUT_COMPLETE, self._logOutComplete, self) facebook:removeEventListener(Event.LOGIN_ERROR, self._logInError, self) facebook:removeEventListener(Event.LOGIN_COMPLETE, self._logInComplete, self) -- facebook:removeEventListener(Event.LOGIN_CANCEL, self._logInCancel, self) facebook:removeEventListener(Event.LOGOUT_ERROR, self._logOutError, self) facebook:removeEventListener(Event.DIALOG_ERROR, self._dialogueError, self) facebook:removeEventListener(Event.DIALOG_COMPLETE, self._dialogueComplete, self) facebook:removeEventListener(Event.REQUEST_COMPLETE, self._reqestComplete, self) facebook:removeEventListener(Event.REQUEST_ERROR, self._requestError, self ) end end ------------------------------------ -- LOGIN / LOGOUT METHODS ------------------------------------ function FacebookManager:logIn(appId, permissions) facebook:login(appId, permissions) end -- Does this work? - Waiting for feedback usecase scenario function FacebookManager:requestOAuth(params) -- I'm not sure how this work yet. if not params then params = {"user_birthday", "user_relationships"} end facebook:dialog("oauth", params) end function FacebookManager:logOut() if facebook:isSessionValid() then -- this will fire a logout event facebook:logout() else print("already logged out") end end ------------------------------------- -- GET ------------------------------------- function FacebookManager:getProfile() local params = {fields="id,name,first_name,last_name"} facebook:getProfile(params) end function FacebookManager:getAppFriends() -- this only returns friends that have the app installed if facebook:isSessionValid() then print("Get application friends...") facebook:get("me/friends") else print("Session not valid. Please login.") end end function FacebookManager:getInvitableFriends() if facebook:isSessionValid() then print("Get invitable friends....") facebook:get("me/invitable_friends") else print("Session not valid. Please login,") end end --------------------------------- -- POST METHODS --------------------------------- function FacebookManager:inviteFriends(message, to, suggestions ) facebook:inviteFriends({message=message, to=to, suggestions=suggestions}) end function FacebookManager:sendAppRequests(params) print("FacebookManager:sendAppRequests(params)") if not params then params = {message = "Check out this awesome app"} end facebook:dialog("apprequests", params) end function FacebookManager:sendToFeed(params) print("FacebookManager:sendAppRequests(params)") if not params then params = {name = "SpeedGram - English Grammar for Android", caption = "Learn English with this great game.", description = "Learn English with this fun and engaging game.", link = "http://wobblemonkey.com", picture = ""} end -- share on your feed -- I noticed that this appears in local language for me facebook:dialog("feed", params) end function FacebookManager:share(params) print("FacebookManager:share(params)") if not params then params = { message = "Some message", link = "http://wobblemonkey.com", picture = "http://www.wobblemonkey.com/images/thumbnail-placeholder.png", name = "some name", caption = "some caption", description = "some description" } end facebook:share(params) end function FacebookManager:postPhoto(photo, params) print("FacebookManager:postPhoto("..photo..")") -- this require if not params then params = {message = "Test"} end facebook:postPhoto(photo, params ) end function FacebookManager:postScore(score) facebook:postScore({score = score}) end function FacebookManager:getScores(params) print("FacebookManager:getScores(params)") facebook:getScores(params) end function FacebookManager:post() facebook:post(path, params) -- general post for any information end function FacebookManager:delete(objID) facebook:delete(objID) --id of the object to delete end function FacebookManager:dialog(dialogType, params) --Description: -- Generate a UI dialog for the desired action. --Syntax: -- Facebook:dialog(action, paramaters) -- Parameters: -- action: (string) The type of dialog to call. Currently supported methods are oauth, feed, and apprequests. -- paramaters: (table, optional) Table representing parameters specific to a particular dialog. facebook:dialog(dialogType, params) end