package models import ( "net/http" ) // NotificationFilter handles users filtering their notification list by category. It is populated // from front-end checkboxes and translates to SQL filters for PaginateNotifications. type NotificationFilter struct { Likes bool `json:"likes"` // form field name Comments bool `json:"comments"` NewPhotos bool `json:"photos"` AlsoCommented bool `json:"replies"` // also_comment and also_posted PrivatePhoto bool `json:"private"` Misc bool `json:"misc"` // friendship_approved, cert_approved, cert_rejected, inner_circle, custom } var defaultNotificationFilter = NotificationFilter{ Likes: true, Comments: true, NewPhotos: true, AlsoCommented: true, PrivatePhoto: true, Misc: true, } // NewNotificationFilterFromForm creates a NotificationFilter struct parsed from an HTTP form. func NewNotificationFilterFromForm(r *http.Request) NotificationFilter { // Are these boxes checked in a frontend post? var ( nf = NotificationFilter{ Likes: r.FormValue("likes") == "true", Comments: r.FormValue("comments") == "true", NewPhotos: r.FormValue("photos") == "true", AlsoCommented: r.FormValue("replies") == "true", PrivatePhoto: r.FormValue("private") == "true", Misc: r.FormValue("misc") == "true", } ) // Default view or when no checkboxes were sent, all are true. if nf.IsZero() { return defaultNotificationFilter } return nf } // IsZero checks for an empty filter. func (nf NotificationFilter) IsZero() bool { return nf == NotificationFilter{} } // IsAll checks if all filters are checked. func (nf NotificationFilter) IsAll() bool { return nf == defaultNotificationFilter } // Query returns the SQL "WHERE" clause that applies the filters to the Notifications query. // // If no filters should be added, ok returns false. func (nf NotificationFilter) Query() (where string, placeholders []interface{}, ok bool) { if nf.IsAll() { return "", nil, false } var ( // Notification types to include. types = []interface{}{} ) // Translate if nf.Likes { types = append(types, NotificationLike) } if nf.Comments { types = append(types, NotificationComment) } if nf.NewPhotos { types = append(types, NotificationNewPhoto) } if nf.AlsoCommented { types = append(types, NotificationAlsoCommented, NotificationAlsoPosted) } if nf.PrivatePhoto { types = append(types, NotificationPrivatePhoto) } if nf.Misc { types = append(types, NotificationFriendApproved, NotificationCertApproved, NotificationCertRejected, NotificationCustom) } return "type IN ?", types, true }