Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- *
- * TODO
- * [R E F A C T O R P L E A S E]
- *
- */
- // APP START
- var ua = navigator.userAgent.toLowerCase();
- alert(ua);
- var isAndroid = ua.indexOf("android") > -1;
- var isChrome_bad = /chrom(e|ium)/.test(ua.toLowerCase());
- var isNative = ((ua.indexOf('mozilla/5.0') > -1 && ua.indexOf('android ') > -1 && ua.indexOf('applewebkit') > -1) && (ua.indexOf('version') > -1));
- var isChrome = !!window.chrome;
- // window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
- // window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"};
- // window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
- // alert('window.indexedDB: ' + window.indexedDB);
- // alert('window.IDBTransaction: ' + window.IDBTransaction);
- // alert('type of window.IDBKeyRange = ' + typeof IDBKeyRange);
- alert('Version: 0.8');
- function checkCamera() {
- return new Promise(function (fullfill, reject) {
- var preview = document.getElementById('CHECK-video');
- var canvas = document.getElementById('CHECK-canvas');
- var result = false;
- $('#CHECK-canvas').attr('width', 150);
- $('#CHECK-canvas').attr('height', 150);
- var context = canvas.getContext('2d');
- function GetPixel(x, y) {
- var p = context.getImageData(x, y, 1, 1).data;
- var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
- return hex;
- }
- function rgbToHex(r, g, b) {
- if (r > 255 || g > 255 || b > 255)
- throw "Invalid color component";
- return ((r << 16) | (g << 8) | b).toString(16);
- }
- setTimeout(function () {
- context.drawImage(preview, 0, 0, 150, 150);
- var dataURL = canvas.toDataURL('image/jpeg', 0.5);
- var checkers = {
- LT: GetPixel(2, 2),
- RT: GetPixel(148, 2),
- CC: GetPixel(75, 75),
- LB: GetPixel(2, 148),
- RB: GetPixel(148, 148)
- }
- for (var key in checkers) {
- var value = checkers[key];
- if (value !== '#000000') fullfill(true);
- }
- setTimeout(function () {
- fullfill(false);
- }, 1000);
- }, 2000);
- var devicesStore = [];
- function gotDevices(deviceInfos) {
- for (var i = 0; i !== deviceInfos.length; ++i) {
- var deviceInfo = deviceInfos[i];
- var deviceObj = {};
- deviceObj = { id: deviceInfo.deviceId, label: deviceInfo.label };
- devicesStore.push(deviceObj);
- }
- }
- navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
- function gotStream(stream) {
- window.stream = stream;
- preview.srcObject = stream;
- return navigator.mediaDevices.enumerateDevices();
- }
- function start() {
- if (window.stream) {
- window.stream.getTracks().forEach(function (track) {
- track.stop();
- });
- }
- var constraints = {
- audio: false,
- video: true,
- };
- navigator.mediaDevices.getUserMedia(constraints).
- then(gotStream).catch(handleError);
- }
- function handleError(error) {
- console.log('navigator.getUserMedia error: ', error);
- }
- start();
- });
- }
- var app = {
- store: {
- logged: { remember: false, currentUser: '', token: null },
- activeSessions: [],
- currentSession: {},
- cameraEnable: null,
- showSplash: null
- },
- currentSessionId: null,
- defaultEmail: 'Rating@ButyBOOK.cz'
- };
- app.setRemember = function (r) {
- this.store.logged.remember = r;
- }
- app.generateId = function () {
- return '' + Math.random() * (100000 - 1) + 1 + '';
- }
- app.loadData = function () {
- var self = this;
- self.store = JSON.parse(localStorage.getItem('watcutData'));
- }
- app.saveData = function () {
- var self = this;
- setTimeout(function () {
- localStorage.setItem('watcutData', JSON.stringify(self.store));
- }, 100)
- }
- app.addSession = function (session) {
- var copyStore = this.store.activeSessions;
- copyStore.push(session);
- this.store.activeSessions = copyStore;
- this.saveData();
- }
- app.setCurrentSession = function (sesssion) {
- this.store.currentSession = sesssion;
- this.saveData();
- }
- app.removeSessionByIdV2 = function (id) {
- return db.sessions.where('id').equals(id).delete();
- }
- app.logout = function () {
- this.store.logged.token = null;
- this.store.logged.currentUser = null;
- this.saveData();
- }
- app.setToken = function (token) {
- this.store.logged.token = token;
- this.saveData();
- }
- app.setCurrentUser = function (email) {
- this.store.logged.currentUser = email;
- }
- app.getSessionFromDB = function (id) {
- return db.sessions.get(id);
- }
- app.saveToDB = function (session) {
- return db.sessions.put(session);
- }
- app.togglePhotoSelectedV2 = function (photoId, state) {
- var $this = this,
- sessionId = $this.currentSessionId;
- return $this.getSessionFromDB(sessionId).then(function (session) {
- var photos = session.photos;
- if (photos.length > 0) {
- photos.forEach(function (phItem, index, photos) {
- if (phItem.id === photoId) phItem.selected = state;
- $this.updatePhotosInSession(sessionId, photos);
- });
- }
- });
- }
- app.removePhotoByIdV2 = function (id) {
- var $this = this,
- sessionId = $this.currentSessionId;
- $this.getSessionFromDB(sessionId).then(function (session) {
- var photos = session.photos;
- if (photos.length > 0) {
- photos.forEach(function (item, index) {
- if (item != null && item.id === id && item.id != session.cover) {
- photos.splice(index, 1);
- $this.updatePhotosInSession(sessionId, photos).then(function (u) {
- if (u == 1) $('ons-list-item[data-photo-id="' + id + '"]').remove();
- else alert('Error. Try to again.');
- })
- }
- });
- }
- });
- }
- app.rotatePhotoById = function (id) {
- var $this = this,
- sessionId = $this.currentSessionId;
- $this.getSessionFromDB(sessionId).then(function (session) {
- var photos = session.photos;
- if (photos.length > 0) {
- photos.forEach(function (item, index) {
- if (item != null && item.id === id) {
- var canvas = document.getElementById("rotate-edit"),
- ctx = canvas.getContext("2d"),
- img = new Image();
- item.angle += 90;
- if (item.angle == 360) item.angle = 0;
- img.onload = function () {
- var cache = this;
- canvas.width = cache.width; //double the canvas width
- canvas.height = cache.height; //double the canvas height
- ctx.save();
- ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
- ctx.translate(cache.width / 2, cache.height / 2); //let's translate
- ctx.rotate(90 * Math.PI / 180); //increment the angle and rotate the image
- ctx.drawImage(img, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image ;)
- ctx.restore(); //restore the state of canvas
- var b64 = canvas.toDataURL("image/jpeg");
- photos[index].base64 = b64;
- photos[index].angle = item.angle;
- $this.updatePhotosInSession(sessionId, photos).then(function () {
- $('ons-list-item[data-photo-id="' + item.id + '"]').css('background-image', 'url(' + b64 + ')');
- });
- }
- img.src = item.base64;
- }
- });
- }
- });
- }
- app.sendData = function (id, fSuccess, fError) {
- self = this;
- this.getSessionFromDB(id).then(function (session) {
- var link = 'https://butybook.cz/wp-json/wp/v1/haircut',
- currentSession = session;
- console.log(currentSession);
- var dataToSend = {
- id: currentSession.id,
- title: currentSession.title,
- content: '',
- specials: parseInt(currentSession.specials),
- color: parseInt(currentSession.color),
- cut: parseInt(currentSession.cut),
- gender: parseInt(currentSession.gender),
- type: parseInt(currentSession.type),
- coloration: parseInt(currentSession.coloration),
- email: currentSession.email,
- status: 'publish'
- };
- var data = new FormData();
- data.append('title', dataToSend.title);
- data.append('content', dataToSend.content);
- data.append('specials', data.specials);
- data.append('color', dataToSend.color);
- data.append('cut', dataToSend.cut);
- data.append('gender', dataToSend.gender);
- data.append('type', dataToSend.type);
- data.append('coloration', dataToSend.coloration);
- data.append('status', dataToSend.status);
- data.append('email', dataToSend.email);
- console.log(data);
- var xhr = new XMLHttpRequest();
- xhr.addEventListener('readystatechange', function () {
- if (this.readyState === 4) {
- console.log('STATUS: ' + this.status);
- if (this.status === 201) {
- app.removePhotoByIdV2(id);
- var response = this.responseText;
- console.log(response);
- var id = JSON.parse(response).id;
- console.log('Response ID = ' + id);
- if (dataToSend.email !== self.defaultEmail && dataToSend !== '' && dataToSend !== null) {
- self.createUser(id, dataToSend.email);
- }
- self.sendMedia(id, currentSession, fSuccess, fError);
- } else {
- fError(this.statusText);
- }
- }
- });
- xhr.open('POST', 'https://butybook.cz/wp-json/wp/v2/haircut');
- xhr.setRequestHeader('authorization', 'Bearer ' + self.store.logged.token);
- xhr.send(data);
- });
- }
- app.createUser = function (id, email) {
- var createUserData = new FormData();
- createUserData.append('customer_email', email);
- var xhr = new XMLHttpRequest();
- xhr.addEventListener('readystatechange', function () {
- if (this.readyState === 4) {
- console.log('app.createUser STATUS: ' + this.status);
- if (this.status === 201 || this.status === 200) {
- console.log(this.responseText);
- }
- }
- });
- xhr.open('POST', 'https://butybook.cz/wp-json/wp/v2/haircut/' + id);
- xhr.setRequestHeader('authorization', 'Bearer ' + self.store.logged.token);
- xhr.send(createUserData);
- }
- app.sendMedia = function (id, session, fSuccess, fError) {
- var self = this;
- var coverId = session.cover;
- var photos = session.photos;
- photos.forEach(function (item, index, photos) {
- if (item.selected || item.id === coverId) {
- var data = new FormData(),
- fileData = dataURLtoBlob(item.base64);
- data.append('post', id);
- data.append('file', fileData, id + '-photo-' + index + '.jpg');
- data.append('featured', (item.id == coverId ? '1' : '0'));
- var xhr = new XMLHttpRequest();
- xhr.addEventListener('readystatechange', function () {
- if (this.readyState === 4) {
- if (this.status === 201) {
- console.log('Successfully uploded image');
- fSuccess();
- } else {
- fError(this.statusText);
- }
- }
- });
- xhr.open('POST', 'https://butybook.cz/wp-json/wp/v2/media');
- xhr.setRequestHeader('authorization', 'Bearer ' + self.store.logged.token);
- xhr.send(data);
- }
- });
- }
- app.getCoverV2 = function (sessionId, coverId) {
- var photos = null, cover = undefined;
- return app.getSessionFromDB(sessionId).then(function (session) {
- photos = session.photos;
- photos.forEach(function (item, index, photos) {
- if (item !== null && item.id === coverId) {
- cover = item.base64;
- }
- });
- if (cover === undefined) return ('./images/placeholder/cancel.png');
- return cover;
- });
- }
- app.updatePhotosInSession = function (id, photos) {
- return db.sessions.update(id, { photos: photos });
- }
- app.setSessionEmail = function (id, email) {
- return db.sessions.update(id, { email: email });
- }
- //render things
- app.renderActiveSessionsV2 = function () {
- var self = this,
- $list = $('#sessions_list'),
- html = '', lCount = 0, fCount = 0;
- $list.empty();
- $list.append('<svg class="progress-circular"><circle class="progress-circular__primary" cx="50%" cy="50%" r="20%" fill="none" stroke-width="10%" stroke-miterlimit="10"></svg>');
- var c = db.sessions.count(function (ca) {
- fCount = ca;
- if (fCount == 0) {
- $('.progress-circular').remove();
- $list.append('You are not have a active session');
- }
- });
- db.sessions.each(function (session) {
- if (session.user === self.store.logged.currentUser) {
- self.getCoverV2(session.id, session.cover).then(function (cover) {
- lCount++;
- var src = $('#active-session-template').text(),
- template = Handlebars.compile(src),
- html = template({
- 'id': session.id,
- 'cover': cover,
- 'date': session.date,
- 'title': session.title.replace(/ - /g, ', ')
- });
- if ((lCount == (fCount - (fCount - lCount)))) {
- $('.progress-circular').remove();
- $list.append(html);
- }
- });
- }
- });
- }
- app.renderPhotosV2 = function () {
- var $this = this;
- return $this.getSessionFromDB($this.currentSessionId).then(function (session) {
- var photos = session.photos;
- var $list = $('#photos_list');
- $list.empty();
- if (photos.length > 0) {
- photos.forEach(function (item, index, photos) {
- if (item !== null) {
- var src = $('#photo-template').text();
- var template = Handlebars.compile(src);
- var html = template({ 'id': item.id, 'photo-link': item.base64 });
- $list.append(html);
- }
- });
- } else {
- $list.append('<p>You are should take a more photo!</p>');
- }
- });
- }
- // APP END
- ons.ready(function () {
- var nav = document.getElementById('nav');
- if (localStorage.getItem('watcutData') !== null) {
- console.log('-> Loading data');
- app.loadData();
- }
- // nav.pushPage('./templates/signin.html');
- if (app.store.logged.remember === false) {
- app.logout();
- nav.resetToPage('./templates/signin.html', {
- animation: "slide"
- });
- }
- if (app.store.logged.token === undefined || app.store.logged.token === null)
- nav.resetToPage('./templates/signin.html', {
- animation: "slide"
- });
- else {
- if (app.store.showSplash == null)
- nav.resetToPage('./templates/splash.html', {
- animation: "slide"
- });
- else
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- }
- document.addEventListener('show', function (event) {
- initActivity(event.target.id);
- });
- function initActivity(activityId) {
- console.log('Activated activity: ' + activityId);
- switch (activityId) {
- case 'signin': signInActivity(); break;
- case 'splash': splashActivity(); break;
- case 'session': sessionActivity(); break;
- case 'tags-session': tagsActivity(); break;
- case 'camera': cameraActivity(); break;
- case 'photos': photosActivity(); break;
- }
- }
- function splashActivity() {
- console.log('[SPLASH ACTIVITY]');
- if (isChrome) {
- alert('app.store.cameraEnable: ' + app.store.cameraEnable);
- if (app.store.cameraEnable === null) {
- if (!isNative) {
- checkCamera().then(function (res) {
- console.log('-> Camera is ' + (res ? 'enabled' : 'disabled'));
- app.store.cameraEnable = res;
- Init();
- }).catch(function (err) {
- console.log('-> Error: ' + err);
- console.log('-> Camera is disabled');
- app.store.cameraEnable = false;
- Init();
- });
- } else {
- app.store.cameraEnable = false;
- console.log('-> Camera is disabled');
- Init();
- }
- } else {
- console.log('-> Camera is ' + (app.store.cameraEnable ? 'enabled' : 'disabled'));
- Init();
- }
- } else {
- console.log('-> Camera is disabled');
- app.store.cameraEnable = false;
- Init();
- }
- function Init() {
- app.store.showSplash = false;
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- }
- }
- function signInActivity() {
- app.setRemember($(this).is(':checked'));
- if ((app.store.logged.token !== null && app.store.logged.token !== ''))
- if (app.store.showSplash == null)
- nav.resetToPage('./templates/splash.html', {
- animation: "slide"
- });
- else
- nav.pushPage('./templates/session.html');
- $('.sigin__checkbox').on('change', function () {
- app.setRemember($(this).is(':checked'));
- });
- document.querySelector('ons-button[name="signin-btn"]').onclick = function () {
- var login = document.querySelector('input[name="signin-login"]').value,
- password = document.querySelector('input[name="signin-password"]').value;
- if (login != '' && password != '') {
- $('ons-button[name="signin-btn"]').text('');
- $('ons-button[name="signin-btn"]').append('<svg class="progress-circular"><circle class="progress-circular__primary" cx="50%" cy="50%" r="20%" fill="none" stroke-width="10%" stroke-miterlimit="10"></svg>');
- var data = "username=" + encodeURIComponent(login) + "&password=" + encodeURIComponent(password);
- var xhr = new XMLHttpRequest();
- xhr.withCredentials = true;
- xhr.addEventListener("readystatechange", function () {
- if (this.readyState === 4) {
- console.log(this.readyState);
- if (this.status === 200) {
- var d = JSON.parse(this.responseText);
- app.setCurrentUser(login);
- app.setToken(d.token);
- if (app.store.showSplash == null)
- nav.resetToPage('./templates/splash.html', {
- animation: "slide"
- });
- else nav.pushPage('./templates/session.html');
- } else {
- ons.notification.alert({ title: 'Error', message: 'Invalid login or passrword! Try again!' });
- $('.progress-circular').remove();
- $('ons-button[name="signin-btn"]').text('Log In');
- }
- }
- });
- xhr.open("POST", "https://butybook.cz/wp-json/jwt-auth/v1/token");
- xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
- xhr.send(data);
- } else {
- ons.notification.alert({ title: 'Error', message: 'Login or password is empty!' });
- }
- };
- }
- function sessionActivity() {
- app.currentSessionId = null;
- app.renderActiveSessionsV2();
- $('body').on('click', '.active-sessions__delete', function () {
- var $id = $(this).data('session-id');
- app.removeSessionByIdV2($id).then(function () {
- $('ons-list-item[data-session-id="' + $id + '"]').remove();
- app.renderActiveSessionsV2();
- app.currentSessionId = null;
- });
- });
- $('body').on('click', '.active-sessions__item', function () {
- var id = $(this).data('session-id');
- app.getSessionFromDB(id).then(function (session) {
- app.currentSessionId = session.id;
- nav.pushPage('./templates/tags-new-session.html', { data: { session: session } });
- });
- });
- document.querySelector('ons-button[name="new-session-btn"]').addEventListener('click', function () {
- nav.pushPage('./templates/tags-new-session.html');
- });
- document.querySelector('ons-button[name="sign-out"]').addEventListener('click', function () {
- app.logout();
- nav.resetToPage('./templates/signin.html');
- });
- }
- function tagsActivity() {
- var sessionData,
- photos = [],
- isLoaded = false,
- startId = 0;
- if (app.currentSessionId !== null && app.currentSessionId !== undefined) {
- app.getSessionFromDB(app.currentSessionId).then(function (session) {
- sessionData = session;
- photos = sessionData.photos;
- isLoaded = true;
- if (photos.length > 0)
- startId = photos.length;
- else startId = 0;
- loadSession();
- $('.session-footer__new').hide();
- $('.session-footer__continue').show();
- document.querySelector('ons-button[name="continue"]').onclick = function () {
- app.currentSessionId = sessionData.id;
- nav.pushPage('./templates/photos.html', {
- animation: "slide"
- });
- };
- });
- } else {
- saveCutSetting();
- if (app.store.cameraEnable) $('.camera-enabled').show();
- else $('.camera-disabled').show();
- }
- $('input[type="radio"]').on('change', function () {
- saveCutSetting();
- });
- $('input[name="special"]').on('change', function () {
- saveCutSetting();
- });
- function loadSession() {
- $('input[value="' + sessionData.gender + '"]').prop('checked', true);
- $('input[value="' + sessionData.specials + '"]').prop('checked', true);
- $('input[value="' + sessionData.type + '"]').prop('checked', true);
- $('input[value="' + sessionData.color + '"]').prop('checked', true);
- $('input[value="' + sessionData.cut + '"]').prop('checked', true);
- $('input[value="' + sessionData.coloration + '"]').prop('checked', true);
- }
- function saveCutSetting() {
- var gender = $('input[name="gender"]:checked').val(),
- hairType = $('input[name="hair-type"]:checked').val(),
- hairColour = $('input[name="hair-color"]:checked').val(),
- hairLength = $('input[name="hair-length"]:checked').val(),
- specials = $('input[name="special"]:checked').val(),
- coloration = $('input[name="hair-coloration"]:checked').val(),
- newSession = null;
- if (isLoaded) {
- newSession = {
- 'id': sessionData.id, 'user': sessionData.user, 'gender': gender, 'type': hairType,
- 'color': hairColour, 'cut': hairLength, 'specials': specials, 'coloration': coloration,
- 'email': sessionData.email, 'cover': sessionData.cover, 'date': sessionData.date,
- 'photos': sessionData.photos
- };
- } else {
- newSession = {
- 'id': app.generateId(), 'user': app.store.logged.currentUser, 'gender': gender, 'type': hairType,
- 'color': hairColour, 'cut': hairLength, 'specials': specials, 'coloration': coloration,
- 'email': app.defaultEmail, 'cover': 0, 'date': getCurrentDate(),
- 'photos': []
- };
- }
- var title = convertTitle(newSession);
- newSession.title = title;
- sessionData = newSession;
- isLoaded = true;
- app.saveToDB(sessionData);
- }
- if (window.File && window.FileReader && window.FileList && window.Blob) {
- $('body').on('change', '#addPhoto2', function () {
- var modal = document.getElementById('loader');
- modal.show();
- $this = $(this);
- var files = $(this).prop('files');
- alert('Files count (if >1 => input got a file) : ' + files.length);
- for (var i = 0; i < files.length; i++) {
- alert('#1');
- var file = files[i];
- var reader = new FileReader();
- alert('#2');
- reader.onloadend = function () {
- alert('#3');
- var tempImg = new Image();
- tempImg.src = reader.result;
- tempImg.onload = function () {
- alert('#4');
- var MAX_WIDTH = 900;
- var MAX_HEIGHT = 600;
- var tempW = tempImg.width;
- var tempH = tempImg.height;
- if (tempW > tempH) {
- if (tempW > MAX_WIDTH) {
- tempH *= MAX_WIDTH / tempW;
- tempW = MAX_WIDTH;
- }
- } else {
- if (tempH > MAX_HEIGHT) {
- tempW *= MAX_HEIGHT / tempH;
- tempH = MAX_HEIGHT;
- }
- }
- alert('#5');
- function drawRotated(degrees, img, canvas, ctx, o) {
- var w = tempW,
- h = tempH;
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.save();
- if (o == 8) {
- ctx.translate(0, canvas.height * 1.5);
- w *= 1.5;
- h *= 1.5;
- }
- else if (o == 6) {
- ctx.translate(canvas.width / 2 + tempW / 2, -canvas.height + tempH / 6);
- w *= 1.5;
- h *= 1.5;
- }
- else if (o == 3) {
- ctx.translate(canvas.width, canvas.height);
- }
- ctx.rotate(degrees * Math.PI / 180);
- ctx.drawImage(img, 0, 0, w, h); //draw the image ;)
- ctx.restore();
- }
- alert('#6');
- var canvas = document.createElement('canvas');
- canvas.width = tempW;
- canvas.height = tempH;
- alert('#7');
- var ctx = canvas.getContext("2d");
- ctx.drawImage(this, 0, 0, tempW, tempH);
- alert('#8');
- var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(reader.result));
- alert('#9');
- switch (exif.Orientation) {
- case 8:
- drawRotated(-90, this, canvas, ctx, exif.Orientation);
- break;
- case 3:
- drawRotated(180, this, canvas, ctx, exif.Orientation);
- break;
- case 6:
- drawRotated(90, this, canvas, ctx, exif.Orientation);
- break;
- }
- alert('#10');
- // setTimeout(function () {
- var base64 = canvas.toDataURL("image/jpeg");
- alert('#11');
- item = {
- 'id': startId++,
- 'base64': base64,
- 'selected': false,
- 'angle': 0
- };
- alert('#12');
- photos.push(item);
- alert('#13');
- if (i == files.length) {
- alert('#14');
- setTimeout(function () {
- app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
- alert('#15');
- if (updated) {
- alert('#16');
- console.log('photos is updated');
- app.currentSessionId = sessionData.id;
- alert('#17');
- modal.hide();
- nav.pushPage('./templates/photos.html');
- } else console.log('not updated');
- });
- }, 1000);
- }
- }
- }
- alert('#18');
- reader.readAsDataURL(file);
- alert('#19');
- }
- });
- } else {
- alert('The File APIs are not fully supported in this browser.');
- }
- if (isAndroid) {
- document.querySelector('ons-button[name="take-photos-btn"]').onclick = function () {
- app.currentSessionId = sessionData.id;
- nav.pushPage('./templates/camera.html');
- };
- }
- document.querySelector('ons-button[name="finish-later"]').onclick = function () {
- app.currentSessionId = null;
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- };
- }
- function cameraActivity() {
- var sessionData = null,
- cId = null,
- photos = null;
- if (app.currentSessionId !== null && app.currentSessionId !== undefined) {
- app.getSessionFromDB(app.currentSessionId).then(function (session) {
- sessionData = session;
- photos = sessionData.photos;
- if (photos.length > 0)
- startId = photos.length;
- else startId = 0;
- });
- }
- var preview = document.getElementById('video'),
- canvas = document.getElementById('canvas'),
- width = preview.offsetWidth,
- height = preview.offsetHeight,
- cameraRun = false,
- $flash = $('#flash');
- $('#canvas').attr('width', width);
- $('#canvas').attr('height', height);
- var context = canvas.getContext('2d');
- document.getElementById('snap').addEventListener('click', function () {
- if (cameraRun) {
- $flash.addClass('anim-flash');
- setTimeout(function () {
- $flash.removeClass('anim-flash');
- }, 400);
- context.drawImage(preview, 0, 0, width, height);
- var dataURL = canvas.toDataURL('image/jpeg', 0.5);
- document.getElementById('cnvimg').src = dataURL;
- photos.push({ 'id': startId++, 'base64': dataURL, 'selected': false, 'angle': 0 });
- app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
- if (updated) { console.log('photo is captured'); }
- else { console.log('photo is not captured'); }
- });
- }
- });
- var devicesStore = [];
- function gotDevices(deviceInfos) {
- for (var i = 0; i !== deviceInfos.length; ++i) {
- var deviceInfo = deviceInfos[i];
- var deviceObj = {};
- if (deviceInfo.kind === 'videoinput') {
- $('.camera-select').append('<option value=' + deviceInfo.deviceId + '>' + deviceInfo.label + '</option>');
- }
- deviceObj = { id: deviceInfo.deviceId, label: deviceInfo.label };
- devicesStore.push(deviceObj);
- }
- }
- navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
- function gotStream(stream) {
- window.stream = stream; // make stream available to console
- preview.srcObject = stream;
- return navigator.mediaDevices.enumerateDevices();
- }
- function start() {
- if (window.stream) {
- window.stream.getTracks().forEach(function (track) {
- track.stop();
- });
- }
- var videoSource = $('.camera-select').val();
- var constraints = {
- audio: false,
- // video: true,
- video: { deviceId: videoSource ? { exact: videoSource } : undefined }
- };
- navigator.mediaDevices.getUserMedia(constraints).
- then(gotStream).catch(handleError);
- }
- function handleError(error) {
- console.log('navigator.getUserMedia error: ', error);
- }
- $('.camera-select').on('change', function () {
- console.log('Camera changed');
- start();
- })
- start();
- cameraRun = true;
- $('ons-button[name="continue"]').on('click', function () {
- nav.pushPage('./templates/photos.html', {
- data: { session: sessionData }
- });
- });
- if (window.File && window.FileReader && window.FileList && window.Blob) {
- document.getElementById('add-photo').onchange = function () {
- var files = document.getElementById('add-photo').files;
- for (var i = 0; i < files.length; i++) {
- var file = files[i];
- var reader = new FileReader();
- reader.onloadend = function () {
- var tempImg = new Image();
- tempImg.src = reader.result;
- tempImg.onload = function () {
- var MAX_WIDTH = 900;
- var MAX_HEIGHT = 600;
- var tempW = tempImg.width;
- var tempH = tempImg.height;
- if (tempW > tempH) {
- if (tempW > MAX_WIDTH) {
- tempH *= MAX_WIDTH / tempW;
- tempW = MAX_WIDTH;
- }
- } else {
- if (tempH > MAX_HEIGHT) {
- tempW *= MAX_HEIGHT / tempH;
- tempH = MAX_HEIGHT;
- }
- }
- function drawRotated(degrees, img, canvas, ctx, o) {
- var w = tempW,
- h = tempH;
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.save();
- if (o == 8) {
- ctx.translate(0, canvas.height * 1.5);
- w *= 1.5;
- h *= 1.5;
- }
- else if (o == 6) {
- ctx.translate(canvas.width / 2 + tempW / 2, -canvas.height + tempH / 6);
- w *= 1.5;
- h *= 1.5;
- }
- else if (o == 3) {
- ctx.translate(canvas.width, canvas.height);
- }
- ctx.rotate(degrees * Math.PI / 180);
- ctx.drawImage(img, 0, 0, w, h); //draw the image ;)
- ctx.restore();
- }
- var canvas = document.createElement('canvas');
- canvas.width = tempW;
- canvas.height = tempH;
- var ctx = canvas.getContext("2d");
- ctx.drawImage(this, 0, 0, tempW, tempH);
- var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(reader.result));
- switch (exif.Orientation) {
- case 8:
- drawRotated(-90, this, canvas, ctx, exif.Orientation);
- break;
- case 3:
- drawRotated(180, this, canvas, ctx, exif.Orientation);
- break;
- case 6:
- drawRotated(90, this, canvas, ctx, exif.Orientation);
- break;
- }
- var base64 = canvas.toDataURL("image/jpeg"),
- item = {
- 'id': startId++,
- 'base64': base64,
- 'selected': false,
- 'angle': 0
- };
- photos.push(item);
- if (i == files.length) {
- setTimeout(function () {
- app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
- if (updated) {
- console.log('updated!');
- nav.pushPage('./templates/photos.html');
- } else console.log('not updated');
- });
- }, 1000);
- }
- }
- }
- reader.readAsDataURL(file);
- }
- };
- } else {
- alert('The File APIs are not fully supported in this browser.');
- }
- }
- function photosActivity() {
- //checked parametr
- var sessionData = null,
- cId = null,
- photos = null,
- startId = 0;
- if (!app.store.cameraEnable) {
- $('ons-if.cam-button').remove();
- }
- app.getSessionFromDB(app.currentSessionId).then(function (session) {
- sessionData = session;
- photos = sessionData.photos;
- cId = sessionData.cover;
- if (photos.length > 0)
- startId = photos.length;
- else startId = 0;
- if (sessionData.email !== null && sessionData.email !== app.defaultEmail) $('#email-client').val(sessionData.email);
- app.renderPhotosV2().then(function () {
- setCover($('.list-item[data-photo-id="' + cId + '"]'));
- photos.forEach(function (item, index, photos) {
- if (item.selected) {
- setPhotoSelected($('.list-item[data-photo-id="' + item.id + '"]'))
- }
- });
- calculateSelected();
- });
- });
- //list-item
- $('body').unbind().on('click', '.overlay-event', function () {
- setPhotoSelected($(this).parent().parent(), false);
- });
- //[START]
- function calculateSelected() {
- var count = 0;
- app.getSessionFromDB(app.currentSessionId).then(function (session) {
- var photos = session.photos;
- if (photos.length > 0) {
- photos.forEach(function (item, index, photos) {
- if (item.selected) count++;
- });
- }
- if (count >= 1) $('ons-button[name="publish"]').prop('disabled', false);
- else $('ons-button[name="publish"]').prop('disabled', true);
- });
- }
- function setPhotoSelected(el, setOnly) {
- var photoId = el.data('photo-id'),
- isSelected = el.data('isselected'),
- isCover = el.data('iscover');
- if (isCover !== 1) {
- if (isSelected === 0) {
- el.data('isselected', 1);
- el.find('.overlay-selected').addClass('active');
- app.togglePhotoSelectedV2(photoId, true).then(function () {
- calculateSelected();
- });
- calculateSelected();
- } else if (isSelected === 1 && setOnly === false) {
- el.data('isselected', 0);
- el.find('.overlay-selected').removeClass('active');
- app.togglePhotoSelectedV2(photoId, false).then(function () {
- calculateSelected();
- });
- }
- }
- }
- function setCover(el) {
- var isCover = el.data('iscover'),
- photoId = el.data('photo-id');
- if (isCover === 0) {
- setPhotoSelected(el, true);
- $('.overlay-cover').removeClass('active');
- $('.list-item').data('iscover', 0);
- el.data('iscover', 1);
- el.find('.overlay-cover').addClass('active');
- db.sessions.update(app.currentSessionId, { cover: photoId }).then(function (isUpd) {
- if (isUpd) console.log('Cover is updated');
- else console.log('Cover is not updated');
- });
- }
- }
- var timeOut = 0;
- $('body').on('mousedown touchstart', '.overlay-event', function (e) { //list-item
- console.log('click');
- var $this = $(this).parent().parent();
- console.log($this);
- timeOut = setTimeout(function () {
- setCover($this);
- console.log('hold!');
- }, 1000);
- }).bind('mouseup mouseleave touchend', function () {
- clearInterval(timeOut);
- });
- if (window.File && window.FileReader && window.FileList && window.Blob) {
- document.getElementById('addPhoto').onchange = function () {
- app.getSessionFromDB(app.currentSessionId).then(function (session) {
- var photos = session.photos;
- var files = document.getElementById('addPhoto').files;
- for (var i = 0; i < files.length; i++) {
- var file = files[i];
- var reader = new FileReader();
- reader.onloadend = function () {
- var tempImg = new Image();
- tempImg.src = reader.result;
- tempImg.onload = function () {
- var MAX_WIDTH = 900;
- var MAX_HEIGHT = 600;
- var tempW = tempImg.width;
- var tempH = tempImg.height;
- if (tempW > tempH) {
- if (tempW > MAX_WIDTH) {
- tempH *= MAX_WIDTH / tempW;
- tempW = MAX_WIDTH;
- }
- } else {
- if (tempH > MAX_HEIGHT) {
- tempW *= MAX_HEIGHT / tempH;
- tempH = MAX_HEIGHT;
- }
- }
- function drawRotated(degrees, img, canvas, ctx, o) {
- var w = tempW,
- h = tempH;
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.save();
- if (o == 8) {
- ctx.translate(0, canvas.height * 1.5);
- w *= 1.5;
- h *= 1.5;
- }
- else if (o == 6) {
- ctx.translate(canvas.width / 2 + tempW / 2, -canvas.height + tempH / 6);
- w *= 1.5;
- h *= 1.5;
- }
- else if (o == 3) {
- ctx.translate(canvas.width, canvas.height);
- }
- ctx.rotate(degrees * Math.PI / 180);
- ctx.drawImage(img, 0, 0, w, h); //draw the image ;)
- ctx.restore();
- }
- var canvas = document.createElement('canvas');
- canvas.width = tempW;
- canvas.height = tempH;
- var ctx = canvas.getContext("2d");
- ctx.drawImage(this, 0, 0, tempW, tempH);
- var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(reader.result));
- switch (exif.Orientation) {
- case 8:
- drawRotated(-90, this, canvas, ctx, exif.Orientation);
- break;
- case 3:
- drawRotated(180, this, canvas, ctx, exif.Orientation);
- break;
- case 6:
- drawRotated(90, this, canvas, ctx, exif.Orientation);
- break;
- }
- var base64 = canvas.toDataURL("image/jpeg"),
- item = {
- 'id': startId++,
- 'base64': base64,
- 'selected': false,
- 'angle': 0
- };
- photos.push(item);
- if (i == files.length) {
- app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
- if (updated) {
- app.renderPhotosV2().then(function () {
- app.getSessionFromDB(sessionData.id).then(function (session) {
- photos = session.photos;
- setCover($('.list-item[data-photo-id="' + cId + '"]'));
- photos.forEach(function (item, index, photos) {
- if (item.selected) setPhotoSelected($('.list-item[data-photo-id="' + item.id + '"]'))
- });
- calculateSelected();
- });
- console.log('updated');
- });
- } else console.log('not updated');
- });
- }
- }
- }
- reader.readAsDataURL(file);
- }
- });
- };
- } else {
- alert('The File APIs are not fully supported in this browser.');
- }
- $('#email-client').on('click', function () {
- $(this).removeAttr('value');
- });
- $('#email-client').on('change', function () {
- var $email = $(this).val();
- app.setSessionEmail(app.currentSessionId, $email).then(function () {
- console.log('Email changed');
- });
- });
- $('ons-button[name="back-btn"]').on('click', function () {
- $('#photos_list').empty();
- nav.resetToPage('./templates/tags-new-session.html', {
- animation: "slide"
- });
- });
- $('ons-button[name="finish-later"]').on('click', function () {
- $('#photos_list').empty();
- app.currentSessionId = null;
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- });
- if (isAndroid) {
- $('ons-button[name="take-photos-btn"]').on('click', function () {
- $('#photos_list').empty();
- nav.resetToPage('./templates/camera.html', {
- animation: "slide"
- });
- });
- }
- $('ons-button[name="publish"]').on('click', function () {
- if (navigator.onLine === false) {
- ons.notification.confirm({
- message: 'No internet connection. You can save a Cut and upload later.',
- callback: function (t) {
- if (t === 1) {
- app.currentSessionId = null;
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- }
- }
- });
- } else {
- var modal = document.getElementById('modal');
- modal.show();
- //post data on server
- app.sendData(app.currentSessionId, function () {
- app.removeSessionByIdV2(app.currentSessionId).then(function () {
- app.currentSessionId = null;
- modal.hide();
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- });
- }, function (err) {
- ons.notification.confirm({
- title: err + ' 403 ',
- message: 'Save and upload later?',
- callback: function (t) {
- if (t === 1) {
- app.saveCurrentSession();
- nav.resetToPage('./templates/session.html', {
- animation: "slide"
- });
- } else {
- modal.hide();
- }
- }
- });
- });
- }
- });
- }
- // Service Worker
- // if ('serviceWorker' in navigator) {
- // navigator.serviceWorker
- // .register('./service-worker.js')
- // .then(function () { console.log('Service Worker Registered'); });
- // }
- });
- function convertTitle(session) {
- var newTitle = '';
- if (session.specials === '7') newTitle += 'kids - ';
- switch (parseInt(session.cut)) {
- case 4: newTitle += 'long - '; break;
- case 3: newTitle += 'medium - '; break;
- case 2: newTitle += 'short - '; break;
- case 22: newTitle += 'asymmetric - '; break;
- }
- switch (parseInt(session.color)) {
- case 13: newTitle += 'blond - '; break;
- case 14: newTitle += 'brown - '; break;
- case 17: newTitle += 'dark - '; break;
- case 15: newTitle += 'red - '; break;
- case 23: newTitle += 'other - '; break;
- }
- switch (parseInt(session.gender)) {
- case 5: newTitle += 'male - '; break;
- case 6: newTitle += 'female - '; break;
- }
- switch (parseInt(session.type)) {
- case 10: newTitle += 'curly - '; break;
- case 11: newTitle += 'straight - '; break;
- case 18: newTitle += 'wavy - '; break;
- }
- switch (parseInt(session.coloration)) {
- case 19: newTitle += 'colored'; break;
- case 20: newTitle += 'natural'; break;
- case 21: newTitle += 'melir'; break;
- }
- return newTitle;
- }
- function dataURLtoBlob(dataurl) {
- var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
- bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- return new Blob([u8arr], { type: mime });
- }
- function getBase64(file, callback) {
- var reader = new FileReader();
- reader.addEventListener('load', function () {
- callback(reader.result);
- }, false);
- reader.readAsDataURL(file);
- }
- function resizeImage(file, callback) {
- var canvas = document.getElementById('canvas-resize');
- var img = document.createElement("img");
- var reader = new FileReader();
- reader.onload = function (e) {
- img.src = e.target.result;
- }
- reader.readAsDataURL(file);
- var ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0);
- var MAX_WIDTH = 900,
- MAX_HEIGHT = 600,
- width = img.width,
- height = img.height;
- if (width > height) {
- if (width > MAX_WIDTH) {
- height *= MAX_WIDTH / width;
- width = MAX_WIDTH;
- }
- } else {
- if (height > MAX_HEIGHT) {
- width *= MAX_HEIGHT / height;
- height = MAX_HEIGHT;
- }
- }
- canvas.width = width;
- canvas.height = height;
- var ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0, width, height);
- var dataurl = canvas.toDataURL("image/png");
- callback(dataurl);
- }
- function getCurrentDate() {
- var today = new Date();
- var dd = today.getDate();
- var mm = today.getMonth() + 1; //January is 0!
- var yyyy = today.getFullYear();
- if (dd < 10) {
- dd = '0' + dd;
- }
- if (mm < 10) {
- mm = '0' + mm;
- }
- var today = dd + '.' + mm + '.' + yyyy;
- return today;
- }
- function base64ToArrayBuffer(base64) {
- base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
- var binaryString = atob(base64);
- var len = binaryString.length;
- var bytes = new Uint8Array(len);
- for (var i = 0; i < len; i++) {
- bytes[i] = binaryString.charCodeAt(i);
- }
- return bytes.buffer;
- }
Add Comment
Please, Sign In to add comment