Tip: Upload file with content generated by javascript

Here is a tip to save information on the Vera from javascript (client side).

The javascript part :

function _getCgiUrl() {
	var protocol = document.location.protocol;
	var host = document.location.hostname;
	var httpPort = document.location.port;
	var pathName = window.location.pathname;
	var cgiUrl = protocol + "//" + host;

	if ( pathName.indexOf( "/port_3480" ) !== -1 ) {
		// Relay mode
		pathName = pathName.replace( "/port_3480", "" )
		if ( httpPort != "" ) {
			cgiUrl = cgiUrl + ":" + httpPort;
		}
	}
	cgiUrl = cgiUrl + pathName.replace( "/data_request", "" ) + "/cgi-bin/cmh";
	return cgiUrl;
};

function upload( fileName, content, contentType ) {
	var blob = new Blob( [content], { type: contentType } );

	var fd = new FormData();
	fd.append( "upnp_file_1", blob );
	fd.append( "upnp_file_1_name", fileName );

	$.ajax( {
		method: "POST",
		url: _getCgiUrl() + "/upload_upnp_file.sh",
		data: fd,
		contentType: false,
		processData: false
	} )
	.done( function( data ) {
		console.log( data );
	} );
}

upload( "test.xml", "<xml>test</xml>", "text/xml" );

The LUA part to use the content uploaded :

local decompressScript = [[
decompress_lzo_file_in_tmp() {
	SRC_FILE=/etc/cmh-ludl/$1.lzo
	DEST_FILE=/tmp/$1
	if [ ! -e $DEST_FILE -o $SRC_FILE -nt $DEST_FILE ]
	then
		TEMP_FILE=$(mktemp)
		pluto-lzo d $SRC_FILE $TEMP_FILE
		mv $TEMP_FILE $DEST_FILE
	fi
}
]]

function loadFile (fileName)
	local lfs = require("lfs")
	local path = ""
	if lfs.attributes("/etc/cmh-ludl/" .. fileName .. ".lzo", "mode") then
		path = "/tmp/"
		os.execute(decompressScript .. "decompress_lzo_file_in_tmp " .. fileName)
	end
	local file = io.open(path .. fileName)
	assert(file ~= nil)
	for line in file:lines() do
		-- do something with line
	end
	file:close()
end