<commit_before>/**
 * @class Text
 * @extends Asset
 */

var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Asset = require('./Asset'),
    iconv;

try {
    iconv = require('iconv');
} catch (e) {}

/**
 * new Text(options)
 * =================
 *
 * Create a new Text asset instance.
 *
 * Adds text encoding and decoding support to Asset. Serves as a
 * superclass for `Html`, `Xml`, `Css`, `JavaScript`, `CoffeeScript`,
 * `Json`, and `CacheManifest`.
 *
 * In addition to the options already supported by the Asset base
 * class, these options are supported:
 *
 * - `text` (String) The decoded source of the asset. Can be used
 *              instead of `rawSrc` and `rawSrcProxy`.  - `encoding`
 *              (String) Used to decode and reencode the `rawSrc`. Can
 *              be any encoding supported by the `iconv` module. Can
 *              be changed later using the `encoding`
 *              getter/setter. Defaults to "utf-8" (see the docs for
 *              `defaultEncoding` below). If the asset is loaded via
 *              http, the encoding will be read from the
 *              `Content-Type`, and likewise for `data:` urls.
 *
 * Example:
 *
 *     var textAsset = new Text({
 *         // "æøå" in iso-8859-1:
 *         rawSrc: new Buffer([0xe6, 0xf8, 0xe5]),
 *         encoding: "iso-8859-1"
 *     });
 *     textAsset.text; // "æøå" (decoded JavaScript string)
 *     textAsset.encoding = 'utf-8';
 *     textAsset.rawSrc; // <Buffer c3 a6 c3 b8 c3 a5>
 */
function Text(config) {
    if ('text' in config) {
        this._text = config.text;
        delete config.text;
    }
    if (config.encoding) {
        this._encoding = config.encoding;
        delete config.encoding;
    }
    Asset.call(this, config);
}

util.inherits(Text, Asset);

extendWithGettersAndSetters(Text.prototype, {
    /**
     * text.isText
     * ===========
     *
     * Property that's true for all Text instances. Avoids reliance on
     * the `instanceof` operator.
     */

    /**
     * text.defaultEncoding
     * ====================
     *
     * The default encoding for the Text (sub)class. Used for decoding
     * the raw source when the encoding cannot be determined by other
     * means, such as a `Content-Type` header (when the asset was
     * fetched via http), or another indicator specific to the given
     * asset type (`@charset` for Css, `<meta
     * http-equiv="Content-Type" ...>` for Html).
     *
     * Factory setting is "utf-8", but you can override it by setting
     * `Text.prototype.defaultEncoding` to another value supported by
     * the `iconv` module.
     */
    defaultEncoding: 'utf-8',

    supportedExtensions: [
        '.txt',
        '.htaccess',
        '.md',
        '.rst',
        '.ics',
        '.csv',
        '.tsv',
        '.xtemplate' // For Ext.XTemplate + GETTEXT
    ],

    contentType: 'text/plain',

    /**
     * Text.encoding (getter/setter)
     * =============================
     *
     * Get or set the encoding (charset) used for re-encoding the raw
     * source of the asset. To affect the initial decoding of the
     * `rawSrc` option, provide the `encoding` option to the
     * constructor.
     */
    get encoding() {
        if (!this._encoding) {
            this._encoding = this.defaultEncoding;
        }
        return this._encoding;
    },

    set encoding(encoding) {
        if (encoding !== this.encoding) {
            /*jshint ignore:start*/
            var text = this.text; // Make sure this._text exists so the rawSrc is decoded before the original encoding is thrown away
            /*jshint ignore:end*/
            delete this._rawSrc;
            this._encoding = encoding;
            this.markDirty();
        }
    },

    get rawSrc() {
        if (!this._rawSrc) {
            var error;

            if ('_text' in this || this._parseTree) {
                if (/^utf-?8$/i.test(this.encoding)) {
                    this._updateRawSrcAndLastKnownByteLength(new Buffer(this.text, 'utf-8'));
                } else if (/^(?:us-?)?ascii$/i.test(this.encoding)) {
                    this._updateRawSrcAndLastKnownByteLength(new Buffer(this.text, 'ascii'));
                } else if (iconv) {
                    try {
                        this._updateRawSrcAndLastKnownByteLength(new iconv.Iconv('utf-8', this.encoding).convert(this.text));
                    } catch (err) {
                        err.message = 'iconv: Converting ' + this.url + ' from UTF-8 to ' + this.encoding + ' failed:\n' + err.message;
                        if (this.assetGraph) {
                            if (err.code === 'EILSEQ') {
                                err.message += '\nTransliterating and ignoring further failures. Data corruption may occur.';
                                this._updateRawSrcAndLastKnownByteLength(new iconv.Iconv('utf-8', this.encoding + '//TRANSLIT//IGNORE').convert(this.text));
                            }
                            this.assetGraph.emit('warn', err);
                        } else {
                            throw err;
                        }
                    }
                } else {
                    error = new Error('node-iconv not found. Cannot encode ' + this + ' as ' + this.encoding + '. ' +
                                    'Please run \'npm install iconv\' and try again');
                    error.asset = this;

                    if (this.assetGraph) {
                        this.assetGraph.emit('error', error);
                    } else {
                        throw error;
                    }
                }
            } else {
                error =  new Error('Text.rawSrc getter: No _rawSrc or _text property found, asset not loaded?');
                error.asset = this;

                if (this.assetGraph) {
                    this.assetGraph.emit('error', error);
                } else {
                    throw error;
                }
            }
        }
        return this._rawSrc;
    },

    set rawSrc(rawSrc) {
        var assetGraph = this.assetGraph;
        if (assetGraph) {
            assetGraph.removeAsset(this);
        }
        this._updateRawSrcAndLastKnownByteLength(rawSrc);
        delete this._parseTree;
        delete this._text;
        if (assetGraph) {
            assetGraph.addAsset(this);
        }
        this.markDirty();
    },

    /**
     * text.text (getter/setter)
     * =========================
     *
     * Get or set the decoded text contents of the of the asset as a
     * JavaScript string. Unlike browsers AssetGraph doesn't try to
     * sniff the charset of your text-based assets. It will fall back
     * to assuming utf-8 if it's unable to determine the
     * encoding/charset from HTTP headers, `<meta
     * http-equiv='Content-Type'>` tags (Html), `@charset` (Css), so
     * if for some reason you're not using utf-8 for all your
     * text-based assets, make sure to provide those hints. Other
     * asset types provide no standard way to specify the charset
     * within the file itself, so presently there's no way to load
     * eg. JavaScript from disc if it's not utf-8 or ASCII, except by
     * overriding `Text.prototype.defaultEncoding` globally.
     *
     * If the internal state has been changed since the asset was
     * initialized, it will automatically be reserialized when the
     * `text` property is retrieved, for example:
     *
     *     var htmlAsset = new Html({
     *         rawSrc: new Buffer("hello");
     *     });
     *     htmlAsset.text; // "hello"
     *     htmlAsset.parseTree.body.innerHTML = "bye";
     *     htmlAsset.markDirty();
     *     htmlAsset.text; // "bye"
     *
     * Setting this property after the outgoing relations have been
     * accessed currently leads to undefined behavior.
     */
    get text() {
        if (!('_text' in this)) {
            this._text = this._getTextFromRawSrc();
        }
        return this._text;
    },

    set text(text) {
        this.unload();
        this._text = text;
        if (this.assetGraph) {
            this.populate();
        }
        this.markDirty();
    },

    markDirty: function () {
        if (this._parseTree) {
            delete this._text;
        }
        return Asset.prototype.markDirty.call(this);
    },

    _getTextFromRawSrc: function () {
        if (!this.isLoaded) {
            throw new Error('Text._getTextFromRawSrc(): Asset not loaded: ' + this.urlOrDescription);
        }
        if (!this._rawSrc) {
            throw new Error('Text._getTextFromRawSrc(): No _rawSrc property found: ' + this.urlOrDescription);
        }
        if (/^utf-?8$/i.test(this.encoding)) {
            return this._rawSrc.toString('utf-8');
        } else if (/^(?:us-?)?ascii$/i.test(this.encoding)) {
            return this._rawSrc.toString('ascii');
        } else if (iconv) {
            return new iconv.Iconv(this.encoding, 'utf-8').convert(this._rawSrc).toString('utf-8');
        } else {
            var error = new Error('node-iconv not found. Cannot decode ' + this + ' (encoding is ' + this.encoding + '). ' +
                            'Please run `npm install iconv` and try again');
            error.asset = this;

            if (this.assetGraph) {
                this.assetGraph.emit('error', error);
            } else {
                throw error;
            }
        }
    }
});

module.exports = Text;
<commit_msg>Make Text's rawSrc setter work like Asset's.<commit_after>/**
 * @class Text
 * @extends Asset
 */

var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Asset = require('./Asset'),
    iconv;

try {
    iconv = require('iconv');
} catch (e) {}

/**
 * new Text(options)
 * =================
 *
 * Create a new Text asset instance.
 *
 * Adds text encoding and decoding support to Asset. Serves as a
 * superclass for `Html`, `Xml`, `Css`, `JavaScript`, `CoffeeScript`,
 * `Json`, and `CacheManifest`.
 *
 * In addition to the options already supported by the Asset base
 * class, these options are supported:
 *
 * - `text` (String) The decoded source of the asset. Can be used
 *              instead of `rawSrc` and `rawSrcProxy`.  - `encoding`
 *              (String) Used to decode and reencode the `rawSrc`. Can
 *              be any encoding supported by the `iconv` module. Can
 *              be changed later using the `encoding`
 *              getter/setter. Defaults to "utf-8" (see the docs for
 *              `defaultEncoding` below). If the asset is loaded via
 *              http, the encoding will be read from the
 *              `Content-Type`, and likewise for `data:` urls.
 *
 * Example:
 *
 *     var textAsset = new Text({
 *         // "æøå" in iso-8859-1:
 *         rawSrc: new Buffer([0xe6, 0xf8, 0xe5]),
 *         encoding: "iso-8859-1"
 *     });
 *     textAsset.text; // "æøå" (decoded JavaScript string)
 *     textAsset.encoding = 'utf-8';
 *     textAsset.rawSrc; // <Buffer c3 a6 c3 b8 c3 a5>
 */
