diff options
author | FChannel <> | 2021-07-28 15:43:48 -0700 |
---|---|---|
committer | FChannel <> | 2021-07-28 15:43:48 -0700 |
commit | 7c6ee8f4073a5b8fd9cc065f225c9f09f21ee4a1 (patch) | |
tree | f3fdedfcf6a045ac24be12ac62023ed9b3c24782 | |
parent | 98d72c9b94b5dda9a987dfe41552f00512d43574 (diff) |
added soft thread limits. they are not physically archived yet
-rw-r--r-- | client.go | 151 | ||||
-rw-r--r-- | database.go | 490 | ||||
-rw-r--r-- | main.go | 598 | ||||
-rw-r--r-- | static/nposts.html | 16 |
4 files changed, 631 insertions, 624 deletions
@@ -59,7 +59,7 @@ type AdminPage struct { Board Board Key string Actor string - Boards []Board + Boards []Board Following []string Followers []string Reported []Report @@ -118,7 +118,7 @@ func IndexGet(w http.ResponseWriter, r *http.Request, db *sql.DB) { if(len(data.BoardRemainer) == 3){ data.BoardRemainer = make([]int, 0) } - + data.InstanceIndex = GetCollectionFromReq("https://fchan.xyz/followers").Items data.NewsItems = getNewsFromDB(db, 3) @@ -127,9 +127,9 @@ func IndexGet(w http.ResponseWriter, r *http.Request, db *sql.DB) { func NewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB, timestamp int) { t := template.Must(template.New("").Funcs(template.FuncMap{ - "sub": func (i, j int) int { return i - j }, + "sub": func (i, j int) int { return i - j }, "unixtoreadable": func(u int) string { return time.Unix(int64(u), 0).Format("Jan 02, 2006") }}).ParseFiles("./static/main.html", "./static/news.html")) - + actor := GetActorFromDB(db, Domain) var data PageData @@ -143,16 +143,16 @@ func NewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB, timestamp int) data.Board.Post.Actor = actor.Id data.Board.Restricted = actor.Restricted data.NewsItems = []NewsItem{NewsItem{}} - + var err error data.NewsItems[0], err = getNewsItemFromDB(db, timestamp) - + if err != nil { - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) return } - + data.Title = actor.PreferredUsername + ": " + data.NewsItems[0].Title t.ExecuteTemplate(w, "layout", data) @@ -161,9 +161,9 @@ func NewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB, timestamp int) func AllNewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB) { t := template.Must(template.New("").Funcs(template.FuncMap{ "mod": func(i, j int) bool { return i%j == 0 }, - "sub": func (i, j int) int { return i - j }, + "sub": func (i, j int) int { return i - j }, "unixtoreadable": func(u int) string { return time.Unix(int64(u), 0).Format("Jan 02, 2006") }}).ParseFiles("./static/main.html", "./static/anews.html")) - + actor := GetActorFromDB(db, Domain) var data PageData @@ -183,7 +183,6 @@ func AllNewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB) { } func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Collection){ - t := template.Must(template.New("").Funcs(template.FuncMap{ "proxy": func(url string) string { return MediaProxy(url) @@ -199,13 +198,16 @@ func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Co title := strings.ReplaceAll(ParseLinkTitle(actor.Id, op, content), `/\<`, ">") link := "<a href=\"" + actor.Name + "/" + shortURL(actor.Outbox, op) + "#" + shortURL(actor.Outbox, id) + "\" title=\"" + title + "\">>>" + shortURL(actor.Outbox, id) + "</a>" return template.HTML(link) - }, + }, + "add": func (i, j int) int { + return i + j + }, "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/nposts.html", "./static/top.html", "./static/bottom.html", "./static/posts.html")) actor := collection.Actor - postNum := strings.Replace(r.URL.EscapedPath(), "/" + actor.Name + "/", "", 1) + postNum := r.URL.Query().Get("page") page, _ := strconv.Atoi(postNum) @@ -230,7 +232,7 @@ func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Co returnData.Title = "/" + actor.Name + "/ - " + actor.PreferredUsername - returnData.Key = *Key + returnData.Key = *Key returnData.Boards = Boards returnData.Posts = collection.OrderedItems @@ -241,11 +243,16 @@ func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Co for j, k := range e.Replies.OrderedItems { returnData.Posts[i].Replies.OrderedItems[j].ContentHTML = ParseContent(db, returnData.Board.Actor, e.Id, k.Content, e) } - } + } - var offset = 8 + var offset = 15 var pages []int pageLimit := (float64(collection.TotalItems) / float64(offset)) + + if pageLimit > 11 { + pageLimit = 11 + } + for i := 0.0; i < pageLimit; i++ { pages = append(pages, int(i)) } @@ -259,15 +266,15 @@ func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Co func CatalogGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Collection){ t := template.Must(template.New("").Funcs(template.FuncMap{ "proxy": func(url string) string { - return MediaProxy(url) + return MediaProxy(url) }, "short": func(actorName string, url string) string { return shortURL(actorName, url) }, "parseAttachment": func(obj ObjectBase, catalog bool) template.HTML { return ParseAttachment(obj, catalog) - }, - "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/ncatalog.html", "./static/top.html")) + }, + "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/ncatalog.html", "./static/top.html")) actor := collection.Actor var returnData PageData @@ -286,9 +293,9 @@ func CatalogGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection C returnData.Board.Post.Actor = actor.Id returnData.Instance = GetActorFromDB(db, Domain) - + returnData.Board.Captcha = Domain + "/" + GetRandomCaptcha(db) - returnData.Board.CaptchaCode = GetCaptchaCode(returnData.Board.Captcha) + returnData.Board.CaptchaCode = GetCaptchaCode(returnData.Board.Captcha) returnData.Title = "/" + actor.Name + "/ - " + actor.PreferredUsername @@ -302,7 +309,7 @@ func CatalogGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection C func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ t := template.Must(template.New("").Funcs(template.FuncMap{ "proxy": func(url string) string { - return MediaProxy(url) + return MediaProxy(url) }, "short": func(actorName string, url string) string { return shortURL(actorName, url) @@ -316,9 +323,9 @@ func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ title := strings.ReplaceAll(ParseLinkTitle(actor.Id, op, content), `/\<`, ">") link := "<a href=\"" + actor.Name + "/" + shortURL(actor.Outbox, op) + "#" + shortURL(actor.Outbox, id) + "\" title=\"" + title + "\">>>" + shortURL(actor.Outbox, id) + "</a>" return template.HTML(link) - }, + }, "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/npost.html", "./static/top.html", "./static/bottom.html", "./static/posts.html")) - + path := r.URL.Path actor := GetActorFromPath(db, path, "/") re := regexp.MustCompile("\\w+$") @@ -344,7 +351,7 @@ func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ returnData.Title = "/" + returnData.Board.Name + "/ - " + returnData.Board.PrefName - returnData.Key = *Key + returnData.Key = *Key returnData.Boards = Boards @@ -366,7 +373,7 @@ func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ collection := GetObjectByIDFromDB(db, inReplyTo) if collection.Actor != nil { returnData.Board.Post.Actor = collection.Actor.Id - returnData.Board.InReplyTo = inReplyTo + returnData.Board.InReplyTo = inReplyTo if len(collection.OrderedItems) > 0 { returnData.Posts = append(returnData.Posts, collection.OrderedItems[0]) @@ -386,7 +393,7 @@ func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ } } - t.ExecuteTemplate(w, "layout", returnData) + t.ExecuteTemplate(w, "layout", returnData) } func GetBoardCollection(db *sql.DB) []Board { @@ -406,7 +413,7 @@ func GetBoardCollection(db *sql.DB) []Board { } sort.Sort(BoardSortAsc(collection)) - + return collection } @@ -415,14 +422,18 @@ func WantToServePage(db *sql.DB, actorName string, page int) (Collection, bool) var collection Collection serve := false + if page > 10 { + return collection, serve + } + actor := GetActorByNameFromDB(db, actorName) if actor.Id != "" { collection = GetObjectFromDBPage(db, actor.Id, page) - collection.Actor = &actor + collection.Actor = &actor return collection, true } - + return collection, serve } @@ -435,10 +446,10 @@ func WantToServeCatalog(db *sql.DB, actorName string) (Collection, bool) { if actor.Id != "" { collection = GetObjectFromDBCatalog(db, actor.Id) - collection.Actor = &actor + collection.Actor = &actor return collection, true } - + return collection, serve } @@ -465,7 +476,7 @@ func GetCaptchaCode(captcha string) string { func CreateLocalDeleteDB(db *sql.DB, id string, _type string) { query := `select id from removed where id=$1` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "could not query removed") @@ -478,26 +489,26 @@ func CreateLocalDeleteDB(db *sql.DB, id string, _type string) { if i != "" { query := `update removed set type=$1 where id=$2` - - _, err := db.Exec(query, _type, id) - + + _, err := db.Exec(query, _type, id) + CheckError(err, "Could not update removed post") - + } } else { query := `insert into removed (id, type) values ($1, $2)` - - _, err := db.Exec(query, id, _type) - + + _, err := db.Exec(query, id, _type) + CheckError(err, "Could not insert removed post") } } func GetLocalDeleteDB(db *sql.DB) []Removed { var deleted []Removed - + query := `select id, type from removed` - + rows, err := db.Query(query) CheckError(err, "could not query removed") @@ -518,7 +529,7 @@ func GetLocalDeleteDB(db *sql.DB) []Removed { func CreateLocalReportDB(db *sql.DB, id string, board string, reason string) { query := `select id, count from reported where id=$1 and board=$2` - rows, err := db.Query(query, id, board) + rows, err := db.Query(query, id, board) CheckError(err, "could not query reported") @@ -534,23 +545,23 @@ func CreateLocalReportDB(db *sql.DB, id string, board string, reason string) { count = count + 1 query := `update reported set count=$1 where id=$2` - _, err := db.Exec(query, count, id) - + _, err := db.Exec(query, count, id) + CheckError(err, "Could not update reported post") } } else { query := `insert into reported (id, count, board, reason) values ($1, $2, $3, $4)` - - _, err := db.Exec(query, id, 1, board, reason) - + + _, err := db.Exec(query, id, 1, board, reason) + CheckError(err, "Could not insert reported post") - } + } } func GetLocalReportDB(db *sql.DB, board string) []Report { var reported []Report - + query := `select id, count, reason from reported where board=$1` rows, err := db.Query(query, board) @@ -573,7 +584,7 @@ func GetLocalReportDB(db *sql.DB, board string) []Report { func CloseLocalReportDB(db *sql.DB, id string, board string) { query := `delete from reported where id=$1 and board=$2` - _, err := db.Exec(query, id, board) + _, err := db.Exec(query, id, board) CheckError(err, "Could not delete local report from db") } @@ -586,7 +597,7 @@ func GetActorFollowNameFromPath(path string) string{ actor = re.FindString(path) actor = strings.Replace(actor, "f", "", 1) - actor = strings.Replace(actor, "-", "", 1) + actor = strings.Replace(actor, "-", "", 1) return actor } @@ -646,7 +657,7 @@ func MediaProxy(url string) string { if re.MatchString(url) { return url - } + } MediaHashs[HashMedia(url)] = url return "/api/media?hash=" + HashMedia(url) @@ -675,15 +686,15 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { media += "preview=\"" + MediaProxy(obj.Preview.Href) + "\"" } else { media += "src=\"" + MediaProxy(obj.Attachment[0].Href) + "\"" - media += "preview=\"" + MediaProxy(obj.Attachment[0].Href) + "\"" + media += "preview=\"" + MediaProxy(obj.Attachment[0].Href) + "\"" } media += ">" return template.HTML(media) - } + } - if(regexp.MustCompile(`audio\/`).MatchString(obj.Attachment[0].MediaType)){ + if(regexp.MustCompile(`audio\/`).MatchString(obj.Attachment[0].MediaType)){ media = "<audio " media += "controls=\"controls\" " media += "preload=\"metadta\" " @@ -699,17 +710,17 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { media += ">" media += "Audio is not supported." media += "</audio>" - + return template.HTML(media) } - if(regexp.MustCompile(`video\/`).MatchString(obj.Attachment[0].MediaType)){ + if(regexp.MustCompile(`video\/`).MatchString(obj.Attachment[0].MediaType)){ media = "<video " media += "controls=\"controls\" " media += "preload=\"metadta\" " media += "muted=\"muted\" " if catalog { - media += "style=\"margin-right: 10px; margin-bottom: 10px; max-width: 180px; max-height: 180px;\" " + media += "style=\"margin-right: 10px; margin-bottom: 10px; max-width: 180px; max-height: 180px;\" " } else { media += "style=\"float: left; margin-right: 10px; margin-bottom: 10px; max-width: 250px; max-height: 250px;\" " } @@ -720,7 +731,7 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { media += ">" media += "Video is not supported." media += "</video>" - + return template.HTML(media) } @@ -729,8 +740,8 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { func ParseContent(db *sql.DB, board Actor, op string, content string, thread ObjectBase) template.HTML { - nContent := strings.ReplaceAll(content, `<`, "<") - + nContent := strings.ReplaceAll(content, `<`, "<") + nContent = ParseLinkComments(db, board, op, nContent, thread) nContent = ParseCommentQuotes(nContent) @@ -748,7 +759,7 @@ func ParseLinkComments(db *sql.DB, board Actor, op string, content string, threa for i, _ := range match { link := strings.Replace(match[i][0], ">>", "", 1) isOP := "" - + domain := match[i][2] if link == op { @@ -791,18 +802,18 @@ func ParseLinkComments(db *sql.DB, board Actor, op string, content string, threa replyID, isReply := IsReplyToOP(db, op, parsedLink) if isReply { id := shortURL(board.Outbox, replyID) - + content = strings.Replace(content, match[i][0], "<a class=\"reply\" style=\"" + style + "\" title=\"" + quoteTitle + "\" href=\"/" + board.Name + "/" + shortURL(board.Outbox, op) + "#" + id + "\">>>" + id + "" + isOP + "</a>", -1) } else { - + //this is a cross post parsedOP := GetReplyOP(db, parsedLink) if parsedOP != "" { link = parsedOP + "#" + shortURL(parsedOP, parsedLink) } - + content = strings.Replace(content, match[i][0], "<a class=\"reply\" style=\"" + style + "\" title=\"" + quoteTitle + "\" href=\"" + link + "\">>>" + shortURL(board.Outbox, parsedLink) + isOP + " →</a>", -1) } } @@ -818,8 +829,8 @@ func ParseLinkTitle(actorName string, op string, content string) string { link := strings.Replace(match[i][0], ">>", "", 1) isOP := "" - domain := match[i][2] - + domain := match[i][2] + if link == op { isOP = " (OP)" } @@ -839,9 +850,9 @@ func ParseCommentQuotes(content string) string { // replace quotes re := regexp.MustCompile(`((\r\n|\r|\n|^)>(.+)?[^\r\n])`) match := re.FindAllStringSubmatch(content, -1) - + for i, _ := range match { - quote := strings.Replace(match[i][0], ">", ">", 1) + quote := strings.Replace(match[i][0], ">", ">", 1) line := re.ReplaceAllString(match[i][0], "<span class=\"quote\">" + quote + "</span>") content = strings.Replace(content, match[i][0], line, 1) } diff --git a/database.go b/database.go index db6a3d1..911a42d 100644 --- a/database.go +++ b/database.go @@ -8,15 +8,15 @@ import ( "strings" "regexp" "time" - "html/template" + "html/template" _ "github.com/lib/pq" ) func GetActorFromDB(db *sql.DB, id string) Actor { - var nActor Actor + var nActor Actor - query :=`select type, id, name, preferedusername, inbox, outbox, following, followers, restricted, summary, publickeypem from actor where id=$1` + query :=`select type, id, name, preferedusername, inbox, outbox, following, followers, restricted, summary, publickeypem from actor where id=$1` rows, err := db.Query(query, id) @@ -37,7 +37,7 @@ func GetActorFromDB(db *sql.DB, id string) Actor { CheckError(err, "error creating public key from private") } - return nActor + return nActor } func GetActorByNameFromDB(db *sql.DB, name string) Actor { @@ -51,8 +51,8 @@ func GetActorByNameFromDB(db *sql.DB, name string) Actor { return nActor } - var publicKeyPem string - defer rows.Close() + var publicKeyPem string + defer rows.Close() for rows.Next() { err = rows.Scan(&nActor.Type, &nActor.Id, &nActor.Name, &nActor.PreferredUsername, &nActor.Inbox, &nActor.Outbox, &nActor.Following, &nActor.Followers, &nActor.Restricted, &nActor.Summary, &publicKeyPem) CheckError(err, "error with actor from db scan ") @@ -63,7 +63,7 @@ func GetActorByNameFromDB(db *sql.DB, name string) Actor { CheckError(err, "error creating public key from private") } - return nActor + return nActor } func CreateNewBoardDB(db *sql.DB, actor Actor) Actor{ @@ -100,7 +100,7 @@ func CreateNewBoardDB(db *sql.DB, actor Actor) Actor{ verify.Code = CreateKey(50) verify.Type = "post" - CreateVerification(db, verify) + CreateVerification(db, verify) var nverify Verify nverify.Board = actor.Id @@ -119,7 +119,7 @@ func CreateNewBoardDB(db *sql.DB, actor Actor) Actor{ CreateBoardMod(db, nverify) CreatePem(db, actor) - + if actor.Name != "main" { var nObject ObjectBase var nActivity Activity @@ -149,17 +149,17 @@ func GetBoards(db *sql.DB) []Actor { var board []Actor query := `select type, id, name, preferedusername, inbox, outbox, following, followers FROM actor` - + rows, err := db.Query(query) CheckError(err, "could not get boards from db query") - defer rows.Close() + defer rows.Close() for rows.Next(){ var actor = new(Actor) - + err = rows.Scan(&actor.Type, &actor.Id, &actor.Name, &actor.PreferredUsername, &actor.Inbox, &actor.Outbox, &actor.Following, &actor.Followers) - + if err !=nil{ panic(err) } @@ -180,9 +180,9 @@ func WriteObjectToDB(db *sql.DB, obj ObjectBase) ObjectBase { obj.Preview.AttributedTo = obj.Id WritePreviewToDB(db, *obj.Preview) } - + for i, _ := range obj.Attachment { - obj.Attachment[i].Id = fmt.Sprintf("%s/%s", obj.Actor, CreateUniqueID(db, obj.Actor)) + obj.Attachment[i].Id = fmt.Sprintf("%s/%s", obj.Actor, CreateUniqueID(db, obj.Actor)) obj.Attachment[i].Published = time.Now().UTC().Format(time.RFC3339) obj.Attachment[i].Updated = time.Now().UTC().Format(time.RFC3339) obj.Attachment[i].AttributedTo = obj.Id @@ -202,22 +202,22 @@ func WriteObjectToDB(db *sql.DB, obj ObjectBase) ObjectBase { func WriteObjectUpdatesToDB(db *sql.DB, obj ObjectBase) { query := `update activitystream set updated=$1 where id=$2` - + _, e := db.Exec(query, time.Now().UTC().Format(time.RFC3339), obj.Id) - + if e != nil{ fmt.Println("error inserting updating inreplyto") - panic(e) + panic(e) } query = `update cacheactivitystream set updated=$1 where id=$2` - + _, e = db.Exec(query, time.Now().UTC().Format(time.RFC3339), obj.Id) - + if e != nil{ fmt.Println("error inserting updating cache inreplyto") - panic(e) - } + panic(e) + } } func WriteObjectReplyToLocalDB(db *sql.DB, id string, replyto string) { @@ -263,13 +263,13 @@ func WriteObjectReplyToDB(db *sql.DB, obj ObjectBase) { rows.Next() rows.Scan(&id) - if id == "" { + if id == "" { query := `insert into replies (id, inreplyto) values ($1, $2)` - _, err := db.Exec(query, obj.Id, e.Id) + _, err := db.Exec(query, obj.Id, e.Id) - CheckError(err, "error inserting replies db") + CheckError(err, "error inserting replies db") } update := true @@ -279,10 +279,10 @@ func WriteObjectReplyToDB(db *sql.DB, obj ObjectBase) { break } } - + if update { WriteObjectUpdatesToDB(db, e) - } + } } if len(obj.InReplyTo) < 1 { @@ -301,7 +301,7 @@ func WriteObjectReplyToDB(db *sql.DB, obj ObjectBase) { if id == "" { query := `insert into replies (id, inreplyto) values ($1, $2)` - _, err := db.Exec(query, obj.Id, "") + _, err := db.Exec(query, obj.Id, "") CheckError(err, "error inserting replies db") } @@ -322,13 +322,13 @@ func WriteActorObjectReplyToDB(db *sql.DB, obj ObjectBase) { rows.Next() rows.Scan(&id) - if id == "" { + if id == "" { query := `insert into replies (id, inreplyto) values ($1, $2)` - _, err := db.Exec(query, obj.Id, e.Id) + _, err := db.Exec(query, obj.Id, e.Id) - CheckError(err, "error inserting replies db") + CheckError(err, "error inserting replies db") } } @@ -348,7 +348,7 @@ func WriteActorObjectReplyToDB(db *sql.DB, obj ObjectBase) { if id == "" { query := `insert into replies (id, inreplyto) values ($1, $2)` - _, err := db.Exec(query, obj.Id, "") + _, err := db.Exec(query, obj.Id, "") CheckError(err, "error inserting replies db") } @@ -356,18 +356,18 @@ func WriteActorObjectReplyToDB(db *sql.DB, obj ObjectBase) { } func WriteWalletToDB(db *sql.DB, obj ObjectBase) { - for _, e := range obj.Option { + for _, e := range obj.Option { if e == "wallet" { for _, e := range obj.Wallet { query := `insert into wallet (id, type, address) values ($1, $2, $3)` - _, err := db.Exec(query, obj.Id ,e.Type, e.Address) + _, err := db.Exec(query, obj.Id ,e.Type, e.Address) CheckError(err, "error with write wallet query") } - return + return } - } + } } func WriteActivitytoDB(db *sql.DB, obj ObjectBase) { @@ -378,49 +378,49 @@ func WriteActivitytoDB(db *sql.DB, obj ObjectBase) { query := `insert into activitystream (id, type, name, content, published, updated, attributedto, actor, tripcode, sensitive) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)` - _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Content, obj.Published, obj.Updated, obj.AttributedTo, obj.Actor, obj.TripCode, obj.Sensitive) - + _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Content, obj.Published, obj.Updated, obj.AttributedTo, obj.Actor, obj.TripCode, obj.Sensitive) + if e != nil{ fmt.Println("error inserting new activity") - panic(e) - } + panic(e) + } } func WriteActivitytoDBWithAttachment(db *sql.DB, obj ObjectBase, attachment ObjectBase, preview NestedObjectBase) { - + obj.Name = EscapeString(obj.Name) obj.Content = EscapeString(obj.Content) obj.AttributedTo = EscapeString(obj.AttributedTo) query := `insert into activitystream (id, type, name, content, attachment, preview, published, updated, attributedto, actor, tripcode, sensitive) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)` - _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Content, attachment.Id, preview.Id, obj.Published, obj.Updated, obj.AttributedTo, obj.Actor, obj.TripCode, obj.Sensitive) - + _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Content, attachment.Id, preview.Id, obj.Published, obj.Updated, obj.AttributedTo, obj.Actor, obj.TripCode, obj.Sensitive) + if e != nil{ fmt.Println("error inserting new activity with attachment") - panic(e) - } + panic(e) + } } func WriteAttachmentToDB(db *sql.DB, obj ObjectBase) { query := `insert into activitystream (id, type, name, href, published, updated, attributedTo, mediatype, size) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)` - - _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Href, obj.Published, obj.Updated, obj.AttributedTo, obj.MediaType, obj.Size) - + + _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Href, obj.Published, obj.Updated, obj.AttributedTo, obj.MediaType, obj.Size) + if e != nil{ fmt.Println("error inserting new attachment") - panic(e) + panic(e) } } func WritePreviewToDB(db *sql.DB, obj NestedObjectBase) { query := `insert into activitystream (id, type, name, href, published, updated, attributedTo, mediatype, size) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)` - + _, e := db.Exec(query, obj.Id ,obj.Type, obj.Name, obj.Href, obj.Published, obj.Updated, obj.AttributedTo, obj.MediaType, obj.Size) - + if e != nil{ fmt.Println("error inserting new attachment") - panic(e) + panic(e) } } @@ -433,22 +433,22 @@ func GetActivityFromDB(db *sql.DB, id string) Collection { query := `select actor, id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where id=$1 order by updated asc` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error query object from db") - + defer rows.Close() for rows.Next(){ var post ObjectBase var actor Actor - var attachID string + var attachID string var previewID string - + err = rows.Scan(&nColl.Actor.Id, &post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.Updated, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) - + CheckError(err, "error scan object into post struct") - post.Actor = actor.Id + post.Actor = actor.Id var postCnt int var imgCnt int @@ -459,23 +459,23 @@ func GetActivityFromDB(db *sql.DB, id string) Collection { post.Attachment = GetObjectAttachment(db, attachID) - post.Preview = GetObjectPreview(db, previewID) + post.Preview = GetObjectPreview(db, previewID) result = append(result, post) } nColl.OrderedItems = result - return nColl + return nColl } func GetObjectFromDBPage(db *sql.DB, id string, page int) Collection { var nColl Collection var result []ObjectBase - query := `select count (x.id) over(), x.id, x.name, x.content, x.type, x.published, x.updated, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor=$1 and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from cacheactivitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note') as x order by x.updated desc limit 8 offset $2` + query := `select count (x.id) over(), x.id, x.name, x.content, x.type, x.published, x.updated, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor=$1 and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from cacheactivitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note') as x order by x.updated desc limit 15 offset $2` - rows, err := db.Query(query, id, page * 8) + rows, err := db.Query(query, id, page * 15) CheckError(err, "error query object from db") @@ -485,20 +485,20 @@ func GetObjectFromDBPage(db *sql.DB, id string, page int) Collection { var post ObjectBase var actor Actor var attachID string - var previewID string - + var previewID string + err = rows.Scan(&count, &post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.Updated, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) - + CheckError(err, "error scan object into post struct") post.Actor = actor.Id var postCnt int - var imgCnt int + var imgCnt int post.Replies, postCnt, imgCnt = GetObjectRepliesDBLimit(db, post, 5) post.Replies.TotalItems = postCnt - post.Replies.TotalImgs = imgCnt + post.Replies.TotalImgs = imgCnt post.Attachment = GetObjectAttachment(db, attachID) @@ -510,7 +510,7 @@ func GetObjectFromDBPage(db *sql.DB, id string, page int) Collection { nColl.TotalItems = count nColl.OrderedItems = result - return nColl + return nColl } func GetObjectFromDB(db *sql.DB, id string) Collection { @@ -519,29 +519,29 @@ func GetObjectFromDB(db *sql.DB, id string) Collection { query := `select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor=$1 and id in (select id from replies where inreplyto='') and type='Note' order by updated desc` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error query object from db") - + defer rows.Close() for rows.Next(){ var post ObjectBase var actor Actor var attachID string - var previewID string - + var previewID string + err = rows.Scan(&post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.Updated, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) - + CheckError(err, "error scan object into post struct") post.Actor = actor.Id var postCnt int - var imgCnt int + var imgCnt int post.Replies, postCnt, imgCnt = GetObjectRepliesDB(db, post) post.Replies.TotalItems = postCnt - post.Replies.TotalImgs = imgCnt + post.Replies.TotalImgs = imgCnt post.Attachment = GetObjectAttachment(db, attachID) @@ -552,7 +552,7 @@ func GetObjectFromDB(db *sql.DB, id string) Collection { nColl.OrderedItems = result - return nColl + return nColl } func GetObjectFromDBFromID(db *sql.DB, id string) Collection { @@ -568,31 +568,31 @@ func GetObjectFromDBFromID(db *sql.DB, id string) Collection { re := regexp.MustCompile(`(.+)\-`) id = re.ReplaceAllString(id, "") id = "%" + match[1] + "/" + id - } + } - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error query object from db") - + defer rows.Close() for rows.Next(){ var post ObjectBase var actor Actor var attachID string - var previewID string - + var previewID string + err = rows.Scan(&post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.Updated, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) - + CheckError(err, "error scan object into post struct") post.Actor = actor.Id var postCnt int - var imgCnt int + var imgCnt int post.Replies, postCnt, imgCnt = GetObjectRepliesDB(db, post) post.Replies.TotalItems = postCnt - post.Replies.TotalImgs = imgCnt + post.Replies.TotalImgs = imgCnt post.Attachment = GetObjectAttachment(db, attachID) @@ -603,28 +603,28 @@ func GetObjectFromDBFromID(db *sql.DB, id string) Collection { nColl.OrderedItems = result - return nColl + return nColl } func GetObjectFromDBCatalog(db *sql.DB, id string) Collection { var nColl Collection var result []ObjectBase - query := `select x.id, x.name, x.content, x.type, x.published, x.updated, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor=$1 and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from cacheactivitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note') as x order by x.updated desc` + query := `select x.id, x.name, x.content, x.type, x.published, x.updated, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor=$1 and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from cacheactivitystream where actor in (select following from following where id=$1) and id in (select id from replies where inreplyto='') and type='Note') as x order by x.updated desc limit 165` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error query object from db") - + defer rows.Close() for rows.Next(){ var post ObjectBase var actor Actor var attachID string - var previewID string - + var previewID string + err = rows.Scan(&post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.Updated, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) - + CheckError(err, "error scan object into post struct") post.Actor = actor.Id @@ -633,7 +633,7 @@ func GetObjectFromDBCatalog(db *sql.DB, id string) Collection { post.Replies = &replies - post.Replies.TotalItems, post.Replies.TotalImgs = GetObjectRepliesCount(db, post) + post.Replies.TotalItems, post.Replies.TotalImgs = GetObjectRepliesCount(db, post) post.Attachment = GetObjectAttachment(db, attachID) @@ -644,7 +644,7 @@ func GetObjectFromDBCatalog(db *sql.DB, id string) Collection { nColl.OrderedItems = result - return nColl + return nColl } func GetObjectByIDFromDB(db *sql.DB, postID string) Collection { @@ -653,33 +653,33 @@ func GetObjectByIDFromDB(db *sql.DB, postID string) Collection { query := `select x.id, x.name, x.content, x.type, x.published, x.updated, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where id=$1 and type='Note' union select id, name, content, type, published, updated, attributedto, attachment, preview, actor, tripcode, sensitive from cacheactivitystream where id=$1 and type='Note') as x` - rows, err := db.Query(query, postID) + rows, err := db.Query(query, postID) CheckError(err, "error query object from db") - + defer rows.Close() for rows.Next(){ var post ObjectBase var actor Actor var attachID string - var previewID string - + var previewID string + err = rows.Scan(&post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.Updated, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) - + CheckError(err, "error scan object into post struct") actor = GetActorFromDB(db, actor.Id) post.Actor = actor.Id - nColl.Actor = &actor + nColl.Actor = &actor var postCnt int - var imgCnt int + var imgCnt int post.Replies, postCnt, imgCnt = GetObjectRepliesDB(db, post) post.Replies.TotalItems = postCnt - post.Replies.TotalImgs = imgCnt + post.Replies.TotalImgs = imgCnt post.Attachment = GetObjectAttachment(db, attachID) @@ -690,13 +690,13 @@ func GetObjectByIDFromDB(db *sql.DB, postID string) Collection { nColl.OrderedItems = result - return nColl + return nColl } func GetInReplyToDB(db *sql.DB, parent ObjectBase) []ObjectBase { var result []ObjectBase - query := `select inreplyto from replies where id =$1` + query := `select inreplyto from replies where id =$1` rows, err := db.Query(query, parent.Id) @@ -721,22 +721,22 @@ func GetObjectRepliesDBLimit(db *sql.DB, parent ObjectBase, limit int) (*Collect query := `select count(x.id) over(), sum(case when RTRIM(x.attachment) = '' then 0 else 1 end) over(), x.id, x.name, x.content, x.type, x.published, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select * from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' union select * from cacheactivitystream where id in (select id from replies where inreplyto=$1) and type='Note') as x order by x.published desc limit $2` - rows, err := db.Query(query, parent.Id, limit) + rows, err := db.Query(query, parent.Id, limit) CheckError(err, "error with replies db query") var postCount int var attachCount int - - defer rows.Close() + + defer rows.Close() for rows.Next() { var post ObjectBase var actor Actor var attachID string - var previewID string + var previewID string post.InReplyTo = append(post.InReplyTo, parent) - + err = rows.Scan(&postCount, &attachCount, &post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) CheckError(err, "error with replies db scan") @@ -753,14 +753,14 @@ func GetObjectRepliesDBLimit(db *sql.DB, parent ObjectBase, limit int) (*Collect post.Attachment = GetObjectAttachment(db, attachID) - post.Preview = GetObjectPreview(db, previewID) + post.Preview = GetObjectPreview(db, previewID) - result = append(result, post) + result = append(result, post) } nColl.OrderedItems = result - sort.Sort(ObjectBaseSortAsc(nColl.OrderedItems)) + sort.Sort(ObjectBaseSortAsc(nColl.OrderedItems)) return &nColl, postCount, attachCount } @@ -770,24 +770,24 @@ func GetObjectRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, int, in var nColl CollectionBase var result []ObjectBase - query := `select count(x.id) over(), sum(case when RTRIM(x.attachment) = '' then 0 else 1 end) over(), x.id, x.name, x.content, x.type, x.published, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select * from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' union select * from cacheactivitystream where id in (select id from replies where inreplyto=$1) and type='Note') as x order by x.published asc` + query := `select count(x.id) over(), sum(case when RTRIM(x.attachment) = '' then 0 else 1 end) over(), x.id, x.name, x.content, x.type, x.published, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select * from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' union select * from cacheactivitystream where id in (select id from replies where inreplyto=$1) and type='Note') as x order by x.published asc` - rows, err := db.Query(query, parent.Id) + rows, err := db.Query(query, parent.Id) CheckError(err, "error with replies db query") var postCount int var attachCount int - defer rows.Close() + defer rows.Close() for rows.Next() { var post ObjectBase var actor Actor var attachID string - var previewID string + var previewID string post.InReplyTo = append(post.InReplyTo, parent) - + err = rows.Scan(&postCount, &attachCount, &post.Id, &post.Name, &post.Content, &post.Type, &post.Published, &post.AttributedTo, &attachID, &previewID, &actor.Id, &post.TripCode, &post.Sensitive) CheckError(err, "error with replies db scan") @@ -796,17 +796,17 @@ func GetObjectRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, int, in var postCnt int var imgCnt int - + post.Replies, postCnt, imgCnt = GetObjectRepliesRepliesDB(db, post) post.Replies.TotalItems = postCnt - post.Replies.TotalImgs = imgCnt - + post.Replies.TotalImgs = imgCnt + post.Attachment = GetObjectAttachment(db, attachID) - post.Preview = GetObjectPreview(db, previewID) + post.Preview = GetObjectPreview(db, previewID) - result = append(result, post) + result = append(result, post) } nColl.OrderedItems = result @@ -821,7 +821,7 @@ func GetObjectRepliesReplies(db *sql.DB, parent ObjectBase) (*CollectionBase, in query := `select id, name, content, type, published, attributedto, attachment, preview, actor, tripcode, sensitive from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' order by updated asc` - rows, err := db.Query(query, parent.Id) + rows, err := db.Query(query, parent.Id) CheckError(err, "error with replies replies db query") @@ -830,7 +830,7 @@ func GetObjectRepliesReplies(db *sql.DB, parent ObjectBase) (*CollectionBase, in var post ObjectBase var actor Actor var attachID string - var previewID string + var previewID string post.InReplyTo = append(post.InReplyTo, parent) @@ -842,14 +842,14 @@ func GetObjectRepliesReplies(db *sql.DB, parent ObjectBase) (*CollectionBase, in post.Attachment = GetObjectAttachment(db, attachID) - post.Preview = GetObjectPreview(db, previewID) + post.Preview = GetObjectPreview(db, previewID) - result = append(result, post) + result = append(result, post) } nColl.OrderedItems = result - return &nColl, 0, 0 + return &nColl, 0, 0 } func GetObjectRepliesRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, int, int) { @@ -857,7 +857,7 @@ func GetObjectRepliesRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, var nColl CollectionBase var result []ObjectBase - query := `select count(x.id) over(), sum(case when RTRIM(x.attachment) = '' then 0 else 1 end) over(), x.id, x.name, x.content, x.type, x.published, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select * from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' union select * from cacheactivitystream where id in (select id from replies where inreplyto=$1) and type='Note') as x order by x.published asc` + query := `select count(x.id) over(), sum(case when RTRIM(x.attachment) = '' then 0 else 1 end) over(), x.id, x.name, x.content, x.type, x.published, x.attributedto, x.attachment, x.preview, x.actor, x.tripcode, x.sensitive from (select * from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' union select * from cacheactivitystream where id in (select id from replies where inreplyto=$1) and type='Note') as x order by x.published asc` rows, err := db.Query(query, parent.Id) @@ -870,7 +870,7 @@ func GetObjectRepliesRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, var post ObjectBase var actor Actor var attachID string - var previewID string + var previewID string post.InReplyTo = append(post.InReplyTo, parent) @@ -882,12 +882,12 @@ func GetObjectRepliesRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, post.Attachment = GetObjectAttachment(db, attachID) - post.Preview = GetObjectPreview(db, previewID) + post.Preview = GetObjectPreview(db, previewID) - result = append(result, post) + result = append(result, post) } - nColl.OrderedItems = result + nColl.OrderedItems = result return &nColl, postCount, attachCount } @@ -895,7 +895,7 @@ func GetObjectRepliesRepliesDB(db *sql.DB, parent ObjectBase) (*CollectionBase, func CheckIfObjectOP(db *sql.DB, id string) bool { var count int - + query := `select count(id) from replies where inreplyto='' and id=$1 ` rows, err := db.Query(query, id) @@ -918,9 +918,9 @@ func GetObjectRepliesCount(db *sql.DB, parent ObjectBase) (int, int) { var countImg int query := `select count(x.id) over(), sum(case when RTRIM(x.attachment) = '' then 0 else 1 end) over() from (select id, attachment from activitystream where id in (select id from replies where inreplyto=$1) and type='Note' union select id, attachment from cacheactivitystream where id in (select id from replies where inreplyto=$1) and type='Note') as x` - - rows, err := db.Query(query, parent.Id) - + + rows, err := db.Query(query, parent.Id) + CheckError(err, "error with replies count db query") defer rows.Close() @@ -932,11 +932,11 @@ func GetObjectRepliesCount(db *sql.DB, parent ObjectBase) (int, int) { func GetObjectAttachment(db *sql.DB, id string) []ObjectBase { - var attachments []ObjectBase + var attachments []ObjectBase query := `select x.id, x.type, x.name, x.href, x.mediatype, x.size, x.published from (select id, type, name, href, mediatype, size, published from activitystream where id=$1 union select id, type, name, href, mediatype, size, published from cacheactivitystream where id=$1) as x` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "could not select object attachment query") @@ -961,10 +961,10 @@ func GetObjectPreview(db *sql.DB, id string) *NestedObjectBase { var preview NestedObjectBase query := `select x.id, x.type, x.name, x.href, x.mediatype, x.size, x.published from (select id, type, name, href, mediatype, size, published from activitystream where id=$1 union select id, type, name, href, mediatype, size, published from cacheactivitystream where id=$1) as x` - - rows, err := db.Query(query, id) - CheckError(err, "could not select object preview query") + rows, err := db.Query(query, id) + + CheckError(err, "could not select object preview query") defer rows.Close() for rows.Next() { @@ -979,16 +979,16 @@ func GetObjectPostsTotalDB(db *sql.DB, actor Actor) int{ count := 0 query := `select count(id) from activitystream where actor=$1 and id in (select id from replies where inreplyto='' and type='Note')` - rows, err := db.Query(query, actor.Id) + rows, err := db.Query(query, actor.Id) - CheckError(err, "could not select post total count query") + CheckError(err, "could not select post total count query") - defer rows.Close() + defer rows.Close() for rows.Next() { err = rows.Scan(&count) CheckError(err, "error with total post db scan") } - + return count } @@ -997,9 +997,9 @@ func GetObjectImgsTotalDB(db *sql.DB, actor Actor) int{ count := 0 query := `select count(attachment) from activitystream where actor=$1 and id in (select id from replies where inreplyto='' and type='Note' )` - rows, err := db.Query(query, actor.Id) + rows, err := db.Query(query, actor.Id) - CheckError(err, "error with posts total db query") + CheckError(err, "error with posts total db query") defer rows.Close() for rows.Next() { @@ -1007,7 +1007,7 @@ func GetObjectImgsTotalDB(db *sql.DB, actor Actor) int{ CheckError(err, "error with total post db scan") } - + return count } @@ -1015,9 +1015,9 @@ func DeletePreviewFromFile(db *sql.DB, id string) { var query = `select href from activitystream where id in (select preview from activitystream where id=$1)` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) - CheckError(err, "error query delete attachment") + CheckError(err, "error query delete attachment") defer rows.Close() for rows.Next() { @@ -1041,9 +1041,9 @@ func RemovePreviewFromFile(db *sql.DB, id string) { var query = `select href from activitystream where id in (select preview from activitystream where id=$1)` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) - CheckError(err, "error query delete attachment") + CheckError(err, "error query delete attachment") defer rows.Close() for rows.Next() { @@ -1068,9 +1068,9 @@ func DeleteAttachmentFromFile(db *sql.DB, id string) { var query = `select href from activitystream where id in (select attachment from activitystream where id=$1)` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) - CheckError(err, "error query delete attachment") + CheckError(err, "error query delete attachment") defer rows.Close() for rows.Next() { @@ -1092,42 +1092,42 @@ func DeleteAttachmentFromFile(db *sql.DB, id string) { func TombstonePreviewRepliesFromDB(db *sql.DB, id string) { var query = `select id from activitystream where id in (select id from replies where inreplyto=$1)` - + rows, err := db.Query(query, id) CheckError(err, "error query tombstone preview replies") - defer rows.Close() + defer rows.Close() for rows.Next() { var attachment string err := rows.Scan(&attachment) CheckError(err, "error scanning tombstone preview") - + DeletePreviewFromFile(db, attachment) TombstonePreviewFromDB(db, attachment) - } + } } func TombstoneAttachmentRepliesFromDB(db *sql.DB, id string) { var query = `select id from activitystream where id in (select id from replies where inreplyto=$1)` - - rows, err := db.Query(query, id) + + rows, err := db.Query(query, id) CheckError(err, "error query tombstone attachment replies") - defer rows.Close() + defer rows.Close() for rows.Next() { var attachment string err := rows.Scan(&attachment) CheckError(err, "error scanning delete attachment") - + DeleteAttachmentFromFile(db, attachment) TombstoneAttachmentFromDB(db, attachment) - } + } } func TombstoneAttachmentFromDB(db *sql.DB, id string) { @@ -1135,29 +1135,29 @@ func TombstoneAttachmentFromDB(db *sql.DB, id string) { var query = `update activitystream set type='Tombstone', mediatype='image/png', href=$1, name='', content='', attributedto='deleted', deleted=$2 where id in (select attachment from activitystream where id=$3)` - _, err := db.Exec(query, Domain + "/static/notfound.png", datetime, id) + _, err := db.Exec(query, Domain + "/static/notfound.png", datetime, id) CheckError(err, "error with tombstone attachment") query = `update cacheactivitystream set type='Tombstone', mediatype='image/png', href=$1, name='', content='', attributedto='deleted', deleted=$2 where id in (select attachment from cacheactivitystream where id=$3)` - _, err = db.Exec(query, Domain + "/static/notfound.png", datetime, id) + _, err = db.Exec(query, Domain + "/static/notfound.png", datetime, id) - CheckError(err, "error with tombstone cache attachment") + CheckError(err, "error with tombstone cache attachment") } func DeleteAttachmentFromDB(db *sql.DB, id string) { var query = `delete from activitystream where id in (select attachment from activitystream where id=$1)` - _, err := db.Exec(query, id) + _, err := db.Exec(query, id) CheckError(err, "error with delete attachment") query = `delete from cacheactivitystream where id in (select attachment from cacheactivitystream where id=$1)` - _, err = db.Exec(query, id) + _, err = db.Exec(query, id) - CheckError(err, "error with delete cache attachment") + CheckError(err, "error with delete cache attachment") } func TombstonePreviewFromDB(db *sql.DB, id string) { @@ -1165,73 +1165,73 @@ func TombstonePreviewFromDB(db *sql.DB, id string) { var query = `update activitystream set type='Tombstone', mediatype='image/png', href=$1, name='', content='', attributedto='deleted', deleted=$2 where id in (select preview from activitystream where id=$3)` - _, err := db.Exec(query, Domain + "/static/notfound.png", datetime, id) + _, err := db.Exec(query, Domain + "/static/notfound.png", datetime, id) CheckError(err, "error with tombstone preview") query = `update cacheactivitystream set type='Tombstone', mediatype='image/png', href=$1, name='', content='', attributedto='deleted', deleted=$2 where id in (select preview from cacheactivitystream where id=$3)` - _, err = db.Exec(query, Domain + "/static/notfound.png", datetime, id) + _, err = db.Exec(query, Domain + "/static/notfound.png", datetime, id) - CheckError(err, "error with tombstone cache preview") + CheckError(err, "error with tombstone cache preview") } func DeletePreviewFromDB(db *sql.DB, id string) { var query = `delete from activitystream where id=$1` - _, err := db.Exec(query, id) + _, err := db.Exec(query, id) CheckError(err, "error with delete preview") query = `delete from cacheactivitystream where id in (select preview from cacheactivitystream where id=$1)` - _, err = db.Exec(query, id) + _, err = db.Exec(query, id) - CheckError(err, "error with delete cache preview") + CheckError(err, "error with delete cache preview") } func DeleteObjectRepliedTo(db *sql.DB, id string){ query := `delete from replies where id=$1` _, err := db.Exec(query, id) - CheckError(err, "error with delete object replies") + CheckError(err, "error with delete object replies") } func TombstoneObjectFromDB(db *sql.DB, id string) { datetime := time.Now().UTC().Format(time.RFC3339) var query = `update activitystream set type='Tombstone', name='', content='', attributedto='deleted', tripcode='', deleted=$1 where id=$2` - _, err := db.Exec(query, datetime, id) + _, err := db.Exec(query, datetime, id) CheckError(err, "error with tombstone object") query = `update cacheactivitystream set type='Tombstone', name='', content='', attributedto='deleted', tripcode='', deleted=$1 where id=$2` - _, err = db.Exec(query, datetime, id) + _, err = db.Exec(query, datetime, id) - CheckError(err, "error with tombstone cache object") + CheckError(err, "error with tombstone cache object") } func DeleteObjectFromDB(db *sql.DB, id string) { var query = `delete from activitystream where id=$1` - _, err := db.Exec(query, id) + _, err := db.Exec(query, id) CheckError(err, "error with delete object") query = `delete from cacheactivitystream where id=$1` - _, err = db.Exec(query, id) + _, err = db.Exec(query, id) - CheckError(err, "error with delete cache object") + CheckError(err, "error with delete cache object") } func DeleteObjectsInReplyTo(db *sql.DB, id string) { - query := `delete from replies where id in (select id from replies where inreplyto=$1)` + query := `delete from replies where id in (select id from replies where inreplyto=$1)` _, err := db.Exec(query, id) - CheckError(err, "error with delete object replies to") + CheckError(err, "error with delete object replies to") } func TombstoneObjectRepliesFromDB(db *sql.DB, id string) { @@ -1239,13 +1239,13 @@ func TombstoneObjectRepliesFromDB(db *sql.DB, id string) { var query = `update activitystream set type='Tombstone', name='', content='', attributedto='deleted', tripcode='', deleted=$1 where id in (select id from replies where inreplyto=$2)` - _, err := db.Exec(query, datetime, id) + _, err := db.Exec(query, datetime, id) CheckError(err, "error with tombstone object replies") query = `update cacheactivitystream set type='Tombstone', name='', content='', attributedto='deleted', tripcode='', deleted=$1 where id in (select id from replies where inreplyto=$2)` - _, err = db.Exec(query, datetime, id) - CheckError(err, "error with tombstone object cache replies") + _, err = db.Exec(query, datetime, id) + CheckError(err, "error with tombstone object cache replies") } @@ -1254,15 +1254,15 @@ func SetAttachmentFromDB(db *sql.DB, id string, _type string) { var query = `update activitystream set type=$1, deleted=$2 where id in (select attachment from activitystream where id=$3)` - _, err := db.Exec(query, _type, datetime, id) + _, err := db.Exec(query, _type, datetime, id) CheckError(err, "error with set attachment") query = `update cacheactivitystream set type=$1, deleted=$2 where id in (select attachment from cacheactivitystream where id=$3)` - _, err = db.Exec(query, _type, datetime, id) + _, err = db.Exec(query, _type, datetime, id) - CheckError(err, "error with set cache attachment") + CheckError(err, "error with set cache attachment") } func SetAttachmentRepliesFromDB(db *sql.DB, id string, _type string) { @@ -1270,15 +1270,15 @@ func SetAttachmentRepliesFromDB(db *sql.DB, id string, _type string) { var query = `update activitystream set type=$1, deleted=$2 where id in (select attachment from activitystream where id in (select id from replies where inreplyto=$3))` - _, err := db.Exec(query, _type, datetime, id) + _, err := db.Exec(query, _type, datetime, id) CheckError(err, "error with set attachment") query = `update cacheactivitystream set type=$1, deleted=$2 where id in (select attachment from cacheactivitystream where id in (select id from replies where inreplyto=$3))` - _, err = db.Exec(query, _type, datetime, id) + _, err = db.Exec(query, _type, datetime, id) - CheckError(err, "error with set cache attachment") + CheckError(err, "error with set cache attachment") } func SetPreviewFromDB(db *sql.DB, id string, _type string) { @@ -1286,15 +1286,15 @@ func SetPreviewFromDB(db *sql.DB, id string, _type string) { var query = `update activitystream set type=$1, deleted=$2 where id in (select preview from activitystream where id=$3)` - _, err := db.Exec(query, _type, datetime, id) + _, err := db.Exec(query, _type, datetime, id) CheckError(err, "error with set preview") query = `update cacheactivitystream set type=$1, deleted=$2 where id in (select preview from cacheactivitystream where id=$3)` - _, err = db.Exec(query, _type, datetime, id) + _, err = db.Exec(query, _type, datetime, id) - CheckError(err, "error with set cache preview") + CheckError(err, "error with set cache preview") } func SetPreviewRepliesFromDB(db *sql.DB, id string, _type string) { @@ -1302,43 +1302,43 @@ func SetPreviewRepliesFromDB(db *sql.DB, id string, _type string) { var query = `update activitystream set type=$1, deleted=$2 where id in (select preview from activitystream where id in (select id from replies where inreplyto=$3))` - _, err := db.Exec(query, _type, datetime, id) + _, err := db.Exec(query, _type, datetime, id) CheckError(err, "error with set preview") - query = `update cacheactivitystream set type=$1, deleted=$2 where id in (select preview from cacheactivitystream where id in (select id from replies where inreplyto=$3))` + query = `update cacheactivitystream set type=$1, deleted=$2 where id in (select preview from cacheactivitystream where id in (select id from replies where inreplyto=$3))` - _, err = db.Exec(query, _type, datetime, id) + _, err = db.Exec(query, _type, datetime, id) - CheckError(err, "error with set cache preview") + CheckError(err, "error with set cache preview") } func SetObjectFromDB(db *sql.DB, id string, _type string) { datetime := time.Now().UTC().Format(time.RFC3339) - + var query = `update activitystream set type=$1, deleted=$2 where id=$3` - _, err := db.Exec(query, _type, datetime, id) + _, err := db.Exec(query, _type, datetime, id) CheckError(err, "error with set object") query = `update cacheactivitystream set type=$1, deleted=$2 where id=$3` - _, err = db.Exec(query, _type, datetime, id) + _, err = db.Exec(query, _type, datetime, id) - CheckError(err, "error with set cache object") + CheckError(err, "error with set cache object") } func SetObjectRepliesFromDB(db *sql.DB, id string, _type string) { datetime := time.Now().UTC().Format(time.RFC3339) var query = `update activitystream set type=$1, deleted=$2 where id in (select id from replies where inreplyto=$3)` - _, err := db.Exec(query, _type, datetime, id) + _, err := db.Exec(query, _type, datetime, id) CheckError(err, "error with set object replies") query = `update cacheactivitystream set type=$1, deleted=$2 where id in (select id from replies where inreplyto=$3)` - _, err = db.Exec(query, _type, datetime, id) - CheckError(err, "error with set cache object replies") + _, err = db.Exec(query, _type, datetime, id) + CheckError(err, "error with set cache object replies") } func SetObject(db *sql.DB, id string, _type string) { @@ -1353,7 +1353,7 @@ func SetObjectAndReplies(db *sql.DB, id string, _type string) { SetObjectRepliesFromDB(db, id, _type); SetAttachmentRepliesFromDB(db, id, _type); SetPreviewRepliesFromDB(db, id, _type); - SetObjectFromDB(db, id, _type); + SetObjectFromDB(db, id, _type); } func DeleteObject(db *sql.DB, id string) { @@ -1361,7 +1361,7 @@ func DeleteObject(db *sql.DB, id string) { DeleteAttachmentFromFile(db, id) DeleteAttachmentFromDB(db, id) DeletePreviewFromFile(db, id) - DeletePreviewFromDB(db, id) + DeletePreviewFromDB(db, id) DeleteObjectFromDB(db, id) DeleteObjectRepliedTo(db, id) } @@ -1371,16 +1371,16 @@ func TombstoneObject(db *sql.DB, id string) { DeleteAttachmentFromFile(db, id) TombstoneAttachmentFromDB(db, id) DeletePreviewFromFile(db, id) - TombstonePreviewFromDB(db, id) + TombstonePreviewFromDB(db, id) TombstoneObjectFromDB(db, id) } func TombstoneObjectAndReplies(db *sql.DB, id string) { - DeleteReportActivity(db, id) + DeleteReportActivity(db, id) DeleteAttachmentFromFile(db, id) - TombstoneAttachmentFromDB(db, id) + TombstoneAttachmentFromDB(db, id) DeletePreviewFromFile(db, id) - TombstonePreviewFromDB(db, id) + TombstonePreviewFromDB(db, id) TombstoneObjectRepliesFromDB(db, id) TombstoneAttachmentRepliesFromDB(db, id) TombstonePreviewRepliesFromDB(db, id) @@ -1397,10 +1397,10 @@ func GetRandomCaptcha(db *sql.DB) string{ var verify string defer rows.Close() - + rows.Next() err = rows.Scan(&verify) - + CheckError(err, "Could not get verify captcha") return verify @@ -1410,11 +1410,11 @@ func GetCaptchaTotal(db *sql.DB) int{ query := `select count(*) from verification where type='captcha'` rows, err := db.Query(query) - - CheckError(err, "could not get query captcha total") + + CheckError(err, "could not get query captcha total") defer rows.Close() - + var count int for rows.Next(){ if err := rows.Scan(&count); err != nil{ @@ -1436,7 +1436,7 @@ func GetCaptchaCodeDB(db *sql.DB, verify string) string { defer rows.Close() var code string - + rows.Next() err = rows.Scan(&code) @@ -1450,19 +1450,19 @@ func GetCaptchaCodeDB(db *sql.DB, verify string) string { func GetActorAuth(db *sql.DB, actor string) []string { query := `select type from actorauth where board=$1` - rows, err := db.Query(query, actor) + rows, err := db.Query(query, actor) - CheckError(err, "could not get actor auth") + CheckError(err, "could not get actor auth") - defer rows.Close() + defer rows.Close() var auth []string - + for rows.Next() { var e string err = rows.Scan(&e) - CheckError(err, "could not get actor auth row scan") + CheckError(err, "could not get actor auth row scan") auth = append(auth, e) } @@ -1473,7 +1473,7 @@ func GetActorAuth(db *sql.DB, actor string) []string { func DeleteCaptchaCodeDB(db *sql.DB, verify string) { query := `delete from verification where identifier=$1` - _, err := db.Exec(query, verify) + _, err := db.Exec(query, verify) CheckError(err, "could not delete captcah code db") @@ -1488,7 +1488,7 @@ func EscapeString(text string) string { func GetActorReportedTotal(db *sql.DB, id string) int { query := `select count(id) from reported where board=$1` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error getting actor reported total query") @@ -1498,7 +1498,7 @@ func GetActorReportedTotal(db *sql.DB, id string) int { for rows.Next() { rows.Scan(&count) } - + return count } @@ -1507,7 +1507,7 @@ func GetActorReportedDB(db *sql.DB, id string) []ObjectBase { query := `select id, count, reason from reported where board=$1` - rows, err := db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error getting actor reported query") @@ -1531,7 +1531,7 @@ func GetActorPemFromDB(db *sql.DB, pemID string) PublicKeyPem { CheckError(err, "could not get public key pem from database") var pem PublicKeyPem - + defer rows.Close() rows.Next() rows.Scan(&pem.Id, &pem.Owner, &pem.PublicKeyPem) @@ -1542,7 +1542,7 @@ func GetActorPemFromDB(db *sql.DB, pemID string) PublicKeyPem { } pem.PublicKeyPem = strings.ReplaceAll(string(f), "\r\n", `\n`) - + return pem } @@ -1570,13 +1570,13 @@ func MarkObjectSensitive(db *sql.DB, id string, sensitive bool) { query = `update cacheactivitystream set sensitive=$1 where id=$2` _, err = db.Exec(query, sensitive, id) - CheckError(err, "error updating sensitive object in cacheactivitystream") + CheckError(err, "error updating sensitive object in cacheactivitystream") } //if limit less than 1 return all news items func getNewsFromDB(db *sql.DB, limit int) []NewsItem { var news []NewsItem - + var query string if(limit > 0) { query =`select title, content, time from newsItem order by time desc limit $1` @@ -1591,7 +1591,7 @@ func getNewsFromDB(db *sql.DB, limit int) []NewsItem { } else { rows, err = db.Query(query) } - + if CheckError(err, "could not get news from db query") != nil { return news @@ -1608,10 +1608,10 @@ func getNewsFromDB(db *sql.DB, limit int) []NewsItem { content = strings.ReplaceAll(content, "\n", "<br>") n.Content = template.HTML(content) - + news = append(news, n) } - + return news } @@ -1619,24 +1619,24 @@ func getNewsItemFromDB(db *sql.DB, timestamp int) (NewsItem, error) { var news NewsItem var content string query := `select title, content, time from newsItem where time=$1 limit 1` - + rows, err := db.Query(query, timestamp) - + if err != nil { return news, err } - + defer rows.Close() rows.Next() err = rows.Scan(&news.Title, &content, &news.Time) - + if err != nil { return news, err } content = strings.ReplaceAll(content, "\n", "<br>") - news.Content = template.HTML(content) - + news.Content = template.HTML(content) + return news, nil } @@ -1647,9 +1647,9 @@ func deleteNewsItemFromDB(db *sql.DB, timestamp int) { func WriteNewsToDB(db *sql.DB, news NewsItem) { query := `insert into newsItem (title, content, time) values ($1, $2, $3)` - + _, err := db.Exec(query, news.Title, news.Content, time.Now().Unix()) - + CheckError(err, "error writing news item") } @@ -1658,7 +1658,7 @@ func WriteRegexBlacklistDB(db *sql.DB, regex string) { rows, err := db.Query(query, regex) - CheckError(err, "error select from postblacklist db") + CheckError(err, "error select from postblacklist db") var re string defer rows.Close() @@ -1681,13 +1681,13 @@ func GetRegexBlacklistDB(db *sql.DB) []PostBlacklist { rows, err := db.Query(query) - CheckError(err, "error with select all from postblacklist db") + CheckError(err, "error with select all from postblacklist db") var List []PostBlacklist defer rows.Close() for rows.Next() { - var temp PostBlacklist + var temp PostBlacklist rows.Scan(&temp.Id, &temp.Regex) List = append(List, temp) @@ -21,7 +21,7 @@ import ( "bufio" "io" "github.com/gofrs/uuid" - "crypto/sha256" + "crypto/sha256" "encoding/hex" ) @@ -68,7 +68,7 @@ func main() { *Key = CreateKey(32) FollowingBoards = GetActorFollowingDB(db, Domain) - + Boards = GetBoardCollection(db) // root actor is used to follow remote feeds that are not local @@ -76,16 +76,16 @@ func main() { if GetConfigValue("instancename") != "" { CreateNewBoardDB(db, *CreateNewActor("", GetConfigValue("instancename"), GetConfigValue("instancesummary"), authReq, false)) if PublicIndexing == "true" { - AddInstanceToIndex(Domain) + AddInstanceToIndex(Domain) } } - + // Allow access to public media folder fileServer := http.FileServer(http.Dir("./public")) http.Handle("/public/", http.StripPrefix("/public", neuter(fileServer))) javascriptFiles := http.FileServer(http.Dir("./static")) - http.Handle("/static/", http.StripPrefix("/static", neuter(javascriptFiles))) + http.Handle("/static/", http.StripPrefix("/static", neuter(javascriptFiles))) // main routing http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){ @@ -101,7 +101,7 @@ func main() { var mainInbox bool var mainOutbox bool var mainFollowing bool - var mainFollowers bool + var mainFollowers bool var actorMain bool var actorInbox bool @@ -110,22 +110,22 @@ func main() { var actorPost bool var actorFollowing bool var actorFollowers bool - var actorReported bool + var actorReported bool var actorVerification bool var actorMainPage bool var accept = r.Header.Get("Accept") - + var method = r.Method var actor = GetActorFromPath(db, path, "/") if actor.Name == "main" { - mainActor = (path == "/") + mainActor = (path == "/") mainInbox = (path == "/inbox") mainOutbox = (path == "/outbox") mainFollowing = (path == "/following") - mainFollowers = (path == "/followers") + mainFollowers = (path == "/followers") } else { actorMain = (path == "/" + actor.Name) actorInbox = (path == "/" + actor.Name + "/inbox") @@ -133,7 +133,7 @@ func main() { actorOutbox = (path == "/" + actor.Name + "/outbox") actorFollowing = (path == "/" + actor.Name + "/following") actorFollowers = (path == "/" + actor.Name + "/followers") - actorReported = (path == "/" + actor.Name + "/reported") + actorReported = (path == "/" + actor.Name + "/reported") actorVerification = (path == "/" + actor.Name + "/verification") escapedActorName := strings.Replace(actor.Name, "*", "\\*", -1) @@ -141,15 +141,15 @@ func main() { escapedActorName = strings.Replace(escapedActorName, "$", "\\$", -1) escapedActorName = strings.Replace(escapedActorName, "?", "\\?", -1) escapedActorName = strings.Replace(escapedActorName, "+", "\\+", -1) - escapedActorName = strings.Replace(escapedActorName, ".", "\\.", -1) + escapedActorName = strings.Replace(escapedActorName, ".", "\\.", -1) re := regexp.MustCompile("/" + escapedActorName + "/[0-9]{1,2}$") actorMainPage = re.MatchString(path) - + re = regexp.MustCompile("/" + escapedActorName + "/\\w+") - - actorPost = re.MatchString(path) + + actorPost = re.MatchString(path) } if mainActor { @@ -159,27 +159,27 @@ func main() { } IndexGet(w, r, db) - + return } - + if mainInbox { if method == "POST" { - + } else { - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) } return } - + if mainOutbox { if method == "GET" { GetActorOutbox(w, r, db) } else if method == "POST" { ParseOutboxRequest(w, r, db) } else { - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) } return @@ -198,17 +198,17 @@ func main() { if actorMain || actorMainPage { if acceptActivity(accept) { GetActorInfo(w, db, actor.Id) - return + return } - postNum := strings.Replace(r.URL.EscapedPath(), "/" + actor.Name + "/", "", 1) + postNum := r.URL.Query().Get("page") - page, _ := strconv.Atoi(postNum) + page, _ := strconv.Atoi(postNum) collection, valid := WantToServePage(db, actor.Name, page) if valid { OutboxGet(w, r, db, collection) - } + } return } @@ -221,14 +221,14 @@ func main() { if actorFollowers { GetActorFollowers(w, db, actor.Id) return - } + } if actorInbox { if method == "POST" { ParseInboxRequest(w, r, db) } else { w.WriteHeader(http.StatusForbidden) - w.Write([]byte("404 no path")) + w.Write([]byte("404 no path")) } return } @@ -243,12 +243,12 @@ func main() { if actorOutbox { if method == "GET" { - GetActorOutbox(w, r, db) + GetActorOutbox(w, r, db) } else if method == "POST" { ParseOutboxRequest(w, r, db) } else { w.WriteHeader(http.StatusForbidden) - w.Write([]byte("404 no path")) + w.Write([]byte("404 no path")) } return } @@ -272,31 +272,31 @@ func main() { auth := CreateTripCode(verify.Code) auth = CreateTripCode(auth) - + if CreateTripCode(auth) == code { w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusUnauthorized) } - - w.Write([]byte("")) + + w.Write([]byte("")) } //catch all if actorPost { - if acceptActivity(accept) { + if acceptActivity(accept) { GetActorPost(w, db, path) - return + return } PostGet(w, r, db) - return - } + return + } - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) }) - + http.HandleFunc("/news/", func(w http.ResponseWriter, r *http.Request){ timestamp := r.URL.Path[6:] @@ -308,10 +308,10 @@ func main() { if timestamp[len(timestamp)-1:] == "/" { timestamp = timestamp[:len(timestamp)-1] } - + ts, err := strconv.Atoi(timestamp) if err != nil { - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) } else { NewsGet(w, r, db, ts) @@ -328,7 +328,7 @@ func main() { fmt.Println("\n\nBlacklist post blocked\n\n") http.Redirect(w, r, Domain + "/", http.StatusMovedPermanently) return - } + } if(file != nil && header.Size > (7 << 20)){ w.Write([]byte("7MB max file size")) @@ -337,9 +337,9 @@ func main() { if(r.FormValue("inReplyTo") == "" && file == nil) { w.Write([]byte("Media is required for new posts")) - return + return } - + if(r.FormValue("inReplyTo") == "" || file == nil) { if(r.FormValue("comment") == "" && r.FormValue("subject") == ""){ @@ -356,25 +356,25 @@ func main() { if(len(r.FormValue("subject")) > 100 || len(r.FormValue("name")) > 100 || len(r.FormValue("options")) > 100) { w.Write([]byte("Name, Subject or Options limit 100 characters")) return - } + } if(r.FormValue("captcha") == "") { w.Write([]byte("Incorrect Captcha")) return - } - + } + b := bytes.Buffer{} we := multipart.NewWriter(&b) if(file != nil){ var fw io.Writer - + fw, err := we.CreateFormFile("file", header.Filename) CheckError(err, "error with form file create") _, err = io.Copy(fw, file) - + CheckError(err, "error with form file copy") } @@ -389,21 +389,21 @@ func main() { err := we.WriteField(key, name) CheckError(err, "error with writing name field") err = we.WriteField("tripcode", tripcode) - CheckError(err, "error with writing tripcode field") + CheckError(err, "error with writing tripcode field") }else{ err := we.WriteField(key, r0[0]) CheckError(err, "error with writing field") } } - + if(r.FormValue("inReplyTo") == "" && reply != ""){ err := we.WriteField("inReplyTo", reply) - CheckError(err, "error with writing inReplyTo field") + CheckError(err, "error with writing inReplyTo field") } - + we.Close() - sendTo := r.FormValue("sendTo") + sendTo := r.FormValue("sendTo") req, err := http.NewRequest("POST", sendTo, &b) CheckError(err, "error with post form req") @@ -417,16 +417,16 @@ func main() { defer resp.Body.Close() if(resp.StatusCode == 200){ - + body, _ := ioutil.ReadAll(resp.Body) - + var obj ObjectBase obj = ParseOptions(r, obj) for _, e := range obj.Option { if(e == "noko" || e == "nokosage"){ http.Redirect(w, r, Domain + "/" + r.FormValue("boardName") + "/" + shortURL(r.FormValue("sendTo"), string(body)) , http.StatusMovedPermanently) - return + return } } @@ -442,7 +442,7 @@ func main() { w.Write([]byte("Incorrect Captcha")) return } - + http.Redirect(w, r, Domain + "/" + r.FormValue("boardName"), http.StatusMovedPermanently) }) @@ -486,22 +486,22 @@ func main() { if following.MatchString(follow) { followingActor := FingerActor(follow) col := GetActorCollection(followingActor.Following) - + var nObj ObjectBase nObj.Id = followingActor.Id col.Items = append(col.Items, nObj) - + for _, e := range col.Items { if !IsAlreadyFollowing(db, actorId, e.Id) && e.Id != Domain && e.Id != actorId { followActivity := MakeFollowActivity(db, actorId, e.Id) if FingerActor(e.Id).Id != "" { MakeActivityRequestOutbox(db, followActivity) - } + } } } - + //follow all of boards followers } else if followers.MatchString(follow){ followersActor := FingerActor(follow) @@ -510,17 +510,17 @@ func main() { var nObj ObjectBase nObj.Id = followersActor.Id - col.Items = append(col.Items, nObj) - + col.Items = append(col.Items, nObj) + for _, e := range col.Items { if !IsAlreadyFollowing(db, actorId, e.Id) && e.Id != Domain && e.Id != actorId { followActivity := MakeFollowActivity(db, actorId, e.Id) if FingerActor(e.Id).Id != "" { MakeActivityRequestOutbox(db, followActivity) - } + } } } - + //do a normal follow to a single board } else { followActivity := MakeFollowActivity(db, actorId, follow) @@ -531,16 +531,16 @@ func main() { } if FingerActor(follow).Id != ""{ - MakeActivityRequestOutbox(db, followActivity) + MakeActivityRequestOutbox(db, followActivity) } } - + var redirect string if(actor.Name != "main") { redirect = "/" + actor.Name - } - - http.Redirect(w, r, "/" + *Key + "/" + redirect, http.StatusSeeOther) + } + + http.Redirect(w, r, "/" + *Key + "/" + redirect, http.StatusSeeOther) } else if manage && actor.Name != "" { t := template.Must(template.New("").Funcs(template.FuncMap{ "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/manage.html")) @@ -577,7 +577,7 @@ func main() { r.ID = e.ID r.Reason = e.Reason reports = append(reports, r) - } + } var adminData AdminPage adminData.Following = following @@ -599,11 +599,11 @@ func main() { t.ExecuteTemplate(w, "layout", adminData) - + } else if admin || actor.Id == Domain { t := template.Must(template.New("").Funcs(template.FuncMap{ - "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/nadmin.html")) - + "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/nadmin.html")) + actor := GetActor(Domain) follow := GetActorCollection(actor.Following).Items follower := GetActorCollection(actor.Followers).Items @@ -628,12 +628,12 @@ func main() { adminData.Board.ModCred,_ = GetPasswordFromSession(r) adminData.Boards = Boards - + adminData.Board.Post.Actor = actor.Id - adminData.PostBlacklist = GetRegexBlacklistDB(db) + adminData.PostBlacklist = GetRegexBlacklistDB(db) - t.ExecuteTemplate(w, "layout", adminData) + t.ExecuteTemplate(w, "layout", adminData) } }) @@ -642,9 +642,9 @@ func main() { actor := GetActorFromDB(db, Domain) if !HasValidation(w, r, actor) { - return + return } - + var newActorActivity Activity var board Actor r.ParseForm() @@ -655,7 +655,7 @@ func main() { } else { restrict = false } - + board.Name = r.FormValue("name") board.PreferredUsername = r.FormValue("prefname") board.Summary = r.FormValue("summary") @@ -671,12 +671,12 @@ func main() { newActorActivity.Object.Alias = board.Name newActorActivity.Object.Name = board.PreferredUsername newActorActivity.Object.Summary = board.Summary - newActorActivity.Object.Sensitive = board.Restricted + newActorActivity.Object.Sensitive = board.Restricted MakeActivityRequestOutbox(db, newActorActivity) - http.Redirect(w, r, "/" + *Key, http.StatusSeeOther) + http.Redirect(w, r, "/" + *Key, http.StatusSeeOther) }) - + http.HandleFunc("/" + *Key + "/postnews", func(w http.ResponseWriter, r *http.Request) { actor := GetActorFromDB(db, Domain) @@ -684,17 +684,17 @@ func main() { if !HasValidation(w, r, actor) { return } - + var newsitem NewsItem - + newsitem.Title = r.FormValue("title") newsitem.Content = template.HTML(r.FormValue("summary")) - + WriteNewsToDB(db, newsitem) - - http.Redirect(w, r, "/", http.StatusSeeOther) + + http.Redirect(w, r, "/", http.StatusSeeOther) }) - + http.HandleFunc("/" + *Key + "/newsdelete/", func(w http.ResponseWriter, r *http.Request){ actor := GetActorFromDB(db, Domain) @@ -702,13 +702,13 @@ func main() { if !HasValidation(w, r, actor) { return } - + timestamp := r.URL.Path[13+len(*Key):] - + tsint, err := strconv.Atoi(timestamp) - + if(err != nil){ - w.WriteHeader(http.StatusForbidden) + w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) return } else { @@ -728,12 +728,12 @@ func main() { verify.Code = code j, _ := json.Marshal(&verify) - + req, err := http.NewRequest("POST", Domain + "/auth", bytes.NewBuffer(j)) CheckError(err, "error making verify req") - req.Header.Set("Content-Type", activitystreams) + req.Header.Set("Content-Type", activitystreams) resp, err := http.DefaultClient.Do(req) @@ -747,15 +747,15 @@ func main() { if(resp.StatusCode != 200) { t := template.Must(template.ParseFiles("./static/verify.html")) - t.Execute(w, "wrong password " + verify.Code) + t.Execute(w, "wrong password " + verify.Code) } else { - + sessionToken, _ := uuid.NewV4() _, err := cache.Do("SETEX", sessionToken, "86400", body + "|" + verify.Code) if err != nil { t := template.Must(template.ParseFiles("./static/verify.html")) - t.Execute(w, "") + t.Execute(w, "") return } @@ -765,18 +765,18 @@ func main() { Expires: time.Now().UTC().Add(60 * 60 * 48 * time.Second), }) - http.Redirect(w, r, "/", http.StatusSeeOther) + http.Redirect(w, r, "/", http.StatusSeeOther) } } else { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("404 no path")) + w.Write([]byte("404 no path")) } }) http.HandleFunc("/banmedia", func(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") board := r.URL.Query().Get("board") - + _, auth := GetPasswordFromSession(r) if id == "" || auth == "" { @@ -788,7 +788,7 @@ func main() { col := GetCollectionFromID(id) if len(col.OrderedItems) > 0 { - + actor := col.OrderedItems[0].Actor if !HasAuth(db, auth, actor) { @@ -796,7 +796,7 @@ func main() { w.Write([]byte("")) return } - + if len(col.OrderedItems[0].Attachment) > 0 { re := regexp.MustCompile(Domain) file := re.ReplaceAllString(col.OrderedItems[0].Attachment[0].Href, "") @@ -812,7 +812,7 @@ func main() { if err != nil { fmt.Println("error readin bytes for setting media ban") } - + if !IsMediaBanned(db, f) { query := `insert into bannedmedia (hash) values ($1)` @@ -825,8 +825,8 @@ func main() { var obj ObjectBase obj.Id = id obj.Actor = actor - - isOP := CheckIfObjectOP(db, obj.Id) + + isOP := CheckIfObjectOP(db, obj.Id) var OP string if len(col.OrderedItems[0].InReplyTo) > 0 { @@ -859,13 +859,13 @@ func main() { } } w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) - }) + w.Write([]byte("")) + }) http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request){ id := r.URL.Query().Get("id") board := r.URL.Query().Get("board") - + _, auth := GetPasswordFromSession(r) if id == "" || auth == "" { @@ -883,7 +883,7 @@ func main() { w.Write([]byte("")) return } - + if !CheckIfObjectOP(db, id) { TombstoneObject(db, id) } else { @@ -898,7 +898,7 @@ func main() { return } } - + actor := col.OrderedItems[0].Actor if !HasAuth(db, auth, actor) { @@ -910,8 +910,8 @@ func main() { var obj ObjectBase obj.Id = id obj.Actor = actor - - isOP := CheckIfObjectOP(db, obj.Id) + + isOP := CheckIfObjectOP(db, obj.Id) var OP string if len(col.OrderedItems[0].InReplyTo) > 0 { @@ -943,15 +943,15 @@ func main() { http.Redirect(w, r, "/" + board, http.StatusSeeOther) return } - + w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) + w.Write([]byte("")) }) http.HandleFunc("/deleteattach", func(w http.ResponseWriter, r *http.Request){ - + id := r.URL.Query().Get("id") - board := r.URL.Query().Get("board") + board := r.URL.Query().Get("board") _, auth := GetPasswordFromSession(r) @@ -960,8 +960,8 @@ func main() { w.Write([]byte("")) return } - - manage := r.URL.Query().Get("manage") + + manage := r.URL.Query().Get("manage") col := GetCollectionFromID(id) if len(col.OrderedItems) < 1 { @@ -970,12 +970,12 @@ func main() { w.Write([]byte("")) return } - + DeleteAttachmentFromFile(db, id) TombstoneAttachmentFromDB(db, id) - + DeletePreviewFromFile(db, id) - TombstonePreviewFromDB(db, id) + TombstonePreviewFromDB(db, id) if(manage == "t"){ http.Redirect(w, r, "/" + *Key + "/" + board , http.StatusSeeOther) @@ -985,7 +985,7 @@ func main() { return } } - + actor := col.OrderedItems[0].Actor var OP string @@ -994,7 +994,7 @@ func main() { } else { OP = id } - + if !HasAuth(db, auth, actor) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("")) @@ -1003,10 +1003,10 @@ func main() { DeleteAttachmentFromFile(db, id) TombstoneAttachmentFromDB(db, id) - + DeletePreviewFromFile(db, id) TombstonePreviewFromDB(db, id) - + if (manage == "t") { http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) return @@ -1019,13 +1019,13 @@ func main() { } w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) + w.Write([]byte("")) }) http.HandleFunc("/marksensitive", func(w http.ResponseWriter, r *http.Request){ - + id := r.URL.Query().Get("id") - board := r.URL.Query().Get("board") + board := r.URL.Query().Get("board") _, auth := GetPasswordFromSession(r) @@ -1034,7 +1034,7 @@ func main() { w.Write([]byte("")) return } - + col := GetCollectionFromID(id) if len(col.OrderedItems) < 1 { @@ -1045,11 +1045,11 @@ func main() { } MarkObjectSensitive(db, id, true) - + http.Redirect(w, r, "/" + board, http.StatusSeeOther) return } - + actor := col.OrderedItems[0].Actor var OP string @@ -1058,7 +1058,7 @@ func main() { } else { OP = id } - + if !HasAuth(db, auth, actor) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("")) @@ -1076,14 +1076,14 @@ func main() { } w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) - }) + w.Write([]byte("")) + }) http.HandleFunc("/remove", func(w http.ResponseWriter, r *http.Request){ id := r.URL.Query().Get("id") manage := r.URL.Query().Get("manage") board := r.URL.Query().Get("board") - col := GetCollectionFromID(id) + col := GetCollectionFromID(id) actor := col.OrderedItems[0].Actor _, auth := GetPasswordFromSession(r) @@ -1102,8 +1102,8 @@ func main() { var obj ObjectBase obj.Id = id obj.Actor = actor - - isOP := CheckIfObjectOP(db, obj.Id) + + isOP := CheckIfObjectOP(db, obj.Id) var OP string if len(col.OrderedItems[0].InReplyTo) > 0 { @@ -1131,17 +1131,17 @@ func main() { http.Redirect(w, r, "/" + board, http.StatusSeeOther) return } - + w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) + w.Write([]byte("")) }) http.HandleFunc("/removeattach", func(w http.ResponseWriter, r *http.Request){ - + id := r.URL.Query().Get("id") - manage := r.URL.Query().Get("manage") - board := r.URL.Query().Get("board") - col := GetCollectionFromID(id) + manage := r.URL.Query().Get("manage") + board := r.URL.Query().Get("board") + col := GetCollectionFromID(id) actor := col.OrderedItems[0].Actor var OP string @@ -1150,7 +1150,7 @@ func main() { } else { OP = id } - + _, auth := GetPasswordFromSession(r) if id == "" || auth == "" { @@ -1167,7 +1167,7 @@ func main() { SetAttachmentFromDB(db, id, "Removed") SetPreviewFromDB(db, id, "Removed") - + if (manage == "t") { http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) return @@ -1180,8 +1180,8 @@ func main() { } w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) - }) + w.Write([]byte("")) + }) http.HandleFunc("/report", func(w http.ResponseWriter, r *http.Request){ @@ -1204,10 +1204,10 @@ func main() { if(close != "1" && !CheckCaptcha(db, captcha)) { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("captcha required")) - return + w.Write([]byte("captcha required")) + return } - + if close == "1" { if !HasAuth(db, auth, actor.Id) { w.WriteHeader(http.StatusBadRequest) @@ -1216,14 +1216,14 @@ func main() { } if !IsIDLocal(db, id) { - CloseLocalReportDB(db, id, board) + CloseLocalReportDB(db, id, board) http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) - return + return } reported := DeleteReportActivity(db, id) if reported { - http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) return } @@ -1235,17 +1235,17 @@ func main() { if !IsIDLocal(db, id) { CreateLocalReportDB(db, id, board, reason) http.Redirect(w, r, "/" + board + "/" + remoteShort(id), http.StatusSeeOther) - return + return } - + reported := ReportActivity(db, id, reason) if reported { - http.Redirect(w, r, id, http.StatusSeeOther) + http.Redirect(w, r, id, http.StatusSeeOther) return } w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) + w.Write([]byte("")) }) http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request){ @@ -1266,7 +1266,7 @@ func main() { } w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("")) + w.Write([]byte("")) }) http.HandleFunc("/.well-known/webfinger", func(w http.ResponseWriter, r *http.Request) { @@ -1274,7 +1274,7 @@ func main() { if(len(acct) < 1) { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("resource needs a value")) + w.Write([]byte("resource needs a value")) return } @@ -1284,7 +1284,7 @@ func main() { if(len(actorDomain) < 2) { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("accpets only subject form of acct:board@instance")) + w.Write([]byte("accpets only subject form of acct:board@instance")) return } @@ -1296,13 +1296,13 @@ func main() { if !IsActorLocal(db, TP + "" + actorDomain[1] + "" + actorDomain[0]) { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("actor not local")) + w.Write([]byte("actor not local")) return } var finger Webfinger var link WebfingerLink - + finger.Subject = "acct:" + actorDomain[0] + "@" + actorDomain[1] link.Rel = "self" link.Type = "application/activity+json" @@ -1314,7 +1314,7 @@ func main() { w.Header().Set("Content-Type", activitystreams) w.Write(enc) - + }) http.HandleFunc("/addtoindex", func(w http.ResponseWriter, r *http.Request) { @@ -1348,10 +1348,10 @@ func main() { testCase := r.FormValue("testCase") if regex == "" { - http.Redirect(w, r, "/", http.StatusSeeOther) + http.Redirect(w, r, "/", http.StatusSeeOther) return } - + r.ParseForm() re := regexp.MustCompile(regex) @@ -1362,9 +1362,9 @@ func main() { WriteRegexBlacklistDB(db, regex) } } - - http.Redirect(w, r, "/" + *Key + "#regex", http.StatusSeeOther) - }) + + http.Redirect(w, r, "/" + *Key + "#regex", http.StatusSeeOther) + }) http.HandleFunc("/api/media", func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("hash") != "" { @@ -1380,30 +1380,30 @@ func main() { board := r.URL.Query().Get("board") actor := GetActorByNameFromDB(db, board) - + SetActorAutoSubscribeDB(db, actor.Id) autoSub := GetActorAutoSubscribeDB(db, actor.Id) if autoSub { AutoFollow(db, actor.Id) } - - http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) - }) + + http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) + }) fmt.Println("Server for " + Domain + " running on port " + Port) fmt.Println("Mod key: " + *Key) PrintAdminAuth(db) - - http.ListenAndServe(Port, nil) + + http.ListenAndServe(Port, nil) } func CheckError(e error, m string) error{ if e != nil { - fmt.Println() + fmt.Println() fmt.Println(m) - fmt.Println() + fmt.Println() panic(e) } @@ -1417,7 +1417,7 @@ func ConnectDB() *sql.DB { user := GetConfigValue("dbuser") password := GetConfigValue("dbpass") dbname := GetConfigValue("dbname") - + psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s " + "dbname=%s sslmode=disable", host, port, user, password, dbname) @@ -1436,20 +1436,20 @@ func CreateKey(len int) string { var key string str := (CreateTripCode(RandomID(len))) for i := 0; i < len; i++ { - key += fmt.Sprintf("%c", str[i]) + key += fmt.Sprintf("%c", str[i]) } return key } func neuter(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if strings.HasSuffix(r.URL.Path, "/") { - http.NotFound(w, r) - return - } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/") { + http.NotFound(w, r) + return + } - next.ServeHTTP(w, r) - }) + next.ServeHTTP(w, r) + }) } func CreateTripCode(input string) string { @@ -1485,10 +1485,10 @@ func GetActorFromPath(db *sql.DB, location string, prefix string) Actor { var nActor Actor - nActor = GetActorByNameFromDB(db, actor) + nActor = GetActorByNameFromDB(db, actor) if nActor.Id == "" { - nActor = GetActorByName(db, actor) + nActor = GetActorByName(db, actor) } return nActor @@ -1497,7 +1497,7 @@ func GetActorFromPath(db *sql.DB, location string, prefix string) Actor { func GetContentType(location string) string { elements := strings.Split(location, ";") if len(elements) > 0 { - return elements[0] + return elements[0] } else { return location } @@ -1511,16 +1511,16 @@ func RandomID(size int) string { for i := 0; i < rng; i++ { newID += string(domain[rand.Intn(len(domain))]) } - + return newID } func CreateUniqueID(db *sql.DB, actor string) string { - var newID string + var newID string isUnique := false for !isUnique { newID = RandomID(8) - + query := fmt.Sprintf("select id from activitystream where id='%s/%s/%s'", Domain, actor, newID) rows, err := db.Query(query) @@ -1533,12 +1533,12 @@ func CreateUniqueID(db *sql.DB, actor string) string { for rows.Next(){ count += 1 } - + if count < 1 { isUnique = true } } - + return newID } @@ -1578,7 +1578,7 @@ func GetActorInfo(w http.ResponseWriter, db *sql.DB, id string) { func GetActorPost(w http.ResponseWriter, db *sql.DB, path string) { collection := GetCollectionFromPath(db, Domain + "" + path) if len(collection.OrderedItems) > 0 { - enc, _ := json.MarshalIndent(collection, "", "\t") + enc, _ := json.MarshalIndent(collection, "", "\t") w.Header().Set("Content-Type", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"") w.Write(enc) } @@ -1597,7 +1597,7 @@ func CreateObject(objType string) ObjectBase { func AddFollowersToActivity(db *sql.DB, activity Activity) Activity{ activity.To = append(activity.To, activity.Actor.Id) - + for _, e := range activity.To { aFollowers := GetActorCollection(e + "/followers") for _, k := range aFollowers.Items { @@ -1606,11 +1606,11 @@ func AddFollowersToActivity(db *sql.DB, activity Activity) Activity{ } var nActivity Activity - + for _, e := range activity.To { var alreadyTo = false for _, k := range nActivity.To { - if e == k || e == activity.Actor.Id { + if e == k || e == activity.Actor.Id { alreadyTo = true } } @@ -1618,17 +1618,17 @@ func AddFollowersToActivity(db *sql.DB, activity Activity) Activity{ if !alreadyTo { nActivity.To = append(nActivity.To, e) } - } + } + + activity.To = nActivity.To - activity.To = nActivity.To - return activity } func CreateActivity(activityType string, obj ObjectBase) Activity { var newActivity Activity actor := FingerActor(obj.Actor) - + newActivity.AtContext.Context = "https://www.w3.org/ns/activitystreams" newActivity.Type = activityType newActivity.Published = obj.Published @@ -1642,10 +1642,10 @@ func CreateActivity(activityType string, obj ObjectBase) Activity { } for _, e := range obj.Cc { - if obj.Actor != e { + if obj.Actor != e { newActivity.Cc = append(newActivity.Cc, e) } - } + } return newActivity } @@ -1722,7 +1722,7 @@ func CreateAttachmentObject(file multipart.File, header *multipart.FileHeader) ( var nAttachment []ObjectBase var image ObjectBase - + image.Type = "Attachment" image.Name = filename image.Href = Domain + "/" + tempFile.Name() @@ -1737,18 +1737,18 @@ func CreateAttachmentObject(file multipart.File, header *multipart.FileHeader) ( func ParseCommentForReplies(db *sql.DB, comment string, op string) []ObjectBase { - re := regexp.MustCompile(`(>>(https?://[A-Za-z0-9_.:\-~]+\/[A-Za-z0-9_.\-~]+\/)(f[A-Za-z0-9_.\-~]+-)?([A-Za-z0-9_.\-~]+)?#?([A-Za-z0-9_.\-~]+)?)`) + re := regexp.MustCompile(`(>>(https?://[A-Za-z0-9_.:\-~]+\/[A-Za-z0-9_.\-~]+\/)(f[A-Za-z0-9_.\-~]+-)?([A-Za-z0-9_.\-~]+)?#?([A-Za-z0-9_.\-~]+)?)`) match := re.FindAllStringSubmatch(comment, -1) var links []string for i:= 0; i < len(match); i++ { str := strings.Replace(match[i][0], ">>", "", 1) - str = strings.Replace(str, "www.", "", 1) + str = strings.Replace(str, "www.", "", 1) str = strings.Replace(str, "http://", "", 1) - str = strings.Replace(str, "https://", "", 1) + str = strings.Replace(str, "https://", "", 1) str = TP + "" + str - _ , isReply := IsReplyToOP(db, op, str) + _ , isReply := IsReplyToOP(db, op, str) if !IsInStringArray(links, str) && isReply { links = append(links, str) } @@ -1776,7 +1776,7 @@ func CheckValidActivity(id string) (Collection, bool) { } req, err := http.NewRequest("GET", id, nil) - + if err != nil { fmt.Println("error with request") panic(err) @@ -1788,7 +1788,7 @@ func CheckValidActivity(id string) (Collection, bool) { if err != nil { fmt.Println("error with response") - panic(err) + panic(err) } defer resp.Body.Close() @@ -1866,7 +1866,7 @@ func GetActorCollection(collection string) Collection { resp, err := RouteProxy(req) if err != nil { - fmt.Println("error with getting actor collection resp " + collection) + fmt.Println("error with getting actor collection resp " + collection) return nCollection } @@ -1875,13 +1875,13 @@ func GetActorCollection(collection string) Collection { if resp.StatusCode == 200 { body, _ := ioutil.ReadAll(resp.Body) - if len(body) > 0 { + if len(body) > 0 { err = json.Unmarshal(body, &nCollection) - + CheckError(err, "error getting actor collection from body " + collection) } } - + return nCollection } @@ -1893,7 +1893,7 @@ func IsValidActor(id string) (Actor, bool) { return actor, true; } - return actor, false; + return actor, false; } func IsActivityLocal(db *sql.DB, activity Activity) bool { @@ -1918,7 +1918,7 @@ func IsActivityLocal(db *sql.DB, activity Activity) bool { func IsIDLocal(db *sql.DB, id string) bool { activity := GetActivityFromDB(db, id) - return len(activity.OrderedItems) > 0 + return len(activity.OrderedItems) > 0 } func IsActorLocal(db *sql.DB, id string) bool { @@ -1957,22 +1957,22 @@ func IsObjectCached(db *sql.DB, id string) bool { var nID string defer rows.Close() rows.Next() - rows.Scan(&nID) + rows.Scan(&nID) if nID == "" { return false } - return true + return true } func GetObjectFromActivity(activity Activity) ObjectBase { - return *activity.Object + return *activity.Object } func MakeCaptchas(db *sql.DB, total int) { difference := total - GetCaptchaTotal(db) - + for i := 0; i < difference; i++ { CreateNewCaptcha(db) } @@ -2011,9 +2011,9 @@ func SupportedMIMEType(mime string) bool { return true } } - + return false -} +} func DeleteReportActivity(db *sql.DB, id string) bool { @@ -2025,7 +2025,7 @@ func DeleteReportActivity(db *sql.DB, id string) bool { CheckError(err, "error closing reported activity") return false } - + return true } @@ -2038,7 +2038,7 @@ func ReportActivity(db *sql.DB, id string, reason string) bool { actor := GetActivityFromDB(db, id) query := `select count from reported where id=$1` - + rows, err := db.Query(query, id) CheckError(err, "could not select count from reported") @@ -2058,13 +2058,13 @@ func ReportActivity(db *sql.DB, id string, reason string) bool { CheckError(err, "error inserting new reported activity") return false } - + } else { count = count + 1 query = `update reported set count=$1 where id=$2` _, err := db.Exec(query, count, id) - + if err != nil { CheckError(err, "error updating reported activity") return false @@ -2090,7 +2090,7 @@ func GetActorReported(w http.ResponseWriter, r *http.Request, db *sql.DB, id str w.Write([]byte("")) return } - + var following Collection following.AtContext.Context = "https://www.w3.org/ns/activitystreams" @@ -2098,7 +2098,7 @@ func GetActorReported(w http.ResponseWriter, r *http.Request, db *sql.DB, id str following.TotalItems = GetActorReportedTotal(db, id) following.Items = GetActorReportedDB(db, id) - enc, _ := json.MarshalIndent(following, "", "\t") + enc, _ := json.MarshalIndent(following, "", "\t") w.Header().Set("Content-Type", activitystreams) w.Write(enc) } @@ -2112,10 +2112,10 @@ func MakeActivityRequestOutbox(db *sql.DB, activity Activity) { req, err := http.NewRequest("POST", activity.Actor.Outbox, bytes.NewBuffer(j)) - CheckError(err, "error with sending activity req to outbox") + CheckError(err, "error with sending activity req to outbox") re := regexp.MustCompile("https?://(www.)?") - + var instance string if activity.Actor.Id == Domain { instance = re.ReplaceAllString(Domain, "") @@ -2132,16 +2132,16 @@ func MakeActivityRequestOutbox(db *sql.DB, activity Activity) { sig := fmt.Sprintf("(request-target): %s %s\nhost: %s\ndate: %s", "post", path, instance, date) encSig, err := ActivitySign(db, *activity.Actor, sig) CheckError(err, "unable to sign activity response") - signature := fmt.Sprintf("keyId=\"%s\",headers=\"(request-target) host date\",signature=\"%s\"", activity.Actor.PublicKey.Id, encSig) - - req.Header.Set("Content-Type", activitystreams) + signature := fmt.Sprintf("keyId=\"%s\",headers=\"(request-target) host date\",signature=\"%s\"", activity.Actor.PublicKey.Id, encSig) + + req.Header.Set("Content-Type", activitystreams) req.Header.Set("Date", date) req.Header.Set("Signature", signature) req.Host = instance _, err = RouteProxy(req) - CheckError(err, "error with sending activity resp to") + CheckError(err, "error with sending activity resp to") } func MakeActivityRequest(db *sql.DB, activity Activity) { @@ -2150,7 +2150,7 @@ func MakeActivityRequest(db *sql.DB, activity Activity) { for _, e := range activity.To { if e != activity.Actor.Id { - + actor := FingerActor(e) if actor.Id != "" { @@ -2164,7 +2164,7 @@ func MakeActivityRequest(db *sql.DB, activity Activity) { date := time.Now().UTC().Format(time.RFC1123) path := strings.Replace(actor.Inbox, instance, "", 1) - + re := regexp.MustCompile("https?://(www.)?") path = re.ReplaceAllString(path, "") @@ -2173,7 +2173,7 @@ func MakeActivityRequest(db *sql.DB, activity Activity) { CheckError(err, "unable to sign activity response") signature := fmt.Sprintf("keyId=\"%s\",headers=\"(request-target) host date\",signature=\"%s\"", activity.Actor.PublicKey.Id, encSig) - req.Header.Set("Content-Type", activitystreams) + req.Header.Set("Content-Type", activitystreams) req.Header.Set("Date", date) req.Header.Set("Signature", signature) req.Host = instance @@ -2183,21 +2183,21 @@ func MakeActivityRequest(db *sql.DB, activity Activity) { if err != nil { fmt.Println("error with sending activity resp to actor " + instance) } - } + } } } - } + } } func GetCollectionFromID(id string) Collection { var nColl Collection - + req, err := http.NewRequest("GET", id, nil) CheckError(err, "could not get collection from id req") - req.Header.Set("Accept", activitystreams) - + req.Header.Set("Accept", activitystreams) + resp, err := RouteProxy(req) if err != nil { @@ -2247,11 +2247,11 @@ func PrintAdminAuth(db *sql.DB){ var code string var identifier string - + rows.Next() rows.Scan(&identifier, &code) - fmt.Println("Admin Login: " + identifier + ", Code: " + code) + fmt.Println("Admin Login: " + identifier + ", Code: " + code) } func IsInStringArray(array []string, value string) bool { @@ -2266,10 +2266,10 @@ func IsInStringArray(array []string, value string) bool { func GetUniqueFilename(_type string) string { id := RandomID(8) file := "/public/" + id + "." + _type - + for true { if _, err := os.Stat("." + file); err == nil { - id = RandomID(8) + id = RandomID(8) file = "/public/" + id + "." + _type }else{ return "/public/" + id + "." + _type @@ -2307,18 +2307,18 @@ func DeleteObjectRequest(db *sql.DB, id string) { func DeleteObjectAndRepliesRequest(db *sql.DB, id string) { var nObj ObjectBase - var nActor Actor + var nActor Actor nObj.Id = id nObj.Actor = nActor.Id - + activity := CreateActivity("Delete", nObj) - + obj := GetObjectByIDFromDB(db, id) activity.Actor.Id = obj.OrderedItems[0].Actor activity.Object = &obj.OrderedItems[0] - + followers := GetActorFollowDB(db, obj.OrderedItems[0].Actor) for _, e := range followers { activity.To = append(activity.To, e.Id) @@ -2327,7 +2327,7 @@ func DeleteObjectAndRepliesRequest(db *sql.DB, id string) { following := GetActorFollowingDB(db, obj.OrderedItems[0].Actor) for _, e := range following { activity.To = append(activity.To, e.Id) - } + } MakeActivityRequest(db, activity) } @@ -2343,13 +2343,13 @@ func ResizeAttachmentToPreview(db *sql.DB) { defer rows.Close() for rows.Next() { - var id string + var id string var href string var mediatype string var name string var size int var published string - + rows.Scan(&id, &href, &mediatype, &name, &size, &published) re := regexp.MustCompile(`^\w+`) @@ -2368,20 +2368,20 @@ func ResizeAttachmentToPreview(db *sql.DB) { re = regexp.MustCompile(`/\w+$`) actor := re.ReplaceAllString(id, "") - + nPreview.Type = "Preview" - nPreview.Id = fmt.Sprintf("%s/%s", actor, CreateUniqueID(db, actor)) + nPreview.Id = fmt.Sprintf("%s/%s", actor, CreateUniqueID(db, actor)) nPreview.Name = name nPreview.Href = Domain + "" + nHref nPreview.MediaType = mediatype nPreview.Size = int64(size) nPreview.Published = published - nPreview.Updated = published + nPreview.Updated = published re = regexp.MustCompile(`/public/.+`) objFile := re.FindString(href) - + if(id != "") { cmd := exec.Command("convert", "." + objFile ,"-resize", "250x250>", "-strip", "." + nHref) @@ -2390,10 +2390,10 @@ func ResizeAttachmentToPreview(db *sql.DB) { CheckError(err, "error with resize attachment preview") if err == nil { - fmt.Println(objFile + " -> " + nHref) + fmt.Println(objFile + " -> " + nHref) WritePreviewToDB(db, nPreview) UpdateObjectWithPreview(db, id, nPreview.Id) - } + } } } } @@ -2409,7 +2409,7 @@ func UpdateObjectWithPreview(db *sql.DB, id string, preview string) { } func ParseCommentForReply(comment string) string { - + re := regexp.MustCompile(`(>>(https?://[A-Za-z0-9_.:\-~]+\/[A-Za-z0-9_.\-~]+\/)(f[A-Za-z0-9_.\-~]+-)?([A-Za-z0-9_.\-~]+)?#?([A-Za-z0-9_.\-~]+)?)`) match := re.FindAllStringSubmatch(comment, -1) @@ -2427,7 +2427,7 @@ func ParseCommentForReply(comment string) string { return links[0] } } - + return "" } @@ -2453,7 +2453,7 @@ func GetActorCollectionReq(r *http.Request, collection string) Collection { req.Header.Set("Accept", activitystreams) - req.Header.Set("Authorization", "Basic " + pass) + req.Header.Set("Authorization", "Basic " + pass) resp, err := RouteProxy(req) @@ -2469,7 +2469,7 @@ func GetActorCollectionReq(r *http.Request, collection string) Collection { CheckError(err, "error getting actor collection from body " + collection) } - + return nCollection } @@ -2496,8 +2496,8 @@ func shortURL(actorName string, url string) string { if(temp == actor){ id := localShort(op) - re := regexp.MustCompile(`.+\/`) - replyCheck := re.FindString(reply) + re := regexp.MustCompile(`.+\/`) + replyCheck := re.FindString(reply) if(reply != "" && replyCheck == actor){ id = id + "#" + localShort(reply) @@ -2505,20 +2505,20 @@ func shortURL(actorName string, url string) string { id = id + "#" + remoteShort(reply) } - return id; + return id; }else{ id := remoteShort(op) - re := regexp.MustCompile(`.+\/`) - replyCheck := re.FindString(reply) + re := regexp.MustCompile(`.+\/`) + replyCheck := re.FindString(reply) if(reply != "" && replyCheck == actor){ id = id + "#" + localShort(reply) } else if reply != "" { id = id + "#" + remoteShort(reply) - } + } - return id; + return id; } } @@ -2578,18 +2578,18 @@ func RunDatabaseSchema(db *sql.DB) { query, err := ioutil.ReadFile("databaseschema.psql") CheckError(err, "could not read databaseschema.psql file") if _, err := db.Exec(string(query)); err != nil { - CheckError(err, "could not exec databaseschema.psql") + CheckError(err, "could not exec databaseschema.psql") } } func CreatedNeededDirectories() { if _, err := os.Stat("./public"); os.IsNotExist(err) { - os.Mkdir("./public", 0755) + os.Mkdir("./public", 0755) } if _, err := os.Stat("./pem/board"); os.IsNotExist(err) { - os.MkdirAll("./pem/board", 0700) - } + os.MkdirAll("./pem/board", 0700) + } } //looks for actor with pattern of board@instance @@ -2606,10 +2606,10 @@ func FingerActor(path string) Actor{ if ActorCache[actor + "@" + instance].Id != "" { nActor = ActorCache[actor + "@" + instance] } else { - r := FingerRequest(actor, instance) + r := FingerRequest(actor, instance) if r != nil && r.StatusCode == 200 { defer r.Body.Close() - + body, _ := ioutil.ReadAll(r.Body) err := json.Unmarshal(body, &nActor) @@ -2617,7 +2617,7 @@ func FingerActor(path string) Actor{ CheckError(err, "error getting fingerrequet resp from json body") ActorCache[actor + "@" + instance] = nActor - } + } } return nActor @@ -2639,7 +2639,7 @@ func FingerRequest(actor string, instance string) (*http.Response){ if resp.StatusCode == 200 { defer resp.Body.Close() - + body, _ := ioutil.ReadAll(resp.Body) err := json.Unmarshal(body, &finger) @@ -2651,11 +2651,11 @@ func FingerRequest(actor string, instance string) (*http.Response){ for _, e := range finger.Links { if(e.Type == "application/activity+json"){ req, err := http.NewRequest("GET", e.Href, nil) - + CheckError(err, "could not get finger request from id req") - req.Header.Set("Accept", activitystreams) - + req.Header.Set("Accept", activitystreams) + resp, err := RouteProxy(req) return resp } @@ -2683,7 +2683,7 @@ func GetActorInstance(path string) (string, string) { if(len(match) > 2) { return "main", match[3] } - } + } re = regexp.MustCompile(`(https?://)?(www)?([\w\d-_.:]+)\/([\w\d-_.]+)(\/([\w\d-_.]+))?`) httpFormat := re.MatchString(path) @@ -2694,7 +2694,7 @@ func GetActorInstance(path string) (string, string) { if match[4] == "users" { return match[6], match[3] } - + return match[4], match[3] } } @@ -2708,7 +2708,7 @@ func AddInstanceToIndex(actor string) { if re.MatchString(actor) { return } - + followers := GetCollectionFromID("https://fchan.xyz/followers") var alreadyIndex = false @@ -2725,14 +2725,14 @@ func AddInstanceToIndex(actor string) { _, err = http.DefaultClient.Do(req) - CheckError(err, "error with add instance to actor index resp") + CheckError(err, "error with add instance to actor index resp") } } func AddInstanceToIndexDB(db *sql.DB, actor string) { time.Sleep(15 * time.Second) - + followers := GetCollectionFromID("https://fchan.xyz/followers") var alreadyIndex = false @@ -2745,7 +2745,7 @@ func AddInstanceToIndexDB(db *sql.DB, actor string) { checkActor := GetActor(actor) if checkActor.Id == actor { - if !alreadyIndex { + if !alreadyIndex { query := `insert into follower (id, follower) values ($1, $2)` _, err := db.Exec(query, "https://fchan.xyz", actor) @@ -2776,7 +2776,7 @@ func GetCollectionFromReq(path string) Collection { if err != nil { panic(err) - } + } return respCollection } @@ -2809,7 +2809,7 @@ func RouteImages(w http.ResponseWriter, media string) { fileBytes, err := ioutil.ReadFile("./static/notfound.png") CheckError(err, "could not get /static/notfound.png file bytes") - + w.Write(fileBytes) return } @@ -2818,12 +2818,12 @@ func RouteImages(w http.ResponseWriter, media string) { body, _ := ioutil.ReadAll(resp.Body) for name, values := range resp.Header { - for _, value := range values { - w.Header().Set(name, value) + for _, value := range values { + w.Header().Set(name, value) } } - - w.Write(body) + + w.Write(body) } func IsPostBlacklist(db *sql.DB, comment string) bool { @@ -2842,9 +2842,9 @@ func IsPostBlacklist(db *sql.DB, comment string) bool { func HasValidation(w http.ResponseWriter, r *http.Request, actor Actor) bool { id, _ := GetPasswordFromSession(r) - + if id == "" || (id != actor.Id && id != Domain) { - http.Redirect(w, r, "/", http.StatusSeeOther) + http.Redirect(w, r, "/", http.StatusSeeOther) return false } @@ -2865,20 +2865,20 @@ func IsReplyToOP(db *sql.DB, op string, link string) (string, bool) { link = re.ReplaceAllString(link, "") link = "%" + match[1] + "/" + link } - + query := `select id from replies where id like $1 and inreplyto=$2` rows, err := db.Query(query, link, op) CheckError(err, "error selecting in reply to op from db") - var id string + var id string defer rows.Close() rows.Next() rows.Scan(&id) if id != "" { - + return id, true } diff --git a/static/nposts.html b/static/nposts.html index d106f74..2b05b66 100644 --- a/static/nposts.html +++ b/static/nposts.html @@ -18,7 +18,7 @@ {{ $board := .Board }} <hr> <ul style="margin: 0; padding: 0; display: inline"> - <li style="display: inline"><a href="/{{ $board.Name }}/catalog">[Catalog]</a></li> + <li style="display: inline"><a href="/{{ $board.Name }}/catalog">[Catalog]</a></li> <li style="display: inline"><a href="#bottom">[Bottom]</a></li> <li style="display: inline"><a href="javascript:location.reload()">[Refresh]</a></li> </ul> @@ -35,19 +35,19 @@ {{ if gt .TotalPage 0 }} {{ $totalPage := .TotalPage }} <ul style="float: right; margin: 0; padding: 0; display: inline"> - {{ $page := .CurrentPage }} + {{ $page := .CurrentPage }} {{ if gt $page 0 }} - <li style="display: inline"><button onclick="previous('{{$board.Name }}', '{{ $page }}')">Previous</button></li> + <li style="display: inline"><a href="/{{ $board.Name }}?page={{ sub $page 1 }}">[ < ]</a></li> {{ end }} {{ range $i, $e := .Pages }} {{ if eq $i $page}} - <li style="display: inline"><a href="/{{ $board.Name }}/{{ $i }}"><b>[{{ $i }}]</b></a></li> + <li style="display: inline"><a href="/{{ $board.Name }}?page={{ $i }}"><b>[{{ $i }}]</b></a></li> {{ else }} - <li style="display: inline"><a href="/{{ $board.Name }}/{{ $i }}">[{{ $i }}]</a></li> + <li style="display: inline"><a href="/{{ $board.Name }}?page={{ $i }}">[{{ $i }}]</a></li> {{ end }} {{ end }} {{ if lt .CurrentPage .TotalPage }} - <li style="display: inline"><button onclick="next('{{ $board.Name }}','{{ $totalPage }}' ,'{{ $page }}')">next</button></li> + <li style="display: inline"><a href="/{{ $board.Name }}?page={{ add $page 1 }}">[ > ]</a></li> {{ end }} </ul> {{ end }} @@ -55,8 +55,4 @@ {{ define "script" }} <script src="/static/js/footerscript.js"></script> -<script> - viewLink("{{ .Board.Name }}", "{{ .Board.Actor.Id }}") - -</script> {{ end }} |