def add_tool(request):
    t = {}
    if request.method == 'POST':
        name = request.POST.get('name')
        t = Tool(
            name=name)
        t.save()
    return HttpResponse(serializers.serialize("json", [t]))
Beispiel #2
0
def save_changes(bin, form, new=False):
    """
    Save the changes to the database
    """
    # Get data from form and assign it to the correct attributes
    # of the SQLAlchemy table object
    tool = Tool()
    tool.name = form.partnumber.data

    bin.partnumber = tool
    bin.location = form.location.data

    if new:
        # Add the new album to the database
        db_session.add(bin)

    # commit the data to the database
    db_session.commit()
Beispiel #3
0
def new_tool():
    form = ToolForm()
    if form.validate_on_submit():
        tool = Tool()
        form.populate_obj(tool)
        db.session.add(tool)
        db.session.commit()
        return redirect(url_for('list_tools'))
    return render_template('tool.html', form=form, is_new=True)
Beispiel #4
0
def admin_tools_add():
    tool = Tool(
        name=request.form['name'],
        path=request.form['path'],
        description=request.form['description'],
    )
    db.session.add(tool)
    db.session.commit()
    flash('Tool added.')
    return redirect(url_for('admin'))
Beispiel #5
0
    def __parse_xliff(self, contents):
        ns = {"xliff": "urn:oasis:names:tc:xliff:document:1.2"}

        tree = ElementTree.parse(self.xliff_path)
        root = tree.getroot()

        for file in root:
            localized_contents = LocalizedContents()
            localized_contents.file = file.get("original")
            localized_contents.source = file.get("source-language")
            localized_contents.target = file.get("target-language")

            header = file.find("xliff:header", ns)
            header_tool = header.find("xliff:tool", ns)
            tool = Tool()
            tool.id = header_tool.get("tool-id")
            tool.name = header_tool.get("tool-name")
            tool.version = header_tool.get("tool-version")
            tool.build = header_tool.get("build-num")
            localized_contents.tool = tool

            for trans_unit in (body := file.find("xliff:body", ns)):
                translation = Translation()
                translation.id = trans_unit.get("id")

                if (source_tag := trans_unit.find("xliff:source",
                                                  ns)) is not None:
                    translation.source = source_tag.text

                if (target_tag := trans_unit.find("xliff:target",
                                                  ns)) is not None:
                    translation.target = target_tag.text
    def __parse_translation_sheets(self, contents, wb):
        # Get metadata
        index = wb["_metadata_"]
        temp_localized_contents = []
        for i in range(4, index.max_row + 1):
            localized_contents = LocalizedContents()

            localized_contents.file = index["C" + str(i)].value
            localized_contents.source = index["D" + str(i)].value
            localized_contents.target = index["E" + str(i)].value

            tool = Tool()
            tool.id = index["F" + str(i)].value
            tool.name = index["G" + str(i)].value
            tool.version = index["H" + str(i)].value
            tool.build = index["I" + str(i)].value
            localized_contents.tool = tool

            temp_localized_contents.append(localized_contents)

        # Parse all sheets
        for sheetname in wb.sheetnames:
            if sheetname == "_metadata_":
                continue

            ws = wb[sheetname]
            row = 1

            if ws["A" + str(row)].value != "No":
                row += 1

            if ws["A" + str(row)].value != "No":
                print("Sheet format is invalidated : {}".format(sheetname))
                continue

            row += 1

            # Get localized content with metadata
            filtered_localized_contents = list(
                filter(lambda c: c.basename == sheetname,
                       temp_localized_contents))
            if filtered_localized_contents == False:
                print("Sheet metadata not found: {}".format(sheetname))
                continue

            localized_contents = filtered_localized_contents[0]

            # Add translations
            for i in range(row, ws.max_row + 1):
                translation = Translation()
                translation.id = ws["B" + str(i)].value
                translation.source = ws["C" + str(i)].value
                translation.target = ws["D" + str(i)].value
                translation.note = ws["E" + str(i)].value

                localized_contents.translations.append(translation)

            contents.localized_contents.append(localized_contents)
