diff --git a/config.json b/config.json
index 7e97a4a..18697d0 100644
--- a/config.json
+++ b/config.json
@@ -27,6 +27,10 @@
"enableImages": true,
"maxImages": 3
},
+ "match": {
+ "generateProfileNameFromUsers": true,
+ "allowEdtiableProfileName": true
+ },
"bank": {
"showNotifications": true
},
diff --git a/import.sql b/import.sql
index 97f6b72..4754cfb 100644
--- a/import.sql
+++ b/import.sql
@@ -54,6 +54,33 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
CONSTRAINT `tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
);
+CREATE TABLE IF NOT EXISTS `npwd_match_profiles` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `identifier` varchar(255) NOT NULL,
+ `name` varchar(90) NOT NULL,
+ `image` varchar(255) NOT NULL,
+ `bio` varchar(512) DEFAULT NULL,
+ `location` varchar(45) DEFAULT NULL,
+ `job` varchar(45) DEFAULT NULL,
+ `tags` varchar(255) NOT NULL DEFAULT '',
+ `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `name_UNIQUE` (`name`),
+ UNIQUE KEY `identifier_UNIQUE` (`identifier`)
+) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+CREATE TABLE IF NOT EXISTS `npwd_match_views` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `identifier` varchar(40) NOT NULL,
+ `profile` int NOT NULL,
+ `liked` tinyint DEFAULT '0',
+ `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ KEY `match_profile_idx` (`profile`),
+ CONSTRAINT `match_profile` FOREIGN KEY (`profile`) REFERENCES `npwd_match_profiles` (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=131 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS npwd_notes (
id int(11) NOT NULL AUTO_INCREMENT,
diff --git a/phone/src/Phone.tsx b/phone/src/Phone.tsx
index 8b94452..bbedc87 100644
--- a/phone/src/Phone.tsx
+++ b/phone/src/Phone.tsx
@@ -15,6 +15,7 @@ import { useApps } from './os/apps/hooks/useApps';
import { useContactsService } from './apps/contacts/hooks/useContactsService';
import { useTwitterService } from './apps/twitter/hooks/useTwitterService';
+import { useMatchService } from './apps/match/hooks/useMatchService';
import { useSelloutService } from './apps/sellout/hooks/useSelloutService';
import { useBankService } from './apps/bank/hooks/useBankService';
import { useMessagesService } from './apps/messages/hooks/useMessageService';
@@ -66,6 +67,7 @@ function Phone() {
useSimcardService();
useContactsService();
useTwitterService();
+ useMatchService();
useSelloutService();
useBankService();
useMessagesService();
diff --git a/phone/src/apps/match/components/ActiveProfile.tsx b/phone/src/apps/match/components/ActiveProfile.tsx
new file mode 100644
index 0000000..27ac327
--- /dev/null
+++ b/phone/src/apps/match/components/ActiveProfile.tsx
@@ -0,0 +1,163 @@
+import React, { useState, useRef } from 'react';
+import { Card, Fab, Box, Tooltip } from '@material-ui/core';
+import CancelIcon from '@material-ui/icons/Clear';
+import FireIcon from '@material-ui/icons/Whatshot';
+import { makeStyles } from '@material-ui/core/styles';
+import { useTranslation } from 'react-i18next';
+
+import { FormattedProfile } from '../../../../../typings/match';
+import Draggable from './Draggable';
+import StatusDisplay from './StatusDisplay';
+import Profile from './profile/Profile';
+
+const useStyles = makeStyles({
+ root: {
+ position: 'absolute',
+ margin: '15px 15px 25px 15px',
+ height: 'calc(100% - 90px)',
+ width: 'calc(100% - 30px)',
+ overflow: 'hidden',
+ cursor: 'pointer',
+ },
+ media: {
+ height: '60%',
+ },
+ content: {
+ height: '40%',
+ },
+ status: {
+ position: 'absolute',
+ zIndex: 20,
+ padding: '5px 15px',
+ top: 40,
+ fontSize: '28px',
+ fontWeight: 'bold',
+ },
+ statusVisible: {
+ transition: 'opacity 0.25s ease-in-out',
+ },
+ // when a user swipes on a profile we need to hide the transition
+ // otherwise the status will be transitioning out when the next
+ // profile shows up
+ statusNull: {
+ transition: 'opacity 0s',
+ },
+ like: {
+ color: 'green',
+ border: '6px solid green',
+ left: 30,
+ transform: 'rotate(-18deg)',
+ },
+ nope: {
+ color: 'red',
+ border: '6px solid red',
+ right: 30,
+ transform: 'rotate(18deg)',
+ },
+ buttons: {
+ position: 'absolute',
+ bottom: '3px',
+ width: '100%',
+ height: '55px',
+ },
+ button: {
+ margin: '0px 15px',
+ },
+});
+
+interface IProps {
+ profile: FormattedProfile;
+ onSwipe: (id: number, liked: boolean) => void;
+}
+
+// this represents how far from the original mouse
+// click a user has to drag the profile in order for
+// it to be registered as a like or dislike
+const DECISION_THRESHOLD_X_px = 150;
+
+const ActiveProfile = ({ profile, onSwipe }: IProps) => {
+ const c = useStyles();
+ const { t } = useTranslation();
+ const [status, setStatus] = useState(null);
+ const statusRef = useRef(null);
+ const idRef = useRef(null);
+
+ // we are reading mutated state from the Draggable element so we
+ // keep track of it using a ref. Without this ref it will appear
+ // from React's point of view that the state is not updating
+ statusRef.current = status;
+ idRef.current = profile.id;
+
+ function onDrag(deltaX: number): void {
+ const hasDecision = status !== null;
+ if (!hasDecision && deltaX > DECISION_THRESHOLD_X_px) {
+ setStatus(true);
+ } else if (!hasDecision && deltaX < -DECISION_THRESHOLD_X_px) {
+ setStatus(false);
+ } else if (deltaX > -DECISION_THRESHOLD_X_px && deltaX < DECISION_THRESHOLD_X_px) {
+ setStatus(null);
+ }
+ }
+
+ // handles when user uses mouse to "swipe", or
+ // more specifically drag the card to one side or the other
+ const handleSwipe = () => {
+ onSwipe(idRef.current, statusRef.current);
+ setStatus(null);
+ };
+
+ // these handlers are explicit and used for when the
+ // user clicks on buttons
+ const handleLike = () => {
+ onSwipe(idRef.current, true);
+ setStatus(null);
+ };
+ const handleNope = () => {
+ onSwipe(idRef.current, false);
+ setStatus(null);
+ };
+
+ const isLiked = status === true;
+ const notLiked = status === false;
+
+ const likeClass = `${c.status} ${isLiked ? c.statusVisible : c.statusNull} ${c.like}`;
+ const nopeClass = `${c.status} ${notLiked ? c.statusVisible : c.statusNull} ${c.nope}`;
+
+ return (
+ <>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ >
+ );
+};
+
+export default ActiveProfile;
diff --git a/phone/src/apps/match/components/BottomNavigation.tsx b/phone/src/apps/match/components/BottomNavigation.tsx
new file mode 100644
index 0000000..70075b5
--- /dev/null
+++ b/phone/src/apps/match/components/BottomNavigation.tsx
@@ -0,0 +1,29 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { makeStyles } from '@material-ui/core/styles';
+import { BottomNavigation, BottomNavigationAction } from '@material-ui/core';
+import HomeIcon from '@material-ui/icons/Whatshot';
+import GroupIcon from '@material-ui/icons/Group';
+import ProfileIcon from '@material-ui/icons/Person';
+
+const useStyles = makeStyles({
+ root: {
+ width: '100%',
+ },
+});
+
+export function MatchBottomNavigation({ activePage, handleChange }) {
+ const classes = useStyles();
+
+ console.log(activePage);
+
+ return (
+
+ } />
+ } />
+ } />
+
+ );
+}
+
+export default MatchBottomNavigation;
diff --git a/phone/src/apps/match/components/Draggable.tsx b/phone/src/apps/match/components/Draggable.tsx
new file mode 100644
index 0000000..2300f4f
--- /dev/null
+++ b/phone/src/apps/match/components/Draggable.tsx
@@ -0,0 +1,61 @@
+import React, { useEffect, useRef } from 'react';
+import { makeStyles } from '@material-ui/core';
+
+import { LikeorDislikeDraggableElement } from '../utils/drag';
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ height: '100%',
+ width: '100%',
+ },
+ like: {
+ position: 'absolute',
+ zIndex: 20,
+ padding: '5px 15px',
+ top: 100,
+
+ color: 'green',
+ border: '4px solid green',
+ right: 15,
+ },
+ nope: {
+ position: 'absolute',
+ zIndex: 20,
+ padding: '5px 15px',
+ top: 100,
+
+ color: 'red',
+ border: '4px solid red',
+ left: 15,
+ },
+});
+
+interface IProps {
+ id: string;
+ children: JSX.Element | JSX.Element[];
+ onDrag: (deltaX: number) => void;
+ onDrop: () => void;
+}
+
+const MAX_ROTATION_DEG = 15;
+
+function Draggable({ id, children, onDrag, onDrop }: IProps) {
+ const classes = useStyles();
+ const elementRef = useRef(null);
+
+ useEffect(() => {
+ const drag = new LikeorDislikeDraggableElement(elementRef, MAX_ROTATION_DEG, onDrag, onDrop);
+ return () => drag.cleanup();
+ }, [elementRef]); // eslint-disable-line
+
+ return (
+ <>
+
+ {children}
+
+ >
+ );
+}
+
+export default Draggable;
diff --git a/phone/src/apps/match/components/Error.tsx b/phone/src/apps/match/components/Error.tsx
new file mode 100644
index 0000000..bb37d2e
--- /dev/null
+++ b/phone/src/apps/match/components/Error.tsx
@@ -0,0 +1,28 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { Box, Typography } from '@material-ui/core';
+import { makeStyles, Theme } from '@material-ui/core/styles';
+
+const useStyles = makeStyles((theme: Theme) => ({
+ root: {
+ color: theme.palette.primary.main,
+ fontSize: theme.typography.fontSize,
+ height: '100%',
+ width: '100%',
+ display: 'flex',
+ justifyContent: 'center',
+ paddingTop: '140px',
+ },
+}));
+
+function NoProfiles() {
+ const classes = useStyles();
+ const { t } = useTranslation();
+ return (
+
+ {t('APPS_MATCH_NO_PROFILES')}
+
+ );
+}
+
+export default NoProfiles;
diff --git a/phone/src/apps/match/components/Loader.tsx b/phone/src/apps/match/components/Loader.tsx
new file mode 100644
index 0000000..a592e7c
--- /dev/null
+++ b/phone/src/apps/match/components/Loader.tsx
@@ -0,0 +1,26 @@
+import React from 'react';
+import { Box, CircularProgress } from '@material-ui/core';
+import { makeStyles } from '@material-ui/core/styles';
+
+const useStyles = makeStyles({
+ root: {
+ height: '100%',
+ width: '100%',
+ display: 'flex',
+ justifyContent: 'center',
+ },
+ progress: {
+ marginTop: '140px',
+ },
+});
+
+function Loader() {
+ const classes = useStyles();
+ return (
+
+
+
+ );
+}
+
+export default Loader;
diff --git a/phone/src/apps/match/components/MatchApp.tsx b/phone/src/apps/match/components/MatchApp.tsx
new file mode 100644
index 0000000..82a83d8
--- /dev/null
+++ b/phone/src/apps/match/components/MatchApp.tsx
@@ -0,0 +1,158 @@
+import React, { useState, useEffect } from 'react';
+import { Route } from 'react-router-dom';
+
+import { AppWrapper } from '../../../ui/components';
+import { AppTitle } from '../../../ui/components/AppTitle';
+import { AppContent } from '../../../ui/components/AppContent';
+import { useApp } from '../../../os/apps/hooks/useApps';
+import InjectDebugData from '../../../os/debug/InjectDebugData';
+import { MatchThemeProvider } from '../providers/MatchThemeProvider';
+
+import Nui from '../../../os/nui-events/utils/Nui';
+import MatchBottomNavigation from '../components/BottomNavigation';
+import MatchPage from './views/MatchPage';
+import ProfileEditor from './views/ProfileEditor';
+import MatchList from './views/MatchList';
+import { MatchEvents } from '../../../../../typings/match';
+import { useProfile } from '../hooks/useProfile';
+
+export const MatchApp = () => {
+ const match = useApp('MATCH');
+ const [activePage, setActivePage] = useState(0);
+ const { noProfileExists } = useProfile();
+
+ useEffect(() => {
+ Nui.send(MatchEvents.INITIALIZE);
+ }, []);
+
+ const handlePageChange = (e, page) => setActivePage(page);
+
+ return (
+
+
+
+ {noProfileExists ? (
+
+
+
+ ) : (
+ <>
+
+
+
+
+
+
+ >
+ )}
+
+
+ );
+};
+
+InjectDebugData(
+ [
+ {
+ app: 'MATCH',
+ method: 'phone:getMatchProfilesSuccess',
+ data: [
+ {
+ id: 1,
+ image:
+ 'https://cdn.vox-cdn.com/thumbor/9xCALlkm2Mc0HQk8kMr1Ui3YNbc=/0x0:5464x3070/920x613/filters:focal(2295x1098:3169x1972):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/67031748/shutterstock_1450403549.0.jpg',
+ name: 'Person Alpha',
+ bio:
+ 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.',
+ createdAt: 1615932985,
+ updatedAt: 1615932985,
+ lastActive: 1616004986,
+ job: 'Gardener',
+ location: 'Grapeseed',
+ tags: 'gardening',
+ phoneNumber: '987-6543',
+ },
+ {
+ id: 2,
+ image:
+ 'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
+ name: 'Person Beta',
+ bio: 'l impedit quo minus id quod maxime placeat facere possimus',
+ createdAt: 1615846585,
+ updatedAt: 1615846585,
+ lastActive: 1615850185,
+ job: 'Mechanic',
+ location: 'Harmony',
+ tags: 'tinkering,robotics',
+ phoneNumber: '654-3219',
+ },
+ {
+ id: 3,
+ image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
+ name: 'Person Charlie',
+ bio: 'ut aut reiciendis voluptatibus',
+ createdAt: 1615850185,
+ updatedAt: 1615850185,
+ lastActive: 1613607385,
+ job: 'Lawyer',
+ location: 'Los Santos',
+ tags: 'reading,coolstuff, coffee',
+ phoneNumber: '123-4567',
+ },
+ ],
+ },
+ {
+ app: 'MATCH',
+ method: 'phone:getMyProfileSuccess',
+ data: {
+ id: 4,
+ image:
+ 'https://www.middlebury.edu/institute/sites/www.middlebury.edu.institute/files/styles/1040x585/public/2018-10/Nashville-skyline.jpg?fv=mS11EKrT&itok=HNhHqYUX',
+ name: 'Kire Says',
+ bio: "Kire's cool profile that has many cool things. And others.",
+ createdAt: 1615932985,
+ updatedAt: 1615932985,
+ lastActive: 1616004986,
+ job: 'Engineer',
+ location: 'Boston',
+ tags: 'code,books',
+ phoneNumber: '999-9999',
+ },
+ },
+ {
+ app: 'MATCH',
+ method: 'phone:getMatchesSuccess',
+ data: [
+ {
+ id: 5,
+ image:
+ 'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
+ name: 'Person Delta',
+ bio: 'l impedit quo minus id quod maxime placeat facere possimus',
+ createdAt: 1615846585,
+ updatedAt: 1615846585,
+ lastActive: 1615850185,
+ matchedAt: 1613607385,
+ job: 'Mechanic',
+ location: 'Harmony',
+ tags: 'tinkering,robotics',
+ phoneNumber: '654-3219',
+ },
+ {
+ id: 6,
+ image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
+ name: 'Person Echo',
+ bio: 'ut aut reiciendis voluptatibus',
+ createdAt: 1615850185,
+ updatedAt: 1615850185,
+ lastActive: 1613607385,
+ job: 'Lawyer',
+ location: 'Los Santos',
+ tags: 'reading,coolstuff, coffee',
+ phoneNumber: '123-4567',
+ matchedAt: 1613607385,
+ },
+ ],
+ },
+ ],
+ 200,
+);
diff --git a/phone/src/apps/match/components/PageText.tsx b/phone/src/apps/match/components/PageText.tsx
new file mode 100644
index 0000000..00d6f46
--- /dev/null
+++ b/phone/src/apps/match/components/PageText.tsx
@@ -0,0 +1,31 @@
+import React from 'react';
+import { Box, Typography } from '@material-ui/core';
+import { makeStyles, Theme } from '@material-ui/core/styles';
+
+const useStyles = makeStyles((theme: Theme) => ({
+ root: {
+ color: theme.palette.primary.main,
+ fontSize: theme.typography.fontSize,
+ height: '100%',
+ width: '100%',
+ display: 'flex',
+ justifyContent: 'center',
+ textAlign: 'center',
+ padding: '140px 15px 15px 15px',
+ },
+}));
+
+interface IProps {
+ text: string;
+}
+
+function PageText({ text }: IProps) {
+ const classes = useStyles();
+ return (
+
+ {text}
+
+ );
+}
+
+export default PageText;
diff --git a/phone/src/apps/match/components/StatusDisplay.tsx b/phone/src/apps/match/components/StatusDisplay.tsx
new file mode 100644
index 0000000..8901067
--- /dev/null
+++ b/phone/src/apps/match/components/StatusDisplay.tsx
@@ -0,0 +1,14 @@
+import React from 'react';
+import { Box } from '@material-ui/core';
+
+function StatusDisplay({ className, visible, text }) {
+ const style = { opacity: visible ? '0.65' : '0.0' };
+
+ return (
+
+ {text}
+
+ );
+}
+
+export default StatusDisplay;
diff --git a/phone/src/apps/match/components/matches/Match.tsx b/phone/src/apps/match/components/matches/Match.tsx
new file mode 100644
index 0000000..29b335d
--- /dev/null
+++ b/phone/src/apps/match/components/matches/Match.tsx
@@ -0,0 +1,62 @@
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useHistory } from 'react-router-dom';
+import ListItemText from '@material-ui/core/ListItemText';
+import { Box, Button, ListItem, makeStyles } from '@material-ui/core';
+import PersonIcon from '@material-ui/icons/Person';
+import ChatIcon from '@material-ui/icons/Chat';
+
+import { FormattedMatch } from '../../../../../../typings/match';
+import Profile from '../profile/Profile';
+
+const useStyles = makeStyles({
+ profile: {
+ position: 'relative',
+ height: '90%',
+ marginTop: '15px',
+ },
+});
+
+interface IProps {
+ match: FormattedMatch;
+}
+
+export const Match = ({ match }: IProps) => {
+ const history = useHistory();
+ const classes = useStyles();
+ const { t } = useTranslation();
+ const [showProfile, setShowProfile] = useState(false);
+
+ const handleMessage = () => {
+ history.push(`/messages/new/${match.phoneNumber}`);
+ };
+
+ const handleProfile = () => {
+ setShowProfile((show) => !show);
+ };
+
+ const secondaryText = t('APPS_MATCH_PROFILE_MATCHED_AT', {
+ matchedAt: match.matchedAtFormatted,
+ });
+
+ return (
+ <>
+
+
+
+
+
+ {showProfile && (
+
+
+
+ )}
+ >
+ );
+};
+
+export default Match;
diff --git a/phone/src/apps/match/components/profile/Profile.tsx b/phone/src/apps/match/components/profile/Profile.tsx
new file mode 100644
index 0000000..60454b8
--- /dev/null
+++ b/phone/src/apps/match/components/profile/Profile.tsx
@@ -0,0 +1,78 @@
+import React from 'react';
+import { CardContent, CardMedia, Chip, Typography } from '@material-ui/core';
+import { makeStyles } from '@material-ui/core/styles';
+import { useTranslation } from 'react-i18next';
+
+import { FormattedProfile, FormattedMatch } from '../../../../../../typings/match';
+
+const useStyles = makeStyles({
+ root: {},
+ tags: {
+ position: 'absolute',
+ bottom: '40%',
+ },
+ tag: {
+ margin: '3px 3px 0px 0px',
+ opacity: '0.8',
+ },
+ media: {
+ height: '60%',
+ },
+ content: {
+ height: '40%',
+ overflowY: 'auto',
+ },
+});
+
+interface IProps {
+ profile: FormattedProfile | FormattedMatch;
+}
+
+const DEFAULT_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg';
+
+const Profile = ({ profile }: IProps) => {
+ const c = useStyles();
+ const { t } = useTranslation();
+
+ function parseSecondaryBio(): string | undefined {
+ const { location, job } = profile;
+ if (location && job) {
+ return `${location} - ${job}`;
+ } else if (location) {
+ return location;
+ } else if (job) {
+ return job;
+ }
+ }
+
+ const bioSecondary = parseSecondaryBio();
+
+ return (
+ <>
+
+ {profile.tagList.map((tag) => (
+
+ ))}
+
+
+
+
+ {profile.name}
+
+
+ {t('APPS_MATCH_PROFILE_LAST_ACTIVE', { lastActive: profile.lastActiveFormatted })}
+
+ {bioSecondary && (
+
+ {bioSecondary}
+
+ )}
+
+ {profile.bio}
+
+
+ >
+ );
+};
+
+export default Profile;
diff --git a/phone/src/apps/match/components/profile/ProfileForm.tsx b/phone/src/apps/match/components/profile/ProfileForm.tsx
new file mode 100644
index 0000000..bb93546
--- /dev/null
+++ b/phone/src/apps/match/components/profile/ProfileForm.tsx
@@ -0,0 +1,128 @@
+import React, { useState } from 'react';
+import { makeStyles } from '@material-ui/core/styles';
+import { useTranslation } from 'react-i18next';
+
+import Nui from '../../../../os/nui-events/utils/Nui';
+import {
+ Profile as IProfile,
+ FormattedProfile,
+ MatchEvents,
+} from '../../../../../../typings/match';
+import ProfileField from '../../../../ui/components/ProfileField';
+import UpdateButton from '../../../../ui/components/UpdateButton';
+import { Card } from '@material-ui/core';
+import Profile from './Profile';
+import { usePhone } from '../../../../os/phone/hooks/usePhone';
+import PageText from '../PageText';
+
+const useStyles = makeStyles({
+ root: {
+ position: 'relative',
+ width: '100%',
+ height: 'calc(100% - 40px)',
+ padding: '15px',
+ },
+ card: {
+ position: 'absolute',
+ margin: '15px 15px 25px 15px',
+ height: 'calc(100% - 80px)',
+ width: 'calc(100% - 30px)',
+ overflow: 'hidden',
+ },
+ spacer: {
+ height: '8px',
+ },
+});
+
+interface IProps {
+ profile: FormattedProfile;
+ showPreview: boolean;
+}
+
+export function ProfileForm({ profile, showPreview }: IProps) {
+ const classes = useStyles();
+ const { t } = useTranslation();
+ const { config } = usePhone();
+
+ // note that this assumes we are defensively checking
+ // that profile is not null in a parent above this component.
+ // Annoyingling adding conditionals above this line to not render
+ // when profile === null results in a react error that different
+ // amounts of hooks are rendering
+ const [image, setImage] = useState(profile?.image || '');
+ const [name, setName] = useState(profile?.name || '');
+ const [bio, setBio] = useState(profile?.bio || '');
+ const [job, setJob] = useState(profile?.job || '');
+ const [location, setLocation] = useState(profile?.location || '');
+ const [tags, setTags] = useState(profile?.tags || '');
+
+ const update: FormattedProfile = {
+ ...profile,
+ image,
+ name,
+ bio,
+ location,
+ job,
+ tagList: tags.split(',').map((tag) => tag.trim()),
+ };
+
+ const handleUpdate = () => {
+ const updatedProfile: IProfile = {
+ ...update,
+ name: update.name.trim(),
+ image: update.image.trim(),
+ tags: update.tagList.join(','),
+ };
+ const event = profile ? MatchEvents.UPDATE_MY_PROFILE : MatchEvents.CREATE_MY_PROFILE;
+ Nui.send(event, updatedProfile);
+ };
+
+ if (!profile && !config.match.allowEdtiableProfileName) {
+ return ;
+ }
+
+ if (showPreview) {
+ return (
+
+
+
+ );
+ }
+
+ return (
+
+ );
+}
+
+export default ProfileForm;
diff --git a/phone/src/apps/match/components/views/MatchList.tsx b/phone/src/apps/match/components/views/MatchList.tsx
new file mode 100644
index 0000000..22138cc
--- /dev/null
+++ b/phone/src/apps/match/components/views/MatchList.tsx
@@ -0,0 +1,52 @@
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Box, makeStyles } from '@material-ui/core';
+
+import { useMatches } from '../../hooks/useMatches';
+import Loader from '../Loader';
+import PageText from '../PageText';
+import Match from '../matches/Match';
+import Nui from '../../../../os/nui-events/utils/Nui';
+import { MatchEvents } from '../../../../../../typings/match';
+
+const useStyles = makeStyles({
+ root: {
+ height: '100%',
+ },
+});
+
+const MINIMUM_LOAD_TIME = 1500;
+
+function MatchList() {
+ const classes = useStyles();
+ const { t } = useTranslation();
+ const { matches, error } = useMatches();
+ const [loaded, setLoaded] = useState(false);
+
+ // We make the conscious descion here to fetch matches everytime
+ // a user loads this page because this list is dependent on
+ // other player's database interactions (i.e. their likes/dislikes)
+ // not just the current players.
+ // This is less performant but means that we will always have the
+ // correct state when the player views this page
+ useEffect(() => {
+ Nui.send(MatchEvents.GET_MATCHES);
+ window.setTimeout(() => {
+ setLoaded(true);
+ }, MINIMUM_LOAD_TIME);
+ }, []);
+
+ if (error) return ;
+ if (!loaded || !matches) return ;
+ if (matches.length === 0) return ;
+
+ return (
+
+ {matches.map((match) => (
+
+ ))}
+
+ );
+}
+
+export default MatchList;
diff --git a/phone/src/apps/match/components/views/MatchPage.tsx b/phone/src/apps/match/components/views/MatchPage.tsx
new file mode 100644
index 0000000..99d38c3
--- /dev/null
+++ b/phone/src/apps/match/components/views/MatchPage.tsx
@@ -0,0 +1,53 @@
+import React, { useEffect, useState } from 'react';
+import { Paper } from '@material-ui/core';
+import { makeStyles } from '@material-ui/core/styles';
+import { useTranslation } from 'react-i18next';
+
+import { useProfiles } from '../../hooks/useProfiles';
+import Loader from '../Loader';
+import PageText from '../PageText';
+import ActiveProfile from '../ActiveProfile';
+
+const useStyles = makeStyles({
+ root: {
+ height: '100%',
+ width: '100%',
+ overflow: 'hidden',
+ },
+});
+
+// set a minimum load time so the user doesn't see a flash
+// of the loader and then the matches themselves
+const MINIMUM_LOAD_TIME = 1250;
+
+const MatchPage = () => {
+ const classes = useStyles();
+ const { t } = useTranslation();
+ const { profiles, error, activeProfile, setViewed } = useProfiles();
+ const [loaded, setLoaded] = useState(false);
+
+ useEffect(() => {
+ window.setTimeout(() => {
+ setLoaded(true);
+ }, MINIMUM_LOAD_TIME);
+ }, []);
+
+ const handleSwipe = (id: number, liked: boolean) => {
+ // the user didn't choose (didn't swipe far enough)
+ if (liked === null) return;
+
+ setViewed(id, liked);
+ };
+
+ if (error) return ;
+ if (!loaded || !profiles) return ;
+ if (!activeProfile) return ;
+
+ return (
+
+
+
+ );
+};
+
+export default MatchPage;
diff --git a/phone/src/apps/match/components/views/ProfileEditor.tsx b/phone/src/apps/match/components/views/ProfileEditor.tsx
new file mode 100644
index 0000000..17fc1ad
--- /dev/null
+++ b/phone/src/apps/match/components/views/ProfileEditor.tsx
@@ -0,0 +1,45 @@
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { makeStyles } from '@material-ui/core/styles';
+import { Box, FormControlLabel, Switch } from '@material-ui/core';
+
+import { useProfile } from '../../hooks/useProfile';
+import Loader from '../Loader';
+import ProfileForm from '../profile/ProfileForm';
+
+const useStyles = makeStyles({
+ root: {
+ height: '100%',
+ width: '100%',
+ },
+ switch: {
+ marginLeft: '15px',
+ },
+});
+
+function ProfileEditor() {
+ const { profile, noProfileExists } = useProfile();
+ const classes = useStyles();
+ const { t } = useTranslation();
+ const [showPreview, setShowPreview] = useState(false);
+
+ const toggleSwitch = () => {
+ setShowPreview((preview) => !preview);
+ };
+
+ if (!profile && !noProfileExists) return ;
+
+ return (
+
+
+ }
+ label={t('APPS_MATCH_EDIT_PROFILE_PREVIEW')}
+ />
+
+
+
+ );
+}
+
+export default ProfileEditor;
diff --git a/phone/src/apps/match/hooks/state.ts b/phone/src/apps/match/hooks/state.ts
new file mode 100644
index 0000000..2d86410
--- /dev/null
+++ b/phone/src/apps/match/hooks/state.ts
@@ -0,0 +1,28 @@
+import { atom } from 'recoil';
+
+export const matchState = {
+ profiles: atom({
+ key: 'profiles',
+ default: null,
+ }),
+ errorLoadingProfiles: atom({
+ key: 'errorLoadingProfiles',
+ default: false,
+ }),
+ matches: atom({
+ key: 'matches',
+ default: null,
+ }),
+ errorLoadingMatches: atom({
+ key: 'errorLoadingMatches',
+ default: false,
+ }),
+ myProfile: atom({
+ key: 'myProfile',
+ default: null,
+ }),
+ noProfileExists: atom({
+ key: 'noProfileExists',
+ default: false,
+ }),
+};
diff --git a/phone/src/apps/match/hooks/useMatchService.ts b/phone/src/apps/match/hooks/useMatchService.ts
new file mode 100644
index 0000000..37a0fda
--- /dev/null
+++ b/phone/src/apps/match/hooks/useMatchService.ts
@@ -0,0 +1,86 @@
+import { useSetRecoilState } from 'recoil';
+import { matchState } from './state';
+import { useTranslation } from 'react-i18next';
+import dayjs from 'dayjs';
+
+import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
+import { Profile, FormattedProfile, Match, MatchEvents } from '../../../../../typings/match';
+import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
+
+export const useMatchService = () => {
+ const { addAlert } = useSnackbar();
+ const { t } = useTranslation();
+ const setNoProfileExists = useSetRecoilState(matchState.noProfileExists);
+ const setProfiles = useSetRecoilState(matchState.profiles);
+ const setProfile = useSetRecoilState(matchState.myProfile);
+ const setMatches = useSetRecoilState(matchState.matches);
+ const setErrorLoadingMatches = useSetRecoilState(matchState.errorLoadingMatches);
+ const setErrorLoadingProfiles = useSetRecoilState(matchState.errorLoadingProfiles);
+
+ const handleAddAlert = ({ message, type }: IAlert) => {
+ addAlert({
+ message: t(message),
+ type,
+ });
+ };
+
+ function formatProfile(profile: Profile): FormattedProfile | null {
+ return {
+ ...profile,
+ tagList: profile.tags.split(',').filter((t) => t), // remove any empty tags
+ lastActiveFormatted: dayjs.unix(profile.lastActive).format(t('DATE_TIME_FORMAT')),
+ viewed: false,
+ };
+ }
+
+ const _setProfiles = (profiles: Profile[]): void => {
+ setProfiles(profiles.map(formatProfile));
+ };
+ const _setProfile = (profile: Profile) => {
+ if (!profile) {
+ setNoProfileExists(true);
+ } else {
+ setNoProfileExists(false);
+ setProfile(formatProfile(profile));
+ }
+ };
+ const _handleGetProfilesFailed = (alert: IAlert): void => {
+ handleAddAlert(alert);
+ setErrorLoadingProfiles(true);
+ };
+
+ const _setMatches = (matches: Match[]): void => {
+ setMatches(
+ matches.map((match) => ({
+ ...match,
+ tagList: match.tags.split(',').filter((t) => t), // remove any empty tags
+ lastActiveFormatted: dayjs.unix(match.lastActive).format(t('DATE_TIME_FORMAT')),
+ matchedAtFormatted: dayjs.unix(match.matchedAt).format(t('DATE_TIME_FORMAT')),
+ })),
+ );
+ };
+
+ const _handleGetMatchesFailed = (alert: IAlert): void => {
+ handleAddAlert(alert);
+ setErrorLoadingMatches(true);
+ };
+
+ const _handleUpdateProfile = (profile: Profile) => {
+ _setProfile(profile);
+ handleAddAlert({ message: 'APPS_MATCH_UPDATE_PROFILE_SUCCEEDED', type: 'info' });
+ };
+
+ useNuiEvent('MATCH', MatchEvents.GET_PROFILES_SUCCESS, _setProfiles);
+ useNuiEvent('MATCH', MatchEvents.GET_PROFILES_FAILED, _handleGetProfilesFailed);
+ useNuiEvent('MATCH', MatchEvents.GET_MY_PROFILE_SUCCESS, _setProfile);
+ useNuiEvent('MATCH', MatchEvents.GET_MY_PROFILE_FAILED, handleAddAlert);
+ useNuiEvent('MATCH', MatchEvents.GET_MATCHES_SUCCESS, _setMatches);
+ useNuiEvent('MATCH', MatchEvents.GET_MATCHES_FAILED, _handleGetMatchesFailed);
+ useNuiEvent('MATCH', MatchEvents.SAVE_LIKES_FAILED, handleAddAlert);
+ useNuiEvent('MATCH', MatchEvents.NEW_MATCH, handleAddAlert);
+ useNuiEvent('MATCH', MatchEvents.UPDATE_MY_PROFILE_SUCCESS, _handleUpdateProfile);
+ useNuiEvent('MATCH', MatchEvents.UPDATE_MY_PROFILE_FAILED, handleAddAlert);
+ useNuiEvent('MATCH', MatchEvents.CREATE_MY_PROFILE_SUCCESS, _handleUpdateProfile);
+ useNuiEvent('MATCH', MatchEvents.CREATE_MY_PROFILE_FAILED, handleAddAlert);
+ return {};
+};
diff --git a/phone/src/apps/match/hooks/useMatches.ts b/phone/src/apps/match/hooks/useMatches.ts
new file mode 100644
index 0000000..3c880da
--- /dev/null
+++ b/phone/src/apps/match/hooks/useMatches.ts
@@ -0,0 +1,15 @@
+import { useRecoilValue } from 'recoil';
+import { matchState } from './state';
+
+import { FormattedMatch } from '../../../../../typings/match';
+
+interface IUseMatches {
+ matches: FormattedMatch[];
+ error: boolean;
+}
+
+export const useMatches = (): IUseMatches => {
+ const matches = useRecoilValue(matchState.matches);
+ const error = useRecoilValue(matchState.errorLoadingMatches);
+ return { matches, error };
+};
diff --git a/phone/src/apps/match/hooks/useProfile.ts b/phone/src/apps/match/hooks/useProfile.ts
new file mode 100644
index 0000000..be95c80
--- /dev/null
+++ b/phone/src/apps/match/hooks/useProfile.ts
@@ -0,0 +1,16 @@
+import { useRecoilState, useRecoilValue } from 'recoil';
+import { matchState } from './state';
+
+import { FormattedProfile } from '../../../../../typings/match';
+
+interface IUseProfiles {
+ profile: FormattedProfile;
+ setProfile: (profile: FormattedProfile) => void;
+ noProfileExists: boolean;
+}
+
+export const useProfile = (): IUseProfiles => {
+ const [profile, setProfile] = useRecoilState(matchState.myProfile);
+ const noProfileExists = useRecoilValue(matchState.noProfileExists);
+ return { profile, setProfile, noProfileExists };
+};
diff --git a/phone/src/apps/match/hooks/useProfiles.ts b/phone/src/apps/match/hooks/useProfiles.ts
new file mode 100644
index 0000000..6d1522c
--- /dev/null
+++ b/phone/src/apps/match/hooks/useProfiles.ts
@@ -0,0 +1,33 @@
+import { useRecoilState, useRecoilValue } from 'recoil';
+import { matchState } from './state';
+
+import { FormattedProfile, MatchEvents } from '../../../../../typings/match';
+import Nui from '../../../os/nui-events/utils/Nui';
+
+interface IUseProfiles {
+ profiles: FormattedProfile[];
+ activeProfile: FormattedProfile | null;
+ setViewed: (index: number, liked: boolean) => void;
+ error: boolean;
+}
+
+export const useProfiles = (): IUseProfiles => {
+ const [profiles, setProfiles] = useRecoilState(matchState.profiles);
+ const error = useRecoilValue(matchState.errorLoadingProfiles);
+
+ const setViewed = (id: number, liked: boolean) => {
+ setProfiles((profiles) =>
+ profiles.map((profile) => {
+ if (id === profile.id) return { ...profile, viewed: true, liked };
+ return profile;
+ }),
+ );
+
+ Nui.send(MatchEvents.SAVE_LIKES, [{ id, liked }]);
+ };
+
+ const filteredProfiles = profiles ? profiles.filter((profile) => !profile.viewed) : null;
+ const activeProfile = profiles ? filteredProfiles[0] : null;
+
+ return { profiles, activeProfile, error, setViewed };
+};
diff --git a/phone/src/apps/match/match.theme.ts b/phone/src/apps/match/match.theme.ts
new file mode 100644
index 0000000..018658b
--- /dev/null
+++ b/phone/src/apps/match/match.theme.ts
@@ -0,0 +1,27 @@
+import { red, common } from '@material-ui/core/colors';
+
+export const MATCH_APP_PRIMARY_COLOR = '#FE3B73';
+export const MATCH_APP_TEXT_COLOR = common.white;
+
+const theme = {
+ palette: {
+ primary: {
+ main: MATCH_APP_PRIMARY_COLOR,
+ dark: red[700],
+ light: red[300],
+ contrastText: MATCH_APP_TEXT_COLOR,
+ },
+ secondary: {
+ main: '#d32f2f',
+ light: '#eb4242',
+ dark: '#941212',
+ contrastText: MATCH_APP_TEXT_COLOR,
+ },
+ success: {
+ main: '#2196f3',
+ contrastText: MATCH_APP_TEXT_COLOR,
+ },
+ },
+};
+
+export default theme;
diff --git a/phone/src/apps/match/providers/MatchThemeProvider.tsx b/phone/src/apps/match/providers/MatchThemeProvider.tsx
new file mode 100644
index 0000000..3263fc9
--- /dev/null
+++ b/phone/src/apps/match/providers/MatchThemeProvider.tsx
@@ -0,0 +1,5 @@
+import { createAppThemeProvider } from '../../../os/apps/utils/createAppThemeProvider';
+
+import matchTheme from '../match.theme';
+
+export const MatchThemeProvider = createAppThemeProvider(matchTheme);
diff --git a/phone/src/apps/match/utils/drag.ts b/phone/src/apps/match/utils/drag.ts
new file mode 100644
index 0000000..f2bdbbf
--- /dev/null
+++ b/phone/src/apps/match/utils/drag.ts
@@ -0,0 +1,161 @@
+interface IDeltas {
+ deltaX: number;
+ deltaY: number;
+}
+
+/**
+ * Given a React ref, which should point to some HTML element,
+ * add draggable functionality to that element so the user can
+ * interact with it.
+ *
+ * It should be noted that when using this in React that this
+ * class is directly mutating the DOM, not relying on React state
+ * to do so. This can cause some problems when relying on React
+ * state updates based on the values derived from this class. That
+ * is why we primarily use refs to interact with it.
+ *
+ * Order of operations:
+ * 1. User clicks "down" on element - this initializes event
+ * handlers and saves initial state
+ * 2. User moves mouse. Every mouse move event triggers a movement
+ * of the HTML element and also performs some logic to see how far
+ * we have moved
+ * 3. User "releases" mouse - cleanup event handlers and do logic
+ * to compare our final position to our initial position
+ */
+export class DraggableElement {
+ private element: HTMLElement;
+
+ private width: number = 0;
+ private initialX: number = 0;
+ private initialY: number = 0;
+ private mouseDownInitialX: number = 0;
+ private mouseDownInitialY: number = 0;
+
+ private useRotation: boolean;
+ private maxRotationDeg: null | number;
+
+ private updatedX: number = 0;
+ private updatedY: number = 0;
+ private mouseDownX: number = 0;
+ private mouseDownY: number = 0;
+
+ constructor(ref: React.MutableRefObject, maxRotationDeg: number | null = null) {
+ this.element = ref.current;
+ this.width = this.element.clientWidth;
+ this.maxRotationDeg = maxRotationDeg;
+ this.useRotation = maxRotationDeg !== null;
+
+ this.element.onmousedown = this.onMouseDown;
+ }
+
+ onMouseDown = (e: MouseEvent): void => {
+ e.preventDefault();
+ // get the mouse cursor position at startup:
+ this.mouseDownX = e.clientX;
+ this.mouseDownY = e.clientY;
+
+ // save where we initially started dragging from
+ // so we can do some math later
+ this.mouseDownInitialX = this.mouseDownX;
+ this.mouseDownInitialY = this.mouseDownY;
+
+ document.onmouseup = this.onMouseUp;
+ // call a function whenever the cursor moves:
+ document.onmousemove = this.onMouseMove;
+ };
+
+ onMouseMove = (e: MouseEvent): void => {
+ e.preventDefault();
+ const x = e.clientX;
+ const y = e.clientY;
+ this._onMouseMove(x, y);
+ };
+
+ _onMouseMove = (x: number, y: number): void => {
+ // calculate the new cursor position:
+ this.updatedX = this.mouseDownX - x;
+ this.updatedY = this.mouseDownY - y;
+ this.mouseDownX = x;
+ this.mouseDownY = y;
+
+ // set the element's new position:
+ this.element.style.top = this.element.offsetTop - this.updatedY + 'px';
+ this.element.style.left = this.element.offsetLeft - this.updatedX + 'px';
+
+ if (this.useRotation) {
+ const { deltaX } = this.deltas(this.mouseDownX, this.mouseDownY);
+ const pctWidth = deltaX / this.width;
+ const rotationDeg = -1 * this.maxRotationDeg * pctWidth;
+
+ this.element.style.webkitTransform = `rotate(${rotationDeg}deg)`;
+ }
+ };
+
+ onMouseUp = (e: MouseEvent): void => {
+ e.preventDefault();
+ this._onMouseUp();
+ };
+
+ _onMouseUp = (): void => {
+ // stop moving when mouse button is released:
+ this.cleanup();
+
+ // revert back to intitial position
+ this.element.style.left = `${this.initialX}px`;
+ this.element.style.top = `${this.initialY}px`;
+ if (this.useRotation) {
+ this.element.style.webkitTransform = 'rotate(0deg)';
+ }
+ };
+
+ cleanup = (): void => {
+ document.onmouseup = null;
+ document.onmousemove = null;
+ };
+
+ deltas = (x: number, y: number): IDeltas => {
+ const deltaX = x - this.mouseDownInitialX;
+ const deltaY = y - this.mouseDownInitialX;
+ return { deltaX, deltaY };
+ };
+}
+
+type StatusChange = (deltaX: number) => void;
+
+/**
+ * This class adds hooks to the base DraggableElement class
+ * so we can update application state based on events
+ */
+export class LikeorDislikeDraggableElement extends DraggableElement {
+ private onDrag: StatusChange;
+ private onDrop: () => void;
+
+ constructor(
+ ref: React.MutableRefObject,
+ maxRotationDeg: number,
+ onDrag: StatusChange,
+ onDrop: () => void,
+ ) {
+ super(ref, maxRotationDeg);
+
+ this.onDrag = onDrag;
+ this.onDrop = onDrop;
+ }
+
+ onMouseMove = (e: MouseEvent): void => {
+ e.preventDefault();
+ const x = e.clientX;
+ const y = e.clientY;
+
+ const { deltaX } = this.deltas(x, y);
+
+ this.onDrag(deltaX);
+ this._onMouseMove(x, y);
+ };
+
+ onMouseUp = (): void => {
+ this.onDrop();
+ this._onMouseUp();
+ };
+}
diff --git a/phone/src/apps/twitter/components/buttons/ProfileUpdateButton.tsx b/phone/src/apps/twitter/components/buttons/ProfileUpdateButton.tsx
index e587c7a..56bc6d7 100644
--- a/phone/src/apps/twitter/components/buttons/ProfileUpdateButton.tsx
+++ b/phone/src/apps/twitter/components/buttons/ProfileUpdateButton.tsx
@@ -1,45 +1,16 @@
-import React, { useState, useEffect } from 'react';
-import { makeStyles } from '@material-ui/core/styles';
-import { Fab } from '@material-ui/core';
-import PublishIcon from '@material-ui/icons/Publish';
+import React from 'react';
+import UpdateButton from '../../../../ui/components/UpdateButton';
import { useProfile } from '../../hooks/useProfile';
-const useStyles = makeStyles((theme) => ({
- root: {
- position: 'absolute',
- bottom: '15px',
- right: '15px',
- },
- button: {
- background: '#00acee',
- },
-}));
+interface IProps {
+ handleClick: () => void;
+}
-const MINIMUM_LOAD_TIME = 750;
-
-export function ProfileUpdateButton({ handleClick }) {
- const classes = useStyles();
- const [minimumLoadPassed, setMimimumLoadPassed] = useState(true);
+export function ProfileUpdateButton({ handleClick }: IProps) {
const { updateProfileLoading } = useProfile();
- useEffect(() => {
- setMimimumLoadPassed(false);
- const timeout = window.setTimeout(() => {
- setMimimumLoadPassed(true);
- }, MINIMUM_LOAD_TIME);
- return () => window.clearTimeout(timeout);
- }, [updateProfileLoading]);
-
- const isLoading = updateProfileLoading || !minimumLoadPassed;
-
- return (
-
- );
+ return ;
}
export default ProfileUpdateButton;
diff --git a/phone/src/apps/twitter/components/profile/Profile.tsx b/phone/src/apps/twitter/components/profile/Profile.tsx
index 8ef2c28..53885b3 100644
--- a/phone/src/apps/twitter/components/profile/Profile.tsx
+++ b/phone/src/apps/twitter/components/profile/Profile.tsx
@@ -5,10 +5,10 @@ import { useTranslation } from 'react-i18next';
import Nui from '../../../../os/nui-events/utils/Nui';
import { useProfile } from '../../hooks/useProfile';
import Avatar from '../Avatar';
-import ProfileField from './ProfileField';
import ProfileUpdateButton from '../buttons/ProfileUpdateButton';
import { usePhone } from '../../../../os/phone/hooks/usePhone';
import { TwitterEvents } from '../../../../../../typings/twitter';
+import ProfileField from '../../../../ui/components/ProfileField';
const useStyles = makeStyles((theme) => ({
root: {
diff --git a/phone/src/apps/twitter/components/profile/ProfilePrompt.tsx b/phone/src/apps/twitter/components/profile/ProfilePrompt.tsx
index a25c027..3ff0668 100644
--- a/phone/src/apps/twitter/components/profile/ProfilePrompt.tsx
+++ b/phone/src/apps/twitter/components/profile/ProfilePrompt.tsx
@@ -3,14 +3,14 @@ import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import Nui from '../../../../os/nui-events/utils/Nui';
+import ProfileField from '../../../../ui/components/ProfileField';
import { useProfile } from '../../hooks/useProfile';
-import ProfileField from './ProfileField';
-import DefaultProfilePrompt from './DefaultProfilePrompt';
import ProfileUpdateButton from '../buttons/ProfileUpdateButton';
import { useRecoilValue } from 'recoil';
import { twitterState } from '../../hooks/state';
import { usePhone } from '../../../../os/phone/hooks/usePhone';
import { TwitterEvents } from '../../../../../../typings/twitter';
+import DefaultProfilePrompt from './DefaultProfilePrompt';
const useStyles = makeStyles((theme) => ({
root: {
diff --git a/phone/src/config.autogen.json b/phone/src/config.autogen.json
index 7e97a4a..18697d0 100644
--- a/phone/src/config.autogen.json
+++ b/phone/src/config.autogen.json
@@ -27,6 +27,10 @@
"enableImages": true,
"maxImages": 3
},
+ "match": {
+ "generateProfileNameFromUsers": true,
+ "allowEdtiableProfileName": true
+ },
"bank": {
"showNotifications": true
},
diff --git a/phone/src/locale/en.json b/phone/src/locale/en.json
index 45c25a1..48bb638 100644
--- a/phone/src/locale/en.json
+++ b/phone/src/locale/en.json
@@ -94,6 +94,36 @@
"APPS_TWITTER_NEW_RETWEET_BROADCAST": "@{{ profile_name }} retweeted someone!",
"APPS_TWITTER_UNREAD_MESSAGES": "You have {{ count }} new tweets in your timeline!",
+ "APPS_MATCH": "Matchmaker",
+ "APPS_MATCH_LIKED": "LIKE",
+ "APPS_MATCH_NOPE": "NOPE",
+ "APPS_MATCH_LIKE": "Like",
+ "APPS_MATCH_DISLIKE": "Dislike",
+ "APPS_MATCH_NO_PROFILES": "No Recent Profiles Found",
+ "APPS_MATCH_NO_MATCHES": "No matches Found",
+ "APPS_MATCH_PROFILES_ERROR": "Error loading profiles",
+ "APPS_MATCH_MATCHES_ERROR": "Error loading matches",
+ "APPS_MATCH_PROFILE_CONFIGURATION": "App is incorrectly configured - cannot create profile. Please contact an administrator.",
+ "APPS_MATCH_MY_PROFILE_ERROR": "Error loading profile",
+ "APPS_MATCH_PROFILE_LAST_ACTIVE": "Last Active: {{ lastActive }}",
+ "APPS_MATCH_PROFILE_MATCHED_AT": "Matched: {{ matchedAt }}",
+ "APPS_MATCH_EDIT_PROFILE_PREVIEW": "Show Preview",
+ "APPS_MATCH_EDIT_PROFILE_IMAGE": "Image URL",
+ "APPS_MATCH_EDIT_PROFILE_NAME": "Profile name",
+ "APPS_MATCH_EDIT_PROFILE_BIO": "Bio",
+ "APPS_MATCH_EDIT_PROFILE_LOCATION": "Location",
+ "APPS_MATCH_EDIT_PROFILE_JOB": "Job",
+ "APPS_MATCH_EDIT_PROFILE_TAGS": "Tags",
+ "APPS_MATCH_GET_MY_PROFILE_FAILED": "Failed to retrieve player's profile",
+ "APPS_MATCH_GET_PROFILES_FAILED": "Failed to retrieve profiles",
+ "APPS_MATCH_GET_MATCHES_FAILED": "Failed to retrieve matches",
+ "APPS_MATCH_UPDATE_PROFILE_SUCCEEDED": "Successfully updated profile",
+ "APPS_MATCH_UPDATE_PROFILE_FAILED": "Failed to update profile",
+ "APPS_MATCH_CREATE_PROFILE_FAILED": "Failed to create profile",
+ "APPS_MATCH_SAVE_LIKES_FAILED": "Failed to save likes",
+ "APPS_MATCH_SAVE_LIKES_SUCCEDED": "Successfully saved likes",
+ "APPS_MATCH_NEW_LIKE_FOUND": "New match found!",
+
"APPS_BANK_TRANSFER": "Transfer",
"APPS_BANK_HOME_TITLE": "Welcome",
"APPS_BANK_ACCOUNT_LINK": "Account",
diff --git a/phone/src/os/apps/config/apps.tsx b/phone/src/os/apps/config/apps.tsx
index 17cb08c..2370952 100644
--- a/phone/src/os/apps/config/apps.tsx
+++ b/phone/src/os/apps/config/apps.tsx
@@ -13,6 +13,7 @@ import { faTwitter } from '@fortawesome/free-brands-svg-icons';
import ContactsIcon from '@material-ui/icons/Contacts';
import SettingsIcon from '@material-ui/icons/Settings';
import MessageIcon from '@material-ui/icons/Message';
+import FireIcon from '@material-ui/icons/Whatshot';
import { CalculatorIcon } from '../../../apps/calculator/components/CalculatorIcon';
import CameraAltIcon from '@material-ui/icons/CameraAlt';
import { DialerApp } from '../../../apps/dialer/components/DialerApp';
@@ -21,6 +22,7 @@ import { CalculatorApp } from '../../../apps/calculator/components/CalculatorApp
import { SettingsApp } from '../../../apps/settings/components/SettingsApp';
import { BankApp } from '../../../apps/bank/components/BankApp';
import { MessagesApp } from '../../../apps/messages/components/MessagesApp';
+import { MatchApp } from '../../../apps/match/components/MatchApp';
import { TwitterApp } from '../../../apps/twitter/components/TwitterApp';
import { ExampleApp } from '../../../apps/example/components/ExampleApp';
import { SelloutApp } from '../../../apps/sellout/components/SelloutApp';
@@ -46,6 +48,7 @@ import {
TWITTER_APP_PRIMARY_COLOR,
TWITTER_APP_TEXT_COLOR,
} from '../../../apps/twitter/twitter.theme';
+import { MATCH_APP_PRIMARY_COLOR, MATCH_APP_TEXT_COLOR } from '../../../apps/match/match.theme';
export interface IAppConfig {
id: string;
@@ -119,6 +122,16 @@ export const APPS: IAppConfig[] = [
path: '/bank',
Route: () => ,
},
+ {
+ id: 'MATCH',
+ nameLocale: 'APPS_MATCH',
+ icon: ,
+ notificationIcon: ,
+ backgroundColor: MATCH_APP_PRIMARY_COLOR,
+ color: MATCH_APP_TEXT_COLOR,
+ path: '/match',
+ Route: () => ,
+ },
{
id: 'TWITTER',
nameLocale: 'APPS_TWITTER',
diff --git a/phone/src/os/notifications/components/NotificationItem.tsx b/phone/src/os/notifications/components/NotificationItem.tsx
index 5d5a28c..ca70db0 100644
--- a/phone/src/os/notifications/components/NotificationItem.tsx
+++ b/phone/src/os/notifications/components/NotificationItem.tsx
@@ -32,6 +32,7 @@ export const NotificationItem = ({
}) => {
const { title, icon, content, cantClose, onClick } = notification;
const classes = useStyles({ cantClose });
+
return (
void;
+ loading: boolean;
+}
+
+export function ProfileUpdateButton({ handleClick, loading }: IProps) {
+ const classes = useStyles();
+ const [minimumLoadPassed, setMimimumLoadPassed] = useState(true);
+
+ useEffect(() => {
+ setMimimumLoadPassed(false);
+ const timeout = window.setTimeout(() => {
+ setMimimumLoadPassed(true);
+ }, MINIMUM_LOAD_TIME);
+ return () => window.clearTimeout(timeout);
+ }, [loading]);
+
+ const isLoading = loading || !minimumLoadPassed;
+
+ return (
+
+ );
+}
+
+export default ProfileUpdateButton;
diff --git a/phone/yarn.lock b/phone/yarn.lock
index 47b6190..10ebfc9 100644
--- a/phone/yarn.lock
+++ b/phone/yarn.lock
@@ -11668,14 +11668,7 @@ react-app-polyfill@^2.0.0:
regenerator-runtime "^0.13.7"
whatwg-fetch "^3.4.1"
-react-app-rewired@^2.1.8:
- version "2.1.8"
- resolved "https://registry.yarnpkg.com/react-app-rewired/-/react-app-rewired-2.1.8.tgz#e192f93b98daf96889418d33d3e86cf863812b56"
- integrity sha512-wjXPdKPLscA7mn0I1de1NHrbfWdXz4S1ladaGgHVKdn1hTgKK5N6EdGIJM0KrS6bKnJBj7WuqJroDTsPKKr66Q==
- dependencies:
- semver "^5.6.0"
-
-react-dev-utils@^11.0.1, react-dev-utils@^11.0.4:
+react-dev-utils@^11.0.1:
version "11.0.4"
resolved "https://registry.yarnpkg.com/react-dev-utils/-/react-dev-utils-11.0.4.tgz#a7ccb60257a1ca2e0efe7a83e38e6700d17aa37a"
integrity sha512-dx0LvIGHcOPtKbeiSUM4jqpBl3TcY7CDjZdfOIcKeznE7BWr9dg0iPG90G5yfVQ+p/rGNMXdbfStvzQZEVEi4A==
diff --git a/resources/client/cl_main.ts b/resources/client/cl_main.ts
index 9d59e15..8fcdbac 100644
--- a/resources/client/cl_main.ts
+++ b/resources/client/cl_main.ts
@@ -10,6 +10,7 @@ import { NotesEvents } from '../../typings/notes';
import { BankEvents } from '../../typings/bank';
import { PhotoEvents } from '../../typings/photo';
import { CallEvents } from '../../typings/call';
+import { MatchEvents } from '../../typings/match';
let isPhoneOpen = false;
let isPhoneReady = false;
diff --git a/resources/client/cl_match.ts b/resources/client/cl_match.ts
new file mode 100644
index 0000000..b002537
--- /dev/null
+++ b/resources/client/cl_match.ts
@@ -0,0 +1,53 @@
+import { Like, Profile, MatchEvents } from '../../typings/match';
+import { sendMatchEvent } from '../utils/messages';
+
+/**
+ * Many events that are just statuses are passed directly from
+ * the server to NUI and the client is just acting as a middle man.
+ * For those cases this function allows us to simply transfer all the
+ * data associated with the event.
+ * @param eventName - event we are propagating
+ */
+const transferEvent = (eventName: string) => (...args: any) => {
+ sendMatchEvent(eventName, ...args);
+};
+
+onNet(MatchEvents.GET_PROFILES_FAILED, transferEvent(MatchEvents.GET_PROFILES_FAILED));
+onNet(MatchEvents.SAVE_LIKES_SUCCESS, transferEvent(MatchEvents.SAVE_LIKES_SUCCESS));
+onNet(MatchEvents.SAVE_LIKES_FAILED, transferEvent(MatchEvents.SAVE_LIKES_FAILED));
+onNet(MatchEvents.GET_MATCHES_SUCCESS, transferEvent(MatchEvents.GET_MATCHES_SUCCESS));
+onNet(MatchEvents.GET_MATCHES_FAILED, transferEvent(MatchEvents.GET_MATCHES_FAILED));
+onNet(MatchEvents.GET_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.GET_MY_PROFILE_SUCCESS));
+onNet(MatchEvents.GET_MY_PROFILE_FAILED, transferEvent(MatchEvents.GET_MY_PROFILE_FAILED));
+onNet(MatchEvents.GET_PROFILES_SUCCESS, transferEvent(MatchEvents.GET_PROFILES_SUCCESS));
+onNet(MatchEvents.UPDATE_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.UPDATE_MY_PROFILE_SUCCESS));
+onNet(MatchEvents.CREATE_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.CREATE_MY_PROFILE_SUCCESS));
+onNet(MatchEvents.CREATE_MY_PROFILE_FAILED, transferEvent(MatchEvents.CREATE_MY_PROFILE_FAILED));
+onNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, transferEvent(MatchEvents.UPDATE_MY_PROFILE_FAILED));
+onNet(MatchEvents.NEW_MATCH, transferEvent(MatchEvents.NEW_MATCH));
+
+RegisterNuiCallbackType(MatchEvents.SAVE_LIKES);
+on(`__cfx_nui:${MatchEvents.SAVE_LIKES}`, (likes: Like[], cb: Function) => {
+ emitNet(MatchEvents.SAVE_LIKES, likes);
+ cb();
+});
+
+RegisterNuiCallbackType(MatchEvents.GET_MATCHES);
+on(`__cfx_nui:${MatchEvents.GET_MATCHES}`, () => {
+ emitNet(MatchEvents.GET_MATCHES);
+});
+
+RegisterNuiCallbackType(MatchEvents.INITIALIZE);
+on(`__cfx_nui:${MatchEvents.INITIALIZE}`, () => {
+ emitNet(MatchEvents.INITIALIZE);
+});
+
+RegisterNuiCallbackType(MatchEvents.CREATE_MY_PROFILE);
+on(`__cfx_nui:${MatchEvents.CREATE_MY_PROFILE}`, (profile: Profile) => {
+ emitNet(MatchEvents.CREATE_MY_PROFILE, profile);
+});
+
+RegisterNuiCallbackType(MatchEvents.UPDATE_MY_PROFILE);
+on(`__cfx_nui:${MatchEvents.UPDATE_MY_PROFILE}`, (profile: Profile) => {
+ emitNet(MatchEvents.UPDATE_MY_PROFILE, profile);
+});
diff --git a/resources/client/client.ts b/resources/client/client.ts
index 526700d..dccf6c4 100644
--- a/resources/client/client.ts
+++ b/resources/client/client.ts
@@ -9,6 +9,7 @@ import './cl_notes';
import './cl_photo';
import './cl_messages';
import './cl_call';
+import './cl_match';
import './functions';
export const ClUtils = new ClientUtils();
diff --git a/resources/server/players/sv_players.ts b/resources/server/players/sv_players.ts
index ea51eeb..93a79db 100644
--- a/resources/server/players/sv_players.ts
+++ b/resources/server/players/sv_players.ts
@@ -104,11 +104,14 @@ async function getCleanedPlayerInfo(identifier: string): Promise {
+export async function generateProfileName(
+ identifier: string,
+ delimiter: string = '_',
+): Promise {
const { firstname, lastname, phone_number } = await getCleanedPlayerInfo(identifier);
if (firstname && lastname) {
- return `${firstname}_${lastname}`;
+ return `${firstname}${delimiter}${lastname}`;
} else if (firstname) {
return firstname;
} else if (lastname) {
diff --git a/resources/server/server.ts b/resources/server/server.ts
index 5ab17b5..e894106 100644
--- a/resources/server/server.ts
+++ b/resources/server/server.ts
@@ -9,6 +9,7 @@ import './sv_bank';
import './sv_notes';
import './sv_photo';
import './sv_messages';
+import './sv_match';
import './sv_call';
import './players/sv_player_events';
import { mainLogger } from './sv_logger';
diff --git a/resources/server/sv_match.ts b/resources/server/sv_match.ts
new file mode 100644
index 0000000..41c2137
--- /dev/null
+++ b/resources/server/sv_match.ts
@@ -0,0 +1,357 @@
+import { ResultSetHeader, RowDataPacket } from 'mysql2';
+
+import { pool } from './db';
+import { getIdentifier, getSource } from './functions';
+import config from '../utils/config';
+import { Like, Match, Profile, MatchEvents, NewProfile } from '../../typings/match';
+import { mainLogger } from './sv_logger';
+import { generateProfileName } from './players/sv_players';
+
+const matchLogger = mainLogger.child({ module: 'match' });
+const DEFAULT_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg';
+
+/**
+ * Select profiles that:
+ * 1. aren't the current player
+ * 2. haven't been viewed before
+ * 3. have been viewed before but that was at least 7 days ago
+ * @param identifier - players identifier
+ * @returns - array of profiles
+ */
+async function getPotentialProfiles(identifier: string): Promise {
+ const query = `
+ SELECT
+ npwd_match_profiles.*,
+ UNIX_TIMESTAMP(npwd_match_profiles.updatedAt) AS lastActive,
+ MaxDates.lastSeen
+ FROM npwd_match_profiles
+ LEFT OUTER JOIN (
+ SELECT id, profile, MAX(createdAt) AS lastSeen
+ FROM npwd_match_views
+ WHERE identifier = ?
+ GROUP BY id, profile
+ ) AS MaxDates ON npwd_match_profiles.id = MaxDates.profile
+ WHERE npwd_match_profiles.identifier != ? AND
+ (MaxDates.lastSeen IS NULL OR MaxDates.lastSeen < NOW() - INTERVAL 7 DAY)
+ ORDER BY npwd_match_profiles.updatedAt DESC
+ LIMIT 25
+ `;
+ const [results] = await pool.query(query, [identifier, identifier]);
+ const profiles = results;
+ return profiles;
+}
+
+/**
+ * Save a list of Like objects
+ * @param identifier - player's identifier
+ * @param likes - likes to be saved to the database
+ * @returns ResultSet
+ */
+async function saveLikes(identifier: string, likes: Like[]): Promise {
+ const query = `INSERT INTO npwd_match_views (identifier, profile, liked) VALUES ?`;
+ const formattedLikes = likes.map((like) => [identifier, like.id, like.liked]);
+
+ const results = await pool.query(query, [formattedLikes]);
+ const result = results;
+ return result;
+}
+
+/**
+ * Determines if a profile we just liked has already liked us in the past which
+ * indicates a match has occurred
+ * @param identifier - player's identifier
+ * @param id - profile ID we just liked
+ * @returns Profile[] - list of profiles that are a match
+ */
+async function checkForMatchById(identifier: string, id: number): Promise {
+ const query = `
+ SELECT
+ targetProfile.*,
+ UNIX_TIMESTAMP(targetProfile.updatedAt) AS lastActive
+ FROM npwd_match_views
+ LEFT OUTER JOIN npwd_match_profiles AS playerProfile ON npwd_match_views.profile = playerProfile.id
+ LEFT OUTER JOIN npwd_match_profiles AS targetProfile ON npwd_match_views.identifier = targetProfile.identifier
+ WHERE playerProfile.identifier = ? AND targetProfile.id = ? AND Liked = 1
+ `;
+ const [results] = await pool.query(query, [identifier, id]);
+ return results;
+}
+
+/**
+ * Given a list of likes determine if any of the profiles we liked have also
+ * liked us which indicates a match has occurred.
+ * @param identifier - player's identifier
+ * @param likes - list of new Likes
+ * @returns Profile[] - list of profiles we matched with
+ */
+async function findNewMatches(identifier: string, likes: Like[]): Promise {
+ let matches: Profile[] = [];
+ for (const like of likes) {
+ if (!like.liked) continue;
+ const matchedProfiles = await checkForMatchById(identifier, like.id);
+ matches = matches.concat(matchedProfiles);
+ }
+ return matches;
+}
+
+/**
+ * Return all matches associated with a player regardless of date/time. A
+ * match is a case where two profiles have liked each other.
+ * @param identifier - player's identifier
+ * @returns Match[] - all matches associated with the current player
+ */
+async function findAllMatches(identifier: string): Promise {
+ const query = `
+ SELECT
+ targetProfile.*,
+ UNIX_TIMESTAMP(targetProfile.updatedAt) AS lastActive,
+ UNIX_TIMESTAMP(GREATEST(npwd_match_views.createdAt, targetViews.createdAt)) AS matchedAt,
+ targetUser.phone_number AS phoneNumber
+ FROM npwd_match_views
+ LEFT OUTER JOIN npwd_match_profiles AS targetProfile ON npwd_match_views.profile = targetProfile.id
+ LEFT OUTER JOIN npwd_match_profiles AS myProfile ON npwd_match_views.identifier = myProfile.identifier
+ LEFT OUTER JOIN npwd_match_views AS targetViews ON targetProfile.identifier = targetViews.identifier AND targetViews.profile = myProfile.id
+ LEFT OUTER JOIN users AS targetUser ON targetProfile.identifier = targetUser.identifier
+ WHERE npwd_match_views.identifier = ? AND npwd_match_views.liked = 1 AND targetViews.liked = 1
+ ORDER BY matchedAt DESC
+ `;
+ const [results] = await pool.query(query, [identifier]);
+ return results;
+}
+
+/**
+ * Retrieve the current player's profile
+ * @param identifier - player's identifier
+ * @returns Profile - player's current profile
+ */
+async function getPlayerProfile(identifier: string): Promise {
+ const query = `
+ SELECT *,
+ UNIX_TIMESTAMP(updatedAt) AS lastActive
+ FROM npwd_match_profiles
+ WHERE identifier = ?
+ LIMIT 1
+ `;
+ const [results] = await pool.query(query, [identifier]);
+ const profiles = results;
+ return profiles[0];
+}
+
+/**
+ * Create a profile and associate it with the current player
+ * @param identifier - player's identifier
+ * @param profile - profile we are going to create
+ * @returns Profile - the created profile
+ */
+async function createProfile(identifier: string, profile: NewProfile): Promise {
+ const { name, image, bio, location, job, tags } = profile;
+ const query = `
+ INSERT INTO npwd_match_profiles (identifier, name, image, bio, location, job, tags)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ `;
+
+ await pool.execute(query, [identifier, name, image, bio, location, job, tags]);
+ return await getPlayerProfile(identifier);
+}
+
+/**
+ * Update the current player's profile
+ * @param identifier - player's identifier
+ * @param profile Profile - player's updated profile
+ */
+async function updateProfile(identifier: string, profile: Profile): Promise {
+ const { image, name, bio, location, job, tags } = profile;
+ const query = `
+ UPDATE npwd_match_profiles
+ SET image = ?, name = ?, bio = ?, location = ?, job = ?, tags = ?
+ WHERE identifier = ?
+ `;
+ await pool.execute(query, [image, name, bio, location, job, tags, identifier]);
+ return await getPlayerProfile(identifier);
+}
+
+/**
+ * Create a default profile for a player based on information
+ * associated with them (name, phone number, etc.)
+ * @param identifier - player's identifier
+ * @returns Profile | null - the player's profile or null if it does not exist
+ * and could not be created
+ */
+async function createDefaultProfile(identifier: string): Promise {
+ // case where the server owner wants players to select their own names
+ if (!config.match.generateProfileNameFromUsers) return null;
+
+ const defaultProfileName = await generateProfileName(identifier, ' ');
+ // case where we tried to generate a profile name but failed due to
+ // some database misconfiguration or error
+ if (!defaultProfileName) return null;
+
+ const defaultProfile = {
+ name: defaultProfileName,
+ image: DEFAULT_IMAGE,
+ bio: '',
+ location: '',
+ job: '',
+ tags: '',
+ };
+
+ matchLogger.info(`Creating default match profile ${defaultProfileName} for ${identifier}`);
+ return await createProfile(identifier, defaultProfile);
+}
+
+/**
+ * Retrieve the player's profile by their identifier if it exists. If
+ * not, create it and return it.
+ * @param identifier - player's identifier
+ * @returns Profile - player's profile
+ */
+export async function getOrCreateProfile(identifier: string): Promise {
+ const profile = await getPlayerProfile(identifier);
+ return profile || (await createDefaultProfile(identifier));
+}
+
+/**
+ * We track when the player last used the app so other players can
+ * be aware of how active that player is when they are liking/disliking
+ * @param identifier - player's identifier
+ */
+async function updateLastActive(identifier: string): Promise {
+ const query = `
+ UPDATE npwd_match_profiles
+ SET updatedAt = CURRENT_TIMESTAMP()
+ WHERE identifier = ?
+ `;
+ await pool.execute(query, [identifier]);
+}
+
+async function dispatchPlayerProfile(identifier: string, source: number): Promise {
+ try {
+ const profile = await getOrCreateProfile(identifier);
+ emitNet(MatchEvents.GET_MY_PROFILE_SUCCESS, source, profile);
+ } catch (e) {
+ matchLogger.error(`Failed to get player profile, ${e.message}`);
+ emitNet(MatchEvents.GET_MY_PROFILE_FAILED, source, {
+ message: 'APPS_MATCH_GET_MY_PROFILE_FAILED',
+ type: 'error',
+ });
+ }
+}
+
+async function dispatchProfiles(identifier: string, source: number): Promise {
+ try {
+ const profiles = await getPotentialProfiles(identifier);
+ emitNet(MatchEvents.GET_PROFILES_SUCCESS, source, profiles);
+ } catch (e) {
+ matchLogger.error(`Failed to retrieve profiles, ${e.message}`);
+ emitNet(MatchEvents.GET_PROFILES_FAILED, source, {
+ message: 'APPS_MATCH_GET_PROFILES_FAILED',
+ type: 'error',
+ });
+ }
+}
+
+onNet(MatchEvents.INITIALIZE, async () => {
+ const _source = getSource();
+ const identifier = getIdentifier(_source);
+ matchLogger.debug(`Initializing match for identifier: ${identifier}`);
+
+ await dispatchPlayerProfile(identifier, _source);
+ await dispatchProfiles(identifier, _source);
+ await updateLastActive(identifier);
+});
+
+onNet(MatchEvents.CREATE_MY_PROFILE, async (profile: Profile) => {
+ const _source = getSource();
+ const identifier = getIdentifier(_source);
+ matchLogger.debug(`Creating profile for identifier: ${identifier}`);
+ matchLogger.debug(profile);
+
+ try {
+ if (!profile.name || !profile.name.trim()) {
+ throw new Error('Profile name must not be blank');
+ }
+
+ const newProfile = await createProfile(identifier, profile);
+ emitNet(MatchEvents.CREATE_MY_PROFILE_SUCCESS, _source, newProfile);
+ } catch (e) {
+ matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
+ emitNet(MatchEvents.CREATE_MY_PROFILE_FAILED, _source, {
+ message: 'APPS_MATCH_CREATE_PROFILE_FAILED',
+ type: 'error',
+ });
+ }
+});
+
+onNet(MatchEvents.UPDATE_MY_PROFILE, async (profile: Profile) => {
+ const _source = getSource();
+ const identifier = getIdentifier(_source);
+ matchLogger.debug(`Updating profile for identifier: ${identifier}`);
+ matchLogger.debug(profile);
+
+ try {
+ if (!profile.name || !profile.name.trim()) {
+ throw new Error('Profile name must not be blank');
+ }
+
+ const updatedProfile = await updateProfile(identifier, profile);
+ emitNet(MatchEvents.UPDATE_MY_PROFILE_SUCCESS, _source, updatedProfile);
+ } catch (e) {
+ matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
+ emitNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, _source, {
+ message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
+ type: 'error',
+ });
+ }
+});
+
+onNet(MatchEvents.SAVE_LIKES, async (likes: Like[]) => {
+ const _source = getSource();
+ const identifier = getIdentifier(_source);
+ matchLogger.debug(`Saving likes for identifier ${identifier}`);
+
+ try {
+ await saveLikes(identifier, likes);
+ } catch (e) {
+ matchLogger.error(`Failed to save likes, ${e.message}`);
+ emitNet(MatchEvents.SAVE_LIKES_FAILED, _source, {
+ message: 'APPS_MATCH_SAVE_LIKES_FAILED',
+ type: 'error',
+ });
+ }
+
+ try {
+ const newMatches = await findNewMatches(identifier, likes);
+ if (newMatches.length > 0) {
+ emitNet(MatchEvents.NEW_MATCH, _source, {
+ message: 'APPS_MATCH_NEW_LIKE_FOUND',
+ type: 'info',
+ });
+ }
+ } catch (e) {
+ matchLogger.error(`Failed to find new matches, ${e.message}`);
+ }
+});
+
+onNet(MatchEvents.GET_MATCHES, async () => {
+ const _source = getSource();
+ const identifier = getIdentifier(_source);
+
+ try {
+ const matchedProfiles = await findAllMatches(identifier);
+ emitNet(MatchEvents.GET_MATCHES_SUCCESS, _source, matchedProfiles);
+ } catch (e) {
+ matchLogger.error(`Failed to retrieve matches, ${e.message}`);
+ emitNet(MatchEvents.GET_MATCHES_FAILED, _source, {
+ message: 'APPS_MATCH_GET_MATCHES_FAILED',
+ type: 'error',
+ });
+ }
+});
+
+if (!config.match.allowEdtiableProfileName && !config.match.generateProfileNameFromUsers) {
+ const warning =
+ `Both allowEdtiableProfileName and generateProfileNameFromUsers ` +
+ `are set false - this means users will likely not have profile names ` +
+ `for the Match App and won't be able to use it!`;
+ matchLogger.warn(warning);
+}
diff --git a/resources/server/sv_twitter.ts b/resources/server/sv_twitter.ts
index 2172025..2d78b75 100644
--- a/resources/server/sv_twitter.ts
+++ b/resources/server/sv_twitter.ts
@@ -516,3 +516,11 @@ onNet(TwitterEvents.REPORT, async (tweetId: number) => {
});
}
});
+
+if (!config.twitter.allowEdtiableProfileName && !config.twitter.generateProfileNameFromUsers) {
+ const warning =
+ `Both allowEdtiableProfileName and generateProfileNameFromUsers ` +
+ `are set false - this means users will likely not have profile names ` +
+ `for the Twitter App and won't be able to use it!`;
+ twitterLogger.warn(warning);
+}
diff --git a/resources/utils/apps.ts b/resources/utils/apps.ts
index dbc059f..dbc326d 100644
--- a/resources/utils/apps.ts
+++ b/resources/utils/apps.ts
@@ -1,5 +1,6 @@
export default {
TWITTER: 'TWITTER',
+ MATCH: 'MATCH',
MESSAGES: 'MESSAGES',
NOTES: 'NOTES',
MARKETPLACE: 'SELLOUT',
diff --git a/resources/utils/messages.ts b/resources/utils/messages.ts
index c978904..ea0b640 100644
--- a/resources/utils/messages.ts
+++ b/resources/utils/messages.ts
@@ -33,3 +33,7 @@ export function sendContactsEvent(method: string, data: any = {}) {
export function sendCameraEvent(method: string, data: any = {}) {
sendMessage(apps.CAMERA, method, data);
}
+
+export function sendMatchEvent(method: string, data: any = {}) {
+ return sendMessage(apps.MATCH, method, data);
+}
diff --git a/typings/config.ts b/typings/config.ts
index 5b97dbe..4090c76 100644
--- a/typings/config.ts
+++ b/typings/config.ts
@@ -12,6 +12,10 @@ interface TwitterConfig {
maxImages: number;
}
+interface MatchConfig {
+ generateProfileNameFromUsers: boolean;
+ allowEdtiableProfileName: boolean;
+}
interface Debug {
level: 'error' | 'warn' | 'info' | 'verbose' | 'debug';
enabled: boolean;
@@ -40,6 +44,7 @@ export interface IServerConfig {
DestoryChance: number;
DestroyPhoneReCheck: number;
twitter: TwitterConfig;
+ match: MatchConfig;
bank: BankConfig;
notificationPosition: NotificationConfig;
general: General;
diff --git a/typings/match.ts b/typings/match.ts
new file mode 100644
index 0000000..5799ad2
--- /dev/null
+++ b/typings/match.ts
@@ -0,0 +1,61 @@
+import { Contact } from './contact';
+
+export interface NewProfile {
+ name: string;
+ image: string;
+ bio: string;
+ job: string;
+ location: string;
+ tags: string;
+}
+
+export interface Profile extends NewProfile {
+ id: number;
+ identifier: string;
+ phoneNumber: string;
+ viewed: boolean;
+ createdAt: number;
+ updatedAt: number;
+ lastActive: number;
+}
+
+export interface FormattedProfile extends Profile {
+ lastActiveFormatted: string;
+ tagList: string[];
+}
+
+export interface Match extends Profile {
+ matchedAt: number;
+}
+
+export interface FormattedMatch extends FormattedProfile {
+ matchedAtFormatted: string;
+}
+
+export interface Like {
+ id: number; // profile id
+ liked: boolean;
+}
+
+export enum MatchEvents {
+ INITIALIZE = 'phone:initializeMatch',
+ GET_PROFILES = 'phone:getMatchProfiles',
+ GET_PROFILES_SUCCESS = 'phone:getMatchProfilesSuccess',
+ GET_PROFILES_FAILED = 'phone:getMatchProfilesError',
+ CREATE_MY_PROFILE = 'phone:createMyProfile',
+ CREATE_MY_PROFILE_SUCCESS = 'phone:createMyProfileSuccess',
+ CREATE_MY_PROFILE_FAILED = 'phone:createMyProfileError',
+ GET_MY_PROFILE = 'phone:getMyProfile',
+ GET_MY_PROFILE_SUCCESS = 'phone:getMyProfileSuccess',
+ GET_MY_PROFILE_FAILED = 'phone:getMyProfileError',
+ UPDATE_MY_PROFILE = 'phone:updateMyProfile',
+ UPDATE_MY_PROFILE_SUCCESS = 'phone:updateMyProfileSuccess',
+ UPDATE_MY_PROFILE_FAILED = 'phone:updateMyProfileError',
+ GET_MATCHES = 'phone:getMatches',
+ GET_MATCHES_SUCCESS = 'phone:getMatchesSuccess',
+ GET_MATCHES_FAILED = 'phone:getMatchesError',
+ SAVE_LIKES = 'phone:saveLikes',
+ SAVE_LIKES_SUCCESS = 'phone:saveLikesSuccess',
+ SAVE_LIKES_FAILED = 'phone:saveLikesError',
+ NEW_MATCH = 'phone:newMatchFound',
+}