react-native#ToastAndroid JavaScript Examples
The following examples show how to use
react-native#ToastAndroid.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserStarting.js From FlappyFace with MIT License | 6 votes |
async onContinueWithGoogle() {
try {
await GoogleSignin.hasPlayServices();
const {idToken} = await GoogleSignin.signIn();
const googleCredentials = auth.GoogleAuthProvider.credential(idToken);
return auth().signInWithCredential(googleCredentials);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
ToastAndroid.show('User Cancelled Sign In', ToastAndroid.SHORT);
} else if (error.code === statusCodes.IN_PROGRESS) {
ToastAndroid.show('Working', ToastAndroid.SHORT);
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
ToastAndroid.show(
'Please install Google Play Services!',
ToastAndroid.SHORT,
);
} else if (error.message === 'NETWORK_ERROR') {
ToastAndroid.show(
'We are having Network issues :<',
ToastAndroid.SHORT,
);
} else {
console.log(error.message);
}
}
}
Example #2
Source File: CalendarComponent.js From react-native-todolist with MIT License | 6 votes |
closeSyncDialog(visible) {
if (!visible) {
ToastAndroid.showWithGravityAndOffset(Utils.SYNC_CALENDAR_MSG,
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
25, 200);
}
this.setState({
syncDone: false,
syncDialogVisible: visible
})
}
Example #3
Source File: index.js From Cosmos with MIT License | 6 votes |
setComment(comment) {
if (comment.length >= 300) {
return ToastAndroid.showWithGravity(
'Sorry maximum comment length is 300 characters',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
}
this.setState({
comment,
});
}
Example #4
Source File: tools.js From lx-music-mobile with Apache License 2.0 | 6 votes |
toast = (message, duration = 'short', position = 'bottom') => {
switch (duration) {
case 'long':
duration = ToastAndroid.LONG
break
case 'short':
default:
duration = ToastAndroid.SHORT
break
}
switch (position) {
case 'top':
position = ToastAndroid.TOP
break
case 'center':
position = ToastAndroid.CENTER
break
case 'bottom':
default:
position = ToastAndroid.BOTTOM
break
}
ToastAndroid.show(message, duration, position)
}
Example #5
Source File: Utilities.js From hugin-mobile with GNU Affero General Public License v3.0 | 6 votes |
export function toastPopUp(message, short = true) {
/* IOS doesn't have toast support */
/* TODO */
if (Platform.OS === 'ios') {
return;
}
ToastAndroid.show(message, short ? ToastAndroid.SHORT : ToastAndroid.LONG);
}
Example #6
Source File: index.js From Cosmos with MIT License | 6 votes |
comment() {
const {comment, post} = this.state;
const {state} = this.context;
if (comment.length === 0) {
return ToastAndroid.showWithGravity(
'You forgot to write your comment ?',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
}
this.setState({commenting: true});
commentOnPost(state.box, post.name, comment)
.then(() => {
this.setState({
comment: '',
commenting: false,
});
})
.catch((err) => {
console.log(err.message);
this.setState({
commenting: false,
});
});
}
Example #7
Source File: firebase.js From Cosmos with MIT License | 6 votes |
reactToPost = (box, postName, reactiontype) => {
return new Promise(async (resolve, reject) => {
try {
const isReactionValid = ['love', 'meh', 'sad'].find(
(reaction) => reaction === reactiontype,
);
if (!isReactionValid) {
throw new Error('Invalid Reaction Type');
}
const uid = auth().currentUser.uid;
const name = postName.split('.')[0];
const post = await getPost(box, name);
if (Object.keys(post).includes(reactiontype)) {
const alreadyReacted = post[reactiontype].find((u) => u === uid);
if (alreadyReacted) {
post[reactiontype] = post[reactiontype].filter((u) => u !== uid);
await setPost(box, name, post);
return resolve();
} else {
post[reactiontype] = [...post[reactiontype], uid];
await setPost(box, name, post);
return resolve();
}
} else {
post[reactiontype] = [uid];
await setPost(box, name, post);
return resolve();
}
} catch (err) {
console.log(err);
ToastAndroid.showWithGravity(
err.message,
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
reject(err);
}
});
}
Example #8
Source File: PostHandlers.js From Cosmos with MIT License | 6 votes |
onDelete = (box, name, goBack) => {
Alert.alert('Delete Post', 'Are you sure you want to delete this post?', [
{text: 'cancel', onPress: () => {}},
{
text: 'Delete',
onPress: () => {
goBack();
database().ref(box).child(name.split('.')[0]).off();
deletePosts(box, name)
.then(() => {
ToastAndroid.showWithGravity(
'Post Deleted Successfully',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
})
.catch((err) => {
console.log('Error at onDelete:', err.message);
goBack();
});
},
},
]);
}
Example #9
Source File: Toast.js From duofolio with GNU General Public License v3.0 | 5 votes |
export default function RenderToast(message) {
ToastAndroid.showWithGravityAndOffset(message, ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 300);
}
Example #10
Source File: RemoveFriendModal.js From app with GNU General Public License v3.0 | 5 votes |
RemoveFriendModal = ({modalVisible,toggleVisibility,id}) => {
const {updateUser,user,token} = useContext(GlobalContext);
const [removingText,setRemovingText] = useState(false);
const removeFriend = () => {
console.log(id,"in remove");
setRemovingText(true);
axios.post(`${userApiUrl}/friends/removeFriend`,
{
friendId:id,
},{
headers: {
Authorization: "Bearer " + token,
},
})
.then(async (res) => {
console.log(res.data,"remove user data");
updateUser(res.data);
setRemovingText(false);
await AsyncStorage.setItem('user', JSON.stringify(res.data));
ToastAndroid.show("Friend Removed", ToastAndroid.SHORT);
}).catch((err) => {
setRemovingText(false);
console.log(err,"err");
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
}
}
})
}
const closeModal = () => {
console.log("lol closed");
toggleVisibility(!modalVisible);
}
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
toggleVisibility(!modalVisible);
}}>
<View style={styles.modalView}>
<Text style={{
color:"black",
fontSize:18,
marginLeft:15,
fontFamily:"NotoSans-Regular"
}}>
Are you sure you want to remove them as friends?
</Text>
<View style={{
marginLeft:"70%",
marginTop:20
}}>
<View style={{
flexDirection:"row",
justifyContent:"space-between",
right:100,
top:20,
}}>
<Button title="Yes" onPressFunction={removeFriend}>
{removingText ? "Pro.." : "Yes"}
</Button>
<Button title="No" onPressFunction={closeModal}>
No
</Button>
</View>
</View>
</View>
</Modal>
)
}
Example #11
Source File: CardApproval.js From id.co.moonlay-eworkplace-mobile with MIT License | 5 votes |
buttonApprove(){
const headers = {
'accept': 'application/json',
'Authorization': 'Bearer ' + this.props.tokenJWT
};
axios({
method: 'PUT',
url: Url_Clockin + '/' + this.props.person.Id,
headers: headers,
data : {
Name: this.props.person.Name,
Username: this.props.person.Username,
CheckIn: this.props.person.CheckIn,
CheckOut: this.props.person.CheckOut,
State: this.props.person.State,
Location: this.props.person.Location,
Approval: 'Approved',
Photo: this.props.person.Photo,
Note: this.props.person.Note,
ProjectName: this.props.person.ProjectName,
HeadDivision: this.props.person.HeadDivision,
ApprovalByAdmin: this.props.person.ApprovalByAdmin,
CompanyName: this.props.person.CompanyName,
ClientName: this.props.person.ClientName,
}
}).then((response) => {
console.log('Success: Approve')
this.setState({
visible: false
});
this.props.loadData();
ToastAndroid.showWithGravity(
'Approve success',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
);
}).catch((errorr) => {
console.log('Error: Approve')
this.setState({
visible: false
});
ToastAndroid.showWithGravity(
'Approve fail',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
);
});
}
Example #12
Source File: CardApproval.js From id.co.moonlay-eworkplace-mobile with MIT License | 5 votes |
buttonDecline(){
const headers = {
'accept': 'application/json',
'Authorization': 'Bearer ' + this.props.tokenJWT
};
axios({
method: 'PUT',
url: Url_Clockin+ '/' + this.props.person.Id,
headers: headers,
data : {
Name: this.props.person.Name,
Username: this.props.person.Username,
CheckIn: this.props.person.CheckIn,
CheckOut: this.props.person.CheckOut,
State: this.props.person.State,
Location: this.props.person.Location,
Approval: 'Declined',
Photo: this.props.person.Photo,
Note: this.props.person.Note,
ProjectName: this.props.person.ProjectName,
HeadDivision: this.props.person.HeadDivision,
ApprovalByAdmin: this.props.person.ApprovalByAdmin,
CompanyName: this.props.person.CompanyName,
ClientName: this.props.person.ClientName,
}
}).then((response) => {
console.log('Success: Decline')
this.setState({
visible: false
});
this.props.loadData();
ToastAndroid.showWithGravity(
'Decline success',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
);
}).catch((errorr) => {
console.log('Error: Decline')
this.setState({
visible: false
});
ToastAndroid.showWithGravity(
'Decline fail',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
);
});
}
Example #13
Source File: index.js From Cosmos with MIT License | 5 votes |
async continueWithGoogle() {
const {setUid} = this.context;
try {
await GoogleSignin.hasPlayServices();
const {idToken} = await GoogleSignin.signIn();
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
const resp = await auth().signInWithCredential(googleCredential);
return setUid(resp.user.uid);
} catch (error) {
console.log('Error while user clicked Continue With Google Button');
switch (error.code) {
case statusCodes.SIGN_IN_CANCELLED: {
ToastAndroid.showWithGravity(
'You dont like OAuth? ?',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
break;
}
case statusCodes.IN_PROGRESS: {
ToastAndroid.showWithGravity(
'Hey we are signing you in, chill ?',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
break;
}
case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: {
ToastAndroid.showWithGravity(
'Hey the Play Service was not found or is outdated ?',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
break;
}
default: {
console.log(error.code);
ToastAndroid.showWithGravity(
error.message,
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
}
}
}
}
Example #14
Source File: Apply.js From mobile with GNU General Public License v3.0 | 5 votes |
function Apply({email, url, position}) {
function emailNotSupported() {
Alert.alert(
'E-posta uygulaması bulunamadı!',
`${email} adresine "${position} Başvurusu" başlığı ile e-posta gönderebilirsiniz. E-posta adresini kopyalamak için başvuru düğmesine basılı tutabilirsiniz.`,
);
}
function onPressEmail() {
const email_url = `mailto:${email}?subject=${position} Başvurusu&body=%0A%0A%0A%0A-%0Akodilan.com aracılığıyla gönderilmiştir`;
Linking.canOpenURL(email_url)
.then(supported => {
if (supported) {
Linking.openURL(email_url);
} else {
emailNotSupported();
}
})
.catch(() => {
emailNotSupported();
});
}
function onPressUrl() {
Linking.openURL(url);
}
function onLongPressButton(text) {
Clipboard.setString(text);
if (Platform.OS === 'android') {
ToastAndroid.show('Bağlantı panoya kopyalandı.', ToastAndroid.SHORT);
} else {
Alert.alert('Bilgi', 'Bağlantı panoya kopyalandı.');
}
}
return (
<View style={styles.applyButtons}>
{email ? (
<TouchableOpacity
activeOpacity={0.8}
style={styles.applyButton}
onPress={() => onPressEmail()}
onLongPress={() => onLongPressButton(email)}>
<Icon name="mail" color="#FFF" size={20} />
<Text style={styles.applyButtonText}>E-Posta ile BaÅŸvur</Text>
</TouchableOpacity>
) : null}
{url ? (
<TouchableOpacity
activeOpacity={0.8}
style={[styles.applyButton, styles.applyButtonMargin]}
onPress={() => onPressUrl()}
onLongPress={() => onLongPressButton(url)}>
<Icon name="link" color="#FFF" size={20} />
<Text style={styles.applyButtonText}>Site Ãœzerinden BaÅŸvur</Text>
</TouchableOpacity>
) : null}
</View>
);
}
Example #15
Source File: index.js From Cosmos with MIT License | 4 votes |
render() {
const {image, imageCaption, isLoading} = this.state;
const {state} = this.context;
if (state.box.length === 0) {
return (
<View style={styles.addContainer}>
<Backpack size={width / 2.5} mood="sad" color="#FFD882" />
<Headline style={[Styles.fontMedium, styles.imgText]}>
Oops looks like you haven't created a group yet. Please go back to
the Home screen and take Sun's help to create one first
</Headline>
</View>
);
}
if (isLoading) {
return (
<View style={styles.addContainer}>
<BoxLoading />
</View>
);
}
if (image !== null) {
return (
<View style={styles.addContainer}>
<AppHeader
iconLeft="x"
onPressLeft={() => {
Alert.alert(
'Discard Post',
'Do you want to discard your post, all changes will be lost?',
[
{
text: 'Discard',
onPress: () =>
this.setState({
isLoading: false,
fileBlog: null,
image: null,
imageCaption: '',
}),
},
{
text: 'Cancel',
onPress: () => {},
},
],
{cancelable: true},
);
}}
iconRight="send"
onPressRight={this.onPostUpload}
/>
<ScrollView showsVerticalScrollIndicator={false}>
<View>
<Image style={styles.loadedImage} source={image} />
<View style={styles.captionContainer}>
<TextInput
value={imageCaption}
style={styles.textInputCaption}
onChangeText={(caption) => this.setImageCaption(caption)}
placeholder="Write a caption"
placeholderTextColor="white"
autoCapitalize="sentences"
autoFocus={true}
maxLength={300}
multiline={true}
numberOfLines={6}
textAlignVertical="top"
defaultValue="No Caption"
/>
</View>
</View>
</ScrollView>
</View>
);
}
return (
<View style={styles.addContainer}>
<Backpack size={width / 2.5} mood="excited" color="#FFD882" />
<Headline style={[Styles.fontMedium, styles.imgText]}>
Lets see what you got in your bag of pics, or I can help you get a
shot if you need help with that
</Headline>
<View style={styles.optionsContainer}>
<TouchableOpacity
style={styles.optionContainer}
onPress={() => {
if (state.box === '') {
return ToastAndroid.showWithGravity(
'No Box selected!',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
}
this.openImagePicker();
}}>
<Icon size={width * 0.06} name="plus" color="white" />
<Text style={Styles.fontMedium}>Open Bag</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.optionContainer}
onPress={() => {
if (state.box === '') {
return ToastAndroid.showWithGravity(
'No Box selected!',
ToastAndroid.SHORT,
ToastAndroid.CENTER,
);
}
this.openImageCamera();
}}>
<Icon size={width * 0.06} name="camera" color="white" />
<Text style={Styles.fontMedium}>Start Camera</Text>
</TouchableOpacity>
</View>
</View>
);
}
Example #16
Source File: ViewProfileScreen.js From app with GNU General Public License v3.0 | 4 votes |
ViewProfileScreen = ({route,navigation}) => {
const [color,setColor] = useState(color);
const [friendModalVisible, setFriendModalVisible] = useState(false);
const [pendingModalVisible,setPendingModalVisible] = useState(false);
const [listModalVisible,setListModalVisible] = useState(false);
const [refreshing,setRefreshing] = useState(false);
const [isSent,setIsSent] = useState(false);
const [areFriends,setAreFriends] = useState(false);
const {updateUser,user,token} = useContext(GlobalContext);
const {item} = route.params;
//Setting the initial state with the data coming from the route
const [currentUser,setCurrentUser] = useState(item);
const imageUrl = "https://images.unsplash.com/photo-1500048993953-d23a436266cf?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1949&q=80";
const renderer = ({item}) => {
return(
<TouchableOpacity onPress={() => {
navigation.navigate("PlaylistScreen",{
item
})
}}>
<List item = {item} />
</TouchableOpacity>
)
}
const openModal = () => {
setFriendModalVisible(true);
}
const showPending = () => {
setPendingModalVisible(true);
}
const createPlaylist = () => {
setListModalVisible(true);
}
console.log(currentUser._id,"id radio");
useEffect(() => {
const fetchUser = () => {
axios.post(`${userApiUrl}/user/getAUser`,{
userId:currentUser._id
},{
headers: {
Authorization: "Bearer " + token,
}
})
.then(async (res) => {
setRefreshing(false);
console.log(res.data,"data");
setCurrentUser(res.data);
}).catch((err) => {
setRefreshing(false);
console.log(err,"err");
})
}
if(refreshing !== false || areFriends === false ){
fetchUser();
}
},[refreshing,isSent,areFriends])
//Function to set the bg gradient simmilar to profile pic's colors
useEffect(() => {
const getDominantColors = async () => {
const colors = await ImageColors.getColors(imageUrl, {
fallback: '#7f8c8d',
});
if (colors.platform === 'android') {
const {lightVibrant,average} = colors;
if(lightVibrant === "#000000"){
averageColor = average;
}
else {
averageColor = lightVibrant;
}
setColor(averageColor);
} else {
const backgroundColor = colors.background;
setColor(backgroundColor);
}
return averageColor;
};
getDominantColors();
}, [imageUrl]);
const onRefresh = React.useCallback(() => {
setRefreshing(true);
}, []);
const genFunc = () => {
if(!isSent && !areFriends){
//Send request
axios.post(`${userApiUrl}/friends/addFriend`,{
friendId:currentUser._id,
},{
headers: {
Authorization: "Bearer " + token,
}
}).then((res) => {
setIsSent(true);
setAreFriends(false);
if (Platform.OS === 'android') {
ToastAndroid.show("Request sent successfully", ToastAndroid.SHORT);
}
}).catch((err) => {
// if (Array.isArray(err.response.data.errors)) {
// if (Platform.OS === 'android') {
// ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
// }
// }
console.log(err);
})
}
if(areFriends){
//Remove from friends
axios.post(`${userApiUrl}/friends/removeFriend`,
{
friendId:currentUser._id,
},{
headers: {
Authorization: "Bearer " + token,
}
})
.then(async (res) => {
setAreFriends(false);
setIsSent(false);
updateUser(res.data);
await AsyncStorage.setItem('user', JSON.stringify(res.data));
ToastAndroid.show(`Friendship ended with ${currentUser.name}`, ToastAndroid.SHORT);
}).catch((err) => {
console.log(err,"err");
// if (Array.isArray(err.response.data.errors)) {
// if (Platform.OS === 'android') {
// ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
// }
// }
})
}
}
useEffect(() => {
//Checking if the auth user has sent request to the currentUser
currentUser.pending.map((peep) => {
if(peep == user._id){
setIsSent(true);
}
})
//Checking if the auth user is friends with the current user
currentUser.friends.map((peep) => {
if(peep._id === user._id){
setAreFriends(true);
}
})
},[refreshing])
return (
<LinearGradientComp
bgcolors={{
colorOne: '#2b4162',
colorTwo: ACCENT,
}}>
<PlayListModal
toggleVisibility={setListModalVisible}
modalVisible={listModalVisible}
/>
<FriendsModal
currentUser={true}
data={currentUser ? currentUser.friends : user.friends}
toggleVisibility={setFriendModalVisible}
modalVisible={friendModalVisible}
/>
<PendingRequestsModal
data = {user.pending}
toggleVisibility={setPendingModalVisible}
modalVisible={pendingModalVisible}
/>
<ScrollView
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
/>
}
>
<View style={{
flexDirection:"column",
justifyContent:"space-between",
alignItems:"center",
marginTop:"20%"
}}>
<Image
source={{uri: currentUser.photo}}
style={{
borderRadius: 70,
width: 140,
height: 140,
}} />
<View style={{
alignItems:"center",
flexDirection:'column',
}}>
<Text style={{
...styles.text,
top:"-15%"
}}>
{currentUser.username}
</Text>
<Button buttonStyle={{
width:100,
height:50,
marginRight:"17.5%",
borderRadius:8
}}
backColor = {areFriends ? "red" : ""}
textStyles = {{
fontSize:20,
marginTop:5,
}}
title="Send" onPressFunction={genFunc}>
{
areFriends ? "Remove" : (
isSent ? "Sent" : "Send"
)
}
</Button>
</View>
</View>
<View style={{
flexDirection:"row",
justifyContent:"space-around",
marginTop:20,
}}>
<View style={{
flexDirection:"column",
}}>
<TouchableOpacity onPress={openModal}>
<Text style={{
...styles.text,
fontWeight:"bold",
fontFamily:"NotoSans-Regular",
fontSize:20,
top:"8%"
}}>
{currentUser.friends.length}
</Text>
<Text style={{
...styles.text,
fontFamily:"5NotoSans-Regular",
fontSize:20,
top:"8%"
}}>
Friends
</Text>
</TouchableOpacity>
</View>
<View style={{
flexDirection:"column"
}}>
<Text style={{
...styles.text,
fontFamily:"NotoSans-Regular",
fontSize:20,
fontWeight:"bold"
}}>
{currentUser.playlists.length}
</Text>
<Text style={{
...styles.text,
fontFamily:"NotoSans-Regular",
fontSize:20
}}>
Playlists
</Text>
</View>
</View>
</ScrollView>
{currentUser.playlists.length > 0 ? (
<>
<Text style={{
...styles.text,
marginLeft:"5%",
marginBottom:"5%",
marginTop:"-45%"
}}>
Public Playlists</Text>
<ScrollView>
<FlatList
keyExtractor={(item) => (item._id).toString()}
data= {currentUser.playlists}
renderItem={renderer}
showsVerticalScrollIndicator={false}
/>
</ScrollView>
</>
):(
<View style={{
marginBottom:"40%",
alignItems:"center",
flexDirection:'column'
}}>
<Text style={{
color:"white",
fontSize:24,
opacity:0.8,
fontFamily:"Noto-Sans"
}}>
The User has no playlist!
</Text>
<Text style={{
color:"white",
fontSize:24,
opacity:0.8,
marginTop:"2%",
fontFamily:"Noto-Sans"
}}>
Send them a song maybe?
</Text>
</View>
)}
</LinearGradientComp>
)
}
Example #17
Source File: ChatScreen.js From app with GNU General Public License v3.0 | 4 votes |
ChatScreen = ({navigation}) => { const [searchQuery, setSearchQuery] = useState(''); const {user,updateMessages,messages,token,queue} = useContext(GlobalContext); const [refreshing,setRefreshing] = useState(false); const search = () => { console.log('in search frands'); }; //?Todo On first login it wont get messages from global queue, so pass it from the messaging //?Todo screen only console.log(messages,"messages from gs"); const dateFunc = (dynamicDate) => { const d = new Date(dynamicDate); const today = new Date(); const diff = parseInt(((today - d)/60000)); if(diff>0 && diff<60){ return `${diff} mins`; } else if(diff > 60 && diff < 1440){ return `${parseInt(diff/60)} hours` } else if(diff > 1440 && diff < 10800){ return `${parseInt(diff/1440)} days` } else if(diff > 10080 && diff < 43200){ return `${parseInt(diff/10080)} weeks` } else if(diff > 43200 && diff < 518400){ return `${parseInt(diff/43200)} months` } else{ return `${diff} secs` } } useEffect(() => { if(messages.length === 0 || refreshing){ console.log("in") axios.get(`${userApiUrl}/messages/getMessages`,{ headers: { Authorization: "Bearer " + token, } }) .then(async (res) => { console.log(res.data,"from local messages"); updateMessages(res.data); setRefreshing(false); await AsyncStorage.setItem("messages",JSON.stringify(res.data)); }).catch((err) => { console.log(err,"err"); setRefreshing(false); if (Platform.OS === 'android') { ToastAndroid.show("Network Error", ToastAndroid.SHORT); } }) } },[refreshing]) const onRefresh = useCallback(() => { setRefreshing(true); }, []); const renderer = ({item}) => { const pressChatBox = () => { navigation.navigate("MessagingScreen",{ item }) } return ( <View key={item._id} style={{ flexDirection: 'column', marginVertical:"5%", height: '10%', marginBottom: "12%" }}> <TouchableOpacity onPress={pressChatBox} style={{ flexDirection: 'row', }}> <Image source={{uri: item.to._id !== user._id ? item.to.photo : item.user.photo}} style={{ borderRadius: 20, left: 10, width: 50, height: 50, }} /> <View style={{ flex: 1, }}> <View style={{ flexDirection: 'row', }}> <Text style={{ ...styles.options, marginLeft:30 }}> {item.to._id !== user._id ? item.to.username.length > 30 ? item.to.username.substring(0, 30) + '...' : item.to.username : ( item.user.username.length > 30 ? item.user.username.substring(0, 30) + '...' : item.user.username ) } </Text> </View> <View style={{ maxWidth: '80%', flexDirection: 'row', }}> <View style={{ width:"90%" }}> <Text style={{ ...styles.options, fontSize: 14, marginLeft:30, marginTop: 2, fontFamily: 'NotoSans-Regular', }}> {`${item.chat[item.chat.length-1].user._id === user._id ? "You" : item.chat[item.chat.length-1].user.username} shared ${item.chat[item.chat.length-1].message.trackName}`}. </Text> </View> <Text style={{ ...styles.options, opacity:0.75, marginTop: -25, marginLeft:10, }}> {dateFunc(item.chat[item.chat.length-1].messageSentAt)} </Text> </View> </View> </TouchableOpacity> </View> ) } return ( <LinearGradientComp bgcolors={{ colorOne: "rgb(15, 15, 15)", colorTwo: "rgb(15, 15, 15)", }}> <ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> } > <Text style={{ marginTop:"15%", fontSize: 26, color: 'white', marginBottom: 10, marginLeft: 20, letterSpacing: 0, fontFamily: 'NotoSans-Regular', }}> Messages </Text> <View style={{ marginBottom:20 }}> { messages.length > 0 ? ( <FlatList keyExtractor={(item) => item._id} data={messages} renderItem={renderer} showsVerticalScrollIndicator={false} /> ) :( <> <FillerContent extraStyles={true} text={"No messages to Show"} /> </> ) } </View> </ScrollView> {queue && queue.length > 0 ? <MiniPlayer nav={navigation} /> : null} </LinearGradientComp> ); }
Example #18
Source File: UsernameScreen.js From app with GNU General Public License v3.0 | 4 votes |
UsernameScreen = ({navigation}) => {
const [username,setUsername] = useState('');
const [submitting, isSubmitting] = useState(false);
const [color,setColor] = useState("");
const {user,updateUser,token} = useContext(GlobalContext);
const handleUsernameChange= (text) => setUsername(text);
useEffect(() => {
const getDominantColors = async () => {
const colors = await ImageColors.getColors(BG, {
fallback: '#7f8c8d',
});
if (colors.platform === 'android') {
averageColor = colors.average;
setColor(averageColor);
} else {
const backgroundColor = colors.background;
setColor(backgroundColor);
}
return averageColor;
};
getDominantColors();
}, []);
const handleUpdateUsername = () => {
isSubmitting(true);
axios.post(`${userApiUrl}/user/updateUsername`,{
username,
email:user.email,
},{
headers: {
Authorization: "Bearer " + token,
},
}).then(async (result) => {
console.log(result.data,"data");
isSubmitting(false);
updateUser(result.data.user);
await AsyncStorage.setItem('user', JSON.stringify(result.data.user));
if (Platform.OS === 'android') {
ToastAndroid.show('Username added successfully', ToastAndroid.SHORT);
}
navigation.dispatch(StackActions.replace('MainApp'));
}).catch((err) => {
console.log(err.response.data.message,"error");
isSubmitting(false);
if (Platform.OS === 'android') {
ToastAndroid.show(err?.response?.data?.message, ToastAndroid.SHORT);
}
})
};
return (
<LinearGradientComp
bgcolors={{
colorOne: "#2d3436",
colorTwo: "#000000",
}}>
{/* <KeyboardAvoidingView
keyboardVerticalOffset={-height / 2}
style={{flex: 1, alignItems: 'center'}}
behavior="position"> */}
{/* <View style={{backgroundColor:"white", paddingHorizontal: 10}}> */}
<View
style={{
flex: 0.5,
justifyContent: 'center',
marginTop:height/3,
margin:30,
minHeight: height / 10,
maxHeight: height / 2.5,
}}>
<View
style={{flexDirection: 'column',marginBottom:60, alignItems:"center"}}>
<Image
source={LOGO}
style={{height:height/4, width: width/2}}
/>
<Text style={{
color:"white",
fontSize:26,
// marginRight: "5%",
letterSpacing:1,
marginBottom:5,
alignContent: "center",
fontWeight:"bold"
}}>{"Pick a username"}</Text>
</View>
<InputBox
style={{
backgroundColor: "transparent",
color: "white",
fontSize: 16,
borderLeftWidth:0,
borderRightWidth:0,
borderTopWidth:0,
borderWidth: 1,
}}
label="Username"
value={username}
onChangeText={handleUsernameChange}
autoCapitalize={'none'}
autoCompleteType={'username'}
/>
<View style={{
flexDirection:"row",
justifyContent:"center",
marginTop:50
}}>
<Btn
style={{
width:width/3,
color: "black",
backgroundColor:"rgb(243, 244, 246)"
}}
title={"Let's Go!"}
loading={submitting}
loadingText={"Loading"}
onPress={handleUpdateUsername}
/>
</View>
</View>
</LinearGradientComp>
);
}
Example #19
Source File: SignupScreen.js From app with GNU General Public License v3.0 | 4 votes |
LoginScreen = ({navigation}) => {
const [name,setName] = useState("");
const [phone,setPhone] = useState("");
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [submitting, isSubmitting] = useState(false);
const [color,setColor] = useState("");
const {updateUser,updateToken} = useContext(GlobalContext);
const handleNameChange = (text) => setName(text);
const handlePhoneChange = (text) => setPhone(text);
const handleEmailChange = (text) => setEmail(text);
const handlePasswordChange = (text) => setPassword(text);
const handleSignIn = () => {
navigation.navigate("LoginScreen");
};
useEffect(() => {
const getDominantColors = async () => {
const colors = await ImageColors.getColors(BG, {
fallback: '#7f8c8d',
});
if (colors.platform === 'android') {
averageColor = colors.average;
setColor(averageColor);
} else {
const backgroundColor = colors.background;
setColor(backgroundColor);
}
return averageColor;
};
getDominantColors();
}, []);
const handleSignUp = () => {
const re=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (!name || !email || !phone || !password) {
if (Platform.OS === 'android') {
ToastAndroid.show('Field cannot be empty', ToastAndroid.SHORT);
}
} else {
if (!email.match(re)) {
if (Platform.OS === 'android') {
ToastAndroid.show('Invalid Email', ToastAndroid.SHORT);
}
} else {
isSubmitting(true);
axios.post(`${userApiUrl}/user/signup`,{
name,
phone,
email,
password
}).then(async () => {
isSubmitting(false);
if (Platform.OS === 'android') {
ToastAndroid.show('Signup Successful', ToastAndroid.SHORT);
}
navigation.navigate("LoginScreen");
}).catch((err) => {
isSubmitting(false);
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
}
}
})
}
}
}
return (
// <SafeAreaView style={{flex: 0.5,flexDirection:"column", justifyContent: 'center'}}>
<LinearGradientComp
bgcolors={{
// colorOne: PRIMARY,
colorOne: "#004e92",
colorTwo: "#000428",
}}>
{/* <KeyboardAvoidingView
keyboardVerticalOffset={-height / 2}
style={{flex: 1, alignItems: 'center'}}
behavior="position"> */}
{/* <View style={{backgroundColor:"white", paddingHorizontal: 10}}> */}
<View
style={{
flex: 0.5,
justifyContent: 'center',
marginTop:height/3,
margin:30,
minHeight: height / 10,
maxHeight: height / 2.5,
}}>
<View
style={{flexDirection: 'column',marginBottom:60, alignItems:"center"}}>
<Image
source={LOGO}
style={{height:height/4, width: width/2}}
/>
<Text style={{
color:"white",
fontSize:26,
marginRight: "5%",
letterSpacing:1,
marginBottom:5,
alignContent: "center",
fontWeight:"bold"
}}>{"Sign Up"}</Text>
</View>
<InputBox
style={{
backgroundColor: "transparent",
color: "white",
fontSize: 16,
borderLeftWidth:0,
borderRightWidth:0,
borderTopWidth:0,
borderWidth: 1,
}}
label="Name"
value={name}
onChangeText={handleNameChange}
autoCapitalize={'none'}
/>
<InputBox
style={{
backgroundColor: "transparent",
color: "white",
fontSize: 16,
borderLeftWidth:0,
borderRightWidth:0,
borderTopWidth:0,
borderWidth: 1,
}}
label="Phone"
value={phone}
onChangeText={handlePhoneChange}
autoCapitalize={'none'}
/>
<InputBox
style={{
backgroundColor: "transparent",
color: "white",
fontSize: 16,
borderLeftWidth:0,
borderRightWidth:0,
borderTopWidth:0,
borderWidth: 1,
}}
label="Email"
value={email}
onChangeText={handleEmailChange}
autoCapitalize={'none'}
/>
<InputBox
style={{
backgroundColor: "transparent",
color: "white",
borderLeftWidth:0,
fontSize: 16,
borderRightWidth:0,
borderTopWidth:0,
borderWidth: 1,
}}
label="Password"
value={password}
onChangeText={handlePasswordChange}
textContentType={'password'}
autoCompleteType={'password'}
secureTextEntry={true}
viewStyle={{marginBottom: 2}}
/>
<View style={{
flexDirection:"row",
justifyContent:"center",
marginTop:50
}}>
<Btn
style={{
width:width/3,
color: "black",
backgroundColor:"rgb(243, 244, 246)"
}}
title={"SignUp"}
onPress={handleSignUp}
loading={submitting}
loadingText={"Loading"}
/>
</View>
<Text onPress={handleSignIn} style={{textAlign: 'center', margin:30, color:"white", fontSize: 16}}>
{"Already have an account? Sign In"}
<Icon name="arrow-forward" style={{fontSize: 15}} />
</Text>
</View>
</LinearGradientComp>
);
}
Example #20
Source File: LoginScreen.js From app with GNU General Public License v3.0 | 4 votes |
LoginScreen = ({navigation}) => {
const [color,setColor] = useState("");
const {updateUser,updateIsAuthenticated,updateToken} = useContext(GlobalContext);
useEffect(() => {
const getDominantColors = async () => {
const colors = await ImageColors.getColors(BG, {
fallback: '#7f8c8d',
});
if (colors.platform === 'android') {
averageColor = colors.average;
setColor(averageColor);
} else {
const backgroundColor = colors.background;
setColor(backgroundColor);
}
return averageColor;
};
getDominantColors();
}, []);
useEffect(() => {
GoogleSignin.configure({
webClientId
});
const subscriber = auth().onAuthStateChanged(async(user) => {
if (user) {
console.log(user,"user");
axios.post(`${userApiUrl}/user/signup`,{
name:user.displayName,
email:user.email,
photo:user.photoURL
}).then(async (result) => {
console.log(result.data,"data");
updateUser(result.data.user);
await AsyncStorage.setItem('user', JSON.stringify(result.data.user));
updateToken(result.data.token);
await AsyncStorage.setItem('token',JSON.stringify(result.data.token));
updateIsAuthenticated(true);
await AsyncStorage.setItem('isAuthenticated',JSON.stringify(true));
if (Platform.OS === 'android') {
ToastAndroid.show('Login Successful', ToastAndroid.SHORT);
}
//If username present
if(result.data.user.username) {
navigation.dispatch(StackActions.replace('MainApp'));
}
else{
navigation.navigate("UsernameScreen");
}
}).catch((err) => {
console.log(err);
if (Platform.OS === 'android') {
ToastAndroid.show('Network Error', ToastAndroid.SHORT);
}
})
}
});
return subscriber;
}, []);
async function onGoogleButtonPress() {
// Get the users ID token
const { idToken } = await GoogleSignin.signIn();
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
}
return (
<LinearGradientComp
bgcolors={{
colorOne: "#2d3436",
colorTwo: "#000000",
}}>
{/* <KeyboardAvoidingView
keyboardVerticalOffset={-height / 2}
style={{flex: 1, alignItems: 'center'}}
behavior="position"> */}
{/* <View style={{backgroundColor:"white", paddingHorizontal: 10}}> */}
<View
style={{
flex: 0.4,
justifyContent: 'center',
marginTop:height/5,
margin:30,
minHeight: height / 10,
maxHeight: height / 2.5,
}}>
<View
style={{flexDirection: 'column',marginBottom:50, alignItems:"center"}}>
<Image
source={LOGO}
style={{height:height/4, width: width/2, marginBottom: 50}}
/>
<Text style={{
color:"white",
fontSize:26,
// marginRight: "5%",
letterSpacing:1,
marginBottom:20,
alignContent: "center",
fontWeight:"bold"
}}>{"Welcome Aboard!"}</Text>
</View>
<View style={{
justifyContent:"center",
alignItems:'center'
}}>
<GoogleSigninButton
style={{ width: 192, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={onGoogleButtonPress}
/>
</View>
</View>
</LinearGradientComp>
);
}
Example #21
Source File: MiniPlayer.js From app with GNU General Public License v3.0 | 4 votes |
MiniPlayer = (props) => {
const [liked, setLiked] = useState(false);
const {queue,selectedTrack,updatePausedState,pausedState,likedSongs,updateLikedSongs} = useContext(GlobalContext);
const onPressPlay = () => {
updatePausedState(false);
MusicControl.updatePlayback({
state: MusicControl.STATE_PLAYING,
})
};
const onPressPause = () => {
MusicControl.updatePlayback({
state: MusicControl.STATE_PAUSED,
})
updatePausedState(true);
}
useEffect(() => {
let c=0;
console.log("in mini");
likedSongs.map((song) => {
if(song._id == queue[selectedTrack]?.id){
setLiked(true);
c++;
return;
}
})
if(c==0){
setLiked(false);
}
},[props])
const onPressLike = () => {
if(!liked) {
setLiked(true);
const trackDetails = likedSongs;
trackDetails.push({
trackName: queue[selectedTrack].title,
artistName: queue[selectedTrack].artist,
albumArt: queue[selectedTrack].artwork,
trackUrl: queue[selectedTrack].url,
_id:queue[selectedTrack].id
});
updateLikedSongs(trackDetails);
const persistingData = async () => {
await AsyncStorage.setItem(
'likedSongs',
JSON.stringify(trackDetails),
);
};
persistingData();
ToastAndroid.show("Added to liked songs",ToastAndroid.SHORT);
}
else {
setLiked(false);
let trackDetails = likedSongs;
console.log(trackDetails,"current liked");
let newLikedSongs = trackDetails.filter((song) => {
return song._id !== queue[selectedTrack].id
})
console.log(newLikedSongs,"new liked songs");
updateLikedSongs(newLikedSongs);
const persistingData = async () => {
await AsyncStorage.setItem(
'likedSongs',
JSON.stringify(newLikedSongs),
);
};
persistingData();
ToastAndroid.show("Removed from liked songs",ToastAndroid.SHORT);
}
};
const openMiniPlayer = () => {
props.nav.navigate('PlayerScreen');
};
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.mainContainer}
onPress={openMiniPlayer}>
<Image
style={{
width: 50,
height: 50,
borderRadius: 8,
marginLeft: 8,
}}
source={{
uri: queue[selectedTrack].artwork,
}}
/>
<View
style={{
marginLeft: 15,
}}>
<Text
style={{
...styles.text,
fontSize: 16,
paddingBottom: 2,
fontWeight: 'bold',
}}>
{queue[selectedTrack].title.length > 20
? queue[selectedTrack].title.substring(0, 20) + '...'
: queue[selectedTrack].title}
</Text>
<Text style={styles.text}>
{queue[selectedTrack].artist.length > 20
? queue[selectedTrack].artist.substring(0, 20) + '...'
: queue[selectedTrack].artist}
</Text>
</View>
</TouchableOpacity>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
width: 80,
marginRight: 20,
justifyContent: 'space-between',
}}>
<TouchableOpacity onPress={onPressLike}>
{liked ? (
<Icon
size={30}
name="heart"
style={[
{
color: defaultString.darkColor,
},
]}
/>
) : (
<Icon
size={30}
name="heart-outline"
style={[
{
color: defaultString.darkColor,
},
]}
/>
)}
</TouchableOpacity>
{!pausedState ?
(
<TouchableOpacity onPress={onPressPause}>
<Icon
size={30}
name="pause-outline"
style={{
color: defaultString.darkColor,
}}
/>
</TouchableOpacity>
) :
(
<TouchableOpacity onPress={onPressPlay}>
<Icon
size={30}
name="play-outline"
style={{
color: defaultString.darkColor,
}}
/>
</TouchableOpacity>
)}
</View>
</View>
);
}
Example #22
Source File: Player.js From app with GNU General Public License v3.0 | 4 votes |
Player = (props) => {
//Context
const {updateColor,selectedTrack,updateSelectedTrack,queue,updateQueue,
updatePausedState,pausedState,likedSongs,updateLikedSongs
} = useContext(GlobalContext);
// const [paused, setPaused] = useState(true);
const [totalLength, setTotalLength] = useState(1);
const [currentPosition, setCurrentPosition] = useState(0);
const [repeatOn, setRepeatOn] = useState(false);
const [shuffleOn, setShuffleOn] = useState(false);
const [isChanging, setIsChanging] = useState(false);
const [color, setColor] = useState('');
const [liked, setLiked] = useState(false);
const [loading,setLoading] = useState(false);
const audioElement = useRef(null);
const selectedSongData = {
track_name:queue[selectedTrack].title,
album_image:queue[selectedTrack].artwork,
artist_name:queue[selectedTrack].artist,
track_url:queue[selectedTrack].url,
track_id:queue[selectedTrack].id
}
const setDuration = (data) => {
setLoading(false);
setTotalLength(Math.floor(data.duration));
};
const loadingStarts = () => {
setLoading(true);
}
useEffect(() => {
let c=0;
likedSongs.map((song) => {
if(song._id == queue[selectedTrack]?.id){
setLiked(true);
c++;
return;
}
})
if(c==0){
setLiked(false);
}
},[selectedTrack,props])
useEffect(() => {
if(queue[selectedTrack]?.url.slice((queue[selectedTrack].url.length)-11,queue[selectedTrack.length]) == "None_96.mp4") {
ToastAndroid.show("This song is currently not available", ToastAndroid.LONG);
}
},[selectedTrack])
console.log(queue,"queue");
useEffect(() => {
//Pausing song on coming to end
if(selectedTrack === queue.length - 1 && !repeatOn && loading){
//Add simmilar songs to the queue
if(queue[selectedTrack].id !== "trending"){
axios
.post(
`${apiUrl}recommend`,
{
ref_id: track.id
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((res) => {
const result = res.data;
console.log(result,"result");
const tracks = queue;
// for(let i =3,j=1;i<res.data.length;i+=3,j++){
let i = Math.floor(Math.random() * (10)) +0;
console.log(i,"value of i")
tracks[selectedTrack+1] = {
title : result[i].track_name,
artist: result[i].artist_name,
artwork: result[i].album_image,
url: result[i].track_url,
id: result[i].track_id,
}
// }
updateQueue(tracks);
const persistingData = async () => {
await AsyncStorage.setItem(
'queue',
JSON.stringify(tracks),
);
};
persistingData();
})
.catch((err) => {
console.log("lol");
console.log(err,"err");
});
}
else{
console.log("in trending");
axios
.get(
`${apiUrl}trending/tracks`,
)
.then((res) => {
const result = res.data;
console.log(result,"result");
const tracks = queue;
let i = 4;
tracks[selectedTrack+1] = {
title : result[i].track_name,
artist: result[i].artist_name,
artwork: result[i].album_image,
url: result[i].track_url,
id: result[i].ref_id,
}
updateQueue(tracks);
const persistingData = async () => {
await AsyncStorage.setItem(
'queue',
JSON.stringify(tracks),
);
};
persistingData();
})
.catch((err) => {
console.log(err,"err");
});
}
}
},[selectedTrack, loading, repeatOn])
//?Todo use useMemo in Controls' child components and you dont want them to rerender
//?todo when this parent component re renders(upon every 250ms of playing)
useEffect(() => {
MusicControl.setNowPlaying({
title:queue[selectedTrack].title,
artwork:queue[selectedTrack].artwork,
artist:queue[selectedTrack].artist,
description:"rezonance",
color:0xffffff,
rating: 1,
duration:totalLength,
notificationIcon: 'my_custom_icon',
})
MusicControl.on(Command.pause, () => {
MusicControl.updatePlayback({
state: MusicControl.STATE_PAUSED,
})
updatePausedState(true);
})
MusicControl.on(Command.closeNotification, ()=> {
console.log("true");
})
MusicControl.on(Command.play,() => {
MusicControl.updatePlayback({
state: MusicControl.STATE_PLAYING,
})
updatePausedState(false);
// await AsyncStorage.setItem('pausedState',false);
})
MusicControl.on(Command.nextTrack, ()=> {
onForward();
})
MusicControl.on(Command.previousTrack, ()=> {
onBack();
})
MusicControl.enableBackgroundMode(true);
MusicControl.enableControl('play', true);
MusicControl.enableControl('pause', true);
MusicControl.enableControl('nextTrack', true);
MusicControl.enableControl('previousTrack', true);
MusicControl.enableControl('changePlaybackPosition', true)
MusicControl.enableControl('seek', true) // Android only
MusicControl.enableControl('setRating', false)
MusicControl.enableControl('volume', true) // Only affected when remoteVolume is enabled
MusicControl.enableControl('remoteVolume', false)
MusicControl.enableControl('closeNotification', true, { when: 'paused' })
MusicControl.setNotificationId(1, 'channel');
},[selectedTrack,props])
const setTime = (data) => {
setCurrentPosition(Math.floor(data.currentTime));
};
const seek = (time) => {
time = Math.round(time);
audioElement.current && audioElement.current.seek(time);
setCurrentPosition(time);
updatePausedState(false);
};
const onBack = () => {
if (currentPosition < 10 && selectedTrack > 0) {
audioElement.current && audioElement.current.seek(0);
setIsChanging(true);
setTimeout(() => {
setCurrentPosition(0);
updatePausedState(false);
setTotalLength(1);
setIsChanging(false);
updateSelectedTrack(-1);
const persistingData = async () => {
const currentSelectedTrack = await AsyncStorage.getItem("selectedTrack");
const previous = JSON.parse(currentSelectedTrack)-1;
await AsyncStorage.setItem('selectedTrack', JSON.stringify(previous));
}
persistingData();
}, 0);
} else {
audioElement.current.seek(0);
setCurrentPosition(0);
}
};
const onForward = () => {
// if (selectedTrack < props.tracks.length - 1) {
audioElement.current && audioElement.current.seek(0);
setIsChanging(true);
setTimeout(() => {
setCurrentPosition(0);
updatePausedState(false);
setTotalLength(1);
setIsChanging(false);
updateSelectedTrack(1);
const persistingData = async () => {
const currentSelectedTrack = await AsyncStorage.getItem("selectedTrack");
const next = JSON.parse(currentSelectedTrack)+1;
await AsyncStorage.setItem('selectedTrack', JSON.stringify(next));
}
persistingData();
}, 0);
// }
};
const pressLike = () => {
if(!liked) {
setLiked(true);
const trackDetails = likedSongs;
trackDetails.push({
trackName: queue[selectedTrack].title,
artistName: queue[selectedTrack].artist,
albumArt: queue[selectedTrack].artwork,
trackUrl: queue[selectedTrack].url,
_id:queue[selectedTrack].id
});
updateLikedSongs(trackDetails);
const persistingData = async () => {
await AsyncStorage.setItem(
'likedSongs',
JSON.stringify(trackDetails),
);
};
persistingData();
ToastAndroid.show("Added to liked songs",ToastAndroid.SHORT);
}
else {
setLiked(false);
let trackDetails = likedSongs;
let newLikedSongs = trackDetails.filter((song) => {
return song._id !== queue[selectedTrack].id
})
console.log(newLikedSongs,"removed liked songs");
updateLikedSongs(newLikedSongs);
const persistingData = async () => {
await AsyncStorage.setItem(
'likedSongs',
JSON.stringify(newLikedSongs),
);
};
persistingData();
ToastAndroid.show("Removed from liked songs",ToastAndroid.SHORT);
}
}
const videoError = (data) => {
console.log(data, 'error');
};
const popSongFromQueue = () => {
queue.shift();
updateQueue(queue);
const persistingData = async () => {
await AsyncStorage.setItem('queue', JSON.stringify(queue));
};
persistingData();
};
const track = props.tracks[selectedTrack];
useEffect(() => {
const getDominantColors = async () => {
const colors = await ImageColors.getColors(track.artwork, {
fallback: '#7f8c8d',
});
if (colors.platform === 'android') {
averageColor = colors.vibrant;
setColor(averageColor);
updateColor(averageColor);
} else {
const backgroundColor = colors.background;
setColor(backgroundColor);
updateColor(backgroundColor);
}
return averageColor;
};
getDominantColors();
}, [track]);
const onEnd = () => {
console.log("in end");
}
const video = isChanging ? null : (
<Video
source={{uri: track.url}} // Can be a URL or a local file.
ref={audioElement}
playInBackground={true}
playWhenInactive={true}
paused={pausedState} // Pauses playback entirely.
resizeMode="cover" // Fill the whole screen at aspect ratio.
repeat={repeatOn} // Repeat forever.
onLoadStart={loadingStarts}
onLoad={setDuration} // Callback when video loads
onProgress={setTime} // Callback every ~250ms with currentTime
onEnd={onEnd} // Callback when playback finishes
onError={videoError} // Callback when video cannot be loaded
style={styles.audioElement}
onEnd={popSongFromQueue}
/>
);
return (
<LinearGradientComp
bgcolors={{
colorOne: color ? color : '#7f8c8d',
colorTwo: ACCENT,
}}>
<TrackDetails
track_name={track.title}
artist_name={track.artist}
album_image={track.artwork}
/>
<SeekBar
onSeek={seek}
trackLength={totalLength}
onSlidingStart={() => updatePausedState(true)}
currentPosition={currentPosition}
/>
<Controls
selectedSong={selectedSongData}
onPressLike={pressLike}
liked={liked}
onPressRepeat={() => setRepeatOn((repeatOn) => !repeatOn)}
repeatOn={repeatOn}
shuffleOn={shuffleOn}
backwardDisabled={selectedTrack === 0}
forwardDisabled={selectedTrack === props.tracks.length - 1}
onPressShuffle={() => setShuffleOn((shuffleOn) => !shuffleOn)}
onPressPlay={() => {
MusicControl.updatePlayback({
state: MusicControl.STATE_PLAYING,
})
updatePausedState(false);
// await AsyncStorage.setItem('pausedState',false);
}}
onPressPause={() => {
MusicControl.updatePlayback({
state: MusicControl.STATE_PAUSED,
})
updatePausedState(true);
// await AsyncStorage.setItem('pausedState',true);
}}
navig={props.navig}
onBack={onBack}
onForward={onForward}
paused={pausedState}
/>
{video}
</LinearGradientComp>
);
}
Example #23
Source File: ChatModal.js From app with GNU General Public License v3.0 | 4 votes |
ChatModal = ({modalVisible, toggleVisibility,selectedSong}) => {
const [searchQuery, setSearchQuery] = useState(null);
const {user,updateUser,updateMessages,token} = useContext(GlobalContext);
const [isSending,setIsSending] = useState({});
const [searchResults,setSearchResults] = useState([]);
const {album_image,track_name,track_url,artist_name,track_id} = selectedSong;
console.log(user,"user");
useEffect(() => {
if(searchQuery == null){
setSearchResults(user.friends);
}
},[])
const search = (value) => {
//Searching using regex
let re = new RegExp(value, "i")
let results = [];
user.friends.map((friend) => {
console.log("lol");
if(friend.username.match(re)){
results.push(friend);
setSearchResults(results);
}
else if(value == ""){
results.push(friend);
setSearchResults(results);
}
else{
setSearchResults([]);
console.log("lol");
}
})
};
const playlistData = {
trackName:track_name,
artistName:artist_name,
albumArt:album_image,
to:"lol",
trackUrl:track_url,
track_id
}
const sendSong = (userId) => {
setIsSending({
id:userId._id,
switch:true
});
axios.post(`${userApiUrl}/messages/send`,
{
...playlistData,
to:userId._id,
},{
headers: {
Authorization: "Bearer " + token,
},
})
.then(async (res) => {
setIsSending({
id:userId._id,
switch:false
});
ToastAndroid.show("Song sent", ToastAndroid.SHORT);
//?Todo remove this request later on and optimize in single request only
axios.get(`${userApiUrl}/messages/getMessages`,{
headers: {
Authorization: "Bearer " + token,
}
}
)
.then(async (res) => {
console.log(res.data,"from local messages");
updateMessages(res.data);
await AsyncStorage.setItem("messages",JSON.stringify(res.data));
}).catch((err) => {
console.log(err,"err");
})
}).catch((err) => {
console.log(err,"err");
setIsSending({
id:userId._id,
switch:false
});
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show("Error sending the message", ToastAndroid.SHORT);
}
}
})
}
return (
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
toggleVisibility(!modalVisible);
}}>
<LinearGradient
bgcolors={{
colorOne: 'rgba(0, 0, 0, 0.25)',
colorTwo: 'rgba(0, 0, 0, 1)',
}}>
<View>
<View style={styles.modalView}>
<SearchBox
placeholder="Search Friends"
searchQuery={searchQuery}
setSearchQuery={search}
/>
<ScrollView
showsVerticalScrollIndicator={true}
style={{
color: 'white',
}}>
{searchResults.map((user, i) => (
<View
key={i}
style={{
flexDirection: 'column',
alignContent: 'space-between',
margin: '2%',
}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'flex-start',
}}>
<Image
source={{"uri": user.photo}}
style={{
borderRadius: 20,
left: 10,
width: 50,
height: 50,
}}
/>
<Text style={styles.options}>
{user.username}
</Text>
<View
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
marginRight: 20,
}}>
<TouchableOpacity onPress={() => sendSong(user)}>
<View style={styles.button}>
<Text style={styles.textButton}>
{
isSending.id === user._id && isSending.switch ? "Sending" : "Send"
}
</Text>
</View>
</TouchableOpacity>
</View>
</View>
</View>
))}
</ScrollView>
</View>
</View>
</LinearGradient>
</Modal>
);
}
Example #24
Source File: Overlay.js From app with GNU General Public License v3.0 | 4 votes |
Overlay = ({toggleVisibility, modalVisible, data, selectedSong,navig}) => {
const [liked, setLiked] = useState(false);
const [heartIcon, setHeartIcon] = useState('heart-outline');
const [chatModalVisible, setChatModalVisible] = useState(false);
const {queue, updateQueue,likedSongs,updateLikedSongs} = useContext(GlobalContext);
const [recommendModalVisible, setRecommendModalVisible] = useState(false);
const [addToPlaylistModalVisible,setAddToPlaylistModalVisible] = useState(false);
useEffect(() => {
if(modalVisible){
let c=0;
likedSongs.map((song) => {
if(song._id == selectedSong.ref_id){
setLiked(true);
setHeartIcon("heart");
c++;
return;
}
})
if(c==0){
console.log("in");
setHeartIcon("heart-outline");
setLiked(false);
}
}
},[modalVisible,selectedSong])
const options = [
{
name: liked ? 'Remove from Liked Songs' : 'Add to Liked Songs',
icon_name: heartIcon,
onPress: () => {
//Todo Async State updates
if(!liked) {
setLiked(true);
setHeartIcon('heart');
const trackDetails = likedSongs;
trackDetails.push({
trackName: selectedSong.track_name,
artistName: selectedSong.artist_name,
albumArt: selectedSong.album_image,
trackUrl: selectedSong.track_url,
_id:selectedSong.ref_id
});
updateLikedSongs(trackDetails);
const persistingData = async () => {
await AsyncStorage.setItem(
'likedSongs',
JSON.stringify(trackDetails),
);
};
persistingData();
ToastAndroid.show("Added to liked songs",ToastAndroid.SHORT);
}
else {
setLiked(false);
setHeartIcon('heart-outline');
let trackDetails = likedSongs;
console.log(trackDetails,"current liked");
let newLikedSongs = trackDetails.filter((song) => {
return song._id !== selectedSong.ref_id
})
console.log(newLikedSongs,"new liked songs");
updateLikedSongs(newLikedSongs);
const persistingData = async () => {
await AsyncStorage.setItem(
'likedSongs',
JSON.stringify(newLikedSongs),
);
};
persistingData();
ToastAndroid.show("Removed from liked songs",ToastAndroid.SHORT);
}
}
},
{
name: 'Add to queue',
icon_name: 'add-outline',
onPress: () => {
const trackDetails = queue;
trackDetails.push({
title: selectedSong.track_name,
artist: selectedSong.artist_name,
artwork: selectedSong.album_image,
url: selectedSong.track_url,
id:selectedSong.ref_id
});
updateQueue(trackDetails);
ToastAndroid.show("Added to queue",ToastAndroid.SHORT);
const persistingData = async () => {
await AsyncStorage.setItem(
'queue',
JSON.stringify(trackDetails),
);
};
persistingData();
},
},
{
name: 'Send to Friends',
icon_name: 'rocket-outline',
onPress: () => {
setChatModalVisible(true);
},
},
{
name: 'Add to Playlist',
icon_name: 'list-outline',
onPress: () => {
setAddToPlaylistModalVisible(true);
},
},
{
name: 'View artist',
icon_name: 'person-outline',
onPress: () => {
axios
.post(
`${apiUrl}search/artists`,
{
query: selectedSong.artist_name,
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((result) => {
axios
.post(
`${apiUrl}fetch/albums`,
{
artist_id: result.data[0].artist_id,
},
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((res) => {
navig.navigate('ViewArtistScreen', {
albumData: res.data,
artist_id: result.data[0].artist_id,
artist_image:result.data[0].artist_image,
artist_name: result.data[0].artist_name,
});
toggleVisibility(false);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
},
},
{
name: 'Similar Songs',
icon_name: 'layers-outline',
onPress: () => {
setRecommendModalVisible(true);
},
},
];
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
toggleVisibility(!modalVisible);
}}>
<ChatModal
selectedSong={selectedSong}
toggleVisibility={setChatModalVisible}
modalVisible={chatModalVisible}
/>
<Recommend
selectedSong={selectedSong}
navig={navig}
toggleVisibility={setRecommendModalVisible}
modalVisible={recommendModalVisible}
/>
<AddToPlayListModal
selectedSong={selectedSong}
navig={navig}
toggleVisibility={setAddToPlaylistModalVisible}
modalVisible={addToPlaylistModalVisible}
/>
<LinearGradient
bgcolors={{
colorOne: '#2d3436AF',
colorTwo: '#000000FF',
}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<View
style={{
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'space-between',
}}>
<Image
source={{
uri: selectedSong.album_image,
}}
style={{
width: 200,
borderRadius: 12,
height: 200,
}}
/>
<Text
style={{
color: 'white',
paddingTop: 20,
fontSize: 18,
width: '100%',
textAlign: 'center',
fontWeight: 'bold',
}}>
{selectedSong.track_name}
</Text>
<Text
style={{
color: 'white',
fontSize: 16,
paddingTop: 15,
width: '100%',
textAlign: 'center',
paddingBottom: 20,
}}>
{selectedSong.artist_name}
</Text>
</View>
{options.map((option, i) => (
<TouchableOpacity key={i} onPress={option.onPress}>
<View
style={{
flexDirection: 'column',
alignContent: 'space-between',
margin: '4%',
}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'flex-start',
}}>
<Icon
name={option.icon_name}
size={24}
style={{left: 10}}
color="white"
/>
<Text style={styles.options}>
{option.name}
</Text>
</View>
</View>
</TouchableOpacity>
))}
</View>
</View>
</LinearGradient>
</Modal>
);
}
Example #25
Source File: AddToPlaylistModal.js From app with GNU General Public License v3.0 | 4 votes |
AddToPlayListModal = ({modalVisible, toggleVisibility,selectedSong}) => {
const {user,updateUser,token} = useContext(GlobalContext);
console.log(user,"user");
console.log(selectedSong,"selected song");
const {album_image,track_name,track_url,artist_name} = selectedSong
let playlistNames = [];
//Saving the playlist names
user.playlists.map((playlist) => {
playlistNames.push(playlist.name);
})
const [searchQuery, setSearchQuery] = useState('');
const [searchResults,setSearchResults] = useState(playlistNames);
const search = (value) => {
//Searching using regex
let re = new RegExp(`^${value}`);
let results = [];
playlistNames.map((playlist) => {
if(playlist.match(re)){
results.push(playlist);
setSearchResults(results);
}
})
};
const playlistData = {
trackName:track_name,
artistName:artist_name,
playlistName:"lol",
albumArt:album_image,
trackUrl:track_url
}
const addToPlaylist = (playlist) => {
console.log(playlist,"playlist");
axios.post(`${userApiUrl}/songs/addSong`,
{
...playlistData,
playlistName:playlist,
},{
headers: {
Authorization: "Bearer " + token,
},
})
.then(async (res) => {
console.log(res.data,"add song in the playlist");
updateUser(res.data);
await AsyncStorage.setItem('user', JSON.stringify(res.data));
ToastAndroid.show("Song added", ToastAndroid.SHORT);
}).catch((err) => {
console.log(err,"err");
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
}
}
})
}
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
toggleVisibility(!modalVisible);
}}>
<LinearGradientComp
bgcolors={{
colorOne: 'rgba(0, 0, 0, 0.3)',
colorTwo: 'rgba(0, 0, 0, 1)',
}}>
<View>
<View style={styles.modalView}>
<SearchBox
placeholder="Search Playlists"
searchQuery={searchQuery}
setSearchQuery={search}
/>
<ScrollView
showsVerticalScrollIndicator={true}
style={{
color: 'white',
}}>
{searchResults && searchResults.map((playlist, i) => (
<View
key={i}
style={{
flexDirection: 'column',
alignContent: 'space-between',
margin: '2%',
}}>
<TouchableOpacity onPress={() => addToPlaylist(playlist)}>
<View
style={{
flexDirection: 'row',
justifyContent: 'flex-start',
}}>
<Image
source={{uri: "https://i.scdn.co/image/ab67616d0000b27388b3414802727efbacf8dc43"}}
style={{
left: 10,
width: 50,
height: 50,
}}
/>
<Text style={styles.options}>
{playlist}
</Text>
</View>
</TouchableOpacity>
</View>
)
)}
</ScrollView>
</View>
</View>
</LinearGradientComp>
</Modal>
);
}
Example #26
Source File: List.js From app with GNU General Public License v3.0 | 4 votes |
List = ({item,friends,pending,currentUser,playlists}) => {
const {updateUser,user,token} = useContext(GlobalContext);
const [confirmationModalVisible,setConfirmationModalVisible] = useState(false);
const [playlistRemoveModalVisible,setPlaylistRemoveModalVisible] = useState(false);
const acceptRequest = () => {
axios.post(`${userApiUrl}/friends/acceptFriendRequest`,
{
friendId:item._id,
},{
headers: {
Authorization: "Bearer " + token,
},
})
.then(async (res) => {
console.log(res.data.friends,"accept user data");
updateUser(res.data.friends);
ToastAndroid.show(`You are now friends with ${item.name}`, ToastAndroid.SHORT);
await AsyncStorage.setItem('user', JSON.stringify(res.data.friends));
}).catch((err) => {
console.log(err,"err");
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
}
}
})
}
const removeFriend = () => {
setConfirmationModalVisible(true);
}
const removePlaylist = () => {
setPlaylistRemoveModalVisible(true);
}
const rejectRequest = () => {
axios.post(`${userApiUrl}/friends/rejectRequest`,
{
friendId:item._id
},{
headers: {
Authorization: "Bearer " + token,
},
})
.then(async (res) => {
console.log(res.data.friends,"remove friend user data");
updateUser(res.data.friends);
ToastAndroid.show(`Request rejected`, ToastAndroid.SHORT);
await AsyncStorage.setItem('user', JSON.stringify(res.data.friends));
}).catch((err) => {
console.log(err,"err");
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
}
}
})
}
return (
<View style={{flexDirection: 'row', width: '100%'}}>
<RemoveFriendModal
id = {item._id}
toggleVisibility={setConfirmationModalVisible}
modalVisible={confirmationModalVisible}
/>
<ConfirmationModal
id = {item._id}
toggleVisibility={setPlaylistRemoveModalVisible}
modalVisible={playlistRemoveModalVisible}
/>
{/* <TouchableOpacity onPress={renderFunc}> */}
<View
style={{
width: width / 7,
height: width / 7,
marginVertical: 7,
marginHorizontal: 15,
justifyContent: 'center',
alignItems: 'center',
}}>
{/* <TouchableOpacity onPress = {}> */}
<Image
source={{
uri: item?.songs && item.songs.length > 0 ? item.songs[0].albumArt : (
item.username ? item.photo : "https://images.unsplash.com/photo-1624387832956-1a33ddb5f7f9?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2735&q=80"
)
}}
style={{
width: 50,
height: 50,
borderRadius: 6,
overflow: 'hidden',
}}
/>
</View>
<View
style={{
marginVertical: 10,
marginHorizontal: 15,
justifyContent: 'space-around',
flex: 1,
}}>
<View
style={{
flexDirection: 'row',
marginTop: 5,
justifyContent: 'space-between',
flex:1,
width: '100%',
}}>
<View style={{
flex:1
}}>
<Type
style={{
fontSize: width / 22,
width: '80%',
color: colors.text,
marginTop:-2,
fontFamily:"NotoSans-Bold"
}}>
{
item.username ? item.username : item.name
}
</Type>
</View>
{
pending ? (
<View style={{
flexDirection:"row",
flex:1.2,
justifyContent:"space-around"
}}>
<Button title="accept" onPressFunction={acceptRequest}>Accept</Button>
<Button backColor="transparent" title="Reject" borderColor="white" onPressFunction={rejectRequest}>Delete</Button>
</View>
):(
friends && currentUser === user._id?
(
<Button title="remove" backColor = {friends ? "red" :""} onPressFunction={removeFriend}>Remove</Button>
): (
playlists && currentUser._id === user._id ?
(
<TouchableOpacity onPress = {removePlaylist}
hitSlop={{top: 20, bottom: 20, left: 20, right: 20}}
>
<Text style={{
color:"white",
fontSize:24
}}>X</Text>
</TouchableOpacity>
):(
<>
</>
)
)
)
}
</View>
<Type
style={{
fontSize: width / 24,
color: '#D3D3D3',
marginTop:-12,
fontFamily:"NotoSans"
}}>
{
pending ? (
""
):(
friends ?
(
""
): (
`${item.songs.length} ${item.songs.length> 1 ? "songs" : "song"}`
)
)
}
</Type>
</View>
{/* </TouchableOpacity> */}
</View>
)
}
Example #27
Source File: ConfirmationModal.js From app with GNU General Public License v3.0 | 4 votes |
ConfirmationModal = ({modalVisible,toggleVisibility,id}) => {
const {updateUser,user,token} = useContext(GlobalContext);
const [removingText,setRemovingText] = useState(false);
console.log(id,"in remove");
const removePlaylist = () => {
setRemovingText(true);
axios.post(`${userApiUrl}/songs/deletePlaylist`,
{
playlistId:id,
},{
headers: {
Authorization: "Bearer " + token,
},
})
.then(async (res) => {
console.log(res.data,"remove user data");
updateUser(res.data);
setRemovingText(false);
await AsyncStorage.setItem('user', JSON.stringify(res.data));
toggleVisibility(!modalVisible);
ToastAndroid.show("Playlist removed", ToastAndroid.SHORT);
}).catch((err) => {
setRemovingText(false);
console.log(err,"err");
if (Array.isArray(err.response.data.errors)) {
if (Platform.OS === 'android') {
ToastAndroid.show(err.response.data.errors[0].msg, ToastAndroid.SHORT);
}
}
})
}
const closeModal = () => {
console.log("lol closed");
toggleVisibility(!modalVisible);
}
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
toggleVisibility(!modalVisible);
}}>
<View style={styles.modalView}>
<Text style={{
color:"black",
fontSize:18,
marginLeft:15,
fontFamily:"NotoSans-Regular"
}}>
Are you sure you want to remove this playlist?
</Text>
<View style={{
marginLeft:"70%",
marginTop:20
}}>
<View style={{
flexDirection:"row",
justifyContent:"space-between",
right:100,
top:20,
}}>
<Button title="Yes" onPressFunction={removePlaylist}>
{removingText ? "Pro.." : "Yes"}
</Button>
<Button title="No" onPressFunction={closeModal}>
No
</Button>
</View>
</View>
</View>
</Modal>
)
}
Example #28
Source File: Controls.js From app with GNU General Public License v3.0 | 4 votes |
Controls = ({
selectedSong,
liked,
onPressLike,
paused,
shuffleOn,
repeatOn,
onPressPlay,
onPressPause,
onBack,
onForward,
onPressShuffle,
onPressRepeat,
backwardDisabled,
forwardDisabled,
navig
}) => {
const [chatModalVisible, setChatModalVisible] = useState(false);
const [recommendModalVisible, setRecommendModalVisible] = useState(false);
const REMOTE_IMAGE_PATH = selectedSong.track_url
const checkPermission = async () => {
if (Platform.OS === 'ios') {
downloadImage();
} else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Storage Permission Required',
message:
'App needs access to your storage to download Photos',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('Storage Permission Granted.');
downloadImage();
}
else {
ToastAndroid.show("Storage Permission Not Granted", ToastAndroid.SHORT);
}
}
catch (err) {
console.warn(err);
}
}
};
const downloadImage = () => {
let media_URL = REMOTE_IMAGE_PATH;
let ext = getExtention(media_URL);
ext = '.' + ext[0];
const { config, fs } = RNFetchBlob;
let PictureDir = fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path:
PictureDir +
'/song_' +
selectedSong.track_name +
ext,
description: 'Media',
},
};
config(options)
.fetch('GET', media_URL)
.then(res => {
console.log('res -> ', JSON.stringify(res));
ToastAndroid.show("Downloaded Successfully", ToastAndroid.SHORT);
});
};
const getExtention = filename => {
return /[.]/.exec(filename) ?
/[^.]+$/.exec(filename) : undefined;
};
return (
<View style={styles.container}>
<View>
<ChatModal
selectedSong={selectedSong}
toggleVisibility={setChatModalVisible}
modalVisible={chatModalVisible}
/>
<Recommend
navig={navig}
toggleVisibility={setRecommendModalVisible}
modalVisible={recommendModalVisible}
/>
<View
style={{
width: '100%',
bottom: '10%',
flexDirection: 'row',
justifyContent: 'space-around',
}}>
<TouchableOpacity
activeOpacity={0}
onPress={checkPermission}>
<Icon
size={30}
name="download-outline"
style={[
{color: defaultString.darkColor}
]}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={onPressLike}>
{liked ? (
<Icon
size={30}
name="heart"
style={[
{
color: defaultString.darkColor,
},
]}
/>
) : (
<Icon
size={30}
name="heart-outline"
style={[
{
color: defaultString.darkColor,
},
]}
/>
)}
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setRecommendModalVisible(true);
}}>
<OctIcon
size={30}
name="versions"
style={[{color: defaultString.darkColor}]}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
console.log('sending to the moon');
setChatModalVisible(true);
}}>
<Icon
size={30}
name="rocket-outline"
style={[{color: defaultString.darkColor}]}
/>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.0}
onPress={onPressRepeat}>
<Icon
size={30}
name="repeat-outline"
style={[
{color: defaultString.darkColor},
repeatOn ? [] : styles.off,
]}
/>
</TouchableOpacity>
</View>
<View
style={{
marginLeft: '20%',
top: '5%',
width: '60%',
flexDirection: 'row',
justifyContent: 'space-around',
}}>
<TouchableOpacity
onPress={onBack}
disabled={backwardDisabled}>
<Icon
size={40}
name="play-skip-back-circle-outline"
style={[
{
color: defaultString.darkColor,
},
backwardDisabled && {opacity: 0.3},
]}
/>
</TouchableOpacity>
{!paused ? (
<TouchableOpacity onPress={onPressPause}>
<View style={styles.playButton}>
<Icon
size={40}
name="pause-outline"
style={{
color: defaultString.darkColor,
}}
/>
</View>
</TouchableOpacity>
) : (
<TouchableOpacity onPress={onPressPlay}>
<View style={styles.playButton}>
<Icon
size={40}
name="play-outline"
style={{
color: defaultString.darkColor,
marginLeft: 5,
}}
/>
</View>
</TouchableOpacity>
)}
<TouchableOpacity
onPress={onForward}
disabled={forwardDisabled}>
<Icon
size={40}
name="play-skip-forward-circle-outline"
style={[
forwardDisabled && {opacity: 0.3},
{color: defaultString.darkColor},
]}
/>
</TouchableOpacity>
</View>
</View>
</View>
);
}
Example #29
Source File: sick.js From id.co.moonlay-eworkplace-mobile with MIT License | 4 votes |
async submitAll(){
const value = await AsyncStorage.getItem('clockin_state2');
const location = await AsyncStorage.getItem('location');
const sickValue = await AsyncStorage.getItem('sick_submit');
if(this.props.clockin_status === true || value === 'clockin'){
Alert.alert(
"You can't submit!",'You have clocked in today, your next submit will be start tomorrow at 07.00 AM',
[
{ text: "OK", onPress: () => console.log('OK'), style: "cancel"},
],
{ cancelable: false },
);
this.props.addLoad(false)
return true;
}
else if(this.state.headDivision === '' || this.state.projectName === '' || this.state.message === ''){
alert('All form must be filled!');
}
else if(sickValue === '1'){
Alert.alert(
"You can't submit!",'You have submitted sick form today. Your next submit will be start tomorrow at 07.00 AM',
[
{ text: "OK", onPress: () => console.log('OK'), style: "cancel"},
],
{ cancelable: false },
);
this.props.addLoad(false)
return true;
}
else if(location === null || location === ''){
Alert.alert(
'Location is nowhere','You must enable your location before clock in!',
[
{ text: "OK", onPress: () => console.log('OK'), style: "cancel"},
],
{ cancelable: false },
);
this.props.addLoad(false)
return true;
}
else if(this.state.headDivision !== '' && this.state.projectName !== '' && this.props.clockin_status === false && this.state.message !== ''){
axios({
method: 'POST',
url: Url_Clockin,
headers: {
'accept': 'application/json',
'Authorization': 'Bearer ' + this.props.tokenJWT
},
data: {
Username: this.state.username,
Name: this.state.fullname,
CheckIn: new Date(),
State: this.state.status,
Location : this.state.Location,
Approval : 'Pending',
ApprovalByAdmin : 'Pending',
HeadDivision: this.state.headDivision,
ProjectName: this.state.projectName,
Note: this.state.message
}
}).then((response) => {
console.log('Success: Submit sick data')
this.props.addClockin(false, ' ', this.state.idUser, this.state.status);
this.setState({
idUser: response.data.Id,
});
deviceStorage.saveItem("sick_submit", "1");
deviceStorage.saveItem("sick_submit_day", moment().format('dddd'));
this.props.addLoad(true)
if(this.state.permission === 1){
this.props.navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'HomeHD' },
],
})
)
}
else if(this.state.permission === 2){
this.props.navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'Home' },
],
})
)
}
ToastAndroid.showWithGravity(
'Submit success!',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
);
})
.catch((errorr) => {
console.log('Error: Submit sick data')
ToastAndroid.showWithGravity(
'Submit fail!',
ToastAndroid.SHORT,
ToastAndroid.BOTTOM,
);
});
}
}