Пример #1
0
def create_asset():
    """Create a new asset"""
    form = AssetForm()
    form["csrf_token"].data = request.cookies["csrf_token"]
    
    if form.validate_on_submit():
        image_filename = upload_file(form["image"].data)
        asset = Asset(
            user=current_user,
            category=form["category"].data,
            title=form["title"].data,
            description=form["description"].data,
            color=form["color"].data,
            icon=form["icon"].data,
            image=image_filename,
            value=form["value"].data,
            max=form["max"].data,
            is_allowed_multiple=form["is_allowed_multiple"].data,
            )
        
        # TODO Option to add asset assets, meters, conditions?
        db.session.add(asset)
        db.session.commit()
        return asset.to_dict()
    else:
        return {"errors": validation_errors_to_messages(form.errors)}, 401
Пример #2
0
 def addAsset(self, assetName, assetSymbol, assetType):
     sector, subSector = self.GFinSectorIndustry(assetSymbol)
     portfolio = Asset(name=assetName,
                       symbol=assetSymbol,
                       type=assetType,
                       sector=sector,
                       subSector=subSector)
     portfolio.save()
Пример #3
0
def get_monthly_top_commented_articles(top=10, since=None):
    months = Comment.select(fn.date_trunc('month', Comment.created))
    if since:
        months = months.where(Comment.created >= since)
    months = months.group_by(fn.date_trunc('month', Comment.created)).order_by(
        SQL('date_trunc').asc()).tuples()
    month_top_commented_articles_map = {m[0]: [] for m in months}
    output_formatter = lambda mtc: (Asset.get_by_id(mtc[1]).url, mtc[2])
    for month in months:
        month_top_commented_articles_map[month[0]].extend(
            list(
                map(
                    output_formatter,
                    Comment.select(
                        fn.date_trunc('month',
                                      Comment.created), Comment.asset_id,
                        fn.count(Comment.id)).group_by(
                            fn.date_trunc('month', Comment.created),
                            Comment.asset_id).where(
                                fn.date_trunc('month', Comment.created) ==
                                month).order_by((SQL('date_trunc')),
                                                (SQL('count')).desc()).limit(
                                                    int(top)).tuples())))
    first_month = min(month_top_commented_articles_map.keys())
    last_month = max(month_top_commented_articles_map.keys())
    months = get_week_or_month_counter(metric='month',
                                       first_metric_value=first_month,
                                       last_metric_value=last_month)
    monthly_top_commented_articles = list(
        month_top_commented_articles_map.items())
    ret = fill_output_with_default_values(
        metric_counter=months,
        output=monthly_top_commented_articles,
        default_value=[])
    return ret
Пример #4
0
def get(id):
    portf = Portfolio.query.get(id)
    if portf is None:
        abort(404)
    create_asset_form = CreateAssetForm()
    content = PortfolioCard(portf, create_asset_form)
    title = Title(portf.name)
    if create_asset_form.validate_on_submit():
        ticker = create_asset_form.symbol.data.upper()
        symbol = Symbol.query.filter_by(ticker=ticker).first()
        if symbol is None:
            symbol = Symbol(ticker=ticker)
            db.session.add(symbol)
        asset = Asset(
            user=current_user,
            portfolio=portf,
            symbol=symbol,
            price=create_asset_form.price.data,
            volume=create_asset_form.volume.data,
        )
        db.session.add(asset)
        db.session.commit()
        flash("Successfully added asset!", "success")
        return redirect(url_for("portfolio.get", id=portf.id))
    return render_template("portfolio/get.html", content=content, title=title)
