@@ -9,7 +9,8 @@
9 FlexibleInstances,
9 FlexibleInstances,
10 KindSignatures,
10 KindSignatures,
11 DeriveAnyClass,
11 DeriveAnyClass,
12− RecordWildCards #-}
12+ RecordWildCards,
13+ ScopedTypeVariables #-}
14{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
15{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
@@ -55,7 +56,17 @@ module Data.Query (
55 UserCreation(..),
56 UserCreation(..),
56 createUser,
57 createUser,
57 tryActivateToken,
58 tryActivateToken,
58− deactivateToken
59+ deactivateToken,
69+ groupChatIsValidForUser
61import Squeal.PostgreSQL
72import Squeal.PostgreSQL
@@ -85,7 +96,7 @@ import Data.Text (Text)
85import qualified Data.Text as T
96import qualified Data.Text as T
86import Data.Channel.NamedChannel
97import Data.Channel.NamedChannel
87import Data.Channel.AnonymousChannel
98import Data.Channel.AnonymousChannel
88−import Data.Maybe (fromMaybe, isJust)
99+import Data.Maybe (fromMaybe, catMaybes, isJust)
89import Squeal.PostgreSQL.Render
100import Squeal.PostgreSQL.Render
90import Data.GroupChat
101import Data.GroupChat
91import Data.Message
102import Data.Message
@@ -97,6 +108,8 @@ import Data.Foldable (fold)
97import Data.Char
108import Data.Char
98import qualified Data.Vector as V
109import qualified Data.Vector as V
99import Server.Auth.Token
110import Server.Auth.Token
112+import Data.Text.Validator
101-- MARK: Documentation
114-- MARK: Documentation
@@ -284,12 +297,40 @@ getChannelForUserQ = selectStar $
284 from (table #channels) &
297 from (table #channels) &
285 where_ (#namedChannelFullOwner .== param @1 .&& #namedChannelFullId .== param @2)
298 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)
287getAllChannelsForUserQ :: Query Schema (TuplePG (Only UserId)) (RowPG NamedChannelFull)
312getAllChannelsForUserQ :: Query Schema (TuplePG (Only UserId)) (RowPG NamedChannelFull)
288getAllChannelsForUserQ = selectStar $
313getAllChannelsForUserQ = selectStar $
289 from (table #channels) &
314 from (table #channels) &
290 where_ (#namedChannelFullOwner .== param @1) &
315 where_ (#namedChannelFullOwner .== param @1) &
291 orderBy [#namedChannelFullId & Desc]
316 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)
293updateFacultyQ :: Manipulation Schema (TuplePG Faculty) '[]
334updateFacultyQ :: Manipulation Schema (TuplePG Faculty) '[]
294updateFacultyQ = insertRow #faculties
335updateFacultyQ = insertRow #faculties
@@ -320,6 +361,11 @@ createNamedChannelQ = insertRow #channels
320 OnConflictDoRaise
361 OnConflictDoRaise
321 (Returning $ #namedChannelFullId `as` #fromOnly)
362 (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)
323deleteNamedChannelQ :: Manipulation Schema (TuplePG (Only NamedChannelId)) '[]
369deleteNamedChannelQ :: Manipulation Schema (TuplePG (Only NamedChannelId)) '[]
324deleteNamedChannelQ = deleteFrom_ #channels (#namedChannelFullId .== param @1)
370deleteNamedChannelQ = deleteFrom_ #channels (#namedChannelFullId .== param @1)
@@ -352,7 +398,7 @@ getChannelPostsQ lim dir uIds tags = getLastPostsQ
352 Just uIdsQ -> (`in_` uIdsQ)
398 Just uIdsQ -> (`in_` uIdsQ)
353 Nothing -> const $ false
399 Nothing -> const $ false
355−getTagsQ :: Query Schema '[] (RowPG (Only String))
401+getTagsQ :: Query Schema params (RowPG (Only String))
356getTagsQ = selectDistinct (unsafeFunction "unnest" #postRowTags `as` #fromOnly) $
402getTagsQ = selectDistinct (unsafeFunction "unnest" #postRowTags `as` #fromOnly) $
357 from (table #posts)
403 from (table #posts)
@@ -363,15 +409,26 @@ createMessageQ :: Manipulation
363createMessageQ = insertRow #messages
409createMessageQ = insertRow #messages
365 Default `as` #messageStorageId :*
411 Default `as` #messageStorageId :*
366− Set (param @1) `as` #messageStorageAuthorId :*
412+ Set (notNull $ param @1) `as` #messageStorageAuthorId :*
367 Set (param @2) `as` #messageStorageDestinationGroupId :*
413 Set (param @2) `as` #messageStorageDestinationGroupId :*
368 Set (param @3) `as` #messageStorageDestinationUserId :*
414 Set (param @3) `as` #messageStorageDestinationUserId :*
369− Set (param @4) `as` #messageStorageBody :*
415+ Set (notNull $ param @4) `as` #messageStorageBody :*
370 Set currentTimestamp `as` #messageStorageTime
416 Set currentTimestamp `as` #messageStorageTime
372 OnConflictDoRaise
418 OnConflictDoRaise
373 (Returning $ #messageStorageId `as` #fromOnly)
419 (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
375createGroupChatQ :: Manipulation Schema (TuplePG GroupChatCreation) (RowPG (Only GroupChatId))
432createGroupChatQ :: Manipulation Schema (TuplePG GroupChatCreation) (RowPG (Only GroupChatId))
376createGroupChatQ = insertRow #groupChats
433createGroupChatQ = insertRow #groupChats
@@ -447,7 +504,7 @@ getChatsQ lim dir = select (
447 (ifThenElse
504 (ifThenElse
448 (#messageStorageAuthorId .== param @1)
505 (#messageStorageAuthorId .== param @1)
449 #messageStorageDestinationUserId
506 #messageStorageDestinationUserId
450− (notNull #messageStorageAuthorId)) `as` #messageUserId) $
507+ #messageStorageAuthorId) `as` #messageUserId) $
451 from (table #messages) &
508 from (table #messages) &
452 where_ (isNotNull #messageStorageDestinationUserId .&&
509 where_ (isNotNull #messageStorageDestinationUserId .&&
453 (#messageStorageAuthorId .== param @1 .||
510 (#messageStorageAuthorId .== param @1 .||
@@ -514,21 +571,83 @@ getGroupChatForUserQ = selectStar $
514getFacultySearchResultQ :: Query Schema (TuplePG (Only Text)) (RowPG Faculty)
571getFacultySearchResultQ :: Query Schema (TuplePG (Only Text)) (RowPG Faculty)
515getFacultySearchResultQ = selectStar (from (table #faculties) &
572getFacultySearchResultQ = selectStar (from (table #faculties) &
516 where_ (vector @@ query) &
573 where_ (vector @@ query) &
575+ tsRankCd vector1 query & Desc,
576+ tsRankCd vector2 query & Desc,
517− orderBy [tsRankCd vector query & Desc])
577+ tsRankCd vector query & Desc
519 vector = tsVector "russian" (textArrayToText [
580 vector = tsVector "russian" (textArrayToText [
520 #facultyName,
581 #facultyName,
521 #facultyPath,
582 #facultyPath,
522 #facultyCampusName,
583 #facultyCampusName,
523 (arrayToText #facultyTags)])
584 (arrayToText #facultyTags)])
585+ vector1 = tsVector "russian" #facultyName
586+ vector2 = tsVector "russian" (textArrayToText [
524 query = tsQuery "russian" (param @1)
589 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
527 :: Expression schema from grouping params ('NotNull 'PGtext)
646 :: Expression schema from grouping params ('NotNull 'PGtext)
528 -> Expression schema from grouping params ('NotNull 'PGtext)
647 -> Expression schema from grouping params ('NotNull 'PGtext)
529 -> Expression schema from grouping params ('NotNull 'PGfloat4)
648 -> Expression schema from grouping params ('NotNull 'PGfloat4)
530tsRankCd vector query = UnsafeExpression $
649tsRankCd vector query = UnsafeExpression $
531− "ts_rank_cd" <> parenthesized (commaSeparated . map renderExpression $ [vector, query])
650+ "ts_rank_cd" <> parenthesized (commaSeparated ["ARRAY[1,1,1,1]", renderExpression vector, renderExpression query, "2|4|8|16|32"])
534 :: ByteString -- ^ Language
653 :: ByteString -- ^ Language
@@ -537,6 +656,12 @@ tsVector
537tsVector lang x = UnsafeExpression $
656tsVector lang x = UnsafeExpression $
538 "to_tsvector" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
657 "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)
541 :: ByteString -- ^ Language
666 :: ByteString -- ^ Language
542 -> Expression schema from grouping params ('NotNull 'PGtext)
667 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -544,6 +669,12 @@ tsQuery
544tsQuery lang x = UnsafeExpression $
669tsQuery lang x = UnsafeExpression $
545 "to_tsquery" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
670 "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)
547arrayToText
678arrayToText
548 :: Expression schema from grouping params ('NotNull ('PGvararray ('NotNull 'PGtext)))
679 :: Expression schema from grouping params ('NotNull ('PGvararray ('NotNull 'PGtext)))
549 -> Expression schema from grouping params ('NotNull 'PGtext)
680 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -631,20 +762,42 @@ getTokenActivationQ = selectStar (from (table #tokens) &
631 where_ (#tokenUserId .== param @1 .&&
762 where_ (#tokenUserId .== param @1 .&&
632 #tokenActivationCode .== param @2))
763 #tokenActivationCode .== param @2))
634−deactivateTokenQ :: Manipulation Schema (TuplePG (UserId, ByteString)) (RowPG (Only UserId))
765+deactivateTokenQ :: Manipulation Schema (TuplePG (UserId, ByteString)) (RowPG (Only Text))
635deactivateTokenQ = deleteFrom #tokens
766deactivateTokenQ = deleteFrom #tokens
636 (#tokenUserId .== param @1 .&&
767 (#tokenUserId .== param @1 .&&
637 #tokenDeactivationCode .== param @2)
768 #tokenDeactivationCode .== param @2)
638− (Returning (#tokenUserId `as` #fromOnly))
769+ (Returning (#tokenUserAgent `as` #fromOnly))
640getVerifiedTokenQ :: Query Schema (TuplePG (UserId, ByteString)) (RowPG Token)
771getVerifiedTokenQ :: Query Schema (TuplePG (UserId, ByteString)) (RowPG Token)
641getVerifiedTokenQ = selectStar (from (table #tokens) &
772getVerifiedTokenQ = selectStar (from (table #tokens) &
642 where_ (#tokenUserId .== param @1 .&&
773 where_ (#tokenUserId .== param @1 .&&
643 #tokenValue .== param @2 .&&
774 #tokenValue .== param @2 .&&
644− isNull #tokenVerificationCode))
775+ 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))
646-- MARK: FrontEnd Data Structures
791-- MARK: FrontEnd Data Structures
793+instance HasValidatableText UserCreation where
794+ validateText UserCreation{..} = all validateText [
795+ userCreationFirstName,
796+ userCreationMiddleName,
797+ userCreationLastName,
798+ userCreationUserFaculty,
799+ userCreationUserEmail]
648data UserCreation = UserCreation {
801data UserCreation = UserCreation {
649 userCreationFirstName :: Text,
802 userCreationFirstName :: Text,
650 userCreationMiddleName :: Text,
803 userCreationMiddleName :: Text,
@@ -663,9 +816,18 @@ instance ToJSON UserCreation where
665instance FromJSON UserCreation where
818instance FromJSON UserCreation where
666− parseJSON = withObject "named channel" $ \e ->
819+ parseJSON = withObject "user creation" $ \e ->
667 UserCreation <$> e .: "firstName" <*> e .: "middleName" <*> e .: "lastName" <*> e .: "faculty" <*> e .: "email"
820 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)
669data NamedChannelCreation = NamedChannelCreation {
831data NamedChannelCreation = NamedChannelCreation {
670 namedChannelCreationOwner :: UserId,
832 namedChannelCreationOwner :: UserId,
671 namedChannelCreationName :: Text,
833 namedChannelCreationName :: Text,
@@ -701,11 +863,13 @@ getChannelForUser uId cId = do
701 Nothing -> lift $ S.throwError S.err404
863 Nothing -> lift $ S.throwError S.err404
703-- TODO: Reject bad requests. Should be binary.
865-- TODO: Reject bad requests. Should be binary.
704−verifiedUsers :: [UserId] -> StaticPQ [UserId]
866+verifyUsers :: [UserId] -> StaticPQ ()
705−verifiedUsers uIds =
867+verifyUsers uIds =
706 case verifiedUserIdsQ uIds of
868 case verifiedUserIdsQ uIds of
707− Just uIdsQ -> fmap fromOnly <$> (runQuery uIdsQ >>= getRows)
870+ (us :: [UserId]) <- fmap fromOnly <$> (runQuery uIdsQ >>= getRows)
871+ when (length us /= length uIds) $ lift $ S.throwError impossibleContent
708− Nothing -> return []
872+ Nothing -> return ()
710deleteGroupChat :: GroupChatId -> StaticPQ ()
874deleteGroupChat :: GroupChatId -> StaticPQ ()
711deleteGroupChat gId = do
875deleteGroupChat gId = do
@@ -767,30 +931,40 @@ getAllUsers :: StaticPQ [User Faculty]
767getAllUsers = fmap rowToUser <$> (runQuery getAllUsersQ >>= getRows)
931getAllUsers = fmap rowToUser <$> (runQuery getAllUsersQ >>= getRows)
769publishPost :: UserId -> PostCreation -> StaticPQ PostId
933publishPost :: UserId -> PostCreation -> StaticPQ PostId
770−publishPost uId pc = commitedTransactionallyUpdate $ do
934+publishPost uId pc = commitedTransactionallyUpdate $ do
771 pId' <- manipulateParams createPostRowQ (uId, postCreationTags pc) >>= firstRow
935 pId' <- manipulateParams createPostRowQ (uId, postCreationTags pc) >>= firstRow
772 case pId' of
936 case pId' of
773 (Just (Only pId)) -> do
937 (Just (Only pId)) -> do
774− traversePrepared_ createPostElementRowsQ $ elementsToRows pId (postCreationBody pc)
938+ traversePrepared_ createPostElementRowsQ $ elementsToRows pId (map stripPostElement $ postCreationBody pc)
775 return pId
939 return pId
776 _ -> lift $ S.throwError S.err404
940 _ -> lift $ S.throwError S.err404
778createNewChannel :: UserId -> NamedChannelCreationRequest -> StaticPQ (Maybe NamedChannelId)
942createNewChannel :: UserId -> NamedChannelCreationRequest -> StaticPQ (Maybe NamedChannelId)
779createNewChannel uId req = commitedTransactionallyUpdate $ do
943createNewChannel uId req = commitedTransactionallyUpdate $ do
780− uIds <- verifiedUsers . toList $ namedChannelCreationRequestPeopleIds req
944+ let uIds = toList $ namedChannelCreationRequestPeopleIds req
781 cId <- manipulateParams createNamedChannelQ (addUserToChannelCreate uId (req {namedChannelCreationRequestPeopleIds = fromList uIds})) >>= firstRow
946 cId <- manipulateParams createNamedChannelQ (addUserToChannelCreate uId (req {namedChannelCreationRequestPeopleIds = fromList uIds})) >>= firstRow
782 return $ fmap fromOnly cId
947 return $ fmap fromOnly cId
949+channelCountForUser :: UserId -> StaticPQ Int64
950+channelCountForUser uId = (fromMaybe 0 . fmap fromOnly) <$> (runQueryParams countChannelsQ (Only uId) >>= firstRow)
784updateChannel :: UserId -> NamedChannel UserId -> StaticPQ ()
952updateChannel :: UserId -> NamedChannel UserId -> StaticPQ ()
785−updateChannel uId req = commitedTransactionallyUpdate $ do
953+updateChannel uId req = do
786− uIds <- fmap fromList . verifiedUsers . toList $ namedChannelPeopleIds req
954+ let uIds = namedChannelPeopleIds req
955+ verifyUsers (toList uIds)
787 _ <- getChannelForUser uId $ namedChannelId req
956 _ <- getChannelForUser uId $ namedChannelId req
788− _ <- manipulateParams updateNamedChannelQ $ addUserToChannelUpdate uId (req {namedChannelPeopleIds = uIds})
957+ _ <- commitedTransactionallyUpdate $ manipulateParams updateNamedChannelQ $ addUserToChannelUpdate uId (req {namedChannelPeopleIds = uIds})
789 return ()
958 return ()
791getFaculty :: Text -> StaticPQ Faculty
960getFaculty :: Text -> StaticPQ Faculty
792getFaculty t = runQueryParams getFacultyQ (Only t) >>= firstRow >>= fromMaybe404
961getFaculty 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
794updateFaculty :: Faculty -> StaticPQ ()
968updateFaculty :: Faculty -> StaticPQ ()
795updateFaculty fac = void $ manipulateParams updateFacultyQ fac
969updateFaculty fac = void $ manipulateParams updateFacultyQ fac
@@ -827,13 +1001,13 @@ getAllChannels uId = fmap (map removeUserFromChannel) $
827 runQueryParams getAllChannelsForUserQ (Only uId) >>= getRows
1001 runQueryParams getAllChannelsForUserQ (Only uId) >>= getRows
829deleteNamedChannel :: UserId -> NamedChannelId -> StaticPQ ()
1003deleteNamedChannel :: UserId -> NamedChannelId -> StaticPQ ()
830−deleteNamedChannel uId cId = commitedTransactionallyUpdate $ do
1004+deleteNamedChannel uId cId = do
831 _ <- getChannelForUser uId cId
1005 _ <- getChannelForUser uId cId
832− _ <- manipulateParams deleteNamedChannelQ (Only cId)
1006+ _ <- commitedTransactionallyUpdate $ manipulateParams deleteNamedChannelQ (Only cId)
833 return ()
1007 return ()
835−getTags :: StaticPQ [String]
1009+getTags :: Limit -> StaticPQ [String]
836−getTags = map fromOnly <$> (runQuery getTagsQ >>= getRows)
1010+getTags lim = map fromOnly <$> (runQuery (getNpopularTagsQ lim) >>= getRows)
838getDialogs
1012getDialogs
839 :: UserId
1013 :: UserId
@@ -866,36 +1040,40 @@ getMessagesInGroupChat
866getMessagesInGroupChat selfId gId mId lim dir = do
1040getMessagesInGroupChat selfId gId mId lim dir = do
867 _ <- getGroupChatForUser selfId gId
1041 _ <- getGroupChatForUser selfId gId
868 resp <- runQueryParams (getGroupMessagesQ lim dir) (gId, mId) >>= getRows
1042 resp <- runQueryParams (getGroupMessagesQ lim dir) (gId, mId) >>= getRows
869− (return . sequence . map restoreMessage $ resp) >>= fromMaybe500
1043+ return . catMaybes . map restoreMessage $ resp
871sendMessage :: UserId -> MessageCreation -> StaticPQ MessageId
1045sendMessage :: UserId -> MessageCreation -> StaticPQ MessageId
872−sendMessage selfId (MessageCreation (Just gId) uId@Nothing body) = do
1046+sendMessage selfId (MessageCreation (Just gId) uId@Nothing (Jsonb body)) = do
873 _ <- getGroupChatForUser selfId gId
1047 _ <- getGroupChatForUser selfId gId
874− (Only mId) <- manipulateParams createMessageQ (selfId, Just gId, uId, body)
1048+ (Only mId) <- manipulateParams createMessageQ (selfId, Just gId, uId, Jsonb $ stripPostElement body)
875 >>= firstRow >>= fromMaybe500
1049 >>= firstRow >>= fromMaybe500
876 return mId
1050 return mId
877−sendMessage selfId (MessageCreation gId@Nothing (Just uId) body) = do
1051+sendMessage selfId (MessageCreation gId@Nothing (Just uId) (Jsonb body)) = do
878− (Only mId) <- manipulateParams createMessageQ (selfId, gId, Just uId, body)
1053+ (Only mId) <- manipulateParams createMessageQ (selfId, gId, Just uId, Jsonb $ stripPostElement body)
879 >>= firstRow >>= fromMaybe500
1054 >>= firstRow >>= fromMaybe500
880 return mId
1055 return mId
881sendMessage _ _ = lift $ S.throwError S.err400
1056sendMessage _ _ = lift $ S.throwError S.err400
883createGroupChat :: UserId -> GroupChatCreation -> StaticPQ GroupChatId
1058createGroupChat :: UserId -> GroupChatCreation -> StaticPQ GroupChatId
884createGroupChat uId (GroupChatCreation (Jsonb chatUsers) name) = do
1059createGroupChat uId (GroupChatCreation (Jsonb chatUsers) name) = do
1060+ verifyUsers . M.keys $ chatUsers
1061+ commitedTransactionallyUpdate $ do
885− let chatUsers' = M.insert uId maxChatPermissions chatUsers
1062+ let chatUsers' = M.insert uId maxChatPermissions chatUsers
886− (Only chatId) <- manipulateParams createGroupChatQ (GroupChatCreation (Jsonb chatUsers') name)
1063+ (Only chatId) <- manipulateParams createGroupChatQ (GroupChatCreation (Jsonb chatUsers') name)
887− >>= firstRow >>= fromMaybe500
1064+ >>= firstRow >>= fromMaybe500
888− -- TODO: Do somehting with this
1065+ _ <- manipulateParams createPhantomMessageQ (Only chatId)
889− _ <- sendMessage uId $ MessageCreation (Just chatId) Nothing (Jsonb $ Markdown "henlo")
890− return chatId
1066+ return chatId
892updateGroupChat :: UserId -> GroupChat -> StaticPQ ()
1068updateGroupChat :: UserId -> GroupChat -> StaticPQ ()
893−updateGroupChat uId (GroupChat gId (Jsonb perms) name) = commitedTransactionallyUpdate $ do
1069+updateGroupChat uId (GroupChat gId (Jsonb perms) name) = do
1070+ verifyUsers . M.keys $ perms
1071+ commitedTransactionallyUpdate $ do
894− (GroupChat _ (Jsonb perms') _) <- getGroupChatForUser uId gId
1072+ (GroupChat _ (Jsonb perms') _) <- getGroupChatForUser uId gId
895− let userPerm = fromMaybe minChatPermissions $ M.lookup uId perms'
1073+ let userPerm = fromMaybe minChatPermissions $ M.lookup uId perms'
896− unless (isAdmin userPerm) $ lift $ S.throwError $ S.err401
1074+ unless (isAdmin userPerm) $ lift $ S.throwError $ S.err401
897− let newPerms = M.insert uId userPerm perms
1075+ let newPerms = M.insert uId userPerm perms
898− void $ manipulateParams updateGroupChatQ (GroupChat gId (Jsonb newPerms) name)
1076+ void $ manipulateParams updateGroupChatQ (GroupChat gId (Jsonb newPerms) name)
900leaveGroupChat :: UserId -> GroupChatId -> StaticPQ ()
1078leaveGroupChat :: UserId -> GroupChatId -> StaticPQ ()
901leaveGroupChat uId gId = commitedTransactionallyUpdate $ do
1079leaveGroupChat uId gId = commitedTransactionallyUpdate $ do
@@ -912,13 +1090,43 @@ getGroupChatForUser uId gId = do
912 (Just c) -> return c
1090 (Just c) -> return c
913 Nothing -> lift $ S.throwError S.err404
1091 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
915getFacultyFromQuery :: T.Text -> StaticPQ [Faculty]
1098getFacultyFromQuery :: T.Text -> StaticPQ [Faculty]
916getFacultyFromQuery query =
1099getFacultyFromQuery query =
917− runQueryParams getFacultySearchResultQ (Only . queryFromText $ query) >>= getRows
1100+ runQueryParams getFacultySearchResultQ (Only . queryFromTextAbbr $ 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)
919createToken :: Token -> StaticPQ ()
1115createToken :: Token -> StaticPQ ()
920createToken token = void $ manipulateParams createTokenQ token
1116createToken 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
923-- NOTE: Not transactional
1131-- NOTE: Not transactional
924validateToken :: Token -> StaticPQ ()
1132validateToken :: Token -> StaticPQ ()
@@ -946,7 +1154,7 @@ tryVerifyToken uId tokenData code = commitedTransactionallyUpdate $ do
946 _ <- manipulateParams updateTokenQ newToken
1154 _ <- manipulateParams updateTokenQ newToken
947 return Nothing
1155 return Nothing
949−tryActivateToken :: UserId -> ByteString -> StaticPQ (Maybe ByteString)
1157+tryActivateToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
950tryActivateToken uId activationData = do
1158tryActivateToken uId activationData = do
951 let hData = hash activationData
1159 let hData = hash activationData
952 token' <- runQueryParams getTokenActivationQ (uId, hData) >>= firstRow
1160 token' <- runQueryParams getTokenActivationQ (uId, hData) >>= firstRow
@@ -954,19 +1162,29 @@ tryActivateToken uId activationData = do
954 Nothing -> return Nothing
1162 Nothing -> return Nothing
955 Just token -> do
1163 Just token -> do
956 if (tokenActivationCode token == Just hData)
1164 if (tokenActivationCode token == Just hData)
957− then commitedTransactionallyUpdate (validateToken token) >> return (Just $ tokenValue token)
1165+ then commitedTransactionallyUpdate (validateToken token) >> (return $ Just token)
958 else return Nothing
1166 else return Nothing
960−deactivateToken :: UserId -> ByteString -> StaticPQ Bool
1168+deactivateToken :: UserId -> ByteString -> StaticPQ (Maybe Text)
961−deactivateToken uId dData = do
962− res <- manipulateParams deactivateTokenQ (uId, hash dData) >>= firstRow
1169+deactivateToken uId dData = fmap fromOnly <$> (manipulateParams deactivateTokenQ (uId, hash dData) >>= firstRow)
963− return $ isJust (res :: Maybe (Only UserId))
965getVerifiedToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
1171getVerifiedToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
966getVerifiedToken uId tokenData = runQueryParams getVerifiedTokenQ (uId, hash tokenData) >>= firstRow
1172getVerifiedToken uId tokenData = runQueryParams getVerifiedTokenQ (uId, hash tokenData) >>= firstRow
1174+updateUser :: (UserUpdateRow) -> StaticPQ (Maybe UserId)
1175+updateUser user = fmap fromOnly <$> (manipulateParams updateUserQ (normalizeUser user) >>= firstRow)
968-- MARK: Utils
1177-- 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
970data UserRow = UserRow {
1188data UserRow = UserRow {
971 userRowId :: UserId,
1189 userRowId :: UserId,
972 userRowFirstName :: Text,
1190 userRowFirstName :: Text,
@@ -1002,8 +1220,8 @@ rowToUser UserRow{..} = User {
1002 userEmail = userRowEmail
1220 userEmail = userRowEmail
1005−queryFromText :: Text -> Text
1223+queryFromTextAbbr :: Text -> Text
1006−queryFromText = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isAlphaNum)
1224+queryFromTextAbbr = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isAlphaNum)
1008 processTerm :: Text -> Text
1226 processTerm :: Text -> Text
1009 processTerm t = "(" <> t <> ":*" <> (
1227 processTerm t = "(" <> t <> ":*" <> (
@@ -1012,6 +1230,12 @@ queryFromText = T.unwords . L.intersperse "&" . map processTerm . filter (not .
1012 else mempty
1230 else mempty
1013 ) <> ")"
1231 ) <> ")"
1233+queryFromText :: Text -> Text
1234+queryFromText = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isPrint)
1236+ processTerm :: Text -> Text
1237+ processTerm t = t <> ":*"
1015directionToOperator
1239directionToOperator
1016 :: P.PaginationDirection
1240 :: P.PaginationDirection
1017 -> (ConditionOp schema0 from0 grouping0 params0 nullity0 nullity1 (ty :: PGType),
1241 -> (ConditionOp schema0 from0 grouping0 params0 nullity0 nullity1 (ty :: PGType),