@@ -9,8 +9,7 @@
99 FlexibleInstances,
1010 KindSignatures,
1111 DeriveAnyClass,
12− RecordWildCards,
13− ScopedTypeVariables #-}
12+ RecordWildCards #-}
1413
1514{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
1615
@@ -56,17 +55,7 @@ module Data.Query (
5655 UserCreation(..),
5756 createUser,
5857 tryActivateToken,
59− deactivateToken,
60− searchUsers,
61− searchTags,
62− updateUser,
63− UserUpdateRow(..),
64− killAllTokens,
65− channelCountForUser,
66− pruneAuth,
67− searchChannels,
68− isValidFaculty,
69− groupChatIsValidForUser
58+ deactivateToken
7059 ) where
7160
7261import Squeal.PostgreSQL
@@ -96,7 +85,7 @@ import Data.Text (Text)
9685import qualified Data.Text as T
9786import Data.Channel.NamedChannel
9887import Data.Channel.AnonymousChannel
99−import Data.Maybe (fromMaybe, catMaybes, isJust)
88+import Data.Maybe (fromMaybe, isJust)
10089import Squeal.PostgreSQL.Render
10190import Data.GroupChat
10291import Data.Message
@@ -108,8 +97,6 @@ import Data.Foldable (fold)
10897import Data.Char
10998import qualified Data.Vector as V
11099import Server.Auth.Token
111−import Server.Error
112−import Data.Text.Validator
113100
114101-- MARK: Documentation
115102
@@ -297,40 +284,12 @@ getChannelForUserQ = selectStar $
297284 from (table #channels) &
298285 where_ (#namedChannelFullOwner .== param @1 .&& #namedChannelFullId .== param @2)
299286
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)
311−
312287getAllChannelsForUserQ :: Query Schema (TuplePG (Only UserId)) (RowPG NamedChannelFull)
313288getAllChannelsForUserQ = selectStar $
314289 from (table #channels) &
315290 where_ (#namedChannelFullOwner .== param @1) &
316291 orderBy [#namedChannelFullId & Desc]
317292
318−searchChannelsForUserQ :: Query Schema (TuplePG (UserId, Text)) (RowPG NamedChannelFull)
319−searchChannelsForUserQ = selectStar $
320− from (table #channels) &
321− where_ (#namedChannelFullOwner .== param @1) &
322− orderBy [
323− tsRankCd vector1 query & Desc,
324− tsRankCd vector query & Desc
325− ]
326− where
327− vector = tsVector' (textArrayToText [
328− #namedChannelFullName,
329− unsafeFunction "unnest" #namedChannelFullTags
330− ])
331− vector1 = tsVector' #namedChannelFullName
332− query = tsQuery' (param @2)
333−
334293updateFacultyQ :: Manipulation Schema (TuplePG Faculty) '[]
335294updateFacultyQ = insertRow #faculties
336295 (
@@ -361,11 +320,6 @@ createNamedChannelQ = insertRow #channels
361320 OnConflictDoRaise
362321 (Returning $ #namedChannelFullId `as` #fromOnly)
363322
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)
368−
369323deleteNamedChannelQ :: Manipulation Schema (TuplePG (Only NamedChannelId)) '[]
370324deleteNamedChannelQ = deleteFrom_ #channels (#namedChannelFullId .== param @1)
371325
@@ -398,7 +352,7 @@ getChannelPostsQ lim dir uIds tags = getLastPostsQ
398352 Just uIdsQ -> (`in_` uIdsQ)
399353 Nothing -> const $ false
400354
401−getTagsQ :: Query Schema params (RowPG (Only String))
355+getTagsQ :: Query Schema '[] (RowPG (Only String))
402356getTagsQ = selectDistinct (unsafeFunction "unnest" #postRowTags `as` #fromOnly) $
403357 from (table #posts)
404358
@@ -409,26 +363,15 @@ createMessageQ :: Manipulation
409363createMessageQ = insertRow #messages
410364 (
411365 Default `as` #messageStorageId :*
412− Set (notNull $ param @1) `as` #messageStorageAuthorId :*
366+ Set (param @1) `as` #messageStorageAuthorId :*
413367 Set (param @2) `as` #messageStorageDestinationGroupId :*
414368 Set (param @3) `as` #messageStorageDestinationUserId :*
415− Set (notNull $ param @4) `as` #messageStorageBody :*
369+ Set (param @4) `as` #messageStorageBody :*
416370 Set currentTimestamp `as` #messageStorageTime
417371 )
418372 OnConflictDoRaise
419373 (Returning $ #messageStorageId `as` #fromOnly)
420374
421−createPhantomMessageQ :: Manipulation Schema (TuplePG (Only GroupChatId)) '[]
422−createPhantomMessageQ = insertRow_ #messages
423− (
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
430− )
431−
432375createGroupChatQ :: Manipulation Schema (TuplePG GroupChatCreation) (RowPG (Only GroupChatId))
433376createGroupChatQ = insertRow #groupChats
434377 (
@@ -504,7 +447,7 @@ getChatsQ lim dir = select (
504447 (ifThenElse
505448 (#messageStorageAuthorId .== param @1)
506449 #messageStorageDestinationUserId
507− #messageStorageAuthorId) `as` #messageUserId) $
450+ (notNull #messageStorageAuthorId)) `as` #messageUserId) $
508451 from (table #messages) &
509452 where_ (isNotNull #messageStorageDestinationUserId .&&
510453 (#messageStorageAuthorId .== param @1 .||
@@ -571,83 +514,21 @@ getGroupChatForUserQ = selectStar $
571514getFacultySearchResultQ :: Query Schema (TuplePG (Only Text)) (RowPG Faculty)
572515getFacultySearchResultQ = selectStar (from (table #faculties) &
573516 where_ (vector @@ query) &
574− orderBy [
575− tsRankCd vector1 query & Desc,
576− tsRankCd vector2 query & Desc,
577− tsRankCd vector query & Desc
578− ])
517+ orderBy [tsRankCd vector query & Desc])
579518 where
580519 vector = tsVector "russian" (textArrayToText [
581520 #facultyName,
582521 #facultyPath,
583522 #facultyCampusName,
584523 (arrayToText #facultyTags)])
585− vector1 = tsVector "russian" #facultyName
586− vector2 = tsVector "russian" (textArrayToText [
587− #facultyName,
588− #facultyPath])
589524 query = tsQuery "russian" (param @1)
590525
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] &
613− limit 100)
614− where
615− vector = tsVector' (textArrayToText [
616− #users ! #userRowFirstName,
617− #users ! #userRowMiddleName,
618− #users ! #userRowLastName
619− ])
620− query = tsQuery' (param @1)
621−
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) &
626− groupBy #fromOnly)
627−
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] &
632− limit lim)
633−
634−
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] &
640− limit 100
641− where
642− query = tsQuery' (param @1)
643− vector = tsVector' #tag
644−
645526tsRankCd
646527 :: Expression schema from grouping params ('NotNull 'PGtext)
647528 -> Expression schema from grouping params ('NotNull 'PGtext)
648529 -> Expression schema from grouping params ('NotNull 'PGfloat4)
649530tsRankCd vector query = UnsafeExpression $
650− "ts_rank_cd" <> parenthesized (commaSeparated ["ARRAY[1,1,1,1]", renderExpression vector, renderExpression query, "2|4|8|16|32"])
531+ "ts_rank_cd" <> parenthesized (commaSeparated . map renderExpression $ [vector, query])
651532
652533tsVector
653534 :: ByteString -- ^ Language
@@ -656,12 +537,6 @@ tsVector
656537tsVector lang x = UnsafeExpression $
657538 "to_tsvector" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
658539
659−tsVector'
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)
664−
665540tsQuery
666541 :: ByteString -- ^ Language
667542 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -669,12 +544,6 @@ tsQuery
669544tsQuery lang x = UnsafeExpression $
670545 "to_tsquery" <> parenthesized (commaSeparated [singleQuotedUtf8 lang, renderExpression x])
671546
672−tsQuery'
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)
677−
678547arrayToText
679548 :: Expression schema from grouping params ('NotNull ('PGvararray ('NotNull 'PGtext)))
680549 -> Expression schema from grouping params ('NotNull 'PGtext)
@@ -762,42 +631,20 @@ getTokenActivationQ = selectStar (from (table #tokens) &
762631 where_ (#tokenUserId .== param @1 .&&
763632 #tokenActivationCode .== param @2))
764633
765−deactivateTokenQ :: Manipulation Schema (TuplePG (UserId, ByteString)) (RowPG (Only Text))
634+deactivateTokenQ :: Manipulation Schema (TuplePG (UserId, ByteString)) (RowPG (Only UserId))
766635deactivateTokenQ = deleteFrom #tokens
767636 (#tokenUserId .== param @1 .&&
768637 #tokenDeactivationCode .== param @2)
769− (Returning (#tokenUserAgent `as` #fromOnly))
638+ (Returning (#tokenUserId `as` #fromOnly))
770639
771640getVerifiedTokenQ :: Query Schema (TuplePG (UserId, ByteString)) (RowPG Token)
772641getVerifiedTokenQ = selectStar (from (table #tokens) &
773642 where_ (#tokenUserId .== param @1 .&&
774643 #tokenValue .== param @2 .&&
775− isNull #tokenVerificationCode .&&
776− currentTimestamp .< #tokenExpiryDate))
777−
778−killAllTokensQ :: Manipulation Schema (TuplePG (Only UserId)) '[]
779−killAllTokensQ = deleteFrom_ #tokens
780− (#tokenUserId .== param @1)
781−
782−pruneDeadTokensQ :: Manipulation Schema '[] '[]
783−pruneDeadTokensQ = deleteFrom_ #tokens
784− (#tokenExpiryDate .< currentTimestamp)
785−
786−pruneGhostUsersQ :: Manipulation Schema '[] '[]
787−pruneGhostUsersQ = deleteFrom_ #users
788− ((not_ . in_ #userRowId $ select (#tokens ! #tokenUserId `as` #id) (from $ table #tokens)) .&&
789− (not_ . notNull $ #userRowIsValidated))
644+ isNull #tokenVerificationCode))
790645
791646-- MARK: FrontEnd Data Structures
792647
793−instance HasValidatableText UserCreation where
794− validateText UserCreation{..} = all validateText [
795− userCreationFirstName,
796− userCreationMiddleName,
797− userCreationLastName,
798− userCreationUserFaculty,
799− userCreationUserEmail]
800−
801648data UserCreation = UserCreation {
802649 userCreationFirstName :: Text,
803650 userCreationMiddleName :: Text,
@@ -816,18 +663,9 @@ instance ToJSON UserCreation where
816663 ]
817664
818665instance FromJSON UserCreation where
819− parseJSON = withObject "user creation" $ \e ->
666+ parseJSON = withObject "named channel" $ \e ->
820667 UserCreation <$> e .: "firstName" <*> e .: "middleName" <*> e .: "lastName" <*> e .: "faculty" <*> e .: "email"
821668
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)
829−
830−
831669data NamedChannelCreation = NamedChannelCreation {
832670 namedChannelCreationOwner :: UserId,
833671 namedChannelCreationName :: Text,
@@ -863,13 +701,11 @@ getChannelForUser uId cId = do
863701 Nothing -> lift $ S.throwError S.err404
864702
865703-- TODO: Reject bad requests. Should be binary.
866−verifyUsers :: [UserId] -> StaticPQ ()
867−verifyUsers uIds =
704+verifiedUsers :: [UserId] -> StaticPQ [UserId]
705+verifiedUsers uIds =
868706 case verifiedUserIdsQ uIds of
869− Just uIdsQ -> do
870− (us :: [UserId]) <- fmap fromOnly <$> (runQuery uIdsQ >>= getRows)
871− when (length us /= length uIds) $ lift $ S.throwError impossibleContent
872− Nothing -> return ()
707+ Just uIdsQ -> fmap fromOnly <$> (runQuery uIdsQ >>= getRows)
708+ Nothing -> return []
873709
874710deleteGroupChat :: GroupChatId -> StaticPQ ()
875711deleteGroupChat gId = do
@@ -931,40 +767,30 @@ getAllUsers :: StaticPQ [User Faculty]
931767getAllUsers = fmap rowToUser <$> (runQuery getAllUsersQ >>= getRows)
932768
933769publishPost :: UserId -> PostCreation -> StaticPQ PostId
934−publishPost uId pc = commitedTransactionallyUpdate $ do
770+publishPost uId pc = commitedTransactionallyUpdate $ do
935771 pId' <- manipulateParams createPostRowQ (uId, postCreationTags pc) >>= firstRow
936772 case pId' of
937773 (Just (Only pId)) -> do
938− traversePrepared_ createPostElementRowsQ $ elementsToRows pId (map stripPostElement $ postCreationBody pc)
774+ traversePrepared_ createPostElementRowsQ $ elementsToRows pId (postCreationBody pc)
939775 return pId
940776 _ -> lift $ S.throwError S.err404
941777
942778createNewChannel :: UserId -> NamedChannelCreationRequest -> StaticPQ (Maybe NamedChannelId)
943779createNewChannel uId req = commitedTransactionallyUpdate $ do
944− let uIds = toList $ namedChannelCreationRequestPeopleIds req
945− verifyUsers uIds
780+ uIds <- verifiedUsers . toList $ namedChannelCreationRequestPeopleIds req
946781 cId <- manipulateParams createNamedChannelQ (addUserToChannelCreate uId (req {namedChannelCreationRequestPeopleIds = fromList uIds})) >>= firstRow
947782 return $ fmap fromOnly cId
948783
949−channelCountForUser :: UserId -> StaticPQ Int64
950−channelCountForUser uId = (fromMaybe 0 . fmap fromOnly) <$> (runQueryParams countChannelsQ (Only uId) >>= firstRow)
951−
952784updateChannel :: UserId -> NamedChannel UserId -> StaticPQ ()
953−updateChannel uId req = do
954− let uIds = namedChannelPeopleIds req
955− verifyUsers (toList uIds)
785+updateChannel uId req = commitedTransactionallyUpdate $ do
786+ uIds <- fmap fromList . verifiedUsers . toList $ namedChannelPeopleIds req
956787 _ <- getChannelForUser uId $ namedChannelId req
957− _ <- commitedTransactionallyUpdate $ manipulateParams updateNamedChannelQ $ addUserToChannelUpdate uId (req {namedChannelPeopleIds = uIds})
788+ _ <- manipulateParams updateNamedChannelQ $ addUserToChannelUpdate uId (req {namedChannelPeopleIds = uIds})
958789 return ()
959790
960791getFaculty :: Text -> StaticPQ Faculty
961792getFaculty t = runQueryParams getFacultyQ (Only t) >>= firstRow >>= fromMaybe404
962793
963−isValidFaculty :: FacultyUrl -> StaticPQ Bool
964−isValidFaculty url = do
965− (faculty :: Maybe Faculty) <- runQueryParams getFacultyQ (Only url) >>= firstRow
966− return $ isJust faculty
967−
968794updateFaculty :: Faculty -> StaticPQ ()
969795updateFaculty fac = void $ manipulateParams updateFacultyQ fac
970796
@@ -1001,13 +827,13 @@ getAllChannels uId = fmap (map removeUserFromChannel) $
1001827 runQueryParams getAllChannelsForUserQ (Only uId) >>= getRows
1002828
1003829deleteNamedChannel :: UserId -> NamedChannelId -> StaticPQ ()
1004−deleteNamedChannel uId cId = do
830+deleteNamedChannel uId cId = commitedTransactionallyUpdate $ do
1005831 _ <- getChannelForUser uId cId
1006− _ <- commitedTransactionallyUpdate $ manipulateParams deleteNamedChannelQ (Only cId)
832+ _ <- manipulateParams deleteNamedChannelQ (Only cId)
1007833 return ()
1008834
1009−getTags :: Limit -> StaticPQ [String]
1010−getTags lim = map fromOnly <$> (runQuery (getNpopularTagsQ lim) >>= getRows)
835+getTags :: StaticPQ [String]
836+getTags = map fromOnly <$> (runQuery getTagsQ >>= getRows)
1011837
1012838getDialogs
1013839 :: UserId
@@ -1040,40 +866,36 @@ getMessagesInGroupChat
1040866getMessagesInGroupChat selfId gId mId lim dir = do
1041867 _ <- getGroupChatForUser selfId gId
1042868 resp <- runQueryParams (getGroupMessagesQ lim dir) (gId, mId) >>= getRows
1043− return . catMaybes . map restoreMessage $ resp
869+ (return . sequence . map restoreMessage $ resp) >>= fromMaybe500
1044870
1045871sendMessage :: UserId -> MessageCreation -> StaticPQ MessageId
1046−sendMessage selfId (MessageCreation (Just gId) uId@Nothing (Jsonb body)) = do
872+sendMessage selfId (MessageCreation (Just gId) uId@Nothing body) = do
1047873 _ <- getGroupChatForUser selfId gId
1048− (Only mId) <- manipulateParams createMessageQ (selfId, Just gId, uId, Jsonb $ stripPostElement body)
874+ (Only mId) <- manipulateParams createMessageQ (selfId, Just gId, uId, body)
1049875 >>= firstRow >>= fromMaybe500
1050876 return mId
1051−sendMessage selfId (MessageCreation gId@Nothing (Just uId) (Jsonb body)) = do
1052− verifyUsers [uId]
1053− (Only mId) <- manipulateParams createMessageQ (selfId, gId, Just uId, Jsonb $ stripPostElement body)
877+sendMessage selfId (MessageCreation gId@Nothing (Just uId) body) = do
878+ (Only mId) <- manipulateParams createMessageQ (selfId, gId, Just uId, body)
1054879 >>= firstRow >>= fromMaybe500
1055880 return mId
1056881sendMessage _ _ = lift $ S.throwError S.err400
1057882
1058883createGroupChat :: UserId -> GroupChatCreation -> StaticPQ GroupChatId
1059884createGroupChat uId (GroupChatCreation (Jsonb chatUsers) name) = do
1060− verifyUsers . M.keys $ chatUsers
1061− commitedTransactionallyUpdate $ do
1062− let chatUsers' = M.insert uId maxChatPermissions chatUsers
1063− (Only chatId) <- manipulateParams createGroupChatQ (GroupChatCreation (Jsonb chatUsers') name)
1064− >>= firstRow >>= fromMaybe500
1065− _ <- manipulateParams createPhantomMessageQ (Only chatId)
1066− return chatId
885+ let chatUsers' = M.insert uId maxChatPermissions chatUsers
886+ (Only chatId) <- manipulateParams createGroupChatQ (GroupChatCreation (Jsonb chatUsers') name)
887+ >>= firstRow >>= fromMaybe500
888+ -- TODO: Do somehting with this
889+ _ <- sendMessage uId $ MessageCreation (Just chatId) Nothing (Jsonb $ Markdown "henlo")
890+ return chatId
1067891
1068892updateGroupChat :: UserId -> GroupChat -> StaticPQ ()
1069−updateGroupChat uId (GroupChat gId (Jsonb perms) name) = do
1070− verifyUsers . M.keys $ perms
1071− commitedTransactionallyUpdate $ do
1072− (GroupChat _ (Jsonb perms') _) <- getGroupChatForUser uId gId
1073− let userPerm = fromMaybe minChatPermissions $ M.lookup uId perms'
1074− unless (isAdmin userPerm) $ lift $ S.throwError $ S.err401
1075− let newPerms = M.insert uId userPerm perms
1076− void $ manipulateParams updateGroupChatQ (GroupChat gId (Jsonb newPerms) name)
893+updateGroupChat uId (GroupChat gId (Jsonb perms) name) = commitedTransactionallyUpdate $ do
894+ (GroupChat _ (Jsonb perms') _) <- getGroupChatForUser uId gId
895+ let userPerm = fromMaybe minChatPermissions $ M.lookup uId perms'
896+ unless (isAdmin userPerm) $ lift $ S.throwError $ S.err401
897+ let newPerms = M.insert uId userPerm perms
898+ void $ manipulateParams updateGroupChatQ (GroupChat gId (Jsonb newPerms) name)
1077899
1078900leaveGroupChat :: UserId -> GroupChatId -> StaticPQ ()
1079901leaveGroupChat uId gId = commitedTransactionallyUpdate $ do
@@ -1090,43 +912,13 @@ getGroupChatForUser uId gId = do
1090912 (Just c) -> return c
1091913 Nothing -> lift $ S.throwError S.err404
1092914
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
1097−
1098915getFacultyFromQuery :: T.Text -> StaticPQ [Faculty]
1099916getFacultyFromQuery query =
1100− runQueryParams getFacultySearchResultQ (Only . queryFromTextAbbr $ query) >>= getRows
1101−
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)
1106− then return []
1107− else map rowToUser <$> (runQueryParams searchUsersQ (Only . queryFromText $ query) >>= getRows)
1108−
1109−searchTags :: T.Text -> StaticPQ [Text]
1110−searchTags "" = return []
1111−searchTags query = map fromOnly <$>
1112− (runQueryParams searchTagsQ
1113− (Only . (<> ":*") . T.strip $ query) >>= getRows)
917+ runQueryParams getFacultySearchResultQ (Only . queryFromText $ query) >>= getRows
1114918
1115919createToken :: Token -> StaticPQ ()
1116920createToken token = void $ manipulateParams createTokenQ token
1117921
1118−killAllTokens :: UserId -> StaticPQ ()
1119−killAllTokens = void . manipulateParams killAllTokensQ . Only
1120−
1121−pruneAuth :: StaticPQ ()
1122−pruneAuth = do
1123− _ <- commitedTransactionallyUpdate . manipulate $ pruneDeadTokensQ
1124− _ <- commitedTransactionallyUpdate . manipulate $ pruneGhostUsersQ
1125− return ()
1126−
1127−searchChannels :: UserId -> Text -> StaticPQ [NamedChannel UserId]
1128−searchChannels uId query = fmap (map removeUserFromChannel) $
1129− runQueryParams searchChannelsForUserQ (uId, queryFromText query) >>= getRows
1130922
1131923-- NOTE: Not transactional
1132924validateToken :: Token -> StaticPQ ()
@@ -1154,7 +946,7 @@ tryVerifyToken uId tokenData code = commitedTransactionallyUpdate $ do
1154946 _ <- manipulateParams updateTokenQ newToken
1155947 return Nothing
1156948
1157−tryActivateToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
949+tryActivateToken :: UserId -> ByteString -> StaticPQ (Maybe ByteString)
1158950tryActivateToken uId activationData = do
1159951 let hData = hash activationData
1160952 token' <- runQueryParams getTokenActivationQ (uId, hData) >>= firstRow
@@ -1162,29 +954,19 @@ tryActivateToken uId activationData = do
1162954 Nothing -> return Nothing
1163955 Just token -> do
1164956 if (tokenActivationCode token == Just hData)
1165− then commitedTransactionallyUpdate (validateToken token) >> (return $ Just token)
957+ then commitedTransactionallyUpdate (validateToken token) >> return (Just $ tokenValue token)
1166958 else return Nothing
1167959
1168−deactivateToken :: UserId -> ByteString -> StaticPQ (Maybe Text)
1169−deactivateToken uId dData = fmap fromOnly <$> (manipulateParams deactivateTokenQ (uId, hash dData) >>= firstRow)
960+deactivateToken :: UserId -> ByteString -> StaticPQ Bool
961+deactivateToken uId dData = do
962+ res <- manipulateParams deactivateTokenQ (uId, hash dData) >>= firstRow
963+ return $ isJust (res :: Maybe (Only UserId))
1170964
1171965getVerifiedToken :: UserId -> ByteString -> StaticPQ (Maybe Token)
1172966getVerifiedToken uId tokenData = runQueryParams getVerifiedTokenQ (uId, hash tokenData) >>= firstRow
1173967
1174−updateUser :: (UserUpdateRow) -> StaticPQ (Maybe UserId)
1175−updateUser user = fmap fromOnly <$> (manipulateParams updateUserQ (normalizeUser user) >>= firstRow)
1176−
1177968-- MARK: Utils
1178969
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
1186−}
1187−
1188970data UserRow = UserRow {
1189971 userRowId :: UserId,
1190972 userRowFirstName :: Text,
@@ -1220,8 +1002,8 @@ rowToUser UserRow{..} = User {
12201002 userEmail = userRowEmail
12211003 }
12221004
1223−queryFromTextAbbr :: Text -> Text
1224−queryFromTextAbbr = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isAlphaNum)
1005+queryFromText :: Text -> Text
1006+queryFromText = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isAlphaNum)
12251007 where
12261008 processTerm :: Text -> Text
12271009 processTerm t = "(" <> t <> ":*" <> (
@@ -1230,12 +1012,6 @@ queryFromTextAbbr = T.unwords . L.intersperse "&" . map processTerm . filter (no
12301012 else mempty
12311013 ) <> ")"
12321014
1233−queryFromText :: Text -> Text
1234−queryFromText = T.unwords . L.intersperse "&" . map processTerm . filter (not . T.null) . T.split (not . isPrint)
1235− where
1236− processTerm :: Text -> Text
1237− processTerm t = t <> ":*"
1238−
12391015directionToOperator
12401016 :: P.PaginationDirection
12411017 -> (ConditionOp schema0 from0 grouping0 params0 nullity0 nullity1 (ty :: PGType),