Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

All methods on models as pointer receivers #1325

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions model/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ type Chat struct {
}

// getColors returns all colors chat names are mapped to
func (c Chat) getColors() []string {
func getColors() []string {
return []string{"#368bd6", "#ac3ba8", "#0dbd8b", "#e64f7a", "#ff812d", "#2dc2c5", "#5c56f5", "#74d12c"}
}

Expand Down Expand Up @@ -103,7 +103,7 @@ func (c *Chat) BeforeCreate(tx *gorm.DB) (err error) {
}

// set chat color:
colors := c.getColors()
colors := getColors()
userIdInt, err := strconv.Atoi(c.UserID)
if err != nil {
c.Color = colors[0]
Expand Down Expand Up @@ -135,14 +135,20 @@ func (c *Chat) AfterFind(_ *gorm.DB) (err error) {
return nil
}

// getUrlHtml returns the html for urls, the <a> tag includes target="_blank" and rel="nofollow noopener"
func getUrlHtml(url string) string {
h := blackfriday.Run([]byte(url))
return strings.TrimSuffix(string(chatHTMLPolicy.SanitizeBytes(h)), "\n")
}

// SanitiseMessage sets chat.SanitizedMessage to the sanitized html version of chat.Message, including <a> tags for links
func (c *Chat) SanitiseMessage() {
msg := html.EscapeString(c.Message)
urls := chatURLPolicy.FindAllStringIndex(msg, -1)
newMsg := ""
for _, urlIndex := range urls {
newMsg += msg[:urlIndex[0]]
newMsg += c.getUrlHtml(msg[urlIndex[0]:urlIndex[1]])
newMsg += getUrlHtml(msg[urlIndex[0]:urlIndex[1]])
}
if len(urls) > 0 {
newMsg += msg[urls[len(urls)-1][1]:]
Expand All @@ -151,9 +157,3 @@ func (c *Chat) SanitiseMessage() {
}
c.SanitizedMessage = newMsg
}

// getUrlHtml returns the html for urls, the <a> tag includes target="_blank" and rel="nofollow noopener"
func (c Chat) getUrlHtml(url string) string {
h := blackfriday.Run([]byte(url))
return strings.TrimSuffix(string(chatHTMLPolicy.SanitizeBytes(h)), "\n")
}
60 changes: 30 additions & 30 deletions model/course.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ func (c *Course) ToDTO() CourseDTO {
}

// GetUrl returns the URL of the course, e.g. /course/2022/S/MyCourse
func (c Course) GetUrl() string {
func (c *Course) GetUrl() string {
return fmt.Sprintf("/course/%d/%s/%s", c.Year, c.TeachingTerm, c.Slug)
}

// GetStreamUrl returns the URL of the stream, e.g. /w/MyStream/42
func (c Course) GetStreamUrl(stream Stream) string {
func (c *Course) GetStreamUrl(stream Stream) string {
return fmt.Sprintf("/w/%s/%d", c.Slug, stream.ID)
}

Expand All @@ -87,7 +87,7 @@ type CameraPresetPreference struct {
}

// GetCameraPresetPreference retrieves the camera preset preferences
func (c Course) GetCameraPresetPreference() []CameraPresetPreference {
func (c *Course) GetCameraPresetPreference() []CameraPresetPreference {
var res []CameraPresetPreference
err := json.Unmarshal([]byte(c.CameraPresetPreferences), &res)
if err != nil {
Expand All @@ -111,7 +111,7 @@ type SourcePreference struct {
}

// GetSourcePreference retrieves the source preferences
func (c Course) GetSourcePreference() []SourcePreference {
func (c *Course) GetSourcePreference() []SourcePreference {
var res []SourcePreference
err := json.Unmarshal([]byte(c.SourcePreferences), &res)
if err != nil {
Expand All @@ -121,7 +121,7 @@ func (c Course) GetSourcePreference() []SourcePreference {
}

// GetSourceModeForLectureHall retrieves the source preference for the given lecture hall, returns default SourcePreference if non-existing
func (c Course) GetSourceModeForLectureHall(id uint) SourceMode {
func (c *Course) GetSourceModeForLectureHall(id uint) SourceMode {
for _, preference := range c.GetSourcePreference() {
if preference.LectureHallID == id {
return preference.SourceMode
Expand All @@ -131,7 +131,7 @@ func (c Course) GetSourceModeForLectureHall(id uint) SourceMode {
}

// CanUseSource returns whether the specified source type is allowed for the lecture hall id given
func (c Course) CanUseSource(lectureHallID uint, sourceType string) bool {
func (c *Course) CanUseSource(lectureHallID uint, sourceType string) bool {
mode := c.GetSourceModeForLectureHall(lectureHallID)
switch sourceType {
case "PRES":
Expand All @@ -155,15 +155,15 @@ func (c *Course) SetSourcePreference(pref []SourcePreference) {
}

// CompareTo used for sorting. Falling back to old java habits...
func (c Course) CompareTo(other Course) bool {
func (c *Course) CompareTo(other Course) bool {
if !other.HasNextLecture() {
return true
}
return c.GetNextLectureDate().Before(other.GetNextLectureDate())
}

// IsLive returns whether the course has a lecture that is live
func (c Course) IsLive() bool {
func (c *Course) IsLive() bool {
for _, s := range c.Streams {
if s.LiveNow {
return true
Expand All @@ -173,7 +173,7 @@ func (c Course) IsLive() bool {
}

// IsNextLectureStartingSoon checks whether the course has a lecture that starts soon
func (c Course) IsNextLectureStartingSoon() bool {
func (c *Course) IsNextLectureStartingSoon() bool {
for _, s := range c.Streams {
if s.IsComingUp() {
return true
Expand All @@ -183,7 +183,7 @@ func (c Course) IsNextLectureStartingSoon() bool {
}

// NumStreams returns the number of streams for the course that are VoDs or live
func (c Course) NumStreams() int {
func (c *Course) NumStreams() int {
res := 0
for i := range c.Streams {
if c.Streams[i].Recording || c.Streams[i].LiveNow {
Expand All @@ -193,7 +193,7 @@ func (c Course) NumStreams() int {
return res
}

func (c Course) StreamTimes() []string {
func (c *Course) StreamTimes() []string {
streamTimes := make([]string, len(c.Streams))

for i, s := range c.Streams {
Expand All @@ -204,7 +204,7 @@ func (c Course) StreamTimes() []string {
}

// HasRecordings returns whether the course has any recordings.
func (c Course) HasRecordings() bool {
func (c *Course) HasRecordings() bool {
for i := range c.Streams {
if c.Streams[i].Recording {
return true
Expand All @@ -214,17 +214,17 @@ func (c Course) HasRecordings() bool {
}

// NumUsers returns the number of users enrolled in the course
func (c Course) NumUsers() int {
func (c *Course) NumUsers() int {
return len(c.Users)
}

// NextLectureHasReachedTimeSlot returns whether the courses next lecture arrived at its timeslot
func (c Course) NextLectureHasReachedTimeSlot() bool {
func (c *Course) NextLectureHasReachedTimeSlot() bool {
return c.GetNextLecture().TimeSlotReached()
}

// GetNextLecture returns the next lecture of the course
func (c Course) GetNextLecture() Stream {
func (c *Course) GetNextLecture() *Stream {
var earliestLecture Stream
earliestLectureDate := time.Now().Add(time.Hour * 24 * 365 * 10) // 10 years from now.
for _, s := range c.Streams {
Expand All @@ -233,27 +233,27 @@ func (c Course) GetNextLecture() Stream {
earliestLecture = s
}
}
return earliestLecture
return &earliestLecture
}

// GetLastRecording returns the most recent lecture of the course
// Assumes an ascending order of c.Streams
func (c Course) GetLastRecording() Stream {
func (c *Course) GetLastRecording() *Stream {
var lastLecture Stream
now := time.Now()
for _, s := range c.Streams {
if s.Start.After(now) {
return lastLecture
return &lastLecture
}
if s.Recording {
lastLecture = s
}
}
return lastLecture
return &lastLecture
}

// GetLiveStreams returns the current live streams of the course or an empty slice if none are live
func (c Course) GetLiveStreams() []Stream {
func (c *Course) GetLiveStreams() []Stream {
var res []Stream
for _, s := range c.Streams {
if s.LiveNow {
Expand All @@ -264,7 +264,7 @@ func (c Course) GetLiveStreams() []Stream {
}

// GetNextLectureDate returns the next lecture date of the course
func (c Course) GetNextLectureDate() time.Time {
func (c *Course) GetNextLectureDate() time.Time {
// TODO: Refactor this with IsNextLectureSelfStream when the sorting error fixed
earliestLectureDate := time.Now().Add(time.Hour * 24 * 365 * 10) // 10 years from now.
for _, s := range c.Streams {
Expand All @@ -276,17 +276,17 @@ func (c Course) GetNextLectureDate() time.Time {
}

// IsNextLectureSelfStream checks whether the next lecture is a self stream
func (c Course) IsNextLectureSelfStream() bool {
func (c *Course) IsNextLectureSelfStream() bool {
return c.GetNextLecture().IsSelfStream()
}

// GetNextLectureDateFormatted returns a JavaScript friendly formatted date string
func (c Course) GetNextLectureDateFormatted() string {
func (c *Course) GetNextLectureDateFormatted() string {
return c.GetNextLectureDate().Format("2006-01-02 15:04:05")
}

// HasNextLecture checks whether there is another upcoming lecture
func (c Course) HasNextLecture() bool {
func (c *Course) HasNextLecture() bool {
n := time.Now()
for _, s := range c.Streams {
if s.Start.After(n) {
Expand All @@ -297,12 +297,12 @@ func (c Course) HasNextLecture() bool {
}

// HasStreams checks whether the lecture has any streams (recorded, live or upcoming) associated to it
func (c Course) HasStreams() bool {
func (c *Course) HasStreams() bool {
return len(c.Streams) > 0
}

// GetRecordings returns all recording of this course as streams
func (c Course) GetRecordings() []Stream {
func (c *Course) GetRecordings() []Stream {
var recordings []Stream
for _, s := range c.Streams {
if s.Recording {
Expand All @@ -313,22 +313,22 @@ func (c Course) GetRecordings() []Stream {
}

// IsHidden returns true if visibility is set to 'hidden' and false if not
func (c Course) IsHidden() bool {
func (c *Course) IsHidden() bool {
return c.Visibility == "hidden"
}

// IsLoggedIn returns true if visibility is set to 'loggedin' and false if not
func (c Course) IsLoggedIn() bool {
func (c *Course) IsLoggedIn() bool {
return c.Visibility == "loggedin"
}

// IsEnrolled returns true if visibility is set to 'enrolled' and false if not
func (c Course) IsEnrolled() bool {
func (c *Course) IsEnrolled() bool {
return c.Visibility == "enrolled"
}

// AdminJson is the JSON representation of a courses streams for the admin panel
func (c Course) AdminJson(lhs []LectureHall) []gin.H {
func (c *Course) AdminJson(lhs []LectureHall) []gin.H {
var res []gin.H
for _, s := range c.Streams {
res = append(res, s.getJson(lhs, c))
Expand Down
10 changes: 5 additions & 5 deletions model/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ type File struct {
Type FileType `gorm:"not null; default: 1"`
}

func (f File) GetDownloadFileName() string {
func (f *File) GetDownloadFileName() string {
pts := strings.Split(f.Path, "/")
if len(pts) == 0 {
return ""
}
return pts[len(pts)-1]
}

func (f File) GetFriendlyFileName() string {
func (f *File) GetFriendlyFileName() string {
fn := f.GetDownloadFileName()
if strings.Contains(strings.ToLower(fn), "cam") {
return "Camera-view"
Expand All @@ -57,7 +57,7 @@ func (f File) GetFriendlyFileName() string {
}

// GetVodTypeByName infers the type of a video file based on its name.
func (f File) GetVodTypeByName() string {
func (f *File) GetVodTypeByName() string {
if strings.HasSuffix(f.Path, "CAM.mp4") {
return "CAM"
}
Expand All @@ -67,11 +67,11 @@ func (f File) GetVodTypeByName() string {
return "COMB"
}

func (f File) IsThumb() bool {
func (f *File) IsThumb() bool {
return f.Type == FILETYPE_THUMB_CAM || f.Type == FILETYPE_THUMB_PRES || f.Type == FILETYPE_THUMB_COMB
}

func (f File) IsURL() bool {
func (f *File) IsURL() bool {
parsedUrl, err := url.Parse(f.Path)
if err != nil {
return false
Expand Down
2 changes: 1 addition & 1 deletion model/info-page.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type InfoPage struct {
Type InfoPageType `gorm:"not null; default: 1"`
}

func (mt InfoPage) Render() template.HTML {
func (mt *InfoPage) Render() template.HTML {
var renderedContent template.HTML = ""
switch mt.Type {
case INFOPAGE_MARKDOWN:
Expand Down
2 changes: 1 addition & 1 deletion model/lecture_hall.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const (
Panasonic
)

func (l LectureHall) NumSources() int {
func (l *LectureHall) NumSources() int {
num := 0
if l.CombIP != "" {
num++
Expand Down
2 changes: 1 addition & 1 deletion model/notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ func (n *Notification) AfterFind(_ *gorm.DB) error {
return nil
}

func (n Notification) GetBodyForGoTemplate() template.HTML {
func (n *Notification) GetBodyForGoTemplate() template.HTML {
return template.HTML(n.SanitizedBody)
}
2 changes: 1 addition & 1 deletion model/poll.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type PollOption struct {
Votes []User `gorm:"many2many:poll_option_user_votes" json:"-"`
}

func (o PollOption) GetStatsMap(votes int64) gin.H {
func (o *PollOption) GetStatsMap(votes int64) gin.H {
return gin.H{
"ID": o.ID,
"answer": o.Answer,
Expand Down
8 changes: 4 additions & 4 deletions model/server-notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@ type ServerNotification struct {
Expires time.Time `gorm:"not null"`
}

func (s ServerNotification) BeforeCreate(tx *gorm.DB) (err error) {
func (s *ServerNotification) BeforeCreate(tx *gorm.DB) (err error) {
if s.Expires.Before(s.Start) {
err = errors.New("can't save notification where expires is before start")
}
return
}

func (s ServerNotification) FormatFrom() string {
func (s *ServerNotification) FormatFrom() string {
return s.Start.Format("2006-01-02 15:04")
}

func (s ServerNotification) FormatExpires() string {
func (s *ServerNotification) FormatExpires() string {
return s.Expires.Format("2006-01-02 15:04")
}

func (s ServerNotification) HTML() template.HTML {
func (s *ServerNotification) HTML() template.HTML {
return template.HTML(s.Text)
}
Loading
Loading