Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TIMOB-12265] Fixed bugs in the analytics library when the user is offline. #18

Merged
merged 1 commit into from
Jan 12, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
276 changes: 107 additions & 169 deletions lib/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ var path = require('path'),
urlEncode = require('./net').urlEncode,
events = [],
url = 'https://api.appcelerator.net/p/v1/app-track',
needsEnroll = false,
sessionTimeout = 60 * 60 * 1000; // 1 hour

exports.addEvent = function (name, data, type) {
Expand All @@ -37,201 +36,140 @@ exports.addEvent = function (name, data, type) {
exports.send = function (args) {
var child = require('child_process').fork(module.filename);
args.events = events;
child.send(mix(args, { doEnroll: needsEnroll }));
needsEnroll = false;
};

exports.enroll = function() {
needsEnroll = true;
child.send(args);
};

process.on('message', function(m) {
if (!m || !['appId', 'appName', 'appGuid', 'directory', 'version', 'doEnroll'].every(function (p) { return m.hasOwnProperty(p); })) {
if (!m || !['appId', 'appName', 'appGuid', 'directory', 'version'].every(function (p) { return m.hasOwnProperty(p); })) {
return;
}

var appId = m.appId,
appName = m.appName,
appGuid = m.appGuid,
directory = afs.resolvePath(m.directory),
sessionFile = path.join(directory, 'analytics_session.json'),
logFile = path.join(directory, 'analytics.json'),
version = m.version,
deployType = m.deployType,
events = m.events,
payload = [],
seqId = 0,
sid,
mid,
sessionExpiration,
doEnroll = m.doEnroll,
OSInfo,
requests = [];

function add(type, event, id, ts, data) {
payload.push(mix({
event: event,
type: type,
sid: sid,
guid: appGuid,
mid: mid,
creator_user_id: m.uid,
app_name: appName,
app_version: version,
// mac_addr: ,
version: '1.1.0',
tz: (new Date()).getTimezoneOffset(),
ver: '2',
un: m.email,
// ip: ,
data: JSON.stringify(data),
id: id || uuid.v4(),
}, OSInfo));
}

async.series([
function (next) {
auth.getMID(function(fetchedMID) {
mid = fetchedMID;
doEnroll = doEnroll || needsEnroll;
next();
async.parallel({
mid: function (cb) {
auth.getMID(function(mid) {
cb(null, mid);
});
},

function (next) {
osinfo: function (cb) {
getOSInfo(function (info) {
OSInfo = info;
next();
cb(null, info);
});
},

function (next) {

var analyticsSession,
restoredPreviousSession = false;

directory = afs.resolvePath(directory);
afs.exists(directory) || wrench.mkdirSyncRecursive(directory);

deployType = deployType || 'production';

// Do we have a valid session
if (afs.exists(sessionFile)) {
try {
var analyticsSession = JSON.parse(fs.readFileSync(sessionFile));
sid = analyticsSession.sid;
seqId = analyticsSession.seqId;
sessionExpiration = analyticsSession.sessionExpiration;

// If the expiration has expired, create a new one
if (sessionExpiration > Date.now()) {
restoredPreviousSession = true;
}
} catch (e) {} // file was malformed, treat as if a new session
}

// If the previous session was not restored, create a new one
if (!restoredPreviousSession) {
sid = uuid.v4();
sessionExpiration = Date.now() + sessionTimeout;
}

// Studio does not use an enroll event
// // Enroll if need be
// if (doEnroll) {
// add('ti.enroll', 'ti.enroll', null, null, mix({
// app_id: appId,
// app_name: appName || 'node-appc',
// deploytype: deployType,
// platform: 'node.js'
// }, OSInfo));
// }
next();
},
}
}, function (err, results) {
var directory = afs.resolvePath(m.directory),
sessionFile = path.join(directory, 'analytics_session.json'),
logFile = path.join(directory, 'analytics.json'),
payload = [],
payloadRetry = [],
restoredPreviousSession = false,
now = (new Date).getTime(),
mid = results.mid,
sid,
sessionExpiration;

function (next) {
var logExists = afs.exists(logFile),
logMtime = logExists ? fs.statSync(logFile).mtime : 0;

// when was the last event?
if (!logExists || Date.now() - logMtime > sessionTimeout) {
if (logExists) {
function add(type, event, id, ts, data) {
payload.push(mix({
event: event,
type: type,
sid: sid,
guid: m.appGuid,
mid: mid,
creator_user_id: m.uid,
app_id: m.appId,
app_name: m.appName,
app_version: m.version,
version: '1.1.0',
tz: (new Date()).getTimezoneOffset(),
ver: '2',
un: m.email,
data: JSON.stringify(data),
id: id || uuid.v4(),
}, results.osinfo));
}

afs.exists(directory) || wrench.mkdirSyncRecursive(directory);

// Do we have a valid session
if (afs.exists(sessionFile)) {
try {
var analyticsSession = JSON.parse(fs.readFileSync(sessionFile));

sid = analyticsSession.sid;
sessionExpiration = analyticsSession.sessionExpiration;

// If the expiration has expired, create a new one
if (sid && sessionExpiration && sessionExpiration > now) {
restoredPreviousSession = true;
} else {
// add the ti.end event
add('ti.end', 'ti.end', null, null);
// need to generate a new session id
fs.writeFileSync(sessionFile, JSON.stringify({ sid: sid = uuid.v4(), seqId: seqId = 0, sessionExpiration: Date.now() }));
}

add('ti.start', 'ti.start', null, null, null);
}
next();
} catch (e) {} // file was malformed, treat as if a new session
}
], function () {
var tmp,
i;


// If the previous session was not restored, create a new one
if (!restoredPreviousSession) {
// need to generate a new session id
fs.writeFileSync(sessionFile, JSON.stringify({
mid: mid,
sid: sid = uuid.v4(),
sessionExpiration: sessionExpiration = now + sessionTimeout
}));

add('ti.start', 'ti.start', null, null, null);
}

// add the list of app.feature events
events.forEach(function (evt) {
m.events.forEach(function (evt) {
add(evt.type, evt.name, evt.id, evt.ts, evt.data);
});

// append payload to disk
if (afs.exists(logFile)) {
try {
tmp = JSON.parse(fs.readFileSync(logFile));
} catch (e) {
tmp = [];
}
payload = tmp.concat(payload);
payload = JSON.parse(fs.readFileSync(logFile)).concat(payload);
} catch (e) {}
}


function save() {
// save events that failed to send
fs.writeFileSync(logFile, JSON.stringify(payloadRetry));

// make sure we save the latest session expiration
fs.writeFileSync(sessionFile, JSON.stringify({
mid: mid,
sid: sid,
sessionExpiration: (new Date).getTime() + sessionTimeout
}));
}

if (payload.length) {
// record the events before posting just in case of a problem
fs.writeFileSync(logFile, JSON.stringify(payload, null, ''));
fs.writeFileSync(logFile, JSON.stringify(payload));

// console.log(payload);

var cookie = auth.status().cookie;

// send the request
for (i = 0; i < payload.length ; i++) {
requests.push(createRequest(i, payload, cookie));
}

// Reset the tmp array
tmp = [];

async.parallel(requests, function (err, results) {

for (i = 0; i < results.length; i++) {
if (typeof results[i] == 'number') {
tmp.push(payload[results[i]])
}
}

// save events that failed to send
fs.writeFileSync(logFile, JSON.stringify(tmp));

// make sure we save the latest seqId
fs.writeFileSync(sessionFile, JSON.stringify({ sid: sid, mid: mid, seqId: seqId }));

});
async.series(payload.map(function (data) {
return function (callback) {
request({
uri: url,
method: 'POST',
headers: {
Cookie: auth.status().cookie
},
body: urlEncode(data)
}, function (error, response, body) {
// Return the index if it failed and it needs to be written to the logfile again
if (error || response.statusCode != 204) {
payloadRetry.push(data);
}
callback();
});
};
}), save);
} else {
save();
}
});
});

function createRequest (index, payload, cookie) {
return function(callback) {
request({
uri: url,
method: 'POST',
headers: {
Cookie: cookie
},
body: urlEncode(payload[index])
}, function (error, response, body) {
// Return the index if it failed and it needs to be written to the logfile again
callback(error, (!error && response.statusCode == 204) ? undefined : index);
});
};
}
});
3 changes: 0 additions & 3 deletions lib/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,6 @@ exports.getMID = function (callback) {
}
fs.writeFileSync(midFile, JSON.stringify({ mid: mid }));

// Enroll in analytics, since creating a new MID is basically a new installation
analytics.enroll();

callback && callback(mid);
});
}
Expand Down