Ejemplo n.º 1
0
def handle_equipments():
    if request.method == 'GET':
        return jsonify(Equipment.getAllSerialized()), 200
    if request.method == 'POST':
        body = request.get_json()
        newEquipment = Equipment.newInstance(body)
        newEquipment.addCommit()
        return toJson(newEquipment), 201
Ejemplo n.º 2
0
def testGivePlayerEquipment(player_key_string):
    player = ndb.Key(urlsafe=player_key_string).get()
    player.equipment.append(
        Equipment(
            equipment_type=1,
            armor_data=Armor(armor_type=0,
                             damage_reduction=0.6,
                             durability=400),
        ).put())
    player.equipment.append(
        Equipment(
            equipment_type=0,
            weapon_data=Weapon(weapon_type=0, power=20, reliability=0.995),
        ).put())
    player.put()
Ejemplo n.º 3
0
def add():
    admin = request.form.get('admin')
    location = request.form.get('location')
    status = request.form.get('status')
    gaode_latitude = request.form.get('gaode_latitude')
    gaode_longitude = request.form.get('gaode_longitude')
    admin = Admin_people.query.filter(Admin_people.name == admin).first()
    print(status)
    if not admin or admin.role_id != 3:
        return jsonify({'msg': 'fail', 'error': '管理员不存在!'})
    data = {
        'location': location,
        'status': status,
        'gaode_longitude': gaode_longitude,
        'gaode_latitude': gaode_latitude,
        'admin_id': admin.id,
    }
    try:
        e = Equipment(**data)
        db.session.add(e)
        db.session.commit()
        return jsonify({'msg': 'success'})
    except Exception as e:
        print(e)
        return jsonify({'msg': 'fail', 'error': '添加失败!'})
Ejemplo n.º 4
0
def list_site_availability(camp_area, start_date, end_date, equipment_type):
    """
    Retrieve the Availability for all Sites in a Camp Area which can host the selected Equipment within a date range
    :param camp_area:
    :param start_date:
    :param end_date:
    :param equipment_type:
    :return:
    """
    data = {
       'mapId':camp_area.map_id,
       'bookingCategoryId':0,
       'startDate':start_date.isoformat(),
       'endDate':end_date.isoformat(),
       'isReserving':True,
       'getDailyAvailability':True,
       'partySize':1,
       'equipmentId':equipment_type,
       'subEquipmentId':equipment_type,
       'generateBreadcrumbs':False,
    }
    results = post_json('MAPDATA', data)
    sites_availability = {}
    for entry in results['resourcesOnMap']:
        site = Site(entry['resourceId'], entry['localizedValues'][0]['name'],entry['localizedValues'][0]['description'])
        allowed_equipment = [Equipment(e['item1'],e['item2'], None) for e in entry['allowedEquipment']]
        availability = [
            SiteAvailability(site, e['availability'], allowed_equipment)
            for e in results['resourceAvailabilityMap'][str(site.resource_id)]
        ]
        sites_availability[site] = availability
    return OrderedDict(sorted(sites_availability.items(), key=lambda sa: sa[0].name.zfill(3)))
Ejemplo n.º 5
0
def start_edit_equipment(call):
    if not is_person(call.message.chat):
        return
    try:
        user = User.get(telegram_id=call.message.chat.id)
        if user not in User.select(User).join(Links).join(Group).where(Group.group_name == 'Inventarization'):
            raise Exception("Unauthorized user")
    except Exception:
        logger.info(
            f'User {user.first_name} {user.last_name} tried to use inventarization functions, but this user is not in Inventarization group!')
        bot.send_message(text='У Вас нет доступа к этой функции', chat_id=call.message.chat.id)
        return
    equipment = Equipment.get(id=int(call.data.split('-')[1]))
    field_name = call.data.split('/')[1].split('-')[0]
    if field_name == 'type':
        bot.edit_message_text(chat_id=user.telegram_id,
                              message_id=call.message.message_id,
                              text='Введите новое наименование типа')
        User.update(status=f'edit-type_{equipment.id}').where(User.id == user.id).execute()
    elif field_name == 'mark':
        bot.edit_message_text(chat_id=user.telegram_id,
                              message_id=call.message.message_id,
                              text='Введите новое наименование марки')
        User.update(status=f'edit-mark_{equipment.id}').where(User.id == user.id).execute()
    elif field_name == 'model':
        bot.edit_message_text(chat_id=user.telegram_id,
                              message_id=call.message.message_id,
                              text='Введите новое наименование модели')
        User.update(status=f'edit-model_{equipment.id}').where(User.id == user.id).execute()
    elif field_name == 'serial':
        bot.edit_message_text(chat_id=user.telegram_id,
                              message_id=call.message.message_id,
                              text='Введите новый серийный номер')
        User.update(status=f'edit-serial_{equipment.id}').where(User.id == user.id).execute()
Ejemplo n.º 6
0
    def test_user_profile(self):
        self.assertEqual(str(self.user.userprofile), self.user.username)
        self.assertEqual(0, self.user.userprofile.points)
        self.assertIsNotNone(self.user.userprofile.observer)
        self.assertIsNotNone(self.user.userprofile.sunset)

        Equipment(instrument="test equipment", user_profile=self.user.userprofile).save()
        self.assertEqual(1, len(self.user.userprofile.equipment_set.all()))
Ejemplo n.º 7
0
def list_equipments():
    """
    Retrieve all known Equipment
    :return:
    """
    equipments = []
    equipment_all = sorted(get_json('LIST_EQUIPMENT'), key=lambda e: e['order'])
    for category in equipment_all:
        equipment = category['subEquipmentCategories']
        equipments.extend([Equipment(category['equipmentCategoryId'],e['subEquipmentCategoryId'],e['localizedValues'][0]['name']) for e in equipment])
    return equipments
