def display_events(self, lhs, rhs): if lhs: self.display_event(lhs) return now = utcnow() interval = duration_from_string('6h') expired = now - interval events = Event.objects.filter(date_schedule__gte=expired).order_by('date_schedule') tz = self.player.settings.get('timezone') last_day = '' check_day = '' message = list() message.append(self.player.render.header("Current Schedule - %s" % self.player.time.display(format='%Z'))) for event in events: check_day = self.caller.display_local_time(date=event.date_schedule, format='%a %b %d %Y') if check_day != last_day: message.append(self.player.render.subheader(check_day)) last_day = check_day time = self.caller.display_local_time(date=event.date_schedule, format='%I:%M%p') tag_mark = ' ' taggers = set(event.interest.all()) alts = set(self.player.get_all_characters()) check_set = taggers.intersection(alts) if len(check_set): tag_mark = ANSIString('|C*|n') if self.character in taggers: tag_mark = ANSIString('|r*|n') if event.owner == self.character: tag_mark = ANSIString('|g*|n') tag_count = event.interest.all().count() display_string = "{}{:<2} {:<4}{:40.40}{:23.23}{:7}".format(tag_mark, tag_count, event.id, event.title, event.owner, time) message.append(display_string) message.append(self.player.render.footer()) self.msg_lines(message)
def edit_post(self, find=None, replace=None): if not find: raise ValueError("No text entered to find.") if not replace: replace = '' self.date_modified = utcnow() self.text = self.text.replace(find, replace)
def switch_add(self, lhs, rhs): if not lhs: raise ValueError("What time shall it happen?") return if '/' not in lhs: raise ValueError("What will the scene's title be?") return time, title = lhs.split('/', 1) try: check_time = utc_from_string( time, self.character.settings.get('timezone')) except ValueError as err: raise ValueError(str(err)) return if not check_time > utcnow(): raise ValueError( "No scheduling things in the past, that's just silly.") return if not title: raise ValueError("What will the scene's title be?") return if not rhs: raise ValueError("What will the scene's description be?") return new_event = Event.objects.create(owner=self.character, title=title, date_schedule=check_time, description=rhs) new_event.setup() self.sys_msg("Your new Event's ID is: %s" % new_event.id) return
def switch_add(self, lhs, rhs): if not lhs: self.error("What time shall it happen?") return if '/' not in lhs: self.error("What will the scene's title be?") return time, title = lhs.split('/', 1) try: check_time = utc_from_string(time, self.character.settings.get('timezone')) except ValueError as err: self.error(unicode(err)) return if not check_time > utcnow(): self.error("No scheduling things in the past, that's just silly.") return if not title: self.error("What will the scene's title be?") return if not rhs: self.error("What will the scene's description be?") return new_event = Event.objects.create(owner=self.character, title=title, date_schedule=check_time, description=rhs) new_event.setup() self.sys_msg("Your new Event's ID is: %s" % new_event.id) return
def process_timeout(self): if not self.timeout: return start_date = self.timeout_date or self.creation_date check_date = start_date + self.timeout if check_date < utcnow(): self.delete() return True
def create_post(self, poster, subject, text, date=None): if not date: date = utcnow() order = self.next_post_number new_post = self.post_class.create(self, poster, subject, text, date, order) self.next_post_number = order + 1 return new_post
def get_state(self): """ Returns: False if not banned. dict of stuff if yes. """ if (banned_until := self.state.get( 'until', None)) and banned_until > (now := utcnow()):
def display(self, date=None, format=None): if not format: format = '%b %d %I:%M%p %Z' if not date: date = utcnow() tz = self.config['timezone'] time = date.astimezone(tz) return time.strftime(format)
def make_comment(self, comment_mode=1, text=None, is_private=False): now = utcnow() if not is_private: self.job.public_update = now self.job.admin_update = now return self.comments.create(comment_mode=comment_mode, text=text, is_private=is_private, date_made=now)
def update_time(self, fields): timestamp = utcnow() if isinstance(fields, basestring): setattr(self, fields, timestamp) self.save(update_fields=[fields]) return for field in fields: setattr(self, field, timestamp) self.save(update_fields=fields)
def set_approved(self, approver=None): if not approver: raise ValueError("Approver is not defined.") if self.approved: raise ValueError("File '%s' is already approved." % self.title) self.approved = True self.approved_by = approver self.date_approved = utcnow() self.save() self.character_obj.sys_msg("File '%s' is now approved." % self.title, sys_name=self.info_type.category.key)
def set(self, account, until, reason): new_ban = { 'account': account, 'until': until, 'reason': reason, 'started': utcnow() } self.account.attributes.add(key='ban', category='system', value=new_ban) self.load()
def remaining_time(self): if not self.timeout: return '(No Timeout)' rem_time = (self.timeout_date or self.creation_date) + self.timeout if rem_time > utcnow(): rem_time = 'Timed out!' if not self.board.timeout: return '(Board Timeouts Disabled - %s)' % rem_time if not self.board.category.timeout: return '(Timeouts Disabled - %s)' % rem_time else: return '(Time Left: %s)' % rem_time
def switch_none(self): if not self.args: current_tz = self.player.player_settings.timezone now = utcnow().astimezone(current_tz) self.sys_msg("Your Current Timezone is '%s'. Is it %s where you are right now?" % (str(current_tz), now.strftime('%c %Z'))) return self.player.player_settings.timezone = self.args self.player.player_settings.save(update_fields=['timezone']) tz = self.player.player_settings.timezone self.sys_msg("Your Current Timezone is now '%s'. Is it %s where you are right now?" % (str(tz), utcnow().astimezone(tz).strftime('%c %Z')))
def create_post(self, account, character, subject, text, date=None): if not date: date = utcnow() name = ANSIString(subject) if '|' in name: raise ValueError("Malformed ANSI in post subject!") cname = name.raw() next = self.next_post_id new_post = self.posts.create(account=account, character=character, name=name.clean(), cname=cname, order=next, body=text, date_created=date, date_modified=date) new_post.update_read(account) next += 1 return new_post
def set_contents(self, newtext=None, setby=None): if not setby: raise ValueError("File setter data not found.") if not newtext: raise ValueError("No text entered to set!") if self.approved: raise ValueError("Cannot edit an approved file.") self.text = penn_substitutions(newtext) self.set_by = setby self.date_modified = utcnow() self.save() self.character_obj.sys_msg("File '%s' has been updated." % self.title, sys_name=self.info_type.category.key)
def new(self, viewer): interval = utcnow() - duration('14d') unseen_ids = self.jobs.exclude(links__account_stub=viewer.stub) #updated = Q(submit_date__gte=interval) unseen = Q(id__in=unseen_ids) if self.locks.check(viewer, 'admin'): last = Q(links__account_stub=viewer.stub, admin_update__gt=F('links__check_date')) else: last = Q(links__account_stub=viewer.stub, public_update__gt=F('links__check_date')) jobs = self.jobs.filter(last | unseen).exclude(submit_date__lt=interval) return jobs
def make_job(self, account, title, opening): now = utcnow() due = now + self.due job = self.jobs.create(title=title, submit_date=now, due_date=due, admin_update=now, public_update=now) job.save() handler = job.links.create(account_stub=account.stub, link_type=3, check_date=now) handler.make_comment(text=opening, comment_mode=0) handler.latest_check() return job
def make_post(self, character=None, subject=None, text=None, announce=True, date=None): if not character: raise ValueError("No player data to use.") if not text: raise ValueError("Text field empty.") if not subject: raise ValueError("Subject field empty.") if not date: date = utcnow() order = self.posts.all().count() + 1 post = self.posts.create(owner=character, subject=subject, text=text, creation_date=date, modify_date=date, timeout=self.timeout, order=order) if announce: self.announce_post(post) return post
def switch_list(self): message = [] message.append(self.player.render.header('Available Timezones')) tz_list = pytz.common_timezones if self.args: tz_list = [tz for tz in tz_list if tz.lower().startswith(self.args.lower())] if not tz_list: self.error("'%s' returned no matches.") return tz_table = self.player.render.make_table(['Name', 'Current Time'], width=[35, 43]) for zone in tz_list: now = utcnow().astimezone(pytz.timezone(zone)) tz_table.add_row(zone, now.strftime('%c %Z')) message.append(tz_table) message.append(self.player.render.footer()) self.msg_lines(message)
def display_line(self, account, admin, mode=None): start = f"{self.unread_star(account, admin)}{self.status_letter()}" num = str(self.id).rjust(4).ljust(5) owner_link = self.owner owner = str(self.owner) if owner_link else '' owner = owner[:15].ljust(16) title = self.title[:29].ljust(30) claimed = self.handler_names()[:12].ljust(13) now = utcnow().timestamp() last_updated = self.public_update.timestamp() if admin: last_updated = max(self.admin_update.timestamp(), last_updated) due = self.due_date.timestamp() - now if due <= 0: due = ANSIString("|rOVER|n") else: due = time_format(due, 1) due = due.rjust(6).ljust(7) last = time_format(now - last_updated, 1).rjust(4) return f"{start} {num}{owner}{title}{claimed}{due}{last}"
def display_events(self, lhs, rhs): if lhs: self.display_event(lhs) return now = utcnow() interval = duration_from_string('6h') expired = now - interval events = Event.objects.filter( date_schedule__gte=expired).order_by('date_schedule') tz = self.player.settings.get('timezone') last_day = '' check_day = '' message = list() message.append( header("Current Schedule - %s" % self.caller.display_local_time(format='%Z'), viewer=self.caller)) for event in events: check_day = self.caller.display_local_time( date=event.date_schedule, format='%a %b %d %Y') if check_day != last_day: message.append(subheader(check_day)) last_day = check_day time = self.caller.display_local_time(date=event.date_schedule, format='%I:%M%p') tag_mark = ' ' taggers = set(event.interest.all()) alts = set(self.player.get_all_characters()) check_set = taggers.intersection(alts) if len(check_set): tag_mark = ANSIString('|C*|n') if self.character in taggers: tag_mark = ANSIString('|r*|n') if event.owner == self.character: tag_mark = ANSIString('|g*|n') tag_count = event.interest.all().count() display_string = "{}{:<2} {:<4}{:40.40}{:23.23}{:7}".format( tag_mark, tag_count, event.id, event.title, event.owner, time) message.append(display_string) message.append(header(viewer=self.caller)) self.msg_lines(message)
def switch_reschedule(self, lhs, rhs): if not lhs: self.error("No scene ID entered to reschedule.") return event = Event.objects.filter(id=lhs).first() if not event: self.error("Event not found.") return if not self.caller.is_admin or event.owner != self.character: self.error("Permission denied.") return try: check_time = utc_from_string(rhs, self.character.settings.get('timezone')) except ValueError as err: self.error(unicode(err)) return if not check_time > utcnow(): self.error("No scheduling things in the past, that's just silly.") return event.reschedule(check_time) self.sys_msg("Rescheduled to: %s" % self.caller.display_local_time(date=check_time))
def switch_reschedule(self, lhs, rhs): if not lhs: raise ValueError("No scene ID entered to reschedule.") return event = Event.objects.filter(id=lhs).first() if not event: raise ValueError("Event not found.") return if not self.caller.is_admin or event.owner != self.character: raise ValueError("Permission denied.") return try: check_time = utc_from_string( rhs, self.character.settings.get('timezone')) except ValueError as err: raise ValueError(str(err)) return if not check_time > utcnow(): raise ValueError( "No scheduling things in the past, that's just silly.") return event.reschedule(check_time) self.sys_msg("Rescheduled to: %s" % self.caller.display_local_time(date=check_time))
def update_post(self): if self.post: self.post.text = self.post_text() self.post.modify_date = utcnow() self.post.save(update_fields=['text', 'modify_date'])
def latest_check(self): self.check_date = utcnow()
def active(self): interval = utcnow() - duration('7d') return self.jobs.filter( Q(status=0, close_date=None) | Q(close_date__gte=interval)).order_by('id').reverse()
) or not enactor.check_lock("pperm(Admin)"): raise ValueError("Permission denied.") account = self.find_account(account) if not account.db._disabled: raise ValueError("Account is not disabled!") del account.db._disabled entities = {'enactor': enactor, 'account': account} amsg.EnableMessage(entities).send() def ban_account(self, session, account, duration, reason): if not (enactor := session.get_account() ) or not enactor.check_lock("pperm(Moderator)"): raise ValueError("Permission denied.") account = self.find_account(account) duration = duration_from_string(duration) ban_date = utcnow() + duration if not reason: raise ValueError("Must include a reason!") account.db._banned = ban_date account.db._ban_reason = reason entities = {'enactor': enactor, 'account': account} amsg.BanMessage(entities, duration=time_format(duration.total_seconds(), style=2), ban_date=ban_date.strftime('%c'), reason=reason).send() account.force_disconnect(reason) def unban_account(self, session, account): if not (enactor := session.get_account() ) or not enactor.check_lock("pperm(Moderator)"):
def save(self, *args, **kwargs): self.creation_date = utcnow() return super(Message, self).save(*args, **kwargs)
def switch_jobs(self): # Step one is importing all of the Job Categories from the MUSH data. Each category is a THING object # So we don't need mysql just yet. cat_dict = dict() old_categories = cobj('jobdb').children.all() for old_cat in old_categories: new_cat, created = JobCategory.objects.get_or_create(key=old_cat.name) if created: new_cat.setup() cat_dict[old_cat.objid] = new_cat # Establishing Mysql Connection! from commands.mysql import sql_dict db = MySQLdb.connect(host=sql_dict['site'], user=sql_dict['username'], passwd=sql_dict['password'], db=sql_dict['database'], cursorclass=cursors.DictCursor) c = db.cursor() # Our next order of business is retrieving all of the players who've ever posted jobs. # This section searches the database by OBJID and creates a dictionary that links the old jobsys player_id # to the new communications.ObjectStub, creating them if necessary. c.execute("""SELECT * from jobsys_players""") old_players = c.fetchall() char_dict = dict() for old_player in old_players: match = objmatch(old_player['objid']) if match: char = match.obj else: key = old_player['player_name'] char = create.create_object(typeclass='classes.characters.BaseCharacter', key=key) objid = old_player['objid'] dbref, csecs = objid.split(':', 1) cdate = from_unixtimestring(csecs) MushObject.objects.create(objid=objid, dbref=dbref, created=cdate, type=8, recreated=1, obj=char) char_dict[old_player['player_id']] = char # Now that we have the Player ID->Stub dictionary, we can begin the process of actually importing job data! # we only want the jobs from categories that actually exist. Probably rare that any of them wouldn't be, but # just in case... cat_list = ', '.join("'%s'" % cat for cat in cat_dict.keys()) c.execute("""SELECT * from jobsys_jobs WHERE job_objid IN (%s) ORDER BY job_id""" % cat_list) old_jobs = c.fetchall() for row in old_jobs: job_id = row['job_id'] if row['close_date']: close_date = row['close_date'].replace(tzinfo=pytz.utc) else: close_date = None if row['due_date']: due_date = row['due_date'].replace(tzinfo=pytz.utc) else: due_date = None if row['submit_date']: submit_date = row['submit_date'].replace(tzinfo=pytz.utc) else: submit_date = None title = row['job_title'] status = row['job_status'] owner = char_dict[row['player_id']] text = penn_substitutions(row['job_text']) category = cat_dict[row['job_objid']] handler_dict = dict() # We have our job row data prepped! Now to create the job and its opening comment as well as the owner-handler. new_job = category.jobs.create(title=title, submit_date=submit_date, due_date=due_date, close_date=close_date, status=status) new_owner = new_job.characters.create(character=owner, is_owner=True, check_date=utcnow()) new_owner.comments.create(text=text, date_made=submit_date) handler_dict[row['player_id']] = new_owner # Here it's time to import all of the job's claims, handlers, watchers, and create JobHandler rows for them. c.execute("""SELECT * from jobsys_claim WHERE job_id=%s""", (job_id,)) claim_data = c.fetchall() for old_claim in claim_data: stub = char_dict[old_claim['player_id']] new_handler, created = new_job.characters.get_or_create(character=stub, check_date=utcnow()) if old_claim['claim_mode'] == 0: new_handler.is_handler = True if old_claim['claim_mode'] == 1: new_handler.is_helper = True new_handler.save() handler_dict[old_claim['player_id']] = new_handler # Unfortunately it's also possible that people who didn't claim it might also need JobHandler entries so... c.execute("""SELECT DISTINCT player_id from jobsys_comments WHERE job_id=%s""", (job_id,)) all_speakers = c.fetchall() for speaker in all_speakers: if speaker['player_id'] not in handler_dict: new_handler, created = new_job.characters.get_or_create(character=char_dict[speaker['player_id']], check_date=utcnow()) handler_dict[speaker['player_id']] = new_handler # And another round. This time it's a matter of importing handlers for anyone who ever CHECKED a job. # Here we'll also import everyone's 'last date they checked the job'. c.execute("""SELECT * FROM jobsys_check WHERE job_id=%s""", (job_id,)) old_checks = c.fetchall() for check in old_checks: if check['player_id'] not in handler_dict: handler, created = new_job.characters.get_or_create(character=char_dict[check['player_id']], check_date=utcnow()) handler_dict[check['player_id']] = new_handler else: handler = handler_dict[check['player_id']] handler.check_date = check['check_date'].replace(tzinfo=pytz.utc) handler.save(update_fields=['check_date']) # Now to import all of the comments and replies. c.execute("""SELECT * from jobsys_comments WHERE job_id=%s ORDER BY comment_id""", (job_id,)) old_comments = c.fetchall() for old_com in old_comments: handler = handler_dict[old_com['player_id']] comment_text = penn_substitutions(old_com['comment_text']) comment_date = old_com['comment_date'].replace(tzinfo=pytz.utc) private = old_com['comment_type'] handler.comments.create(text=comment_text, date_made=comment_date, is_private=private) db.close()
def update_last_played(self): self.last_played = utcnow() self.save(update_fields=['last_played'])
def update_read(self, account): acc_read, created = self.read.get_or_create(account=account) acc_read.date_read = utcnow() acc_read.save()
def expired(self): return (self.creation_date + self.expires) < utcnow()