// // Manage download file from HoGo // var HoGoDownload = (function ($) { var _kr_authkey = "AQEBAYAAISjDV+QFkeK9rrcOiEeO+J58Km7gbw0OhTwNlaAjFnx2YBlFx6Nd7bDgTgCsmyWAkvDfNv/3V2Tav1mPudywhIor15byfFII0cAAB4J4DFGsw1kmsOoyAmjs/eqsUelj7z6GHvfwk8A/TvQ5MuJqnoKHpXKbb5DRNWOrFx1KDU4AABAAjhEDHD0oJiFihzZUgmJuvRUAAACwWFkYOca75kSLgjDY/SKl6CS/cyE="; // Detect Chrome version var chromeVersion = 0; var chromeVersionLimit = 42; var packageID, email, title, docID, itself; // Document's stuff // var submitting = false, isMultipleDownload = false, isMultiDownloading = false, emailDownloadMultiple = ""; // var supportedOS = ["Windows", "iOS", "Android", "Mac"]; var supportedOSView = ["Windows", "Mac", "iOS", "Android"]; // Store list document var packInfo, docList = []; //Contain IDs are checked var queueDocumentDownload = []; var lEnableButton = {'list_button': []}; // Init list lEnableButton.list_button.push({'id': "btDownloadAll", 'color': 'orange', 'submit': false, 'handler': fnDownloadAllDocument, "form_id": null}); var lDisableButton = {'list_button': []}; lDisableButton.list_button.push({'id': "btDownloadAll", 'color': 'orange', 'handler': fnDownloadAllDocument}); function checkSupportPlatform(type) { if (typeof BEObj == 'undefined') return; // Check OS var OS = BEObj.getOS2(), content; // Detect Chrome version try { // major version only as int: chromeVersion = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10); } catch (e) { } // View online just only Windows, Mac switch (type) { case 'register': if ($.inArray(OS, supportedOS) === -1) { content = "Only support Windows, iOS, Android"; } break; case 'view': if ($.inArray(OS, supportedOSView) === -1) { content = "Only support Windows, Mac"; } else { // Check Chrome version, chrome not support NPAPI http://blog.chromium.org/2014/11/the-final-countdown-for-npapi.html // Not support Chrome 42 or above. // major version only as int: if (typeof (chromeVersion) !== 'undefined') { if (chromeVersion >= chromeVersionLimit) content = "Chrome 42 or above is not supported. Please use IE or Firefox."; } } break; default: if ($.inArray(OS, supportedOS) === -1) { content = "Only support Windows, iOS, Android"; } break; } if (content) { Modal.showAlert({ title: "Unsupported OS", content: content }); return false; } else return true; } /** * Show check password popup */ function showCheckPasswordPopup() { //Clean error first $('#checkPasswordPopup').find(".formError").remove(); var boxpanel = '
' + '
' + 'HoGo' + '
' + '
' + '' + '
' + '' + '
' + '
' + '' + '
'; $(boxpanel).appendTo('body'); var pp = $('#checkPasswordPopup'); // Translate pp.i18n(); //Show pp.reveal({closeonbackgroundclick: false}); // Check button pp.find('.check').unbind('click').bind('click', function (e) { var form = $(this).parents('form'); form.submit(); doCheckPassword(); }); // Keypress enter pp.find('#Password').keypress(function (e) { if (e.which === 13 || e.keyCode === 13) { //Enter key var form = $(this).parents('form'); form.submit(); doCheckPassword(); } }); // Cancel pp.find('.cancel').unbind('click').bind('click', function () { //Modal.closeModal(); window.location.href = 'index'; }); HoGoUtils.validateForm('validationPP', HoGoDownload); } /** * Do check valid password */ function doCheckPassword() { $('form#validationPP').find('.formErrorContent').css('white-space', 'nowrap'); if (!HoGoDownload.fStatus) { return false; } var postData = {}; postData["PID"] = packageID; postData["password"] = $("#Password").val(); return $.ajax({ type: "POST", url: "ValidateLinkPass", data: postData, dataType: "json", success: function (data) { var status = data.status; if (status === "Invalid") { $("#errormgs").html(i18n.t('password.message.invalid_password')); $("#errormgs").show(); } else { //show info of package showViewDownloadPage(); Modal.closeModal(); } } }); } /** * Display view depend method number * @returns {undefined} */ function showViewDownloadPage() { var packageOption = packInfo.package_option; var OS = BEObj.getOS2(); if (packageOption === 2 && $.inArray(OS, supportedOSView) === -1) { Modal.showAlert({ title: "Unsupported OS", content: "This package allows view document oline only. Only support Windows, Mac" }); return; } // Render infomation var method = packInfo.package_type, exprDate = packInfo.link_expiry_date; if (new Date(exprDate).getFullYear() === 9999) exprDate = i18n.t('download.label.not_available'); // N/A $('#userName').html(packInfo.last_name + ' ' + packInfo.first_name); $('#exprDate').text(exprDate); $('#createDate').text(packInfo.create_date); // Display required information based on method & current language if (HoGoUtils.detectBrowserLang() === 'ja') { // $('#downloadInfoJapanese, #download160, #download161').removeClass('hid'); $.get("Script/downloadpdf/ja_description.html", function (data) { $('#download_construction').append(data); }); } else { // $('#downloadInfoEnglish, #download25, #download24').removeClass('hid'); // Load eng template $.get("Script/downloadpdf/en_description.html", function (data) { $('#download_construction').append(data); }); } $('#lbFrom1').text(i18n.t('download.label.label_from_1')); $('#lbFrom2').text(i18n.t('download.label.label_from_2')); // Draw list drawResponsiveListDocument(); } /** * Append data on document list in new responsive UI * @returns {undefined} */ function drawResponsiveListDocument() { var packageOption = parseInt(packInfo.package_option); var OS = BEObj.getOS2(); var contentList = ""; // Start draw $.each(docList, function (i, value) { console.log("packInfo.package_option :", value); var ft = HoGoUtils.getExtFromFileType(value.type); switch (parseInt(packInfo.package_type)) { case HoGoConst.WIZARD_CREATE_LINK_TYPE: contentList += '
' + '
' + '' + '
' + '
' + '
' + '' + '
' + '
' + '
' + '
' + '' + '
' + '
' + '' + value.title + '' + '
' + '
' + '
' + '
' + '' + '
' + '
' + '' + value.description + '' + '
' + '
' + '
' + '
' + '' + '
' + '
' + '' + bytesToSize(value.file_size) + '' + '
' + '
' + '
' + '
' + '' + i18n.t('download.buttons.download') + '' + '' + '' + '
' + '
' + '
' + '' + '
' + '
' + '
' + '
' + '' + '
' + '
' + '' + value.title + '' + '
' + '
' + '
' + '
' + '' + '
' + '
' + '' + value.description + '' + '
' + '
' + '
' + '
' + '' + '
' + '
' + '' + bytesToSize(value.file_size) + '' + '
' + '
' + '
' + '
' + '' + i18n.t('download.buttons.download') + '' + ' if (queueDocumentDownload.length > 0) { //Enable DTUtils.fnEnableControl(lEnableButton); } else { //Disable DTUtils.fnDisableControl(lDisableButton); } }); $('#cbo_selectall').on('click', function () { selectAllDocument(this, "child", queueDocumentDownload); if (queueDocumentDownload.length > 0) { DTUtils.fnEnableControl(lEnableButton); } else { DTUtils.fnDisableControl(lDisableButton); } }); function selectAllDocument(itself, cbChildName, checkedList, attrName) { var _this = $(itself); $('#downloadContent :checkbox[name=' + cbChildName + ']').prop("checked", _this.prop("checked")); if (_this.prop("checked")) { console.log("checked"); $('#downloadContent :checkbox[name=' + cbChildName + ']').each(function () { var attr = (attrName === undefined || attrName === '') ? $(this).attr("id") : $(this).attr(attrName); if (jQuery.inArray(attr, checkedList) === -1) { checkedList.push(attr);//Add } }); } else { console.log("non checked"); console.log(checkedList); console.log(attrName); console.log(cbChildName); $('#downloadContent :checkbox[name=' + cbChildName + ']').each(function () { var index = (attrName === undefined || attrName === '') ? jQuery.inArray($(this).attr("id"), checkedList) : jQuery.inArray($(this).attr(attrName), checkedList); checkedList.splice(index, 1); //Remove }); } return checkedList; } } /** * Checking support OS then download to HoGo viewer * @param {type} _title * @param {type} _documentID * @param {type} user_id * @returns {undefined} */ function doDownloadContent(_title, _documentID, user_id) { if (!checkSupportPlatform()) return; var OS = BEObj.getOS2(); console.log(OS); // Check block plugin or not if (BEObj.isBookendPluginBlocked() === true && OS !== "Android") { console.log("1"); // Show warning Modal.showAlert({ title: i18n.t('notification.ask_enable_plugin.title'), content: i18n.t('notification.ask_enable_plugin.content') }); } else if (OS !== "iOS" && OS !== "Android" && BEObj.isAdobeReaderPluginInstalled() === false && chromeVersion < chromeVersionLimit) { console.log("2"); Modal.showAlert({ title: i18n.t('notification.ask_enable_plugin.title'), content: i18n.t('notification.ask_enable_plugin.content') }); } // Chrome 42 else if (OS !== "iOS" && OS !== "Android" && chromeVersion >= chromeVersionLimit) { // If in Chrome 42 does not install Adobereder // var adobeReaderVersion=BEObj.getAdobeReaderVersion(true); // if (adobeReaderVersion === ''){ // Modal.showAlert({ // title: i18n.t('notification.ask_enable_plugin.title'), // content: i18n.t('notification.ask_enable_plugin.content') // }); // } // else if(!checkBookendExtension()) console.log("3", isBookendExtensionInstalled); if (!isBookendExtensionInstalled) { console.log("aaaaa"); var installExtentionTitle = "Install Bookend Plug-in Extension"; var installExtentionMessage = "Please install the Bookend Plug-in Extension from here to download your document(s)."; if (HoGoUtils.detectBrowserLang() === 'ja') { installExtentionTitle = "拡張機能が必要です"; installExtentionMessage = "ダウンロードをするためには、Bookend Plug-in Extensionが必要です。 こ こ からインストールしてください。"; } Modal.showAlert({ title: installExtentionTitle, content: installExtentionMessage }); } else { console.log("aaaaa", user_id); // OK to download to viewer checkValidPackageThenDownload(_title, _documentID, false, null, user_id); } } else { console.log("4"); // Do download to viewer checkValidPackageThenDownload(_title, _documentID, false, user_id); } } /** * Initialize HoGo Viewer, then do download to HoGo viewer installed on local PC (DOWNLOAD TO VIEWER) * @param {string}: _title : Document's Title * @param {string}: _accesscode : AccessCode to document */ function doDownloadToViewer(_title, _accesscode, documentId) { // Status submitting = true; if (!packInfo) return; var OS = BEObj.getOS2(); // Get link download to viewer $.when(getLinkDocumentFile(_accesscode, "", documentId, packInfo.package_id)).done(function (link1) { // Check has link or not if (('link' in link1) === false) return; var link = link1.link, linkThumb = link + '_thumb'; // Download software BEObj.setOption({ url_ins_win: "http://bookend.keyring.net/dl/clsw/hogo/bookendsetup_hogo.exe", // Windows url_ins_ios: "http://itunes.apple.com/jp/app/hogo-viewer/id540674502?mt=8", // iOS url_ins_and: "https://play.google.com/store/apps/details?id=net.keyring.hogo", // Android - Offical link: "http://" + _kr_host_hogo + "/dl/android", ins_app_name: "HoGo Viewer", //"bookendDesktop" ins_img_logo: "http://www.hogodoc.com/HoGo/Images/install_logo_hogo.jpg", ins_img_win_dlbtn: "http://www.hogodoc.com/HoGo/Images/install_bt_download_win.jpg" }); // Create some variable var username = packInfo.last_name + ' ' + packInfo.first_name; //$("#userName").val(); // Set time expiry date var download_id = BEObj.createDownloadID(), prinable = packInfo.printable, numberOfPrint = packInfo.number_of_print, date = new Date(Date.parse(packInfo.document_expiry_date)), year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate(), hours = date.getHours(), minutes = date.getMinutes(), folder = packInfo.folder, localCopy = packInfo.local_copies, expiryDate = (year === 9999) ? -1 : BEObj.timeDateToMinute(year.toString(), month.toString(), day.toString(), hours.toString(), minutes.toString()); console.log(numberOfPrint); var options = { AuthKey: [_kr_authkey], ContentsType: "krpdf", ContentsURL: link, ThumbURL: linkThumb, Title: _title, DistributorName: username, Tag: folder, ValidTerm: expiryDate, NumberOfBrowsing: "-1", NumberOfPrinting: numberOfPrint, DownloadablePlatform: "win,ios,android", CustomName: "hogo", RedirectType: 2, MaxSharedDevice: localCopy, GlobalDownloadID: download_id, RedirectInsPage: false, OnSuccess: function ( ) { $.post("api/v1/UpdateDownloadDistributionLink", {"AccessCode": _accesscode, "NewDownloadID": download_id, "BeUserId": user_id, "PackageID": packInfo.package_id}, function (data) { // Submitted submitting = false; } ); } // MinClientVerWin:"2.5.14" }; // Set more option with new type if (link1.type) { if (link1.type === 'KRPDFX') { options.ContentsType = 'krpdfx'; options.MinClientVerWin = '2.5.14'; } } // Do download to viewer BEObj.downloadContents(options); }); } /** * Check valid package with document then do download with specific method {Create Link/ Specific Link} * @param {string}: title Document title * @param {string}: documentID Document's ID * @param {boolean}: isZeroDownload Method 3,4 * @param {object}: btnDownload Button download * @param {string}: beUserId */ function checkValidPackageThenDownload(title, documentID, isZeroDownload, btnDownload, beUserId) { // Check support OS for this feature if (!checkSupportPlatform()) { return; } console.log(beUserId); var postData = {}; postData["PackageID"] = packageID; postData["DocumentID"] = documentID; postData["beUserID"] = beUserId; // is submitting submitting = true; // Call APi check package return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/CheckDownloadLinkValid", data: postData, dataType: "json", success: function (data) { // Done submit submitting = false; // Get access code var accessCode = data.accesscode; if (data.status === "OK") { var OS = BEObj.getOS2(); // Append AC on tag $(btnDownload).attr("ac", accessCode); switch (OS) { case "iOS": if (parseInt(packInfo.package_type) === HoGoConst.WIZARD_CREATE_LINK_TYPE) { doDownloadToViewer(title, accessCode, documentID); } else { window.location = "https://itunes.apple.com/jp/app/hogo-viewer/id540674502?mt=8"; } break; case "Android": // Update in Mobile Download, go to Appstore instead download directly to avoid dublicate license if (parseInt(packInfo.package_type) === HoGoConst.WIZARD_CREATE_LINK_TYPE) { doDownloadToViewer(title, accessCode, documentID); } else { window.location = "https://play.google.com/store/apps/details?id=net.keyring.hogo"; } break; case "Windows": case "Mac": if (isZeroDownload) { // Show pop-up repairing download Modal.showAlert({content: i18n.t('download.message.prepare_download'), closeClickBG: true}); // Get link then download to local device doGetLinkThenDownload(accessCode, btnDownload); } else { if (OS === "Mac") { // Does noe support HoGo Viewer in Mac Modal.showAlert({ title: "Unsupported OS", content: "Only support download to HoGo Viewer in Windows, iOS and Android." }); return false; } else { // Support HoGo Viewer in Windows Only if ((user_id === null || typeof user_id === 'undefined') && (OS === "Windows")) { Modal.showAlert({ title: "Install HoGo Viewer", content: '
Document in this package only can view by HoGo viewer
' + '
Click here to download HoGo Viewer
' }); return false; } else { doDownloadToViewer(title, accessCode, documentID); } } } break; } } else { // Errors var msg = i18n.t('error.unknown'); switch (data.status) { case APIConst.INSUFFICIENT_POINT: msg = i18n.t('download.message.out_of_point'); break; case APIConst.DOCUMENT_EXPIRED: msg = i18n.t('download.message.download_document_expiry'); break; case APIConst.MAX_DOWNLOAD: msg = i18n.t('download.message.reach_max_download'); break; case APIConst.DOWNLOAD_DISABLED: msg = i18n.t('download.message.download_disabled'); break; default: HoGoUtils.writeLog(data.status_desc); //msg = i18n.t('error.unknown'); break; } if (msg) { Modal.showAlert({content: msg}); } } } }); } /** * Button download click for method anonymous {Anonymous} * @param {string}: _title : Document Title * @param {string}: _documentID : Document ID * @param {DOM}: _this : Button download */ function showRegisterBookendPopup(_title, _documentID, _this) { isMultipleDownload = false; if (!checkSupportPlatform('register')) return; // Set value to do on Popup title = _title; docID = _documentID; itself = _this; // Clean error first $('#registerEmailPopup').find(".formError").remove(); var boxpanel = '
' + '
' + 'HoGo' + '
' + '
' + '' + '
' + '' + '
' + '
' + '
'; //If multiple download => just show input email one time console.log(isMultipleDownload); if (isMultipleDownload) isMultiDownloading = true; $(boxpanel).appendTo('body'); var pp = $('#registerEmailPopup'); pp.i18n(); //Show pp.reveal({closeonbackgroundclick: false}); // Submit event pp.find('#downloadDocZero').bind('click', function () { var form = $(this).parents('form'); form.submit(); email = $('#email').val(); checkLicenseBeforeDownload(isMultipleDownload); }); // Keypress enter pp.find('#email').live('keypress', function (e) { if (e.which === 13 || e.keyCode === 13) { var form = $(this).parents('form'); form.submit(); email = $('#email').val(); checkLicenseBeforeDownload(isMultipleDownload); } }); // Cancel event pp.find('.cancel').unbind('click').bind('click', function () { Modal.closeModal(); }); HoGoUtils.validateForm('validationRE', HoGoDownload); } /** * Do register client's email on Bookend then download file directly to PC {Anonymous} * @param {type} listDocDup * @param {type} _documentID * @param {type} _this * @returns {jqXHR|undefined|Boolean} */ function doRegisterEmail(listDocDup, _documentID, _this) { console.log("load user Id: ", user_id); // user_id ==null for fix bugs can't download file pdf on IE because notify limit download at the first time var user_id = null; docID = _documentID; itself = _this; $('form#validationRE').find('.formErrorContent').css('white-space', 'nowrap'); console.log("load user Id sau: ", user_id); if (!HoGoDownload.fStatus) { return false; } else { // Checking if user already install HoGo Viewer but input differrence email //https://gitlab.com/nitsoftware/HoGo1.x_Production/issues/30 // if(user_id!==null || user_id!=='undefined') // { // // In this case recipient already register email in HoGo Viewer // // So we need to check email input with email registed // // If email input = email registed => allow download to Viewer // // If email input != email registed => Show error message "The E-mail address that you entered does not match the E-mail used to register your HoGo Viewer application. Please enter the correct E-mail address." // } // Avoid setting for another button var cBtn = $(itself); // submitting = true; var postData = {}, emailAddress; // If multiple download if (isMultipleDownload) emailAddress = emailDownloadMultiple; else emailAddress = email; postData["EmailAddress"] = emailAddress; // email input postData["PackageID"] = packageID; postData["DocumentID"] = docID; console.log(postData); // Call API for registering return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/RegisterEmailDownload", data: postData, dataType: "json", cache: false, beforeSend: function () { // Close popup Modal.closeModal(); }, success: function (data) { submitting = false; var accessCode = data.accesscode; var currentButton = $("a[docid='" + docID + "']"); var ft = currentButton.attr('f-t'); if (data.status === "OK") { // notify if content owner download => they will have full control of document if (data.is_owner) { HoGoUtils.makeNotifyServer({ "msg": i18n.t('notification.is_content_owner_download'), "autoClose": true, "time": 5000 }); } // Append ac (AccessCode) & e (Email) cBtn.attr("ac", accessCode); cBtn.attr("e", emailAddress); // Check OS var OS = BEObj.getOS2(); console.log("OS SOS SOS :", OS); switch (OS) { case 'iOS': //window.location = "https://itunes.apple.com/jp/app/hogo-viewer/id540674502?mt=8"; updateHistoryAnonymousLink(accessCode, emailAddress, "iOS"); break; case 'Android': //window.location = "https://play.google.com/store/apps/details?id=net.keyring.bookend"; updateHistoryAnonymousLink(accessCode, emailAddress, "Android"); break; case 'Windows': // Detect environment for anonymous link if (ft === "pdf" && user_id !== null && typeof user_id !== 'undefined') { console.log("pdf"); // Update distribution updateHistoryAnonymousLink(accessCode, emailAddress, "Windows"); } else { console.log("non-pdf"); doGetLinkThenDownload(accessCode, cBtn); } break; default: // PC doGetLinkThenDownload(accessCode, cBtn); break; } // delete license duplicate if (listDocDup.length > 0) { var postData = []; $.each(listDocDup, function (key, value) { var id = value.id; if (id === docID) { $.each(value.reps, function (k, v) { postData.push(id + '_' + v.email); }); } }); $.post('api/v1/DeleteLicenseDuplicate', {UserID: packInfo.user_id, PackageId: packageID, Data: postData.join()}, function (data) { if (data.status === 'OK') { } else { HoGoUtils.writeLog(data.status_desc); Modal.showAlert({content: i18n.t('error.unknown')}); } }); } } else { var msg = i18n.t('error.unknown'); switch (data.status) { case APIConst.REGISTER_EMAIL_ERROR: msg = i18n.t('download.message.register_fail'); break; case APIConst.INSUFFICIENT_POINT: msg = i18n.t('download.message.out_of_point'); break; case APIConst.DOCUMENT_EXPIRED: msg = i18n.t('download.message.download_document_expiry'); break; case APIConst.MAX_DOWNLOAD: msg = i18n.t('download.message.reach_max_download'); break; default: HoGoUtils.writeLog(data.status_desc); break; } // Show error Modal.showAlert({content: msg}); } } }); } } /** * Get valid link. Do download then if everything's OK * @param {string} accessCode : AccessCode to access file * @param {DOM} btDownload Button download */ function doGetLinkThenDownload(accessCode, btDownload, isUpdated) { console.log(isUpdated); // Check access code if (accessCode.length !== 32) { Modal.showAlert({ title: 'Invalid content', content: "This file is invalid" }); return false; } // Submitting submitting = true; // Check valid link to get link download return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/GetLinkFileDownload/" + accessCode, dataType: "json", success: function (lData) { // Check valid link // Window browser - Do download directly to local PC if (lData.status === "OK") { // Download file doDownloadFile(lData.link, lData.file_name, btDownload); // Update download history if (!isUpdated) { // Update download history console.log("update history"); $.post('api/v1/UpdateDownloadHistory', {"AccessCode": $(btDownload).attr('ac'), "Email": $(btDownload).attr('e')}, function (data) { Modal.closeModal(); submitting = false; if (data.status !== "OK") HoGoUtils.writeLog(data.status_desc); }); } } else { // Invalid link //Modal.showAlert({content: "We cannot get link for this file. Please check again"}); // HoGoUtils.writeLog(lData.status_desc); // Modal.showAlert({content: i18n.t('error.unknown')}); var msg = i18n.t('error.unknown'); switch (lData.status) { case APIConst.REGISTER_EMAIL_ERROR: msg = i18n.t('download.message.register_fail'); break; case APIConst.INSUFFICIENT_POINT: msg = i18n.t('download.message.out_of_point'); break; case APIConst.DOCUMENT_EXPIRED: msg = i18n.t('download.message.download_document_expiry'); break; case APIConst.MAX_DOWNLOAD: msg = i18n.t('download.message.reach_max_download'); break; default: HoGoUtils.writeLog(lData.status_desc); break; } // Show error Modal.showAlert({content: msg}); } } }); } /** * Download file from Amazone S3 directly * @param {string} link : url * @param {string} fileName : File name * @param {object} _this : DOM button download */ function doDownloadFile(link, fileName, _this) { var fileType = null; if ($(_this).attr('f-t')) { fileType = '&FileType=' + $(_this).attr('f-t'); fileName = trimFileExtention(fileName, $(_this).attr('f-t')); } // // There're 2 method: // - DownloadFile2: Using IOUtils to copy stream to byte. Maybe catch error OutOfMemory but it can avoid catching link of IDM // - DownloadFile: Using traditional method could avoid catching OutOfMemory // var url = 'api/v1/DownloadFile?Link=' + link + '&FileName=' + window.encodeURIComponent(fileName) + fileType; // Call API $.fileDownload(url, { httpMethod: 'get' // prepareCallback: function() { // //prepareDownloadCallBack(_this); // }, // successCallback: function() { // //successCallBackDownload(_this); // // Update history for download // } }); return false; } // Function trim file extention ( file name ) function trimFileExtention(fileName, fileType) { var trimFileType = null; switch (fileType) { case 'pdf': trimFileType = fileName.substr(fileName.length - 4); if (trimFileType === '.pdf') fileName = fileName.slice(0, -4); break; case 'docx': case 'xlsx': case 'pptx': trimFileType = fileName.substr(fileName.length - 5); if (trimFileType === '.docx' || trimFileType === '.xlsx' || trimFileType === '.pptx') fileName = fileName.slice(0, -5); break; } return fileName; } /** * Update history after download using Anonymous * @param {type} accessCode * @param {type} email * @returns {undefined} */ function updateHistoryAnonymousLink(accessCode, email, OS) { return $.ajax({ type: "POST", timeout: HoGoConst.APITimeout, url: "api/v1/UpdateDownloadHistory", data: {"AccessCode": accessCode, "Email": email}, dataType: "json", cache: false, success: function (data) { //Open Hogo Viewer in iOS if (OS === "iOS") { window.location = "https://itunes.apple.com/jp/app/hogo-viewer/id540674502?mt=8"; } else if (OS === "Android") { window.location = "https://play.google.com/store/apps/details?id=net.keyring.hogo"; } else if (OS === "Windows" && data.status === "OK") { var currentButton = $("a[docid='" + docID + "']"); (data.be_user_id === user_id) ? doDownloadToViewer(currentButton.attr('docName'), currentButton.attr('ac'), currentButton.attr('docid')) : doGetLinkThenDownload(accessCode, currentButton, true); } } }); } //Get document function getLinkDocumentFile(accesscode, type, documentId, packageId) { var dfd = $.Deferred(); // var urlContent = ""; var url = ""; if (type === "thumb") { url = "api/v1/GetThumbnailFile/" + accesscode; if (accesscode === 'NotUsed') url = "api/v1/GetThumbnailFile/" + accesscode + "?DocumentID=" + documentId + "&PackageID=" + packageId; } else { url = "api/v1/GetLinkedDocumentFile/" + accesscode; if (accesscode === 'NotUsed') url = "api/v1/GetLinkedDocumentFile/" + accesscode + "?DocumentID=" + documentId + "&PackageID=" + packageId; } $.ajax({ type: "GET", url: url, dataType: "json" }).done(function (data) { if (data.status === 'OK') // urlContent = data.link; dfd.resolve(data); }).error(dfd.reject); return dfd; } /** * multiple download document * @param {type} listDocDup : duplicated license list will be deleted after register email * @param {type} queueDocumentDownloadNotDup : queue docID haven't been duplicated * @returns {undefined} */ function doDownloadAllDocument(listDocDup, queueDocumentDownloadNotDup) { var timeDelayDownload = 2000;// 2 second; var listDocIdDuplicatedDelete = []; // get list documentId have license duplicate if (listDocDup.length > 0) { $.each(listDocDup, function (k, v) { listDocIdDuplicatedDelete.push(v.id); }); } // Include both duplicated and unduplicated docID that are selected to download var queueDocument = $.merge($.merge([], listDocIdDuplicatedDelete), queueDocumentDownloadNotDup); // TODO // for (var i = 0; i < queueDocument.length; i++) { var i = 0; var workerDownload = setInterval(function () { console.log(queueDocument.length, i); if (queueDocument.length > i) { DTUtils.fnDisableControl(lDisableButton); isMultipleDownload = true; // var documentId = queueDocument.shift(); var documentId = queueDocument[i]; var documentTile = $("a[docid='" + documentId + "']").attr("docname"); // Do download base on each each package type switch (parseInt(packInfo.package_type)) { // Create link case HoGoConst.WIZARD_CREATE_LINK_TYPE: // Downloadable if (parseInt(packInfo.downloadable) === 1) { // Download to hogo viewer if (!submitting) { doDownloadContent(documentTile, documentId, ""); } } break; case HoGoConst.WIZARD_SPECIFY_LINK_TYPE: case HoGoConst.WIZARD_ANONYMOUS_TYPE: // Event for buttons zero link // Make sure one download at a time if (parseInt(packInfo.package_type) === HoGoConst.WIZARD_SPECIFY_LINK_TYPE) { // Download directly checkValidPackageThenDownload(documentTile, documentId, true, $("a[docid='" + documentId + "']"), ""); } else { // showRegisterBookendPopup(documentTile,documentId, $("a[docid='"+documentId+"']")); // setTimeout(function(){ doRegisterEmail(listDocDup, documentId, $("a[docid='" + documentId + "']")); console.log("1"); //}, 2000); } break; } i++; } else { clearInterval(workerDownload); DTUtils.fnEnableControl(lEnableButton); isMultipleDownload = false; isMultiDownloading = false; emailDownloadMultiple = ""; queueDocument = new Array(); console.log("2"); } // } }, timeDelayDownload); } /** * fnDownloadAllDocument * @returns {undefined} */ function fnDownloadAllDocument() { var packageType = parseInt(packInfo.package_type); if (packageType === HoGoConst.WIZARD_ANONYMOUS_TYPE) { // Show input email register $('#registerEmailPopup').find(".formError").remove(); var boxpanel = '
' + '
' + 'HoGo' + '
' + '
' + '' + '
' + '' + '
' + '
' + '
'; //If multiple download => just show input email one time $(boxpanel).appendTo('body'); var pp = $('#registerEmailPopup'); pp.i18n(); //Show pp.reveal({closeonbackgroundclick: false}); // Submit event pp.find('#downloadDocZero').bind('click', function () { var form = $(this).parents('form'); form.submit(); isMultipleDownload = true; isMultiDownloading = true; emailDownloadMultiple = $('#email').val(); // check duplicated license checkLicenseBeforeDownload(isMultipleDownload); }); // Keypress enter pp.find('#downloadDocZero').keypress(function (e) { if (e.which === 13 || e.keyCode === 13) { var form = $(this).parents('form'); form.submit(); isMultipleDownload = true; isMultiDownloading = true; emailDownloadMultiple = $('#email').val(); checkLicenseBeforeDownload(isMultipleDownload); } }); // Cancel event pp.find('.cancel').unbind('click').bind('click', function () { Modal.closeModal(); }); HoGoUtils.validateForm('validationRE', HoGoDownload); } else { doDownloadAllDocument([], queueDocumentDownload); } // queueDocumentDownload = []; // $('#cbo_selectall').attr('checked', false); // $('.child-check').attr('checked', false); isMultipleDownload = false; isMultiDownloading = false; emailDownloadMultiple = ""; } /** * Check duplicated license of document before download anonymous * @param {type} isMultipleDownload * @returns {jqXHR} */ function checkLicenseBeforeDownload(isMultipleDownload) { var documens; if (isMultipleDownload) { documens = queueDocumentDownload.toString(); } else documens = docID; return $.post('api/v1/CheckLicenseDuplicate', {UserID: packInfo.user_id, Documents: documens, Recipients: $('#email').val(), PackageId: packageID}, function (data) { if (data.status === 'OK') { if (data.result.length > 0) { WizardCore.showLicenseDuplicatePopup(4, {data: data, listDocId: $.extend([], queueDocumentDownload), isMultipleDownload: isMultipleDownload, fnForMultiDownload: doDownloadAllDocument, fnForDownload: doRegisterEmail}); } else { // for download one document if (!isMultipleDownload) doRegisterEmail([], docID, $("a[docid='" + docID + "']")); else // for download multiple document doDownloadAllDocument([], queueDocumentDownload); } } else { Modal.showAlert({content: i18n.t('error.unknown')}); } }); } // Detect Bookend Chrome extention var isBookendExtensionInstalled = false; function checkBookendExtension() { try { BEObj.isChromeExtensionInstalled({callback: function (result) { isBookendExtensionInstalled = result; }}); } catch (e) { //console.log(e); isBookendExtensionInstalled = false; } } // Detect HOGO Viewer var version = null; var user_id = null; function detectHoGoViewerInstalled() { checkBookendExtension(); var OS = BEObj.getOS2(); if ((OS === "Windows")) { try { // Step 1: Check general function that support plugin try { BEObj.setOption({custom_name: "hogo"}); version = BEObj.getBookendClientVersion(); // console.log("version="+version); user_id = BEObj.getBookendClientInfo("UserID"); // console.log("user_id="+user_id); } catch (e) { } } catch (e) { } } } return { // Form status fStatus: false, init: function () { // Getting required parameter packageID = HoGoUtils.getParameter()["PID"]; if (packageID) { $.post('api/v1/GetPackageDownloadInformation', {PackageID: packageID}, function (data) { if (data.status === 'OK') { $('.opening-panel').addClass('hid'); // Set package packInfo = data.package_download_info; // List document docList = data.list_document; // Detect HOGO Viewer installed or not detectHoGoViewerInstalled(); if (packInfo.password) { // Show check valid password popup showCheckPasswordPopup(); } else { // Get package information for download page showViewDownloadPage(); } } else { //There's an error //window.location.href = 'ErrorNotice?error=' + data.status; ErrorNotice.drawErrorView(data.status); $('.opening-panel').addClass('hid'); $('section, aside').addClass('hid'); $('#contents_inner').removeClass('hid'); $('.checkbox').addClass('hid'); $('#btDownloadAll').addClass('hid'); } }); $("#primaryNav").hide(); replaceURLJapanseVersion(); $(".btn-slide").click(function () { $("#panel").slideToggle("fast"); $(this).toggleClass("active"); return false; }); } if (i18n.lng() === 'ja') { $('a#btnHome').attr('href', 'http://www.hogodoc.com/ja'); } else { $('a#btnHome').attr('href', 'http://www.hogodoc.com'); } }, setisMultipleDownload: function (value) { isMultipleDownload = value; }, setisMultiDownloading: function (value) { isMultiDownloading = value; }, getisMultipleDownload: function () { return isMultipleDownload; }, getisMultiDownloading: function () { return isMultiDownloading; } }; }(jQuery));