Пример #5
0
def create():

    db.create_all()

    for sitename in site_names:
        site = Site(name=sitename)
        site.inbuildings_config = InbuildingsConfig(enabled=False, key="")
        db.session.add(site)

    for typename in asset_types:
        asset_type = AssetType(name=typename)
        db.session.add(asset_type)

    for pointname in point_types:
        point_type = PointType(name=pointname)
        db.session.add(point_type)

    site = Site.query.filter_by(name=site_names[0]).one()
    asset_type = AssetType.query.filter_by(name=asset_types[0]).one()
    asset = Asset(name=test_asset_name,
                  site=site,
                  type=asset_type,
                  health=0,
                  priority=1,
                  notes='')

    # add one of each point type to dummy unit
    for pointtype in point_types:
        point = PointType.query.filter_by(name=pointtype).one()
        asset_point = AssetPoint(name=pointtype, type=point, asset=asset)
        asset.points.append(asset_point)

    db.session.add(asset)
    db.session.commit()
    db.session.close()
Пример #6
0
def insert_assets(waduk_name, waduk_id):
    mycursor.execute(f"SHOW columns FROM asset")
    columns = [column[0] for column in mycursor.fetchall()]

    kerusakan_query = """SELECT * FROM asset"""
    mycursor.execute(kerusakan_query + f" WHERE table_name='{waduk_name}'")
    all_asset = res2array(mycursor.fetchall(), columns)
    for asset in all_asset:
        try:
            obj_dict = {
                "id": asset['id'],
                "kategori": asset['kategori'],
                "nama": asset['nama'],
                "merk": asset['merk'],
                "model": asset['model'],
                "perolehan": asset['perolehan'],
                "nilai_perolehan": asset['nilai_perolehan'],
                "bmn": asset['bmn'],
                "bendungan_id": waduk_id,
                "c_user": asset["cuser"],
                "c_date": asset["cdate"]
            }
            bend_asset = Asset.query.get(asset['id'])
            if bend_asset:
                print(f"Updating asset {asset['id']}")
                for key, value in obj_dict.items():
                    setattr(bend_asset, key, value)
            else:
                print(f"Inserting asset {asset['id']}")
                new_emb = Asset(**obj_dict)
                db.session.add(new_emb)
            db.session.commit()
        except Exception as e:
            print(f"Error Asset : {e}")
            db.session.rollback()
Пример #7
0
def get_assets(id, after=None, page: int=1, limit: int=20):
    assets = Asset.select().order_by(Asset.created.desc())
    where = [Asset.publication==id]
    if after:
        where.append(Asset.created > arrow.get(after).datetime)
    assets = assets.where(*where).paginate(page, limit)
    return [asset.to_dict() for asset in assets]
Пример #8
0
def index():

    form = AssetForm()

    if debug:
        flash('flashing() works.')

    # get all assets from database,
    assets = Asset.query.all()

    # always false on GET request
    if form.validate_on_submit():

        # TODO: data is sanitized? of what? https://wtforms.readthedocs.io/en/2.2.1/fields/
        new_thing = Asset(name=form.name.data,
                          owner=form.owner.data,
                          properties=form.properties.data,
                          services=form.services.data,
                          events=form.events.data)

        db.session.add(new_thing)
        db.session.commit()
        flash('New thing submitted, reloading...?')
        return redirect(url_for('index'))

    return render_template('index_holygrail.html',
                           title='Home',
                           assets=assets,
                           form=form)
Пример #9
0
def get_last2days_top_commented_articles(top=10):
    last2days_top_commented_articles = Comment.select(
        Comment.asset_id, fn.count(Comment.id)).group_by(
            Comment.asset_id).where(Comment.created >= arrow.utcnow().shift(
                days=-int(2)).span('day')[0].date()).order_by(
                    (SQL('count')).desc()).limit(int(top))
    return [(Asset.get_by_id(asset_id).url, count)
            for asset_id, count in last2days_top_commented_articles.tuples()]
Пример #10
0
def list_():
    assets = Asset.select().order_by(Asset.created.desc())
    return [{
        'comments_count': asset.comments_count,
        'pending_comments_count': asset.pending_comments_count,
        'rejected_comments_count': asset.rejected_comments_count,
        **asset.to_dict()
    } for asset in assets]
