add attach functionality

This commit is contained in:
King Kévin 2023-01-31 03:37:49 +01:00
parent eb66f0c81a
commit ebe52f2d38
3 changed files with 49 additions and 0 deletions

View File

@ -42,6 +42,7 @@
<tbody id="properties"></tbody>
</table>
<div class="hscroll" id="attachments"></div>
<div><input type="text" id="attachment" placeholder="URL"><button type="button" onclick="attach()">attach</button></div>
<table>
<thead><tr><th>component</th><th>quantity</th><th>description</th></tr></thead>
<tbody id="components"></tbody>

View File

@ -262,3 +262,29 @@ function update_part()
};
post.send(JSON.stringify(part));
}
function attach()
{
const results = document.getElementById('results');
if (results.selectedIndex >= 0) {
part_id = parseInt(results.options[results.selectedIndex].value);
} else {
part_id = null;
return;
}
const attachment = document.getElementById('attachment');
if (null == attachment.value || 0 == attachment.value.length) {
return;
}
const xhr = new XMLHttpRequest();
xhr.open('GET', '/attach?id=' + part_id + "&url=" + encodeURI(attachment.value), true);
xhr.onload = function() {
clear();
search(); // refresh search
};
xhr.onerror = function() {
console.log("part attachment failed");
};
xhr.send();
}

View File

@ -17,6 +17,7 @@ require 'json'
require 'sinatra'
require 'uri'
require 'net/http'
require 'cgi'
# allow dumping crashes in browser
DEBUG = false
@ -463,3 +464,24 @@ get '/import/lcsc/:lcsc' do
end
return 200, "#{part['name']} added"
end
get '/attach?' do
halt 401, "part name or id required" unless params['id'] or params['name']
halt 401, "attachement URL required" unless params['url']
statement = @db.prepare("SELECT id, name FROM part WHERE id = ? OR name = ?")
part = statement.execute(params['id'], params['name']).to_a[0]
halt 401, "unknown part" unless part
file = CGI.unescape(params['url']).split("/")[-1]
dir = PUBLIC + "/" + ATTACHMENTS + "/" + part["name"].gsub("/", "_")
path = "#{dir}/#{file}"
unless File.file?(path) then
uri = URI(params['url'])
res = Net::HTTP.get_response(uri)
if (res.is_a?(Net::HTTPSuccess)) then
Dir.mkdir(dir) unless File.directory?(dir)
File.open(path, "wb") do |f|
f.write res.body
end
end
end
end