# HG changeset patch # User veltr # Date 1345649367 -7200 # Node ID e27a08b0a03798deca9ab2f06f53cc3551706869 # Parent ed1126cd2b803d07726bd76041f840189cb09e49 Added Tagger and POST/PUT test diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/jwplayer.htm --- a/metadataplayer/jwplayer.htm Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/jwplayer.htm Wed Aug 22 17:29:27 2012 +0200 @@ -39,11 +39,10 @@ { type: "Slice" }, { type: "Arrow" }, { type: "Annotation" }, -/* { - type: "CreateAnnotation", - api_endpoint_template: "http://192.168.56.101/pf/ldtplatform/api/ldt/annotations/{{id}}.json", - creator_name: "Metadataplayer" - }, */ + { + type: "Tagger", + api_endpoint: "post-test.php", + }, { type: "Tweet" }, { type: "Tagcloud", diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/libs/ZeroClipboard.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/metadataplayer/libs/ZeroClipboard.js Wed Aug 22 17:29:27 2012 +0200 @@ -0,0 +1,311 @@ +// Simple Set Clipboard System +// Author: Joseph Huckaby + +var ZeroClipboard = { + + version: "1.0.7", + clients: {}, // registered upload clients on page, indexed by id + moviePath: 'ZeroClipboard.swf', // URL to movie + nextId: 1, // ID of next movie + + $: function(thingy) { + // simple DOM lookup utility function + if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); + if (!thingy.addClass) { + // extend element with a few useful methods + thingy.hide = function() { this.style.display = 'none'; }; + thingy.show = function() { this.style.display = ''; }; + thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; + thingy.removeClass = function(name) { + var classes = this.className.split(/\s+/); + var idx = -1; + for (var k = 0; k < classes.length; k++) { + if (classes[k] == name) { idx = k; k = classes.length; } + } + if (idx > -1) { + classes.splice( idx, 1 ); + this.className = classes.join(' '); + } + return this; + }; + thingy.hasClass = function(name) { + return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); + }; + } + return thingy; + }, + + setMoviePath: function(path) { + // set path to ZeroClipboard.swf + this.moviePath = path; + }, + + dispatch: function(id, eventName, args) { + // receive event from flash movie, send to client + var client = this.clients[id]; + if (client) { + client.receiveEvent(eventName, args); + } + }, + + register: function(id, client) { + // register new client to receive events + this.clients[id] = client; + }, + + getDOMObjectPosition: function(obj, stopObj) { + // get absolute coordinates for dom element + var info = { + left: 0, + top: 0, + width: obj.width ? obj.width : obj.offsetWidth, + height: obj.height ? obj.height : obj.offsetHeight + }; + + while (obj && (obj != stopObj)) { + info.left += obj.offsetLeft; + info.top += obj.offsetTop; + obj = obj.offsetParent; + } + + return info; + }, + + Client: function(elem) { + // constructor for new simple upload client + this.handlers = {}; + + // unique ID + this.id = ZeroClipboard.nextId++; + this.movieId = 'ZeroClipboardMovie_' + this.id; + + // register client with singleton to receive flash events + ZeroClipboard.register(this.id, this); + + // create movie + if (elem) this.glue(elem); + } +}; + +ZeroClipboard.Client.prototype = { + + id: 0, // unique ID for us + ready: false, // whether movie is ready to receive events or not + movie: null, // reference to movie object + clipText: '', // text to copy to clipboard + handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor + cssEffects: true, // enable CSS mouse effects on dom container + handlers: null, // user event handlers + + glue: function(elem, appendElem, stylesToAdd) { + // glue to DOM element + // elem can be ID or actual DOM element object + this.domElement = ZeroClipboard.$(elem); + + // float just above object, or zIndex 99 if dom element isn't set + var zIndex = 99; + if (this.domElement.style.zIndex) { + zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; + } + + if (typeof(appendElem) == 'string') { + appendElem = ZeroClipboard.$(appendElem); + } + else if (typeof(appendElem) == 'undefined') { + appendElem = document.getElementsByTagName('body')[0]; + } + + // find X/Y position of domElement + var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); + + // create floating DIV above element + this.div = document.createElement('div'); + var style = this.div.style; + style.position = 'absolute'; + style.left = '' + box.left + 'px'; + style.top = '' + box.top + 'px'; + style.width = '' + box.width + 'px'; + style.height = '' + box.height + 'px'; + style.zIndex = zIndex; + + if (typeof(stylesToAdd) == 'object') { + for (addedStyle in stylesToAdd) { + style[addedStyle] = stylesToAdd[addedStyle]; + } + } + + // style.backgroundColor = '#f00'; // debug + + appendElem.appendChild(this.div); + + this.div.innerHTML = this.getHTML( box.width, box.height ); + }, + + getHTML: function(width, height) { + // return HTML for movie + var html = ''; + var flashvars = 'id=' + this.id + + '&width=' + width + + '&height=' + height; + + if (navigator.userAgent.match(/MSIE/)) { + // IE gets an OBJECT tag + var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; + html += ''; + } + else { + // all other browsers get an EMBED tag + html += ''; + } + return html; + }, + + hide: function() { + // temporarily hide floater offscreen + if (this.div) { + this.div.style.left = '-2000px'; + } + }, + + show: function() { + // show ourselves after a call to hide() + this.reposition(); + }, + + destroy: function() { + // destroy control and floater + if (this.domElement && this.div) { + this.hide(); + this.div.innerHTML = ''; + + var body = document.getElementsByTagName('body')[0]; + try { body.removeChild( this.div ); } catch(e) {;} + + this.domElement = null; + this.div = null; + } + }, + + reposition: function(elem) { + // reposition our floating div, optionally to new container + // warning: container CANNOT change size, only position + if (elem) { + this.domElement = ZeroClipboard.$(elem); + if (!this.domElement) this.hide(); + } + + if (this.domElement && this.div) { + var box = ZeroClipboard.getDOMObjectPosition(this.domElement); + var style = this.div.style; + style.left = '' + box.left + 'px'; + style.top = '' + box.top + 'px'; + } + }, + + setText: function(newText) { + // set text to be copied to clipboard + this.clipText = newText; + if (this.ready) this.movie.setText(newText); + }, + + addEventListener: function(eventName, func) { + // add user event listener for event + // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel + eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + if (!this.handlers[eventName]) this.handlers[eventName] = []; + this.handlers[eventName].push(func); + }, + + setHandCursor: function(enabled) { + // enable hand cursor (true), or default arrow cursor (false) + this.handCursorEnabled = enabled; + if (this.ready) this.movie.setHandCursor(enabled); + }, + + setCSSEffects: function(enabled) { + // enable or disable CSS effects on DOM container + this.cssEffects = !!enabled; + }, + + receiveEvent: function(eventName, args) { + // receive event from flash + eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + + // special behavior for certain events + switch (eventName) { + case 'load': + // movie claims it is ready, but in IE this isn't always the case... + // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function + this.movie = document.getElementById(this.movieId); + if (!this.movie) { + var self = this; + setTimeout( function() { self.receiveEvent('load', null); }, 1 ); + return; + } + + // firefox on pc needs a "kick" in order to set these in certain cases + if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { + var self = this; + setTimeout( function() { self.receiveEvent('load', null); }, 100 ); + this.ready = true; + return; + } + + this.ready = true; + this.movie.setText( this.clipText ); + this.movie.setHandCursor( this.handCursorEnabled ); + break; + + case 'mouseover': + if (this.domElement && this.cssEffects) { + this.domElement.addClass('hover'); + if (this.recoverActive) this.domElement.addClass('active'); + } + break; + + case 'mouseout': + if (this.domElement && this.cssEffects) { + this.recoverActive = false; + if (this.domElement.hasClass('active')) { + this.domElement.removeClass('active'); + this.recoverActive = true; + } + this.domElement.removeClass('hover'); + } + break; + + case 'mousedown': + if (this.domElement && this.cssEffects) { + this.domElement.addClass('active'); + } + break; + + case 'mouseup': + if (this.domElement && this.cssEffects) { + this.domElement.removeClass('active'); + this.recoverActive = false; + } + break; + } // switch eventName + + if (this.handlers[eventName]) { + for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { + var func = this.handlers[eventName][idx]; + + if (typeof(func) == 'function') { + // actual function reference + func(this, args); + } + else if ((typeof(func) == 'object') && (func.length == 2)) { + // PHP style object + method, i.e. [myObject, 'myMethod'] + func[0][ func[1] ](this, args); + } + else if (typeof(func) == 'string') { + // name of function + window[func](this, args); + } + } // foreach event handler defined + } // user defined handler for event + } + +}; diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/libs/ZeroClipboard.swf Binary file metadataplayer/libs/ZeroClipboard.swf has changed diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/libs/json2.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/metadataplayer/libs/json2.js Wed Aug 22 17:29:27 2012 +0200 @@ -0,0 +1,487 @@ +/* + json2.js + 2011-10-19 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +var JSON; +if (!JSON) { + JSON = {}; +} + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + if (typeof Date.prototype.toJSON !== 'function') { + + Date.prototype.toJSON = function (key) { + + return isFinite(this.valueOf()) + ? this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z' + : null; + }; + + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } + + +// If the JSON object does not yet have a parse method, give it one. + + if (typeof JSON.parse !== 'function') { + JSON.parse = function (text, reviver) { + +// The parse method takes a text and an optional reviver function, and returns +// a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + +// The walk method is used to recursively walk the resulting structure so +// that modifications can be made. + + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + + +// Parsing happens in four stages. In the first stage, we replace certain +// Unicode characters with escape sequences. JavaScript handles many characters +// incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text); + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + +// In the second stage, we run the text against regular expressions that look +// for non-JSON patterns. We are especially concerned with '()' and 'new' +// because they can cause invocation, and '=' because it can cause mutation. +// But just to be safe, we want to reject all unexpected forms. + +// We split the second stage into 4 regexp operations in order to work around +// crippling inefficiencies in IE's and Safari's regexp engines. First we +// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we +// replace all simple value tokens with ']' characters. Third, we delete all +// open brackets that follow a colon or comma or that begin the text. Finally, +// we look to see that the remaining characters are only whitespace or ']' or +// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + +// In the third stage we use the eval function to compile the text into a +// JavaScript structure. The '{' operator is subject to a syntactic ambiguity +// in JavaScript: it can begin a block or an object literal. We wrap the text +// in parens to eliminate the ambiguity. + + j = eval('(' + text + ')'); + +// In the optional fourth stage, we recursively walk the new structure, passing +// each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' + ? walk({'': j}, '') + : j; + } + +// If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError('JSON.parse'); + }; + } +}()); diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/libs/tracemanager.js --- a/metadataplayer/libs/tracemanager.js Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/libs/tracemanager.js Wed Aug 22 17:29:27 2012 +0200 @@ -1,540 +1,540 @@ -/* - * Modelled Trace API - * - * This file is part of ktbs4js. - * - * ktbs4js is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * ktbs4js is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with ktbs4js. If not, see . - * - */ -/* FIXME: properly use require.js feature. This will do for debugging in the meantime */ -window.tracemanager = (function($) { - // If there are more than MAX_FAILURE_COUNT synchronisation - // failures, then disable synchronisation - MAX_FAILURE_COUNT = 20; - - // If there are more than MAX_BUFFER_SIZE obsels in the buffer, - // then "compress" them as a single "ktbsFullBuffer" - MAX_BUFFER_SIZE = 500; - - var BufferedService_prototype = { - /* - * Buffered service for traces - */ - // url: "", - // buffer: [], - // isReady: false, - // timer: null, - // failureCount: 0, - - /* Flush buffer */ - flush: function() { - // FIXME: add mutex on this.buffer - if (! this.isReady) - { - if (window.console) window.console.log("Sync service not ready"); - } else if (this.failureCount > MAX_FAILURE_COUNT) - { - // Disable synchronisation - this.set_sync_mode('none'); - } else if (this.buffer.length) { - var temp = this.buffer; - this.buffer = []; - - if (this.mode == 'GET') - { - // GET mode: do some data mangline. We mark the - // "compressed" nature of the generated JSON by - // prefixing it with c - var data = 'c' + JSON.stringify(temp.map(function (o) { return o.toCompactJSON(); })); - // Swap " (very frequent, which will be - // serialized into %22) and ; (rather rare), this - // saves some bytes - data = data.replace(/[;"#]/g, function(s){ return s == ';' ? '"' : ( s == '"' ? ';' : '%23'); }); - // FIXME: check data length (< 2K is safe) - var request=$('').error( function() { this.failureCount += 1; }) - .load( function() { this.failureCount = 0; }) - .attr('src', this.url + 'trace/?data=' + data); - } - else - { - $.ajax({ url: this.url + 'trace/', - type: 'POST', - contentType: 'application/json', - data: JSON.stringify(temp.map(function (o) { return o.toJSON(); })), - processData: false, - // Type of the returned data. - dataType: "html", - error: function(jqXHR, textStatus, errorThrown) { - if (window.console) window.console.log("Error when sending buffer:", textStatus); - this.failureCount += 1; - }, - success: function(data, textStatus, jqXHR) { - // Reset failureCount to 0 as soon as there is 1 valid answer - this.failureCount = 0; - } - }); - } - } - }, - - /* Sync mode: delayed, sync (immediate sync), none (no - * synchronisation with server, the trace has to be explicitly saved - * if needed */ - set_sync_mode: function(mode, default_subject) { - this.sync_mode = mode; - if (! this.isReady && mode !== "none") - this.init(default_subject); - if (mode == 'delayed') { - this.start_timer(); - } else { - this.stop_timer(); - } - }, - - /* Enqueue an obsel */ - enqueue: function(obsel) { - if (this.buffer.length > MAX_BUFFER_SIZE) - { - obsel = new Obsel('ktbsFullBuffer', this.buffer[0].begin, - this.buffer[this.buffer.length - 1].end, this.buffer[0].subject); - obsel.trace = this.buffer[0].trace; - this.buffer = []; - } - this.buffer.push(obsel); - if (this.sync_mode === 'sync') { - // Immediate sync of the obsel. - this.flush(); - } - }, - - start_timer: function() { - var self = this; - if (this.timer === null) { - this.timer = window.setInterval(function() { - self.flush(); - }, this.timeOut); - } - }, - - stop_timer: function() { - if (this.timer !== null) { - window.clearInterval(this.timer); - this.timer = null; - } - }, - - /* - * Initialize the sync service - */ - init: function(default_subject) { - var self = this; - if (this.isReady) - /* Already initialized */ - return; - if (typeof default_subject === 'undefined') - default_subject = 'anonymous'; - if (this.mode == 'GET') - { - var request=$('').attr('src', this.url + 'login?userinfo={"default_subject": "' + default_subject + '"}'); - // Do not wait for the return, assume it is - // initialized. This assumption will not work anymore - // if login returns some necessary information - this.isReady = true; - } - else - { - $.ajax({ url: this.url + 'login', - type: 'POST', - data: 'userinfo={"default_subject":"' + default_subject + '"}', - success: function(data, textStatus, jqXHR) { - self.isReady = true; - if (self.buffer.length) { - self.flush(); - } - } - }); - } - } - }; - var BufferedService = function(url, mode) { - this.url = url; - this.buffer = []; - this.isReady = false; - this.timer = null; - this.failureCount = 0; - // sync_mode is either "none", "sync" or "buffered" - this.sync_mode = "none"; - /* mode can be either POST or GET */ - if (mode == 'POST' || mode == 'GET') - this.mode = mode; - else - this.mode = 'POST'; - /* Flush buffer every timeOut ms if the sync_mode is delayed */ - this.timeOut = 2000; - }; - BufferedService.prototype = BufferedService_prototype; - - var Trace_prototype = { - /* FIXME: We could/should use a sorted list such as - http://closure-library.googlecode.com/svn/docs/class_goog_structs_AvlTree.html - to speed up queries based on time */ - obsels: [], - /* Trace URI */ - uri: "", - default_subject: "", - /* baseuri is used as the base URI to resolve relative - * attribute-type names in obsels. Strictly speaking, this - * should rather be expressed as a reference to model, or - * more generically, as a qname/URI dict */ - baseuri: "", - /* Mapping of obsel type or property name to a compact - * representation (shorthands). - */ - shorthands: null, - syncservice: null, - - /* Define the trace URI */ - set_uri: function(uri) { - this.uri = uri; - }, - - /* Sync mode: delayed, sync (immediate sync), none (no - * synchronisation with server, the trace has to be explicitly saved - * if needed */ - set_sync_mode: function(mode) { - if (this.syncservice !== null) { - this.syncservice.set_sync_mode(mode, this.default_subject); - } - }, - - /* - * Return a list of the obsels of this trace matching the parameters - */ - list_obsels: function(_begin, _end, _reverse) { - var res; - if (typeof _begin !== 'undefined' || typeof _end !== 'undefined') { - /* - * Not optimized yet. - */ - res = []; - var l = this.obsels.length; - for (var i = 0; i < l; i++) { - var o = this.obsels[i]; - if ((typeof _begin !== 'undefined' && o.begin > _begin) && (typeof _end !== 'undefined' && o.end < _end)) { - res.push(o); - } - } - } - - if (typeof _reverse !== 'undefined') { - if (res !== undefined) { - /* Should reverse the whole list. Make a copy. */ - res = this.obsels.slice(0); - } - res.sort(function(a, b) { return b.begin - a.begin; }); - return res; - } - - if (res === undefined) { - res = this.obsels; - } - return res; - - }, - - /* - * Return the obsel of this trace identified by the URI, or undefined - */ - get_obsel: function(id) { - for (var i = 0; i < this.obsels.length; i++) { - /* FIXME: should check against variations of id/uri, take this.baseuri into account */ - if (this.obsels[i].uri === id) { - return this.obsels[i]; - } - } - return undefined; - }, - - set_default_subject: function(subject) { - // FIXME: if we call this method after the sync_service - // init method, then the default_subject will not be - // consistent anymore. Maybe we should then call init() again? - this.default_subject = subject; - }, - - get_default_subject: function() { - return this.default_subject; - }, - - /* (type:ObselType, begin:int, end:int?, subject:str?, attributes:[AttributeType=>any]?) */ - /* Create a new obsel and add it to the trace */ - create_obsel: function(type, begin, end, subject, _attributes) { - var o = new Obsel(type, begin, end, subject); - if (typeof _attributes !== 'undefined') { - o.attributes = _attributes; - } - o.trace = this; - this.obsels.push(o); - if (this.syncservice !== null) - this.syncservice.enqueue(o); - }, - - /* Helper methods */ - - /* Create a new obsel with the given attributes */ - trace: function(type, _attributes, _begin, _end, _subject) { - var t = (new Date()).getTime(); - if (typeof begin === 'undefined') { - _begin = t; - } - if (typeof end === 'undefined') { - _end = _begin; - } - if (typeof subject === 'undefined') { - _subject = this.default_subject; - } - if (typeof _attributes === 'undefined') { - _attributes = {}; - } - return this.create_obsel(type, _begin, _end, _subject, _attributes); - } - }; - - var Trace = function(uri, requestmode) { - /* FIXME: We could/should use a sorted list such as - http://closure-library.googlecode.com/svn/docs/class_goog_structs_AvlTree.html - to speed up queries based on time */ - this.obsels = []; - /* Trace URI */ - if (uri === undefined) - uri = ""; - this.uri = uri; - this.sync_mode = "none"; - this.default_subject = ""; - this.shorthands = {}; - /* baseuri is used a the base URI to resolve relative attribute names in obsels */ - this.baseuri = ""; - - this.syncservice = new BufferedService(uri, requestmode); - $(window).unload( function () { - if (this.syncservice && this.sync_mode !== 'none') { - this.syncservice.flush(); - this.syncservice.stop_timer(); - } - }); - }; - Trace.prototype = Trace_prototype; - - var Obsel_prototype = { - /* The following attributes are here for documentation - * purposes. They MUST be defined in the constructor - * function. */ - trace: undefined, - type: undefined, - begin: undefined, - end: undefined, - subject: undefined, - /* Dictionary indexed by ObselType URIs */ - attributes: {}, - - /* Method definitions */ - get_trace: function() { - return this.trace; - }, - - get_obsel_type: function() { - return this.type; - }, - get_begin: function() { - return this.begin; - }, - get_end: function() { - return this.end; - }, - get_subject: function() { - return this.subject; - }, - - list_attribute_types: function() { - var result = []; - for (var prop in this.attributes) { - if (this.attributes.hasOwnProperty(prop)) - result.push(prop); - } - /* FIXME: we return URIs here instead of AttributeType elements */ - return result; - }, - - list_relation_types: function() { - /* FIXME: not implemented yet */ - }, - - list_related_obsels: function (rt) { - /* FIXME: not implemented yet */ - }, - list_inverse_relation_types: function () { - /* FIXME: not implemented yet */ - }, - list_relating_obsels: function (rt) { - /* FIXME: not implemented yet */ - }, - /* - * Return the value of the given attribute type for this obsel - */ - get_attribute_value: function(at) { - if (typeof at === "string") - /* It is a URI */ - return this.attributes[at]; - else - /* FIXME: check that at is instance of AttributeType */ - return this.attributes[at.uri]; - }, - - - /* obsel modification (trace amendment) */ - - set_attribute_value: function(at, value) { - if (typeof at === "string") - /* It is a URI */ - this.attributes[at] = value; - /* FIXME: check that at is instance of AttributeType */ - else - this.attributes[at.uri] = value; - }, - - del_attribute_value: function(at) { - if (typeof at === "string") - /* It is a URI */ - delete this.attributes[at]; - /* FIXME: check that at is instance of AttributeType */ - else - delete this.attributes[at.uri]; - }, - - add_related_obsel: function(rt, value) { - /* FIXME: not implemented yet */ - }, - - del_related_obsel: function(rt, value) { - /* FIXME: not implemented yet */ - }, - - /* - * Return a JSON representation of the obsel - */ - toJSON: function() { - var r = { - "@id": this.id, - "@type": this.type, - "begin": this.begin, - "end": this.end, - "subject": this.subject - }; - for (var prop in this.attributes) { - if (this.attributes.hasOwnProperty(prop)) - r[prop] = this.attributes[prop]; - } - return r; - }, - - /* - * Return a compact JSON representation of the obsel. - * Use predefined + custom shorthands for types/properties - */ - toCompactJSON: function() { - var r = { - "@t": (this.trace.shorthands.hasOwnProperty(this.type) ? this.trace.shorthands[this.type] : this.type), - "@b": this.begin, - }; - // Transmit subject only if different from default_subject - if (this.subject !== this.trace.default_subject) - r["@s"] = this.subject; - - // Store duration (to save some bytes) and only if it is non-null - if (this.begin !== this.end) - r["@d"] = this.end - this.begin; - - // Store id only if != "" - if (this.id !== "") - r["@i"] = this.id; - - for (var prop in this.attributes) { - if (this.attributes.hasOwnProperty(prop)) - { - var v = this.attributes[prop]; - r[prop] = this.trace.shorthands.hasOwnProperty(v) ? this.trace.shorthands[v] : v; - } - } - return r; - }, - - toJSONstring: function() { - return JSON.stringify(this.toJSON()); - } - }; - - var Obsel = function(type, begin, end, subject, attributes) { - this.trace = undefined; - this.uri = ""; - this.id = ""; - this.type = type; - this.begin = begin; - this.end = end; - this.subject = subject; - /* Is the obsel synched with the server ? */ - this.sync_status = false; - /* Dictionary indexed by ObselType URIs */ - this.attributes = {}; - }; - Obsel.prototype = Obsel_prototype; - - var TraceManager_prototype = { - traces: [], - /* - * Return the trace with id name - * If it was not registered, return undefined. - */ - get_trace: function(name) { - return this.traces[name]; - }, - - /* - * Explicitly create and initialize a new trace with the given name. - * The optional uri parameter allows to initialize the trace URI. - * - * If another existed with the same name before, then it is replaced by a new one. - */ - init_trace: function(name, params) - { - if (window.console) window.console.log("init_trace", params); - url = params.url ? params.url : ""; - requestmode = params.requestmode ? params.requestmode : "POST"; - syncmode = params.syncmode ? params.syncmode : "none"; - default_subject = params.default_subject ? params.default_subject : "default"; - var t = new Trace(url, requestmode); - t.set_default_subject(default_subject); - t.set_sync_mode(syncmode); - this.traces[name] = t; - return t; - } - }; - - var TraceManager = function() { - this.traces = {}; - }; - TraceManager.prototype = TraceManager_prototype; - - var tracemanager = new TraceManager(); - return tracemanager; - })(jQuery); +/* + * Modelled Trace API + * + * This file is part of ktbs4js. + * + * ktbs4js is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * ktbs4js is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with ktbs4js. If not, see . + * + */ +/* FIXME: properly use require.js feature. This will do for debugging in the meantime */ +window.tracemanager = (function($) { + // If there are more than MAX_FAILURE_COUNT synchronisation + // failures, then disable synchronisation + MAX_FAILURE_COUNT = 20; + + // If there are more than MAX_BUFFER_SIZE obsels in the buffer, + // then "compress" them as a single "ktbsFullBuffer" + MAX_BUFFER_SIZE = 500; + + var BufferedService_prototype = { + /* + * Buffered service for traces + */ + // url: "", + // buffer: [], + // isReady: false, + // timer: null, + // failureCount: 0, + + /* Flush buffer */ + flush: function() { + // FIXME: add mutex on this.buffer + if (! this.isReady) + { + if (window.console) window.console.log("Sync service not ready"); + } else if (this.failureCount > MAX_FAILURE_COUNT) + { + // Disable synchronisation + this.set_sync_mode('none'); + } else if (this.buffer.length) { + var temp = this.buffer; + this.buffer = []; + + if (this.mode == 'GET') + { + // GET mode: do some data mangline. We mark the + // "compressed" nature of the generated JSON by + // prefixing it with c + var data = 'c' + JSON.stringify(temp.map(function (o) { return o.toCompactJSON(); })); + // Swap " (very frequent, which will be + // serialized into %22) and ; (rather rare), this + // saves some bytes + data = data.replace(/[;"#]/g, function(s){ return s == ';' ? '"' : ( s == '"' ? ';' : '%23'); }); + // FIXME: check data length (< 2K is safe) + var request=$('').error( function() { this.failureCount += 1; }) + .load( function() { this.failureCount = 0; }) + .attr('src', this.url + 'trace/?data=' + data); + } + else + { + $.ajax({ url: this.url + 'trace/', + type: 'POST', + contentType: 'application/json', + data: JSON.stringify(temp.map(function (o) { return o.toJSON(); })), + processData: false, + // Type of the returned data. + dataType: "html", + error: function(jqXHR, textStatus, errorThrown) { + if (window.console) window.console.log("Error when sending buffer:", textStatus); + this.failureCount += 1; + }, + success: function(data, textStatus, jqXHR) { + // Reset failureCount to 0 as soon as there is 1 valid answer + this.failureCount = 0; + } + }); + } + } + }, + + /* Sync mode: delayed, sync (immediate sync), none (no + * synchronisation with server, the trace has to be explicitly saved + * if needed */ + set_sync_mode: function(mode, default_subject) { + this.sync_mode = mode; + if (! this.isReady && mode !== "none") + this.init(default_subject); + if (mode == 'delayed') { + this.start_timer(); + } else { + this.stop_timer(); + } + }, + + /* Enqueue an obsel */ + enqueue: function(obsel) { + if (this.buffer.length > MAX_BUFFER_SIZE) + { + obsel = new Obsel('ktbsFullBuffer', this.buffer[0].begin, + this.buffer[this.buffer.length - 1].end, this.buffer[0].subject); + obsel.trace = this.buffer[0].trace; + this.buffer = []; + } + this.buffer.push(obsel); + if (this.sync_mode === 'sync') { + // Immediate sync of the obsel. + this.flush(); + } + }, + + start_timer: function() { + var self = this; + if (this.timer === null) { + this.timer = window.setInterval(function() { + self.flush(); + }, this.timeOut); + } + }, + + stop_timer: function() { + if (this.timer !== null) { + window.clearInterval(this.timer); + this.timer = null; + } + }, + + /* + * Initialize the sync service + */ + init: function(default_subject) { + var self = this; + if (this.isReady) + /* Already initialized */ + return; + if (typeof default_subject === 'undefined') + default_subject = 'anonymous'; + if (this.mode == 'GET') + { + var request=$('').attr('src', this.url + 'login?userinfo={"default_subject": "' + default_subject + '"}'); + // Do not wait for the return, assume it is + // initialized. This assumption will not work anymore + // if login returns some necessary information + this.isReady = true; + } + else + { + $.ajax({ url: this.url + 'login', + type: 'POST', + data: 'userinfo={"default_subject":"' + default_subject + '"}', + success: function(data, textStatus, jqXHR) { + self.isReady = true; + if (self.buffer.length) { + self.flush(); + } + } + }); + } + } + }; + var BufferedService = function(url, mode) { + this.url = url; + this.buffer = []; + this.isReady = false; + this.timer = null; + this.failureCount = 0; + // sync_mode is either "none", "sync" or "buffered" + this.sync_mode = "none"; + /* mode can be either POST or GET */ + if (mode == 'POST' || mode == 'GET') + this.mode = mode; + else + this.mode = 'POST'; + /* Flush buffer every timeOut ms if the sync_mode is delayed */ + this.timeOut = 2000; + }; + BufferedService.prototype = BufferedService_prototype; + + var Trace_prototype = { + /* FIXME: We could/should use a sorted list such as + http://closure-library.googlecode.com/svn/docs/class_goog_structs_AvlTree.html + to speed up queries based on time */ + obsels: [], + /* Trace URI */ + uri: "", + default_subject: "", + /* baseuri is used as the base URI to resolve relative + * attribute-type names in obsels. Strictly speaking, this + * should rather be expressed as a reference to model, or + * more generically, as a qname/URI dict */ + baseuri: "", + /* Mapping of obsel type or property name to a compact + * representation (shorthands). + */ + shorthands: null, + syncservice: null, + + /* Define the trace URI */ + set_uri: function(uri) { + this.uri = uri; + }, + + /* Sync mode: delayed, sync (immediate sync), none (no + * synchronisation with server, the trace has to be explicitly saved + * if needed */ + set_sync_mode: function(mode) { + if (this.syncservice !== null) { + this.syncservice.set_sync_mode(mode, this.default_subject); + } + }, + + /* + * Return a list of the obsels of this trace matching the parameters + */ + list_obsels: function(_begin, _end, _reverse) { + var res; + if (typeof _begin !== 'undefined' || typeof _end !== 'undefined') { + /* + * Not optimized yet. + */ + res = []; + var l = this.obsels.length; + for (var i = 0; i < l; i++) { + var o = this.obsels[i]; + if ((typeof _begin !== 'undefined' && o.begin > _begin) && (typeof _end !== 'undefined' && o.end < _end)) { + res.push(o); + } + } + } + + if (typeof _reverse !== 'undefined') { + if (res !== undefined) { + /* Should reverse the whole list. Make a copy. */ + res = this.obsels.slice(0); + } + res.sort(function(a, b) { return b.begin - a.begin; }); + return res; + } + + if (res === undefined) { + res = this.obsels; + } + return res; + + }, + + /* + * Return the obsel of this trace identified by the URI, or undefined + */ + get_obsel: function(id) { + for (var i = 0; i < this.obsels.length; i++) { + /* FIXME: should check against variations of id/uri, take this.baseuri into account */ + if (this.obsels[i].uri === id) { + return this.obsels[i]; + } + } + return undefined; + }, + + set_default_subject: function(subject) { + // FIXME: if we call this method after the sync_service + // init method, then the default_subject will not be + // consistent anymore. Maybe we should then call init() again? + this.default_subject = subject; + }, + + get_default_subject: function() { + return this.default_subject; + }, + + /* (type:ObselType, begin:int, end:int?, subject:str?, attributes:[AttributeType=>any]?) */ + /* Create a new obsel and add it to the trace */ + create_obsel: function(type, begin, end, subject, _attributes) { + var o = new Obsel(type, begin, end, subject); + if (typeof _attributes !== 'undefined') { + o.attributes = _attributes; + } + o.trace = this; + this.obsels.push(o); + if (this.syncservice !== null) + this.syncservice.enqueue(o); + }, + + /* Helper methods */ + + /* Create a new obsel with the given attributes */ + trace: function(type, _attributes, _begin, _end, _subject) { + var t = (new Date()).getTime(); + if (typeof begin === 'undefined') { + _begin = t; + } + if (typeof end === 'undefined') { + _end = _begin; + } + if (typeof subject === 'undefined') { + _subject = this.default_subject; + } + if (typeof _attributes === 'undefined') { + _attributes = {}; + } + return this.create_obsel(type, _begin, _end, _subject, _attributes); + } + }; + + var Trace = function(uri, requestmode) { + /* FIXME: We could/should use a sorted list such as + http://closure-library.googlecode.com/svn/docs/class_goog_structs_AvlTree.html + to speed up queries based on time */ + this.obsels = []; + /* Trace URI */ + if (uri === undefined) + uri = ""; + this.uri = uri; + this.sync_mode = "none"; + this.default_subject = ""; + this.shorthands = {}; + /* baseuri is used a the base URI to resolve relative attribute names in obsels */ + this.baseuri = ""; + + this.syncservice = new BufferedService(uri, requestmode); + $(window).unload( function () { + if (this.syncservice && this.sync_mode !== 'none') { + this.syncservice.flush(); + this.syncservice.stop_timer(); + } + }); + }; + Trace.prototype = Trace_prototype; + + var Obsel_prototype = { + /* The following attributes are here for documentation + * purposes. They MUST be defined in the constructor + * function. */ + trace: undefined, + type: undefined, + begin: undefined, + end: undefined, + subject: undefined, + /* Dictionary indexed by ObselType URIs */ + attributes: {}, + + /* Method definitions */ + get_trace: function() { + return this.trace; + }, + + get_obsel_type: function() { + return this.type; + }, + get_begin: function() { + return this.begin; + }, + get_end: function() { + return this.end; + }, + get_subject: function() { + return this.subject; + }, + + list_attribute_types: function() { + var result = []; + for (var prop in this.attributes) { + if (this.attributes.hasOwnProperty(prop)) + result.push(prop); + } + /* FIXME: we return URIs here instead of AttributeType elements */ + return result; + }, + + list_relation_types: function() { + /* FIXME: not implemented yet */ + }, + + list_related_obsels: function (rt) { + /* FIXME: not implemented yet */ + }, + list_inverse_relation_types: function () { + /* FIXME: not implemented yet */ + }, + list_relating_obsels: function (rt) { + /* FIXME: not implemented yet */ + }, + /* + * Return the value of the given attribute type for this obsel + */ + get_attribute_value: function(at) { + if (typeof at === "string") + /* It is a URI */ + return this.attributes[at]; + else + /* FIXME: check that at is instance of AttributeType */ + return this.attributes[at.uri]; + }, + + + /* obsel modification (trace amendment) */ + + set_attribute_value: function(at, value) { + if (typeof at === "string") + /* It is a URI */ + this.attributes[at] = value; + /* FIXME: check that at is instance of AttributeType */ + else + this.attributes[at.uri] = value; + }, + + del_attribute_value: function(at) { + if (typeof at === "string") + /* It is a URI */ + delete this.attributes[at]; + /* FIXME: check that at is instance of AttributeType */ + else + delete this.attributes[at.uri]; + }, + + add_related_obsel: function(rt, value) { + /* FIXME: not implemented yet */ + }, + + del_related_obsel: function(rt, value) { + /* FIXME: not implemented yet */ + }, + + /* + * Return a JSON representation of the obsel + */ + toJSON: function() { + var r = { + "@id": this.id, + "@type": this.type, + "begin": this.begin, + "end": this.end, + "subject": this.subject + }; + for (var prop in this.attributes) { + if (this.attributes.hasOwnProperty(prop)) + r[prop] = this.attributes[prop]; + } + return r; + }, + + /* + * Return a compact JSON representation of the obsel. + * Use predefined + custom shorthands for types/properties + */ + toCompactJSON: function() { + var r = { + "@t": (this.trace.shorthands.hasOwnProperty(this.type) ? this.trace.shorthands[this.type] : this.type), + "@b": this.begin, + }; + // Transmit subject only if different from default_subject + if (this.subject !== this.trace.default_subject) + r["@s"] = this.subject; + + // Store duration (to save some bytes) and only if it is non-null + if (this.begin !== this.end) + r["@d"] = this.end - this.begin; + + // Store id only if != "" + if (this.id !== "") + r["@i"] = this.id; + + for (var prop in this.attributes) { + if (this.attributes.hasOwnProperty(prop)) + { + var v = this.attributes[prop]; + r[prop] = this.trace.shorthands.hasOwnProperty(v) ? this.trace.shorthands[v] : v; + } + } + return r; + }, + + toJSONstring: function() { + return JSON.stringify(this.toJSON()); + } + }; + + var Obsel = function(type, begin, end, subject, attributes) { + this.trace = undefined; + this.uri = ""; + this.id = ""; + this.type = type; + this.begin = begin; + this.end = end; + this.subject = subject; + /* Is the obsel synched with the server ? */ + this.sync_status = false; + /* Dictionary indexed by ObselType URIs */ + this.attributes = {}; + }; + Obsel.prototype = Obsel_prototype; + + var TraceManager_prototype = { + traces: [], + /* + * Return the trace with id name + * If it was not registered, return undefined. + */ + get_trace: function(name) { + return this.traces[name]; + }, + + /* + * Explicitly create and initialize a new trace with the given name. + * The optional uri parameter allows to initialize the trace URI. + * + * If another existed with the same name before, then it is replaced by a new one. + */ + init_trace: function(name, params) + { + if (window.console) window.console.log("init_trace", params); + url = params.url ? params.url : ""; + requestmode = params.requestmode ? params.requestmode : "POST"; + syncmode = params.syncmode ? params.syncmode : "none"; + default_subject = params.default_subject ? params.default_subject : "default"; + var t = new Trace(url, requestmode); + t.set_default_subject(default_subject); + t.set_sync_mode(syncmode); + this.traces[name] = t; + return t; + } + }; + + var TraceManager = function() { + this.traces = {}; + }; + TraceManager.prototype = TraceManager_prototype; + + var tracemanager = new TraceManager(); + return tracemanager; + })(jQuery); diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/mashup/player-html.htm --- a/metadataplayer/mashup/player-html.htm Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/mashup/player-html.htm Wed Aug 22 17:29:27 2012 +0200 @@ -52,9 +52,9 @@ IriSP.widgetsDir = "../metadataplayer"; IriSP.language = 'fr'; var _metadata = { - url: 'bab_files/mashup.json', +// url: 'bab_files/mashup.json', // url: 'http://ldt.iri.centrepompidou.fr/ldtplatform/ldt/cljson/id/b2754186-a0c9-11e0-b8bd-00145ea49a02?callback=?', -// url: 'http://ldt.iri.centrepompidou.fr/ldtplatform/ldt/cljson/id/5afd8bbe-9b75-11e1-9e5d-00145ea4a2be?callback=?', + url: 'http://ldt.iri.centrepompidou.fr/ldtplatform/ldt/cljson/id/5afd8bbe-9b75-11e1-9e5d-00145ea4a2be?callback=?', format: 'ldt' }; var _canPlayMp4 = document.createElement('video').canPlayType('video/mp4'); @@ -79,15 +79,20 @@ annotation_type: false }, { + type: "Tagger", + api_endpoint: "../post-test.php", + tags: ["actif","amour","bonheur","captif","charité","désir","dieu","doute","famille","idéal","internationale","passif","patrie","peur","politique","président","spleen","travail"] + }, + { type: "MediaList", container: "mediaList" }, { type: "AnnotationsList", container: "annotationList", - ajax_url: "http://ldt.iri.centrepompidou.fr/ldtplatform/api/ldt/segments/{{media}}/{{begin}}/{{end}}?callback=?", - ajax_granularity: 30000, - limit_count: 3 + //ajax_url: "http://ldt.iri.centrepompidou.fr/ldtplatform/api/ldt/segments/{{media}}/{{begin}}/{{end}}?callback=?", + //ajax_granularity: 30000, + //limit_count: 3 }, { type: "Mediafragment" } ] diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/metadataplayer/Annotation.css --- a/metadataplayer/metadataplayer/Annotation.css Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/metadataplayer/Annotation.css Wed Aug 22 17:29:27 2012 +0200 @@ -23,6 +23,31 @@ font-weight: bold; } +.Ldt-Annotation-Cleared { + clear: both; +} + +.Ldt-Annotation-MaxMinButton { + float: right; margin: 5px 5px 0; width: 17px; height: 17px; + background: url(img/widget-control.png); background-position: 0 -51px; cursor: pointer; +} + +.Ldt-Annotation-Social { + float: right; +} + +.Ldt-Annotation-MaxMinButton:hover { + background-position: -17px -51px; +} + +.Ldt-Annotation-Minimized div.Ldt-Annotation-MaxMinButton { + background-position: 0 -34px; +} + +.Ldt-Annotation-Minimized div.Ldt-Annotation-MaxMinButton:hover { + background-position: -17px -34px; +} + .Ldt-Annotation-Inner h3.Ldt-Annotation-MashupOrigin { font-size: 12px; } @@ -36,55 +61,23 @@ } .Ldt-Annotation-Inner p { - margin: 5px 0; font-size: 12px; -} - -.Ldt-Annotation-ShareIcons { - float: right; -} - -.Ldt-Annotation-Share { - display: inline-block; width: 24px; height: 24px; margin: 2px 0 0 2px; background: url(img/socialbuttons.png); -} - -.Ldt-Annotation-Twitter { - background-position: 0 0; + font-size: 12px; } -.Ldt-Annotation-Twitter:hover { - background-position: 0 -24px; -} - -.Ldt-Annotation-Fb { - background-position: -24px 0; +.Ldt-Annotation-Label { + font-size: 12px; font-weight: bold; max-width: 90px; float: left; clear: left; } -.Ldt-Annotation-Fb:hover { - background-position: -24px -24px; -} - -.Ldt-Annotation-Gplus { - background-position: -48px 0; -} - -.Ldt-Annotation-Gplus:hover { - background-position: -48px -24px; +.Ldt-Annotation-Labelled { + margin: 5px 0 0 90px; clear: right; } .Ldt-Annotation-Tags-Block { font-size: 12px; } -.Ldt-Annotation-NoTags { - display: none; -} - -.Ldt-Annotation-TagTitle { - margin: 5px 0 2px; font-size: 12px; -} - ul.Ldt-Annotation-Tags { - display: inline; list-style: none; padding: 0; margin: 5px 0; + list-style: none; padding: 0; } li.Ldt-Annotation-TagLabel { @@ -122,3 +115,7 @@ display: none; } +.Ldt-Annotation-EmptyBlock { + display: none; +} + diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/metadataplayer/Annotation.js --- a/metadataplayer/metadataplayer/Annotation.js Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/metadataplayer/Annotation.js Wed Aug 22 17:29:27 2012 +0200 @@ -1,67 +1,73 @@ -// TODO: Open share links in a small window - Migrate Timeupdate functions to Extract +// TODO: Migrate Timeupdate functions to Extract IriSP.Widgets.Annotation = function(player, config) { IriSP.Widgets.Widget.call(this, player, config); this.lastAnnotation = false; + this.minimized = this.start_minimized || false; + this.bounds = [ 0, 0 ]; }; IriSP.Widgets.Annotation.prototype = new IriSP.Widgets.Widget(); IriSP.Widgets.Annotation.prototype.messages = { - "fr": { - share_on: "Partager sur", + fr: { watching: "Je regarde ", on_site: " sur ", - tags: "Mots-clés :", + tags_: "Mots-clés :", + description_: "Description :", excerpt_from: "Extrait de :" }, - "en": { - share_on: "Share on", + en: { watching: "I'm watching ", on_site: " on ", - tags: "Keywords:", + tags_: "Keywords:", + description_: "Description:", excerpt_from: "Excerpt from:" } } IriSP.Widgets.Annotation.prototype.template = '
' - + '
' - + '' - + '' - + '' - + '