Пример #11
0
def add_asset():
    form = AssetForm()

    if form.validate_on_submit():
        assets = Asset(name=form.name.data)
        db.session.add(assets)
        db.session.commit()
        return redirect(url_for('main.inventory_detail'))
    return render_template('main/add_assets.html', form=form)
Пример #12
0
def add_asset_upload(sitename):

    site = Site.query.filter_by(name=sitename).one()

    # check if file was uploaded
    if 'file' not in request.files:
        flash('No file selected')
        return redirect(url_for('add_asset', sitename=sitename))
    file = request.files['file']
    if file.filename == '':
        flash('No file selected')
        return redirect(url_for('add_asset', sitename=sitename))

    # check if file is correct type
    if not (file and ('.' in file.filename) and
            (file.filename.rsplit('.', 1)[1].lower() in ['xlsx', 'xlsm'])):
        flash('File must be xlsx/xlsm')
        return redirect(url_for('add_asset', sitename=sitename))

    wb = load_workbook(file)
    asset_list = []

    # each sheet corresponds to a different asset type, with the sheet name as the type name
    for ws in wb.worksheets:
        asset_type = AssetType.query.filter_by(name=ws.title).one()

        # generate asset for each non-blank row in the worksheet
        for row in tuple(ws.rows)[1:]:
            # skip if not all required information is present (name+location+priority)
            if not row[0].value is None and not row[
                    1].value is None and not row[3].value is None:
                # if a field is empty it will be read as the string 'None', so convert to empty string ''
                name = str(row[0].value)
                location = str(row[1].value)
                if location == "None":
                    location = ""
                group = str(row[2].value)
                if group == "None":
                    group = ""
                priority = row[3].value
                notes = str(row[4].value)
                if notes == "None":
                    notes = ""
                asset = Asset(name=name,
                              location=location,
                              group=group,
                              type=asset_type,
                              priority=priority,
                              notes=notes,
                              site=site)
                asset_list.append(asset)

    # generate a page to display and confirm the upload
    return render_template('add_asset_confirm.html',
                           assets=asset_list,
                           site=site)
Пример #13
0
def get_assets_with_comment_stats(id, page: int=1, limit: int=20, after=None):
    assets = Asset.select(
            Asset,
            fn.COUNT(PendingComment.id).alias('total_pending_comments')
        ).where(
            Asset.publication == id
        ).join(
            PendingComment, JOIN.LEFT_OUTER
        ).order_by(
            fn.COUNT(PendingComment.id).desc(),
            Asset.created.desc()
        ).group_by(
            Asset.id
        ).paginate(page, limit)

    asset_ids = [asset.id for asset in assets]

    assets_with_rejected_comments_count = RejectedComment.select(
            RejectedComment.asset_id,
            fn.COUNT(RejectedComment.id).alias('total_rejected_comments')
        ).where(
            RejectedComment.asset_id << asset_ids
        ).group_by(RejectedComment.asset_id)
    rejected_comment_counts = {
        asset.asset_id: asset.total_rejected_comments for asset in assets_with_rejected_comments_count
    }

    assets_with_comments_count = Comment.select(
            Comment.asset_id,
            fn.COUNT(Comment.id).alias('total_comments')
        ).where(
            Comment.asset_id << asset_ids
        ).group_by(Comment.asset_id)
    comment_counts = {
        asset.id: asset.total_comments for asset in assets_with_comments_count
    }

    return [
        {
            'comments_count': comment_counts.get(asset.id, 0),
            'pending_comments_count': asset.total_pending_comments,
            'rejected_comments_count': rejected_comment_counts.get(asset.id, 0),
            'commenting_closed': asset.commenting_closed,
            **asset.to_dict()
        }
        for asset in assets
    ]
