File size: 6,210 Bytes
9a92a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Google Cloud Storage Helper
 * Direct upload to newimagesndma bucket - NO BACKEND NEEDED! ๐Ÿš€
 * 
 * Bucket: newimagesndma (allUsers has Storage Object Admin permission)
 * Features:
 * - Upload images directly to GCS from React Native
 * - No backend server needed
 * - Get instant public URLs
 * - AsyncStorage for offline access
 */

import AsyncStorage from '@react-native-async-storage/async-storage';

// GCS Configuration for PUBLIC bucket
const GCS_CONFIG = {
  bucketName: 'newimagesndma',
  projectId: 'axiomatic-skill-473605-i3',
  
  // Get public URL for a file
  getPublicUrl: (fileName) => `https://storage.googleapis.com/newimagesndma/${fileName}`,
  
  // Upload endpoint for public bucket (allUsers has Storage Object Admin)
  uploadEndpoint: (fileName) => 
    `https://storage.googleapis.com/upload/storage/v1/b/newimagesndma/o?uploadType=media&name=${encodeURIComponent(fileName)}`,
};

/**
 * Upload file to GCS - DIRECT UPLOAD (No Backend!) ๐ŸŽฏ
 * Works because newimagesndma bucket has allUsers with Storage Object Admin permission
 * @param {string} fileUri - Local file URI (from ImagePicker)
 * @param {string} folder - Folder name (e.g., 'profiles', 'csv', 'images')
 * @param {string} fileName - Custom file name (optional)
 * @param {string} contentType - MIME type (default: image/jpeg)
 * @returns {Promise<string>} Public GCS URL
 */
export const uploadToGCS = async (fileUri, folder = 'uploads', fileName = null, contentType = 'image/jpeg') => {
  try {
    // Generate unique filename if not provided
    if (!fileName) {
      const timestamp = Date.now();
      const extension = fileUri.split('.').pop() || 'jpg';
      const randomId = Math.random().toString(36).substr(2, 9);
      fileName = `${folder}/${timestamp}_${randomId}.${extension}`;
    } else {
      fileName = `${folder}/${fileName}`;
    }
    
    console.log(`๐Ÿ“ค Uploading to GCS: ${fileName}`);
    
    // Read file as blob
    const response = await fetch(fileUri);
    const blob = await response.blob();
    
    // Upload directly to GCS public bucket
    const uploadUrl = GCS_CONFIG.uploadEndpoint(fileName);
    console.log('๐Ÿ”— Upload URL:', uploadUrl);
    
    const uploadResponse = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Content-Type': contentType,
      },
      body: blob,
    });

    if (!uploadResponse.ok) {
      const errorText = await uploadResponse.text();
      console.error('โŒ GCS Upload failed:', uploadResponse.status, errorText);
      throw new Error(`Upload failed: ${uploadResponse.status}`);
    }

    const publicUrl = GCS_CONFIG.getPublicUrl(fileName);
    console.log('โœ… File uploaded to GCS:', publicUrl);
    
    // Store URL in AsyncStorage for offline access
    await AsyncStorage.setItem(`@file_${fileName}`, publicUrl);
    
    return publicUrl;
  } catch (error) {
    console.error('โŒ GCS upload error:', error);
    throw error;
  }
};

/**
 * Upload profile picture
 * @param {string} imageUri - Local image URI
 * @param {string} userId - User ID or email
 * @returns {Promise<string>} Public URL
 */
export const uploadProfilePicture = async (imageUri, userId) => {
  const safeUserId = userId.replace(/[@.]/g, '_');
  const fileName = `${safeUserId}_${Date.now()}.jpg`;
  const publicUrl = await uploadToGCS(imageUri, 'profiles', fileName, 'image/jpeg');
  
  // Save to AsyncStorage for offline access
  await AsyncStorage.setItem(`@profile_pic_${userId}`, publicUrl);
  
  return publicUrl;
};

/**
 * Upload CSV file
 * @param {string} fileUri - Local CSV file URI
 * @param {string} fileName - Custom file name
 * @returns {Promise<string>} Public URL
 */
export const uploadCSV = async (fileUri, fileName) => {
  return await uploadToGCS(fileUri, 'csv', fileName, 'text/csv');
};

/**
 * Upload image
 * @param {string} imageUri - Local image URI
 * @param {string} folder - Subfolder (optional)
 * @returns {Promise<string>} Public URL
 */
export const uploadImage = async (imageUri, folder = 'images') => {
  const timestamp = Date.now();
  const fileName = `img_${timestamp}.jpg`;
  return await uploadToGCS(imageUri, folder, fileName, 'image/jpeg');
};

/**
 * Upload training report image
 * @param {string} imageUri - Local image URI
 * @param {string} reportId - Report ID
 * @returns {Promise<string>} Public URL
 */
export const uploadTrainingImage = async (imageUri, reportId) => {
  const fileName = `training_${reportId}_${Date.now()}.jpg`;
  return await uploadToGCS(imageUri, 'training-reports', fileName, 'image/jpeg');
};

/**
 * Get profile picture from storage
 * @param {string} userId - User ID
 * @returns {Promise<string|null>} Cached URL or null
 */
export const getProfilePicture = async (userId) => {
  try {
    const url = await AsyncStorage.getItem(`@profile_pic_${userId}`);
    return url;
  } catch (error) {
    console.error('Error loading profile picture:', error);
    return null;
  }
};

/**
 * Delete file from GCS (requires authentication - use with caution)
 * Note: This won't work without proper auth. Keep files or implement backend for deletion.
 */
export const deleteFromGCS = async (fileName) => {
  console.warn('โš ๏ธ Delete operation requires authentication. File will remain in bucket.');
  // For now, just remove from AsyncStorage
  try {
    await AsyncStorage.removeItem(`@file_${fileName}`);
  } catch (error) {
    console.error('Error removing from storage:', error);
  }
};

/**
 * List files (mock - requires backend or proper auth)
 * For now, returns cached URLs from AsyncStorage
 */
export const listFiles = async (prefix = '') => {
  try {
    const keys = await AsyncStorage.getAllKeys();
    const fileKeys = keys.filter(key => key.startsWith('@file_'));
    const files = [];
    
    for (const key of fileKeys) {
      const url = await AsyncStorage.getItem(key);
      if (url) {
        files.push({ key, url });
      }
    }
    
    return files;
  } catch (error) {
    console.error('Error listing files:', error);
    return [];
  }
};

export default {
  uploadToGCS,
  uploadProfilePicture,
  uploadCSV,
  uploadImage,
  uploadTrainingImage,
  getProfilePicture,
  deleteFromGCS,
  listFiles,
  GCS_CONFIG,
};