Ejemplo n.º 8
0
    def setUp(self):
        """create test client, add sample data"""
        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        self.testuser = User.signup(email='*****@*****.**', password="******",
                                    username='******', first_name='Test', last_name='User', image_url=User.image_url.default.arg, cover_url=User.cover_url.default.arg)
        self.testuser_id = 1234
        self.testuser.id = self.testuser_id

        db.session.commit()
        p1 = Post(id=5678, title='testpost1', details='this is a test post',
                  is_private=False, user_id=self.testuser_id, timestamp=None)

        db.session.add(p1)
        db.session.commit()

        p1 = Post.query.get(5678)
        self.testuser.likes.append(p1)
        self.testuser_likes = self.testuser.likes
        db.session.commit()
        self.p1 = p1
        self.p1_id = self.p1.id
        db.session.commit()

        biceps = Muscle(name='biceps', body_part='arms')
        triceps = Muscle(name='triceps', body_part='arms')
        deltoids = Muscle(name='deltoids', body_part='shoulders')

        db.session.add_all([biceps, triceps, deltoids])
        db.session.commit()

        barbell = Equipment(name='barbell')
        kettlebell = Equipment(name='kettlebell')
        dumbbells = Equipment(name='dumbbells')

        db.session.add_all([barbell, kettlebell, dumbbells])
        db.session.commit()
Ejemplo n.º 9
0
def new_gauge():
    """
    Add a new Equipment
    """
    form = gEquipmentForm(request.form)

    if request.method == 'POST' and form.validate():
        # save the album
        equipment = Equipment()
        his = History()
        gsave_changes(his, equipment, form, new=True)
        flash('Equipment added successfully!')
        return redirect('/')
    print(form.make)
    return render_template('new_gauge.html', form=form)
Ejemplo n.º 10
0
def new_instrument():
    """
    Add a new Equipment
    """
    form = iEquipmentForm(request.form)

    if request.method == 'POST' and form.validate():
        # save the album
        equipment = Equipment()
        his = History()
        isave_changes(his, equipment, form, new=True)
        flash('Equipment added successfully!')
        flash('Itemcode is ' + equipment.itemcode)
        return redirect('/')

    return render_template('new_instrument.html', form=form)
Ejemplo n.º 11
0
def start_moving_equipment(call):
    if not is_person(call.message.chat):
        return
    try:
        user = User.get(telegram_id=call.message.chat.id)
        if user not in User.select(User).join(Links).join(Group).where(Group.group_name == 'Inventarization'):
            raise Exception("Unauthorized user")
    except Exception:
        logger.info(
            f'User {user.first_name} {user.last_name} tried to use inventarization functions, but this user is not in Inventarization group!')
        bot.send_message(text='У Вас нет доступа к этой функции', chat_id=call.message.chat.id)
        return
    equipment = Equipment.get(id=int(call.data.split('-')[1]))
    bot.send_message(chat_id=user.telegram_id,
                     text='Выберите корпус для перемещения',
                     reply_markup=get_kurpus_keyboard_for_create_movement(equipment))
Ejemplo n.º 12
0
def eq_add(request):
    result = {"state": "error", "data": ""}
    if request.method == "POST":
        data = request.POST
        ip = data.get("ip")
        port = data.get("port")
        user = data.get("username")
        password = data.get("password")
        if ip and port and user and password:
            eq = Equipment()
            eq.IP = ip
            eq.User = user
            eq.Password = password
            try:
                trans = paramiko.Transport(ip, port)
                trans.connect(username=user, password=password)
                sftp = paramiko.SFTPClient.from_transport(trans)
                ssh = paramiko.SSHClient()
                ssh._transport = trans
                stdin, stdout, stderr = ssh.exec_command("mkdir CMDBClient")
                sftp.put("sftpDir/getData.py", "/root/CMDBClient/getData.py")
                sftp.put("sftpDir/sendData.py", "/root/CMDBClient/sendData.py")
                sftp.put("sftpDir/main.py", "/root/CMDBClient/main.py")
                stdin, stdout, stderr = ssh.exec_command(
                    "python /root/CMDBClient/main.py")
                trans.close()
                result["state"] = "success"
                result["data"] = "操作成功!"
                eq.Statue = "True"
            except Exception as e:
                eq.Statue = "False"
                result["data"] = "远程连接错误:%s" % e
            finally:
                eq.save()
        else:
            result["data"] = "IP、port、user、password不能为空,请检查"
    else:
        result["data"] = "请求错误,请刷新重试"
    return JsonResponse(result)
Ejemplo n.º 13
0
def start_edit_equipment(call):
    if not is_person(call.message.chat):
        return
    try:
        user = User.get(telegram_id=call.message.chat.id)
        if user not in User.select(User).join(Links).join(Group).where(Group.group_name == 'Inventarization'):
            raise Exception("Unauthorized user")
    except Exception:
        logger.info(
            f'User {user.first_name} {user.last_name} tried to use inventarization functions, but this user is not in Inventarization group!')
        bot.send_message(text='У Вас нет доступа к этой функции', chat_id=call.message.chat.id)
        return
    equipment = Equipment.get(id=int(call.data.split('-')[1]))
    bot.send_message(chat_id=user.telegram_id,
                     text='Выберите параметр для редактирования',
                     reply_markup=get_edit_equipment_keyboard(equipment))
    User.update(status='choose parameter for edit').where(User.id == user.id).execute()
Ejemplo n.º 14
0
def start_moving_equipment(call):
    if not is_person(call.message.chat):
        return
    try:
        user = User.get(telegram_id=call.message.chat.id)
        if user not in User.select(User).join(Links).join(Group).where(Group.group_name == 'Inventarization'):
            raise Exception("Unauthorized user")
    except Exception:
        logger.info(
            f'User {user.first_name} {user.last_name} tried to use inventarization functions, but this user is not in Inventarization group!')
        bot.send_message(text='У Вас нет доступа к этой функции', chat_id=call.message.chat.id)
        return
    campus = call.data.split('-')[1].split('UK')[1]
    equipment = Equipment.get(id=int(call.data.split('-')[2]))
    bot.edit_message_text(message_id=call.message.message_id,
                          chat_id=user.telegram_id,
                          text='Введите кабинет для перемещения')
    User.update(status=f'create_movement/UK-{campus}/id-{equipment.id}').where(User.id == user.id).execute()
async def api_create_equipment(request, *, name, model, asset_number,
                               acessories, warehouse, scrapped):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'name cannot be empty.')
    if not model or not model.strip():
        raise APIValueError('model', 'model cannot be empty.')
    if not asset_number or not asset_number.strip():
        raise APIValueError('asset_number', 'asset_number cannot be empty.')
    equipment = Equipment(name=name.strip(),
                          model=model.strip(),
                          asset_number=asset_number.strip(),
                          acessories=acessories.strip(),
                          warehouse=warehouse.strip(),
                          scrapped=scrapped.strip(),
                          user_id='',
                          user_name='',
                          user_image='')
    await equipment.save()
    return equipment
