Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Website demo – support HTTP uploads #1024

Merged
merged 3 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 34 additions & 39 deletions website/app/components/demo-upload.gjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,59 +7,54 @@ import { FileState } from 'ember-file-upload';
import FileDropzone from 'ember-file-upload/components/file-dropzone';
import fileQueue from 'ember-file-upload/helpers/file-queue';
import { onloadstart, onprogress, onloadend } from 'ember-file-upload/internal';
import { on } from '@ember/modifier';

// Values in kilobits per second (kbps)
const UPLOAD_RATES = {
'Disconnected - 0 Mbps': 0,
'Very slow - 0.1 Mbps': 100,
'Slow 3G - 0.4 Mbps': 400,
'Fast 3G - 0.675 Mbps': 675,
'ADSL - 1.5 Mbps': 1_500,
'4G/LTE - 50 Mbps': 50_000,
'Fast Fibre - 100 Mbps': 100_000,
};

const STEP_INTERVAL = 100; // Progress events every 100ms
const STEPS_PER_SECOND = 1_000 / STEP_INTERVAL;
import OptionsForm, { UPLOAD_TYPES, DEFAULT_OPTIONS } from './options-form';

// Simulated progress events every 100ms
const SIMULATED_TICK_INTERVAL = 100;
const SIMULATED_TICKS_PER_SECOND = 1_000 / SIMULATED_TICK_INTERVAL;
const BYTES_PER_KILOBYTE = 1_024;
const BITS_PER_BYTE = 8;

const round = (number) => Math.round(number);
const localeNumber = (number) => number.toLocaleString('en-GB');
const eq = (a, b) => a === b;

