angular.module('starter.controllers', ["angular-humanize", 'mcot.filters']) .controller('AppCtrl', function($scope, $ionicModal, $timeout, $cordovaFacebook, mcotcms, $cordovaSQLite, $location, $ionicHistory, $ionicPopup, $state, $ionicLoading, $cordovaLocalNotification, $rootScope, $interval, $cordovaOauth, $cordovaInAppBrowser, $http) { $scope.data = { bcount: 0 }; $scope.igLogin = function(){ $cordovaOauth.instagram("aede22fcf7a145779da9a3cd094069f5", ["basic"]) .then(function(success){ console.log(success); var token = success.access_token; $http.get("https://api.instagram.com/v1/users/self/?access_token="+token) .then(function(success){ console.log(success); }, function(error){ console.log(error); }); },function(error){ console.log(error); }); }; $scope.twitterlogin = function(){ console.log("twitter login"); var api_key = "VNA6F7wAAwn10KJ7vqhdUPVzR"; //Enter your Consumer Key (API Key) var api_secret = "bJDNQhpZPlScH45WuARaJtvv0fMTR68AVTI3VbsfImeht8tt3S"; // Enter your Consumer Secret (API Secret) console.log("twitterlogin function got called"); /* var options = { location: 'yes', clearcache: 'yes', toolbar: 'no' }; $cordovaInAppBrowser.open('http://ngcordova.com', '_blank') .then(function(event) { // success }) .catch(function(event) { // error });*/ /* $cordovaOauth.twitter(api_key, api_secret).then(function(result) { console.log(result); }, function(error){ console.log(error); });*/ $cordovaOauth.google("314112088577-mqifo59b09psg38fg5l3s27e8h2ihj2c.apps.googleusercontent.com", ["email"]).then(function(result) { console.log("Response Object -> " + JSON.stringify(result)); }, function(error) { console.log("Error -> " + error); }); }; $rootScope.$on('$cordovaInAppBrowser:loaderror', function(e, event) { console.log("load error"); console.log(e); console.log(event); }); $scope.authenticate = function(provider) { $auth.authenticate(provider); }; /* $interval(function() { //$scope.fetchNotification(); $cordovaLocalNotification.schedule({ id: Math.floor(Date.now() / 1000), title: 'test noti', text: 'description', }).then(function(result) { console.log(result); }); console.log("noti"); }, 5000);*/ $scope.fetchNotification = function(){ var token = mcotcms.get_token(); if( token !== null ){ mcotcms.fetch_noti(token, {type: 'post'}) .then(function(success){ console.log("fetch_noti"); $scope.data.bcount = success.data.output.length; for(var i = 0; i < success.data.output.length; i++) { post = success.data.output[i]; console.log("the post"); console.log(post); $cordovaLocalNotification.schedule({ id: post._id.$oid, title: post.title, text: post.description, data: { oid: success.data.output[i]._id.$oid } }).then(function(result) { console.log(result); }); } }, function(error){ }); } }; $scope.scheduleSingleNotification = function() { var now = new Date().getTime(); var _10SecondsFromNow = new Date(now + 10 * 1000); console.log("run notification"); /* $cordovaLocalNotification.schedule({ id: 1, title: 'Title here', text: 'Text here', at: _10SecondsFromNow }).then(function(result) { console.log(result); });*/ }; $rootScope.$on('$cordovaLocalNotification:trigger', function(event, notification, state) { console.log("trigger"); console.log(event); console.log(notification); console.log(state); }); $rootScope.$on('$cordovaLocalNotification:update', function(event, notification, state) { console.log("update"); console.log(event); console.log(notification); console.log(state); }); $rootScope.$on('$cordovaLocalNotification:click', function(event, notification, state) { console.log("click"); console.log(event); console.log(notification); console.log(state); var d = angular.fromJson(notification.data); console.log(d); $state.go("app.view", { id: d.oid}); }); $scope.loadData = function() { //console.log(db); console.log(window.localStorage); console.log("load call"); mcotcms.load_personal_data("token") .then( function(res) { if (res.rows.length > 0) { $scope.newMessage = res.rows.item(0); $scope.statusMessage = "Message loaded successful, cheers!"; } }, function(error) { $scope.statusMessage = "Error on loading: " + error.message; } ); }; // With the new view caching in Ionic, Controllers are only called // when they are recreated or on app start, instead of every page change. // To listen for when this page is active (for example, to refresh data), // listen for the $ionicView.enter event: //$scope.$on('$ionicView.enter', function(e) { //}); // Form data for the login modal $scope.loginData = {}; $scope.signupData = {}; $scope.showAlert = function(title, text) { var alertPopup = $ionicPopup.alert({ title: title, template: text }); alertPopup.then(function(res) { console.log('Thank you for not eating my delicious ice cream cone'); }); }; $scope.logout = function() { if (angular.isDefined($scope.modal)) $scope.modal.hide(); if (angular.isDefined($scope.signup_modal)) $scope.signup_modal.hide(); mcotcms.clear_data(); $ionicHistory.nextViewOptions({ disableBack: true }); $state.go('app.index'); $cordovaFacebook.logout() .then(function(success) { // success console.log("logout"); console.log(success); }, function(error) { // error }); }; $scope.doSignUp = function() { if ($scope.signupData.password == $scope.signupData.confirm_password) { $scope.signupData.message = "Success"; mcotcms.add_user_by_form({ email: $scope.signupData.email, password: $scope.signupData.password }) .then(function(success) { console.log("add user "); //mcotcms.execute(); //mcotcms.select(); console.log(success); $scope.signup_modal.hide(); $scope.$emit('requireLogin', {}) /* $cordovaSQLite.execute(db, 'INSERT INTO Messages (message) VALUES (?)', ["tum"]) .then(function(result) { $scope.statusMessage = "Message saved successful, cheers!"; }, function(error) { $scope.statusMessage = "Error on saving: " + error.message; })*/ }, function(error) { console.log("add erro user "); console.log(error); $scope.$emit("signupError", { msg: error.data.error }) //console.log(error); //$scope.statusMessage = err.data.error; //console.log(err); }); } else { $scope.signupData.message = "Not Matched"; } }; $scope.getStatus = function() { $cordovaFacebook.getLoginStatus() .then(function(success) { console.log("get status"); console.log(success); /* { authResponse: { userID: "12345678912345", accessToken: "kgkh3g42kh4g23kh4g2kh34g2kg4k2h4gkh3g4k2h4gk23h4gk2h34gk234gk2h34AndSoOn", session_Key: true, expiresIn: "5183738", sig: "..." }, status: "connected" } */ }, function(error) { // error }); }; $scope.fblogin = function() { $cordovaFacebook.login(["public_profile", "email", "user_friends"]) .then(function(login_obj) { console.log("fb login"); console.log(login_obj); $cordovaFacebook.api("me", ["public_profile"]) .then(function(me_obj) { console.log("me"); //console.log(me_obj); mcotcms.add_user({ 'login': login_obj, 'me': me_obj }) .then(function(result) { console.log(" success add_user "); console.log(result.data.token); mcotcms.store_token(result.data.token) .then(function(result) { $scope.$emit('signinSuccess', {}); }, function(error) { console.log(error); }); }, function(err) { console.log(err); }); }, function(error) { console.log("error fb"); }); // { id: "634565435", // lastName: "bob" // ... // } }, function(error) { console.log("error fb"); }); }; // Create the login modal that we will use later $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; }); $scope.openLoginDialog = function() { console.log("modal"); console.log($scope.modal); }; // Create the login modal that we will use later $scope.$on('requireLogin', function(event, args) { if( angular.isDefined($scope.modal)) { $scope.modal.remove(); } $ionicModal.fromTemplateUrl('templates/login.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; $scope.modal.show(); }); //$scope.openLoginDialog(); }); $scope.$on('logoutEvent', function(event, args) { $scope.logout(); }); $scope.$on('signinError', function(event, args) { console.log("Sign In Error"); $scope.showAlert("Sign In Error", args.msg); }); $scope.$on('showLoading', function(event, args) { console.log("show loading"); $ionicLoading.show({ template: args.text }).then(function() { console.log("The loading indicator is now displayed"); }); }); $scope.$on('hideLoading', function(event, args) { $ionicLoading.hide().then(function() { console.log("The loading indicator is now hidden"); }); }); $scope.$on('signupError', function(event, args) { console.log("Sign Up Error"); $scope.showAlert("Sign Up Error", args.msg); }); $scope.$on('signinSuccess', function(event, args) { console.log("Sign in success"); $state.go("app.index"); $scope.closeLogin(); $scope.closeSignUp(); }); $ionicModal.fromTemplateUrl('templates/signup.html', { scope: $scope }).then(function(su_modal) { $scope.signup_modal = su_modal; }); // Triggered in the login modal to close it $scope.closeLogin = function() { console.log("close sigin"); if(angular.isDefined($scope.modal)) $scope.modal.hide(); var token = mcotcms.get_token(); console.log(token); if (token == 'null') { console.log('null ?'); $ionicHistory.nextViewOptions({ disableBack: true }); $state.go('app.index'); } }; $scope.closeSignUp = function() { if( angular.isDefined($scope.signup_modal)) $scope.signup_modal.hide(); var token = mcotcms.get_token(); if (token == null) { $ionicHistory.nextViewOptions({ disableBack: true }); $state.go('app.index'); } }; // Open the login modal $scope.login = function() { $scope.modal.show(); }; // Perform the login action when the user submits the login form $scope.doLogin = function() { console.log('Doing login', $scope.loginData); // Simulate a login delay. Remove this and replace with your login // code if using a login system mcotcms.login($scope.loginData.username, $scope.loginData.password) .then(function(success) { console.log(success); mcotcms.store_token(success.data.access_token) .then(function(result) { console.log(result); }, function(error) { console.log(error); }); }, function(error) { $scope.$emit("signinError", { msg: error.data.description }) console.log(error); }); $timeout(function() { $scope.closeLogin(); }, 1000); }; }) .controller('RequireLoginCtrl', function($scope, mcotcms, $location) { console.log("check login ..."); var token = mcotcms.get_token(); if (token == 'null' || token == null) { console.log("token null"); mcotcms.store_token(null); $scope.$emit('requireLogin', {}); } }) .controller('UtilCtrl', function($scope, mcotcms, $location) { $scope.toDate = function(mongoDate) { console.log(mongoDate) if( angular.isDefined(mongoDate) ) { return new Date(mongoDate.$date); }else { return new Date(); } }; $scope.go = function ( path ) { $location.path( path ); }; $scope.fav = function(post_id, type) { var token = mcotcms.get_token(); mcotcms.add_fav(token, post_id, type) .then(function(success) { console.log(success); }, function(error) { console.log(error); }); }; }) .controller('LoadMoreCtrl', function($scope, mcotcms, PAGE_LIMIT) { $scope.current_page = 0; $scope.is_empty = true; $scope.moreDataCanBeLoaded = function() { console.log("more data canbe loaded"); return $scope.is_empty == false; }; $scope.firstLoad = function() { console.log("load 1"); $scope.is_empty = true; if (angular.isUndefined($scope.results)) { $scope.results = []; } if (angular.isDefined($scope.special_action)) { console.log("wait im"); if ($scope.special_action == "get_fav") { var the_query = mcotcms.get_fav($scope.token, { 'page': $scope.current_page++, 'type': 'post' }); } else if ($scope.special_action == "get_nearby") { console.log("get nearby"); var the_query = mcotcms.nearby($scope.position, { 'page': $scope.current_page++, 'type': 'post' }); } } else { var the_query = mcotcms.get_posts({ 'query': $scope.query, 'page': $scope.current_page++, 'version': $scope.post_version }); } the_query.then(function successCallback(response) { // this callback will be called asynchronously // when the response is available console.log("first load"); console.log(response.data) if (response.data.output.length == 0) { $scope.is_empty = true; return; } var output = []; // for(var i = 0; i < 10; i++ ){ output = output.concat(response.data.output); //} console.log("update results"); $scope.results = $scope.results.concat(output); console.log($scope.results); $scope.is_empty = false; //$scope.$broadcast('scroll.infiniteScrollComplete'); //$scope.results = response.data.output; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); }; $scope.firstLoad(); $scope.loadMoreData = function() { console.log("load more 2"); if ($scope.is_empty == true) { return; } if (angular.isUndefined($scope.results)) { console.log("recreate "); $scope.results = []; } if (angular.isDefined($scope.special_action)) { console.log("wait im"); if ($scope.special_action == "get_fav") { var the_query = mcotcms.get_fav($scope.token, { 'page': $scope.current_page++, 'type': 'post' }); } else if ($scope.special_action == "get_nearby") { var the_query = mcotcms.nearby($scope.position, { 'page': $scope.current_page++, 'type': 'post' }); } } else { var the_query = mcotcms.get_posts({ 'query': $scope.query, 'page': $scope.current_page++, 'version': $scope.post_version }) } the_query.then(function successCallback(response) { // this callback will be called asynchronously // when the response is available console.log("... =>"); console.log(response.data.output.length); if (response.data.output.length == 0) { $scope.is_empty = true; return; } console.log("not empty "); var output = []; /* for(var i = 0; i < 10; i++ ){*/ output = output.concat(response.data.output); /*}*/ console.log("update results"); $scope.results = $scope.results.concat(output); $scope.is_empty = false; $scope.$broadcast('scroll.infiniteScrollComplete'); //$scope.results = response.data.output; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); }; $scope.$on('$stateChangeSuccess', function() { $scope.loadMoreData(); }); }) .controller('FavCtrl', function($scope, mcotcms, $controller) { $scope.query = {}; $scope.post_version = "short"; $scope.special_action = "get_fav"; $controller('RequireLoginCtrl', { $scope: $scope }); $scope.token = mcotcms.get_token(); if ($scope.token != 'null') { $controller('LoadMoreCtrl', { $scope: $scope }); } }) .controller('ByAuthorCtrl', function($scope, $stateParams, $controller, mcotcms) { console.log($stateParams); $scope.catname = $stateParams.uid; $scope.uid = $stateParams.uid; $scope.query = { 'author': $stateParams.uid }; $scope.post_version = "short"; mcotcms.by_author($scope.uid) .then(function(success){ console.log("author"); console.log(success); $scope.by_author = success.data.output; },function(error){ }); $controller('LoadMoreCtrl', { $scope: $scope }); }) .controller('NearbyCtrl', function($scope, mcotcms, $controller, $cordovaGeolocation, $ionicLoading) { $scope.query = {}; var posOptions = { timeout: 10000, enableHighAccuracy: false }; $scope.$emit("showLoading", { text: "Getting Current Position" }); $cordovaGeolocation .getCurrentPosition(posOptions) .then(function(position) { var lat = position.coords.latitude var long = position.coords.longitude $scope.position = position.coords; $scope.post_version = "short"; $scope.special_action = "get_nearby"; console.log(position.coords); console.log("get nearby call"); $scope.$emit("hideLoading", {}); $controller('LoadMoreCtrl', { $scope: $scope }); }, function(err) { // error }); }) .controller('PlaylistsCtrl', function($scope) { $scope.playlists = [{ title: 'Reggae', id: 1 }, { title: 'Chill', id: 2 }, { title: 'Dubstep', id: 3 }, { title: 'Indie', id: 4 }, { title: 'Rap', id: 5 }, { title: 'Cowbell', id: 6 }]; $scope.settingsList = [{ text: "Wireless", checked: true }, { text: "GPS", checked: false }, { text: "Bluetooth", checked: false }]; }) .controller('SettingCtrl', function($scope, mcotcms, $controller) { $controller('RequireLoginCtrl', { $scope: $scope }); var token = mcotcms.get_token(); $scope.token = token; $scope.openUserLink = function() { window.open('http://mcot-simplitic.simplico.net/user_panel/'+$scope.token, '_system'); }; console.log("token ", token); $scope.categories = [{ title: "nearme", value: true }, { title: "Breaking News", value: true }, { title: "ข่าวพาดหัว", value: true }, { title: "health", value: true }, { title: "fashion", value: true }, { title: "perspective", value: true }, { title: "idea", value: true }, { title: "outlook", value: true }, { title: "phototalk", value: true }, ]; $scope.$on('$destroy', function() { console.log("leaving from setting"); console.log($scope.categories); mcotcms.save_settings(token, $scope.categories); }); mcotcms.get_settings(token) .then(function(success) { var cat_serv = success.data.output; console.log(cat_serv); for (var i in $scope.categories) { c = $scope.categories[i]; console.log(cat_serv[c.title]); if (cat_serv[c.title] != true) { c.value = false; } } }, function(error) { console.log("errror ..", error); mcotcms.store_token(null); //$scope.$emit("requireLogin", {}); }); $scope.logout = function() { console.log("logout ..."); $scope.$emit('logoutEvent', {}); }; }) .controller('IndexPageCtrl', function($scope, mcotcms, $controller) { $scope.query = { 'categories.text': 'TNA'}; $scope.post_version = "short"; $controller('UtilCtrl', { $scope: $scope }); $controller('LoadMoreCtrl', { $scope: $scope }); /* mcotcms.all_posts() .then(function successCallback(response) { // this callback will be called asynchronously // when the response is available var output = []; for(var i = 0; i < 10; i++ ){ output = output.concat(response.data.output); } $scope.results = output ; //$scope.results = response.data.output; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. });*/ }) .controller('PlaylistCtrl', function($scope, $stateParams) {}) .controller('LoginCtrl', function($scope, $stateParams, $cordovaFacebook) { $scope.login = function() { $cordovaFacebook.login(["public_profile", "email", "user_friends"]) .then(function(success) { console.log(success); // { id: "634565435", // lastName: "bob" // ... // } }, function(error) { // error }); }; }) .controller('ViewCtrl', function($scope, $stateParams, mcotcms, $cordovaDatePicker, $cordovaSocialSharing, $filter, $controller, $sce, PUBLIC_TOKEN) { //var deviceType = (navigator.userAgent.match(/iPad/i)) == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i)) == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null"; var isIOS = ionic.Platform.isIOS(); var isAndroid = ionic.Platform.isAndroid(); //console.log(deviceType); console.log("is IOS ", isIOS); console.log("is ANd ", isAndroid); var id = $stateParams.id; $controller('UtilCtrl', { $scope: $scope }); $scope.openMap = function(loc) { window.open("https://www.google.com/maps?q="+loc[1]+","+loc[0],'_system'); }; mcotcms.get_share(id) .then(function(success){ console.log(success); $scope.shareCounts = success.data.output; },function(error){ }); mcotcms.get_post_by_id(id) .then(function successCallback(response) { $scope.post = response.data.output[0]; $scope.post_body = $sce.trustAsHtml($scope.post.body); mcotcms.by_author($scope.post['author']) .then(function(success){ console.log("author"); console.log(success); $scope.by_author = success.data.output; },function(error){ }); mcotcms.post_api(PUBLIC_TOKEN, "LIST", { query: {'categories.text': $scope.post.categories[$scope.post.categories.length - 1].text} }) .then(function(success){ $scope.more_ons = success.data.output; }, function(error){ }); }, function errorCallback(response) {}); $scope.doSomething = function() { var options = { date: new Date(), mode: 'date', // or 'time' minDate: new Date() - 10000, allowOldDates: true, allowFutureDates: false, doneButtonLabel: 'DONE', doneButtonColor: '#F2F3F4', cancelButtonLabel: 'CANCEL', cancelButtonColor: '#000000' }; $cordovaDatePicker.show(options).then(function(date) { alert(date); }); }; $scope.share = function() { var link_url = "http://www.tnamcot.com/view/" + $scope.post._id.$oid; $cordovaSocialSharing //.share($scope.post.title + " | " + $scope.post.description + ' ' + link_url, null, null, link_url) // Share via native share sheet .share(null, null, null, link_url) // Share via native share sheet .then(function(result) { // Success! console.log("share result ", result); if (result == true) { console.log("share true !!"); mcotcms.update_share($scope.post._id.$oid) .then(function successCallBack(response) { console.log("share ok"); }, function errorCallback(response) { console.log("fail"); }); } console.log("Share completed? ", result.completed); // On Android apps mostly return false even while it's true console.log("Shared to app: ", result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false) }, function(err) { // An error occured. Show a message to the user console.log("share error ", err); }); }; }) .controller('ListPageCtrl', function($scope, $stateParams, $controller, mcotcms) { console.log($stateParams); $scope.catname = $stateParams.catname; $scope.query = {'categories.text': $stateParams.catname}; $controller('LoadMoreCtrl', { $scope: $scope }); }) .controller('SearchCtrl', function($scope, $stateParams, $http, $ionicHistory, mcotcms, $controller) { console.log("search ctrl"); $scope.search = ""; $scope.search2 = ""; $scope.query = {'categories.text': 'TNA'}; $scope.post_version = "short"; $controller('UtilCtrl', { $scope: $scope }); $controller('LoadMoreCtrl', { $scope: $scope }); $scope.change = function(v) { $scope.query = {'title': {'$regex': v} }; $scope.results = []; $scope.current_page = 0; $scope.firstLoad(); }; });