function Text(config) {
    if ('text' in config) {
        this._text = config.text;
        delete config.text;
    }
    if (config.encoding) {
        this._encoding = config.encoding;
        delete config.encoding;
    }
    Asset.call(this, config);
}

util.inherits(Text, Asset);

extendWithGettersAndSetters(Text.prototype, {
    /**
     * text.isText
     * ===========
     *
     * Property that's true for all Text instances. Avoids reliance on
     * the `instanceof` operator.
     */

    /**
     * text.defaultEncoding
     * ====================
     *
     * The default encoding for the Text (sub)class. Used for decoding
     * the raw source when the encoding cannot be determined by other
     * means, such as a `Content-Type` header (when the asset was
     * fetched via http), or another indicator specific to the given
     * asset type (`@charset` for Css, `<meta
     * http-equiv="Content-Type" ...>` for Html).
     *
     * Factory setting is "utf-8", but you can override it by setting
     * `Text.prototype.defaultEncoding` to another value supported by
     * the `iconv` module.
     */
    defaultEncoding: 'utf-8',

    supportedExtensions: [
        '.txt',
        '.htaccess',
        '.md',
        '.rst',
        '.ics',
        '.csv',
        '.tsv',
        '.xtemplate' // For Ext.XTemplate + GETTEXT
    ],

    contentType: 'text/plain',

    /**
     * Text.encoding (getter/setter)
     * =============================
     *
     * Get or set the encoding (charset) used for re-encoding the raw
     * source of the asset. To affect the initial decoding of the
     * `rawSrc` option, provide the `encoding` option to the
     * constructor.
     */
    get encoding() {
        if (!this._encoding) {
            this._encoding = this.defaultEncoding;
        }
        return this._encoding;
    },

    set encoding(encoding) {
        if (encoding !== this.encoding) {
            /*jshint ignore:start*/
            var text = this.text; // Make sure this._text exists so the rawSrc is decoded before the original encoding is thrown away
            /*jshint ignore:end*/
            delete this._rawSrc;
            this._encoding = encoding;
            this.markDirty();
        }
    },

    get rawSrc() {
        if (!this._rawSrc) {
            var error;

            if ('_text' in this || this._parseTree) {
                if (/^utf-?8$/i.test(this.encoding)) {
                    this._updateRawSrcAndLastKnownByteLength(new Buffer(this.text, 'utf-8'));
                } else if (/^(?:us-?)?ascii$/i.test(this.encoding)) {
                    this._updateRawSrcAndLastKnownByteLength(new Buffer(this.text, 'ascii'));
                } else if (iconv) {
                    try {
                        this._updateRawSrcAndLastKnownByteLength(new iconv.Iconv('utf-8', this.encoding).convert(this.text));
                    } catch (err) {
                        err.message = 'iconv: Converting ' + this.url + ' from UTF-8 to ' + this.encoding + ' failed:\n' + err.message;
                        if (this.assetGraph) {
                            if (err.code === 'EILSEQ') {
                                err.message += '\nTransliterating and ignoring further failures. Data corruption may occur.';
                                this._updateRawSrcAndLastKnownByteLength(new iconv.Iconv('utf-8', this.encoding + '//TRANSLIT//IGNORE').convert(this.text));
                            }
                            this.assetGraph.emit('warn', err);
                        } else {
                            throw err;
                        }
                    }
                } else {
                    error = new Error('node-iconv not found. Cannot encode ' + this + ' as ' + this.encoding + '. ' +
                                    'Please run \'npm install iconv\' and try again');
                    error.asset = this;

                    if (this.assetGraph) {
                        this.assetGraph.emit('error', error);
                    } else {
                        throw error;
                    }
                }
            } else {
                error =  new Error('Text.rawSrc getter: No _rawSrc or _text property found, asset not loaded?');
                error.asset = this;

                if (this.assetGraph) {
                    this.assetGraph.emit('error', error);
                } else {
                    throw error;
                }
            }
        }
        return this._rawSrc;
    },

    set rawSrc(rawSrc) {
        this.unload();
        delete this._parseTree;
        delete this._text;
        this._updateRawSrcAndLastKnownByteLength(rawSrc);
        if (this.assetGraph) {
            this.populate();
        }
        this.markDirty();
    },

    /**
     * text.text (getter/setter)
     * =========================
     *
     * Get or set the decoded text contents of the of the asset as a
     * JavaScript string. Unlike browsers AssetGraph doesn't try to
     * sniff the charset of your text-based assets. It will fall back
     * to assuming utf-8 if it's unable to determine the
     * encoding/charset from HTTP headers, `<meta
     * http-equiv='Content-Type'>` tags (Html), `@charset` (Css), so
     * if for some reason you're not using utf-8 for all your
     * text-based assets, make sure to provide those hints. Other
     * asset types provide no standard way to specify the charset
     * within the file itself, so presently there's no way to load
     * eg. JavaScript from disc if it's not utf-8 or ASCII, except by
     * overriding `Text.prototype.defaultEncoding` globally.
     *
     * If the internal state has been changed since the asset was
     * initialized, it will automatically be reserialized when the
     * `text` property is retrieved, for example:
     *
     *     var htmlAsset = new Html({
     *         rawSrc: new Buffer("hello");
     *     });
     *     htmlAsset.text; // "hello"
     *     htmlAsset.parseTree.body.innerHTML = "bye";
     *     htmlAsset.markDirty();
     *     htmlAsset.text; // "bye"
     *
     * Setting this property after the outgoing relations have been
     * accessed currently leads to undefined behavior.
     */
    get text() {
        if (!('_text' in this)) {
            this._text = this._getTextFromRawSrc();
        }
        return this._text;
    },

    set text(text) {
        this.unload();
        this._text = text;
        if (this.assetGraph) {
            this.populate();
        }
        this.markDirty();
    },

    markDirty: function () {
        if (this._parseTree) {
            delete this._text;
        }
        return Asset.prototype.markDirty.call(this);
    },

    _getTextFromRawSrc: function () {
        if (!this.isLoaded) {
            throw new Error('Text._getTextFromRawSrc(): Asset not loaded: ' + this.urlOrDescription);
        }
        if (!this._rawSrc) {
            throw new Error('Text._getTextFromRawSrc(): No _rawSrc property found: ' + this.urlOrDescription);
        }
        if (/^utf-?8$/i.test(this.encoding)) {
            return this._rawSrc.toString('utf-8');
        } else if (/^(?:us-?)?ascii$/i.test(this.encoding)) {
            return this._rawSrc.toString('ascii');
        } else if (iconv) {
            return new iconv.Iconv(this.encoding, 'utf-8').convert(this._rawSrc).toString('utf-8');
        } else {
            var error = new Error('node-iconv not found. Cannot decode ' + this + ' (encoding is ' + this.encoding + '). ' +
                            'Please run `npm install iconv` and try again');
            error.asset = this;

            if (this.assetGraph) {
                this.assetGraph.emit('error', error);
            } else {
                throw error;
            }
        }
    }
});

module.exports = Text;
<|endoftext|>