Пример #14
0
def get_pending_comments_by_asset(since=None):
    pending_comments_by_asset = PendingComment.select(
        PendingComment.asset_id,
        fn.count(PendingComment.id)).group_by(PendingComment.asset_id)
    if since:
        pending_comments_by_asset = pending_comments_by_asset.where(
            PendingComment.created >= since)
    total_pending = sum(
        [count for asset_id, count in pending_comments_by_asset.tuples()])
    pending_comments_by_asset = [
        (Asset.get_by_id(asset_id).url, count)
        for asset_id, count in pending_comments_by_asset.tuples()
    ]
    return {
        'total_pending': total_pending,
        'pending_comments_by_asset': pending_comments_by_asset
    }
def clone_asset(id, cloneassetid):
    analyse = Analyse.query.get_or_404(id)
    form = AnalyseForm(obj=analyse)

    # clone asset and assign to analyse
    asset = Asset.query.get_or_404(cloneassetid)
    newasset = Asset()
    newasset.name = asset.name + "_CLONED " + datetime.datetime.now().strftime(
        "%I:%M%p on %B %d, %Y")
    newasset.analyse_id = id
    #for a in asset.assetattackers:
    #    newasset.assetattackers.append(a)
    newasset.criticality = asset.criticality
    newasset.sensitivity = asset.sensitivity
    newasset.description = asset.description
    newasset.exposition = asset.exposition
    db.session.add(newasset)
    #db.session.commit()

    attackers = Attacker.query.all()
    for attacker in attackers:
        aa = AssetAttacker.query.filter_by(asset_id=asset.id).filter_by(
            attacker_id=attacker.id).first()
        if (aa):
            mya = AssetAttacker()
            mya.asset_id = newasset.id
            mya.attacker_id = attacker.id
            mya.description = aa.description
            mya.wert = aa.wert
            db.session.add(mya)
            #db.session.commit()
    db.session.commit()

    add_analyse = False
    assets = analyse.assets
    allassets = Asset.query.all()
    return render_template('home/analyses/analyse.html',
                           add_analyse=add_analyse,
                           form=form,
                           title="Edit Analyse",
                           assets=assets,
                           allassets=allassets,
                           analyseid=id)
Пример #16
0
def flupload():
    saved_asset_ids = []
    sub_folder = str(time.strftime('%y%m%d'))
    directory_id = 0

    directory = _pop_last_directory()
    if directory:
        current_directory = Directory.query.filter_by(name=directory).first()
        directory_id = current_directory.id

    # for key, file in request.files.iteritems():
    for f in request.files.getlist('file'):
        upload_name = f.filename
        # start to save
        name_prefix = 'admin' + str(time.time())
        name_prefix = hashlib.md5(name_prefix.encode('utf-8')).hexdigest()[:15]

        filename = uploader.save(f, folder=sub_folder, name=name_prefix + '.')

        storage_filepath = uploader.path(filename)

        current_app.logger.warning('upload filename: %s, filepath: %s' %
                                   (filename, storage_filepath))

        # get info of upload image
        im = Image.open(storage_filepath)

        size = os.path.getsize(storage_filepath) / 1024  # k

        new_asset = Asset(master_uid=Master.master_uid(),
                          site_id=Site.master_site_id(current_user),
                          user_id=current_user.id,
                          filepath=filename,
                          filename=upload_name,
                          directory_id=directory_id,
                          width=im.width,
                          height=im.height,
                          size=size)
        db.session.add(new_asset)
        db.session.commit()

        saved_asset_ids.append(new_asset.id)

    return jsonify({'status': 200, 'ids': saved_asset_ids})
