try to optimise routeAPI

This commit is contained in:
Azareal 2020-03-09 15:16:44 +10:00
parent b04d77d7b6
commit 28f210371e
18 changed files with 75 additions and 63 deletions

View File

@ -192,7 +192,7 @@ func buildAlertSb(sb *strings.Builder, msg string, sub []string, path, avatar st
sb.WriteRune('}') sb.WriteRune('}')
} }
func BuildAlertSb(sb *strings.Builder, a Alert, user User /* The current user */) (err error) { func BuildAlertSb(sb *strings.Builder, a *Alert, user User /* The current user */) (err error) {
var targetUser *User var targetUser *User
if a.Actor == nil { if a.Actor == nil {
a.Actor, err = Users.Get(a.ActorID) a.Actor, err = Users.Get(a.ActorID)

View File

@ -46,7 +46,7 @@ function bindToAlerts() {
ev.stopPropagation(); ev.stopPropagation();
ev.preventDefault(); ev.preventDefault();
$.ajax({ $.ajax({
url: "/api/?action=set&module=dismiss-alert", url: "/api/?a=set&m=dismiss-alert",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
data: { id: $(this).attr("data-asid") }, data: { id: $(this).attr("data-asid") },
@ -137,7 +137,7 @@ function loadAlerts(menuAlerts, eTc = false) {
$.ajax({ $.ajax({
type: 'get', type: 'get',
dataType: 'json', dataType: 'json',
url:'/api/?module=alerts' + tc, url:'/api/?m=alerts' + tc,
success: (data) => { success: (data) => {
if("errmsg" in data) { if("errmsg" in data) {
setAlertError(menuAlerts,data.errmsg) setAlertError(menuAlerts,data.errmsg)
@ -150,7 +150,7 @@ function loadAlerts(menuAlerts, eTc = false) {
if(eTc && lastTc != 0) { if(eTc && lastTc != 0) {
for(var i in data.msgs) wsAlertEvent(data.msgs[i]); for(var i in data.msgs) wsAlertEvent(data.msgs[i]);
} else {*/ } else {*/
console.log("data:",data.count); console.log("data",data);
for(var i in data.msgs) addAlert(data.msgs[i]); for(var i in data.msgs) addAlert(data.msgs[i]);
alertCount = data.count; alertCount = data.count;
updateAlertList(menuAlerts); updateAlertList(menuAlerts);
@ -311,7 +311,7 @@ function runWebSockets(resume = false) {
moreTopicBlock.classList.remove("more_topic_block_initial"); moreTopicBlock.classList.remove("more_topic_block_initial");
moreTopicBlock.classList.add("more_topic_block_active"); moreTopicBlock.classList.add("more_topic_block_active");
console.log("phraseBox:",phraseBox); console.log("phraseBox",phraseBox);
let msgBox = moreTopicBlock.getElementsByClassName("more_topics")[0]; let msgBox = moreTopicBlock.getElementsByClassName("more_topics")[0];
msgBox.innerText = phraseBox["topic_list"]["topic_list.changed_topics"].replace("%d",moreTopicCount); msgBox.innerText = phraseBox["topic_list"]["topic_list.changed_topics"].replace("%d",moreTopicCount);
} }
@ -347,7 +347,7 @@ function runWebSockets(resume = false) {
console.log("before notify on alert") console.log("before notify on alert")
// We can only get away with this because template_alert has no phrases, otherwise it too would have to be part of the "dance", I miss Go concurrency :( // We can only get away with this because template_alert has no phrases, otherwise it too would have to be part of the "dance", I miss Go concurrency :(
if(!noAlerts) { if(!noAlerts) {
notifyOnScriptW("template_alert", (e) => { notifyOnScriptW("template_alert", e => {
if(e!=undefined) console.log("failed alert? why?", e) if(e!=undefined) console.log("failed alert? why?", e)
}, () => { }, () => {
if(!Template_alert) throw("template function not found"); if(!Template_alert) throw("template function not found");
@ -424,8 +424,8 @@ function mainInit(){
moreTopicCount = 0; moreTopicCount = 0;
}) })
$(".add_like,.remove_like").click(function(event) { $(".add_like,.remove_like").click(function(ev) {
event.preventDefault(); ev.preventDefault();
//$(this).unbind("click"); //$(this).unbind("click");
let target = this.closest("a").getAttribute("href"); let target = this.closest("a").getAttribute("href");
console.log("target", target); console.log("target", target);
@ -467,11 +467,11 @@ function mainInit(){
}); });
}); });
$(".link_label").click(function(event) { $(".link_label").click(function(ev) {
event.preventDefault(); ev.preventDefault();
let linkSelect = $('#'+$(this).attr("data-for")); let linkSelect = $('#'+$(this).attr("data-for"));
if(!linkSelect.hasClass("link_opened")) { if(!linkSelect.hasClass("link_opened")) {
event.stopPropagation(); ev.stopPropagation();
linkSelect.addClass("link_opened"); linkSelect.addClass("link_opened");
} }
}); });
@ -902,10 +902,10 @@ function mainInit(){
$(".unix_to_24_hour_time").each(function(){ $(".unix_to_24_hour_time").each(function(){
let unixTime = this.innerText; let unixTime = this.innerText;
let date = new Date(unixTime*1000); let date = new Date(unixTime*1000);
console.log("date: ", date); console.log("date", date);
let minutes = "0" + date.getMinutes(); let minutes = "0" + date.getMinutes();
let formattedTime = date.getHours() + ":" + minutes.substr(-2); let formattedTime = date.getHours() + ":" + minutes.substr(-2);
console.log("formattedTime:", formattedTime); console.log("formattedTime", formattedTime);
this.innerText = formattedTime; this.innerText = formattedTime;
}); });
@ -913,10 +913,10 @@ function mainInit(){
// TODO: Localise this // TODO: Localise this
let monthList = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; let monthList = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
let date = new Date(this.innerText * 1000); let date = new Date(this.innerText * 1000);
console.log("date: ", date); console.log("date", date);
let day = "0" + date.getDate(); let day = "0" + date.getDate();
let formattedTime = monthList[date.getMonth()] + " " + day.substr(-2) + " " + date.getFullYear(); let formattedTime = monthList[date.getMonth()] + " " + day.substr(-2) + " " + date.getFullYear();
console.log("formattedTime:", formattedTime); console.log("formattedTime", formattedTime);
this.innerText = formattedTime; this.innerText = formattedTime;
}); });
@ -939,7 +939,7 @@ function mainInit(){
$("#poll_results_" + pollID).removeClass("auto_hide"); $("#poll_results_" + pollID).removeClass("auto_hide");
fetch("/poll/results/" + pollID, { fetch("/poll/results/" + pollID, {
credentials: 'same-origin' credentials: 'same-origin'
}).then((response) => response.text()).catch((error) => console.error("Error:",error)).then((rawData) => { }).then(resp => resp.text()).catch(err => console.error("err:",err)).then((rawData) => {
// TODO: Make sure the received data is actually a list of integers // TODO: Make sure the received data is actually a list of integers
let data = JSON.parse(rawData); let data = JSON.parse(rawData);
let allZero = true; let allZero = true;

View File

@ -102,7 +102,7 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
}); });
} catch(e) { } catch(e) {
// TODO: Use a notice instead // TODO: Use a notice instead
console.log("e:",e); console.log("e",e);
alert(e); alert(e);
} }
} }
@ -142,7 +142,7 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
}); });
} catch(e) { } catch(e) {
// TODO: Use a notice instead // TODO: Use a notice instead
console.log("e:",e); console.log("e",e);
alert(e); alert(e);
} }
} }
@ -248,8 +248,8 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
} }
}); });
}; };
$(".mod_floater_submit").click(function(event){ $(".mod_floater_submit").click(function(ev){
event.preventDefault(); ev.preventDefault();
let selectNode = this.form.querySelector(".mod_floater_options"); let selectNode = this.form.querySelector(".mod_floater_options");
let optionNode = selectNode.options[selectNode.selectedIndex]; let optionNode = selectNode.options[selectNode.selectedIndex];
let action = optionNode.getAttribute("value"); let action = optionNode.getAttribute("value");
@ -265,12 +265,12 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
let fid = this.getAttribute("data-fid"); let fid = this.getAttribute("data-fid");
if (fid == null) return; if (fid == null) return;
this.classList.add("pane_selected"); this.classList.add("pane_selected");
console.log("fid:" + fid); console.log("fid", fid);
forumToMoveTo = fid; forumToMoveTo = fid;
$("#mover_submit").unbind("click"); $("#mover_submit").unbind("click");
$("#mover_submit").click(function(event){ $("#mover_submit").click(ev => {
event.preventDefault(); ev.preventDefault();
bulkActionSender("move",selectedTopics,forumToMoveTo); bulkActionSender("move",selectedTopics,forumToMoveTo);
}); });
}); });
@ -284,7 +284,7 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
function addPollInput() { function addPollInput() {
console.log("clicked on pollinputinput"); console.log("clicked on pollinputinput");
let dataPollInput = $(this).parent().attr("data-pollinput"); let dataPollInput = $(this).parent().attr("data-pollinput");
console.log("dataPollInput:", dataPollInput); console.log("dataPollInput", dataPollInput);
if(dataPollInput == undefined) return; if(dataPollInput == undefined) return;
if(dataPollInput != (pollInputIndex-1)) return; if(dataPollInput != (pollInputIndex-1)) return;
$(".poll_content_row .formitem").append(Template_topic_c_poll_input({ $(".poll_content_row .formitem").append(Template_topic_c_poll_input({
@ -292,13 +292,13 @@ var imageExts = ["png", "jpg", "jpe","jpeg","jif","jfi","jfif", "svg", "bmp", "g
Place: phraseBox["topic"]["topic.reply_add_poll_option"].replace("%d",pollInputIndex), Place: phraseBox["topic"]["topic.reply_add_poll_option"].replace("%d",pollInputIndex),
})); }));
pollInputIndex++; pollInputIndex++;
console.log("new pollInputIndex: ", pollInputIndex); console.log("new pollInputIndex", pollInputIndex);
$(".pollinputinput").off("click"); $(".pollinputinput").off("click");
$(".pollinputinput").click(addPollInput); $(".pollinputinput").click(addPollInput);
} }
var pollInputIndex = 1; var pollInputIndex = 1;
$("#add_poll_button").click((ev) => { $("#add_poll_button").click(ev => {
ev.preventDefault(); ev.preventDefault();
$(".poll_content_row").removeClass("auto_hide"); $(".poll_content_row").removeClass("auto_hide");
$("#has_poll_input").val("1"); $("#has_poll_input").val("1");

View File

@ -140,13 +140,13 @@ func UploadAction(fname, path string, args ...string) *uploadAction {
return &uploadAction{route} return &uploadAction{route}
} }
func (action *uploadAction) MaxSizeVar(varName string) *RouteImpl { func (a *uploadAction) MaxSizeVar(varName string) *RouteImpl {
action.Route.LitBeforeMultiline(`err = c.HandleUploadRoute(w,req,user,` + varName + `) a.Route.LitBeforeMultiline(`err = c.HandleUploadRoute(w,req,user,` + varName + `)
if err != nil { if err != nil {
return err return err
}`) }`)
action.Route.Before("NoUploadSessionMismatch") a.Route.Before("NoUploadSessionMismatch")
return action.Route return a.Route
} }
type RouteSet struct { type RouteSet struct {

View File

@ -41,7 +41,7 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
return c.PreErrorJS("Bad Form", w, r) return c.PreErrorJS("Bad Form", w, r)
} }
action := r.FormValue("action") action := r.FormValue("a")
if action == "" { if action == "" {
action = "get" action = "get"
} }
@ -49,7 +49,7 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
return c.PreErrorJS("Invalid Action", w, r) return c.PreErrorJS("Invalid Action", w, r)
} }
switch r.FormValue("module") { switch r.FormValue("m") {
// TODO: Split this into it's own function // TODO: Split this into it's own function
case "dismiss-alert": case "dismiss-alert":
id, err := strconv.Atoi(r.FormValue("id")) id, err := strconv.Atoi(r.FormValue("id"))
@ -104,12 +104,24 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
return c.InternalErrorJS(err, w, r) return c.InternalErrorJS(err, w, r)
} }
if count == 0 {
gzw, ok := w.(c.GzipResponseWriter)
if ok {
w = gzw.ResponseWriter
h := w.Header()
h.Del("Content-Type")
h.Del("Content-Encoding")
}
_, _ = io.WriteString(w, `{}`)
return nil
}
rCreatedAt, _ := strconv.ParseInt(r.FormValue("t"), 10, 64) rCreatedAt, _ := strconv.ParseInt(r.FormValue("t"), 10, 64)
rCount, _ := strconv.Atoi(r.FormValue("c")) rCount, _ := strconv.Atoi(r.FormValue("c"))
//log.Print("rCreatedAt:", rCreatedAt) //log.Print("rCreatedAt:", rCreatedAt)
//log.Print("rCount:", rCount) //log.Print("rCount:", rCount)
var actors []int var actors []int
var alerts []c.Alert var alerts []*c.Alert
var createdAt time.Time var createdAt time.Time
var topCreatedAt int64 var topCreatedAt int64
@ -121,7 +133,7 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
var al c.Alert al := &c.Alert{}
err = rows.Scan(&al.ASID, &al.ActorID, &al.TargetUserID, &al.Event, &al.ElementType, &al.ElementID, &createdAt) err = rows.Scan(&al.ASID, &al.ActorID, &al.TargetUserID, &al.Event, &al.ElementType, &al.ElementID, &createdAt)
if err != nil { if err != nil {
return c.InternalErrorJS(err, w, r) return c.InternalErrorJS(err, w, r)
@ -142,7 +154,7 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
} }
} }
if count == 0 || len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) { if len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) {
gzw, ok := w.(c.GzipResponseWriter) gzw, ok := w.(c.GzipResponseWriter)
if ok { if ok {
w = gzw.ResponseWriter w = gzw.ResponseWriter