Ejemplo n.º 16
0
def add_data(scope):
    from models import Admin,Owner,THistory,HHistory,Equipment
    # 创建表
    db = scope['db']

    admin = Admin('sjw','123')
    db.session.add(admin)
    db.session.commit()

    owner = Owner('李强','123')
    db.session.add(owner)
    db.session.commit()

    owner2 = Owner('王建林','123')
    db.session.add(owner2)
    db.session.commit()

    eqp_name = '设备2'
    eqp_uuid = getUuid()
    print(eqp_uuid)
    eqp = Equipment(_id=eqp_uuid,name=eqp_name,max_t=40,min_t=0,max_h=50,min_h=10,owner_id=owner.id,create_date=None)
    db.session.add(eqp)
    db.session.commit()
Ejemplo n.º 17
0
def craftEquipment(inputs):
    """ @param inputs a json object with inputs."""
    # TODO: Break up this code into functional pieces.
    # TODO: Validate inputs.
    # TODO: Think hard about redesigning the crafting logic.
    equipment_template_key = inputs['equipment_template_key']
    # Make sure the player has all of the necessary resources.
    cost_to_craft = EQUIPMENT_TEMPLATE_CRAFT_COSTS[equipment_template_key]
    player_key = ndb.Key(urlsafe=inputs['player_id'])  # TODO: error handle.
    player = player_key.get()
    resources_to_put = []
    formula_input = {}
    # TODO: Make this more generic, instead of checking each. DRY this up.
    if cost_to_craft.metal > 0:
        # Check for adequate metal resources.
        if 'metal_resource_key' not in inputs:
            logging.error('metal_resource_key missing from input!')
            # TODO: handle failure better than returning none.
            return None
        resource_key = ndb.Key(urlsafe=inputs['metal_resource_key'])
        if resource_key in player.resources:
            resource = resource_key.get()
            template = resource.resource_template.get()
            if (resource.quantity >= cost_to_craft.metal
                    and template.resource_type
                    == RESOURCE_TYPES_INT_MAPPING[METAL_KEY]):
                resource.quantity -= cost_to_craft.metal
                resources_to_put.append(resource)
                formula_input[METAL_KEY] = template
                # TODO: Add crafting power formulas logic here!
            else:
                logging.error(
                    'Metal Quantity too low, or resource is not metal!')
                # TODO: handle failure better than returning none.
                return None
        else:
            logging.error('Player does not own metal resource!')
            # TODO: handle failure better than returning none.
            return None
    if cost_to_craft.wood > 0:
        # Check for adequate wood resources.
        if 'wood_resource_key' not in inputs:
            logging.error('wood_resource_key missing from input!')
            # TODO: handle failure better than returning none.
            return None
        resource_key = ndb.Key(urlsafe=inputs['wood_resource_key'])
        if resource_key in player.resources:
            resource = resource_key.get()
            template = resource.resource_template.get()
            if (resource.quantity >= cost_to_craft.wood
                    and template.resource_type
                    == RESOURCE_TYPES_INT_MAPPING[WOOD_KEY]):
                resource.quantity -= cost_to_craft.wood
                resources_to_put.append(resource)
                formula_input[WOOD_KEY] = template
                # TODO: Add crafting power formulas logic here!
            else:
                logging.error(
                    'Wood Quantity too low, or resource is not wood!')
                # TODO: handle failure better than returning none.
                return None
        else:
            logging.error('Player does not own wood resource!')
            # TODO: handle failure better than returning none.
            return None
    if cost_to_craft.leather > 0:
        # Check for adequate leather resources.
        if 'leather_resource_key' not in inputs:
            logging.error('leather_resource_key missing from input!')
            # TODO: handle failure better than returning none.
            return None
        resource_key = ndb.Key(urlsafe=inputs['leather_resource_key'])
        if resource_key in player.resources:
            resource = resource_key.get()
            template = resource.resource_template.get()
            if (resource.quantity >= cost_to_craft.leather
                    and template.resource_type
                    == RESOURCE_TYPES_INT_MAPPING[LEATHER_KEY]):
                resource.quantity -= cost_to_craft.leather
                resources_to_put.append(resource)
                formula_input[LEATHER_KEY] = template
                # TODO: Add crafting power formulas logic here!
            else:
                logging.error(
                    'Leather Quantity too low, or resource is not leather!')
                # TODO: handle failure better than returning none.
                return None
        else:
            logging.error('Player does not own leather resource!')
            # TODO: handle failure better than returning none.
            return None

    # Validation has passed. Create the equipment.
    equipment_type = EQUIPMENT_TEMPLATE_TO_TYPE_MAPPING[equipment_template_key]
    crafted_equipment = Equipment(equipment_type=equipment_type,
                                  player=player_key)

    if equipment_type == EQUIPMENT_TYPE_INT_MAPPING[WEAPON_KEY]:
        crafted_equipment.weapon_data = Weapon(
            weapon_type=WEAPON_TYPE_INT_MAPPING[equipment_template_key],
            power=int(
                getAttributeValue(
                    formula_input,
                    WEAPON_POWER_FORMULA[equipment_template_key])),
            reliability=getAttributeValue(
                formula_input,
                WEAPON_RELIABILITY_FORMULA[equipment_template_key]))
        player.equipment.append(crafted_equipment.put())
        player.put()

    # TODO: Handle armor crafting.

    # Crafting complete. Now update the resources.
    ndb.put_multi(resources_to_put)