<commit_before>;(function(){
	var iframeEl = $('#shareIframe');
	var EditMark = '/cgi/editmark', //修改备注
		MoveFile = '/cgi/movefile', //移动文件到文件夹
		UnColl = '/cgi/uncoll',
		AddColl = '/cgi/addcoll';   //添加收藏
    $("#newFolds").validate({
            rules:{
                    foldname : {
                            required : true,
                            maxlength : 120,
                            minlength : 2
                    }
            },
            messages:{
                    foldname : {
                            require : '请输入文件夹名称',
                            maxlength : '文件名称最长120个字',
                            minlength : '文件名称至少需要2个字'
                    }
            },
            submitHandler : function(form) {
			 	var value = $('#foldname').val();
			 	var pid = $('#newFolds .parentid').val();
			 	var gid = $('#newFolds .groupid').val();
			 	if(value != ''){
			 		////console.log(value);
			 		$.post('/cgi/addfold',{name: value,pid: pid,gid:gid,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			 			if(d.ret==0){
			 				$("#newFold .close").click();
			 				window.location.reload();
			 			}else{
			 				alert(d.msg);
			 			}
			 			$("#newFold .close").click();
			 		});
			 	}
                //return false;
            }
    });

    $("#reName").validate({
        rules:{
            fname : {
                    required : true,
                    maxlength : 120,
                    minlength : 2
            }
        },
        messages:{
            fname : {
                    require : '请输入文件名称',
                    maxlength : '文件名称最长120个字',
                    minlength : '文件名称至少需要2个字'
            }
        },
        submitHandler : function(form) {
        	var data = {
        		fname : $('#reName .foldname').val(),
        		fid : $('#reName .fid').val(),
        		csrf_test_name:$.cookie('csrf_cookie_name')
        	}
        	$.post('/cgi/renamefile',data,function(d){
	 			if(d.ret==0){
	 				$("#renameFile .close").click();
	 				window.location.reload();
	 			}else{
	 				alert(d.msg);
	 			}
	 			$("#renameFile .close").click();
        	});
            return false;
        }
    });

	// var uploader = new plupload.Uploader({
	// 	runtimes : 'html5,flash,silverlight,html4',
	// 	browse_button : 'btnUpload', // you can pass in id...
	// 	container: document.getElementById('uploadContainer'), // ... or DOM Element itself
	// 	url : '/cgi/gupload?gid='+nowGroupId+'&csrf_test_name='+$.cookie('csrf_cookie_name'),
	// 	unique_names : true,
	// 	flash_swf_url : '/js/lib/Moxie.swf',
	// 	silverlight_xap_url : '/js/lib/Moxie.xap',

	// 	filters : {
	// 		max_file_size : '500mb',
	// 		mime_types: [
	// 			{title : "图片", extensions : "jpg,gif,png"},
	// 			{title : "文档", extensions : "doc,txt"},
	// 			{title : "音乐", extensions : "mid,mp3"},
	// 			{title : "视频", extensions : "avi,mp4"},
	// 			{title : "应用", extensions : "exe"},
	// 			{title : "压缩文件", extensions : "zip"}
	// 			// {title : "文本", extensions : "txt"},
	// 			// {title : "word文档", extensions : "doc"}
	// 		]
	// 	},

	// 	init: {
	// 		PostInit: function() {
	// 			$('#file_uploadList').html('');
	// 			//document.getElementById('file_uploadList').innerHTML = '';
	// 			$('#btnStartUload').bind('click',function(){
	// 				//uploader.settings.url = '';
	// 				var fid = $('#uploadFile .foldid').val();
	// 				if(fid){
	// 					uploader.settings.url = '/cgi/gupload?gid='+nowGroupId+'&fid='+fid+'&csrf_test_name='+$.cookie('csrf_cookie_name');
	// 				}
	// 				uploader.start();
	// 			});
	// 		},
	// 		FilesAdded: function(up, files) {
	// 			//console.log(plupload);
	// 			plupload.each(files, function(file) {
	// 				$('#file_uploadList').append('
' + file.name + ' (' + plupload.formatSize(file.size) + ')
');

	// 			});
	// 		},

	// 		UploadProgress: function(up, file) {
	// 			document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '' + file.percent + "%";
	// 		},
	// 		FileUploaded: function(e,file){
	// 			//console.log(e,file);
	// 			//window.location.reload();
	// 		},
	// 		Error: function(up, err) {
	// 			//console.log(up,err);
	// 			//document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
	// 		}
	// 	}
	// });

	uploader.init();

	$('#collFiles').bind('click',collFiles);

	$("#groupDesc a").bind('click',function(){
		$("#groupDesc").hide();
		$("#groupEdit").removeClass('hide');
	})

	$('#groupEdit .save').bind('click',function(){
		var c = $('#groupEdit textarea').val();
		$.post('/cgi/group_edit_desc',{d:c,gid:ginfo.id,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			if(d.ret == 0){
				$("#groupDesc p").text(c);
				$("#groupDesc").show();
				$("#groupEdit").addClass('hide');
			}else{
				alert(d.msg);
			}
		});
	});
	$('#groupEdit .sec').bind('click',function(){
		$("#groupDesc").show();
		$("#groupEdit").addClass('hide');
	});

	$("#postWin .btn-post").bind('click',function(){
		var c = $("#postWin textarea").val();
		$.post('/cgi/add_board',{d:c,gid:ginfo.id,type:1,pid:0,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			if(d.ret == 0){
				//$('#postWin').modal('hide');
				window.location.reload();
			}else{
				alert(d.msg);
			}
		});
	});

	var showShare = function(id,cmd){
		var il = [],
			nl = [];
		if(!id){
			$('#fileList .fclick:checked').each(function(){
				il.push($(this).val());
			});
		}else if(typeof id == 'string'){
			il.push(id);
			nl.push(name);
		}else{
			il = id;
			nl = name;
		}
		var id = il.join(',');
		switch(cmd){
			case 'toother':
				$('#shareWin h4').text('共享 发送给别人');
				//console.log(12345);
				iframeEl.attr('src','/share/other?id='+id+'&gid='+ginfo.id);
				break;
			case 'togroup':
				$('#shareWin h4').text('共享 到小组空间');
				iframeEl.attr('src','/share/group?id='+id+'&gid='+ginfo.id);
				break;
			case 'todep':
				$('#shareWin h4').text('共享 到部门空间');
				iframeEl.attr('src','/share/dep?id='+id+'&gid='+ginfo.id);
				break;
		}
	}

	var collFiles = function(){
		var il = [];
		$('#fileList .fclick:checked').each(function(){
			//if($(this).parents('li.file').find('i.s').length == 0){
				il.push($(this).val());
			//}
		});
		id = il.join(',');
		$.post(AddColl,{id:id,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			if(d.ret == 0){
				//target.parent('span').prev('span').text(d.info);
				window.location.reload();
			}else{
				//console.log(d.msg);
			}
		});
	}

	var collFile = function(id,target){
		var data = {
			id : id,
			csrf_test_name:$.cookie('csrf_cookie_name')
		}
		$.post(AddColl,data,function(d){
			//console.log(d);
			if(d.ret == 0){
				target.addClass('s');
			}
		});
	}

	var uncollFile = function(id,target){
		var data = {
			id : id,
			csrf_test_name:$.cookie('csrf_cookie_name')
		}
		$.post(UnColl,data,function(d){
			//console.log(d);
			if(d.ret == 0){
				target.removeClass('s');
			}
		});
	}

	var deleteFile = function(item){
		item.remove();
		if($("#fileList .file").length == 0){
			$('#fileList .file-list').hide(200);
		}
	}

    //显示或者隐藏重命名和评论
    var checkAct = function(){
    	var l = $('#fileList .fclick:checked').length;
    	//console.log(l);
    	if(l==0){
			$('.tool-zone').removeClass('hide');
			$('.file-act-zone').addClass('hide');
    	}else{
			$('.tool-zone').addClass('hide');
			$('.file-act-zone').removeClass('hide');
    		if(l>1){
	    		$('#renameAct').addClass('hide');
	    		$('#remarkAct').addClass('hide');
    		}else{
	    		$('#renameAct').removeClass('hide');
	    		$('#remarkAct').removeClass('hide');
    		}
    	}
    }
    //输入框点击事件
	$("#fileList input").click(function(e){
		checkAct();
	})

	$('#fileList').bind('click',function(e){
		var target = $(e.target),
			cmd = target.attr('cmd');
		switch(cmd){
			case 'toother':
			case 'togroup':
			case 'todep':
				var id = target.attr('data-id');
				var name = target.attr('data-name');
				showShare(id,cmd);
				break;
			case 'coll':
				var id = target.attr('data-id'),
					type = target.attr('data-type');
					if(type == 'file'){
						collFile(id,target);
					}
				break;
			case 'uncoll':
				var id = target.attr('data-id'),
					type = target.attr('data-type');
					if(type == 'file'){
						uncollFile(id,target);
					}
				break;
			case 'edit':
				target.hide();
				target.next('span').removeClass('hide');
				break;
			case 'editComp':
				var mark = target.prev('input').val(),
					id = target.attr('data-id'),
					type = target.attr('data-type');
					//console.log(id,type);
					editMark(id,mark,type,target);
					target.parent('span').prev('span').show();
					target.parent('span').addClass('hide');
				break;
			case 'editClose':
				var mark = target.attr('data-value');
				target.prev('input').val(mark);
				target.parent('span').prev('span').show();
				target.parent('span').addClass('hide');
				break;
		}
	});

	$('.file-act-zone a').bind('click',function(e){
		var target = $(e.target),
			cmd = target.attr('cmd');
		switch(cmd){
			case 'toother':
			case 'togroup':
			case 'todep':
				showShare(null,cmd);
				break;
			case 'copyFile':
				copyFile();
				break;
		}
	})

	$("#fileList .file .file-name").click(function(e){
		var target = $(e.target);
		var fid = target.attr('data-fid');
		var id= target.attr('data-id');
		//review?fid=24&t=2&gid=0&id=18
		$("#reviewIframe").attr('src','/review?fid='+fid+'&id='+id);
		$('#reviewFile').modal('show');
	});
})()<commit_msg>group js bug<commit_after>;(function(){
	var iframeEl = $('#shareIframe');
	var EditMark = '/cgi/editmark', //修改备注
		MoveFile = '/cgi/movefile', //移动文件到文件夹
		UnColl = '/cgi/uncoll',
		AddColl = '/cgi/addcoll';   //添加收藏
    $("#newFolds").validate({
            rules:{
                    foldname : {
                            required : true,
                            maxlength : 120,
                            minlength : 2
                    }
            },
            messages:{
                    foldname : {
                            require : '请输入文件夹名称',
                            maxlength : '文件名称最长120个字',
                            minlength : '文件名称至少需要2个字'
                    }
            },
            submitHandler : function(form) {
			 	var value = $('#foldname').val();
			 	var pid = $('#newFolds .parentid').val();
			 	var gid = $('#newFolds .groupid').val();
			 	if(value != ''){
			 		////console.log(value);
			 		$.post('/cgi/addfold',{name: value,pid: pid,gid:gid,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			 			if(d.ret==0){
			 				$("#newFold .close").click();
			 				window.location.reload();
			 			}else{
			 				alert(d.msg);
			 			}
			 			$("#newFold .close").click();
			 		});
			 	}
                //return false;
            }
    });

    $("#reName").validate({
        rules:{
            fname : {
                    required : true,
                    maxlength : 120,
                    minlength : 2
            }
        },
        messages:{
            fname : {
                    require : '请输入文件名称',
                    maxlength : '文件名称最长120个字',
                    minlength : '文件名称至少需要2个字'
            }
        },
        submitHandler : function(form) {
        	var data = {
        		fname : $('#reName .foldname').val(),
        		fid : $('#reName .fid').val(),
        		csrf_test_name:$.cookie('csrf_cookie_name')
        	}
        	$.post('/cgi/renamefile',data,function(d){
	 			if(d.ret==0){
	 				$("#renameFile .close").click();
	 				window.location.reload();
	 			}else{
	 				alert(d.msg);
	 			}
	 			$("#renameFile .close").click();
        	});
            return false;
        }
    });

	// var uploader = new plupload.Uploader({
	// 	runtimes : 'html5,flash,silverlight,html4',
	// 	browse_button : 'btnUpload', // you can pass in id...
	// 	container: document.getElementById('uploadContainer'), // ... or DOM Element itself
	// 	url : '/cgi/gupload?gid='+nowGroupId+'&csrf_test_name='+$.cookie('csrf_cookie_name'),
	// 	unique_names : true,
	// 	flash_swf_url : '/js/lib/Moxie.swf',
	// 	silverlight_xap_url : '/js/lib/Moxie.xap',

	// 	filters : {
	// 		max_file_size : '500mb',
	// 		mime_types: [
	// 			{title : "图片", extensions : "jpg,gif,png"},
	// 			{title : "文档", extensions : "doc,txt"},
	// 			{title : "音乐", extensions : "mid,mp3"},
	// 			{title : "视频", extensions : "avi,mp4"},
	// 			{title : "应用", extensions : "exe"},
	// 			{title : "压缩文件", extensions : "zip"}
	// 			// {title : "文本", extensions : "txt"},
	// 			// {title : "word文档", extensions : "doc"}
	// 		]
	// 	},

	// 	init: {
	// 		PostInit: function() {
	// 			$('#file_uploadList').html('');
	// 			//document.getElementById('file_uploadList').innerHTML = '';
	// 			$('#btnStartUload').bind('click',function(){
	// 				//uploader.settings.url = '';
	// 				var fid = $('#uploadFile .foldid').val();
	// 				if(fid){
	// 					uploader.settings.url = '/cgi/gupload?gid='+nowGroupId+'&fid='+fid+'&csrf_test_name='+$.cookie('csrf_cookie_name');
	// 				}
	// 				uploader.start();
	// 			});
	// 		},
	// 		FilesAdded: function(up, files) {
	// 			//console.log(plupload);
	// 			plupload.each(files, function(file) {
	// 				$('#file_uploadList').append('
' + file.name + ' (' + plupload.formatSize(file.size) + ')
');

	// 			});
	// 		},

	// 		UploadProgress: function(up, file) {
	// 			document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '' + file.percent + "%";
	// 		},
	// 		FileUploaded: function(e,file){
	// 			//console.log(e,file);
	// 			//window.location.reload();
	// 		},
	// 		Error: function(up, err) {
	// 			//console.log(up,err);
	// 			//document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
	// 		}
	// 	}
	// });

	//uploader.init();

	$('#collFiles').bind('click',collFiles);

	$("#groupDesc a").bind('click',function(){
		$("#groupDesc").hide();
		$("#groupEdit").removeClass('hide');
	})

	$('#groupEdit .save').bind('click',function(){
		var c = $('#groupEdit textarea').val();
		$.post('/cgi/group_edit_desc',{d:c,gid:ginfo.id,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			if(d.ret == 0){
				$("#groupDesc p").text(c);
				$("#groupDesc").show();
				$("#groupEdit").addClass('hide');
			}else{
				alert(d.msg);
			}
		});
	});
	$('#groupEdit .sec').bind('click',function(){
		$("#groupDesc").show();
		$("#groupEdit").addClass('hide');
	});

	$("#postWin .btn-post").bind('click',function(){
		var c = $("#postWin textarea").val();
		$.post('/cgi/add_board',{d:c,gid:ginfo.id,type:1,pid:0,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			if(d.ret == 0){
				//$('#postWin').modal('hide');
				window.location.reload();
			}else{
				alert(d.msg);
			}
		});
	});

	var showShare = function(id,cmd){
		var il = [],
			nl = [];
		if(!id){
			$('#fileList .fclick:checked').each(function(){
				il.push($(this).val());
			});
		}else if(typeof id == 'string'){
			il.push(id);
			nl.push(name);
		}else{
			il = id;
			nl = name;
		}
		var id = il.join(',');
		switch(cmd){
			case 'toother':
				$('#shareWin h4').text('共享 发送给别人');
				//console.log(12345);
				iframeEl.attr('src','/share/other?id='+id+'&gid='+ginfo.id);
				break;
			case 'togroup':
				$('#shareWin h4').text('共享 到小组空间');
				iframeEl.attr('src','/share/group?id='+id+'&gid='+ginfo.id);
				break;
			case 'todep':
				$('#shareWin h4').text('共享 到部门空间');
				iframeEl.attr('src','/share/dep?id='+id+'&gid='+ginfo.id);
				break;
		}
	}

	var collFiles = function(){
		var il = [];
		$('#fileList .fclick:checked').each(function(){
			//if($(this).parents('li.file').find('i.s').length == 0){
				il.push($(this).val());
			//}
		});
		id = il.join(',');
		$.post(AddColl,{id:id,csrf_test_name:$.cookie('csrf_cookie_name')},function(d){
			if(d.ret == 0){
				//target.parent('span').prev('span').text(d.info);
				window.location.reload();
			}else{
				//console.log(d.msg);
			}
		});
	}

	var collFile = function(id,target){
		var data = {
			id : id,
			csrf_test_name:$.cookie('csrf_cookie_name')
		}
		$.post(AddColl,data,function(d){
			//console.log(d);
			if(d.ret == 0){
				target.addClass('s');
			}
		});
	}

	var uncollFile = function(id,target){
		var data = {
			id : id,
			csrf_test_name:$.cookie('csrf_cookie_name')
		}
		$.post(UnColl,data,function(d){
			//console.log(d);
			if(d.ret == 0){
				target.removeClass('s');
			}
		});
	}

	var deleteFile = function(item){
		item.remove();
		if($("#fileList .file").length == 0){
			$('#fileList .file-list').hide(200);
		}
	}

    //显示或者隐藏重命名和评论
    var checkAct = function(){
    	var l = $('#fileList .fclick:checked').length;
    	//console.log(l);
    	if(l==0){
			$('.tool-zone').removeClass('hide');
			$('.file-act-zone').addClass('hide');
    	}else{
			$('.tool-zone').addClass('hide');
			$('.file-act-zone').removeClass('hide');
    		if(l>1){
	    		$('#renameAct').addClass('hide');
	    		$('#remarkAct').addClass('hide');
    		}else{
	    		$('#renameAct').removeClass('hide');
	    		$('#remarkAct').removeClass('hide');
    		}
    	}
    }
    //输入框点击事件
	$("#fileList input").click(function(e){
		checkAct();
	})

	$('#fileList').bind('click',function(e){
		var target = $(e.target),
			cmd = target.attr('cmd');
		switch(cmd){
			case 'toother':
			case 'togroup':
			case 'todep':
				var id = target.attr('data-id');
				var name = target.attr('data-name');
				showShare(id,cmd);
				break;
			case 'coll':
				var id = target.attr('data-id'),
					type = target.attr('data-type');
					if(type == 'file'){
						collFile(id,target);
					}
				break;
			case 'uncoll':
				var id = target.attr('data-id'),
					type = target.attr('data-type');
					if(type == 'file'){
						uncollFile(id,target);
					}
				break;
			case 'edit':
				target.hide();
				target.next('span').removeClass('hide');
				break;
			case 'editComp':
				var mark = target.prev('input').val(),
					id = target.attr('data-id'),
					type = target.attr('data-type');
					//console.log(id,type);
					editMark(id,mark,type,target);
					target.parent('span').prev('span').show();
					target.parent('span').addClass('hide');
				break;
			case 'editClose':
				var mark = target.attr('data-value');
				target.prev('input').val(mark);
				target.parent('span').prev('span').show();
				target.parent('span').addClass('hide');
				break;
		}
	});

	$('.file-act-zone a').bind('click',function(e){
		var target = $(e.target),
			cmd = target.attr('cmd');
		switch(cmd){
			case 'toother':
			case 'togroup':
			case 'todep':
				showShare(null,cmd);
				break;
			case 'copyFile':
				copyFile();
				break;
		}
	})

	$("#fileList .file .file-name").click(function(e){
		var target = $(e.target);
		var fid = target.attr('data-fid');
		var id= target.attr('data-id');
		//review?fid=24&t=2&gid=0&id=18
		$("#reviewIframe").attr('src','/review?fid='+fid+'&id='+id);
		$('#reviewFile').modal('show');
	});
})()<|endoftext|>