Beispiel #7
0
def setup_fake_data():
    print('Adding fake data to database...')

    tool = Tool(name=u'Martillo',
                description=u'Pa martillar',
                location=u'AETEL – Panel de herramientas',
                manual=u'here',
                documentation=u'there')
    db_session.add(tool)

    workshop1 = Workshop(name=u'Croquetas Caseras', description=u'¿Alguna vez has querido hacer tus propias croquetas caseras?', \
                        members_only=False, participants=99, date=(datetime.now() + timedelta(days=1)))
    db_session.add(workshop1)

    workshop2 = Workshop(name=u'Empanadillas Caseras', description=u'¿Alguna vez has querido hacer tus propias empanadillas caseras?', \
                        members_only=True, participants=99, date=datetime.now())
    db_session.add(workshop2)

    test_user = db_session.query(User).filter_by(dni='00000001A').first()

    test_user.workshop_instructor.append(workshop1)
    test_user.workshop_instructor.append(workshop2)

    tool.workshops.append(workshop1)
    test_user.tool_maintainer.append(tool)

    db_session.commit()

    nombre = u'¡Elegimos fiesta nacional!'
    voting = Voting(name=nombre, description='Fiesta fiesta fiesta', \
                    start_date=datetime.now(), end_date=(datetime.now() + timedelta(days=3)) )
    db_session.add(voting)
    db_session.commit()

    option1 = Option(
        name=u'Día Nacional de la croqueta',
        voting_id=db_session.query(Voting).filter_by(name=nombre).first().id)
    db_session.add(option1)
    option2 = Option(
        name=u'Día Nacional de la empanadilla',
        voting_id=db_session.query(Voting).filter_by(name=nombre).first().id)
    db_session.add(option2)

    db_session.commit()
    def __parse_metadata_sheet(self, contents, wb):
        index = wb["_metadata_"]

        contents.file = pathlib.Path(index["C2"].value)
        contents.version = index["B2"].value
        contents.source = index["D2"].value
        contents.target = index["E2"].value

        tool = Tool()
        tool.id = index["F2"].value
        tool.name = index["G2"].value
        tool.version = index["H2"].value
        tool.build = index["I2"].value
        contents.tool = tool
Beispiel #9
0
    def __parse_contents_json(self, contents):
        with open(self.contents_json_path, "r") as contents_json:
            root = json.load(contents_json)
            contents.source = root["developmentRegion"]
            contents.target = root["targetLocale"]
            contents.version = root["version"]

            tool_info = root["toolInfo"]
            tool = Tool()
            tool.id = tool_info["toolID"]
            tool.name = tool_info["toolName"]
            tool.version = tool_info["toolVersion"]
            tool.build = tool_info["toolBuildNumber"]
            contents.tool = tool
Beispiel #10
0
def add_tool_form():
    """add a tool"""
    form = ToolAddForm()
    username = session["username"]
    if "username" not in session or username != session['username']:
        flash("You are not authorized to view that page", "danger")
        return redirect('/')

    if form.validate_on_submit():
        user = User.query.filter_by(username=username).first()  #get the user
        name = form.name.data
        description = form.description.data

        new_tool = Tool(owner_id=user.id,
                        name=name,
                        description=description,
                        location_id=user.zip_code)
        db.session.add(new_tool)
        db.session.commit()
        flash("New Tool Added", "success")
        return redirect(f"/users/{username}")

    user = User.query.filter_by(username=username).first()
    return render_template('tools/add_tool.html', user=user, form=form)
Beispiel #11
0
def view_tool():
    session['url'] = request.url[len(request.url_root):]
    if request.method == 'GET':
        if 'name' in request.args:
            name = request.args.get('name')
            result = db_session.query(Tool).filter_by(name=name).first()
            return render_template('tool.html',
                                   result=result,
                                   title='cutrenet',
                                   subtitle=name)
        elif not current_user.has_role('admin'):
            flash(u'No tienes permisos para editar esta herramienta', 'error')
            return redirect('/tools', code=302)
        elif 'add' in request.args:
            form = ToolForm()
            return render_template('tool.html',
                                   form=form,
                                   title='cutrenet',
                                   subtitle="new tool")
        elif 'edit' in request.args:
            ename = request.args.get('edit')
            form = ToolForm(self_edit=ename)
            result = db_session.query(Tool).filter_by(name=ename).first()
            form.description.data = result.description  # Prepopulate textarea with past information, can´t do it at render time
            if result.maintainer is not None:
                form.maintainer.data = result.maintainer.dni
            return render_template('tool.html',
                                   form=form,
                                   result=result,
                                   title='cutrenet',
                                   subtitle=ename)
        elif 'delete_img' in request.args:
            del_img = request.args.get('delete_img')
            tool = db_session.query(Tool).filter_by(name=del_img).first()
            if tool.image:
                os.remove(tool.image)  # Delete old image
                tool.image = None
                db_session.commit()
                flash(u'Imagen eliminada', 'success')
            else:
                flash(u'No hay imagen que eliminar', 'alert')
            return render_template('tool.html',
                                   result=tool,
                                   title='cutrenet',
                                   subtitle=tool.name)
        elif 'delete' in request.args:
            delete = request.args.get('delete')
            tool = db_session.query(Tool).filter_by(name=delete).first()
            db_session.delete(tool)
            db_session.commit()
            flash(u'Herramienta eliminada', 'success')
            return redirect('/tools', code=302)
        else:
            flash(u'Tienes que seleccionar una herramienta', 'error')
            return redirect('/tools', code=302)

    if request.method == 'POST' and current_user.has_role('admin'):
        if 'edit' in request.args:
            ename = request.args.get('edit')
            tool = db_session.query(Tool).filter_by(name=ename).first()
            form = ToolForm(self_edit=ename)
            if form.validate_on_submit():
                tool.name = request.form['name']
                tool.description = request.form['description']
                tool.location = request.form['location']
                tool.manual = request.form['manual']
                tool.documentation = request.form['documentation']

                maintainer = db_session.query(User).filter_by(
                    dni=request.form['maintainer']).first()
                if maintainer is not None:
                    maintainer.tool_maintainer.append(tool)

                if form.image.data:
                    if tool.image is not None:
                        os.remove(tool.image)  # Delete old image
                    f = form.image.data
                    filename = secure_filename(f.filename)
                    directory = app.config['UPLOAD_FOLDER'] + '/tools'
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    file_path = os.path.join(directory, filename)
                    f.save(file_path)
                    tool.image = file_path  # Save the file path of the Tool image in the database

                db_session.commit()
                flash(u'Herramienta editada', 'success')
            return render_template('tool.html',
                                   form=form,
                                   result=tool,
                                   title='cutrenet',
                                   subtitle=tool.name)
        elif 'add' in request.args:
            tool = Tool()
            form = ToolForm()
            if form.validate_on_submit():
                tool.name = request.form['name']
                tool.description = request.form['description']
                tool.location = request.form['location']
                tool.manual = request.form['manual']
                tool.documentation = request.form['documentation']

                maintainer = db_session.query(User).filter_by(
                    dni=request.form['maintainer']).first()
                if maintainer is not None:
                    maintainer.tool_maintainer.append(tool)

                if form.image.data:
                    if tool.image is not None:
                        os.remove(tool.image)  # Delete old image
                    f = form.image.data
                    filename = secure_filename(f.filename)
                    directory = app.config['UPLOAD_FOLDER'] + '/tools'
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    file_path = os.path.join(directory, filename)
                    f.save(file_path)
                    tool.image = file_path  # Save the file path of the Tool image in the database

                db_session.add(tool)
                db_session.commit()
                flash(u'Herramienta añadida', 'success')
                return redirect('tools', code=302)
            return render_template('tool.html',
                                   form=form,
                                   title='cutrenet',
                                   subtitle="new tool")