export default class DemoUploadComponent extends Component {
@service fileQueue;

@tracked uploadOptions = DEFAULT_OPTIONS;
@tracked files = [];
@tracked uploadRate = UPLOAD_RATES['Fast 3G - 0.675 Mbps'];

get queue() {
return this.fileQueue.find('demo');
}

get bytesPerStep() {
get simulatedBytesPerStep() {
const kilobytesPerSecond =
// Convert to kilobytes
(this.uploadRate / BITS_PER_BYTE) *
(this.uploadOptions.rate / BITS_PER_BYTE) *
// and then to bytes
BYTES_PER_KILOBYTE;
return kilobytesPerSecond / STEPS_PER_SECOND;
return kilobytesPerSecond / SIMULATED_TICKS_PER_SECOND;
}

@action
setUploadRate(event) {
this.uploadRate = parseInt(event.target.value, 10);
setUploadOptions(options) {
this.uploadOptions = options;
}

@action
addToQueue(file) {
file.queue = this.queue;
file.state = FileState.Queued;
this.files = [file, ...this.files];

this.simulateUpload.perform(file);
switch (this.uploadOptions.type) {
case UPLOAD_TYPES.simulated:
file.queue = this.queue;
this.simulateUpload.perform(file);
break;
case UPLOAD_TYPES.http:
this.httpUpload.perform(file);
break;
}
}

@task({ enqueue: true })
Expand All @@ -76,13 +71,13 @@ export default class DemoUploadComponent extends Component {
);

while (file.progress < 100) {
yield timeout(STEP_INTERVAL);
yield timeout(SIMULATED_TICK_INTERVAL);

onprogress(
file,
new ProgressEvent('progress', {
lengthComputable: true,
loaded: file.loaded + this.bytesPerStep,
loaded: file.loaded + this.simulatedBytesPerStep,
total: file.size,
}),
);
Expand All @@ -101,19 +96,19 @@ export default class DemoUploadComponent extends Component {
file.queue.flush();
}

@task({ enqueue: true })
*httpUpload(file) {
yield file.upload(this.uploadOptions.url, {
method: this.uploadOptions.method,
headers: this.uploadOptions.headers,
});
}

<template>
<form aria-label='Simulate upload speed'>
<label>
Simulate upload speed:
<select name='uploadRate' {{on 'change' this.setUploadRate}}>
{{#each-in UPLOAD_RATES as |name rate|}}
<option value={{rate}} selected={{eq this.uploadRate rate}}>
{{name}}
</option>
{{/each-in}}
</select>
</label>
</form>
<OptionsForm
@uploadOptions={{this.uploadOptions}}
@onUpdate={{this.setUploadOptions}}
/>

{{#let (fileQueue name='demo' onFileAdded=this.addToQueue) as |queue|}}
<FileDropzone
Expand Down
120 changes: 120 additions & 0 deletions website/app/components/options-form.gjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import { htmlSafe } from '@ember/template';

export const UPLOAD_TYPES = {
simulated: 'Simulated 🧑‍🔬',
http: 'HTTP 📡',
};

// Simulated
// Values in kilobits per second (kbps)
const RATES = {
'Disconnected - 0 Mbps': 0,
'Very slow - 0.1 Mbps': 100,
'Slow 3G - 0.4 Mbps': 400,
'Fast 3G - 0.675 Mbps': 675,
'ADSL - 1.5 Mbps': 1_500,
'4G/LTE - 50 Mbps': 50_000,
'Fast Fibre - 100 Mbps': 100_000,
};
const DEFAULT_RATE = RATES['Fast 3G - 0.675 Mbps'];

// HTTP
const DEFAULT_URL = 'https://api.bytescale.com/v1/files/basic';
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'HEAD'];
const DEFAULT_METHOD = 'POST';
const DEFAULT_HEADERS = {
Authorization: 'Basic YXBpa2V5OmZyZWU',
'Content-Type': 'application/x-www-form-urlencoded',
};
Copy link
Collaborator Author

@gilest gilest Nov 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While looking for a public "black hole" upload endpoint I found this documented in the MIT npm package react-uploader README

And it worked for me 🙃

I also read the terms that this company publishes and there's nothing referencing public API endpoints really...

This is a suggestion that a visitor may want to use. When doing so they are using this API on their own behalf 🤷🏻

Copy link
Collaborator Author

@gilest gilest Nov 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ended up replacing this with a WireMock endpoint from a free account I created. It doesn't behave as much like a real upload endpoint, but it does work


export const DEFAULT_OPTIONS = {
type: UPLOAD_TYPES.simulated,
// Simulated
rate: DEFAULT_RATE,
// HTTP
url: DEFAULT_URL,
method: DEFAULT_METHOD,
headers: DEFAULT_HEADERS,
};

const eq = (a, b) => a === b;

export default class OptionsFormComponent extends Component {
@action
setOptions(event) {
const formData = new FormData(event.currentTarget);
const entries = Object.fromEntries(formData.entries());
const uploadOptions = {
...entries,
rate: parseInt(entries.rate, 10),
headers: JSON.parse(entries.headers),
};
this.args.onUpdate(uploadOptions);
}

// Keep forms in DOM to prevent data loss
toggleVisibility = (type) => {
return this.args.uploadOptions.type === type
? htmlSafe('')
: htmlSafe('display: none');
};

<template>
<form aria-label='Upload options' {{on 'change' this.setOptions}}>
<fieldset>
<legend>Upload type:</legend>
{{#each (Object.values UPLOAD_TYPES) as |type|}}
<div>
<input
type='radio'
name='type'
id={{type}}
value={{type}}
checked={{eq @uploadOptions.type type}}
/>
<label for={{type}}>{{type}}</label>
</div>
{{/each}}
</fieldset>

<label style={{this.toggleVisibility UPLOAD_TYPES.simulated}}>
Simulated speed:
<select name='rate'>
{{#each-in RATES as |name rate|}}
<option value={{rate}} selected={{eq @uploadOptions.rate rate}}>
{{name}}
</option>
{{/each-in}}
</select>
</label>

<label style={{this.toggleVisibility UPLOAD_TYPES.http}}>
URL:
<input type='text' name='url' value={{DEFAULT_URL}} />
</label>

<label style={{this.toggleVisibility UPLOAD_TYPES.http}}>
Method:
<select name='method'>
{{#each METHODS as |method|}}
<option value={{method}} selected={{eq @uploadOptions.method method}}>
{{method}}
</option>
{{/each}}
</select>
</label>

<label style={{this.toggleVisibility UPLOAD_TYPES.http}}>
Headers:
<textarea name='headers' rows='5' spellcheck='false'>{{JSON.stringify
DEFAULT_HEADERS
null
2
}}</textarea>
</label>
</form>
</template>
}