Spaces:
Runtime error
Runtime error
File size: 10,274 Bytes
c5b7daf | 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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | # Box.com Storage Integration
Complete guide for Box.com OAuth 2.0 cloud storage integration with automatic token management and file streaming.
## π Table of Contents
- [Features](#features)
- [Setup Guide](#setup-guide)
- [Configuration](#configuration)
- [API Endpoints](#api-endpoints)
- [Usage Examples](#usage-examples)
- [File Type Support](#file-type-support)
- [Troubleshooting](#troubleshooting)
---
## β¨ Features
- β
OAuth 2.0 User Authentication
- β
Automatic token refresh and persistence (box-tokens.json)
- β
File upload with automatic folder routing (IMAGE/VIDEO/DOCUMENT)
- β
File streaming through your server (supports images, videos, PDFs, audio, etc.)
- β
File deletion by ID
- β
No manual token management required
---
## π Setup Guide
### Step 1: Create a Box Custom App
1. Go to [Box Developer Console](https://app.box.com/developers/console)
2. Click **"Create New App"**
3. Select **"Custom App"**
4. Choose **"User Authentication (OAuth 2.0)"** β οΈ (NOT JWT or Client Credentials)
5. Name your app (e.g., "Streamflix API")
### Step 2: Configure OAuth Settings
1. In your app's **Configuration** tab:
- Copy **Client ID** and **Client Secret**
- Add redirect URI: `http://localhost:5119/box/oauth/callback`
- Enable scopes:
- β
Read all files and folders
- β
Write all files and folders
- Save changes
### Step 3: Get Folder IDs
1. Log in to [Box.com](https://app.box.com)
2. Create your folder structure:
```
Streamflix/
βββ images/
βββ videos/
βββ documents/
```
3. Open each folder and copy the ID from the URL:
```
https://app.box.com/folder/358198319436
^^^^^^^^^^^^
This is the folder ID
```
### Step 4: Configure Environment Variables
Update your `.env` file:
```env
# Box.com OAuth 2.0 Configuration
BOX_CLIENT_ID="your_client_id_here"
BOX_CLIENT_SECRET="your_client_secret_here"
BOX_REDIRECT_URI="http://localhost:5119/box/oauth/callback"
# Box Folder IDs (get from Box.com URLs)
BOX_STREAMFLIX_FOLDER_ID="358198319436" # Main folder
BOX_IMAGES_FOLDER_ID="358199056099" # For IMAGE type uploads
BOX_VIDEOS_FOLDER_ID="358199692412" # For VIDEO type uploads
BOX_DOCUMENTS_FOLDER_ID="358199056099" # For DOCUMENT type uploads
# App URL (for generating content URLs)
APP_URL="http://localhost:5119"
```
### Step 5: Authorize Your Application (One-Time)
1. Start your application:
```bash
npm run start:dev
```
2. Visit the authorization URL in your browser:
```
http://localhost:5119/box/oauth/authorize
```
3. Log in to Box.com and grant access
4. **Done!** Tokens are automatically saved to `box-tokens.json`
---
## βοΈ Configuration
### Automatic Token Management
- Tokens are stored in `box-tokens.json` (already in `.gitignore`)
- Access tokens automatically refresh every ~1 hour
- Refresh tokens are automatically updated when Box issues new ones
- No manual intervention required after initial authorization
### Folder Routing
When uploading files, specify the `fileType` parameter:
- `fileType=IMAGE` β Uploads to `BOX_IMAGES_FOLDER_ID`
- `fileType=VIDEO` β Uploads to `BOX_VIDEOS_FOLDER_ID`
- `fileType=DOCUMENT` β Uploads to `BOX_DOCUMENTS_FOLDER_ID`
- No parameter β Uploads to `BOX_STREAMFLIX_FOLDER_ID` (main folder)
---
## π‘ API Endpoints
### 1. OAuth Authorization
**Start OAuth Flow**
```
GET /box/oauth/authorize
```
Redirects to Box.com for user authorization (one-time setup).
**OAuth Callback** (Automatically called by Box)
```
GET /box/oauth/callback?code={code}
```
Exchanges authorization code for tokens and saves to `box-tokens.json`.
---
### 2. Upload File
```
POST /box/upload
```
**Query Parameters:**
- `fileType` (optional): `IMAGE`, `VIDEO`, or `DOCUMENT`
- `customFilename` (optional): Custom filename without extension
**Form Data:**
- `file`: Binary file data
**Example Request:**
```bash
curl -X POST "http://localhost:5119/box/upload?fileType=IMAGE" \
-F "file=@photo.jpg"
```
**Response:**
```json
{
"success": true,
"name": "1766841360028-photo.jpg",
"boxFileId": "2087753948639",
"size": 357909,
"folderId": "358199056099",
"publicUrl": "https://app.box.com/s/xxxxx",
"contentUrl": "http://localhost:5119/box/file/2087753948639",
"extraData": {
"sha1": "22a487ac758861029dfa5791d94c8d50c51b909e",
"createdAt": "2025-12-27T05:16:01-08:00",
"modifiedAt": "2025-12-27T05:16:01-08:00"
}
}
```
**Use `contentUrl` for direct file access!**
---
### 3. Stream File Content
```
GET /box/file/:fileId
```
Streams file content through your server. Works for images, videos, PDFs, audio, and more.
**Example:**
```html
<!-- Display image -->
<img src="http://localhost:5119/box/file/2087753948639" />
<!-- Embed video -->
<video controls>
<source src="http://localhost:5119/box/file/2087753948639" />
</video>
<!-- Embed PDF -->
<iframe src="http://localhost:5119/box/file/2087753948639"></iframe>
```
**Supported Features:**
- β
Images display inline
- β
Videos support seeking (Accept-Ranges header)
- β
PDFs display in browser
- β
Audio files play inline
- β
Text files display inline
- β
Cached for 1 year (optimal performance)
---
### 4. Delete File
```
DELETE /box/by-id?fileId={fileId}
```
**Query Parameters:**
- `fileId` (required): Box file ID
**Example:**
```bash
curl -X DELETE "http://localhost:5119/box/by-id?fileId=2087753948639"
```
**Response:**
```json
{
"message": "File deleted successfully",
"success": true,
"deletedFileId": "2087753948639"
}
```
---
## π― Usage Examples
### Upload and Display Image
```javascript
// Upload
const formData = new FormData();
formData.append('file', imageFile);
const response = await fetch(
'http://localhost:5119/box/upload?fileType=IMAGE',
{
method: 'POST',
body: formData,
},
);
const data = await response.json();
// Display using contentUrl
const img = document.createElement('img');
img.src = data.contentUrl; // http://localhost:5119/box/file/2087753948639
document.body.appendChild(img);
```
### Upload and Play Video
```javascript
// Upload
const formData = new FormData();
formData.append('file', videoFile);
const response = await fetch(
'http://localhost:5119/box/upload?fileType=VIDEO',
{
method: 'POST',
body: formData,
},
);
const data = await response.json();
// Play video
const video = document.createElement('video');
video.src = data.contentUrl;
video.controls = true;
document.body.appendChild(video);
```
### Delete File
```javascript
const fileId = '2087753948639';
await fetch(`http://localhost:5119/box/by-id?fileId=${fileId}`, {
method: 'DELETE',
});
```
---
## π¨ File Type Support
### Images (Display Inline)
- JPG/JPEG, PNG, GIF, WebP, SVG, BMP, ICO, TIFF
### Videos (Play Inline with Seeking)
- MP4, WebM, OGG, AVI, MOV, WMV, FLV, MKV, M4V, 3GP
### Audio (Play Inline)
- MP3, WAV, OGG, M4A, AAC, FLAC
### Documents (Display Inline)
- PDF (viewable in browser)
- Word, Excel, PowerPoint (will download)
### Text (Display Inline)
- TXT, HTML, CSS, JS, JSON, XML, CSV, Markdown
### Archives (Download)
- ZIP, RAR, 7Z, TAR, GZ
---
## π§ Troubleshooting
### "No tokens found! Please authorize via OAuth"
**Solution:** Run the OAuth flow once:
```
http://localhost:5119/box/oauth/authorize
```
---
### "Refresh token expired!"
**Solution:** The refresh token has expired. Re-authorize:
```
http://localhost:5119/box/oauth/authorize
```
---
### "Box OAuth credentials not configured"
**Solution:** Check your `.env` file:
- `BOX_CLIENT_ID` must be set
- `BOX_CLIENT_SECRET` must be set
- Restart your application after updating `.env`
---
### File downloads instead of displaying inline
**Cause:** Incorrect MIME type or Content-Disposition header
**Solution:** Already fixed! The stream endpoint now:
- Detects MIME types from file extensions
- Sets `Content-Disposition: inline`
- Supports 50+ file formats
---
### Video won't seek/skip
**Cause:** Missing `Accept-Ranges` header
**Solution:** Already fixed! The stream endpoint now includes:
```
Accept-Ranges: bytes
```
This enables video seeking in all browsers.
---
### Images are resized/compressed
**Answer:** No! Files are streamed **byte-for-byte** from Box.com with no modifications. What you upload is exactly what gets delivered.
---
## π Security Notes
1. **Never commit `box-tokens.json`** - Already in `.gitignore`
2. **Keep `.env` secure** - Never commit to version control
3. **Use environment variables** in production
4. **Rotate tokens** if compromised (re-run OAuth flow)
---
## π Technical Details
### Token Flow
1. **Initial Authorization** (one-time)
- User visits `/box/oauth/authorize`
- Redirected to Box.com
- User grants access
- Tokens saved to `box-tokens.json`
2. **Automatic Refresh** (background)
- Access token expires after 60 minutes
- Service automatically refreshes using refresh token
- New tokens saved to `box-tokens.json`
- If Box issues new refresh token, it's automatically updated
3. **Persistence**
- Tokens survive application restarts
- Loaded from `box-tokens.json` on startup
- No manual intervention required
### File Streaming
- Files are **streamed**, not downloaded to server
- Zero server storage used
- Supports large files (videos, archives)
- Browser caching enabled for optimal performance
- Range requests supported for video seeking
---
## π Additional Resources
- [Box API Documentation](https://developer.box.com/reference/)
- [Box OAuth 2.0 Guide](https://developer.box.com/guides/authentication/oauth2/)
- [Box Developer Console](https://app.box.com/developers/console)
---
## π Quick Start Checklist
- [ ] Create Box Custom App with OAuth 2.0
- [ ] Get Client ID and Client Secret
- [ ] Create folder structure in Box.com
- [ ] Get folder IDs from URLs
- [ ] Update `.env` file
- [ ] Start application
- [ ] Visit `/box/oauth/authorize`
- [ ] Grant access to Box
- [ ] Test upload: `POST /box/upload`
- [ ] Test display: Use `contentUrl` in browser
- [ ] Done! π
---
**Need help?** Check the troubleshooting section or contact support.
|