@@ -9,8 +9,7 @@
9 FlexibleInstances,
9 FlexibleInstances,
10 KindSignatures,
10 KindSignatures,
11 DeriveAnyClass,
11 DeriveAnyClass,
12− RecordWildCards,
12+ RecordWildCards #-}
13− ScopedTypeVariables #-}
15{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
14{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
@@ -54,19 +53,7 @@ module Data.Query (
54 tryVerifyToken,
53 tryVerifyToken,
55 getVerifiedToken,
54 getVerifiedToken,
56 UserCreation(..),
55 UserCreation(..),
57− createUser,
56+ createUser
69− groupChatIsValidForUser
72import Squeal.PostgreSQL
59import Squeal.PostgreSQL
@@ -96,7 +83,7 @@ import Data.Text (Text)
96import qualified Data.Text as T
83import qualified Data.Text as T
97import Data.Channel.NamedChannel
84import Data.Channel.NamedChannel
98import Data.Channel.AnonymousChannel
85import Data.Channel.AnonymousChannel
99−import Data.Maybe (fromMaybe, catMaybes, isJust)
86+import Data.Maybe (fromMaybe)
100import Squeal.PostgreSQL.Render
87import Squeal.PostgreSQL.Render
101import Data.GroupChat
88import Data.GroupChat
102import Data.Message
89import Data.Message
@@ -108,8 +95,7 @@ import Data.Foldable (fold)
108import Data.Char
95import Data.Char
109import qualified Data.Vector as V
96import qualified Data.Vector as V
110import Server.Auth.Token
97import Server.Auth.Token
111−import Server.Error
98+import Data.Int
112−import Data.Text.Validator
114-- MARK: Documentation
100-- MARK: Documentation
@@ -206,8 +192,7 @@ getUsersQ uIds = case idsToColumn uIds of
206 #faculties ! #facultyPath `as` #userRowFacultyPath :*
192 #faculties ! #facultyPath `as` #userRowFacultyPath :*
207 #faculties ! #facultyCampusName `as` #userRowFacultyCampusName :*
193 #faculties ! #facultyCampusName `as` #userRowFacultyCampusName :*
208 #faculties ! #facultyCampusCode `as` #userRowFacultyCampusCode :*
194 #faculties ! #facultyCampusCode `as` #userRowFacultyCampusCode :*
209− #faculties ! #facultyTags `as` #userRowFacultyTags :*
195+ #faculties ! #facultyTags `as` #userRowFacultyTags
210− #faculties ! #facultyAddress `as` #userRowFacultyAddress
211 ) (from (subquery (idQ `As` #ids) &
196 ) (from (subquery (idQ `As` #ids) &
212 innerJoin (table #users)
197 innerJoin (table #users)
213 (#ids ! #id .== #users ! #userRowId) &
198 (#ids ! #id .== #users ! #userRowId) &
@@ -230,8 +215,7 @@ getAllUsersQ = select (
230 #faculties ! #facultyPath `as` #userRowFacultyPath :*
215 #faculties ! #facultyPath `as` #userRowFacultyPath :*
231 #faculties ! #facultyCampusName `as` #userRowFacultyCampusName :*
216 #faculties ! #facultyCampusName `as` #userRowFacultyCampusName :*
232 #faculties ! #facultyCampusCode `as` #userRowFacultyCampusCode :*
217 #faculties ! #facultyCampusCode `as` #userRowFacultyCampusCode :*
233− #faculties ! #facultyTags `as` #userRowFacultyTags :*
218+ #faculties ! #facultyTags `as` #userRowFacultyTags
234− #faculties ! #facultyAddress `as` #userRowFacultyAddress
235 ) (from ((table #users) &
219 ) (from ((table #users) &
236 innerJoin (table #faculties)
220 innerJoin (table #faculties)
237 (#users ! #userRowFacultyUrl .== #faculties ! #facultyUrl))&
221 (#users ! #userRowFacultyUrl .== #faculties ! #facultyUrl))&
@@ -297,40 +281,12 @@ getChannelForUserQ = selectStar $
297 from (table #channels) &
281 from (table #channels) &
298 where_ (#namedChannelFullOwner .== param @1 .&& #namedChannelFullId .== param @2)
282 where_ (#namedChannelFullOwner .== param @1 .&& #namedChannelFullId .== param @2)
300−updateUserQ :: Manipulation Schema (TuplePG (UserUpdateRow)) (RowPG (Only UserId))
301−updateUserQ = update #users (
302− Same `as` #userRowId :*
303− Set (param @2) `as` #userRowFirstName :*
304− Set (param @3) `as` #userRowMiddleName :*
305− Set (param @4) `as` #userRowLastName :*
306− Set (param @5) `as` #userRowFacultyUrl :*
307− Same `as` #userRowEmail :*
308− Same `as` #userRowIsValidated)
309− (#userRowId .== param @1)
310− (Returning $ #userRowId `as` #fromOnly)
312getAllChannelsForUserQ :: Query Schema (TuplePG (Only UserId)) (RowPG NamedChannelFull)
284getAllChannelsForUserQ :: Query Schema (TuplePG (Only UserId)) (RowPG NamedChannelFull)
313getAllChannelsForUserQ = selectStar $
285getAllChannelsForUserQ = selectStar $
314 from (table #channels) &
286 from (table #channels) &
315 where_ (#namedChannelFullOwner .== param @1) &
287 where_ (#namedChannelFullOwner .== param @1) &
316 orderBy [#namedChannelFullId & Desc]
288 orderBy [#namedChannelFullId & Desc]
318−searchChannelsForUserQ :: Query Schema (TuplePG (UserId, Text)) (RowPG NamedChannelFull)
319−searchChannelsForUserQ = selectStar $
320− from (table #channels) &
321− where_ (#namedChannelFullOwner .== param @1) &
323− tsRankCd vector1 query & Desc,
324− tsRankCd vector query & Desc
327− vector = tsVector' (textArrayToText [
328− #namedChannelFullName,
329− unsafeFunction "unnest" #namedChannelFullTags
331− vector1 = tsVector' #namedChannelFullName
332− query = tsQuery' (param @2)
334updateFacultyQ :: Manipulation Schema (TuplePG Faculty) '[]
290updateFacultyQ :: Manipulation Schema (TuplePG Faculty) '[]
335updateFacultyQ = insertRow #faculties
291updateFacultyQ = insertRow #faculties
@@ -339,8 +295,7 @@ updateFacultyQ = insertRow #faculties
339 Set (param @3) `as` #facultyPath :*
295 Set (param @3) `as` #facultyPath :*
340 Set (param @4) `as` #facultyCampusName :*
296 Set (param @4) `as` #facultyCampusName :*
341 Set (param @5) `as` #facultyCampusCode :*
297 Set (param @5) `as` #facultyCampusCode :*
342− Set (param @6) `as` #facultyTags :*
298+ Set (param @6) `as` #facultyTags
343− Set (param @7) `as` #facultyAddress
345 (OnConflictDoNothing)
300 (OnConflictDoNothing)
346 (Returning Nil)
301 (Returning Nil)
@@ -361,11 +316,6 @@ createNamedChannelQ = insertRow #channels
361 OnConflictDoRaise
316 OnConflictDoRaise
362 (Returning $ #namedChannelFullId `as` #fromOnly)
317 (Returning $ #namedChannelFullId `as` #fromOnly)
364−countChannelsQ :: Query Schema (TuplePG (Only UserId)) (RowPG (Only Int64))
365−countChannelsQ = select (countStar `as` #fromOnly) (from (table #channels) &
366− where_ (#namedChannelFullOwner .== param @1) &
367− groupBy #namedChannelFullOwner)
369deleteNamedChannelQ :: Manipulation Schema (TuplePG (Only NamedChannelId)) '[]
319deleteNamedChannelQ :: Manipulation Schema (TuplePG (Only NamedChannelId)) '[]
370deleteNamedChannelQ = deleteFrom_ #channels (#namedChannelFullId .== param @1)
320deleteNamedChannelQ = deleteFrom_ #channels (#namedChannelFullId .== param @1)
@@ -398,7 +348,7 @@ getChannelPostsQ lim dir uIds tags = getLastPostsQ
398 Just uIdsQ -> (`in_` uIdsQ)
348 Just uIdsQ -> (`in_` uIdsQ)
399 Nothing -> const $ false
349 Nothing -> const $ false
401−getTagsQ :: Query Schema params (RowPG (Only String))
351+getTagsQ :: Query Schema '[] (RowPG (Only String))
402getTagsQ = selectDistinct (unsafeFunction "unnest" #postRowTags `as` #fromOnly) $
352getTagsQ = selectDistinct (unsafeFunction "unnest" #postRowTags `as` #fromOnly) $
403 from (table #posts)
353 from (table #posts)
@@ -409,26 +359,15 @@ createMessageQ :: Manipulation
409createMessageQ = insertRow #messages
359createMessageQ = insertRow #messages
411 Default `as` #messageStorageId :*
361 Default `as` #messageStorageId :*
412− Set (notNull $ param @1) `as` #messageStorageAuthorId :*
362+ Set (param @1) `as` #messageStorageAuthorId :*
413 Set (param @2) `as` #messageStorageDestinationGroupId :*
363 Set (param @2) `as` #messageStorageDestinationGroupId :*
414 Set (param @3) `as` #messageStorageDestinationUserId :*
364 Set (param @3) `as` #messageStorageDestinationUserId :*
415− Set (notNull $ param @4) `as` #messageStorageBody :*
365+ Set (param @4) `as` #messageStorageBody :*
416 Set currentTimestamp `as` #messageStorageTime
366 Set currentTimestamp `as` #messageStorageTime
418 OnConflictDoRaise
368 OnConflictDoRaise
419 (Returning $ #messageStorageId `as` #fromOnly)
369 (Returning $ #messageStorageId `as` #fromOnly)
421−createPhantomMessageQ :: Manipulation Schema (TuplePG (Only GroupChatId)) '[]
422−createPhantomMessageQ = insertRow_ #messages
424− Default `as` #messageStorageId :*
425− Set null_ `as` #messageStorageAuthorId :*
426− Set (notNull $ param @1) `as` #messageStorageDestinationGroupId :*
427− Set null_ `as` #messageStorageDestinationUserId :*
428− Set null_ `as` #messageStorageBody :*
429− Set currentTimestamp `as` #messageStorageTime
432createGroupChatQ :: Manipulation Schema (TuplePG GroupChatCreation) (RowPG (Only GroupChatId))
371createGroupChatQ :: Manipulation Schema (TuplePG GroupChatCreation) (RowPG (Only GroupChatId))
433createGroupChatQ = insertRow #groupChats
372createGroupChatQ = insertRow #groupChats
@@ -504,7 +443,7 @@ getChatsQ lim dir = select (
504 (ifThenElse
443 (ifThenElse
505 (#messageStorageAuthorId .== param @1)
444 (#messageStorageAuthorId .== param @1)
506 #messageStorageDestinationUserId
445 #messageStorageDestinationUserId
507− #messageStorageAuthorId) `as` #messageUserId) $
446+ (notNull #messageStorageAuthorId)) `as` #messageUserId) $
508 from (table #messages) &
447 from (table #messages) &
509 where_ (isNotNull #messageStorageDestinationUserId .&&
448 where_ (isNotNull #messageStorageDestinationUserId .&&
510 (#messageStorageAuthorId .== param @1 .||
449 (#messageStorageAuthorId .== param @1 .||
@@ -571,83 +510,21 @@ getGroupChatForUserQ = selectStar $
571getFacultySearchResultQ :: Query Schema (TuplePG (Only Text)) (RowPG Faculty)
510getFacultySearchResultQ :: Query Schema (TuplePG (Only Text)) (RowPG Faculty)
572getFacultySearchResultQ = selectStar (from (table #faculties) &
511getFacultySearchResultQ = selectStar (from (table #faculties) &
573 where_ (vector @@ query) &
512 where_ (vector @@ query) &
575− tsRankCd vector1 query & Desc,
576− tsRankCd vector2 query & Desc,
577− tsRankCd vector query & Desc
513+ orderBy [tsRankCd vector query & Desc])
580 vector = tsVector "russian" (textArrayToText [
515 vector = tsVector "russian" (textArrayToText [
581 #facultyName,
516 #facultyName,
582 #facultyPath,
517 #facultyPath,
583 #facultyCampusName,
518 #facultyCampusName,
584 (arrayToText #facultyTags)])
519 (arrayToText #facultyTags)])
585− vector1 = tsVector "russian" #facultyName
586− vector2 = tsVector "russian" (textArrayToText [
589 query = tsQuery "russian" (param @1)
520 query = tsQuery "russian" (param @1)
591−searchUsersQ :: Query Schema (TuplePG (Only Text)) (RowPG UserRow)
592−searchUsersQ = select (
593− #users ! #userRowId :*
594− #users ! #userRowFirstName :*
595− #users ! #userRowMiddleName :*
596− #users ! #userRowLastName :*
597− #users ! #userRowFacultyUrl :*
598− #users ! #userRowEmail :*
599− #users ! #userRowIsValidated :*
600− #faculties ! #facultyName `as` #userRowFacultyName :*
601− #faculties ! #facultyUrl `as` #userRowFacultyURL :*
602− #faculties ! #facultyPath `as` #userRowFacultyPath :*
603− #faculties ! #facultyCampusName `as` #userRowFacultyCampusName :*
604− #faculties ! #facultyCampusCode `as` #userRowFacultyCampusCode :*
605− #faculties ! #facultyTags `as` #userRowFacultyTags :*
606− #faculties ! #facultyAddress `as` #userRowFacultyAddress
607− ) (from ((table #users) &
608− innerJoin (table #faculties)
609− (#users ! #userRowFacultyUrl .== #faculties ! #facultyUrl)) &
610− where_ (notNull $ #users ! #userRowIsValidated) &
611− where_ (vector @@ query) &
612− orderBy [tsRankCd vector query & Desc] &
615− vector = tsVector' (textArrayToText [
616− #users ! #userRowFirstName,
617− #users ! #userRowMiddleName,
618− #users ! #userRowLastName
620− query = tsQuery' (param @1)
622−tagsByFrquencyQ :: Query Schema params '["tag" ::: 'NotNull (PG Text), "count" ::: 'NotNull 'PGint8]
623−tagsByFrquencyQ = select
624− (#fromOnly `as` #tag :* count #fromOnly `as` #count)
625− (from (subquery $ getTagsQ `As` #tt) &
628−getNpopularTagsQ :: Limit -> Query Schema param (RowPG (Only Text))
629−getNpopularTagsQ lim = select (#tag `as` #fromOnly)
630− (from (subquery $ tagsByFrquencyQ `As` #tt) &
631− orderBy [#count & Desc] &
635−searchTagsQ :: Query Schema (TuplePG (Only Text)) (RowPG (Only Text))
636−searchTagsQ = select (#tag `as` #fromOnly) $
637− from (subquery (tagsByFrquencyQ `As` #tt)) &
638− where_ (vector @@ query) &
639− orderBy [#count & Desc] &
642− query = tsQuery' (param @1)
643− vector = tsVector' #tag
646 :: Expression schema from grouping params ('NotNull 'PGtext)
523 :: Expression schema from grouping params ('NotNull 'PGtext)
647 -> Expression schema from grouping params ('NotNull 'PGtext)
524 -> Expression schema from grouping params ('NotNull 'PGtext)
648 -> Expression schema from grouping params ('NotNull 'PGfloat4)
525 -> Expression schema from grouping params ('NotNull 'PGfloat4)
649tsRankCd vector query = UnsafeExpression $
526tsRankCd vector query = UnsafeExpression $
650− "ts_rank_cd" <> parenthesized (commaSeparated ["ARRAY[1,1,1,1]", renderExpression vector, renderExpression query, "2|4|8|16|32"])
527+ "ts_rank_cd" <> parenthesized (commaSeparated . map renderExpression $ [vector, query])
653 :: ByteString -- ^ Language
530 :: ByteString -- ^ Language
@@ -656,12 +533,6 @@ tsVector
656tsVector lang x = UnsafeExpression $
533tsVector lang x = UnsafeExpression $
657 "to_tsvector" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
534 "to_tsvector" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
660− :: Expression schema from grouping params ('NotNull 'PGtext)
661− -> Expression schema from grouping params ('NotNull 'PGtext)
662−tsVector' x = UnsafeExpression $
663− "to_tsvector" <> parenthesized (renderExpression x)
666 :: ByteString -- ^ Language
537 :: ByteString -- ^ Language
667 -> Expression schema from grouping params ('NotNull 'PGtext)
538 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -669,12 +540,6 @@ tsQuery
669tsQuery lang x = UnsafeExpression $
540tsQuery lang x = UnsafeExpression $
670 "to_tsquery" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
541 "to_tsquery" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
673− :: Expression schema from grouping params ('NotNull 'PGtext)
674− -> Expression schema from grouping params ('NotNull 'PGtext)
675−tsQuery' x = UnsafeExpression $
676− "to_tsquery" <> parenthesized (renderExpression x)
678arrayToText
543arrayToText
679 :: Expression schema from grouping params ('NotNull ('PGvararray ('NotNull 'PGtext)))
544 :: Expression schema from grouping params ('NotNull ('PGvararray ('NotNull 'PGtext)))
680 -> Expression schema from grouping params ('NotNull 'PGtext)
545 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -757,47 +622,14 @@ getTokenQ = selectStar (from (table #tokens) &
757 where_ (#tokenUserId .== param @1 .&&
622 where_ (#tokenUserId .== param @1 .&&
758 #tokenValue .== param @2))
623 #tokenValue .== param @2))
760−getTokenActivationQ :: Query Schema (TuplePG (UserId, ByteString)) (RowPG Token)
761−getTokenActivationQ = selectStar (from (table #tokens) &
762− where_ (#tokenUserId .== param @1 .&&
763− #tokenActivationCode .== param @2))
765−deactivateTokenQ :: Manipulation Schema (TuplePG (UserId, ByteString)) (RowPG (Only Text))
766−deactivateTokenQ = deleteFrom #tokens
767− (#tokenUserId .== param @1 .&&
768− #tokenDeactivationCode .== param @2)
769− (Returning (#tokenUserAgent `as` #fromOnly))
771getVerifiedTokenQ :: Query Schema (TuplePG (UserId, ByteString)) (RowPG Token)
625getVerifiedTokenQ :: Query Schema (TuplePG (UserId, ByteString)) (RowPG Token)
772getVerifiedTokenQ = selectStar (from (table #tokens) &
626getVerifiedTokenQ = selectStar (from (table #tokens) &
773 where_ (#tokenUserId .== param @1 .&&
627 where_ (#tokenUserId .== param @1 .&&
774 #tokenValue .== param @2 .&&
628 #tokenValue .== param @2 .&&
775− isNull #tokenVerificationCode .&&
629+ isNull #tokenVerificationCode))
776− currentTimestamp .< #tokenExpiryDate))
778−killAllTokensQ :: Manipulation Schema (TuplePG (Only UserId)) '[]
779−killAllTokensQ = deleteFrom_ #tokens
780− (#tokenUserId .== param @1)
782−pruneDeadTokensQ :: Manipulation Schema '[] '[]
783−pruneDeadTokensQ = deleteFrom_ #tokens
784− (#tokenExpiryDate .< currentTimestamp)
786−pruneGhostUsersQ :: Manipulation Schema '[] '[]
787−pruneGhostUsersQ = deleteFrom_ #users
788− ((not_ . in_ #userRowId $ select (#tokens ! #tokenUserId `as` #id) (from $ table #tokens)) .&&
789− (not_ . notNull $ #userRowIsValidated))
791-- MARK: FrontEnd Data Structures
631-- MARK: FrontEnd Data Structures
793−instance HasValidatableText UserCreation where
794− validateText UserCreation{..} = all validateText [
795− userCreationFirstName,
796− userCreationMiddleName,
797− userCreationLastName,
798− userCreationUserFaculty,
799− userCreationUserEmail]
801data UserCreation = UserCreation {
633data UserCreation = UserCreation {
802 userCreationFirstName :: Text,
634 userCreationFirstName :: Text,
803 userCreationMiddleName :: Text,
635 userCreationMiddleName :: Text,
@@ -816,18 +648,9 @@ instance ToJSON UserCreation where
818instance FromJSON UserCreation where
650instance FromJSON UserCreation where
819− parseJSON = withObject "user creation" $ \e ->
651+ parseJSON = withObject "named channel" $ \e ->
820 UserCreation <$> e .: "firstName" <*> e .: "middleName" <*> e .: "lastName" <*> e .: "faculty" <*> e .: "email"
652 UserCreation <$> e .: "firstName" <*> e .: "middleName" <*> e .: "lastName" <*> e .: "faculty" <*> e .: "email"
822−data UserUpdateRow = UserUpdateRow {
823− userUpdateRowId :: UserId,
824− userUpdateRowFirstName :: Text,
825− userUpdateRowMiddleName :: Text,
826− userUpdateRowLastName :: Text,
827− userUpdateRowUserFaculty :: FacultyUrl
828−} deriving (GHC.Generic, SOP.Generic, SOP.HasDatatypeInfo)
831data NamedChannelCreation = NamedChannelCreation {
654data NamedChannelCreation = NamedChannelCreation {
832 namedChannelCreationOwner :: UserId,
655 namedChannelCreationOwner :: UserId,
833 namedChannelCreationName :: Text,
656 namedChannelCreationName :: Text,
@@ -863,13 +686,11 @@ getChannelForUser uId cId = do
863 Nothing -> lift $ S.throwError S.err404
686 Nothing -> lift $ S.throwError S.err404
865-- TODO: Reject bad requests. Should be binary.
688-- TODO: Reject bad requests. Should be binary.
866−verifyUsers :: [UserId] -> StaticPQ ()
689+verifiedUsers :: [UserId] -> StaticPQ [UserId]
867−verifyUsers uIds =
690+verifiedUsers uIds =
868 case verifiedUserIdsQ uIds of
691 case verifiedUserIdsQ uIds of
870− (us :: [UserId]) <- fmap fromOnly <$> (runQuery uIdsQ >>= getRows)
692+ Just uIdsQ -> fmap fromOnly <$> (runQuery uIdsQ >>= getRows)
871− when (length us /= length uIds) $ lift $ S.throwError impossibleContent
872− Nothing -> return ()
693+ Nothing -> return []
874deleteGroupChat :: GroupChatId -> StaticPQ ()
695deleteGroupChat :: GroupChatId -> StaticPQ ()
875deleteGroupChat gId = do
696deleteGroupChat gId = do
@@ -931,40 +752,30 @@ getAllUsers :: StaticPQ [User Faculty]
931getAllUsers = fmap rowToUser <$> (runQuery getAllUsersQ >>= getRows)
752getAllUsers = fmap rowToUser <$> (runQuery getAllUsersQ >>= getRows)
933publishPost :: UserId -> PostCreation -> StaticPQ PostId
754publishPost :: UserId -> PostCreation -> StaticPQ PostId
934−publishPost uId pc = commitedTransactionallyUpdate $ do
755+publishPost uId pc = commitedTransactionallyUpdate $ do
935 pId' <- manipulateParams createPostRowQ (uId, postCreationTags pc) >>= firstRow
756 pId' <- manipulateParams createPostRowQ (uId, postCreationTags pc) >>= firstRow
936 case pId' of
757 case pId' of
937 (Just (Only pId)) -> do
758 (Just (Only pId)) -> do
938− traversePrepared_ createPostElementRowsQ $ elementsToRows pId (map stripPostElement $ postCreationBody pc)
759+ traversePrepared_ createPostElementRowsQ $ elementsToRows pId (postCreationBody pc)
939 return pId
760 return pId
940 _ -> lift $ S.throwError S.err404
761 _ -> lift $ S.throwError S.err404
942createNewChannel :: UserId -> NamedChannelCreationRequest -> StaticPQ (Maybe NamedChannelId)
763createNewChannel :: UserId -> NamedChannelCreationRequest -> StaticPQ (Maybe NamedChannelId)
943createNewChannel uId req = commitedTransactionallyUpdate $ do
764createNewChannel uId req = commitedTransactionallyUpdate $ do
944− let uIds = toList $ namedChannelCreationRequestPeopleIds req
765+ uIds <- verifiedUsers . toList $ namedChannelCreationRequestPeopleIds req
946 cId <- manipulateParams createNamedChannelQ (addUserToChannelCreate uId (req {namedChannelCreationRequestPeopleIds = fromList uIds})) >>= firstRow
766 cId <- manipulateParams createNamedChannelQ (addUserToChannelCreate uId (req {namedChannelCreationRequestPeopleIds = fromList uIds})) >>= firstRow
947 return $ fmap fromOnly cId
767 return $ fmap fromOnly cId
949−channelCountForUser :: UserId -> StaticPQ Int64
950−channelCountForUser uId = (fromMaybe 0 . fmap fromOnly) <$> (runQueryParams countChannelsQ (Only uId) >>= firstRow)
952updateChannel :: UserId -> NamedChannel UserId -> StaticPQ ()
769updateChannel :: UserId -> NamedChannel UserId -> StaticPQ ()
953−updateChannel uId req = do
770+updateChannel uId req = commitedTransactionallyUpdate $ do
954− let uIds = namedChannelPeopleIds req
771+ uIds <- fmap fromList . verifiedUsers . toList $ namedChannelPeopleIds req
955− verifyUsers (toList uIds)
956 _ <- getChannelForUser uId $ namedChannelId req
772 _ <- getChannelForUser uId $ namedChannelId req
957− _ <- commitedTransactionallyUpdate $ manipulateParams updateNamedChannelQ $ addUserToChannelUpdate uId (req {namedChannelPeopleIds = uIds})
773+ _ <- manipulateParams updateNamedChannelQ $ addUserToChannelUpdate uId (req {namedChannelPeopleIds = uIds})
958 return ()
774 return ()
960getFaculty :: Text -> StaticPQ Faculty
776getFaculty :: Text -> StaticPQ Faculty
961getFaculty t = runQueryParams getFacultyQ (Only t) >>= firstRow >>= fromMaybe404
777getFaculty t = runQueryParams getFacultyQ (Only t) >>= firstRow >>= fromMaybe404
963−isValidFaculty :: FacultyUrl -> StaticPQ Bool
964−isValidFaculty url = do
965− (faculty :: Maybe Faculty) <- runQueryParams getFacultyQ (Only url) >>= firstRow
966− return $ isJust faculty
968updateFaculty :: Faculty -> StaticPQ ()
779updateFaculty :: Faculty -> StaticPQ ()
969updateFaculty fac = void $ manipulateParams updateFacultyQ fac
780updateFaculty fac = void $ manipulateParams updateFacultyQ fac
@@ -1001,13 +812,13 @@ getAllChannels uId = fmap (map removeUserFromChannel) $
1001 runQueryParams getAllChannelsForUserQ (Only uId) >>= getRows
812 runQueryParams getAllChannelsForUserQ (Only uId) >>= getRows
1003deleteNamedChannel :: UserId -> NamedChannelId -> StaticPQ ()
814deleteNamedChannel :: UserId -> NamedChannelId -> StaticPQ ()
1004−deleteNamedChannel uId cId = do
815+deleteNamedChannel uId cId = commitedTransactionallyUpdate $ do
1005 _ <- getChannelForUser uId cId
816 _ <- getChannelForUser uId cId
1006− _ <- commitedTransactionallyUpdate $ manipulateParams deleteNamedChannelQ (Only cId)
817+ _ <- manipulateParams deleteNamedChannelQ (Only cId)
1007 return ()
818 return ()
1009−getTags :: Limit -> StaticPQ [String]
820+getTags :: StaticPQ [String]
1010−getTags lim = map fromOnly <$> (runQuery (getNpopularTagsQ lim) >>= getRows)
821+getTags = map fromOnly <$> (runQuery getTagsQ >>= getRows)
1012getDialogs
823getDialogs
1013 :: UserId
824 :: UserId
@@ -1040,40 +851,36 @@ getMessagesInGroupChat
1040getMessagesInGroupChat selfId gId mId lim dir = do
851getMessagesInGroupChat selfId gId mId lim dir = do
1041 _ <- getGroupChatForUser selfId gId
852 _ <- getGroupChatForUser selfId gId
1042 resp <- runQueryParams (getGroupMessagesQ lim dir) (gId, mId) >>= getRows
853 resp <- runQueryParams (getGroupMessagesQ lim dir) (gId, mId) >>= getRows
1043− return . catMaybes . map restoreMessage $ resp
854+ (return . sequence . map restoreMessage $ resp) >>= fromMaybe500
1045sendMessage :: UserId -> MessageCreation -> StaticPQ MessageId
856sendMessage :: UserId -> MessageCreation -> StaticPQ MessageId
1046−sendMessage selfId (MessageCreation (Just gId) uId@Nothing (Jsonb body)) = do
857+sendMessage selfId (MessageCreation (Just gId) uId@Nothing body) = do
1047 _ <- getGroupChatForUser selfId gId
858 _ <- getGroupChatForUser selfId gId
1048− (Only mId) <- manipulateParams createMessageQ (selfId, Just gId, uId, Jsonb $ stripPostElement body)
859+ (Only mId) <- manipulateParams createMessageQ (selfId, Just gId, uId, body)
1049 >>= firstRow >>= fromMaybe500
860 >>= firstRow >>= fromMaybe500
1050 return mId
861 return mId
1051−sendMessage selfId (MessageCreation gId@Nothing (Just uId) (Jsonb body)) = do
862+sendMessage selfId (MessageCreation gId@Nothing (Just uId) body) = do
1053− (Only mId) <- manipulateParams createMessageQ (selfId, gId, Just uId, Jsonb $ stripPostElement body)
863+ (Only mId) <- manipulateParams createMessageQ (selfId, gId, Just uId, body)
1054 >>= firstRow >>= fromMaybe500
864 >>= firstRow >>= fromMaybe500
1055 return mId
865 return mId
1056sendMessage _ _ = lift $ S.throwError S.err400
866sendMessage _ _ = lift $ S.throwError S.err400
1058createGroupChat :: UserId -> GroupChatCreation -> StaticPQ GroupChatId
868createGroupChat :: UserId -> GroupChatCreation -> StaticPQ GroupChatId
1059createGroupChat uId (GroupChatCreation (Jsonb chatUsers) name) = do
869createGroupChat uId (GroupChatCreation (Jsonb chatUsers) name) = do
1060− verifyUsers . M.keys $ chatUsers
1061− commitedTransactionallyUpdate $ do
1062− let chatUsers' = M.insert uId maxChatPermissions chatUsers
870+ let chatUsers' = M.insert uId maxChatPermissions chatUsers
1063− (Only chatId) <- manipulateParams createGroupChatQ (GroupChatCreation (Jsonb chatUsers') name)
871+ (Only chatId) <- manipulateParams createGroupChatQ (GroupChatCreation (Jsonb chatUsers') name)
1064− >>= firstRow >>= fromMaybe500
872+ >>= firstRow >>= fromMaybe500
1065− _ <- manipulateParams createPhantomMessageQ (Only chatId)
873+ -- TODO: Do somehting with this
874+ _ <- sendMessage uId $ MessageCreation (Just chatId) Nothing (Jsonb $ Markdown "henlo")
1066− return chatId
875+ return chatId
1068updateGroupChat :: UserId -> GroupChat -> StaticPQ ()
877updateGroupChat :: UserId -> GroupChat -> StaticPQ ()
1069−updateGroupChat uId (GroupChat gId (Jsonb perms) name) = do
878+updateGroupChat uId (GroupChat gId (Jsonb perms) name) = commitedTransactionallyUpdate $ do
1070− verifyUsers . M.keys $ perms
1071− commitedTransactionallyUpdate $ do
1072− (GroupChat _ (Jsonb perms') _) <- getGroupChatForUser uId gId
879+ (GroupChat _ (Jsonb perms') _) <- getGroupChatForUser uId gId
1073− let userPerm = fromMaybe minChatPermissions $ M.lookup uId perms'
880+ let userPerm = fromMaybe minChatPermissions $ M.lookup uId perms'
1074− unless (isAdmin userPerm) $ lift $ S.throwError $ S.err401
881+ unless (isAdmin userPerm) $ lift $ S.throwError $ S.err401
1075− let newPerms = M.insert uId userPerm perms
882+ let newPerms = M.insert uId userPerm perms
1076− void $ manipulateParams updateGroupChatQ (GroupChat gId (Jsonb newPerms) name)
883+ void $ manipulateParams updateGroupChatQ (GroupChat gId (Jsonb newPerms) name)
1078leaveGroupChat :: UserId -> GroupChatId -> StaticPQ ()
885leaveGroupChat :: UserId -> GroupChatId -> StaticPQ ()
1079leaveGroupChat uId gId = commitedTransactionallyUpdate $ do
886leaveGroupChat uId gId = commitedTransactionallyUpdate $ do
@@ -1090,60 +897,30 @@ getGroupChatForUser uId gId = do
1090 (Just c) -> return c
897 (Just c) -> return c
1091 Nothing -> lift $ S.throwError S.err404
898 Nothing -> lift $ S.throwError S.err404
1093−groupChatIsValidForUser :: UserId -> GroupChatId -> StaticPQ Bool
1094−groupChatIsValidForUser uId gId = do
1095− (chat :: Maybe GroupChat) <- runQueryParams getGroupChatForUserQ (show uId, gId) >>= firstRow
1096− return $ isJust chat
1098getFacultyFromQuery :: T.Text -> StaticPQ [Faculty]
900getFacultyFromQuery :: T.Text -> StaticPQ [Faculty]
1099getFacultyFromQuery query =
901getFacultyFromQuery query =
1100− runQueryParams getFacultySearchResultQ (Only . queryFromTextAbbr $ query) >>= getRows
902+ runQueryParams getFacultySearchResultQ (Only . queryFromText $ query) >>= getRows
1102−searchUsers :: T.Text -> StaticPQ [User Faculty]
1103−searchUsers query = do
1104− unless (validateText query) $ lift $ throwError lengthExceeded
1105− if (T.null . T.filter isAlpha $ query)
1107− else map rowToUser <$> (runQueryParams searchUsersQ (Only . queryFromText $ query) >>= getRows)
1109−searchTags :: T.Text -> StaticPQ [Text]
1110−searchTags "" = return []
1111−searchTags query = map fromOnly <$>
1112− (runQueryParams searchTagsQ
1113− (Only . (<> ":*") . T.strip $ query) >>= getRows)
1115createToken :: Token -> StaticPQ ()
904createToken :: Token -> StaticPQ ()
1116createToken token = void $ manipulateParams createTokenQ token
905createToken token = void $ manipulateParams createTokenQ token
1118−killAllTokens :: UserId -> StaticPQ ()
1119−killAllTokens = void . manipulateParams killAllTokensQ . Only
1121−pruneAuth :: StaticPQ ()
1123− _ <- commitedTransactionallyUpdate . manipulate $ pruneDeadTokensQ
1124− _ <- commitedTransactionallyUpdate . manipulate $ pruneGhostUsersQ
1127−searchChannels :: UserId -> Text -> StaticPQ [NamedChannel UserId]
1128−searchChannels uId query = fmap (map removeUserFromChannel) $
1129− runQueryParams searchChannelsForUserQ (uId, queryFromText query) >>= getRows
1131-- NOTE: Not transactional
908-- NOTE: Not transactional
1132validateToken :: Token -> StaticPQ ()
909validateToken :: Token -> StaticPQ ()
1133validateToken token = do
910validateToken token = do
1134− void $ manipulateParams updateTokenQ token{tokenVerificationCode = Nothing, tokenActivationCode = Nothing}
911+ void $ manipulateParams updateTokenQ token{tokenVerificationCode = Nothing}
1135 void $ manipulateParams validateUserQ $ Only $ tokenUserId token
912 void $ manipulateParams validateUserQ $ Only $ tokenUserId token
1137invalidateToken :: UserId -> ByteString -> StaticPQ ()
914invalidateToken :: UserId -> ByteString -> StaticPQ ()
1138invalidateToken uId bs = void . manipulateParams deleteTokenQ $ (uId, bs)
915invalidateToken uId bs = void . manipulateParams deleteTokenQ $ (uId, bs)
1140−tryVerifyToken :: UserId -> ByteString -> Int -> StaticPQ (Maybe Token)
917+tryVerifyToken :: UserId -> ByteString -> Int32 -> StaticPQ (Maybe Token)
1141tryVerifyToken uId tokenData code = commitedTransactionallyUpdate $ do
918tryVerifyToken uId tokenData code = commitedTransactionallyUpdate $ do
1142− token' <- runQueryParams getTokenQ (uId, hash tokenData) >>= firstRow
919+ token' <- runQueryParams getTokenQ (uId, tokenData) >>= firstRow
1143 case token' of
920 case token' of
1144 Nothing -> return Nothing
921 Nothing -> return Nothing
1145 Just token -> do
922 Just token -> do
1146− if (tokenVerificationCode token == Just (hashVerificationCode code))
923+ if (tokenVerificationCode token == Just code)
1147 then validateToken token >> (return $ Just token)
924 then validateToken token >> (return $ Just token)
1149 let triesLeft = tokenActivationTriesLeft token - 1
926 let triesLeft = tokenActivationTriesLeft token - 1
@@ -1154,37 +931,11 @@ tryVerifyToken uId tokenData code = commitedTransactionallyUpdate $ do
1154 _ <- manipulateParams updateTokenQ newToken
931 _ <- manipulateParams updateTokenQ newToken
1155 return Nothing
932 return Nothing
1157−tryActivateToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
1158−tryActivateToken uId activationData = do
1159− let hData = hash activationData
1160− token' <- runQueryParams getTokenActivationQ (uId, hData) >>= firstRow
1162− Nothing -> return Nothing
1164− if (tokenActivationCode token == Just hData)
1165− then commitedTransactionallyUpdate (validateToken token) >> (return $ Just token)
1166− else return Nothing
1168−deactivateToken :: UserId -> ByteString -> StaticPQ (Maybe Text)
1169−deactivateToken uId dData = fmap fromOnly <$> (manipulateParams deactivateTokenQ (uId, hash dData) >>= firstRow)
1171getVerifiedToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
934getVerifiedToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
1172−getVerifiedToken uId tokenData = runQueryParams getVerifiedTokenQ (uId, hash tokenData) >>= firstRow
935+getVerifiedToken uId tokenData = runQueryParams getVerifiedTokenQ (uId, tokenData) >>= firstRow
1174−updateUser :: (UserUpdateRow) -> StaticPQ (Maybe UserId)
1175−updateUser user = fmap fromOnly <$> (manipulateParams updateUserQ (normalizeUser user) >>= firstRow)
1177-- MARK: Utils
937-- MARK: Utils
1179−normalizeUser :: UserUpdateRow -> UserUpdateRow
1180−normalizeUser UserUpdateRow{..} = UserUpdateRow {
1181− userUpdateRowId = userUpdateRowId,
1182− userUpdateRowFirstName = T.strip $ userUpdateRowFirstName,
1183− userUpdateRowMiddleName = T.strip $ userUpdateRowMiddleName,
1184− userUpdateRowLastName = T.strip $ userUpdateRowLastName,
1185− userUpdateRowUserFaculty = T.toLower . T.strip $ userUpdateRowUserFaculty
1188data UserRow = UserRow {
939data UserRow = UserRow {
1189 userRowId :: UserId,
940 userRowId :: UserId,
1190 userRowFirstName :: Text,
941 userRowFirstName :: Text,
@@ -1198,8 +949,7 @@ data UserRow = UserRow {
1198 userRowFacultyPath :: T.Text,
949 userRowFacultyPath :: T.Text,
1199 userRowFacultyCampusName :: T.Text,
950 userRowFacultyCampusName :: T.Text,
1200 userRowFacultyCampusCode :: T.Text,
951 userRowFacultyCampusCode :: T.Text,
1201− userRowFacultyTags :: V.Vector T.Text,
952+ userRowFacultyTags :: V.Vector T.Text
1202− userRowFacultyAddress :: T.Text
1203} deriving (GHC.Generic, SOP.Generic, SOP.HasDatatypeInfo)
953} deriving (GHC.Generic, SOP.Generic, SOP.HasDatatypeInfo)
1205rowToUser :: UserRow -> User Faculty
955rowToUser :: UserRow -> User Faculty
@@ -1214,27 +964,13 @@ rowToUser UserRow{..} = User {
1214 facultyPath = userRowFacultyPath,
964 facultyPath = userRowFacultyPath,
1215 facultyCampusName = userRowFacultyCampusName,
965 facultyCampusName = userRowFacultyCampusName,
1216 facultyCampusCode = userRowFacultyCampusCode,
966 facultyCampusCode = userRowFacultyCampusCode,
1217− facultyTags = userRowFacultyTags,
967+ facultyTags = userRowFacultyTags
1218− facultyAddress = userRowFacultyAddress
1220 userEmail = userRowEmail
969 userEmail = userRowEmail
1223−queryFromTextAbbr :: Text -> Text
1224−queryFromTextAbbr = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isAlphaNum)
1226− processTerm :: Text -> Text
1227− processTerm t = "(" <> t <> ":*" <> (
1229− then (" | (" <>) . (<> ")") . T.unwords . L.intersperse "<->" . map (<> ":*") . map T.singleton . T.unpack $ t
1233queryFromText :: Text -> Text
972queryFromText :: Text -> Text
1234−queryFromText = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isPrint)
973+queryFromText = T.unwords . L.intersperse "&" . map (`T.append` ":*") . filter (not . T.null) . T.split (not . isAlphaNum)
1236− processTerm :: Text -> Text
1237− processTerm t = t <> ":*"
1239directionToOperator
975directionToOperator
1240 :: P.PaginationDirection
976 :: P.PaginationDirection