Пример #17
0
def new_upload():
    mode = 'create'
    form = UploadForm()

    if request.method == 'POST':
        saved_asset_ids = []
        sub_folder = str(time.strftime('%y%m%d'))
        #for key, file in request.files.iteritems():
        for f in request.files.getlist('file'):
            upload_name = f.filename
            # start to save
            name_prefix = 'admin' + str(time.time())
            name_prefix = hashlib.md5(
                name_prefix.encode('utf-8')).hexdigest()[:15]

            filename = uploader.save(f,
                                     folder=sub_folder,
                                     name=name_prefix + '.')

            storage_filepath = uploader.path(filename)

            current_app.logger.warning('upload filename: %s, filepath: %s' %
                                       (filename, storage_filepath))

            # get info of upload image
            im = Image.open(storage_filepath)

            size = os.path.getsize(storage_filepath) / 1024  # k

            new_asset = Asset(filepath=filename,
                              filename=upload_name,
                              width=im.width,
                              height=im.height,
                              size=size)
            db.session.add(new_asset)
            db.session.commit()

            saved_asset_ids.append(new_asset.id)

        return jsonify({'status': 200, 'ids': saved_asset_ids})

    return render_template('admin/uploads/new_upload.html',
                           form=form,
                           mode=mode)
Пример #18
0
    def test_asset_model(self):
        """
        Test number of records in asssets table
        """

        # create test department
        asset = Asset(comments="test comments for asset",
            inventory_id=Inventory.query.first().id,
            location=Location.query.first().id,
            managed_by=User.query.first().id,
            assigned_to=User.query.first().id,
            certified_by=User.query.first().id,
             )

        # save department to database
        db.session.add(asset)
        db.session.commit()

        self.assertEqual(Asset.query.count(), 1)
Пример #19
0
def add_asset_confirm(sitename):
    site = Site.query.filter_by(name=sitename).one()
    assets_json = request.get_json(force=True)
    # returns a dict with each 'value' being the data for one asset, so iterate through the values
    for asset_json in assets_json.values():
        asset_type = AssetType.query.filter_by(name=asset_json['type']).one()
        asset = Asset(name=asset_json['name'],
                      location=asset_json['location'],
                      group=asset_json['group'],
                      type=asset_type,
                      priority=asset_json['priority'],
                      notes=asset_json['notes'],
                      health=0,
                      site=site)
        db.session.add(asset)
    db.session.commit()
    # return true generates error 'bool is not callable', which has no impact
    # todo: return something that doesn't generate an error?
    return True
Пример #20
0
def get_with_featured_comments(asset_ids, no_of_comments=1):
    commented_assets = Comment.select(
        Comment.asset_id).where(Comment.asset_id << asset_ids).distinct()
    assets = Asset.select().order_by(
        Asset.created.desc()).where((Asset.id << asset_ids) & (
            (Asset.open_till > arrow.utcnow().datetime)
            | (Asset.id << commented_assets)))
    asset_ids = [asset.id for asset in assets]
    featured_comments = commentlib.get_featured_comments_for_assets(
        asset_ids, no_of_comments)

    return {
        'assets': [{
            'comments_count': asset.comments_count,
            'commenting_closed': asset.commenting_closed,
            'featured_comments': featured_comments.get(asset.id, []),
            **asset.to_dict()
        } for asset in assets]
    }
Пример #21
0
def create_or_replace(id,
                      url,
                      title,
                      publication,
                      moderation_policy,
                      open_till=None):
    asset = get_by_url(url)
    if asset:
        return asset.id

    if open_till is None:
        open_till = arrow.utcnow().shift(
            days=settings.DEFAULT_ASSET_OPEN_DURATION).datetime
    asset = Asset.create(id=id,
                         url=url,
                         title=title,
                         publication=publication,
                         open_till=open_till,
                         moderation_policy=moderation_policy)
    return asset.id
def add_asset(id):
    """
    Add a asset to the database
    """
    #check_admin

    add_asset = True

    form = AssetForm()
    if form.validate_on_submit():
        asset = Asset(
            name=form.name.data,
            description=form.description.data,
            analyse_id=id,
            sensitivity=form.sensitivity.data,
            criticality=form.criticality.data,
        )

        try:
            # add asset to the database
            db.session.add(asset)
            db.session.commit()
            flash('You have successfully added a new asset.')
        except:
            # in case asset name already exists
            flash('Error: asset name already exists.')

        # redirect to the assets page
        #return redirect(url_for('home.list_assets'))
        return redirect(url_for('home.edit_analyse', id=id))

    # load asset template
    w, h = 4, 4
    myscores = [[0 for x in range(w)] for y in range(h)]
    # analyse = Analyse.query.get_or_404(id)
    return render_template('home/assets/asset.html',
                           add_asset=add_asset,
                           myscores=myscores,
                           analyse_id=id,
                           form=form,
                           title='Add Asset')
