Skip to content

Commit

Permalink
Initial commit of the screenshot resource.
Browse files Browse the repository at this point in the history
  • Loading branch information
blattersturm committed Jan 15, 2019
0 parents commit 546416b
Show file tree
Hide file tree
Showing 17 changed files with 2,355 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist/
node_modules/
yarn-error.log
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2019 The CitizenFX Developers

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# screenshot-basic for FiveM

## Description

screenshot-basic is a basic resource for making screenshots of clients' screens using FiveM. It uses the same backing
WebGL/OpenGL ES calls as used by the `application/x-cfx-game-view` plugin (see the code in [citizenfx/fivem](https://github.com/citizenfx/fivem/blob/b0a7cda1007dc53d2ba0f638c035c0a5d1402796/data/client/bin/d3d_rendering.cc#L248)),
and wraps these calls using Three.js to 'simplify' WebGL initialization and copying to a buffer from asynchronous NUI.

## Usage

1. Make sure your [cfx-server-data](https://github.com/cfx-server-data) is updated as of 2019-01-15 or later. You can easily
update it by running `git pull` in your local clone directory.
2. Install `screenshot-basic`:
```
mkdir -p 'resources/[local]/'
cd 'resources/[local]'
git clone https://github.com/citizenfx/screenshot-basic.git screenshot-basic
```
3. Make/use a resource that uses it. Currently, there is no directly-usable commands, it is only usable through exports.

## API

### Client

#### requestScreenshot(options?: any, cb: (result: string) => void)
Takes a screenshot and passes the data URI to a callback. Please don't send this through _any_ server events.

Arguments:
* **options**: An optional object containing options.
* **encoding**: 'png' | 'jpg' | 'webp' - The target image encoding. Defaults to 'jpg'.
* **quality**: number - The quality for a lossy image encoder, in a range for 0.0-1.0. Defaults to 0.92.
* **cb**: A callback upon result.
* **result**: A `base64` data URI for the image.

Example:

```lua
exports['screenshot-basic']:requestScreenshot(function(data)
TriggerEvent('chat:addMessage', { template = '<img src="{0}" style="max-width: 300px;" />', args = { data } })
end)
```

#### requestScreenshotUpload(url: string, field: string, options?: any, cb: (result: string) => void)
Takes a screenshot and uploads it as a file (`multipart/form-data`) to a remote HTTP URL.

Arguments:
* **url**: The URL to a file upload handler.
* **field**: The name for the form field to add the file to.
* **options**: An optional object containing options.
* **encoding**: 'png' | 'jpg' | 'webp' - The target image encoding. Defaults to 'jpg'.
* **quality**: number - The quality for a lossy image encoder, in a range for 0.0-1.0. Defaults to 0.92.
* **cb**: A callback upon result.
* **result**: The response data for the remote URL.

Example:

```lua
exports['screenshot-basic']:requestScreenshotUpload('https://wew.wtf/upload.php', 'files[]', function(data)
local resp = json.decode(data)
TriggerEvent('chat:addMessage', { template = '<img src="{0}" style="max-width: 300px;" />', args = { resp.files[1].url } })
end)
```

### Server
The server can also request a client to take a screenshot and upload it to a built-in HTTP handler on the server.

Using this API on the server requires at least FiveM client version 1129160, and server pipeline 1011 or higher.

#### requestClientScreenshot(player: string | number, options: any, cb: (err: string | boolean, data: string) => void)
Requests the specified client to take a screenshot.

Arguments:
* **player**: The target player's player index.
* **options**: An object containing options.
* **fileName**: string? - The file name on the server to save the image to. If not passed, the callback will get a data URI for the image data.
* **encoding**: 'png' | 'jpg' | 'webp' - The target image encoding. Defaults to 'jpg'.
* **quality**: number - The quality for a lossy image encoder, in a range for 0.0-1.0. Defaults to 0.92.
* **cb**: A callback upon result.
* **err**: `false`, or an error string.
* **data**: The local file name the upload was saved to, or the data URI for the image.


Example:
```lua
exports['screenshot-basic']:requestClientScreenshot(GetPlayers()[1], {
fileName = 'cache/screenshot.jpg'
}, function(err, data)
print('err', err)
print('data', data)
end)
```
17 changes: 17 additions & 0 deletions __resource.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'

client_script 'dist/client.js'
server_script 'dist/server.js'

dependency 'yarn'
dependency 'webpack'

webpack_config 'client.config.js'
webpack_config 'server.config.js'
webpack_config 'ui.config.js'

files {
'dist/ui.html'
}

ui_page 'dist/ui.html'
22 changes: 22 additions & 0 deletions client.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = {
entry: './src/client/client.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'client.js',
path: __dirname + '/dist/'
},
node: {
fs: 'empty'
}
};
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "screenshot-basic",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"dependencies": {
"@citizenfx/client": "^1.0.1012-1",
"@citizenfx/http-wrapper": "^0.2.0",
"@citizenfx/server": "^1.0.1012-1",
"@citizenfx/three": "^0.100.0",
"@types/koa": "^2.0.48",
"@types/koa-router": "^7.0.37",
"@types/mv": "^2.1.0",
"@types/node": "^10.12.18",
"@types/uuid": "^3.4.4",
"html-webpack-inline-source-plugin": "^0.0.10",
"html-webpack-plugin": "^3.2.0",
"koa": "^2.6.2",
"koa-body": "^4.0.6",
"koa-router": "^7.4.0",
"mv": "^2.1.1",
"ts-loader": "^5.3.3",
"typescript": "^3.2.2",
"typescript-styled-plugin": "^0.13.0",
"uuid": "^3.3.2"
}
}
29 changes: 29 additions & 0 deletions server.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const webpack = require('webpack');

module.exports = {
entry: './src/server/server.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
// https://github.com/felixge/node-formidable/issues/337#issuecomment-153408479
plugins: [
new webpack.DefinePlugin({ "global.GENTLY": false })
],
optimization: {
minimize: false
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'server.js',
path: __dirname + '/dist/'
},
target: 'node'
};
79 changes: 79 additions & 0 deletions src/client/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
const exp = (<any>global).exports;

RegisterNuiCallbackType('screenshot_created');

class ResultData {
cb: (data: string) => void;
}

const results: {[id: string]: ResultData} = {};
let correlationId = 0;

function registerCorrelation(cb: (result: string) => void) {
const id = correlationId.toString();

results[id] = { cb };

correlationId++;

return id;
}

on('__cfx_nui:screenshot_created', (body: any, cb: (arg: any) => void) => {
cb(true);

if (body.id !== undefined && results[body.id]) {
results[body.id].cb(body.data);
delete results[body.id];
}
});

exp('requestScreenshot', (options: any, cb: (result: string) => void) => {
const realOptions = (cb !== undefined) ? options : {
encoding: 'jpg'
};

const realCb = (cb !== undefined) ? cb : options;

realOptions.resultURL = null;
realOptions.targetField = null;
realOptions.targetURL = `http://${GetCurrentResourceName()}/screenshot_created`;

realOptions.correlation = registerCorrelation(realCb);

SendNuiMessage(JSON.stringify({
request: realOptions
}));
});

exp('requestScreenshotUpload', (url: string, field: string, options: any, cb: (result: string) => void) => {
const realOptions = (cb !== undefined) ? options : {
encoding: 'jpg'
};

const realCb = (cb !== undefined) ? cb : options;

realOptions.targetURL = url;
realOptions.targetField = field;
realOptions.resultURL = `http://${GetCurrentResourceName()}/screenshot_created`;

realOptions.correlation = registerCorrelation(realCb);

SendNuiMessage(JSON.stringify({
request: realOptions
}));
});

onNet('screenshot_basic:requestScreenshot', (options: any, url: string) => {
options.encoding = options.encoding || 'jpg';

options.targetURL = `http://${GetCurrentServerEndpoint()}${url}`;
options.targetField = 'file';
options.resultURL = null;

options.correlation = registerCorrelation(() => {});

SendNuiMessage(JSON.stringify({
request: options
}));
});
18 changes: 18 additions & 0 deletions src/client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"outDir": "./",
"noImplicitAny": true,
"module": "es6",
"target": "es6",
"allowJs": true,
"lib": ["es2017"],
"types": ["@citizenfx/server", "@citizenfx/client", "node"],
"moduleResolution": "node"
},
"include": [
"./**/*"
],
"exclude": [

]
}
Loading

0 comments on commit 546416b

Please sign in to comment.