-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathApp.js
238 lines (208 loc) · 6.79 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import * as DocumentPicker from 'expo-document-picker';
import { makeRedirectUri } from 'expo-auth-session'
import * as WebBrowser from 'expo-web-browser';
import React, { useEffect, useState } from 'react';
import {
Image,
SafeAreaView,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
useColorScheme
} from 'react-native';
import { Account, Client, Databases, ID, Permission, Role, Storage, OAuthProvider } from 'react-native-appwrite';
import { StatusBar } from 'expo-status-bar';
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
*/
let client;
let account;
let storage;
let databases;
function App() {
const isDarkMode = useColorScheme() === 'dark';
const [user, setUser] = useState();
const [event, setEvent] = useState();
const [file, setFile] = useState();
let subscription;
let setupAppwrite = async () => {
client = new Client();
client.setEndpoint('https://cloud.appwrite.io/v1').setProject('rntest').setPlatform('io.appwrite.playgroundForReactNative');
account = new Account(client);
storage = new Storage(client);
databases = new Databases(client);
// For session persistance we can get the current account data here
await getAccount();
}
let createSession = async () => {
try {
getAccount();
} catch (e) {
console.log(e);
}
}
let createAnonymousSession = async () => {
await account.createAnonymousSession();
getAccount();
}
let createOAuth2Session = async (provider) => {
try {
// REQUIRED
// Make sure a scheme is set in your app.json
// Create deep link that works across Expo environments
// Ensure localhost is used for the hostname to validation error for success/failure URLs
const deepLink = new URL(makeRedirectUri({preferLocalhost: true}));
if (!deepLink.hostname) {
deepLink.hostname = 'localhost';
}
const scheme = `${deepLink.protocol}//`; // e.g. 'exp://' or 'playground://'
// Start OAuth flow
const loginUrl = await account.createOAuth2Token(
provider,
`${deepLink}`,
`${deepLink}`,
);
// Open loginUrl and listen for the scheme redirect
const result = await WebBrowser.openAuthSessionAsync(`${loginUrl}`, scheme);
// Extract credentials from OAuth redirect URL
const url = new URL(result.url);
const secret = url.searchParams.get('secret');
const userId = url.searchParams.get('userId');
// Create session with OAuth credentials
await account.createSession(userId, secret);
await getAccount(); // get user, set state, and redirect as needed
} catch (e) {
console.log(e);
}
}
let createDoc = async () => {
await databases.createDocument('65e7e1452ea7c6473b01', 'usernames', ID.unique(), {
username: 'test'
}, [
Permission.read(Role.any()),
Permission.write(Role.any())
]);
}
let logout = async () => {
await account.deleteSession('current');
setUser(undefined);
}
let getAccount = async () => {
let user = await account.get();
setUser(user);
}
let subscribe = async () => {
subscription = client.subscribe(['documents', 'files'], (event) => {
setEvent(event);
});
}
let pickFile = async () => {
var fl = await DocumentPicker.getDocumentAsync({
copyToCacheDirectory: true,
multiple: false
});
let storage = new Storage(client);
if (!fl.assets) return;
try {
var pickedFile = fl.assets[0];
pickedFile = { name: pickedFile.name, type: pickedFile.mimeType, uri: pickedFile.uri, size: pickedFile.size };
console.log(pickedFile);
let uploaded = await storage.createFile('test', ID.unique(), pickedFile, [
Permission.read(Role.users()),
], (progress) => {
console.log(progress.chunksUploaded);
});
setFile(uploaded);
} catch (e) {
console.log(e);
}
}
const backgroundStyle = {
backgroundColor: isDarkMode ? '#333333' : '#f2f2f2f2',
padding: 20,
paddingTop: 60,
};
const buttonStyle = {
backgroundColor: isDarkMode ? 'black' : 'white',
marginBottom: 20,
padding: 20,
alignItems: 'center',
}
const buttonTextStyle = {
color: isDarkMode ? 'white' : 'black'
}
const headingStyle = {
color: isDarkMode ? 'white' : 'black',
fontSize: 28,
textAlign: 'center',
marginBottom: 20,
}
// Set up appwrite only once upon mounting the application
useEffect(() => {
if(!client){
setupAppwrite();
}
},[]);
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<ScrollView>
<View style={backgroundStyle}>
<Text style={headingStyle}>Appwrite playground</Text>
<TouchableOpacity onPress={createAnonymousSession} style={buttonStyle}>
<Text style={buttonTextStyle}>Anonymous login</Text>
</TouchableOpacity>
<TouchableOpacity onPress={createSession} style={buttonStyle}>
<Text style={buttonTextStyle}>Login with email</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => createOAuth2Session(OAuthProvider.Google)} style={buttonStyle}>
<Text style={buttonTextStyle}>Login with Google</Text>
</TouchableOpacity>
<TouchableOpacity onPress={subscribe} style={buttonStyle}>
<Text style={buttonTextStyle}>Subscribe</Text>
</TouchableOpacity>
{event && <Text>{JSON.stringify(event.payload , null, 2)}</Text>}
{file && file.$id && <Image style={{ height: 500, objectFit: 'contain' }} source={{ uri: storage.getFilePreview('test', file.$id, 400, 500).href }} />}
<TouchableOpacity onPress={createDoc} style={buttonStyle} disabled={!user}>
<Text style={buttonTextStyle}>Create Doc</Text>
</TouchableOpacity>
<TouchableOpacity onPress={pickFile} style={buttonStyle} disabled={!user}>
<Text style={buttonTextStyle}>Upload</Text>
</TouchableOpacity>
{user && <Text>{user.name.length ? user.name : 'Anonymous user'}</Text>}
<TouchableOpacity onPress={logout} style={buttonStyle}>
<Text style={buttonTextStyle}>Logout</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default App;