Пример #23
0
def asset_add(assetinfo):
    try:
        for i in assetinfo:
            _asset = Asset(hostname_raw=i['hostname_raw'],
                           ip=i['ip'],
                           port=i['ip'],
                           vendor=i['vendor'],
                           model=i['model'],
                           cpu_model=i['cpu_model'],
                           cpu_count=i['cpu_count'],
                           cpu_cores=i['cpu_cores'],
                           memory=i['memory'],
                           platform=i['platform'],
                           os=i['os'],
                           os_version=i['os_version'],
                           os_arch=i['os_arch'])
            db.session.add(_asset)
        db.session.commit()
        return {"static": 0, "message": u"添加成功"}
    except Exception as e:
        return {"static": 1, "messsage": e}
Пример #24
0
def add_asset(sitename):

    # TODO: search by site name will not work if not unique site names
    site = Site.query.filter_by(name=sitename).one()
    asset_types = AssetType.query.all()
    form = AddAssetForm()

    # render the page
    if request.method == 'GET':
        return render_template('add_asset.html',
                               site=site,
                               asset_types=asset_types,
                               form=form)

    # process a submitted form
    elif request.method == 'POST':
        # if form has errors, return the page (errors will display)
        if not form.validate_on_submit():
            # clear type value. the user needs to manually select this on the page to trigger some javascript
            form.type.data = ""
            return render_template('add_asset.html',
                                   site=site,
                                   asset_types=asset_types,
                                   form=form)

        # create asset with 0 health based on form data
        asset_type = AssetType.query.filter_by(name=form.type.data).one()
        asset = Asset(type=asset_type,
                      name=form.name.data,
                      location=form.location.data,
                      group=form.group.data,
                      priority=form.priority.data,
                      notes=form.notes.data,
                      site=site,
                      health=0)
        db.session.add(asset)
        db.session.commit()

        # points/descriptors/algorithms don't use WTForms since they are dynamically generated by javascript
        # so we must extract them from request.form directly

        # generate points
        # to match up new points and their corresponding logs in the form, the data comes in as two fields
        # 'pointX':'point_name' and 'logX':'log_path' where X is an iterator
        # here we iterate throught X=1-100 and see if we can find matching pairs
        # making the asssumption that there are always less than 100 points on an asset
        # TODO: need a better system of reading in values than string-matching point1 and log1
        for i in range(1, 100):
            # find if there is a point for that value of i
            point_type_name = request.form.get('point' + str(i))
            if not point_type_name is None:
                # create the point
                point_type = PointType.query.filter_by(
                    name=point_type_name).one()
                point = AssetPoint(type=point_type,
                                   name=point_type_name,
                                   asset=asset)

                # find the corresponding log path for that value of i
                log_path = request.form.get('log' + str(i))
                if not log_path == '':  # and not session is None:
                    # pull the id of that log from the remote webreports database and assign it to the point
                    log = session.query(LoggedEntity).filter_by(
                        path=log_path).one()
                    point.loggedentity_id = log.id

        # set functional descriptors
        # each descriptor comes through as a field with name 'function' and value '<the descriptor name>'
        # use getlist to get all the values with this name in a single list
        function_list = request.form.getlist('function')
        for function_name in function_list:
            # create the descriptor
            print(function_name)
            if function_name != None and function_name != "":
                function = FunctionalDescriptor.query.filter_by(
                    name=function_name).one()
                asset.functions.append(function)

        # set excluded algorithms
        # the database operates via excluding algorithms
        # however the form only sends through algorithms that are ticked (i.e. included)
        # therefore subtract the inclusions from the total set of algorithms to get the exclusions
        try:
            inclusions = []
            included_list = request.form.getlist('algorithm')
            for algorithm_descr in included_list:
                inclusions.append(
                    Algorithm.query.filter_by(descr=algorithm_descr).one())
                exclusions = set(Algorithm.query.all()) - set(inclusions)
                asset.exclusions.extend(exclusions)
        except:
            app.logger.error('add asset failed to set associated algorithms')

        db.session.commit()

        return redirect(url_for('asset_list', sitename=sitename))
