Advertisement
Guest User

Untitled

a guest
Sep 4th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.92 KB | None | 0 0
  1. ---
  2. --Tools to operate with Google Play Game Services
  3. --@module GooglePlayGameServices
  4. --@alias M
  5. ----
  6. local M = {}
  7.  
  8. local const = require "const"
  9. local FileSystem = require "Libs.FileSystem"
  10.  
  11. local platform = system.getInfo("platform")
  12.  
  13. local gameNetwork = {}
  14. if platform == "android" then
  15.     gameNetwork = require "plugin.gpgs.v2"
  16. elseif platform == "ios" then
  17.     gameNetwork = require "gameNetwork"
  18. end
  19. gameNetwork.hasInitialised = false
  20. gameNetwork.hasLogin = false
  21. gameNetwork.showRating = false
  22. gameNetwork.showAchievements = false
  23.  
  24. local playerId
  25. local playerName
  26. local userAuthListener
  27.  
  28. local initCallback
  29. , networkLoginCallback
  30. , onEventLoadPhoto
  31. , trySendEvent
  32. , loadPlayerCallback
  33. , loadAvatarCallbackGpgs
  34. , tryLoadPhotoGpgs
  35. , isSuccessLoginEvent
  36.  
  37. ---
  38. -- @field isError (<b>bool</b>)
  39. -- @field type (<b>str</b>) "init" || "login".
  40. -- @table EventGPGS
  41.  
  42. ---Authenticate the user in GPGS.
  43. --@func authListener listener to call after login. Generates @EventGPGS
  44. function M.auth(authListener)
  45.     if authListener then
  46.         userAuthListener = authListener
  47.     end
  48.     if not gameNetwork.hasInitialised then
  49.         if platform == "android" then
  50.             gameNetwork.login( { userInitiated = true, listener = networkLoginCallback } )
  51.         elseif platform == "ios" then
  52.             gameNetwork.init( "gamecenter", networkLoginCallback )
  53.         end
  54.     else
  55.         if not M.isLogin() then
  56.             if platform == "android" then
  57.                 gameNetwork.login( {userInitiated=true, listener=networkLoginCallback} )
  58.             end
  59.         else
  60.             trySendEvent({type = "login", isError = false})
  61.         end
  62.     end
  63. end
  64.  
  65. ---Logout from GPGS account
  66. function M.logout()
  67.     if (platform == 'android') then
  68.         pcall(gameNetwork.logout)
  69.         gameNetwork.hasInitialised = false
  70.     end
  71.     gameNetwork.hasLogin = false
  72. end
  73.  
  74. ---Shows the rating table
  75. function M.showLeaderboards()
  76.     if ( system.getInfo("environment") == "simulator") then
  77.         print( "GooglePlayGameServices.showLeaderboards() is not available on the simulator" )
  78.    
  79.     elseif platform == "android" then
  80.         if M.isLogin() then
  81.             gameNetwork.leaderboards.show()
  82.         else
  83.             M.auth(userAuthListener)
  84.             gameNetwork.showRating = true
  85.         end
  86.    
  87.     elseif platform == "ios" then
  88.         gameNetwork.show( "leaderboards", { leaderboard = {timeScope="AllTime"} } )
  89.     end
  90.    
  91.     return true
  92. end
  93.  
  94. ---Shows user achievements
  95. function M.showAchievements()
  96.     if ( system.getInfo("environment") == "simulator") then
  97.         print( "GooglePlayGameServices.showAchievements() is not available on the simulator" )
  98.    
  99.     elseif platform == "android" then
  100.         if M.isLogin() then
  101.             gameNetwork.achievements.show()
  102.         else
  103.             M.auth(userAuthListener)
  104.             gameNetwork.showAchievements = true
  105.         end
  106.    
  107.     elseif platform == "ios" then
  108.         gameNetwork.show( "achievements" )
  109.     end
  110.    
  111.     return true
  112. end
  113.  
  114. ---Add user scores
  115. --@int score value
  116. function M.setHighscore(score)
  117.     local function requestCallback( event )
  118.         if ( event.type == "setHighScore" ) then
  119.             print("score updated")
  120.         end
  121.  
  122.         if not event.isError then
  123.             if event.name == "submit" then
  124.                 print("score updated")
  125.             end
  126.         else
  127.             print(event.errorCode, event.errorMessage)
  128.         end
  129.     end
  130.    
  131.     if M.isLogin() then
  132.         if platform == "android" then
  133.             gameNetwork.leaderboards.submit( {leaderboardId=const.GPGS_RATING_ID, score=score, listener=requestCallback} )
  134.         elseif platform == "ios" then
  135.             gameNetwork.request( "setHighScore", { localPlayerScore = { category=const.GPGS_RATING_ID, value=score }, listener = requestCallback} )
  136.         end
  137.     end
  138. end
  139.  
  140. ---Unlock user achievement
  141. --@string achievement_id - key to specific achievement
  142. --@usage gpgs.unlockAchievement( "GPGS_unique_key" )
  143. function M.unlockAchievement(achievement_id)
  144.     local function requestCallback( event )
  145.         if ( event.type == "unlockAchievement" ) then
  146.             print "achievement updated"
  147.         end
  148.  
  149.         if not event.isError then
  150.             if event.name == "submit" then
  151.                 print("achievement updated")
  152.             end
  153.         else
  154.             print(event.errorCode, event.errorMessage)
  155.         end
  156.     end
  157.  
  158.     if M.isLogin() then
  159.         if platform == "android" then
  160.             gameNetwork.achievements.unlock( {achievementId=achievement_id, listener=requestCallback} )
  161.         elseif platform == "ios" then
  162.             gameNetwork.request( "unlockAchievement",{achievement={ identifier=achievement_id, percentComplete=100, showsCompletionBanner=true }, listener=requestCallback} )
  163.         end
  164.     end
  165. end
  166.  
  167. --- To load achievements data from google/apple and execute function
  168. --@table requestCallback it listener executed after get data from server
  169. function M.loadAchievements(requestCallback)
  170.     if ( system.getInfo("environment") == "simulator") then
  171.         print( "GooglePlayGameServices.loadAchievements() is not available on the simulator" )
  172.         return
  173.     end
  174.  
  175.     if M.isLogin() then
  176.         if platform == "android" then
  177.             gameNetwork.achievements.load({ reload=true, listener=requestCallback })
  178.         elseif platform == "ios" then
  179.             gameNetwork.request("loadAchievementDescriptions", { listener=requestCallback })
  180.         end
  181.     end
  182. end
  183.  
  184. --- To load image from google/ios by uri/identifier
  185. --@field uri  <b>string</b> Image resource URI, it must be something that was retrieved from another call to Google Play services. (or identifer from apple)
  186. --@field filename  <b>string</b> Path for the to be saved PNG image file.
  187. --@field baseDir  <b>Constant</b> Constant corresponding to the base directory where the file will be located. Default value is system.CachesDirectory if the parameter is not provided.
  188. --@field listener  <b>Listener</b> Receives loadImage event.
  189. --@table params it listener executed after get data from server
  190. function M.loadImage(params)
  191.     if platform == "android" then
  192.         gameNetwork.loadImage(params)
  193.    
  194.     elseif platform == "ios" then
  195.         gameNetwork.request("loadAchievementImage", {
  196.             achievementDescription = {
  197.                 identifier = params.uri
  198.             },
  199.             listener = function(event)
  200.                 if not event.data then
  201.                     if params.listener then
  202.                         params.listener()
  203.                     end
  204.                 else
  205.                     display.save(event.data.image, {
  206.                         filename = params.filename,
  207.                         baseDir = system.CachesDirectory,
  208.                     })
  209.                     event.data.image:removeSelf()
  210.  
  211.                     if params.listener then
  212.                         params.listener()
  213.                     end
  214.                 end
  215.             end
  216.         })
  217.     end
  218. end
  219.  
  220. function initCallback( event )
  221.     if not event.isError then
  222.         gameNetwork.hasInitialised = true
  223.         gameNetwork.login( { userInitiated = true, listener = networkLoginCallback } )
  224.         trySendEvent({type = "init", isError = false})
  225.     else
  226.         native.showAlert( "Init failed!", event.errorMessage, { "OK" } )
  227.         trySendEvent({type = "init", isError = true})
  228.     end
  229. end
  230.  
  231. function networkLoginCallback( event )
  232.     if isSuccessLoginEvent(event) then
  233.         gameNetwork.hasInitialised = true
  234.         gameNetwork.hasLogin = true
  235.        
  236.         if gameNetwork.showRating == true then
  237.             gameNetwork.showRating = false
  238.             M.showLeaderboards()
  239.        
  240.         elseif gameNetwork.showAchievements == true then
  241.             gameNetwork.showAchievements = false
  242.             M.showAchievements()       
  243.         end
  244.  
  245.         if platform == "android" then
  246.             gameNetwork.players.load( { listener = loadPlayerCallback} )
  247.         elseif platform == "ios" then
  248.             gameNetwork.request( "loadLocalPlayer", { listener = loadPlayerCallback } )    
  249.         end
  250.     else
  251.         trySendEvent({isError = true})
  252.     end
  253.        
  254.     return true
  255. end
  256.  
  257. function isSuccessLoginEvent(event)
  258.     local result = false
  259.    
  260.     if (platform == 'android' and not event.isError and event.phase == 'logged in') then
  261.         result = true
  262.        
  263.     elseif (platform == 'ios' and event.data) then
  264.         result = true
  265.     end
  266.     return result
  267. end
  268.  
  269. function loadPlayerCallback(event)
  270.     local anroidPlayerPhoto
  271.     if(event.isError) then
  272.         trySendEvent({type = 'login', isError = true})
  273.         return
  274.     else
  275.         if (platform == "android") then
  276.             player = event.players[1]
  277.             anroidPlayerPhoto = player.largeImageUri
  278.  
  279.             playerName = player.name
  280.             playerId = player.id
  281.            
  282.         elseif platform == "ios" then
  283.             playerId = event.data.playerID
  284.             playerName = event.data.alias
  285.         end
  286.  
  287.         trySendEvent({type = "login", isError = false, playerId = playerId, playerName = playerName})
  288.     end
  289.    
  290.     if (not M.isExistPlayerPhoto()) then
  291.         if platform == "android" then
  292.             if (anroidPlayerPhoto) then
  293.                 tryLoadPhotoGpgs(anroidPlayerPhoto)
  294.             end
  295.         elseif platform == "ios" then
  296.             gameNetwork.request( "localPlayerPhoto", {playerID=playerId, size="Normal", listener=onEventLoadPhoto} )
  297.         end
  298.     end
  299. end
  300.  
  301. function tryLoadPhotoGpgs(imageUri)
  302.     if (imageUri) then
  303.         gameNetwork.loadImage({
  304.             uri = imageUri
  305.             , filename = const.GPGS_AVATAR_NAME
  306.             , baseDir = system.CachesDirectory
  307.             , listener = loadAvatarCallbackGpgs
  308.         })
  309.     end
  310. end
  311.  
  312. function loadAvatarCallbackGpgs(event)
  313.     if ( event.isError ) then
  314.         print( "Network error - download failed" )
  315.     else
  316.         local fileName, baseDir = M.getPlayerPhotoInfo()
  317.         trySendEvent({type = 'loadAvatar', isError = false, fileName = fileName, baseDir = baseDir})
  318.     end
  319. end
  320.  
  321. function onEventLoadPhoto(event)
  322.     if event.data.photo then
  323.         display.save(event.data.photo, {
  324.             filename = const.GPGS_AVATAR_NAME,
  325.             baseDir = system.CachesDirectory,
  326.         })
  327.         local fileName, baseDir = M.getPlayerPhotoInfo()
  328.         trySendEvent({type = 'loadAvatar', isError = false, fileName = fileName, baseDir = baseDir})
  329.     end
  330. end
  331.  
  332. function trySendEvent(event)
  333.     if (userAuthListener) then
  334.         userAuthListener(event)
  335.     end
  336. end
  337.  
  338. ---Verifies that the module is initialized and the user is connected to the services
  339. --@treturn bool
  340. function M.isLogin()
  341.     local result = false
  342.     if (gameNetwork.hasInitialised == true and gameNetwork.hasLogin == true) then
  343.         result = true
  344.     end
  345.     return result  
  346. end
  347.  
  348. ---Return player name in GameNetwork
  349. --@treturn string
  350. function M.getPlayerName()
  351.     return playerName
  352. end
  353.  
  354. ---Return player identifier in GameNetword
  355. --@treturn string
  356. function M.getPlayerId()
  357.     return playerId
  358. end
  359.  
  360. ---Сhecks the file has been downloaded
  361. --@treturn bool
  362. function M.isExistPlayerPhoto()
  363.     local result = false
  364.     if (FileSystem:fileIsExists(const.GPGS_AVATAR_NAME, system.CachesDirectory)) then
  365.         result = true
  366.     end
  367.     return result
  368. end
  369.  
  370. ---Return information about file player photo
  371. --@treturn string filename
  372. --@treturn string system directory
  373. function M.getPlayerPhotoInfo()
  374.     return const.GPGS_AVATAR_NAME, system.CachesDirectory
  375. end
  376.  
  377.  
  378. return M
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement