ChatJSONLog.js

// 
// there doesn't seem to be a json logger, so what the heck, i just feel like making one
/*
	notes:
	1. best to use a GET request to parse the existing json, add the new contents, and then edit
*/
(function() {
	var a = {
			"date": (function(a) {
					var MM = a.getMonth() + 1,
						DD = a.getUTCDate();
					function pad(n) {
				 		return String(n).length == 1 ? "0" + n : n;
					}
					return a.getUTCFullYear() + "-" + pad(MM) + "-" + pad(DD);
				}(new Date())), // date
			"notes": [], // notes
//			"loggers": [], // userids of chat loggers
			"users": [], // userids array
			"buffer": [], // array of messages that have yet to be saved. merged with 'this.messages' when publishing, and is then blanked
			"messages": [] // array of all saved messages
		},
		b = new MutationObserver(function() {
			var obj = mainRoom.model.chats.models;
			while (a.messages.length + a.buffer.length < obj.length) {
				var i = a.messages.length + a.buffer.length,
					alert = obj[i].attributes.isInlineAlert ? true : false, // is inline alert?
					userid = alert ? -1 : Number(obj[i].attributes.avatarSrc.match(/\/\d+\.[a-z]+/g)[0].substr(1).split(".")[0]);
				if (userid > -1 && a.users.indexOf(userid) == -1) {
					a.users.push(userid);
				}
				a.buffer.push({
					u: userid,
					ts: obj[i].attributes.timeStamp,
					t: obj[i].attributes.text,
					c: obj[i].attributes.continued
				});
			}
		});
	window.chat_logger = $('').html(0);
	b.observe(chat_logger[0],{childList: true});
	$("body").on("DOMNodeInserted", ".Chat:first > ul > li", function(e) {
		$(chat_logger).html(Number($(chat_logger).html()) + 1);
	});
	function save() {
		a.messages = a.messages.concat(a.buffer);
		a.buffer = [];
		var url = "/api.php?action=edit&format=json&title=" + encodeURIComponent("Project:Chat/logs/" + a.date + ".js") + "&contentformat=application/json&bot&minor&text=" + encodeURIComponent(JSON.stringify(a)) + "&token=" + encodeURIComponent(mw.user.tokens.get("editToken"));
		$.ajax({
			url: url,
			type: "POST",
			success: function() {
				console.log("chat_logger: Saved.");
			},
			error: function() {
				console.log("chat_logger: Error; There was an error publishing the most recent logs.");
			}
		});
		console.log(location.origin + url);
	}
	$('').css({
		"display": "inline-block",
		"width": "16px",
		"height": "16px",
		"position": "absolute",
		"bottom": "7px",
		"left": "7px",
		"background": "url('http://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Format-indent-more.svg/16px-Format-indent-more.svg.png') center no-repeat",
		"cursor": "hand",
		"cursor": "pointer"
	}).attr({
		"title": "Click here to save the logs"
	}).click(function() {
		save();
	}).appendTo(
		"form#Write"
	);
}());
//