<commit_before>var fs = require('fs');

function TumblrClient(credentials) {
  this.credentials = credentials || {};
}

var request;

module.exports = {

  Client: TumblrClient,

  createClient: function (credentials) {
    return new TumblrClient(credentials);
  },

  request: function(r) {
    request = r;
  }

};

var baseURL = 'http://api.tumblr.com/v2';

var calls = {

  postCreation: function (type, requireOptions, acceptsData) {
    return function (blogName, options, callback) {
      requireValidation(options, requireOptions);
      options.type = type;
      if (!acceptsData) {
        delete options.data;
      }
      this._post(blogPath(blogName, '/post'), options, callback);
    };
  },

  getWithOptions: function (path) {
    return function (options, callback) {
      if (isFunction(options)) { callback = options; options = {}; }
      this._get(path, options, callback);
    };
  },

  blogList: function (path) {
    return function (blogName, options, callback) {
      if (isFunction(options)) { callback = options; options = {}; }
      this._get(blogPath(blogName, path), options, callback);
    }
  }

};

TumblrClient.prototype = {

  // Tagged

  tagged: function (tag, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }

    options = options || {};
    options.tag = tag;

    this._get('/tagged', options, callback, true);
  },

  // Blogs

  blogInfo: function (blogName, callback) {
    this._get(blogPath(blogName, '/info'), {}, callback, true);
  },

  avatar: function (blogName, size, callback) {
    if (isFunction(size)) { callback = size; size = null; }
    var path = size ? '/avatar/' + size : '/avatar';
    this._get(blogPath(blogName, path), {}, callback, true);
  },

  blogLikes: function (blogName, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get(blogPath(blogName, '/likes'), options, callback, true);
  },

  followers: function (blogName, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get(blogPath(blogName, '/followers'), options, callback);
  },

  posts: function (blogName, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    options = options || {};
    var path = options.type ? '/posts/' + options.type : '/posts';
    this._get(blogPath(blogName, path), options, callback, true);
  },

  queue:       calls.blogList('/posts/queue'),
  drafts:      calls.blogList('/posts/draft'),
  submissions: calls.blogList('/posts/submission'),

  // Posts

  edit: function (blogName, options, callback) {
    this._post(blogPath(blogName, '/post/edit'), options, callback);
  },

  reblog: function (blogName, options, callback) {
    this._post(blogPath(blogName, '/post/reblog'), options, callback);
  },

  deletePost: function (blogName, id, callback) {
    this._post(blogPath(blogName, '/post/delete'), {id: id}, callback);
  },

  photo: calls.postCreation('photo', ['data', 'source'],       true),
  audio: calls.postCreation('audio', ['data', 'external_url'], true),
  video: calls.postCreation('video', ['data', 'embed'],        true),
  quote: calls.postCreation('quote', ['quote'],                false),
  text:  calls.postCreation('text',  ['body'],                 false),
  link:  calls.postCreation('link',  ['url'],                  false),
  chat:  calls.postCreation('chat',  ['conversation'],         false),

  // User

  userInfo: function (callback) {
    this._get('/user/info', {}, callback);
  },

  likes: function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/user/likes', options, callback, true);
  },

  follow: function (url, callback) {
    this._post('/user/follow', {url: url}, callback);
  },

  unfollow: function (url, callback) {
    this._post('/user/unfollow', {url: url}, callback);
  },

  like: function (id, reblogKey, callback) {
    this._post('/user/like', {id: id, reblog_key: reblogKey}, callback);
  },

  unlike: function (id, reblogKey, callback) {
    this._post('/user/unlike', {id: id, reblog_key: reblogKey}, callback);
  },

  dashboard: calls.getWithOptions('/user/dashboard'),
  following: calls.getWithOptions('/user/following'),

  // Helpers

  _get: function (path, params, callback, addApiKey) {

    params = params || {};
    if (addApiKey) {
      params.api_key = this.credentials.consumer_key;
    }

    request.get({
      url: baseURL + path,
      json: true,
      qs: params,
      oauth: this.credentials,
      followRedirect: false
    }, requestCallback(callback));

  },

  _post: function (path, params, callback) {

    var data = params.data;
    delete params.data;

    // Sign without multipart data
    var r = request.post(baseURL + path, function (err, response, body) {
      body = JSON.parse(body);
      requestCallback(callback)(err, response, body);
    });

    // Sign it with the non-data parameters
    r.form(params);
    r.oauth(this.credentials);

    // Clear the side effects from form(param)
    delete r.headers['content-type'];
    delete r.body;

    // And then add the full body
    var form = r.form();
    for (var key in params) {
      form.append(key, params[key]);
    }
    if (data) {
      form.append('data', fs.createReadStream(data));
    }

    // Add the form header back
    var headers = form.getHeaders();
    for (var key in headers) {
      r.headers[key] = headers[key];
    }

  }

};

