Skip to content

Instantly share code, notes, and snippets.

@Zirak
Created September 20, 2014 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zirak/b28bc3c63faf304663ee to your computer and use it in GitHub Desktop.
Save Zirak/b28bc3c63faf304663ee to your computer and use it in GitHub Desktop.
Changes from HEAD to working tree
6 files changed, 195 insertions(+), 132 deletions(-)
source/bot.js | 65 +------------------------
source/memory.js | 103 ++++++++++++++++++++++++++++++++++++++++
source/plugins/export.js | 32 -------------
source/plugins/import-export.js | 82 ++++++++++++++++++++++++++++++++
source/plugins/import.js | 35 --------------
source/util.js | 10 +++-
Modified source/bot.js
diff --git a/source/bot.js b/source/bot.js
index d77a07d..f3e72f1 100644
--- a/source/bot.js
+++ b/source/bot.js
@@ -267,69 +267,6 @@ var bot = window.bot = {
}
};
-//a place to hang your coat and remember the past. provides an abstraction over
-// localStorage or whatever data-storage will be used in the future.
-bot.memory = {
- saveInterval : 900000, //15(min) * 60(sec/min) * 1000(ms/sec) = 900000(ms)
-
- data : {},
-
- get : function ( name, defaultVal ) {
- if ( !this.data[name] ) {
- this.set( name, defaultVal || {} );
- }
-
- return this.data[ name ];
- },
-
- set : function ( name, val ) {
- this.data[ name ] = val;
- },
-
- loadAll : function () {
- var self = this;
-
- Object.iterate( localStorage, function ( key, val ) {
- if ( key.startsWith('bot_') ) {
- console.log( key, val );
- self.set( key.replace(/^bot_/, ''), JSON.parse(val) );
- }
- });
- },
-
- save : function ( name ) {
- if ( name ) {
- localStorage[ 'bot_' + name ] = JSON.stringify( this.data[name] );
- return;
- }
-
- var self = this;
- Object.keys( this.data ).forEach(function ( name ) {
- self.save( name );
- });
-
- this.saveLoop();
- },
-
- saveLoop : function () {
- clearTimeout( this.saveIntervalId );
- setTimeout( this.saveLoop.bind(this), this.saveInterval );
- },
-
- clear : function () {
- Object.iterate( localStorage, function ( key, val ) {
- if ( key.startsWith('bot_') ) {
- localStorage.removeItem(key);
- }
- });
- this.data = {};
- }
-};
-
-bot.memory.loadAll();
-window.addEventListener( 'beforeunload', function () { bot.memory.save(); } );
-bot.memory.saveLoop();
-
bot.banlist = bot.memory.get( 'ban' );
bot.banlist.contains = function ( id ) {
return this.hasOwnProperty( id );
@@ -547,6 +484,8 @@ bot.isOwner = function ( usrid ) {
IO.register( 'input', bot.parseMessage, bot );
+//#build memory.js
+
//#build eval.js
//#build parseCommandArgs.js
New source/memory.js
diff --git a/source/memory.js b/source/memory.js
new file mode 100644
index 0000000..5feaef6
--- /dev/null
+++ b/source/memory.js
@@ -0,0 +1,103 @@
+//a place to hang your coat and remember the past. provides an abstraction over
+// localStorage or whatever data-storage will be used in the future.
+bot.memory = {
+ saveInterval : 900000, //15(min) * 60(sec/min) * 1000(ms/sec) = 900000(ms)
+
+ data : {},
+
+ get : function ( name, defaultVal ) {
+ if ( !this.data[name] ) {
+ this.set( name, defaultVal || {} );
+ }
+
+ return this.data[ name ];
+ },
+
+ set : function ( name, val ) {
+ this.data[ name ] = val;
+ },
+
+ loadAll : function () {
+ var self = this;
+
+ Object.iterate( localStorage, function ( key, val ) {
+ if ( key.startsWith('bot_') ) {
+ console.log( key, val );
+ self.set( key.replace(/^bot_/, ''), JSON.parse(val) );
+ }
+ });
+ },
+
+ save : function ( name ) {
+ if ( name ) {
+ localStorage[ 'bot_' + name ] = JSON.stringify( this.data[name] );
+ return;
+ }
+
+ var self = this;
+ Object.keys( this.data ).forEach(function ( name ) {
+ self.save( name );
+ });
+
+ this.saveLoop();
+ },
+
+ saveLoop : function () {
+ clearTimeout( this.saveIntervalId );
+ setTimeout( this.saveLoop.bind(this), this.saveInterval );
+ },
+
+ replace : function ( obj ) {
+ // down with memory!
+ Object.iterate( this.memory, function ( key, val, memory ) {
+ if ( !obj.hasOwnProperty(key) ) {
+ delete memory[ key ];
+ }
+ });
+
+ // long live memory!
+ Object.extend( this.memory, obj );
+ },
+
+ clear : function () {
+ Object.iterate( localStorage, function ( key, val ) {
+ if ( key.startsWith('bot_') ) {
+ localStorage.removeItem( key );
+ }
+ });
+ this.data = {};
+ },
+
+ export : function ( cb ) {
+ IO.xhr({
+ method : 'POST',
+ url : 'https://api.github.com/gists',
+
+ //hurray
+ data : {
+ //for
+ files : {
+ //deep
+ 'memory.json' : {
+ //nesting!
+ content : JSON.stringify( this.data )
+ }
+ }
+ },
+
+ complete : cb
+ });
+ },
+
+ import : function ( id, cb ) {
+ IO.xhr({
+ method : 'GET',
+ url : 'https://api.github.com/gists/' + id,
+ complete : cb
+ });
+ }
+};
+
+bot.memory.loadAll();
+window.addEventListener( 'beforeunload', function () { bot.memory.save(); } );
+bot.memory.saveLoop();
Deleted source/plugins/export.js
diff --git a/source/plugins/export.js b/source/plugins/export.js
deleted file mode 100644
index ef94c78..0000000
--- a/source/plugins/export.js
+++ /dev/null
@@ -1,32 +0,0 @@
-(function() {
- "use strict";
-
- bot.addCommand({
- name : 'export',
- fun : function(args) {
- var req = new XMLHttpRequest();
- req.open('POST', 'https://api.github.com/gists', false);
- req.send(JSON.stringify({
- files: {
- 'bot.json': {
- content: JSON.stringify(bot.memory.data)
- }
- }
- }));
-
- if (req.status !== 201) {
- var resp = '';
- if (req.responseText) {
- resp = '\n' + req.responseText.match(/.{1,400}/g).join('\n');
- }
- return 'Failed: ' + req.status + ': ' + req.statusText + resp;
- }
-
- var resp = JSON.parse(req.responseText);
-
- return 'Exported to gist, id: `' + resp.id + '` viewable at ' + resp.html_url;
- },
- permissions : { del : 'NONE', use : 'OWNER' },
- description : 'Blurts out a message with the persistent memory storage for export `/export`'
- });
-})();
New source/plugins/import-export.js
diff --git a/source/plugins/import-export.js b/source/plugins/import-export.js
new file mode 100644
index 0000000..37de421
--- /dev/null
+++ b/source/plugins/import-export.js
@@ -0,0 +1,82 @@
+(function() {
+"use strict";
+
+bot.addCommand({
+ name : 'export',
+ fun : function( args ) {
+ bot.memory.export( finish );
+
+ function finish ( resp, req ) {
+ var reply;
+
+ if (req.status === 201) {
+ reply = generateExportMessage( resp, req );
+ }
+ else {
+ reply = generateErrorMessage( resp, req );
+ }
+
+ args.reply( reply );
+ }
+ },
+ permissions : { del : 'NONE', use : 'OWNER' },
+ description : 'Saves the bot memory to external site. `/export`'
+});
+
+bot.addCommand({
+ name : 'import',
+ fun : function (args) {
+ if ( args.trim() === 'clear' ) {
+ bot.memory.clear();
+
+ return 'Bot memory cleared. Please restart the bot.';
+ }
+
+ bot.memory.import( args, finish );
+
+ function finish ( resp, req ) {
+ var reply;
+ if (req.status === 200) {
+ reply = 'Imported succesfully!';
+ bot.memory.replace( getImportMemory(resp) );
+ }
+ else {
+ reply = generateErrorMessage( resp, req );
+ }
+
+ args.reply( reply );
+ }
+
+ function getImportMemory ( responseText ) {
+ var resp = JSON.parse( responseText );
+ //TODO check if a valid gist id was provided, and not something
+ // random.
+ //TODO there's a 1mb limit. above that, the response is truncated
+ // and we need to query the raw gist. do we care?
+ return resp.files['memory.json'].content;
+ }
+ },
+ permissions : { del : 'NONE', use : 'OWNER' },
+ description : 'Import memory which was `/export`ed. Pass clear to clear.' +
+ '`/import export-id|clear'
+});
+
+function generateErrorMessage ( resp, req ) {
+ var partialErr = '';
+
+ if ( resp ) {
+ partialErr = '\n' + resp.match(/.{1,400}/g).join('\n');
+ }
+
+ return 'Failed: {0}: {1}'.supplant(req.status, req.statusText, resp);
+}
+
+function generateExportMessage ( responseText ) {
+ //https://developer.github.com/v3/gists/#create-a-gist
+ var resp = JSON.parse( responseText ),
+ format = 'Exported to gist, id: `{0}` viewable at {1}';
+
+ return format.supplant( resp.id, resp.html_url );
+}
+
+})();
Deleted source/plugins/import.js
diff --git a/source/plugins/import.js b/source/plugins/import.js
deleted file mode 100644
index d254665..0000000
--- a/source/plugins/import.js
+++ /dev/null
@@ -1,35 +0,0 @@
-(function() {
- "use strict";
-
- bot.addCommand({
- name : 'import',
- fun : function (args) {
- if (args.trim() === 'clear') {
- bot.memory.clear();
-
- return 'Bot memory cleared. Please restart the bot.';
- }
-
- var req = new XMLHttpRequest();
- req.open('GET', 'https://api.github.com/gists/' + args, false);
- req.send(null);
-
- if (req.status !== 200) {
- var resp = '';
- if (req.responseText) {
- resp = '\n' + req.responseText.match(/.{1,400}/g).join('\n');
- }
- return 'Failed: ' + req.status + ': ' + req.statusText + resp;
- }
-
- var resp = JSON.parse(req.responseText);
-
- bot.memory.data = JSON.parse(resp.files['bot.json'].content);
- bot.memory.save();
-
- return "Imported and persisted successfully. Please restart the bot.";
- },
- permissions : { del : 'NONE', use : 'OWNER' },
- description : 'Imports the persistent memory described in args `/export <exported-content>`'
- });
-})();
Modified source/util.js
diff --git a/source/util.js b/source/util.js
index 1d27b33..e2169c3 100644
--- a/source/util.js
+++ b/source/util.js
@@ -7,14 +7,20 @@
// > Object.merge( {a : 4, b : 5}, {a : 6, c : 7} )
// { a : 6, b : 5, c : 7 }
Object.merge = function () {
- return [].reduce.call( arguments, function ( ret, merger ) {
+ var args = Array.from( arguments );
+ args.unshift( {} );
+ return Object.extend.apply( this, args );
+};
+Object.extend = function ( subject ) {
+ return Array.from( arguments, 1 ).reduce(function ( ret, merger ) {
+ // TODO replace with Object.iterate
Object.keys( merger ).forEach(function ( key ) {
ret[ key ] = merger[ key ];
});
return ret;
- }, {} );
+ }, subject);
};
//iterates over an object. the callback receives the key, value and the obejct.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment