Best JavaScript code snippet using appium-xcuitest-driver
main.js
Source:main.js
1var urlServer_g = "http://apportaalapaz.centrodememoriahistorica.gov.co/MemoriaApp/servidor/";2var urlLandingPage_g = "http://www.centrodememoriahistorica.gov.co/memoriapp/";3// var urlServer_g = "http://localhost/MemoriApp/servidor/";4var DBSize_g = 200000;//bytes5var wholeSelRectEl_g = null;6var startSelEl_g, endSelEl_g;7var workingDirEntry_g;8var sWorkingDir_g = ".MemoriAPP/";9var epubDirEntryPath_g;10var tempDirEntry_g;11var event_global ;12var range_g;13var startSelect_g = 0;14var selectionString_g;15var Book_g;16var firstRun_g = true;17var bookTitle_g = "";18var bookURL_g = "";19var downloadEpubUrl_g = "";20var epubId_g = 0;21var alertDebug = 0;22var handleMoving_g = 0;23var color_background="";24var bookElement_g;25var bookFavoritesElement_g;26var coleccion_g = 1;27var library_g = true;28var favorites_g = false;29var searchString_g = "";30var lastPage_g = 0;31var currentChapter_id="";32var load_fragmento_g=false;33var cfi_fragmento_g="";34var percentaje_fragmento_g="";35var Historial_epub=[];36//constantes para saber desde que pagina se abre el epub37var PAGE_COLLECCION = 1;38var PAGE_LIBRARY = 2;39var PAGE_FAVORITES = 3;40var PAGE_FRAGMENTS = 3;41function backButtonHandler_f(){42// event.preventDefault();43// event.stopPropagation();44 if (Historial_epub.length==0) {45 switch( lastPage_g ){46 case PAGE_COLLECCION:47 viewColeccion_f(coleccion_g);48 break;49 case PAGE_LIBRARY:50 viewLibrary();51 break;52 case PAGE_FAVORITES:53 viewFavorites();54 break;55 case PAGE_FRAGMENTS:56 viewBookmark_f();57 break;58 default:59 viewMain_f();60 }61 }else{62 back_history ();63 }64 65 return false;66}67function getnumbers() {68 var oLibros = JSON.parse( window.localStorage.getItem("libros") );69 $("#number_library").html(_.size(oLibros));70 var oLibros = JSON.parse( window.localStorage.getItem("favoritos") );71 $("#number_favorites").html(_.size(oLibros));72 var oFragmentos = JSON.parse( window.localStorage.getItem("fragmentos") );73 $("#number_fragmentos_menu").html(_.size(oFragmentos));74 //getNumbersfragmentos_f();75}76function resetPage_f(){77 document.removeEventListener("touchmove",preventDefaultScroll_f);78 if( typeof( sharePopover ) != "undefined" ) sharePopover.hide();79 if( typeof( meaningPopover ) != "undefined" ) meaningPopover.hide();80}81function viewMain_f(){82 viewColeccion_f( 1 ); 83}84function viewColeccion_f( coleccion ){85 Modal.show();86 lastPage_g = PAGE_COLLECCION;87 coleccion_g = coleccion;88 menu.setMainPage('main.html', {closeMenu: true});89 resetPage_f();90 getnumbers();91}92function viewLibrary(){93 Modal.show();94 lastPage_g = PAGE_LIBRARY;95 library_g = true;96 menu.setMainPage('main.html', {closeMenu: true});97 resetPage_f();98 getnumbers();99}100function viewFavorites(){101 Modal.show();102 lastPage_g = PAGE_FAVORITES;103 favorites_g = true;104 menu.setMainPage('main.html', {closeMenu: true});105 resetPage_f();106 getnumbers();107}108function viewabout_f(){109 menu.setMainPage('about.html', {closeMenu: true});110 resetPage_f();111}112function viewBookimage_f (element) {113 var buttonTxt = element.getAttribute("buttonTxt");114 ons.notification.confirm({115 message: 'Desea '+buttonTxt.toLowerCase()+' el libro',116 // or messageHTML: '<div>Message in HTML</div>',117 title: '',118 buttonLabels: ['Aceptar', 'Cancelar'],119 animation: 'default', // or 'none'120 primaryButtonIndex: 1,121 cancelable: true,122 callback: function(index) {123 switch(index) {124 case 0:125 viewBook_f( element );126 case 1:127 128 break;129 }130 }131 });132}133function viewBook_f( element ){134 downloadEpubUrl_g = urlServer_g + "uploads/epub/" + element.getAttribute("epub");135 bookElement_g = element;136 bookFavoritesElement_g = element;137 epubId_g = element.getAttribute("epubId");138 bookTitle_g = element.getAttribute("title");139 bookURL_g = element.getAttribute("bookURL");140 menu.setMainPage('epub_viewer.html', {closeMenu: true, callback: starting});141 document.addEventListener("touchmove",preventDefaultScroll_f);142}143// function viewBookmark_f(){144// lastPage_g = PAGE_FRAGMENTS;145// menu.setMainPage('bookmark.html', {closeMenu: true, callback: function(){146// var db = window.openDatabase("memoriappDB", "1.0", "fragmentos", DBSize_g);147// db.transaction(listFragmentosDB_f, onError_f);148// }});149// resetPage_f();150// }151// function getNumbersfragmentos_f(){152// var db = window.openDatabase("memoriappDB", "1.0", "fragmentos", DBSize_g);153// db.transaction(NumbFragmentosDB_f, onError_f);154// }155// function NumbFragmentosDB_f(tx){156// createTableFragmentDB_f(tx);157// tx.executeSql('SELECT * FROM fragmentos', [],function(tx, results){//success158// $("#number_fragmentos_menu").html(results.rows.length);159// }, onError_f);160// }161/* This code prevents users from dragging the page (IOS fix) */162var preventDefaultScroll_f = function( event ) {163 event.preventDefault();164 window.scroll(0,0);165 return false;166};167function starting(){168 rangy.init();169 carousel.on('overscroll', function(event){170 if (handleMoving_g === 0 && startSelect_g === 0) {171 if (event.direction == "right"){172 nextPage();173 }174 if (event.direction == "left"){175 prevPage();176 }177 }178 });179 if (firstRun_g){ //evitar amarrar el mismo evento varias veces180 firstRun_g = false;181 // declaracion de handle de comienzo de seleccion182 startSelEl_g = document.createElement("img");183 startSelEl_g.id = "startSelection";184 startSelEl_g.src = "img/select_handle_left.png";185 // startSelEl_g = document.createElement("div");186 // startSelEl_g.id = "startSelection";187 // startSelEl_g.innerHTML = " ^ ";188 $(document).on('touch', '#startSelection', beginHandleMove);189 $(document).on('touchmove', '#startSelection', handleMove);190 $(document).on('release', '#startSelection', handleRelease);191 //declaracion de handle de final de seleccion192 endSelEl_g = document.createElement("img");193 endSelEl_g.id = "endSelection";194 endSelEl_g.src = "img/select_handle_right.png";195 // endSelEl_g = document.createElement("div");196 // endSelEl_g.id = "endSelection";197 // endSelEl_g.innerHTML = " ^ ";198 $(document).on('touch', '#endSelection', beginHandleMove);199 $(document).on('touchmove', '#endSelection', handleMove);200 $(document).on('release', '#endSelection', handleRelease); 201 //***************************************202 //** POPOVERs203 //***************************************204 //popover para redes sociales205 ons.createPopover('share-popover.html').then(function(){206 sharePopover.on("postshow", function(e){207 var pop = $('#share-popover')[0];208 var mask = pop.children[0];209 mask.style.zIndex = -1;210 });211 });212 ons.createPopover('meaning-popover.html').then(function(){213 meaningPopover.on("preshow", function(e){214 var pop = $('#meaning-popover')[0];215 var mask = pop.children[0];216 mask.style.zIndex = -1;217 });218 });219 ons.createDialog( 'Dialog_copiado.html' );220 ons.createDialog( 'Dialog_descargando.html' );221 222 //*********** DESACTIVADO DEL SWIPE Y SELECCION *******************223 $(document).on('hold', '#area', function(e) {224 startSelect_g = 1;225 e.preventDefault();226 var xSelectStart = e.originalEvent.gesture.center.clientX;227 var ySelectStart = e.originalEvent.gesture.center.clientY;228 console.log("hold area");229 wordSelectionFromPoint(xSelectStart, ySelectStart);230 });231 $(document).on('release', '#area', function(e) {232 if ( startSelect_g === 0 ){233 if (color_background!="") {234 paint_bookmarks();235 };236 handleMoving_g = 0;237 sharePopover.hide();238 meaningPopover.hide();239 240 241 //console.log('hide');242 }else{243 //console.log('no hide');244 }245 });246 $(document).on('touchstart', '#area', function(e) {click_detect (e)});247 ons.orientation.on('change', function( e ){248 setTimeout(alignEPUBRotation_f, 1000);249 });250 }251 //verificar si el EPUB se ha bajado antes252 var oLibros = JSON.parse( window.localStorage.getItem( "libros" ) );253 if( oLibros !== null ){254 var oLibro = oLibros[ epubId_g ];255 if( oLibro !== undefined ){256 modalEpub.show();257 openEPUB_f( workingDirEntry_g.toURL() + "epub/" + oLibro.id + ".epub" );258 }else{259 downloadEPUB_f(epubId_g, downloadEpubUrl_g);260 }261 }else{262 downloadEPUB_f(epubId_g, downloadEpubUrl_g);263 }264 console.log("starting complete");265// openEPUB_f (cordova.file.applicationDirectory+"www/VIOLACIONES DE DDHH.epub");266}267//*******************************************268//** Descarga y lectura de EPUBs269//*******************************************270function alignEPUBRotation_f (){271 var isPortrait = ons.orientation.isPortrait();272 var iframe = $('iframe')[0];273 var area = $('#area')[0];274 if (isPortrait){275 if (document.body.clientWidth > document.body.clientHeight){276 iframe.style.width = document.body.clientHeight* 1.0 + "px";277 iframe.style.height = area.clientWidth* 1.0 + "px";278 }else{ 279 iframe.style.width = document.body.clientWidth* 1.0 + "px";280 iframe.style.height = area.clientHeight* 1.0 + "px";281 }282 }else{283 if (document.body.clientWidth > document.body.clientHeight){284 iframe.style.width = document.body.clientWidth* 1.0 + "px";285 iframe.style.height = area.clientHeight* 1.0 + "px";286 }else{ 287 iframe.style.width = document.body.clientHeight* 1.0 + "px";288 iframe.style.height = area.clientWidth* 1.0 + "px";289 }290 }291 removeSelectionIndicators();292}293function downloadEPUB_f(id, URI){294 modalDownload.show();295 var ft = new FileTransfer();296 // if (alertDebug == 1) alert ("begining download");297 ft.download(298 URI,299 workingDirEntry_g.toURL() + "epub/" + id + ".epub",300 function (entry) {//success download301 console.log("download complete: " + entry.fullPath);302 saveEPUBinStorage_f( id );303 modalEpub.show();304 modalDownload.hide();305 openEPUB_f (workingDirEntry_g.toURL() + "epub/" + id + ".epub");306 },307 function(error) {//error download308 // switch(error.code){309 // default:310 console.log('Error downloading file ' + ': ' + error.code);311 console.log("download error source " + error.source);312 console.log("download error target " + error.target);313 console.log("download error code" + error.code);314 // }315 // onError_f(error);316 },317 false,318 { headers: {"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="} }319 );320} 321function openEPUB_f( epubFile ){322 var tempdir;323 if ( device.platform == "Android" ){324 tempdir = workingDirEntry_g.toURL() + "tempepub/" ;325 }else{326 tempdir = epubDirEntryPath_g + "tempepub/" ;327 }328 window.resolveLocalFileSystemURL(329 tempdir,330 function(dirEntry){331 dirEntry.removeRecursively(332 function(){//success remove333 unzip_f(epubFile, tempdir);334 },335 function(){//fail remove336 unzip_f(epubFile, tempdir);337 }338 );339 },340 function(){//fail resolveLocalFileSystemURL341 unzip_f(epubFile, tempdir);342 }343 );344}345//open_webbrowserepub("epub/")346//347function open_webbrowserepub(destDir){348 Book_g = ePub(349 destDir,350 { style: 'img { width: 100px;}', spreads: false });351 Book_g.renderTo('area').then(function (){352 var iframe = $("iframe")[0];353 var cssLink = document.createElement("link");354 cssLink.href = "styles/epub_image.css"; 355 cssLink.rel = "stylesheet"; 356 cssLink.type = "text/css";357 iframe.contentDocument.body.appendChild(cssLink);358 load_last_visited_page ();359 alignEPUBRotation_f(); 360 });361 // Book_g.on("renderer:locationChanged", function(cfi) {362 // pageChanged(cfi);363 // });364}365function unzip_f(epubFile, destDir){366 zip.unzip(367 epubFile,368 destDir, 369 function ( ret ){//zip callback370 if (ret === 0){371 Book_g = ePub(372 destDir,373 { style: 'img { width: 100px;}', spreads: false }374 );375 Book_g.renderTo('area').then(function (){376 var iframe = $("iframe")[0];377 var cssLink = document.createElement("link");378 cssLink.href = cordova.file.applicationDirectory+"www/styles/epub_image.css"; 379 cssLink.rel = "stylesheet"; 380 cssLink.type = "text/css";381 iframe.contentDocument.body.appendChild(cssLink);382 //modalEpub.hide();383 load_last_visited_page ();384 alignEPUBRotation_f(); 385 386 });387 Book_g.on("renderer:locationChanged", function(cfi) {388 pageChanged(cfi);389 });390 391 }else{392 alert("Error al abrir el EPUB.");393 }394 },395 null //progress callback396 );397}398//***********************************************399//** Inicialización para manejo del sistema de archivos en phonegap400//**********************************************401$( document ).ready(function() {402 document.addEventListener("deviceready", onDeviceReady, false);403});404function onDeviceReady() {405 splash_f();406 yepnope({407 test : window.device.platform === 'iOS' && parseFloat(window.device.version) === 7.0,408 yep : 'styles/ios7.css', 409 });410 411 // back button412 ons.disableDeviceBackButtonHandler();413 document.addEventListener("backbutton", backButtonHandler_f, false);414 // CREAR ESTRUCTURA DE DIRECTORIOS415 var epubDirEntry;416 if (device.platform == "Android"){417 epubDirEntry = cordova.file.externalRootDirectory;418 window.resolveLocalFileSystemURL(419 epubDirEntry,420 function(dirEntry){421 if (alertDebug == 1){422 alert(dirEntry.toURL());423 }424 dirEntry.getDirectory(425 "Android/",426 {create: true},427 function(dirEntry){428 if (alertDebug == 1){429 alert(dirEntry.toURL()); 430 }431 dirEntry.getDirectory(432 "data/",433 {create: true},434 function(dirEntry){435 if (alertDebug == 1){436 alert(dirEntry.toURL());437 }438 dirEntry.getDirectory(439 sWorkingDir_g,440 {create: true},441 function(dirEntry){442 if (alertDebug == 1){443 alert(dirEntry.toURL());444 }445 workingDirEntry_g = dirEntry;446 dirEntry.getDirectory(447 "epub/",448 {create: true},449 function(dirEntry){450 if (alertDebug == 1){451 alert(dirEntry.toURL());452 }453 epubDirEntryPath_g = dirEntry.toURL();454 },455 onError_f456 );457 },458 onError_f459 );460 },461 onError_f462 );463 },464 onError_f465 );466 },467 onError_f468 );469 }else{470// window.plugin.statusbarOverlay.hide();471 epubDirEntry = cordova.file.dataDirectory ;472 window.resolveLocalFileSystemURL(473 epubDirEntry, 474 function(dirEntry){475 dirEntry.getDirectory(476 sWorkingDir_g,477 {create: true},478 function(dirEntry){479 window.resolveLocalFileSystemURL(480 epubDirEntry+sWorkingDir_g, 481 function(dirEntry){482 if (alertDebug == 1) 483 alert(dirEntry.toURL());484 workingDirEntry_g = dirEntry;485 dirEntry.getDirectory(486 "epub/",487 {create: true},488 function(dirEntry){489 if (alertDebug == 1) 490 alert(dirEntry.toURL());491 epubDirEntryPath_g = cordova.file.documentsDirectory+"/";492 },493 onError_f494 );495 },496 onError_f);497 },498 onError_f499 );500 },501 onError_f502 );503 504 }505 console.log("onDeviceReady complete");506 507}508function splash_f(){509 var div = document.createElement("div");510 div.id = "splashDiv";511 div.style.position = "absolute";512 div.style.top = "0";513 div.style.left = "0";514 div.style.width = "100%";515 div.style.height = "100%";516 div.style.backgroundColor = "#02D1BD";517 var img = document.createElement("img");518 img.style.display = "block";519 img.style.marginLeft = "auto";520 img.style.marginRight = "auto";521 img.style.opacity = "0";522 img.style.height = "100%";523 //img.style.width = "100%";524 if ( document.body.clientHeight < 481 ){525 img.src = "img/splash/logos/splash230x480.png";526 }else if ( document.body.clientHeight < 961 ){527 img.src = "img/splash/logos/splash480x960.png";528 }else if ( document.body.clientHeight < 1137 ){529 img.src = "img/splash/logos/splash640x1136.png";530 }else{531 img.src = "img/splash/logos/splash966x1715.png";532 }533 //img.src = "img/splash/logos/splash768x1724.png";534 div.appendChild(img);535 document.body.appendChild( div );536 setTimeout( function(){537 navigator.splashscreen.hide();538 TweenMax.to(539 img, 540 3,541 {opacity: 1.0, force3D: true , onComplete: 542 function(){543 setTimeout( function(){544 document.body.removeChild( document.getElementById("splashDiv") );545 }, 1000);546 }547 }548 );549 }, 1000 );550}551function onError_f(e){552 alert(e);553 console.log(e);554}555// ********************** 556// ** EPUB NAVIGATION 557// ***********************558function nextPage(){559 var ePage = document.getElementsByTagName("iframe")[0];560 var winWidth = $(window).width();561 TweenMax.fromTo(562 ePage, 563 0.3,564 {x: winWidth , force3D:true},565 {x: 0, force3D:true, onStart:function(){ epubNextPage(); } } 566 );567}568function prevPage(){569 var ePage = document.getElementsByTagName("iframe")[0];570 var winWidth = $(window).width();571 TweenMax.fromTo(572 ePage, 573 0.3, 574 {x: -winWidth , force3D:true}, 575 {x: 0 , force3D:true ,onStart:function(){ epubPrevPage(); } }576 );577 578}579function epubNextPage(){580 Book_g.nextPage().then(581 function (){582 var iframe = $('iframe')[0];583 var cssLink = document.createElement("link");584 cssLink.href = cordova.file.applicationDirectory+"www/styles/epub_image.css"; 585 cssLink.rel = "stylesheet"; 586 cssLink.type = "text/css"; 587 iframe.contentDocument.body.appendChild(cssLink);588 //detecta un capitulo nuevo y carga resaltados guardados589 if (currentChapter_id!==Book_g.currentChapter.id) {590 591 load_rects_chapter(epubId_g,Book_g.currentChapter.id );592 currentChapter_id=Book_g.currentChapter.id;593 };594 595 }596 );597}598function epubPrevPage(){599 Book_g.prevPage().then(600 function (){601 var iframe = $('iframe')[0];602 var cssLink = document.createElement("link");603 cssLink.href = cordova.file.applicationDirectory+"www/styles/epub_image.css"; 604 cssLink.rel = "stylesheet"; 605 cssLink.type = "text/css"; 606 iframe.contentDocument.body.appendChild(cssLink);607 //detecta un capitulo nuevo608 if (currentChapter_id!==Book_g.currentChapter.id) {609 load_rects_chapter(epubId_g,Book_g.currentChapter.id );610 currentChapter_id=Book_g.currentChapter.id;611 };612 }613 );614}615//********************************616//*********** RANGY *****************617//******************************618function wordSelectionFromPoint(startX, startY) {619 console.log('wordSelectionFromPoint');620 var iframe = document.getElementsByTagName('iframe')[0];621 var iframePos = getPosition(iframe);622 startX -= iframePos.x;623 startY -= iframePos.y;624 625 var doc = iframe.contentDocument || iframe.contentWindow.document;626 627 var text;628 var start, end;629 if (typeof doc.caretPositionFromPoint != "undefined") {630 start = doc.caretPositionFromPoint(startX, startY);631 end = doc.caretPositionFromPoint(startX, startY);632 range_g = doc.createRange();633 range_g.setStart(start.offsetNode, start.offset);634 range_g.setEnd(end.offsetNode, end.offset);635 } else if (typeof doc.caretRangeFromPoint != "undefined") {636 start = doc.caretRangeFromPoint(startX, startY);637 range_g = doc.createRange();638 range_g.setStart(start.startContainer, start.startOffset);639 range_g.setEnd(start.startContainer, start.startOffset);640 }641 // buscar inicio de palabra642 var i = 0;643 for (i = 0; i< 100 && range_g.startOffset >0; i++){644 text = range_g.toString();645 if (text.charAt(0) == " "){646 range_g.setStart(range_g.startContainer, range_g.startOffset +1 );647 break;648 }else{649 range_g.setStart(range_g.startContainer, range_g.startOffset -1 );650 }651 }652 // buscar final de palabra653 for (i = 0; i< 100; i++){654 text = range_g.toString();655 if (text.charAt(text.length -1) == " " ){656 range_g.setEnd(range_g.endContainer, range_g.endOffset -1 );657 break;658 }else if (range_g.endContainer.length == range_g.endOffset ){659 range_g.setEnd(range_g.endContainer, range_g.endOffset );660 break;661 }else{662 range_g.setEnd(range_g.endContainer, range_g.endOffset +1 );663 }664 }665 // seleccionar el rango666 selectRange(startX,startY,0,0,iframe,doc);667 meaningPopover.show('.wholeSelection');668 669}670//coordenadas del elemento con respecto al documento (absolutas)671function getPosition(element) {672 var xPosition = 0;673 var yPosition = 0;674 675 while(element) {676 xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);677 yPosition += (element.offsetTop - element.scrollTop + element.clientTop);678 element = element.offsetParent;679 }680 return { x: xPosition, y: yPosition };681}682function removeSelectionIndicators() {683 console.log('removeSelectionIndicators');684 685 $(document).off('touch', '#area', removeSelectionIndicators);686 if (wholeSelRectEl_g !== null) {687 wholeSelRectEl_g.parentNode.removeChild(wholeSelRectEl_g);688 startSelEl_g.parentNode.removeChild(startSelEl_g);689 endSelEl_g.parentNode.removeChild(endSelEl_g);690 wholeSelRectEl_g = null;691 startSelect_g = 0;692 }693 console.log(startSelect_g);694}695//Mostrar todos los indicadores de la seleccion (sombreado y handles)696function showSelectionPosition() {697 console.log('showSelectionPosition');698 // carousel1 es el elemento del DOM que va contener los indicadores de seleccion699 var carousel1 = $("#carousel-1")[0];700 var iframe = $("iframe")[0];701 var iframePos = getPosition(iframe);702 var iframeX = iframe.parentNode.offsetLeft;703 var iframeY = iframe.parentNode.offsetTop;704 var selRects = rangy.getSelection(iframe).getRangeAt(0).nativeRange.getClientRects();705 706 rangy_Andres=rangy.getSelection(iframe).getRangeAt(0);707 //console.log(rangy.serializeRange(rangy_Andres,null,iframe));708 removeSelectionIndicators();709 710 showSelectionRects(selRects, carousel1);711 712 // Draw elements at the start and end of the selection713 // var startPos = rangy.getSelection(iframe).getStartDocumentPos();714 var startPos = { 715 x : $(".wholeSelection")[0].offsetLeft,716 y : $(".wholeSelection")[0].offsetTop+ $(".wholeSelection")[0].offsetHeight,717 };718 carousel1.appendChild(startSelEl_g);719 startSelEl_g.style.left = startPos.x - ((startSelEl_g.offsetWidth*3)/4) + "px";720 // startSelEl_g.style.left = startPos.x+iframeX - (startSelEl_g.offsetWidth/2) + "px";721 // startSelEl_g.style.top = startPos.y+iframeY - startSelEl_g.offsetHeight + "px";722 startSelEl_g.style.top = startPos.y - 3 + "px";723 var endPos = rangy.getSelection(iframe).getEndDocumentPos();724 carousel1.appendChild(endSelEl_g);725 endSelEl_g.style.left = (endPos.x+iframeX ) - (endSelEl_g.offsetWidth/4) + "px";726 endSelEl_g.style.top = (endPos.y+iframeY ) - 3 + "px";727 728// sharePopover.show('.wholeSelection');729 $(document).on('touch', '#area', removeSelectionIndicators);730}731//Sombreado de texto seleccionado (solucion para problema IOS)732function showSelectionRects(selRects, element){733 console.log('showSelectionRects')734 var iframe = $("iframe")[0];735 var iframePos = getPosition(iframe);736 var iframeX = iframe.parentNode.offsetLeft;737 var iframeY = iframe.parentNode.offsetTop;738 var i = 0;739 var rect;740 wholeSelRectEl_g = document.createElement("div");741 wholeSelRectEl_g.id = "wholeselection";742 for ( i = 0; i< selRects.length; i++){743 rect = document.createElement("div");744 rect.className = "wholeSelection "+color_background;745 rect.style.left = selRects[i].left+iframeX + "px";746 rect.style.top = selRects[i].top+iframeY + "px";747 rect.style.width = selRects[i].width + "px";748 rect.style.height = selRects[i].height + "px";749 wholeSelRectEl_g.appendChild(rect);750 }751 element.appendChild(wholeSelRectEl_g);752}753function beginHandleMove(e){754 handleMoving_g = 1;755}756function handleMove(e) { 757 event_global = e; // solo para debug758 759 var iframePos;760 e.preventDefault();761 if (handleMoving_g == 1){762 var iframe = $("iframe")[0];763 iframePos = getPosition(iframe);764 if (e.target.id == "startSelection"){765 e.target.style.left = ( e.originalEvent.targetTouches[0].clientX - ((e.target.offsetWidth)/4)) + "px";766 e.target.style.top = ( e.originalEvent.targetTouches[0].clientY - (e.target.offsetHeight * 1.5)) + "px";767 }else{768 e.target.style.left = ( e.originalEvent.targetTouches[0].clientX - ((e.target.offsetWidth * 3)/4)) + "px";769 e.target.style.top = ( e.originalEvent.targetTouches[0].clientY - (e.target.offsetHeight * 1.5)) + "px";770 }771 }772 return false;773}774function handleRelease(e) { 775 var iframe = document.getElementsByTagName('iframe')[0];776 var endX = endSelEl_g.offsetLeft - iframe.offsetLeft + (endSelEl_g.offsetWidth/4);777 var endY = endSelEl_g.offsetTop - iframe.offsetTop -iframe.parentNode.offsetTop-2;778 var startX = startSelEl_g.offsetLeft - iframe.offsetLeft + ((startSelEl_g.offsetWidth*3)/4);779 var startY = startSelEl_g.offsetTop - iframe.offsetTop -iframe.parentNode.offsetTop -2;// + (startSelEl_g.offsetHeight) ;780 781 // endX -= iframe.offsetLeft;782 // endY -= iframe.offsetTop;783 var doc = iframe.contentDocument || iframe.contentWindow.document;784 785 var start, end;786 if (typeof doc.caretPositionFromPoint != "undefined") {787 start = doc.caretPositionFromPoint(startX, startY);788 end = doc.caretPositionFromPoint(endX, endY);789 range_g.setStart(start.offsetNode, start.offset);790 range_g.setEnd(end.offsetNode, end.offset);791 } else if (typeof doc.caretRangeFromPoint != "undefined") {792 start = doc.caretRangeFromPoint(startX, startY);793 end = doc.caretRangeFromPoint(endX, endY);794 range_g.setStart(start.startContainer, start.startOffset);795 range_g.setEnd(end.startContainer, end.startOffset);796 }797 selectRange(startX,startY,endX,endY,iframe,doc);798 meaningPopover.hide();799 sharePopover.show('.wholeSelection');800}801function selectRange(startX,startY,endX,endY,iframe,doc){802 console.log('selectRange');803 var sel;804 if (range_g !== null && typeof iframe.contentWindow.getSelection != "undefined") {805 sel = iframe.contentWindow.getSelection();806 sel.removeAllRanges();807 sel.addRange(range_g);808 console.log('selectRangea');809 // sel.removeAllRanges();810 }else if(typeof doc.body.createTextRange != "undefined") {811 var endRange = range_g.duplicate();812 sel = iframe.contentWindow.getSelection();813 range_g.moveToPoint(startX, startY); 814 endRange.moveToPoint(endX, endY);815 range_g.setEndPoint("EndToEnd", endRange);816 range_g.select();817 console.log('selectRangeb');818 }819 selectionString_g = iframe.contentWindow.getSelection().toString();820 console.log(selectionString_g);821 822 removeSelectionIndicators();823 showSelectionPosition();824 sel.removeAllRanges();825 // selectionString_g = iframe.contentWindow.getSelection().toString();826}827//************************828//** REDES SOCIALES 829//************************830function shareFacebook() {831 if ( device.platform == "Android" ){ //FacebookConnectPlugin832 facebookConnectPlugin.login(833 [ "email" ],834 function( response ) {//success835 showDialogFacebookConnect_f(); 836 },837 function ( response ) {//error838 console.log( JSON.stringify( response ) );839 }840 );841 }else{ //SocialSharing Plugin842 // Beware: passing a base64 file as 'data:' is not supported on Android 2.x: https://code.google.com/p/android/issues/detail?id=7901#c43843 // Hint: when sharing a base64 encoded file on Android you can set the filename by passing it as the subject (second param)844 window.plugins.socialsharing.shareViaFacebook(845 '"'+selectionString_g+'"\n ââ ' + bookTitle_g + '\n ' + bookURL_g, //probar html tags si necesario846 null /* img */, 847 null /*url*/, 848 function() {//success849 console.log( 'share ok' ); 850 }, 851 function( errormsg ){//error852 console.log( errormsg );853 }854 );855 }856 // showDialog();857}858function shareTwitter() {859 //************************************860 //** GENERAR IMAGEN CON TEXTO PARA COMPARTIR861 //************************************862// var canvas = document.createElement("canvas");863// canvas.style.width = "300px";864// canvas.style.height = "1000px";865// var URI = drawText_f ( canvas, '"'+selectionString_g+'"\n ââ ' + bookTitle_g, "12px serif", 10, 25, 280);866 867 // Beware: passing a base64 file as 'data:' is not supported on Android 2.x: https://code.google.com/p/android/issues/detail?id=7901#c43868 // Hint: when sharing a base64 encoded file on Android you can set the filename by passing it as the subject (second param)869 var footText = ". Tomado de libro vÃa #MemoriApp del @CentroMemoriaH";870 // Recortar texto para el tweet 140 - 22(url) = 118871 var maxLength = 118 - footText.length - 6; //tilde?872 var text = '"'+selectionString_g.substring(0,maxLength)+'" '+ footText ;873 874 window.plugins.socialsharing.shareViaTwitter(875 text, /*texto*/876 null,/* img */877 //bookURL_g, /*url*/878 urlLandingPage_g, /*url*/879 function() {//success880 console.log('share ok');881 }, 882 function( errormsg ){ //error883 console.log(errormsg);884 }885 );886}887function shareWhatsapp() {888 window.plugins.socialsharing.shareViaWhatsApp(889 '"'+selectionString_g+'"\n ââ ' + bookTitle_g + '\n ' + bookURL_g, /*texto*/890 null,/* img */891 null, /*url*/892 function() {//success893 console.log('share ok');894 }, 895 function( errormsg ){ //error896 console.log(errormsg);897 }898 );899}900function shareEmail() {901 window.plugins.socialsharing.shareViaEmail(902 '"'+selectionString_g+'"\n ââ ' + bookTitle_g + '\n ' + bookURL_g, /*texto*/903 null,/* img */904 null, /*url*/905 function() {//success906 console.log('share ok');907 }, 908 function( errormsg ){ //error909 console.log(errormsg);910 }911 );912}913function share() {//pruebas914 var canvas = document.createElement("canvas");915 var ctx = canvas.getContext("2d");916 // var ctx = document.getElementById('canvas').getContext('2d');917 ctx.font = "48px serif";918 ctx.fillText(selectionString_g, 10, 50);919 var URI = canvas.toDataURL();920 // console.log(temp);921 // window.plugins.socialsharing.share(null, null, 'https://www.google.nl/images/srpr/logo4w.png', null)">image only</button>922 // Beware: passing a base64 file as 'data:' is not supported on Android 2.x: https://code.google.com/p/android/issues/detail?id=7901#c43923 // Hint: when sharing a base64 encoded file on Android you can set the filename by passing it as the subject (second param)924 // window.plugins.socialsharing.share(null, 'Android filename', URI , "http://www.google.com");925 window.plugins.socialsharing.shareViaFacebookWithPasteMessageHint(926 'Message via Facebook',927 URI /* img */,928 "html://www.google.com/" /* url */,929 'Paste it dude!',930 function() {931 console.log('share ok');932 },933 function(errormsg){934 alert(errormsg);935 }936 );937 938 // window.plugins.socialsharing.shareViaTwitter('Message and link via Facebook', URI /* img */, null /*url*/, function() {console.log('share ok')}, function(errormsg){alert(errormsg)});939 // window.plugins.socialsharing.shareViaFacebook('Message via Facebook', null /* img */, null /* url */, function() {console.log('share ok')}, function(errormsg){alert(errormsg)});940}941function showDialogFacebookConnect_f() {942 943 facebookConnectPlugin.showDialog(944 {945 method: "feed",946 name: '"'+ selectionString_g+'"',947 //link: bookURL_g,948 link: urlLandingPage_g,949 description: bookTitle_g,950 // picture: workingDirEntry_g.toURL() + "asd.png",951 // caption: selectionString_g952 }, 953 function (response) { 954 console.log(JSON.stringify(response)) ;955 },956 function (response) { 957 console.log(JSON.stringify(response));958 }959 );960 961}962var drawText_f = function (canvas, textString, font, x, y, maxWidth){963 var canvasTemp = document.createElement("canvas");964 canvasTemp.width = canvas.width;965 canvasTemp.height = canvas.height;966 var contextTemp = canvasTemp.getContext("2d");967 contextTemp.font = font;968 var x1 = x;969 var y1 = y;970 var j = 0;971 var i = 0;972 var wordEnd = 0;973 var textMetric;974 var substringText ="";975 var textLines;976 // textLines solo se usa para evitar bucles infinitos977 for (j = 0, textLines = 0; i < textString.length && textLines < 30; j = i, textLines++){978 for (i = j; i < textString.length; i++){979 textMetric = contextTemp.measureText(textString.substring(j, i)); // TextMetrics object980 if (textMetric.width > maxWidth){981 i = wordEnd;982 break;983 }984 if (textString.charAt(i) == " " || textString.charAt(i) == "\n"){985 wordEnd = i;986 }987 if (textString.charAt(i) == "\n"){988 i++;989 break;990 }991 }992 substringText = textString.substring(j, i);993 contextTemp.fillText(substringText, x1, y1);994 y1 += 12;995 }996 canvas.height = y1;997 var context = canvas.getContext("2d");998 context.fillStyle= "#ffffff"; // sets color999 context.fillRect(0,0,canvas.width,canvas.height);1000 context.drawImage(canvasTemp, 0,0);1001 1002 var URI = canvas.toDataURL();1003 return URI;1004};1005//**********************************1006//** Compartir libro1007//**********************************1008function shareBookOnWhatsapp() {1009 window.plugins.socialsharing.shareViaWhatsApp(1010 //bookTitle_g + '\n ' + bookURL_g, 1011 bookTitle_g + '\n ' + urlLandingPage_g, 1012 null /* img */,1013 null /*url*/,1014 function() {//success1015 console.log( 'share ok' ); 1016 }, 1017 function( errormsg ){//error1018 console.log( "error: " + errormsg );1019 }1020 );1021}1022function shareBookOnEmail() {1023 window.plugins.socialsharing.shareViaEmail(1024 //bookTitle_g + '\n ' + bookURL_g, //probar html tags si necesario1025 bookTitle_g + '\n ' + urlLandingPage_g, 1026 null /* img */,1027 null /*url*/,1028 function() {//success1029 console.log( 'share ok' ); 1030 }, 1031 function( errormsg ){//error1032 console.log( "error: " + errormsg );1033 }1034 );1035}1036function shareBookOnFacebook() {1037 if ( device.platform == "Android" ){ //FacebookConnectPlugin1038 facebookConnectPlugin.login(1039 [ "email" ],1040 function( response ) {//success1041 showDialogBookOnFacebookConnect_f(); 1042 },1043 function ( response ) {//error1044 console.log( JSON.stringify( response ) );1045 }1046 );1047 }else{ //SocialSharing Plugin1048 window.plugins.socialsharing.shareViaFacebook(1049 bookTitle_g + '\n ' + bookURL_g, //probar html tags si necesario1050 null /* img */, 1051 null /*url*/, 1052 function() {//success1053 console.log( 'share ok' ); 1054 }, 1055 function( errormsg ){//error1056 console.log( errormsg );1057 }1058 );1059 }1060}1061function shareBookOnTwitter() {1062 var footText = ". Libro del @CentroMemoriaH vÃa #MemoriApp.";1063 // Recortar texto para el tweet 140 - 22(url) = 1181064 var maxLength = 118 - footText.length - 6; //tilde?1065 var text = '"'+bookTitle_g.substring(0,maxLength)+'" '+ footText ;1066 window.plugins.socialsharing.shareViaTwitter(1067 text, /*texto*/1068 null, /* img */1069 // bookURL_g, /*url*/1070 urlLandingPage_g, /*url*/1071 function() {//success1072 console.log('share ok');1073 }, 1074 function( errormsg ){ //error1075 console.log(errormsg);1076 }1077 );1078}1079function showDialogBookOnFacebookConnect_f() {1080 1081 facebookConnectPlugin.showDialog(1082 {1083 method: "feed",1084 //link: bookURL_g,1085 link: urlLandingPage_g,1086 name: bookTitle_g,1087 // picture: workingDirEntry_g.toURL() + "asd.png",1088 // caption: selectionString_g1089 }, 1090 function (response) { 1091 console.log(JSON.stringify(response)) ;1092 },1093 function (response) { 1094 console.log(JSON.stringify(response));1095 }1096 );1097 1098}1099//**********************************1100//** Guardado de fragmentos y libros1101//**********************************1102function saveFragment_f(){1103 var oFragmentos = JSON.parse( window.localStorage.getItem("fragmentos") );1104 if( oFragmentos === null) { 1105 oFragmentos = {};1106 var last_id_fragmento= 1;1107 }else{1108 var last_id_fragmento= parseInt(window.localStorage.getItem("last_id_fragmento")) +1;1109 }1110 //Libro, Fragmento, Fecha, epubid, url, percentaje, cfi1111 var date = new Date();1112 //getMonth: el mes es un numero entre 0-111113 var sDate = date.getDate()+"/" + (parseInt(date.getMonth())+1) + "/"+date.getFullYear();1114 var cfi_fragmento=Book_g.getCurrentLocationCfi();1115 var percentaje=Book_g.renderer.currentRenderedPage()/Book_g.renderer.pagesInCurrentChapter();1116 // bookTitle_g+"','"+selectionString_g+"','"+ sDate +"','"+ epubId_g +"','"+ bookURL_g +"','"+ percentaje +"','"+ cfi_fragmento +"')");1117 var oFragmento = {1118 id : last_id_fragmento,1119 Libro : bookTitle_g, 1120 Fragmento : selectionString_g,1121 Fecha : sDate,1122 epubid : epubId_g,1123 url : bookURL_g,1124 percentaje : percentaje,1125 cfi : cfi_fragmento1126 };1127 oFragmentos[last_id_fragmento] = oFragmento ;1128 window.localStorage.setItem("fragmentos", JSON.stringify( oFragmentos ));1129 window.localStorage.setItem("last_id_fragmento", JSON.stringify( last_id_fragmento ));1130 Dialog_fragment_save.show();1131 setTimeout('Dialog_fragment_save.hide()', 2000);1132}/*1133function saveFragment_f(){1134 var db = window.openDatabase("memoriappDB", "1.0", "fragmentos", DBSize_g);1135 db.transaction(saveFragmentDB_f, onError_f, function(){ //success1136 });1137 Dialog_fragment_save.show();1138 setTimeout('Dialog_fragment_save.hide()', 2000);1139 1140}1141function saveFragmentDB_f(tx) {1142 createTableFragmentDB_f(tx);1143 var date = new Date();1144 //getMonth: el mes es un numero entre 0-111145 var sDate = date.getDate()+"/" + (parseInt(date.getMonth())+1) + "/"+date.getFullYear();1146 1147 var cfi_fragmento=Book_g.getCurrentLocationCfi();1148 var percentaje=Book_g.renderer.currentRenderedPage()/Book_g.renderer.pagesInCurrentChapter();1149 tx.executeSql("INSERT INTO fragmentos (Libro, Fragmento, Fecha, epubid, url, percentaje, cfi) VALUES ('"+bookTitle_g+"','"+selectionString_g+"','"+ sDate +"','"+ epubId_g +"','"+ bookURL_g +"','"+ percentaje +"','"+ cfi_fragmento +"')");1150}*/1151//******************************************1152//** Despliegue de fragmentos1153//******************************************1154function viewBookmark_f(){1155 menu.setMainPage('bookmark.html', {closeMenu: true, callback: function(){1156 listFragmentos_f();1157 }});1158}1159function listFragmentos_f(){1160 var oFragmentos = JSON.parse( window.localStorage.getItem("fragmentos") );1161 if( oFragmentos === null) { 1162 oFragmentos = {}; 1163 }1164 var div = document.getElementById("fragment_list");1165 var container = document.getElementById("container_fragmentos");1166 div.removeChild(container);1167 container = document.createElement("div");1168 container.id = "container_fragmentos";1169 $("#number_fragmentos").html(_.size(oFragmentos));1170 for(var index in oFragmentos) { 1171 var id = oFragmentos[index].id;1172 var libro = oFragmentos[index].Libro;1173 var date = oFragmentos[index].Fecha;1174 var fragmento = oFragmentos[index].Fragmento;1175 var item = document.createElement("div");1176 item.id = "fragmento_"+id;1177 var epubid = oFragmentos[index].epubid;1178 var bookURL = oFragmentos[index].url;1179 var title = oFragmentos[index].Libro;1180 var percentaje =oFragmentos[index].percentaje;1181 var cfi_frag =oFragmentos[index].cfi;1182 1183 item.innerHTML = 1184 '<ons-list class="card-bookmark list ons-list-inner list--inset" style="margin-top: 10px">'+1185 '<ons-list-item class="to-wrapper smallfont list__item ons-list-item-inner">'+1186 'Agregado el '+ dateToString_f(date) +1187 '</ons-list-item>'+1188 '<P onclick="load_epub_bookmark (this, \''+cfi_frag+'\')" epubId="'+epubid+'" percentaje="'+percentaje+'" title="'+title+'" style="font-family:\'TitilliumWeb-Italic\';" bookURL="'+bookURL+'">"'+ fragmento +'"</P>'+1189 '<ons-list-item epubId="'+epubid+'" percentaje="'+percentaje+'" title="'+title+'" bookURL="'+bookURL+'" style="line-height:19px" class="to-wrapper smallfont list__item ons-list-item-inner">'+1190 'Tomado de libro <span style="text-decoration: underline;" >'+ libro +'</span>'+1191 '<span onclick="deleteFragmento_f('+ id +');">'+1192 ' <ons-icon icon="ion-trash-a" style="float:right" class="trash ons-icon ons-icon--ion ion-trash-a fa-lg""></ons-icon>'+1193 '</span>'+1194 '</ons-list-item>'+1195 '</ons-list>';1196 container.appendChild(item);1197 }1198 div.appendChild(container);1199 1200}1201// function viewBookmark_f(){1202// menu.setMainPage('bookmark.html', {closeMenu: true, callback: function(){1203// var db = window.openDatabase("memoriappDB", "1.0", "fragmentos", DBSize_g);1204// db.transaction(listFragmentosDB_f, onError_f);1205// }});1206// }1207var dateToString_f = function (date){1208 var splitDate = date.split("/");1209 return splitDate[0] + " de " + monthToString_f(splitDate[1]) + " de " + splitDate[2];1210};1211var monthToString_f = function (nMonth){1212 switch(parseInt(nMonth)){1213 case 1:1214 return "Enero";1215 case 2:1216 return "Febrero";1217 case 3:1218 return "Marzo";1219 case 4:1220 return "Abril";1221 case 5:1222 return "Mayo";1223 case 6:1224 return "Junio";1225 case 7:1226 return "Julio";1227 case 8:1228 return "Agosto";1229 case 9:1230 return "Septiembre";1231 case 10:1232 return "Octubre";1233 case 11:1234 return "Noviembre";1235 case 12:1236 return "Diciembre";1237 default:1238 return "-1";1239 }1240};1241var idFragmentoDB_g;1242// function deleteFragmento2_f(idFragmento){1243// ons.notification.confirm({1244// message: '¿Esta seguro que desea eliminar el fragmento favorito?',1245// // or messageHTML: '<div>Message in HTML</div>',1246// title: 'Eliminar fragmento',1247// buttonLabels: ['Aceptar', 'Cancelar'],1248// animation: 'default', // or 'none'1249// primaryButtonIndex: 1,1250// cancelable: true,1251// callback: function(index) {1252// switch(index) {1253// case 0:1254// idFragmentoDB_g = idFragmento;1255// var db = window.openDatabase("memoriappDB", "1.0", "fragmentos", DBSize_g);1256// db.transaction(1257// deleteFragmentoDB_f,1258// onError_f, 1259// function(){ //success1260// console.log("borrado");1261// var item = document.getElementById("fragmento_"+idFragmento);1262// var container = document.getElementById("container_fragmentos");1263// container.removeChild(item);1264// }1265// );1266// ons.notification.alert({1267// message: 'Fragmento eliminado'1268// });1269// break;1270// case 1:1271 1272// break;1273// }1274// }1275// });1276// }1277function deleteFragmento_f(idFragmento){1278 ons.notification.confirm({1279 message: '¿Esta seguro que desea eliminar el fragmento favorito?',1280 // or messageHTML: '<div>Message in HTML</div>',1281 title: 'Eliminar fragmento',1282 buttonLabels: ['Aceptar', 'Cancelar'],1283 animation: 'default', // or 'none'1284 primaryButtonIndex: 1,1285 cancelable: true,1286 callback: function(index) {1287 switch(index) {1288 case 0: 1289 removeFragmentofromLocalStorage_f( idFragmento );1290 console.log("borrado");1291 var item = document.getElementById("fragmento_"+idFragmento);1292 var container = document.getElementById("container_fragmentos");1293 container.removeChild(item);1294 ons.notification.alert({1295 message: 'Fragmento eliminado'1296 });1297 break;1298 case 1:1299 1300 break;1301 }1302 }1303 });1304}1305function removeFragmentofromLocalStorage_f( id ){1306 var oFragmentos = JSON.parse( window.localStorage.getItem("fragmentos") );1307 if( oFragmentos === null) {1308 oFragmentos = {};1309 }1310 oFragmentos[ id ] = undefined ;1311 window.localStorage.setItem("fragmentos", JSON.stringify( oFragmentos ));1312 getnumbers();1313}1314//******************************************1315//** Guardado de Favoritos1316//******************************************1317function addBookFavorites( element ){1318 var img = element.childNodes[0];1319 console.log( img.src );1320 if ( img.getAttribute( "src" ) == "img/estrella.png" ){1321 // agregar a favoritos1322 bookFavoritesElement_g = element;1323 saveEPUBinFavorites_f();1324 ons.notification.alert({1325 title : 'Mensaje',1326 message : 'El libro se ha agregado a favoritos',1327 buttonLabel : 'Aceptar',1328 });1329 img.src = "img/estrella2.png";1330 getnumbers();1331 }else{1332 //borrar de favoritos1333 ons.notification.confirm({1334 title : '¡Alerta!',1335 message : '¿Está seguro que desea eliminar el libro de sus favoritos?',1336 buttonLabels: ['Si', 'No'],1337 callback: function(idx) {1338 switch(idx) {1339 case 0://si1340 var oLibros = JSON.parse( window.localStorage.getItem("favoritos") );1341 var epubId = element.getAttribute("epubId");1342 if( oLibros === null) {1343 oLibros = {};1344 }1345 oLibros[ epubId ] = undefined ;1346 window.localStorage.setItem("favoritos", JSON.stringify( oLibros ));1347 img.src = "img/estrella.png";1348 getnumbers();1349 break;1350 case 1://no1351 break;1352 }1353 }1354 });1355 1356 }1357}1358function saveEPUBinFavorites_f(){1359 var oLibros = JSON.parse( window.localStorage.getItem("favoritos") );1360 if( oLibros === null) { 1361 oLibros = {};1362 }1363 var oLibro = {1364 description : bookFavoritesElement_g.getAttribute("description"), 1365 title : bookFavoritesElement_g.getAttribute("title"),1366 img : bookFavoritesElement_g.getAttribute("img"),1367 epub : bookFavoritesElement_g.getAttribute("epub"),1368 id : bookFavoritesElement_g.getAttribute("epubId"),1369 epubId : bookFavoritesElement_g.getAttribute("epubId"),1370 bookURL : bookFavoritesElement_g.getAttribute("bookURL"),1371 star_img :"img/estrella2.png",1372 };1373 oLibros[ bookFavoritesElement_g.getAttribute("epubId") ] = oLibro ;1374 window.localStorage.setItem("favoritos", JSON.stringify( oLibros ));1375}1376//******************************************1377//** Guardado de EPUBs1378//******************************************1379function saveEPUBinStorage_f( id ){1380 var oLibros = JSON.parse( window.localStorage.getItem("libros") );1381 if( oLibros === null) {1382 oLibros = {};1383 }1384 var oLibro = {1385 description : bookElement_g.getAttribute("description"), 1386 title : bookElement_g.getAttribute("title"),1387 img : bookElement_g.getAttribute("img"),1388 epub : bookElement_g.getAttribute("epub"),1389 id : bookElement_g.getAttribute("epubId"),1390 epubId : bookElement_g.getAttribute("epubId"),1391 bookURL : bookElement_g.getAttribute("bookURL"),1392 trash :'visible',1393 };1394 oLibros[ id ] = oLibro ;1395 window.localStorage.setItem("libros", JSON.stringify( oLibros ));1396 getnumbers();1397}1398function removeConfirmDialog_f( element ){1399 ons.notification.confirm({1400 title: '¡Advertencia!',1401 message: '¿Está seguro que desea eliminar el libro? También se perderán los marcadores.',1402 buttonLabels: ['Si', 'No'],1403 callback: function(idx) {1404 switch(idx) {1405 case 0://si1406 deleteEPUB_f( element );1407 break;1408 case 1://no1409 break;1410 }1411 }1412 });1413}1414function deleteEPUB_f( element ){1415 var id = element.getAttribute("epubId");1416 window.resolveLocalFileSystemURL(1417 workingDirEntry_g.toURL() + "epub/" + id + ".epub",1418 function(fileEntry){1419 fileEntry.remove(1420 function(){//success remove1421 removeEPUBfromLocalStorage_f( id );1422 },1423 function(){//fail remove1424 console.log("fail remove");1425 removeEPUBfromLocalStorage_f( id );1426 }1427 );1428 },1429 function(){//fail resolveLocalFileSystemURL1430 console.log("fail resolve filesystem");1431 removeEPUBfromLocalStorage_f( id );1432 }1433 );1434}1435function removeEPUBfromLocalStorage_f( id ){1436 var oLibros = JSON.parse( window.localStorage.getItem("libros") );1437 if( oLibros === null) {1438 oLibros = {};1439 }1440 oLibros[ id ] = undefined ;1441 window.localStorage.setItem("libros", JSON.stringify( oLibros ));1442 backButtonHandler_f();1443 getnumbers();1444}1445//******************************************1446//** POPOVER DEL DICCIONARIO1447//******************************************1448function showMeaning_f(){1449 searchDicMemoriApp_f();1450}1451function searchDicMemoriApp_f(){1452 meaningPopover.hide();1453 // removeSelectionIndicators();1454 var URL = urlServer_g + "index.php/dictionary/buscar/" + selectionString_g.toLowerCase().trim();1455 $.ajax({1456 url: URL,1457 dataType: "jsonp",1458 success: function (aResponse) {1459 console.log("success");1460 var div = createDicPopover_f();1461 console.log(aResponse);1462 var content;1463 if ( aResponse[0] !== undefined ){1464 content = aResponse[0].definicion;1465 }else{1466 searchWiktionary_f( div );1467 return;1468 }1469 var textLines = content.split("\n");1470 var sMeaning = "";1471 var i=0;1472 textLines.every(function(line) {1473 i++;1474 sMeaning += "<br/>" + line;1475 return (i < 3); //break if i not < 31476 });1477 div.innerHTML = selectionString_g + ":<br/>" + sMeaning;1478 console.log(sMeaning);1479 },1480 error: function(e, text){1481 console.log(text);1482 var div = createDicPopover_f();1483 searchWiktionary_f( div );1484 }1485 });1486}1487 1488function searchWiktionary_f( div ){1489 meaningPopover.hide();1490 // removeSelectionIndicators();1491 var URL = "http://es.wiktionary.org/w/api.php?action=query&titles=" + selectionString_g.toLowerCase().trim() + "&prop=revisions&rvprop=content&format=json";1492 $.ajax({1493 url: URL,1494 dataType: "jsonp",1495 success: function (aResponse) {1496 console.log("success");1497 console.log(aResponse);1498 var pages = aResponse.query.pages;1499 var page = getElement( pages );1500 var content;1501 if ( page.missing === undefined ){1502 content = page.revisions[0]["*"];1503 }else{1504 div.innerHTML = selectionString_g + ":<br/>No encontrado";1505 return;1506 }1507 var textLines = content.split("\n");1508 var sMeaning = "";1509 var i=0;1510 textLines.every(function(line) {1511 if( line.substr(0,1) == ";" && !isNaN( parseInt( line.substr(1,1) ) ) ){1512 i++;1513 sMeaning += "<br/>" + line.substr(1);1514 }1515 return (i < 3); //break if i not < 31516 });1517 sMeaning = wikiFormat_f(sMeaning.substr(5));1518 div.innerHTML = selectionString_g + ":<br/>" + sMeaning;1519 console.log(sMeaning);1520 },1521 error: function(e, text){1522 console.log(text);1523 }1524 });1525}1526function createDicPopover_f(){1527 //crear overlay que contiene el popover del diccionario1528 var maskOverlay = document.createElement("div");1529 document.body.appendChild(maskOverlay);1530 maskOverlay.id = "diccionario_overlay"1531 maskOverlay.style.position = "absolute";1532 maskOverlay.style.top = "0px";1533 maskOverlay.style.left = "0px";1534 maskOverlay.style.width = "100%";1535 maskOverlay.style.height = "100%";1536 $(document).on('click', '#diccionario_overlay', function(e) {1537 hideMeaning_f();1538 });1539 //crear popover donde se muestra el significado1540 var div = document.createElement("div");1541 div.style.position = "absolute";1542 maskOverlay.appendChild(div);1543 div.style.bottom = "0px";1544 div.style.left = "0px";1545 div.style.width = "100%";1546 div.style.top = "70%";1547// div.style.padding = "10px";1548 div.style.backgroundColor = "#DDDDDD";1549 var p = document.createElement("div");1550 div.appendChild(p);1551 p.style.margin = "10px";1552 1553 return p;1554}1555function hideMeaning_f(){1556 var div = document.getElementById("diccionario_overlay");1557 var parent = div.parentNode;1558 parent.removeChild(div);1559}1560function getElement( data ){1561 if( typeof(data) != "undefined" ){1562 for (var prop in data){1563 return data[prop];1564 }1565 }1566}1567function wikiFormat_f( str ){1568 var result = str;1569 var aMatch = result.match(/(\[{2}[^\[]+\|[^\[]+\]{2})/g);1570 var word = "";1571 if (aMatch !== null){1572 aMatch.forEach(function( match ){1573 word = match.match(/([^\|]*(?=\]\]))/)[0];1574 match = match.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");1575 result = result.replace(RegExp(match,"g"), word);1576 });1577 }1578 result = result.replace(/([\[\]\{\}]|ucf\|)/g,"");1579 return result;1580}1581//*******************************************1582//** Busqueda de tags1583//*******************************************1584function search_f( element ){1585 searchString_g = element.value;1586 menu.setMainPage('main.html', {closeMenu: true});1587 document.removeEventListener("touchmove",preventDefaultScroll_f);1588}1589//***********************************1590//** Portapapeles1591//***********************************1592function copiar_f(){1593 window.plugins.clipboard.copy(1594 selectionString_g,1595 function(){ //success1596 Dialog_copiado.show();1597 setTimeout('Dialog_copiado.hide()', 2000);1598 },1599 function(){ //error1600 console.log("error al copiar.");1601 }1602 );...
helpers.js
Source:helpers.js
1"use strict";2var logger = require('./server/logger.js').get('appium')3 , fs = require('fs')4 , ncp = require('ncp').ncp5 , request = require('request')6 , _ = require('underscore')7 , path = require('path')8 , rimraf = require('rimraf')9 , exec = require('child_process').exec10 , osType = require('os').type()11 , tempdir = require('./tempdir')12 , glob = require('glob')13 , AdmZip = require('adm-zip');14exports.downloadFile = function (fileUrl, suffix, cb) {15 // We will be downloading the files to a directory, so make sure it's there16 // This step is not required if you have manually created the directory17 tempdir.open({prefix: 'appium-app', suffix: suffix}, function (err, info) {18 var file = fs.createWriteStream(info.path);19 request(fileUrl).pipe(file).on('close', function () {20 logger.debug(fileUrl + ' downloaded to ' + info.path);21 cb(info.path);22 });23 });24};25exports.copyLocalZip = function (localZipPath, cb) {26 logger.debug("Copying local zip to tmp dir");27 fs.stat(localZipPath, function (err) {28 if (err) return cb(err);29 tempdir.open({prefix: 'appium-app', suffix: '.zip'}, function (err, info) {30 var infile = fs.createReadStream(localZipPath);31 var outfile = fs.createWriteStream(info.path);32 infile.pipe(outfile).on('close', function () {33 logger.debug(localZipPath + ' copied to ' + info.path);34 cb(null, info.path);35 });36 });37 });38};39exports.unzipFile = function (zipPath, cb) {40 logger.debug("Unzipping " + zipPath);41 exports.testZipArchive(zipPath, function (err, valid) {42 if (valid) {43 if (exports.isWindows()) {44 var zip = new AdmZip(zipPath);45 zip.extractAllTo(path.dirname(zipPath), true);46 logger.debug("Unzip successful");47 cb(null, null);48 } else {49 var execEnv = _.clone(process.env);50 delete execEnv.UNZIP;51 var execOpts = {cwd: path.dirname(zipPath), maxBuffer: 524288,52 env: execEnv};53 exec('unzip -o ' + zipPath, execOpts, function (err, stderr, stdout) {54 if (!err) {55 logger.debug("Unzip successful");56 cb(null, stderr);57 } else {58 logger.error("Unzip threw error " + err);59 logger.error("Stderr: " + stderr);60 logger.error("Stdout: " + stdout);61 cb("Archive could not be unzipped, check appium logs.", null);62 }63 });64 }65 } else {66 cb(err, null);67 }68 });69};70exports.testZipArchive = function (zipPath, cb) {71 logger.debug("Testing zip archive: " + zipPath);72 if (exports.isWindows()) {73 if (fs.existsSync(zipPath)) {74 logger.debug("Zip archive tested clean");75 cb(null, true);76 } else {77 cb("Zip archive was not found.", false);78 }79 } else {80 var execEnv = _.clone(process.env);81 delete execEnv.UNZIP;82 var execOpts = {cwd: path.dirname(zipPath), maxBuffer: 524288,83 env: execEnv};84 exec("unzip -tq " + zipPath, execOpts, function (err, stderr, stdout) {85 if (!err) {86 if (/No errors detected/.exec(stderr)) {87 logger.debug("Zip archive tested clean");88 cb(null, true);89 } else {90 logger.error("Zip file " + zipPath + " was not valid");91 logger.error("Stderr: " + stderr);92 logger.error("Stdout: " + stdout);93 cb("Zip archive did not test successfully, check appium server logs " +94 "for output", false);95 }96 } else {97 logger.error("Test zip archive threw error " + err);98 logger.error("Stderr: " + stderr);99 logger.error("Stdout: " + stdout);100 cb("Error testing zip archive, are you sure this is a zip file? " + err, null);101 }102 });103 }104};105exports.unzipApp = function (zipPath, appExt, cb) {106 exec("find " + path.dirname(zipPath) + " -type d -name '*" + appExt + "' | xargs rm -rf " + path.dirname(zipPath) +107 "/Payload*", function (error /*, stdout, stderr*/) {108 if (!error) {109 exports.unzipFile(zipPath, function (err, output) {110 if (!err) {111 var relaxedRegStr = "(?:creating|inflating|extracting): (.+" + appExt + ")/?";112 // in the strict regex, we check for an entry which ends with the113 // extension114 var strictReg = new RegExp(relaxedRegStr + "$", 'm');115 // otherwise, we allow an entry which contains the extension, but we116 // need to be careful, because it might be a false positive117 var relaxedReg = new RegExp(relaxedRegStr, 'm');118 var strictMatch = strictReg.exec(output);119 var relaxedMatch = relaxedReg.exec(output);120 var getAppPath = function (match) {121 return path.resolve(path.dirname(zipPath), match[1]);122 };123 if (strictMatch) {124 cb(null, getAppPath(strictMatch));125 } else if (relaxedMatch) {126 logger.debug("Got a relaxed match for app in zip, be careful for app match errors");127 cb(null, getAppPath(relaxedMatch));128 } else {129 cb("App zip unzipped OK, but we couldn't find a .app bundle in it. " +130 "Make sure your archive contains the .app package and nothing else",131 null);132 }133 } else {134 cb(err, null);135 }136 });137 } else {138 cb(error, null);139 }140 });141};142exports.checkBuiltInApp = function (appName, version, tmpDir, cb) {143 logger.debug("Looking for built in app " + appName);144 var newAppDir = path.resolve(tmpDir, 'Appium-' + appName + '.app');145 var checkApp = function (s, appPath, cb) {146 if (!s.isDirectory()) {147 cb(new Error("App package was not a directory"), appPath);148 return false;149 }150 return true;151 };152 exports.getBuiltInAppDir(version, function (err, appDir) {153 if (err) return cb(err);154 var appPath = path.resolve(appDir, appName + ".app");155 fs.stat(appPath, function (err, s) {156 if (err && err.message.indexOf("ENOENT") !== -1) {157 logger.debug("App is not at " + appPath);158 fs.stat(newAppDir, function (err, s) {159 if (err) {160 logger.warn("App is also not at " + newAppDir);161 return cb(new Error("Couldn't find built in app in its home " +162 "or temp dir!"));163 }164 if (checkApp(s, appPath, cb)) {165 logger.debug("Couldn't find original app, but found the temp " +166 "Appium one so using that");167 cb(null, newAppDir, appPath);168 }169 });170 return;171 } else if (err) {172 return cb(err);173 }174 if (checkApp(s, appPath, cb)) {175 if (parseInt(version, 10) < 7) {176 logger.debug("Got app, trying to copy " + appPath + " to tmp dir");177 ncp(appPath, newAppDir, function (err) {178 if (err) return cb(err);179 logger.debug("Copied " + appName);180 cb(null, newAppDir, null);181 });182 } else {183 logger.debug("Got app, trying to move " + appPath + " to tmp dir");184 exports.moveBuiltInApp(appPath, appName, newAppDir, cb);185 }186 }187 });188 });189};190exports.checkSafari = function (version, tmpDir, cb) {191 exports.checkBuiltInApp("MobileSafari", version, tmpDir, cb);192};193exports.checkPreferencesApp = function (version, tmpDir, cb) {194 exports.checkBuiltInApp("Preferences", version, tmpDir, cb);195};196exports.getBuiltInAppDir = function (version, cb) {197 exports.getXcodeFolder(function (err, xcodeDir) {198 if (err) return cb(err);199 var appDir = path.resolve(xcodeDir, "Platforms/iPhoneSimulator.platform/" +200 "Developer/SDKs/iPhoneSimulator" + version +201 ".sdk/Applications/");202 fs.stat(appDir, function (err, s) {203 if (err) {204 cb(err);205 } else if (!s.isDirectory()) {206 cb(new Error("Could not load built in applications directory"));207 } else {208 cb(null, appDir);209 }210 });211 });212};213exports.moveBuiltInApp = function (appPath, appName, newAppDir, cb) {214 ncp(appPath, newAppDir, function (err) {215 if (err) return cb(err);216 logger.debug("Copied " + appName + " to " + newAppDir);217 rimraf(appPath, function (err) {218 if (err) {219 if (err.message.indexOf("EACCES") !== -1) {220 return cb(new Error("We don't have write access to " + appPath +221 ", please re-run authorize as " + process.env.USER));222 }223 return cb(err);224 }225 logger.debug("Temporarily deleted original app at " + appPath);226 cb(null, newAppDir, appPath);227 });228 });229};230exports.cleanSafari = function (safariVer, cb) {231 var baseDir = "Library/Application Support/iPhone Simulator/" +232 safariVer + "*/Library/";233 exports.getUser(function (err, user) {234 if (err) {235 logger.error(err);236 cb(err);237 } else {238 var baseSupportDirs = path.resolve("/Users", user, baseDir);239 glob(baseSupportDirs, function (err, pathList) {240 if (err) return cb(err);241 if (pathList.length === 0) {242 logger.debug("Couldn't find Safari support directories in order " +243 "to clear out old data");244 return cb();245 }246 var pathsFinished = 0;247 var errToRet = null;248 var finishAll = function (err) {249 if (err) errToRet = err;250 pathsFinished++;251 if (pathsFinished === pathList.length) {252 cb(err);253 }254 };255 _.each(pathList, function (baseSupportDir) {256 var toDeletes = [257 'Caches/Snapshots/com.apple.mobilesafari'258 , 'Caches/com.apple.mobilesafari/Cache.db*'259 , 'Caches/com.apple.WebAppCache/*.db'260 , 'Safari/*.plist'261 , 'WebKit/LocalStorage/*.*'262 , 'Library/WebKit/GeolocationSites.plist'263 , 'Cookies/*.binarycookies'264 ];265 var deletes = 0;266 var errToRet = null;267 var finishOne = function (err) {268 deletes++;269 if (err) {270 errToRet = err;271 }272 if (deletes === toDeletes.length) {273 finishAll(errToRet);274 }275 };276 _.each(toDeletes, function (del) {277 var toDelete = path.resolve(baseSupportDir, del);278 toDelete = toDelete.replace(/ /g, "\\ ");279 logger.debug("Deleting " + toDelete);280 var cmd = "rm -rf " + toDelete;281 exec(cmd, function (err) {282 finishOne(err);283 });284 });285 });286 });287 }288 });289};290exports.getUser = function (cb) {291 logger.debug("Determining current user");292 exec("whoami", { maxBuffer: 524288 }, function (err, stdout) {293 if (err) {294 logger.error(err);295 cb(err);296 } else {297 logger.debug("User is " + stdout.trim());298 cb(null, stdout.trim());299 }300 });301};302exports.delay = function (secs) {303 var date = new Date();304 var curDate = null;305 do { curDate = new Date(); }306 while (curDate - date < (secs * 1000.0));307};308// var pad0 = function (x) {309// if (x.toString().length == 1) {310// x = '0' + x;311// }312// return x;313// };314exports.escapeSpecialChars = function (str, quoteEscape) {315 if (typeof str !== "string") {316 return str;317 }318 if (typeof quoteEscape === "undefined") {319 quoteEscape = false;320 }321 str = str322 .replace(/[\\]/g, '\\\\')323 .replace(/[\/]/g, '\\/')324 .replace(/[\b]/g, '\\b')325 .replace(/[\f]/g, '\\f')326 .replace(/[\n]/g, '\\n')327 .replace(/[\r]/g, '\\r')328 .replace(/[\t]/g, '\\t')329 .replace(/[\"]/g, '\\"')330 .replace(/\\'/g, "\\'");331 if (quoteEscape) {332 var re = new RegExp(quoteEscape, "g");333 str = str.replace(re, "\\" + quoteEscape);334 }335 return str;336};337exports.parseWebCookies = function (cookieStr) {338 var cookies = [];339 var splits = cookieStr.trim().split(";");340 _.each(splits, function (split) {341 split = split.trim();342 if (split !== "") {343 split = split.split("=");344 cookies.push({345 name: decodeURIComponent(split[0])346 , value: decodeURIComponent(split[1])347 });348 }349 });350 return cookies;351};352var warningsEmitted = {};353var deprecationWarnings = [];354var warningText = _.template(355 "[DEPRECATED] The <%= deprecated %> <%= kind %> has been deprecated and will " +356 "be removed."357);358var replacementText = _.template(359 " Please use the <%= replacement %> <%= kind %> instead."360);361exports.formatDeprecationWarning = function (kind, deprecated, replacement) {362 var warning = warningText({kind: kind, deprecated: deprecated});363 if (typeof replacement !== 'undefined') {364 warning += replacementText({kind: kind, replacement: replacement});365 }366 return warning;367};368exports.logDeprecationWarning = function (kind, deprecated, replacement) {369 if (!_.has(warningsEmitted, kind)) {370 warningsEmitted[kind] = {};371 }372 if (!_.has(warningsEmitted[kind], deprecated)) {373 var warning = exports.formatDeprecationWarning(kind, deprecated, replacement);374 deprecationWarnings.push(warning);375 logger.warn(warning);376 warningsEmitted[kind][deprecated] = true;377 }378};379exports.logCustomDeprecationWarning = function (kind, deprecated, msg) {380 if (!_.has(warningsEmitted, kind)) {381 warningsEmitted[kind] = {};382 }383 if (!_.has(warningsEmitted[kind], deprecated)) {384 deprecationWarnings.push(msg);385 logger.warn(msg);386 warningsEmitted[kind][deprecated] = true;387 }388};389exports.logFinalDeprecationWarning = function () {390 var numWarnings = deprecationWarnings.length;391 if (numWarnings > 0) {392 logger.warn("[DEPRECATED] You used " + numWarnings + " deprecated" +393 " capabilities during this session. Please check the logs" +394 " as they will be removed in a future version of Appium.");395 }396};397exports.getDeprecationWarnings = function () {398 return deprecationWarnings;399};400exports.clearWarnings = function () {401 warningsEmitted = {};402 deprecationWarnings = [];403};404exports.rotateImage = function (imgPath, deg, cb) {405 logger.debug("Rotating image " + imgPath + " " + deg + " degrees");406 var scriptPath = require('appium-uiauto').rotate;407 var cmd = "osascript " + scriptPath + " " + JSON.stringify(imgPath) +408 " " + deg;409 exec(cmd, { maxBuffer: 524288 }, function (err, stdout) {410 if (err) return cb(err);411 console.log(stdout);412 cb(null);413 });414};415exports.isWindows = function () {416 return osType === 'Windows_NT';417};418exports.isMac = function () {419 return osType === 'Darwin';420};421exports.isLinux = function () {422 return !exports.isWindows() && !exports.isMac();423};424exports.macVersionArray = function (cb) {425 var versions = [];426 if (exports.isMac()) {427 exec("sw_vers -productVersion", function (err, stdout) {428 if (err) return cb(err);429 stdout = stdout.trim();430 if (/\d+\.\d+\.\d+/.test(stdout)) {431 _.each(stdout.split("."), function (ver) {432 versions.push(parseInt(ver, 10));433 });434 cb(null, versions);435 } else {436 cb(new Error("Could not parse version information from: " + stdout));437 }438 });439 } else {440 cb(null, versions);441 }442};443exports.getGitRev = function (cb) {444 var cwd = path.resolve(__dirname, "..");445 exec("git rev-parse HEAD", {cwd: cwd, maxBuffer: 524288}, function (err, stdout) {446 if (err) return cb(err);447 cb(null, stdout.trim());448 });449};450exports.getXcodeFolder = function (cb) {451 exec('xcode-select --print-path', { maxBuffer: 524288, timeout: 3000 }, function (err, stdout, stderr) {452 if (!err) {453 var xcodeFolderPath = stdout.replace("\n", "");454 if (fs.existsSync(xcodeFolderPath)) {455 cb(null, xcodeFolderPath);456 } else {457 logger.error(xcodeFolderPath + "does not exist.");458 cb(new Error("xcode-select could not find xcode"), null);459 }460 } else {461 logger.error("xcode-select threw error " + err);462 logger.error("Stderr: " + stderr);463 logger.error("Stdout: " + stdout);464 cb(new Error("xcode-select threw an error"), null);465 }466 });467};468exports.getXcodeVersion = function (cb) {469 exports.getXcodeFolder(function (err, xcodePath) {470 if (err !== null) {471 cb(err, null);472 } else {473 var xcodebuildPath = path.resolve(xcodePath, "usr/bin/xcodebuild");474 if (!fs.existsSync(xcodebuildPath)) {475 cb(new Error("Could not get Xcode version: " + xcodebuildPath + " does not exist on disk."), null);476 } else {477 exec(JSON.stringify(xcodebuildPath) + ' -version', { maxBuffer: 524288, timeout: 3000 }, function (err, stdout) {478 var versionPattern = /\d\.\d\.*\d*/;479 var match = versionPattern.exec(stdout);480 if (match === null) {481 cb(new Error("Could not parse Xcode version (xcodebuild output was: " + stdout + ")"), null);482 } else {483 var versionNumber = match[0];484 cb(null, versionNumber);485 }486 });487 }488 }489 });490};491exports.getiOSSDKVersion = function (cb) {492 var msg;493 exports.getXcodeVersion(function (err, versionNumber) {494 if (err) {495 msg = "Could not get the iOS SDK version because the Xcode version could not be determined.";496 logger.error(msg);497 cb(new Error(msg), null);498 } else if (versionNumber[0] === '4') {499 cb(null, '6.1');500 } else {501 exec('xcrun --sdk iphonesimulator --show-sdk-version', { maxBuffer: 524288, timeout: 3000 }, function (err, stdout, stderr) {502 if (!err) {503 var iosSDKVersion = stdout.replace("\n", "");504 var match = /\d.\d/.exec(iosSDKVersion);505 if (match) {506 cb(null, iosSDKVersion);507 } else {508 msg = "xcrun returned a non-numeric iOS SDK version: " + iosSDKVersion;509 logger.error(msg);510 cb(new Error(msg), null);511 }512 } else {513 msg = "xcrun threw an error " + err;514 logger.error(msg);515 logger.error("Stderr: " + stderr);516 logger.error("Stdout: " + stdout);517 cb(new Error(msg), null);518 }519 });520 }521 });522};523exports.getiOSSimulatorDirectories = function (cb) {524 var basePath = path.resolve(process.env.HOME, "Library", "Application Support",525 "iPhone Simulator");526 glob(basePath + "/*.*", function (err, pathList) {527 if (err) {528 var msg = "Could not find any directories for the iOS Simulator";529 logger.error(msg);530 cb(new Error(msg));531 } else {532 cb(null, pathList);533 }534 });535};536exports.getAppiumConfig = function () {537 var configPath = path.resolve(__dirname, "..", ".appiumconfig.json");538 var config539 , msg;540 try {541 config = require(configPath);542 } catch (e) {543 if (e.code === "MODULE_NOT_FOUND") {544 msg = "Could not find config file: " + configPath +545 "; looks like config hasn't been run." +546 " Please run reset.sh or appium configure.";547 logger.error(msg);548 throw new Error(msg);549 } else {550 msg = "Invalid config file at " + configPath +551 " please re-run reset.sh or appium config";552 logger.error(msg);553 throw new Error(msg);554 }555 }556 return config;557};558exports.iosConfigured = function () {559 return typeof exports.getAppiumConfig().ios !== "undefined";560};561exports.truncateDecimals = function (number, digits) {562 var multiplier = Math.pow(10, digits),563 adjustedNum = number * multiplier,564 truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum);565 return truncatedNum / multiplier;...
Using AI Code Generation
1const wd = require('wd');2const { XCUITestDriver } = require('appium-xcuitest-driver');3const { getSimulator } = require('appium-ios-simulator');4const { createDevice, deleteDevice } = require('node-simctl');5const { fs, tempDir } = require('appium-support');6const { exec } = require('teen_process');7const PORT = 4723;8const HOST = 'localhost';9async function main () {10 const driver = new XCUITestDriver();11 await driver.createSession({
Using AI Code Generation
1const tempDir = require('appium-support').tempDir;2const path = require('path');3const fs = require('fs');4const dir = tempDir.open('tempDir');5console.log(dir);6const filePath = path.resolve(dir, 'test.txt');7fs.writeFileSync(filePath, 'Hello World');8console.log('File is created at '+filePath);9tempDir.cleanup();10tempDir.cleanup('tempDir');11tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');12tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');13tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');14tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');15tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');16tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');17tempDir.cleanup('tempDir', '20190729-1940-1y5m5y5');
Using AI Code Generation
1const tempDir = require('temp-dir');2const { open } = tempDir;3console.log(open('test'));4const tempDir = require('temp-dir');5const { openSync } = tempDir;6console.log(openSync('test'));7const tempDir = require('temp-dir');8const { path } = tempDir;9console.log(path);10const tempDir = require('temp-dir');11const { write } = tempDir;12console.log(write('test'));13const tempDir = require('temp-dir');14const { writeSync } = tempDir;15console.log(writeSync('test'));16const tempDir = require('temp-dir');17const { writeJson } = tempDir;18console.log(writeJson('test', { test: 'test' }));
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!