Plato on Github
Report Home
space/photos/_photos_list.js
Maintainability
58.44
Lines of code
2267
Difficulty
71.94
Estimated Errors
27.51
Function weight
By Complexity
By SLOC
/*global Y, window, document, YUI, initLytebox, myLytebox, Image */ /*jslint bitwise: true */ /** *
JavaScript for #photos-list Module
* ~/miiicasa/static/space/photos/_photos_list.js * * @author Hunter Wu * @module space * @submodule _photos_list */ YUI.add("space/photos/_photos_list", function (Y) { var _api, _currentPath, _currentCoverUrl, // holding current cover url for set cover overlay _currentStorage = null, _deviceInfo, // holding deviceInfo _deviceConnector, _titleEditable, _descEditable, _editable, _featureSupport, // holding flags those feature support or not, true is for support _fileList, // files in current folder _firstPhotoIndex = -1, // for genCover _genCoverRetry = 0, _genThumbIndex = 0, _genThumbList = [], // holding files to gen thumb _genThumbRetry = 0, _hasCover, _isAngelDevice, _isRegenerating = false, _lang = {}, // L10N language strings _mappings = {}, // Mappings for comment and share amount. _lightbox, _lightboxContentReady, _lightboxNode, _needReload = false, // if delete files from flash UI, need to reload page after flash closed _newFolderData = {}, _node, _photoList = [], // holding photo list instead of file list, for setCover use _photoIndex = -1, _rotateMenuOverlay, // holding rotate menu overlay _sideNode, // side node (cover, setting link, etc...) _uploadDescCompleteCallback = null, _uploader, _viewer, //=========================== // Shortcut //=========================== MIIICASA = window.MIIICASA || {}, PAGE, currentPath, isLan, isShare, isWanShare, util, Lang, UPLOAD_URL, UA, //=========================== // Constants //=========================== MODULE_ID = "#photos-list", CONST, DIRECTLY_RELOAD_NO = 0, DIRECTLY_RELOAD_YES = 1, ROTATE_MENU_OFFSET = 1, ROTATE_LEFT = 3, ROTATE_RIGHT = 1, LIMIT_POST_PHOTO = 100, CHANGE_COVER_BTN = ".change-cover-link", SLIDESHOW_BTN = ".slideshow-link", //=========================== // Private Events //=========================== _folderShareEnterHandler, _folderShareLeaveHandler, _createLinkHandler, _checkAllHandler, _commentClickHandler, _deleteButtonHandler, _downloadButtonHandler, _hideRotateMenuOverlayHandler, _itemSelectHandler, _submitFolderNameHandler, _regenClickHandler, _rotateButtonHandler, _rotateLeftHandler, _rotateRightHandler, _pickerButtonHandler, //=========================== // Private Methods //=========================== _blockUploadButtons, _checkIsShared, _doCreateDirectory, _doDeleteFiles, _doRotate, _doSetCover, _expandViewer, _fetchDesc, _getFileList, _getSubFolderURL, _getSharedComments, _handleSharedFolders, _initLightbox, _initLytebox, _initUI, _listStorages, _renameFolder, _renameTitle, _refreshPage, _redirectToNewFolder, _setCoverURL, _slideShow, _stickTaskRow, _syncCheckAllBox, _syncSelectedItem, _uploadDesc, _getFoundFolder, _updateFileLists, _updateSharedComments, _syncFileInfo, //=========================== // Public Methods //=========================== init, onviewload; //=========================== // Private Events //=========================== _folderShareEnterHandler = function (e) { e.currentTarget.previous().setStyle("display", "block"); }; _folderShareLeaveHandler = function (e) { e.currentTarget.previous().setStyle("display", "none"); }; _commentClickHandler = function (e) { _api.log("commentClickHandler(e) is executed."); e.preventDefault(); var node, queryString, href, params, segments, media; node = e.currentTarget; href = node.get("href"); queryString = href.split("?")[1]; segments = href.split("?")[0].split("/"); media = segments[segments.length - 2]; queryString = queryString + "&type=" + media; params = Y.QueryString.parse(queryString); if (Y.Lang.isUndefined(params.sort) || !params.sort) { params.sort = "aa"; } queryString = Y.QueryString.stringify(params); if (Y.Lang.isUndefined(params.viewer)) { return; } _expandViewer(queryString); }; /** * When user click create album click * @event _createLinkHandler * @private */ _createLinkHandler = function (e) { var storagesData = [{ name : PAGE.label, free_space : _currentStorage === null ? -1 : _currentStorage.free_space }]; _api.broadcast("show-create-folder", { storages : storagesData, callback : _doCreateDirectory }); e.preventDefault(); }; /** * When user click checkall box * @event _checkAllHandler * @private */ _checkAllHandler = function (e) { var isChecked = e.currentTarget.get("checked"); if (isChecked) { _node.all("span.miii-checkbox a").addClass("miii-checkbox-checked"); _node.all("div.storage input, #selectall-a, #selectall-b").set("checked", "checked"); _node.all("div.storage ul li .body").addClass("checked"); } else { _node.all("span.miii-checkbox a").removeClass("miii-checkbox-checked"); _node.all("div.storage input, #selectall-a, #selectall-b").set("checked", ""); _node.all("div.storage ul li .body").removeClass("checked"); } }; /** * When user click delete button * @event _deleteButtonHandler * @private */ _deleteButtonHandler = function (e) { var data = {}, hasShared = false, attr, okHandler, selectedNodes = _node.all("input[name=list-item]:checked"); if (selectedNodes._nodes.length === 0) { attr = { title : _lang.oops, content : _lang.noFileSelected }; _api.alert(attr); return; } // check share status Y.each(selectedNodes, function (node) { var fileInfo = node.get("id").split("-"); if (!Lang.isUndefined(_fileList[fileInfo[3]].shared) && _fileList[fileInfo[3]].shared === true) { hasShared = true; } }); data = { src_folderpath : currentPath, filelist : [], fullfilenames : [] }; okHandler = function (result) { if (!result) { return; } Y.each(selectedNodes, function (node) { var fileInfo = node.get("id").split("-"), filename = _fileList[fileInfo[3]].name; data.filelist.push("\"" + filename + "\""); data.fullfilenames.push("\"" + currentPath + "/" + filename + "\""); }); _api.broadcast("show-main-loading"); _doDeleteFiles(data, DIRECTLY_RELOAD_YES); }; attr = { title : _api.getTrans("confirm_delete_title", "Confirm delete?"), content : hasShared ? _api.getTrans("confirm_shared_delete", "One or more folders have been shared, are you sure to delete these selected files?") : _api.getTrans("confirm_delete", "Are you sure to delete these selected files?") }; _api.confirm(attr, okHandler); e.preventDefault(); }; /** * Hide rotate menu when user click, scroll and resize window. * @event _hideRotateMenuOverlayHandler * @private */ _hideRotateMenuOverlayHandler = function (e) { _api.log("_hideRotateMenuOverlayHandler()"); if (e.target.get("name") !== "rotate-button") { _rotateMenuOverlay.hide(); var rotateButtons = _node.all("span.rotate-button"); if (rotateButtons._nodes.length > 0) { rotateButtons.removeClass("miii-button-active"); } return; } }; /** * When user click download button * @event _downloadButtonHandler * @private */ _downloadButtonHandler = function (e) { _api.log("_downloadButtonHandler()"); var fileCnt = 0, filesArray = [], folderCnt = 0, selectedNodes = _node.all("input[name=list-item]:checked"), targetname = "", attr; if (!_featureSupport.download) { attr = { title : _lang.oops, content : _lang.featureNotSupported }; _api.alert(attr); return; } if (selectedNodes._nodes.length === 0) { attr = { title : _lang.oops, content : _lang.noFileSelected }; _api.alert(attr); return; } // downloadFiles Y.each(selectedNodes, function (node) { var fileInfo = node.get("id").split("-"), theFile = _fileList[fileInfo[3]]; filesArray.push('"' + theFile.name + '"'); if (theFile.type === CONST.FILE_TYPE_FILE) { fileCnt += 1; } else { folderCnt += 1; } targetname = theFile.name; }); // target filename if (fileCnt === 0 && folderCnt === 1) { targetname += ".zip"; } else if (fileCnt + folderCnt > 1) { targetname = 'miiiCasa_' + Y.DataType.Date.format(new Date(), {format: "%Y-%m-%d"}) + '.zip'; } _deviceConnector.downloadFilesByPost({ base_path : isWanShare ? PAGE.subpath : currentPath, targetname : targetname, filenames : "[" + filesArray.join(",") + "]" }); e.preventDefault(); }; /** * When user select an item by checkbox * @event _itemSelectHandler * @private */ _itemSelectHandler = function (e) { _syncSelectedItem(e.currentTarget); _syncCheckAllBox(e.currentTarget); }; _regenClickHandler = function (e) { _api.log("_regenClickHandler() is executed."); e.preventDefault(); var attr, okHandler; okHandler = function (result) { if (!result) { return; } _genThumbIndex = 0; _genThumbList = []; Y.each(_fileList, function (item, i) { if (item.type !== 1) { return; } if (!Y.Lang.isUndefined(item.thumb)) { item.thumb = 0; } if (!Y.Lang.isUndefined(item.thumb_l)) { item.thumb_l = 0; } _genThumbList.push(item); }); _node.addClass("regenerating"); MIIICASA.photosList.genCoverByUploader(0); _isRegenerating = true; }; attr = { title : _api.getTrans("confirm_regen_title", "Confirm Regeneratng All Thumbnails"), content : _api.getTrans("confirm_regen_msg", "Once you click 'OK', the system will start to regenerate all photo thumbnails for current album. Are you sure?") }; _api.confirm(attr, okHandler); }; /** * Submit folder name after editing. * * @event _submitFolderNameHandler * @private * @param e {Y.Event} The event instance */ _submitFolderNameHandler = function (e) { _api.log("_submitFolderNameHandler() is executed.", "info", MODULE_ID); var details, folderNode, storageIndex, data, isFound; details = e.details[0]; folderNode = details.target; storageIndex = folderNode.get("id").split("-")[1]; isFound = _getFoundFolder(details.value); if (details.value.toLowerCase() === _editable.get("activeValue").toLowerCase()) { _editable.set("errorMessage", _lang.same_foldername_error); e.preventDefault(); return; } if (isFound) { _editable.set("errorMessage", _lang.same_foldername_error); e.preventDefault(); } else { _renameFolder(details.value, _editable.get("activeValue"), folderNode); } }; /** * When user click rotate button * @event _rotateButtonHandler * @private */ _rotateButtonHandler = function (e) { _api.log("_rotateButtonHandler()"); var attr, buttonRegion, //the current button menuHeight, viewport, //user's viewport middleLine, //middle line of viewport showAbove, //determine show above or under the current button showX, showY, target; if (!_featureSupport.upload) { attr = { title: _lang.oops, content: _lang.featureNotSupported }; _api.alert(attr); return; } if (Lang.isUndefined(_rotateMenuOverlay)) { // init overlay _rotateMenuOverlay = new Y.Overlay({ boundingBox : "#rotate-menu", visible : true, zIndex : 1 }); _rotateMenuOverlay.render("body"); Y.one(document).on("click", _hideRotateMenuOverlayHandler); Y.one(window).on("resize", _hideRotateMenuOverlayHandler); Y.one(window).on("scroll", _hideRotateMenuOverlayHandler); Y.one("#rotate-menu .rotate-left").on("click", _rotateLeftHandler); Y.one("#rotate-menu .rotate-right").on("click", _rotateRightHandler); } target = e.target; buttonRegion = target.ancestor().get("region"); menuHeight = _rotateMenuOverlay.get("boundingBox").get("offsetHeight"); viewport = Y.DOM.viewportRegion(); middleLine = viewport.top + Math.floor(viewport.height / 2); showAbove = (buttonRegion.top > middleLine); showX = buttonRegion.left; showY = (showAbove ? buttonRegion.top : buttonRegion.bottom) + (showAbove ? -menuHeight - 2 : 0) + (showAbove ? -ROTATE_MENU_OFFSET : ROTATE_MENU_OFFSET); _rotateMenuOverlay.set("xy", [showX, showY]); _rotateMenuOverlay.show(); _node.all("span.rotate-button").removeClass("miii-button-active"); target.ancestor(".miii-button").addClass("miii-button-active"); e.preventDefault(); }; /** * When user click rotate left link * @event _rotateLeftHandler * @private */ _rotateLeftHandler = function (e) { _api.log("_rotateLeftHandler()"); _doRotate(e, ROTATE_LEFT); }; /** * When user click rotate right link * @event _rotateRightHandler * @private */ _rotateRightHandler = function (e) { _api.log("_rotateRightHandler()"); _doRotate(e, ROTATE_RIGHT); }; _pickerButtonHandler = function (e) { _api.log("_pickerButtonHandler() is executed."); var type = e.target.getAttribute("name").split("-")[0]; Y.FilePicker.show(type, { nodes : _node.all("input[name=list-item]:checked"), files : [_fileList], path : currentPath, mediaType : CONST.SPACE_MEDIA_TYPE_FOLDERS.photos, type : type }, _api); }; //=========================== // Private Methods //=========================== /** * Block upload buttons if user's device not support upload * @method _blockUploadButtons * @private */ _blockUploadButtons = function () { var uploadLink = _node.one("span.upload-link"), allNewUploadLink = _node.one("span.allnew-upload-link"), attr; attr = { title : _lang.oops, content : _lang.featureNotSupported }; if (uploadLink) { uploadLink.on("click", function (e) { _api.alert(attr); e.preventDefault(); }); } if (allNewUploadLink) { allNewUploadLink.on("click", function (e) { _api.alert(attr); e.preventDefault(); }); } }; /** * Asking server to know if current folder and subfolders have been shared. * @method _checkIsShared * @private */ _checkIsShared = function (folderList) { _api.log("checkIsShared()"); var postData = []; if (isWanShare) { postData.push("fid=" + PAGE.fid); postData.push("subpath=" + encodeURIComponent(PAGE.subpath)); } else { postData.push("did=" + PAGE.did); postData.push("base_path=" + encodeURIComponent(currentPath)); } Y.each(folderList, function (folder) { postData.push("dirnames[]=" + encodeURIComponent(folder.folderName)); }); Y.io("/space/q/is_shared", { method: "POST", data: postData.join("&"), on : { success: function (id, o, a) { _api.log("success on checkIsShared"); try { var result = Y.JSON.parse(o.responseText); if (result.status === "ok") { _handleSharedFolders(folderList, result); } else { _api.log("error on checkIsShared", "error"); } } catch (e) { _api.log("json parse error:" + o); } } } }); }; /** * Call device api to create directory * @method _doCreateDirectory * @private */ _doCreateDirectory = function (storageName, folderName, folderDesc) { var afterCreateDirectory, failureHandler, timeoutHandler, loadingNode; afterCreateDirectory = function (o) { //_api.log("MIIICASA.photosList.afterCreateDirectory"); var data, opt; if (o.status !== "ok") { _api.broadcast("hide-main-loading"); _api.broadcast("show-create-folder-errmsg", o); return false; } // upload folder desc if (_newFolderData.folderDesc === "") { _redirectToNewFolder(); return; } data = { tok : _deviceInfo.token, path : currentPath + "/" + _newFolderData.folderName + "/.miiithumbs" }; if (!isLan) { data.cp = Y.Cookie.get("p"); data.cs = Y.Cookie.get("s"); } opt = { fileVar : "uploadedfile", uploadTo: UPLOAD_URL, desc : _newFolderData.folderDesc, filename: "desc.txt" }; if (!isLan) { data.did = PAGE.did; } _uploader.uploadDesc(data, opt); _api.log("[uploadDesc] running..."); }; failureHandler = function () { _api.log("failureHandler()", "error"); }; timeoutHandler = function () { _api.log("timeoutHandler()", "error"); }; _newFolderData = { storageName : storageName, folderName : folderName, folderDesc : folderDesc }; _deviceConnector.createDirectory({ path : currentPath, dirname : folderName }, { on: { success: afterCreateDirectory, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); _api.log("[doCreateDirectory]" + storageName + "," + folderName + "," + folderDesc); // loading loadingNode = Y.one("#main-loading").setStyle("display", "block"); }; /** * Call device api to delete files * @method _doDeleteFiles * @private */ _doDeleteFiles = function (data, directlyReload) { var afterDeleteFiles, failureHandler, timeoutHandler; afterDeleteFiles = function (o) { _api.log("afterDeleteFiles()"); var syncData, syncCallback; syncData = { did : MIIICASA.env.did, act : "del", src_folderpath : data.src_folderpath, filelist : "[" + data.filelist.join(",") + "]" }; syncCallback = function () { if (directlyReload) { util.pageReload(); } else { _needReload = true; //reload page after user close large view } }; _syncFileInfo(syncData, syncCallback); }; failureHandler = function () { _api.log("failureHandler()", "error"); }; timeoutHandler = function () { _api.log("timeoutHandler()", "error"); }; _deviceConnector.deleteFiles({ fullfilenames : "[" + data.fullfilenames.join(",") + "]" }, { on: { success: afterDeleteFiles, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); }; /** * Performs input check and redirect if valid * @method _doRotate * @private */ _doRotate = function (e, angle) { var filesArray = [], thumbsArray = [], hasDir = false, selectedNodes = _node.all("input[name=list-item]:checked"), attr; if (selectedNodes._nodes.length === 0) { attr = { title: _lang.oops, content: _lang.noPhotoSelected + "
" + _lang.pleaseSelectPhoto }; _api.alert(attr); return; } Y.each(selectedNodes, function (node) { var id = node.get("id"), fileInfo = id.split("-"); if (_fileList[fileInfo[3]].type === CONST.FILE_TYPE_DIRECTORY) { hasDir = true; } else { filesArray.push(_fileList[fileInfo[3]].name); thumbsArray.push(_fileList[fileInfo[3]].thumbUrl); } }); if (hasDir) { attr = { title: _lang.oops, content: _lang.errorRotateAlbum + "
" + _lang.pleaseSelectPhotoInstead }; _api.alert(attr); return; } document.forms["photos-rotate"].elements.files.value = Y.JSON.stringify(filesArray); document.forms["photos-rotate"].elements.thumbs.value = Y.JSON.stringify(thumbsArray); document.forms["photos-rotate"].elements.angle.value = angle; document.forms["photos-rotate"].submit(); }; /** * Performing setCover * @method _doSetCover * @private */ _doSetCover = function (newCoverIndex) { _api.log(newCoverIndex); var loadingNode = Y.one("#main-loading").setStyle("display", "block"); MIIICASA.photosList.genCover(newCoverIndex); }; /** * Expand the viewer. * * @method _expandViewer * @param queryString {String} The space query string. */ _expandViewer = function (queryString) { _api.log("_expandViewer(e) is executed."); var href, segments, media; if (!queryString) { href = window.location.href; if (href.indexOf("#") !== -1) { href = href.slice(0, href.indexOf("#")); } queryString = href.split("?")[1]; segments = href.split("?")[0].split("/"); media = segments[segments.length - 2]; queryString += "&type=" + media; if (queryString.indexOf("&viewer") === -1) { queryString += "&viewer"; } } if (!_viewer) { _viewer = new Y.Viewer(); _viewer.render(); } _viewer.expand(queryString); }; /** * Performing download text file for folder desc * @method _fetchDesc * @private */ _fetchDesc = function () { _api.log("_fetchDesc"); var afterDownloadDesc, failureHandler, timeoutHandler; afterDownloadDesc = function (o) { var txt = "", tooltip = ""; if (!Lang.isUndefined(o.data)) { txt = util.nl2br(util.htmlspecialchars(o.data)); txt = UA.gecko ? util.wbr(txt) : txt; tooltip = o.data ? _lang.edit_desc_tooltip : ""; } _sideNode.one(".desc").set("innerHTML", txt); if (PAGE.permission >= CONST.PERMISSION_MANAGE) { _sideNode.one(".desc").set("title", tooltip); _descEditable = new Y.Editable({ "inputType" : "textarea", "selector" : ".desc-editable", "emptyDefault" : _lang.edit_desc_tooltip, "tooltip" : tooltip, "validateRule" : "max_length[300]", "sync" : true }); _descEditable.on("submit", function (e) { txt = e.details[0].value; _uploadDesc(txt); tooltip = txt ? _lang.edit_desc_tooltip : ""; _descEditable.set("tooltip", tooltip); }); } else { _sideNode.one(".desc").set("title", ""); } }; failureHandler = function () { _api.log("failureHandler()", "error"); }; timeoutHandler = function () { _api.log("timeoutHandler()", "error"); }; _deviceConnector.downloadTextFile({ fullfilename : (isWanShare ? PAGE.subpath : currentPath) + "/.miiithumbs/desc.txt" }, { on: { success: afterDownloadDesc, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); }; /** * Get total count of share/comment for any folder. * * @method _getSharedComments * @private * @param storageIndex {Number} * @return void */ _getSharedComments = function () { _api.log("_getSharedComments() is executed.", "info", MODULE_ID); Y.io("/space/q/get_shared_comments?" + PAGE.queryString, { method: "POST", on : { success: function (id, o, a) { var data = Y.JSON.parse(o.responseText); Y.each(data, function (o, key) { if (!Y.Object.hasKey(_mappings, key)) { return; } if (Y.Lang.isNumber(o.c)) { _node.one("#" + _mappings[key].comment).setContent(" (" + o.c + ")"); } }); } } }); }; /** * Performing getFileList to show photos and albums of current folder * @method _getFileList * @private */ _getFileList = function () { _api.log("_getFileList"); var afterGetFileList, failureHandler, timeoutHandler, getFileListArgvs = {}, showTotal = ""; afterGetFileList = function (o) { _api.log("afterGetFileList()"); var dirIndex = -1, folderList = [], // holding folder info (to query is_shared) foldGroup, // holding image loader group html, html2 = [], lightBoxInitialized = false, okHandler, attr; _api.broadcast("after-getfilelist", {"count": o.count }); if (o.label_name && MIIICASA.env.label !== o.label_name) { util.showLabelName(o.label_name); } _hasCover = (o.cover !== 0); if (Lang.isUndefined(o.status) || o.status !== "ok") { okHandler = function (e) { window.location.href = "/"; }; if (o.errno === 6001) { _api.broadcast("show-access-fail-request", {isShare: Y.MiiiCasa.isShare}); return; } else if (!Lang.isUndefined(_lang.deviceMessage[o.errno])) { attr = { title : _lang.oops, content : _lang.deviceMessage[o.errno] }; _api.alert(attr, okHandler); } else { attr = { title : _lang.oops, content : _lang.deviceMessage["5001"] }; _api.alert(attr, okHandler); } _api.broadcast("hide-main-loading"); return; } if (Lang.isUndefined(o.count) || o.count === 0) { //empty _api.broadcast("hide-main-loading"); _node.one(".sort-row").setStyle("display", "none"); _node.one(".task-row-container").remove(); _node.one(".empty").setStyle("display", "block"); if (!isShare) { _node.one(CHANGE_COVER_BTN).remove(); } } else { //has file(s) _fileList = o.files; Y.each(_fileList, function (file, i) { var commentLink = "", fileURI = "", fileLink = "", isPhoto = util.isPhoto(file), thumbId = ["thumb", 0, i].join("-"), thumbUrl = util.getThumbURL(file, isWanShare ? PAGE.subpath : o.filepath), commentTotalId, commentClass, shareTotalId, shareURL, regenControl, commentControl, shareControl; file.thumbUrl = thumbUrl; if (isPhoto) { _photoList.push(file); _photoIndex += 1; if (isLan && _featureSupport.flash && !lightBoxInitialized) { _initLightbox(); lightBoxInitialized = true; } regenControl = MIIICASA.tpls.regenControl; } else if (file.type === CONST.FILE_TYPE_DIRECTORY) { shareTotalId = Y.guid(); dirIndex += 1; regenControl = ""; } // Add share control panel from substitute. // Check file type and append control panel // if file type is not file style. // and if permission is 3( can modify, share, delete) if (file.type !== CONST.FILE_TYPE_FILE && MIIICASA.PAGE.photosList.permission === 3) { shareURL = Y.substitute(PAGE.shareSubDir, { SUBDIR : encodeURIComponent(file.name) }); shareControl = Y.substitute(MIIICASA.tpls.shareControl, { shareURL : shareURL }); } else { shareControl = ""; } fileURI = util.encodeURIForDa(file.uri, false); if (!Lang.isUndefined(file.thumb_l) && file.thumb_l === 1) { fileURI = util.getThumbURL(file, currentPath, "l"); } commentControl = ""; commentLink = isPhoto ? Y.substitute(PAGE.viewerURL, {F: encodeURIComponent(file.name)}) : _getSubFolderURL(PAGE.listURL, file.name, file.mtime) + "&viewer"; commentClass = isPhoto ? " comment-link" : ""; fileLink = isPhoto ? commentLink : _getSubFolderURL(PAGE.listURL, file.name, file.mtime); if (!_isAngelDevice) { commentTotalId = Y.guid(); commentControl = Y.substitute(MIIICASA.tpls.commentControl, { commentLink : commentLink, commentTotalId : commentTotalId }); } else { if (isPhoto) { fileLink = "javascript:void(0);"; commentClass = " no-link"; } } file.commentLink = fileLink; html2.push(Y.substitute(MIIICASA.tpls.item, { fileListId : ["filelist", 0, i].join("-"), fileLink : fileLink, typeClass : file.type === CONST.FILE_TYPE_FILE ? "type-file" : "type-folder", rel : file.type === CONST.FILE_TYPE_FILE ? ("slide:true group:lyteshow" + (UA.ie ? " doanimations:false" : "")) : "", rel2 : file.type === CONST.FILE_TYPE_FILE ? ("slide:true group:lyteshow2" + (UA.ie ? " doanimations:false" : "")) : "", thumbURL : thumbUrl, thumbId : thumbId, commentClass : commentClass, checkboxId : ["list-item", 0, i].join("-"), fullFileName : util.htmlspecialchars(file.name), fileDate : Y.DataType.Date.format(new Date(file.mtime * 1000), {format: "%x"}), shareTotalId : isPhoto ? "" : shareTotalId, editableClass : isPhoto ? "aaa" : " editable", photoClass : isPhoto ? " is-photo" : "", lyteboxClass : isPhoto ? " lytebox" : "", photoIdAttr : isPhoto ? ' id="photo-0-' + _photoIndex + '"' : "", defaultImgSrc : (file.thumb !== 0 && i >= 12) ? "" : " src=\"" + thumbUrl + "\"", // Append controll panel if file type if folder commentControl : commentControl, regenControl : regenControl, shareControl : file.type === CONST.FILE_TYPE_FILE ? "" : shareControl })); _api.broadcast("thumb-queued", {"thumb_url": thumbUrl}); if (isPhoto) { // set _firstPhotoIndex to genCover if (_featureSupport.upload && !_hasCover && _firstPhotoIndex === -1) { _firstPhotoIndex = i; } // store _genThumbList file.id = i; if (_featureSupport.upload && (file.thumb === 0 || (!Lang.isUndefined(file.thumb_l) && file.thumb_l === 0))) { _genThumbList.push(file); } _fileList[i].photoIndex = _photoIndex; //file -> photo } if (file.type === CONST.FILE_TYPE_DIRECTORY) { folderList.push({ id : i, folderName: file.name }); } _mappings[file.name] = {}; _mappings[file.name].comment = commentTotalId; if (shareTotalId) { _mappings[file.name].share = shareTotalId; } }); html = Y.substitute(MIIICASA.tpls.storage, { items : html2.join("") }); _node.insert(html, _node.one(".insert-before")); // show folder statistics if (dirIndex > -1) { showTotal = Y.substitute(_lang.totalAlbums, { num : util.addComma(dirIndex + 1) }); } if (_photoIndex > -1) { if (showTotal !== "") { showTotal += _lang.and; } showTotal += Y.substitute(_lang.totalPhotos, { num : util.addComma(_photoIndex + 1) }); } _node.one("div.stat").set("innerHTML", "(" + showTotal + ")"); if (folderList.length > 0) { _checkIsShared(folderList); } foldGroup = new Y.ImgLoadGroup({ foldDistance: 100, className: "lazyload" }); } _initUI(); Y.later(500, null, function () { _node.removeClass("loading"); }); }; failureHandler = function () { _api.log("failureHandler()", "error"); }; timeoutHandler = function () { _api.log("timeoutHandler()", "error"); _api.broadcast("show-access-fail-request", {isShare: isShare}); }; if (isWanShare) { getFileListArgvs = { subpath : PAGE.subpath, sortby : PAGE.sort, filter : "photo" }; } else { getFileListArgvs = { path : currentPath, sortby : PAGE.sort, filter : "photo" }; } if (PAGE.width) { getFileListArgvs.width = PAGE.width; // for API, resize on the fly } _deviceConnector.getFileList(getFileListArgvs, { on: { success: afterGetFileList, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); _node.addClass("loading"); }; /** * Get sub folder URL * @method _getSubFolderURL * @private */ _getSubFolderURL = function (template, dirName, mtime) { ///space/photos/lists?did=d123&s=USB_USB_Disk_172D56A_1&d=/ABC/{SUB_DIR}&sort=aa ///space/photos/lists?fid=f123&subpath=/ABC/{SUB_DIR}&sort=aa var url = Y.substitute(template, { SUB_DIR : encodeURIComponent(dirName) }); if (mtime) { url += "&mt=" + mtime; } return url; }; /** * Show share folder icon and add shard flag to the folder * @method _handleSharedFolders * @private */ _handleSharedFolders = function (folderList, result) { Y.each(folderList, function (folder, i) { // show share icon disabled // if (result.self[i] === 1) { // var fileListId = ["filelist", 0, folder.id].join("-"); // Y.one("#" + fileListId + " a.link").insert('
', "before"); // } // mark as shared, will confirm while delete if (result.self_or_sub[i] === 1) { _fileList[folder.id].shared = true; } }); }; /** * Initial lightbox component if browser has flash installed * @method _initLightbox * @private */ _initLightbox = function () { _api.log("initLightbox"); _lightboxNode = Y.one("#lightbox-overlay"); _lightboxNode.setStyle("position", "fixed"); _lightbox = new Y.Lightbox({ containerID : "lightbox-overlay", swfURL : CONST.STATIC_URL + "lib/mui/lightbox/assets/lightbox.swf?" + CONST.VER_LIGHTBOX }); _lightbox.addListener("contentReady", MIIICASA.photosList.lightboxContentReadyHandler); _lightbox.addListener("close", MIIICASA.photosList.lightboxCloseHandler); _lightbox.addListener("delete", MIIICASA.photosList.lightboxDeleteHandler); _lightbox.addListener("download", MIIICASA.photosList.lightboxDownloadHandler); _lightbox.addListener("setCover", MIIICASA.photosList.lightboxSetCoverHandler); _lightbox.addListener("edit", MIIICASA.photosList.lightboxEditHandler); }; /** * Initial (JS) Lytxbox component if browser has no flash installed * @method _initLytebox * @private */ _initLytebox = function () { _api.log("initLytebox"); initLytebox(); myLytebox.isPaused = true; myLytebox.doAnimations = UA.ie ? false : true; }; /** * Initial main UI / binding events * @method _initUI * @private */ _initUI = function () { // initail non-flash largeview/slideshow if (_photoIndex !== -1) { _initLytebox(); } // slideshow if (_node.one(SLIDESHOW_BTN)) { _node.one(SLIDESHOW_BTN).on("click", _slideShow); } if (_hasCover) { _setCoverURL(); } _api.broadcast("hide-main-loading"); _api.broadcast("show-mastfoot"); _node.all("input[name=download-button]").on("click", _downloadButtonHandler); _node.all("input[name=rotate-button]").on("click", _rotateButtonHandler); Y.delegate("click", _itemSelectHandler, _node, "input[name=list-item]"); Y.delegate("click", _regenClickHandler, _node, "a.regen-thumb-link"); _node.all("input[name=copyto-button]").on("click", _pickerButtonHandler); _node.all("input[name=moveto-button]").on("click", _pickerButtonHandler); _getSharedComments(); // handle UI & events by permission if (PAGE.permission >= CONST.PERMISSION_MANAGE) { // Edit each album name on the list. _editable = new Y.Editable({ "selector" : ".editable", "node" : _node, "tooltip" : _lang.edit_name_tooltip, "emptyDefault" : _lang.edit_name_tooltip, "validateRule" : "required|max_length[70]|filename", "sync" : true }); _editable.on("submit", _submitFolderNameHandler); // full control _node.all("input[name=delete-button]").on("click", _deleteButtonHandler); _node.one(".create-link").on("click", _createLinkHandler); } // attach event for devices not support upload if (!_featureSupport.canTryUpload && PAGE.permission >= CONST.PERMISSION_UPLOAD) { _blockUploadButtons(); } // show _node.setStyle("visibility", "visible"); //fetch storage data for free_space _listStorages(); // fetch desc _fetchDesc(); Y.later(100, this, _stickTaskRow); Y.Space.bindCentralize(); }; /** * Start list storages for each devices * @method _listStorages * @private */ _listStorages = function () { _api.log("_listStorages()"); var afterListStorages, failureHandler, timeoutHandler, attr; afterListStorages = function (o) { _api.log("afterListStorages"); var storagesData, thisDeviceLabels = {}, labelUpdated = false; Y.each(o.storages, function (storage) { Y.each(storage.mountpoints, function (partition) { thisDeviceLabels[partition.mountpoint.substr(1)] = partition.name; if ("/" + PAGE.storage === partition.mountpoint) { if (!Lang.isUndefined(MIIICASA.env.label) && MIIICASA.env.label !== partition.name) { labelUpdated = true; } _currentStorage = { model : storage.model, type : storage.type, mountpoint : partition.mountpoint, name : util.formatLabelName(partition.name), storage : partition.storage, used_space : partition.used_space, free_space : partition.storage - partition.used_space }; PAGE.label = _currentStorage.name; if (_currentStorage.free_space < CONST.ONE_MB && _node.one(CHANGE_COVER_BTN)) { _node.one(CHANGE_COVER_BTN).on("click", function (e) { _api.log("Current Storage free space is less than 1 MB. You can't change cover."); attr = { title : _lang.oops, content : _lang.featureNotSupported }; _api.alert(attr); e.preventDefault(); }); _firstPhotoIndex = -1; return; } if (_currentStorage.free_space > CONST.ONE_MB) { if (_genThumbList.length > 0) { Y.later(10, this, MIIICASA.photosList.genThumb); return; } if (_firstPhotoIndex > -1) { MIIICASA.photosList.genCover(0); } } } }); }); if (labelUpdated) { util.saveLabel(PAGE.did, thisDeviceLabels); } // update create folder overlay ui storagesData = [{ name : PAGE.label, free_space : _currentStorage.free_space }]; _api.broadcast("show-create-folder-update-ui", { storages : storagesData, callback : _doCreateDirectory }); }; failureHandler = function () { _api.log("failureHandler()", "error"); }; timeoutHandler = function () { _api.log("timeoutHandler()", "error"); }; _deviceConnector.listStorages({}, { on: { success: afterListStorages, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); }; /** * Refresh Page after editing folder name. * * @method _refreshPage * @private * @param option {String} folder name after editing * @return void */ _refreshPage = function (folderName) { var url = Y.substitute(PAGE.baseBackURL, { CURRENT_DIR : encodeURIComponent(folderName) }); window.location.href = url; }; /** * Redirect to new folder after create folder * @method _redirectToNewFolder * @private */ _redirectToNewFolder = function (e) { if (_newFolderData.folderName) { var url = Y.substitute(PAGE.listURL, { SUB_DIR : encodeURIComponent(_newFolderData.folderName) }); window.location.href = url; } }; /** * Update url of share/comment after renaming album name. * * @method _updateSharedComments * @private * @param liNode{Y.Node} The folder node * @param storage{Array} The storage * @param name{String} The folder name * @return void */ _updateSharedComments = function (liNode, storage, name) { _api.log("_updateSharedComments() is executed.", "info", MODULE_ID); var replaceToken, queryString, commentLink, shareLink; replaceToken = { "SUBDIR" : encodeURIComponent(name, false), "S" : storage }; queryString = Y.substitute(PAGE.subQueryString, replaceToken); commentLink = "/space/photos/list?" + queryString + "&viewer"; shareLink = Y.substitute(PAGE.shareSubDir, replaceToken); liNode.one(".extra .comment-link").setAttribute("href", commentLink); if (liNode.one(".extra .share-link")) { liNode.one(".extra .share-link").setAttribute("href", shareLink); } }; /** * Get true or false if there is the same folder name. * * @method _getFoundFolder * @private * @return boolean */ _getFoundFolder = function (value) { var isFound = false; Y.each(_fileList, function (obj, i) { if (obj.type === 2 && obj.name.toLowerCase() === value.toLowerCase()) { isFound = true; } }); return isFound; }; /** * Update array _fileList after saving folder name edited. * * @method _updateFileLists * @private * @param node {Y.Node} The album node * @param name {String} The folder name * @return void */ _updateFileLists = function (node, name) { _api.log("_updateFileLists() is executed.", "info", MODULE_ID); var idArr = node.get("id").split("-"), folderIndex = idArr[2]; _fileList[folderIndex].name = name; }; /** * Rename album name. * * @event _renameFolder * @private * @param folderName{String} The new folder name * @param baseFolderName{String} The old folder name * @param node {Y.Node} The folder node * @return void */ _renameFolder = function (folderName, baseFolderName, node) { _api.log("_renameFolder() is executed.", "info", MODULE_ID); var storageId, storage, mountpoint, path, afterRenameFolder, failureHandler, timeoutHandler; mountpoint = PAGE.storage; folderName = Lang.trim(folderName); baseFolderName = Lang.trim(baseFolderName) || null; _currentPath = currentPath + "/" + baseFolderName; afterRenameFolder = function (o) { var linkNode, linkUrl, attr, syncData; if (o.status === "ok") { // Send a request to server for folder rename shared or commented. syncData = { did : MIIICASA.env.did, act : "rename", src_folderpath : currentPath, filelist : "[\"" + baseFolderName + "\"]", filename : folderName }; _syncFileInfo(syncData); if (node) { linkNode = node.ancestor(".photo").one(".link"); linkNode.setAttribute("title", util.htmlspecialchars(folderName)); linkUrl = Y.substitute(PAGE.listURL, { "SUB_DIR": encodeURIComponent(folderName, false) }); linkNode.setAttribute("href", linkUrl); } _updateFileLists(node, folderName); _updateSharedComments(node.ancestor("li"), mountpoint, folderName); } else { if (o.errno === 6001) { _api.broadcast("show-access-fail-request"); return; } else if (!Lang.isUndefined(_lang.deviceMessage[o.errno])) { attr = { title : _lang.oops, content : _lang.deviceMessage[o.errno] }; _api.alert(attr); } else { attr = { title : _lang.oops, content : _lang.deviceMessage["5001"] }; _api.alert(attr); } return; } }; failureHandler = function () { _api.log("failureHandler() is executed.", "error"); }; timeoutHandler = function () { _api.log("timeoutHandler() is executed.", "error"); }; _deviceConnector.renameFile({ src_fullfilename : _currentPath, dst_filename : folderName }, { on: { success: afterRenameFolder, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); }; /** * After renaming or deleting folder or files, send the request to delete record in database. * Also, delete shared record. * * @method _syncFileInfo * @private * @param data{Object} The data synchronized with comments and sharing. * @param callback{Function} The callback function. * @return void */ _syncFileInfo = function (data, callback) { _api.log("_syncFileInfo() is executed."); data = util.composeData(data); var url = "/space/q/sync_file_info", cfg; cfg = { method: "POST", data: data, on: { complete: function (id, o, a) { var response = Y.JSON.parse(o.responseText); if (response.status === "ok") { _api.log("_syncFileInfo() is success."); if (callback) { callback(); } } else { _api.log("_syncFileInfo() is failed.", "error", MODULE_ID); } } } }; Y.io(url, cfg); }; /** * Rename album name. * * @method _renameTitle * @private * @param folderName{String} folder name after editing * @param baseFolderName{String} The old folder name * @return void */ _renameTitle = function (folderName, baseFolderName) { var afterRenameFolder, failureHandler, timeoutHandler; _currentPath = util.dirname(currentPath) + "/" + baseFolderName; afterRenameFolder = function (o) { _api.log("afterRenameFolder() is executed.", "info", MODULE_ID); var attr, syncData, syncCallback; if (o.status === "ok") { // Send a request to server for folder rename shared or commented. syncData = { did : MIIICASA.env.did, act : "rename", src_folderpath : util.dirname(currentPath), filelist : "[\"" + baseFolderName + "\"]", filename : folderName }; syncCallback = function () { _refreshPage(folderName); }; _syncFileInfo(syncData, syncCallback); } else { if (o.errno === 6001) { _api.broadcast("show-access-fail-request"); return; } else if (!Lang.isUndefined(_lang.deviceMessage[o.errno])) { attr = { title : _lang.oops, content : _lang.deviceMessage[o.errno] }; _api.alert(attr); } else { attr = { title : _lang.oops, content : _lang.deviceMessage["5001"] }; _api.alert(attr); } _titleEditable.hide(); return; } }; failureHandler = function () { _api.log("failureHandler() is executed.", "error", MODULE_ID); }; timeoutHandler = function () { _api.log("timeoutHandler() is executed.", "error", MODULE_ID); }; // currentPath = "/USB_JetFlash_Transcend_16GB_XAZBOVM_1/miiiCasa_Music/Vivian 2012"; _deviceConnector.renameFile({ src_fullfilename : _currentPath, dst_filename : folderName }, { on: { success: afterRenameFolder, failure: failureHandler, timeout: timeoutHandler }, timeout: CONST.CLIENT_TIMEOUT }); }; /** * set cover url * @method _setCoverURL * @private */ _setCoverURL = function () { var file, coverPath; file = { type : CONST.FILE_TYPE_DIRECTORY, thumb : new Date().getTime(), name : "" }; _currentCoverUrl = util.getThumbURL(file, isWanShare ? PAGE.subpath : currentPath, CONST.COVER_SIZE_100); coverPath = "url(\"" + util.getThumbURL(file, isWanShare ? PAGE.subpath : currentPath) + "\")"; _sideNode.one(".cover").setStyle("backgroundImage", coverPath); //_sideNode.one("img").set("src", util.getThumbURL(file, isWanShare ? PAGE.subpath : currentPath)); _api.broadcast("after-gen-cover", _currentCoverUrl); }; /** * Run slideshow * @method _slideShow * @private */ _slideShow = function (e) { var attr, getResourceFileUrl, getResourceFileArgvs = { sortby : PAGE.sort, filter : "photo", format : "1" }; if (_photoIndex === -1) { attr = { title : _lang.oops, content : _lang.noPhotoFound }; _api.alert(attr); return; } if (isWanShare) { getResourceFileArgvs.subpath = PAGE.subpath; } else { getResourceFileArgvs.path = currentPath; } if (PAGE.width) { getResourceFileArgvs.width = PAGE.width; // for API, resize on the fly } getResourceFileUrl = _deviceConnector.getResourceFileUrl(getResourceFileArgvs); _api.broadcast("show-slideshow-overlay", {fileList : _fileList, getResourceFileUrl : getResourceFileUrl}); e.preventDefault(); }; /** * Makes the taskrow stick inside viewport * @event _stickTaskRow * @private */ _stickTaskRow = function () { var firstTaskRowNode = _node.one("div.task-row-container"); if (!firstTaskRowNode) { return; } firstTaskRowNode.plug(Y.Plugin.NodeStickViewport); firstTaskRowNode.stickViewport.setDistance("top", 75); firstTaskRowNode.stickViewport.clone(); }; /** * Check/Uncheck "Select All" check box according to other check boxes' check status. * If one of the check boxes is not checked, "Select All" check box shouldn't be checked then. * @method _syncCheckAllBox * @private * @return void */ _syncCheckAllBox = function (node) { var isChecked = node.get("checked"), checkNodes, i, j; if (isChecked) { checkNodes = _node.all("div.storage input"); for (i = 0, j = checkNodes.size(); i < j; i += 1) { if (!checkNodes.item(i).get("checked")) { return; } } _node.all("#selectall-a, #selectall-b").set("checked", "checked"); _node.all("#selectall-a-miii-checkbox, #selectall-b-miii-checkbox").addClass("miii-checkbox-checked"); } else { _node.all("#selectall-a, #selectall-b").set("checked", ""); _node.all("#selectall-a-miii-checkbox, #selectall-b-miii-checkbox").removeClass("miii-checkbox-checked"); } }; /** * Sync checkbox status with miii-checkbox * @method _syncSelectedItem * @private */ _syncSelectedItem = function (node) { var isChecked = node.get("checked"), li = node.get("parentNode").get("parentNode"); if (isChecked) { li.addClass("checked"); } else { li.removeClass("checked"); } }; _uploadDesc = function (desc) { var data, opt; data = { tok : _deviceInfo.token, path : currentPath + "/.miiithumbs" }; if (!isLan) { data.cp = Y.Cookie.get("p"); data.cs = Y.Cookie.get("s"); data.did = PAGE.did; } opt = { fileVar : "uploadedfile", uploadTo : UPLOAD_URL, desc : desc, filename : "desc.txt" }; _uploader.uploadDesc(data, opt); }; /** * Module initialization * @event init * @param api {Y.Sandbox} Module API * @public * @return void */ init = function (sandbox) { _api = sandbox; _api.log("init() is executed"); _lang = { and : _api.getTrans("and", " & "), cancel : _api.getTrans("cancel_button", "Cancel"), errorPostAlbum : _api.getTrans("error_post_album", "We don't support posting album(s). The album(s) you selected could not be posted."), limitPostAlbum : _api.getTrans("error_post_limit_album", "You can only post {num} photos at a time.", {num : LIMIT_POST_PHOTO}), errorRotateAlbum : _api.getTrans("error_rotate_album", "We don't support rotating album(s). The album(s) you selected could not be rotated."), featureNotSupported : _api.getTrans("feature_not_supported", "This feature is not supported for your device!"), lightboxPrevious : _api.getTrans("lightbox_previous", "Previous"), lightboxNext : _api.getTrans("lightbox_next", "Next"), lightboxDelete : _api.getTrans("lightbox_delete", "Delete"), lightboxDownload : _api.getTrans("lightbox_download", "Download"), lightboxSetcover : _api.getTrans("lightbox_setcover", "Set Cover"), lightboxEdit : _api.getTrans("lightbox_edit", "Edit"), lightboxPhotoCount : _api.getTrans("lightbox_photo_count", "{currentIndex} of {totalAmount} images"), lightboxDeleteConfirm : _api.getTrans("lightbox_delete_confirm", "Delete Confirm"), lightboxSetcoverConfirm : _api.getTrans("lightbox_setcover_confirm", "Set Cover Confirm"), lightboxPlayAgain : _api.getTrans("lightbox_play_again", "Play Again"), lightboxYes : _api.getTrans("lightbox_yes", "Yes"), lightboxNo : _api.getTrans("lightbox_no", "No"), noAlbumSelected : _api.getTrans("no_album_selected", "You don't select any albums."), noFileSelected : _api.getTrans("no_file_selected", "You don't select any files."), noPhotoFound : _api.getTrans("no_photo_found", "We can't find any photo in the folder."), noPhotoSelected : _api.getTrans("no_photo_selected", "You don't select any photos."), ok : _api.getTrans("ok_button", "Ok"), oops : _api.getTrans("oops", "Oops"), pleaseSelectAnAlbum : _api.getTrans("please_select_an_album", "Please select an album to share."), pleaseSelectOneAlbum : _api.getTrans("please_select_one_album", "Please just select one album instead of selecting multiple photos or albums."), pleaseSelectPhoto : _api.getTrans("please_select_photo", "Please select single/multiple photos first."), pleaseSelectPhotoInstead : _api.getTrans("please_select_photo_instead", "Please select single/multiple photos instead of selecting albums."), shareOneFolderOnly : _api.getTrans("share_one_folder_only", "Share one folder only"), shareFolderOnly : _api.getTrans("share_folder_only", "Share folder only"), tooManyAlbumsToShare : _api.getTrans("too_many_albums_to_share", "You can share only one album at one time."), totalAlbums : _api.getTrans("total_albums", "{num} albums"), totalPhotos : _api.getTrans("total_photos", "{num} photos"), edit_name_tooltip : _api.getTrans("edit_name_tooltip", "Rename Album"), edit_desc_tooltip : _api.getTrans("edit_desc_tooltip", "Edit Description"), same_foldername_error : _api.getTrans("same_foldername_error", "Your input already exists."), cant_move_files_cross_media : _api.getTrans("cant_move_files_cross_media", "You can't move files cross different media types.") }; _api.broadcast("get-device-message", { callback : function (msg) { _lang.deviceMessage = msg; _api.lang = _lang; } }); _api.listen("expand-viewer", function (name, moduleId, queryString) { _expandViewer(queryString); }); }; /** * Module content ready * @event onviewload * @public * @return void */ onviewload = function () { if (!_lang.deviceMessage) { Y.later(50, this, onviewload); return; } _api.log("onviewload() is executed"); PAGE = MIIICASA.PAGE.photosList; currentPath = PAGE.currentPath; _deviceInfo = Y.MiiiCasa.deviceInfo; _node = _api.getViewNode(); _sideNode = _node.one("div.cover-container"); isLan = MIIICASA.env.isLan; isShare = Y.MiiiCasa.isShare; isWanShare = !isLan && Y.MiiiCasa.isShare; util = Y.MiiiCasa.util; CONST = Y.merge(window.MIIICASA.CONST, Y.MiiiCasa.CONST); Lang = Y.Lang; UPLOAD_URL = Y.MiiiCasa.uploadURL; UA = Y.UA; _featureSupport = util.featureDetect(); _isAngelDevice = (!PAGE.did && PAGE.fid === "03030303030303030303030303030303") ? true : false; // If viewer exists, expand the viewer. var queryString, hash, hashes, params, toolbar, toolbarOver, toolbarOut; queryString = window.location.href.split("?")[1]; if (queryString.indexOf("#") !== -1) { queryString = queryString.substring(0, queryString.indexOf("#")); hash = window.location.hash; params = Y.QueryString.parse(hash.substr(hash.indexOf("?") + 1)); } else { params = Y.QueryString.parse(queryString); } params.type = "photos"; if (Y.Lang.isUndefined(params.sort)) { params.sort = "aa"; } if (!Y.Lang.isUndefined(params.viewer)) { _expandViewer(Y.QueryString.stringify(params)); } // create device connector instance and performs getFileList _deviceConnector = new Y.DeviceConnector({ wsip : isLan ? _deviceInfo.wsip : CONST.API_URL, did : PAGE.did, isLan : isLan, isShare : isShare, fid : PAGE.fid, tok : _deviceInfo.token }); _getFileList(); if (_featureSupport.upload) { _uploader = new Y.Uploader({ containerID : "uploader-container", swfURL : CONST.STATIC_URL + "lib/mui/uploader/assets/uploader.swf?" + CONST.VER_UPLOADER, bindings : { contentReady : MIIICASA.photosList.uploaderContentReadyHandler, genCoverComplete : MIIICASA.photosList.uploaderGenCoverCompleteHandler, genThumbComplete : MIIICASA.photosList.uploaderGenThumbCompleteHandler, uploadDescComplete : MIIICASA.photosList.uploaderUploadDescCompleteHandler, thumbnailUploadError : MIIICASA.photosList.uploaderThumbnailUploadError } }); } // uncheck "checkall" - for chrome _node.all("#selectall-a").set("checked", ""); // checkall _node.all("#selectall-a").on("click", _checkAllHandler); // Bind share button, it will attack tooltip display. Y.delegate("mouseleave", _folderShareLeaveHandler, _node, "span.share-control a"); Y.delegate("mouseenter", _folderShareEnterHandler, _node, "span.share-control a"); Y.delegate("click", _commentClickHandler, _node, ".comment-link"); if (isShare) { // Track page view for open link (non-login). if (!MIIICASA.env.is_login) { _api.trackEvent("photos", "View"); } return; } // The album name on the top. _titleEditable = new Y.Editable({ "selector" : ".title-editable", "tooltip" : _lang.edit_name_tooltip, "emptyDefault" : _lang.edit_name_tooltip, "sync" : true, "validateRule" : "required|max_length[70]|filename" }); _titleEditable.on("submit", function (e) { _renameTitle(e.details[0].value, _titleEditable.get("activeValue")); e.preventDefault(); }); }; //============================= // callback & global functions //============================= MIIICASA.photosList = {}; MIIICASA.photosList.genCover = function (fileIndex) { if (isLan || CONST.P2P_UPLOAD) { MIIICASA.photosList.genCoverByUploader(fileIndex); } else { MIIICASA.photosList.genCoverByServer(fileIndex); } }; MIIICASA.photosList.genCoverByUploader = function (fileIndex) { var file, filename, data, daUrl, opt; if (!_uploader.get("isReady")) { if (_genCoverRetry < 10) { _api.log("[genCover] uploader is not ready, waiting 500ms to try again."); Y.later(500, this, function () { MIIICASA.photosList.genCoverByUploader(fileIndex); }); } _genCoverRetry += 1; return; } Y.log("[genCoverByUploader] is executed."); data = { tok : _deviceInfo.token, path : currentPath + "/.miiithumbs" }; if (!isLan) { if (isWanShare) { data.fid = PAGE.fid; data.subpath = PAGE.subpath; data.path = "/.miiithumbs"; } else { data.did = PAGE.did; } data.cp = Y.Cookie.get("p"); data.cs = Y.Cookie.get("s"); } file = _photoList[fileIndex]; filename = file.name; filename = [filename.substr(0, filename.lastIndexOf(".")), "_", file.mtime, "_", file.size, "_l.jpg"].join(""); daUrl = util.getDaUrl([isWanShare ? PAGE.subpath : currentPath, '/.miiithumbs/', filename].join("")); //source file, no url_encode //thumb largefile, no url_encode opt = { fileVar : "uploadedfile", from : daUrl, uploadTo: UPLOAD_URL, coverSize: { "cover.jpg" : { h: 150, useCrazy: true}, "cover_100.jpg" : {w: 240, h: 240} } }; if (!isLan && CONST.P2P_UPLOAD) { opt.getUploadUri = CONST.API_URL + "ws/device/getUploadParam?alt=1"; } _uploader.genCover(data, opt); _api.log("[genCoverByUploader] running..."); }; MIIICASA.photosList.genCoverByServer = function (fileIndex) { var getCoverURL = [ CONST.API_URL, "ws/device/setCover", (isWanShare ? "?fid=" + PAGE.fid : "?did=" + PAGE.did), "&tok=" + _deviceInfo.token, "&callback=MIIICASA.photosList.serverGenCoverCompleteHandler", "&f=", encodeURIComponent((isWanShare ? PAGE.subpath : currentPath) + '/' + _photoList[fileIndex].name) ].join(""); Y.Get.script(getCoverURL); _api.log("[genCoverByServer] running..."); }; MIIICASA.photosList.genThumb = function () { if (isLan || CONST.P2P_UPLOAD) { MIIICASA.photosList.genThumbByUploader(); } else { MIIICASA.photosList.genThumbByServer(); } }; MIIICASA.photosList.genThumbByUploader = function (ignoreExist) { _api.log("genThumbByUploader"); ignoreExist = (!Y.Lang.isUndefined(ignoreExist) && ignoreExist === true) ? true : false; if (!_uploader.get("isReady")) { if (_genThumbRetry < 10) { _api.log("[genThumb] uploader is not ready, waiting 500ms to try again."); Y.later(500, this, MIIICASA.photosList.genThumbByUploader); } _genThumbRetry += 1; return; } if (_genThumbIndex > _genThumbList.length) { return; } var data, daUrl, opt, thumbFile = _genThumbList[_genThumbIndex], thumbFormats = []; data = { tok : _deviceInfo.token, path : currentPath + "/.miiithumbs" }; if (!isLan) { if (isWanShare) { data.fid = PAGE.fid; data.subpath = PAGE.subpath; data.path = "/.miiithumbs"; } else { data.did = PAGE.did; } data.cp = Y.Cookie.get("p"); data.cs = Y.Cookie.get("s"); } if (ignoreExist || thumbFile.thumb === 0) { thumbFormats.push({ namePattern: "{name}_{mtime}_{size}.jpg", w: 240, h: 240, crop: true, jpegRatio: 90 }); // non-block with uploader Y.later(0, this, function () { util.showBlockLoading(Y.one("#filelist-0-" + thumbFile.id + " .photo-content")); }); } if (ignoreExist || (!Lang.isUndefined(thumbFile.thumb_l) && thumbFile.thumb_l === 0)) { thumbFormats.push({ namePattern: "{name}_{mtime}_{size}_l.jpg", w: 1920, h: 1080, crop: false, jpegRatio: 70 }); } _uploader.setMakeThumbs(true, thumbFormats); daUrl = util.getDaUrl([isWanShare ? PAGE.subpath : currentPath, '/', thumbFile.name].join("")); //source file opt = { filename: thumbFile.name, // no encode fileVar : "uploadedfile", from : daUrl, uploadTo: UPLOAD_URL, mtime : thumbFile.mtime, size : thumbFile.size }; if (!isLan && CONST.P2P_UPLOAD) { opt.getUploadUri = CONST.API_URL + "ws/device/getUploadParam?alt=1"; } _uploader.genThumbFromOriginal(data, opt); _api.log("[genThumbByUploader] running..."); }; MIIICASA.photosList.genThumbByServer = function () { if (_genThumbIndex > _genThumbList.length) { return; } var genThumbingURL, thumbFile = _genThumbList[_genThumbIndex], thumbFormats = 0; if (thumbFile.thumb === 0) { thumbFormats |= 1; // bitwise or // non-block with script tag Y.later(0, this, function () { util.showBlockLoading(Y.one("#filelist-0-" + thumbFile.id + " img")); }); } if (!Lang.isUndefined(thumbFile.thumb_l) && thumbFile.thumb_l === 0) { thumbFormats |= 2; // bitwise or } genThumbingURL = [ CONST.API_URL, "ws/device/doThumbing", (isWanShare ? "?fid=" + PAGE.fid : "?did=" + PAGE.did), "&tok=" + Y.Cookie.get("dt"), "&callback=MIIICASA.photosList.serverGenThumbCompleteHandler", "&size=", thumbFile.size, "&mtime=", thumbFile.mtime, "&f=", encodeURIComponent((isWanShare ? PAGE.subpath : currentPath) + '/' + thumbFile.name), "&thumb=", thumbFormats ].join(""); Y.Get.script(genThumbingURL); _api.log("[genThumbByServer] running..."); }; // server callback functions MIIICASA.photosList.serverGenCoverCompleteHandler = function (o) { _api.log("[genCoverByServer] compelted"); _api.broadcast("hide-main-loading"); if (o.status === "ok") { _setCoverURL(new Date().getTime()); } else { _api.log("[genCover] failed"); var data = { src_folderpath: currentPath + "/.miiithumbs", filelist: ["cover.jpg", "cover_100.jpg"], fullfilename: ["\"" + currentPath + "/.miiithumbs/cover.jpg" + "\"", "\"" + currentPath + "/.miiithumbs/cover_100.jpg" + "\""] }; _doDeleteFiles(data, DIRECTLY_RELOAD_NO); _sideNode.one(".cover").setStyle("backgroundImage", CONST.STATIC_URL + "index/space/photos/ico_default_photos.png"); return; } }; MIIICASA.photosList.serverGenThumbCompleteHandler = function (o) { _api.log("MIIICASA.photosList.serverGenThumbCompleteHandler"); var largeThumbURL, thumbFile = _genThumbList[_genThumbIndex], thumbURL; if (o.status === "ok") { _fileList[thumbFile.id].thumb = thumbFile.thumb = 1; if (!Lang.isUndefined(_fileList[thumbFile.id].thumb_l)) { _fileList[thumbFile.id].thumb_l = 1; largeThumbURL = util.getThumbURL(thumbFile, currentPath, "l"); _node.one("#filelist-0-" + thumbFile.id + " a.is-photo").set("href", largeThumbURL); } thumbURL = util.getThumbURL(thumbFile, currentPath); _node.one("#filelist-0-" + thumbFile.id + " img").set("src", thumbURL); _api.broadcast("after-gen-thumb", {photoIndex: _fileList[thumbFile.id].photoIndex, thumbURL: thumbURL}); } // next _genThumbIndex += 1; if (_genThumbIndex < _genThumbList.length) { MIIICASA.photosList.genThumbByServer(); } util.hideBlockLoading(); }; // uploader callback functions MIIICASA.photosList.uploaderContentReadyHandler = function () { // sometimes it's too fast to bind this event! amazing... (Chrome) _api.log("uploader content ready"); Y.later(1, this, function () { if (!isLan) { // add domain policy file in WAN (for p2p download/upload) if (_deviceInfo.remoteip) { _uploader.addDomainPolicyFile("http://" + _deviceInfo.remoteip); } else if (MIIICASA.env.remoteip) { _uploader.addDomainPolicyFile("http://" + MIIICASA.env.remoteip); } } }); }; MIIICASA.photosList.uploaderGenCoverCompleteHandler = function (e) { Y.log("[genCoverByUploader] compelted"); _setCoverURL(new Date().getTime()); if (_isRegenerating) { MIIICASA.photosList.genThumbByUploader(true); _isRegenerating = false; } else { _api.broadcast("hide-main-loading"); } }; MIIICASA.photosList.uploaderGenThumbCompleteHandler = function (e) { _api.log("MIIICASA.photosList.uploaderGenThumbCompleteHandler"); Y.log("MIIICASA.photosList.uploaderGenThumbCompleteHandler"); var thumbFile = _genThumbList[_genThumbIndex], largeThumbURL, thumbURL; _fileList[thumbFile.id].thumb = thumbFile.thumb = 1; if (!Lang.isUndefined(_fileList[thumbFile.id].thumb_l)) { _fileList[thumbFile.id].thumb_l = 1; largeThumbURL = util.getThumbURL(thumbFile, currentPath, "l"); if (thumbFile.id >= 0 && _firstPhotoIndex > -1) { MIIICASA.photosList.genCover(0); _firstPhotoIndex = -1; } thumbURL = util.getThumbURL(thumbFile, currentPath); _node.one("#filelist-0-" + thumbFile.id + " a.is-photo").setStyle("backgroundImage", 'url("' + thumbURL + '")'); } thumbURL = thumbURL || util.getThumbURL(thumbFile, currentPath); if (_lightboxContentReady === true) { _lightbox.setAttr("fileList", _fileList); // update navigation } _api.broadcast("after-gen-thumb", {photoIndex: _fileList[thumbFile.id].photoIndex, thumbURL: thumbURL}); // next _genThumbIndex += 1; if (_genThumbIndex < _genThumbList.length) { MIIICASA.photosList.genThumbByUploader(); } util.hideBlockLoading(); }; MIIICASA.photosList.uploaderUploadDescCompleteHandler = function (e) { _api.log("UploadDescComplete"); if (_uploadDescCompleteCallback) { _uploadDescCompleteCallback(e); _uploadDescCompleteCallback = null; return; } _redirectToNewFolder(); }; MIIICASA.photosList.uploaderThumbnailUploadError = function (e) { _api.log("MIIICASA.photosList.uploaderThumbnailUploadError", "error"); if (e.status && e.status.indexOf("[genCover]") !== -1) { _api.log("[genCover] failed"); _api.broadcast("hide-main-loading"); var filesArray = ['"' + currentPath + "/.miiithumbs/cover.jpg" + '"', '"' + currentPath + "/.miiithumbs/cover_100.jpg" + '"']; _doDeleteFiles(filesArray, DIRECTLY_RELOAD_NO); _sideNode.one(".cover").setStyle("backgroundImage", CONST.STATIC_URL + "index/space/photos/ico_default_photos.png"); return; } // next _genThumbIndex += 1; if (_genThumbIndex < _genThumbList.length) { MIIICASA.photosList.genThumbByUploader(); } else { if (_firstPhotoIndex > -1) { _photoList.reverse(); Y.some(_photoList, function (photo, i) { if (photo.thumb) { MIIICASA.photosList.genCover(i); _firstPhotoIndex = -1; } }); } util.hideBlockLoading(); } }; _api = new Y.Module({ selector: MODULE_ID, langModule: "space", init: init, on: { viewload: onviewload } }); }, "0.0.1", { "group" : "space", "js" : "space/photos/_photos_list.js", "css" : "space/photos/_photos_list.css", "requires": [ "module", "module-intl", "module-popup", "module-analytics", "querystring", "datatype-date-format", "json", "overlay", "event-base", "node-base", "node-style", "substitute", "io-base", "cookie", "node-style", "viewer", "editable", "imageloader", "lightbox", "event-delegate", "node-stickviewport", "device-connector", "uploader", "space", "space/filepicker", "space-centralize" ] });