Пример #25
0
def get_all(ids):
    assets = Asset.select().where(Asset.id << ids)
    return [asset.to_dict() for asset in assets]
Пример #26
0
def seed_entities():
    """Seed assets needed for Demo Tale."""

    # assets
    asset1 = Asset(
        user_id=1,
        category="item",
        title="Red Key",
        description=
        "A tiny red key found in the blue room. It probably unlocks red doors, because why not?",
        color="#e05265ff",
        icon="key",
        value=100,
    )
    asset2 = Asset(
        user_id=1,
        category="item",
        title="Candy",
        description=
        "Colorful pieces of candy wrapped in crinkly celophane. They look delicious.",
        color="#964a70ff",
        icon="candy-cane",
        value=0.25,
    )
    asset3 = Asset(
        user_id=1,
        category="deed",
        title="Took Candy",
        color="#964a70ff",
        description="A candy has been taken.",
        icon="hand-sparkles",
    )
    asset4 = Asset(
        user_id=1,
        category="item",
        title="Ball",
        description="A ball from the Sweet Fairy.",
        color="#8cb15eff",
        icon="baseball-ball",
        value=10,
    )
    asset5 = Asset(
        user_id=1,
        category="currency",
        title="Gold",
        description="The currency of the world of Demolandia.",
        color="#f0bc62ff",
        icon="coins",
        image="close-up-coin-textures.jpg",
        value=1,
    )

    # places
    place1 = Entity(
        user_id=1,
        type="place",
        title="The Beginning",
        description=
        "There is a red door on the left and a blue door on the right",
        icon="dungeon",
        image="vintage-binocular-lens.jpg")

    place2 = Entity(
        user_id=1,
        type="place",
        title="The Red Room",
        description=
        "The room is very red, and there is another red door on the far wall. There is a table with a vase of flowers and a pile of candy.",
        color="#e05265ff",
        icon="door-closed",
    )

    place3 = Entity(
        user_id=1,
        type="place",
        title="The Blue Room",
        description=
        "The room is very blue, and there is another blue door on the far wall. There is a table with a red key on it.",
        color="#5a70ccff",
        icon="door-open",
    )

    place4 = Entity(
        user_id=1,
        type="place",
        title="The Joined Room",
        description=
        "Looking back, there is a red and blue door. An angry fairy is in the corner of the room.",
        color="#4f4686ff",
        icon="door-open",
        image="vintage-binocular-lens.jpg",
    )

    # characters
    character1 = Entity(
        user_id=1,
        type="character",
        category="fairy",
        title="Sweet Fairy",
        description="A young fairy with a sweet tooth",
        color="#885c58ff",
        icon="user-circle",
        image=
        "https://i.vippng.com/png/small/320-3207217_vintage-fairy-pngs-daisy-fairy-cicely-mary-barker.png",
    )

    # statuses
    status1 = Status(
        user_id=1,
        category="mood",
        title="Angry",
        description="An angry mood",
        color="#e05265ff",
        icon="angry",
    )
    status2 = Status(
        user_id=1,
        category="mood",
        title="Happy",
        description="A happy mood",
        color="#f0bc62ff",
        icon="grin",
    )
    # TODO Figure out how to add assets/etc. to entities via join table

    # ba1 = BearerAsset(
    #     bearer=character1,
    #     asset=asset4,
    #     )
    # ba2 = BearerAsset(
    #     bearer=character1,
    #     asset=condition1,
    #     )

    meter1 = Meter(
        user_id=1,
        title="Popularity",
        description="This indicates how well people like you.",
        color="#f0bc62ff",
        icon="users",
        image=
        "https://previews.123rf.com/images/torky/torky1112/torky111200013/11377065-vintage-heart-of-roses.jpg",
        min=0,
        max=10,
        base=100,
        mod=10,
    )
    meter2 = Meter(
        user_id=1,
        title="Perception",
        description=
        "How sharp is your senses? Can you notice when something seems off around you?",
        color="#1b9d8eff",
        icon="eye",
        min=0,
        max=20,
        base=10,
        mod=1,
    )
    meter3 = Meter(
        user_id=1,
        title="Killing Arts",
        description=
        "Do you have what it takes to become America's most deadly assassin?",
        color="#1b9d8eff",
        icon="wrench",
        min=0,
        max=50,
        base=10,
        mod=2,
    )
    meter4 = Meter(
        user_id=1,
        title="Gardening",
        description="How green is your thumb?",
        color="#1b9d8eff",
        icon="seedling",
        min=0,
        max=10,
        base=1000,
        mod=5,
    )
    # em1 = EntityMeter(
    #   entity=character1,
    #   meter=meter1,
    #   progress=50,
    # )

    db.session.add(asset1)
    db.session.add(asset2)
    db.session.add(asset3)
    db.session.add(asset4)
    db.session.add(place1)
    db.session.add(place2)
    db.session.add(place3)
    db.session.add(place4)
    db.session.add(character1)
    db.session.add(status1)
    db.session.add(status2)
    db.session.add(meter1)
    db.session.add(meter2)
    db.session.add(meter3)
    db.session.add(meter4)
    db.session.commit()