Ejemplo n.º 18
0
def google_update(message: Message):
    if not is_person(message.chat):
        return
    try:
        user = User.get(telegram_id=message.chat.id)
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Admins'):
            raise Exception("Unauthorized user")
    except Exception:
        bot.send_message(text=get_unauthorized_user_start_message(),
                         chat_id=message.chat.id)
        return
    cur_equipments = Equipment.select()
    cur_movement = Movement.select()
    gs = GoogleSync()
    equipments_from_google = gs.read_range(
        list_name='Список оборудования',
        range_in_list=f'A{cur_equipments.count() + 2}:G')
    movements_from_google = gs.read_range(
        list_name='Перемещение оборудования',
        range_in_list=f'A{cur_movement.count() + 2}:C')
    if equipments_from_google is not None:
        if len(equipments_from_google) > 0:
            for item in equipments_from_google:
                if len(item) < 7:
                    for j in range(len(item), 7):
                        item.append('')
                Equipment.create(it_id=item[0],
                                 pos_in_buh=item[1],
                                 invent_num=item[2],
                                 type=item[3],
                                 mark=item[4],
                                 model=item[5],
                                 serial_num=item[6])
    if movements_from_google is not None:
        if len(movements_from_google) > 0:
            for item in movements_from_google:
                if len(item) < 7:
                    for j in range(len(item), 7):
                        item.append('')
                if item[0] == '':
                    continue
                Movement.create(equipment=Equipment.get(it_id=item[0]),
                                campus=item[1],
                                room=item[2])
    # cur_persons_count = Person.select().count()
    # gs_phones = GoogleSync(spreadsheet_id=PHONE_SPREADSHEET_ID)
    # persons_from_google = gs_phones.read_range(list_name='List1',
    #                                            range_in_list=f'A{cur_persons_count + 2}:F')
    # for person in persons_from_google:
    #     if len(person) < 6:
    #         for j in range(len(person), 6):
    #             person.append('')
    #     Person.get_or_create(name=person[1],
    #                          surname=person[0],
    #                          patronymic=person[2],
    #                          defaults={
    #                              'position': person[3],
    #                              'phone': f'+{person[4]}',
    #                              'email': person[5],
    #                              'photo': '',
    #                              'actual': 'True'
    #                          })
    bot.send_message(chat_id=user.telegram_id, text='Данные получены')
Ejemplo n.º 19
0
from models import Data, DataInfo, Equipment
import time
import datetime
import sqlalchemy
import sqlalchemy.orm
from sqlalchemy import *
from sqlalchemy.orm import *
from create_db import connect_to_db

engine = connect_to_db()
Session = sessionmaker(bind=engine)
session = Session()

e = Equipment(name='Hertz Meter',
              location='Power Plant',
              info='This is a sensor that performs frequency readings')

di = DataInfo(equipment_id=1,
              name='frequency',
              unit='Hz',
              longunit='Hertz',
              mType='sensor')

session.add_all([e, di])

with open('dummydata.txt') as f:
    content = f.readlines()

for line in content:
    tup = line.split()
