Implemented serialize functions new-model
authorveltr
Fri, 13 Apr 2012 18:08:19 +0200
branchnew-model
changeset 860 7fd843e0dc4e
parent 858 ad1ffe0c0955
child 864 5e76a06b961c
Implemented serialize functions
src/js/model.js
src/js/serializers/PlatformSerializer.js
test/model/test.html
--- a/src/js/model.js	Thu Apr 12 15:54:33 2012 +0200
+++ b/src/js/model.js	Fri Apr 13 18:08:19 2012 +0200
@@ -4,7 +4,44 @@
     SOURCE_STATUS_EMPTY : 0,
     SOURCE_STATUS_WAITING : 1,
     SOURCE_STATUS_READY : 2,
-    ID_AUTO_INCREMENT : 0
+    ID_AUTO_INCREMENT : 0,
+    getAI : function() {
+        return "autoid-" + (++this.ID_AUTO_INCREMENT);
+    },
+    isoToDate : function(_str) {
+        // http://delete.me.uk/2005/03/iso8601.html
+        var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
+        var d = _str.match(new RegExp(regexp));
+    
+        var offset = 0;
+        var date = new Date(d[1], 0, 1);
+    
+        if (d[3]) { date.setMonth(d[3] - 1); }
+        if (d[5]) { date.setDate(d[5]); }
+        if (d[7]) { date.setHours(d[7]); }
+        if (d[8]) { date.setMinutes(d[8]); }
+        if (d[10]) { date.setSeconds(d[10]); }
+        if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
+        if (d[14]) {
+            offset = (Number(d[16]) * 60) + Number(d[17]);
+            offset *= ((d[15] == '-') ? 1 : -1);
+        }
+    
+        offset -= date.getTimezoneOffset();
+        time = (Number(date) + (offset * 60 * 1000));
+        var _res = new Date();
+        _res.setTime(Number(time));
+        return _res;
+    },
+    dateToIso : function(d) {  
+        function pad(n){return n<10 ? '0'+n : n}  
+        return d.getUTCFullYear()+'-'  
+            + pad(d.getUTCMonth()+1)+'-'  
+            + pad(d.getUTCDate())+'T'  
+            + pad(d.getUTCHours())+':'  
+            + pad(d.getUTCMinutes())+':'  
+            + pad(d.getUTCSeconds())+'Z'  
+    }
 }
 
 /* */