var requireValidation = function (options, choices) {
  var count = 0;
  for (var i = 0; i < choices.length; i++) {
    if (options[choices[i]]) {
      count += 1;
    }
  }
  if (choices.length === 1) {
    if (count === 0) {
      throw new Error('Missing required field: "' + choices[0] + '"');
    }
  } else if (choices.length > 1) {
    if (count === 0) {
      throw new Error('Missing one of: ' + choices.join(','));
    }
    if (count > 1) {
      throw new Error('Can only use one of: ' + choices.join(','));
    }
  }
};

function blogPath(blogName, path) {
  var bn = blogName.indexOf('.') !== -1 ? blogName : blogName + '.tumblr.com';
  return '/blog/' + bn + path;
}

function requestCallback(callback) {
  if (!callback) return;
  return function (err, response, body) {
    if (err) return callback(err);
    if (response.statusCode >= 400) {
      var err = body.meta ? body.meta.msg : body.error;
      return callback(new Error('API error: ' + response.statusCode + ' ' + err));
    }
    return callback(null, body.response);
  };
}

function isFunction(value) {
  return Object.prototype.toString.call(value) == '[object Function]';
}
<commit_msg>Fix for userLikes<commit_after>var fs = require('fs');

function TumblrClient(credentials) {
  this.credentials = credentials || {};
}

var request;

module.exports = {

  Client: TumblrClient,

  createClient: function (credentials) {
    return new TumblrClient(credentials);
  },

  request: function(r) {
    request = r;
  }

};

var baseURL = 'http://api.tumblr.com/v2';

var calls = {

  postCreation: function (type, requireOptions, acceptsData) {
    return function (blogName, options, callback) {
      requireValidation(options, requireOptions);
      options.type = type;
      if (!acceptsData) {
        delete options.data;
      }
      this._post(blogPath(blogName, '/post'), options, callback);
    };
  },

  getWithOptions: function (path) {
    return function (options, callback) {
      if (isFunction(options)) { callback = options; options = {}; }
      this._get(path, options, callback);
    };
  },

  blogList: function (path) {
    return function (blogName, options, callback) {
      if (isFunction(options)) { callback = options; options = {}; }
      this._get(blogPath(blogName, path), options, callback);
    }
  }

};

TumblrClient.prototype = {

  // Tagged

  tagged: function (tag, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }

    options = options || {};
    options.tag = tag;

    this._get('/tagged', options, callback, true);
  },

  // Blogs

  blogInfo: function (blogName, callback) {
    this._get(blogPath(blogName, '/info'), {}, callback, true);
  },

  avatar: function (blogName, size, callback) {
    if (isFunction(size)) { callback = size; size = null; }
    var path = size ? '/avatar/' + size : '/avatar';
    this._get(blogPath(blogName, path), {}, callback, true);
  },

  blogLikes: function (blogName, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get(blogPath(blogName, '/likes'), options, callback, true);
  },

  followers: function (blogName, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get(blogPath(blogName, '/followers'), options, callback);
  },

  posts: function (blogName, options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    options = options || {};
    var path = options.type ? '/posts/' + options.type : '/posts';
    this._get(blogPath(blogName, path), options, callback, true);
  },

  queue:       calls.blogList('/posts/queue'),
  drafts:      calls.blogList('/posts/draft'),
  submissions: calls.blogList('/posts/submission'),

  // Posts

  edit: function (blogName, options, callback) {
    this._post(blogPath(blogName, '/post/edit'), options, callback);
  },

  reblog: function (blogName, options, callback) {
    this._post(blogPath(blogName, '/post/reblog'), options, callback);
  },

  deletePost: function (blogName, id, callback) {
    this._post(blogPath(blogName, '/post/delete'), {id: id}, callback);
  },

  photo: calls.postCreation('photo', ['data', 'source'],       true),
  audio: calls.postCreation('audio', ['data', 'external_url'], true),
  video: calls.postCreation('video', ['data', 'embed'],        true),
  quote: calls.postCreation('quote', ['quote'],                false),
  text:  calls.postCreation('text',  ['body'],                 false),
  link:  calls.postCreation('link',  ['url'],                  false),
  chat:  calls.postCreation('chat',  ['conversation'],         false),

  // User

  userInfo: function (callback) {
    this._get('/user/info', {}, callback);
  },

  likes: function (options, callback) {
    if (isFunction(options)) { callback = options; options = {}; }
    this._get('/user/likes', options, callback);
  },

  follow: function (url, callback) {
    this._post('/user/follow', {url: url}, callback);
  },

  unfollow: function (url, callback) {
    this._post('/user/unfollow', {url: url}, callback);
  },

  like: function (id, reblogKey, callback) {
    this._post('/user/like', {id: id, reblog_key: reblogKey}, callback);
  },

  unlike: function (id, reblogKey, callback) {
    this._post('/user/unlike', {id: id, reblog_key: reblogKey}, callback);
  },

  dashboard: calls.getWithOptions('/user/dashboard'),
  following: calls.getWithOptions('/user/following'),

  // Helpers

  _get: function (path, params, callback, addApiKey) {

    params = params || {};
    if (addApiKey) {
      params.api_key = this.credentials.consumer_key;
    }

    request.get({
      url: baseURL + path,
      json: true,
      qs: params,
      oauth: this.credentials,
      followRedirect: false
    }, requestCallback(callback));

  },

  _post: function (path, params, callback) {

    var data = params.data;
    delete params.data;

    // Sign without multipart data
    var r = request.post(baseURL + path, function (err, response, body) {
      body = JSON.parse(body);
      requestCallback(callback)(err, response, body);
    });

    // Sign it with the non-data parameters
    r.form(params);
    r.oauth(this.credentials);

    // Clear the side effects from form(param)
    delete r.headers['content-type'];
    delete r.body;

    // And then add the full body
    var form = r.form();
    for (var key in params) {
      form.append(key, params[key]);
    }
    if (data) {
      form.append('data', fs.createReadStream(data));
    }

    // Add the form header back
    var headers = form.getHeaders();
    for (var key in headers) {
      r.headers[key] = headers[key];
    }

  }

};

var requireValidation = function (options, choices) {
  var count = 0;
  for (var i = 0; i < choices.length; i++) {
    if (options[choices[i]]) {
      count += 1;
    }
  }
  if (choices.length === 1) {
    if (count === 0) {
      throw new Error('Missing required field: "' + choices[0] + '"');
    }
  } else if (choices.length > 1) {
    if (count === 0) {
      throw new Error('Missing one of: ' + choices.join(','));
    }
    if (count > 1) {
      throw new Error('Can only use one of: ' + choices.join(','));
    }
  }
};

function blogPath(blogName, path) {
  var bn = blogName.indexOf('.') !== -1 ? blogName : blogName + '.tumblr.com';
  return '/blog/' + bn + path;
}

function requestCallback(callback) {
  if (!callback) return;
  return function (err, response, body) {
    if (err) return callback(err);
    if (response.statusCode >= 400) {
      var err = body.meta ? body.meta.msg : body.error;
      return callback(new Error('API error: ' + response.statusCode + ' ' + err));
    }
    return callback(null, body.response);
  };
}

function isFunction(value) {
  return Object.prototype.toString.call(value) == '[object Function]';
}
<|endoftext|>


<commit_before>/*
    Copyright 2010 Emilis Dambauskas

    This file is part of PolicyFeed module.

    PolicyFeed is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PolicyFeed 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with PolicyFeed.  If not, see <http://www.gnu.org/licenses/>.
*/

var update_url = "http://localhost:8081/solr/update";
var search_url = 'http://localhost:8081/solr/select/?start=0&rows=100&sort=published+desc&fl=id,published,type,org,organization,title&wt=json&q=';

var httpclient = require("ringo/httpclient");
var jstorage = require("ctl/JsonStorage");

/**
 *
 */
var prepareDate = function(str) {
    if (!str.match(/^\d\d\d\d-\d\d-\d\d.\d\d:\d\d:\d\d/))
        throw Error("Unsupported date format: " + str);

    var arr = str.replace(/[-T:. Z]/g, "-").split("-");
    arr[1] = parseInt(arr[1], 10) - 1;
    var timestamp = Date.apply(undefined, arr);

    return new Date(timestamp).toISOString();
}

/**
 *
 */
var stripTags = function(str) {
    return str.replace(/<[^>]*>/g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/&\w+;/g, " ").trim();
}

/**
 *
 */