Ejemplo n.º 20
0
def plain_text(message: Message):
    if not is_person(message.chat):
        return
    try:
        user = User.get(telegram_id=message.chat.id)
        if user in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Unauthorized'):
            raise Exception("Unauthorized user")
    except Exception:
        bot.send_message(text=get_unauthorized_user_start_message(),
                         chat_id=message.chat.id)
        return

    if user.status == 'Adding group':
        if user in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Admins'):
            group, created = Group.get_or_create(group_name=message.text)
            bot.send_message(chat_id=message.chat.id, text='Группа добавлена')
            groups = Group.select()
            return_str = 'Список групп:\n'
            for group in groups:
                return_str += group.group_name + '\n'
            bot.send_message(text=return_str, chat_id=message.chat.id)
            logger.info(
                f'Admin {user.first_name} {user.last_name} add new group - {message.text}'
            )

    elif user.status == 'zavhoz_check_equipment':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Zavhoz'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            looking_invent_num = message.text
            try:
                Equipment.get(invent_num=looking_invent_num)
            except Exception as e:
                logger.info(
                    f'User {user.first_name} {user.last_name} looking for unexisting equipment with {looking_invent_num} invent number'
                )
                bot.send_message(
                    chat_id=user.telegram_id,
                    text=
                    f'Оборудование с инвентарным номером {looking_invent_num} не стоит на балансе'
                )
                User.update(status='').where(User.id == user.id).execute()
                return
            found_equipments = Equipment.select().where(
                Equipment.invent_num == looking_invent_num)
            for item in found_equipments:
                bot.send_message(chat_id=user.telegram_id,
                                 text=equipment_info(equipment=item))
            logger.info(
                f'User {user.first_name} {user.last_name} looked info about {looking_invent_num} invent number'
            )

    elif user.status == 'invent_search':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            invent_num = message.text
            found_equipments = Equipment.select().where(
                Equipment.invent_num == invent_num)
            if found_equipments.count() == 0:
                bot.send_message(
                    chat_id=user.telegram_id,
                    text=
                    f'Оборудование с инвентарным номером {invent_num} не стоит на балансе'
                )
            else:
                for equipment in found_equipments:
                    bot.send_message(
                        chat_id=user.telegram_id,
                        text=equipment_info(equipment),
                        reply_markup=get_equipment_reply_markup(equipment))

    elif user.status == 'serial_search':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            serial_num = message.text
            found_equipments = Equipment.select().where(
                Equipment.serial_num == serial_num)
            if found_equipments.count() == 0:
                bot.send_message(
                    chat_id=user.telegram_id,
                    text=
                    f'Оборудование с серийным номером {serial_num} не стоит на балансе'
                )
            else:
                for equipment in found_equipments:
                    bot.send_message(
                        chat_id=user.telegram_id,
                        text=equipment_info(equipment),
                        reply_markup=get_equipment_reply_markup(equipment))

    elif user.status.split('_')[0] == 'edit-type':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            equipment = Equipment.get(id=user.status.split('_')[1])
            Equipment.update(type=message.text).where(
                Equipment.id == equipment.id).execute()
            equipment = Equipment.get(id=user.status.split('_')[1])
            bot.send_message(
                chat_id=user.telegram_id,
                text=equipment_info(equipment),
                reply_markup=get_equipment_reply_markup(equipment))
            send_equipment_info_to_google_sheet(equipment)
            logger.info(
                f'User {user.first_name} {user.last_name} edit equipment ID {equipment.it_id}: new type is {equipment.type}'
            )
    elif user.status.split('_')[0] == 'edit-mark':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            equipment = Equipment.get(id=user.status.split('_')[1])
            Equipment.update(mark=message.text).where(
                Equipment.id == equipment.id).execute()
            equipment = Equipment.get(id=user.status.split('_')[1])
            bot.send_message(
                chat_id=user.telegram_id,
                text=equipment_info(equipment),
                reply_markup=get_equipment_reply_markup(equipment))
            send_equipment_info_to_google_sheet(equipment)
            logger.info(
                f'User {user.first_name} {user.last_name} edit equipment ID {equipment.it_id}: new mark is {equipment.mark}'
            )
    elif user.status.split('_')[0] == 'edit-model':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            equipment = Equipment.get(id=user.status.split('_')[1])
            Equipment.update(model=message.text).where(
                Equipment.id == equipment.id).execute()
            equipment = Equipment.get(id=user.status.split('_')[1])
            bot.send_message(
                chat_id=user.telegram_id,
                text=equipment_info(equipment),
                reply_markup=get_equipment_reply_markup(equipment))
            send_equipment_info_to_google_sheet(equipment)
            logger.info(
                f'User {user.first_name} {user.last_name} edit equipment ID {equipment.it_id}: new model is {equipment.model}'
            )
    elif user.status.split('_')[0] == 'edit-serial':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            equipment = Equipment.get(id=user.status.split('_')[1])
            Equipment.update(serial_num=message.text).where(
                Equipment.id == equipment.id).execute()
            equipment = Equipment.get(id=user.status.split('_')[1])
            bot.send_message(
                chat_id=user.telegram_id,
                text=equipment_info(equipment),
                reply_markup=get_equipment_reply_markup(equipment))
            send_equipment_info_to_google_sheet(equipment)
            logger.info(
                f'User {user.first_name} {user.last_name} edit equipment ID {equipment.it_id}: new serial num is {equipment.serial_num}'
            )
    elif user.status.split('/')[0] == 'create_movement':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'Inventarization'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            campus = user.status.split('/')[1].split('-')[1]
            room = message.text
            equipment = Equipment.get(
                id=user.status.split('/')[2].split('-')[1])
            movement = Movement.create(
                equipment=equipment,
                campus=f'УК {campus}'
                if not campus == 'spisanie' else 'Списание',
                room=room)
            equipment = Equipment.get(
                id=user.status.split('/')[2].split('-')[1])
            bot.send_message(
                chat_id=user.telegram_id,
                text=equipment_info(equipment),
                reply_markup=get_equipment_reply_markup(equipment))
            send_movement_to_google_sheet(equipment, movement)
            logger.info(
                f'User {user.first_name} {user.last_name} move equipment ID {equipment.it_id}: new location is {movement.campus} {movement.room}'
            )
    elif user.status.split(':')[0] == 'Edit_person_info':
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'PhonesAdmin'):
            bot.send_message(chat_id=user.telegram_id,
                             text='У Вас нет доступа к этой функции')
            logger.info(
                f'User {user.first_name} {user.last_name} had unsupported status!'
            )
        else:
            edit_parameter = user.status.split(':')[1].split('_')[0]
            person = Person.get(id=user.status.split(':')[1].split('_')[1])
            if edit_parameter == 'surname':
                Person.update(surname=message.text).where(
                    Person.id == person.id).execute()
            elif edit_parameter == 'name':
                Person.update(name=message.text).where(
                    Person.id == person.id).execute()
            elif edit_parameter == 'patronymic':
                Person.update(patronymic=message.text).where(
                    Person.id == person.id).execute()
            elif edit_parameter == 'phone':
                Person.update(phone=message.text).where(
                    Person.id == person.id).execute()
            elif edit_parameter == 'position':
                Person.update(position=message.text).where(
                    Person.id == person.id).execute()
            elif edit_parameter == 'email':
                Person.update(email=message.text).where(
                    Person.id == person.id).execute()
            elif edit_parameter == 'photo':
                bot.send_message(
                    chat_id=message.chat.id,
                    text=
                    'Для редактирования фото сотрудника необходимо прислать фото, а не текст!'
                )
                return
            person = Person.get(id=user.status.split(':')[1].split('_')[1])
            update_person_info_in_google(person)
            if not person.photo == '':
                bot.send_photo(chat_id=message.chat.id,
                               photo=person.photo,
                               caption=get_person_info(person),
                               reply_markup=get_contact_reply_markup(
                                   user, person))
            else:
                bot.send_message(chat_id=message.chat.id,
                                 text=get_person_info(person),
                                 reply_markup=get_contact_reply_markup(
                                     user, person))
            bot.send_contact(chat_id=message.chat.id,
                             phone_number=person.phone,
                             first_name=person.surname,
                             last_name=f"{person.name} {person.patronymic}")
    elif user.status.split('/')[0] == 'phone_search':
        search_parameter = user.status.split('/')[1]
        template = message.text
        founded_persons = None
        if search_parameter == 'surname':
            if user not in User.select(User).join(Links).join(Group).where(
                    Group.group_name == 'PhonesAdmin'):
                founded_persons = Person.select().where(
                    Person.surname == template).where(Person.actual == 'True')
            else:
                founded_persons = Person.select().where(
                    Person.surname == template)
        elif search_parameter == 'name':
            if user not in User.select(User).join(Links).join(Group).where(
                    Group.group_name == 'PhonesAdmin'):
                founded_persons = Person.select().where(
                    Person.name == template.split(' ')[0]
                    and Person.patronymic == template.split(' ')[1]).where(
                        Person.actual == 'True')
            else:
                founded_persons = Person.select().where(
                    Person.name == template.split(' ')[0]
                    and Person.patronymic == template.split(' ')[1])
        elif search_parameter == 'number':
            if user not in User.select(User).join(Links).join(Group).where(
                    Group.group_name == 'PhonesAdmin'):
                founded_persons = Person.select().where(
                    Person.phone == template).where(Person.actual == 'True')
            else:
                founded_persons = Person.select().where(
                    Person.phone == template)
        if user not in User.select(User).join(Links).join(Group).where(
                Group.group_name == 'PhonesAdmin'):
            founded_persons = founded_persons.where(Person.actual == 'True')
        if founded_persons.count() > 0:
            for person in founded_persons:
                if not person.photo == '':
                    bot.send_photo(chat_id=message.chat.id,
                                   photo=person.photo,
                                   caption=get_person_info(person),
                                   reply_markup=get_contact_reply_markup(
                                       user, person))
                else:
                    bot.send_message(chat_id=message.chat.id,
                                     text=get_person_info(person),
                                     reply_markup=get_contact_reply_markup(
                                         user, person))
                bot.send_contact(
                    chat_id=message.chat.id,
                    phone_number=person.phone,
                    first_name=person.surname,
                    last_name=f"{person.name} {person.patronymic}")
        else:
            bot.send_message(chat_id=message.chat.id,
                             text='Я никого не нашел по введенным Вами данным')
    else:
        bot.send_message(
            chat_id=message.chat.id,
            text=
            'Воспользуйтесь кнопками или командами (/help) для выбора функции')
    User.update(status='').where(User.id == user.id).execute()