' + + '
' + + '
' + + '
' + + '

' + '( - )

' + '

{{l10n.excerpt_from}} ' + '( - )

' - + '

' - + '
{{l10n.tags}}

    '; + + '
    {{l10n.description_}}
    ' + + '

    ' + + '
    ' + + '
    {{l10n.tags_}}
      ' + + '
      '; IriSP.Widgets.Annotation.prototype.defaults = { annotation_type : "chap", + start_minimized: true, show_top_border : false, site_name : "Lignes de Temps" } IriSP.Widgets.Annotation.prototype.draw = function() { this.renderTemplate(); + this.insertSubwidget(this.$.find(".Ldt-Annotation-Social"), "socialWidget", { type: "Social" }); this.bindPopcorn("timeupdate","onTimeupdate"); this.bindPopcorn("IriSP.Annotation.hide","hide"); this.bindPopcorn("IriSP.Annotation.show","show"); this.bindPopcorn("IriSP.Annotation.minimize","minimize"); this.bindPopcorn("IriSP.Annotation.maximize","maximize"); + this.bindPopcorn("IriSP.Annotation.getBounds","sendBounds"); + this.$.find(".Ldt-Annotation-MaxMinButton").click(this.functionWrapper("toggleSize")); this.onTimeupdate(); } IriSP.Widgets.Annotation.prototype.onTimeupdate = function() { var _time = Math.floor(this.player.popcorn.currentTime() * 1000), - _list = this.getWidgetAnnotations().filter(function(_annotation) { - return _annotation.begin <= _time && _annotation.end > _time; - }); + _list = this.getWidgetAnnotationsAtTime(); if (_list.length) { if (_list[0].id !== this.lastAnnotation) { this.drawAnnotation(_list[0]); - this.player.popcorn.trigger("IriSP.Annotation.boundsChanged",[ _list[0].begin.valueOf(), _list[0].end.valueOf() ]); + this.bounds = [ _list[0].begin.valueOf(), _list[0].end.valueOf() ]; } this.player.popcorn.trigger("IriSP.Arrow.updatePosition",{widget: this.type, time: ( _list[0].begin + _list[0].end ) / 2}); } @@ -69,8 +75,13 @@ this.lastAnnotation = false; this.$.find(".Ldt-Annotation-Inner").addClass("Ldt-Annotation-Empty"); this.player.popcorn.trigger("IriSP.Arrow.updatePosition",{widget: this.type, time: _time}); - this.player.popcorn.trigger("IriSP.Annotation.boundsChanged",[ _time, _time ]); + this.bounds = [ _time, _time ]; } + this.sendBounds(); +} + +IriSP.Widgets.Annotation.prototype.sendBounds = function() { + this.player.popcorn.trigger("IriSP.Annotation.boundsChanged",this.bounds); } IriSP.Widgets.Annotation.prototype.drawAnnotation = function(_annotation) { @@ -85,7 +96,7 @@ return '
    • ' + _tag + '
    • '; }).join(""); this.$.find(".Ldt-Annotation-Tags").html(_html); - this.$.find(".Ldt-Annotation-Tags-Block").removeClass("Ldt-Annotation-NoTags"); + this.$.find(".Ldt-Annotation-Tags-Block").removeClass("Ldt-Annotation-EmptyBlock"); /* Correct the empty tag bug */ this.$.find('.Ldt-Annotation-TagLabel').each(function() { @@ -99,10 +110,16 @@ _this.player.popcorn.trigger("IriSP.search.triggeredSearch", IriSP.jQuery(this).text().replace(/(^\s+|\s+$)/g,'')); }); } else { - this.$.find(".Ldt-Annotation-Tags-Block").addClass("Ldt-Annotation-NoTags"); + this.$.find(".Ldt-Annotation-Tags-Block").addClass("Ldt-Annotation-EmptyBlock"); } this.$.find(".Ldt-Annotation-Title").html(_annotation.title); - this.$.find(".Ldt-Annotation-Description").html(_annotation.description); + var _desc = _annotation.description.replace(/(^\s+|\s+$)/g,''); + if (_desc) { + this.$.find(".Ldt-Annotation-Description-Block").removeClass("Ldt-Annotation-EmptyBlock"); + this.$.find(".Ldt-Annotation-Description").html(_desc); + } else { + this.$.find(".Ldt-Annotation-Description-Block").addClass("Ldt-Annotation-EmptyBlock"); + } this.$.find(".Ldt-Annotation-Begin").html(_annotation.begin.toString()); this.$.find(".Ldt-Annotation-End").html(_annotation.end.toString()); if (_annotation.elementType === "mashedAnnotation") { @@ -113,9 +130,16 @@ } else { this.$.find('.Ldt-Annotation-Inner').removeClass("Ldt-Annotation-isMashup"); } - this.$.find(".Ldt-Annotation-Fb").attr("href", "http://www.facebook.com/share.php?" + IriSP.jQuery.param({ u: _url, t: _text })); - this.$.find(".Ldt-Annotation-Twitter").attr("href", "https://twitter.com/intent/tweet?" + IriSP.jQuery.param({ url: _url, text: _text })); - this.$.find(".Ldt-Annotation-Gplus").attr("href", "https://plusone.google.com/_/+1/confirm?" + IriSP.jQuery.param({ url: _url, title: _text })); + if (typeof this.socialWidget !== "undefined") { + this.socialWidget.updateUrls(_url, _text); + } else { + var _this = this; + setTimeout(function() { + if (typeof _this.socialWidget !== "undefined") { + _this.socialWidget.updateUrls(_url, _text); + } + },800); + } this.$.find(".Ldt-Annotation-Inner").removeClass("Ldt-Annotation-Empty"); } @@ -127,10 +151,20 @@ this.$.slideDown(); } +IriSP.Widgets.Annotation.prototype.toggleSize = function() { + if (this.minimized) { + this.maximize(); + } else { + this.minimize(); + } +} + IriSP.Widgets.Annotation.prototype.minimize = function() { + this.minimized = true; this.$.find('.Ldt-Annotation-Inner').addClass("Ldt-Annotation-Minimized"); } IriSP.Widgets.Annotation.prototype.maximize = function() { + this.minimized = false; this.$.find('.Ldt-Annotation-Inner').removeClass("Ldt-Annotation-Minimized"); } \ No newline at end of file diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/metadataplayer/AnnotationsList.css --- a/metadataplayer/metadataplayer/AnnotationsList.css Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/metadataplayer/AnnotationsList.css Wed Aug 22 17:29:27 2012 +0200 @@ -21,7 +21,7 @@ min-height: 60px; } .Ldt-AnnotationsList-li:hover { - background: url(img/pinstripe-grey.png); + background: url(img/pinstripe-grey.png) !important; } .Ldt-AnnotationsList-highlight { background: #F7268E; @@ -59,7 +59,7 @@ p.Ldt-AnnotationsList-Description { margin: 2px 0 2px 82px; font-size: 12px; - color: #666666; + color: #333333; } ul.Ldt-AnnotationsList-Tags { list-style: none; diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/metadataplayer/AnnotationsList.js --- a/metadataplayer/metadataplayer/AnnotationsList.js Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/metadataplayer/AnnotationsList.js Wed Aug 22 17:29:27 2012 +0200 @@ -19,7 +19,7 @@ /* number of milliseconds before/after the current timecode when calling the segment API */ ajax_granularity : 300000, - default_thumbnail : "http://ldt.iri.centrepompidou.fr/static/site/ldt/css/imgs/video_sequence.png", + default_thumbnail : "", /* URL when the annotation is not in the current project, * e.g. http://ldt.iri.centrepompidou.fr/ldtplatform/ldt/front/player/{{media}}/{{project}}/{{annotationType}}#id={{annotation}} */ @@ -27,14 +27,27 @@ annotation_type : false, refresh_interval : 0, limit_count : 10, - newest_first : false + newest_first : false, + polemics : [{ + keyword: "++", + background_color: "#c9ecc6" + },{ + keyword: "--", + background_color: "#f9c5c6" + },{ + keyword: "??", + background_color: "#cec5f9" + },{ + keyword: "==", + background_color: "#f9f4c6" + }] }; IriSP.Widgets.AnnotationsList.prototype.template = '
      ' + '
      {{/polemics.length}}' + '
      ' + '
      {{l10n.wait_while_processing}}
      ' - + '
      {{l10n.error_while_contacting}}
      ' - + '
      {{l10n.annotation_saved}}
      ' + + '
      {{^always_visible}}{{/always_visible}}
      {{l10n.error_while_contacting}}
      ' + + '
      {{^always_visible}}{{/always_visible}}
      {{l10n.annotation_saved}}
      ' + ''; IriSP.Widgets.CreateAnnotation.prototype.draw = function() { + var _this = this; + if (this.tag_titles && !this.tags) { + this.tags = IriSP._(this.tag_titles).map(function(_tag_title) { + var _tag, + _tags = _this.source.getTags().searchByTitle(_tag_title); + if (_tags.length) { + _tag = _tags[0]; + } else { + _tag = new IriSP.Model.Tag(false, _this.source); + _tag.title = _tag_title; + } + return _tag; + }); + } if (!this.tags) { this.tags = this.source.getTags() .sortBy(function (_tag) { @@ -110,12 +135,13 @@ .map(function(_tag) { return _tag; }); - // We have to use the map function because Mustache doesn't like our tags object + /* We have to use the map function because Mustache doesn't like our tags object */ } - var _this = this; this.renderTemplate(); this.$.find(".Ldt-CreateAnnotation-Close").click(function() { - _this.hide(); + _this.close_after_send + ? _this.hide() + : _this.showScreen("Main"); return false; }); this.$.find(".Ldt-CreateAnnotation-TagLi, .Ldt-CreateAnnotation-PolemicLi").click(function() { @@ -126,9 +152,17 @@ if (this.show_title_field) { this.$.find(".Ldt-CreateAnnotation-Title").bind("change keyup input paste", this.functionWrapper("onTitleChange")); } + if (this.show_creator_field) { + this.$.find(".Ldt-CreateAnnotation-Creator").bind("change keyup input paste", this.functionWrapper("onCreatorChange")); + } - this.$.hide(); - this.hide(); + if (this.start_visible) { + this.show(); + } else { + this.$.hide(); + this.hide(); + } + this.bindPopcorn("IriSP.CreateAnnotation.toggle","toggle"); this.bindPopcorn("IriSP.Slice.boundsChanged","onBoundsChanged"); this.begin = new IriSP.Model.Time(); @@ -145,25 +179,38 @@ this.visible = true; this.showScreen('Main'); this.$.find(".Ldt-CreateAnnotation-Description").val("").css("border-color", "#666666"); - this.$.find(".Ldt-CreateAnnotation-Title").val("").css("border-color", "#666666"); + if (this.show_title_field) { + this.$.find(".Ldt-CreateAnnotation-Title").val("").css("border-color", "#666666"); + } + if (this.show_creator_field) { + this.$.find(".Ldt-CreateAnnotation-Creator").val(this.creator_name).css("border-color", "#666666"); + } this.$.find(".Ldt-CreateAnnotation-TagLi, .Ldt-CreateAnnotation-PolemicLi").removeClass("selected"); this.$.slideDown(); - this.player.popcorn.trigger("IriSP.Annotation.minimize"); + if (this.minimize_annotation_widget) { + this.player.popcorn.trigger("IriSP.Annotation.minimize"); + } this.player.popcorn.trigger("IriSP.Slice.show"); } IriSP.Widgets.CreateAnnotation.prototype.hide = function() { - this.visible = false; - this.$.slideUp(); - this.player.popcorn.trigger("IriSP.Annotation.maximize"); - this.player.popcorn.trigger("IriSP.Slice.hide"); + if (!this.always_visible) { + this.visible = false; + this.$.slideUp(); + if (this.minimize_annotation_widget) { + this.player.popcorn.trigger("IriSP.Annotation.maximize"); + } + this.player.popcorn.trigger("IriSP.Slice.hide"); + } } IriSP.Widgets.CreateAnnotation.prototype.toggle = function() { - if (this.visible) { - this.hide(); - } else { - this.show(); + if (!this.always_visible) { + if (this.visible) { + this.hide(); + } else { + this.show(); + } } } @@ -178,7 +225,7 @@ var _field = this.$.find(".Ldt-CreateAnnotation-Description"), _rx = IriSP.Model.regexpFromTextOrArray(_keyword), _contents = _field.val(); - _contents = ( _rx.test(_contents) + _contents = ( !!_contents.match(_rx) ? _contents.replace(_rx,"") : _contents + " " + _keyword ); @@ -186,18 +233,25 @@ this.onDescriptionChange(); } +IriSP.Widgets.CreateAnnotation.prototype.pauseOnWrite = function() { + if (this.pause_on_write && !this.player.popcorn.media.paused) { + this.player.popcorn.pause(); + } +} + IriSP.Widgets.CreateAnnotation.prototype.onDescriptionChange = function() { var _field = this.$.find(".Ldt-CreateAnnotation-Description"), _contents = _field.val(); _field.css("border-color", !!_contents ? "#666666" : "#ff0000"); this.$.find(".Ldt-CreateAnnotation-TagLi, .Ldt-CreateAnnotation-PolemicLi").each(function() { var _rx = IriSP.Model.regexpFromTextOrArray(IriSP.jQuery(this).text().replace(/(^\s+|\s+$)/g,'')); - if (_rx.test(_contents)) { + if (_contents.match(_rx)) { IriSP.jQuery(this).addClass("selected"); } else { IriSP.jQuery(this).removeClass("selected"); } }); + this.pauseOnWrite(); return !!_contents; } @@ -205,57 +259,95 @@ var _field = this.$.find(".Ldt-CreateAnnotation-Title"), _contents = _field.val(); _field.css("border-color", !!_contents ? "#666666" : "#ff0000"); + this.pauseOnWrite(); return !!_contents; } + +IriSP.Widgets.CreateAnnotation.prototype.onCreatorChange = function() { + var _field = this.$.find(".Ldt-CreateAnnotation-Creator"), + _contents = _field.val(); + _field.css("border-color", !!_contents ? "#666666" : "#ff0000"); + this.pauseOnWrite(); + return !!_contents; +} + +/* Fonction effectuant l'envoi des annotations */ IriSP.Widgets.CreateAnnotation.prototype.onSubmit = function() { - if (!this.onDescriptionChange() || (!this.onTitleChange() && this.show_title_field)) { + /* Si les champs obligatoires sont vides, on annule l'envoi */ + if (!this.onDescriptionChange() || (this.show_title_field && !this.onTitleChange()) || (this.show_creator_field && !this.onCreatorChange())) { return; } - var _exportedAnnotations = new IriSP.Model.List(this.player.sourceManager); - _export = this.player.sourceManager.newLocalSource({serializer: IriSP.serializers[this.api_serializer]}), - _annotation = new IriSP.Model.Annotation(false, _export), - _annotationTypes = this.source.getAnnotationTypes().searchByTitle(this.annotation_type), - _annotationType = (_annotationTypes.length ? _annotationTypes[0] : new IriSP.Model.AnnotationType(false, _export)), - _url = Mustache.to_html(this.api_endpoint_template, {id: this.source.projectId}); - + var _exportedAnnotations = new IriSP.Model.List(this.player.sourceManager), /* Création d'une liste d'annotations contenant une annotation afin de l'envoyer au serveur */ + _export = this.player.sourceManager.newLocalSource({serializer: IriSP.serializers[this.api_serializer]}), /* Création d'un objet source utilisant un sérialiseur spécifique pour l'export */ + _annotation = new IriSP.Model.Annotation(false, _export), /* Création d'une annotation dans cette source avec un ID généré à la volée (param. false) */ + _annotationTypes = this.source.getAnnotationTypes().searchByTitle(this.annotation_type), /* Récupération du type d'annotation dans lequel l'annotation doit être ajoutée */ + _annotationType = (_annotationTypes.length ? _annotationTypes[0] : new IriSP.Model.AnnotationType(false, _export)), /* Si le Type d'Annotation n'existe pas, il est créé à la volée */ + _url = Mustache.to_html(this.api_endpoint_template, {id: this.source.projectId}); /* Génération de l'URL à laquelle l'annotation doit être envoyée, qui doit inclure l'ID du projet */ + + /* Si nous avons dû générer un ID d'annotationType à la volée... */ if (!_annotationTypes.length) { + /* Il ne faudra pas envoyer l'ID généré au serveur */ _annotationType.dont_send_id = true; + /* Il faut inclure le titre dans le type d'annotation */ + _annotationType.title = this.annotation_type; } - _annotationType.title = this.annotation_type; - _annotation.setBegin(this.begin); - _annotation.setEnd(this.end); - _annotation.setMedia(this.source.currentMedia.id); - _annotation.setAnnotationType(_annotationType.id); + /* + * Nous remplissons les données de l'annotation générée à la volée + * ATTENTION: Si nous sommes sur un MASHUP, ces éléments doivent se référer AU MEDIA D'ORIGINE + * */ + _annotation.setBegin(this.begin); /*Timecode de début */ + _annotation.setEnd(this.end); /* Timecode de fin */ + _annotation.setMedia(this.source.currentMedia.id); /* Id du média annoté */ + + _annotation.setAnnotationType(_annotationType.id); /* Id du type d'annotation */ if (this.show_title_field) { - _annotation.title = this.$.find(".Ldt-CreateAnnotation-Title").val() + /* Champ titre, seulement s'il est visible */ + _annotation.title = this.$.find(".Ldt-CreateAnnotation-Title").val(); } - _annotation.created = new Date(); - _annotation.description = this.$.find(".Ldt-CreateAnnotation-Description").val(); - _annotation.setTags(this.$.find(".Ldt-CreateAnnotation-TagLi.selected").map(function() { return IriSP.jQuery(this).attr("tag-id")})); + _annotation.created = new Date(); /* Date de création de l'annotation */ + _annotation.description = this.$.find(".Ldt-CreateAnnotation-Description").val(); /* Champ description */ + _annotation.setTags(this.$.find(".Ldt-CreateAnnotation-TagLi.selected") + .map(function() { return IriSP.jQuery(this).attr("tag-id")})); /*Liste des ids de tags */ - _export.creator = this.creator_name; + /* Les données créateur/date de création sont envoyées non pas dans l'annotation, mais dans le projet */ + if (this.show_creator_field) { + _export.creator = this.$.find(".Ldt-CreateAnnotation-Creator").val(); + } else { + _export.creator = this.creator_name; + } _export.created = new Date(); - _exportedAnnotations.push(_annotation); - _export.addList("annotation",_exportedAnnotations); + _exportedAnnotations.push(_annotation); /* Ajout de l'annotation à la liste à exporter */ + _export.addList("annotation",_exportedAnnotations); /* Ajout de la liste à exporter à l'objet Source */ var _this = this; + /* Envoi de l'annotation via AJAX au serveur ! */ IriSP.jQuery.ajax({ url: _url, type: this.api_method, contentType: 'application/json', - data: _export.serialize(), + data: _export.serialize(), /* L'objet Source est sérialisé */ success: function(_data) { - _this.showScreen('Saved'); - if (_this.close_widget_timeout) { - window.setTimeout(_this.functionWrapper("hide"),_this.close_widget_timeout); + _this.showScreen('Saved'); /* Si l'appel a fonctionné, on affiche l'écran "Annotation enregistrée" */ + if (_this.after_send_timeout) { /* Selon les options de configuration, on revient à l'écran principal ou on ferme le widget, ou rien */ + window.setTimeout( + function() { + _this.close_after_send + ? _this.hide() + : _this.showScreen("Main"); + }, + _this.after_send_timeout + ); } - _export.getAnnotations().removeElement(_annotation, true); - _export.deSerialize(_data); - _this.source.merge(_export); - _this.player.popcorn.trigger("IriSP.AnnotationsList.refresh"); + _export.getAnnotations().removeElement(_annotation, true); /* Pour éviter les doublons, on supprime l'annotation qui a été envoyée */ + _export.deSerialize(_data); /* On désérialise les données reçues pour les réinjecter */ + _this.source.merge(_export); /* On récupère les données réimportées dans l'espace global des données */ + if (_this.pause_on_write && _this.player.popcorn.media.paused) { + _this.player.popcorn.play(); + } + _this.player.popcorn.trigger("IriSP.AnnotationsList.refresh"); /* On force le rafraîchissement du widget AnnotationsList */ }, error: function(_xhr, _error, _thrown) { IriSP.log("Error when sending annotation", _thrown); @@ -264,7 +356,7 @@ window.setTimeout(function(){ _this.showScreen("Main") }, - (_this.close_widget_timeout || 5000)); + (_this.after_send_timeout || 5000)); } }); this.showScreen('Wait'); diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/metadataplayer/LdtPlayer-core.css --- a/metadataplayer/metadataplayer/LdtPlayer-core.css Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/metadataplayer/LdtPlayer-core.css Wed Aug 22 17:29:27 2012 +0200 @@ -9,7 +9,7 @@ } .Ldt-Widget { - /*font-family: Arial, Helvetica, sans-serif;*/ +/* font-family: Arial, Helvetica, sans-serif; */ color: black; font-size: 12px; -} +} \ No newline at end of file diff -r ed1126cd2b80 -r e27a08b0a037 metadataplayer/metadataplayer/LdtPlayer-core.js --- a/metadataplayer/metadataplayer/LdtPlayer-core.js Fri Jun 29 12:12:38 2012 +0200 +++ b/metadataplayer/metadataplayer/LdtPlayer-core.js Wed Aug 22 17:29:27 2012 +0200 @@ -97,13 +97,15 @@ /* widget specific requirements */ for(var _i = 0; _i < this.config.gui.widgets.length; _i++) { var _t = this.config.gui.widgets[_i].type; - if (typeof IriSP.widgetsRequirements[_t] !== "undefined" && typeof IriSP.widgetsRequirements[_t].requires !== "undefined") { - $L.script(IriSP.getLib(IriSP.widgetsRequirements[_t].requires)); + if (typeof IriSP.widgetsRequirements[_t] !== "undefined" && typeof IriSP.widgetsRequirements[_t].requires !== "undefined" ) { + for (var _j = 0; _j < IriSP.widgetsRequirements[_t].requires.length; _j++) { + $L.script(IriSP.getLib(IriSP.widgetsRequirements[_t].requires[_j])); + } } } var _this = this; - IriSP.log($L); + $L.wait(function() { _this.onLibsLoaded(); }); @@ -151,7 +153,10 @@ } IriSP.Metadataplayer.prototype.onVideoDataLoaded = function() { - if (typeof this.videoData !== "undefined" && typeof this.config.player.video === "undefined") { + + /* Setting default media from metadata */ + + if (typeof this.videoData !== "undefined") { var _media; @@ -177,16 +182,146 @@ this.videoData.currentMedia = _media; - if (typeof _media !== "undefined" && typeof _media.video !== "undefined") { + /* Getting video URL from metadata if it's not in the player config options */ + + if (typeof _media !== "undefined" && typeof _media.video !== "undefined" && typeof this.config.player.video === "undefined") { this.config.player.video = _media.video; - if (typeof _media.streamer !== "undefined") { + if (typeof this.config.player.streamer == "undefined" && typeof _media.streamer !== "undefined") { this.config.player.streamer = _media.streamer; - this.config.player.video = _media.video.replace(_media.streamer,''); } } } - this.configurePopcorn(); + + if (typeof this.config.player.video === "string" && this.config.player.url_transform === "function") { + this.config.player.video = this.config.player.url_transform(this.config.player.video); + } + + var _pop, + _divs = this.layoutDivs("video",this.config.player.height || undefined), + containerDiv = _divs[0], + spacerDiv = _divs[1], + _this = this, + _types = { + "html5" : /\.(ogg|ogv|webm)$/, + "youtube" : /^(https?:\/\/)?(www\.)?youtube\.com/, + "dailymotion" : /^(https?:\/\/)?(www\.)?dailymotion\.com/ + }; + + if (this.config.player.type === "auto") { + this.config.player.type = "jwplayer"; + IriSP._(_types).each(function(_v, _k) { + if (_v.test(_this.config.player.video)) { + _this.config.player.type = _k + } + }); + } + + switch(this.config.player.type) { + case "html5": + var _tmpId = Popcorn.guid("video"), + _videoEl = IriSP.jQuery('