diff --git a/phone/src/apps/twitter/components/AddTweetStatus.js b/phone/src/apps/twitter/components/AddTweetStatus.js index 501e24d..20b44f7 100644 --- a/phone/src/apps/twitter/components/AddTweetStatus.js +++ b/phone/src/apps/twitter/components/AddTweetStatus.js @@ -10,8 +10,6 @@ function AddTweetStatus() { const { isSuccessful } = useTweetStatus(); const { t } = useTranslation(); - console.log(isSuccessful); - // on the "true" case the tweet was created and the user should // see their tweet at the top of the list, so there's no need // to directly prompt them that it was successful. diff --git a/phone/src/apps/twitter/components/TweetList.js b/phone/src/apps/twitter/components/TweetList.js index 4e290a9..6b4ad94 100644 --- a/phone/src/apps/twitter/components/TweetList.js +++ b/phone/src/apps/twitter/components/TweetList.js @@ -5,11 +5,10 @@ import { List } from "../../../ui/components/List"; import { useTweets } from "../hooks/useTweets"; import Tweet from "./Tweet"; -const TWEETS_REFRESH_RATE = 5000; // TODO move this to twitter config +const TWEETS_REFRESH_RATE = 50000000; // TODO move this to twitter config export function TweetList() { const { tweets } = useTweets(); - console.log(tweets); useEffect(() => { Nui.send("phone:fetchTweets", {}); diff --git a/phone/src/apps/twitter/components/TwitterApp.js b/phone/src/apps/twitter/components/TwitterApp.js index 96630b8..ac73464 100644 --- a/phone/src/apps/twitter/components/TwitterApp.js +++ b/phone/src/apps/twitter/components/TwitterApp.js @@ -1,12 +1,15 @@ -import React, { useState, useCallback } from "react"; +import React, { useState, useCallback, useEffect } from "react"; import { blue } from "@material-ui/core/colors"; import { makeStyles, Button } from "@material-ui/core"; import AddCircleIcon from "@material-ui/icons/AddCircle"; + +import Nui from "../../../os/nui-events/utils/Nui"; import { AppTitle } from "../../../ui/components/AppTitle"; import { AppWrapper } from "../../../ui/components"; import { AppContent } from "../../../ui/components/AppContent"; +import { AppLoader } from "../../../ui/components/AppLoader"; import { useApp } from "../../../os/apps/hooks/useApps"; - +import { useProfile } from "../hooks/useProfile"; import TweetList from "./TweetList"; import AddTweetModal from "./AddTweetModal"; @@ -25,13 +28,33 @@ const useStyles = makeStyles((theme) => ({ }, })); +const MINIMUM_LOAD_TIME = 750; + export const TwitterApp = () => { const [modalVisible, setModalVisible] = useState(false); + const [minimumLoadPassed, setMimimumLoadPassed] = useState(false); const classes = useStyles(); const twitter = useApp("TWITTER"); + const { profile } = useProfile(); - const openModal = useCallback(() => setModalVisible(true), []); - const hideModal = useCallback(() => setModalVisible(false), []); + useEffect(() => { + Nui.send("phone:getOrCreateTwitterProfile", {}); + }, []); + + useEffect(() => { + const timeout = window.setTimeout(() => { + setMimimumLoadPassed(true); + }, MINIMUM_LOAD_TIME); + return () => window.clearTimeout(timeout); + }); + + const openModal = () => setModalVisible(true); + const hideModal = () => setModalVisible(false); + + // we add a minimum (but short) load time here so that + // there isn't a quick flash of loading and immediately + // another flash to the tweets screen. + const hasLoaded = profile && minimumLoadPassed; return ( @@ -44,8 +67,14 @@ export const TwitterApp = () => { - - + {hasLoaded ? ( + <> + + + + ) : ( + + )} ); diff --git a/phone/src/apps/twitter/hooks/state.js b/phone/src/apps/twitter/hooks/state.js index e660759..afb81ee 100644 --- a/phone/src/apps/twitter/hooks/state.js +++ b/phone/src/apps/twitter/hooks/state.js @@ -1,6 +1,10 @@ import { atom } from "recoil"; export const twitterState = { + profile: atom({ + key: "profile", + default: null, + }), tweets: atom({ key: "tweets", default: [], diff --git a/phone/src/apps/twitter/hooks/useProfile.js b/phone/src/apps/twitter/hooks/useProfile.js new file mode 100644 index 0000000..234977a --- /dev/null +++ b/phone/src/apps/twitter/hooks/useProfile.js @@ -0,0 +1,7 @@ +import { useRecoilValue } from "recoil"; +import { twitterState } from "./state"; + +export const useProfile = () => { + const profile = useRecoilValue(twitterState.profile); + return { profile }; +}; diff --git a/phone/src/apps/twitter/hooks/useTwitterService.js b/phone/src/apps/twitter/hooks/useTwitterService.js index 46c94e2..09a5e6a 100644 --- a/phone/src/apps/twitter/hooks/useTwitterService.js +++ b/phone/src/apps/twitter/hooks/useTwitterService.js @@ -16,18 +16,28 @@ function processTweet(tweet) { // we store images in the database as a varchar field with // comma separated links to images, so here we split them // back into their distinct members - console.log(tweet); const imageLinks = tweet.images ? tweet.images.split(IMAGE_DELIMITER) : []; - console.log(imageLinks); const images = imageLinks.map((link) => ({ id: uuidv4(), link })); return { ...tweet, images }; } +/** + * Service to handle all NUI <> client interactions. We take + * this opportunity to act as a middleware layer between the + * client and the react components. Because I'm terrible with lua + * I have given up on parsing/cleaning database query results there + * there and have moved that logic here instead. + */ export const useTwitterService = () => { + const setProfile = useSetRecoilState(twitterState.profile); const setTweets = useSetRecoilState(twitterState.tweets); const setCreateLoading = useSetRecoilState(twitterState.createTweetLoading); const setCreateSuccess = useSetRecoilState(twitterState.createTweetSuccess); + const _setProfile = (profile) => { + setProfile(profile[0]); // server returns an array of 1 profile + }; + const _setCreateSuccess = (isSuccessful) => { setCreateSuccess(isSuccessful === 1); // numeric 1 is returned by MySQL on successful query setCreateLoading(false); // on any result we should set loading to false @@ -37,9 +47,8 @@ export const useTwitterService = () => { setTweets(tweets.map(processTweet)); }; + useNuiEvent(types.APP_TWITTER, "getOrCreateTwitterProfile", _setProfile); useNuiEvent(types.APP_TWITTER, "fetchTweets", _setTweets); useNuiEvent(types.APP_TWITTER, "createTweetLoading", setCreateLoading); useNuiEvent(types.APP_TWITTER, "createTweetResult", _setCreateSuccess); - - return useTweets(); }; diff --git a/phone/src/os/nui-events/hooks/useNuiEvent.js b/phone/src/os/nui-events/hooks/useNuiEvent.js index 0d5469b..f56b73d 100644 --- a/phone/src/os/nui-events/hooks/useNuiEvent.js +++ b/phone/src/os/nui-events/hooks/useNuiEvent.js @@ -10,14 +10,15 @@ export const useNuiEvent = (app, method, handler, options = {}) => { }, [handler]); useEffect(() => { + const eventName = eventNameFactory(app, method); const eventListener = (event) => { if (savedHandler.current && savedHandler.current.call) { const { data } = event; + console.log(eventName, data); savedHandler.current(data); } }; const opts = { capture, passive, once }; - const eventName = eventNameFactory(app, method); window.addEventListener(eventName, eventListener, opts); return () => window.removeEventListener(eventName, eventListener, opts); }, [app, method, capture, passive, once]); diff --git a/phone/src/ui/components/AppLoader.js b/phone/src/ui/components/AppLoader.js new file mode 100644 index 0000000..287c171 --- /dev/null +++ b/phone/src/ui/components/AppLoader.js @@ -0,0 +1,27 @@ +// intended for use on initial application loads +import React from "react"; +import { makeStyles, CircularProgress } from "@material-ui/core"; + +const useStyles = makeStyles((theme) => ({ + root: { + height: "400px", + width: "100%", + display: "flex", + flexFlow: "row nowrap", + justifyContent: "center", + alignItems: "center", + }, + progress: { + color: "white", + }, +})); + +export const AppLoader = () => { + const classes = useStyles(); + + return ( +
+ +
+ ); +}; diff --git a/resources/client/cl_twitter.lua b/resources/client/cl_twitter.lua index b591363..2fbb95d 100644 --- a/resources/client/cl_twitter.lua +++ b/resources/client/cl_twitter.lua @@ -9,7 +9,6 @@ end) local APP_NAME = 'TWITTER' - function sendMessage(method, data) SendNUIMessage( { @@ -40,3 +39,10 @@ RegisterNUICallback('phone:createTweet', function(data) TriggerEvent('phone:fetchTweets') end, data) end) + +RegisterNUICallback('phone:getOrCreateTwitterProfile', function() + print('phone:getOrCreateTwitterProfile') + ESX.TriggerServerCallback('phone:getOrCreateTwitterProfile', function(profile) + sendMessage('getOrCreateTwitterProfile', profile) + end) +end) diff --git a/resources/server/sv_twitter.lua b/resources/server/sv_twitter.lua index ba6a57c..5f93053 100644 --- a/resources/server/sv_twitter.lua +++ b/resources/server/sv_twitter.lua @@ -1,11 +1,16 @@ ESX = nil +function printO(o) + for key, value in pairs(o) do + print(key, value) + end +end + TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) ESX.RegisterServerCallback('phone:fetchTweets', function(source, cb) - print('RegisterServerCallback: phone:fetchTweets') local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local _identifier = xPlayer.getIdentifier() @@ -16,7 +21,6 @@ end) ESX.RegisterServerCallback('phone:createTweet', function(source, cb, data) - print('RegisterServerEvent: phone:createTweet') local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local _identifier = xPlayer.getIdentifier() @@ -31,3 +35,72 @@ ESX.RegisterServerCallback('phone:createTweet', function(source, cb, data) cb(result) end) end) + +function getProfile(identifier, cb) + MySQL.Async.fetchAll('SELECT * FROM npwd_twitter_profiles WHERE identifier = @identifier', + { + ['identifier'] = identifier, + }, function(result) + cb(result) + end) +end + +function getProfileName(identifier, cb) + local defaultProfileName = '' -- handle any edge cases where the user does not exist or their name isn't populated + MySQL.Async.fetchAll('SELECT first_name, last_name FROM users WHERE identifier = @identifier LIMIT 1', {['identifier'] = identifier }, function(users) + -- no user found with this identifier + if next(users) == nil then + cb(defaultProfileName) + return + end + + local first_name = users[1].first_name + local last_name = users[1].last_name + if (first_name == "" and last_name == "") then + cb(defaultProfileName) + else + local profileName = first_name .. '_' .. last_name + cb(profileName) + end + end) +end + +function createDefaultProfile(identifier, cb) + getProfileName(identifier, function(profileName) + MySQL.Async.execute('INSERT INTO npwd_twitter_profiles (`identifier`, `profile_name`) VALUES (@identifier, @profile_name)', + { + ['identifier'] = identifier, + ['profile_name'] = profileName, + }, function(result) + if result == 1 then -- if we created the profile then return it + getProfile(identifier, cb) + else -- otherwise just give back the failed result + cb(result) + end + end) + end) +end + +-- Retrieve a twitter profile by identifier. If it does not exist then +-- create and return it +function getOrCreateProfile(identifier, cb) + getProfile(identifier, function(retrieveResult) + if next(retrieveResult) == nil then -- profile does not exist, attempt to create it + createDefaultProfile(identifier, function(createResult) + cb(createResult) + end) + else -- profile does exist + cb(retrieveResult) + end + end) +end + +ESX.RegisterServerCallback('phone:getOrCreateTwitterProfile', function(source, cb) + local _source = source + local xPlayer = ESX.GetPlayerFromId(_source) + local _identifier = xPlayer.getIdentifier() + + getOrCreateProfile(_identifier, function(result) + cb(result) + end) +end)