diff options
-rw-r--r-- | accept.go | 2 | ||||
-rw-r--r-- | activityPubStruct.go | 234 | ||||
-rw-r--r-- | cacheDatabase.go | 116 | ||||
-rw-r--r-- | client.go | 243 | ||||
-rw-r--r-- | database.go | 164 | ||||
-rw-r--r-- | follow.go | 11 | ||||
-rw-r--r-- | main.go | 458 | ||||
-rw-r--r-- | outboxGet.go | 4 | ||||
-rw-r--r-- | outboxPost.go | 29 | ||||
-rw-r--r-- | session.go | 19 | ||||
-rw-r--r-- | tripcode.go | 51 | ||||
-rw-r--r-- | verification.go | 249 | ||||
-rw-r--r-- | webfinger.go | 8 |
13 files changed, 785 insertions, 803 deletions
@@ -11,7 +11,7 @@ func acceptActivity(header string) bool { if strings.Contains(header, ";") { split := strings.Split(header, ";") accept = accept || activityRegexp.MatchString(split[0]) - accept = accept || strings.Contains(split[len(split)-1], "profile=\"https://www.w3.org/ns/activitystreams\"") + accept = accept || strings.Contains(split[len(split)-1], "profile=\"https://www.w3.org/ns/activitystreams\"") } else { accept = accept || activityRegexp.MatchString(header) } diff --git a/activityPubStruct.go b/activityPubStruct.go index 62fabe1..459259a 100644 --- a/activityPubStruct.go +++ b/activityPubStruct.go @@ -11,17 +11,17 @@ type AtContextRaw struct { type ActivityRaw struct { AtContextRaw - Type string `json:"type,omitempty"` - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Summary string `json:"summary,omitempty"` - Auth string `json:"auth,omitempty"` - ToRaw json.RawMessage `json:"to,omitempty"` - BtoRaw json.RawMessage `json:"bto,omitempty"` - CcRaw json.RawMessage `json:"cc,omitempty"` - Published string `json:"published,omitempty"` - ActorRaw json.RawMessage `json:"actor,omitempty"` - ObjectRaw json.RawMessage `json:"object,omitempty"` + Type string `json:"type,omitempty"` + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Summary string `json:"summary,omitempty"` + Auth string `json:"auth,omitempty"` + ToRaw json.RawMessage `json:"to,omitempty"` + BtoRaw json.RawMessage `json:"bto,omitempty"` + CcRaw json.RawMessage `json:"cc,omitempty"` + Published string `json:"published,omitempty"` + ActorRaw json.RawMessage `json:"actor,omitempty"` + ObjectRaw json.RawMessage `json:"object,omitempty"` } type AtContext struct { @@ -29,7 +29,7 @@ type AtContext struct { } type AtContextArray struct { - Context []interface {} `json:"@context,omitempty"` + Context []interface{} `json:"@context,omitempty"` } type AtContextString struct { @@ -69,133 +69,133 @@ type CcOjectString struct { } type Actor struct { - Type string `json:"type,omitempty"` - Id string `json:"id,omitempty"` - Inbox string `json:"inbox,omitempty"` - Outbox string `json:"outbox,omitempty"` - Following string `json:"following,omitempty"` - Followers string `json:"followers,omitempty"` - Name string `json:"name,omitempty"` - PreferredUsername string `json:"preferredUsername,omitempty"` - PublicKey PublicKeyPem `json:"publicKey,omitempty"` - Summary string `json:"summary,omitempty"` - AuthRequirement []string `json:"authrequirement,omitempty"` - Restricted bool `json:"restricted"` + Type string `json:"type,omitempty"` + Id string `json:"id,omitempty"` + Inbox string `json:"inbox,omitempty"` + Outbox string `json:"outbox,omitempty"` + Following string `json:"following,omitempty"` + Followers string `json:"followers,omitempty"` + Name string `json:"name,omitempty"` + PreferredUsername string `json:"preferredUsername,omitempty"` + PublicKey PublicKeyPem `json:"publicKey,omitempty"` + Summary string `json:"summary,omitempty"` + AuthRequirement []string `json:"authrequirement,omitempty"` + Restricted bool `json:"restricted"` } type PublicKeyPem struct { - Id string `json:"id,omitempty"` - Owner string `json:"owner,omitempty"` - PublicKeyPem string `json:"publicKeyPem,omitempty"` + Id string `json:"id,omitempty"` + Owner string `json:"owner,omitempty"` + PublicKeyPem string `json:"publicKeyPem,omitempty"` } type Activity struct { AtContext - Type string `json:"type,omitempty"` - Id string `json:"id,omitempty"` - Actor *Actor `json:"actor,omitempty"` - Name string `json:"name,omitempty"` - Summary string `json:"summary,omitempty"` - Auth string `json:"auth,omitempty"` - To []string `json:"to, omitempty"` - Bto []string `json:"bto,omitempty"` - Cc []string `json:"cc, omitempty"` - Published string `json:"published,omitempty"` - Object *ObjectBase `json:"object, omitempty"` + Type string `json:"type,omitempty"` + Id string `json:"id,omitempty"` + Actor *Actor `json:"actor,omitempty"` + Name string `json:"name,omitempty"` + Summary string `json:"summary,omitempty"` + Auth string `json:"auth,omitempty"` + To []string `json:"to, omitempty"` + Bto []string `json:"bto,omitempty"` + Cc []string `json:"cc, omitempty"` + Published string `json:"published,omitempty"` + Object *ObjectBase `json:"object, omitempty"` } type ObjectBase struct { - Type string `json:"type,omitempty"` - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Option []string `json:"option,omitempty"` - Alias string `json:"alias,omitempty"` - AttributedTo string `json:"attributedTo,omitempty"` - TripCode string `json:"tripcode,omitempty"` - Actor string `json:"actor,omitempty"` - Audience string `json:"audience,omitempty"` - ContentHTML template.HTML `json:"contenthtml,omitempty"` - Content string `json:"content,omitempty"` - EndTime string `json:"endTime,omitempty"` - Generator string `json:"generator,omitempty"` - Icon string `json:"icon,omitempty"` - Image string `json:"image,omitempty"` - InReplyTo []ObjectBase `json:"inReplyTo,omitempty"` - Location string `json:"location,omitempty"` - Preview *NestedObjectBase `json:"preview,omitempty"` - Published string `json:"published,omitempty"` - Updated string `json:"updated,omitempty"` - Object *NestedObjectBase `json:"object,omitempty"` - Attachment []ObjectBase `json:"attachment,omitempty"` - Replies *CollectionBase `json:"replies,omitempty"` - StartTime string `json:"startTime,omitempty"` - Summary string `json:"summary,omitempty"` - Tag []ObjectBase `json:"tag,omitempty"` - Wallet []CryptoCur `json:"wallet,omitempty"` - Deleted string `json:"deleted,omitempty"` - Url []ObjectBase `json:"url,omitempty"` - Href string `json:"href,omitempty"` - To []string `json:"to,omitempty"` - Bto []string `json:"bto,omitempty"` - Cc []string `json:"cc,omitempty"` - Bcc string `json:"Bcc,omitempty"` - MediaType string `json:"mediatype,omitempty"` - Duration string `json:"duration,omitempty"` - Size int64 `json:"size,omitempty"` - Sensitive bool `json:"sensitive,omitempty"` + Type string `json:"type,omitempty"` + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Option []string `json:"option,omitempty"` + Alias string `json:"alias,omitempty"` + AttributedTo string `json:"attributedTo,omitempty"` + TripCode string `json:"tripcode,omitempty"` + Actor string `json:"actor,omitempty"` + Audience string `json:"audience,omitempty"` + ContentHTML template.HTML `json:"contenthtml,omitempty"` + Content string `json:"content,omitempty"` + EndTime string `json:"endTime,omitempty"` + Generator string `json:"generator,omitempty"` + Icon string `json:"icon,omitempty"` + Image string `json:"image,omitempty"` + InReplyTo []ObjectBase `json:"inReplyTo,omitempty"` + Location string `json:"location,omitempty"` + Preview *NestedObjectBase `json:"preview,omitempty"` + Published string `json:"published,omitempty"` + Updated string `json:"updated,omitempty"` + Object *NestedObjectBase `json:"object,omitempty"` + Attachment []ObjectBase `json:"attachment,omitempty"` + Replies *CollectionBase `json:"replies,omitempty"` + StartTime string `json:"startTime,omitempty"` + Summary string `json:"summary,omitempty"` + Tag []ObjectBase `json:"tag,omitempty"` + Wallet []CryptoCur `json:"wallet,omitempty"` + Deleted string `json:"deleted,omitempty"` + Url []ObjectBase `json:"url,omitempty"` + Href string `json:"href,omitempty"` + To []string `json:"to,omitempty"` + Bto []string `json:"bto,omitempty"` + Cc []string `json:"cc,omitempty"` + Bcc string `json:"Bcc,omitempty"` + MediaType string `json:"mediatype,omitempty"` + Duration string `json:"duration,omitempty"` + Size int64 `json:"size,omitempty"` + Sensitive bool `json:"sensitive,omitempty"` } type CryptoCur struct { - Type string `json:"type,omitempty"` + Type string `json:"type,omitempty"` Address string `json:"address,omitempty"` } type NestedObjectBase struct { AtContext - Type string `json:"type,omitempty"` - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Alias string `json:"alias,omitempty"` - AttributedTo string `json:"attributedTo,omitempty"` - TripCode string `json:"tripcode,omitempty"` - Actor string `json:"actor,omitempty"` - Audience string `json:"audience,omitempty"` - ContentHTML template.HTML `json:"contenthtml,omitempty"` - Content string `json:"content,omitempty"` - EndTime string `json:"endTime,omitempty"` - Generator string `json:"generator,omitempty"` - Icon string `json:"icon,omitempty"` - Image string `json:"image,omitempty"` - InReplyTo []ObjectBase `json:"inReplyTo,omitempty"` - Location string `json:"location,omitempty"` - Preview ObjectBase `json:"preview,omitempty"` - Published string `json:"published,omitempty"` - Attachment []ObjectBase `json:"attachment,omitempty"` - Replies *CollectionBase `json:"replies,omitempty"` - StartTime string `json:"startTime,omitempty"` - Summary string `json:"summary,omitempty"` - Tag []ObjectBase `json:"tag,omitempty"` - Updated string `json:"updated,omitempty"` - Deleted string `json:"deleted,omitempty"` - Url []ObjectBase `json:"url,omitempty"` - Href string `json:"href,omitempty"` - To []string `json:"to,omitempty"` - Bto []string `json:"bto,omitempty"` - Cc []string `json:"cc,omitempty"` - Bcc string `json:"Bcc,omitempty"` - MediaType string `json:"mediatype,omitempty"` - Duration string `json:"duration,omitempty"` - Size int64 `json:"size,omitempty"` + Type string `json:"type,omitempty"` + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Alias string `json:"alias,omitempty"` + AttributedTo string `json:"attributedTo,omitempty"` + TripCode string `json:"tripcode,omitempty"` + Actor string `json:"actor,omitempty"` + Audience string `json:"audience,omitempty"` + ContentHTML template.HTML `json:"contenthtml,omitempty"` + Content string `json:"content,omitempty"` + EndTime string `json:"endTime,omitempty"` + Generator string `json:"generator,omitempty"` + Icon string `json:"icon,omitempty"` + Image string `json:"image,omitempty"` + InReplyTo []ObjectBase `json:"inReplyTo,omitempty"` + Location string `json:"location,omitempty"` + Preview ObjectBase `json:"preview,omitempty"` + Published string `json:"published,omitempty"` + Attachment []ObjectBase `json:"attachment,omitempty"` + Replies *CollectionBase `json:"replies,omitempty"` + StartTime string `json:"startTime,omitempty"` + Summary string `json:"summary,omitempty"` + Tag []ObjectBase `json:"tag,omitempty"` + Updated string `json:"updated,omitempty"` + Deleted string `json:"deleted,omitempty"` + Url []ObjectBase `json:"url,omitempty"` + Href string `json:"href,omitempty"` + To []string `json:"to,omitempty"` + Bto []string `json:"bto,omitempty"` + Cc []string `json:"cc,omitempty"` + Bcc string `json:"Bcc,omitempty"` + MediaType string `json:"mediatype,omitempty"` + Duration string `json:"duration,omitempty"` + Size int64 `json:"size,omitempty"` } type CollectionBase struct { - Actor *Actor `json:"actor,omitempty"` - Summary string `json:"summary,omitempty"` - Type string `json:"type,omitempty"` - TotalItems int `json:"totalItems,omitempty"` - TotalImgs int `json:"totalImgs,omitempty"` + Actor *Actor `json:"actor,omitempty"` + Summary string `json:"summary,omitempty"` + Type string `json:"type,omitempty"` + TotalItems int `json:"totalItems,omitempty"` + TotalImgs int `json:"totalImgs,omitempty"` OrderedItems []ObjectBase `json:"orderedItems,omitempty"` - Items []ObjectBase `json:"items,omitempty"` + Items []ObjectBase `json:"items,omitempty"` } type Collection struct { diff --git a/cacheDatabase.go b/cacheDatabase.go index 2fe0a38..ffe5dad 100644 --- a/cacheDatabase.go +++ b/cacheDatabase.go @@ -6,16 +6,16 @@ import _ "github.com/lib/pq" func WriteObjectToCache(db *sql.DB, obj ObjectBase) ObjectBase { - if(IsPostBlacklist(db, obj.Content)){ + if IsPostBlacklist(db, obj.Content) { fmt.Println("\n\nBlacklist post blocked\n\n") return obj } - + if len(obj.Attachment) > 0 { if obj.Preview.Href != "" { WritePreviewToCache(db, *obj.Preview) } - + for i, _ := range obj.Attachment { WriteAttachmentToCache(db, obj.Attachment[i]) WriteActivitytoCacheWithAttachment(db, obj, obj.Attachment[i], *obj.Preview) @@ -38,19 +38,19 @@ func WriteObjectToCache(db *sql.DB, obj ObjectBase) ObjectBase { func WriteActorObjectToCache(db *sql.DB, obj ObjectBase) ObjectBase { - if(IsPostBlacklist(db, obj.Content)){ + if IsPostBlacklist(db, obj.Content) { return obj } - + if len(obj.Attachment) > 0 { - + if IsIDLocal(db, obj.Id) { return obj } if obj.Preview.Href != "" { WritePreviewToCache(db, *obj.Preview) } - + for i, _ := range obj.Attachment { WriteAttachmentToCache(db, obj.Attachment[i]) WriteActivitytoCacheWithAttachment(db, obj, obj.Attachment[i], *obj.Preview) @@ -83,7 +83,7 @@ func WriteActivitytoCache(db *sql.DB, obj ObjectBase) { CheckError(err, "error selecting obj id from cache") - var id string + var id string defer rows.Close() rows.Next() rows.Scan(&id) @@ -98,16 +98,16 @@ func WriteActivitytoCache(db *sql.DB, obj ObjectBase) { query = `insert into cacheactivitystream (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) - - if e != nil{ + _, 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 cache") - panic(e) - } + panic(e) + } } func WriteActivitytoCacheWithAttachment(db *sql.DB, obj ObjectBase, attachment ObjectBase, preview NestedObjectBase) { - + obj.Name = EscapeString(obj.Name) obj.Content = EscapeString(obj.Content) obj.AttributedTo = EscapeString(obj.AttributedTo) @@ -118,7 +118,7 @@ func WriteActivitytoCacheWithAttachment(db *sql.DB, obj ObjectBase, attachment O CheckError(err, "error selecting activity with attachment obj id cache") - var id string + var id string defer rows.Close() rows.Next() rows.Scan(&id) @@ -129,16 +129,16 @@ func WriteActivitytoCacheWithAttachment(db *sql.DB, obj ObjectBase, attachment O if obj.Updated == "" { obj.Updated = obj.Published - } + } query = `insert into cacheactivitystream (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) - - if e != nil{ + _, 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 cache") - panic(e) - } + panic(e) + } } func WriteAttachmentToCache(db *sql.DB, obj ObjectBase) { @@ -149,7 +149,7 @@ func WriteAttachmentToCache(db *sql.DB, obj ObjectBase) { CheckError(err, "error selecting attachment obj id cache") - var id string + var id string defer rows.Close() rows.Next() rows.Scan(&id) @@ -160,15 +160,15 @@ func WriteAttachmentToCache(db *sql.DB, obj ObjectBase) { if obj.Updated == "" { obj.Updated = obj.Published - } - + } + query = `insert into cacheactivitystream (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{ + + _, 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 cache") - panic(e) + panic(e) } } @@ -180,7 +180,7 @@ func WritePreviewToCache(db *sql.DB, obj NestedObjectBase) { CheckError(err, "error selecting preview obj id cache") - var id string + var id string defer rows.Close() rows.Next() rows.Scan(&id) @@ -191,22 +191,22 @@ func WritePreviewToCache(db *sql.DB, obj NestedObjectBase) { if obj.Updated == "" { obj.Updated = obj.Published - } - + } + query = `insert into cacheactivitystream (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{ + + _, 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 preview cache") - panic(e) + panic(e) } } func WriteObjectReplyToCache(db *sql.DB, obj ObjectBase) { - + for i, e := range obj.InReplyTo { - if(i == 0 || IsReplyInThread(db, obj.InReplyTo[0].Id, e.Id)){ + if i == 0 || IsReplyInThread(db, obj.InReplyTo[0].Id, e.Id) { query := `select id from replies where id=$1` @@ -214,7 +214,7 @@ func WriteObjectReplyToCache(db *sql.DB, obj ObjectBase) { CheckError(err, "error selecting obj id cache reply") - var id string + var id string defer rows.Close() rows.Next() rows.Scan(&id) @@ -222,14 +222,14 @@ func WriteObjectReplyToCache(db *sql.DB, obj ObjectBase) { if id != "" { return } - + query = `insert into cachereplies (id, inreplyto) values ($1, $2)` - _, err = db.Exec(query, obj.Id, e.Id) - - if err != nil{ + _, err = db.Exec(query, obj.Id, e.Id) + + if err != nil { fmt.Println("error inserting replies cache") - panic(err) + panic(err) } } } @@ -237,13 +237,13 @@ func WriteObjectReplyToCache(db *sql.DB, obj ObjectBase) { if len(obj.InReplyTo) < 1 { query := `insert into cachereplies (id, inreplyto) values ($1, $2)` - _, err := db.Exec(query, obj.Id, "") - - if err != nil{ + _, err := db.Exec(query, obj.Id, "") + + if err != nil { fmt.Println("error inserting replies cache") - panic(err) + panic(err) } - } + } } func WriteObjectReplyCache(db *sql.DB, obj ObjectBase) { @@ -257,7 +257,7 @@ func WriteObjectReplyCache(db *sql.DB, obj ObjectBase) { CheckError(err, "error selecting obj id cache reply") - var inreplyto string + var inreplyto string defer rows.Close() rows.Next() rows.Scan(&inreplyto) @@ -265,14 +265,14 @@ func WriteObjectReplyCache(db *sql.DB, obj ObjectBase) { if inreplyto != "" { return } - + query = `insert into cachereplies (id, inreplyto) values ($1, $2)` - _, err = db.Exec(query, e.Id, obj.Id) - - if err != nil{ + _, err = db.Exec(query, e.Id, obj.Id) + + if err != nil { fmt.Println("error inserting replies cache") - panic(err) + panic(err) } if !IsObjectLocal(db, e.Id) { @@ -280,7 +280,7 @@ func WriteObjectReplyCache(db *sql.DB, obj ObjectBase) { } } - return + return } } @@ -293,7 +293,7 @@ func WriteActorToCache(db *sql.DB, actorID string) { } } -func DeleteActorCache(db *sql.DB, actorID string) { +func DeleteActorCache(db *sql.DB, actorID string) { query := `select id from cacheactivitystream where id in (select id from cacheactivitystream where actor=$1)` rows, err := db.Query(query, actorID) @@ -1,16 +1,16 @@ package main import ( - "net/http" - "html/template" "database/sql" + "fmt" _ "github.com/lib/pq" - "strings" - "strconv" - "sort" + "html/template" + "net/http" "regexp" + "sort" + "strconv" + "strings" "time" - "fmt" ) var Key *string = new(string) @@ -19,85 +19,84 @@ var FollowingBoards []ObjectBase var Boards []Board -type Board struct{ - Name string - Actor Actor - Summary string - PrefName string - InReplyTo string - Location string - To string - RedirectTo string - Captcha string +type Board struct { + Name string + Actor Actor + Summary string + PrefName string + InReplyTo string + Location string + To string + RedirectTo string + Captcha string CaptchaCode string - ModCred string - Domain string - TP string - Restricted bool - Post ObjectBase + ModCred string + Domain string + TP string + Restricted bool + Post ObjectBase } type PageData struct { - Title string + Title string PreferredUsername string - Board Board - Pages []int - CurrentPage int - TotalPage int - Boards []Board - Posts []ObjectBase - Key string - PostId string - Instance Actor - InstanceIndex []ObjectBase - ReturnTo string - NewsItems []NewsItem - BoardRemainer []int + Board Board + Pages []int + CurrentPage int + TotalPage int + Boards []Board + Posts []ObjectBase + Key string + PostId string + Instance Actor + InstanceIndex []ObjectBase + ReturnTo string + NewsItems []NewsItem + BoardRemainer []int } type AdminPage struct { - Title string - Board Board - Key string - Actor string - Boards []Board - Following []string - Followers []string - Reported []Report - Domain string - IsLocal bool + Title string + Board Board + Key string + Actor string + Boards []Board + Following []string + Followers []string + Reported []Report + Domain string + IsLocal bool PostBlacklist []PostBlacklist AutoSubscribe bool } type Report struct { - ID string - Count int + ID string + Count int Reason string } type Removed struct { - ID string - Type string + ID string + Type string Board string } - type NewsItem struct { - Title string + Title string Content template.HTML - Time int + Time int } type PostBlacklist struct { - Id int + Id int Regex string } func IndexGet(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 }, + "mod": func(i, j int) bool { return i%j == 0 }, + "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/index.html")) actor := GetActorFromDB(db, Domain) @@ -115,20 +114,20 @@ func IndexGet(w http.ResponseWriter, r *http.Request, db *sql.DB) { data.Board.Restricted = actor.Restricted //almost certainly there is a better algorithm for this but the old one was wrong //and I suck at math. This works at least. - data.BoardRemainer = make([]int, 3-(len(data.Boards) % 3)) - if(len(data.BoardRemainer) == 3){ + data.BoardRemainer = make([]int, 3-(len(data.Boards)%3)) + if len(data.BoardRemainer) == 3 { data.BoardRemainer = make([]int, 0) } data.InstanceIndex = GetCollectionFromReq("https://fchan.xyz/followers").Items data.NewsItems = getNewsFromDB(db, 3) - t.ExecuteTemplate(w, "layout", data) + t.ExecuteTemplate(w, "layout", data) } 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) @@ -156,13 +155,13 @@ func NewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB, timestamp int) data.Title = actor.PreferredUsername + ": " + data.NewsItems[0].Title - t.ExecuteTemplate(w, "layout", data) + t.ExecuteTemplate(w, "layout", data) } 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 }, + "mod": func(i, j int) bool { return i%j == 0 }, + "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) @@ -180,10 +179,10 @@ func AllNewsGet(w http.ResponseWriter, r *http.Request, db *sql.DB) { data.Board.Restricted = actor.Restricted data.NewsItems = getNewsFromDB(db, 0) - t.ExecuteTemplate(w, "layout", data) + t.ExecuteTemplate(w, "layout", data) } -func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Collection){ +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) @@ -198,33 +197,32 @@ func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Co return ParseContent(db, board, op, content, thread) }, "shortImg": func(url string) string { - return ShortImg(url) + return ShortImg(url) }, "convertSize": func(size int64) string { - return ConvertSize(size) + return ConvertSize(size) }, "isOnion": func(url string) bool { - return IsOnion(url) + return IsOnion(url) }, "showArchive": func() bool { col := GetActorCollectionDBTypeLimit(db, collection.Actor.Id, "Archive", 1) if len(col.OrderedItems) > 0 { - return true + return true } - return false; + return false }, "parseReplyLink": func(actorId string, op string, id string, content string) template.HTML { actor := FingerActor(actorId) 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>" + 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 { + "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")) - + "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 @@ -273,10 +271,10 @@ func OutboxGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Co returnData.Pages = pages returnData.TotalPage = len(returnData.Pages) - 1 - t.ExecuteTemplate(w, "layout", returnData) + t.ExecuteTemplate(w, "layout", returnData) } -func CatalogGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Collection){ +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) @@ -288,17 +286,17 @@ func CatalogGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection C return ParseAttachment(obj, catalog) }, "isOnion": func(url string) bool { - return IsOnion(url) + return IsOnion(url) }, "showArchive": func() bool { col := GetActorCollectionDBTypeLimit(db, collection.Actor.Id, "Archive", 1) if len(col.OrderedItems) > 0 { - return true + return true } - return false; + return false }, - "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 @@ -328,10 +326,10 @@ func CatalogGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection C returnData.Posts = collection.OrderedItems - t.ExecuteTemplate(w, "layout", returnData) + t.ExecuteTemplate(w, "layout", returnData) } -func ArchiveGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection Collection){ +func ArchiveGet(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) @@ -345,8 +343,8 @@ func ArchiveGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection C "parseAttachment": func(obj ObjectBase, catalog bool) template.HTML { return ParseAttachment(obj, catalog) }, - "mod": func(i, j int) bool { return i % j == 0 }, - "sub": func (i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/archive.html", "./static/bottom.html")) + "mod": func(i, j int) bool { return i%j == 0 }, + "sub": func(i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/archive.html", "./static/bottom.html")) actor := collection.Actor @@ -376,10 +374,10 @@ func ArchiveGet(w http.ResponseWriter, r *http.Request, db *sql.DB, collection C returnData.Posts = collection.OrderedItems - t.ExecuteTemplate(w, "layout", returnData) + t.ExecuteTemplate(w, "layout", returnData) } -func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ +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) @@ -394,21 +392,21 @@ func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ return ParseContent(db, board, op, content, thread) }, "shortImg": func(url string) string { - return ShortImg(url) + return ShortImg(url) }, "convertSize": func(size int64) string { - return ConvertSize(size) + return ConvertSize(size) }, "isOnion": func(url string) bool { - return IsOnion(url) + return IsOnion(url) }, "parseReplyLink": func(actorId string, op string, id string, content string) template.HTML { actor := FingerActor(actorId) 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>" + 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")) + "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, "/") @@ -469,7 +467,7 @@ func PostGet(w http.ResponseWriter, r *http.Request, db *sql.DB){ returnData.PostId = shortURL(returnData.Board.To, returnData.Posts[0].Id) } - t.ExecuteTemplate(w, "layout", returnData) + t.ExecuteTemplate(w, "layout", returnData) } func GetBoardCollection(db *sql.DB) []Board { @@ -565,7 +563,7 @@ func GetCaptchaCode(captcha string) string { return code } -func CreateLocalDeleteDB(db *sql.DB, id string, _type string) { +func CreateLocalDeleteDB(db *sql.DB, id string, _type string) { query := `select id from removed where id=$1` rows, err := db.Query(query, id) @@ -681,7 +679,7 @@ func CloseLocalReportDB(db *sql.DB, id string, board string) { CheckError(err, "Could not delete local report from db") } -func GetActorFollowNameFromPath(path string) string{ +func GetActorFollowNameFromPath(path string) string { var actor string re := regexp.MustCompile("f\\w+-") @@ -709,11 +707,11 @@ func GetActorsFollowFromName(actor Actor, name string) []string { return followingActors } -func GetActorsFollowPostFromId(db *sql.DB, actors []string, id string) Collection{ +func GetActorsFollowPostFromId(db *sql.DB, actors []string, id string) Collection { var collection Collection for _, e := range actors { - tempCol := GetObjectByIDFromDB(db, e + "/" + id) + tempCol := GetObjectByIDFromDB(db, e+"/"+id) if len(tempCol.OrderedItems) > 0 { collection = tempCol return collection @@ -724,19 +722,22 @@ func GetActorsFollowPostFromId(db *sql.DB, actors []string, id string) Collectio } type ObjectBaseSortDesc []ObjectBase -func (a ObjectBaseSortDesc) Len() int { return len(a) } + +func (a ObjectBaseSortDesc) Len() int { return len(a) } func (a ObjectBaseSortDesc) Less(i, j int) bool { return a[i].Updated > a[j].Updated } -func (a ObjectBaseSortDesc) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a ObjectBaseSortDesc) Swap(i, j int) { a[i], a[j] = a[j], a[i] } type ObjectBaseSortAsc []ObjectBase -func (a ObjectBaseSortAsc) Len() int { return len(a) } + +func (a ObjectBaseSortAsc) Len() int { return len(a) } func (a ObjectBaseSortAsc) Less(i, j int) bool { return a[i].Published < a[j].Published } -func (a ObjectBaseSortAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a ObjectBaseSortAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] } type BoardSortAsc []Board -func (a BoardSortAsc) Len() int { return len(a) } + +func (a BoardSortAsc) Len() int { return len(a) } func (a BoardSortAsc) Less(i, j int) bool { return a[i].Name < a[j].Name } -func (a BoardSortAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a BoardSortAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func MediaProxy(url string) string { re := regexp.MustCompile("(.+)?" + Domain + "(.+)?") @@ -762,7 +763,7 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { } var media string - if(regexp.MustCompile(`image\/`).MatchString(obj.Attachment[0].MediaType)){ + if regexp.MustCompile(`image\/`).MatchString(obj.Attachment[0].MediaType) { media = "<img " media += "id=\"img\" " media += "main=\"1\" " @@ -786,7 +787,7 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { 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\" " @@ -806,7 +807,7 @@ func ParseAttachment(obj ObjectBase, catalog bool) template.HTML { 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\" " @@ -841,7 +842,7 @@ func ParseContent(db *sql.DB, board Actor, op string, content string, thread Obj nContent = strings.ReplaceAll(nContent, `/\<`, ">") return template.HTML(nContent) -}; +} func ParseLinkComments(db *sql.DB, board Actor, op string, content string, thread ObjectBase) 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_.\-~]+)?)`) @@ -895,7 +896,7 @@ func ParseLinkComments(db *sql.DB, board Actor, op string, content string, threa 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) + 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 { @@ -908,7 +909,7 @@ func ParseLinkComments(db *sql.DB, board Actor, op string, content string, threa } if actor.Id != "" { - content = strings.Replace(content, match[i][0], "<a class=\"reply\" style=\"" + style + "\" title=\"" + quoteTitle + "\" href=\"" + link + "\">>>" + shortURL(board.Outbox, parsedLink) + isOP + " →</a>", -1) + content = strings.Replace(content, match[i][0], "<a class=\"reply\" style=\""+style+"\" title=\""+quoteTitle+"\" href=\""+link+"\">>>"+shortURL(board.Outbox, parsedLink)+isOP+" →</a>", -1) } } } @@ -931,7 +932,7 @@ func ParseLinkTitle(actorName string, op string, content string) string { } link = ConvertHashLink(domain, link) - content = strings.Replace(content, match[i][0], ">>" + shortURL(actorName, link) + isOP , 1) + content = strings.Replace(content, match[i][0], ">>"+shortURL(actorName, link)+isOP, 1) } content = strings.ReplaceAll(content, "'", "") @@ -948,7 +949,7 @@ func ParseCommentQuotes(content string) string { for i, _ := range match { quote := strings.Replace(match[i][0], ">", ">", 1) - line := re.ReplaceAllString(match[i][0], "<span class=\"quote\">" + quote + "</span>") + line := re.ReplaceAllString(match[i][0], "<span class=\"quote\">"+quote+"</span>") content = strings.Replace(content, match[i][0], line, 1) } @@ -979,7 +980,7 @@ func ShortImg(url string) string { fileName := re.ReplaceAllString(url, "") - if(len(fileName) > 26) { + if len(fileName) > 26 { re := regexp.MustCompile(`(^.{26})`) match := re.FindStringSubmatch(fileName) @@ -993,35 +994,35 @@ func ShortImg(url string) string { match = re.FindStringSubmatch(url) if len(match) > 0 { - nURL = nURL + "(...)" + match[0]; + nURL = nURL + "(...)" + match[0] } } - return nURL; + return nURL } func ConvertSize(size int64) string { var rValue string - convert := float32(size) / 1024.0; + convert := float32(size) / 1024.0 - if(convert > 1024) { - convert = convert / 1024.0; + if convert > 1024 { + convert = convert / 1024.0 rValue = fmt.Sprintf("%.2f MB", convert) } else { rValue = fmt.Sprintf("%.2f KB", convert) } - return rValue; + return rValue } func ShortExcerpt(post ObjectBase) string { var returnString string if post.Name != "" { - returnString = post.Name + "| " + post.Content; + returnString = post.Name + "| " + post.Content } else { - returnString = post.Content; + returnString = post.Content } re := regexp.MustCompile(`(^(.|\r\n|\n){100})`) @@ -1037,7 +1038,7 @@ func ShortExcerpt(post ObjectBase) string { match = re.FindStringSubmatch(returnString) if len(match) > 0 { - returnString = strings.Replace(returnString, match[0], "<b>" + match[0] + "</b>", 1) + returnString = strings.Replace(returnString, match[0], "<b>"+match[0]+"</b>", 1) returnString = strings.Replace(returnString, "|", ":", 1) } @@ -1046,8 +1047,8 @@ func ShortExcerpt(post ObjectBase) string { func IsOnion(url string) bool { re := regexp.MustCompile(`\.onion`) - if(re.MatchString(url)) { - return true; + if re.MatchString(url) { + return true } return false diff --git a/database.go b/database.go index 9c68364..0a99086 100644 --- a/database.go +++ b/database.go @@ -3,20 +3,20 @@ package main import ( "database/sql" "fmt" + "html/template" "os" + "regexp" "sort" "strings" - "regexp" "time" - "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) @@ -32,7 +32,7 @@ func GetActorFromDB(db *sql.DB, id string) Actor { } nActor.PublicKey = GetActorPemFromDB(db, publicKeyPem) - if nActor.Id != "" && nActor.PublicKey.PublicKeyPem == ""{ + if nActor.Id != "" && nActor.PublicKey.PublicKeyPem == "" { err = CreatePublicKeyFromPrivate(db, &nActor, publicKeyPem) CheckError(err, "error creating public key from private") } @@ -43,7 +43,7 @@ func GetActorFromDB(db *sql.DB, id string) Actor { func GetActorByNameFromDB(db *sql.DB, name string) Actor { var nActor Actor - query :=`select type, id, name, preferedusername, inbox, outbox, following, followers, restricted, summary, publickeypem from actor where name=$1` + query := `select type, id, name, preferedusername, inbox, outbox, following, followers, restricted, summary, publickeypem from actor where name=$1` rows, err := db.Query(query, name) @@ -58,7 +58,7 @@ func GetActorByNameFromDB(db *sql.DB, name string) Actor { CheckError(err, "error with actor from db scan ") } - if nActor.Id != "" && nActor.PublicKey.PublicKeyPem == ""{ + if nActor.Id != "" && nActor.PublicKey.PublicKeyPem == "" { err = CreatePublicKeyFromPrivate(db, &nActor, publicKeyPem) CheckError(err, "error creating public key from private") } @@ -66,7 +66,7 @@ func GetActorByNameFromDB(db *sql.DB, name string) Actor { return nActor } -func CreateNewBoardDB(db *sql.DB, actor Actor) Actor{ +func CreateNewBoardDB(db *sql.DB, actor Actor) Actor { query := `insert into actor (type, id, name, preferedusername, inbox, outbox, following, followers, summary, restricted) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)` @@ -77,7 +77,7 @@ func CreateNewBoardDB(db *sql.DB, actor Actor) Actor{ } else { fmt.Println("board added") for _, e := range actor.AuthRequirement { - query = `insert into actorauth (type, board) values ($1, $2)` + query = `insert into actorauth (type, board) values ($1, $2)` _, err := db.Exec(query, e, actor.Name) CheckError(err, "auth exists") } @@ -85,20 +85,20 @@ func CreateNewBoardDB(db *sql.DB, actor Actor) Actor{ var verify Verify verify.Identifier = actor.Id - verify.Code = CreateKey(50) - verify.Type = "admin" + verify.Code = CreateKey(50) + verify.Type = "admin" CreateVerification(db, verify) verify.Identifier = actor.Id - verify.Code = CreateKey(50) - verify.Type = "janitor" + verify.Code = CreateKey(50) + verify.Type = "janitor" CreateVerification(db, verify) verify.Identifier = actor.Id - verify.Code = CreateKey(50) - verify.Type = "post" + verify.Code = CreateKey(50) + verify.Type = "post" CreateVerification(db, verify) @@ -155,12 +155,12 @@ func GetBoards(db *sql.DB) []Actor { CheckError(err, "could not get boards from db query") defer rows.Close() - for rows.Next(){ + 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{ + if err != nil { panic(err) } @@ -205,7 +205,7 @@ func WriteObjectUpdatesToDB(db *sql.DB, obj ObjectBase) { _, e := db.Exec(query, time.Now().UTC().Format(time.RFC3339), obj.Id) - if e != nil{ + if e != nil { fmt.Println("error inserting updating inreplyto") panic(e) } @@ -214,7 +214,7 @@ func WriteObjectUpdatesToDB(db *sql.DB, obj ObjectBase) { _, e = db.Exec(query, time.Now().UTC().Format(time.RFC3339), obj.Id) - if e != nil{ + if e != nil { fmt.Println("error inserting updating cache inreplyto") panic(e) } @@ -229,7 +229,7 @@ func WriteObjectReplyToLocalDB(db *sql.DB, id string, replyto string) { query = `select inreplyto from replies where id=$1` - rows, err := db.Query(query,replyto) + rows, err := db.Query(query, replyto) CheckError(err, "Could not query select inreplyto") @@ -260,7 +260,6 @@ func WriteObjectReplyToDB(db *sql.DB, obj ObjectBase) { } } - query := `select id from replies where id=$1 and inreplyto=$2` rows, err := db.Query(query, obj.Id, e.Id) @@ -336,7 +335,6 @@ func WriteActorObjectReplyToDB(db *sql.DB, obj ObjectBase) { _, err := db.Exec(query, obj.Id, e.Id) - CheckError(err, "error inserting replies db") } } @@ -370,7 +368,7 @@ func WriteWalletToDB(db *sql.DB, obj ObjectBase) { 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") } @@ -387,9 +385,9 @@ 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{ + if e != nil { fmt.Println("error inserting new activity") panic(e) } @@ -403,9 +401,9 @@ func WriteActivitytoDBWithAttachment(db *sql.DB, obj ObjectBase, attachment Obje 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{ + if e != nil { fmt.Println("error inserting new activity with attachment") panic(e) } @@ -414,9 +412,9 @@ func WriteActivitytoDBWithAttachment(db *sql.DB, obj ObjectBase, attachment Obje 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{ + if e != nil { fmt.Println("error inserting new attachment") panic(e) } @@ -425,9 +423,9 @@ func WriteAttachmentToDB(db *sql.DB, obj ObjectBase) { 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) + _, 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{ + if e != nil { fmt.Println("error inserting new attachment") panic(e) } @@ -447,11 +445,11 @@ func GetActivityFromDB(db *sql.DB, id string) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string - var previewID 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) @@ -484,13 +482,13 @@ func GetObjectFromDBPage(db *sql.DB, id string, page int) Collection { 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 * 15) + rows, err := db.Query(query, id, page*15) CheckError(err, "error query object from db") var count int defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -533,7 +531,7 @@ func GetActorObjectCollectionFromDB(db *sql.DB, actorId string) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -575,7 +573,7 @@ func GetObjectFromDB(db *sql.DB, id string) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -626,7 +624,7 @@ func GetObjectFromDBFromID(db *sql.DB, id string) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -668,7 +666,7 @@ func GetObjectFromDBCatalog(db *sql.DB, id string) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -709,7 +707,7 @@ func GetObjectByIDFromDB(db *sql.DB, postID string) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -987,7 +985,7 @@ func GetObjectAttachment(db *sql.DB, id string) []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") @@ -996,7 +994,7 @@ func GetObjectAttachment(db *sql.DB, id string) []ObjectBase { var attachment = new(ObjectBase) err = rows.Scan(&attachment.Id, &attachment.Type, &attachment.Name, &attachment.Href, &attachment.MediaType, &attachment.Size, &attachment.Published) - if err !=nil{ + if err != nil { fmt.Println("error with attachment db query") panic(err) } @@ -1025,7 +1023,7 @@ func GetObjectPreview(db *sql.DB, id string) *NestedObjectBase { return &preview } -func GetObjectPostsTotalDB(db *sql.DB, actor Actor) int{ +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')` @@ -1043,7 +1041,7 @@ func GetObjectPostsTotalDB(db *sql.DB, actor Actor) int{ return count } -func GetObjectImgsTotalDB(db *sql.DB, actor Actor) int{ +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' )` @@ -1075,10 +1073,10 @@ func DeletePreviewFromFile(db *sql.DB, id string) { var href string err := rows.Scan(&href) - href = strings.Replace(href, Domain + "/", "", 1) + href = strings.Replace(href, Domain+"/", "", 1) CheckError(err, "error scanning delete attachment") - if(href != "static/notfound.png") { + if href != "static/notfound.png" { _, err = os.Stat(href) if err == nil { os.Remove(href) @@ -1101,10 +1099,10 @@ func RemovePreviewFromFile(db *sql.DB, id string) { var href string err := rows.Scan(&href) - href = strings.Replace(href, Domain + "/", "", 1) + href = strings.Replace(href, Domain+"/", "", 1) CheckError(err, "error scanning delete attachment") - if(href != "static/notfound.png") { + if href != "static/notfound.png" { _, err = os.Stat(href) if err == nil { os.Remove(href) @@ -1128,10 +1126,10 @@ func DeleteAttachmentFromFile(db *sql.DB, id string) { var href string err := rows.Scan(&href) - href = strings.Replace(href, Domain + "/", "", 1) + href = strings.Replace(href, Domain+"/", "", 1) CheckError(err, "error scanning delete preview") - if(href != "static/notfound.png") { + if href != "static/notfound.png" { _, err = os.Stat(href) if err == nil { os.Remove(href) @@ -1186,13 +1184,13 @@ 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") } @@ -1216,13 +1214,13 @@ 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") } @@ -1241,7 +1239,7 @@ func DeletePreviewFromDB(db *sql.DB, id string) { CheckError(err, "error with delete cache preview") } -func DeleteObjectRepliedTo(db *sql.DB, id string){ +func DeleteObjectRepliedTo(db *sql.DB, id string) { query := `delete from replies where id=$1` _, err := db.Exec(query, id) @@ -1264,7 +1262,7 @@ func TombstoneObjectFromDB(db *sql.DB, id string) { } func DeleteObjectFromDB(db *sql.DB, id string) { - var query = `delete from activitystream where id=$1` + var query = `delete from activitystream where id=$1` _, err := db.Exec(query, id) @@ -1393,18 +1391,18 @@ func SetObjectRepliesFromDB(db *sql.DB, id string, _type string) { } func SetObject(db *sql.DB, id string, _type string) { - SetAttachmentFromDB(db, id, _type); - SetPreviewFromDB(db, id, _type); - SetObjectFromDB(db, id, _type); + SetAttachmentFromDB(db, id, _type) + SetPreviewFromDB(db, id, _type) + SetObjectFromDB(db, id, _type) } func SetObjectAndReplies(db *sql.DB, id string, _type string) { - SetAttachmentFromDB(db, id, _type); - SetPreviewFromDB(db, id, _type); - SetObjectRepliesFromDB(db, id, _type); - SetAttachmentRepliesFromDB(db, id, _type); - SetPreviewRepliesFromDB(db, id, _type); - SetObjectFromDB(db, id, _type); + SetAttachmentFromDB(db, id, _type) + SetPreviewFromDB(db, id, _type) + SetObjectRepliesFromDB(db, id, _type) + SetAttachmentRepliesFromDB(db, id, _type) + SetPreviewRepliesFromDB(db, id, _type) + SetObjectFromDB(db, id, _type) } func DeleteObject(db *sql.DB, id string) { @@ -1438,7 +1436,7 @@ func TombstoneObjectAndReplies(db *sql.DB, id string) { TombstoneObjectFromDB(db, id) } -func GetRandomCaptcha(db *sql.DB) string{ +func GetRandomCaptcha(db *sql.DB) string { query := `select identifier from verification where type='captcha' order by random() limit 1` rows, err := db.Query(query) @@ -1457,7 +1455,7 @@ func GetRandomCaptcha(db *sql.DB) string{ return verify } -func GetCaptchaTotal(db *sql.DB) int{ +func GetCaptchaTotal(db *sql.DB) int { query := `select count(*) from verification where type='captcha'` rows, err := db.Query(query) @@ -1467,8 +1465,8 @@ func GetCaptchaTotal(db *sql.DB) int{ defer rows.Close() var count int - for rows.Next(){ - if err := rows.Scan(&count); err != nil{ + for rows.Next() { + if err := rows.Scan(&count); err != nil { CheckError(err, "could not get captcha total") } } @@ -1587,7 +1585,7 @@ func GetActorPemFromDB(db *sql.DB, pemID string) PublicKeyPem { rows.Next() rows.Scan(&pem.Id, &pem.Owner, &pem.PublicKeyPem) f, err := os.ReadFile(pem.PublicKeyPem) - if err != nil{ + if err != nil { pem.PublicKeyPem = "" return pem } @@ -1597,7 +1595,7 @@ func GetActorPemFromDB(db *sql.DB, pemID string) PublicKeyPem { return pem } -func GetActorPemFileFromDB(db *sql.DB, pemID string) string{ +func GetActorPemFileFromDB(db *sql.DB, pemID string) string { query := `select file from publickeypem where id=$1` rows, err := db.Query(query, pemID) @@ -1629,21 +1627,20 @@ 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` + if limit > 0 { + query = `select title, content, time from newsItem order by time desc limit $1` } else { - query =`select title, content, time from newsItem order by time desc` + query = `select title, content, time from newsItem order by time desc` } var rows *sql.Rows var err error - if(limit > 0) { + if limit > 0 { rows, err = db.Query(query, limit) } else { rows, err = db.Query(query) } - if CheckError(err, "could not get news from db query") != nil { return news } @@ -1755,10 +1752,10 @@ func DeleteRegexBlacklistDB(db *sql.DB, id int) { CheckError(err, "error with delete from postblacklist") } -func GetActorAutoSubscribeDB(db *sql.DB, id string) bool{ +func GetActorAutoSubscribeDB(db *sql.DB, id string) bool { query := `select autosubscribe from actor where id=$1` - rows, err:= db.Query(query, id) + rows, err := db.Query(query, id) CheckError(err, "error with getting actor auto subscribe status from db") @@ -1767,7 +1764,6 @@ func GetActorAutoSubscribeDB(db *sql.DB, id string) bool{ rows.Next() rows.Scan(&subscribed) - return subscribed } @@ -1802,12 +1798,12 @@ func AddInstanceToInactiveDB(db *sql.DB, instance string) { } else { if IsInactiveTimestamp(db, timeStamp) { query := `delete from following where following like $1` - _, err:= db.Exec(query, "%" + instance + "%") + _, err := db.Exec(query, "%"+instance+"%") CheckError(err, "error deleting inactive instance following") query = `delete from follower where follower like $1` - _, err= db.Exec(query, "%" + instance + "%") + _, err = db.Exec(query, "%"+instance+"%") CheckError(err, "error deleting inactive instance follower") @@ -1856,7 +1852,7 @@ func GetAllActorArchiveDB(db *sql.DB, id string, offset int) Collection { CheckError(err, "error query object from db") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase err = rows.Scan(&post.Id, &post.Updated) @@ -1884,7 +1880,7 @@ func GetActorCollectionDBType(db *sql.DB, actorId string, nType string) Collecti CheckError(err, "error query object from db archive") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -1924,7 +1920,7 @@ func GetActorCollectionDBTypeLimit(db *sql.DB, actorId string, nType string, lim CheckError(err, "error query object from db archive") defer rows.Close() - for rows.Next(){ + for rows.Next() { var post ObjectBase var actor Actor var attachID string @@ -34,7 +34,6 @@ func GetActorFollowers(w http.ResponseWriter, db *sql.DB, id string) { w.Write(enc) } - func GetActorFollowingDB(db *sql.DB, id string) []ObjectBase { var followingCollection []ObjectBase query := `select following from following where id=$1` @@ -164,7 +163,7 @@ func IsAlreadyFollowing(db *sql.DB, actor string, follow string) bool { } } - return false; + return false } func IsAlreadyFollower(db *sql.DB, actor string, follow string) bool { @@ -176,7 +175,7 @@ func IsAlreadyFollower(db *sql.DB, actor string, follow string) bool { } } - return false; + return false } func SetActorFollowerDB(db *sql.DB, activity Activity) Activity { @@ -202,7 +201,7 @@ func SetActorFollowerDB(db *sql.DB, activity Activity) Activity { activity.Type = "Accept" return activity } else { - query = `insert into follower (id, follower) values ($1, $2)` + query = `insert into follower (id, follower) values ($1, $2)` activity.Summary = activity.Object.Actor + " Follow " + activity.Actor.Id _, err := db.Exec(query, activity.Actor.Id, activity.Object.Actor) @@ -216,7 +215,6 @@ func SetActorFollowerDB(db *sql.DB, activity Activity) Activity { return activity } - return activity } @@ -283,8 +281,7 @@ func SetActorFollowingDB(db *sql.DB, activity Activity) Activity { return activity } - - return activity + return activity } func AutoFollow(db *sql.DB, actor string) { @@ -1,43 +1,43 @@ package main import ( - "fmt" - "strings" - "strconv" - "net/http" - "net/url" + "bufio" + "bytes" + "crypto/sha256" "database/sql" + "encoding/hex" + "encoding/json" + "fmt" + "github.com/gofrs/uuid" _ "github.com/lib/pq" - "math/rand" "html/template" - "time" - "regexp" - "os/exec" - "bytes" - "encoding/json" + "io" "io/ioutil" + "math/rand" "mime/multipart" + "net/http" + "net/url" "os" - "bufio" - "io" - "github.com/gofrs/uuid" - "crypto/sha256" - "encoding/hex" + "os/exec" + "regexp" + "strconv" + "strings" + "time" ) var Port = ":" + GetConfigValue("instanceport") -var TP = GetConfigValue("instancetp") +var TP = GetConfigValue("instancetp") var Instance = GetConfigValue("instance") var Domain = TP + "" + Instance -var authReq = []string{"captcha","email","passphrase"} +var authReq = []string{"captcha", "email", "passphrase"} -var supportedFiles = []string{"image/gif","image/jpeg","image/png", "image/webp", "image/apng","video/mp4","video/ogg","video/webm","audio/mpeg","audio/ogg","audio/wav", "audio/wave", "audio/x-wav"} +var supportedFiles = []string{"image/gif", "image/jpeg", "image/png", "image/webp", "image/apng", "video/mp4", "video/ogg", "video/webm", "audio/mpeg", "audio/ogg", "audio/wav", "audio/wave", "audio/x-wav"} -var SiteEmail = GetConfigValue("emailaddress") //contact@fchan.xyz +var SiteEmail = GetConfigValue("emailaddress") //contact@fchan.xyz var SiteEmailPassword = GetConfigValue("emailpass") -var SiteEmailServer = GetConfigValue("emailserver") //mail.fchan.xyz -var SiteEmailPort = GetConfigValue("emailport") //587 +var SiteEmailServer = GetConfigValue("emailserver") //mail.fchan.xyz +var SiteEmailPort = GetConfigValue("emailport") //587 var TorProxy = GetConfigValue("torproxy") //127.0.0.1:9050 @@ -57,7 +57,7 @@ func main() { InitCache() - db := ConnectDB(); + db := ConnectDB() defer db.Close() @@ -92,7 +92,7 @@ func main() { http.Handle("/static/", http.StripPrefix("/static", neuter(javascriptFiles))) // main routing - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path // remove trailing slash @@ -132,15 +132,15 @@ func main() { mainFollowing = (path == "/following") mainFollowers = (path == "/followers") } else { - actorMain = (path == "/" + actor.Name) - actorInbox = (path == "/" + actor.Name + "/inbox") - actorCatalog = (path == "/" + actor.Name + "/catalog") - actorOutbox = (path == "/" + actor.Name + "/outbox") - actorFollowing = (path == "/" + actor.Name + "/following") - actorFollowers = (path == "/" + actor.Name + "/followers") - actorReported = (path == "/" + actor.Name + "/reported") - actorVerification = (path == "/" + actor.Name + "/verification") - actorArchive = (path == "/" + actor.Name + "/archive") + actorMain = (path == "/"+actor.Name) + actorInbox = (path == "/"+actor.Name+"/inbox") + actorCatalog = (path == "/"+actor.Name+"/catalog") + actorOutbox = (path == "/"+actor.Name+"/outbox") + actorFollowing = (path == "/"+actor.Name+"/following") + actorFollowers = (path == "/"+actor.Name+"/followers") + actorReported = (path == "/"+actor.Name+"/reported") + actorVerification = (path == "/"+actor.Name+"/verification") + actorArchive = (path == "/"+actor.Name+"/archive") escapedActorName := strings.Replace(actor.Name, "*", "\\*", -1) escapedActorName = strings.Replace(escapedActorName, "^", "\\^", -1) @@ -155,7 +155,7 @@ func main() { re = regexp.MustCompile("/" + escapedActorName + "/\\w+") - actorPost = re.MatchString(path) + actorPost = re.MatchString(path) } if mainActor { @@ -311,10 +311,10 @@ func main() { w.Write([]byte("404 no path")) }) - http.HandleFunc("/news/", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/news/", func(w http.ResponseWriter, r *http.Request) { timestamp := r.URL.Path[6:] - if(len(timestamp) < 2) { + if len(timestamp) < 2 { AllNewsGet(w, r, db) return } @@ -332,47 +332,46 @@ func main() { } }) - http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(10 << 20) file, header, _ := r.FormFile("file") - if(IsPostBlacklist(db, r.FormValue("comment"))){ + if IsPostBlacklist(db, r.FormValue("comment")) { fmt.Println("\n\nBlacklist post blocked\n\n") - http.Redirect(w, r, Domain + "/", http.StatusMovedPermanently) + http.Redirect(w, r, Domain+"/", http.StatusMovedPermanently) return } - if(file != nil && header.Size > (7 << 20)){ + if file != nil && header.Size > (7<<20) { w.Write([]byte("7MB max file size")) return } - if(r.FormValue("inReplyTo") == "" && file == nil) { + if r.FormValue("inReplyTo") == "" && file == nil { w.Write([]byte("Media is required for new posts")) return } - - if(r.FormValue("inReplyTo") == "" || file == nil) { - if(r.FormValue("comment") == "" && r.FormValue("subject") == ""){ + if r.FormValue("inReplyTo") == "" || file == nil { + if r.FormValue("comment") == "" && r.FormValue("subject") == "" { w.Write([]byte("Comment or Subject required")) return } } - if(len(r.FormValue("comment")) > 2000) { + if len(r.FormValue("comment")) > 2000 { w.Write([]byte("Comment limit 2000 characters")) return } - if(len(r.FormValue("subject")) > 100 || len(r.FormValue("name")) > 100 || len(r.FormValue("options")) > 100) { + 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") == "") { + if r.FormValue("captcha") == "" { w.Write([]byte("Incorrect Captcha")) return } @@ -380,7 +379,7 @@ func main() { b := bytes.Buffer{} we := multipart.NewWriter(&b) - if(file != nil){ + if file != nil { var fw io.Writer fw, err := we.CreateFormFile("file", header.Filename) @@ -395,22 +394,22 @@ func main() { reply := ParseCommentForReply(r.FormValue("comment")) for key, r0 := range r.Form { - if(key == "captcha") { - err := we.WriteField(key, r.FormValue("captchaCode") + ":" + r.FormValue("captcha")) + if key == "captcha" { + err := we.WriteField(key, r.FormValue("captchaCode")+":"+r.FormValue("captcha")) CheckError(err, "error with writing captcha field") - }else if(key == "name") { + } else if key == "name" { name, tripcode := CreateNameTripCode(r, db) err := we.WriteField(key, name) CheckError(err, "error with writing name field") err = we.WriteField("tripcode", tripcode) CheckError(err, "error with writing tripcode field") - }else{ + } else { err := we.WriteField(key, r0[0]) CheckError(err, "error with writing field") } } - if(r.FormValue("inReplyTo") == "" && reply != ""){ + if r.FormValue("inReplyTo") == "" && reply != "" { err := we.WriteField("inReplyTo", reply) CheckError(err, "error with writing inReplyTo field") } @@ -430,7 +429,7 @@ func main() { defer resp.Body.Close() - if(resp.StatusCode == 200){ + if resp.StatusCode == 200 { body, _ := ioutil.ReadAll(resp.Body) @@ -438,32 +437,32 @@ func main() { 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) + if e == "noko" || e == "nokosage" { + http.Redirect(w, r, Domain+"/"+r.FormValue("boardName")+"/"+shortURL(r.FormValue("sendTo"), string(body)), http.StatusMovedPermanently) return } } - if(r.FormValue("returnTo") == "catalog"){ - http.Redirect(w, r, Domain + "/" + r.FormValue("boardName") + "/catalog", http.StatusMovedPermanently) + if r.FormValue("returnTo") == "catalog" { + http.Redirect(w, r, Domain+"/"+r.FormValue("boardName")+"/catalog", http.StatusMovedPermanently) } else { - http.Redirect(w, r, Domain + "/" + r.FormValue("boardName"), http.StatusMovedPermanently) + http.Redirect(w, r, Domain+"/"+r.FormValue("boardName"), http.StatusMovedPermanently) } return } - if(resp.StatusCode == 403){ + if resp.StatusCode == 403 { w.Write([]byte("Incorrect Captcha")) return } - http.Redirect(w, r, Domain + "/" + r.FormValue("boardName"), http.StatusMovedPermanently) + http.Redirect(w, r, Domain+"/"+r.FormValue("boardName"), http.StatusMovedPermanently) }) - http.HandleFunc("/" + *Key + "/", func(w http.ResponseWriter, r *http.Request) { + http.HandleFunc("/"+*Key+"/", func(w http.ResponseWriter, r *http.Request) { id, _ := GetPasswordFromSession(r) - actor := GetActorFromPath(db, r.URL.Path, "/" + *Key + "/") + actor := GetActorFromPath(db, r.URL.Path, "/"+*Key+"/") if actor.Id == "" { actor = GetActorFromDB(db, Domain) @@ -481,10 +480,10 @@ func main() { re = regexp.MustCompile("/" + *Key + "/" + actor.Name) manage := re.MatchString(r.URL.Path) - re = regexp.MustCompile("/" + *Key ) + re = regexp.MustCompile("/" + *Key) admin := re.MatchString(r.URL.Path) - re = regexp.MustCompile("/" + *Key + "/follow" ) + re = regexp.MustCompile("/" + *Key + "/follow") adminFollow := re.MatchString(r.URL.Path) if follow || adminFollow { @@ -517,7 +516,7 @@ func main() { } //follow all of boards followers - } else if followers.MatchString(follow){ + } else if followers.MatchString(follow) { followersActor := FingerActor(follow) col := GetActorCollection(followersActor.Followers) @@ -544,28 +543,28 @@ func main() { return } - if FingerActor(follow).Id != ""{ + if FingerActor(follow).Id != "" { MakeActivityRequestOutbox(db, followActivity) } } var redirect string - if(actor.Name != "main") { + 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")) + "sub": func(i, j int) int { return i - j }}).ParseFiles("./static/main.html", "./static/manage.html")) follow := GetActorCollection(actor.Following) follower := GetActorCollection(actor.Followers) - reported := GetActorCollectionReq(r, actor.Id + "/reported") + reported := GetActorCollectionReq(r, actor.Id+"/reported") var following []string var followers []string - var reports []Report + var reports []Report for _, e := range follow.Items { following = append(following, e.Id) @@ -578,7 +577,7 @@ func main() { for _, e := range reported.Items { var r Report r.Count = int(e.Size) - r.ID = e.Id + r.ID = e.Id r.Reason = e.Content reports = append(reports, r) } @@ -588,7 +587,7 @@ func main() { for _, e := range localReports { var r Report r.Count = e.Count - r.ID = e.ID + r.ID = e.ID r.Reason = e.Reason reports = append(reports, r) } @@ -596,7 +595,7 @@ func main() { var adminData AdminPage adminData.Following = following adminData.Followers = followers - adminData.Reported = reports + adminData.Reported = reports adminData.Domain = Domain adminData.IsLocal = IsActorLocal(db, actor.Id) @@ -609,14 +608,13 @@ func main() { adminData.Board.Post.Actor = actor.Id - adminData.AutoSubscribe = GetActorAutoSubscribeDB(db, actor.Id); - + adminData.AutoSubscribe = GetActorAutoSubscribeDB(db, actor.Id) 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 @@ -639,7 +637,7 @@ func main() { adminData.Actor = actor.Id adminData.Key = *Key adminData.Domain = Domain - adminData.Board.ModCred,_ = GetPasswordFromSession(r) + adminData.Board.ModCred, _ = GetPasswordFromSession(r) adminData.Boards = Boards @@ -647,11 +645,11 @@ func main() { adminData.PostBlacklist = GetRegexBlacklistDB(db) - t.ExecuteTemplate(w, "layout", adminData) + t.ExecuteTemplate(w, "layout", adminData) } }) - http.HandleFunc("/" + *Key + "/addboard", func(w http.ResponseWriter, r *http.Request) { + http.HandleFunc("/"+*Key+"/addboard", func(w http.ResponseWriter, r *http.Request) { actor := GetActorFromDB(db, Domain) @@ -688,10 +686,10 @@ func main() { 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) { + http.HandleFunc("/"+*Key+"/postnews", func(w http.ResponseWriter, r *http.Request) { actor := GetActorFromDB(db, Domain) @@ -709,7 +707,7 @@ func main() { http.Redirect(w, r, "/", http.StatusSeeOther) }) - http.HandleFunc("/" + *Key + "/newsdelete/", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/"+*Key+"/newsdelete/", func(w http.ResponseWriter, r *http.Request) { actor := GetActorFromDB(db, Domain) @@ -721,7 +719,7 @@ func main() { tsint, err := strconv.Atoi(timestamp) - if(err != nil){ + if err != nil { w.WriteHeader(http.StatusForbidden) w.Write([]byte("404 no path")) return @@ -731,8 +729,8 @@ func main() { } }) - http.HandleFunc("/verify", func(w http.ResponseWriter, r *http.Request){ - if(r.Method == "POST") { + http.HandleFunc("/verify", func(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" { r.ParseForm() identifier := r.FormValue("id") code := r.FormValue("code") @@ -743,7 +741,7 @@ func main() { j, _ := json.Marshal(&verify) - req, err := http.NewRequest("POST", Domain + "/auth", bytes.NewBuffer(j)) + req, err := http.NewRequest("POST", Domain+"/auth", bytes.NewBuffer(j)) CheckError(err, "error making verify req") @@ -759,14 +757,14 @@ func main() { body := string(rBody) - if(resp.StatusCode != 200) { + 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) + _, err := cache.Do("SETEX", sessionToken, "86400", body+"|"+verify.Code) if err != nil { t := template.Must(template.ParseFiles("./static/verify.html")) t.Execute(w, "") @@ -853,22 +851,22 @@ func main() { TombstoneObjectAndReplies(db, id) } - if IsIDLocal(db, id){ + if IsIDLocal(db, id) { go DeleteObjectRequest(db, id) } UnArchiveLast(db, actor) if !isOP { - if (!IsIDLocal(db, id)){ - http.Redirect(w, r, "/" + board + "/" + remoteShort(OP), http.StatusSeeOther) + if !IsIDLocal(db, id) { + http.Redirect(w, r, "/"+board+"/"+remoteShort(OP), http.StatusSeeOther) return } else { http.Redirect(w, r, OP, http.StatusSeeOther) return } } else { - http.Redirect(w, r, "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+board, http.StatusSeeOther) return } } @@ -877,7 +875,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") board := r.URL.Query().Get("board") @@ -907,12 +905,11 @@ func main() { UnArchiveLast(db, actor.Id) - - if(manage == "t"){ - http.Redirect(w, r, "/" + *Key + "/" + board , http.StatusSeeOther) + if manage == "t" { + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } else { - http.Redirect(w, r, "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+board, http.StatusSeeOther) return } } @@ -942,25 +939,25 @@ func main() { TombstoneObjectAndReplies(db, id) } - if IsIDLocal(db, id){ + if IsIDLocal(db, id) { go DeleteObjectRequest(db, id) } UnArchiveLast(db, actor) - if(manage == "t"){ - http.Redirect(w, r, "/" + *Key + "/" + board , http.StatusSeeOther) + if manage == "t" { + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } else if !isOP { - if (!IsIDLocal(db, id)){ - http.Redirect(w, r, "/" + board + "/" + remoteShort(OP), http.StatusSeeOther) + if !IsIDLocal(db, id) { + http.Redirect(w, r, "/"+board+"/"+remoteShort(OP), http.StatusSeeOther) return } else { http.Redirect(w, r, OP, http.StatusSeeOther) return } } else { - http.Redirect(w, r, "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+board, http.StatusSeeOther) return } @@ -968,7 +965,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/deleteattach", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/deleteattach", func(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") board := r.URL.Query().Get("board") @@ -997,11 +994,11 @@ func main() { DeletePreviewFromFile(db, id) TombstonePreviewFromDB(db, id) - if(manage == "t"){ - http.Redirect(w, r, "/" + *Key + "/" + board , http.StatusSeeOther) + if manage == "t" { + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } else { - http.Redirect(w, r, "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+board, http.StatusSeeOther) return } } @@ -1009,7 +1006,7 @@ func main() { actor := col.OrderedItems[0].Actor var OP string - if (len(col.OrderedItems[0].InReplyTo) > 0 && col.OrderedItems[0].InReplyTo[0].Id != "") { + if len(col.OrderedItems[0].InReplyTo) > 0 && col.OrderedItems[0].InReplyTo[0].Id != "" { OP = col.OrderedItems[0].InReplyTo[0].Id } else { OP = id @@ -1027,11 +1024,11 @@ func main() { DeletePreviewFromFile(db, id) TombstonePreviewFromDB(db, id) - if (manage == "t") { - http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) + if manage == "t" { + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } else if !IsIDLocal(db, OP) { - http.Redirect(w, r, "/" + board + "/" + remoteShort(OP), http.StatusSeeOther) + http.Redirect(w, r, "/"+board+"/"+remoteShort(OP), http.StatusSeeOther) return } else { http.Redirect(w, r, OP, http.StatusSeeOther) @@ -1042,7 +1039,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/marksensitive", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/marksensitive", func(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") board := r.URL.Query().Get("board") @@ -1066,14 +1063,14 @@ func main() { MarkObjectSensitive(db, id, true) - http.Redirect(w, r, "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+board, http.StatusSeeOther) return } actor := col.OrderedItems[0].Actor var OP string - if (len(col.OrderedItems[0].InReplyTo) > 0 && col.OrderedItems[0].InReplyTo[0].Id != "") { + if len(col.OrderedItems[0].InReplyTo) > 0 && col.OrderedItems[0].InReplyTo[0].Id != "" { OP = col.OrderedItems[0].InReplyTo[0].Id } else { OP = id @@ -1088,7 +1085,7 @@ func main() { MarkObjectSensitive(db, id, true) if !IsIDLocal(db, OP) { - http.Redirect(w, r, "/" + board + "/" + remoteShort(OP), http.StatusSeeOther) + http.Redirect(w, r, "/"+board+"/"+remoteShort(OP), http.StatusSeeOther) return } else { http.Redirect(w, r, OP, http.StatusSeeOther) @@ -1099,7 +1096,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/remove", func(w http.ResponseWriter, r *http.Request){ + 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") @@ -1136,19 +1133,19 @@ func main() { SetObjectAndReplies(db, id, "Removed") } - if(manage == "t"){ - http.Redirect(w, r, "/" + *Key + "/" + board , http.StatusSeeOther) + if manage == "t" { + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } else if !isOP { - if (!IsIDLocal(db, id)){ - http.Redirect(w, r, "/" + board + "/" + remoteShort(OP), http.StatusSeeOther) + if !IsIDLocal(db, id) { + http.Redirect(w, r, "/"+board+"/"+remoteShort(OP), http.StatusSeeOther) return } else { http.Redirect(w, r, OP, http.StatusSeeOther) return } } else { - http.Redirect(w, r, "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+board, http.StatusSeeOther) return } @@ -1156,7 +1153,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/removeattach", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/removeattach", func(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") manage := r.URL.Query().Get("manage") @@ -1165,7 +1162,7 @@ func main() { actor := col.OrderedItems[0].Actor var OP string - if (len(col.OrderedItems[0].InReplyTo) > 0 && col.OrderedItems[0].InReplyTo[0].Id != "") { + if len(col.OrderedItems[0].InReplyTo) > 0 && col.OrderedItems[0].InReplyTo[0].Id != "" { OP = col.OrderedItems[0].InReplyTo[0].Id } else { OP = id @@ -1188,11 +1185,11 @@ func main() { SetAttachmentFromDB(db, id, "Removed") SetPreviewFromDB(db, id, "Removed") - if (manage == "t") { - http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) + if manage == "t" { + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } else if !IsIDLocal(db, OP) { - http.Redirect(w, r, "/" + board + "/" + remoteShort(OP), http.StatusSeeOther) + http.Redirect(w, r, "/"+board+"/"+remoteShort(OP), http.StatusSeeOther) return } else { http.Redirect(w, r, OP, http.StatusSeeOther) @@ -1203,7 +1200,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/report", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/report", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() @@ -1222,7 +1219,7 @@ func main() { return } - if(close != "1" && !CheckCaptcha(db, captcha)) { + if close != "1" && !CheckCaptcha(db, captcha) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("captcha required")) return @@ -1237,13 +1234,13 @@ func main() { if !IsIDLocal(db, id) { CloseLocalReportDB(db, id, board) - http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } reported := DeleteReportActivity(db, id) if reported { - http.Redirect(w, r, "/" + *Key + "/" + board, http.StatusSeeOther) + http.Redirect(w, r, "/"+*Key+"/"+board, http.StatusSeeOther) return } @@ -1254,7 +1251,7 @@ func main() { if !IsIDLocal(db, id) { CreateLocalReportDB(db, id, board, reason) - http.Redirect(w, r, "/" + board + "/" + remoteShort(id), http.StatusSeeOther) + http.Redirect(w, r, "/"+board+"/"+remoteShort(id), http.StatusSeeOther) return } @@ -1268,7 +1265,7 @@ func main() { w.Write([]byte("")) }) - http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request){ + http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) { var verify Verify defer r.Body.Close() @@ -1292,7 +1289,7 @@ func main() { http.HandleFunc("/.well-known/webfinger", func(w http.ResponseWriter, r *http.Request) { acct := r.URL.Query()["resource"] - if(len(acct) < 1) { + if len(acct) < 1 { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("resource needs a value")) return @@ -1302,7 +1299,7 @@ func main() { actorDomain := strings.Split(acct[0], "@") - if(len(actorDomain) < 2) { + if len(actorDomain) < 2 { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("accpets only subject form of acct:board@instance")) return @@ -1314,7 +1311,7 @@ func main() { actorDomain[0] = "/" + actorDomain[0] } - if !IsActorLocal(db, TP + "" + actorDomain[1] + "" + actorDomain[0]) { + if !IsActorLocal(db, TP+""+actorDomain[1]+""+actorDomain[0]) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("actor not local")) return @@ -1360,7 +1357,7 @@ func main() { SetObjectType(db, id, "Note") - http.Redirect(w, r, "/" + board + "/archive", http.StatusSeeOther) + http.Redirect(w, r, "/"+board+"/archive", http.StatusSeeOther) }) http.HandleFunc("/blacklist", func(w http.ResponseWriter, r *http.Request) { @@ -1399,7 +1396,7 @@ func main() { } } - 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) { @@ -1424,7 +1421,7 @@ func main() { 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) @@ -1435,7 +1432,7 @@ func main() { http.ListenAndServe(Port, nil) } -func CheckError(e error, m string) error{ +func CheckError(e error, m string) error { if e != nil { fmt.Println() fmt.Println(m) @@ -1448,13 +1445,13 @@ func CheckError(e error, m string) error{ func ConnectDB() *sql.DB { - host := GetConfigValue("dbhost") - port,_ := strconv.Atoi(GetConfigValue("dbport")) - user := GetConfigValue("dbuser") + host := GetConfigValue("dbhost") + port, _ := strconv.Atoi(GetConfigValue("dbport")) + user := GetConfigValue("dbuser") password := GetConfigValue("dbpass") - dbname := GetConfigValue("dbname") + dbname := GetConfigValue("dbname") - psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s " + + psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s "+ "dbname=%s sslmode=disable", host, port, user, password, dbname) db, err := sql.Open("postgres", psqlInfo) @@ -1478,14 +1475,14 @@ func CreateKey(len int) string { } 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 { @@ -1509,7 +1506,7 @@ func GetActorFromPath(db *sql.DB, location string, prefix string) Actor { var actor string - if(len(match) < 1 ) { + if len(match) < 1 { actor = "/" } else { actor = strings.Replace(match[1], "/", "", -1) @@ -1521,10 +1518,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 @@ -1566,7 +1563,7 @@ func CreateUniqueID(db *sql.DB, actor string) string { defer rows.Close() var count int = 0 - for rows.Next(){ + for rows.Next() { count += 1 } @@ -1578,7 +1575,7 @@ func CreateUniqueID(db *sql.DB, actor string) string { return newID } -func CreateNewActor(board string, prefName string, summary string, authReq []string, restricted bool) *Actor{ +func CreateNewActor(board string, prefName string, summary string, authReq []string, restricted bool) *Actor { actor := new(Actor) var path string @@ -1612,7 +1609,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) + collection := GetCollectionFromPath(db, Domain+""+path) if len(collection.OrderedItems) > 0 { enc, _ := json.MarshalIndent(collection, "", "\t") w.Header().Set("Content-Type", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"") @@ -1630,7 +1627,7 @@ func CreateObject(objType string) ObjectBase { return nObj } -func AddFollowersToActivity(db *sql.DB, activity Activity) Activity{ +func AddFollowersToActivity(db *sql.DB, activity Activity) Activity { activity.To = append(activity.To, activity.Actor.Id) @@ -1733,11 +1730,11 @@ func CreatePreviewObject(obj ObjectBase) *NestedObjectBase { objFile := re.FindString(obj.Href) - cmd := exec.Command("convert", "." + objFile ,"-resize", "250x250>", "-strip","." + href) + cmd := exec.Command("convert", "."+objFile, "-resize", "250x250>", "-strip", "."+href) err := cmd.Run() - if CheckError(err, "error with resize attachment preview") != nil { + if CheckError(err, "error with resize attachment preview") != nil { var preview NestedObjectBase return &preview } @@ -1754,7 +1751,7 @@ func CreateAttachmentObject(file multipart.File, header *multipart.FileHeader) ( fileType := re.ReplaceAllString(contentType, "") - tempFile, _ := ioutil.TempFile("./public", "*." + fileType) + tempFile, _ := ioutil.TempFile("./public", "*."+fileType) var nAttachment []ObjectBase var image ObjectBase @@ -1778,22 +1775,22 @@ func ParseCommentForReplies(db *sql.DB, comment string, op string) []ObjectBase var links []string - for i:= 0; i < len(match); i++ { + for i := 0; i < len(match); i++ { str := strings.Replace(match[i][0], ">>", "", 1) str = strings.Replace(str, "www.", "", 1) str = strings.Replace(str, "http://", "", 1) str = strings.Replace(str, "https://", "", 1) str = TP + "" + str - _ , isReply := IsReplyToOP(db, op, str) - if !IsInStringArray(links, str) && isReply { + _, isReply := IsReplyToOP(db, op, str) + if !IsInStringArray(links, str) && isReply { links = append(links, str) } } var validLinks []ObjectBase - for i:= 0; i < len(links); i++ { + for i := 0; i < len(links); i++ { _, isValid := CheckValidActivity(links[i]) - if(isValid) { + if isValid { var reply = new(ObjectBase) reply.Id = links[i] reply.Published = time.Now().UTC().Format(time.RFC3339) @@ -1837,11 +1834,11 @@ func CheckValidActivity(id string) (Collection, bool) { panic(err) } - if respCollection.AtContext.Context == "https://www.w3.org/ns/activitystreams" && respCollection.OrderedItems[0].Id != "" { - return respCollection, true; + if respCollection.AtContext.Context == "https://www.w3.org/ns/activitystreams" && respCollection.OrderedItems[0].Id != "" { + return respCollection, true } - return respCollection, false; + return respCollection, false } func GetActor(id string) Actor { @@ -1854,8 +1851,8 @@ func GetActor(id string) Actor { actor, instance := GetActorInstance(id) - if ActorCache[actor + "@" + instance].Id != "" { - respActor = ActorCache[actor + "@" + instance] + if ActorCache[actor+"@"+instance].Id != "" { + respActor = ActorCache[actor+"@"+instance] } else { req, err := http.NewRequest("GET", id, nil) @@ -1879,7 +1876,7 @@ func GetActor(id string) Actor { return respActor } - ActorCache[actor + "@" + instance] = respActor + ActorCache[actor+"@"+instance] = respActor } return respActor @@ -1894,7 +1891,7 @@ func GetActorCollection(collection string) Collection { req, err := http.NewRequest("GET", collection, nil) - CheckError(err, "error with getting actor collection req " + collection) + CheckError(err, "error with getting actor collection req "+collection) req.Header.Set("Accept", activitystreams) @@ -1913,7 +1910,7 @@ func GetActorCollection(collection string) Collection { if len(body) > 0 { err = json.Unmarshal(body, &nCollection) - CheckError(err, "error getting actor collection from body " + collection) + CheckError(err, "error getting actor collection from body "+collection) } } @@ -1925,10 +1922,10 @@ func IsValidActor(id string) (Actor, bool) { actor := FingerActor(id) if actor.Id != "" { - return actor, true; + return actor, true } - return actor, false; + return actor, false } func IsActivityLocal(db *sql.DB, activity Activity) bool { @@ -2161,7 +2158,6 @@ func MakeActivityRequestOutbox(db *sql.DB, activity Activity) { date := time.Now().UTC().Format(time.RFC1123) path := strings.Replace(activity.Actor.Outbox, instance, "", 1) - path = re.ReplaceAllString(path, "") sig := fmt.Sprintf("(request-target): %s %s\nhost: %s\ndate: %s", "post", path, instance, date) @@ -2254,7 +2250,7 @@ func GetCollectionFromID(id string) Collection { return nColl } -func GetConfigValue(value string) string{ +func GetConfigValue(value string) string { file, err := os.Open("config") CheckError(err, "there was an error opening the config file") @@ -2273,7 +2269,7 @@ func GetConfigValue(value string) string{ return "" } -func PrintAdminAuth(db *sql.DB){ +func PrintAdminAuth(db *sql.DB) { query := fmt.Sprintf("select identifier, code from boardaccess where board='%s' and type='admin'", Domain) rows, err := db.Query(query) @@ -2299,14 +2295,14 @@ func IsInStringArray(array []string, value string) bool { } func GetUniqueFilename(_type string) string { - id := RandomID(8) + 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{ + } else { return "/public/" + id + "." + _type } } @@ -2374,7 +2370,6 @@ func ResizeAttachmentToPreview(db *sql.DB) { CheckError(err, "error getting attachments") - defer rows.Close() for rows.Next() { @@ -2417,8 +2412,8 @@ func ResizeAttachmentToPreview(db *sql.DB) { objFile := re.FindString(href) - if(id != "") { - cmd := exec.Command("convert", "." + objFile ,"-resize", "250x250>", "-strip", "." + nHref) + if id != "" { + cmd := exec.Command("convert", "."+objFile, "-resize", "250x250>", "-strip", "."+nHref) err := cmd.Run() @@ -2450,15 +2445,15 @@ func ParseCommentForReply(comment string) string { var links []string - for i:= 0; i < len(match); i++ { + for i := 0; i < len(match); i++ { str := strings.Replace(match[i][0], ">>", "", 1) links = append(links, str) } - if(len(links) > 0){ + if len(links) > 0 { _, isValid := CheckValidActivity(strings.ReplaceAll(links[0], ">", "")) - if(isValid) { + if isValid { return links[0] } } @@ -2468,11 +2463,11 @@ func ParseCommentForReply(comment string) string { func GetActorByName(db *sql.DB, name string) Actor { var actor Actor - for _, e := range Boards { - if e.Actor.Name == name { - actor = e.Actor - } + for _, e := range Boards { + if e.Actor.Name == name { + actor = e.Actor } + } return actor } @@ -2482,17 +2477,17 @@ func GetActorCollectionReq(r *http.Request, collection string) Collection { req, err := http.NewRequest("GET", collection, nil) - CheckError(err, "error with getting actor collection req " + collection) + CheckError(err, "error with getting actor collection req "+collection) _, pass := GetPasswordFromSession(r) req.Header.Set("Accept", activitystreams) - req.Header.Set("Authorization", "Basic " + pass) + req.Header.Set("Authorization", "Basic "+pass) resp, err := RouteProxy(req) - CheckError(err, "error with getting actor collection resp " + collection) + CheckError(err, "error with getting actor collection resp "+collection) if resp.StatusCode == 200 { @@ -2502,13 +2497,12 @@ func GetActorCollectionReq(r *http.Request, collection string) Collection { err = json.Unmarshal(body, &nCollection) - CheckError(err, "error getting actor collection from body " + collection) + CheckError(err, "error getting actor collection from body "+collection) } return nCollection } - func shortURL(actorName string, url string) string { re := regexp.MustCompile(`.+\/`) @@ -2528,44 +2522,44 @@ func shortURL(actorName string, url string) string { re = regexp.MustCompile(`\w+$`) temp := re.ReplaceAllString(op, "") - if(temp == actor){ + if temp == actor { id := localShort(op) re := regexp.MustCompile(`.+\/`) replyCheck := re.FindString(reply) - if(reply != "" && replyCheck == actor){ + if reply != "" && replyCheck == actor { id = id + "#" + localShort(reply) } else if reply != "" { id = id + "#" + remoteShort(reply) } - return id; - }else{ + return id + } else { id := remoteShort(op) re := regexp.MustCompile(`.+\/`) replyCheck := re.FindString(reply) - if(reply != "" && replyCheck == actor){ + if reply != "" && replyCheck == actor { id = id + "#" + localShort(reply) } else if reply != "" { id = id + "#" + remoteShort(reply) } - return id; + return id } } func localShort(url string) string { - re := regexp.MustCompile(`\w+$`) - return re.FindString(StripTransferProtocol(url)); + re := regexp.MustCompile(`\w+$`) + return re.FindString(StripTransferProtocol(url)) } func remoteShort(url string) string { re := regexp.MustCompile(`\w+$`) - id := re.FindString(StripTransferProtocol(url)); + id := re.FindString(StripTransferProtocol(url)) re = regexp.MustCompile(`.+/.+/`) @@ -2590,7 +2584,7 @@ func RouteProxy(req *http.Request) (*http.Response, error) { CheckError(err, "error parsing tor proxy url") proxyTransport := &http.Transport{Proxy: http.ProxyURL(proxyUrl)} - client := &http.Client{ Transport: proxyTransport, Timeout: time.Second * 10 } + client := &http.Client{Transport: proxyTransport, Timeout: time.Second * 10} return client.Do(req) } @@ -2628,7 +2622,7 @@ func CreatedNeededDirectories() { } //looks for actor with pattern of board@instance -func FingerActor(path string) Actor{ +func FingerActor(path string) Actor { var nActor Actor @@ -2638,8 +2632,8 @@ func FingerActor(path string) Actor{ return nActor } - if ActorCache[actor + "@" + instance].Id != "" { - nActor = ActorCache[actor + "@" + instance] + if ActorCache[actor+"@"+instance].Id != "" { + nActor = ActorCache[actor+"@"+instance] } else { r := FingerRequest(actor, instance) if r != nil && r.StatusCode == 200 { @@ -2651,16 +2645,16 @@ func FingerActor(path string) Actor{ CheckError(err, "error getting fingerrequet resp from json body") - ActorCache[actor + "@" + instance] = nActor + ActorCache[actor+"@"+instance] = nActor } } return nActor } -func FingerRequest(actor string, instance string) (*http.Response){ +func FingerRequest(actor string, instance string) *http.Response { acct := "acct:" + actor + "@" + instance - req, err := http.NewRequest("GET", "http://" + instance + "/.well-known/webfinger?resource=" + acct, nil) + req, err := http.NewRequest("GET", "http://"+instance+"/.well-known/webfinger?resource="+acct, nil) CheckError(err, "could not get finger request from id req") @@ -2682,9 +2676,9 @@ func FingerRequest(actor string, instance string) (*http.Response){ CheckError(err, "error getting fingerrequet resp from json body") } - if(len(finger.Links) > 0) { + if len(finger.Links) > 0 { for _, e := range finger.Links { - if(e.Type == "application/activity+json"){ + if e.Type == "application/activity+json" { req, err := http.NewRequest("GET", e.Href, nil) CheckError(err, "could not get finger request from id req") @@ -2704,18 +2698,18 @@ func GetActorInstance(path string) (string, string) { re := regexp.MustCompile(`([@]?([\w\d.-_]+)[@](.+))`) atFormat := re.MatchString(path) - if(atFormat) { + if atFormat { match := re.FindStringSubmatch(path) - if(len(match) > 2) { + if len(match) > 2 { return match[2], match[3] } } re = regexp.MustCompile(`(https?://)(www)?([\w\d-_.:]+)(/|\s+|\r|\r\n)?$`) mainActor := re.MatchString(path) - if(mainActor) { + if mainActor { match := re.FindStringSubmatch(path) - if(len(match) > 2) { + if len(match) > 2 { return "main", match[3] } } @@ -2723,9 +2717,9 @@ func GetActorInstance(path string) (string, string) { re = regexp.MustCompile(`(https?://)?(www)?([\w\d-_.:]+)\/([\w\d-_.]+)(\/([\w\d-_.]+))?`) httpFormat := re.MatchString(path) - if(httpFormat) { + if httpFormat { match := re.FindStringSubmatch(path) - if(len(match) > 3) { + if len(match) > 3 { if match[4] == "users" { return match[6], match[3] } @@ -2754,7 +2748,7 @@ func AddInstanceToIndex(actor string) { } if !alreadyIndex { - req, err := http.NewRequest("GET", "https://fchan.xyz/addtoindex?id=" + actor, nil) + req, err := http.NewRequest("GET", "https://fchan.xyz/addtoindex?id="+actor, nil) CheckError(err, "error with add instance to actor index req") @@ -2817,13 +2811,13 @@ func GetCollectionFromReq(path string) Collection { } func HashMedia(media string) string { - h:= sha256.New() + h := sha256.New() h.Write([]byte(media)) return hex.EncodeToString(h.Sum(nil)) } func HashBytes(media []byte) string { - h:= sha256.New() + h := sha256.New() h.Write(media) return hex.EncodeToString(h.Sum(nil)) } @@ -2876,12 +2870,12 @@ func IsPostBlacklist(db *sql.DB, comment string) bool { } func HasValidation(w http.ResponseWriter, r *http.Request, actor Actor) bool { - id, _ := GetPasswordFromSession(r) + id, _ := GetPasswordFromSession(r) - if id == "" || (id != actor.Id && id != Domain) { - http.Redirect(w, r, "/", http.StatusSeeOther) - return false - } + if id == "" || (id != actor.Id && id != Domain) { + http.Redirect(w, r, "/", http.StatusSeeOther) + return false + } return true } diff --git a/outboxGet.go b/outboxGet.go index f656b3e..d2fabc4 100644 --- a/outboxGet.go +++ b/outboxGet.go @@ -35,7 +35,7 @@ func GetCollectionFromPath(db *sql.DB, path string) Collection { defer rows.Close() - for rows.Next(){ + for rows.Next() { var actor Actor var post ObjectBase var attachID string @@ -72,7 +72,7 @@ func GetCollectionFromPath(db *sql.DB, path string) Collection { return nColl } -func GetObjectFromPath(db *sql.DB, path string) ObjectBase{ +func GetObjectFromPath(db *sql.DB, path string) ObjectBase { var nObj ObjectBase diff --git a/outboxPost.go b/outboxPost.go index 0292e4f..cb48d3e 100644 --- a/outboxPost.go +++ b/outboxPost.go @@ -23,18 +23,18 @@ func ParseOutboxRequest(w http.ResponseWriter, r *http.Request, db *sql.DB) { defer r.Body.Close() if contentType == "multipart/form-data" || contentType == "application/x-www-form-urlencoded" { r.ParseMultipartForm(5 << 20) - if(BoardHasAuthType(db, actor.Name, "captcha") && CheckCaptcha(db, r.FormValue("captcha"))) { + if BoardHasAuthType(db, actor.Name, "captcha") && CheckCaptcha(db, r.FormValue("captcha")) { f, header, _ := r.FormFile("file") - if(header != nil) { + if header != nil { defer f.Close() - if(header.Size > (7 << 20)){ + if header.Size > (7 << 20) { w.WriteHeader(http.StatusRequestEntityTooLarge) w.Write([]byte("7MB max file size")) return } - if(IsMediaBanned(db, f)) { + if IsMediaBanned(db, f) { fmt.Println("media banned") http.Redirect(w, r, Domain, http.StatusSeeOther) return @@ -42,7 +42,7 @@ func ParseOutboxRequest(w http.ResponseWriter, r *http.Request, db *sql.DB) { contentType, _ := GetFileContentType(f) - if(!SupportedMIMEType(contentType)) { + if !SupportedMIMEType(contentType) { w.WriteHeader(http.StatusNotAcceptable) w.Write([]byte("file type not supported")) return @@ -235,7 +235,7 @@ func GetObjectFromJson(obj []byte) ObjectBase { return nObj } -func GetActorFromJson(actor []byte) Actor{ +func GetActorFromJson(actor []byte) Actor { var generic interface{} var nActor Actor err := json.Unmarshal(actor, &generic) @@ -338,7 +338,7 @@ func ObjectFromForm(r *http.Request, db *sql.DB, obj ObjectBase) ObjectBase { var tempFile = new(os.File) obj.Attachment, tempFile = CreateAttachmentObject(file, header) - defer tempFile.Close(); + defer tempFile.Close() fileBytes, _ := ioutil.ReadAll(file) @@ -348,7 +348,7 @@ func ObjectFromForm(r *http.Request, db *sql.DB, obj ObjectBase) ObjectBase { if re.MatchString(obj.Attachment[0].MediaType) { fileLoc := strings.ReplaceAll(obj.Attachment[0].Href, Domain, "") - cmd := exec.Command("exiv2", "rm", "." + fileLoc) + cmd := exec.Command("exiv2", "rm", "."+fileLoc) err := cmd.Run() @@ -433,7 +433,7 @@ func ParseOptions(r *http.Request, obj ObjectBase) ObjectBase { } else if e == "nokosage" { obj.Option = append(obj.Option, "nokosage") } else if email.MatchString(e) { - obj.Option = append(obj.Option, "email:" + e) + obj.Option = append(obj.Option, "email:"+e) } else if wallet.MatchString(e) { obj.Option = append(obj.Option, "wallet") var wallet CryptoCur @@ -502,19 +502,19 @@ func GetActivityFromJson(r *http.Request, db *sql.DB) Activity { func CheckCaptcha(db *sql.DB, captcha string) bool { parts := strings.Split(captcha, ":") - if strings.Trim(parts[0], " ") == "" || strings.Trim(parts[1], " ") == ""{ + if strings.Trim(parts[0], " ") == "" || strings.Trim(parts[1], " ") == "" { return false } - path := "public/" + parts[0] + ".png" - code := GetCaptchaCodeDB(db, path) + path := "public/" + parts[0] + ".png" + code := GetCaptchaCodeDB(db, path) if code != "" { DeleteCaptchaCodeDB(db, path) CreateNewCaptcha(db) } - if (code == strings.ToUpper(parts[1])) { + if code == strings.ToUpper(parts[1]) { return true } @@ -535,7 +535,7 @@ func ParseInboxRequest(w http.ResponseWriter, r *http.Request, db *sql.DB) { return } - switch(activity.Type) { + switch activity.Type { case "Create": for _, e := range activity.To { if IsActorLocal(db, e) { @@ -563,7 +563,6 @@ func ParseInboxRequest(w http.ResponseWriter, r *http.Request, db *sql.DB) { } break - case "Follow": for _, e := range activity.To { if GetActorFromDB(db, e).Id != "" { @@ -1,13 +1,12 @@ package main - import ( + "bufio" "fmt" - "net/http" - "bufio" - "os" - "strings" "github.com/gomodule/redigo/redis" + "net/http" + "os" + "strings" ) var cache redis.Conn @@ -20,7 +19,7 @@ func InitCache() { cache = conn } -func CheckSession(w http.ResponseWriter, r *http.Request) (interface{}, error){ +func CheckSession(w http.ResponseWriter, r *http.Request) (interface{}, error) { c, err := r.Cookie("session_token") @@ -29,15 +28,15 @@ func CheckSession(w http.ResponseWriter, r *http.Request) (interface{}, error){ w.WriteHeader(http.StatusUnauthorized) return nil, err } - + w.WriteHeader(http.StatusBadRequest) return nil, err } - + sessionToken := c.Value response, err := cache.Do("GET", sessionToken) - + if err != nil { w.WriteHeader(http.StatusInternalServerError) return nil, err @@ -50,7 +49,7 @@ func CheckSession(w http.ResponseWriter, r *http.Request) (interface{}, error){ return response, nil } -func GetClientKey() string{ +func GetClientKey() string { file, err := os.Open("clientkey") CheckError(err, "could not open client key in file") diff --git a/tripcode.go b/tripcode.go index 7e19cf0..b567bf0 100644 --- a/tripcode.go +++ b/tripcode.go @@ -1,15 +1,15 @@ package main import ( - "golang.org/x/text/encoding/japanese" - "golang.org/x/text/transform" - "github.com/simia-tech/crypt" - "strings" "bytes" - "regexp" "database/sql" _ "github.com/lib/pq" - "net/http" + "github.com/simia-tech/crypt" + "golang.org/x/text/encoding/japanese" + "golang.org/x/text/transform" + "net/http" + "regexp" + "strings" ) const SaltTable = "" + @@ -22,7 +22,6 @@ const SaltTable = "" + "................................" + "................................" - func TripCode(pass string) string { pass = TripCodeConvert(pass) @@ -32,25 +31,25 @@ func TripCode(pass string) string { s := []rune(pass + "H..")[1:3] for i, r := range s { - salt[i] = rune(SaltTable[r % 256]) + salt[i] = rune(SaltTable[r%256]) } - enc, err := crypt.Crypt(pass, "$1$" + string(salt[:])) - + enc, err := crypt.Crypt(pass, "$1$"+string(salt[:])) + CheckError(err, "crypt broke") - - return enc[len(enc) - 10 : len(enc)] + + return enc[len(enc)-10 : len(enc)] } func TripCodeSecure(pass string) string { pass = TripCodeConvert(pass) - enc, err := crypt.Crypt(pass, "$1$" + Salt) - + enc, err := crypt.Crypt(pass, "$1$"+Salt) + CheckError(err, "crypt secure broke") - - return enc[len(enc) - 10 : len(enc)] + + return enc[len(enc)-10 : len(enc)] } func TripCodeConvert(str string) string { @@ -76,30 +75,30 @@ func CreateNameTripCode(r *http.Request, db *sql.DB) (string, string) { if tripSecure.MatchString(input) { chunck := tripSecure.FindString(input) chunck = strings.Replace(chunck, "##", "", 1) - - ce := regexp.MustCompile(`(?i)Admin`) + + ce := regexp.MustCompile(`(?i)Admin`) admin := ce.MatchString(chunck) board, modcred := GetPasswordFromSession(r) - - if(admin && HasAuth(db, modcred, board)) { + + if admin && HasAuth(db, modcred, board) { return tripSecure.ReplaceAllString(input, ""), "#Admin" } hash := TripCodeSecure(chunck) return tripSecure.ReplaceAllString(input, ""), "!!" + hash - } - + } + trip := regexp.MustCompile("#(.+)?") if trip.MatchString(input) { chunck := trip.FindString(input) chunck = strings.Replace(chunck, "#", "", 1) - - ce := regexp.MustCompile(`(?i)Admin`) + + ce := regexp.MustCompile(`(?i)Admin`) admin := ce.MatchString(chunck) board, modcred := GetPasswordFromSession(r) - - if(admin && HasAuth(db, modcred, board)) { + + if admin && HasAuth(db, modcred, board) { return trip.ReplaceAllString(input, ""), "#Admin" } diff --git a/verification.go b/verification.go index 555e9ee..c575ae4 100644 --- a/verification.go +++ b/verification.go @@ -25,32 +25,31 @@ import ( "strings" ) - type Verify struct { - Type string + Type string Identifier string - Code string - Created string - Board string + Code string + Created string + Board string } type VerifyCooldown struct { Identifier string - Code string - Time int + Code string + Time int } type Signature struct { - KeyId string - Headers []string + KeyId string + Headers []string Signature string - Algorithm string + Algorithm string } func DeleteBoardMod(db *sql.DB, verify Verify) { query := `select code from boardaccess where identifier=$1 and board=$1` - rows, err := db.Query(query, verify.Identifier, verify.Board) + rows, err := db.Query(query, verify.Identifier, verify.Board) CheckError(err, "could not select code from boardaccess") @@ -62,25 +61,25 @@ func DeleteBoardMod(db *sql.DB, verify Verify) { if code != "" { query := `delete from crossverification where code=$1` - + _, err := db.Exec(query, code) - + CheckError(err, "could not delete code from crossverification") query = `delete from boardaccess where identifier=$1 and board=$2` - _, err = db.Exec(query, verify.Identifier, verify.Board) - - CheckError(err, "could not delete identifier from boardaccess") + _, err = db.Exec(query, verify.Identifier, verify.Board) + + CheckError(err, "could not delete identifier from boardaccess") } } -func GetBoardMod(db *sql.DB, identifier string) Verify{ +func GetBoardMod(db *sql.DB, identifier string) Verify { var nVerify Verify query := `select code, board, type, identifier from boardaccess where identifier=$1` - rows, err := db.Query(query, identifier) + rows, err := db.Query(query, identifier) CheckError(err, "could not select boardaccess query") @@ -97,14 +96,14 @@ func CreateBoardMod(db *sql.DB, verify Verify) { query := `select code from verification where identifier=$1 and type=$2` - rows, err := db.Query(query, verify.Board, verify.Type) + rows, err := db.Query(query, verify.Board, verify.Type) CheckError(err, "could not select verifcaiton query") defer rows.Close() var code string - + rows.Next() rows.Scan(&code) @@ -112,8 +111,8 @@ func CreateBoardMod(db *sql.DB, verify Verify) { query := `select identifier from boardaccess where identifier=$1 and board=$2` - rows, err := db.Query(query, verify.Identifier, verify.Board) - + rows, err := db.Query(query, verify.Identifier, verify.Board) + CheckError(err, "could not select idenifier from boardaccess") defer rows.Close() @@ -126,14 +125,14 @@ func CreateBoardMod(db *sql.DB, verify Verify) { query := `insert into crossverification (verificationcode, code) values ($1, $2)` - _, err := db.Exec(query, code, pass) - + _, err := db.Exec(query, code, pass) + CheckError(err, "could not insert new crossverification") query = `insert into boardaccess (identifier, code, board, type) values ($1, $2, $3, $4)` _, err = db.Exec(query, verify.Identifier, pass, verify.Board, verify.Type) - + CheckError(err, "could not insert new boardaccess") fmt.Printf("Board access - Board: %s, Identifier: %s, Code: %s\n", verify.Board, verify.Identifier, pass) @@ -144,7 +143,7 @@ func CreateBoardMod(db *sql.DB, verify Verify) { func CreateVerification(db *sql.DB, verify Verify) { query := `insert into verification (type, identifier, code, created) values ($1, $2, $3, $4)` - _, err := db.Exec(query, verify.Type, verify.Identifier, verify.Code, time.Now().UTC().Format(time.RFC3339)) + _, err := db.Exec(query, verify.Type, verify.Identifier, verify.Code, time.Now().UTC().Format(time.RFC3339)) CheckError(err, "error creating verify") } @@ -154,20 +153,20 @@ func GetVerificationByEmail(db *sql.DB, email string) Verify { query := `select type, identifier, code, board from boardaccess where identifier=$1` - rows, err := db.Query(query, email) + rows, err := db.Query(query, email) defer rows.Close() - CheckError(err, "error getting verify by email query") + CheckError(err, "error getting verify by email query") defer rows.Close() for rows.Next() { err := rows.Scan(&verify.Type, &verify.Identifier, &verify.Code, &verify.Board) - CheckError(err, "error getting verify by email scan") + CheckError(err, "error getting verify by email scan") } - + return verify } @@ -176,7 +175,7 @@ func GetVerificationByCode(db *sql.DB, code string) Verify { query := `select type, identifier, code, board from boardaccess where code=$1` - rows, err := db.Query(query, code) + rows, err := db.Query(query, code) defer rows.Close() @@ -188,9 +187,9 @@ func GetVerificationByCode(db *sql.DB, code string) Verify { for rows.Next() { err := rows.Scan(&verify.Type, &verify.Identifier, &verify.Code, &verify.Board) - CheckError(err, "error getting verify by code scan") + CheckError(err, "error getting verify by code scan") } - + return verify } @@ -199,7 +198,7 @@ func GetVerificationCode(db *sql.DB, verify Verify) Verify { query := `select type, identifier, code, board from boardaccess where identifier=$1 and board=$2` - rows, err := db.Query(query, verify.Identifier, verify.Board) + rows, err := db.Query(query, verify.Identifier, verify.Board) defer rows.Close() @@ -211,9 +210,9 @@ func GetVerificationCode(db *sql.DB, verify Verify) Verify { for rows.Next() { err := rows.Scan(&nVerify.Type, &nVerify.Identifier, &nVerify.Code, &nVerify.Board) - CheckError(err, "error getting verify by code scan") + CheckError(err, "error getting verify by code scan") } - + return nVerify } @@ -222,29 +221,29 @@ func VerifyCooldownCurrent(db *sql.DB, auth string) VerifyCooldown { query := `select identifier, code, time from verificationcooldown where code=$1` - rows, err := db.Query(query, auth) + rows, err := db.Query(query, auth) - defer rows.Close() + defer rows.Close() if err != nil { query := `select identifier, code, time from verificationcooldown where identifier=$1` - rows, err := db.Query(query, auth) + rows, err := db.Query(query, auth) defer rows.Close() - + if err != nil { return current } - + defer rows.Close() for rows.Next() { err = rows.Scan(¤t.Identifier, ¤t.Code, ¤t.Time) CheckError(err, "error scanning current verify cooldown verification") - } + } } defer rows.Close() @@ -261,7 +260,7 @@ func VerifyCooldownCurrent(db *sql.DB, auth string) VerifyCooldown { func VerifyCooldownAdd(db *sql.DB, verify Verify) { query := `insert into verficationcooldown (identifier, code) values ($1, $2)` - _, err := db.Exec(query, verify.Identifier, verify.Code) + _, err := db.Exec(query, verify.Identifier, verify.Code) CheckError(err, "error adding verify to cooldown") } @@ -272,23 +271,23 @@ func VerficationCooldown(db *sql.DB) { rows, err := db.Query(query) - defer rows.Close() + defer rows.Close() CheckError(err, "error with verifiy cooldown query ") defer rows.Close() for rows.Next() { - var verify VerifyCooldown + var verify VerifyCooldown err = rows.Scan(&verify.Identifier, &verify.Code, &verify.Time) CheckError(err, "error with verifiy cooldown scan ") - nTime := verify.Time - 1; + nTime := verify.Time - 1 query = `update set time=$1 where identifier=$2` - _, err := db.Exec(query, nTime, verify.Identifier) + _, err := db.Exec(query, nTime, verify.Identifier) CheckError(err, "error with update cooldown query") @@ -318,11 +317,10 @@ func SendVerification(verify Verify) { "Subject: Image Board Verification\n\n" + body - err := smtp.SendMail(SiteEmailServer + ":" + SiteEmailPort, + err := smtp.SendMail(SiteEmailServer+":"+SiteEmailPort, smtp.PlainAuth("", from, pass, SiteEmailServer), from, []string{to}, []byte(msg)) - CheckError(err, "error with smtp") } @@ -341,8 +339,8 @@ func IsEmailSetup() bool { if SiteEmailPort == "" { return false - } - + } + return true } @@ -354,7 +352,7 @@ func HasAuth(db *sql.DB, code string, board string) bool { return true } - return false; + return false } func HasAuthCooldown(db *sql.DB, auth string) bool { @@ -363,7 +361,7 @@ func HasAuthCooldown(db *sql.DB, auth string) bool { return true } - fmt.Println("has auth is false") + fmt.Println("has auth is false") return false } @@ -377,19 +375,19 @@ func GetVerify(db *sql.DB, access string) Verify { return verify } -func CreateNewCaptcha(db *sql.DB){ - id := RandomID(8) +func CreateNewCaptcha(db *sql.DB) { + id := RandomID(8) file := "public/" + id + ".png" - + for true { if _, err := os.Stat("./" + file); err == nil { - id = RandomID(8) + id = RandomID(8) file = "public/" + id + ".png" - }else{ + } else { break } } - + captcha := Captcha() var pattern string @@ -398,53 +396,53 @@ func CreateNewCaptcha(db *sql.DB){ srnd := string(rnd) switch srnd { - case "0" : + case "0": pattern = "pattern:verticalbricks" break - case "1" : + case "1": pattern = "pattern:verticalsaw" break - - case "2" : + + case "2": pattern = "pattern:hs_cross" - break + break } - + cmd := exec.Command("convert", "-size", "200x98", pattern, "-transparent", "white", file) err := cmd.Run() CheckError(err, "error with captcha first pass") - - cmd = exec.Command("convert", file, "-fill", "blue", "-pointsize", "62", "-annotate", "+0+70", captcha, "-tile", "pattern:left30", "-gravity", "center", "-transparent", "white", file) + + cmd = exec.Command("convert", file, "-fill", "blue", "-pointsize", "62", "-annotate", "+0+70", captcha, "-tile", "pattern:left30", "-gravity", "center", "-transparent", "white", file) err = cmd.Run() CheckError(err, "error with captcha second pass") - rnd = fmt.Sprintf("%d", rand.Intn(24) - 12) - - cmd = exec.Command("convert", file, "-rotate", rnd, "-wave", "5x35", "-distort", "Arc", "20", "-wave", "2x35", "-transparent", "white", file) + rnd = fmt.Sprintf("%d", rand.Intn(24)-12) + + cmd = exec.Command("convert", file, "-rotate", rnd, "-wave", "5x35", "-distort", "Arc", "20", "-wave", "2x35", "-transparent", "white", file) err = cmd.Run() - CheckError(err, "error with captcha third pass") + CheckError(err, "error with captcha third pass") var verification Verify - verification.Type = "captcha" - verification.Code = captcha + verification.Type = "captcha" + verification.Code = captcha verification.Identifier = file CreateVerification(db, verification) } func CreateBoardAccess(db *sql.DB, verify Verify) { - if(!HasBoardAccess(db, verify)){ - query := `insert into boardaccess (identifier, board) values($1, $2)` + if !HasBoardAccess(db, verify) { + query := `insert into boardaccess (identifier, board) values($1, $2)` - _, err := db.Exec(query, verify.Identifier, verify.Board) + _, err := db.Exec(query, verify.Identifier, verify.Board) CheckError(err, "could not instert verification and board into board access") } @@ -453,18 +451,18 @@ func CreateBoardAccess(db *sql.DB, verify Verify) { func HasBoardAccess(db *sql.DB, verify Verify) bool { query := `select count(*) from boardaccess where identifier=$1 and board=$2` - rows, err := db.Query(query, verify.Identifier, verify.Board) + rows, err := db.Query(query, verify.Identifier, verify.Board) - defer rows.Close() + defer rows.Close() - CheckError(err, "could not select boardaccess based on verify") + CheckError(err, "could not select boardaccess based on verify") var count int rows.Next() rows.Scan(&count) - if(count > 0) { + if count > 0 { return true } else { return false @@ -475,11 +473,11 @@ func BoardHasAuthType(db *sql.DB, board string, auth string) bool { authTypes := GetActorAuth(db, board) for _, e := range authTypes { - if(e == auth){ + if e == auth { return true } } - + return false } @@ -491,39 +489,39 @@ func Captcha() string { for i := 0; i < rng; i++ { newID += string(domain[rand.Intn(len(domain))]) } - + return newID -} +} func CreatePem(db *sql.DB, actor Actor) { privatekey, err := rsa.GenerateKey(crand.Reader, 2048) CheckError(err, "error creating private pem key") privateKeyBytes := x509.MarshalPKCS1PrivateKey(privatekey) - + privateKeyBlock := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: privateKeyBytes, } - + privatePem, err := os.Create("./pem/board/" + actor.Name + "-private.pem") - CheckError(err, "error creating private pem file for " + actor.Name) - + CheckError(err, "error creating private pem file for "+actor.Name) + err = pem.Encode(privatePem, privateKeyBlock) CheckError(err, "error encoding private pem") publickey := &privatekey.PublicKey publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey) - CheckError(err, "error Marshaling public key to X509") - + CheckError(err, "error Marshaling public key to X509") + publicKeyBlock := &pem.Block{ Type: "PUBLIC KEY", Bytes: publicKeyBytes, } - + publicPem, err := os.Create("./pem/board/" + actor.Name + "-public.pem") - CheckError(err, "error creating public pem file for " + actor.Name) - + CheckError(err, "error creating public pem file for "+actor.Name) + err = pem.Encode(publicPem, publicKeyBlock) CheckError(err, "error encoding public pem") @@ -534,13 +532,13 @@ func CreatePem(db *sql.DB, actor Actor) { StorePemToDB(db, actor) } - fmt.Println(`Created PEM keypair for the "` + actor.Name +`" board. Please keep in mind that + fmt.Println(`Created PEM keypair for the "` + actor.Name + `" board. Please keep in mind that the PEM key is crucial in identifying yourself as the legitimate owner of the board, -so DO NOT LOSE IT!!! If you lose it, YOU WILL LOSE ACCESS TO YOUR BOARD!`); +so DO NOT LOSE IT!!! If you lose it, YOU WILL LOSE ACCESS TO YOUR BOARD!`) } -func CreatePublicKeyFromPrivate(db *sql.DB, actor *Actor, publicKeyPem string) error{ - publicFilename := GetActorPemFileFromDB(db, publicKeyPem); +func CreatePublicKeyFromPrivate(db *sql.DB, actor *Actor, publicKeyPem string) error { + publicFilename := GetActorPemFileFromDB(db, publicKeyPem) privateFilename := strings.ReplaceAll(publicFilename, "public.pem", "private.pem") _, err := os.Stat(privateFilename) if err == nil { @@ -551,7 +549,7 @@ func CreatePublicKeyFromPrivate(db *sql.DB, actor *Actor, publicKeyPem string) e if block == nil || block.Type != "RSA PRIVATE KEY" { return errors.New("failed to decode PEM block containing public key") } - + key, err := x509.ParsePKCS1PrivateKey(block.Bytes) CheckError(err, "failed to parse private key") @@ -562,13 +560,13 @@ func CreatePublicKeyFromPrivate(db *sql.DB, actor *Actor, publicKeyPem string) e Headers: nil, Bytes: publicKeyDer, } - + publicFileWriter, err := os.Create(publicFilename) - CheckError(err, "error creating public pem file for " + actor.Name) + CheckError(err, "error creating public pem file for "+actor.Name) err = pem.Encode(publicFileWriter, &pubKeyBlock) CheckError(err, "error encoding public pem") - }else{ + } else { fmt.Println(`\nUnable to locate private key from public key generation. Now, this means that you are now missing the proof that you are the owner of the "` + actor.Name + `" board. If you are the developer, @@ -584,15 +582,15 @@ accepting your posts from your board from this site. Good luck ;)`) func StorePemToDB(db *sql.DB, actor Actor) { query := "select publicKeyPem from actor where id=$1" rows, err := db.Query(query, actor.Id) - - CheckError(err, "error selecting publicKeyPem id from actor") + + CheckError(err, "error selecting publicKeyPem id from actor") var result string defer rows.Close() rows.Next() rows.Scan(&result) - if(result != "") { + if result != "" { return } @@ -619,22 +617,22 @@ func ActivitySign(db *sql.DB, actor Actor, signature string) (string, error) { rows.Next() rows.Scan(&file) - file = strings.ReplaceAll(file, "public.pem", "private.pem") + file = strings.ReplaceAll(file, "public.pem", "private.pem") _, err = os.Stat(file) if err == nil { - publickey, err:= ioutil.ReadFile(file) + publickey, err := ioutil.ReadFile(file) CheckError(err, "error reading file") block, _ := pem.Decode(publickey) pub, _ := x509.ParsePKCS1PrivateKey(block.Bytes) - rng :=crand.Reader + rng := crand.Reader hashed := sha256.New() - hashed.Write([]byte(signature)) + hashed.Write([]byte(signature)) cipher, _ := rsa.SignPKCS1v15(rng, pub, crypto.SHA256, hashed.Sum(nil)) return base64.StdEncoding.EncodeToString(cipher), nil - }else{ + } else { fmt.Println(`\n Unable to locate private key. Now, this means that you are now missing the proof that you are the owner of the "` + actor.Name + `" board. If you are the developer, @@ -666,22 +664,21 @@ func ActivityVerify(actor Actor, signature string, verify string) error { func VerifyHeaderSignature(r *http.Request, actor Actor) bool { s := ParseHeaderSignature(r.Header.Get("Signature")) - var method string - var path string - var host string - var date string - var digest string - var contentLength string + var method string + var path string + var host string + var date string + var digest string + var contentLength string var sig string for i, e := range s.Headers { var nl string - if i < len(s.Headers) - 1 { + if i < len(s.Headers)-1 { nl = "\n" } - - + if e == "(request-target)" { method = strings.ToLower(r.Method) path = r.URL.Path @@ -709,9 +706,9 @@ func VerifyHeaderSignature(r *http.Request, actor Actor) bool { if e == "content-length" { contentLength = r.Header.Get("content-length") - sig += "content-length: " + contentLength + "" + nl + sig += "content-length: " + contentLength + "" + nl continue - } + } } if s.KeyId != actor.PublicKey.Id { @@ -720,14 +717,14 @@ func VerifyHeaderSignature(r *http.Request, actor Actor) bool { t, _ := time.Parse(time.RFC1123, date) - if(time.Now().UTC().Sub(t).Seconds() > 75) { + if time.Now().UTC().Sub(t).Seconds() > 75 { return false } - + if ActivityVerify(actor, s.Signature, sig) != nil { return false } - + return true } @@ -737,7 +734,7 @@ func ParseHeaderSignature(signature string) Signature { keyId := regexp.MustCompile(`keyId=`) headers := regexp.MustCompile(`headers=`) sig := regexp.MustCompile(`signature=`) - algo := regexp.MustCompile(`algorithm=`) + algo := regexp.MustCompile(`algorithm=`) signature = strings.ReplaceAll(signature, "\"", "") parts := strings.Split(signature, ",") @@ -747,7 +744,7 @@ func ParseHeaderSignature(signature string) Signature { nsig.KeyId = keyId.ReplaceAllString(e, "") continue } - + if headers.MatchString(e) { header := headers.ReplaceAllString(e, "") nsig.Headers = strings.Split(header, " ") @@ -762,7 +759,7 @@ func ParseHeaderSignature(signature string) Signature { if algo.MatchString(e) { nsig.Algorithm = algo.ReplaceAllString(e, "") continue - } + } } return nsig diff --git a/webfinger.go b/webfinger.go index 004bdca..c8fd0ae 100644 --- a/webfinger.go +++ b/webfinger.go @@ -1,12 +1,12 @@ package main type Webfinger struct { - Subject string `json:"subject,omitempty"` - Links []WebfingerLink `json:"links,omitempty"` + Subject string `json:"subject,omitempty"` + Links []WebfingerLink `json:"links,omitempty"` } type WebfingerLink struct { - Rel string `json:"rel,omitempty"` + Rel string `json:"rel,omitempty"` Type string `json:"type,omitempty"` - Href string `json:"href,omitempty"` + Href string `json:"href,omitempty"` } |