Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Qna network #42

Merged
merged 3 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
EXPO_PUBLIC_API_BASE_URL=
EXPO_PUBLIC_DISABLE_ANALYTICS=true
EXPO_PUBLIC_QNA_API_BASE_URL=

EXPO_PUBLIC_DISABLE_ANALYTICS=true
5 changes: 5 additions & 0 deletions .github/workflows/preview.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ jobs:
runs-on: ubuntu-latest
env:
EXPO_PUBLIC_API_BASE_URL: ${{ vars.EXPO_PUBLIC_API_BASE_URL }}
EXPO_PUBLIC_QNA_API_BASE_URL: ${{ vars.EXPO_PUBLIC_QNA_API_BASE_URL }}
permissions:
contents: read
pull-requests: write
Expand All @@ -27,6 +28,10 @@ jobs:
echo "EXPO_PUBLIC_API_BASE_URL is not set"
exit 1
fi
if [ -z "${{ vars.EXPO_PUBLIC_QNA_API_BASE_URL }}" ]; then
echo "EXPO_PUBLIC_QNA_API_BASE_URL is not set"
exit 1
fi
- name: Checkout repository
uses: actions/checkout@v3

Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/update.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ jobs:
runs-on: ubuntu-latest
env:
EXPO_PUBLIC_API_BASE_URL: ${{ vars.EXPO_PUBLIC_API_BASE_URL }}
EXPO_PUBLIC_QNA_API_BASE_URL: ${{ vars.EXPO_PUBLIC_QNA_API_BASE_URL }}
steps:
- name: Check for EXPO_TOKEN
run: |
Expand All @@ -24,6 +25,10 @@ jobs:
echo "EXPO_PUBLIC_API_BASE_URL is not set"
exit 1
fi
if [ -z "${{ vars.EXPO_PUBLIC_QNA_API_BASE_URL }}" ]; then
echo "EXPO_PUBLIC_QNA_API_BASE_URL is not set"
exit 1
fi
- name: Checkout repository
uses: actions/checkout@v3

Expand Down
2 changes: 2 additions & 0 deletions app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ config();

const EXPO_PUBLIC_API_BASE_URL = env.get('EXPO_PUBLIC_API_BASE_URL').required().asString();
const EXPO_PUBLIC_DISABLE_ANALYTICS = env.get('EXPO_PUBLIC_DISABLE_ANALYTICS').default('false').asBool();
const EXPO_PUBLIC_QNA_API_BASE_URL = env.get('EXPO_PUBLIC_QNA_API_BASE_URL').required().asString();