Ejemplo n.º 21
0
    # Search linked channels
    url = channel_url + '&station=%s' % s.code
    channels = get(url)
    for channel in channels:
        c = Channel(api_url, channel)
        c.station = s  # Add a link from channel to station
        s.channels.append(c)
        if c.network and c.network.code not in s.networks:
            s.networks.append(c.network.code)
        # Search linked parameters
        url = params_url + '&channel=%s' % c.id
        params = get(url)
        for param in params:
            p = Parameter(api_url, param)
            c.parameters.append(p)
    # Search equipments linked to the station, but not linked to a channel
    station_equipment_url = equipment_url + '&station=%s' % searched_site_code
    equipments = get(station_equipment_url)
    for equipment in equipments:
        e = Equipment(api_url, equipment)
        s.equipments.append(e)
    # Remember station
    result.append(s)

# FINALLY DISPLAY RESULT
for station in result:
    print(s)

# Bye bye!
sys.exit(0)
Ejemplo n.º 22
0
def addEquipment():
    '''
        新增设备
        将新设备添加至数据库
    :return: 数据添加结果
    '''
    child = request.args.get('child', None)
    user_id = child if child and child != 'None' else session.get('id')

    if not user_id:
        return jsonify({'msg': 'fail', 'data': 'please to login'})
    user = User.query.filter(User.id == user_id).first()

    name = request.form.get('name')
    class_ = request.form.get('class_')
    use_department = request.form.get('use_department')
    location = request.form.get('location')
    gaode_location = request.form.get('gaode_location')
    manufacturer = request.form.get('manufacturer')
    model = request.form.get('model')
    SIM_id = request.form.get("SIM_id")
    remarks = request.form.get('remarks')

    gaode_longitude, gaode_latitude = [
        float(x) for x in gaode_location.split(',')
    ]

    cityData = requests.get(
        'https://restapi.amap.com/v3/geocode/regeo?output=json&location={}&key=1f5f34e6c96735e4be689afb6ec22a82&radius=10&extensions=base'
        .format(gaode_location)).json()

    position_province = cityData['regeocode']['addressComponent']['province']
    position_city = cityData['regeocode']['addressComponent']['city']
    position_district = cityData['regeocode']['addressComponent']['district']

    position_province = position_province if position_province else None
    position_city = position_city if position_city else None
    position_district = position_district if position_district else None

    equipmentInfo = {
        'name': name,
        'use_department': use_department,
        'location': location,
        'gaode_latitude': gaode_latitude,
        'gaode_longitude': gaode_longitude,
        'class_': class_,
        'manufacturer': manufacturer,
        'model': model,
        'remarks': remarks,
        'SIM_id': SIM_id,
        'admin': user,
        'position_province': position_province,
        'position_city': position_city,
        'position_district': position_district
    }

    if equipmentInfo['class_'] == '电气':
        equipmentInfo['id'] = 'e_' + str(int(time.time()))

    try:
        equipment = Equipment(**equipmentInfo)
        equipment.group.append(user.group)
        while user.parent_id:
            user = user.parent
            equipment.group.append(user.group)
        db.session.add(equipment)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({
            'msg': 'fail',
            'data': 'add equipment error when commit database'
        })
    return jsonify({'msg': 'success', 'data': 'add success'})
Ejemplo n.º 23
0
def server_add(request):
    '''
    服务器添加方法,根据ip、port、username、password对服务器操作:远程登录、脚本上传、脚本远程执行
    :param request:
    :return:
    '''
    result = {'status':'error','data':''}
    if request.method == 'POST':
        ip = request.POST.get('ip')
        port = request.POST.get('port')
        username = request.POST.get('username')
        password = request.POST.get('password')
        print ip,port,username,password
        if ip and port and username and password:
            #save db
            equipment = Equipment()
            equipment.ip = ip
            equipment.port = port
            equipment.username = username
            equipment.password = password
            equipment.save()
            #连接远程虚拟机
            connect = connect_server(ip,port,username,password)
            if connect['status'] == 'success':
                trans = connect['data']
                # 用于文件上传和下载的sftp服务
                sftp = paramiko.SFTPClient.from_transport(trans)
                # 远程执行命令服务
                ssh = paramiko.SSHClient()
                ssh._transport = trans
                # 创建目录
                stdin,stdout,stderr = ssh.exec_command('mkdir CMDBClient')
                time.sleep(1)
                # 上传文件
                sftp.put('sftpDir/getData.py','CMDBClient/getData.py')
                sftp.put('sftpDir/sendData.py', 'CMDBClient/sendData.py')
                sftp.put('sftpDir/main.py', 'CMDBClient/main.py')
                # 调用脚本
                stdin,stdout,stderr = ssh.exec_command('python CMDBClient/main.py')
                trans.close()
                # 连接成功状态记录到数据库
                equipment = Equipment.objects.get(ip=ip)
                equipment.status = 'True'
                equipment.save()
            else:
                result['data'] = connect['data']
                # 连接失败状态记录到数据库
                equipment = Equipment.objects.get(ip = ip)
                equipment.status = 'False'
                equipment.save()
        else:
            result['data'] = 'ip and port and username and password not be null'
    else:
        result['data'] = 'your request must be post'
    return JsonResponse(result)
Ejemplo n.º 24
0
def add_eq(request):
    for i in range(100):
        e = Equipment()
        e.hostname = "localhost_%s" % i
        e.IP = "192.168.1.%s" % (i + 2)
        e.System = random.choice([
            "win7_32",
            "win7_64",
            "centos.6_32",
            "centos.7",
        ])
        e.Statue = random.choice(["True", "False"])
        e.Mac = random.choice(["00:0c:29:92:85:4e", "00:0c:29:5b:2a:a1"])
        e.user = "******"
        e.Password = "******"
        e.save()
    return JsonResponse({"statue": "ahh"})
Ejemplo n.º 25
0
def equipment_exists(form, field):
    if Equipment.select().where(Equipment.unitnumber == field.data).exists():
        raise ValidationError('Equipment with that unit number already exists.')
