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

Loading of default libraries into the backend while building the project and loading of circuits from gallery fixed #259

Merged
merged 7 commits into from
Jun 5, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ export default function ComponentSidebar ({ compRef }) {
setLoading(true)
var config = {}
const token = localStorage.getItem('esim_token')
if (token !== null || token !== undefined) {
if (token !== null && token !== undefined) {
console.log(token)
config = {
headers: {
Authorization: `Token ${token}`
Expand Down
11 changes: 4 additions & 7 deletions eda-frontend/src/redux/actions/schematicEditorActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,14 @@ export const fetchLibrary = (libraryId) => (dispatch) => {
// "saved_on": "2021-05-10T20:29:01.794498Z",
// "id": 363
// } -- Single Object
// const token = store.getState().authReducer.token
// const config = {headers: {
// 'Content-Type': 'application/json'
// }}
// if(token)
// config.headers.Authorization = `Token ${token}`
const token = store.getState().authReducer.token
const config = {
headers: {
Authorization: `Token ${store.getState().authReducer.token}`
'Content-Type': 'application/json'
}
}
if (token) { config.headers.Authorization = `Token ${token}` }

api.get(`libraries/${libraryId}`, config).then(res => {
dispatch({
type: actions.FETCH_LIBRARY,
Expand Down
12 changes: 6 additions & 6 deletions eda-frontend/src/utils/GallerySchSample.js

Large diffs are not rendered by default.

13 changes: 5 additions & 8 deletions esim-cloud-backend/libAPI/admin.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from libAPI.lib_utils import handle_uploaded_libs
from django.contrib import admin, messages
from django.contrib.auth import get_user_model
from libAPI.models import LibraryComponent, \
Library, \
LibrarySet, \
FavouriteComponent, \
delete_uploaded_files, \
save_libs
from .forms import LibrarySetForm
FavouriteComponent
from libAPI.forms import LibrarySetForm
from inline_actions.admin import InlineActionsMixin
from inline_actions.admin import InlineActionsModelAdminMixin
from django.shortcuts import redirect
Expand Down Expand Up @@ -92,12 +91,10 @@ def save_model(self, request, obj, form, change):
files = request.FILES.getlist('files')
if len(files) != 0:
path = os.path.join(
settings.BASE_DIR,
settings.BASE_DIR[6:],
'kicad-symbols',
obj.user.username + '-' + obj.name)

save_libs(obj, path, files) # defined in ./models.py
delete_uploaded_files(files, path)
handle_uploaded_libs(obj, path, files) # defined in ./lib_utils.py
return redirect('/api/admin/libAPI/libraryset/' + str(obj.id))


Expand Down
7 changes: 7 additions & 0 deletions esim-cloud-backend/libAPI/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ class LibrarySetForm(forms.ModelForm):
widget=forms.ClearableFileInput(attrs={'multiple': True})
)

def __init__(self, *args, **kwargs):
super(LibrarySetForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['user'].widget.attrs['disabled'] = True
self.fields['name'].widget.attrs['readonly'] = True

class Meta:
model = LibrarySet
fields = ('name', 'user', 'default', 'files')
116 changes: 116 additions & 0 deletions esim-cloud-backend/libAPI/lib_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
from libAPI.helper.main import generate_svg_and_save_to_folder
from libAPI.models import Library, LibraryComponent, ComponentAlternate
import os
import glob


def save_uploaded_files(files, path):
for f in files:
filepath = os.path.join(path, f._name)
with open(filepath, 'wb') as dest:
for chunk in f.chunks():
dest.write(chunk)


def handle_uploaded_libs(library_set, path, files):
if not os.path.isdir(path):
os.mkdir(path)
save_uploaded_files(files, path)
filenames = []
for f in files:
filenames.append(f._name)
save_libs(filenames, path, path, library_set)
for f in files:
os.remove(path + '/' + f._name)


def save_libs(files, path, out_path, library_set):
for f in files:
if '.dcm' in f:
flag = 0
for f1 in files:
if f1[:-4] == f[:-4] and '.lib' in f1:
flag = 1
if flag == 0:
raise FileNotFoundError(
f'.lib file for {f} does not exist')
if '.lib' in f:
lib_output_location = os.path.join(out_path, 'symbol-svgs')
lib_location = os.path.join(path, f)
component_details = generate_svg_and_save_to_folder(
lib_location,
lib_output_location
)
library = Library.objects.filter(
library_name=f, library_set=library_set).first()
if not library:
library = Library(
library_name=f,
library_set=library_set
)
library.save()

library_svg_folder = os.path.join(
lib_output_location, f[:-4])
thumbnails = glob.glob(library_svg_folder + '/*_thumbnail.svg')

for component_svg in glob.glob(library_svg_folder + '/*-1-A.svg'):
thumbnail_path = component_svg[:-4] + '_thumbnail.svg'
if thumbnail_path not in thumbnails:
raise FileNotFoundError(
f'Thumbnail does not exist for {component_svg}')

# Get Component name
component_svg = os.path.split(component_svg)[-1]

# Get Corresponding Details
svg_desc = component_details[component_svg[:-4]]

# Seed DB
component = LibraryComponent.objects.filter(
name=svg_desc['name'],
svg_path=os.path.join(
library_svg_folder, component_svg),
thumbnail_path=thumbnail_path,
symbol_prefix=svg_desc['symbol_prefix'],
full_name=svg_desc['full_name'],
keyword=svg_desc['keyword'],
description=svg_desc['description'],
data_link=svg_desc['data_link'],
component_library=library
).first()
if not component:
component = LibraryComponent(
name=svg_desc['name'],
svg_path=os.path.join(
library_svg_folder, component_svg),
thumbnail_path=thumbnail_path,
symbol_prefix=svg_desc['symbol_prefix'],
full_name=svg_desc['full_name'],
keyword=svg_desc['keyword'],
description=svg_desc['description'],
data_link=svg_desc['data_link'],
component_library=library
)
component.save()

# Seed Alternate Components
for component_svg in glob.glob(library_svg_folder + '/*[B-Z].svg'):
component_svg = os.path.split(component_svg)[-1]
svg_desc = component_details[component_svg[:-4]]
alternate_component = ComponentAlternate.objects.filter(
part=svg_desc['part'], dmg=svg_desc['dmg'],
full_name=svg_desc['full_name'],
svg_path=os.path.join(
library_svg_folder, component_svg),
parent_component=component
).first()
if not alternate_component:
alternate_component = ComponentAlternate(
part=svg_desc['part'], dmg=svg_desc['dmg'],
full_name=svg_desc['full_name'],
svg_path=os.path.join(
library_svg_folder, component_svg),
parent_component=component
)
alternate_component.save()
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.core.management.base import BaseCommand
import logging
logger = logging.getLogger(__name__)


class Command(BaseCommand):
help = "Create default admin user if not already present."

def add_arguments(self, parser):
parser.add_argument(
'--username', type=str,
help="username of admin account"
)
parser.add_argument(
'--password', type=str,
help="password of the admin account"
)

def handle(self, *args, **options):
if options['username'] and options['password']:
User = get_user_model()
user = User.objects.filter(username=options['username'])
if user.count() > 0:
raise Exception(f"User with same username exists")
user = User.objects.create_superuser(
username=options['username'],
email='', password=options['password']
)
logger.info(
f"Creating user {options['user']}"
" with password {options['password']}")
user.save()
else:
raise Exception("Username or Password not present")
75 changes: 75 additions & 0 deletions esim-cloud-backend/libAPI/management/commands/load_default_libs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from libAPI.lib_utils import save_libs
from libAPI.models import LibrarySet
from esimCloud import settings
import os
import logging
logger = logging.getLogger(__name__)


class Command(BaseCommand):
help = "Load default libraries if not already present."

def add_arguments(self, parser):
parser.add_argument(
'--username',
help='input a user\'s username', type=str
)
parser.add_argument(
'--location', type=self.dir_path,
help="Directory containing kicad library files"
)
parser.add_argument(
'--default', action='store_true',
help="set if the library is default or not"
)

def dir_path(self, path):
if os.path.isdir(path):
return path
else:
raise Exception(f"{path} is not a valid path")

def handle(self, *args, **options):
User = get_user_model()

if options['username']:
user = User.objects.get(username=options['username'])
else:
raise Exception("Enter a superuser to associate libs")
name = 'esim-default' if options['default'] else 'esim-additional'
library_set = LibrarySet.objects.filter(
user=user,
default=options['default'],
name=name
).first()
if not library_set:
library_set = LibrarySet(
user=user,
default=True if options['default'] else False,
name=name
)
library_set.save()

out_location = os.path.join(
"kicad-symbols/",
library_set.user.username + "-" + name
)

logger.info(f"Reading libraries from {options['location']}")
logger.info(f"Saving as " + name[6:])
logger.info(f"Saving Libraries to {out_location}")

if not os.path.isdir(out_location):
os.mkdir(out_location)
try:
save_libs(
os.listdir(options['location']),
options['location'],
out_location,
library_set
)
logger.info("Finished without errors")
except Exception:
logger.error("Couldn't save all the libs")
Loading