exports.itemToXml = function(item) {

    var text = item.text ? item.text : item.html;

    return '<doc>'
        + '<field name="id">' + item._id + '</field>'
        + '<field name="published">' + prepareDate(item.published) + '</field>'
        + '<field name="type">' + item.type + '</field>'
        + '<field name="org">' + item.org + '</field>'
        + '<field name="organization">' + item.organization + '</field>'
        + '<field name="title">' + stripTags(item.title) + '</field>'
        + '<field name="html">' + stripTags(text) + '</field>'
        + '</doc>';
}

/**
 *
 */
exports.indexItem = function(item) {
    print("SolrClient.indexItem", item._id);
    try {
        var req = {
            method: "POST",
            url: update_url,
            contentType: "text/xml; charset=utf-8",
            data: '<add>' + this.itemToXml(item) + "</add>",
            error: function(e) { print(e, e.stack); throw e; }
            };
    } catch (e) {
        throw Error("Failed to create request for item " + item._id + ". Error: " + e.message);
    }

    return httpclient.request(req);
}

/**
 *
 */
exports.removeItem = function(id) {
    var req = {
        method: "POST",
        url: update_url,
        contentType: "text/xml; charset=utf-8",
        data: '<delete><id>' + id + '</id></delete>'
    };

    return httpclient.request(req);
}

/**
 *
 */
exports.reindex = function(path) {
    if (path === undefined)
        path = "/docs";

    var gen = jstorage.iterate(path);

    for each (var doc in gen) {
        try {
            var e = this.indexItem(doc);
            if (e.content != '<result status="0"></result>')
                print(doc._id, e.content);
        } catch (e) {
            print(e.message);
        }
    }
}

/**
 *
 */
exports.onItemChange = function(action, _id, item) {
    print("SolrClient.onItemChange", action, _id);
    if (_id.indexOf("/docs/") > -1) {
        try {
            switch (action) {
                case "after-write":
                    return exports.indexItem(item);
                break;
                case "after-remove":
                    return exports.removeItem(_id);
                break;
            }
        } catch(e) {
            print(e, e.stack);
        }
    }
}

/**
 *
 */
exports.search = function(query, options) {
    query = encodeURIComponent(query);

    options = options || {};
    var {highlight, fields, limit} = options;

    var url = search_url;
    if (fields && fields.length)
        var url = url.replace(/fl=[^&]+/, "fl=" + fields.join(","));
    if (limit)
        var url = url.replace(/rows=[^&]+/, "rows=" + limit);
    if (highlight)
        url = url.replace("&q=", "&hl=true&hl.fl=html&q=");;

    var res = httpclient.get(url + query);
    if (res.status === 200)
        return JSON.parse(res.content);
}

function getYmd(str) {
    var [year, month, day] = str.split("-");

    year = parseInt(year, 10);
    month = month ? (parseInt(month, 10) - 1) : 0;
    day = day ? parseInt(day, 10) : 1;

    return [year, month, day];
}

/**
 *
 */
exports.searchByDateRange = function(from, to, options) {
    from = new Date(from);
    to = new Date(to);

    return this.search( "published:[" + from.toISOString() + " TO " + to.toISOString() + "]" );
}

/**
 *
 */
exports.searchByDay = function(day) {
    var [year, month, day] = getYmd(day);
    var from = new Date(year, month, day, 0, 0, 0, 0);
    var to = new Date(year, month, day + 1, 0, 0, 0, -1);

    return this.searchByDateRange(from, to);
}

/**
 *
 */
exports.searchByMonth = function(month) {
    var [year, month, day] = getYmd(day);
    var from = new Date(year, month, day, 0, 0, 0, 0);
    var to = new Date(year, month + 1, day, 0, 0, 0, -1);

    return this.searchByDateRange(from, to);
}

/**
 *
 */
exports.searchByYear = function(year) {
    var [year, month, day] = getYmd(day);
    var from = new Date(year, month, day, 0, 0, 0, 0);
    var to = new Date(year + 1, month, day, 0, 0, 0, -1);

    return this.searchByDateRange(from, to);
}

/**
 *
 */
exports.getLatestDocs = function (options) {
    return this.search("*:*", options).response;
}
<commit_msg>Fixed a hard to catch error in PolicyFeed/SolrClient prepareDate(): unable to set Date month to february on 29th, 30th and 31st of the month.<commit_after>/*
    Copyright 2010 Emilis Dambauskas

    This file is part of PolicyFeed module.

    PolicyFeed is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PolicyFeed 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with PolicyFeed.  If not, see <http://www.gnu.org/licenses/>.
*/

var update_url = "http://localhost:8081/solr/update";
var search_url = 'http://localhost:8081/solr/select/?start=0&rows=100&sort=published+desc&fl=id,published,type,org,organization,title&wt=json&q=';

var httpclient = require("ringo/httpclient");
var jstorage = require("ctl/JsonStorage");

/**
 *
 */
var prepareDate = function(str) {
    if (!str.match(/^\d\d\d\d-\d\d-\d\d.\d\d:\d\d:\d\d/))
        throw Error("Unsupported date format: " + str);

    // Turn string into date parts array:
    str = str.replace(/[-T:Z. ]/g, "-").split("-").map(function(item) { return parseInt(item, 10); });

    var d = new Date();
    d.setFullYear(str[0]);
    d.setDate(str[2]); // Date before month! Or you'll get march instead of february every 30th and 31th of the month.
    d.setMonth(str[1] - 1);
    d.setHours(str[3]);
    d.setMinutes(str[4]);
    d.setSeconds(str[5]);
    return d.toISOString();
}

/**
 *
 */
var stripTags = function(str) {
    return str.replace(/<[^>]*>/g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/&\w+;/g, " ").trim();
}

/**
 *
 */
exports.itemToXml = function(item) {

    var text = item.text ? item.text : item.html;

    return '<doc>'
        + '<field name="id">' + item._id + '</field>'
        + '<field name="published">' + prepareDate(item.published) + '</field>'
        + '<field name="type">' + item.type + '</field>'
        + '<field name="org">' + item.org + '</field>'
        + '<field name="organization">' + item.organization + '</field>'
        + '<field name="title">' + stripTags(item.title) + '</field>'
        + '<field name="html">' + stripTags(text) + '</field>'
        + '</doc>';
}

/**
 *
 */
exports.indexItem = function(item) {
    print("SolrClient.indexItem", item._id);
    try {
        var req = {
            method: "POST",
            url: update_url,
            contentType: "text/xml; charset=utf-8",
            data: '<add>' + this.itemToXml(item) + "</add>",
            error: function(e) { print(e, e.stack); throw e; }
            };
    } catch (e) {
        throw Error("Failed to create request for item " + item._id + ". Error: " + e.message);
    }

    return httpclient.request(req);
}

/**
 *
 */
exports.removeItem = function(id) {
    var req = {
        method: "POST",
        url: update_url,
        contentType: "text/xml; charset=utf-8",
        data: '<delete><id>' + id + '</id></delete>'
    };

    return httpclient.request(req);
}

/**
 *
 */
exports.reindex = function(path) {
    if (path === undefined)
        path = "/docs";

    var gen = jstorage.iterate(path);

    for each (var doc in gen) {
        try {
            var e = this.indexItem(doc);
            if (e.content != '<result status="0"></result>')
                print(doc._id, e.content);
        } catch (e) {
            print(e.message);
        }
    }
}

/**
 *
 */
exports.onItemChange = function(action, _id, item) {
    print("SolrClient.onItemChange", action, _id);
    if (_id.indexOf("/docs/") > -1) {
        try {
            switch (action) {
                case "after-write":
                    return exports.indexItem(item);
                break;
                case "after-remove":
                    return exports.removeItem(_id);
                break;
            }
        } catch(e) {
            print(e, e.stack);
        }
    }
}

/**
 *
 */
exports.search = function(query, options) {
    query = encodeURIComponent(query);

    options = options || {};
    var {highlight, fields, limit} = options;

    var url = search_url;
    if (fields && fields.length)
        var url = url.replace(/fl=[^&]+/, "fl=" + fields.join(","));
    if (limit)
        var url = url.replace(/rows=[^&]+/, "rows=" + limit);
    if (highlight)
        url = url.replace("&q=", "&hl=true&hl.fl=html&q=");;

    var res = httpclient.get(url + query);
    if (res.status === 200)
        return JSON.parse(res.content);
}

function getYmd(str) {
    var [year, month, day] = str.split("-");

    year = parseInt(year, 10);
    month = month ? (parseInt(month, 10) - 1) : 0;
    day = day ? parseInt(day, 10) : 1;

    return [year, month, day];
}

/**
 *
 */
exports.searchByDateRange = function(from, to, options) {
    from = new Date(from);
    to = new Date(to);

    return this.search( "published:[" + from.toISOString() + " TO " + to.toISOString() + "]" );
}

/**
 *
 */
exports.searchByDay = function(day) {
    var [year, month, day] = getYmd(day);
    var from = new Date(year, month, day, 0, 0, 0, 0);
    var to = new Date(year, month, day + 1, 0, 0, 0, -1);

    return this.searchByDateRange(from, to);
}

/**
 *
 */
exports.searchByMonth = function(month) {
    var [year, month, day] = getYmd(day);
    var from = new Date(year, month, day, 0, 0, 0, 0);
    var to = new Date(year, month + 1, day, 0, 0, 0, -1);

    return this.searchByDateRange(from, to);
}

/**
 *
 */
exports.searchByYear = function(year) {
    var [year, month, day] = getYmd(day);
    var from = new Date(year, month, day, 0, 0, 0, 0);
    var to = new Date(year + 1, month, day, 0, 0, 0, -1);

    return this.searchByDateRange(from, to);
}

/**
 *
 */
exports.getLatestDocs = function (options) {
    return this.search("*:*", options).response;
}
<|endoftext|>


<commit_before>angular.module('SecompTodo')

	.factory('Tarefas', function () {

		var tarefas = [];

		return {
			getTarefas: function () {
				return tarefas;
			},

			criarTarefa: function (tarefa) {
				tarefas.push(tarefa);
			},

			concluirTarefa: function (tarefa) {
				tarefa.concluida = true;
			}
		};
	});