Ejemplo n.º 26
0
def equip_api(request):  #下面客户传来的数据接收并存库
    result = {"statue": "error", "data": ""}
    if request.method == "POST":
        requestData = request.POST
        hostname = requestData.get("hostname")
        mac = requestData.get("mac")
        ip = request.META["REMOTE_ADDR"]
        system_type = requestData.get("version")
        memory = requestData.get("memory")
        disk = requestData.get("disk")
        cpu_count = requestData.get("cpu_count")
        system_version = requestData.get("system")
        try:
            eq = Equipment()
            eq.hostname = hostname
            eq.mac = mac
            eq.ip = ip
            eq.sys_type = system_type
            eq.memory = memory
            eq.disk = disk
            eq.cpu_count = cpu_count
            eq.sys_version = system_version
            eq.save()
        except Exception as e:
            result["data"] = str(e)
        else:
            result["statue"] = "success"
            result["data"] = "your data is saved"
    else:
        result["data"] = "request must be post"
    return JsonResponse(result)
Ejemplo n.º 27
0
import sqlalchemy
import sqlalchemy.orm
from sqlalchemy import *
from sqlalchemy.orm import *
from create_db import connect_to_db

engine = connect_to_db()
Session = sessionmaker(bind=engine)
session = Session()

timeNominal1 = 1448254800
timeDeferred = 1448255460
timeNominal2 = 1448256545

e = Equipment(name='Temperature Controller',
              location='Power Plant',
              info='This piece of equipment controlls temperature set points')

di = DataInfo(equipment_id=2,
              name='Temperature',
              unit='C',
              longunit='Celsius',
              mType='setpoint')

d1 = Data(info_id=2,
          value=float(45),
          timestamp=datetime.datetime.fromtimestamp(float(timeNominal1)))
d2 = Data(info_id=2,
          value=float(40),
          timestamp=datetime.datetime.fromtimestamp(float(timeDeferred)))
