Refactoring of Task.svelte

This commit is contained in:
Andrea Fazzi 2022-02-16 12:58:01 +01:00
parent 9691ca6c5c
commit 1b9f1b8c86
8 changed files with 168 additions and 199 deletions

1
backend/.gitignore vendored
View file

@ -1,2 +1,3 @@
backend
youtube-dl-service

View file

@ -96,9 +96,8 @@ func getToken(config *Config, password string) ([]byte, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(claims))
/* Sign the token with our secret */
tokenString, err := token.SignedString(config.JWTSigningKey)
tokenString, err := token.SignedString([]byte(config.JWTSigningKey))
if err != nil {
log.Println(err)
return nil, err
}

View file

@ -44,16 +44,16 @@ func (t *testSuite) BeforeAll() {
// Test the creation of a new task. A new task is created with a POST
// request to the endpoint.
func (t *testSuite) TestCreateTask() {
video, err := postTask("https://www.youtube.com/watch?v=AVIBLFl28vo")
video, err := postTask("https://www.youtube.com/watch?v=zGDzdps75ns")
if err != nil {
panic(err)
}
t.Equal("AVIBLFl28vo", video.ID)
t.Equal("zGDzdps75ns", video.ID)
}
// Test the response of a GET /tasks/:id requests.
func (t *testSuite) TestGetTask() {
video, err := postTask("https://www.youtube.com/watch?v=AVIBLFl28vo")
video, err := postTask("https://www.youtube.com/watch?v=zGDzdps75ns")
if err != nil {
panic(err)
}
@ -83,7 +83,7 @@ func (t *testSuite) TestGetTask() {
panic(err)
}
t.Equal("AVIBLFl28vo", ts.ID)
t.Equal("zGDzdps75ns", video.ID)
t.Equal(task.StatusCompleted, ts.Status)
}

View file

@ -119,6 +119,9 @@ var app = (function () {
throw new Error('Function called outside component initialization');
return current_component;
}
function onMount(fn) {
get_current_component().$$.on_mount.push(fn);
}
const dirty_components = [];
const binding_callbacks = [];
@ -302,12 +305,6 @@ var app = (function () {
}
info.block.p(child_ctx, dirty);
}
const globals = (typeof window !== 'undefined'
? window
: typeof globalThis !== 'undefined'
? globalThis
: global);
function outro_and_destroy_block(block, lookup) {
transition_out(block, 1, 1, () => {
lookup.delete(block.key);
@ -911,14 +908,12 @@ var app = (function () {
}
/* src/Task.svelte generated by Svelte v3.42.4 */
const { Error: Error_1 } = globals;
const file$2 = "src/Task.svelte";
// (60:0) {:catch error}
// (24:0) {:catch error}
function create_catch_block(ctx) {
let p;
let t_value = /*error*/ ctx[9].message + "";
let t_value = /*error*/ ctx[3].message + "";
let t;
const block = {
@ -926,7 +921,7 @@ var app = (function () {
p = element("p");
t = text(t_value);
set_style(p, "color", "red");
add_location(p, file$2, 60, 2, 1693);
add_location(p, file$2, 24, 2, 940);
},
m: function mount(target, anchor) {
insert_dev(target, p, anchor);
@ -942,20 +937,20 @@ var app = (function () {
block,
id: create_catch_block.name,
type: "catch",
source: "(60:0) {:catch error}",
source: "(24:0) {:catch error}",
ctx
});
return block;
}
// (48:0) {:then video_info}
// (12:0) {:then video_info}
function create_then_block(ctx) {
let a;
let div2;
let div0;
let h5;
let t0_value = /*video_info*/ ctx[3].Title + "";
let t0_value = /*video_info*/ ctx[2].Title + "";
let t0;
let t1;
let div1;
@ -968,7 +963,7 @@ var app = (function () {
let t6;
let img;
let img_src_value;
let if_block = /*status*/ ctx[1].Status && create_if_block$1(ctx);
let if_block = status.Status && create_if_block$1(ctx);
const block = {
c: function create() {
@ -989,23 +984,23 @@ var app = (function () {
t5 = text(/*url*/ ctx[0]);
t6 = space();
img = element("img");
add_location(h5, file$2, 50, 49, 1276);
add_location(h5, file$2, 14, 49, 523);
attr_dev(div0, "class", "pb-2 flex-grow-1 bd-highlight");
add_location(div0, file$2, 50, 6, 1233);
add_location(small0, file$2, 51, 42, 1352);
add_location(div0, file$2, 14, 6, 480);
add_location(small0, file$2, 15, 42, 599);
attr_dev(div1, "class", "pb-2 px-2 bd-highlight");
add_location(div1, file$2, 51, 6, 1316);
add_location(div1, file$2, 15, 6, 563);
attr_dev(div2, "class", "d-flex bd-highlight");
add_location(div2, file$2, 49, 4, 1193);
add_location(small1, file$2, 56, 7, 1574);
add_location(p, file$2, 56, 4, 1571);
add_location(div2, file$2, 13, 4, 440);
add_location(small1, file$2, 20, 7, 821);
add_location(p, file$2, 20, 4, 818);
attr_dev(img, "alt", "This is a thumbnail");
if (!src_url_equal(img.src, img_src_value = /*video_info*/ ctx[3].Thumbnails[0].URL)) attr_dev(img, "src", img_src_value);
add_location(img, file$2, 57, 4, 1603);
attr_dev(a, "href", /*download_path*/ ctx[2]);
if (!src_url_equal(img.src, img_src_value = /*video_info*/ ctx[2].Thumbnails[0].URL)) attr_dev(img, "src", img_src_value);
add_location(img, file$2, 21, 4, 850);
attr_dev(a, "href", download_path);
attr_dev(a, "class", "list-group-item list-group-item-action");
attr_dev(a, "aria-current", "true");
add_location(a, file$2, 48, 2, 1097);
add_location(a, file$2, 12, 2, 344);
},
m: function mount(target, anchor) {
insert_dev(target, a, anchor);
@ -1026,24 +1021,8 @@ var app = (function () {
append_dev(a, img);
},
p: function update(ctx, dirty) {
if (/*status*/ ctx[1].Status) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$1(ctx);
if_block.c();
if_block.m(div2, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (status.Status) if_block.p(ctx, dirty);
if (dirty & /*url*/ 1) set_data_dev(t5, /*url*/ ctx[0]);
if (dirty & /*download_path*/ 4) {
attr_dev(a, "href", /*download_path*/ ctx[2]);
}
},
d: function destroy(detaching) {
if (detaching) detach_dev(a);
@ -1055,43 +1034,36 @@ var app = (function () {
block,
id: create_then_block.name,
type: "then",
source: "(48:0) {:then video_info}",
source: "(12:0) {:then video_info}",
ctx
});
return block;
}
// (53:6) {#if status.Status}
// (17:6) {#if status.Status}
function create_if_block$1(ctx) {
let div;
let span;
let t_value = /*statusBadge*/ ctx[4][/*status*/ ctx[1].Status].text + "";
let t_value = statusBadge[status.Status].text + "";
let t;
let span_class_value;
const block = {
c: function create() {
div = element("div");
span = element("span");
t = text(t_value);
attr_dev(span, "class", span_class_value = /*statusBadge*/ ctx[4][/*status*/ ctx[1].Status].class);
add_location(span, file$2, 53, 37, 1450);
attr_dev(span, "class", statusBadge[status.Status].class);
add_location(span, file$2, 17, 37, 697);
attr_dev(div, "class", "pb-2 px-2 bd-highlight");
add_location(div, file$2, 53, 1, 1414);
add_location(div, file$2, 17, 1, 661);
},
m: function mount(target, anchor) {
insert_dev(target, div, anchor);
append_dev(div, span);
append_dev(span, t);
},
p: function update(ctx, dirty) {
if (dirty & /*status*/ 2 && t_value !== (t_value = /*statusBadge*/ ctx[4][/*status*/ ctx[1].Status].text + "")) set_data_dev(t, t_value);
if (dirty & /*status*/ 2 && span_class_value !== (span_class_value = /*statusBadge*/ ctx[4][/*status*/ ctx[1].Status].class)) {
attr_dev(span, "class", span_class_value);
}
},
p: noop,
d: function destroy(detaching) {
if (detaching) detach_dev(div);
}
@ -1101,14 +1073,14 @@ var app = (function () {
block,
id: create_if_block$1.name,
type: "if",
source: "(53:6) {#if status.Status}",
source: "(17:6) {#if status.Status}",
ctx
});
return block;
}
// (46:24) <p>waiting...</p> {:then video_info}
// (10:24) <p>waiting...</p> {:then video_info}
function create_pending_block(ctx) {
let p;
@ -1116,7 +1088,7 @@ var app = (function () {
c: function create() {
p = element("p");
p.textContent = "waiting...";
add_location(p, file$2, 46, 2, 1058);
add_location(p, file$2, 10, 2, 305);
},
m: function mount(target, anchor) {
insert_dev(target, p, anchor);
@ -1131,7 +1103,7 @@ var app = (function () {
block,
id: create_pending_block.name,
type: "pending",
source: "(46:24) <p>waiting...</p> {:then video_info}",
source: "(10:24) <p>waiting...</p> {:then video_info}",
ctx
});
@ -1149,11 +1121,11 @@ var app = (function () {
pending: create_pending_block,
then: create_then_block,
catch: create_catch_block,
value: 3,
error: 9
value: 2,
error: 3
};
handle_promise(/*startDownload*/ ctx[5](), info);
handle_promise(startDownload(), info);
const block = {
c: function create() {
@ -1161,7 +1133,7 @@ var app = (function () {
info.block.c();
},
l: function claim(nodes) {
throw new Error_1("options.hydrate only works if the component was compiled with the `hydratable: true` option");
throw new Error("options.hydrate only works if the component was compiled with the `hydratable: true` option");
},
m: function mount(target, anchor) {
insert_dev(target, await_block_anchor, anchor);
@ -1197,109 +1169,47 @@ var app = (function () {
function instance$2($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
validate_slots('Task', slots, []);
let { url } = $$props;
let { endpoint } = $$props;
let video_info = {};
let status = {};
let { url } = $$props;
let statusBadge = {
1: {
"class": "badge bg-secondary",
"text": "Downloading"
},
2: {
"class": "badge bg-success",
"text": "Completed"
},
3: {
"class": "badge bg-error",
"text": "Error"
}
};
let download_path = "#";
async function startDownload() {
// FIXME: Payload shoud be sent as JSON
onMount(async () => {
const res = await fetch(`${endpoint}/task`, {
method: 'POST',
body: new URLSearchParams({ url })
});
$$invalidate(3, video_info = await res.json());
await res.json();
});
if (res.ok) {
return video_info;
} else {
throw new Error(video_info);
}
}
async function getStatus() {
const res = await fetch(`${endpoint}/task/${video_info.ID}`);
$$invalidate(1, status = await res.json());
if (res.ok) {
if (status.Id) {
$$invalidate(2, download_path = `${endpoint}/data/${status.Id}`);
}
return status;
} else {
throw new Error(status);
}
}
const interval = setInterval(
() => {
getStatus();
},
1000
);
const writable_props = ['url', 'endpoint'];
const writable_props = ['endpoint', 'url'];
Object.keys($$props).forEach(key => {
if (!~writable_props.indexOf(key) && key.slice(0, 2) !== '$$' && key !== 'slot') console.warn(`<Task> was created with unknown prop '${key}'`);
});
$$self.$$set = $$props => {
if ('endpoint' in $$props) $$invalidate(1, endpoint = $$props.endpoint);
if ('url' in $$props) $$invalidate(0, url = $$props.url);
if ('endpoint' in $$props) $$invalidate(6, endpoint = $$props.endpoint);
};
$$self.$capture_state = () => ({
url,
endpoint,
video_info,
status,
statusBadge,
download_path,
startDownload,
getStatus,
interval
});
$$self.$capture_state = () => ({ onMount, endpoint, url });
$$self.$inject_state = $$props => {
if ('endpoint' in $$props) $$invalidate(1, endpoint = $$props.endpoint);
if ('url' in $$props) $$invalidate(0, url = $$props.url);
if ('endpoint' in $$props) $$invalidate(6, endpoint = $$props.endpoint);
if ('video_info' in $$props) $$invalidate(3, video_info = $$props.video_info);
if ('status' in $$props) $$invalidate(1, status = $$props.status);
if ('statusBadge' in $$props) $$invalidate(4, statusBadge = $$props.statusBadge);
if ('download_path' in $$props) $$invalidate(2, download_path = $$props.download_path);
};
if ($$props && "$$inject" in $$props) {
$$self.$inject_state($$props.$$inject);
}
return [url, status, download_path, video_info, statusBadge, startDownload, endpoint];
return [url, endpoint];
}
class Task extends SvelteComponentDev {
constructor(options) {
super(options);
init(this, options, instance$2, create_fragment$2, safe_not_equal, { url: 0, endpoint: 6 });
init(this, options, instance$2, create_fragment$2, safe_not_equal, { endpoint: 1, url: 0 });
dispatch_dev("SvelteRegisterComponent", {
component: this,
@ -1311,29 +1221,29 @@ var app = (function () {
const { ctx } = this.$$;
const props = options.props || {};
if (/*endpoint*/ ctx[1] === undefined && !('endpoint' in props)) {
console.warn("<Task> was created without expected prop 'endpoint'");
}
if (/*url*/ ctx[0] === undefined && !('url' in props)) {
console.warn("<Task> was created without expected prop 'url'");
}
if (/*endpoint*/ ctx[6] === undefined && !('endpoint' in props)) {
console.warn("<Task> was created without expected prop 'endpoint'");
}
}
get url() {
throw new Error_1("<Task>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}
set url(value) {
throw new Error_1("<Task>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}
get endpoint() {
throw new Error_1("<Task>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
throw new Error("<Task>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}
set endpoint(value) {
throw new Error_1("<Task>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
throw new Error("<Task>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}
get url() {
throw new Error("<Task>: Props cannot be read directly from the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}
set url(value) {
throw new Error("<Task>: Props cannot be set directly on the component instance unless compiling with 'accessors: true' or '<svelte:options accessors/>'");
}
}

File diff suppressed because one or more lines are too long

View file

@ -1,45 +1,13 @@
<script>
export let url;
export let endpoint;
<script lang="ts">
import { onMount } from 'svelte'
export let endpoint: string
export let url: string
let video_info = {};
let status = {};
let statusBadge = {
1: {"class": "badge bg-secondary", "text": "Downloading"},
2: {"class": "badge bg-success", "text": "Completed"},
3: {"class": "badge bg-error", "text": "Error"}
};
let download_path = "#";
async function startDownload() {
// FIXME: Payload shoud be sent as JSON
const res = await fetch(`${endpoint}/task`, {method: 'POST', body: new URLSearchParams({'url': url})});
video_info = await res.json();
if (res.ok) {
return video_info;
} else {
throw new Error(video_info);
}
}
async function getStatus() {
const res = await fetch(`${endpoint}/task/${video_info.ID}`);
status = await res.json();
if (res.ok) {
if (status.Id) {
download_path = `${endpoint}/data/${status.Id}`;
}
return status;
} else {
throw new Error(status);
}
}
const interval = setInterval(() => { getStatus(); }, 1000);
onMount(async () => {
const res = await fetch(`${endpoint}/task`, {method: 'POST', body: new URLSearchParams({'url': url})})
const videoInfo = await res.json()
})
</script>

View file

@ -0,0 +1,62 @@
<script>
export let url;
export let endpoint;
let video_info = {};
let status = {};
let statusBadge = {
1: {"class": "badge bg-secondary", "text": "Downloading"},
2: {"class": "badge bg-success", "text": "Completed"},
3: {"class": "badge bg-error", "text": "Error"}
};
let download_path = "#";
async function startDownload() {
// FIXME: Payload shoud be sent as JSON
const res = await fetch(`${endpoint}/task`, {method: 'POST', body: new URLSearchParams({'url': url})});
video_info = await res.json();
if (res.ok) {
return video_info;
} else {
throw new Error(video_info);
}
}
async function getStatus() {
const res = await fetch(`${endpoint}/task/${video_info.ID}`);
status = await res.json();
if (res.ok) {
if (status.ID) {
download_path = `${endpoint}/data/${status.ID}`;
}
return status;
} else {
throw new Error(status);
}
}
const interval = setInterval(() => { getStatus(); }, 1000);
</script>
{#await startDownload()}
<p>waiting...</p>
{:then video_info}
<a href={download_path} class="list-group-item list-group-item-action" aria-current="true">
<div class="d-flex bd-highlight">
<div class="pb-2 flex-grow-1 bd-highlight"><h5>{video_info.Title}</h5></div>
<div class="pb-2 px-2 bd-highlight"><small>2 minutes ago</small></div>
{#if status.Status}
<div class="pb-2 px-2 bd-highlight"><span class={statusBadge[status.Status].class}>{statusBadge[status.Status].text}</span></div>
{/if}
</div>
<p><small>{url}</small></p>
<img alt="This is a thumbnail" src={video_info.Thumbnails[0].URL}/>
</a>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}

29
tmux.bash Executable file
View file

@ -0,0 +1,29 @@
#!/bin/bash
# Set Session Name
SESSION="yt-dls"
SESSIONEXISTS=$(tmux list-sessions | grep $SESSION)
# Only create tmux session if it doesn't already exist
if [ "$SESSIONEXISTS" = "" ]
then
# Start New Session with our name
tmux new-session -d -s $SESSION
# Name first Pane and start zsh
tmux rename-window -t 0 'Main'
# Create and setup pane for running the backend
# tmux send-keys -t 'Main' 'bash' C-m 'clear' C-m 'cd backend && go build -o backend . && ./backend' C-m
tmux send-keys -t 'Main' 'cd backend && go build -o backend . && ./backend' C-m
# Create and setup pane for running the backend
tmux split-window -h 'cd frontend && npm run dev'
# Create an horizontal pane for terminal commands
tmux split-window -vf -l 1
tmux send-keys 'emacs backend/main.go &' Enter
fi
# Attach Session, on the Main window
tmux attach-session -t $SESSION:0