<commit_msg>Salvando no localstorage a cada mudança na lista de tarefas<commit_after>angular.module('SecompTodo')

	.factory('Tarefas', function () {

		var tarefas = [];
		var TAREFAS_KEY = 'TAREFAS_KEY';

		function salvarLista() {
			localStorage.setItem(TAREFAS_KEY, JSON.stringify(tarefas));
		};

		var listaSalva = localStorage.getItem(TAREFAS_KEY);
		if (listaSalva) {
			try {
				tarefas = JSON.parse(listaSalva);
			} catch (erro) {
				tarefas = [];
			}
		}

		return {
			getTarefas: function () {
				return tarefas;
			},

			criarTarefa: function (tarefa) {
				tarefas.push(tarefa);
				salvarLista();
			},

			concluirTarefa: function (tarefa) {
				tarefa.concluida = true;
				salvarLista();
			}
		};
	});
<|endoftext|>


<commit_before>'use strict';

var React = (window ? window.React : null) || require('react');
var {getSelection, setSelection} = require('./SelectionUtils');
var formatValidator = require('./formatValidator');

var DEFAULT_TRANSLATIONS = {
  '9': /\d/,
  'a': /[A-Za-z]/,
  '*': /[A-Za-z0-9]/
};

var MaskedField = React.createClass({
  propTypes: {
    mask: React.PropTypes.string,
    format: formatValidator,
    translations: React.PropTypes.object,
    value: React.PropTypes.string,
    onChange: React.PropTypes.func,
    onKeyDown: React.PropTypes.func,
    onComplete: React.PropTypes.func,
    onFocus: React.PropTypes.func,
    valueLink: React.PropTypes.object
  },
  getDefaultProps: function() {
    return {format: '_'};
  },
  getInitialState: function() {
    if (this.props.mask == null) {
      return null;
    }

    this._buffer = [];
    for (var idx = 0; idx < this.props.mask.length; ++idx) {
      if (this._getPattern(idx)) {
        if (this._firstNonMaskIdx == null) {
          this._firstNonMaskIdx = idx;
        }
        this._buffer.push(this._getFormatChar(idx));
      }
      else {
        this._buffer.push(this.props.mask[idx]);
      }
    }

    this._cursorPos = this._firstNonMaskIdx;
    return {
      // TODO: Any way we can do this in one pass?
      value: this._maskedValue(this._getPropsValue() || '')
    };
  },
  componentDidUpdate: function() {
    if (this._cursorPos != null) {
      this._setSelection(this._cursorPos);
    }
  },
  componentDidMount: function() {
    var propsValue = this._getPropsValue();
    if (this.props.mask != null && propsValue != null && this.state.value !== propsValue) {
      this._callOnChange(this.state.value);
    }
  },
  render: function() {
    var props;
    if (this.props.mask != null) {
      props = {
        onChange: this._handleChange,
        onKeyDown: this._handleKeyDown,
        onFocus: this._handleFocus,
        value: this.state.value,
        valueLink: null
      };
    }
    else {
      props = {};
    }

    return <input {...this.props} {...props} />;
  },
  _getSelection: function() {
    if (this.isMounted()) {
      return getSelection(this.getDOMNode());
    }
    else {
      return {start: 0, end: 0};
    }
  },
  _setSelection: function(start, end) {
    if (end == null) {
      end = start;
    }
    setSelection(this.getDOMNode(), start, end);
  },
  _getPropsValue: function() {
    if (this.props.valueLink != null) {
      return this.props.valueLink.value;
    }
    else {
      return this.props.value;
    }
  },
  _getPattern: function(idx) {
    var maskChar = this.props.mask[idx];
    var pattern = this.props.translations ? this.props.translations[maskChar] : null;

    return pattern || DEFAULT_TRANSLATIONS[maskChar];
  },
  _getFormatChar: function(idx) {
    idx = idx < this.props.format.length ? idx : 0;
    return this.props.format[idx];
  },
  _resetBuffer: function(start, end) {
    for (var i = start; i < end; ++i) {
      if (this._getPattern(i)) {
        this._buffer[i] = this._getFormatChar(i);
      }
    }
  },
  _nextNonMaskIdx: function(idx) {
    for (var next = idx + 1; next < this.props.mask.length; ++next) {
      if (this._getPattern(next)) {
        break;
      }
    }

    return next;
  },
  _prevNonMaskIdx: function(idx) {
    for (var prev = idx - 1; prev >= 0; --prev) {
      if (this._getPattern(prev)) {
        break;
      }
    }

    return prev;
  },
  _callOnChange: function(value) {
    if (this.props.valueLink != null) {
      this.props.valueLink.requestChange(value);
    }
    else if (this.props.onChange) {
      this.props.onChange({target: {value: value}});
    }
  },
  _callOnComplete: function(value) {
    if (this.props.onComplete) {
      for (var i = 0; i < this.props.mask.length; ++i) {
        if (this._getPattern(i) && this._buffer[i] === this._getFormatChar(i)) {
          return;
        }
      }

      this.props.onComplete(value);
    }
  },
  _setValue: function(value) {
    if (value !== this.state.value) {
      this._callOnChange(value);
    }
    this.setState({value});
  },
  _handleFocus: function(e) {
    setTimeout(() => {
      this._setSelection(this._cursorPos);
    }, 0);

    if (this.props.onFocus) {
      this.props.onFocus(e);
    }
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Backspace' || e.key === 'Delete') {
      var {start, end} = this._getSelection();

      if (start === end) {
        start = e.key === 'Delete' ? this._nextNonMaskIdx(start - 1) : this._prevNonMaskIdx(start);
        end = this._nextNonMaskIdx(start);
      }

      var value;
      var pattern = this._getPattern(start);
      if (pattern && pattern.test(this._buffer[end])) {
        value = this._maskedValue(this.state.value.substring(end), start);
      }
      else {
        this._resetBuffer(start, end);
        value = this._buffer.join('');
      }

      this._setValue(value);
      this._cursorPos = Math.max(start, this._firstNonMaskIdx);

      e.preventDefault();
    }

    if (this.props.onKeyDown) {
      this.props.onKeyDown(e);
    }
  },
  _handleChange: function(e) {
    var value = this._maskedValue(e.target.value);
    this._setValue(value);
    this._callOnComplete(value);
  },
  _maskedValue: function(value, start) {
    start = start || 0;

    var originalCursorPos = this._cursorPos = this._getSelection().start;
    for (var bufferIdx = start, valueIdx = 0; bufferIdx < this.props.mask.length; ++bufferIdx)  {
      var pattern = this._getPattern(bufferIdx);
      if (pattern) {
        this._buffer[bufferIdx] = this._getFormatChar(bufferIdx);
        while (valueIdx < value.length) {
          var c = value[valueIdx++];
          if (pattern.test(c)) {
            this._buffer[bufferIdx] = c;
            break;
          }
          else if (this._cursorPos > bufferIdx) {
            this._cursorPos--;
          }
        }

        if (valueIdx >= value.length) {
          this._resetBuffer(bufferIdx + 1, this.props.mask.length);
          break;
        }
      }
      else {
        if (valueIdx <= originalCursorPos) {
          this._cursorPos++;
        }
        if (this._buffer[bufferIdx] === value[valueIdx]) {
          valueIdx++;
        }
      }
    }

    return this._buffer.join('');
  }
});