d3 = Data(info_id=2,
Ejemplo n.º 28
0
def addequipment():

    if request.method == "POST":
        print 'ssssssssss22'
        #pdb.set_trace()
        name = request.form.get('name')  #设备名称
        code = request.form.get('code')  #设备代码
        type_code = request.form.get('type_code')  #类别代码
        type_name = request.form.get('type_name')  #类别名称
        brand = request.form.get('brand')  #品牌
        type_model = request.form.get('type_model')  #规格型号
        equ_num = request.form.get('equ_num')  #机身号
        by_use = request.form.get('by_use')  #用途
        use_unit = request.form.get('use_unit')  #使用单位
        unit_num = request.form.get('unit_num')  #单位代码
        depository = request.form.get('depository')  #保管人
        location = request.form.get('location')  #存放地点
        buy_time = request.form.get('buy_date')  #购置日期
        put_time = request.form.get('put_date')  #更新日期
        out_time = request.form.get('out_date')  #打印日期
        details = request.form.get('details')  #备注
        status = request.form.get('status')
        #移动载体
        secret_degree = request.form.get('secret_degree', '')  #保密级别(密级)
        #计算机数据
        system = request.form.get('system', '')  #操作系统
        mac_addr = request.form.get('MAC', '')  #MAC地址
        upd_sys_time = request.form.get('upd_sys_time', '0000-00-00')  #系统更新时间
        disk_num = request.form.get('disk_num', 0)  #硬盘个数
        disk_type = request.form.get('disk_type', '')  #硬盘型号
        disk_volume = request.form.get('disk_volume', '')  #硬盘容量
        disk_code = request.form.get('disk_code', '')  #硬盘序列号
        ip_address = request.form.get('ip_address', '')  #IP地址
        hostname = request.form.get('hostname', '')  #主机名
        license = request.form.get('license', '')  #使用许可证号
        cpu = request.form.get('cpu', '')  #CPU规格
        memory_capacity = request.form.get('memory_capacity', '')  #内存容量
        cd_type = request.form.get('cd_type', '')  #光驱类型
        cd_type_num = request.form.get('cd_type_num', '')  #光驱型号
        fd = request.form.get('fd', 0)  #有无软驱
        card_reader = request.form.get('card_reader', 0)  #有无读卡器
        external = request.form.get('external', '')  #外接设备

        equ_type = request.form.get('equ_type')
        if int(status) == 0: status = u'已废弃'
        else: status = u'使用中'
        if int(fd) == 0: fd = u'无光驱'
        else: fd = u'有光驱'
        if int(card_reader) == 0: card_reader = u'无读卡器'
        else: card_reader = u'有读卡器'
        try:
            e = Equipment(name=name,
                          code=code,
                          type_code=type_code,
                          type_name=type_name,
                          brand=brand,
                          type_model=type_model,
                          equ_num=equ_num,
                          by_use=by_use,
                          use_unit=use_unit,
                          unit_num=unit_num,
                          depository=depository,
                          location=location,
                          buy_time=buy_time,
                          put_time=put_time,
                          out_time=out_time,
                          details=details,
                          status=status,
                          secret_degree=secret_degree,
                          system=system,
                          mac_addr=mac_addr,
                          upd_sys_time=upd_sys_time,
                          disk_num=disk_num,
                          disk_type=disk_type,
                          disk_volume=disk_volume,
                          disk_code=disk_code,
                          ip_address=ip_address,
                          hostname=hostname,
                          license=license,
                          cpu=cpu,
                          memory_capacity=memory_capacity,
                          cd_type=cd_type,
                          cd_type_num=cd_type_num,
                          fd=fd,
                          card_reader=card_reader,
                          external=external,
                          equ_type=equ_type)
            db.session.add(e)
            db.session.commit()
        except Exception, err:
            print err
        return redirect('/VEQ/1')
Ejemplo n.º 29
0
def handleGetMapRequest(inputs):
    """
    Gets the map state of the game from the given player's interest model.
    @returns A built Response with the following sets of data:
             map_tiles: a list of serialized MapTiles.
             units: a list of serialized Units.
             resource_templates: a list of ResourceTemplates.
             equipment: a list of Equipment, only including equiped items.
    NOTE: Eventually this will include a more detailed interest model, to allow
    for fog of war, but for now we return the entire world, and only use the
    interest model (player_id) to determine if a tile is a player home or enemy
    home.
  """

    # Make sure the player is already in the game.
    player_key = ndb.Key(urlsafe=inputs['player_id'])
    player = player_key.get()
    if not player.home_tile:
        # If the player does not have a home tile, then they aren't in the game, and
        # they need to join the game.
        logging.error('Player: ' + player_key.urlsafe() +
                      " is not in the game!")
        error_message = 'Player is not in the game.'
        return ResponseBuilder().setErrorMessage(error_message).build()

    # Get the tiles
    map_query = MapTile.query()
    if map_query.count() > 0:
        map_tiles = map_query.fetch()
        ## The map_object will be built up and built into the response.
        ## Its keys will be a the urlsafe key of the serialized maptile value.
        map_object = {'mapTiles': []}
        for tile in map_tiles:
            # Serialize the map tile into what the client needs.
            serialized_tile = {}
            serialized_tile['key'] = tile.key.urlsafe()
            serialized_tile['coordinate_x'] = tile.coordinate_x
            serialized_tile['coordinate_y'] = tile.coordinate_y
            serialized_tile['resources'] = []
            for resource_key in tile.resources:
                tile_resource = resource_key.get()
                resource = {}
                resource['saturation'] = tile_resource.saturation
                resource[
                    'template_key'] = tile_resource.resource_template.urlsafe(
                    )
                serialized_tile['resources'].append(resource)
            serialized_tile['unit_keys'] = []
            unit_keys = tile.units.fetch(keys_only=True)
            for unit_key in unit_keys:
                serialized_tile['unit_keys'].append(unit_key.urlsafe())
            serialized_tile['structure_keys'] = []
            structure_keys = tile.structures.fetch(keys_only=True)
            for structure_key in structure_keys:
                serialized_tile['structure_keys'].append(
                    structure_key.urlsafe())
            # Tell the client if this map tile is a home tile.
            serialized_tile['is_player_home'] = False
            serialized_tile['is_enemy_home'] = False
            if tile.is_home_tile:
                if tile.key == player.home_tile:
                    serialized_tile['is_player_home'] = True
                else:
                    # For now, anyone that isn't the player is an enemy.
                    serialized_tile['is_enemy_home'] = True
            map_object['mapTiles'].append(serialized_tile)

    # TODO: There is a lot of repetition here, find a way to DRY this up.
    # Get the units.
    unit_query = Unit.query()
    if unit_query.count() > 0:
        map_object['units'] = []
        units = unit_query.fetch()
        for unit in units:
            # Serialize the unit into what the client needs.
            serialized_unit = {}
            serialized_unit['key'] = unit.key.urlsafe()
            serialized_unit['unit_type'] = unit.unit_type
            serialized_unit['owner_key'] = unit.owner_key.urlsafe()
            serialized_unit['health'] = unit.health

            if unit.weapon:
                serialized_unit['weapon_key'] = unit.weapon.urlsafe()
            if unit.armor:
                serialized_unit['armor_key'] = unit.armor.urlsafe()

            location_tile = unit.location_tile.get()
            serialized_unit['coordinate_x'] = location_tile.coordinate_x
            serialized_unit['coordinate_y'] = location_tile.coordinate_y

            serialized_unit['has_order'] = unit.has_order
            if unit.has_order:
                serialized_unit[
                    'current_order_key'] = unit.current_order.urlsafe()

            map_object['units'].append(serialized_unit)

    # Get the resource_templates.
    rt_query = ResourceTemplate.query()
    if rt_query.count() > 0:
        map_object['resource_templates'] = []
        resource_templates = rt_query.fetch()
        for template in resource_templates:
            # Serialize the resource_template into what the client needs.
            serialized_rt = {}
            serialized_rt['key'] = template.key.urlsafe()
            serialized_rt['name'] = template.name
            serialized_rt['type'] = template.resource_type
            if template.resource_type == RESOURCE_TYPES_INT_MAPPING[METAL_KEY]:
                serialized_rt[
                    'metal_properties'] = template.metal_properties.to_dict()
            if template.resource_type == RESOURCE_TYPES_INT_MAPPING[WOOD_KEY]:
                serialized_rt[
                    'wood_properties'] = template.wood_properties.to_dict()
            if template.resource_type == RESOURCE_TYPES_INT_MAPPING[
                    LEATHER_KEY]:
                serialized_rt[
                    'leather_properties'] = template.leather_properties.to_dict(
                    )
            map_object['resource_templates'].append(serialized_rt)

    # Get the equipment.
    eq_query = Equipment.query()
    if eq_query.count() > 0:
        map_object['equipment'] = []
        equipment_list = eq_query.fetch()
        for equipment in equipment_list:
            # Serialize the equipment into what the client needs.
            serialized_eq = {}
            serialized_eq['key'] = equipment.key.urlsafe()
            serialized_eq['owner_key'] = equipment.player.urlsafe()
            serialized_eq['type'] = equipment.type
            if equipment.type == EQUIPMENT_TYPE_INT_MAPPING[ARMOR_KEY]:
                serialized_eq['armor_data'] = equipment.armor_data.to_dict()
            if equipment.type == EQUIPMENT_TYPE_INT_MAPPING[WEAPON_KEY]:
                serialized_eq['weapon_data'] = equipment.weapon_data.to_dict()
            map_object['equipment'].append()

    # Get the structures
    struct_query = PlayerStructure.query()
    if struct_query.count() > 0:
        map_object['structures'] = []
        structures = struct_query.fetch()
        for structure in structures:
            # Serialize the structure into what the client needs.
            serialized_struct = {}
            serialized_struct['key'] = structure.key.urlsafe()
            serialized_struct['owner_key'] = structure.owner_key.urlsafe()
            serialized_struct['type'] = structure.structure_type
            serialized_struct['health'] = structure.health
            location_tile = structure.location.get()
            serialized_struct['coordinate_x'] = location_tile.coordinate_x
            serialized_struct['coordinate_y'] = location_tile.coordinate_y
            if (structure.structure_type ==
                    STRUCTURE_TYPE_INT_MAPPING[HARVESTING_CAMP_KEY]):
                # We need to further serialize the camp data.
                camp_data = {
                    'tile_resource_key':
                    structure.harvesting_camp_data.tile_resource_key
                }
            map_object['structures'].append(serialized_struct)

    # The map_object is built, set it on the response data as a json string.
    if len(map_object['mapTiles']) > 0:
        return ResponseBuilder().setData(json.dumps(map_object)).build()
    # No tiles exist, the game has not started.
    else:
        return ResponseBuilder().setErrorMessage("No game has started.")