Пример #27
0
def get_by_url(url):
    return Asset.get_or_none(Asset.url == url)
Пример #28
0
def regenerate():

    # ensure session is closed
    db.session.close()

    # regenerate all tables in the database, based on models
    db.drop_all()
    db.create_all()

    # add some initial data
    for sitename in site_names:
        site = Site(name=sitename)
        site.inbuildings_config = InbuildingsConfig(enabled=False, key="")
        db.session.add(site)

    for typename in asset_types:
        asset_type = AssetType(name=typename)
        db.session.add(asset_type)

    for pointname in point_types:
        point_type = PointType(name=pointname)
        db.session.add(point_type)

    site = Site.query.filter_by(name=site_names[0]).one()
    asset_type = AssetType.query.filter_by(name=asset_types[0]).one()
    asset = Asset(name=test_asset_name,
                  site=site,
                  type=asset_type,
                  health=0,
                  priority=1,
                  notes='')

    # add one of each point type to dummy unit
    for pointtype in point_types:
        point = PointType.query.filter_by(name=pointtype).one()
        asset_point = AssetPoint(name=pointtype, type=point, asset=asset)
        asset.points.append(asset_point)

    # add and commit to db
    db.session.add(asset)
    db.session.commit()

    # map assets to algorithms
    map_all()

    # generate users
    admin = User(username=admin_user,
                 password=user_manager.hash_password(admin_pw),
                 active=True)
    test = User(username=test_user,
                password=user_manager.hash_password(test_pw),
                active=True)
    db.session.add(admin)
    db.session.add(test)

    # generate roles
    for role_name in roles:
        role = Role(name=role_name, label=role_name)
        admin.roles.append(role)

    db.session.commit()
    db.session.close()
Пример #29
0
def stop_all():
    open_till = arrow.utcnow().datetime
    Asset.update({
        'open_till': open_till
    }).where(Asset.open_till > open_till).execute()
Пример #30
0
def get_open_assets():
    open_assets = Asset.select(
        Asset.url).where(Asset.open_till > arrow.utcnow().datetime).tuples()
    open_assets = [asset_url for asset_url, in open_assets]
    return {'count': len(open_assets), 'open_assets': open_assets}