@@ -12,6 +49,9 @@
 IriSP.Model.List = function(_directory) {
     this.contents = [];
     this.directory = _directory;
+    if (typeof _directory == "undefined") {
+        throw("Error : new IriSP.Model.List(directory): directory is undefined");
+    }
 }
 
 IriSP.Model.List.prototype.toString = function() {
@@ -139,29 +179,34 @@
 
 /* */
 
-IriSP.Model.Reference = function(_directory, _idRef) {
-    this.directory = _directory;
+IriSP.Model.Reference = function(_source, _idRef) {
+    this.source = _source;
     if (typeof _idRef === "object") {
         this.isList = true;
-        this.contents = new IriSP.Model.List(this.directory);
-        this.contents.addIdsFromArray(_idRef);
+        this.contents = new IriSP.Model.List(this.source.directory);
+        this.contents.addIdsFromArray(IriSP._(_idRef).map(function(_id) {
+            return _source.getNamespaced(_id).fullname;
+        }));
     } else {
         this.isList = false;
-        this.contents = _idRef;
+        this.contents = _source.getNamespaced(_idRef).fullname;
     }
 }
 
 IriSP.Model.Reference.prototype.getContents = function() {
-    return (this.isList ? this.contents : this.directory.getElement(this.contents));
+    return (this.isList ? this.contents : this.source.directory.getElement(this.contents));
 }
 
 /* */
 
 IriSP.Model.Element = function(_id, _source) {
     this.elementType = 'element';
-    if (typeof _id !== "undefined" && typeof _source !== "undefined") {
+    if (typeof _source !== "undefined") {
+        if (typeof _id === "undefined" || !_id) {
+            _id = IriSP.Model.getAI();
+        }
         this.source = _source;
-        this.id = _id;
+        this.id = _source.getNamespaced(_id).fullname;
         this.title = "";
         this.description = "";
         this.source.directory.addElement(this);
@@ -173,7 +218,7 @@
 }
 
 IriSP.Model.Element.prototype.setReference = function(_elementType, _idRef) {
-    this[_elementType] = new IriSP.Model.Reference(this.source.directory, _idRef);
+    this[_elementType] = new IriSP.Model.Reference(this.source, _idRef);
 }
 
 IriSP.Model.Element.prototype.getReference = function(_elementType) {
@@ -261,24 +306,57 @@
 
 /* */
 
-IriSP.Model.Source = function(_properties) {
+IriSP.Model.Source = function(_config) {
     this.status = IriSP.Model.SOURCE_STATUS_EMPTY;
-    this.config = _properties;
-    this.callbackQueue = [];
-    this.contents = {};
-    this.get();
+    if (typeof _config !== "undefined") {
+        var _this = this;
+        IriSP._(_config).each(function(_v, _k) {
+            _this[_k] = _v;
+        })
+        this.callbackQueue = [];
+        this.contents = {};
+        if (typeof this.namespace === "undefined") {
+            this.namespace = IriSP.Model.getAI();
+        }
+        if (typeof this.namespaceUrl === "undefined") {
+            this.namespaceUrl = (typeof this.url !== "undefined" ? this.url : this.namespaceUrl);
+        }
+        this.directory.namespaces[this.namespace] = this.namespaceUrl;
+        this.get();
+    }
+}
+
+IriSP.Model.Source.prototype.getNamespaced = function(_id) {
+    var _tab = _id.split(':');
+    if (_tab.length > 1) {
+        return {
+            namespace : _tab[0],
+            name : _tab[1],
+            fullname : _id
+        }
+    } else {
+        return {
+            namespace : this.namespace,
+            name : _id,
+            fullname : this.namespace + ':' + _id
+        }
+    }
+}
+    
+IriSP.Model.Source.prototype.unNamespace = function(_id) {
+    return _id.replace(this.namespace + ':', '');
 }
 
 IriSP.Model.Source.prototype.addList = function(_listId, _contents) {
     if (typeof this.contents[_listId] === "undefined") {
-        this.contents[_listId] = new IriSP.Model.List(this.config.directory);
+        this.contents[_listId] = new IriSP.Model.List(this.directory);
     }
     this.contents[_listId].addIdsFromList(_contents);
 }
 
 IriSP.Model.Source.prototype.getList = function(_listId) {
     if (typeof this.contents[_listId] === "undefined") {
-        return this.config.directory.getGlobalList.filter(function(_e) {
+        return this.directory.getGlobalList().filter(function(_e) {
             return (_e.elType === _listId);
         });
     } else {
@@ -286,6 +364,13 @@
     }
 }
 
+IriSP.Model.Source.prototype.each = function(_callback) {
+    var _this = this;
+    IriSP._(this.contents).each(function(_value, _key) {
+        _callback.call(_this, _value, _key);
+    })
+}
+
 IriSP.Model.Source.prototype.getElement = function(_listId, _elId) {
     var _list = this.getList(_listId);
     return (typeof _list !== "undefined" ? _list.getElement(_elId) : undefined);
@@ -293,7 +378,7 @@
 
 IriSP.Model.Source.prototype.setCurrentMediaId = function(_idRef) {
     if (typeof _idRef !== "undefined") {
-        this.currentMedia = _idRef;
+        this.currentMedia = this.getNamespaced(_idRef).fullname;
     }
 }
 
@@ -303,8 +388,21 @@
     }
 }
 
+IriSP.Model.Source.prototype.listNamespaces = function() {
+    var _this = this,
+        _nsls = [];
+    this.each(function(_list) {
+        IriSP._(_list.contents).each(function(_id) {
+            var _ns = _id.replace(/:.*$/,'');
+            if (_nsls.indexOf(_ns) === -1) {
+                _nsls.push(_ns);
+            }
+        })
+    });
+    return _nsls;
+}
+
 IriSP.Model.Source.prototype.get = function() {
-    this.status = IriSP.Model.SOURCE_STATUS_WAITING;
     this.status = IriSP.Model.SOURCE_STATUS_READY;
     var _this = this;
     if (_this.callbackQueue.length) {
@@ -315,6 +413,10 @@
     _this.callbackQueue = [];
 }
 
+IriSP.Model.Source.prototype.serialize = function() {
+    return this.serializer.serialize(this);
+}
+
 IriSP.Model.Source.prototype.addCallback = function(_callback) {
     if (this.status === IriSP.Model.SOURCE_STATUS_READY) {
         callback.call(this);
@@ -337,9 +439,8 @@
 
 /* */
 
-IriSP.Model.RemoteSource = function() {
-    IriSP.Model.Element.call(this, _id, _directory);
-    this.elementType = 'tag';
+IriSP.Model.RemoteSource = function(_config) {
+    IriSP.Model.Source.call(this, _config);
 }
 
 IriSP.Model.RemoteSource.prototype = new IriSP.Model.Source();
@@ -363,18 +464,24 @@
 
 IriSP.Model.Directory = function() {
     this.remoteSources = {};
-    this.localSource = [];
     this.elements = {};
-    this.nameSpaces = {};
+    this.namespaces = {};
 }
 
 IriSP.Model.Directory.prototype.remoteSource = function(_properties) {
+    var _config = IriSP._({ directory: this }).extend(_properties);
     if (typeof this.remoteSources[_properties.url] === "undefined") {
-        this.remoteSources[_properties.url] = new IriSP.Model.RemoteSource(_properties);
+        this.remoteSources[_properties.url] = new IriSP.Model.RemoteSource(_config);
     }
     return this.remoteSources[_properties.url];
 }
 
+IriSP.Model.Directory.prototype.newLocalSource = function(_properties) {
+    var _config = IriSP._({ directory: this }).extend(_properties),
+        _res = new IriSP.Model.Source(_config);
+    return _res;
+}
+
 IriSP.Model.Directory.prototype.getElement = function(_id) {
     return this.elements[_id];
 }
--- a/src/js/serializers/PlatformSerializer.js	Thu Apr 12 15:54:33 2012 +0200
+++ b/src/js/serializers/PlatformSerializer.js	Fri Apr 13 18:08:19 2012 +0200
@@ -3,64 +3,121 @@
 }
 
 IriSP.serializers.platform = {
-    deSerialize : function(_data, _container) {
-        
-        var _types = [
-            {
-                serialized_name : "medias",
-                model_name : "media",
-                deserializer : function(_data) {
-                    var _res = new IriSP.Model.Media(_data.id, _container);
-                    _res.url = _data.href;
-                    _res.title = _data.meta["dc:title"];
-                    _res.description = _data.meta["dc:description"];
-                    _res.setDuration(_data.meta["dc:duration"]);
-                    return _res;        
-                }
-            },
-            {
-                serialized_name : "tags",
-                model_name : "tag",
-                deserializer : function(_data) {
-                    var _res = new IriSP.Model.Tag(_data.id, _container);
-                    _res.title = _data["dc:title"];
-                    return _res;        
-                }
+    types :  {
+        media : {
+            serialized_name : "medias",
+            model_name : "media",
+            deserializer : function(_data, _container) {
+                var _res = new IriSP.Model.Media(_data.id, _container);
+                _res.url = _data.href;
+                _res.title = _data.meta["dc:title"];
+                _res.description = _data.meta["dc:description"];
+                _res.setDuration(_data.meta["dc:duration"]);
+                return _res;        
             },
-            {
-                serialized_name : "annotation-types",
-                model_name : "annotationType",
-                deserializer : function(_data) {
-                    var _res = new IriSP.Model.AnnotationType(_data.id, _container);
-                    _res.title = _data["dc:title"];
-                    _res.description = _data["dc:description"];
-                    return _res;        
+            serializer : function(_data, _container) {
+                return {
+                    id : _container.unNamespace(_data.id),
+                    href : _data.url,
+                    meta : {
+                        "dc:title" : _data.title,
+                        "dc:description" : _data.description,
+                        "dc:duration" : _data.duration.milliseconds
+                    }
                 }
+            }
+        },
+        tag : {
+            serialized_name : "tags",
+            model_name : "tag",
+            deserializer : function(_data, _container) {
+                var _res = new IriSP.Model.Tag(_data.id, _container);
+                _res.title = _data.meta["dc:title"];
+                return _res;        
             },
-            {
-                serialized_name : "annotations",
-                model_name : "annotation",
-                deserializer : function(_data) {
-                    var _res = new IriSP.Model.Annotation(_data.id, _container);
-                    _res.title = _data.content.title;
-                    _res.description = _data.content.description;
-                    _res.setMedia(_data.media, _container);
-                    _res.setAnnotationType(_data.meta["id-ref"]);
-                    _res.setTags(IriSP._(_data.tags).pluck("id-ref"));
-                    _res.setBegin(_data.begin);
-                    _res.setEnd(_data.end);
-                    return _res;
+            serializer : function(_data, _container) {
+                return {
+                    id : _container.unNamespace(_data.id),
+                    meta : {
+                        "dc:title" : _data.title
+                    }
                 }
             }
-        ];
-        
-        IriSP._(_types).each(function(_type) {
+        },
+        annotationTypes : {
+            serialized_name : "annotation-types",
+            deserializer : function(_data, _container) {
+                var _res = new IriSP.Model.AnnotationType(_data.id, _container);
+                _res.title = _data["dc:title"];
+                _res.description = _data["dc:description"];
+                return _res;        
+            },
+            serializer : function(_data, _container) {
+                return {
+                    id : _container.unNamespace(_data.id),
+                    "dc:title" : _data.title,
+                    "dc:description" : _data.description
+                }
+            }
+        },
+        annotation : {
+            serialized_name : "annotations",
+            deserializer : function(_data, _container) {
+                var _res = new IriSP.Model.Annotation(_data.id, _container);
+                _res.title = _data.content.title;
+                _res.description = _data.content.description;
+                _res.created = IriSP.Model.isoToDate(_data.meta["dc:created"]);
+                var _c = parseInt(_data.color).toString(16);
+                while (_c.length < 6) {
+                    _c = '0' + _c;
+                }
+                _res.color = '#' + _c;
+                _res.setMedia(_data.media, _container);
+                _res.setAnnotationType(_data.meta["id-ref"]);
+                _res.setTags(IriSP._(_data.tags).pluck("id-ref"));
+                _res.setBegin(_data.begin);
+                _res.setEnd(_data.end);
+                return _res;
+            },
+            serializer : function(_data, _container) {
+                return {
+                    id : _container.unNamespace(_data.id),
+                    content : {
+                        title : _data.title,
+                        description : _data.description
+                    },
+                    media : _container.unNamespace(_data.media.contents),
+                    meta : {
+                        "id-ref" : _container.unNamespace(_data.annotationType.contents),
+                        "dc:created" : IriSP.Model.dateToIso(_data.created)
+                    },
+                    tags : _data.getTags().map(function(_el, _id) {
+                       return {
+                           "id-ref" : _container.unNamespace(_id)
+                       } 
+                    })
+                }
+            }
+        }
+    },
+    serialize : function(_container) {
+        var _res = {},
+            _this = this;
+        _container.each(function(_list, _typename) {
+            _res[_this.types[_typename].serialized_name] = _list.map(function(_el) {
+                return _this.types[_typename].serializer(_el, _container);
+            });
+        });
+        return _res;
+    },
+    deSerialize : function(_data, _container) {
+        IriSP._(this.types).each(function(_type, _typename) {
             if (typeof _data[_type.serialized_name] !== "undefined") {
                 var _list = new IriSP.Model.List(_container.directory);
                 IriSP._(_data[_type.serialized_name]).each(function(_el) {
-                    _list.addElement(_type.deserializer(_el));
+                    _list.addElement(_type.deserializer(_el, _container));
                 });
-                _container.addList(_type.model_name, _list);
+                _container.addList(_typename, _list);
             }
         });
         
--- a/test/model/test.html	Thu Apr 12 15:54:33 2012 +0200
+++ b/test/model/test.html	Fri Apr 13 18:08:19 2012 +0200
@@ -15,10 +15,24 @@
             IriSP.jQuery = jQuery;
             IriSP._ = _;
             var _directory = new IriSP.Model.Directory();
-            var _source = _directory.source("../integration/polemic_fr.json", "ns", "ns", IriSP.serializers.platform);
+            var _source = _directory.remoteSource({
+                url: "../integration/polemic_fr.json",
+                namespace: "metadataplayer",
+                serializer: IriSP.serializers.platform
+            });
+            function showExport() {
+                console.log(_source.serialize());
+                $("body").html(JSON.stringify(_source.serialize()).replace(/(\[|\{)/g,'$1<ul><li>').replace(/(\]|\})/g,'</li></ul>$1').replace(/,/g,',</li><li>'))
+            }
         </script>
+        <style type="text/css">
+            ul, li {
+                list-style: none;
+                margin: 0;
+            }
+        </style>
     </head>
     <body>
-        <h1></h1>
+        <a href="#" onclick="showExport(); return false;">Export Json</a>
     </body>
 </html>