diff options
author | Loic Blot <loic.blot@unix-experience.fr> | 2017-12-28 20:34:15 +0300 |
---|---|---|
committer | Loic Blot <loic.blot@unix-experience.fr> | 2017-12-28 20:34:15 +0300 |
commit | cc14f868936e06cdc9d1c626a8ff8d9914a92214 (patch) | |
tree | 6046373552f6d5582c9ba987537fd2705890dfdc /js | |
parent | 0c54bfbf060270de12db8b9f92212bd34604c807 (diff) |
Move generateUrl to Sms object, add SmsSettings::init & drop it from angular app
Diffstat (limited to 'js')
-rw-r--r-- | js/app.min.js | 2 | ||||
-rw-r--r-- | js/devel/app.js | 14 | ||||
-rw-r--r-- | js/devel/legacy.js | 61 | ||||
-rw-r--r-- | js/devel/notifications.js | 4 | ||||
-rw-r--r-- | js/devel/settings.js | 28 |
5 files changed, 58 insertions, 51 deletions
diff --git a/js/app.min.js b/js/app.min.js index 7ac13bf..a9e4ed7 100644 --- a/js/app.min.js +++ b/js/app.min.js @@ -1 +1 @@ -var Sms={selectedConversation:null,unreadCountCurrentConv:0,unreadCountAllConv:0,unreadCountNotifStep:12,lastUnreadCountAllConv:0,originalTitle:document.title};var ContactRenderer={generateColor:function(input){if(typeof input==="undefined"){return""}if(typeof input.toHsl==="function"){var hsl=input.toHsl();return"hsl("+hsl[0]+", "+hsl[1]+"%, "+hsl[2]+"%)"}else{var hash=md5(input).substring(0,4),maxRange=parseInt("ffff",16),hue=parseInt(hash,16)/maxRange*256;return"hsl("+hue+", 90%, 65%)"}},generateFirstCharacter:function(input){if(input.charAt(0)==="+"){return"#"}return input.charAt(0)}};function inArray(val,arr){return $.inArray(val,arr)!==-1}function arrayUnique(arr){return arr.filter(function(item,i,arr){return i===arr.indexOf(item)})}function toBool(str){if(str==="true"){return true}else if(str==="false"){return false}return null}var app=angular.module("OcSms",[]);app.directive("toInt",function(){return{require:"ngModel",link:function(scope,element,attrs,modelCtrl){modelCtrl.$parsers.push(function(inputValue){return parseInt(inputValue,10)})}}});app.filter("peerColor",function(){return ContactRenderer.generateColor});app.filter("firstCharacter",function(){return ContactRenderer.generateFirstCharacter});app.controller("OcSmsController",["$scope","$interval","$timeout","$compile",function($scope,$interval,$timeout,$compile){$scope.lastConvMessageDate=0;$scope.lastContactListMsgDate=0;$scope.isConvLoading=false;$scope.isContactsLoading=true;$scope.buttons=[{text:"Send"}];$scope.vsettings=SmsSettings;$scope.contacts=[];$scope.messages=[];$scope.totalMessageCount=0;$scope.photoVersion=1;$scope.selectedContact={};$scope.lastSearch="";$scope.generateUrl=function(endpoint){var winRegexp=/(.*)\/ocsms.*/;var match=winRegexp.exec(window.location.href);if(match.length!==2){console.log("A very bad error happened when parsing window location")}return match[1]+"/ocsms"+endpoint};$scope.sendCountry=function(){$.post($scope.generateUrl("/set/country"),{country:$("select[name=intl_phone]").val()})};$scope.setMessageLimit=function(){$.post($scope.generateUrl("/set/msglimit"),{limit:SmsSettings.messageLimit})};$scope.setNotificationSetting=function(){$.post($scope.generateUrl("/set/notification_state"),{notification:SmsSettings.enableNotifications?1:0})};$scope.setContactOrderSetting=function(){$.post($scope.generateUrl("/set/contact_order"),{attribute:SmsSettings.contactOrderBy,reverse:SmsSettings.reverseContactOrder})};$scope.loadConversation=function(contact){OC.Util.History.pushState("phonenumber="+contact.nav);if(contact.nav!==null){$scope.fetchConversation(contact);changeSelectedConversation($("a[mailbox-navigation='"+contact.nav+"']"))}};$scope.fetchConversation=function(contact){if(contact!=null){$scope.selectedContact=contact;$scope.isConvLoading=true}$scope.messages=[];$scope.lastConvMessageDate=0;$.getJSON($scope.generateUrl("/front-api/v1/conversation"),{phoneNumber:$scope.selectedContact.nav},function(jsondata,status){var phoneNumberLabel=$scope.selectedContact.nav;if(typeof jsondata["phoneNumbers"]!=="undefined"){var phoneNumberList=arrayUnique(jsondata["phoneNumbers"]);phoneNumberLabel=phoneNumberList.toString()}$scope.formatConversation(jsondata);$scope.$apply(function(){if(typeof jsondata["contactName"]==="undefined"||jsondata["contactName"]===""){$scope.selectedContact.label=phoneNumberLabel;$scope.selectedContact.opt_numbers=""}else{$scope.selectedContact.label=jsondata["contactName"];$scope.selectedContact.opt_numbers=phoneNumberLabel}$scope.totalMessageCount=jsondata["msgCount"]!==undefined?jsondata["msgCount"]:0;$scope.isConvLoading=false});$("#app-content").scrollTop(1e10)})};$scope.refreshConversation=function(){$.getJSON($scope.generateUrl("/ocsms/front-api/v1/conversation"),{phoneNumber:$scope.selectedContact.nav,lastDate:$scope.lastConvMessageDate},function(jsondata,status){var fmt=$scope.formatConversation(jsondata);var conversationBuf=fmt[1];if(conversationBuf===true){$("#app-content").scrollTop(1e10);if(document.hasFocus()===false){Sms.unreadCountCurrentConv+=parseInt(fmt[0]);document.title=Sms.originalTitle+" ("+Sms.unreadCountCurrentConv+")";$scope.desktopNotify(Sms.unreadCountCurrentConv+" unread message(s) in conversation with "+$scope.selectedContact.label)}}$scope.totalMessageCount=jsondata["msgCount"]!==undefined?parseInt(jsondata["msgCount"]):0})};$scope.checkNewMessages=function(){Sms.unreadCountAllConv=0;$.getJSON($scope.generateUrl("/front-api/v1/new_messages"),{lastDate:$scope.lastContactListMsgDate},function(jsondata,status){var bufferedContacts=[];$.each(jsondata["phonelist"],function(id,val){var fn,peerLabel;if(typeof jsondata["contacts"][id]==="undefined"){peerLabel=id}else{fn=jsondata["contacts"][id];peerLabel=fn}if(!inArray(peerLabel,bufferedContacts)){var contactObj={label:peerLabel,nav:id,unread:parseInt(val)};if(typeof jsondata["photos"][peerLabel]!=="undefined"){contactObj.avatar=jsondata["photos"][peerLabel]}if(typeof jsondata["uids"][peerLabel]!=="undefined"){contactObj.uid=jsondata["uids"][peerLabel]}else{contactObj.uid=peerLabel}$scope.modifyContact(contactObj);bufferedContacts.push(peerLabel);if(id===$scope.selectedContact.nav){changeSelectedConversation($("a[mailbox-navigation='"+id+"']"))}Sms.unreadCountAllConv+=parseInt(val)}});if(Sms.unreadCountNotifStep>0){Sms.unreadCountNotifStep--}if(Sms.unreadCountAllConv>0){if(Sms.unreadCountNotifStep===0||Sms.lastUnreadCountAllConv!==Sms.unreadCountAllConv){$scope.desktopNotify(Sms.unreadCountAllConv+" unread message(s) for all conversations");Sms.unreadCountNotifStep=12;Sms.lastUnreadCountAllConv=Sms.unreadCountAllConv}}})};$scope.removeConversation=function(){$.post($scope.generateUrl("/delete/conversation"),{contact:$scope.selectedContact.label},function(data){$scope.selectedContact.label="";$scope.selectedContact.opt_numbers="";$scope.selectedContact.avatar=undefined;$scope.removeContact($scope.selectedContact);$scope.$apply(function(){$scope.messages=[]});$scope.selectedContact.nav="";OC.Util.History.pushState("")})};$scope.filterSms=function(query){if(query!==$scope.lastSearch){}};OC.Plugins.register("OCA.Search",{attach:function(search){search.setFilter("sms",$scope.filterSms)}});$scope.addContact=function(ct){$scope.$apply(function(){$scope.contacts.push(ct)})};$scope.removeContact=function(ct){var len=$scope.contacts.length;for(var i=0;i<len;i++){var curCt=$scope.contacts[i];if(curCt["nav"]===ct["nav"]){$scope.$apply(function(){$scope.contacts.splice(i,1)});return}}};$scope.modifyContact=function(ct){var len=$scope.contacts.length;for(var i=0;i<len;i++){if($scope.contacts[i]["nav"]===ct["nav"]){$scope.$apply(function(){$scope.contacts[i].unread=parseInt(ct.unread);if(typeof ct.avatar!=="undefined"){$scope.contacts[i].avatar=ct.avatar}})}}};$scope.addConversationMessage=function(msg){$scope.$apply(function(){$scope.messages.push(msg)})};$scope.removeConversationMessage=function(msgId){var len=$scope.messages.length;for(var i=0;i<len;i++){var curMsg=$scope.messages[i];if(curMsg["id"]===msgId){$.post($scope.generateUrl("/delete/message"),{messageId:msgId,phoneNumber:$scope.selectedContact.label},function(data){$scope.$apply(function(){$scope.messages.splice(i,1)})});return}}};$scope.fetchInitialSettings=function(){$.getJSON($scope.generateUrl("/front-api/v1/settings"),function(jsondata,status){if(jsondata["status"]===true){$("#sel_intl_phone").val(jsondata["country"]);$("input[name=setting_msg_per_page]").val(parseInt(jsondata["message_limit"]));$("select[name=setting_notif]").val(jsondata["notification_state"]);$("select[name=setting_contact_order]").val(jsondata["contact_order"]);$("input[name=setting_contact_order_reverse]").val(toBool(jsondata["contact_order_reverse"]));SmsSettings.messageLimit=parseInt(jsondata["message_limit"]);SmsSettings.enableNotifications=parseInt(jsondata["notification_state"])!==0;SmsSettings.contactOrderBy=jsondata["contact_order"];SmsSettings.reverseContactOrder=toBool(jsondata["contact_order_reverse"])}})};$scope.fetchInitialPeerList=function(jsondata){var bufferedContacts=[];$scope.photoVersion=jsondata["photo_version"];$.each(jsondata["phonelist"],function(id,val){var peerLabel;if(typeof jsondata["contacts"][id]==="undefined"){peerLabel=id}else{peerLabel=jsondata["contacts"][id]}if(!inArray(peerLabel,bufferedContacts)){var contactObj={label:peerLabel,nav:id,unread:0,lastmsg:parseInt(val)};if(typeof jsondata["photos"][peerLabel]!=="undefined"){contactObj["avatar"]=jsondata["photos"][peerLabel]}if(typeof jsondata["uids"][peerLabel]!=="undefined"){contactObj.uid=jsondata["uids"][peerLabel]}else{contactObj.uid=peerLabel}$scope.addContact(contactObj);bufferedContacts.push(peerLabel)}});$scope.$apply(function(){$scope.isContactsLoading=false});$scope.lastContactListMsgDate=jsondata["lastRead"]};$scope.formatConversation=function(jsondata){var buf=false;var msgClass="";var msgCount=0;$.each(jsondata["conversation"],function(id,vals){if(vals["type"]===1){msgClass="recv"}else if(vals["type"]===2){msgClass="sent"}else{msgClass=""}if(id/100>$scope.lastConvMessageDate/100){$scope.lastConvMessageDate=id;$scope.addConversationMessage({id:id,type:msgClass,date:new Date(id*1),content:vals["msg"]});buf=true;msgCount++}});return[msgCount,buf]};$scope.desktopNotify=function(msg){if(!SmsSettings.enableNotifications){return}SmsNotifications.notify(msg)};$interval($scope.refreshConversation,1e4);$interval($scope.checkNewMessages,1e4);$timeout(function(){Sms.originalTitle=document.title;$.getJSON($scope.generateUrl("/front-api/v1/peerlist"),function(jsondata,status){$scope.fetchInitialPeerList(jsondata);var pnParam=$.urlParam("phonenumber");if(pnParam!=null){var urlPhoneNumber=decodeURIComponent(pnParam);if(urlPhoneNumber!=null){if($scope.selectedContact.nav===undefined){$scope.selectedContact.label=urlPhoneNumber;$scope.selectedContact.nav=urlPhoneNumber;$scope.selectedContact.avatar=undefined}$scope.fetchConversation(null);changeSelectedConversation($("a[mailbox-navigation='"+urlPhoneNumber+"']"))}}});$scope.fetchInitialSettings();SmsNotifications.init();$scope.checkNewMessages()})}]);$.urlParam=function(name){var results=new RegExp("[?&]"+name+"=([^&#]*)").exec(window.location.href);if(results==null){return null}else{return results[1]||0}};function changeSelectedConversation(item){if(item==="undefined"||item==null){return}if(Sms.selectedConversation!=null){Sms.selectedConversation.parent().removeClass("selected")}Sms.selectedConversation=item;Sms.selectedConversation.parent().addClass("selected");Sms.selectedConversation.css("font-weight","normal");Sms.selectedConversation.html(Sms.selectedConversation.attr("mailbox-label"))}(function($,OC){window.onfocus=function(){Sms.unreadCountCurrentConv=0;document.title=Sms.originalTitle}})(jQuery,OC);var SmsNotifications={init:function(){if(!("Notification"in window)){return}Notification.requestPermission(function(permission){if(!("permission"in Notification)){Notification.permission=permission}})},notify:function(message){if(!("Notification"in window)){return}if(Notification.permission==="granted"){new Notification("Phone Sync - "+message)}else if(Notification.permission!=="denied"){Notification.requestPermission(function(permission){if(!("permission"in Notification)){Notification.permission=permission}if(permission==="granted"){new Notification("Phone Sync - "+message)}})}}};var SmsSettings={messageLimit:100,enableNotifications:true,contactOrderBy:"lastmsg",reverseContactOrder:true}; +var Sms={selectedConversation:null,unreadCountCurrentConv:0,unreadCountAllConv:0,unreadCountNotifStep:12,lastUnreadCountAllConv:0,originalTitle:document.title,_winRegexp:/(.*)\/ocsms.*/,generateURL:function(endpoint){var match=this._winRegexp.exec(window.location.href);if(match.length!==2){console.log("A very bad error happened when parsing window location")}return match[1]+"/ocsms"+endpoint}};var ContactRenderer={generateColor:function(input){if(typeof input==="undefined"){return""}if(typeof input.toHsl==="function"){var hsl=input.toHsl();return"hsl("+hsl[0]+", "+hsl[1]+"%, "+hsl[2]+"%)"}else{var hash=md5(input).substring(0,4),maxRange=parseInt("ffff",16),hue=parseInt(hash,16)/maxRange*256;return"hsl("+hue+", 90%, 65%)"}},generateFirstCharacter:function(input){if(input.charAt(0)==="+"){return"#"}return input.charAt(0)}};function inArray(val,arr){return $.inArray(val,arr)!==-1}function arrayUnique(arr){return arr.filter(function(item,i,arr){return i===arr.indexOf(item)})}function toBool(str){if(str==="true"){return true}else if(str==="false"){return false}return null}var app=angular.module("OcSms",[]);app.directive("toInt",function(){return{require:"ngModel",link:function(scope,element,attrs,modelCtrl){modelCtrl.$parsers.push(function(inputValue){return parseInt(inputValue,10)})}}});app.filter("peerColor",function(){return ContactRenderer.generateColor});app.filter("firstCharacter",function(){return ContactRenderer.generateFirstCharacter});app.controller("OcSmsController",["$scope","$interval","$timeout","$compile",function($scope,$interval,$timeout,$compile){$scope.lastConvMessageDate=0;$scope.lastContactListMsgDate=0;$scope.isConvLoading=false;$scope.isContactsLoading=true;$scope.buttons=[{text:"Send"}];$scope.vsettings=SmsSettings;$scope.contacts=[];$scope.messages=[];$scope.totalMessageCount=0;$scope.photoVersion=1;$scope.selectedContact={};$scope.lastSearch="";$scope.sendCountry=function(){$.post(Sms.generateURL("/set/country"),{country:$("select[name=intl_phone]").val()})};$scope.setMessageLimit=function(){$.post(Sms.generateURL("/set/msglimit"),{limit:SmsSettings.messageLimit})};$scope.setNotificationSetting=function(){$.post(Sms.generateURL("/set/notification_state"),{notification:SmsSettings.enableNotifications?1:0})};$scope.setContactOrderSetting=function(){$.post(Sms.generateURL("/set/contact_order"),{attribute:SmsSettings.contactOrderBy,reverse:SmsSettings.reverseContactOrder})};$scope.loadConversation=function(contact){OC.Util.History.pushState("phonenumber="+contact.nav);if(contact.nav!==null){$scope.fetchConversation(contact);changeSelectedConversation($("a[mailbox-navigation='"+contact.nav+"']"))}};$scope.fetchConversation=function(contact){if(contact!=null){$scope.selectedContact=contact;$scope.isConvLoading=true}$scope.messages=[];$scope.lastConvMessageDate=0;$.getJSON(Sms.generateURL("/front-api/v1/conversation"),{phoneNumber:$scope.selectedContact.nav},function(jsondata,status){var phoneNumberLabel=$scope.selectedContact.nav;if(typeof jsondata["phoneNumbers"]!=="undefined"){var phoneNumberList=arrayUnique(jsondata["phoneNumbers"]);phoneNumberLabel=phoneNumberList.toString()}$scope.formatConversation(jsondata);$scope.$apply(function(){if(typeof jsondata["contactName"]==="undefined"||jsondata["contactName"]===""){$scope.selectedContact.label=phoneNumberLabel;$scope.selectedContact.opt_numbers=""}else{$scope.selectedContact.label=jsondata["contactName"];$scope.selectedContact.opt_numbers=phoneNumberLabel}$scope.totalMessageCount=jsondata["msgCount"]!==undefined?jsondata["msgCount"]:0;$scope.isConvLoading=false});$("#app-content").scrollTop(1e10)})};$scope.refreshConversation=function(){$.getJSON(Sms.generateURL("/ocsms/front-api/v1/conversation"),{phoneNumber:$scope.selectedContact.nav,lastDate:$scope.lastConvMessageDate},function(jsondata,status){var fmt=$scope.formatConversation(jsondata);var conversationBuf=fmt[1];if(conversationBuf===true){$("#app-content").scrollTop(1e10);if(document.hasFocus()===false){Sms.unreadCountCurrentConv+=parseInt(fmt[0]);document.title=Sms.originalTitle+" ("+Sms.unreadCountCurrentConv+")";SmsNotifications.notify(Sms.unreadCountCurrentConv+" unread message(s) in conversation with "+$scope.selectedContact.label)}}$scope.totalMessageCount=jsondata["msgCount"]!==undefined?parseInt(jsondata["msgCount"]):0})};$scope.checkNewMessages=function(){Sms.unreadCountAllConv=0;$.getJSON(Sms.generateURL("/front-api/v1/new_messages"),{lastDate:$scope.lastContactListMsgDate},function(jsondata,status){var bufferedContacts=[];$.each(jsondata["phonelist"],function(id,val){var fn,peerLabel;if(typeof jsondata["contacts"][id]==="undefined"){peerLabel=id}else{fn=jsondata["contacts"][id];peerLabel=fn}if(!inArray(peerLabel,bufferedContacts)){var contactObj={label:peerLabel,nav:id,unread:parseInt(val)};if(typeof jsondata["photos"][peerLabel]!=="undefined"){contactObj.avatar=jsondata["photos"][peerLabel]}if(typeof jsondata["uids"][peerLabel]!=="undefined"){contactObj.uid=jsondata["uids"][peerLabel]}else{contactObj.uid=peerLabel}$scope.modifyContact(contactObj);bufferedContacts.push(peerLabel);if(id===$scope.selectedContact.nav){changeSelectedConversation($("a[mailbox-navigation='"+id+"']"))}Sms.unreadCountAllConv+=parseInt(val)}});if(Sms.unreadCountNotifStep>0){Sms.unreadCountNotifStep--}if(Sms.unreadCountAllConv>0){if(Sms.unreadCountNotifStep===0||Sms.lastUnreadCountAllConv!==Sms.unreadCountAllConv){SmsNotifications.notify(Sms.unreadCountAllConv+" unread message(s) for all conversations");Sms.unreadCountNotifStep=12;Sms.lastUnreadCountAllConv=Sms.unreadCountAllConv}}})};$scope.removeConversation=function(){$.post(Sms.generateURL("/delete/conversation"),{contact:$scope.selectedContact.label},function(data){$scope.selectedContact.label="";$scope.selectedContact.opt_numbers="";$scope.selectedContact.avatar=undefined;$scope.removeContact($scope.selectedContact);$scope.$apply(function(){$scope.messages=[]});$scope.selectedContact.nav="";OC.Util.History.pushState("")})};$scope.filterSms=function(query){if(query!==$scope.lastSearch){}};OC.Plugins.register("OCA.Search",{attach:function(search){search.setFilter("sms",$scope.filterSms)}});$scope.addContact=function(ct){$scope.$apply(function(){$scope.contacts.push(ct)})};$scope.removeContact=function(ct){var len=$scope.contacts.length;for(var i=0;i<len;i++){var curCt=$scope.contacts[i];if(curCt["nav"]===ct["nav"]){$scope.$apply(function(){$scope.contacts.splice(i,1)});return}}};$scope.modifyContact=function(ct){var len=$scope.contacts.length;for(var i=0;i<len;i++){if($scope.contacts[i]["nav"]===ct["nav"]){$scope.$apply(function(){$scope.contacts[i].unread=parseInt(ct.unread);if(typeof ct.avatar!=="undefined"){$scope.contacts[i].avatar=ct.avatar}})}}};$scope.addConversationMessage=function(msg){$scope.$apply(function(){$scope.messages.push(msg)})};$scope.removeConversationMessage=function(msgId){var len=$scope.messages.length;for(var i=0;i<len;i++){var curMsg=$scope.messages[i];if(curMsg["id"]===msgId){$.post(Sms.generateURL("/delete/message"),{messageId:msgId,phoneNumber:$scope.selectedContact.label},function(data){$scope.$apply(function(){$scope.messages.splice(i,1)})});return}}};$scope.fetchInitialPeerList=function(jsondata){var bufferedContacts=[];$scope.photoVersion=jsondata["photo_version"];$.each(jsondata["phonelist"],function(id,val){var peerLabel;if(typeof jsondata["contacts"][id]==="undefined"){peerLabel=id}else{peerLabel=jsondata["contacts"][id]}if(!inArray(peerLabel,bufferedContacts)){var contactObj={label:peerLabel,nav:id,unread:0,lastmsg:parseInt(val)};if(typeof jsondata["photos"][peerLabel]!=="undefined"){contactObj["avatar"]=jsondata["photos"][peerLabel]}if(typeof jsondata["uids"][peerLabel]!=="undefined"){contactObj.uid=jsondata["uids"][peerLabel]}else{contactObj.uid=peerLabel}$scope.addContact(contactObj);bufferedContacts.push(peerLabel)}});$scope.$apply(function(){$scope.isContactsLoading=false});$scope.lastContactListMsgDate=jsondata["lastRead"]};$scope.formatConversation=function(jsondata){var buf=false;var msgClass="";var msgCount=0;$.each(jsondata["conversation"],function(id,vals){if(vals["type"]===1){msgClass="recv"}else if(vals["type"]===2){msgClass="sent"}else{msgClass=""}if(id/100>$scope.lastConvMessageDate/100){$scope.lastConvMessageDate=id;$scope.addConversationMessage({id:id,type:msgClass,date:new Date(id*1),content:vals["msg"]});buf=true;msgCount++}});return[msgCount,buf]};$interval($scope.refreshConversation,1e4);$interval($scope.checkNewMessages,1e4);$timeout(function(){Sms.originalTitle=document.title;$.getJSON(Sms.generateURL("/front-api/v1/peerlist"),function(jsondata,status){$scope.fetchInitialPeerList(jsondata);var pnParam=$.urlParam("phonenumber");if(pnParam!=null){var urlPhoneNumber=decodeURIComponent(pnParam);if(urlPhoneNumber!=null){if($scope.selectedContact.nav===undefined){$scope.selectedContact.label=urlPhoneNumber;$scope.selectedContact.nav=urlPhoneNumber;$scope.selectedContact.avatar=undefined}$scope.fetchConversation(null);changeSelectedConversation($("a[mailbox-navigation='"+urlPhoneNumber+"']"))}}});SmsSettings.init();SmsNotifications.init();$scope.checkNewMessages()})}]);$.urlParam=function(name){var results=new RegExp("[?&]"+name+"=([^&#]*)").exec(window.location.href);if(results==null){return null}else{return results[1]||0}};function changeSelectedConversation(item){if(item==="undefined"||item==null){return}if(Sms.selectedConversation!=null){Sms.selectedConversation.parent().removeClass("selected")}Sms.selectedConversation=item;Sms.selectedConversation.parent().addClass("selected");Sms.selectedConversation.css("font-weight","normal");Sms.selectedConversation.html(Sms.selectedConversation.attr("mailbox-label"))}(function($,OC){window.onfocus=function(){Sms.unreadCountCurrentConv=0;document.title=Sms.originalTitle}})(jQuery,OC);var SmsNotifications={init:function(){if(!("Notification"in window)){return}Notification.requestPermission(function(permission){if(!("permission"in Notification)){Notification.permission=permission}})},notify:function(message){if(!SmsSettings.enableNotifications){return}if(!("Notification"in window)){return}if(Notification.permission==="granted"){new Notification("Phone Sync - "+message)}else if(Notification.permission!=="denied"){Notification.requestPermission(function(permission){if(!("permission"in Notification)){Notification.permission=permission}if(permission==="granted"){new Notification("Phone Sync - "+message)}})}}};var SmsSettings={messageLimit:100,enableNotifications:true,contactOrderBy:"lastmsg",reverseContactOrder:true,country:"",init:function(){$.getJSON(Sms.generateURL("/front-api/v1/settings"),function(jsondata,status){if(jsondata["status"]===true){this.messageLimit=parseInt(jsondata["message_limit"]);this.enableNotifications=parseInt(jsondata["notification_state"])!==0;this.contactOrderBy=jsondata["contact_order"];this.reverseContactOrder=toBool(jsondata["contact_order_reverse"]);this.country=jsondata["country"];this.updateView()}})},updateView:function(){$("#sel_intl_phone").val(this.country);$("input[name=setting_msg_per_page]").val(this.messageLimit);$("select[name=setting_notif]").val(this.enableNotifications?1:0);$("select[name=setting_contact_order]").val(this.contactOrderBy);$("input[name=setting_contact_order_reverse]").val(this.reverseContactOrder)}}; diff --git a/js/devel/app.js b/js/devel/app.js index 5b3df6f..9dd4ea5 100644 --- a/js/devel/app.js +++ b/js/devel/app.js @@ -9,12 +9,24 @@ */ var Sms = { + // Attributes selectedConversation: null, unreadCountCurrentConv: 0, unreadCountAllConv: 0, unreadCountNotifStep: 12, lastUnreadCountAllConv: 0, - originalTitle: document.title + originalTitle: document.title, + + _winRegexp: /(.*)\/ocsms.*/, + + // Functions + generateURL: function (endpoint) { + var match = this._winRegexp.exec(window.location.href); + if (match.length !== 2) { + console.log("A very bad error happened when parsing window location"); + } + return match[1] + '/ocsms' + endpoint; + } }; var ContactRenderer = { diff --git a/js/devel/legacy.js b/js/devel/legacy.js index d0a2cf2..6a60eaf 100644 --- a/js/devel/legacy.js +++ b/js/devel/legacy.js @@ -50,26 +50,17 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' $scope.selectedContact = {}; $scope.lastSearch = ''; - $scope.generateUrl = function (endpoint) { - var winRegexp = /(.*)\/ocsms.*/; - var match = winRegexp.exec(window.location.href); - if (match.length !== 2) { - console.log("A very bad error happened when parsing window location"); - } - return match[1] + '/ocsms' + endpoint; - }; - // Settings $scope.sendCountry = function () { - $.post($scope.generateUrl('/set/country'), {'country': $('select[name=intl_phone]').val()}); + $.post(Sms.generateURL('/set/country'), {'country': $('select[name=intl_phone]').val()}); }; $scope.setMessageLimit = function () { - $.post($scope.generateUrl('/set/msglimit'), {'limit': SmsSettings.messageLimit}); + $.post(Sms.generateURL('/set/msglimit'), {'limit': SmsSettings.messageLimit}); }; $scope.setNotificationSetting = function () { - $.post($scope.generateUrl('/set/notification_state'), + $.post(Sms.generateURL('/set/notification_state'), { 'notification': SmsSettings.enableNotifications ? 1 : 0 } @@ -77,7 +68,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' }; $scope.setContactOrderSetting = function () { - $.post($scope.generateUrl('/set/contact_order'), + $.post(Sms.generateURL('/set/contact_order'), { 'attribute': SmsSettings.contactOrderBy, 'reverse': SmsSettings.reverseContactOrder @@ -106,7 +97,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' $scope.messages = []; $scope.lastConvMessageDate = 0; - $.getJSON($scope.generateUrl('/front-api/v1/conversation'), {'phoneNumber': $scope.selectedContact.nav}, + $.getJSON(Sms.generateURL('/front-api/v1/conversation'), {'phoneNumber': $scope.selectedContact.nav}, function (jsondata, status) { var phoneNumberLabel = $scope.selectedContact.nav; @@ -137,7 +128,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' ); }; $scope.refreshConversation = function () { - $.getJSON($scope.generateUrl('/ocsms/front-api/v1/conversation'), + $.getJSON(Sms.generateURL('/ocsms/front-api/v1/conversation'), { 'phoneNumber': $scope.selectedContact.nav, "lastDate": $scope.lastConvMessageDate @@ -151,7 +142,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' if (document.hasFocus() === false) { Sms.unreadCountCurrentConv += parseInt(fmt[0]); document.title = Sms.originalTitle + " (" + Sms.unreadCountCurrentConv + ")"; - $scope.desktopNotify(Sms.unreadCountCurrentConv + " unread message(s) in conversation with " + $scope.selectedContact.label); + SmsNotifications.notify(Sms.unreadCountCurrentConv + " unread message(s) in conversation with " + $scope.selectedContact.label); } } @@ -162,7 +153,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' }; $scope.checkNewMessages = function () { Sms.unreadCountAllConv = 0; - $.getJSON($scope.generateUrl('/front-api/v1/new_messages'), + $.getJSON(Sms.generateURL('/front-api/v1/new_messages'), {'lastDate': $scope.lastContactListMsgDate}, function (jsondata, status) { var bufferedContacts = []; @@ -222,7 +213,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' * or if unreadCount changes */ if (Sms.unreadCountNotifStep === 0 || Sms.lastUnreadCountAllConv !== Sms.unreadCountAllConv) { - $scope.desktopNotify(Sms.unreadCountAllConv + " unread message(s) for all conversations"); + SmsNotifications.notify(Sms.unreadCountAllConv + " unread message(s) for all conversations"); Sms.unreadCountNotifStep = 12; Sms.lastUnreadCountAllConv = Sms.unreadCountAllConv; } @@ -232,7 +223,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' }; $scope.removeConversation = function () { - $.post($scope.generateUrl('/delete/conversation'), {"contact": $scope.selectedContact.label}, function (data) { + $.post(Sms.generateURL('/delete/conversation'), {"contact": $scope.selectedContact.label}, function (data) { // Reinit main window $scope.selectedContact.label = ""; $scope.selectedContact.opt_numbers = ""; @@ -307,7 +298,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' for (var i = 0; i < len; i++) { var curMsg = $scope.messages[i]; if (curMsg['id'] === msgId) { - $.post($scope.generateUrl('/delete/message'), + $.post(Sms.generateURL('/delete/message'), {"messageId": msgId, "phoneNumber": $scope.selectedContact.label}, function (data) { $scope.$apply(function () { $scope.messages.splice(i, 1); @@ -318,24 +309,6 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' } }; - $scope.fetchInitialSettings = function () { - $.getJSON($scope.generateUrl('/front-api/v1/settings'), function (jsondata, status) { - if (jsondata['status'] === true) { - $('#sel_intl_phone').val(jsondata["country"]); - - $('input[name=setting_msg_per_page]').val(parseInt(jsondata["message_limit"])); - $('select[name=setting_notif]').val(jsondata["notification_state"]); - $('select[name=setting_contact_order]').val(jsondata["contact_order"]); - $('input[name=setting_contact_order_reverse]').val(toBool(jsondata["contact_order_reverse"])); - - SmsSettings.messageLimit = parseInt(jsondata["message_limit"]); - SmsSettings.enableNotifications = parseInt(jsondata["notification_state"]) !== 0; - SmsSettings.contactOrderBy = jsondata["contact_order"]; - SmsSettings.reverseContactOrder = toBool(jsondata["contact_order_reverse"]); - } - }); - }; - $scope.fetchInitialPeerList = function (jsondata) { // Use a buffer for better jQuery performance var bufferedContacts = []; @@ -419,14 +392,6 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' return [msgCount, buf]; }; - $scope.desktopNotify = function (msg) { - if (!SmsSettings.enableNotifications) { - return; - } - - SmsNotifications.notify(msg); - }; - $interval($scope.refreshConversation, 10000); $interval($scope.checkNewMessages, 10000); @@ -435,7 +400,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' Sms.originalTitle = document.title; // Now bind the events when we click on the phone number - $.getJSON($scope.generateUrl('/front-api/v1/peerlist'), function (jsondata, status) { + $.getJSON(Sms.generateURL('/front-api/v1/peerlist'), function (jsondata, status) { $scope.fetchInitialPeerList(jsondata); var pnParam = $.urlParam('phonenumber'); @@ -453,7 +418,7 @@ app.controller('OcSmsController', ['$scope', '$interval', '$timeout', '$compile' } } }); - $scope.fetchInitialSettings(); + SmsSettings.init(); SmsNotifications.init(); $scope.checkNewMessages(); }); diff --git a/js/devel/notifications.js b/js/devel/notifications.js index 6b22c71..901a894 100644 --- a/js/devel/notifications.js +++ b/js/devel/notifications.js @@ -21,6 +21,10 @@ var SmsNotifications = { }); }, notify: function (message) { + if (!SmsSettings.enableNotifications) { + return; + } + if (!("Notification" in window)) { return; } diff --git a/js/devel/settings.js b/js/devel/settings.js index 967ccad..9183114 100644 --- a/js/devel/settings.js +++ b/js/devel/settings.js @@ -9,8 +9,34 @@ */ var SmsSettings = { + // Attributes messageLimit: 100, enableNotifications: true, contactOrderBy: 'lastmsg', - reverseContactOrder: true + reverseContactOrder: true, + country: '', + + // Functions + init: function () { + $.getJSON(Sms.generateURL('/front-api/v1/settings'), function (jsondata, status) { + if (jsondata['status'] === true) { + this.messageLimit = parseInt(jsondata["message_limit"]); + this.enableNotifications = parseInt(jsondata["notification_state"]) !== 0; + this.contactOrderBy = jsondata["contact_order"]; + this.reverseContactOrder = toBool(jsondata["contact_order_reverse"]); + this.country = jsondata["country"]; + + this.updateView(); + } + }); + }, + + // This function should be moved to a renderer or something else + updateView: function () { + $('#sel_intl_phone').val(this.country); + $('input[name=setting_msg_per_page]').val(this.messageLimit); + $('select[name=setting_notif]').val(this.enableNotifications ? 1 : 0); + $('select[name=setting_contact_order]').val(this.contactOrderBy); + $('input[name=setting_contact_order_reverse]').val(this.reverseContactOrder); + } };
\ No newline at end of file |