def zone(request, zone_id=False): if zone_id: if 'delete_range' in request.POST: pr = IPRange.objects.get(id=request.POST.get('delete_range')) pr.delete() if 'ip' in request.POST: z = Zone.objects.get(id=zone_id) new_range = IPRange( ip_address=request.POST.get('ip'), mask=request.POST.get('mask'), description=request.POST.get('description'), zone=z) new_range.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: z = Zone.objects.get(id=zone_id) return render(request, 'zone.html', {'zone': z}) else: if 'delete_zone' in request.POST: dz = Zone.objects.get(id=request.POST.get('delete_zone')) dz.delete() if 'zone_name' in request.POST: new_zone = Zone( name=request.POST.get('zone_name'), description=request.POST.get('description'), criticality=request.POST.get('criticality')) new_zone.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: zones = Zone.objects.all() return render(request, 'all_zones.html', {'zones': zones})
def env_test_01(): admin_user = User(name="Administrator", role=ROLE_ADMIN, access_code="1234") admin_user.add_registration_code("1234") session.add_all([ admin_user, User(name="Chuck Norris", role=ROLE_USER, access_code="1111") ]) print(" - Created users") z1 = Zone(name="No delay", description="Alert with no delay") z2 = Zone(name="Tamper", disarmed_delay=0, away_alert_delay=None, stay_alert_delay=None, description="Sabotage alert") z3 = Zone(name="Away/stay delayed", away_alert_delay=5, stay_alert_delay=5, description="Alert delayed when armed AWAY or STAY") z4 = Zone(name="Stay delayed", stay_alert_delay=5, description="Alert delayed when armed STAY") z5 = Zone(name="Stay", stay_alert_delay=None, description="No alert when armed STAY") session.add_all([z1, z2, z3, z4, z5]) print(" - Created zones") session.add_all(SENSOR_TYPES) print(" - Created sensor types") s1 = Sensor(channel=0, sensor_type=SENSOR_TYPES[0], zone=z3, description="Garage") s2 = Sensor(channel=1, sensor_type=SENSOR_TYPES[2], zone=z5, description="Test room") s3 = Sensor(channel=2, sensor_type=SENSOR_TYPES[1], zone=z2, description="Tamper") session.add_all([s1, s2, s3]) print(" - Created sensors") kt1 = KeypadType(1, "DSC", "DSC keybus (DSC PC-1555RKZ)") kt2 = KeypadType(2, "WIEGAND", "Wiegand keypad") session.add_all([kt1, kt2]) print(" - Created keypad types") k1 = Keypad(keypad_type=kt1) session.add_all([k1]) print(" - Created keypads") session.commit()
def create_zone(): zone = Zone() zone.update(request.json) if not zone.description: zone.description = zone.name db.session.add(zone) db.session.commit() IPCClient().update_configuration() return jsonify(zone.serialize)
def list_zones(self, limit): frontier = PaginationFrontier([self.tenant]) found_zones = [] while not frontier.is_empty(): link, tenant = frontier.pop_next_zone_link() if not link: return found_zones path, params = frontier.parse_url(link) params['sort_key'] = 'id' print "%s: GET %s" % (self.tenant.id, link) resp = self.client.get(path, params=params) check_resp(resp) zones = resp.json()['zones'] links = resp.json()['links'] if 'next' in links: next_link = links['next'] frontier.add_zone_link(next_link, tenant) for z in zones: zone = Zone(z['id'], z['name']) found_zones.append(zone) if len(found_zones) >= limit: return found_zones return found_zones
def update_zones(): # Request data about zones url = 'https://datos.cdmx.gob.mx/api/records/1.0/download/?dataset=alcaldias' r = requests.get(url, allow_redirects=True) decoded_content = r.content.decode('utf-8') cr = csv.reader(decoded_content.splitlines(), delimiter=';') # Skips headers next(cr) # Remove old data Zone.query.delete() # Insert all records for row in cr: shape = geojson.loads(row[5]) geom = from_shape(asShape(shape), srid=4326) newZone = Zone( name=row[0], shape=geom, ) db.session.add(newZone) db.session.commit()
def exit(self, args): """Remove a character from the scene with a staging note Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] self.check_scene() if not self.char and not self.char.category == 'Character': raise Exception(f'You have no active character.```css\n.d c "CHARACTER NAME"```') if not self.sc.started_on: raise Exception(f'***{self.sc.name}*** has not yet started. You may not enter.') if self.sc.ended_on: raise Exception(f'***{self.sc.name}*** has already ended. You missed it.') zones = list(Zone.filter(scene_id=str(self.sc.id), archived=False)) leaving = [z for z in zones if str(self.char.id) in z.characters] for l in leaving: messages.extend(zone_svc.player(('p', 'delete', self.char.name), self.channel, l, self.user)) self.note(('note', f'***{self.char.name}*** exits the _{l.name}_ zone')) if self.channel and self.channel.active_engagement: engagement = Engagement().get_by_id(self.channel.active_engagement) messages.extend(engagement_svc.player(('player', 'delete', self.char.name), self.channel, engagement, self.user)) messages.extend(self.player(('p', 'delete', self.char.name))) self.note(('note', f'***{self.char.name}*** exits the _{self.sc.name}_ scene')) return messages
def save(self, *args, **kwargs): if self.id is None: zone_1 = Zone() zone_1.save() self.grid_zone_1 = zone_1 zone_2 = Zone() zone_2.save() self.grid_zone_2 = zone_2 zone_3 = Zone() zone_3.save() self.grid_zone_3 = zone_3 self.type = 'Grid_' + '_'.join(self.GRID_CHOICES[self.grid_type-1][1].split('/')) super(GridWidget, self).save(*args, **kwargs)
def handle_zhejiang_zone(self): from data import zhejiang_zone for k, v in zhejiang_zone.items(): if v: for v_k, v_v in v.items(): zone = Zone(k, v_k, v_v) self.db.add(zone) self.db.commit() print('insert zhejiang zone is ok!')
def create_zone(self): zone_name, email = random_zone_email() payload = { "name": zone_name, "email": email, "ttl": 7200 } resp = self.client.post_zone(data=json.dumps(payload)) check_resp(resp) zone = Zone(resp.json()['id'], resp.json()['name']) print '%s: Created zone %s' % (self.tenant.id, zone.name) return zone
def __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for ZoneCommand Parameters ---------- parent : DreamcraftHandler The handler for Dreamcraft Bot commands and subcommands ctx : object(Context) The Discord.Context object used to retrieve and send information to Discord users args : array(str) The arguments sent to the bot to parse and evaluate guild : Guild The guild object containing information about the server issuing commands user : User The user database object containing information about the user's current setttings, and dialogs channel : Channel The channel from which commands were issued Returns ------- ZoneCommand - object for processing zone commands and subcommands """ self.parent = parent self.new = parent.new self.delete = parent.delete self.ctx = ctx self.args = args[1:] if args[0] in ['zone', 'z'] else args self.guild = guild self.user = user self.command = self.args[0].lower() if len(self.args) > 0 else 'select' channel = 'private' if ctx.channel.type.name == 'private' else ctx.channel.name self.channel = Channel().get_or_create(channel, self.guild.name, self.user) self.scenario = Scenario().get_by_id(self.channel.active_scenario) if self.channel and self.channel.active_scenario else None self.sc = Scene().get_by_id(self.channel.active_scene) if self.channel and self.channel.active_scene else None self.zone = Zone().get_by_id(self.channel.active_zone) if self.channel and self.channel.active_zone else None self.can_edit = self.user.role == 'Game Master' if self.user and self.zone else True self.char = Character().get_by_id(self.user.active_character) if self.user and self.user.active_character else None
def delete_zone(self, args, guild, channel, scene, zone, user): messages = [] search = '' if len(args) == 1: if not zone: raise Exception('No zone provided for deletion') else: search = ' '.join(args[1:]) zone = Zone().find(guild.name, str(channel.id), str(scene.id), search) if not zone: return [f'{search} was not found. No changes made.'] else: search = str(zone.name) channel_id = str(zone.channel_id) if zone.channel_id else '' zone.character.archive(user) zone.archived = True self.save(zone, user) messages.append(f'***{search}*** removed') if channel_id: channel = Channel().get_by_id(channel_id) messages.append(channel.get_string()) return messages
def SaveZone(lst): try: logok = '' logero = '' first_sheet = lst.sheet_by_index(0) for r in range(1, first_sheet.nrows): m = first_sheet.cell(r, 0).value m2 = first_sheet.cell(r, 2).value chk = Zone.objects.filter(ZoneName=m, Network=m2).exists() if chk == False: sv = Zone( ZoneName=m, Description=first_sheet.cell(r, 1).value, Network=m2, ) sv.save() logok += m.encode("utf-8") + '/' elif chk == True: logero += m.encode("utf-8") + '/' return {'y0': logok, 'y1': logero} except: return False
def __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for UndoCommand Parameters ---------- parent : DreamcraftHandler The handler for Dreamcraft Bot commands and subcommands ctx : object(Context) The Discord.Context object used to retrieve and send information to Discord users args : array(str) The arguments sent to the bot to parse and evaluate guild : Guild The guild object containing information about the server issuing commands user : User The user database object containing information about the user's current setttings, and dialogs channel : Channel The channel from which commands were issued Returns ------- UndoCommand - object for processing undo/redo commands and subcommands """ self.parent = parent self.new = parent.new self.delete = parent.delete self.ctx = ctx self.args = args[1:] self.guild = guild self.user = user self.channel = channel self.command = self.args[0].lower() if len(self.args) > 0 else 'undo' self.scenario = Scenario().get_by_id( self.channel.active_scenario ) if self.channel and self.channel.active_scenario else None self.sc = Scene().get_by_id( self.channel.active_scene ) if self.channel and self.channel.active_scene else None self.zone = Zone().get_by_id( self.channel.active_zone ) if self.channel and self.channel.active_zone else None self.char = Character().get_by_id( self.user.active_character ) if self.user and self.user.active_character else None
def move(self, args): """Move a Character to the current zone Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] self.check_scene() if not self.char or (self.char and self.char.category != 'Character'): raise Exception(f'You have no active character.```css\n.d c "CHARACTER NAME"```') zones = list(Zone.filter(scene_id=str(self.sc.id), archived=False)) if len(args) == 1: leaving = [z for z in zones if str(self.char.id) in z.characters] leaving_str = f'You are currently in the _{leaving[0].name}_ zone.\n' if leaving else '' zones_string = '\n'.join([f'.d s move {z.name}' for z in zones]) raise Exception(f'{leaving_str}Which zone do you want?```css\n{zones_string}```') if not zones: raise Exception('There are no zones to move into.') if args[1] == 'to': zone_name = ' '.join(args[2:]) else: zone_name = ' '.join(args[1:]) zone = [z for z in zones if zone_name.lower() in z.character.name.lower()] if not zone: raise Exception(f'***{zone_name}*** not found in ***{self.sc.name}***') if len(zone) > 1: zones_string = '\n'.join([f'.d s move {z.name}' for z in zones]) raise Exception(f'Which zone do you want?```css\n{zones_string}```') if str(self.char.id) in zone[0].characters: raise Exception(f'***{self.char.name}*** is already in the _{zone[0].name}_ zone.') leaving = [z for z in zones if str(self.char.id) in z.characters] for l in leaving: messages.extend(zone_svc.player(('p', 'delete', self.char.name), self.channel, l, self.user)) self.note(('note', f'***{self.char.name}*** exits the _{l.name}_ zone')) messages.extend(zone_svc.player(('p', self.char.name), self.channel, zone[0], self.user)) self.note(('note', f'***{self.char.name}*** enters the _{zone[0].name}_ zone')) return messages
def addZones(db, zonesList): res = [] for zone in zonesList: z = Zone(name=zone[0]) map_ = Map.query.filter_by(id=zone[1]).first() if map_ != None: print ('Added to {0} zone {1}'.format(map_.name, z.name)) map_.zones.append(z) db.session.add(map_) db.session.add(z) db.session.flush() res.append(z.id) print ('Added zone {0}'.format(zone[0])) db.session.commit() return res
def _gen_zone(zone_name, latency, pricing, datacenters_map): supported_cloud_providers = set({"aws", "gcp"}) zone_parts = zone_name.split("-") if len(zone_parts) < 2: print("Zone must be complete - ", zone_parts) return None cp_name = zone_parts[0] if cp_name not in supported_cloud_providers: print("Unsupported cloud provider - ", cp_name) return None cp = CloudProvider(cp_name) region_name = "-".join(zone_parts[1:len(zone_parts)]) region_location = datacenters_map[cp_name + "-" + region_name]["location"] region = Region(region_name, region_location) zone = Zone("1", region, cp, latency, pricing[cp_name]) return zone
def gather_zones(self): if self.done(): LOG.debug("we're done!") self.done_gathering.fire() return # grab a list zones link from our 'frontier' of links link, tenant = self.frontier.pop_next_zone_link() if not link: return # we want to be careful to retain the 'marker=<uuid>' that's used to # grab different pages of a paginated list path, params = self.frontier.parse_url(link) params['sort_key'] = 'id' client = self.designate_client.as_user(tenant) resp = client.get(path, name='/v2/zones', params=params) if not resp.ok: LOG.error("failed to list zones while gathering zones") return zones = resp.json()['zones'] links = resp.json()['links'] LOG.info("%s -- fetched %s zones for tenant %s", resp.request.url, len(zones), tenant) if 'next' in links: self.frontier.add_zone_link(links['next'], tenant) else: LOG.debug("no more zone 'next' links to pursue") for z in zones: zone = Zone(z['id'], z['name']) # be sure to avoid storing recordsets on zones we're going to delete if len(tenant.data.zones_for_get) <= len(tenant.data.zones_for_delete): tenant.data.zones_for_get.append(zone) path, _ = self.frontier.parse_url(z['links']['self']) recordset_link = "{0}/recordsets".format(path) self.frontier.add_recordset_link(zone, recordset_link, tenant) else: tenant.data.zones_for_delete.append(zone)
def parse_data(self): try: for i in range(len(self.zone_provice_code)): print("provice code: %s" % self.zone_provice_code[i]) for k , v in self.zone_data[i][0].items(): city_code = hashlib.md5(os.urandom(16)).hexdigest() city = City(self.zone_provice_code[i], city_code, v) self.db.add(city) print("add city: %s" % v) city_zones = self.zone_data[i][1].get(k) if city_zones: for zk, zv in city_zones.items(): if zv: zone = Zone(city_code, zk, zv) self.db.add(zone) print("city: %s - zone: %s" % (v, zv)) self.db.commit() except Exception as e: self.db.rollback() finally: self.db.close()
def zone_list(self, args): """Display a dialog for viewing and selecting Zones Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] if not self.sc: raise Exception('No active scene. Try this:```css\n.d scene "SCENE NAME"```') def canceler(cancel_args): if cancel_args[0].lower() in ['zone']: return ZoneCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() messages.extend(Dialog({ 'svc': zone_svc, 'user': self.user, 'title': 'Zone List', 'command': 'zone ' + (' '.join(args)), 'type': 'view', 'type_name': 'ZONE', 'getter': { 'method': Zone().get_by_scene, 'params': {'scene': self.sc, 'archived': False} }, 'formatter': lambda item, item_num, page_num, page_size: f'{item.get_short_string(self.channel)}', 'cancel': canceler }).open()) return messages
def _do_create_domain(self): tenant = self.select_random_tenant() if not tenant: return client = self.designate_client.as_user(tenant) zone_name, email = random_zone_email() payload = {"name": zone_name, "email": email, "ttl": 7200} # the with block lets us specify when the request has succeeded. # this lets us time how long until an active or error status. start_time = time.time() post_resp = client.post_zone(data=json.dumps(payload), name='/v2/zones') if not post_resp.ok: return if CONFIG.use_digaas: self.digaas_behaviors.observe_zone_create(post_resp, start_time) api_call = lambda: client.get_zone(zone_id=post_resp.json()['id'], name='/v2/zones/ID - status check') self._poll_until_active_or_error( api_call=api_call, status_function=lambda r: r.json()['status'], success_function=lambda: self.async_success( post_resp, start_time, '/v2/zones - async'), failure_function=lambda msg: self.async_failure( post_resp, start_time, '/v2/zones - async', msg), ) # if we successfully created the zone, add it to our list # todo: add some domains to the delete list resp = api_call() if resp.ok and resp.json()['status'] == 'ACTIVE': zone = Zone(resp.json()['id'], resp.json()['name']) # LOG.info("%s -- Added zone %s", tenant, zone) tenant.data.zones_for_delete.append(zone)
def adjoin(self, args, guild, channel, sc, user): messages = [] incorrect_sytax = f'Incorrect syntax:```css\n.d scene {args[0]} "ZONE NAME 1" to "Zone Name 2"```' if len(args) < 4 or ' to ' not in ' '.join(args): raise Exception('\n'.join(['No zones adjoined', incorrect_sytax])) if not sc: raise Exception( 'You don\'t have an active scene. Try this:```css\n.d new scene SCENE_NAME```' ) zones = ' '.join(args).replace(f'{args[0]} ', '').split(' to ') zone_list = [] for z in zones: zone = Zone().find(name=z, guild=guild, channel_id=str(channel.id), scene_id=str(sc.id)) if zone: zone_list.append(zone) if len(zone_list) < 2: raise Exception(f'***{zones[0]}*** or ***{zones[1]}*** not found') adjoined = [] if sc.adjoined_zones: adjoined = copy.deepcopy(sc.adjoined_zones) for adjoin in adjoined: if str(zone_list[0].id) in adjoin and str( zone_list[1].id) in adjoin: raise Exception( f'***{zone_list[0].name}*** and ***{zone_list[1].name}*** are already adjoined in ***{sc.name}***' ) adjoined.append([str(z.id) for z in zone_list]) sc.adjoined_zones = adjoined self.save(sc, user) messages.append( f'***{zone_list[0].name}*** and ***{zone_list[1].name}*** are now adjoined in ***{sc.name}***' ) return messages
#!/usr/bin/env python3 import sys from pathlib import Path # add parent folder sys.path.append(str(Path(__file__).parent.parent.absolute())) from app import db, app # noqa: E402 from models import Zone # noqa: E402 zone = Zone(zone=input("Enter zone name: ")) with app.app_context(): db.session.add(zone) db.session.commit()
def env_live_01(): session.add_all([ User(name="Administrator", role=ROLE_ADMIN, access_code="1234"), User(name="Chuck.Norris", role=ROLE_USER, access_code="1111"), ]) print(" - Created users") z1 = Zone(name="No delay", description="Alert with no delay") z2 = Zone(name="Away delayed", away_alert_delay=20, description="Alert delayed when armed AWAY") z3 = Zone(name="Stay delayed", stay_alert_delay=20, description="Alert delayed when armed STAY") z4 = Zone(name="Stay", stay_alert_delay=None, description="No alert when armed STAY") z5 = Zone(name="Away/Stay delayed", away_alert_delay=40, stay_alert_delay=20, description="Alert delayed when armed AWAY/STAY") z6 = Zone(name="Tamper", disarmed_delay=0, away_alert_delay=None, stay_alert_delay=None, description="Sabotage alert") session.add_all([z1, z2, z3, z4, z5, z6]) print(" - Created zones") session.add_all(SENSOR_TYPES) print(" - Created sensor types") s1 = Sensor(channel=0, sensor_type=SENSOR_TYPES[0], zone=z5, description="Garage") s2 = Sensor(channel=1, sensor_type=SENSOR_TYPES[0], zone=z5, description="Hall") s3 = Sensor(channel=2, sensor_type=SENSOR_TYPES[2], zone=z5, description="Front door") s4 = Sensor(channel=3, sensor_type=SENSOR_TYPES[0], zone=z3, description="Kitchen") s5 = Sensor(channel=4, sensor_type=SENSOR_TYPES[0], zone=z1, description="Living room") s6 = Sensor(channel=5, sensor_type=SENSOR_TYPES[0], zone=z4, description="Children's room") s7 = Sensor(channel=6, sensor_type=SENSOR_TYPES[0], zone=z4, description="Bedroom") s8 = Sensor(channel=7, sensor_type=SENSOR_TYPES[1], zone=z6, description="Tamper") session.add_all([s1, s2, s3, s4, s5, s6, s7, s8]) print(" - Created sensors") kt1 = KeypadType(1, "DSC", "DSC keybus (DSC PC-1555RKZ)") session.add_all([kt1]) print(" - Created keypad types") k1 = Keypad(keypad_type=kt1) session.add_all([k1]) print(" - Created keypads") session.commit()
class ZoneCommand(): """ Handle 'zone', 'z' commands and subcommands Subcommands: help - display a set of instructions on ZoneCommand usage note - add a note to the zone say - add dialog to the zone from the zone story - display the zone's story new - create new zones by name name, n - display zones by name description, desc - add/edit the Description in the zone select - display existing zone character, char, c - edit the zone as a character list, l - display a list of existing characters and NPCs players, player, p - add players to the zone delete - remove an zone (archive) """ def __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for ZoneCommand Parameters ---------- parent : DreamcraftHandler The handler for Dreamcraft Bot commands and subcommands ctx : object(Context) The Discord.Context object used to retrieve and send information to Discord users args : array(str) The arguments sent to the bot to parse and evaluate guild : Guild The guild object containing information about the server issuing commands user : User The user database object containing information about the user's current setttings, and dialogs channel : Channel The channel from which commands were issued Returns ------- ZoneCommand - object for processing zone commands and subcommands """ self.parent = parent self.new = parent.new self.delete = parent.delete self.ctx = ctx self.args = args[1:] if args[0] in ['zone', 'z'] else args self.guild = guild self.user = user self.command = self.args[0].lower() if len(self.args) > 0 else 'select' channel = 'private' if ctx.channel.type.name == 'private' else ctx.channel.name self.channel = Channel().get_or_create(channel, self.guild.name, self.user) self.scenario = Scenario().get_by_id(self.channel.active_scenario) if self.channel and self.channel.active_scenario else None self.sc = Scene().get_by_id(self.channel.active_scene) if self.channel and self.channel.active_scene else None self.zone = Zone().get_by_id(self.channel.active_zone) if self.channel and self.channel.active_zone else None self.can_edit = self.user.role == 'Game Master' if self.user and self.zone else True self.char = Character().get_by_id(self.user.active_character) if self.user and self.user.active_character else None def run(self): """ Execute the channel commands by validating and finding their respective methods Returns ------- list(str) - a list of messages in response the command validation and execution """ try: # List of subcommands mapped the command methods switcher = { 'help': self.help, 'name': self.select, 'n': self.select, 'select': self.select, 'say': self.say, 'note': self.note, 'story': self.story, 'description': self.description, 'desc': self.description, 'character': self.character, 'char': self.character, 'c': self.character, 'approaches': self.character, 'approach': self.character, 'apps': self.character, 'app': self.character, 'skills': self.character, 'skill': self.character, 'sks': self.character, 'sk': self.character, 'aspects': self.character, 'aspect': self.character, 'a': self.character, 'stunts': self.character, 'stunt': self.character, 's': self.character, 'custom': self.character, 'stress': self.character, 'st': self.character, 'consequences': self.character, 'consequence':self.character, 'con': self.character, 'players': self.player, 'player': self.player, 'p': self.player, 'list': self.zone_list, 'l': self.zone_list, 'delete': self.delete_zone, 'd': self.delete_zone } if self.new and not self.user.command or self.user.command and 'new' in self.user.command: func = self.new_zone elif self.delete: func = self.delete_zone # Get the function from switcher dictionary elif self.command in switcher: func = switcher.get(self.command, lambda: self.select) else: match = self.search(self.args) if match: self.args = ('select',) + self.args self.command = 'select' func = self.select else: self.args = ('n',) + self.args self.command = 'n' func = self.select if func: # Execute the function messages = func(self.args) # Send messages return messages except Exception as err: traceback.print_exc() # Log every error zone_svc.log( str(self.zone.id) if self.zone else str(self.user.id), self.zone.name if self.zone else self.user.name, str(self.user.id), self.guild.name, 'Error', { 'command': self.command, 'args': self.args, 'traceback': traceback.format_exc() }, 'created') return list(err.args) def help(self, args): """Returns the help text for the command""" return [ZONE_HELP] def search(self, args): """Search for an existing Zone using the command string Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ params = {'name__icontains': ' '.join(args[0:]), 'guild': self.guild.name, 'channel_id': str(self.channel.id), 'archived': False} return zone_svc.search(args, Zone.filter, params) def note(self, args): """Add a note to the Zone story Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if self.zone: Log().create_new(str(self.zone.id), f'Zone: {self.zone.name}', str(self.user.id), self.guild.name, 'Zone', {'by': self.user.name, 'note': ' '.join(args[1:])}, 'created') return ['Log created'] else: return ['No active zone to log'] def say(self, args): """Add dialog to the Zone story Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if not self.zone: return ['No active zone to log'] else: note_text = ' '.join(args[1:]) Log().create_new(str(self.zone.id), f'Zone: {self.zone.name}', str(self.user.id), self.guild.name, 'Zone', {'by': self.user.name, 'note': f'***Narrator*** says, "{note_text}"'}, 'created') return ['Log created'] def story(self, args): """Disaply the Zone story Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages =[] if not self.sc: raise Exception('No active scene. Try this:```css\n.d scene "SCENE NAME"```') command = 'zone ' + (' '.join(args)) def canceler(cancel_args): if cancel_args[0].lower() in ['zone','s']: self.args = cancel_args self.command = self.args[0] return self.run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() response = Dialog({ 'svc': zone_svc, 'user': self.user, 'title': 'Story', 'type': 'view', 'type_name': 'Story Log', 'command': command, 'getter': { 'method': Log.get_by_page, 'params': { 'params': {'parent_id': str(self.sc.id)}, 'sort': 'created' }, 'parent_method': Zone.get_by_page, 'parent_params': { 'params': {'category__in': ['Character','Aspect','Stunt']}, 'sort': 'created' } }, 'formatter': lambda log, num, page_num, page_size: log.get_string(self.user), # if log.category == 'Log' else log.get_string() 'cancel': canceler, 'page_size': 10 }).open() messages.extend(response) return messages def dialog(self, dialog_text, zone=None): """Display Zone information and help text Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ zone, name, get_string, get_short_string = zone_svc.get_info('zone', zone if zone else self.zone, self.channel) category = 'Zone' dialog = { 'create_zone': ''.join([ '**CREATE or ZONE**```css\n', '.d new zone "YOUR ZONE\'S NAME"```' ]), 'active_zone': ''.join([ '***YOU ARE CURRENTLY EDITING...***\n' if self.can_edit else '', f':point_down:\n\n{get_string}' ]), 'active_zone_short': ''.join([ '***YOU ARE CURRENTLY EDITING...:***\n' if self.can_edit else '', f':point_down:\n\n{get_short_string}' ]), 'rename_delete': ''.join([ f'\n\n_Is ***{name}*** not the {category.lower()} name you wanted?_', f'```css\n.d zone rename "NEW NAME"```_Want to remove ***{name}***?_', '```css\n.d zone delete```' ]), 'go_back_to_parent': ''.join([ f'\n\n***You can GO BACK to the parent zone, aspect, or stunt***', '```css\n.d zone parent```' ]) } dialog_string = '' if dialog_text == 'all': if not zone: dialog_string += dialog.get('create_zone', '') dialog_string += dialog.get('rename_delete', '') elif category == 'Zone': if dialog_text: dialog_string += dialog.get(dialog_text, '') else: dialog_string += dialog.get('active_zone', '') dialog_string += dialog.get('rename_delete', '') if self.can_edit else '' else: if dialog_text: dialog_string += dialog.get(dialog_text, '') else: dialog_string += dialog.get('active_zone', '') if self.can_edit else '' dialog_string += dialog.get('rename_delete', '') if self.can_edit else '' dialog_string += dialog.get('go_back_to_parent', '') if self.can_edit else '' return dialog_string def new_zone(self, args): """Create a new Zone by name Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if not self.sc: raise Exception('No active scene or name provided. Try this:```css\n.d scene "SCENE NAME"```') messages = [] if len(args) == 0: if not self.zone: return [ 'No active zone or name provided\n\n', self.dialog('all') ] messages.append(self.zone.get_string(self.channel)) else: if len(args) == 1 and args[0].lower() == 'short': return [self.dialog('active_zone_short')] zone_name = ' '.join(args) if len(args) > 1 and args[1] == 'rename': zone_name = ' '.join(args[2:]) if not self.zone: return [ 'No active zone or name provided\n\n', self.dialog('all') ] else: zone = Zone().find(self.guild.name, str(self.channel.id), str(self.sc.id), zone_name) if zone: return [f'Cannot rename to _{zone_name}_. Zone already exists'] else: self.zone.name = zone_name zone_svc.save(self.zone, self.user) messages.append(self.dialog('')) else: def canceler(cancel_args): if cancel_args[0].lower() in ['zone','z']: return ZoneCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() def selector(selection): self.zone = selection self.channel.set_active_zone(self.zone, self.user) self.user.set_active_character(self.zone.character) zone_svc.save_user(self.user) return [self.dialog('')] messages.extend(Dialog({ 'svc': zone_svc, 'user': self.user, 'title': 'Zone List', 'command': 'new zone ' + ' '.join(args), 'type': 'select', 'type_name': 'ZONE', 'getter': { 'method': Zone.get_by_page, 'params': {'params': {'name__icontains': zone_name, 'channel_id': str(self.channel.id), 'guild': self.guild.name, 'archived': False}} }, 'formatter': lambda item, item_num, page_num, page_size: f'_ZONE #{item_num+1}_\n{item.get_short_string()}', 'cancel': canceler, 'select': selector, 'confirm': { 'method': Zone().get_or_create, 'params': {'user': self.user, 'name': zone_name, 'scene': self.sc, 'channel': self.channel, 'guild': self.guild.name} } }).open()) return messages def select(self, args): """Select an existing Zone by name Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] if not self.sc: raise Exception('No active scene. Try this:```css\n.d scene "SCENE NAME"```') if len(args) == 0: if not self.zone: return [ 'No active zone or name provided\n\n', self.dialog('all') ] messages.append(self.zone.get_string(self.channel)) else: if len(args) == 1 and args[0].lower() == 'short': return [self.dialog('active_zone_short')] if len(args) == 1 and self.char: return [self.dialog('')] zone_name = ' '.join(args[1:]) def canceler(cancel_args): if cancel_args[0].lower() in ['zone','z']: return ZoneCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() def selector(selection): self.zone = selection self.channel.set_active_zone(self.zone, self.user) self.user.set_active_character(self.zone) zone_svc.save_user(self.user) return [self.dialog('')] messages.extend(Dialog({ 'svc': zone_svc, 'user': self.user, 'title': 'Zone List', 'command': 's ' + ' '.join(args), 'type': 'select', 'type_name': 'ZONE', 'getter': { 'method': Zone.get_by_page, 'params': {'params': {'name__icontains': zone_name, 'scene_id': str(self.sc.id), 'guild': self.guild.name, 'archived': False}} }, 'formatter': lambda item, item_num, page_num, page_size: f'_ZONE #{item_num+1}_\n{item.get_short_string()}', 'cancel': canceler, 'select': selector }).open()) return messages def zone_list(self, args): """Display a dialog for viewing and selecting Zones Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] if not self.sc: raise Exception('No active scene. Try this:```css\n.d scene "SCENE NAME"```') def canceler(cancel_args): if cancel_args[0].lower() in ['zone']: return ZoneCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() messages.extend(Dialog({ 'svc': zone_svc, 'user': self.user, 'title': 'Zone List', 'command': 'zone ' + (' '.join(args)), 'type': 'view', 'type_name': 'ZONE', 'getter': { 'method': Zone().get_by_scene, 'params': {'scene': self.sc, 'archived': False} }, 'formatter': lambda item, item_num, page_num, page_size: f'{item.get_short_string(self.channel)}', 'cancel': canceler }).open()) return messages def description(self, args): """Add/edit the description for a Zone Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if len(args) == 1: return ['No description provided'] if not self.zone: return ['You don\'t have an active zone.\nTry this: ".d s name {name}"'] else: description = ' '.join(args[1:]) self.zone.description = description zone_svc.save(self.zone, self.user) return [ f'Description updated to "{description}"', self.zone.get_string(self.channel) ] def character(self, args): """Edit the Zone as a character Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if self.user: self.user.active_character = str(self.zone.character.id) zone_svc.save_user(self.user) command = CharacterCommand(parent=self.parent, ctx=self.ctx, args=args, guild=self.guild, user=self.user, channel=self.channel, char=self.zone.character) return command.run() def player(self, args): """Add/remove a player from the Zone Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ return zone_svc.player(args, self.channel, self.zone, self.user) def delete_zone(self, args): """Delete (archive) the current active Zone Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if not self.sc: raise Exception('No active scene. Try this:```css\n.d scene "SCENE NAME"```') return zone_svc.delete_zone(args, self.guild, self.channel, self.sc, self.zone, self.user)
def new_zone(self, args): """Create a new Zone by name Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if not self.sc: raise Exception('No active scene or name provided. Try this:```css\n.d scene "SCENE NAME"```') messages = [] if len(args) == 0: if not self.zone: return [ 'No active zone or name provided\n\n', self.dialog('all') ] messages.append(self.zone.get_string(self.channel)) else: if len(args) == 1 and args[0].lower() == 'short': return [self.dialog('active_zone_short')] zone_name = ' '.join(args) if len(args) > 1 and args[1] == 'rename': zone_name = ' '.join(args[2:]) if not self.zone: return [ 'No active zone or name provided\n\n', self.dialog('all') ] else: zone = Zone().find(self.guild.name, str(self.channel.id), str(self.sc.id), zone_name) if zone: return [f'Cannot rename to _{zone_name}_. Zone already exists'] else: self.zone.name = zone_name zone_svc.save(self.zone, self.user) messages.append(self.dialog('')) else: def canceler(cancel_args): if cancel_args[0].lower() in ['zone','z']: return ZoneCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() def selector(selection): self.zone = selection self.channel.set_active_zone(self.zone, self.user) self.user.set_active_character(self.zone.character) zone_svc.save_user(self.user) return [self.dialog('')] messages.extend(Dialog({ 'svc': zone_svc, 'user': self.user, 'title': 'Zone List', 'command': 'new zone ' + ' '.join(args), 'type': 'select', 'type_name': 'ZONE', 'getter': { 'method': Zone.get_by_page, 'params': {'params': {'name__icontains': zone_name, 'channel_id': str(self.channel.id), 'guild': self.guild.name, 'archived': False}} }, 'formatter': lambda item, item_num, page_num, page_size: f'_ZONE #{item_num+1}_\n{item.get_short_string()}', 'cancel': canceler, 'select': selector, 'confirm': { 'method': Zone().get_or_create, 'params': {'user': self.user, 'name': zone_name, 'scene': self.sc, 'channel': self.channel, 'guild': self.guild.name} } }).open()) return messages
def addnew(request): ## The add zone function can be used in two ways. ## one way, is to click add new zone from the zone list page..... ## which will display all the regions and create a zone by selecting a region from the list ## second way, is to click add new zone from the region detailed page... ## which means you already selected the region and adding a zone in that region ## that's why the following variable says whether you already selected region or not selRegionName = request.REQUEST.get("regionname", "") ## Check if there are any regions defined. If not, then zones cannot be added regionsCount = getRegionCount() if (regionsCount == 0): message = "No Regions Defined. First create Region and then try to add Zone" html = "<html><body> %s.</body></html>" % message return HttpResponse(html) ## Check if there are any resource types defined. If not, then zones cannot be added resourceTypesCount = getResourceTypesCount() if (resourceTypesCount == 0): message = "No Resource Types Defined. First create Resource Types and then try to add Zone" html = "<html><body> %s. </body></html>" % message return HttpResponse(html) groups = request.META.get('ADFS_GROUP','') groupsList = groups.split(';') userIsSuperUser = isSuperUser(groupsList) ## If the request is through form submission, then try to add the region or else display the add form if request.method == 'POST': redirectURL = '/cloudman/message/?msg=' regionName = request.POST['region'] zoneName = request.POST['name'] description = request.POST['description'] hepSpecs = request.POST['hepspecs'] memory = request.POST['memory'] storage = request.POST['storage'] bandwidth = request.POST['bandwidth'] hepSpec_overcommit = request.POST['hepspec_overcommit'] memory_overcommit = request.POST['memory_overcommit'] comment = request.POST['comment'] try: validate_name(regionName) validate_name(zoneName) validate_descr(description) validate_float(hepSpecs) validate_int(memory) validate_int(storage) validate_float(bandwidth) validate_comment(comment) validate_float(hepSpec_overcommit) validate_float(memory_overcommit) except ValidationError as e: message ='Add Zone Form '+', '.join(e.messages) html = "<html><HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"4; url=/cloudman/zone/list/\"></HEAD><body> %s.</body></html>" % message return HttpResponse(html) ## check for uniqueness of this zone name in the region nameExists = checkNameIgnoreCase(regionName, zoneName) if nameExists: msgAlreadyExists = 'Zone Name ' + zoneName + ' in Region ' + regionName + ' already exists. Hence Add New Zone Operation Stopped' transaction.rollback() return HttpResponseRedirect(redirectURL + msgAlreadyExists) ## check whether user has any of the following rights ## cloudman resource manager privileges ## If not, then has membership of region admin_group if not userIsSuperUser: userIsAdminOfRegion = isAdminForRegion(regionName, groupsList) if not userIsAdminOfRegion: message = "You neither have membership of administrative group of region " + regionName + " nor possess Cloudman Resource Manager Privileges. Hence you are not authorized to add new Zone"; return HttpResponseRedirect(redirectURL + message) ## Get the Region Object try: region = Region.objects.get(name=regionName) except Region.DoesNotExist: errorMessage = 'No Record Found for Region ' + regionName + '. Hence Add New Zone Operation Stopped' return HttpResponseRedirect(redirectURL + errorMessage) ## validate hepspec, memory, storage and bandwidth values errorMsg = checkAttributeValues(hepSpecs, memory, storage, bandwidth) if (errorMsg != ''): return HttpResponseRedirect(redirectURL + errorMsg) ## validate hepspec over commit and memory over commit values if hepSpec_overcommit < 1: msgFailure = "Hepspec Over Commit value should be greater than or equal to 1. Hence Add Zone Operation Stopped" return HttpResponseRedirect(redirectURL + msgFailure) if memory_overcommit < 1: msgFailure = "Memory Over Commit value should be greater than or equal to 1. Hence Add Zone Operation Stopped" return HttpResponseRedirect(redirectURL + msgFailure) ## get all the resource types check boxes values (resource type name), ## the allowed resource types for this zone will be the ones whose checkbox is selected totalResourceTypes = request.POST['totalresourcetypes'] index = 1 atleastOneRTsel = False resourceTypesList = [] while index <= int(totalResourceTypes): if ('resourcetype'+str(index)) in request.POST.keys() : ## if checkbox selected resourceTypesList.append(request.POST['resourcetype'+str(index)]) atleastOneRTsel = True index = index + 1 if not atleastOneRTsel: message = "No Resource Types selected that are allowed for this Zone. Hence Zone Add Operation Stopped" return HttpResponseRedirect(redirectURL + message) ## get the resource type objects for all those that are selected resourceTypesFullInfoList = [] msgSuccess = '' for oneRT in resourceTypesList: try: resourceType = ResourceType.objects.get(name=oneRT) resourceTypesFullInfoList.append(resourceType) msgSuccess = msgSuccess + ' ' + oneRT; except ResourceType.DoesNotExist: errorMessage = 'No Record Found for Resource Type ' + oneRT + '. Hence Add New Zone Operation Stopped' return HttpResponseRedirect(redirectURL + errorMessage) msgSuccess = 'New Zone ' + zoneName + ' added successfully ' + ' to Region ' + regionName + '. The allowed Resource Types are ' + msgSuccess if hepSpecs == '': hepSpecs = None else: hepSpecs = round((float(hepSpecs)), 3) if memory == '': memory = None else: memory = round((float(memory)), 3) if storage == '': storage = None else: storage = round((float(storage)), 3) if bandwidth == '': bandwidth = None else: bandwidth = round((float(bandwidth)), 3) ## create the zone object and save it newzone = Zone(name=zoneName, description=description, region=region, hepspecs=hepSpecs, memory=memory, storage=storage, bandwidth=bandwidth, hepspec_overcommit=hepSpec_overcommit, memory_overcommit=memory_overcommit) newzone.save() ## get the newly added zone object ## add the allowed resource types for this zone addedZone = Zone.objects.get(name=zoneName, region=region) for oneRT in resourceTypesFullInfoList: zrt = ZoneAllowedResourceType(zone=addedZone, resource_type=oneRT) zrt.save() ##Add the Log for Zone if addLog(request,zoneName,comment,addedZone,None,'zone','add',True): transaction.commit() else: transaction.rollback() msgSuccess = 'Error in creating new zone' + zoneName ## return the success message to the user html = "<html><HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"4; url=/cloudman/zone/list/\"></HEAD><body> %s.</body></html>" % msgSuccess return HttpResponse(html) else: ## Zone can be added provided you have any of the following privileges ## cloudman resource manager privileges ## only to regions for which user has membership of its admin_group if not userIsSuperUser: userIsAdmin = True ## if region is not already selected, then check user has membership of atleast one region admin_group if selRegionName == '': userIsAdmin = isAdminOfAnyRegion(groupsList) if not userIsAdmin: message = "You neither have membership of administrative groups of any region nor possess Cloudman Resource Manager Privileges. Hence you are not authorized to add new Zone"; html = "<html><body> %s.</body></html>" % message return HttpResponse(html) else: userIsAdmin = isAdminForRegion(selRegionName, groupsList) if not userIsAdmin: message = "You neither have membership of administrative group of region " + selRegionName + " nor possess Cloudman Resource Manager Privileges. Hence you are not authorized to add new Zone"; html = "<html><body> %s.</body></html>" % message return HttpResponse(html) form = ZoneForm(userGroups=groupsList, superUserRights=userIsSuperUser) resourceForm=ResourceForm resourceType = ResourceType.objects.all() return render_to_response('zone/addnew.html',locals(),context_instance=RequestContext(request))