Beispiel #12
0
def main():
	commands = {}
	config = None
	ignore_list = []
	settings = AttributeStore()
	tools = {}
	asset_folders = []
	
	p = argparse.ArgumentParser()
	p.add_argument(
		"-c",
		"--config", 
		dest="config_path", 
		metavar="CONFIG_FILE_PATH",
		help="Configuration file path to use when converting assets",
		required=True
	)

	p.add_argument(
		"-p",
		"--platform",
		dest="platform"
	)
	p.add_argument(
		"-y",
		"--clear-cache",
		dest="clear_cache",
		action="store_true"
	)
	p.add_argument(
		"-s",
		"--source_root",
		dest="source_root"
	)

	args = p.parse_args()
	config_cache = KeyValueCache()

	# load config
	config_data = load_config(args.config_path, config_cache)
	
	# the source_root can be specified on the command line;
	# this properly inserts it into the paths dict
	if "paths" in config_data:
		if "source_root" not in config_data["paths"]:
			if not args.source_root:
				raise Exception(
						"source_root is missing. This should be defined"
						" in a config file, or on the command line."
					)				
			else:
				# this path SHOULD be an absolute path
				config_data["paths"]["source_root"] = args.source_root

	config = AttributeStore(config_data)

	if not args.platform:
		args.platform = get_platform()
		logging.info("Target Platform is \"%s\"" % args.platform)


	# load tools
	tools_path = os.path.abspath(
		os.path.join(
		WorkingDirectory.current_directory(),
		os.path.dirname(__file__),
		"tools.conf"
		)
	)

	# get cache path
	cache = Cache(args.config_path, remove=args.clear_cache)
	cache.load()

	# conform all paths
	if getattr(config, "paths", None):
		base_path = os.path.dirname(os.path.abspath(args.config_path))

		# setup environment variables, path, etc.
		config.paths = setup_environment(base_path, config.paths, args.platform)
		
		setattr(settings, "paths", AttributeStore(config.paths))


	# parse all tools
	Tool.load_tools(
		tools,
		tools_path,
		config.tools
	)

	logging.info("Loaded %i tools." % len(tools.items()))

	# parse asset folders
	for asset_glob in config.assets:
		data = dict(
			{u"glob" : asset_glob}.items() +
			config.assets[asset_glob].items()
		)
		asset_folder = AssetFolderMask(**data)
		asset_folder.make_folders_absolute(
			settings.paths.source_root, 
			settings.paths.destination_root
		)
		asset_folders.append(asset_folder)
	logging.info("Loaded %i asset folders." % len(asset_folders))

	# check if we need to enter monitoring mode
	monitor_mode = hasattr(config, "monitor")
	if monitor_mode:
		monitor = config.monitor
		if not "url" in monitor:
			raise Exception("Monitor block requires a \"url\" parameter")

		# run monitoring
		monitor_assets(
			cache,
			settings,
			asset_folders,
			tools,
			args.platform,
			monitor["url"]
		)
	else:
		# just run through all assets
		iterate_assets(
			cache,
			settings,
			asset_folders,
			tools, 
			args.platform
		)

	# write cache to file
	cache.save()