module.exports = MaskedField;
<commit_msg>Add license header to src<commit_after>/**
* Copyright (c) 2015 ZenPayroll
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var React = (window ? window.React : null) || require('react');
var {getSelection, setSelection} = require('./SelectionUtils');
var formatValidator = require('./formatValidator');

var DEFAULT_TRANSLATIONS = {
  '9': /\d/,
  'a': /[A-Za-z]/,
  '*': /[A-Za-z0-9]/
};

var MaskedField = React.createClass({
  propTypes: {
    mask: React.PropTypes.string,
    format: formatValidator,
    translations: React.PropTypes.object,
    value: React.PropTypes.string,
    onChange: React.PropTypes.func,
    onKeyDown: React.PropTypes.func,
    onComplete: React.PropTypes.func,
    onFocus: React.PropTypes.func,
    valueLink: React.PropTypes.object
  },
  getDefaultProps: function() {
    return {format: '_'};
  },
  getInitialState: function() {
    if (this.props.mask == null) {
      return null;
    }

    this._buffer = [];
    for (var idx = 0; idx < this.props.mask.length; ++idx) {
      if (this._getPattern(idx)) {
        if (this._firstNonMaskIdx == null) {
          this._firstNonMaskIdx = idx;
        }
        this._buffer.push(this._getFormatChar(idx));
      }
      else {
        this._buffer.push(this.props.mask[idx]);
      }
    }

    this._cursorPos = this._firstNonMaskIdx;
    return {
      // TODO: Any way we can do this in one pass?
      value: this._maskedValue(this._getPropsValue() || '')
    };
  },
  componentDidUpdate: function() {
    if (this._cursorPos != null) {
      this._setSelection(this._cursorPos);
    }
  },
  componentDidMount: function() {
    var propsValue = this._getPropsValue();
    if (this.props.mask != null && propsValue != null && this.state.value !== propsValue) {
      this._callOnChange(this.state.value);
    }
  },
  render: function() {
    var props;
    if (this.props.mask != null) {
      props = {
        onChange: this._handleChange,
        onKeyDown: this._handleKeyDown,
        onFocus: this._handleFocus,
        value: this.state.value,
        valueLink: null
      };
    }
    else {
      props = {};
    }

    return <input {...this.props} {...props} />;
  },
  _getSelection: function() {
    if (this.isMounted()) {
      return getSelection(this.getDOMNode());
    }
    else {
      return {start: 0, end: 0};
    }
  },
  _setSelection: function(start, end) {
    if (end == null) {
      end = start;
    }
    setSelection(this.getDOMNode(), start, end);
  },
  _getPropsValue: function() {
    if (this.props.valueLink != null) {
      return this.props.valueLink.value;
    }
    else {
      return this.props.value;
    }
  },
  _getPattern: function(idx) {
    var maskChar = this.props.mask[idx];
    var pattern = this.props.translations ? this.props.translations[maskChar] : null;

    return pattern || DEFAULT_TRANSLATIONS[maskChar];
  },
  _getFormatChar: function(idx) {
    idx = idx < this.props.format.length ? idx : 0;
    return this.props.format[idx];
  },
  _resetBuffer: function(start, end) {
    for (var i = start; i < end; ++i) {
      if (this._getPattern(i)) {
        this._buffer[i] = this._getFormatChar(i);
      }
    }
  },
  _nextNonMaskIdx: function(idx) {
    for (var next = idx + 1; next < this.props.mask.length; ++next) {
      if (this._getPattern(next)) {
        break;
      }
    }

    return next;
  },
  _prevNonMaskIdx: function(idx) {
    for (var prev = idx - 1; prev >= 0; --prev) {
      if (this._getPattern(prev)) {
        break;
      }
    }

    return prev;
  },
  _callOnChange: function(value) {
    if (this.props.valueLink != null) {
      this.props.valueLink.requestChange(value);
    }
    else if (this.props.onChange) {
      this.props.onChange({target: {value: value}});
    }
  },
  _callOnComplete: function(value) {
    if (this.props.onComplete) {
      for (var i = 0; i < this.props.mask.length; ++i) {
        if (this._getPattern(i) && this._buffer[i] === this._getFormatChar(i)) {
          return;
        }
      }

      this.props.onComplete(value);
    }
  },
  _setValue: function(value) {
    if (value !== this.state.value) {
      this._callOnChange(value);
    }
    this.setState({value});
  },
  _handleFocus: function(e) {
    setTimeout(() => {
      this._setSelection(this._cursorPos);
    }, 0);

    if (this.props.onFocus) {
      this.props.onFocus(e);
    }
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Backspace' || e.key === 'Delete') {
      var {start, end} = this._getSelection();

      if (start === end) {
        start = e.key === 'Delete' ? this._nextNonMaskIdx(start - 1) : this._prevNonMaskIdx(start);
        end = this._nextNonMaskIdx(start);
      }

      var value;
      var pattern = this._getPattern(start);
      if (pattern && pattern.test(this._buffer[end])) {
        value = this._maskedValue(this.state.value.substring(end), start);
      }
      else {
        this._resetBuffer(start, end);
        value = this._buffer.join('');
      }

      this._setValue(value);
      this._cursorPos = Math.max(start, this._firstNonMaskIdx);

      e.preventDefault();
    }

    if (this.props.onKeyDown) {
      this.props.onKeyDown(e);
    }
  },
  _handleChange: function(e) {
    var value = this._maskedValue(e.target.value);
    this._setValue(value);
    this._callOnComplete(value);
  },
  _maskedValue: function(value, start) {
    start = start || 0;

    var originalCursorPos = this._cursorPos = this._getSelection().start;
    for (var bufferIdx = start, valueIdx = 0; bufferIdx < this.props.mask.length; ++bufferIdx)  {
      var pattern = this._getPattern(bufferIdx);
      if (pattern) {
        this._buffer[bufferIdx] = this._getFormatChar(bufferIdx);
        while (valueIdx < value.length) {
          var c = value[valueIdx++];
          if (pattern.test(c)) {
            this._buffer[bufferIdx] = c;
            break;
          }
          else if (this._cursorPos > bufferIdx) {
            this._cursorPos--;
          }
        }

        if (valueIdx >= value.length) {
          this._resetBuffer(bufferIdx + 1, this.props.mask.length);
          break;
        }
      }
      else {
        if (valueIdx <= originalCursorPos) {
          this._cursorPos++;
        }
        if (this._buffer[bufferIdx] === value[valueIdx]) {
          valueIdx++;
        }
      }
    }

    return this._buffer.join('');
  }
});

module.exports = MaskedField;
<|endoftext|>


<commit_before>AWS.config.update({
    region: bucketRegion,
    credentials: new AWS.CognitoIdentityCredentials({
        IdentityPoolId: identityPoolId
    })
});

var s3 = new AWS.S3({
    apiVersion: '2006-03-01',
    params: {Bucket: bucketName}
});

var isFileTransfer = function(dt) {
    return (
        !$.trim($("#source").val()) &&
        (dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') !== -1 : dt.types.contains('Files')))
    );
};

$(function() {
    $('#highlighting').select2();
    $('#expiration').select2({minimumResultsForSearch: Infinity});

    $('form').bind('submit', function () {
        $(this).find(':input').prop('disabled', false);
    });

    $('#source').on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
        if (isFileTransfer(e.originalEvent.dataTransfer)) {
            e.preventDefault();
            e.stopPropagation();
        }
    }).on('dragenter dragover', function (e) {
        if (isFileTransfer(e.originalEvent.dataTransfer)) {
            $('.source-upload-overlay').fadeIn('fast');
            $('.source').blur().prop('readonly', true);
        }
    }).on('dragleave dragend', function (e) {
        if (isFileTransfer(e.originalEvent.dataTransfer)) {
            if (e.target !== e.relatedTarget) {
                $('.source-upload-overlay').fadeOut('fast');
                $('.source').prop('readonly', false);
            }
        }
    }).on('drop', function (e) {
        var dt = e.originalEvent.dataTransfer;

        if (!isFileTransfer(dt)) {
            return;
        }

        var file = dt.files[0];

        if (dt.files.length > 1 || (!file.type && file.size % 4096 === 0 && file.size <= 102400)) {
            $('.source-upload-overlay').fadeOut('fast');
            $('.source').prop('readonly', false);

            alert('파일을 1개만 올려주세요.');
            return;
        }

        $('#source')
            .prop('placeholder', '')
            .text('\u200b');

        $('#source-upload-overlay-status').html('업로드 준비 중...');
        $('.source-upload-overlay').css('pointer-events', 'auto');
        $('#highlighting')
            .val('auto').trigger('change.select2')
            .prop('disabled', true);

        $.ajax({
            url: '/x/k',
            method: 'POST',
            dataType: 'json'
        }).done(function(data) {
            var key = data.key;
            s3.upload({
                Key: key,
                Body: file,
                ContentDisposition: 'attachment; filename="' + file.name + '"'
            }, function (err) {
                if (err) {
                    alert('upload error');
                    console.log(err);
                } else {
                    $('.source-upload-overlay').addClass('source-upload-overlay-green');
                    $('.source-upload-overlay-icon').removeClass('fa-cloud-upload').addClass('fa-check');
                    $('#source-upload-overlay-status').html('업로드 완료!
하단 정보를 기입하고 만들기 버튼을 눌러주세요.');
                    $('#resource').val(key);
                }
            }).on('httpUploadProgress', function (progress) {
                var percentage = Math.round((progress.loaded / progress.total) * 100);
                var mbLoaded = (progress.loaded / 1000 / 1000).toFixed(2);
                var mbTotal = (progress.total / 1000 / 1000).toFixed(2);
                $('#source-upload-overlay-status').html('업로드 중...
(' + mbLoaded + ' / ' + mbTotal + ' MB, ' + percentage + '%)');
            });
        }).fail(function(xhr, err) {
            alert('generate key error');
            console.log(err);
        });
    });
});
<commit_msg>파일명 encodeURIComponent해서 보내도록 수정<commit_after>AWS.config.update({
    region: bucketRegion,
    credentials: new AWS.CognitoIdentityCredentials({
        IdentityPoolId: identityPoolId
    })
});

var s3 = new AWS.S3({
    apiVersion: '2006-03-01',
    params: {Bucket: bucketName}
});

var isFileTransfer = function(dt) {
    return (
        !$.trim($("#source").val()) &&
        (dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') !== -1 : dt.types.contains('Files')))
    );
};

$(function() {
    $('#highlighting').select2();
    $('#expiration').select2({minimumResultsForSearch: Infinity});

    $('form').bind('submit', function () {
        $(this).find(':input').prop('disabled', false);
    });

    $('#source').on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
        if (isFileTransfer(e.originalEvent.dataTransfer)) {
            e.preventDefault();
            e.stopPropagation();
        }
    }).on('dragenter dragover', function (e) {
        if (isFileTransfer(e.originalEvent.dataTransfer)) {
            $('.source-upload-overlay').fadeIn('fast');
            $('.source').blur().prop('readonly', true);
        }
    }).on('dragleave dragend', function (e) {
        if (isFileTransfer(e.originalEvent.dataTransfer)) {
            if (e.target !== e.relatedTarget) {
                $('.source-upload-overlay').fadeOut('fast');
                $('.source').prop('readonly', false);
            }
        }
    }).on('drop', function (e) {
        var dt = e.originalEvent.dataTransfer;

        if (!isFileTransfer(dt)) {
            return;
        }

        var file = dt.files[0];

        if (dt.files.length > 1 || (!file.type && file.size % 4096 === 0 && file.size <= 102400)) {
            $('.source-upload-overlay').fadeOut('fast');
            $('.source').prop('readonly', false);

            alert('파일을 1개만 올려주세요.');
            return;
        }

        $('#source')
            .prop('placeholder', '')
            .text('\u200b');

        $('#source-upload-overlay-status').html('업로드 준비 중...');
        $('.source-upload-overlay').css('pointer-events', 'auto');
        $('#highlighting')
            .val('auto').trigger('change.select2')
            .prop('disabled', true);

        $.ajax({
            url: '/x/k',
            method: 'POST',
            dataType: 'json'
        }).done(function(data) {
            var key = data.key;
            s3.upload({
                Key: key,
                Body: file,
                ContentDisposition: 'attachment; filename="' + encodeURIComponent(file.name) + '"'
            }, function (err) {
                if (err) {
                    alert('upload error');
                    console.log(err);
                } else {
                    $('.source-upload-overlay').addClass('source-upload-overlay-green');
                    $('.source-upload-overlay-icon').removeClass('fa-cloud-upload').addClass('fa-check');
                    $('#source-upload-overlay-status').html('업로드 완료!
하단 정보를 기입하고 만들기 버튼을 눌러주세요.');
                    $('#resource').val(key);
                }
            }).on('httpUploadProgress', function (progress) {
                var percentage = Math.round((progress.loaded / progress.total) * 100);
                var mbLoaded = (progress.loaded / 1000 / 1000).toFixed(2);
                var mbTotal = (progress.total / 1000 / 1000).toFixed(2);
                $('#source-upload-overlay-status').html('업로드 중...
(' + mbLoaded + ' / ' + mbTotal + ' MB, ' + percentage + '%)');
            });
        }).fail(function(xhr, err) {
            alert('generate key error');
            console.log(err);
        });
    });
});
<|endoftext|>