Merge pull request 104 - Dropbox connector.

This commit is contained in:
Michael
2014-07-16 18:57:50 -04:00
parent 66ba9d9a65
commit 0f78bae1cc
2 changed files with 377 additions and 377 deletions
+361 -361
View File
@@ -1,362 +1,362 @@
(function (Engine, Events, Dropbox, $) { (function (Engine, Events, Dropbox, $) {
/** /**
* Module that enables a save of the gamestate to the dropbox datastore * Module that enables a save of the gamestate to the dropbox datastore
* @see https://www.dropbox.com/developers/datastore * @see https://www.dropbox.com/developers/datastore
* *
* The dropbox datastore (dbds) connector lets you save your data to your own dropbox datastore * The dropbox datastore (dbds) connector lets you save your data to your own dropbox datastore
* without jamming files to it. * without jamming files to it.
* *
* This connector uses the game engines own base64 encoder. * This connector uses the game engines own base64 encoder.
*/ */
'use strict'; 'use strict';
if (!Engine) { return false; } // Game Engine not available if (!Engine) { return false; } // Game Engine not available
if (!Dropbox) { return false; } // Dropbox Connector not available if (!Dropbox) { return false; } // Dropbox Connector not available
var DropboxConnector = { var DropboxConnector = {
options: { options: {
log: false, log: false,
key: 'YOUR_DROPBOX_APP_KEY', // get one at https://www.dropbox.com/developers/apps key: 'q7vyvfsakyfmp3o',
table: 'adarkroom' // use whatever you like table: 'adarkroom'
}, },
client: false, client: false,
table: false, table: false,
dropboxAccount: false, dropboxAccount: false,
savegameKey: false, savegameKey: false,
savegames: {0: null, 1: null, 2: null, 3: null, 4: null}, savegames: {0: null, 1: null, 2: null, 3: null, 4: null},
init: function (options) { init: function (options) {
this.options = $.extend( this.options = $.extend(
this.options, this.options,
options options
); );
this._log = this.options.log; this._log = this.options.log;
this.client = new Dropbox.Client({key: DropboxConnector.options.key}); this.client = new Dropbox.Client({key: DropboxConnector.options.key});
this.connectToDropbox(false); this.connectToDropbox(false);
return this; return this;
}, },
startDropbox: function () { startDropbox: function () {
if (!DropboxConnector.client || !DropboxConnector.table) { if (!DropboxConnector.client || !DropboxConnector.table) {
DropboxConnector.startDropboxConnectEvent(); DropboxConnector.startDropboxConnectEvent();
} else { } else {
DropboxConnector.startDropboxImportEvent(); DropboxConnector.startDropboxImportEvent();
} }
}, },
/** /**
* ****** * ******
* Events * Events
* ****** * ******
*/ */
startDropboxConnectEvent: function () { startDropboxConnectEvent: function () {
Events.startEvent({ Events.startEvent({
title: _('Dropbox connection'), title: _('Dropbox connection'),
scenes: { scenes: {
start: { start: {
text: [_('connect game to dropbox local storage')], text: [_('connect game to dropbox local storage')],
buttons: { buttons: {
'connect': { 'connect': {
text: _('connect'), text: _('connect'),
nextScene: 'end', nextScene: 'end',
onChoose: function () { onChoose: function () {
DropboxConnector.connectToDropbox(DropboxConnector.startDropboxImportEvent); DropboxConnector.connectToDropbox(DropboxConnector.startDropboxImportEvent);
} }
}, },
'cancel': { 'cancel': {
text: _('cancel'), text: _('cancel'),
nextScene: 'end' nextScene: 'end'
} }
} }
} }
} }
}); });
}, },
startDropboxImportEvent: function () { startDropboxImportEvent: function () {
Events.startEvent({ Events.startEvent({
title: _('Dropbox Export / Import'), title: _('Dropbox Export / Import'),
scenes: { scenes: {
start: { start: {
text: [_('export or import save data to dropbox datastorage'), text: [_('export or import save data to dropbox datastorage'),
_('your are connected to dropbox with account / email ') + DropboxConnector.dropboxAccount], _('your are connected to dropbox with account / email ') + DropboxConnector.dropboxAccount],
buttons: { buttons: {
'save': { 'save': {
text: _('save'), text: _('save'),
nextScene: {1: 'saveToSlot'} nextScene: {1: 'saveToSlot'}
}, },
'load': { 'load': {
text: _('load'), text: _('load'),
nextScene: {1: 'loadFromSlot'}, nextScene: {1: 'loadFromSlot'},
onChoose: DropboxConnector.loadGamesFromDropbox onChoose: DropboxConnector.loadGamesFromDropbox
}, },
'signout': { 'signout': {
text: _('signout'), text: _('signout'),
nextScene: 'end', nextScene: 'end',
onChoose: DropboxConnector.signout onChoose: DropboxConnector.signout
}, },
'cancel': { 'cancel': {
text: _('cancel'), text: _('cancel'),
nextScene: 'end' nextScene: 'end'
} }
} }
}, },
saveToSlot: { saveToSlot: {
text: [_('choose one slot to save to')], text: [_('choose one slot to save to')],
buttons: (function () { buttons: (function () {
var buttons = {}; var buttons = {};
$.each(DropboxConnector.savegames, function (n, savegame) { $.each(DropboxConnector.savegames, function (n, savegame) {
buttons['savegame' + n] = { buttons['savegame' + n] = {
text: _('save to slot') + n + ' ' + (savegame ? DropboxConnector.prepareSaveDate(savegame.get('timestamp')) : 'empty'), text: _('save to slot') + n + ' ' + (savegame ? DropboxConnector.prepareSaveDate(savegame.get('timestamp')) : 'empty'),
nextScene: 'end', nextScene: 'end',
onChoose: function () { onChoose: function () {
DropboxConnector.log('Save to slot ' + n + ' initiated'); DropboxConnector.log('Save to slot ' + n + ' initiated');
// timeout prevents error due to fade out animation of the previous event // timeout prevents error due to fade out animation of the previous event
window.setTimeout(function () { window.setTimeout(function () {
DropboxConnector.log('Save to slot ' + n); DropboxConnector.log('Save to slot ' + n);
DropboxConnector.saveGameToDropbox(n, DropboxConnector.savedtoDropboxEvent); DropboxConnector.saveGameToDropbox(n, DropboxConnector.savedtoDropboxEvent);
}, 1000); }, 1000);
} }
}; };
}); });
buttons.cancel = { buttons.cancel = {
text: _('cancel'), text: _('cancel'),
nextScene: 'end' nextScene: 'end'
}; };
return buttons; return buttons;
}()) }())
}, },
loadFromSlot: { loadFromSlot: {
text: [_('choose one slot to load from')], text: [_('choose one slot to load from')],
buttons: (function () { buttons: (function () {
var buttons = {}; var buttons = {};
$.each(DropboxConnector.savegames, function (n, savegame) { $.each(DropboxConnector.savegames, function (n, savegame) {
if (savegame) { if (savegame) {
buttons['savegame' + n] = { buttons['savegame' + n] = {
text: _('load from slot') + n + ' ' + DropboxConnector.prepareSaveDate(savegame.get('timestamp')), text: _('load from slot') + n + ' ' + DropboxConnector.prepareSaveDate(savegame.get('timestamp')),
nextScene: 'end', nextScene: 'end',
onChoose: function () { onChoose: function () {
DropboxConnector.log('Load from slot ' + n + ' initiated'); DropboxConnector.log('Load from slot ' + n + ' initiated');
// timeout prevents error due to fade out animation of the previous event // timeout prevents error due to fade out animation of the previous event
window.setTimeout(function () { window.setTimeout(function () {
DropboxConnector.log('Load from slot ' + n); DropboxConnector.log('Load from slot ' + n);
DropboxConnector.loadGameFromDropbox(n); DropboxConnector.loadGameFromDropbox(n);
}, 1000); }, 1000);
} }
}; };
} }
}); });
buttons.cancel = { buttons.cancel = {
text: _('cancel'), text: _('cancel'),
nextScene: 'end' nextScene: 'end'
}; };
return buttons; return buttons;
}()) }())
} }
} }
}); });
}, },
savedtoDropboxEvent: function (success) { savedtoDropboxEvent: function (success) {
Events.startEvent({ Events.startEvent({
title: _('Dropbox Export / Import'), title: _('Dropbox Export / Import'),
scenes: { scenes: {
start: { start: {
text: success ? [_('successfully saved to dropbox datastorage')] : text: success ? [_('successfully saved to dropbox datastorage')] :
[_('error while saving to dropbox datastorage')], [_('error while saving to dropbox datastorage')],
buttons: { buttons: {
'ok': { 'ok': {
text: _('ok'), text: _('ok'),
nextScene: 'end' nextScene: 'end'
} }
} }
} }
} }
}); });
}, },
/** /**
* *************** * ***************
* functional code * functional code
* *************** * ***************
*/ */
/** /**
* Initiate dropbox connection * Initiate dropbox connection
* *
* @param interactive * @param interactive
* @param callback * @param callback
*/ */
connectToDropbox: function (interactive, callback) { connectToDropbox: function (interactive, callback) {
DropboxConnector.log('start dropbox'); DropboxConnector.log('start dropbox');
var client = this.client; var client = this.client;
client.authenticate({interactive: interactive}, function (error) { client.authenticate({interactive: interactive}, function (error) {
if (error) { if (error) {
DropboxConnector.log('Dropbox Authentication error: ' + error); DropboxConnector.log('Dropbox Authentication error: ' + error);
} }
}); });
if (client.isAuthenticated()) { if (client.isAuthenticated()) {
var datastoreManager = client.getDatastoreManager(); var datastoreManager = client.getDatastoreManager();
datastoreManager.openDefaultDatastore(function (error, datastore) { datastoreManager.openDefaultDatastore(function (error, datastore) {
if (error) { if (error) {
DropboxConnector.log('Error opening default datastore: ' + error); DropboxConnector.log('Error opening default datastore: ' + error);
} else { } else {
DropboxConnector.table = datastore.getTable(DropboxConnector.options.table); DropboxConnector.table = datastore.getTable(DropboxConnector.options.table);
DropboxConnector.loadGamesFromDropbox(); DropboxConnector.loadGamesFromDropbox();
DropboxConnector.log(DropboxConnector.client.credentials()); DropboxConnector.log(DropboxConnector.client.credentials());
DropboxConnector.client.getAccountInfo({}, function (error, info) { DropboxConnector.client.getAccountInfo({}, function (error, info) {
if (!error) { if (!error) {
DropboxConnector.dropboxAccount = info.email; DropboxConnector.dropboxAccount = info.email;
} }
}); });
DropboxConnector.log("Got savegames", DropboxConnector.savegames); DropboxConnector.log("Got savegames", DropboxConnector.savegames);
if (typeof callback === "function") { if (typeof callback === "function") {
callback.call(DropboxConnector.table); callback.call(DropboxConnector.table);
} }
} }
}); });
} else { } else {
DropboxConnector.log('Not connected to dropbox.'); DropboxConnector.log('Not connected to dropbox.');
} }
}, },
/** /**
* Requests your savegames fom dbds * Requests your savegames fom dbds
* *
* @returns {*} * @returns {*}
*/ */
loadGamesFromDropbox: function () { loadGamesFromDropbox: function () {
var savegames = DropboxConnector.savegames; var savegames = DropboxConnector.savegames;
$.each(savegames, function (n) { $.each(savegames, function (n) {
var results = DropboxConnector.table.query({savegameId: DropboxConnector.prepareSavegameID(n)}); var results = DropboxConnector.table.query({savegameId: DropboxConnector.prepareSavegameID(n)});
savegames[n] = results[0]; savegames[n] = results[0];
}); });
return savegames; return savegames;
}, },
/** /**
* Imports a gamestate of a given slotnumber to your game * Imports a gamestate of a given slotnumber to your game
* *
* @param slotnumber * @param slotnumber
*/ */
loadGameFromDropbox: function (slotnumber) { loadGameFromDropbox: function (slotnumber) {
var table = DropboxConnector.table; var table = DropboxConnector.table;
var id = DropboxConnector.prepareSavegameID(slotnumber); var id = DropboxConnector.prepareSavegameID(slotnumber);
var results = table.query({savegameId: id}); var results = table.query({savegameId: id});
var record = results[0]; var record = results[0];
if (record && record.get('gameState')) { if (record && record.get('gameState')) {
Engine.import64(record.get('gameState')); Engine.import64(record.get('gameState'));
} }
}, },
/** /**
* Saves a gamestate to a given slot in dbds * Saves a gamestate to a given slot in dbds
* *
* @param slotnumber * @param slotnumber
* @param callback * @param callback
*/ */
saveGameToDropbox: function (slotnumber, callback) { saveGameToDropbox: function (slotnumber, callback) {
var table = DropboxConnector.table; var table = DropboxConnector.table;
var record = null; var record = null;
var success = false; var success = false;
var id = DropboxConnector.prepareSavegameID(slotnumber); var id = DropboxConnector.prepareSavegameID(slotnumber);
var saveGame = { var saveGame = {
gameState: Engine.generateExport64(), gameState: Engine.generateExport64(),
timestamp: new Date().getTime() timestamp: new Date().getTime()
}; };
if (DropboxConnector.savegames[slotnumber]) { // slot aleady used -> overwrite if (DropboxConnector.savegames[slotnumber]) { // slot aleady used -> overwrite
record = DropboxConnector.savegames[slotnumber]; record = DropboxConnector.savegames[slotnumber];
try { try {
record.update(saveGame); record.update(saveGame);
DropboxConnector.log("Updated savegame ", slotnumber); DropboxConnector.log("Updated savegame ", slotnumber);
success = true; success = true;
} catch (e) { } catch (e) {
success = false; success = false;
} }
} else { } else {
saveGame.savegameId = id; saveGame.savegameId = id;
try { try {
record = table.insert(saveGame); record = table.insert(saveGame);
DropboxConnector.log("Inserted savegame ", record.getId()); DropboxConnector.log("Inserted savegame ", record.getId());
success = true; success = true;
} catch (e) { } catch (e) {
success = false; success = false;
} }
} }
if (typeof callback === "function") { if (typeof callback === "function") {
callback(success); callback(success);
} }
}, },
/** /**
* Terminates the connection to your db account * Terminates the connection to your db account
*/ */
signout: function () { signout: function () {
DropboxConnector.client.signOut({}, function (error) { DropboxConnector.client.signOut({}, function (error) {
if (error) { if (error) {
alert('Error while logout from dropbox'); alert('Error while logout from dropbox');
} else { } else {
alert('Successfully signed out.'); alert('Successfully signed out.');
DropboxConnector.client = null; DropboxConnector.client = null;
DropboxConnector.savegames = null; DropboxConnector.savegames = null;
DropboxConnector.dropboxAccount = null; DropboxConnector.dropboxAccount = null;
} }
}); });
}, },
/** /**
* ************** * **************
* Helper methods * Helper methods
* ************** * **************
*/ */
prepareSavegameID: function (slotnumber) { prepareSavegameID: function (slotnumber) {
return 'adarkroom_savegame_' + slotnumber; return 'adarkroom_savegame_' + slotnumber;
}, },
prepareSaveDate: function (timestamp) { prepareSaveDate: function (timestamp) {
var date = new Date(timestamp); var date = new Date(timestamp);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString(); return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}, },
log: function () { log: function () {
if (this._log) { if (this._log) {
console.log(arguments); console.log(arguments);
} }
} }
}; };
Engine.Dropbox = DropboxConnector; Engine.Dropbox = DropboxConnector;
})(Engine, Events, Dropbox, jQuery); })(Engine, Events, Dropbox, jQuery);
+16 -16
View File
@@ -78,7 +78,7 @@
state: null, state: null,
debug: false, debug: false,
log: false, log: false,
dropbox: true dropbox: true
}, },
init: function(options) { init: function(options) {
@@ -152,37 +152,37 @@
.text(_('save.')) .text(_('save.'))
.click(Engine.exportImport) .click(Engine.exportImport)
.appendTo(menu); .appendTo(menu);
if(this.options.dropbox && Engine.Dropbox) {
this.dropbox = Engine.Dropbox.init();
$('<span>')
.addClass('menuBtn')
.text(_('dropbox.'))
.click(Engine.Dropbox.startDropbox)
.appendTo(menu);
}
$('<span>') $('<span>')
.addClass('menuBtn') .addClass('menuBtn')
.text(_('app store.')) .text(_('app store.'))
.click(function() { window.open('https://itunes.apple.com/us/app/a-dark-room/id736683061'); }) .click(function() { window.open('https://itunes.apple.com/us/app/a-dark-room/id736683061'); })
.appendTo(menu); .appendTo(menu);
if(this.options.dropbox && Engine.Dropbox) {
this.dropbox = Engine.Dropbox.init();
$('<span>')
.addClass('menuBtn')
.text(_('dropbox.'))
.click(Engine.Dropbox.startDropbox)
.appendTo(menu);
}
// Register keypress handlers // Register keypress handlers
$('body').off('keydown').keydown(Engine.keyDown); $('body').off('keydown').keydown(Engine.keyDown);
$('body').off('keyup').keyup(Engine.keyUp); $('body').off('keyup').keyup(Engine.keyUp);
// Register swipe handlers // Register swipe handlers
swipeElement = $('#outerSlider'); swipeElement = $('#outerSlider');
swipeElement.on('swipeleft', Engine.swipeLeft); swipeElement.on('swipeleft', Engine.swipeLeft);
swipeElement.on('swiperight', Engine.swipeRight); swipeElement.on('swiperight', Engine.swipeRight);
swipeElement.on('swipeup', Engine.swipeUp); swipeElement.on('swipeup', Engine.swipeUp);
swipeElement.on('swipedown', Engine.swipeDown); swipeElement.on('swipedown', Engine.swipeDown);
//subscribe to stateUpdates // subscribe to stateUpdates
$.Dispatch('stateUpdate').subscribe(Engine.handleStateUpdates); $.Dispatch('stateUpdate').subscribe(Engine.handleStateUpdates);
$SM.init(); $SM.init();
Notifications.init(); Notifications.init();
Events.init(); Events.init();