forked from walterhiggins/ScriptCraft
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
308 lines (265 loc) · 10.6 KB
/
index.js
File metadata and controls
308 lines (265 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
'use strict';
/*global require, module, __plugin, __dirname, echo, persist, isOp, events, Packages, command, global, setInterval, clearInterval, setTimeout, clearTimeout */
var utils = require('utils'),
watcher = require('watcher'),
autoload = require('plugin').autoload,
foreach = utils.foreach,
watchDir = watcher.watchDir,
unwatchDir = watcher.unwatchDir,
playersDir = __dirname + '/../../players/',
serverAddress = utils.serverAddress();
/************************************************************************
## Classroom Plugin
The `classroom` object contains a couple of utility functions for use
in a classroom setting. The goal of these functions is to make it
easier for tutors to facilitate ScriptCraft for use by students in a
classroom environment. Although granting ScriptCraft access to
students on a shared server is potentially risky (Students can
potentially abuse it), it is slighlty less risky than granting
operator privileges to each student. (Enterprising students will
quickly realise how to grant themselves and others operator privileges
once they have access to ScriptCraft).
The goal of this module is not so much to enforce restrictions
(security or otherwise) but to make it easier for tutors to setup a
shared server so students can learn Javascript. When scripting is
turned on, every player who joins the server will have a dedicated
directory into which they can save scripts. All scripts in such
directories are automatically watched and loaded into a global
variable named after the player.
So for example, if player 'walterh' joins the server, a `walterh`
global variable is created. If a file `greet.js` with the following
content is dropped into the `scriptcraft/players/walterh`
directory...
```javascript
exports.hi = function( player ){
echo( player, 'Hi ' + player.name);
};
```
... then it can be invoked like this: `/js walterh.hi( self )` . This
lets every player/student create their own functions without having
naming collisions.
It's strongly recommended that the
`scriptcraft/players/` directory is shared so that
others can connect to it and drop .js files into their student
directories. On Ubuntu, select the folder in Nautilus (the default
file browser) then right-click and choose *Sharing Options*, check the
*Share this folder* checkbox and the *Allow others to create and
delete files* and *Guest access* checkboxes. Click *Create Share*
button to close the sharing options dialog. Students can then access
the shared folder as follows...
* Windows: Open Explorer, Go to \\{serverAddress}\players\
* Macintosh: Open Finder, Go to smb://{serverAddress}/players/
* Linux: Open Nautilus, Go to smb://{serverAddress}/players/
... where {serverAddress} is the ip address of the server (this is
displayed to whoever invokes the classroom.allowScripting() function.)
### jsp classroom command
The `jsp classroom` command makes it easy for tutors to turn on or off
classroom mode. This command can only be used by server operators. To
turn on classroom mode (enable scripting for all players):
jsp classroom on
To turn off classroom mode (disable scripting for all players):
jsp classroom off
The `jsp classroom` command is provided as an easier way to turn on or
off classroom mode. This should be used in preference to the
classroom.allowScripting() function which is provided only for
programmatically enabling or disabling classroom mode.
### classroom.allowScripting() function
Allow or disallow anyone who connects to the server (or is already
connected) to use ScriptCraft. This function is preferable to granting 'ops' privileges
to every student in a Minecraft classroom environment.
Whenever any file is added/edited or removed from any of the players/
directories the contents are automatically reloaded. This is to
facilitate quick turnaround time for students getting to grips with
Javascript.
#### Parameters
* canScript : true or false
#### Example
To allow all players (and any players who connect to the server) to
use the `js` and `jsp` commands...
/js classroom.allowScripting( true, self )
To disallow scripting (and prevent players who join the server from using the commands)...
/js classroom.allowScripting( false, self )
Only ops users can run the classroom.allowScripting() function - this is so that students
don't try to bar themselves and each other from scripting.
***/
var store = persist('classroom', { enableScripting: false }),
File = java.io.File;
function revokeScripting ( player ) {
if (__plugin.bukkit){
foreach( player.getEffectivePermissions(), function( perm ) {
if ( (''+perm.permission).indexOf( 'scriptcraft.' ) == 0 ) {
if ( perm.attachment ) {
perm.attachment.remove();
}
}
});
}
if (__plugin.canary){
//
var Canary = Packages.net.canarymod.Canary;
Canary.permissionManager().removePlayerPermission('scriptcraft.evaluate',player);
}
var playerName = '' + player.name;
playerName = playerName.replace(/[^a-zA-Z0-9_\-]/g,'');
var playerDir = new File( playersDir + playerName );
unwatchDir( playerDir );
}
var autoloadTime = {};
var playerEventHandlers = {};
var playerIntervals = {};
var playerTimeouts = {};
function reloadPlayerModules( playerContext, playerDir ){
/*
wph 20150118 first unregister any event handlers registered by the player
*/
var playerDirPath = ''+ playerDir.getAbsolutePath();
var eventHandlers = playerEventHandlers[playerDirPath];
if (eventHandlers){
for (var i = 0;i < eventHandlers.length; i++){
eventHandlers[i].unregister();
}
eventHandlers.length = 0;
} else {
playerEventHandlers[playerDirPath] = [];
eventHandlers = playerEventHandlers[playerDirPath];
}
/*
Glorf 20171003 also unregister any timeout and interval registered
*/
var intervals = playerIntervals[playerDirPath];
if (intervals){
for (var i = 0;i < intervals.length; i++){
clearInterval(intervals[i]);
}
intervals.length = 0;
} else {
playerIntervals[playerDirPath] = [];
intervals = playerIntervals[playerDirPath];
}
var timeouts = playerTimeouts[playerDirPath];
if (timeouts){
for (var i = 0;i < timeouts.length; i++){
clearTimeout(timeouts[i]);
}
timeouts.length = 0;
} else {
playerTimeouts[playerDirPath] = [];
timeouts = playerTimeouts[playerDirPath];
}
/*
override events.on() so that the listener is stored here so it can be unregistered.
*/
var oldOn = events.on;
var newOn = function( eventType, fn, priority){
var handler = oldOn(eventType, fn, priority);
eventHandlers.push(handler);
};
events.on = newOn;
/*
Gloorf 20171003 override setInterval()/setTimeout() so the timeout/interval object is stored to be unregistered
*/
var oldInterval = global.setInterval;
var newInterval = function(callback, delay) {
var handler = oldInterval(callback, delay);
intervals.push(handler);
return handler;
};
global.setInterval = newInterval;
var oldTimeout = global.setTimeout;
var newTimeout = function(callback, delay) {
var handler = oldTimeout(callback, delay);
timeouts.push(handler);
return handler;
};
global.setTimeout = newTimeout;
autoload( playerContext, playerDir, { cache: false });
events.on = oldOn;
global.setInterval = oldInterval;
global.setTimeout = oldTimeout;
}
function grantScripting( player ) {
console.log('Enabling scripting for player ' + player.name);
var playerName = '' + player.name;
playerName = playerName.replace(/[^a-zA-Z0-9_\-]/g,'');
var playerDir = new File( playersDir + playerName );
if (!playerDir.exists()) {
playerDir.mkdirs();
var exampleJs = "//Try running this function from Minecraft with: /js $username.hi( self )\n" +
"//Remember to use your real username instead of $username!\n" +
"//So if you had username 'walterh', you would run: /js walterh.hi( self )\n" +
"exports.hi = function( player ){\n" +
"\techo( player, 'Hi ' + player.name);\n" +
"};"
createFile(playerDir, 'greet.js', exampleJs);
}
if (__plugin.bukkit){
player.addAttachment( __plugin, 'scriptcraft.*', true );
}
if (__plugin.canary){
player.permissionProvider.addPermission('scriptcraft.evaluate',true);
}
var playerContext = {};
reloadPlayerModules( playerContext, playerDir );
global[playerName] = playerContext;
watchDir( playerDir, function( changedDir ){
var currentTime = new java.util.Date().getTime();
//this check is here because this callback might get called multiple times for the watch interval
//one call for the file change and another for directory change
//(this happens only in Linux because in Windows the folder lastModifiedTime is not changed)
if (currentTime - autoloadTime[playerName]>1000 ) {
reloadPlayerModules(playerContext, playerDir );
}
autoloadTime[playerName] = currentTime;
});
function createFile(fileDir, fileName, fileContent) {
var out = new java.io.PrintWriter(new File(fileDir, fileName));
out.println(fileContent);
out.close();
}
/*
echo( player, 'Create your own minecraft mods by adding javascript (.js) files');
echo( player, ' Windows: Open Explorer, go to \\\\' + serverAddress + '\\players\\' + player.name);
echo( player, ' Macintosh: Open Finder, Go to smb://' + serverAddress + '/players/' + player.name);
echo( player, ' Linux: Open Nautilus, Go to smb://' + serverAddress + '/players/' + player.name);
*/
}
var _classroom = {
allowScripting: function (/* boolean: true or false */ canScript, sender ) {
sender = utils.player(sender);
if ( !sender ) {
console.log( 'Attempt to set classroom scripting without credentials' );
console.log( 'classroom.allowScripting(boolean, sender)' );
return;
}
/*
only operators should be allowed run this function
*/
if ( !isOp(sender) ) {
console.log( 'Attempt to set classroom scripting without credentials: ' + sender.name );
echo( sender, 'Only operators can use this function');
return;
}
utils.players(function(player){
if (!isOp(player)){
canScript ? grantScripting(player) : revokeScripting(player);
}
});
store.enableScripting = canScript;
echo( sender, 'Scripting turned ' + ( canScript ? 'on' : 'off' ) +
' for all players on server ' + serverAddress);
}
};
if (__plugin.canary){
events.connection( function( event ) {
if ( store.enableScripting ) {
grantScripting(event.player);
}
}, 'CRITICAL');
} else {
events.playerJoin( function( event ) {
if ( store.enableScripting ) {
grantScripting(event.player);
}
}, 'HIGHEST');
}
module.exports = _classroom;