export default ({ config }: ConfigContext) => {
return {
...config,
extra: {
apiBaseUrl: EXPO_PUBLIC_API_BASE_URL,
disableAnalytics: EXPO_PUBLIC_DISABLE_ANALYTICS,
qnaApiBaseUrl: EXPO_PUBLIC_QNA_API_BASE_URL,
...config.extra,
},
};
Expand Down
2 changes: 1 addition & 1 deletion components/qna/input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function Input({ placeholder, onSubmit, disabled = false }: InputProps) {
style={{
bottom: Math.max(130, keyboardOffset + 16),
}}
className='absolute left-0 right-0 mx-5 flex-row space-x-3 rounded-2xl bg-white dark:bg-slate-800 px-3 py-2 shadow-md max-h-60'
className='absolute left-0 right-0 mx-5 flex-row space-x-3 rounded-xl bg-white dark:bg-slate-800 px-3 py-2 shadow-md max-h-60'
>
<TextInput
ref={ref}
Expand Down
6 changes: 6 additions & 0 deletions components/qna/qna-question.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ export function QnaQuestion({ message }: QnaQuestionProps) {
className='bg-primary-500 dark:bg-primary-300 rounded-t-2xl rounded-bl-2xl p-3 mb-2 ml-5'
>
<StyledText className='text-white dark:text-slate-900 text-lg'>{message.text}</StyledText>
{message.status === 'pending' && (
<StyledText className='text-white/80 dark:text-slate-800/80 text-xs text-right'>Küldés...</StyledText>
)}
{message.status === 'error' && (
<StyledText className='text-white/80 dark:text-slate-800/80 text-xs text-right'>Hiba</StyledText>
)}
</Animated.View>
);
}
6 changes: 5 additions & 1 deletion components/qna/qna-screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export function QnaScreen() {

const remainingQuestions = MAX_QUESTION_COUNT - questionCount;

const onSubmission = (messageText: string) => {
messaging.sendMessageText(messageText, id);
};

return (
<Screen>
<Header>
Expand All @@ -63,7 +67,7 @@ export function QnaScreen() {
<Input
disabled={remainingQuestions === 0}
placeholder={`${t('qna.placeholder')} (${remainingQuestions} ${t('qna.remainingQuestions')})`}
onSubmit={messaging.sendMessageText}
onSubmit={onSubmission}
/>
</Screen>
);
Expand Down
1 change: 1 addition & 0 deletions config/env.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ import Constants from 'expo-constants';

export const API_BASE_URL = Constants.expoConfig?.extra?.apiBaseUrl;
export const DISABLE_ANALYTICS = Constants.expoConfig?.extra?.disableAnalytics;
export const QNA_API_BASE_URL = Constants.expoConfig?.extra?.qnaApiBaseUrl;
48 changes: 38 additions & 10 deletions hooks/use-messaging.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,38 @@
import { useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios, { isAxiosError } from 'axios';
import { useEffect, useState } from 'react';

import { QNA_API_BASE_URL } from '../config/env.config';
import { QnaMessage } from '../types/qna.type';
import { generateId } from '../utils/common.utils';

export function useMessaging() {
const [messages, setMessages] = useState<QnaMessage[]>([]);
const [userId, setUserId] = useState<string>();

const loadUserId = () => {
AsyncStorage.getItem('userId').then((userId) => {
if (!userId) {
userId = generateId();
AsyncStorage.setItem('userId', userId);
}
setUserId(userId);
});
};

const addMessage = (newMessage: QnaMessage) => {
setMessages((prevMessages) => [...prevMessages, newMessage]);
};

const updateMessage = (message: QnaMessage) => {
setMessages((prevMessages) => prevMessages.map((prevMessage) => (prevMessage === message ? message : prevMessage)));
setMessages((prevMessages) =>
prevMessages.map((prevMessage) => (prevMessage.id === message.id ? message : prevMessage))
);
};

const addAnswer = (answerText: string) => {
const newMessage: QnaMessage = {
id: generateId(),
kind: 'answer',
text: answerText,
isInitial: false,
Expand All @@ -23,31 +41,41 @@ export function useMessaging() {
addMessage(newMessage);
};

const sendMessageText = async (messageText: string) => {
const sendMessageText = (messageText: string, presentationId: string) => {
if (!userId) return;
const newMessage: QnaMessage = {
id: generateId(),
kind: 'question',
text: messageText,
isInitial: false,
status: 'pending',
};
addMessage(newMessage);
sendMessage(newMessage)
sendMessage(messageText, presentationId, userId)
.then(() => {
updateMessage({ ...newMessage, status: 'sent' });
addAnswer('Kérdésed megkaptuk és moderálás után a felolvasandó kérdések közé kerül. Köszönjük!');
})
.catch(() => {
.catch((e) => {
if (isAxiosError(e)) {
console.error('Error sending question', e.response?.data);
} else {
console.error('Error sending question', e);
}
updateMessage({ ...newMessage, status: 'error' });
});
};

useEffect(() => {
loadUserId();
}, []);

return { messages, sendMessageText };
}

async function sendMessage(message: QnaMessage) {
return await new Promise((resolve) => {
setTimeout(() => {
resolve(message);
}, 2000);
async function sendMessage(content: string, presentationId: string, userId: string) {
return await axios.post(`${QNA_API_BASE_URL}/api/presentation/${presentationId}/question`, {
content,
userId,
});
}
1 change: 1 addition & 0 deletions types/qna.type.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export type QnaMessage = {
id: string;
kind: 'question' | 'answer';
text: string;
isInitial: boolean;
Expand Down
7 changes: 7 additions & 0 deletions utils/common.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,10 @@ export function useSafeSlug() {
const { slug } = useLocalSearchParams();
return Array.isArray(slug) ? slug[0] : slug ?? '';
}

export function generateId(length = 16) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
Loading