From ebe52f2d38b31e41638c18d87aacb2da2364ed1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?King=20K=C3=A9vin?= Date: Tue, 31 Jan 2023 03:37:49 +0100 Subject: [PATCH] add attach functionality --- public/index.html | 1 + public/partdb.js | 26 ++++++++++++++++++++++++++ server.rb | 22 ++++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/public/index.html b/public/index.html index 8ca6059..6c384b9 100644 --- a/public/index.html +++ b/public/index.html @@ -42,6 +42,7 @@
+
diff --git a/public/partdb.js b/public/partdb.js index d5e5498..4eb8c2c 100644 --- a/public/partdb.js +++ b/public/partdb.js @@ -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(); + +} diff --git a/server.rb b/server.rb index 4eacfcc..6680cb0 100755 --- a/server.rb +++ b/server.rb @@ -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
componentquantitydescription