22 |
23 |
24 |
25 |
26 |
27 |
28 | ## About The Project
29 |
30 | This is a library for creating RESTful web endpoints in FiveM server.
31 |
32 |
33 |
34 |
35 | ## Features
36 |
37 | - Familiar API to those that have worked with express.js
38 | - Automatic conversion of tables to data in responses
39 | - Object-Oriented approach makes things easier and self-documenting
40 | - Middleware functions can be used! (see example)
41 | - Supports only `GET` and `POST` for the time being
42 |
43 |
44 |
45 | ## Getting Started
46 |
47 | Simply download the [Latest Release](https://github.com/Cyntaax/fivem-webbed/releases/latest), place into your resources directory and start!
48 |
49 | ### Prerequisites
50 |
51 | - Just a basic understanding of Lua and HTTP
52 |
53 | ### Configuration
54 |
55 | - None Required outside of starting in the server.cfg
56 |
57 | ```ini
58 |
59 | ... (other resources)
60 | ensure fivem-webbed
61 | ```
62 |
63 | ## Usage
64 | The resource alone does nothing. It is a library to be included with another resource to create http endpoints/server files:
65 |
66 | ```lua
67 | --- fxmanifest.lua
68 |
69 | server_scripts {
70 | '@fivem-webbed/server/server.lua',
71 | 'server/server.lua'
72 | }
73 | ```
74 |
75 |
76 | ```lua
77 | --- assume resource is named (api). Looks nice for the URL
78 | --- server/server.lua
79 |
80 | local player = Router.new()
81 |
82 | player:Get("/:playerId", function(req, res)
83 | local target = tonumber(req:Param("playerId"))
84 | print('Player name', GetPlayerName(target))
85 | return 200, {
86 | name = GetPlayerName(target),
87 | target = target
88 | }
89 | end)
90 |
91 | Server.use("/players", player)
92 | Server.listen()
93 | ```
94 |
95 | ```bash
96 | curl -X GET http://localhost:30120/api/players/1
97 | ```
98 |
99 | ```json
100 | {
101 | "name": "Cyntaax",
102 | "target": 1
103 | }
104 | ```
105 |
106 |
107 | ## Roadmap
108 |
109 | - Include some pre-made middlewares
110 | - Lots of examples for different tasks
111 |
112 | See the [open issues](https://github.com/cyntaax/fivem-webbed/issues) for a list of proposed features (and known issues).
113 |
114 |
115 |
116 |
117 | ## Contributing
118 |
119 | Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.
120 |
121 | 1. Fork the Project
122 | 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
123 | 3. Commit your Changes (`git commit -m 'chore: added some amazing feature'`)
124 | 4. Push to the Branch (`git push origin feature/AmazingFeature`)
125 | 5. Open a Pull Request
126 |
127 |
128 |
129 |
130 | ## License
131 |
132 | Distributed under the MIT License. See `LICENSE` for more information.
133 |
134 | ## Notable Mentions
135 |
136 | - [Async](https://github.com/esx-framework/async) - Really helped for dealing with running all of the middlewares
137 |
138 |
139 |
140 |
141 | ## Contact
142 |
143 | Cyntaax - [@cyntaax](https://twitter.com/cyntaax) - cyntaax@gmail.com
144 |
145 | Project Link: [https://github.com/cyntaax/fivem-webbed](https://github.com/cyntaax/fivem-webbed)
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 | [contributors-shield]: https://img.shields.io/github/contributors/cyntaax/fivem-webbed.svg?style=for-the-badge
156 | [contributors-url]: https://github.com/cyntaax/fivem-webbed/graphs/contributors
157 | [forks-shield]: https://img.shields.io/github/forks/cyntaax/fivem-webbed.svg?style=for-the-badge
158 | [forks-url]: https://github.com/cyntaax/fivem-webbed/network/members
159 | [stars-shield]: https://img.shields.io/github/stars/cyntaax/fivem-webbed.svg?style=for-the-badge
160 | [stars-url]: https://github.com/cyntaax/fivem-webbed/stargazers
161 | [issues-shield]: https://img.shields.io/github/issues/cyntaax/fivem-webbed.svg?style=for-the-badge
162 | [issues-url]: https://github.com/cyntaax/fivem-webbed/issues
163 | [license-shield]: https://img.shields.io/github/license/cyntaax/fivem-webbed.svg?style=for-the-badge
164 | [license-url]: https://github.com/cyntaax/fivem-webbed/blob/master/LICENSE
165 | [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
166 | [linkedin-url]: https://linkedin.com/in/cyntaax
167 |
--------------------------------------------------------------------------------
/src/server/Server.lua:
--------------------------------------------------------------------------------
1 | Server = {
2 | ---@type Router[]
3 | Routes = {},
4 | Middlewares = {},
5 | ---@type ServerSession[]
6 | Sessions = {}
7 | }
8 |
9 | function Server:Session(name)
10 | for k,v in pairs(self.Sessions) do
11 | if v.Name == name then
12 | self.Sessions[k] = ServerSession.new(name)
13 | return
14 | end
15 | end
16 |
17 | table.insert(self.Sessions, ServerSession.new(name))
18 | end
19 |
20 | function Server.listen()
21 | SetHttpHandler(function(req, res)
22 | print(req.method .. " => " .. req.path)
23 | ---@type string
24 | local path = req.path
25 | local method = req.method
26 | if method == "OPTIONS" then
27 | print('sending cors headers')
28 | local response = Response.new(res)
29 | response:SetHeader("Access-Control-Allow-Origin", "*")
30 | response:Send("", 200)
31 | return
32 | end
33 | for k,v in pairs(Server.Routes) do
34 | for b,z in pairs(v.Paths) do
35 | local data = exports["fivem-webbed"]:matchRoute(z._path, path)
36 | if data then
37 | if type(data) == "table" then
38 | print(json.encode(data))
39 | end
40 | end
41 | if data then
42 | if z.method == method then
43 | local response = Response.new(res)
44 | local request = Request.new(req)
45 | if z.pathData then
46 | for u,x in pairs(data) do
47 | request:SetParam(u, decodeURI(x))
48 | end
49 | end
50 |
51 | local tasks = {}
52 |
53 | for midx, middleware in pairs(v.Middlewares) do
54 | table.insert(tasks, function(cb)
55 | middleware(request, response, cb)
56 | end)
57 | end
58 |
59 | Citizen.Await(PromiseAsync:Series(tasks))
60 |
61 | if z.method == "POST" then
62 | req.setDataHandler(function(data)
63 | request._Body = json.decode(data) or ""
64 | local status, ret = z.handler(request, response)
65 | if status ~= nil then
66 | if type(status) == "number" then
67 | if type(ret) ~= "table" then
68 | response:Send(ret, status)
69 | else
70 | response:SetHeader("Content-Type", "application/json")
71 | response:Send(json.encode(ret), status)
72 | end
73 | end
74 | end
75 | end)
76 | else
77 | local status, ret = z.handler(request, response)
78 | if status ~= nil then
79 | if type(status) == "number" then
80 | if type(ret) ~= "table" then
81 | response:Send(ret, status)
82 | else
83 | response:SetHeader("Content-Type", "application/json")
84 | response:Send(json.encode(ret), status)
85 | end
86 | end
87 | end
88 | end
89 | return
90 | end
91 | end
92 | end
93 | end
94 | local response = Response.new(res)
95 | local request = Request.new(req)
96 | response:Send("Not Found: " .. request:Method() .. " " .. request:Path(), 404)
97 | end)
98 | end
99 |
100 | --- Specifies a handler/middleware for the server to use
101 | ---@param path string The path for this handler
102 | ---@param handler Router The router to handle this path
103 | function Server.use(path, handler)
104 | if type(path) == "string" then
105 | if type(handler) == "function" then
106 |
107 | elseif type(handler) == "table" then
108 | local mt = getmetatable(handler)
109 | if mt == nil then print("^1Error^0: " + "failed to load route " + path + "expected route class") return end
110 | if mt.__call() ~= "Router" then print("^1Error^0: " + "failed to load route " + path + "expected route class") return end
111 | for k,v in pairs(handler.Paths) do
112 | print("Mounting: ", path .. v._path)
113 | v.path = path .. v.path
114 | v._path = path .. v._path
115 | end
116 | table.insert(Server.Routes, handler)
117 | end
118 | end
119 | end
120 |
--------------------------------------------------------------------------------
/src/server/path.js:
--------------------------------------------------------------------------------
1 | /*! For license information please see path.js.LICENSE.txt */
2 | (()=>{var e={489:(e,t)=>{"use strict";t.parse=function(e,t){if("string"!=typeof e)throw new TypeError("argument str must be a string");for(var n={},i=t||{},p=e.split(o),s=i.decode||r,u=0;u{e.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}},26:e=>{"use strict";e.exports=function(e,t){var r=(t=t||{}).cacheKey||function(e){return 1===arguments.length&&(null==e||"function"!=typeof e&&"object"!=typeof e)?e:JSON.stringify(arguments)},n=function(){var o=n.__cache__,i=r.apply(null,arguments);if(o.has(i)){var a=o.get(i);if("number"!=typeof t.maxAge||Date.now(){var n=r(826);e.exports=function e(t,r,o){return n(r=r||[])?o||(o={}):(o=r,r=[]),t instanceof RegExp?function(e,t){var r=e.source.match(/\((?!\?)/g);if(r)for(var n=0;n{const n=r(357);e.exports=function(e){return n.equal(typeof e,"string"),e.trim().replace(/[\?|#].*$/,"").replace(/^(?:https?\:)\/\//,"").replace(/^(?:[\w+(?:-\w+)+.])+(?:[\:0-9]{4,5})?/,"").replace(/\/$/,"")}},687:e=>{e.exports=function(e,t){1==arguments.length&&(t=e[1],e=e[0]);for(var r={},n=0;n{"use strict";e.exports=require("assert")}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}(()=>{"use strict";let e=r(218),t=r(779),n=r(26),o=r(687),i=r(489);const a=n(((r,n)=>{let i=[],a=t(r,i,{end:!0}).exec(e(n)),p=i.map((e=>e.name));return a?o(p,a.slice(1)):void 0}));global.exports("matchRoute",((e,t)=>{const r=a(e,t);if(r)return r})),global.exports("parseCookie",(e=>i.parse(e))),global.exports("createCookie",((e,t)=>i.serialize(e,t)))})()})();
3 |
--------------------------------------------------------------------------------
/src/server/util.lua:
--------------------------------------------------------------------------------
1 | base64 = {}
2 |
3 | local extract = _G.bit32 and _G.bit32.extract -- Lua 5.2/Lua 5.3 in compatibility mode
4 | if not extract then
5 | if _G.bit then -- LuaJIT
6 | local shl, shr, band = _G.bit.lshift, _G.bit.rshift, _G.bit.band
7 | extract = function( v, from, width )
8 | return band( shr( v, from ), shl( 1, width ) - 1 )
9 | end
10 | elseif _G._VERSION == "Lua 5.1" then
11 | extract = function( v, from, width )
12 | local w = 0
13 | local flag = 2^from
14 | for i = 0, width-1 do
15 | local flag2 = flag + flag
16 | if v % flag2 >= flag then
17 | w = w + 2^i
18 | end
19 | flag = flag2
20 | end
21 | return w
22 | end
23 | else -- Lua 5.3+
24 | extract = load[[return function( v, from, width )
25 | return ( v >> from ) & ((1 << width) - 1)
26 | end]]()
27 | end
28 | end
29 |
30 |
31 | function base64.makeencoder( s62, s63, spad )
32 | local encoder = {}
33 | for b64code, char in pairs{[0]='A','B','C','D','E','F','G','H','I','J',
34 | 'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y',
35 | 'Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
36 | 'o','p','q','r','s','t','u','v','w','x','y','z','0','1','2',
37 | '3','4','5','6','7','8','9',s62 or '+',s63 or'/',spad or'='} do
38 | encoder[b64code] = char:byte()
39 | end
40 | return encoder
41 | end
42 |
43 | function base64.makedecoder( s62, s63, spad )
44 | local decoder = {}
45 | for b64code, charcode in pairs( base64.makeencoder( s62, s63, spad )) do
46 | decoder[charcode] = b64code
47 | end
48 | return decoder
49 | end
50 |
51 | local DEFAULT_ENCODER = base64.makeencoder()
52 | local DEFAULT_DECODER = base64.makedecoder()
53 |
54 | local char, concat = string.char, table.concat
55 |
56 | function base64.encode( str, encoder, usecaching )
57 | encoder = encoder or DEFAULT_ENCODER
58 | local t, k, n = {}, 1, #str
59 | local lastn = n % 3
60 | local cache = {}
61 | for i = 1, n-lastn, 3 do
62 | local a, b, c = str:byte( i, i+2 )
63 | local v = a*0x10000 + b*0x100 + c
64 | local s
65 | if usecaching then
66 | s = cache[v]
67 | if not s then
68 | s = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[extract(v,0,6)])
69 | cache[v] = s
70 | end
71 | else
72 | s = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[extract(v,0,6)])
73 | end
74 | t[k] = s
75 | k = k + 1
76 | end
77 | if lastn == 2 then
78 | local a, b = str:byte( n-1, n )
79 | local v = a*0x10000 + b*0x100
80 | t[k] = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[64])
81 | elseif lastn == 1 then
82 | local v = str:byte( n )*0x10000
83 | t[k] = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[64], encoder[64])
84 | end
85 | return concat( t )
86 | end
87 |
88 | function base64.decode( b64, decoder, usecaching )
89 | decoder = decoder or DEFAULT_DECODER
90 | local pattern = '[^%w%+%/%=]'
91 | if decoder then
92 | local s62, s63
93 | for charcode, b64code in pairs( decoder ) do
94 | if b64code == 62 then s62 = charcode
95 | elseif b64code == 63 then s63 = charcode
96 | end
97 | end
98 | pattern = ('[^%%w%%%s%%%s%%=]'):format( char(s62), char(s63) )
99 | end
100 | b64 = b64:gsub( pattern, '' )
101 | local cache = usecaching and {}
102 | local t, k = {}, 1
103 | local n = #b64
104 | local padding = b64:sub(-2) == '==' and 2 or b64:sub(-1) == '=' and 1 or 0
105 | for i = 1, padding > 0 and n-4 or n, 4 do
106 | local a, b, c, d = b64:byte( i, i+3 )
107 | local s
108 | if usecaching then
109 | local v0 = a*0x1000000 + b*0x10000 + c*0x100 + d
110 | s = cache[v0]
111 | if not s then
112 | local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40 + decoder[d]
113 | s = char( extract(v,16,8), extract(v,8,8), extract(v,0,8))
114 | cache[v0] = s
115 | end
116 | else
117 | local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40 + decoder[d]
118 | s = char( extract(v,16,8), extract(v,8,8), extract(v,0,8))
119 | end
120 | t[k] = s
121 | k = k + 1
122 | end
123 | if padding == 1 then
124 | local a, b, c = b64:byte( n-3, n-1 )
125 | local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40
126 | t[k] = char( extract(v,16,8), extract(v,8,8))
127 | elseif padding == 2 then
128 | local a, b = b64:byte( n-3, n-2 )
129 | local v = decoder[a]*0x40000 + decoder[b]*0x1000
130 | t[k] = char( extract(v,16,8))
131 | end
132 | return concat( t )
133 | end
134 |
135 | PromiseAsync = {}
136 |
137 | function PromiseAsync:Series(tasks)
138 | local p = promise:new()
139 | Async.series(tasks, function(results)
140 | p:resolve(results)
141 | end)
142 | return p
143 | end
144 |
145 | function PatternToRoute(input)
146 | if input == "/" then input = "" end
147 | local routeData = {
148 | _route = input,
149 | route = input,
150 | _path = input,
151 | path = input,
152 | params = {}
153 | }
154 | local matcher = input
155 | for k,v in input:gmatch "/(:%w+)" do
156 | local rawname = k:gsub(":", "")
157 | table.insert(routeData.params, {
158 | name = rawname
159 | })
160 | matcher, _ = matcher:gsub(k, "(%%w+)", 1)
161 | end
162 | routeData._route = matcher
163 | routeData.route = matcher
164 | return routeData
165 | end
166 |
167 |
168 | local function decodeCharacter(code)
169 | return string.char(tonumber(code, 16))
170 | end
171 | function decodeURI(s)
172 | local str = s:gsub("+", " "):gsub('%%(%x%x)', decodeCharacter)
173 | return str
174 | end
--------------------------------------------------------------------------------
/src/server/Async.lua:
--------------------------------------------------------------------------------
1 | --[[
2 | GNU GENERAL PUBLIC LICENSE
3 | Version 3, 29 June 2007
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 | Preamble
8 | The GNU General Public License is a free, copyleft license for
9 | software and other kinds of works.
10 | The licenses for most software and other practical works are designed
11 | to take away your freedom to share and change the works. By contrast,
12 | the GNU General Public License is intended to guarantee your freedom to
13 | share and change all versions of a program--to make sure it remains free
14 | software for all its users. We, the Free Software Foundation, use the
15 | GNU General Public License for most of our software; it applies also to
16 | any other work released this way by its authors. You can apply it to
17 | your programs, too.
18 | When we speak of free software, we are referring to freedom, not
19 | price. Our General Public Licenses are designed to make sure that you
20 | have the freedom to distribute copies of free software (and charge for
21 | them if you wish), that you receive source code or can get it if you
22 | want it, that you can change the software or use pieces of it in new
23 | free programs, and that you know you can do these things.
24 | To protect your rights, we need to prevent others from denying you
25 | these rights or asking you to surrender the rights. Therefore, you have
26 | certain responsibilities if you distribute copies of the software, or if
27 | you modify it: responsibilities to respect the freedom of others.
28 | For example, if you distribute copies of such a program, whether
29 | gratis or for a fee, you must pass on to the recipients the same
30 | freedoms that you received. You must make sure that they, too, receive
31 | or can get the source code. And you must show them these terms so they
32 | know their rights.
33 | Developers that use the GNU GPL protect your rights with two steps:
34 | (1) assert copyright on the software, and (2) offer you this License
35 | giving you legal permission to copy, distribute and/or modify it.
36 | For the developers' and authors' protection, the GPL clearly explains
37 | that there is no warranty for this free software. For both users' and
38 | authors' sake, the GPL requires that modified versions be marked as
39 | changed, so that their problems will not be attributed erroneously to
40 | authors of previous versions.
41 | Some devices are designed to deny users access to install or run
42 | modified versions of the software inside them, although the manufacturer
43 | can do so. This is fundamentally incompatible with the aim of
44 | protecting users' freedom to change the software. The systematic
45 | pattern of such abuse occurs in the area of products for individuals to
46 | use, which is precisely where it is most unacceptable. Therefore, we
47 | have designed this version of the GPL to prohibit the practice for those
48 | products. If such problems arise substantially in other domains, we
49 | stand ready to extend this provision to those domains in future versions
50 | of the GPL, as needed to protect the freedom of users.
51 | Finally, every program is threatened constantly by software patents.
52 | States should not allow patents to restrict development and use of
53 | software on general-purpose computers, but in those that do, we wish to
54 | avoid the special danger that patents applied to a free program could
55 | make it effectively proprietary. To prevent this, the GPL assures that
56 | patents cannot be used to render the program non-free.
57 | The precise terms and conditions for copying, distribution and
58 | modification follow.
59 | TERMS AND CONDITIONS
60 | 0. Definitions.
61 | "This License" refers to version 3 of the GNU General Public License.
62 | "Copyright" also means copyright-like laws that apply to other kinds of
63 | works, such as semiconductor masks.
64 | "The Program" refers to any copyrightable work licensed under this
65 | License. Each licensee is addressed as "you". "Licensees" and
66 | "recipients" may be individuals or organizations.
67 | To "modify" a work means to copy from or adapt all or part of the work
68 | in a fashion requiring copyright permission, other than the making of an
69 | exact copy. The resulting work is called a "modified version" of the
70 | earlier work or a work "based on" the earlier work.
71 | A "covered work" means either the unmodified Program or a work based
72 | on the Program.
73 | To "propagate" a work means to do anything with it that, without
74 | permission, would make you directly or secondarily liable for
75 | infringement under applicable copyright law, except executing it on a
76 | computer or modifying a private copy. Propagation includes copying,
77 | distribution (with or without modification), making available to the
78 | public, and in some countries other activities as well.
79 | To "convey" a work means any kind of propagation that enables other
80 | parties to make or receive copies. Mere interaction with a user through
81 | a computer network, with no transfer of a copy, is not conveying.
82 | An interactive user interface displays "Appropriate Legal Notices"
83 | to the extent that it includes a convenient and prominently visible
84 | feature that (1) displays an appropriate copyright notice, and (2)
85 | tells the user that there is no warranty for the work (except to the
86 | extent that warranties are provided), that licensees may convey the
87 | work under this License, and how to view a copy of this License. If
88 | the interface presents a list of user commands or options, such as a
89 | menu, a prominent item in the list meets this criterion.
90 | 1. Source Code.
91 | The "source code" for a work means the preferred form of the work
92 | for making modifications to it. "Object code" means any non-source
93 | form of a work.
94 | A "Standard Interface" means an interface that either is an official
95 | standard defined by a recognized standards body, or, in the case of
96 | interfaces specified for a particular programming language, one that
97 | is widely used among developers working in that language.
98 | The "System Libraries" of an executable work include anything, other
99 | than the work as a whole, that (a) is included in the normal form of
100 | packaging a Major Component, but which is not part of that Major
101 | Component, and (b) serves only to enable use of the work with that
102 | Major Component, or to implement a Standard Interface for which an
103 | implementation is available to the public in source code form. A
104 | "Major Component", in this context, means a major essential component
105 | (kernel, window system, and so on) of the specific operating system
106 | (if any) on which the executable work runs, or a compiler used to
107 | produce the work, or an object code interpreter used to run it.
108 | The "Corresponding Source" for a work in object code form means all
109 | the source code needed to generate, install, and (for an executable
110 | work) run the object code and to modify the work, including scripts to
111 | control those activities. However, it does not include the work's
112 | System Libraries, or general-purpose tools or generally available free
113 | programs which are used unmodified in performing those activities but
114 | which are not part of the work. For example, Corresponding Source
115 | includes interface definition files associated with source files for
116 | the work, and the source code for shared libraries and dynamically
117 | linked subprograms that the work is specifically designed to require,
118 | such as by intimate data communication or control flow between those
119 | subprograms and other parts of the work.
120 | The Corresponding Source need not include anything that users
121 | can regenerate automatically from other parts of the Corresponding
122 | Source.
123 | The Corresponding Source for a work in source code form is that
124 | same work.
125 | 2. Basic Permissions.
126 | All rights granted under this License are granted for the term of
127 | copyright on the Program, and are irrevocable provided the stated
128 | conditions are met. This License explicitly affirms your unlimited
129 | permission to run the unmodified Program. The output from running a
130 | covered work is covered by this License only if the output, given its
131 | content, constitutes a covered work. This License acknowledges your
132 | rights of fair use or other equivalent, as provided by copyright law.
133 | You may make, run and propagate covered works that you do not
134 | convey, without conditions so long as your license otherwise remains
135 | in force. You may convey covered works to others for the sole purpose
136 | of having them make modifications exclusively for you, or provide you
137 | with facilities for running those works, provided that you comply with
138 | the terms of this License in conveying all material for which you do
139 | not control copyright. Those thus making or running the covered works
140 | for you must do so exclusively on your behalf, under your direction
141 | and control, on terms that prohibit them from making any copies of
142 | your copyrighted material outside their relationship with you.
143 | Conveying under any other circumstances is permitted solely under
144 | the conditions stated below. Sublicensing is not allowed; section 10
145 | makes it unnecessary.
146 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
147 | No covered work shall be deemed part of an effective technological
148 | measure under any applicable law fulfilling obligations under article
149 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
150 | similar laws prohibiting or restricting circumvention of such
151 | measures.
152 | When you convey a covered work, you waive any legal power to forbid
153 | circumvention of technological measures to the extent such circumvention
154 | is effected by exercising rights under this License with respect to
155 | the covered work, and you disclaim any intention to limit operation or
156 | modification of the work as a means of enforcing, against the work's
157 | users, your or third parties' legal rights to forbid circumvention of
158 | technological measures.
159 | 4. Conveying Verbatim Copies.
160 | You may convey verbatim copies of the Program's source code as you
161 | receive it, in any medium, provided that you conspicuously and
162 | appropriately publish on each copy an appropriate copyright notice;
163 | keep intact all notices stating that this License and any
164 | non-permissive terms added in accord with section 7 apply to the code;
165 | keep intact all notices of the absence of any warranty; and give all
166 | recipients a copy of this License along with the Program.
167 | You may charge any price or no price for each copy that you convey,
168 | and you may offer support or warranty protection for a fee.
169 | 5. Conveying Modified Source Versions.
170 | You may convey a work based on the Program, or the modifications to
171 | produce it from the Program, in the form of source code under the
172 | terms of section 4, provided that you also meet all of these conditions:
173 | a) The work must carry prominent notices stating that you modified
174 | it, and giving a relevant date.
175 | b) The work must carry prominent notices stating that it is
176 | released under this License and any conditions added under section
177 | 7. This requirement modifies the requirement in section 4 to
178 | "keep intact all notices".
179 | c) You must license the entire work, as a whole, under this
180 | License to anyone who comes into possession of a copy. This
181 | License will therefore apply, along with any applicable section 7
182 | additional terms, to the whole of the work, and all its parts,
183 | regardless of how they are packaged. This License gives no
184 | permission to license the work in any other way, but it does not
185 | invalidate such permission if you have separately received it.
186 | d) If the work has interactive user interfaces, each must display
187 | Appropriate Legal Notices; however, if the Program has interactive
188 | interfaces that do not display Appropriate Legal Notices, your
189 | work need not make them do so.
190 | A compilation of a covered work with other separate and independent
191 | works, which are not by their nature extensions of the covered work,
192 | and which are not combined with it such as to form a larger program,
193 | in or on a volume of a storage or distribution medium, is called an
194 | "aggregate" if the compilation and its resulting copyright are not
195 | used to limit the access or legal rights of the compilation's users
196 | beyond what the individual works permit. Inclusion of a covered work
197 | in an aggregate does not cause this License to apply to the other
198 | parts of the aggregate.
199 | 6. Conveying Non-Source Forms.
200 | You may convey a covered work in object code form under the terms
201 | of sections 4 and 5, provided that you also convey the
202 | machine-readable Corresponding Source under the terms of this License,
203 | in one of these ways:
204 | a) Convey the object code in, or embodied in, a physical product
205 | (including a physical distribution medium), accompanied by the
206 | Corresponding Source fixed on a durable physical medium
207 | customarily used for software interchange.
208 | b) Convey the object code in, or embodied in, a physical product
209 | (including a physical distribution medium), accompanied by a
210 | written offer, valid for at least three years and valid for as
211 | long as you offer spare parts or customer support for that product
212 | model, to give anyone who possesses the object code either (1) a
213 | copy of the Corresponding Source for all the software in the
214 | product that is covered by this License, on a durable physical
215 | medium customarily used for software interchange, for a price no
216 | more than your reasonable cost of physically performing this
217 | conveying of source, or (2) access to copy the
218 | Corresponding Source from a network server at no charge.
219 | c) Convey individual copies of the object code with a copy of the
220 | written offer to provide the Corresponding Source. This
221 | alternative is allowed only occasionally and noncommercially, and
222 | only if you received the object code with such an offer, in accord
223 | with subsection 6b.
224 | d) Convey the object code by offering access from a designated
225 | place (gratis or for a charge), and offer equivalent access to the
226 | Corresponding Source in the same way through the same place at no
227 | further charge. You need not require recipients to copy the
228 | Corresponding Source along with the object code. If the place to
229 | copy the object code is a network server, the Corresponding Source
230 | may be on a different server (operated by you or a third party)
231 | that supports equivalent copying facilities, provided you maintain
232 | clear directions next to the object code saying where to find the
233 | Corresponding Source. Regardless of what server hosts the
234 | Corresponding Source, you remain obligated to ensure that it is
235 | available for as long as needed to satisfy these requirements.
236 | e) Convey the object code using peer-to-peer transmission, provided
237 | you inform other peers where the object code and Corresponding
238 | Source of the work are being offered to the general public at no
239 | charge under subsection 6d.
240 | A separable portion of the object code, whose source code is excluded
241 | from the Corresponding Source as a System Library, need not be
242 | included in conveying the object code work.
243 | A "User Product" is either (1) a "consumer product", which means any
244 | tangible personal property which is normally used for personal, family,
245 | or household purposes, or (2) anything designed or sold for incorporation
246 | into a dwelling. In determining whether a product is a consumer product,
247 | doubtful cases shall be resolved in favor of coverage. For a particular
248 | product received by a particular user, "normally used" refers to a
249 | typical or common use of that class of product, regardless of the status
250 | of the particular user or of the way in which the particular user
251 | actually uses, or expects or is expected to use, the product. A product
252 | is a consumer product regardless of whether the product has substantial
253 | commercial, industrial or non-consumer uses, unless such uses represent
254 | the only significant mode of use of the product.
255 | "Installation Information" for a User Product means any methods,
256 | procedures, authorization keys, or other information required to install
257 | and execute modified versions of a covered work in that User Product from
258 | a modified version of its Corresponding Source. The information must
259 | suffice to ensure that the continued functioning of the modified object
260 | code is in no case prevented or interfered with solely because
261 | modification has been made.
262 | If you convey an object code work under this section in, or with, or
263 | specifically for use in, a User Product, and the conveying occurs as
264 | part of a transaction in which the right of possession and use of the
265 | User Product is transferred to the recipient in perpetuity or for a
266 | fixed term (regardless of how the transaction is characterized), the
267 | Corresponding Source conveyed under this section must be accompanied
268 | by the Installation Information. But this requirement does not apply
269 | if neither you nor any third party retains the ability to install
270 | modified object code on the User Product (for example, the work has
271 | been installed in ROM).
272 | The requirement to provide Installation Information does not include a
273 | requirement to continue to provide support service, warranty, or updates
274 | for a work that has been modified or installed by the recipient, or for
275 | the User Product in which it has been modified or installed. Access to a
276 | network may be denied when the modification itself materially and
277 | adversely affects the operation of the network or violates the rules and
278 | protocols for communication across the network.
279 | Corresponding Source conveyed, and Installation Information provided,
280 | in accord with this section must be in a format that is publicly
281 | documented (and with an implementation available to the public in
282 | source code form), and must require no special password or key for
283 | unpacking, reading or copying.
284 | 7. Additional Terms.
285 | "Additional permissions" are terms that supplement the terms of this
286 | License by making exceptions from one or more of its conditions.
287 | Additional permissions that are applicable to the entire Program shall
288 | be treated as though they were included in this License, to the extent
289 | that they are valid under applicable law. If additional permissions
290 | apply only to part of the Program, that part may be used separately
291 | under those permissions, but the entire Program remains governed by
292 | this License without regard to the additional permissions.
293 | When you convey a copy of a covered work, you may at your option
294 | remove any additional permissions from that copy, or from any part of
295 | it. (Additional permissions may be written to require their own
296 | removal in certain cases when you modify the work.) You may place
297 | additional permissions on material, added by you to a covered work,
298 | for which you have or can give appropriate copyright permission.
299 | Notwithstanding any other provision of this License, for material you
300 | add to a covered work, you may (if authorized by the copyright holders of
301 | that material) supplement the terms of this License with terms:
302 | a) Disclaiming warranty or limiting liability differently from the
303 | terms of sections 15 and 16 of this License; or
304 | b) Requiring preservation of specified reasonable legal notices or
305 | author attributions in that material or in the Appropriate Legal
306 | Notices displayed by works containing it; or
307 | c) Prohibiting misrepresentation of the origin of that material, or
308 | requiring that modified versions of such material be marked in
309 | reasonable ways as different from the original version; or
310 | d) Limiting the use for publicity purposes of names of licensors or
311 | authors of the material; or
312 | e) Declining to grant rights under trademark law for use of some
313 | trade names, trademarks, or service marks; or
314 | f) Requiring indemnification of licensors and authors of that
315 | material by anyone who conveys the material (or modified versions of
316 | it) with contractual assumptions of liability to the recipient, for
317 | any liability that these contractual assumptions directly impose on
318 | those licensors and authors.
319 | All other non-permissive additional terms are considered "further
320 | restrictions" within the meaning of section 10. If the Program as you
321 | received it, or any part of it, contains a notice stating that it is
322 | governed by this License along with a term that is a further
323 | restriction, you may remove that term. If a license document contains
324 | a further restriction but permits relicensing or conveying under this
325 | License, you may add to a covered work material governed by the terms
326 | of that license document, provided that the further restriction does
327 | not survive such relicensing or conveying.
328 | If you add terms to a covered work in accord with this section, you
329 | must place, in the relevant source files, a statement of the
330 | additional terms that apply to those files, or a notice indicating
331 | where to find the applicable terms.
332 | Additional terms, permissive or non-permissive, may be stated in the
333 | form of a separately written license, or stated as exceptions;
334 | the above requirements apply either way.
335 | 8. Termination.
336 | You may not propagate or modify a covered work except as expressly
337 | provided under this License. Any attempt otherwise to propagate or
338 | modify it is void, and will automatically terminate your rights under
339 | this License (including any patent licenses granted under the third
340 | paragraph of section 11).
341 | However, if you cease all violation of this License, then your
342 | license from a particular copyright holder is reinstated (a)
343 | provisionally, unless and until the copyright holder explicitly and
344 | finally terminates your license, and (b) permanently, if the copyright
345 | holder fails to notify you of the violation by some reasonable means
346 | prior to 60 days after the cessation.
347 | Moreover, your license from a particular copyright holder is
348 | reinstated permanently if the copyright holder notifies you of the
349 | violation by some reasonable means, this is the first time you have
350 | received notice of violation of this License (for any work) from that
351 | copyright holder, and you cure the violation prior to 30 days after
352 | your receipt of the notice.
353 | Termination of your rights under this section does not terminate the
354 | licenses of parties who have received copies or rights from you under
355 | this License. If your rights have been terminated and not permanently
356 | reinstated, you do not qualify to receive new licenses for the same
357 | material under section 10.
358 | 9. Acceptance Not Required for Having Copies.
359 | You are not required to accept this License in order to receive or
360 | run a copy of the Program. Ancillary propagation of a covered work
361 | occurring solely as a consequence of using peer-to-peer transmission
362 | to receive a copy likewise does not require acceptance. However,
363 | nothing other than this License grants you permission to propagate or
364 | modify any covered work. These actions infringe copyright if you do
365 | not accept this License. Therefore, by modifying or propagating a
366 | covered work, you indicate your acceptance of this License to do so.
367 | 10. Automatic Licensing of Downstream Recipients.
368 | Each time you convey a covered work, the recipient automatically
369 | receives a license from the original licensors, to run, modify and
370 | propagate that work, subject to this License. You are not responsible
371 | for enforcing compliance by third parties with this License.
372 | An "entity transaction" is a transaction transferring control of an
373 | organization, or substantially all assets of one, or subdividing an
374 | organization, or merging organizations. If propagation of a covered
375 | work results from an entity transaction, each party to that
376 | transaction who receives a copy of the work also receives whatever
377 | licenses to the work the party's predecessor in interest had or could
378 | give under the previous paragraph, plus a right to possession of the
379 | Corresponding Source of the work from the predecessor in interest, if
380 | the predecessor has it or can get it with reasonable efforts.
381 | You may not impose any further restrictions on the exercise of the
382 | rights granted or affirmed under this License. For example, you may
383 | not impose a license fee, royalty, or other charge for exercise of
384 | rights granted under this License, and you may not initiate litigation
385 | (including a cross-claim or counterclaim in a lawsuit) alleging that
386 | any patent claim is infringed by making, using, selling, offering for
387 | sale, or importing the Program or any portion of it.
388 | 11. Patents.
389 | A "contributor" is a copyright holder who authorizes use under this
390 | License of the Program or a work on which the Program is based. The
391 | work thus licensed is called the contributor's "contributor version".
392 | A contributor's "essential patent claims" are all patent claims
393 | owned or controlled by the contributor, whether already acquired or
394 | hereafter acquired, that would be infringed by some manner, permitted
395 | by this License, of making, using, or selling its contributor version,
396 | but do not include claims that would be infringed only as a
397 | consequence of further modification of the contributor version. For
398 | purposes of this definition, "control" includes the right to grant
399 | patent sublicenses in a manner consistent with the requirements of
400 | this License.
401 | Each contributor grants you a non-exclusive, worldwide, royalty-free
402 | patent license under the contributor's essential patent claims, to
403 | make, use, sell, offer for sale, import and otherwise run, modify and
404 | propagate the contents of its contributor version.
405 | In the following three paragraphs, a "patent license" is any express
406 | agreement or commitment, however denominated, not to enforce a patent
407 | (such as an express permission to practice a patent or covenant not to
408 | sue for patent infringement). To "grant" such a patent license to a
409 | party means to make such an agreement or commitment not to enforce a
410 | patent against the party.
411 | If you convey a covered work, knowingly relying on a patent license,
412 | and the Corresponding Source of the work is not available for anyone
413 | to copy, free of charge and under the terms of this License, through a
414 | publicly available network server or other readily accessible means,
415 | then you must either (1) cause the Corresponding Source to be so
416 | available, or (2) arrange to deprive yourself of the benefit of the
417 | patent license for this particular work, or (3) arrange, in a manner
418 | consistent with the requirements of this License, to extend the patent
419 | license to downstream recipients. "Knowingly relying" means you have
420 | actual knowledge that, but for the patent license, your conveying the
421 | covered work in a country, or your recipient's use of the covered work
422 | in a country, would infringe one or more identifiable patents in that
423 | country that you have reason to believe are valid.
424 | If, pursuant to or in connection with a single transaction or
425 | arrangement, you convey, or propagate by procuring conveyance of, a
426 | covered work, and grant a patent license to some of the parties
427 | receiving the covered work authorizing them to use, propagate, modify
428 | or convey a specific copy of the covered work, then the patent license
429 | you grant is automatically extended to all recipients of the covered
430 | work and works based on it.
431 | A patent license is "discriminatory" if it does not include within
432 | the scope of its coverage, prohibits the exercise of, or is
433 | conditioned on the non-exercise of one or more of the rights that are
434 | specifically granted under this License. You may not convey a covered
435 | work if you are a party to an arrangement with a third party that is
436 | in the business of distributing software, under which you make payment
437 | to the third party based on the extent of your activity of conveying
438 | the work, and under which the third party grants, to any of the
439 | parties who would receive the covered work from you, a discriminatory
440 | patent license (a) in connection with copies of the covered work
441 | conveyed by you (or copies made from those copies), or (b) primarily
442 | for and in connection with specific products or compilations that
443 | contain the covered work, unless you entered into that arrangement,
444 | or that patent license was granted, prior to 28 March 2007.
445 | Nothing in this License shall be construed as excluding or limiting
446 | any implied license or other defenses to infringement that may
447 | otherwise be available to you under applicable patent law.
448 | 12. No Surrender of Others' Freedom.
449 | If conditions are imposed on you (whether by court order, agreement or
450 | otherwise) that contradict the conditions of this License, they do not
451 | excuse you from the conditions of this License. If you cannot convey a
452 | covered work so as to satisfy simultaneously your obligations under this
453 | License and any other pertinent obligations, then as a consequence you may
454 | not convey it at all. For example, if you agree to terms that obligate you
455 | to collect a royalty for further conveying from those to whom you convey
456 | the Program, the only way you could satisfy both those terms and this
457 | License would be to refrain entirely from conveying the Program.
458 | 13. Use with the GNU Affero General Public License.
459 | Notwithstanding any other provision of this License, you have
460 | permission to link or combine any covered work with a work licensed
461 | under version 3 of the GNU Affero General Public License into a single
462 | combined work, and to convey the resulting work. The terms of this
463 | License will continue to apply to the part which is the covered work,
464 | but the special requirements of the GNU Affero General Public License,
465 | section 13, concerning interaction through a network will apply to the
466 | combination as such.
467 | 14. Revised Versions of this License.
468 | The Free Software Foundation may publish revised and/or new versions of
469 | the GNU General Public License from time to time. Such new versions will
470 | be similar in spirit to the present version, but may differ in detail to
471 | address new problems or concerns.
472 | Each version is given a distinguishing version number. If the
473 | Program specifies that a certain numbered version of the GNU General
474 | Public License "or any later version" applies to it, you have the
475 | option of following the terms and conditions either of that numbered
476 | version or of any later version published by the Free Software
477 | Foundation. If the Program does not specify a version number of the
478 | GNU General Public License, you may choose any version ever published
479 | by the Free Software Foundation.
480 | If the Program specifies that a proxy can decide which future
481 | versions of the GNU General Public License can be used, that proxy's
482 | public statement of acceptance of a version permanently authorizes you
483 | to choose that version for the Program.
484 | Later license versions may give you additional or different
485 | permissions. However, no additional obligations are imposed on any
486 | author or copyright holder as a result of your choosing to follow a
487 | later version.
488 | 15. Disclaimer of Warranty.
489 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
490 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
491 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
492 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
493 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
494 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
495 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
496 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
497 | 16. Limitation of Liability.
498 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
499 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
500 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
501 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
502 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
503 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
504 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
505 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
506 | SUCH DAMAGES.
507 | 17. Interpretation of Sections 15 and 16.
508 | If the disclaimer of warranty and limitation of liability provided
509 | above cannot be given local legal effect according to their terms,
510 | reviewing courts shall apply local law that most closely approximates
511 | an absolute waiver of all civil liability in connection with the
512 | Program, unless a warranty or assumption of liability accompanies a
513 | copy of the Program in return for a fee.
514 | END OF TERMS AND CONDITIONS
515 | How to Apply These Terms to Your New Programs
516 | If you develop a new program, and you want it to be of the greatest
517 | possible use to the public, the best way to achieve this is to make it
518 | free software which everyone can redistribute and change under these terms.
519 | To do so, attach the following notices to the program. It is safest
520 | to attach them to the start of each source file to most effectively
521 | state the exclusion of warranty; and each file should have at least
522 | the "copyright" line and a pointer to where the full notice is found.
523 | fxserver-async
524 | Copyright (C) 2015 Jérémie N'gadi
525 | This program is free software: you can redistribute it and/or modify
526 | it under the terms of the GNU General Public License as published by
527 | the Free Software Foundation, either version 3 of the License, or
528 | (at your option) any later version.
529 | This program is distributed in the hope that it will be useful,
530 | but WITHOUT ANY WARRANTY; without even the implied warranty of
531 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
532 | GNU General Public License for more details.
533 | You should have received a copy of the GNU General Public License
534 | along with this program. If not, see .
535 | Also add information on how to contact you by electronic and paper mail.
536 | If the program does terminal interaction, make it output a short
537 | notice like this when it starts in an interactive mode:
538 | fxserver-async Copyright (C) 2015 Jérémie N'gadi
539 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
540 | This is free software, and you are welcome to redistribute it
541 | under certain conditions; type `show c' for details.
542 | The hypothetical commands `show w' and `show c' should show the appropriate
543 | parts of the General Public License. Of course, your program's commands
544 | might be different; for a GUI interface, you would use an "about box".
545 | You should also get your employer (if you work as a programmer) or school,
546 | if any, to sign a "copyright disclaimer" for the program, if necessary.
547 | For more information on this, and how to apply and follow the GNU GPL, see
548 | .
549 | The GNU General Public License does not permit incorporating your program
550 | into proprietary programs. If your program is a subroutine library, you
551 | may consider it more useful to permit linking proprietary applications with
552 | the library. If this is what you want to do, use the GNU Lesser General
553 | Public License instead of this License. But first, please read
554 | .
555 | ]]
556 |
557 | if Citizen and Citizen.CreateThread then
558 | CreateThread = Citizen.CreateThread
559 | end
560 |
561 | Async = {}
562 |
563 | function Async.parallel(tasks, cb)
564 | if #tasks == 0 then
565 | cb({})
566 | return
567 | end
568 |
569 | local remaining = #tasks
570 | local results = {}
571 |
572 | for i = 1, #tasks, 1 do
573 | CreateThread(function()
574 | tasks[i](function(result)
575 | table.insert(results, result)
576 |
577 | remaining = remaining - 1;
578 |
579 | if remaining == 0 then
580 | cb(results)
581 | end
582 | end)
583 | end)
584 | end
585 | end
586 |
587 | function Async.parallelLimit(tasks, limit, cb)
588 | if #tasks == 0 then
589 | cb({})
590 | return
591 | end
592 |
593 | local remaining = #tasks
594 | local running = 0
595 | local queue, results = {}, {}
596 |
597 | for i=1, #tasks, 1 do
598 | table.insert(queue, tasks[i])
599 | end
600 |
601 | local function processQueue()
602 | if #queue == 0 then
603 | return
604 | end
605 |
606 | while running < limit and #queue > 0 do
607 | local task = table.remove(queue, 1)
608 |
609 | running = running + 1
610 |
611 | task(function(result)
612 | table.insert(results, result)
613 |
614 | remaining = remaining - 1;
615 | running = running - 1
616 |
617 | if remaining == 0 then
618 | cb(results)
619 | end
620 | end)
621 | end
622 |
623 | CreateThread(processQueue)
624 | end
625 |
626 | processQueue()
627 | end
628 |
629 | function Async.series(tasks, cb)
630 | Async.parallelLimit(tasks, 1, cb)
631 | end
632 |
--------------------------------------------------------------------------------