Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 5.70 KB | None | 0 0
  1. --[[
  2.     * SERVER CONNECTOR LOGICS
  3.     * If a form object is passed to the query() function then
  4.     * query params are generated by a special query parser entity
  5.     * that knows how to build a uri and what data to include in it and
  6.     * other params. Also it knows whether any other special methods,
  7.     * like websockets or multipart should be called.
  8.     * If a form object is passed to be filled by the response
  9.     * it is parsed by the form parser and then filled by the form filler,
  10.     * another entity that knows how to deal with forms.
  11.     * If no form is passed as a source to build request from,
  12.     * the request is created by its name according to the schema
  13.     * If no form is passed to be filled, then, if the decoded response
  14.     * object has a corresponding activity, according to the schema
  15.     * this activity is called with all non-auxiliary fields of the response
  16.     * as its params. Whether there is such an activity or not,
  17.     * a user handler function passed as a param to the query will be
  18.     * executed, thus allowing users to make queries result in custom
  19.     * events, in addition to the ability to block activities from
  20.     * being generated]]
  21.  
  22.  
  23. local json = require("json")
  24. local ResponseParser = require("src.framework.network.ResponseParser")
  25.  
  26. local serverConnector = {}
  27.  
  28. local instance = false
  29.  
  30. local MAX_ATTEMPTS_COUNT = 5
  31. local MAX_AWAIT_TIME = 300
  32.  
  33. local SUPPORTED_LANGS = {
  34.     "PHP",
  35.     "PHP/laravel",
  36.     "RUBY",
  37.     "RUBY/rails",
  38.     "JAVA",
  39.     "JAVA/spring"
  40. }
  41.  
  42. local REQUEABLE_RESPONSE_CODES = {
  43.     "404",
  44. }
  45.  
  46. local DEFAULT_LANG = "PHP/laravel"
  47.  
  48. local function validateEnum(enum, value)
  49.     for k, v in pairs(enum) do
  50.         if v == value then
  51.             return true
  52.         end
  53.     end
  54.    
  55.     return false
  56. end
  57.  
  58. serverConnector.new = function(p)
  59.     if instance then
  60.         return instance
  61.     else
  62.         local serverConnectorObject = {}
  63.        
  64.         local URL = assert(p.url and type(p.url) == "string" and p.url, "the URL parameter must be a string!")
  65.         local isSecure = p.isSecure and type(p.isSecure) == "boolean" and p.isSecure or false
  66.         local serverMethodParam = p.serverPage and type(p.serverPage) == "string" and p.serverPage or "query"
  67.         local serverLang = p.serverLang and type(p.serverLang) == "string" and validateEnum(p.serverLang, SUPPORTED_LANGS) or DEFAULT_LANG
  68.        
  69.        
  70.         local API = serverLang == "PHP/laravel" and "api.php/"
  71.        
  72.         local queries = {}
  73.        
  74.         local function urlMaker(name, params)
  75.             local protocol = isSecure and "https://" or "http://"
  76.             local paramsString = ""
  77.            
  78.             for k, v in params do
  79.                 paramsString = "&" .. paramsString .. k .. "=" .. serialize(v)
  80.             end
  81.            
  82.             return tostring(protocol .. URL .. "/" ..API .. serverMethodParam .. query .. paramsString)
  83.         end
  84.        
  85.         local function networkListener(event, data)
  86.             if event.isError then
  87.            
  88.             else
  89.                 local r = event.response
  90.                
  91.                 local responseCode = parseHeaders(event.response).code
  92.                 local isResponseValid = validateResponseCode(responseCode)
  93.                
  94.                 if isResponseValid then
  95.                     local decoded, pos, msg = json.decode(r)
  96.                    
  97.                     if not decoded then
  98.                         if DEBUG_MODE then
  99.                             native.showAlert( "The response from the url " .. event.url .. " did not match json format and could not be decoded", { "ok" } )
  100.                         else
  101.                             if data.attemptCount < MAX_ATTEMPTS_COUNT then
  102.                                 data.attemptCount = data.attemptCount + 1
  103.                                 serverConnectorObject:query(data) --perform another attempt to reach the server and get everything
  104.                             end
  105.                         end
  106.                     else
  107.                         local decodedResponseObject = ResponseParser.validateResponse(event, decoded)--either do things according to the server schema or call the user handler
  108.                        
  109.                         if decodedResponseObject.hasCorrespondingActivity then
  110.                             local activity = require(decodedResponseObject.correspondingActivity).new{
  111.                                 layoutName = getLayoutName(decodedResponseObject.correspondingActivity),
  112.                                 params = decodedResponseObject.params
  113.                             }
  114.                         end
  115.                     end
  116.                 elseif validateEnum(REQUEABLE_RESPONSE_CODES, responseCode) then
  117.                     if data.attemptCount < MAX_ATTEMPTS_COUNT then
  118.                         data.attemptCount = data.attemptCount + 1
  119.                         serverConnectorObject:query(data)
  120.                     end
  121.                 end
  122.             end
  123.         end
  124.        
  125.         function serverConnector:isReachable(url, listener)
  126.             if network.canDetectNetworkStatusChanges then
  127.                 network.setStatusListener( url, listener )
  128.                
  129.                 return true
  130.             else
  131.                 if DEBUG_MODE then
  132.                     native.showAlert( "Network status error!", "The url " .. url .. " could not be reached", { "ok" } )
  133.                 else
  134.                     return false
  135.                 end
  136.             end
  137.         end
  138.        
  139.         function serverConnectorObject:query(data)
  140.             data.attemptCount = data.attemptCount and data.attemptCount or 1
  141.            
  142.             local queryObject
  143.            
  144.             if queryType == "default" then
  145.                 queryObject = network.request
  146.             elseif queryType == "download" then
  147.                 queryObject = network.download
  148.             elseif queryType == "upload" then
  149.                 queryObject = network.upload
  150.             end
  151.            
  152.             local queryParams = {}
  153.            
  154.             queryParams.url = urlMaker(name, params)
  155.             queryParams.method = method
  156.             queryParams.listener = function(event) networkListener(event, data) end
  157.             queryParams.queryParams = queryParamsMaker(name)
  158.             queryParams.filename = filename
  159.             queryParams.baseDir = baseDir
  160.            
  161.             queries[name] = queryObject( queryParams.url, queryParams.method, queryParams.listener, queryParams.queryParams, queryParams.filename, queryParams.baseDir )
  162.            
  163.             return queries[name]
  164.         end
  165.        
  166.         function serverConnectorObject:cancelQuery(query)
  167.             network.cancel(query)
  168.         end
  169.        
  170.         function serverConnectorObject:cancelQueryByName(name)
  171.             if queries[name] then
  172.                 network.cancel(queries[name])
  173.                
  174.                 return true
  175.             else
  176.                 return false
  177.             end
  178.         end
  179.        
  180.        
  181.         return serverConnectorObject
  182.     end
  183. end
  184.  
  185. return serverConnector
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement